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
spencer0727/GRU-Time-Series
https://github.com/spencer0727/GRU-Time-Series
56baa2e849cb6e1c92dc119c352674da6b4f6beb
a6cef7f05026d05a4ed351786b7211cb7efefdcc
07d56227218efe6c35c290822687f60ebb40694e
refs/heads/master
2020-04-12T23:30:27.869602
2019-02-14T08:50:15
2019-02-14T08:50:15
162,821,646
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.6779742240905762, "alphanum_fraction": 0.6891224980354309, "avg_line_length": 38.30188751220703, "blob_id": "3ab081bfa429ab5f80289fb28c76232e74521e3e", "content_id": "e56f9887a756dacedeab30df2326e32bbd892a77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6279, "license_type": "permissive", "max_line_length": 197, "num_lines": 159, "path": "/GRU_RNN.py", "repo_name": "spencer0727/GRU-Time-Series", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport math\nimport sklearn\nimport sklearn.preprocessing\nfrom sklearn.preprocessing import MinMaxScaler\nimport datetime\nimport os\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\n#Setting the Validation and Test ratios.\nvalid_set_size_percentage = 10 \ntest_set_size_percentage = 10 \n\n#Defining the dataframe \ndf = pd.read_csv(\"\", index_col = 0)\n\n#Checking the distribution and features of the data\ndf.describe()\n\n'''Normalization of the data may in some instances sacrifice the accuracy of the training data in order to better generalize the testing data.\nThere are a few different methods which can be used, in instances where the robustness of the data is needed I will use the MinMaxScaler.\nNormalizing the data, I used the MiniMax Scaler, shrinks the range such that the range is now between 0 and 1 (or -1 to 1 if there are negative values).\nThis scaler works better for cases in which the standard scaler might not work so well. If the distribution is not Gaussian or the standard deviation is very small, the min-max scaler works better.\nHowever, it is sensitive to outliers, so if there are outliers in the data, you might want to consider the Robust Scaler below.'''\n\ndef normalize_data(df):\n min_max = sklearn.preprocessing.MinMaxScaler()\n df['Close'] = min_max_scaler.fit_transform(df['Close'].values.reshape(-1,1))\n return df\n \n#Next we need to load the data and parse it into train, valid and test sets.\ndef load_data(stock, seq_len):\n data_raw = stock.as_matrix() \n data = []\n for index in range(len(data_raw)-seq_len):\n data.append(data_raw[index: index + seq_len])\n #Separating the data into their respective groups, play around with the test size if needed. \n data = np.array(data);\n valid_set_size = int(np.round(valid_set_size_percentage/100*data.shape[0])); \n test_set_size = int(np.round(test_set_size_percentage/100*data.shape[0]));\n train_set_size = data.shape[0] - (valid_set_size + test_set_size);\n \n #Separating the datasets\n x_train = data[:train_set_size,:-1,:]\n y_train = data[:train_set_size,-1,:]\n \n x_valid = data[train_set_size:train_set_size+valid_set_size,:-1,:]\n y_valid = data[train_set_size:train_set_size+valid_set_size,-1,:]\n \n x_test = data[train_set_size+valid_set_size:,:-1,:]\n y_test = data[train_set_size+valid_set_size:,-1,:]\n \n return [x_train, y_train, x_valid, y_valid, x_test, y_test]\n \n#Creating a copy of the data to pass through the parser\ndf_stock = df.copy()\ndf.columns\ncols = list(df_stock.columns.values)\nprint('df_stock.columns.values = ', cols)\ndf_stock_norm = df_stock.copy()\ndf_stock_norm = normalize_data(df_stock_norm)\nseq_len = 12 \n\n#Sep out the data\nx_train, y_train, x_valid, y_valid, x_test, y_test = load_data(df_stock_norm, seq_len)\n\n#Checking the shape of each of the data \nprint('x_train.shape = ',x_train.shape)\nprint('y_train.shape = ', y_train.shape)\nprint('x_valid.shape = ',x_valid.shape)\nprint('y_valid.shape = ', y_valid.shape)\nprint('x_test.shape = ', x_test.shape)\nprint('y_test.shape = ',y_test.shape)\n \n#Indexing the epoch\nindex_in_epoch = 0;\nperm_array = np.arange(x_train.shape[0])\nnp.random.shuffle(perm_array)\n \n#Setting the parameters to retrive the next batch\ndef get_next_batch(batch_size):\n global index_in_epoch, x_train, perm_array\n start = index_in_epoch\n index_in_epoch += batch_size\n \n \n if index_in_epoch > x_train.shape[0]:\n np.random.shuffle(perm_array) \n start = 0 \n index_in_epoch = batch_size\n \n end = index_in_epoch\n return x_train[perm_array[start:end]], y_train[perm_array[start:end]]\n \n\n#Setting the hyperparameter options\nn_steps = seq_len-1 \nn_inputs = 1 \nn_neurons = 200 \nn_outputs = 1\nn_layers = 2\nlearning_rate = 0.001\nbatch_size = 50\nn_epochs = 100 \ntrain_set_size = x_train.shape[0]\ntest_set_size = x_test.shape[0]\n \n#Begin the processes for tensorflow \ntf.reset_default_graph()\n\n#Set the placeholders, please note the convention of the naming, X is the matrix and y is the vector\nX = tf.placeholder(tf.float32, [None, n_steps, n_inputs])\ny = tf.placeholder(tf.float32, [None, n_outputs])\n\n#Define the layer of the RNN, I also had good results with RNN leaky activation function, and intitialize the TF train process\nlayers = [tf.contrib.rnn.GRUCell(num_units=n_neurons, activation=tf.nn.elu)\n for layer in range(n_layers)]\nmulti_layer_cell = tf.contrib.rnn.MultiRNNCell(layers)\n\nrnn_outputs, states = tf.nn.dynamic_rnn(multi_layer_cell, X, dtype=tf.float32)\n \nstacked_rnn_outputs = tf.reshape(rnn_outputs, [-1, n_neurons]) \nstacked_outputs = tf.layers.dense(stacked_rnn_outputs, n_outputs)\noutputs = tf.reshape(stacked_outputs, [-1, n_steps, n_outputs])\noutputs = outputs[:,n_steps-1,:]\n\nloss = tf.reduce_mean(tf.square(outputs - y))\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate) \ntraining_op = optimizer.minimize(loss)\n \nwith tf.Session() as sess: \n sess.run(tf.global_variables_initializer())\n for iteration in range(int(n_epochs*train_set_size/batch_size)):\n x_batch, y_batch = get_next_batch(batch_size) # fetch the next training batch \n sess.run(training_op, feed_dict={X: x_batch, y: y_batch}) \n if iteration % int(5*train_set_size/batch_size) == 0:\n mse_train = loss.eval(feed_dict={X: x_train, y: y_train}) \n mse_valid = loss.eval(feed_dict={X: x_valid, y: y_valid}) \n print('%.2f epochs: Mean Square Error Training Set & Validation Set = %.6f/%.6f'%(\n iteration*batch_size/train_set_size, mse_train, mse_valid))\n\n y_train_pred = sess.run(outputs, feed_dict={X: x_train})\n y_valid_pred = sess.run(outputs, feed_dict={X: x_valid})\n y_test_pred = sess.run(outputs, feed_dict={X: x_test}) \n \n \n#Check the MSE of the testing data for results \nmse = mean_squared_error(y_test, y_test_pred)\nprint('MSE: %f' % mse)\n \n \n \n#Checking the direction of each of the precidtion of each moves \ncorr_price_development_test = np.sum(np.equal(np.sign(y_test[:,0]-y_test[:,0]),\n np.sign(y_test_pred[:,0]-y_test_pred[:,0])).astype(int)) / y_test.shape[0]\n\nprint('Price up or down predict: %.2f'%(corr_price_development_test))\n \n \n \n \n \n \n \n \n \n \n" }, { "alpha_fraction": 0.7673167586326599, "alphanum_fraction": 0.7895090579986572, "avg_line_length": 50.25862121582031, "blob_id": "222d2da19a010407c999c683cd9ddb85c619d381", "content_id": "986d30768d7d3ee98307b8ada5363fcdde6b0a47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2974, "license_type": "permissive", "max_line_length": 460, "num_lines": 58, "path": "/README.md", "repo_name": "spencer0727/GRU-Time-Series", "src_encoding": "UTF-8", "text": "# GRU-Time-Series Description & Prediction\n\n# Instructions to run\nThe following dependencies are listed at the bottom. Must first intialize a TF environment in order to use TF. \nPlease see https://www.tensorflow.org/install/gpu for help with TF installation.\nPlease read GRU time series for more detailed description\n\n\n# GRU Neural Network Models for Market Movement Prediction\n\nThis is my first attempt for my masters the full thesis shall be published circa June 2018 \n\n# Introduction\nThe first model is a time series MV regression model which takes a split of 80%/10%/10% training, validiation, and testing set and the second model is a MV binary classifier. GRU's have been shown to perform better than LSTM cells with when there is not much data available, thus I wanted to see if it made a difference. The validation set was used in order to ensure the model did not overfit the data before testing the model. \n\n\n# Results\nI had less than wonderful results with the MV regression model, however the binary classifier was fairly good for predicting exact values of daily returns, but gives satisfactory results when used to predict the direction of the movement.\nI ambiguously chose APPL for the financial time series, however the actual selection does not matter as much. \n\nThe classifier is currently a work in progress as I will still need to fit the specifications properly first.\n\n\nThe results of the MV regresion model were meausured by taking the MSE of the training data and the results with the MV binary classifier were measured by taking the F1 Score. \n\n# Dependencies\nPython == 3.7\nnumpy==1.14.2 \npandas==0.22.0 \nplotly==2.5.0 \nscikit-learn==0.19.1 \nscipy==1.0.0 \nseaborn==0.8.1 \nsklearn==0.0 \ntensorflow==1.6.0 \ntensorflow-gpu==1.8.0 \n\nOther Needed Downloads:\nCUDA toolkit 9.0\ncuDNN SDK 7.2\n\nSpecs of machine used:\nNVIDIA GTX 1070\nIntel CPU i7-8750H\n16 GB of 2666 MHz DDR4 SDRAM\n\n\n# License\n\nMIT License\n\nCopyright (c) 2018 Spencer Frebel\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n" } ]
2
leilacey/LIS-511
https://github.com/leilacey/LIS-511
4668a119af61bde49915b76fcd488911fe5e573c
8811d849823abb5d6ad0d1b7c1d4e0d7c06d0a86
79b95dc7cafb6d1f5823794740e7beec4dd47f71
refs/heads/master
2020-04-09T10:10:03.333803
2018-12-03T21:49:56
2018-12-03T21:49:56
160,260,927
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6099071502685547, "alphanum_fraction": 0.6269350051879883, "avg_line_length": 22.923076629638672, "blob_id": "0b8b73b1798621736a48be78d67498f9ae144f68", "content_id": "9a975d51e6bd3a496989f01127fa47d3e8eabbe5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 646, "license_type": "no_license", "max_line_length": 99, "num_lines": 26, "path": "/Chapter 2/name_cases.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#2-3 Personal Message\r\nname = \"Leiya\"\r\nprint(\"Hello \" + name + \", would you like to learn some Python today?\")\r\n\r\n#2-4 Name Cases\r\nname = \"Dennis Ruggerio\"\r\nprint(name.lower())\r\nprint(name.upper())\r\nprint(name.title())\r\n\r\n#2-5 Famous Quotes\r\nname = \"Shaun Spencer\"\r\nquote = \"Don't be a gooey chocolate chip cookie.\"\r\nprint(name .title() + ' once said, \"' + quote + '\"')\r\n\r\n#2-6 Famous Quote 2\r\nfamous_person = \"Shaun Spencer\"\r\nmessage = famous_person.title() + ' once said, \"' + \"Don't be a gooey chocolate chip cookie.\" + '\"'\r\nprint(message)\r\n\r\n#2-7 Stripping Names\r\nname = \"\\t\\n Burton Guster \\t\"\r\nprint(name)\r\nprint(name.lstrip())\r\nprint(name.rstrip())\r\nprint(name.strip())" }, { "alpha_fraction": 0.6176470518112183, "alphanum_fraction": 0.6302521228790283, "avg_line_length": 27.75, "blob_id": "068c389f71b4a2bd4438fd91601c58a919edf097", "content_id": "cdce4fbb56f857f9ed9dd5827f6f8c3ea4ad8306", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 238, "license_type": "no_license", "max_line_length": 64, "num_lines": 8, "path": "/Chapter 3/buffet.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#4-13 Buffet\r\nbuffet_foods = (\"pizza\", \"burger\", \"ramen\", \"sushi\", \"pasta\")\r\nfor food in buffet_foods:\r\n\tprint(food)\r\nprint(\"\\n\")\r\nbuffet_foods = (\"pizza\", \"burger\", \"fries\", \"sandwich\", \"pasta\")\r\nfor food in buffet_foods:\r\n\tprint(food)\r\n" }, { "alpha_fraction": 0.6433408856391907, "alphanum_fraction": 0.6636568903923035, "avg_line_length": 27.33333396911621, "blob_id": "5efacc19ca8fdd92aaed771a3e7e88755e9e94a2", "content_id": "475469f9517bd02c2f37f67a8eed792b4ed919b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 122, "num_lines": 15, "path": "/Chapter 3/names.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# 3-1 Name\r\nfriend_names = ['Shaun Spencer', 'Burton Guster', \"Juliet O'Hara\"]\r\nprint(friend_names[0])\r\nprint(friend_names[1])\r\nprint(friend_names[2])\r\n\r\n#3-2 Greetings\r\nfor friend in friend_names:\r\n\tmessage = \"What's Up \" + friend + \"?\"\r\n\tprint(message)\r\n\r\n#3-3 Your Own List\r\ntransportation_comments = [\"I would like to own a Chevy Camero\", \"I ride the bus almost everyday\", \"I like to drive fast\"]\r\nfor comment in transportation_comments:\r\n\tprint (comment)\r\n\r\n\t" }, { "alpha_fraction": 0.5707070827484131, "alphanum_fraction": 0.6464646458625793, "avg_line_length": 17.799999237060547, "blob_id": "184156bc8ae6d9994dea6543a1c3d924e421ab75", "content_id": "46a12f55f063e2b76d50a55a5f8748f9af548aca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/Chapter 2/numbers.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#2-8 Number Eight\r\nprint (5 + 3)\r\nprint(11 - 3)\r\nprint(4 * 2)\r\nprint(16 / 2)\r\n\r\n#2-9 Favorite Number\r\nfavorite_number = 8\r\nmessage = \"My favorite number is \" + str(favorite_number)\r\nprint(message)\r\n" }, { "alpha_fraction": 0.6756756901741028, "alphanum_fraction": 0.7027027010917664, "avg_line_length": 17, "blob_id": "1a78cbfec49935ac931b29a4fa04a8d3eea365e5", "content_id": "20fe4c64d5dcba7aef1594a60440228cd7cd2050", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 74, "license_type": "no_license", "max_line_length": 34, "num_lines": 4, "path": "/Chapter 2/simple_message.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# 2-1 Simple Message\r\n\r\nmessage = \"This is a test message\"\r\nprint(message)" }, { "alpha_fraction": 0.6086331009864807, "alphanum_fraction": 0.667625904083252, "avg_line_length": 17.36111068725586, "blob_id": "315af7d9de619ab3110423f6002c51f3c26fd710", "content_id": "8f981482a983e808c2d54e03107962108f8fe844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 48, "num_lines": 36, "path": "/Chapter 3/numbers.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# 4-3 Counting to Twenty\r\nnumbers = list(range(1,21))\r\nfor number in numbers:\r\n\tprint(number)\r\n\r\n#4-4 One Million\r\nnumbers = list(range(1, 1000001))\r\n#for number in numbers:\r\n\t#print(number)\r\n\r\n# 4-5 Summing a Million\r\nprint(min(numbers))\r\nprint(max(numbers))\r\nprint(sum(numbers))\r\n\r\n#4-6 Odd Numbers\r\nnumbers = list(range(1, 20, 2))\r\nfor number in numbers:\r\n\tprint(number)\r\n\t\r\n# 4-7 Threes\r\nnumbers = list(range(3, 31, 3))\r\nfor number in numbers:\r\n\tprint(number)\r\n\t\r\n#4-8 Cubes\r\ncubes = []\r\nfor value in range(1,11):\r\n\tcubes.append(value**3)\r\nfor number in cubes:\r\n\tprint(number)\r\n\r\n#4-9 Cube Comprehension\r\ncubes = list(value **3 for value in range(1,11))\r\nfor number in cubes:\r\n\tprint(number)" }, { "alpha_fraction": 0.7298049926757812, "alphanum_fraction": 0.7353760600090027, "avg_line_length": 21.933332443237305, "blob_id": "efe378ec1ca0a4c3a670f6ebcb9b5f05f39ec59f", "content_id": "895728591e043d660a597ee98be9a65238654bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 61, "num_lines": 15, "path": "/Chapter 3/locations.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#3-8 Seeing the World\r\nlocations = [\"Canada\", \"Italy\", \"Germany\", \"UK\", \"Luxemborg\"]\r\nprint(locations)\r\nprint(sorted(locations))\r\nprint(locations)\r\nprint(sorted(locations, reverse=True))\r\nprint(locations)\r\nlocations.reverse()\r\nprint(locations)\r\nlocations.reverse()\r\nprint(locations)\r\nlocations.sort()\r\nprint(locations)\r\nlocations.reverse()\r\nprint(locations)\r\n" }, { "alpha_fraction": 0.6973684430122375, "alphanum_fraction": 0.7157894968986511, "avg_line_length": 52.57143020629883, "blob_id": "7ca6c7e3a6c086c6f39a57043b9eaf45297f25d6", "content_id": "ef3ae1c3fab4c6d77a2693c4048481183024cb64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 380, "license_type": "no_license", "max_line_length": 119, "num_lines": 7, "path": "/Chapter 2/temperature_convertor.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#Assignment 2 Task 5\r\n# This Program converts degrees Fahrenheit to degrees Celsius and prints the result\r\n\r\nfahrenheit_temp = float(input(\"Enter the temperatures in degrees Fahrenheit? \"))\r\ncelsius_temp = round(((fahrenheit_temp - 32) * (5/9)), 2)\r\nprint(\"\")\r\nprint (\"The temperature \" + str(fahrenheit_temp) + \" degrees Fahrenheit is \" + str(celsius_temp) + \" degrees Celsius.\")" }, { "alpha_fraction": 0.6548223495483398, "alphanum_fraction": 0.6776649951934814, "avg_line_length": 17.799999237060547, "blob_id": "3fb992511be3a6fa35bbafa2db83d5e9bf4135b8", "content_id": "96b8e228be95b1f02df1ae95a7b365b4826d2c32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 64, "num_lines": 20, "path": "/Chapter 3/fruit.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#3-10 Every Function\r\nfruit = [\"Apple\", \"Banana\", \"Orange\", \"Pineapple\", \"Strawberry\"]\r\nprint(fruit)\r\nprint(fruit[0])\r\nfruit[2] = 'Lemon'\r\nprint(fruit[2])\r\nfruit.append(\"Orange\")\r\nprint(fruit)\r\ndel fruit[3]\r\nprint(fruit)\r\nfruit.insert(3, \"Pineapple\")\r\nprint(fruit)\r\nfruit.pop(2)\r\nprint(fruit)\r\nfruit.remove('Banana')\r\nprint(fruit)\r\nfruit.sort()\r\nprint(fruit)\r\nfruit.reverse()\r\nprint(len(fruit))" }, { "alpha_fraction": 0.6316239237785339, "alphanum_fraction": 0.6478632688522339, "avg_line_length": 29.675676345825195, "blob_id": "4bb56f528cc0915e04c8bf41d2fc5832f740548c", "content_id": "df053c0e8fc9898cd88dee98c99619046c18b533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 65, "num_lines": 37, "path": "/Chapter 3/guest_list.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# 3-4 Guest List\r\ndinner_guests = ['Kurt Cobain', 'Bill Gates', 'Eddie Veddar']\r\nfor guest in dinner_guests:\r\n\tprint (\"Would you like to have dinner with me \" + guest + \"?\")\r\nprint('\\n')\r\n\r\n# 3-5 Changing Guest List\r\nnot_coming = \"Bill Gates\"\r\ndinner_guests.insert(1, \"Dave Grohl\")\r\ndinner_guests.remove(not_coming)\r\nfor guest in dinner_guests:\r\n\tprint (\"Would you like to have dinner with me \" + guest + \"?\")\r\nprint (not_coming + '\\n')\r\n\r\n#3-6 More Guests\r\ndinner_guests.insert(0, 'Brendan Urie')\r\ndinner_guests.insert(2, 'Patrick Stump')\r\ndinner_guests.append('Tim McIlrath')\r\nfor guest in dinner_guests:\r\n\tprint (\"Would you like to have dinner with me \" + guest + \"?\")\r\nprint(\"I found a bigger table \\n\")\r\n\r\n#3-7 Shrinking Guest List\r\nprint(\"Sorry, I can only invite two people now.\")\r\nwhile (len(dinner_guests) > 2):\r\n\tuninvited_guest = dinner_guests.pop()\r\n\tprint(\"Sorry, you have been uninvited \" + uninvited_guest + \".\")\r\nindex = 0\r\nprint (\"You are still invited \" + dinner_guests[0] + \".\")\r\nprint (\"You are still invited \" + dinner_guests[1] + \".\")\r\ndel dinner_guests[0]\r\ndel dinner_guests[0]\r\nprint(dinner_guests)\r\n\r\n#3-9 Dinner Guests\r\ndinner_guests = ['Kurt Cobain', 'Bill Gates', 'Eddie Veddar']\r\nlen(dinner_guests)" }, { "alpha_fraction": 0.6495468020439148, "alphanum_fraction": 0.6510574221611023, "avg_line_length": 20.133333206176758, "blob_id": "7ffd5a64cb18a2fdc5cc2910d6d91f0a9f9949e3", "content_id": "b0f7b5e4046a35b18b9a10d63f7fa88fe5700eff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "no_license", "max_line_length": 66, "num_lines": 30, "path": "/Chapter 3/makeup.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# Assignment 3 Part B\r\nmakeup_list = []\r\nprompt = \"\\nPlease enter the makeup you want:\"\r\nprompt += \"\\n(Enter 'quit' when you are finished.)\"\r\n\r\nwhile True:\r\n\tmakeup = input(prompt)\r\n\t\r\n\tif makeup == 'quit' :\r\n\t\tbreak\r\n\telse:\r\n\t\tmakeup_list.append(makeup)\r\n\r\nprint(\"This is the makeup you purchased:\")\r\nfor makeup in makeup_list:\r\n\tprint (makeup)\r\n\r\ncontinue_purchase = input(\"Would you like to buy anything else? \")\r\nif continue_purchase == 'yes':\r\n\twhile True:\r\n\t\tmakeup = input(prompt)\r\n\t\t\r\n\t\tif makeup == 'quit' :\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tmakeup_list.append(makeup)\r\n\t\t\t\r\nprint(\"This is the makeup you purchased: \")\r\nfor makeup in makeup_list:\r\n\tprint (makeup)" }, { "alpha_fraction": 0.6285714507102966, "alphanum_fraction": 0.6380952596664429, "avg_line_length": 37.625, "blob_id": "9ded0e937e006859b787e855535c444e1e9fdcd4", "content_id": "a018a904b3239c5e826e31ededb6fd6dd29fdf3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 133, "num_lines": 8, "path": "/Chapter 2/Pay_2.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#Assignment 2 Task 4 Part B\r\n\r\nhours = float(input('Enter hours worked: '))\r\nrate = float(input('Enter a pay rate without $: '))\r\nprint(\" \")\r\n\r\ngross_total = round (hours * rate,2)\r\nprint(\"You're total pay for \" + str(hours) + \" hours worked at a rate of \" + str(rate) + \" dollars per hour is $\" + str(gross_total))" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6794871687889099, "avg_line_length": 21.600000381469727, "blob_id": "1b9cfa2940d5158330ced7710187474b3f6436c4", "content_id": "d0ef52a9fcf7749575208fb921f92d2cfa0e7013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/Chapter 2/hello.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# Assignment 2 Task 2\r\n\r\nmyname = \"Leiya Lacey\"\r\nprogram = \"I am a 2nd year Informatics Student\"\r\nprint(\"This is me printing literal text. Next I’ll try variables\")\r\nprint(\" \")\r\nprint(myname)\r\nprint(program)\r\nprint(\" \")\r\nprint(\"Thank you\")" }, { "alpha_fraction": 0.6377550959587097, "alphanum_fraction": 0.6505101919174194, "avg_line_length": 30.83333396911621, "blob_id": "06da28be20b6763e571b7245bb559e042855353d", "content_id": "164c66b7e753571ec2c726d30c287651478901ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 392, "license_type": "no_license", "max_line_length": 63, "num_lines": 12, "path": "/Chapter 3/Guest List.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# 3-4 Guest List\r\ndinner_guests = ['Kurt Cobain', 'Bill Gates', 'Eddie Veddar']\r\nfor guest in dinner_guests\r\n\tprint (\"Would you like to have dinner with me \" + guest + \"?\")\r\n\t\r\n# 3-5 Changing Guest List\r\nnot_coming = \"Bill Gates\"\r\ndinner_guests.insert(1, \"Dave Grohl\")\r\ndinner_guests.remove(not_coming)\r\nfor guest in dinner_guests\r\n\tprint (\"Would you like to have dinner with me \" + guest + \"?\")\r\nprint (not_coming)" }, { "alpha_fraction": 0.7007299065589905, "alphanum_fraction": 0.7153284549713135, "avg_line_length": 17.85714340209961, "blob_id": "2952ef0ca1ab5fac10fcba7423067dc0375363a8", "content_id": "a91a395ca51ffa4fe887972cdc1fe2c59cc468de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 137, "license_type": "no_license", "max_line_length": 43, "num_lines": 7, "path": "/Chapter 2/simple_messages.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#2-2 Simple Messages\r\n\r\nmessage = \"This is a test message\"\r\nprint(message)\r\n\r\nmessage = \"This is the second test message\"\r\nprint(message)" }, { "alpha_fraction": 0.6458684802055359, "alphanum_fraction": 0.6602023839950562, "avg_line_length": 25.627906799316406, "blob_id": "8858d127e7336c7bf3d4f92664b0a527b23117c1", "content_id": "f4667ab8405d939301ba891ff99ac398c2ef1a61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1186, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/Chapter 3/pizza.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "#4-1 Pizzas\r\npizzas = [\"Pepporoni\", \"Cheese\", \"Hawaiian\", \"Philly\", \"Smoked Mozzerella\"]\r\nfor pizza in pizzas:\r\n\tprint (\"I like \" + pizza + \" pizza.\")\r\nprint('I really love pizza')\r\n\r\n#4-2 Animals\r\nanimals = [\"Penguins\", \"Chickens\", \"Flamingos\"]\r\nfor animal in animals:\r\n\tprint(animal + \" are a bird.\")\r\nprint(\"All of these animals are birds.\")\r\n\r\n#4-10 Slices\r\nprint(\"The first three items in the list are:\")\r\nfor pizza in pizzas[:3]:\r\n\tprint(pizza)\r\nprint(\"The middle three items in the list are:\")\r\nfor pizza in pizzas[1:4]:\r\n\tprint(pizza)\r\nprint(\"The last three items in the list are:\")\r\nfor pizza in pizzas[-3:]:\r\n\tprint(pizza)\r\n\t\r\n#4-11 My Pizzas, Your Pizzas\r\nfriend_pizzas = pizzas[:]\r\npizzas.append(\"Meat\")\r\nfriend_pizzas.append(\"Everything\")\r\nprint(\"My favorite pizzas are \")\r\nfor pizza in pizzas:\r\n\tprint(pizza + \" \")\r\nprint(\"My friend's favorite pizzas are \")\r\nfor pizza in friend_pizzas:\r\n\tprint(pizza + \" \")\r\n\r\n#4-12 More Loops\r\nmy_foods = ['pizza', 'falafel', 'carrot cake']\r\nfriend_foods = my_foods[:]\r\nprint(\"My favorite foods are: \")\r\nfor food in my_foods:\r\n\tprint(food + \" \")\r\nprint(\"\\nMy friend's favorite foods are: \")\r\nfor food in friend_foods:\r\n\tprint(food + \" \")" }, { "alpha_fraction": 0.7109826803207397, "alphanum_fraction": 0.7254335284233093, "avg_line_length": 67.5999984741211, "blob_id": "c900827af74430c22909e63b6c385e529dbdf92b", "content_id": "fdd0f36b66f4b1b9b699469f502264744a9235aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 119, "num_lines": 5, "path": "/Chapter 2/Temperature Converter.py", "repo_name": "leilacey/LIS-511", "src_encoding": "UTF-8", "text": "# This Program converts degrees Fahrenheit to degress Celsius and prints the result\r\nfahrenheit_temp = float(input(\"Enter the temperatures in degrees Fahrenheit? \"))\r\ncelsius_temp = round((fahrenheit_temp - 32) * (5/9)), 2)\r\n\r\nprint (\"The temperature \" + str(fahrenheit_temp) + \" degrees Fahrenheit is \" + str(celsius_temp) + \" degrees Celsius.\")" } ]
17
bpd-d/svg-cleaner
https://github.com/bpd-d/svg-cleaner
b35a2433e866905acb7abbdaea6366a2e4865a86
1e33210e39c834f4d4b04aa2a85e193cb1cffacb
4e6864babcc5b9bd01bf4e190d12af99e9264091
refs/heads/master
2022-11-21T06:12:15.798225
2020-07-17T07:46:59
2020-07-17T07:46:59
269,278,208
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6733001470565796, "alphanum_fraction": 0.6749585270881653, "avg_line_length": 25.2608699798584, "blob_id": "53af9ee59e8a1383f51732ae1f44b426ebd9cc78", "content_id": "2c3bfa518fc821f20f36c4744e4d368292affaa5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 603, "license_type": "permissive", "max_line_length": 168, "num_lines": 23, "path": "/README.md", "repo_name": "bpd-d/svg-cleaner", "src_encoding": "UTF-8", "text": "# svg-cleaner\nSmall CLI tool to clean svg-xml files from environment specific nodes\nScript gets all files from given **input** or from **./icons** if input was not provided in command line, parse and saves modified in the **output** or folder **./out**\n\n# Requirements\nPython 3 installed\n\n# Usage\nRun command\n```\n python main.py - i <inputfile> -o <outputfile> -j -s -c\n```\n\nFor help call\n```\npython main.py -h\n```\nOptions:\n* -i [ --input=] Input folder \n* -o [ --output=] Output folder \n* -j [ --json] Create json file \n* -s [ --js] Create JS file \n* -c [ --clean] Clean output folder before conversion" }, { "alpha_fraction": 0.5450370907783508, "alphanum_fraction": 0.5480395555496216, "avg_line_length": 27.309999465942383, "blob_id": "46ef4f6a67d02a4f51146caaeb285341e759c053", "content_id": "97e34009c44a0a49f04f3ba7eca7b6dde9ba9117", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5662, "license_type": "permissive", "max_line_length": 244, "num_lines": 200, "path": "/main.py", "repo_name": "bpd-d/svg-cleaner", "src_encoding": "UTF-8", "text": "import os\nimport xml.etree.ElementTree as ET\nimport re\nimport sys\nimport getopt\nimport shutil\n\nbasedir = \"icons\"\nnotNeededTags = ['title', 'defs', 'namedview', 'metadata']\nnotNeededAttrs = ['id', 'style', 'connector',\n 'transform', 'arg1', 'arg2', 'nodetypes']\n\nneededArgs = ['height', 'width', 'x', 'y', 'cx', 'cy', 'r', 'd', 'transform']\nremoveSpacesRegex = r'((?<=>)(\\s+)(?=[<]))'\nremoveNewlineRegex = r'((?<=>)(\\n[\\t]*)(?=[^<\\t]))|(?<=[^>\\t])(\\n[\\t]*)(?=<)|\\n'\nchildRegex = './'\n\n\ndef get_files(directory):\n if not directory:\n return None\n return os.listdir(directory)\n\n\ndef cleanFolder(directory):\n for filename in os.listdir(directory):\n file_path = os.path.join(directory, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n\n\ndef savefile(f, content):\n with open(f, 'w') as newF:\n newF.write(content)\n\n\ndef getroot(f):\n tree = ET.parse(f)\n return tree.getroot()\n\n\ndef matches(tagName, arr):\n for t in arr:\n if t in tagName:\n return True\n return False\n\n\ndef equals(tagName, arr):\n for t in arr:\n if t == tagName:\n return True\n return False\n\n\ndef regex_replace(text, replaceStr, reg):\n comp = re.compile(reg)\n return re.sub(comp, replaceStr, text)\n\n\ndef prepare_string(text):\n noNewL = regex_replace(text, \"\", removeNewlineRegex)\n noSpace = regex_replace(noNewL, \"\", removeSpacesRegex)\n return noSpace.replace(\"\\\"\", \"\\\\\\\"\")\n\n\ndef get_keys_to_remove(attribs):\n return [key for key in attribs if not(equals(key, neededArgs))]\n\n\ndef create_file_line(f, content):\n return f'\"{f}\":\"{content}\"'\n\n\ndef create_file_line2(f, content):\n ff = f.replace('-', '_')\n return f'{ff}:\"{content}\"'\n\n\ndef create_json_line(f, content):\n ff = f.replace('-', '_')\n return f'\"{ff}\":\"{content}\"'\n\n\ndef create_all_file(files, json=False):\n count = len(files)\n newF = \"{\"\n for index, (key, value) in enumerate(files.items()):\n if (json == True):\n newF += create_json_line(key[:-4], value)\n else:\n newF += create_file_line2(key[:-4], value)\n if index < count - 1:\n newF += \",\"\n newF += \"\\n\"\n newF += \"}\"\n return newF\n\n\ndef create_all_file_dict(files):\n count = len(files)\n newF = \"[\"\n for index, (key, value) in enumerate(files.items()):\n newF += '{ key: \\\"' + key[:-4] + '\\\", value: \\\"' + value+'\\\"}'\n if index < count - 1:\n newF += \",\"\n newF += \"\\n\"\n newF += \"]\"\n return newF\n\n\ndef adjust_file(f):\n print(f'Parsing file {f}')\n tree = ET.parse(f)\n root = tree.getroot()\n copy = {}\n copy['viewBox'] = root.attrib['viewBox']\n copy['width'] = root.attrib['width']\n copy['height'] = root.attrib['height']\n root.attrib = copy\n\n for element in root.findall(childRegex):\n if matches(element.tag, notNeededTags):\n root.remove(element)\n\n # Remove attributes for existing elements\n for element in root.findall(childRegex):\n toRemove = get_keys_to_remove(element.attrib)\n for key in toRemove:\n del element.attrib[key]\n # //print()\n content = ET.tostring(root, encoding='utf8', method='html')\n return prepare_string(content.decode())\n\n\ndef main(argv):\n print(\"Init\")\n here = os.path.abspath(os.path.dirname(__file__))\n inDir = os.path.join(here, basedir)\n outDir = os.path.join(here, 'out')\n isJson = False\n isJs = False\n cleanOutDir = False\n try:\n opts, args = getopt.getopt(\n argv, \"jcshi:o:\", [\"input=\", \"output=\", \"js\", \"json\", \"clean\"])\n except getopt.GetoptError:\n print('main.py - i <inputfile> -o <outputfile> -j -s -c')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print(\n 'main.py -i <inputfile> -o <outputfile> -j -s \\n -i [ --input=] Input folder \\n -o [ --output=] Output folder \\n -j [ --json] Create json file \\n -s [ --js] Create JS file \\n -c [ --clean] Clean output folder before conversion')\n sys.exit()\n elif opt in (\"-i\", \"--input\"):\n inDir = arg\n elif opt in (\"-o\", \"--output\"):\n outDir = arg\n elif opt in (\"-j\", \"--json\"):\n isJson = True\n elif opt in (\"-s\", \"--js\"):\n isJs = True\n elif opt in (\"-c\", \"--clean\"):\n cleanOutDir = True\n print('Input folder: ', inDir)\n print('Output folder: ', outDir)\n files = get_files(inDir)\n allFiles = dict()\n ET.register_namespace(\"\", \"http://www.w3.org/2000/svg\")\n if files is not None:\n if cleanOutDir:\n print(f'Clean out directory')\n cleanFolder(outDir)\n print(f'Found {len(files)} files')\n for f in files:\n content = adjust_file(os.path.join(inDir, f))\n print(f'Saving file {f}')\n savefile(os.path.join(outDir, f), content)\n allFiles[f] = content\n # Create all icons file\n if isJs:\n print(\"Create js file\")\n savefile(os.path.join(outDir, \"all.js\"),\n create_all_file(allFiles))\n if isJson:\n print(\"Create json file\")\n savefile(os.path.join(outDir, \"all.json\"),\n create_all_file(allFiles, True))\n else:\n print('No files found')\n print(\"Finish\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n" } ]
2
LBAI-InfoLab/MixTube
https://github.com/LBAI-InfoLab/MixTube
9645bd7901cafff80d79da3cd5e94421f73d61e7
7990e04b97afff1f743b16a340a7bf9e2522e0e7
170e50e76aba9553ec73e84791b2ead06f26a936
refs/heads/master
2022-12-03T08:23:02.320107
2020-08-07T13:15:13
2020-08-07T13:15:13
285,833,580
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5810983180999756, "alphanum_fraction": 0.5849297642707825, "avg_line_length": 26.138729095458984, "blob_id": "3cba7b203f08b6ddf01e4d393761802ac07b37ea", "content_id": "f67011141d98a8e8fb75549379ad7ed14084451b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4698, "license_type": "no_license", "max_line_length": 122, "num_lines": 173, "path": "/craft_tube_mix.py", "repo_name": "LBAI-InfoLab/MixTube", "src_encoding": "UTF-8", "text": "\n\n\ndef extract_exlusion_data(exlusion_file):\n \"\"\"\n Read data in exlusion_file to craft a dictionnary\n {metal : [incompatible_metal]}\n\n return a dictionnary\n\n exlusion_file is the name of a csv file. each line of the file consist in:\n a first element : the name of the metal\n all others element : name of the metal incompatible with the first element\n \"\"\"\n\n ## parameters\n metal_to_exclusion = {}\n\n ## loop over exclusion file\n data_metal = open(exlusion_file, \"r\")\n for line in data_metal:\n\n ## parse line\n line = line.rstrip()\n line_in_array = line.split(\",\")\n\n ## extract exclusion\n metal = line_in_array[0]\n exclusion_list = line_in_array[1:]\n\n ## process exclusion list\n exclusion_list_processed = []\n for elt in exclusion_list:\n if(elt != \"\"):\n exclusion_list_processed.append(elt)\n metal_to_exclusion[metal] = exclusion_list_processed\n\n ## close file\n data_metal.close()\n\n ## return dict\n return metal_to_exclusion\n\n\n\n\ndef craft_tube_composition(metal_to_exclusion):\n \"\"\"\n Use metal to exlusion data to craft a composition for the tube\n\n - metal_to_exclusion is a dictionnary generated by the extract_exlusion_data\n function\n\n return a dictionnary (tube composition)\n \"\"\"\n\n ## parameters\n tube_to_metal = {}\n\n ## init data structure\n tube_to_metal[\"tube1\"] = []\n\n ## extract metal list\n metal_list = list(metal_to_exclusion.keys())\n\n ## loop over metal in metal_list\n cmpt_tube = 1\n for metal in metal_list:\n\n ## init status\n tube_assigned = False\n\n ## check if metal can be added\n for tube in tube_to_metal:\n can_be_added = True\n composition = tube_to_metal[tube]\n\n for elt in composition:\n if(elt in metal_to_exclusion[metal]):\n can_be_added = False\n\n if(can_be_added and not tube_assigned):\n tube_to_metal[tube].append(metal)\n tube_assigned = True\n\n ## if metal can't be added, open new tube\n if(not tube_assigned):\n cmpt_tube += 1\n tube_to_metal[\"tube\"+str(cmpt_tube)] = []\n tube_to_metal[\"tube\"+str(cmpt_tube)].append(metal)\n\n ## return dict\n return tube_to_metal\n\n\ndef save_results_to_txt(tube_to_metal, save_file_name):\n \"\"\"\n save tube composition to a text file\n tube_to_metal is a dictionnary generated by the craft_tube_composition\n function\n save_file_name is self explanatory ;)\n \"\"\"\n\n ## open result file\n results = open(save_file_name, \"w\")\n for tube in list(tube_to_metal.keys()):\n\n ## write tube composition\n results.write(str(tube)+\"\\n\")\n results.write(str(tube_to_metal[tube])+\"\\n\")\n results.write(\"#\"*150+\"\\n\")\n\n ## close result file\n results.close()\n\n\n\n\ndef main(argv):\n \"\"\"\n main function of the module\n -> catch user arguments\n -> update default parameters\n -> run the programm\n \"\"\"\n\n ## importation\n import getopt\n\n ## default parameter\n exclusion_file = \"exclusion_data.csv\"\n output_file = \"tube_composition.txt\"\n\n ## catch arguments\n try:\n opts, args = getopt.getopt(argv, \"he:o:d\", [\"help\", \"exclusion_file=\", \"output_file=\"])\n except getopt.GetoptError:\n usage()\n sys.exit(2)\n\n ## parse arguments\n ## update default parameters if needed\n for opt, arg in opts:\n\n if opt in (\"-h\", \"--help\"):\n ## display help\n print(\"#\"*72)\n print(\"#\"*25+\"CRAFT TUBE MIX - HELP \"+\"#\"*25)\n print(\"#\"*72)\n print(\"=> This script is used to craft tube composition that respect icompatibility between specific agents.\")\n print(\"-> run it without arguments to conserve the default settings\")\n print(\"-> you can specify the :\")\n print(\"\\t-name of the exlusion file (-e / --exclusion_file)\")\n print(\"\\t-name of the output file (-o / --output_file)\")\n print(\"-> Exemple of use :\")\n print(\"\\tpython craft_tube_mix.py -e my_exclusion_data.csv -o foo.txt\")\n sys.exit()\n elif opt in (\"-e\", \"--exclusion_file\"):\n exclusion_file = arg\n elif opt in (\"-o\", \"--output_file\"):\n output_file = arg\n\n ## run the programm\n metal_to_exclusion = extract_exlusion_data(exclusion_file)\n tube_to_composition = craft_tube_composition(metal_to_exclusion)\n save_results_to_txt(tube_to_composition, output_file)\n\n\n\nif __name__=='__main__':\n\n ## importation\n import sys\n\n ## run main\n main(sys.argv[1:])\n" } ]
1
jonasserry/GDFT-Net
https://github.com/jonasserry/GDFT-Net
510588d8d5c6c068b73c6568fab0a86c5eabcbf6
1e5141777a704376320d56a2a7cd3bed3abc93e6
c5b74f1980faac9e085f2dbe121f71d074eba2b5
refs/heads/master
2023-01-10T06:48:56.418472
2020-11-11T13:03:19
2020-11-11T13:03:19
307,477,748
0
0
null
2020-10-26T19:06:15
2020-11-01T18:57:45
2020-11-01T19:01:03
Jupyter Notebook
[ { "alpha_fraction": 0.5569592714309692, "alphanum_fraction": 0.5678501129150391, "avg_line_length": 33.24626922607422, "blob_id": "8656f74cbdb5ca11b898419785bd36f10ee29ec4", "content_id": "47d6d0e7ea09ede5383316553ef83957c9df1f7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4591, "license_type": "no_license", "max_line_length": 270, "num_lines": 134, "path": "/Core/GDFT_Tester.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "\nfrom Core import GDFT_Data\nfrom Core import GDFT_Net\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom collections import defaultdict\n\nprint(\"Tester Version: 1.02\")\n\ndef load_tester(path):\n with open(path, 'rb') as input:\n tester = pickle.load(input)\n return(tester)\n\nclass GDFT_Net_Tester():\n\n def __init__(self,Tester_Path,Net_Path,dimensions):\n \n self.Path=Tester_Path\n self.Net_Path = Net_Path\n self.Net=None\n self.version = 1.1\n self.dimensions=dimensions\n\n self.errors = defaultdict(list)\n self.standard_dev_delays = None\n\n\n def load_Net(self):\n self.Net = GDFT_Net.load_GDFT_Net(self.Net_Path)\n self.Net.load_models()\n\n\n def run_RMSE_Testing(self,numImages=None,SNRs=None,DS=None):\n corr = []\n i=0\n if DS != None:\n SNRs = DS.SNRs\n \n for SNR in SNRs:\n if DS == None:\n raw_images,_,labels_1D = GDFT_Data.Create_Images(numImages, self.Net.numSteps, self.Net.dimensions, self.Net.t0, self.Net.wavenumberRange, self.Net.numChan, self.Net.numCoherent, self.Net.numIncoherent, SNR,numSteps_simulated=1024*1024,print_flag=False)\n else:\n raw_images,_,labels_1D = DS.get_Data(with_SNR=SNR)\n prediction = self.Net.process_Images(raw_images,verbose=0)[1]*self.Net.numChan*2-self.Net.numChan\n errors = prediction-labels_1D\n rmse = np.sqrt(np.mean(((errors)**2),axis=1))\n self.errors[round(SNR,2)].extend(errors)\n print(\"SNR: {0:3.2f} RMSE: {1:3.2f} STD: {2:3.2f}\".format(SNR,np.mean(rmse),np.std(rmse)))\n\n corr.append(np.sqrt(np.mean(((labels_1D)**2))))\n i+=1\n\n self.standard_dev_delays = np.mean(corr) #alter this?\n\n def get_RMSE_Data(self):\n means = []\n SNRs = []\n stds = []\n for SNR in sorted(self.errors.keys()):\n SNRs.append(SNR)\n rmses = np.sqrt(np.mean((np.array(self.errors[SNR])**2),axis=1))\n means.append(np.mean(rmses))\n stds.append(np.std(rmses))\n \n return(np.array(SNRs),np.array(means),np.array(stds))\n \n def get_error_at_index(self,i):\n means = []\n SNRs = []\n stds = []\n for SNR in sorted(self.errors.keys()):\n SNRs.append(SNR)\n err = np.abs(np.array(self.errors[SNR])[:,i])\n means.append(np.mean(err))\n stds.append(np.std(err))\n return(np.array(SNRs),np.array(means),np.array(stds))\n \n def get_error_at_index(self,i):\n means = []\n SNRs = []\n stds = []\n for SNR in sorted(self.errors.keys()):\n SNRs.append(SNR)\n err = np.abs(np.array(self.errors[SNR])[:,i])\n means.append(np.mean(err))\n stds.append(np.std(err))\n return(np.array(SNRs),np.array(means),np.array(stds))\n \n def get_error_variation_at_SNR(self,SNR):\n means = []\n inds =[]\n stds = []\n for i in range(self.dimensions[0]):\n inds.append(i)\n err = np.abs(np.array(self.errors[SNR])[:,i])\n means.append(np.mean(err))\n stds.append(np.std(err))\n return(np.array(inds),np.array(means),np.array(stds))\n \n def get_max_error(self):\n means = []\n SNRs = []\n stds = []\n for SNR in sorted(self.errors.keys()):\n SNRs.append(SNR)\n rmses = np.max((np.abs(self.errors[SNR])),axis=1)\n means.append(np.mean(rmses))\n stds.append(np.std(rmses))\n \n return(np.array(SNRs),np.array(means),np.array(stds))\n\n \n def plot_this_data(self,SNRs,means,stds,fig_size=(8,8),corr=1,xlabel=\"SNR\",ylabel=\"RMSE\",label=None,title=None,fontsize=12):\n plt.figure(figsize=fig_size)\n plt.errorbar(SNRs,means/corr,yerr=stds/corr,capsize=3,elinewidth=0.5,c =\"black\", ecolor=\"Black\",label=label) \n plt.title(title,fontsize=fontsize*1.5)\n plt.xlabel(xlabel,fontsize=fontsize)\n plt.ylabel(ylabel,fontsize=fontsize)\n\n def save_data_to_file(self,path):\n np.save(path, np.array(dict(self.errors)),allow_pickle=True)\n \n def load_data_from_file(self,path):\n P = np.load(path,allow_pickle=True)\n self.errors.update(P.item())\n \n def save(self,path=None):\n if not path:\n path = self.Path\n self.Net = None\n with open(path, 'wb') as output: \n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n print(\"Reload Net\")\n\n" }, { "alpha_fraction": 0.6869980692863464, "alphanum_fraction": 0.7160842418670654, "avg_line_length": 42.46226501464844, "blob_id": "503f630beb7a7f2b03911cddb8bd5dcaf63c9ea7", "content_id": "2eaa279d6d7603d14eeb398d170d3892ff73acdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4607, "license_type": "no_license", "max_line_length": 125, "num_lines": 106, "path": "/Core/GDFT_Sim.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "import scipy.signal\nimport numpy as np\nfrom numpy.random import normal\n\n\ndef temprl(nsamp,t0,index=-4.0/3.0):\n \"\"\"Generate a time sequence of samples of atmospheric temporal\n perturbations with a Kolmogorov-Tatarski structure function.\"\"\"\n temp=nsamp/float(t0)\n const=np.sqrt(0.011193/temp/2./2.)/temp**index*nsamp\n amplitude=np.arange(nsamp/2+1,dtype=np.float64)\n amplitude[1:]=const*(amplitude[1:]**index)\n noise=normal(size=(2,int(nsamp/2+1)))\n return np.fft.irfft(amplitude*(noise[0]+1j*noise[1]))\n \ndef RcFilter(samples,tau):\n e=np.exp(-1.0/tau)\n return scipy.signal.lfilter([1-e],[1,-e],samples,axis=0)\n\ndef chop(samples,blockSize):\n \"\"\"Chop first dimension of array into a 2-d array of blocks of length blockSize. The\n original dimension does not have to be a multiple of blockSize - the remainder\n is discarded. Will return an error for arrays which cannot be reshaped in this\n way without copying\"\"\"\n maxSamp=samples.shape[0]\n numBlock=maxSamp//blockSize\n numSamp=numBlock*blockSize\n self=samples[:numSamp].view()\n self.shape=(numBlock,blockSize)+samples.shape[1:]\n return self\n\ndef BlockAverage(samples,blockSize):\n return np.sum(chop(samples,blockSize),axis=1)/float(blockSize)\n\ndef DispersedFringes(delay,wavenumberRange,numChan):\n wavenumber=np.linspace(wavenumberRange[0],wavenumberRange[1],numChan)\n fringePhase=np.multiply.outer(delay,wavenumber)\n v=np.exp(1j*fringePhase)\n return v\n\ndef PowerSpectrum1d(v,oversample=2):\n window = np.hamming(v.shape[-1])\n return np.fft.fftshift(abs(np.fft.fft(v*window,axis=-1,n=v.shape[-1]*oversample))**2,axes=(-1,))\n\ndef ComplexNoise(shape,sigma=1.0):\n r=np.random.normal(size=shape+(2,),scale=sigma/np.sqrt(2))\n return r[...,0]+1j*r[...,1]\n\n\ndef GroupDelaySimulation(phase,wavenumberRange,numChan,numCoherent,numIncoherent,SNR):\n coherentVisibilities=BlockAverage(DispersedFringes(phase,wavenumberRange,numChan),numCoherent)\n coherentVisibilities+=ComplexNoise(coherentVisibilities.shape,sigma=np.sqrt(numChan)/SNR)\n delaySpectrum=RcFilter(PowerSpectrum1d(coherentVisibilities),numIncoherent)\n return delaySpectrum\n\n\ndef modifiedGDT(phase,wavenumberRange,numChan,numCoherent,numIncoherent,SNR):\n \"\"\"Returns GDT output with given phase behaviour with and without applied random Noise\"\"\"\n coherentVisibilities=BlockAverage(DispersedFringes(phase,wavenumberRange,numChan),numCoherent)\n coherentVisibilities_withNoise=ComplexNoise(coherentVisibilities.shape,sigma=np.sqrt(numChan)/SNR) + coherentVisibilities\n withNoise=RcFilter(PowerSpectrum1d(coherentVisibilities_withNoise),numIncoherent)\n withoutNoise=RcFilter(PowerSpectrum1d(coherentVisibilities),numIncoherent)\n return np.transpose(withNoise), np.transpose(withoutNoise)\n\n\n\ndef von_karman_temporal_samples(nsamp, t0, T0=1e6, two_telescopes=False):\n \"\"\"\n Return temporal samples of phase perturbations corresponding to Von Karman turbulence\n\n Parameters\n ----------\n nsamp : int\n Number of time samples to generate - should be much larger than T0\n t0 : float\n Coherence time measured in samples t_0=0.314 r_0/V where V is effective windspeed.\n T0 : float\n Temporal outer scale T_0=L_0/V.\n two_telescopes : boolean\n Simulate phase sequences corresponding to the phase difference between two\n uncorrelated telescopes i.e. twice the variance. If false, simulate the\n perturbations above a single telescope.\n\n Returns:\n --------\n samples : numpy.ndarray[float]\n Samples of the phase perturbations at intervals of 1/t0\n\n Notes:\n ------\n A suitable setting for t_0 might be of order 10 samples.\n\n For r_0=31.4cm (a moderate H-band value) and V=10m/s, then t_0=10ms.\n If L_0=100m then T0=10s, i.e. 1000t_0, or T0=10^4 samples in this example.\n \"\"\"\n f = np.fft.rfftfreq(nsamp)\n # Spectrum scale factor: divide by a factor of 2 to account for noise having a variance of 2\n # Divide by a second factor of two to account for a single-sided spectrum\n # Multiply by a factor of 2 if we want to represent the differential between\n # two telescopes.\n # Multiply by delta-f(=f[1]) to account for power in the range f->f+delta-f\n scale = 0.011193 / (2.0 if two_telescopes else 4.0) * f[1]\n spectrum = scale * t0 ** (-5.0 / 3.0) * (f ** 2 + 1 / T0 ** 2) ** (-4.0 / 3.0)\n noise = normal(size=(2, len(f)))\n # Multiply by nsamp to counteract the normalisation of the inverse fft\n return nsamp * np.fft.irfft(np.sqrt(spectrum) * (noise[0] + 1j * noise[1]))\n" }, { "alpha_fraction": 0.61569744348526, "alphanum_fraction": 0.6445136666297913, "avg_line_length": 45.96341323852539, "blob_id": "7ed4290f67bf54c040cceff2ab089c5e77e080e5", "content_id": "d44093e8d009853ff9348ba13043fcc8021fb798", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11556, "license_type": "no_license", "max_line_length": 290, "num_lines": 246, "path": "/Core/GDFT_Data.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "import time\nimport IPython\nimport gc\nimport cv2\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.signal as sig\n\nfrom Core import GDFT_Sim as Sim\n\nprint(\"Data Version: 1.61\")\n\n\n###---------------- Image Creation --------------------\ndef DownSample(image,dimensions):\n \"\"\"\n Takes image and downsamples and resizes to given dimensions using openCV\n Returns image with dimensions (dimensions[0],dimensions[1],1)\n \"\"\"\n x = cv2.resize(image,dimensions,interpolation = cv2.INTER_AREA) #Interpolation type?\n x = cv2.normalize(x, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX)\n return np.reshape(x,list(x.shape) + [1])\n\ndef Create_Image_From_Delays(delays,wavenumberRange,numChan,numCoherent,numIncoherent,SNR,dimensions,numSkip,numSteps=None,t0=None):\n \"\"\" Returns raw GDFT image, 2D Mask, and 1D Label from given set of delays using specified params\"\"\"\n raw_image,raw_label = Sim.modifiedGDT(delays,wavenumberRange,numChan,numCoherent,numIncoherent,SNR)\n raw_image = DownSample(raw_image[:,numSkip:],dimensions)\n raw_label = DownSample(raw_label[:,numSkip:],dimensions)\n decimated = Decimate_Delays(delays,dimensions[0])\n return raw_image,raw_label,decimated\n\ndef Create_Image(numSteps = 1024*128, dimensions =(256,256), t0 = 10, wavenumberRange=(0.8,1.2), numChan = 100, numCoherent=16, numIncoherent=25, SNR=1,numBatches=1,numSkip=20):\n \"\"\"Returns raw GDFT image, 2D Mask, and 1D Label created using provided parameters\"\"\"\n delays = Sim.von_karman_temporal_samples(1024*1024,t0,T0=1e4, two_telescopes=True)[0:numSteps]\n return(Create_Image_From_Delays(delays,wavenumberRange,numChan,numCoherent,numIncoherent,SNR,dimensions,numSkip))\n\ndef Create_Images(NumImages, numSteps = 1024*128, dimensions =(256,256), t0 = 10, wavenumberRange=(0.8,1.2), numChan = 100, numCoherent=16, numIncoherent=25, SNR=1,numBatches=1,numSkip=20,numSteps_simulated=1024*1024,print_flag=True):\n \"\"\"Returns specified number of raw GDFT image, 2D Mask, and 1D Label created using provided parameters\"\"\"\n Images = np.empty((NumImages,dimensions[1],dimensions[0],1))\n Labels_2D = np.empty((NumImages,dimensions[1],dimensions[0],1))\n Labels_1D = np.empty((NumImages,dimensions[0]))\n \n start_time = time.time()\n\n Images_per_simulated_delays = int(numSteps_simulated/numSteps)\n\n delays = Sim.von_karman_temporal_samples(numSteps_simulated,t0,T0=1e4, two_telescopes=True)\n\n image_index = 0\n \n for i in range(NumImages):\n\n if image_index == Images_per_simulated_delays:\n delays = Sim.von_karman_temporal_samples(numSteps_simulated,t0,T0=1e4, two_telescopes=True)\n image_index = 0\n\n image,label_2D,label_1D = Create_Image_From_Delays(delays[numSteps*image_index:numSteps*image_index+numSteps],wavenumberRange,numChan,numCoherent,numIncoherent,SNR,dimensions,numSkip)\n \n Labels_2D[i] = label_2D\n Labels_1D[i] = label_1D\n Images[i] = image\n image_index+=1\n\n \n if i%10 ==0 and print_flag:\n t = (time.time()-start_time) / (i+1) * (NumImages-i)\n print(\"\\rBatches remaining: %i | Images Remaining in Batch: %s | Time left in Batch: %s\" %(numBatches, NumImages-i, time.strftime(\"%H:%M:%S\", time.gmtime(t))),end='\\r')\n\n if print_flag:\n total_t = time.time()-start_time\n print(\"\\rFinished Batch | Time taken: %s | Total Time Left: %s\" % (time.strftime(\"%H:%M:%S\", time.gmtime(total_t)),time.strftime(\"%H:%M:%S\", time.gmtime(total_t*(numBatches-1)))))\n return (Images,Labels_2D,Labels_1D)\n\ndef ConvertForNextNetwork(train_labels):\n \"\"\"Convert 2D Labels into 1D Labels simply using argmax. NOTE: this is now deprecated\"\"\"\n CorrectFeature = np.empty((train_labels.shape[0],train_labels.shape[2]))\n\n for i in range(train_labels.shape[0]):\n CorrectFeature[i] = Convert_to_1D_Label(train_labels[i])\n\n return (CorrectFeature)\n\ndef Convert_to_1D_Label(label):\n \"\"\"Convert 2D Label into 1D Label simply using argmax. NOTE: this is now deprecated\"\"\"\n return(np.reshape(np.argmax(label,0),-1)/label.shape[0])\n\ndef Decimate_Delays(delays,x_dim):\n \"\"\"Returns decimated (and filtered) delays with dimension given by x_dim\"\"\"\n decimated = sig.decimate(delays,int(len(delays)/x_dim),axis=0,ftype = \"fir\")\n\n assert(len(decimated)==x_dim), \"Decimated length: {0} | Desired dimension {1}\".format(len(decimated),x_dim)\n return(decimated/2/np.pi)\n\n###---------------- Data Set Creation --------------------\n\ndef create_Data_Set(id,NumImages,SNRs,t0=16, numSteps = 1024*128, dimensions =(256,256), wavenumberRange=(1.5,2.0), numChan = 100, numCoherent=16, numIncoherent=25,numSkip=0,**kwargs):\n \"\"\"Returns variable SNR GDFT Data Set with provided SNR distribution and GDFT parameters\"\"\"\n assert(len(NumImages)==len(SNRs))\n Images = np.empty((np.sum(NumImages),dimensions[1],dimensions[0],1))\n Labels_2D = np.empty((np.sum(NumImages),dimensions[1],dimensions[0],1))\n Labels_1D = np.empty((np.sum(NumImages),dimensions[0]))\n n=0\n i=0\n while i<len(NumImages):\n images,labels_2D,labels_1D = Create_Images(NumImages[i],SNR = SNRs[i],numSteps=numSteps, dimensions = dimensions, t0=t0, wavenumberRange = wavenumberRange, numChan = numChan, numCoherent=numCoherent, numIncoherent=numIncoherent,numBatches=(len(NumImages)-i),numSkip=numSkip)\n Images[n:n+NumImages[i]] = images\n Labels_2D[n:n+NumImages[i]] = labels_2D\n Labels_1D[n:n+NumImages[i]] = labels_1D\n n+=NumImages[i]\n i+=1\n return GDFT_Data_Set(id,Images,Labels_2D,Labels_1D,NumImages,SNRs,t0,numChan,dimensions,numSteps,wavenumberRange,numCoherent,numIncoherent,numSkip)\n\ndef create_Data_Sets(id,NumImages,SNRs,t0=10, numSteps = 128000, y_dim=64,x_dims=[16,32,64,128,256,512], wavenumberRange=(1.5,2.0), numChan = 32, numCoherent=10, numIncoherent=25,numSkip=0,**kwargs):\n \"\"\"Returns variable SNR GDFT Data Sets. A single set of GDFT samples is created using the final provided dimension (x_dims[-1]).\n This set is chopped up to create data sets at other provided dimensions. \"\"\"\n assert(len(NumImages)==len(SNRs))\n Images = np.empty((np.sum(NumImages),y_dim,x_dims[-1],1))\n Labels_2D = np.empty((np.sum(NumImages),y_dim,x_dims[-1],1))\n Labels_1D = np.empty((np.sum(NumImages),x_dims[-1]))\n \n \n n=0\n i=0\n while i<len(NumImages): # Create Images at maximum dimension\n images,labels_2D,labels_1D = Create_Images(NumImages[i],SNR = SNRs[i],numSteps=numSteps, dimensions = (x_dims[-1],y_dim), t0=t0, wavenumberRange = wavenumberRange, numChan = numChan, numCoherent=numCoherent, numIncoherent=numIncoherent,numBatches=(len(NumImages)-i),numSkip=numSkip)\n Images[n:n+NumImages[i]] = images\n Labels_2D[n:n+NumImages[i]] = labels_2D\n Labels_1D[n:n+NumImages[i]] = labels_1D\n n+=NumImages[i]\n i+=1\n\n Sets = []\n for x in x_dims: # Chop images into smaller dimensions\n images = []\n labels_2d =[]\n labels_1d = []\n j=0\n for n in NumImages:\n i=0\n while i < x_dims[-1]/x:\n images.extend(Images[j:j+n,:,x*i:x*i+x,:])\n labels_2d.extend(Labels_2D[j:j+n:,:,x*i:x*i+x,:])\n labels_1d.extend(Labels_1D[j:j+n:,x*i:x*i+x])\n i+=1\n j+=n\n Sets.append(GDFT_Data_Set(id+str(x),images,labels_2d,labels_1d,(np.array(NumImages)*x_dims[-1]/x).astype(int),SNRs,t0,numChan,(x,y_dim),int(numSteps*x/x_dims[-1]),wavenumberRange,numCoherent,numIncoherent,numSkip))\n return Sets\n\n\n###---------------- GDFT Data Set --------------------\n\n\nclass GDFT_Data_Set():\n\n def __init__(self,id,Images,Labels_2D,Labels_1D,NumImages,SNRs,t0,numChan,dimensions,numSteps,wavenumberRange,numCoherent,numIncoherent,numSkip):\n self.path = None\n self.id = id\n self.SNRs = SNRs\n self.numSteps = numSteps\n self.t0 = t0\n self.numChan = numChan\n self.dimensions = dimensions\n self.wavenumberRange = wavenumberRange\n self.numCoherent = numCoherent\n self.numIncoherent = numIncoherent\n self.numSkip = numSkip\n self.Images = Images\n self.Labels_1D = Labels_1D\n self.Labels_2D = Labels_2D\n self.Image_Nums = NumImages\n\n self.dmax=numChan/(2*(wavenumberRange[1]-wavenumberRange[0]))\n\n def get_Params(self):\n return(self.numSteps,self.t0,self.numChan,self.wavenumberRange,self.numCoherent,self.numIncoherent,self.numSkip)\n\n def save_As(self,path):\n with open(path+self.id+\".pkl\", 'wb') as output: \n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n self.path=path\n print(\"Saved as: \" + path+self.id+\".pkl\")\n \n def save(self):\n if self.path == None:\n raise Exception(\"No path set. Use save_As\")\n with open(self.path, 'wb') as output: \n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n print(\"Saved as: \" + self.path)\n\n def describe(self):\n print(\"------------------------ID: %s ----------------------------\"%(self.id))\n print(\"numChan {0}\".format(self.numChan))\n print(\"FINISH THIS\")\n \n def get_Data(self,with_SNR=None):\n \"Returns Unshuffled Images and Labels,\"\n if with_SNR == None:\n return(np.array(self.Images),np.array(self.Labels_2D),np.array(self.Labels_1D))\n else:\n i = self.SNRs.index(with_SNR) #SNR Index\n end = np.cumsum(self.Image_Nums)[i]\n if i == 0:\n start = 0\n \n else:\n start = np.cumsum(self.Image_Nums)[i-1]\n return(np.array(self.Images[start:end]),np.array(self.Labels_2D[start:end]),np.array(self.Labels_1D[start:end]))\n \n def get_Shuffled_Data(self):\n \"returns shuffled COPY. Watch out for space\"\n rng_state = np.random.get_state()\n a = np.random.permutation(self.Images)\n np.random.set_state(rng_state)\n b = np.random.permutation(self.Labels_2D)\n np.random.set_state(rng_state)\n c = np.random.permutation(self.Labels_1D)\n return(a,b,c)\n \n def findSNR(self,i):\n \"\"\"Find SNR of sample i in variable SNR Data with distribution given by Bats and SNRs\"\"\"\n cum_Bats = np.cumsum(self.Image_Nums)\n n=0\n while i > cum_Bats[n] and n<len(self.Image_Nums):\n n+=1\n return(self.SNRs[n])\n\n def plot_Image_at_Index(self,i,title=\"\",fs=10,aspect=\"auto\", figsize=(10, 6)):\n \"\"\"Plots Image and Label at given Index\"\"\"\n _, axs = plt.subplots(nrows=3, ncols=1, figsize=figsize,sharex=True)\n axs[0].imshow(self.Images[i][:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect,extent=(0,self.numSteps/self.t0,-self.dmax,self.dmax))\n axs[1].imshow(self.Labels_2D[i][:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect,extent=(0,self.numSteps/self.t0,-self.dmax,self.dmax))\n axs[0].set_ylabel(\"OPD(Wavelengths)\",fontsize=fs)\n axs[1].set_ylabel(\"OPD(Wavelengths)\",fontsize=fs)\n axs[1].set_xlabel(\"time/$t_0$\",fontsize=fs)\n axs[0].set_title(\"Image (SNR = %s)\" % (self.findSNR(i)),fontsize=fs*1.5)\n axs[1].set_title(\"Label\",fontsize=fs*1.5)\n \n axs[2].plot(np.linspace(0,self.numSteps/self.t0,len(self.Labels_1D[i])),self.Labels_1D[i])\n\n plt.suptitle(title)\n\ndef load_Data_Set(path):\n with open(path, 'rb') as input:\n Set = pickle.load(input)\n return(Set)\n\n\n\n" }, { "alpha_fraction": 0.5921846032142639, "alphanum_fraction": 0.6306238174438477, "avg_line_length": 43.79999923706055, "blob_id": "595561084c31b8b60c97b76125fbff132d5b124f", "content_id": "6bb615973f6168950e7c7d8de54ec2fd91810653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17248, "license_type": "no_license", "max_line_length": 196, "num_lines": 385, "path": "/Core/GDFT_Net.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "from Core import GDFT_Data\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pickle\nfrom collections import defaultdict\n\n# pylint: disable=E1130\n\nprint(\"Net Version: 1.72\")\n\n\n#FIX THESE IMPORTS\nimport tensorflow as tf\nfrom tensorflow.keras.callbacks import ModelCheckpoint\nfrom tensorflow.keras import backend \nfrom tensorflow.keras import Input\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras.layers import Conv2D,MaxPooling2D,Dropout,concatenate, Flatten, Dense, UpSampling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.utils import plot_model\n\n\ndef load_GDFT_Net(path):\n with open(path, 'rb') as input:\n Net = pickle.load(input)\n return(Net)\n\nclass GDFT_Net():\n\n def __init__(self,M1_path,M2_path,dimensions,Net_Path=None):\n \"\"\"M1,M2 should be paths\n Dimensions written as (x,y)\n \"\"\"\n self.M1_path = M1_path\n self.M2_path = M2_path\n self.M1 = None\n self.M2 = None\n self.dimensions = dimensions\n self.path = Net_Path\n\n self.P1_val_loss = []\n self.P1_loss = []\n self.P1_epochs_trained = 0\n self.P1_nN = None\n self.P2_val_loss = []\n self.P2_loss = []\n self.P2_epochs_trained = 0\n self.P2_nN = None\n\n self.numSteps = None # This would be better done with a simple params dict that can then be passed to all GDFT_Data functions\n self.t0 = None\n self.numChan = None\n self.wavenumberRange = None\n self.numCoherent = None\n self.numIncoherent = None\n self.numSkip = None\n self.dmax=None\n \n self.RMSEs = defaultdict(list)\n self.errors = defaultdict(list)\n self.standard_dev_delays = None\n\n print(\"Remember: Load Models\")\n\n def describe(self):\n print(\"Dimensions: {0}x{1}\".format(*self.dimensions))\n print(\"nN -> P1: {0} | P2: {1}\".format(self.P1_nN,self.P2_nN))\n print(\"Epochs --> P1: {0} | P2: {1}\".format(self.P1_epochs_trained,self.P2_epochs_trained))\n print(\"Min Loss --> P1: {0} | P2: {1}\".format(min(self.P1_val_loss),min(self.P2_val_loss)))\n\n def set_training_params(self,numSteps,t0,numChan,wavenumberRange,numCoherent,numIncoherent,numSkip):\n\n self.numSteps = numSteps\n self.t0 = t0\n self.numChan = numChan\n self.wavenumberRange = wavenumberRange\n self.numCoherent = numCoherent\n self.numIncoherent = numIncoherent\n self.numSkip = numSkip\n self.dmax=numChan/(2*(wavenumberRange[1]-wavenumberRange[0]))\n \n def load_P1_Model(self):\n self.M1 = load_model(self.M1_path)\n\n def load_P2_Model(self):\n self.M2 = load_model(self.M2_path)\n\n def load_models(self):\n self.load_P1_Model()\n self.load_P2_Model()\n \n def check_if_loaded(self):\n if self.M1 == None:\n self.load_P1_Model()\n if self.M2 == None:\n self.load_P2_Model()\n\n def create_P1_Model(self,nN,model = None):\n self.P1_nN = nN\n self.P1_val_loss = []\n self.P1_loss = []\n self.P1_epochs_trained = 0\n if model == None:\n self.M1 = UNet_P1(input_size=(self.dimensions[1],self.dimensions[0],1),nN=nN) \n else:\n self.M1 = model\n \n \n def train_P1(self,DS,epochs=10,batch_size=16,val_split=0.2):\n assert self.M1 != None,\"No Model Loaded\"\n\n train_images, train_labels, _ = DS.get_Shuffled_Data()\n\n checkpoint = ModelCheckpoint(self.M1_path,monitor=\"val_loss\", save_best_only=True,save_weights_only=False,verbose=1)\n callbacks_list = [checkpoint]\n history = self.M1.fit(train_images, train_labels,batch_size=batch_size, epochs=epochs, callbacks=callbacks_list, validation_split=val_split, verbose = 1)\n self.P1_val_loss.extend(history.history['val_loss'])\n self.P1_loss.extend(history.history['loss'])\n self.P1_epochs_trained += epochs\n\n plt.figure()\n plt.plot(history.history['loss'],label=\"test_loss\")\n plt.plot(history.history['val_loss'],label=\"val_loss\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Loss\")\n plt.legend()\n \n def test_P1(self,SNR,fs=(10,10),aspect=\"auto\"):\n #assert self.M1 != None,\"No Model Loaded\"\n\n raw_image, label_2d, _ = GDFT_Data.Create_Image(self.numSteps, self.dimensions, self.t0 , self.wavenumberRange, self.numChan, self.numCoherent, self.numIncoherent, SNR,self.numSkip)\n p1_pred = self.M1.predict(np.reshape(raw_image,[1] + list(raw_image.shape)))\n self.M1.evaluate(np.reshape(raw_image,[1] + list(raw_image.shape)),np.reshape(label_2d,[1] + list(label_2d.shape)),verbose=1)\n\n plt.figure(figsize=fs)\n plt.imshow(raw_image[:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect)\n\n plt.figure(figsize=fs)\n plt.imshow(p1_pred[0,:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect)\n\n plt.figure(figsize=fs)\n plt.imshow(label_2d[:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect)\n\n \n def create_P2_Model(self,nN,model = None):\n self.P2_nN = nN\n self.P2_val_loss = []\n self.P2_loss = []\n self.P2_epochs_trained = 0\n if model == None:\n self.M2 = UNet_P2(input_size=(self.dimensions[1],self.dimensions[0],1),nN=nN) \n else:\n self.M2 = model\n \n def convert_Data_for_P2(self,DS,reload_P1=True):\n \"\"\"returns shuffled P2 data from given data set\"\"\"\n if reload_P1 or not self.M1:\n self.load_P1_Model()\n images,_,Labels_1D = DS.get_Shuffled_Data()\n P2_images = self.M1.predict(images,verbose=1)\n\n return(P2_images,(Labels_1D+self.dimensions[1]/2)/self.dimensions[1])\n\n def train_P2(self,DS,epochs=10,batch_size=16,val_split=0.2,save_path = None):\n self.check_if_loaded()\n \n if not save_path:\n save_path = self.M2_path\n\n train_images, train_labels = self.convert_Data_for_P2(DS)\n\n checkpoint = ModelCheckpoint(save_path,monitor=\"val_loss\", save_best_only=True,save_weights_only=False,verbose=1)\n callbacks_list = [checkpoint]\n history = self.M2.fit(train_images, train_labels,batch_size=batch_size, epochs=epochs, callbacks=callbacks_list, validation_split=val_split,verbose = 1)\n self.P2_val_loss.extend(history.history['val_loss'])\n self.P2_loss.extend(history.history['loss'])\n self.P2_epochs_trained += epochs\n\n plt.figure()\n plt.plot(history.history['loss'],label=\"test_loss\")\n plt.plot(history.history['val_loss'],label=\"val_loss\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"Loss\")\n plt.legend()\n\n def process_Images(self,images,verbose=0):\n First_Pass_Images = self.M1.predict(images,verbose)\n Second_Pass_Images = self.M2.predict(First_Pass_Images,verbose)\n return(First_Pass_Images,Second_Pass_Images)\n\n def process_Image(self,image,verbose=0):\n P1_Image = self.M1.predict(np.reshape(image,[1] + list(image.shape)),verbose)\n P2_Image = self.M2.predict(P1_Image,verbose)\n return(P1_Image[0],P2_Image[0])\n\n\n def plot_Example(self,raw_image,label_2d,label_1d,SNR=1.0,fs=(10,10),aspect=\"auto\"):\n self.check_if_loaded()\n\n First_Pass_Image,Second_Pass_Image = self.process_Image(raw_image,verbose=0)\n\n\n RMSE = np.sqrt(np.mean((((Second_Pass_Image*self.dmax*2-self.dmax)-label_1d)**2)))\n print(\"Network RMSE: {0:3.1f} Wavelengths\".format(RMSE))\n\n var = np.sqrt(np.mean(((label_1d**2))))\n\n print(\"Variation: {0:3.1f} Wavelengths\".format(var))\n\n #Plotting\n \n _, axs = plt.subplots(nrows=2, ncols=2, figsize=fs,sharey=True)\n\n axs[0, 0].imshow(raw_image[:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect,extent=(0,self.dimensions[0],(-self.dmax),self.dmax))\n axs[0, 0].set_title(r\"GDFT Image ($SNR_0$ = {0:3.2f})\".format(SNR),fontsize=14)\n axs[0, 0].set_ylabel(\"OPD(Wavelengths)\",fontsize=14)\n\n axs[1, 0].imshow(label_2d[:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect,extent=(0,self.dimensions[0],(-self.dmax),self.dmax))\n axs[1, 0].set_title(\"GDFT Image Correct Delays\",fontsize=14)\n axs[1, 0].set_ylabel(\"OPD(Wavelengths)\",fontsize=14)\n axs[1, 0].set_xlabel(r\"Time/$t_0$\",fontsize=14)\n\n axs[0, 1].imshow(First_Pass_Image[:,:,0], cmap=plt.get_cmap('gray_r'),origin=\"lower\",aspect=aspect,extent=(0,self.dimensions[0],(-self.dmax),self.dmax))\n axs[0, 1].set_title(\"First Pass Network Prediction\",fontsize=14)\n\n x = np.linspace(0,self.numSteps/self.t0,len(Second_Pass_Image))\n axs[1, 1].set_title(\"Results\",fontsize=14)\n axs[1, 1].plot(x,Second_Pass_Image*self.dmax*2-self.dmax,label=\"GDFT-Net\",c=\"black\",ls=\"--\")\n axs[1, 1].plot(x,label_1d,label=\"True Delays\",c=\"black\",ls=\"-\")\n axs[1, 1].set_xlabel(r\"Time/$t_0$\",fontsize=14)\n axs[1, 1].legend(fontsize=12)\n return()\n\n def plot_random_Example(self,SNR,fs=(10,10),aspect=\"auto\"):\n raw_image, label_2d, label_1d = GDFT_Data.Create_Image(self.numSteps, self.dimensions, self.t0 , self.wavenumberRange, self.numChan, self.numCoherent, self.numIncoherent, SNR,self.numSkip)\n self.plot_Example(raw_image,label_2d,label_1d,SNR,fs,aspect=\"auto\")\n\n def save_Net(self,filename=None):\n self.M1 = None\n self.M2 = None\n\n if filename is None:\n filename = self.path\n else:\n self.path=filename\n \n with open(filename, 'wb') as output: \n pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)\n print(\"Saved as: \" + self.path)\n print(\"Remember to reload models\")\n\n\n\n \n\ndef UNet_P1 (pretrained_weights = None,input_size = (256,256,1),nN=64,drop=0.4):\n\n inputs = Input(input_size)\n \n conv1 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n conv1 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n \n conv2 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n conv2 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n conv3 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n drop4 = Dropout(drop)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n\n conv5 = Conv2D(nN*16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(nN*16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = Dropout(drop)(conv5)\n\n up6 = Conv2D(nN*8, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n merge6 = concatenate([drop4,up6], axis = 3)\n drop6 = Dropout(drop)(merge6)\n conv6 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop6)\n conv6 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n\n up7 = Conv2D(nN*4, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n merge7 = concatenate([conv3,up7], axis = 3)\n drop7 = Dropout(drop)(merge7)\n conv7 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop7)\n conv7 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n\n up8 = Conv2D(nN*2, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n merge8 = concatenate([conv2,up8], axis = 3)\n drop8 = Dropout(drop)(merge8)\n conv8 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop8)\n conv8 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n\n up9 = Conv2D(nN, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n merge9 = concatenate([conv1,up9], axis = 3)\n drop9 = Dropout(drop)(merge9)\n conv9 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop9)\n conv9 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv9 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = Conv2D(1, 1, activation = 'sigmoid')(conv9)\n\n model = Model(inputs = [inputs], outputs = [conv10])\n\n if(pretrained_weights):\n \tmodel.load_weights(pretrained_weights)\n\n model.compile(optimizer = Adam(lr=1e-4), loss = 'binary_crossentropy', metrics = ['accuracy'])\n \n #model.summary()\n\n\n\n return model\n\n\ndef UNet_P2 (pretrained_weights = None,input_size = (256,256,1),nN = 64,drop=0.4):\n \n inputs = Input(input_size)\n conv1 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(inputs)\n conv1 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv1)\n pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)\n \n conv2 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool1)\n conv2 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv2)\n pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)\n\n conv3 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool2)\n conv3 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv3)\n pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)\n\n conv4 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool3)\n conv4 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv4)\n drop4 = Dropout(drop)(conv4)\n pool4 = MaxPooling2D(pool_size=(2, 2))(drop4)\n\n conv5 = Conv2D(nN*16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(pool4)\n conv5 = Conv2D(nN*16, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv5)\n drop5 = Dropout(drop)(conv5)\n\n up6 = Conv2D(nN*8, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(drop5))\n merge6 = concatenate([drop4,up6], axis = 3)\n drop6 = Dropout(drop)(merge6)\n conv6 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop6)\n conv6 = Conv2D(nN*8, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv6)\n\n up7 = Conv2D(nN*4, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv6))\n merge7 = concatenate([conv3,up7], axis = 3)\n drop7 = Dropout(drop)(merge7)\n conv7 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop7)\n conv7 = Conv2D(nN*4, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv7)\n\n up8 = Conv2D(nN*2, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv7))\n merge8 = concatenate([conv2,up8], axis = 3)\n drop8 = Dropout(drop)(merge8)\n conv8 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop8)\n conv8 = Conv2D(nN*2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv8)\n\n up9 = Conv2D(nN, 2, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(UpSampling2D(size = (2,2))(conv8))\n merge9 = concatenate([conv1,up9], axis = 3)\n drop9 = Dropout(drop)(merge9)\n conv9 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(drop9)\n conv9 = Conv2D(nN, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv10 = Conv2D(2, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv9)\n conv11 = Conv2D(1, 3, activation = 'relu', padding = 'same', kernel_initializer = 'he_normal')(conv10)\n \n flatten = Flatten()(conv11)\n drop = Dropout(drop)(flatten)\n \n dense2 = Dense(input_size[1], activation = \"sigmoid\")(drop)\n\n model = Model(inputs = [inputs], outputs = [dense2])\n\n if(pretrained_weights):\n \tmodel.load_weights(pretrained_weights)\n\n\n model.compile(optimizer = \"adam\", loss = \"mean_absolute_error\", metrics = [\"accuracy\"])\n \n\n return (model)\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 10, "blob_id": "3979a8c9e9266ecef891bb3b48600aaafe323276", "content_id": "bf691dc35a7357331475807323fea4f4a967136a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11, "license_type": "no_license", "max_line_length": 10, "num_lines": 1, "path": "/README.md", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "# GDFT-Net\n" }, { "alpha_fraction": 0.5989847779273987, "alphanum_fraction": 0.6209813952445984, "avg_line_length": 30.774192810058594, "blob_id": "f9a31d4d072af7d0cea0ccee6d43b416575aaef9", "content_id": "5c5d7297ddd3495e080bf520ac0563dc97d6319d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2955, "license_type": "no_license", "max_line_length": 137, "num_lines": 93, "path": "/Core/Heuristic.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "\nimport scipy.stats as stats\nimport numpy as np\nimport time\nimport IPython\nimport matplotlib.pyplot as plt\n\ndef Heuristic(image,sigma0=10, mem = 5,no_mem = True):\n size = image.shape[0]\n raw_image = image[:,:,0]\n correct_delays = []\n\n def shift(correct_delays,i,memory):\n if i<mem or no_mem:\n return 1\n else:\n last_delays = correct_delays[i-mem:i]\n sig = np.std(last_delays)+1\n return (np.sqrt(sig))\n\n previous_delay = np.argmax(raw_image[:,0])\n correct_delays.append(previous_delay)\n i=1\n while i <image.shape[1]:\n col = raw_image[:,i]\n filter = stats.norm.pdf(np.linspace(int(-size/2),int(size/2),size),loc=previous_delay-size/2 ,scale = sigma0) \n previous_delay = np.argmax(col*filter)\n correct_delays.append(previous_delay)\n i+=1\n\n return(np.array(correct_delays)-size/2)\n\n\ndef Heuristic_V2(image,sigma0=10, SN_threshold = 1.4,scaling=np.abs):\n height = image.shape[0]\n length = image.shape[1]\n raw_image = image[:,:,0]\n predicted_delays = []\n\n temp=[sigma0]\n\n current_delay = np.argmax(raw_image[:,0])\n predicted_delays.append(current_delay)\n last_good_estimate=-5\n\n i=1\n while i <length:\n \n \n col = raw_image[:,i]\n broadening_factor = scaling(i-last_good_estimate)*sigma0\n\n #potentially smooth how window moves around?\n window = stats.norm.pdf(np.linspace(int(-height/2),int(height/2),height),loc=current_delay-height/2 ,scale = broadening_factor) \n current_delay = np.argmax(col*window)\n predicted_delays.append(current_delay)\n\n SN = col[current_delay]/np.mean(np.delete(col,current_delay))\n if SN>SN_threshold:\n last_good_estimate=i\n \n temp.append(broadening_factor)\n\n i+=1\n\n \n\n return(np.array(predicted_delays)-height/2,temp)\n\n\n\ndef Hueristic_Images(images,sigma0=10, mem = 5):\n start_time = time.time()\n New_Images = []\n i=0\n out = display(IPython.display.Pretty('Starting'), display_id=True)\n for image in images:\n out.update(IPython.display.Pretty(\"{0:4.1f}% done\".format(i/len(images)*100)))\n New_Images.append(Heuristic(image,sigma0,mem))\n i+=1\n print(\"Finished | Time taken: %s\" % (time.strftime(\"%H:%M:%S\", time.gmtime(time.time()-start_time))))\n return np.array(New_Images)\n \ndef Hueristic_Images_V2(images,sigma0=10, SN_threshold = 5,scaling = np.abs):\n start_time = time.time()\n New_Images = []\n i=0\n out = display(IPython.display.Pretty('Starting'), display_id=True)\n for image in images:\n out.update(IPython.display.Pretty(\"{0:4.1f}% done\".format(i/len(images)*100)))\n New_Images.append(Heuristic_V2(image,sigma0,SN_threshold,scaling)[0])\n i+=1\n print(\"Finished | Time taken: %s\" % (time.strftime(\"%H:%M:%S\", time.gmtime(time.time()-start_time))))\n return np.array(New_Images)" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 72, "blob_id": "39d64a79a12676ca7632aafc383a2bf2406abacc", "content_id": "201df1eb64e716bc9c72ed386c814d34cff73c1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 72, "license_type": "no_license", "max_line_length": 72, "num_lines": 1, "path": "/Core/__init__.py", "repo_name": "jonasserry/GDFT-Net", "src_encoding": "UTF-8", "text": "__all__ = [\"GDFT_Data\", \"GDFT_Net\",\"GDFT_Sim\",\"Heuristic\",\"GDFT_Tester\"]" } ]
7
wwhappylife/deep_equilibrium_inverse
https://github.com/wwhappylife/deep_equilibrium_inverse
fd15fc294734957cde71d5c0208240d006a43af9
94a5ac58b2904d7d3cbd7f7320044fa303c56c65
20057d9000707f326f69c3f3101fdbbe2abf0219
refs/heads/main
2023-05-25T00:58:29.696634
2021-05-31T14:18:46
2021-05-31T14:18:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8061674237251282, "alphanum_fraction": 0.8061674237251282, "avg_line_length": 55.75, "blob_id": "1994b318f634b463281055dd8d5daa6633538f12", "content_id": "a305c35a5b02947e06bb121782fb9848848693f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 227, "license_type": "no_license", "max_line_length": 107, "num_lines": 4, "path": "/README.md", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "# deep_equilibrium_inverse\nCode related to the paper \"Deep Equilibrium Architectures for Inverse Problems in Imaging\"\n\nCode is a bit messy at this time. Cleanup ongoing! Training occurs in the ./scripts/fixedpoints/ directory.\n" }, { "alpha_fraction": 0.4987594485282898, "alphanum_fraction": 0.506636917591095, "avg_line_length": 47.41441345214844, "blob_id": "465cafcafeb44b19f4a7df74db6dc77c04854b2b", "content_id": "c7ebd28afc93a374cde2a3f249dd4a63811a4fc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16122, "license_type": "no_license", "max_line_length": 130, "num_lines": 333, "path": "/training/refactor_equilibrium_training.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nfrom solvers import new_equilibrium_utils as eq_utils\nfrom torch import autograd\nfrom utils import cg_utils\n\ndef train_solver(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs, deep_eq_module,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0):\n\n for epoch in range(start_epoch, n_epochs):\n\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch.to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n optimizer.step()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\ndef train_solver_precond(single_iterate_solver, train_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs, deep_eq_module,\n use_dataparallel=False, device='cpu', scheduler=None, noise_sigma=0.000001, precond_iterates=100,\n print_every_n_steps=2, save_every_n_epochs=5, start_epoch=0, forward_operator = None,\n test_dataloader = None):\n previous_loss = 10.0\n reset_flag = False\n\n for epoch in range(start_epoch, n_epochs):\n\n if reset_flag:\n save_state_dict = torch.load(save_location)\n single_iterate_solver.load_state_dict(save_state_dict['solver_state_dict'])\n optimizer.load_state_dict(save_state_dict['optimizer_state_dict'])\n reset_flag = False\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch[0].to(device=device)\n target_img = sample_batch[1].to(device=device)\n y = measurement_process(sample_batch)\n if forward_operator is not None:\n with torch.no_grad():\n initial_point = forward_operator.adjoint(y)\n reconstruction = deep_eq_module.forward(y, initial_point=initial_point)\n else:\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, target_img)\n if np.isnan(loss.item()):\n reset_flag = True\n break\n loss.backward()\n optimizer.step()\n\n if ii == 0:\n previous_loss = loss.item()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n if ii % 200 == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch+1,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch+1,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n if (previous_loss - loss.item()) / previous_loss < -10.0 or np.isnan(loss.item()):\n reset_flag = True\n\n if scheduler is not None:\n scheduler.step(epoch)\n if not reset_flag:\n if use_dataparallel:\n # torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n # 'epoch': epoch,\n # 'optimizer_state_dict': optimizer.state_dict(),\n # 'scheduler_state_dict': scheduler.state_dict()\n # }, save_location + \"_\" + str(epoch))\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n # torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n # 'epoch': epoch,\n # 'optimizer_state_dict': optimizer.state_dict(),\n # 'scheduler_state_dict': scheduler.state_dict()\n # }, save_location + \"_\" + str(epoch))\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\ndef train_solver_precond1(single_iterate_solver, train_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs, deep_eq_module,\n use_dataparallel=False, device='cpu', scheduler=None, noise_sigma=0.000001, precond_iterates=100,\n print_every_n_steps=2, save_every_n_epochs=5, start_epoch=0, forward_operator = None,\n test_dataloader = None):\n previous_loss = 10.0\n reset_flag = False\n\n for epoch in range(start_epoch, n_epochs):\n\n if reset_flag:\n save_state_dict = torch.load(save_location)\n single_iterate_solver.load_state_dict(save_state_dict['solver_state_dict'])\n optimizer.load_state_dict(save_state_dict['optimizer_state_dict'])\n reset_flag = False\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch.to(device=device)\n y = measurement_process(sample_batch)\n if forward_operator is not None:\n with torch.no_grad():\n initial_point = cg_utils.conjugate_gradient(initial_point=forward_operator.adjoint(y),\n ATA=forward_operator.gramian,\n regularization_lambda=noise_sigma, n_iterations=precond_iterates)\n reconstruction = deep_eq_module.forward(y, initial_point=initial_point)\n else:\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n if np.isnan(loss.item()):\n reset_flag = True\n break\n loss.backward()\n optimizer.step()\n\n if ii == 0:\n previous_loss = loss.item()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if ii % 200 == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch+1,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch+1,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n if (previous_loss - loss.item()) / previous_loss < -10.0 or np.isnan(loss.item()):\n reset_flag = True\n\n if scheduler is not None:\n scheduler.step(epoch)\n if not reset_flag:\n if use_dataparallel:\n # torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n # 'epoch': epoch,\n # 'optimizer_state_dict': optimizer.state_dict(),\n # 'scheduler_state_dict': scheduler.state_dict()\n # }, save_location + \"_\" + str(epoch))\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n # torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n # 'epoch': epoch,\n # 'optimizer_state_dict': optimizer.state_dict(),\n # 'scheduler_state_dict': scheduler.state_dict()\n # }, save_location + \"_\" + str(epoch))\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n\ndef train_solver_mnist(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0, max_iters=100):\n\n n_iterations = [5]*n_epochs\n for ee in range(n_epochs):\n if ee >= 20:\n n_iterations[ee] = 5\n if ee >= 23:\n n_iterations[ee] = 7\n if ee >= 28:\n n_iterations[ee] = 9\n if ee >= 38:\n n_iterations[ee] = 11\n if ee >= 44:\n n_iterations[ee] = 13\n if ee >= 50:\n n_iterations[ee] = 20\n if ee >= 58:\n n_iterations[ee] = 30\n\n forward_iterator = eq_utils.anderson\n deep_eq_module = eq_utils.DEQFixedPoint(single_iterate_solver, solver=forward_iterator,\n m=5, lam=1e-4, max_iter=max_iters, tol=1e-3, beta=1.5)\n\n for epoch in range(start_epoch, n_epochs):\n\n # We are lucky to have\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch[0].to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n optimizer.step()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n #####################TEST##########################\n # loss_accumulator = []\n # mse_loss = torch.nn.MSELoss()\n # for ii, sample_batch in enumerate(test_dataloader):\n # sample_batch = sample_batch.to(device=device)\n # y = measurement_process(sample_batch)\n # initial_point = y\n # reconstruction = solver(initial_point, iterations=6)\n #\n # reconstruction = torch.clamp(reconstruction, -1 ,1)\n #\n # loss = mse_loss(reconstruction, sample_batch)\n # loss_logger = loss.cpu().detach().numpy()\n # loss_accumulator.append(loss_logger)\n #\n # loss_array = np.asarray(loss_accumulator)\n # loss_mse = np.mean(loss_array)\n # PSNR = -10 * np.log10(loss_mse)\n # percentiles = np.percentile(loss_array, [25,50,75])\n # percentiles = -10.0*np.log10(percentiles)\n # print(\"TEST LOSS: \" + str(sum(loss_accumulator) / len(loss_accumulator)), flush=True)\n # print(\"MEAN TEST PSNR: \" + str(PSNR), flush=True)\n # print(\"TEST PSNR QUARTILES AND MEDIAN: \" + str(percentiles[0]) +\n # \", \" + str(percentiles[1]) + \", \" + str(percentiles[2]), flush=True)\n" }, { "alpha_fraction": 0.4902310371398926, "alphanum_fraction": 0.499643474817276, "avg_line_length": 44.8300666809082, "blob_id": "0365c8703fff80b4235beb70929342038ff89058", "content_id": "0ba1d8f8847f8f024c442e84bef55fd37fee4bde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14024, "license_type": "no_license", "max_line_length": 129, "num_lines": 306, "path": "/training/equilibrium_training.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nfrom solvers import equilibrium_utils as eq_utils\nfrom torch import autograd\n\ndef train_solver(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0):\n\n n_iterations = [5]*n_epochs\n for ee in range(n_epochs):\n if ee >= 5:\n n_iterations[ee] = 5\n if ee >= 8:\n n_iterations[ee] = 8\n if ee >= 10:\n n_iterations[ee] = 10\n if ee >= 12:\n n_iterations[ee] = 15\n if ee >= 15:\n n_iterations[ee] = 20\n\n for epoch in range(start_epoch, n_epochs):\n\n # We are lucky to have\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch.to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = eq_utils.get_equilibrium_point(y, single_iterate_solver, max_iterations=n_iterations[epoch])\n\n reconstruction = torch.clamp(reconstruction, -1, 1)\n loss = loss_function(reconstruction, sample_batch)\n\n if epoch < 2:\n loss.backward()\n optimizer.step()\n else:\n\n # f_zstar = single_iterate_solver(static_zstar)\n\n # delf_deltheta = torch.autograd.grad(inputs=static_zstar, outputs=f_zstar,\n # grad_outputs=torch.ones_like(f_zstar))\n\n dell_delz = torch.autograd.grad(inputs=reconstruction, outputs=loss,\n grad_outputs=torch.ones_like(loss))[0]\n\n delf_deltheta_invJ = eq_utils.conjugate_gradient_equilibriumgrad(b=dell_delz,\n input_z=reconstruction,\n f_function=single_iterate_solver,\n n_iterations=5)\n\n # loss.backward(retain_graph=True)\n torch.autograd.backward(tensors=reconstruction, grad_tensors=delf_deltheta_invJ)\n optimizer.step()\n\n # exit()\n # for name, param in single_iterate_solver.named_parameters():\n # jj = 0\n # if param.grad is not None:\n # print(name)\n # print(param.shape)\n # print(param.grad.shape)\n # jj+=1\n # if jj == 2:\n # break\n # exit()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n\n #####################TEST##########################\n # loss_accumulator = []\n # mse_loss = torch.nn.MSELoss()\n # for ii, sample_batch in enumerate(test_dataloader):\n # sample_batch = sample_batch.to(device=device)\n # y = measurement_process(sample_batch)\n # initial_point = y\n # reconstruction = solver(initial_point, iterations=6)\n #\n # reconstruction = torch.clamp(reconstruction, -1 ,1)\n #\n # loss = mse_loss(reconstruction, sample_batch)\n # loss_logger = loss.cpu().detach().numpy()\n # loss_accumulator.append(loss_logger)\n #\n # loss_array = np.asarray(loss_accumulator)\n # loss_mse = np.mean(loss_array)\n # PSNR = -10 * np.log10(loss_mse)\n # percentiles = np.percentile(loss_array, [25,50,75])\n # percentiles = -10.0*np.log10(percentiles)\n # print(\"TEST LOSS: \" + str(sum(loss_accumulator) / len(loss_accumulator)), flush=True)\n # print(\"MEAN TEST PSNR: \" + str(PSNR), flush=True)\n # print(\"TEST PSNR QUARTILES AND MEDIAN: \" + str(percentiles[0]) +\n # \", \" + str(percentiles[1]) + \", \" + str(percentiles[2]), flush=True)\n\ndef train_solver_mnist(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0):\n\n n_iterations = [5]*n_epochs\n for ee in range(n_epochs):\n if ee >= 20:\n n_iterations[ee] = 5\n if ee >= 23:\n n_iterations[ee] = 7\n if ee >= 28:\n n_iterations[ee] = 9\n if ee >= 38:\n n_iterations[ee] = 11\n if ee >= 44:\n n_iterations[ee] = 13\n if ee >= 50:\n n_iterations[ee] = 20\n if ee >= 58:\n n_iterations[ee] = 30\n\n for epoch in range(start_epoch, n_epochs):\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch[0].to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n\n def jacobian_vector_product(f, z, v):\n z = z.detach().requires_grad_()\n v = v.detach().requires_grad_()\n\n vjp_val = autograd.grad(f(z), z, v, create_graph=True)[0]\n return vjp_val\n # jvp_val = autograd.grad(vjp_val, v, v.detach(), create_graph=True)[0]\n # return jvp_val\n\n if epoch < 10:\n reconstruction = eq_utils.get_equilibrium_point(y, single_iterate_solver,\n max_iterations=n_iterations[epoch])\n\n reconstruction = torch.clamp(reconstruction, 0, 1)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n # for name, param in single_iterate_solver.named_parameters():\n # if param.grad is not None:\n # print(name)\n # print(param.grad.shape)\n\n # torch.autograd.backward(reconstruction, grad_tensors=reconstruction)\n # for name, param in single_iterate_solver.named_parameters():\n # if param.grad is not None:\n # print(name)\n # print(param.grad.shape)\n\n # print(autograd.functional.jacobian(single_iterate_solver, reconstruction).shape)\n # exit()\n optimizer.step()\n else:\n exit()\n\n # f_zstar = single_iterate_solver(static_zstar)\n # reconstruction = single_iterate_solver(sample_batch)\n\n # reconstruction = eq_utils.get_equilibrium_point(y, single_iterate_solver,\n # max_iterations=n_iterations[epoch])\n reconstruction = eq_utils.get_equilibrium_point(y, single_iterate_solver,\n max_iterations=n_iterations[epoch])\n\n reconstruction = torch.clamp(reconstruction, 0, 1)\n loss = loss_function(reconstruction, sample_batch)\n\n # delf_deltheta = torch.autograd.grad(inputs=static_zstar, outputs=f_zstar,\n # grad_outputs=torch.ones_like(f_zstar))\n\n dell_delz = torch.autograd.grad(inputs=reconstruction, outputs=loss,\n grad_outputs=torch.ones_like(loss))[0]\n\n\n\n # delf_deltheta_invJ = eq_utils.conjugate_gradient_equilibriumgrad(b=dell_delz,\n # input_z=sample_batch.requires_grad_(),\n # f_function=single_iterate_solver,\n # n_iterations=10)\n # torch.autograd.backward(tensors=single_iterate_solver(sample_batch), grad_tensors=delf_deltheta_invJ)\n\n delf_deltheta_invJ = eq_utils.conjugate_gradient_equilibriumgrad(b=dell_delz,\n input_z=reconstruction,\n f_function=single_iterate_solver,\n n_iterations=10)\n torch.autograd.backward(tensors=reconstruction, grad_tensors=-delf_deltheta_invJ)\n\n torch.nn.utils.clip_grad_norm_(single_iterate_solver.parameters(), 1.0)\n\n # for name, param in single_iterate_solver.named_parameters():\n # if param.grad is not None:\n # print(name)\n # print(torch.norm(param.grad))\n\n # jacobian_vect_product = delf_deltheta_invJ#.flatten(start_dim=1)\n\n # vector_jacobian_product = jacobian_vector_product(single_iterate_solver, reconstruction, jacobian_vect_product)\n # print(vector_jacobian_product.shape)\n # exit()\n\n # gradient = torch.reshape(jacobian_vect_product, (8,1,28,28))\n # gradient = torch.squeeze(torch.mean(gradient, dim=0))\n # print(single_iterate_solver.nonlinear_op.linear_layer(torch.flatten(delf_deltheta_invJ, start_dim=1)))\n # print(delf_deltheta_invJ.shape)\n #\n # exit()\n\n # torch.autograd.backward(tensors=reconstruction, grad_tensors=delf_deltheta_invJ)\n optimizer.step()\n\n # exit()\n # for name, param in single_iterate_solver.named_parameters():\n # jj = 0\n # if param.grad is not None:\n # print(name)\n # print(param.shape)\n # print(param.grad.shape)\n # jj+=1\n # if jj == 2:\n # break\n # exit()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n #####################TEST##########################\n # loss_accumulator = []\n # mse_loss = torch.nn.MSELoss()\n # for ii, sample_batch in enumerate(test_dataloader):\n # sample_batch = sample_batch.to(device=device)\n # y = measurement_process(sample_batch)\n # initial_point = y\n # reconstruction = solver(initial_point, iterations=6)\n #\n # reconstruction = torch.clamp(reconstruction, -1 ,1)\n #\n # loss = mse_loss(reconstruction, sample_batch)\n # loss_logger = loss.cpu().detach().numpy()\n # loss_accumulator.append(loss_logger)\n #\n # loss_array = np.asarray(loss_accumulator)\n # loss_mse = np.mean(loss_array)\n # PSNR = -10 * np.log10(loss_mse)\n # percentiles = np.percentile(loss_array, [25,50,75])\n # percentiles = -10.0*np.log10(percentiles)\n # print(\"TEST LOSS: \" + str(sum(loss_accumulator) / len(loss_accumulator)), flush=True)\n # print(\"MEAN TEST PSNR: \" + str(PSNR), flush=True)\n # print(\"TEST PSNR QUARTILES AND MEDIAN: \" + str(percentiles[0]) +\n # \", \" + str(percentiles[1]) + \", \" + str(percentiles[2]), flush=True)\n" }, { "alpha_fraction": 0.5609123706817627, "alphanum_fraction": 0.5767236948013306, "avg_line_length": 34.73147964477539, "blob_id": "2a567933a1c0b4f86ec5a7dd71b65060d5755ca4", "content_id": "d72636d7c0a0dff83c1b7cdb3dfb483b3bc5e8c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3858, "license_type": "no_license", "max_line_length": 98, "num_lines": 108, "path": "/utils/bsd500.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport h5py\nimport random\nimport numpy as np\nimport os\nfrom PIL import Image\nfrom torchvision import transforms\n\nclass Dataset(torch.utils.data.Dataset):\n def __init__(self, train=True, mode='S'):\n super(Dataset, self).__init__()\n self.train = train\n self.mode = mode\n self.data_loc = '/share/data/vision-greg2/users/gilton/train.h5'\n self.val_loc = '/share/data/vision-greg2/users/gilton/val.h5'\n if self.train:\n if self.mode == 'S':\n h5f = h5py.File(self.data_loc, 'r')\n elif self.mode == 'B':\n h5f = h5py.File('train_B.h5', 'r')\n else:\n if self.mode == 'S':\n h5f = h5py.File(self.val_loc, 'r')\n elif self.mode == 'B':\n h5f = h5py.File('val_B.h5', 'r')\n self.keys = list(h5f.keys())\n random.shuffle(self.keys)\n h5f.close()\n def __len__(self):\n return len(self.keys)\n def __getitem__(self, index):\n if self.train:\n if self.mode == 'S':\n h5f = h5py.File(self.data_loc, 'r')\n elif self.mode == 'B':\n h5f = h5py.File('train_B.h5', 'r')\n # h5f = h5py.File('train.h5', 'r')\n else:\n if self.mode == 'S':\n h5f = h5py.File(self.val_loc, 'r')\n elif self.mode == 'B':\n h5f = h5py.File('val_B.h5', 'r')\n # h5f = h5py.File('val.h5', 'r')\n\n key = self.keys[index]\n #scale from -1 to 1\n data = 2*np.array(h5f[key]) - 1\n h5f.close()\n return torch.Tensor(data)\n\ndef directory_filelist(target_directory):\n file_list = [f for f in sorted(os.listdir(target_directory))\n if os.path.isfile(os.path.join(target_directory, f))]\n file_list = list(file_list)\n file_list = [f for f in file_list if not f.startswith('.')]\n return file_list\n\ndef load_img(file_name):\n with open(file_name,'rb') as f:\n img = Image.open(f).convert(\"L\")\n return img\n\nclass EquilibriumDataset(torch.utils.data.Dataset):\n def __init__(self, target_directory, init_directory, validation_data=False, transform=None):\n super(EquilibriumDataset, self).__init__()\n filelist = directory_filelist(target_directory)\n training_data = filelist\n\n self.full_filelist = [target_directory + single_file for single_file in training_data]\n self.init_directory = init_directory\n\n self.transform = transform\n self.options = ['_1.png','_2.png','_3.png','_4.png']\n\n def __len__(self):\n return len(self.full_filelist)\n\n def convert_to_2d(self, x):\n return torch.cat((x, torch.zeros_like(x)), dim=0)\n\n def __getitem__(self, item):\n image_name = self.full_filelist[item]\n # image_name = \"/Users/dgilton/Documents/MATLAB/prDeep-master/train/test_001.png\"\n data = load_img(image_name)\n if self.transform is not None:\n data = self.transform(data)\n data = 2.0*data - 1.0\n data = self.convert_to_2d(data)\n\n random_choice = random.choice(self.options)\n initial_point_filename = os.path.splitext(os.path.split(image_name)[1])[0] + random_choice\n initial_point = load_img(self.init_directory + initial_point_filename)\n if self.transform is not None:\n initial_point = self.transform(initial_point)\n initial_point = 2.0 * initial_point - 1.0\n initial_point = self.convert_to_2d(initial_point)\n\n return data, initial_point\n\nif __name__==\"__main__\":\n dataset_folder = \"/Users/dgilton/PycharmProjects/provableplaying/training/data/train/\"\n transform = transforms.Compose(\n [\n transforms.ToTensor(),\n ]\n )\n dataset = EquilibriumDataset(dataset_folder, transform=transform)\n print(dataset[0].shape)" }, { "alpha_fraction": 0.6880070567131042, "alphanum_fraction": 0.7009883522987366, "avg_line_length": 38.64327621459961, "blob_id": "83f740579d7782d1a7b863063c5342eff270ed44", "content_id": "bdea86eb5700d9377014eb79d98386e6dcb4c8bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6779, "license_type": "no_license", "max_line_length": 122, "num_lines": 171, "path": "/scripts/fixedpoint/deblur_proxgrad_fixedeta_pre.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport random\nimport sys\nimport argparse\nsys.path.append('/home-nfs/gilton/learned_iterative_solvers')\n# sys.path.append('/Users/dgilton/PycharmProjects/learned_iterative_solvers')\n\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\n\nimport operators.blurs as blurs\nfrom operators.operator import OperatorPlusNoise\nfrom utils.celeba_dataloader import CelebaTrainingDatasetSubset, CelebaTestDataset\nfrom networks.normalized_equilibrium_u_net import UnetModel, DnCNN\nfrom solvers.equilibrium_solvers import EquilibriumProxGrad\nfrom training import refactor_equilibrium_training\nfrom solvers import new_equilibrium_utils as eq_utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', default=80)\nparser.add_argument('--batch_size', type=int, default=16)\nparser.add_argument('--and_maxiters', default=100)\nparser.add_argument('--and_beta', type=float, default=1.0)\nparser.add_argument('--and_m', type=int, default=5)\nparser.add_argument('--lr', type=float, default=0.1)\nparser.add_argument('--etainit', type=float, default=0.9)\nparser.add_argument('--lr_gamma', type=float, default=0.1)\nparser.add_argument('--sched_step', type=int, default=10)\nparser.add_argument('--savepath',\n default=\"/share/data/vision-greg2/users/gilton/celeba_equilibriumgrad_blur_save_inf.ckpt\")\nargs = parser.parse_args()\n\n\n# Parameters to modify\nn_epochs = int(args.n_epochs)\ncurrent_epoch = 0\nbatch_size = int(args.batch_size)\nn_channels = 3\nmax_iters = int(args.and_maxiters)\nanderson_m = int(args.and_m)\nanderson_beta = float(args.and_beta)\n\nlearning_rate = float(args.lr)\nprint_every_n_steps = 2\nsave_every_n_epochs = 1\ninitial_eta = 0.2\n\ninitial_data_points = 10000\n# point this towards your celeba files\ndata_location = \"/share/data/vision-greg2/mixpatch/img_align_celeba/\"\n\nkernel_size = 5\nkernel_sigma = 5.0\nnoise_sigma = 1e-2\n\n# modify this for your machine\n# save_location = \"/share/data/vision-greg2/users/gilton/mnist_equilibriumgrad_blur.ckpt\"\nsave_location = args.savepath\nload_location = \"/share/data/willett-group/users/gilton/denoisers/celeba_denoiser_normunet_3.ckpt\"\n\ngpu_ids = []\nfor ii in range(6):\n try:\n torch.cuda.get_device_properties(ii)\n print(str(ii), flush=True)\n if not gpu_ids:\n gpu_ids = [ii]\n else:\n gpu_ids.append(ii)\n except AssertionError:\n print('Not ' + str(ii) + \"!\", flush=True)\n\nprint(os.getenv('CUDA_VISIBLE_DEVICES'), flush=True)\ngpu_ids = [int(x) for x in gpu_ids]\n# device management\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nuse_dataparallel = len(gpu_ids) > 1\nprint(\"GPU IDs: \" + str([int(x) for x in gpu_ids]), flush=True)\n\n# Set up data and dataloaders\ntransform = transforms.Compose(\n [\n transforms.Resize((128, 128)),\n transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ]\n)\nceleba_train_size = 162770\ntotal_data = initial_data_points\ntotal_indices = random.sample(range(celeba_train_size), k=total_data)\ninitial_indices = total_indices\n\ndataset = CelebaTrainingDatasetSubset(data_location, subset_indices=initial_indices, transform=transform)\ndataloader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=batch_size, shuffle=True, drop_last=True,\n)\n\ntest_dataset = CelebaTestDataset(data_location, transform=transform)\ntest_dataloader = torch.utils.data.DataLoader(\n dataset=test_dataset, batch_size=batch_size, shuffle=False, drop_last=True,\n)\n\n### Set up solver and problem setting\n\nforward_operator = blurs.GaussianBlur(sigma=kernel_sigma, kernel_size=kernel_size,\n n_channels=3, n_spatial_dimensions=2).to(device=device)\nmeasurement_process = OperatorPlusNoise(forward_operator, noise_sigma=noise_sigma).to(device=device)\n\ninternal_forward_operator = blurs.GaussianBlur(sigma=kernel_sigma, kernel_size=kernel_size,\n n_channels=3, n_spatial_dimensions=2).to(device=device)\n\n# standard u-net\n# learned_component = UnetModel(in_chans=n_channels, out_chans=n_channels, num_pool_layers=4,\n# drop_prob=0.0, chans=32)\nlearned_component = DnCNN(channels=n_channels)\n\nif os.path.exists(load_location):\n if torch.cuda.is_available():\n saved_dict = torch.load(load_location)\n else:\n saved_dict = torch.load(load_location, map_location='cpu')\n\n start_epoch = saved_dict['epoch']\n learned_component.load_state_dict(saved_dict['solver_state_dict'])\n\n# learned_component = Autoencoder()\nsolver = EquilibriumProxGrad(linear_operator=internal_forward_operator, nonlinear_operator=learned_component,\n eta=initial_eta, minval=-1, maxval = 1)\n\nif use_dataparallel:\n solver = nn.DataParallel(solver, device_ids=gpu_ids)\nsolver = solver.to(device=device)\n\nstart_epoch = 0\noptimizer = optim.Adam(params=solver.parameters(), lr=learning_rate)\nscheduler = optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=int(args.sched_step), gamma=float(args.lr_gamma))\ncpu_only = not torch.cuda.is_available()\n\n\nif os.path.exists(save_location):\n if not cpu_only:\n saved_dict = torch.load(save_location)\n else:\n saved_dict = torch.load(save_location, map_location='cpu')\n\n start_epoch = saved_dict['epoch']\n solver.load_state_dict(saved_dict['solver_state_dict'])\n # optimizer.load_state_dict(saved_dict['optimizer_state_dict'])\n scheduler.load_state_dict(saved_dict['scheduler_state_dict'])\n\n\n# set up loss and train\nlossfunction = torch.nn.MSELoss(reduction='sum')\n\nforward_iterator = eq_utils.andersonexp\ndeep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, m=anderson_m, beta=anderson_beta, lam=1e-2,\n max_iter=max_iters, tol=1e-5)\n# forward_iterator = eq_utils.forward_iteration\n# deep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, max_iter=100, tol=1e-8)\n\n# Do train\nrefactor_equilibrium_training.train_solver_precond1(\n single_iterate_solver=solver, train_dataloader=dataloader, test_dataloader=test_dataloader,\n measurement_process=measurement_process, optimizer=optimizer, save_location=save_location,\n deep_eq_module=deep_eq_module, loss_function=lossfunction, n_epochs=n_epochs,\n use_dataparallel=use_dataparallel, device=device, scheduler=scheduler,\n print_every_n_steps=print_every_n_steps, save_every_n_epochs=save_every_n_epochs,\n start_epoch=start_epoch, forward_operator = forward_operator, noise_sigma=noise_sigma,\n precond_iterates=60)\n" }, { "alpha_fraction": 0.696672260761261, "alphanum_fraction": 0.707866907119751, "avg_line_length": 39.50310516357422, "blob_id": "5ccad425f2bf7f9e1518480f9238f18e49d7baf2", "content_id": "06c50e3e2f22b9c0f00486506a4d2d998f4465bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6521, "license_type": "no_license", "max_line_length": 121, "num_lines": 161, "path": "/scripts/fixedpoint/mri_prox_fixedeta_pre_and.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport random\nimport sys\nimport argparse\nsys.path.append('/home-nfs/gilton/learned_iterative_solvers')\n# sys.path.append('/Users/dgilton/PycharmProjects/learned_iterative_solvers')\n\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport operators.singlecoil_mri as mrimodel\nfrom operators.operator import OperatorPlusNoise\nfrom utils.fastmri_dataloader import singleCoilFastMRIDataloader\nfrom networks.normalized_equilibrium_u_net import UnetModel, DnCNN\nfrom solvers.equilibrium_solvers import EquilibriumProxGradMRI\nfrom training import refactor_equilibrium_training\nfrom solvers import new_equilibrium_utils as eq_utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', default=80)\nparser.add_argument('--batch_size', type=int, default=16)\nparser.add_argument('--and_maxiters', default=100)\nparser.add_argument('--and_beta', type=float, default=1.0)\nparser.add_argument('--and_m', type=int, default=5)\nparser.add_argument('--lr', type=float, default=0.1)\nparser.add_argument('--etainit', type=float, default=0.4)\nparser.add_argument('--lr_gamma', type=float, default=0.1)\nparser.add_argument('--sched_step', type=int, default=10)\nparser.add_argument('--acceleration', type=float, default=8.0)\nparser.add_argument('--savepath',\n default=\"/share/data/vision-greg2/users/gilton/celeba_equilibriumgrad_mri_save_inf.ckpt\")\nparser.add_argument('--loadpath',\n default=\"/share/data/vision-greg2/users/gilton/celeba_equilibriumgrad_mri_save_inf.ckpt\")\nargs = parser.parse_args()\n\n\n# Parameters to modify\nn_epochs = int(args.n_epochs)\ncurrent_epoch = 0\nbatch_size = int(args.batch_size)\nn_channels = 2\nmax_iters = int(args.and_maxiters)\nanderson_m = int(args.and_m)\nanderson_beta = float(args.and_beta)\n\nlearning_rate = float(args.lr)\nprint_every_n_steps = 2\nsave_every_n_epochs = 1\ninitial_eta = float(args.etainit)\n\ndataheight = 320\ndatawidth = 320\nmri_center_fraction = 0.04\nmri_acceleration = float(args.acceleration)\n\nmask = mrimodel.create_mask(shape=[dataheight, datawidth, 2], acceleration=mri_acceleration,\n center_fraction=mri_center_fraction, seed=10)\n\nnoise_sigma = 1e-2\n\n# modify this for your machine\n# save_location = \"/share/data/vision-greg2/users/gilton/mnist_equilibriumgrad_blur.ckpt\"\nsave_location = args.savepath\nload_location = \"/share/data/willett-group/users/gilton/denoisers/mri_denoiser_unetnorm_4.ckpt\"\n\ngpu_ids = []\nfor ii in range(6):\n try:\n torch.cuda.get_device_properties(ii)\n print(str(ii), flush=True)\n if not gpu_ids:\n gpu_ids = [ii]\n else:\n gpu_ids.append(ii)\n except AssertionError:\n print('Not ' + str(ii) + \"!\", flush=True)\n\nprint(os.getenv('CUDA_VISIBLE_DEVICES'), flush=True)\ngpu_ids = [int(x) for x in gpu_ids]\n# device management\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nuse_dataparallel = len(gpu_ids) > 1\nprint(\"GPU IDs: \" + str([int(x) for x in gpu_ids]), flush=True)\n\n# Set up data and dataloaders\ndata_location = \"/share/data/vision-greg2/users/gilton/singlecoil_curated_clean/\"\ntrainset_size = 2000\ntotal_data = 2194\nrandom.seed(10)\nall_indices = list(range(trainset_size))\ntrain_indices = random.sample(range(total_data), k=trainset_size)\ndataset = singleCoilFastMRIDataloader(data_location, data_indices=train_indices)\ndataloader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=args.batch_size, shuffle=True, drop_last=True,\n)\n\n### Set up solver and problem setting\n\nforward_operator = mrimodel.cartesianSingleCoilMRI(kspace_mask=mask).to(device=device)\nmeasurement_process = OperatorPlusNoise(forward_operator, noise_sigma=noise_sigma).to(device=device)\n\ninternal_forward_operator = mrimodel.cartesianSingleCoilMRI(kspace_mask=mask).to(device=device)\n\n# standard u-net\n# learned_component = UnetModel(in_chans=n_channels, out_chans=n_channels, num_pool_layers=4,\n# drop_prob=0.0, chans=32)\nlearned_component = DnCNN(channels=n_channels)\n\ncpu_only = not torch.cuda.is_available()\nif os.path.exists(load_location):\n if not cpu_only:\n saved_dict = torch.load(load_location)\n else:\n saved_dict = torch.load(load_location, map_location='cpu')\n learned_component.load_state_dict(saved_dict['solver_state_dict'])\n\n# learned_component = Autoencoder()\nsolver = EquilibriumProxGradMRI(linear_operator=internal_forward_operator, nonlinear_operator=learned_component,\n eta=initial_eta, minval=-1, maxval = 1)\n\nif use_dataparallel:\n solver = nn.DataParallel(solver, device_ids=gpu_ids)\nsolver = solver.to(device=device)\n\nstart_epoch = 0\noptimizer = optim.Adam(params=solver.parameters(), lr=learning_rate)\nscheduler = optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=int(args.sched_step), gamma=float(args.lr_gamma))\ncpu_only = not torch.cuda.is_available()\n\n\nif os.path.exists(save_location):\n if not cpu_only:\n saved_dict = torch.load(save_location)\n else:\n saved_dict = torch.load(save_location, map_location='cpu')\n\n start_epoch = saved_dict['epoch']\n solver.load_state_dict(saved_dict['solver_state_dict'])\n # optimizer.load_state_dict(saved_dict['optimizer_state_dict'])\n scheduler.load_state_dict(saved_dict['scheduler_state_dict'])\n\n\n# set up loss and train\nlossfunction = torch.nn.MSELoss(reduction='sum')\n\nforward_iterator = eq_utils.andersonexp\ndeep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, m=anderson_m, beta=anderson_beta, lam=1e-2,\n max_iter=max_iters, tol=1e-4)\n# forward_iterator = eq_utils.forward_iteration\n# deep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, max_iter=max_iters, tol=1e-8)\n\n# Do train\nrefactor_equilibrium_training.train_solver_precond(\n single_iterate_solver=solver, train_dataloader=dataloader,\n measurement_process=measurement_process, optimizer=optimizer, save_location=save_location,\n deep_eq_module=deep_eq_module, loss_function=lossfunction, n_epochs=n_epochs,\n use_dataparallel=use_dataparallel, device=device, scheduler=scheduler,\n print_every_n_steps=print_every_n_steps, save_every_n_epochs=save_every_n_epochs,\n start_epoch=start_epoch, forward_operator = forward_operator, noise_sigma=0.3,\n precond_iterates=50)\n" }, { "alpha_fraction": 0.5825028419494629, "alphanum_fraction": 0.5977671146392822, "avg_line_length": 31.623456954956055, "blob_id": "2949642e90a30a9741d85b85bb6636b4a1f939eb", "content_id": "089adc0a78e814836d6939cd964d47761c25bdb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15854, "license_type": "no_license", "max_line_length": 99, "num_lines": 486, "path": "/operators/singlecoil_mri.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch, numbers, math\nimport torch.nn as nn\nimport torch.nn.functional as torchfunc\nfrom operators.operator import LinearOperator\n\n\n\nimport numpy as np\nimport torch\n\n\ndef to_tensor(data):\n \"\"\"\n Convert numpy array to PyTorch tensor. For complex arrays, the real and imaginary parts\n are stacked along the last dimension.\n Args:\n data (np.array): Input numpy array\n Returns:\n torch.Tensor: PyTorch version of data\n \"\"\"\n if np.iscomplexobj(data):\n data = np.stack((data.real, data.imag), axis=-1)\n return torch.from_numpy(data)\n\n\ndef apply_mask(data, mask_func, seed=None, padding=None):\n \"\"\"\n Subsample given k-space by multiplying with a mask.\n Args:\n data (torch.Tensor): The input k-space data. This should have at least 3 dimensions, where\n dimensions -3 and -2 are the spatial dimensions, and the final dimension has size\n 2 (for complex values).\n mask_func (callable): A function that takes a shape (tuple of ints) and a random\n number seed and returns a mask.\n seed (int or 1-d array_like, optional): Seed for the random number generator.\n Returns:\n (tuple): tuple containing:\n masked data (torch.Tensor): Subsampled k-space data\n mask (torch.Tensor): The generated mask\n \"\"\"\n shape = np.array(data.shape)\n shape[:-3] = 1\n mask = mask_func(shape, seed)\n if padding is not None:\n mask[:, :, :padding[0]] = 0\n mask[:, :, padding[1]:] = 0 # padding value inclusive on right of zeros\n\n masked_data = data * mask + 0.0 # The + 0.0 removes the sign of the zeros\n return masked_data, mask\n\n\ndef mask_center(x, mask_from, mask_to):\n # b, c, h, w, two = x.shape\n mask = torch.zeros_like(x)\n mask[:, :, :, mask_from:mask_to] = x[:, :, :, mask_from:mask_to]\n return mask\n\n\ndef complex_mul(x, y):\n assert x.shape[-1] == y.shape[-1] == 2\n re = x[..., 0] * y[..., 0] - x[..., 1] * y[..., 1]\n im = x[..., 0] * y[..., 1] + x[..., 1] * y[..., 0]\n return torch.stack((re, im), dim=-1)\n\n\ndef complex_conj(x):\n assert x.shape[-1] == 2\n return torch.stack((x[..., 0], -x[..., 1]), dim=-1)\n\n\ndef fft2(data):\n \"\"\"\n Apply centered 2 dimensional Fast Fourier Transform.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n Returns:\n torch.Tensor: The FFT of the input.\n \"\"\"\n if not data.shape[-1] == 2:\n raise ValueError(\"Tensor does not have separate complex dim.\")\n\n data = ifftshift(data, dim=[-3, -2])\n data = torch.view_as_real(\n torch.fft.fftn( # type: ignore\n torch.view_as_complex(data), dim=(-2, -1), norm=\"ortho\"\n )\n )\n data = fftshift(data, dim=[-3, -2])\n\n return data\n\ndef dft_matrix(N, mask):\n learnable_parameters = torch.arange(0,N, dtype=torch.float32)\n learnable_parameters.requires_grad_(True)\n mask_vec = fftshift(mask[0, :], dim=0)\n mask_vec = mask_vec > 0\n mask_vec = mask_vec.squeeze()\n masked_params = torch.masked_select(learnable_parameters, mask_vec)\n normalizer = np.sqrt(N)\n\n ii, jj = torch.meshgrid(masked_params, torch.arange(0,N, dtype=torch.float32))\n\n W = torch.exp(-2.0 * np.pi * 1j * ii*jj / N) / normalizer\n\n return W\n\ndef onedfft(data, dim):\n # data = ifftshift(data, dim=dim)\n dim_size = data.shape[dim]\n for ii in range(dim_size):\n if dim==1:\n data[:,ii,:] = torch.fft.fftn( # type: ignore\n torch.view_as_complex(data), dim=0, norm=\"ortho\")\n else:\n data[ii, :, :] = torch.fft.fftn( # type: ignore\n torch.view_as_complex(data), dim=1, norm=\"ortho\")\n # data = ifftshift(data, dim=dim)\n return data\n\ndef onedifft(data, dim):\n # data = ifftshift(data, dim=dim)\n dim_size = data.shape[dim]\n for ii in range(dim_size):\n if dim==1:\n data[:,ii,:] = torch.fft.ifftn( # type: ignore\n torch.view_as_complex(data), dim=0, norm=\"ortho\")\n else:\n data[ii, :, :] = torch.fft.ifftn( # type: ignore\n torch.view_as_complex(data), dim=1, norm=\"ortho\")\n # data = ifftshift(data, dim=dim)\n return data\n\ndef ifft2(data):\n \"\"\"\n Apply centered 2-dimensional Inverse Fast Fourier Transform.\n Args:\n data (torch.Tensor): Complex valued input data containing at least 3 dimensions: dimensions\n -3 & -2 are spatial dimensions and dimension -1 has size 2. All other dimensions are\n assumed to be batch dimensions.\n Returns:\n torch.Tensor: The IFFT of the input.\n \"\"\"\n if not data.shape[-1] == 2:\n raise ValueError(\"Tensor does not have separate complex dim.\")\n\n data = ifftshift(data, dim=[-3, -2])\n data = torch.view_as_real(\n torch.fft.ifftn( # type: ignore\n torch.view_as_complex(data), dim=(-2, -1), norm=\"ortho\"\n )\n )\n data = fftshift(data, dim=[-3, -2])\n\n return data\n\ndef complex_abs(data):\n \"\"\"\n Compute the absolute value of a complex valued input tensor.\n Args:\n data (torch.Tensor): A complex valued tensor, where the size of the final dimension\n should be 2.\n Returns:\n torch.Tensor: Absolute value of data\n \"\"\"\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1).sqrt()\n\n\ndef complex_abs_sq(data):\n \"\"\"\n Compute the squared absolute value of a complex tensor\n \"\"\"\n assert data.size(-1) == 2\n return (data ** 2).sum(dim=-1)\n\n\ndef root_sum_of_squares(data, dim=0):\n \"\"\"\n Compute the Root Sum of Squares (RSS) transform along a given dimension of a tensor.\n Args:\n data (torch.Tensor): The input tensor\n dim (int): The dimensions along which to apply the RSS transform\n Returns:\n torch.Tensor: The RSS value\n \"\"\"\n return torch.sqrt((data ** 2).sum(dim))\n\n\ndef root_sum_of_squares_complex(data, dim=0):\n \"\"\"\n Compute the Root Sum of Squares (RSS) transform along a given dimension of a tensor.\n Args:\n data (torch.Tensor): The input tensor\n dim (int): The dimensions along which to apply the RSS transform\n Returns:\n torch.Tensor: The RSS value\n \"\"\"\n return torch.sqrt(complex_abs_sq(data).sum(dim))\n\n\ndef center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input real image or batch of real images.\n Args:\n data (torch.Tensor): The input tensor to be center cropped. It should have at\n least 2 dimensions and the cropping is applied along the last two dimensions.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-2]\n assert 0 < shape[1] <= data.shape[-1]\n w_from = (data.shape[-2] - shape[0]) // 2\n h_from = (data.shape[-1] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to]\n\n\ndef complex_center_crop(data, shape):\n \"\"\"\n Apply a center crop to the input image or batch of complex images.\n Args:\n data (torch.Tensor): The complex input tensor to be center cropped. It should\n have at least 3 dimensions and the cropping is applied along dimensions\n -3 and -2 and the last dimensions should have a size of 2.\n shape (int, int): The output shape. The shape should be smaller than the\n corresponding dimensions of data.\n Returns:\n torch.Tensor: The center cropped image\n \"\"\"\n assert 0 < shape[0] <= data.shape[-3]\n assert 0 < shape[1] <= data.shape[-2]\n w_from = (data.shape[-3] - shape[0]) // 2\n h_from = (data.shape[-2] - shape[1]) // 2\n w_to = w_from + shape[0]\n h_to = h_from + shape[1]\n return data[..., w_from:w_to, h_from:h_to, :]\n\n\ndef center_crop_to_smallest(x, y):\n \"\"\"\n Apply a center crop on the larger image to the size of the smaller image.\n \"\"\"\n smallest_width = min(x.shape[-1], y.shape[-1])\n smallest_height = min(x.shape[-2], y.shape[-2])\n x = center_crop(x, (smallest_height, smallest_width))\n y = center_crop(y, (smallest_height, smallest_width))\n return x, y\n\n\ndef normalize(data, mean, stddev, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n Args:\n data (torch.Tensor): Input data to be normalized\n mean (float): Mean value\n stddev (float): Standard deviation\n eps (float): Added to stddev to prevent dividing by zero\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n return (data - mean) / (stddev + eps)\n\n\ndef normalize_instance(data, eps=0.):\n \"\"\"\n Normalize the given tensor using:\n (data - mean) / (stddev + eps)\n where mean and stddev are computed from the data itself.\n Args:\n data (torch.Tensor): Input data to be normalized\n eps (float): Added to stddev to prevent dividing by zero\n Returns:\n torch.Tensor: Normalized tensor\n \"\"\"\n mean = data.mean()\n std = data.std()\n return normalize(data, mean, std, eps), mean, std\n\n\n# Helper functions\n\ndef roll(x, shift, dim):\n \"\"\"\n Similar to np.roll but applies to PyTorch Tensors\n \"\"\"\n if isinstance(shift, (tuple, list)):\n assert len(shift) == len(dim)\n for s, d in zip(shift, dim):\n x = roll(x, s, d)\n return x\n shift = shift % x.size(dim)\n if shift == 0:\n return x\n left = x.narrow(dim, 0, x.size(dim) - shift)\n right = x.narrow(dim, x.size(dim) - shift, shift)\n return torch.cat((right, left), dim=dim)\n\n\ndef fftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.fftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [dim // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = x.shape[dim] // 2\n else:\n shift = [x.shape[i] // 2 for i in dim]\n return roll(x, shift, dim)\n\n\ndef ifftshift(x, dim=None):\n \"\"\"\n Similar to np.fft.ifftshift but applies to PyTorch Tensors\n \"\"\"\n if dim is None:\n dim = tuple(range(x.dim()))\n shift = [(dim + 1) // 2 for dim in x.shape]\n elif isinstance(dim, int):\n shift = (x.shape[dim] + 1) // 2\n else:\n shift = [(x.shape[i] + 1) // 2 for i in dim]\n return roll(x, shift, dim)\n\nclass ApplyKSpaceMask(nn.Module):\n def __init__(self, mask):\n super(ApplyKSpaceMask, self).__init__()\n self.mask = mask\n\n def forward(self, input):\n kspace_data = fft2(ifftshift(input))\n masked_kspace_data = kspace_data * self.mask + 0.0\n visual_data = fftshift(ifft2(masked_kspace_data))\n return visual_data\n\ndef gaussian_oned(x):\n return 1.0 / np.sqrt(2.0*np.pi) * np.exp(-1*x**2 / 2.0)\n\ndef find_nearest(x, array):\n idx = (np.abs(x - array)).argmin()\n return idx\n\ndef exhaustive_sample(center_frac, acceleration, n_cols, seed):\n grid = np.linspace(-3.0,3.0,n_cols)\n sample_grid = np.zeros((n_cols,))\n num_low_freqs = int(round(n_cols * center_frac))\n pad = (n_cols - num_low_freqs + 1) // 2\n sample_grid[pad:pad+num_low_freqs] = [True]*num_low_freqs\n rng = np.random.RandomState(seed=seed)\n while True:\n sample_point = rng.standard_normal()\n if np.abs(sample_point) < 3.0:\n nearest_index = find_nearest(sample_point, grid)\n sample_grid[nearest_index] = True\n\n ratio_sampled = n_cols / sum(sample_grid)\n if acceleration > ratio_sampled:\n return sample_grid\n\n\ndef create_mask(shape, center_fraction, acceleration, seed=0, flipaxis=False):\n num_cols = shape[-2]\n\n # Create the mask\n mask = exhaustive_sample(center_fraction, acceleration, num_cols, seed)\n # num_low_freqs = int(round(num_cols * center_fraction))\n # prob = (num_cols / acceleration - num_low_freqs) / (num_cols - num_low_freqs)\n # rng = np.random.RandomState(seed=seed)\n #\n # mask = rng.standard_normal(size=num_cols) < prob\n # pad = (num_cols - num_low_freqs + 1) // 2\n # mask[pad:pad + num_low_freqs] = True\n\n # Reshape the mask\n mask_shape = [1 for _ in shape]\n if flipaxis:\n mask_shape[0] = num_cols\n else:\n mask_shape[-2] = num_cols\n # mask = mask.astype(np.float32)\n mask = mask.reshape(*mask_shape).astype(np.float32)\n # print(mask.shape)\n # exit()\n\n mask = torch.tensor(mask, requires_grad=False)\n return mask\n\n\n\nclass toKspace(nn.Module):\n def __init__(self, mask=None):\n super(toKspace, self).__init__()\n if mask is None:\n self.mask = mask\n else:\n self.register_buffer('mask', tensor=mask)\n\n\n def forward(self, input):\n kspace_data = fft2(ifftshift(input.permute((0,2,3,1))))\n if self.mask is not None:\n kspace_data = kspace_data * self.mask + 0.0\n return kspace_data.permute((0,3,1,2))\n\nclass toKspaceMulti(nn.Module):\n def __init__(self, masks):\n super(toKspaceMulti, self).__init__()\n self.masks = masks\n self.ii = 0\n\n def advance_ii(self):\n self.ii = (self.ii + 1) % 3\n\n def forward(self, input):\n kspace_data = fft2(ifftshift(input.permute((0,2,3,1))))\n mask = self.masks[self.ii]\n\n kspace_data = kspace_data * mask + 0.0\n return kspace_data.permute((0,3,1,2))\n\n\nclass fromKspace(nn.Module):\n def __init__(self, mask=None):\n super(fromKspace, self).__init__()\n if mask is None:\n self.mask = mask\n else:\n self.register_buffer('mask', tensor=mask)\n\n def forward(self, input):\n if self.mask is not None:\n input = input.permute((0,2,3,1)) * self.mask + 0.0\n else:\n input = input.permute((0,2,3,1))\n image_data = ifftshift(ifft2(input))\n return image_data.permute((0,3,1,2))\n\nclass cartesianSingleCoilMRI(LinearOperator):\n def __init__(self, kspace_mask):\n super(cartesianSingleCoilMRI, self).__init__()\n self.register_buffer('mask', tensor=kspace_mask)\n\n def forward(self, input):\n input = ifftshift(input.permute((0, 2, 3, 1)))\n complex_input = torch.view_as_complex(input)\n kspace = torch.fft.fftn(complex_input, dim=1, norm=\"ortho\")\n kspace = torch.fft.fftn(kspace, dim=2, norm=\"ortho\")\n kspace = fftshift(kspace)\n if self.mask is not None:\n kspace_data = kspace * self.mask + 0.0\n kspace_data = ifftshift(kspace_data)\n return torch.view_as_real(kspace_data)\n\n def gramian(self, input):\n input = ifftshift(input.permute((0, 2, 3, 1)))\n complex_input = torch.view_as_complex(input)\n kspace = torch.fft.fftn(complex_input, dim=1, norm=\"ortho\")\n kspace = torch.fft.fftn(kspace, dim=2, norm=\"ortho\")\n kspace = fftshift(kspace)\n if self.mask is not None:\n kspace_data = kspace * self.mask + 0.0\n kspace_data = ifftshift(kspace_data)\n\n kspace_data = torch.fft.ifftn(kspace_data, dim=1, norm=\"ortho\")\n realspace = torch.fft.ifftn(kspace_data, dim=2, norm=\"ortho\")\n realspace = torch.view_as_real(realspace)\n\n output = ifftshift(realspace).permute((0,3,1,2))\n return output\n\n def adjoint(self, input):\n complex_input = torch.view_as_complex(input)\n complex_input = torch.fft.ifftn(complex_input, dim=1, norm=\"ortho\")\n realspace = torch.fft.ifftn(complex_input, dim=2, norm=\"ortho\")\n\n realspace = torch.view_as_real(realspace)\n\n output = ifftshift(realspace).permute((0, 3, 1, 2))\n return output" }, { "alpha_fraction": 0.5744328498840332, "alphanum_fraction": 0.5845338702201843, "avg_line_length": 45.4538459777832, "blob_id": "3d6cbea8085a1a02b6741d8976a1af2f875b8bf0", "content_id": "1a9f34b0fbcfa347380995ab8fcd0ff672de6457", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6039, "license_type": "no_license", "max_line_length": 135, "num_lines": 130, "path": "/solvers/gradnet.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\nfrom solvers.cg_utils import conjugate_gradient\nfrom PIL import Image\nimport imageio\nimport numpy as np\ntt = 0\nclass GradNet(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta_initial_val=0.1):\n super(GradNet,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(eta_initial_val), requires_grad=True))\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n # This is a bit redundant\n def initial_point(self, y):\n return self._linear_adjoint(y)\n\n def initial_point_precond(self, y):\n initial_point = self._linear_adjoint(y)\n\n preconditioned_input = conjugate_gradient(initial_point, self.linear_op.gramian, regularization_lambda=self.eta,\n n_iterations=60)\n return preconditioned_input\n\n def single_block(self, input, y):\n grad_update = self.linear_op.gramian(input) - self._linear_adjoint(y) - self.nonlinear_op(input)\n return input - self.eta * grad_update\n\n def forward(self, y, iterations):\n initial_point = self.initial_point_precond(y)\n running_term = initial_point\n\n # global tt\n # bsz = initial_point.shape[0]\n # past_iterate = initial_point\n\n for bb in range(iterations):\n running_term = self.single_block(running_term, y)\n\n # # img_array = (np.clip(np.transpose(running_term.cpu().detach().numpy(), (0, 2, 3, 1)), -1,\n # # 1) + 1.0) * 127.5\n # img_array = torch.norm(running_term, dim=1).cpu().detach().numpy() * 255.0 / np.sqrt(2)\n # img_array = img_array.astype(np.uint8)\n #\n # residual = torch.norm(running_term - past_iterate, dim=1).cpu().detach().numpy()\n # if bb % 10 == 0:\n # for k in range(bsz):\n # # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/deblur/img/\" + str(tt + k) + \"_\" + str(bb) + \".png\"\n # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/mrie2e/img/\" + str(tt + k) + \"_\" + str(\n # bb) + \".png\"\n # # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/cs/img/\" + str(tt + k) + \"_\" + str(bb) + \".png\"\n # output_img = Image.fromarray(img_array[k, ...])\n # output_img = output_img.resize((512, 512), resample=Image.NEAREST)\n # imageio.imwrite(filename, output_img, format='PNG-PIL')\n #\n # # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/deblur/res/\" + str(tt + k) + \"_\" + str(bb) + \".png\"\n # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/mrie2e/res/\" + str(tt + k) + \"_\" + str(\n # bb) + \".png\"\n # # filename = \"/share/data/vision-greg2/users/gilton/test_imgs/cs/res/\" + str(tt + k) + \"_\" + str(bb) + \".png\"\n #\n # normalized_res = np.clip(residual[k, :, :] * 8, 0, 1) * 255.0\n # # print(np.shape(normalized_res))\n # # exit()\n # normalized_res = normalized_res.astype(np.uint8)\n # output_img = Image.fromarray(normalized_res)\n # output_img = output_img.resize((512, 512), resample=Image.NEAREST)\n # imageio.imwrite(filename, output_img, format='PNG-PIL')\n #\n # tt += bsz\n return running_term\n\n\nclass PrecondNeumannNet(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, lambda_initial_val=0.1, cg_iterations=10):\n super(PrecondNeumannNet,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n self.cg_iterations = cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(lambda_initial_val), requires_grad=True))\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n # This is a bit redundant\n def initial_point(self, y):\n preconditioned_input = conjugate_gradient(y, self.linear_op.gramian, regularization_lambda=self.eta,\n n_iterations=self.cg_iterations)\n return preconditioned_input\n\n def single_block(self, input):\n preconditioned_step = conjugate_gradient(input, self.linear_op.gramian, regularization_lambda=self.eta,\n n_iterations=self.cg_iterations)\n return self.eta * preconditioned_step - self.nonlinear_op(input)\n\n def forward(self, y, iterations):\n initial_point = self.eta * self.initial_point(y)\n running_term = initial_point\n accumulator = initial_point\n\n for bb in range(iterations):\n running_term = self.single_block(running_term)\n accumulator = accumulator + running_term\n\n return accumulator\n" }, { "alpha_fraction": 0.6432989835739136, "alphanum_fraction": 0.646833598613739, "avg_line_length": 40.40243911743164, "blob_id": "9c8570054074c228a4d495db6c5de8053715d347", "content_id": "9d32884b6054afe087bce2b5ef150a12eb1594dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3395, "license_type": "no_license", "max_line_length": 123, "num_lines": 82, "path": "/solvers/equilibrium_nets.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\nfrom solvers.cg_utils import conjugate_gradient\n\nclass EquilibriumGrad(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta_initial_val=0.1, minval = -1, maxval = 1):\n super(EquilibriumGrad,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n self.minval = minval\n self.maxval = maxval\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(eta_initial_val), requires_grad=True))\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def set_initial_point(self, y):\n self.initial_point = self._linear_adjoint(y)\n\n def get_gradient(self, z, y):\n return self.linear_op.gramian(z) - self._linear_adjoint(y) - self.nonlinear_op(z)\n\n def forward(self, z, y):\n z_tplus1 = z - self.eta * self.get_gradient(z, y)\n z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\nclass PrecondNeumannNet(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, lambda_initial_val=0.1, cg_iterations=10):\n super(PrecondNeumannNet,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n self.cg_iterations = cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(lambda_initial_val), requires_grad=True))\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n # This is a bit redundant\n def initial_point(self, y):\n preconditioned_input = conjugate_gradient(y, self.linear_op.gramian, regularization_lambda=self.eta,\n n_iterations=self.cg_iterations)\n return preconditioned_input\n\n def single_block(self, input):\n preconditioned_step = conjugate_gradient(input, self.linear_op.gramian, regularization_lambda=self.eta,\n n_iterations=self.cg_iterations)\n return self.eta * preconditioned_step - self.nonlinear_op(input)\n\n def forward(self, y, iterations):\n initial_point = self.eta * self.initial_point(y)\n running_term = initial_point\n accumulator = initial_point\n\n for bb in range(iterations):\n running_term = self.single_block(running_term)\n accumulator = accumulator + running_term\n\n return accumulator\n" }, { "alpha_fraction": 0.601943850517273, "alphanum_fraction": 0.6093421578407288, "avg_line_length": 36.16442108154297, "blob_id": "5ed49babe809853bf5a02ec5d399f6fe299fa9f1", "content_id": "a1bd22160ec347a2b556b7b0a877cf0030182b11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13787, "license_type": "no_license", "max_line_length": 122, "num_lines": 371, "path": "/solvers/equilibrium_solvers.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\nimport matplotlib\n# matplotlib.use(\"TkAgg\")\nimport matplotlib.pyplot as plt\n\nfrom solvers.cg_utils import conjugate_gradient\n\nclass EquilibriumGrad(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta, minval = -1, maxval = 1):\n super(EquilibriumGrad,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n # self.eta = eta\n\n self.minval = minval\n self.maxval = maxval\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(eta), requires_grad=True))\n\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def set_initial_point(self, y):\n self.initial_point = self._linear_adjoint(y)\n\n def get_gradient(self, z, y):\n return self.linear_op.gramian(z) - self._linear_adjoint(y) - self.nonlinear_op(z)\n\n def forward(self, z, y):\n z_tplus1 = z - self.eta * self.get_gradient(z, y)\n z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\nclass EquilibriumProxGrad(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta, minval = -1, maxval = 1):\n super(EquilibriumProxGrad,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n self.minval = minval\n self.maxval = maxval\n self.register_parameter(name='eta', param=torch.nn.Parameter(torch.tensor(eta), requires_grad=True))\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def get_gradient(self, z, y):\n return self.linear_op.gramian(z) - self._linear_adjoint(y)\n\n def forward(self, z, y):\n gradstep = z - self.eta * self.get_gradient(z, y)\n z_tplus1 = gradstep + self.nonlinear_op(gradstep)\n z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\n\nclass EquilibriumProxGradMRI(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta, minval = -1, maxval = 1):\n super(EquilibriumProxGradMRI,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n self.minval = minval\n self.maxval = maxval\n self.eta = eta\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def get_gradient(self, z, y):\n return self.linear_op.gramian(z) - self._linear_adjoint(y)\n\n def forward(self, z, y):\n gradstep = z - self.eta * self.get_gradient(z, y)\n z_tplus1 = gradstep + self.nonlinear_op(gradstep)\n z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\nclass ProxPnP(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta, minval = -1, maxval = 1):\n super(ProxPnP,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n self.minval = minval\n self.maxval = maxval\n self.eta = eta\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def get_gradient(self, z, y):\n return self.linear_op.adjoint(self.linear_op.forward(z) - y)\n\n def forward(self, z, y):\n gradstep = z - self.eta*(self.linear_op.adjoint(self.linear_op.forward(z)) - self.linear_op.adjoint(y))\n z_tplus1 = gradstep + self.nonlinear_op(gradstep)\n #z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\nclass DouglasRachford(nn.Module):\n def __init__(self, linear_operator, nonlinear_operator, eta, max_iters = 10, minval = -1, maxval = 1):\n super(DouglasRachford,self).__init__()\n self.linear_op = linear_operator\n self.nonlinear_op = nonlinear_operator\n\n self.minval = minval\n self.maxval = maxval\n self.lambdaval = eta\n self.max_cg_iterations = max_iters\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def internal_prox(self, x, y):\n initial_point = self.linear_op.adjoint(y) + self.lambdaval*x\n return conjugate_gradient(initial_point, self.linear_op.gramian, self.lambdaval,\n n_iterations=self.max_cg_iterations)\n\n def get_gradient(self, z, y):\n return self.linear_op.adjoint(self.linear_op.forward(z) - y)\n\n def forward(self, z, y):\n prox_f = self.internal_prox(z, y)\n net_input = 2*prox_f - z\n z_tplus1 = (z + 2*(self.nonlinear_op(net_input) + net_input)-net_input) / 2.0\n z_tplus1 = torch.clamp(z_tplus1, self.minval, self.maxval)\n return z_tplus1\n\nclass EquilibriumADMM(nn.Module):\n def __init__(self, linear_operator, denoising_net, max_cg_iterations=20, x_alpha=0.4, eta = 0.1, minval=-1, maxval=1):\n super(EquilibriumADMM, self).__init__()\n self.linear_op = linear_operator\n self.denoising_net = denoising_net\n\n self.minval = minval\n self.maxval = maxval\n self.x_alpha = x_alpha\n self.eta = eta\n\n self.max_cg_iters = max_cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def _x_update(self, z, u, y):\n gramian = self.linear_op.gramian\n # initial_point = self._linear_adjoint(y) + 0.0000001 * (z - u)\n initial_point = self._linear_adjoint(y) + self.x_alpha*(z-u)\n\n x_update = conjugate_gradient(initial_point, gramian, self.x_alpha, n_iterations=self.max_cg_iters)\n return x_update, z, u\n\n def _z_update(self, x, z, u):\n net_input = x + u\n z_update = net_input + self.denoising_net(net_input)\n return x, z_update, u\n\n def _u_update(self, x, z, u):\n u_update = u + self.eta * (x - z)\n # u_update = u + z - x\n\n return x, z, u_update\n\n def forward(self, z, u, y):\n x_new, z, u = self._x_update(z, u, y)\n x_new, z_new, u = self._z_update(x_new, z, u)\n x_new, z_new, u_new = self._u_update(x_new, z_new, u)\n z_new = torch.clamp(z_new, self.minval, self.maxval)\n return z_new, u_new\n\nclass EquilibriumADMM2(nn.Module):\n def __init__(self, linear_operator, denoising_net, max_cg_iterations=20, x_alpha=0.4, eta = 0.1, minval=-1, maxval=1):\n super(EquilibriumADMM2, self).__init__()\n self.linear_op = linear_operator\n self.denoising_net = denoising_net\n\n self.minval = minval\n self.maxval = maxval\n self.x_alpha = x_alpha\n self.eta = eta\n\n self.max_cg_iters = max_cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def _x_update(self, z, u, y):\n gramian = self.linear_op.gramian\n # initial_point = self._linear_adjoint(y) + 0.0000001 * (z - u)\n initial_point = self._linear_adjoint(y) + self.x_alpha*(z-u)\n\n x_update = conjugate_gradient(initial_point, gramian, self.x_alpha, n_iterations=self.max_cg_iters)\n return x_update, z, u\n\n def _z_update(self, x, z, u):\n net_input = x + u\n z_update = net_input - self.denoising_net(net_input)\n return x, z_update, u\n\n def _u_update(self, x, z, u):\n u_update = u + self.eta * (x - z)\n # u_update = u + z - x\n\n return x, z, u_update\n\n def forward(self, z, u, y):\n x_new, z, u = self._x_update(z, u, y)\n x_new, z_new, u = self._z_update(x_new, z, u)\n x_new, z_new, u_new = self._u_update(x_new, z_new, u)\n z_new = torch.clamp(z_new, self.minval, self.maxval)\n return z_new, u_new\n\nclass EquilibriumADMM_minus(nn.Module):\n def __init__(self, linear_operator, denoising_net, max_cg_iterations=20, x_alpha=0.4, eta = 0.1, minval=-1, maxval=1):\n super(EquilibriumADMM_minus, self).__init__()\n self.linear_op = linear_operator\n self.denoising_net = denoising_net\n\n self.minval = minval\n self.maxval = maxval\n self.x_alpha = x_alpha\n self.eta = eta\n\n self.max_cg_iters = max_cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def _x_update(self, z, u, y):\n net_input = z - u\n x_update = net_input - self.denoising_net(net_input)\n return x_update, z, u\n\n def _z_update(self, x, u, y):\n gramian = self.linear_op.gramian\n # initial_point = self._linear_adjoint(y) + 0.0000001 * (z - u)\n initial_point = self._linear_adjoint(y) + self.x_alpha*(x+u)\n\n z_update = conjugate_gradient(initial_point, gramian, self.x_alpha, n_iterations=self.max_cg_iters)\n return x, z_update, u\n\n def _u_update(self, x, z, u):\n u_update = u + self.eta * (x - z)\n # u_update = u + z - x\n\n return x, z, u_update\n\n def forward(self, z, u, y):\n x_new, z, u = self._x_update(z, u, y)\n x_new, z_new, u = self._z_update(x_new, u, y)\n x_new, z_new, u_new = self._u_update(x_new, z_new, u)\n z_new = torch.clamp(z_new, self.minval, self.maxval)\n return z_new, u_new\n\nclass EquilibriumADMM_plus(nn.Module):\n def __init__(self, linear_operator, denoising_net, max_cg_iterations=20, x_alpha=0.4, eta = 0.1, minval=-1, maxval=1):\n super(EquilibriumADMM_plus, self).__init__()\n self.linear_op = linear_operator\n self.denoising_net = denoising_net\n\n self.minval = minval\n self.maxval = maxval\n self.x_alpha = x_alpha\n self.eta = eta\n\n self.max_cg_iters = max_cg_iterations\n\n # Check if the linear operator has parameters that can be learned:\n # if so, register them to be learned as part of the network.\n linear_param_name = 'linear_param_'\n for ii, parameter in enumerate(self.linear_op.parameters()):\n parameter_name = linear_param_name + str(ii)\n self.register_parameter(name=parameter_name, param=parameter)\n\n def _linear_op(self, x):\n return self.linear_op.forward(x)\n\n def _linear_adjoint(self, x):\n return self.linear_op.adjoint(x)\n\n def _x_update(self, z, u, y):\n net_input = z - u\n x_update = net_input + self.denoising_net(net_input)\n return x_update, z, u\n\n def _z_update(self, x, u, y):\n gramian = self.linear_op.gramian\n # initial_point = self._linear_adjoint(y) + 0.0000001 * (z - u)\n initial_point = self._linear_adjoint(y) + self.x_alpha*(x+u)\n\n z_update = conjugate_gradient(initial_point, gramian, self.x_alpha, n_iterations=self.max_cg_iters)\n return x, z_update, u\n\n def _u_update(self, x, z, u):\n u_update = u + self.eta * (x - z)\n # u_update = u + z - x\n\n return x, z, u_update\n\n def forward(self, z, u, y):\n x_new, z, u = self._x_update(z, u, y)\n x_new, z_new, u = self._z_update(x_new, u, y)\n x_new, z_new, u_new = self._u_update(x_new, z_new, u)\n z_new = torch.clamp(z_new, self.minval, self.maxval)\n return z_new, u_new" }, { "alpha_fraction": 0.6082987785339355, "alphanum_fraction": 0.6165975332260132, "avg_line_length": 30.710525512695312, "blob_id": "7050dcfaed21686898b03a971e84db0ba048bc03", "content_id": "8125ddea26cb069cd3cb45d68a823dc8d2bb4426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1205, "license_type": "no_license", "max_line_length": 66, "num_lines": 38, "path": "/networks/twolayer_linear_net.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "\"\"\"\nCopyright (c) Facebook, Inc. and its affiliates.\nThis source code is licensed under the MIT license found in the\nLICENSE file in the root directory of this source tree.\n\"\"\"\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\n\nclass LinearNet(nn.Module):\n\n def __init__(self, input_size, bottleneck_size, output_size):\n super().__init__()\n # self.linear_layer = nn.Linear(input_size, output_size)\n # self.linear_layer2 = nn.Linear(output_size, output_size)\n self.network = nn.Sequential(\n nn.Linear(input_size, bottleneck_size),\n nn.ReLU(),\n nn.Linear(bottleneck_size, bottleneck_size),\n nn.ReLU(),\n nn.Linear(bottleneck_size, output_size),\n nn.Tanh()\n )\n self.network.apply(self.init_weights)\n\n def init_weights(self, m):\n if type(m) == nn.Linear:\n torch.nn.init.normal_(m.weight, mean=0.0, std=0.01)\n m.bias.data.fill_(0.01)\n\n def forward(self, input):\n input_shape = input.shape\n output = self.network(torch.flatten(input, start_dim=1))\n output = torch.reshape(output, shape=input_shape)\n\n return output\n" }, { "alpha_fraction": 0.7033955454826355, "alphanum_fraction": 0.7157634496688843, "avg_line_length": 36.369747161865234, "blob_id": "41772d90193ceb6eae9ef82f9311282c2cbacda9", "content_id": "02b6991599579c3f5a1170467edada61daecadc6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4447, "license_type": "no_license", "max_line_length": 121, "num_lines": 119, "path": "/scripts/denoising/mri_unet_denoise.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport random\nimport sys\nimport argparse\nsys.path.append('/home-nfs/gilton/learned_iterative_solvers')\n# sys.path.append('/Users/dgilton/PycharmProjects/learned_iterative_solvers')\n\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport operators.operator as lin_operator\nfrom operators.operator import OperatorPlusNoise\nfrom utils.fastmri_dataloader import singleCoilFastMRIDataloader\nfrom networks.equilibrium_u_net import UnetModel\nfrom solvers.equilibrium_solvers import EquilibriumGrad\nfrom training import denoiser_training\nfrom solvers import new_equilibrium_utils as eq_utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', default=80)\nparser.add_argument('--batch_size', type=int, default=16)\nparser.add_argument('--and_maxiters', default=100)\nparser.add_argument('--and_beta', type=float, default=1.0)\nparser.add_argument('--and_m', type=int, default=5)\nparser.add_argument('--lr', type=float, default=0.1)\nparser.add_argument('--etainit', type=float, default=0.5)\nparser.add_argument('--lr_gamma', type=float, default=0.1)\nparser.add_argument('--sched_step', type=int, default=10)\nparser.add_argument('--acceleration', type=float, default=8.0)\nparser.add_argument('--noise_sigma', type=float, default=0.01)\nparser.add_argument('--savepath',\n default=\"/share/data/vision-greg2/users/gilton/celeba_equilibriumgrad_mri_save_inf.ckpt\")\nargs = parser.parse_args()\n\n\n# Parameters to modify\nn_epochs = int(args.n_epochs)\ncurrent_epoch = 0\nbatch_size = int(args.batch_size)\nn_channels = 2\nmax_iters = int(args.and_maxiters)\nanderson_m = int(args.and_m)\nanderson_beta = float(args.and_beta)\n\nlearning_rate = float(args.lr)\nprint_every_n_steps = 10\nsave_every_n_epochs = 5\ninitial_eta = float(args.etainit)\n\ndataheight = 320\ndatawidth = 320\n\nnoise_sigma = float(args.noise_sigma)\n\n# modify this for your machine\n# save_location = \"/share/data/vision-greg2/users/gilton/mnist_equilibriumgrad_blur.ckpt\"\nsave_location = args.savepath\nload_location = args.savepath\n\ngpu_ids = []\nfor ii in range(6):\n try:\n torch.cuda.get_device_properties(ii)\n print(str(ii), flush=True)\n if not gpu_ids:\n gpu_ids = [ii]\n else:\n gpu_ids.append(ii)\n except AssertionError:\n print('Not ' + str(ii) + \"!\", flush=True)\n\nprint(os.getenv('CUDA_VISIBLE_DEVICES'), flush=True)\ngpu_ids = [int(x) for x in gpu_ids]\n# device management\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nuse_dataparallel = len(gpu_ids) > 1\nprint(\"GPU IDs: \" + str([int(x) for x in gpu_ids]), flush=True)\n\n# Set up data and dataloaders\ndata_location = \"/share/data/vision-greg2/users/gilton/singlecoil_curated_clean/\"\ntrainset_size = 2000\ntotal_data = 2194\nrandom.seed(10)\nall_indices = list(range(trainset_size))\ntrain_indices = random.sample(range(total_data), k=trainset_size)\ndataset = singleCoilFastMRIDataloader(data_location, data_indices=train_indices)\ndataloader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=args.batch_size, shuffle=True, drop_last=True,\n)\n\n### Set up solver and problem setting\n\nforward_operator = lin_operator.Identity().to(device=device)\nmeasurement_process = OperatorPlusNoise(forward_operator, noise_sigma=noise_sigma).to(device=device)\n\nsolver = UnetModel(in_chans=n_channels, out_chans=n_channels, num_pool_layers=4,\n drop_prob=0.0, chans=32)\n\nif use_dataparallel:\n solver = nn.DataParallel(solver, device_ids=gpu_ids)\nsolver = solver.to(device=device)\n\nstart_epoch = 0\noptimizer = optim.Adam(params=solver.parameters(), lr=learning_rate)\nscheduler = optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=int(args.sched_step), gamma=float(args.lr_gamma))\ncpu_only = not torch.cuda.is_available()\n\n\n# set up loss and train\nlossfunction = torch.nn.MSELoss()\n\n# Do train\ndenoiser_training.train_denoiser(denoising_net=solver, train_dataloader=dataloader, test_dataloader=dataloader,\n measurement_process=measurement_process, optimizer=optimizer, save_location=save_location,\n loss_function=lossfunction, n_epochs=n_epochs,\n use_dataparallel=use_dataparallel, device=device, scheduler=scheduler,\n print_every_n_steps=print_every_n_steps, save_every_n_epochs=save_every_n_epochs,\n start_epoch=start_epoch)\n" }, { "alpha_fraction": 0.5186825394630432, "alphanum_fraction": 0.5440844893455505, "avg_line_length": 33.327999114990234, "blob_id": "4b65c6e568da64748ee0e020e5581729a91339cc", "content_id": "5b7cb9fdcd86e81a9f1b75aa9f36d17216b8491d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12873, "license_type": "no_license", "max_line_length": 120, "num_lines": 375, "path": "/solvers/new_equilibrium_utils.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\nimport matplotlib\n#matplotlib.use(\"TkAgg\")\nfrom matplotlib import pyplot as plt\nimport imageio\nimport numpy as np\nfrom PIL import Image\n\ndef complex_conj(x):\n assert x.shape[1] == 2\n return torch.stack((x[:,0, ...], -x[:,1,...]), dim=1)\n\ndef torchdotproduct(x,y):\n # if complexdata:\n # y = complex_conj(y)\n return torch.sum(x*y,dim=[1,2,3])\n\ndef single_cg_iteration(x, d, g, b, ATA, regularization_lambda):\n\n def regATA(input, ATA):\n return ATA(input) + regularization_lambda*input\n\n Qd = regATA(d, ATA)\n dQd = torchdotproduct(d, Qd)\n alpha = -torchdotproduct(g,d) / dQd\n alpha = alpha.view((-1,1,1,1))\n x = x + alpha * d\n g = regATA(x, ATA) - b\n gQd = torchdotproduct(g, Qd)\n beta = gQd / dQd\n beta = beta.view((-1,1,1,1))\n d = -g + beta*d\n return x, d, g\n\n# This function solves the system ATA x = ATy, where initial_point is supposed\n# to be ATy. This can be backpropagated through.\ndef conjugate_gradient(initial_point, ATA, regularization_lambda, n_iterations=10):\n x = torch.zeros_like(initial_point)\n d = initial_point\n g = -d\n for ii in range(n_iterations):\n x, d, g = single_cg_iteration(x, d, g, initial_point, ATA, regularization_lambda)\n return x\n\ndef complex_dotproduct(x, y):\n return torchdotproduct(complex_conj(x), y)\n\ndef single_cg_iteration_MRI(rTr, x, r, p, ATA, regularization_lambda):\n\n batch_size = x.shape[0]\n def regATA(input):\n return ATA(input) + regularization_lambda*input\n\n Ap = regATA(p)\n\n rTr = rTr.view(batch_size, 1, 1, 1)\n alpha = rTr / complex_dotproduct(p, Ap).view(batch_size, 1, 1, 1)\n\n x_new = x + alpha * p\n r_new = r - alpha * Ap\n rTr_new = complex_dotproduct(r_new, r_new)\n rTr_new = rTr_new.view(batch_size, 1, 1, 1)\n\n beta = rTr_new / rTr\n p_new = r + beta * p\n return rTr_new, x_new, r_new, p_new\n\ndef conjugate_gradient_MRI(initial_point, ATA, regularization_lambda, n_iterations=10):\n '''Strightforward implementation of MoDLs code'''\n x = torch.zeros_like(initial_point)\n r = initial_point\n p = initial_point\n rTr = complex_dotproduct(r, r)\n for ii in range(n_iterations):\n rTr, x, r, p = single_cg_iteration_MRI(rTr, x, r, p, ATA, regularization_lambda)\n return x\n\ndef jacobian_vector_product(g, z, v):\n JTv = torch.autograd.grad(outputs=g, inputs=z, grad_outputs=v)[0]\n return JTv\n\ndef conjugate_gradient_equilibriumgrad(b, input_z, f_function, n_iterations=10):\n initial_guess = b.clone()\n x_k = initial_guess\n r_k = b\n p_k = r_k\n batch_size = b.shape[0]\n g = f_function(input_z) - input_z\n\n for ii in range(n_iterations):\n # g = f_function(initial_guess) - initial_guess\n # Ap_k = jacobian_vector_product(g, input_z, x_k)\n Ap_k = (torch.autograd.grad(outputs=g, inputs=input_z, grad_outputs=x_k, retain_graph=True)[0] + 0.00001 * x_k)\n rTr_k = torchdotproduct(r_k, r_k)\n rTr_k = rTr_k.view(batch_size, 1, 1, 1)\n\n pAp_k = torchdotproduct(Ap_k, p_k)\n pAp_k = pAp_k.view(batch_size, 1, 1, 1)\n\n alpha = rTr_k / pAp_k\n\n x_k = x_k + alpha * p_k\n r_kplus1 = r_k - alpha * Ap_k\n rTr_kplus1 = torchdotproduct(r_kplus1, r_kplus1)\n rTr_kplus1 = rTr_kplus1.view(batch_size, 1, 1, 1)\n\n beta = rTr_k / rTr_kplus1\n p_k = r_kplus1 + beta * p_k\n r_k = r_kplus1\n return x_k\n\n#tt= 0\ndef anderson(f, x0, m=5, lam=1e-4, max_iter=50, tol=1e-2, beta=1.0):\n \"\"\" Anderson acceleration for fixed point iteration.\n This was taken from the Deep Equilibrium tutorial here: http://implicit-layers-tutorial.org/deep_equilibrium_models/\n \"\"\"\n\n #global tt\n bsz, d, H, W = x0.shape\n X = torch.zeros(bsz, m, d * H * W, dtype=x0.dtype, device=x0.device)\n F = torch.zeros(bsz, m, d * H * W, dtype=x0.dtype, device=x0.device)\n X[:, 0], F[:, 0] = x0.reshape(bsz, -1), f(x0).reshape(bsz, -1)\n X[:, 1], F[:, 1] = F[:, 0], f(F[:, 0].reshape(x0.shape)).reshape(bsz, -1)\n\n H = torch.zeros(bsz, m + 1, m + 1, dtype=x0.dtype, device=x0.device)\n H[:, 0, 1:] = H[:, 1:, 0] = 1\n y = torch.zeros(bsz, m + 1, 1, dtype=x0.dtype, device=x0.device)\n y[:, 0] = 1\n\n res = []\n current_k = 0\n past_iterate = x0\n for k in range(2, max_iter):\n current_k = k\n n = min(k, m)\n G = F[:, :n] - X[:, :n]\n H[:, 1:n + 1, 1:n + 1] = torch.bmm(G, G.transpose(1, 2)) + lam * torch.eye(n, dtype=x0.dtype, device=x0.device)[\n None]\n alpha = torch.solve(y[:, :n + 1], H[:, :n + 1, :n + 1])[0][:, 1:n + 1, 0] # (bsz x n)\n\n X[:, k % m] = beta * (alpha[:, None] @ F[:, :n])[:, 0] + (1 - beta) * (alpha[:, None] @ X[:, :n])[:, 0]\n current_iterate = beta * (alpha[:, None] @ F[:, :n])[:, 0] + (1 - beta) * (alpha[:, None] @ X[:, :n])[:, 0]\n F[:, k % m] = f(X[:, k % m].reshape(x0.shape)).reshape(bsz, -1)\n res.append((F[:, k % m] - X[:, k % m]).norm().item() / (1e-5 + F[:, k % m].norm().item()))\n\n if (res[-1] < tol):\n break\n #tt += bsz\n return X[:, current_k % m].view_as(x0), res\n\n\ndef andersonexp(f, x0, m=5, lam=1e-4, max_iter=50, tol=1e-2, beta=1.0):\n \"\"\" Anderson acceleration for fixed point iteration. \"\"\"\n # global tt\n bsz, d, H, W = x0.shape\n X = torch.zeros(bsz, m, d * H * W, dtype=x0.dtype, device=x0.device)\n F = torch.zeros(bsz, m, d * H * W, dtype=x0.dtype, device=x0.device)\n X[:, 0], F[:, 0] = x0.reshape(bsz, -1), f(x0).reshape(bsz, -1)\n X[:, 1], F[:, 1] = F[:, 0], f(F[:, 0].reshape(x0.shape)).reshape(bsz, -1)\n\n H = torch.zeros(bsz, m + 1, m + 1, dtype=x0.dtype, device=x0.device)\n H[:, 0, 1:] = H[:, 1:, 0] = 1\n y = torch.zeros(bsz, m + 1, 1, dtype=x0.dtype, device=x0.device)\n y[:, 0] = 1\n\n current_k = 0\n for k in range(2, max_iter):\n current_k = k\n n = min(k, m)\n G = F[:, :n] - X[:, :n]\n H[:, 1:n + 1, 1:n + 1] = torch.bmm(G, G.transpose(1, 2)) + lam * torch.eye(n, dtype=x0.dtype, device=x0.device)[\n None]\n alpha = torch.solve(y[:, :n + 1], H[:, :n + 1, :n + 1])[0][:, 1:n + 1, 0] # (bsz x n)\n\n X[:, k % m] = beta * (alpha[:, None] @ F[:, :n])[:, 0] + (1 - beta) * (alpha[:, None] @ X[:, :n])[:, 0]\n F[:, k % m] = f(X[:, k % m].reshape(x0.shape)).reshape(bsz, -1)\n res = (F[:, k % m] - X[:, k % m]).norm().item() / (1e-5 + F[:, k % m].norm().item())\n\n if (res < tol):\n break\n # tt += bsz\n return X[:, current_k % m].view_as(x0), res\n\ndef L2Norm(x):\n return torch.sum(x**2, dim=[1,2,3], keepdim=True)\n\ndef epsilon2(f, x0, max_iter=50, tol=1e-2, lam=1e-4):\n\n x = x0\n\n for k in range(max_iter):\n f_x = f(x)\n delta_x = f_x - x\n delta_f = f(f_x) - f_x\n delta2_x = delta_f - delta_x\n # term1 = delta_f * L2Norm(delta_x)\n # term2 = delta_x * L2Norm(delta_f)\n x_new = f_x + (delta_f * L2Norm(delta_x) - delta_x * L2Norm(delta_f)) / (L2Norm(delta2_x) + lam)\n residual = (x_new - x).norm().item() / x_new.norm().item()\n x = x_new\n if (residual < tol):\n break\n\n return x, residual\n\ndef forward_iteration(f, x0, max_iter=50, tol=1e-5):\n f0 = f(x0)\n res = []\n for k in range(max_iter):\n x = f0\n f0 = f(x)\n res.append((f0 - x).norm().item() / (1e-7 + f0.norm().item()))\n if (res[-1] < tol):\n break\n return f0, res\n\ndef forward_iteration_plot(f, x0, max_iter=50, tol=1e-5):\n f0 = f(x0)\n res = []\n fig = plt.figure()\n for k in range(max_iter):\n x = f0\n f0 = f(x)\n # sub = fig.add_subplot(10,10, k)\n # plt.imshow(f0[0, : , :, :].detach().cpu().numpy())\n # plt.show()\n res.append((f0 - x).norm().item() / (1e-7 + f0.norm().item()))\n if (res[-1] < tol):\n break\n plt.show()\n return f0, res\n\n\nclass DEQFixedPoint(nn.Module):\n def __init__(self, f, solver, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.kwargs = kwargs\n\n def forward(self, x, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n with torch.no_grad():\n z, self.forward_res = self.solver(lambda z: self.f(z, x), init_point, **self.kwargs)\n z = self.f(z, x)\n\n # set up Jacobian vector product (without additional forward calls)\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n\n def backward_hook(grad):\n g, self.backward_res = self.solver(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0] + grad,\n grad, **self.kwargs)\n return g\n\n z.register_hook(backward_hook)\n return z\n\n\nclass DEQFixedPointExp(nn.Module):\n def __init__(self, f, solver, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.kwargs = kwargs\n\n def forward(self, x, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n with torch.no_grad():\n z, self.forward_res = self.solver(lambda z: self.f(z, x), init_point, **self.kwargs)\n z = self.f(z, x)\n\n # set up Jacobian vector product (without additional forward calls)\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n\n def backward_hook(grad):\n g, self.backward_res = self.solver(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0] + grad,\n grad, **self.kwargs)\n return g\n\n z.register_hook(backward_hook)\n return z\n\nclass DEQFixedPointTest(nn.Module):\n def __init__(self, f, solver, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.kwargs = kwargs\n\n def forward(self, x, truth = None, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n with torch.no_grad():\n z, self.forward_res = self.solver(lambda z: self.f(z, x), init_point, **self.kwargs)\n\n return z\n\ndef neumann_iteration(f, x0,k=10):\n accumulator = x0\n current_iterate = x0\n for _ in range(k):\n current_iterate = f(current_iterate)\n accumulator = accumulator + current_iterate\n\n return accumulator\n\n\nclass DEQFixedPointNeumann(nn.Module):\n def __init__(self, f, solver, neumann_k, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.neumann_k = neumann_k\n self.kwargs = kwargs\n\n def forward(self, x):\n # compute forward pass and re-engage autograd tape\n with torch.no_grad():\n z, self.forward_res = self.solver(lambda z: self.f(z, x), torch.zeros_like(x), **self.kwargs)\n z = self.f(z, x)\n\n # set up Jacobian vector product (without additional forward calls)\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n\n def backward_hook(grad):\n g = neumann_iteration(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0],\n grad, self.neumann_k)\n return g\n\n z.register_hook(backward_hook)\n return z\n\ndef get_equilibrium_point(solver, z, max_iterations=50, tolerance = 0.001):\n old_iterate = z\n for iteration in range(max_iterations):\n new_iterate = solver(old_iterate)\n res = (new_iterate-old_iterate).norm().item() / (1e-5 + new_iterate.norm().item())\n old_iterate = new_iterate\n if res < 1e-3:\n break\n return new_iterate, new_iterate\n\ndef get_equilibrium_point_plot(solver, z, truth, max_iterations=50, tolerance = 0.001):\n running_iterate = z\n # fig = plt.figure()\n jj = 0\n for iteration in range(max_iterations):\n # if iteration % 10 == 0:\n # sub = fig.add_subplot(2, 5, jj+1)\n # img_to_show = torch.abs(running_iterate[0, :, :, :] - truth[0,:,:,:])*5.0\n # # plt.imshow((running_iterate[0, :, :, :].permute(1,2,0).cpu().detach().numpy() + 1.0) / 2.0)\n # # plt.show()\n # # sub.imshow((img_to_show.permute(1,2,0).detach().cpu().numpy() + 1.0)/2.0)\n # sub.imshow(img_to_show.permute(1,2,0).detach().cpu().numpy())\n #\n # jj += 1\n running_iterate = solver(running_iterate)\n # plt.show()\n\n return running_iterate, running_iterate\n" }, { "alpha_fraction": 0.5199684500694275, "alphanum_fraction": 0.5282516479492188, "avg_line_length": 45.30593490600586, "blob_id": "1534a3844d718b59e1fe26e00715dd89457d3d19", "content_id": "0a9845d826d539f5577aa22c8df85a99ee44a639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10141, "license_type": "no_license", "max_line_length": 113, "num_lines": 219, "path": "/training/new_equilibrium_training.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport numpy as np\nfrom solvers import new_equilibrium_utils as eq_utils\nfrom torch import autograd\n\ndef train_solver(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs, forward_iterator, iterator_kwargs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0):\n\n forward_iterator = eq_utils.anderson\n deep_eq_module = eq_utils.DEQFixedPoint(single_iterate_solver, forward_iterator, iterator_kwargs)\n\n for epoch in range(start_epoch, n_epochs):\n\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch.to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n optimizer.step()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\ndef train_solver_noanderson(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0, max_iters=100):\n\n forward_iterator = eq_utils.forward_iteration\n deep_eq_module = eq_utils.DEQFixedPoint(single_iterate_solver, solver=forward_iterator,\n max_iter=max_iters, tol=1e-3)\n\n for epoch in range(start_epoch, n_epochs):\n\n # We are lucky to have\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch.to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n optimizer.step()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n\ndef train_solver_mnist(single_iterate_solver, train_dataloader, test_dataloader,\n measurement_process, optimizer,\n save_location, loss_function, n_epochs,\n use_dataparallel=False, device='cpu', scheduler=None,\n print_every_n_steps=10, save_every_n_epochs=5, start_epoch=0, max_iters=100):\n\n n_iterations = [5]*n_epochs\n for ee in range(n_epochs):\n if ee >= 20:\n n_iterations[ee] = 5\n if ee >= 23:\n n_iterations[ee] = 7\n if ee >= 28:\n n_iterations[ee] = 9\n if ee >= 38:\n n_iterations[ee] = 11\n if ee >= 44:\n n_iterations[ee] = 13\n if ee >= 50:\n n_iterations[ee] = 20\n if ee >= 58:\n n_iterations[ee] = 30\n\n forward_iterator = eq_utils.anderson\n deep_eq_module = eq_utils.DEQFixedPointNeumann(single_iterate_solver, neumann_k=100, solver=forward_iterator,\n m=5, lam=1e-4, max_iter=max_iters, tol=1e-3, beta=1.5)\n\n for epoch in range(start_epoch, n_epochs):\n\n # We are lucky to have\n if epoch % save_every_n_epochs == 0:\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n for ii, sample_batch in enumerate(train_dataloader):\n optimizer.zero_grad()\n\n sample_batch = sample_batch[0].to(device=device)\n y = measurement_process(sample_batch)\n single_iterate_solver.set_initial_point(y)\n reconstruction = deep_eq_module.forward(y)\n loss = loss_function(reconstruction, sample_batch)\n loss.backward()\n optimizer.step()\n\n if ii % print_every_n_steps == 0:\n logging_string = \"Epoch: \" + str(epoch) + \" Step: \" + str(ii) + \\\n \" Loss: \" + str(loss.cpu().detach().numpy())\n print(logging_string, flush=True)\n\n if scheduler is not None:\n scheduler.step(epoch)\n if use_dataparallel:\n torch.save({'solver_state_dict': single_iterate_solver.module.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n else:\n torch.save({'solver_state_dict': single_iterate_solver.state_dict(),\n 'epoch': epoch,\n 'optimizer_state_dict': optimizer.state_dict(),\n 'scheduler_state_dict': scheduler.state_dict()\n }, save_location)\n\n #####################TEST##########################\n # loss_accumulator = []\n # mse_loss = torch.nn.MSELoss()\n # for ii, sample_batch in enumerate(test_dataloader):\n # sample_batch = sample_batch.to(device=device)\n # y = measurement_process(sample_batch)\n # initial_point = y\n # reconstruction = solver(initial_point, iterations=6)\n #\n # reconstruction = torch.clamp(reconstruction, -1 ,1)\n #\n # loss = mse_loss(reconstruction, sample_batch)\n # loss_logger = loss.cpu().detach().numpy()\n # loss_accumulator.append(loss_logger)\n #\n # loss_array = np.asarray(loss_accumulator)\n # loss_mse = np.mean(loss_array)\n # PSNR = -10 * np.log10(loss_mse)\n # percentiles = np.percentile(loss_array, [25,50,75])\n # percentiles = -10.0*np.log10(percentiles)\n # print(\"TEST LOSS: \" + str(sum(loss_accumulator) / len(loss_accumulator)), flush=True)\n # print(\"MEAN TEST PSNR: \" + str(PSNR), flush=True)\n # print(\"TEST PSNR QUARTILES AND MEDIAN: \" + str(percentiles[0]) +\n # \", \" + str(percentiles[1]) + \", \" + str(percentiles[2]), flush=True)\n" }, { "alpha_fraction": 0.5817747712135315, "alphanum_fraction": 0.6064465045928955, "avg_line_length": 41.59321975708008, "blob_id": "f2db023009a13f366d799b62e2632fd4a902afe7", "content_id": "e3fa695cd5a0c9bfdb02dc92b66cba39f0cc021a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2513, "license_type": "no_license", "max_line_length": 106, "num_lines": 59, "path": "/utils/testing_utils.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "from PIL import Image\nimport torch\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport imageio\nfrom PIL import Image\n\ndef save_tensor_as_color_img(img_tensor, filename):\n np_array = img_tensor.cpu().detach().numpy()\n imageio.save(filename, np_array)\n\ndef save_batch_as_color_imgs(tensor_batch, batch_size, ii, folder_name, names):\n # img_array = (np.transpose(tensor_batch.cpu().detach().numpy(),(0,2,3,1)) + 1.0) * 127.5\n img_array = (np.clip(np.transpose(tensor_batch.cpu().detach().numpy(),(0,2,3,1)),-1,1) + 1.0) * 127.5\n # img_array = tensor_batch.cpu().detach().numpy()\n # print(np.max(img_array[:]))\n # print(np.min(img_array[:]))\n\n img_array = img_array.astype(np.uint8)\n\n for kk in range(batch_size):\n desired_img = Image.fromarray(img_array[kk,...])\n desired_img = desired_img.resize((512,512), resample=Image.NEAREST)\n img_number = batch_size*ii + kk\n filename = folder_name + str(img_number) + \"_\" + str(names[kk]) + \".png\"\n # print(np.shape(img_array))\n # print(filename)\n imageio.imwrite(filename, desired_img)\n\ndef save_mri_as_imgs(tensor_batch, batch_size, ii, folder_name, names):\n # img_array = (np.transpose(tensor_batch.cpu().detach().numpy(),(0,2,3,1)) + 1.0) * 127.5\n\n def rescale_to_01(input):\n batch_size = input.shape[0]\n for bb in range(batch_size):\n flattened_img = torch.flatten(input[bb, ...], start_dim=0)\n img_min = torch.min(flattened_img)\n img_max = torch.max(flattened_img - img_min)\n input[bb, ...] = (input[bb, ...] - img_min) / img_max\n return input\n tensor_batch = torch.norm(tensor_batch, dim=1)\n tensor_batch = rescale_to_01(tensor_batch)\n\n # img_array = torch.norm(tensor_batch, dim=1).cpu().detach().numpy()\n img_array = tensor_batch.cpu().detach().numpy()\n\n for kk in range(batch_size):\n img_number = batch_size*ii + kk\n target_img = img_array[kk,...] * 255.0\n target_img = target_img.astype(np.uint8)\n desired_img = Image.fromarray(target_img)\n desired_img = desired_img.resize((512, 512), resample=Image.NEAREST)\n filename = folder_name + str(img_number) + \"_\" + str(names[kk]) + \".png\"\n # plt.imshow(np.sqrt(img_array[kk,0,:,:]**2 + img_array[kk,1,:,:]**2))\n # plt.gray()\n # plt.xticks([])\n # plt.yticks([])\n # plt.savefig(filename, bbox_inches='tight')\n imageio.imwrite(filename, desired_img, format=\"PNG-PIL\")\n" }, { "alpha_fraction": 0.5310698747634888, "alphanum_fraction": 0.5533779263496399, "avg_line_length": 34.54917907714844, "blob_id": "2eb2ffd45f99ca9e61128e848ec1e9bb5f9af181", "content_id": "a9795f01b83cfc6b306c8b184a614b901e0f7b32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17348, "license_type": "no_license", "max_line_length": 120, "num_lines": 488, "path": "/solvers/broyd_equilibrium_utils.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch.nn as nn\nimport torch\nimport matplotlib\n#matplotlib.use(\"TkAgg\")\nfrom matplotlib import pyplot as plt\nimport imageio\nimport numpy as np\nfrom PIL import Image\n\n\ndef _safe_norm(v):\n if not torch.isfinite(v).all():\n return np.inf\n return torch.norm(v)\n\n\ndef scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0):\n ite = 0\n phi_a0 = phi(alpha0) # First do an update with step size 1\n if phi_a0 <= phi0 + c1 * alpha0 * derphi0:\n return alpha0, phi_a0, ite\n\n # Otherwise, compute the minimizer of a quadratic interpolant\n alpha1 = -(derphi0) * alpha0 ** 2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0)\n phi_a1 = phi(alpha1)\n\n # Otherwise loop with cubic interpolation until we find an alpha which\n # satisfies the first Wolfe condition (since we are backtracking, we will\n # assume that the value of alpha is not too small and satisfies the second\n # condition.\n while alpha1 > amin: # we are assuming alpha>0 is a descent direction\n factor = alpha0 ** 2 * alpha1 ** 2 * (alpha1 - alpha0)\n a = alpha0 ** 2 * (phi_a1 - phi0 - derphi0 * alpha1) - \\\n alpha1 ** 2 * (phi_a0 - phi0 - derphi0 * alpha0)\n a = a / factor\n b = -alpha0 ** 3 * (phi_a1 - phi0 - derphi0 * alpha1) + \\\n alpha1 ** 3 * (phi_a0 - phi0 - derphi0 * alpha0)\n b = b / factor\n\n alpha2 = (-b + torch.sqrt(torch.abs(b ** 2 - 3 * a * derphi0))) / (3.0 * a)\n phi_a2 = phi(alpha2)\n ite += 1\n\n if (phi_a2 <= phi0 + c1 * alpha2 * derphi0):\n return alpha2, phi_a2, ite\n\n if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2 / alpha1) < 0.96:\n alpha2 = alpha1 / 2.0\n\n alpha0 = alpha1\n alpha1 = alpha2\n phi_a0 = phi_a1\n phi_a1 = phi_a2\n\n # Failed to find a suitable step length\n return None, phi_a1, ite\n\n\ndef line_search(update, x0, g0, g, nstep=0, on=True):\n \"\"\"\n `update` is the propsoed direction of update.\n Code adapted from scipy.\n \"\"\"\n tmp_s = [0]\n tmp_g0 = [g0]\n tmp_phi = [torch.norm(g0) ** 2]\n s_norm = torch.norm(x0) / torch.norm(update)\n\n def phi(s, store=True):\n if s == tmp_s[0]:\n return tmp_phi[0] # If the step size is so small... just return something\n x_est = x0 + s * update\n g0_new = g(x_est)\n phi_new = _safe_norm(g0_new) ** 2\n if store:\n tmp_s[0] = s\n tmp_g0[0] = g0_new\n tmp_phi[0] = phi_new\n return phi_new\n\n if on:\n s, phi1, ite = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0], amin=1e-2)\n if (not on) or s is None:\n s = 1.0\n ite = 0\n\n x_est = x0 + s * update\n if s == tmp_s[0]:\n g0_new = tmp_g0[0]\n else:\n g0_new = g(x_est)\n return x_est, g0_new, x_est - x0, g0_new - g0, ite\n\n\ndef rmatvec(part_Us, part_VTs, x):\n # Compute x^T(-I + UV^T)\n # x: (N, 2d, L')\n # part_Us: (N, 2d, L', threshold)\n # part_VTs: (N, threshold, 2d, L')\n if part_Us.nelement() == 0:\n return -x\n xTU = torch.einsum('bij, bijd -> bd', x, part_Us) # (N, threshold)\n return -x + torch.einsum('bd, bdij -> bij', xTU, part_VTs) # (N, 2d, L'), but should really be (N, 1, (2d*L'))\n\n\ndef matvec(part_Us, part_VTs, x):\n # Compute (-I + UV^T)x\n # x: (N, 2d, L')\n # part_Us: (N, 2d, L', threshold)\n # part_VTs: (N, threshold, 2d, L')\n if part_Us.nelement() == 0:\n return -x\n VTx = torch.einsum('bdij, bij -> bd', part_VTs, x) # (N, threshold)\n return -x + torch.einsum('bijd, bd -> bij', part_Us, VTx) # (N, 2d, L'), but should really be (N, (2d*L'), 1)\n\n\ndef broyden(g, x0, threshold=9, eps=1e-5, ls=False):\n x0_shape = x0.shape\n x0 = x0.reshape((x0.shape[0], -1, 1))\n bsz, total_hsize, n_elem = x0.size()\n dev = x0.device\n\n x_est = x0 # (bsz, 2d, L')\n gx = g(x_est) # (bsz, 2d, L')\n nstep = 0\n tnstep = 0\n LBFGS_thres = min(threshold, 27)\n\n # For fast calculation of inv_jacobian (approximately)\n Us = torch.zeros(bsz, total_hsize, n_elem, LBFGS_thres).to(dev)\n VTs = torch.zeros(bsz, LBFGS_thres, total_hsize, n_elem).to(dev)\n update = gx\n new_objective = init_objective = torch.norm(gx).item()\n prot_break = False\n trace = [init_objective]\n new_trace = [-1]\n\n # To be used in protective breaks\n protect_thres = 1e6 * n_elem\n lowest = new_objective\n lowest_xest, lowest_gx, lowest_step = x_est, gx, nstep\n\n while new_objective >= eps and nstep < threshold:\n x_est, gx, delta_x, delta_gx, ite = line_search(update, x_est, gx, g, nstep=nstep, on=ls)\n nstep += 1\n tnstep += (ite + 1)\n new_objective = torch.norm(gx).item()\n trace.append(new_objective)\n try:\n new2_objective = torch.norm(delta_x).item() / (torch.norm(x_est - delta_x).item()) # Relative residual\n except:\n new2_objective = torch.norm(delta_x).item() / (torch.norm(x_est - delta_x).item() + 1e-9)\n new_trace.append(new2_objective)\n if new_objective < lowest:\n lowest_xest, lowest_gx = x_est.clone().detach(), gx.clone().detach()\n lowest = new_objective\n lowest_step = nstep\n if new_objective < eps:\n # print(nstep)\n break\n if new_objective < 3 * eps and nstep > 30 and np.max(trace[-30:]) / np.min(trace[-30:]) < 1.3:\n # if there's hardly been any progress in the last 30 steps\n # print(nstep)\n break\n if new_objective > init_objective * protect_thres:\n # prot_break = True\n # print(nstep)\n break\n\n part_Us, part_VTs = Us[:, :, :, :(nstep - 1)], VTs[:, :(nstep - 1)]\n vT = rmatvec(part_Us, part_VTs, delta_x)\n u = (delta_x - matvec(part_Us, part_VTs, delta_gx)) / torch.einsum('bij, bij -> b', vT, delta_gx)[:, None, None]\n vT[vT != vT] = 0\n u[u != u] = 0\n VTs[:, (nstep - 1) % LBFGS_thres] = vT\n Us[:, :, :, (nstep - 1) % LBFGS_thres] = u\n update = -matvec(Us[:, :, :, :nstep], VTs[:, :nstep], gx)\n\n Us, VTs = None, None\n lowest_xest = lowest_xest.reshape(x0_shape)\n return lowest_xest, torch.norm(lowest_gx).item()\n # return {\"result\": lowest_xest,\n # \"nstep\": nstep,\n # \"tnstep\": tnstep,\n # \"lowest_step\": lowest_step,\n # \"diff\": torch.norm(lowest_gx).item(),\n # \"diff_detail\": torch.norm(lowest_gx, dim=1),\n # \"prot_break\": prot_break,\n # \"trace\": trace,\n # \"new_trace\": new_trace,\n # \"eps\": eps,\n # \"threshold\": threshold}\n\n\n\ndef L2Norm(x):\n return torch.sum(x**2, dim=[1,2,3], keepdim=True)\n\ndef epsilon2(f, x0, max_iter=50, tol=1e-2, lam=1e-4):\n\n x = x0\n\n for k in range(max_iter):\n f_x = f(x)\n delta_x = f_x - x\n delta_f = f(f_x) - f_x\n delta2_x = delta_f - delta_x\n # term1 = delta_f * L2Norm(delta_x)\n # term2 = delta_x * L2Norm(delta_f)\n x_new = f_x + (delta_f * L2Norm(delta_x) - delta_x * L2Norm(delta_f)) / (L2Norm(delta2_x) + lam)\n residual = (x_new - x).norm().item() / x_new.norm().item()\n x = x_new\n if (residual < tol):\n break\n\n return x, residual\n\ndef forward_iteration(f, x0, max_iter=50, tol=1e-5):\n f0 = f(x0)\n res = []\n for k in range(max_iter):\n x = f0\n f0 = f(x)\n res.append((f0 - x).norm().item() / (1e-7 + f0.norm().item()))\n if (res[-1] < tol):\n break\n return f0, res\n\ndef forward_iteration_plot(f, x0, max_iter=50, tol=1e-5):\n f0 = f(x0)\n res = []\n fig = plt.figure()\n for k in range(max_iter):\n x = f0\n f0 = f(x)\n # sub = fig.add_subplot(10,10, k)\n # plt.imshow(f0[0, : , :, :].detach().cpu().numpy())\n # plt.show()\n res.append((f0 - x).norm().item() / (1e-7 + f0.norm().item()))\n if (res[-1] < tol):\n break\n plt.show()\n return f0, res\n\n\nclass DEQFixedPoint(nn.Module):\n def __init__(self, f, **kwargs):\n super().__init__()\n self.f = f\n self.kwargs = kwargs\n\n def broyd_output_test(self, z, x, y_shape, input_shape):\n reshaped_x = torch.reshape(input=x, shape=y_shape)\n reshaped_z = torch.reshape(input=z, shape=input_shape)\n output = self.f(reshaped_z, reshaped_x) - reshaped_z\n flattened = torch.reshape(output, (output.shape[0], -1)).unsqueeze(-1)\n return flattened\n\n # def broyd_grad(self, g, z, x, g_shape, z_shape):\n # self.solver(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0] + grad,\n # grad, **self.kwargs)\n\n def internal_g(self, z, x):\n return self.f(z, x) - z\n\n\n def forward(self, x, truth = None, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n # init_point = torch.reshape(init_point, (init_point.shape[0], -1, 1))\n initial_point_shape = initial_point.shape\n g = lambda z: self.broyd_output_test(z, x, x.shape, initial_point_shape)\n with torch.no_grad():\n output_x, self.forward_res = broyden(g, init_point, threshold=self.kwargs['max_iter'], eps=1e-8)\n # output_x = torch.reshape(output_x, initial_point_shape)\n z = self.f(output_x, x)\n\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n # g0 = f0 - z0\n\n def backward_hook(grad):\n\n def internal_function(y):\n input_shape = y.shape\n y = y.reshape(grad.shape)\n broyden_function = grad + torch.autograd.grad(f0, z0, y, retain_graph=True)[0]\n g_version = broyden_function - y\n g_version = g_version.reshape(input_shape)\n return g_version\n\n result = broyden(internal_function, grad, threshold=10, eps=1e-7)\n\n return result[0]\n\n z.register_hook(backward_hook)\n return z\n\nclass DEQFixedPointSimple(nn.Module):\n def __init__(self, f, **kwargs):\n super().__init__()\n self.f = f\n self.kwargs = kwargs\n\n def broyd_output_test(self, z, x, y_shape, input_shape):\n reshaped_x = torch.reshape(input=x, shape=y_shape)\n reshaped_z = torch.reshape(input=z, shape=input_shape)\n output = self.f(reshaped_z, reshaped_x) - reshaped_z\n flattened = torch.reshape(output, (output.shape[0], -1)).unsqueeze(-1)\n return flattened\n\n def internal_g(self, z, x):\n return self.f(z, x) - z\n\n def forward(self, x, truth=None, initial_point=None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n # init_point = torch.reshape(init_point, (init_point.shape[0], -1, 1))\n initial_point_shape = initial_point.shape\n g = lambda z: self.broyd_output_test(z, x, x.shape, initial_point_shape)\n with torch.no_grad():\n output_x, self.forward_res = broyden(g, init_point, threshold=self.kwargs['max_iter'], eps=1e-7)\n # output_x = torch.reshape(output_x, initial_point_shape)\n z = self.f(output_x, x)\n\n return z\n\n # def forward(self, x, initial_point = None):\n # if initial_point is None:\n # init_point = torch.zeros_like(x)\n # else:\n # init_point = initial_point\n # # compute forward pass and re-engage autograd tape\n # with torch.no_grad():\n # z, self.forward_res = self.solver(lambda z: self.f(z, x), init_point, **self.kwargs)\n # z = self.f(z, x)\n #\n # # set up Jacobian vector product (without additional forward calls)\n # z0 = z.clone().detach().requires_grad_()\n # f0 = self.f(z0, x)\n #\n # def backward_hook(grad):\n # g, self.backward_res = self.solver(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0] + grad,\n # grad, **self.kwargs)\n # return g\n #\n # z.register_hook(backward_hook)\n # return z\n\nclass DEQFixedPoint2(nn.Module):\n def __init__(self, f, **kwargs):\n super().__init__()\n self.f = f\n self.kwargs = kwargs\n\n def broyd_output_test(self, z, x, y_shape, input_shape):\n reshaped_x = torch.reshape(input=x, shape=y_shape)\n reshaped_z = torch.reshape(input=z, shape=input_shape)\n output = self.f(reshaped_z, reshaped_x) - reshaped_z\n flattened = torch.reshape(output, (output.shape[0], -1)).unsqueeze(-1)\n return flattened\n\n def internal_g(self, z, x):\n return self.f(z, x) - z\n\n\n def forward(self, x, truth = None, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n # init_point = torch.reshape(init_point, (init_point.shape[0], -1, 1))\n initial_point_shape = initial_point.shape\n g = lambda z: self.broyd_output_test(z, x, x.shape, initial_point_shape)\n with torch.no_grad():\n output_x, self.forward_res = broyden(g, init_point, threshold=100, eps=1e-7)\n # output_x = torch.reshape(output_x, initial_point_shape)\n z = self.f(output_x, x)\n\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n # g0 = f0 - z0\n\n def backward_hook(grad):\n g, self.backward_res = self.solver(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0] + grad,\n grad, **self.kwargs)\n return g\n\n z.register_hook(backward_hook)\n return z\n\nclass DEQFixedPointTest(nn.Module):\n def __init__(self, f, solver, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.kwargs = kwargs\n\n def broyd_output_test(self, z, x, y_shape, input_shape):\n reshaped_x = torch.reshape(input=x, shape=y_shape)\n reshaped_z = torch.reshape(input=z, shape=input_shape)\n output = self.f(reshaped_z, reshaped_x) - reshaped_z\n flattened = torch.reshape(output, (output.shape[0], -1)).unsqueeze(-1)\n return flattened\n\n\n def forward(self, x, truth = None, initial_point = None):\n if initial_point is None:\n init_point = torch.zeros_like(x)\n else:\n init_point = initial_point\n # compute forward pass and re-engage autograd tape\n init_point = torch.reshape(init_point, (init_point.shape[0], -1, 1))\n initial_point_shape = initial_point.shape\n g = lambda z: self.broyd_output_test(z, x, x.shape, initial_point_shape)\n with torch.no_grad():\n output_x, self.forward_res = broyden(g, init_point, threshold=50, eps=1e-7)\n output_x = torch.reshape(output_x, initial_point_shape)\n\n return output_x\n\ndef neumann_iteration(f, x0,k=10):\n accumulator = x0\n current_iterate = x0\n for _ in range(k):\n current_iterate = f(current_iterate)\n accumulator = accumulator + current_iterate\n\n return accumulator\n\n\nclass DEQFixedPointNeumann(nn.Module):\n def __init__(self, f, solver, neumann_k, **kwargs):\n super().__init__()\n self.f = f\n self.solver = solver\n self.neumann_k = neumann_k\n self.kwargs = kwargs\n\n def forward(self, x):\n # compute forward pass and re-engage autograd tape\n with torch.no_grad():\n z, self.forward_res = self.solver(lambda z: self.f(z, x), torch.zeros_like(x), **self.kwargs)\n z = self.f(z, x)\n\n # set up Jacobian vector product (without additional forward calls)\n z0 = z.clone().detach().requires_grad_()\n f0 = self.f(z0, x)\n\n def backward_hook(grad):\n g = neumann_iteration(lambda y: torch.autograd.grad(f0, z0, y, retain_graph=True)[0],\n grad, self.neumann_k)\n return g\n\n z.register_hook(backward_hook)\n return z\n\ndef get_equilibrium_point(solver, z, max_iterations=50, tolerance = 0.001):\n running_iterate = z\n for iteration in range(max_iterations):\n running_iterate = solver(running_iterate)\n return running_iterate, running_iterate\n\ndef get_equilibrium_point_plot(solver, z, truth, max_iterations=50, tolerance = 0.001):\n running_iterate = z\n # fig = plt.figure()\n jj = 0\n for iteration in range(max_iterations):\n # if iteration % 10 == 0:\n # sub = fig.add_subplot(2, 5, jj+1)\n # img_to_show = torch.abs(running_iterate[0, :, :, :] - truth[0,:,:,:])*5.0\n # # plt.imshow((running_iterate[0, :, :, :].permute(1,2,0).cpu().detach().numpy() + 1.0) / 2.0)\n # # plt.show()\n # # sub.imshow((img_to_show.permute(1,2,0).detach().cpu().numpy() + 1.0)/2.0)\n # sub.imshow(img_to_show.permute(1,2,0).detach().cpu().numpy())\n #\n # jj += 1\n running_iterate = solver(running_iterate)\n # plt.show()\n\n return running_iterate, running_iterate\n" }, { "alpha_fraction": 0.7007116675376892, "alphanum_fraction": 0.7134064435958862, "avg_line_length": 36.94890594482422, "blob_id": "d9885e36edf115c91b457544ac76721b4f3100e9", "content_id": "609d980bcb2cecdf68f601e80417acb3f57ce82d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5199, "license_type": "no_license", "max_line_length": 121, "num_lines": 137, "path": "/scripts/denoising/mri_dncnn_denoise.py", "repo_name": "wwhappylife/deep_equilibrium_inverse", "src_encoding": "UTF-8", "text": "import torch\nimport os\nimport random\nimport sys\nimport argparse\nsys.path.append('/home-nfs/gilton/learned_iterative_solvers')\n# sys.path.append('/Users/dgilton/PycharmProjects/learned_iterative_solvers')\n\nimport torch.nn as nn\nimport torch.optim as optim\n\nimport operators.operator as lin_operator\nfrom operators.operator import OperatorPlusNoise\nfrom utils.fastmri_dataloader import singleCoilFastMRIDataloader\nfrom networks.normalized_cnn_2 import DnCNN\nfrom solvers.equilibrium_solvers import EquilibriumGrad\nfrom training import denoiser_training\nfrom solvers import new_equilibrium_utils as eq_utils\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', default=80)\nparser.add_argument('--batch_size', type=int, default=16)\nparser.add_argument('--and_maxiters', default=100)\nparser.add_argument('--and_beta', type=float, default=1.0)\nparser.add_argument('--and_m', type=int, default=5)\nparser.add_argument('--lr', type=float, default=0.1)\nparser.add_argument('--etainit', type=float, default=0.5)\nparser.add_argument('--lr_gamma', type=float, default=0.1)\nparser.add_argument('--sched_step', type=int, default=10)\nparser.add_argument('--acceleration', type=float, default=8.0)\nparser.add_argument('--noise_sigma', type=float, default=0.01)\nparser.add_argument('--savepath',\n default=\"/share/data/vision-greg2/users/gilton/celeba_equilibriumgrad_mri_save_inf.ckpt\")\nargs = parser.parse_args()\n\n\n# Parameters to modify\nn_epochs = int(args.n_epochs)\ncurrent_epoch = 0\nbatch_size = int(args.batch_size)\nn_channels = 2\nmax_iters = int(args.and_maxiters)\nanderson_m = int(args.and_m)\nanderson_beta = float(args.and_beta)\n\nlearning_rate = float(args.lr)\nprint_every_n_steps = 10\nsave_every_n_epochs = 5\ninitial_eta = float(args.etainit)\n\ndataheight = 320\ndatawidth = 320\n\nnoise_sigma = float(args.noise_sigma)\n\n# modify this for your machine\n# save_location = \"/share/data/vision-greg2/users/gilton/mnist_equilibriumgrad_blur.ckpt\"\nsave_location = args.savepath\nload_location = args.savepath\n\ngpu_ids = []\nfor ii in range(6):\n try:\n torch.cuda.get_device_properties(ii)\n print(str(ii), flush=True)\n if not gpu_ids:\n gpu_ids = [ii]\n else:\n gpu_ids.append(ii)\n except AssertionError:\n print('Not ' + str(ii) + \"!\", flush=True)\n\nprint(os.getenv('CUDA_VISIBLE_DEVICES'), flush=True)\ngpu_ids = [int(x) for x in gpu_ids]\n# device management\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nuse_dataparallel = len(gpu_ids) > 1\nprint(\"GPU IDs: \" + str([int(x) for x in gpu_ids]), flush=True)\n\n# Set up data and dataloaders\ndata_location = \"/share/data/vision-greg2/users/gilton/singlecoil_curated_clean/\"\ntrainset_size = 2000\ntotal_data = 2194\nrandom.seed(10)\nall_indices = list(range(trainset_size))\ntrain_indices = random.sample(range(total_data), k=trainset_size)\ndataset = singleCoilFastMRIDataloader(data_location, data_indices=train_indices)\ndataloader = torch.utils.data.DataLoader(\n dataset=dataset, batch_size=args.batch_size, shuffle=True, drop_last=True,\n)\n\n### Set up solver and problem setting\n\nforward_operator = lin_operator.Identity().to(device=device)\nmeasurement_process = OperatorPlusNoise(forward_operator, noise_sigma=noise_sigma).to(device=device)\n\nsolver = DnCNN(in_channels=n_channels, out_channels=n_channels, internal_channels=64,\n num_of_layers=17, lip=1.0)\n\nif use_dataparallel:\n solver = nn.DataParallel(solver, device_ids=gpu_ids)\nsolver = solver.to(device=device)\n\nstart_epoch = 0\noptimizer = optim.Adam(params=solver.parameters(), lr=learning_rate)\nscheduler = optim.lr_scheduler.StepLR(optimizer=optimizer, step_size=int(args.sched_step), gamma=float(args.lr_gamma))\ncpu_only = not torch.cuda.is_available()\n\n\nif os.path.exists(load_location):\n if not cpu_only:\n saved_dict = torch.load(load_location)\n else:\n saved_dict = torch.load(load_location, map_location='cpu')\n\n start_epoch = saved_dict['epoch']\n solver.load_state_dict(saved_dict['solver_state_dict'])\n # optimizer.load_state_dict(saved_dict['optimizer_state_dict'])\n scheduler.load_state_dict(saved_dict['scheduler_state_dict'])\n\n\n# set up loss and train\nlossfunction = torch.nn.MSELoss()\n\n# forward_iterator = eq_utils.anderson\n# deep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, m=anderson_m, beta=anderson_beta, lam=1e-6,\n# max_iter=max_iters, tol=1e-8)\nforward_iterator = eq_utils.forward_iteration\ndeep_eq_module = eq_utils.DEQFixedPoint(solver, forward_iterator, max_iter=100, tol=1e-8)\n\n# Do train\ndenoiser_training.train_denoiser(denoising_net=solver, train_dataloader=dataloader, test_dataloader=dataloader,\n measurement_process=measurement_process, optimizer=optimizer, save_location=save_location,\n loss_function=lossfunction, n_epochs=n_epochs,\n use_dataparallel=use_dataparallel, device=device, scheduler=scheduler,\n print_every_n_steps=print_every_n_steps, save_every_n_epochs=save_every_n_epochs,\n start_epoch=start_epoch)\n" } ]
17
bryanlinamln/Blackjack
https://github.com/bryanlinamln/Blackjack
89b496f179f06066eac0f0112cec5b64c40ecf8a
8c326236fd7bde3e63b52aaac8ede5f9481a30c4
fbd8555d2f82a4cd95556b7afb58365aedb6a0ac
refs/heads/main
2023-01-12T16:06:53.976837
2020-11-19T22:38:42
2020-11-19T22:38:42
314,378,631
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.545997142791748, "alphanum_fraction": 0.5616381764411926, "avg_line_length": 26.607954025268555, "blob_id": "90d5fbb9544a3166fc07ec6c3dddce3eeb233308", "content_id": "8a3865fb50e4c4bd18518495843afd3903495413", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4859, "license_type": "no_license", "max_line_length": 75, "num_lines": 176, "path": "/BlackJack.py", "repo_name": "bryanlinamln/Blackjack", "src_encoding": "UTF-8", "text": "# Black Jack\n# Card is tuple (Suit, Value)\n# (0, 0) is null card\nimport random\n\n# Returns card to be added to stack\ndef generateCard(cardsInPlay):\n # Possible suits of cards\n # Clubs is C, Diamonds is D, Heart is H, and S is Spades\n Suits = ['C', 'D', 'H', 'S']\n # Possible values for cards\n Value = ['A', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K']\n # Suit of generated card\n suit = 0\n # Value of generated card\n value = 0\n # While card isn't a possible card option\n notValid = True\n\n # Generated card until a valid one comes up\n while notValid:\n suit = random.randrange(0, 4)\n value = random.randrange(0, 13)\n\n # Gets Suit Char for card\n if suit == 0:\n suit = 'C'\n elif suit == 1:\n suit = 'D'\n elif suit == 2:\n suit = 'H'\n else:\n suit = 'S'\n\n # Gets Value for card\n if value == 0:\n value = 'A'\n elif value == 10:\n value = 'J'\n elif value == 11:\n value = 'Q'\n elif value == 12:\n value = 'K'\n else:\n value += 1\n\n # Checks if card is already in play\n if (suit, value) in cardsInPlay:\n pass\n else:\n notValid = False\n\n return (suit, value)\n\n# Returns value of stack for player\ndef calculateValue(playersCards):\n # Value of stack\n value = 0\n # Number of aces\n aceCount = 0\n\n # Gets value of cards in stack without Aces\n for card in playersCards:\n if card[1] == 'A':\n aceCount += 1\n elif card[1] == 'J' or card[1] == 'Q' or card[1] == 'K':\n value += 10\n else:\n value += card[1]\n\n # Add value of aces to value of card stack\n value += aceCount\n for i in range(aceCount):\n if value <= 11:\n value += 10\n\n return value\n\n# Decides which move for dealer\ndef dealerDecision(playerCards, dealerCards):\n # If 17, stand\n if calculateValue(dealerCards) == 17:\n return (0, 0)\n # If less than 17, hit\n elif calculateValue(dealerCards) < 17:\n return generateCard(playerCards + dealerCards)\n # If less than player, hit\n elif calculateValue(dealerCards) < calculateValue(playerCards):\n return generateCard(playerCards + dealerCards)\n # Else, stand\n else:\n return (0, 0)\n\n# Gets user's action\ndef readUserInput(cardsInPlay):\n # Asks until valid input is given\n while True:\n move = input('Will you HIT(1) or STAND(2)?')\n # If hit, add card to stack\n if move == 'HIT' or move == '1':\n return generateCard(cardsInPlay)\n # If stand, return null card\n elif move == 'STAND' or move == '2':\n return (0, 0)\n else:\n pass\n\n# Runs game\ndef runGame():\n # Stacks for player and dealer cards\n playerCards = []\n dealerCards = []\n\n # Adds 2 cards to player stack and 1 card to dealer stack\n playerCards.append(generateCard(playerCards + dealerCards))\n dealerCards.append(generateCard(playerCards + dealerCards))\n playerCards.append(generateCard(playerCards + dealerCards))\n\n if calculateValue(playerCards) == 21:\n print('Blackjack! You win!')\n\n # Player's turn\n while True:\n displayCards(playerCards, dealerCards)\n # Checks if bust\n if calculateValue(playerCards) > 21:\n print('You have busted! You lose!')\n return None\n # Player moves\n card = readUserInput(playerCards + dealerCards)\n if card == (0, 0):\n break\n else:\n playerCards.append(card)\n\n # Dealer starts his turn\n dealerCards.append(generateCard(playerCards + dealerCards))\n\n # Dealer's turn\n while True:\n displayCards(playerCards, dealerCards)\n # Checks if bust\n if calculateValue(dealerCards) > 21:\n print('Dealer has busted! You win!')\n return None\n # Dealer moves\n newCard = dealerDecision(playerCards, dealerCards)\n if newCard == (0, 0):\n break\n else:\n dealerCards.append(newCard)\n\n # Checks who wins or if tie\n if calculateValue(playerCards) > calculateValue(dealerCards):\n print('You win!')\n elif calculateValue(dealerCards) > calculateValue(playerCards):\n print('You lose!')\n else:\n print('It\\'s a tie!')\n\n# Displays cards and their values\ndef displayCards(playerCards, dealerCards):\n print(dealerCards, end = ' ')\n print('=', end = ' ')\n print(calculateValue(dealerCards))\n print(playerCards, end = ' ')\n print('=', end = ' ')\n print(calculateValue(playerCards))\n print('--------------------------------------------------------------')\n\ndef main():\n for i in range(5):\n runGame()\n\nif __name__ == '__main__':\n main()\n" } ]
1
jwrr/z80soc
https://github.com/jwrr/z80soc
dde94b0188de65d451c53e41381aa42f931ff7ba
66fdd4a3dc5b418c4cae1e03960ac154fdc97766
27906df08df1d49588e47a0c9640179c8693bd44
refs/heads/master
2022-12-23T23:10:31.248502
2020-09-19T21:28:55
2020-09-19T21:28:55
295,144,891
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.70652174949646, "avg_line_length": 10.375, "blob_id": "ba20930d34a6b0c5b2440fd1b68edb949e90bac0", "content_id": "41136a9560ce8f7040cd3732fa4366abdac0431f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 92, "license_type": "permissive", "max_line_length": 35, "num_lines": 8, "path": "/ctc/cocotb/README.md", "repo_name": "jwrr/z80soc", "src_encoding": "UTF-8", "text": "# CTC Test using cocotb\ncocotb testbench written in Python3\n\n# Run testbench\n\n```\nmake\n``` \n" }, { "alpha_fraction": 0.517630934715271, "alphanum_fraction": 0.5516258478164673, "avg_line_length": 32.341548919677734, "blob_id": "0a21c49dbcffe0663feae5f9059ad5b227640b55", "content_id": "180816826530cfff20b9eb08e20d4227118029ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9472, "license_type": "permissive", "max_line_length": 133, "num_lines": 284, "path": "/ctc/cocotb/test_ctc_core.py", "repo_name": "jwrr/z80soc", "src_encoding": "UTF-8", "text": "\nimport random\nimport cocotb\nfrom cocotb.clock import Clock\nfrom cocotb.triggers import Edge\nfrom cocotb.triggers import FallingEdge\nfrom cocotb.triggers import RisingEdge\nfrom cocotb.triggers import ClockCycles\nfrom cocotb.triggers import ReadOnly\nfrom utils.dvtest import DVTest\n\nfrom cocotb.monitors import Monitor\nfrom cocotb.drivers import BitDriver\nfrom cocotb.binary import BinaryValue\nfrom cocotb.regression import TestFactory\nfrom cocotb.scoreboard import Scoreboard\n\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n\n# Timer\n# Start on TC Load\n# Read timer\n# Start on EDGE change\n# Start on CLK_TRIG re\n# Start on CLK_TRIG fe\n# Counter\n# SW decrement\n# TRIG decrement\n\n# input clk,\n# input reset_n,\n# input ce_n,\n# input cs,\n# input m1_n,\n# input rd_n,\n# input iorq_n,\n# input [DWID-1:0] din,\n# output [DWID-1:0] dout,\n# output oe_n,\n# input iei,\n# output ieo,\n# output int_n,\n#\n# input clk_trg,\n# output zc_to\n\n\nasync def ctc_write(dut, addr, wdata):\n await RisingEdge(dut.clk)\n dut.rd_n = 1\n dut.m1_n = 1\n dut.ce_n = 0\n dut.cs = addr;\n await RisingEdge(dut.clk)\n dut.iorq_n = 0\n dut.din = wdata\n await RisingEdge(dut.clk)\n dut.din = 0x00\n await RisingEdge(dut.clk)\n dut.iorq_n = 1\n dut.rd_n = 1\n dut.m1_n = 1\n dut.ce_n = 1\n dut.cs = 0\n await RisingEdge(dut.clk)\n\n\nasync def ctc_read(dut, addr):\n await RisingEdge(dut.clk)\n dut.rd_n = 1\n dut.m1_n = 1\n dut.ce_n = 0\n dut.cs = addr;\n await RisingEdge(dut.clk)\n dut.iorq_n = 0\n dut.rd_n = 0\n await RisingEdge(dut.clk)\n# await FallingEdge(dut.clk)\n await ReadOnly()\n rdata = dut.dout.value.integer\n await RisingEdge(dut.clk)\n dut.iorq_n = 1\n dut.rd_n = 1\n dut.m1_n = 1\n dut.ce_n = 1\n dut.cs = 0\n await RisingEdge(dut.clk)\n return rdata\n\n\nasync def ctc_hw_reset(dv):\n dut = dv.dut\n dut.reset_n = 0\n dut.ce_n = 1\n dut.m1_n = 1\n dut.rd_n = 1\n dut.iorq_n = 1\n dut.din = 0\n dut.iei = 0\n dut.clk_trg = 0\n await ClockCycles(dut.clk,100)\n dut.reset_n = 1\n await ClockCycles(dut.clk,100)\n\n\nasync def ctc_sw_reset(dv, din):\n dut = dv.dut\n dv.dbg(\" \" + \"Reset Timer\")\n await ctc_write(dut, 0x1, din | 0x03)\n\n\nasync def ctc_poll(dv, nn, din, exp, msg):\n dut = dv.dut\n dv.info(\" \" + msg)\n dut.din = din\n prev = 257\n for i in range(nn):\n await ClockCycles(dut.clk, 100)\n rdata = await ctc_read(dut, 0x1)\n if exp == 0:\n dv.eq(rdata, 0, \"Timer should be off\")\n else:\n dv.neq(rdata, prev, \"Timer should be decrementing\")\n prev = rdata\n\n# =============================================================================\n# =============================================================================\n\n### ===========================================================================\n### CTC TIMER TEST\n\nasync def run_ctc_timer_test(dut):\n\n clk = Clock(dut.clk, 10, units=\"ns\") # Create a 10us period clock on port clk\n cocotb.fork(clk.start()) # Start the clock\n await ClockCycles(dut.clk,2)\n\n# dv = DVTest(dut, \"CTC TIMER TEST\", msg_lvl=\"All\")\n dv = DVTest(dut, \"CTC TIMER TEST\", msg_lvl=\"Fail\")\n\n await ctc_hw_reset(dv)\n\n # Verify auto trigger (trig immediately after the time const is loaded)\n dv.notice(\"Test auto trigger\")\n for i in range(1, 101, 10):\n await ctc_write(dut, 0x1, 0x05)\n await ctc_write(dut, 0x1, i)\n await ctc_poll(dv, 20, 0x88, -1, \"After Loading Time Constant - Timer should decrement (din=0x88)\")\n\n # Reset timer, Configure it to start on with sw edge change \n dv.notice(\"Test software trigger\")\n await ctc_sw_reset(dv, 0x03)\n await ctc_poll(dv, 5, 0x97, 0, \"After Reset - Timer should NOT decrement (din=0x98)\")\n await ctc_write(dut, 0x1, 0x0d) # control word, ext trigger\n await ctc_write(dut, 0x1, 0x80) # time constant\n await ctc_poll(dv, 5, 0x98, 0, \"After loading Time Constant but before Software Trigger - Timer should NOT decrement (din=0x98)\")\n await ctc_write(dut, 0x1, 0x19) # control word\n await ctc_poll(dv, 5, 0x99, -1, \"After Software Trigger - Timer should decrement (din=0x99)\")\n\n # Verify falling edge external trigger\n dv.notice(\"Test falling edge trigger\")\n await ctc_sw_reset(dv,0x0B)\n await ctc_poll(dv, 5, 0xAA, 0, \"After Reset - The timer should stay 0 (din=0xAA)\")\n await ctc_write(dut, 0x1, 0x0d) # control word, ext trigger\n await ctc_write(dut, 0x1, 0x20) # time constant\n await ctc_poll(dv, 5, 0xBB, 0, \"Before External Trigger - The timer should NOT decrement (din=0xBB)\")\n\n dut.clk_trg = 1\n await ctc_poll(dv, 5, 0xCC, 0, \"After Rising Edge - The timer should NOT trigger (din=0xCC)\")\n \n dut.clk_trg = 0\n await ctc_poll(dv, 5, 0xDD, -1, \"After Falling Edge - The timer should trigger (din=0xDD)\")\n \n # Verify rising edge external trigger\n dv.notice(\"Test rising edge trigger\")\n await ctc_sw_reset(dv,0x1B)\n await ctc_poll(dv, 5, 0xE0, 0, \"After Reset - The timer should stay 0 (din=0xE0)\")\n await ctc_write(dut, 0x1, 0x1d) # control word, ext trigger\n await ctc_write(dut, 0x1, 0x20) # time constant\n await ctc_poll(dv, 5, 0xE1, 0, \"Before External Trigger - The timer should NOT decrement (din=0xE1)\")\n\n dut.clk_trg = 1\n await ctc_poll(dv, 5, 0xE2, -1, \"After Rising Edge - The timer should trigger (din=0xE2)\")\n\n dv.done()\n await ClockCycles(dut.clk, 100)\n \n\n### ===========================================================================\n### CTC COUNTER TEST\n\nasync def run_ctc_counter_test(dut):\n clk = Clock(dut.clk, 10, units=\"ns\") # Create a 10us period clock on port clk\n cocotb.fork(clk.start()) # Start the clock\n await ClockCycles(dut.clk,2)\n\n# dv = DVTest(dut, \"CTC COUNTER TEST\", msg_lvl=\"All\")\n dv = DVTest(dut, \"CTC COUNTER TEST\", msg_lvl=\"Fail\")\n\n # -------------------------------------------------------------------------\n \n await ctc_hw_reset(dv)\n dv.notice(\"Test software trigger\")\n await ctc_sw_reset(dv, 0x73)\n await ctc_write(dut, 0x1, 0x75) # channel control word\n await ctc_write(dut, 0x1, 0x10) # time constant\n await ctc_poll(dv, 5, 0xF0, 0, \"After Reset - Counter should NOT decrement (din=0xF0)\")\n \n exp = 0x10\n for i in range(100):\n await ctc_write(dut, 0x1, 0x61) # channel control word\n cnt = await ctc_read(dut, 0x1)\n exp = 0xF if exp==0 else exp - 1\n dv.eq(cnt, exp, \"cnt should decrement on software falling edge\")\n await ctc_write(dut, 0x1, 0x71) # channel control word\n cnt = await ctc_read(dut, 0x1)\n exp = 0xF if exp==0 else exp - 1\n dv.eq(cnt, exp, \"cnt should decrement on software rising edge\")\n\n # -------------------------------------------------------------------------\n \n await ctc_hw_reset(dv)\n dv.notice(\"Test Rising Edge trigger\")\n await ctc_sw_reset(dv, 0x73)\n await ctc_write(dut, 0x1, 0x75) # channel control word\n await ctc_write(dut, 0x1, 0x10) # time constant\n await ctc_poll(dv, 5, 0xF0, 0, \"After Reset - Counter should NOT decrement (din=0xF0)\")\n \n exp = 0x0\n dut.din = 0xF1\n for i in range(100):\n# await ctc_write(dut, 0x1, 0x61) # channel control word\n exp = 0xF if exp==0 else exp - 1\n dut.clk_trg = 1\n await RisingEdge(dut.clk)\n cnt = await ctc_read(dut, 0x1)\n dv.eq(cnt, exp, \"cnt should decrement on clk_trg rising edge\")\n dut.clk_trg = 0\n await RisingEdge(dut.clk)\n cnt = await ctc_read(dut, 0x1)\n dv.eq(cnt, exp, \"cnt should NOT decrement on software falling edge\")\n \n # -------------------------------------------------------------------------\n \n await ctc_hw_reset(dv)\n dv.notice(\"Test Falling Edge trigger\")\n await ctc_sw_reset(dv, 0x63)\n await ctc_write(dut, 0x1, 0x65) # channel control word\n await ctc_write(dut, 0x1, 0x10) # time constant\n await ctc_poll(dv, 5, 0xF0, 0, \"After Reset - Counter should NOT decrement (din=0xF0)\")\n \n exp = 0x0\n dut.din = 0xF1\n for i in range(100):\n dut.clk_trg = 1\n await RisingEdge(dut.clk)\n cnt = await ctc_read(dut, 0x1)\n dv.eq(cnt, exp, \"cnt should NOT decrement on clk_trg rising edge\")\n dut.clk_trg = 0\n await RisingEdge(dut.clk)\n exp = 0xF if exp==0 else exp - 1\n cnt = await ctc_read(dut, 0x1)\n dv.eq(cnt, exp, \"cnt should decrement on software falling edge\")\n \n\n\n dv.done()\n await ClockCycles(dut.clk, 100)\n\n\n# =============================================================================\n# =============================================================================\n\nenable_ctc_timer_test = True\nenable_ctc_counter_test = True\n\nasync def run_test_suite(dut):\n if enable_ctc_timer_test: await run_ctc_timer_test(dut)\n if enable_ctc_counter_test: await run_ctc_counter_test(dut)\n\n# Register the test.\nfactory = TestFactory(run_test_suite)\nfactory.generate_tests()\n\n\n" }, { "alpha_fraction": 0.6940789222717285, "alphanum_fraction": 0.7541118264198303, "avg_line_length": 45.69230651855469, "blob_id": "a9503fafa8f2dd8f34eae1516cb63d27bafff6ae", "content_id": "9427a3315a05b63ab9aae5f10957637f5f72b2db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1216, "license_type": "permissive", "max_line_length": 155, "num_lines": 26, "path": "/README.md", "repo_name": "jwrr/z80soc", "src_encoding": "UTF-8", "text": "# z80soc\n\nz80 + ctc + dma + pio + sio\n\n## Status\n\n**NOTHING WORKS. DO NOT USE.**\n\n* CTC is timer and counter pass basic simulation tests. Interrupts are not implemented yet.\n\n## Description\n\nThis project attempts to recreate the periperals defined in the\n[Z80 Family CPU Peripherals User Manual](http://www.z80.info/zip/um0081.pdf),\nincluding the Counter/Timer Channels (CTC), Direct Memory Access (DMA),\nParallel Input/Output (PIO), and Serial Input/Output (SIO).\n\n## Useful Links\n\n* [Z80 Family CPU Peripherals User Manual](http://www.z80.info/zip/um0081.pdf)\n* [Z8430 Z80 CTC Datasheet](http://arcarc.xmission.com/Tech/Datasheets/Z80%20CTC.pdf)\n* [Howto Program the Z80 CTC](http://www.blunk-electronic.de/train-z/pdf/howto_program_the_Z80-CTC.pdf)\n* [Smithonian Chips - Product Evaluation of the Zilog Z80 CTC](http://smithsonianchips.si.edu/ice/OCR_ScanPE125/PE125(10379-K).pdf)\n* [Let's Add a Z80 CTC](https://www.leonardomiliani.com/en/2019/english-lm80c-lets-add-a-z80-ctc/)\n* [Z80 Family Product Specifications Handbook Feb 1984](http://www.bitsavers.org/components/zilog/z80/Z80_Family_Product_Specifications_Handbook_Feb84.pdf)\n* [Bitsavers - Many Z80 Books](http://bitsavers.org/components/zilog/z80/)\n\n\n" }, { "alpha_fraction": 0.6604709029197693, "alphanum_fraction": 0.6617100238800049, "avg_line_length": 25, "blob_id": "86e0b8beccb2203c61362da997764583ae8191a3", "content_id": "a6f816f04672fbbd371c6c60cc998e6ac03cea0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 807, "license_type": "permissive", "max_line_length": 78, "num_lines": 31, "path": "/ctc/cocotb/Makefile", "repo_name": "jwrr/z80soc", "src_encoding": "UTF-8", "text": "TOPLEVEL ?= ctc_core\nMODULE ?= test_$(TOPLEVEL)\n\n# SRC_PATH = ./$(TOPLEVEL)\nSRC_PATH = ..\nSRC = $(SRC_PATH)/src/$(TOPLEVEL).v\n# SRC += ../tinyfpga_bx_usbserial/usb/*.v\nVERILOG_SOURCES = $(SRC)\n\n\n# If WAVES is define then add waves.v to the compile list to set $dumpvars and\n# $dumpfile. Also define the vcd filename if it has not been set yet.\nWAVES ?= fst\nifneq ( $(WAVES),)\n SRC += ./waves.v\n ifeq ($(WAVES),fst)\n EXTENDED_ARGS += -fst\n WAVES_OUT ?= $(TOPLEVEL).fst\n endif\n PLUSARGS += +WAVES_ON\n WAVES_OUT ?= $(TOPLEVEL).vcd\n COMPILE_ARGS += -DWAVES_OUT=\\\"$(WAVES_OUT)\\\" -s waves\nendif\n\n# DEBUG, INFO, WARNING, ERROR, CRITICAL\nexport COCOTB_LOG_LEVEL ?= INFO\nexport COCOTB_REDUCED_LOG_FMT ?= 1\nSIM ?= icarus\nTOPLEVEL_LANG ?= verilog\n\ninclude $(shell cocotb-config --makefiles)/Makefile.sim\n\n" } ]
4
hernanpesantez/algorithms
https://github.com/hernanpesantez/algorithms
083bc04d7276404e82654821197fd8d56b258dc9
f7d7949e45013a1e12da7d6cf30af109dc8bed38
87cbe1b6bd32181827a4d32a70a775b969f85eec
refs/heads/master
2022-12-06T15:13:53.245901
2020-08-26T16:54:53
2020-08-26T16:54:53
278,458,948
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5037693381309509, "alphanum_fraction": 0.5173918604850769, "avg_line_length": 21.631736755371094, "blob_id": "33d66d52b6e1b42a067ad06c1717432678af2c66", "content_id": "f20d485b1df820a718f44e3951c7d308173d0701", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7561, "license_type": "no_license", "max_line_length": 148, "num_lines": 334, "path": "/assignment6/astar.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\nfrom warnings import warn\nimport heapq\n\nimport sys\nimport sys\nimport re\n\nimport time\nimport subprocess\nimport binascii\n\nimport pprintpp\nimport pprint\nimport codecs\n\n\ndef read_file(filepath):\n with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:\n\n raw_txt = txt.read()\n \n raw_txt = raw_txt.upper()\n raw_txt.replace(' ','')\n raw_txt = raw_txt.strip()\n \n\n matrix = {}\n\n p = []\n m = raw_txt.split('\\n')\n \n print(m)\n\n for i in m:\n x = i.split('=')\n\n value = x[1] \n \n matrix = {x[0]:value}\n # print(matrix)\n p.append(matrix)\n\n width = 0\n height = 0\n source = 0\n target = 0\n kingmode = False\n\n person = []\n for i in range(len(p)):\n\n if 'WIDTH' in p[i].keys():\n \n # print(\"v\",p[i][\"WIDTH\"])\n width = p[i][\"WIDTH\"]\n\n elif 'HEIGHT' in p[i].keys():\n # print(\"v\",p[i][\"HEIGHT\"])\n height = p[i][\"HEIGHT\"]\n\n elif 'SOURCE' in p[i].keys():\n # print(\"v\",p[i][\"SOURCE\"])\n source = p[i][\"SOURCE\"]\n\n source = source.split(',')\n # print(source)\n source = (int(source[0]),int(source[1]))\n\n\n elif 'TARGET' in p[i].keys():\n # print('v',p[i]['TARGET'])\n target = p[i]['TARGET']\n target = target.split(',')\n # print(target)\n target = (int(target[0]),int(target[1]))\n\n elif 'KINGMODE' in p[i].keys():\n # print('v',p[i]['KINGMODE'])\n kingmode = p[i]['KINGMODE'].strip()\n \n if kingmode == 'TRUE':\n kingmode =True\n else:\n kingmode =False\n \n \n \n\n elif \"PERSON\" in p[i].keys():\n # print(\"v\",p[i][\"PERSON\"])s\n \n\n person.append(p[i]['PERSON'])\n###\n width = int(width)+1\n height = int(height)+1\n\n\n \n\n Matrix = [[0 for x in range(height)] for y in range(width)]\n\n\n\n # pprint.pprint(Matrix)\n\n for i in range(len(person)):\n\n man = person[i].split(',')\n x = int(man[0])\n y = int(man[1])\n Matrix[x-1][y-1] = 1 \n\n\n\n\n\n\n pprint.pprint(Matrix)\n\n return Matrix, target, source, kingmode\n \n\n\n\n\n\n# Credit for this: Nicholas Swift\n# as found at https://medium.com/@nicholas.w.swift/easy-a-star-pathfinding-7e6689c7f7b2\n\n\nclass Node:\n \"\"\"\n A node class for A* Pathfinding\n \"\"\"\n\n def __init__(self, parent=None, position=None):\n self.parent = parent\n self.position = position\n\n self.g = 0\n self.h = 0\n self.f = 0\n\n def __eq__(self, other):\n return self.position == other.position\n \n def __repr__(self):\n return f\"{self.position} - g: {self.g} h: {self.h} f: {self.f}\"\n\n # defining less than for purposes of heap queue\n def __lt__(self, other):\n return self.f < other.f\n \n # defining greater than for purposes of heap queue\n def __gt__(self, other):\n return self.f > other.f\n\ndef return_path(current_node):\n path = []\n current = current_node\n while current is not None:\n path.append(current.position)\n current = current.parent\n return path[::-1] # Return reversed path\n\n\ndef astar(maze, start, end, allow_diagonal_movement):\n\n\n count = 0;\n \"\"\"\n Returns a list of tuples as a path from the given start to the given end in the given maze\n :param maze:\n :param start:\n :param end:\n :return:\n \"\"\"\n\n # Create start and end node\n start_node = Node(None, start)\n start_node.g = start_node.h = start_node.f = 0\n end_node = Node(None, end)\n end_node.g = end_node.h = end_node.f = 0\n\n # Initialize both open and closed list\n open_list = []\n closed_list = []\n\n # Heapify the open_list and Add the start node\n heapq.heapify(open_list) \n heapq.heappush(open_list, start_node)\n\n # Adding a stop condition\n outer_iterations = 0\n max_iterations = (len(maze[0]) * len(maze) // 2)\n\n # what squares do we search\n adjacent_squares = ((0, -1), (0, 1), (-1, 0), (1, 0),)\n if allow_diagonal_movement:\n adjacent_squares = ((0, -1), (0, 1), (-1, 0), (1, 0), (-1, -1), (-1, 1), (1, -1), (1, 1),)\n\n # Loop until you find the end\n while len(open_list) > 0:\n \n count += 1\n \n\n outer_iterations += 1\n\n if outer_iterations > max_iterations:\n # if we hit this point return the path such as it is\n # it will not contain the destination\n warn(\"giving up on pathfinding too many iterations\")\n return return_path(current_node), count \n \n\n \n # Get the current node\n current_node = heapq.heappop(open_list)\n closed_list.append(current_node)\n \n\n\n # Found the goal\n if current_node == end_node:\n\n return return_path(current_node), count\n\n # Generate children\n children = []\n \n for new_position in adjacent_squares: # Adjacent squares\n\n count += 1\n\n # Get node position\n node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n\n # Make sure within range\n if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:\n count+=1\n\n continue\n\n # Make sure walkable terrain\n if maze[node_position[0]][node_position[1]] != 0:\n count+=1\n\n continue\n\n # Create new node\n new_node = Node(current_node, node_position)\n\n # Append\n children.append(new_node)\n\n # Loop through children\n for child in children:\n\n\n count += 1\n \n\n # Child is on the closed list\n if len([closed_child for closed_child in closed_list if closed_child == child]) > 0:\n count += 1\n \n continue\n\n # Create the f, g, and h values\n child.g = current_node.g + 1\n child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)\n child.f = child.g + child.h\n\n # Child is already in the open list\n if len([open_node for open_node in open_list if child.position == open_node.position and child.g > open_node.g]) > 0:\n count+=1\n continue\n\n\n # Add the child to the open list\n heapq.heappush(open_list, child)\n \n warn(\"Couldn't get a path to destination\")\n return None\n\n\n\n\n\ndef example( argv , print_maze = True):\n\n maze, target, source, kingmode = read_file(argv[1])\n \n \n \n print(kingmode)\n\n path, count = astar(maze, source, target, kingmode)\n\n if print_maze:\n for step in path:\n maze[step[0]][step[1]] = 2\n \n for row in maze:\n line = []\n for col in row:\n if col == 1:\n line.append(\"p\")\n elif col == 0:\n line.append(\"-\")\n elif col == 2:\n line.append(\"*\")\n print(\"\".join(line))\n\n print(path)\n\n return count\n\n\ndef main(argv):\n\n start_time = time.time()\n result = example(argv) \n time_taken = format(round((time.time() - start_time),9))\n result = {'astar':{'comparisons':result,'clock':time_taken}}\n\n print(result)\n\n \n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5236530900001526, "avg_line_length": 15.55434799194336, "blob_id": "294aaae2a1d5c2f7d7a9eb907d9b7af2758c54a5", "content_id": "9783d3d743960f73e070e891800de915e46f6a11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1522, "license_type": "no_license", "max_line_length": 67, "num_lines": 92, "path": "/assignment4/huff.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "from heapq import heappush, heappop, heapify, nsmallest \nfrom collections import defaultdict\n\nimport pprint\n \ndef encode(symb2freq):\n \"\"\"Huffman encode the given dict mapping symbols to weights\"\"\"\n \n\n heap =[]\n for sym, wt in symb2freq.items():\n # print(sym,wt)\n x = [sym,\"\"]\n y = [wt,x]\n # print(y)\n heap.append(y)\n\n \n\n\n heapify(heap)\n # print(heap)\n \n while len(heap) > 1:\n lo = heappop(heap)\n hi = heappop(heap)\n \n for pair in lo[1:]:\n\n \n pair[1] = '0' + pair[1]\n \n for pair in hi[1:]:\n pair[1] = '1' + pair[1]\n heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])\n # pprint.pprint(heap)\n return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))\n\n\n\n\n\n\n\n\ntxt = \"this is an example for huffman encoding\"\nsymb2freq = defaultdict(int)\nfor ch in txt:\n symb2freq[ch] += 1\n# in Python 3.1+:\n# symb2freq = collections.Counter(txt)\n\n# print(symb2freq.keys())\n# print(symb2freq.values())\n\n\n\nhuff = encode(symb2freq)\n# print(huff)\n\n\n\n\n\n\ndef decode(huff):\n heap = huff\n for p in huff:\n print (p[0], symb2freq[p[0]], p[1]) \n heapify(huff)\n \n nsmallest(huff)\n # print(huff)\n \n while len(heap) > 1:\n lo = heappop(heap)\n hi = heappop(heap)\n print(lo)\n \n \n\n heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])\n return heap\n\n\nx = decode(huff)\n\n# print(x)\n\nwhile len(x)>1:\n v = heappop(x)\n print(v)" }, { "alpha_fraction": 0.37657585740089417, "alphanum_fraction": 0.40585604310035706, "avg_line_length": 33.125, "blob_id": "e031ebdcd001bee1284da323c2867078f995f2e5", "content_id": "448c473f1b8b02bf4a5d1911e745be0ecd57c2e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2459, "license_type": "no_license", "max_line_length": 174, "num_lines": 72, "path": "/assignments1/binarysearchLeaftRight.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "import random\nimport math\n\ndef populateArray(size):\n arr = []\n for x in range(size):\n \n y = x+random.randint(1, 10) \n arr += [y]\n return arr\n \n\n# This function is a modification of a dinary search algorithm by Smitha Dinesh Semwal\n# src: https://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/ \ndef binarySearch(arr, l, r, x): \n comparisons = 0\n while l <= r: \n \n mid = l + (r - l) // 2\n comparisons =comparisons+1\n if arr[mid] == x:\n \n return int(arr[mid]), int(mid), int(comparisons), int(arr[mid+1]), int(arr[mid-1])\n \n # If x is greater, ignore left half\n elif arr[mid] < x:\n comparisons =comparisons+1\n\n l = mid + 1\n # If x is smaller, ignore right half\n else:\n comparisons =comparisons+1\n\n r = mid - 1\n\n \n # If we reach here, then the element \n # was not present \n return [-1, comparisons]\n \n\n# Driver Code \ndef main(keys,size):\n print('keys to search for: ',keys,'\\n')\n j = 0\n for i in keys:\n j = j+1 \n print('Iteration (',j,') searching for: ', i)\n print('===================================================================================================================')\n print('| key | value | comparisons | expected comparisons | left | right | size of array |')\n print('| | | | | | | |')\n\n \n arr = populateArray(size)\n arr.sort()\n expectedComparisons = (1 + math.log2(len(arr)))\n \n # Function call \n value = binarySearch(arr, 0, len(arr)-1, i) \n \n if value[0] != -1: \n print ('| ', value[1],' |',value[0],' | ',value[2], ' | ', int(expectedComparisons),' | ',\n value[4], ' | ',value[3],' | ', len(arr),' |')\n else: \n print('|',i,' | None | ',value[1],' | ',int(expectedComparisons),' | None | None | ' ,len(arr) ,' |')\n print('===================================================================================================================')\n print('\\n')\n\nif __name__ == \"__main__\":\n\n arr =[1111,2222,3333,4444,5555,6666,7777,8888,2233,3322]\n main(arr,65536)\n\n\n" }, { "alpha_fraction": 0.4867452085018158, "alphanum_fraction": 0.49926361441612244, "avg_line_length": 27.27083396911621, "blob_id": "0b926a14e8951fc1c3aaffcd5e74ea3cff8ef30c", "content_id": "8eea471d4e9d38820b4b744f110c664a0e054d93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1358, "license_type": "no_license", "max_line_length": 78, "num_lines": 48, "path": "/algorithms/bin_packing/best_fit.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\n# Python3 program to find number of bins required using \n# First Fit algorithm. \n \n# Returns number of bins required using first fit \n# online algorithm \ndef firstFit(weight, n, c): \n \n # Initialize result (Count of bins) \n res = 0; \n \n # Create an array to store remaining space in bins \n # there can be at most n bins \n bin_rem = [0]*n; \n \n # Place items one by one \n for i in range(n): \n \n # Find the first bin that can accommodate \n # weight[i] \n j = 0; \n \n # Initialize minimum space left and index \n # of best bin \n min = c + 1; \n bi = 0; \n \n for j in range(res): \n if (bin_rem[j] >= weight[i] and bin_rem[j] - weight[i] < min): \n bi = j; \n min = bin_rem[j] - weight[i]; \n \n # If no bin could accommodate weight[i], \n # create a new bin \n if (min == c + 1): \n bin_rem[res] = c - weight[i]; \n res += 1; \n else: # Assign the item to best bin \n bin_rem[bi] -= weight[i]; \n return res; \n \n# Driver code \nif __name__ == '__main__': \n weight = [ 2, 5, 4, 7, 1, 3, 8 ]; \n c = 10; \n n = len(weight); \n print(\"Number of bins required in First Fit : \", firstFit(weight, n, c)); \n \n# This code is contributed by Rajput-Ji " }, { "alpha_fraction": 0.5480915904045105, "alphanum_fraction": 0.5770992636680603, "avg_line_length": 19.4375, "blob_id": "38cc78f6c8e4530a32149e1735786b4d77209140", "content_id": "5e87a58e4bc79dfefb2041a5cafe66817e2d4c92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "no_license", "max_line_length": 54, "num_lines": 32, "path": "/algorithms/numerical/horner.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\n# Python program for \n# implementation of Horner Method \n# for Polynomial Evaluation \n \n# returns value of poly[0]x(n-1) \n# + poly[1]x(n-2) + .. + poly[n-1] \ndef horner(poly, n, x): \n \n # Initialize result \n result = poly[0] \n \n # Evaluate value of polynomial \n # using Horner's method \n for i in range(1, n): \n \n result = result*x + poly[i] \n \n return result \n \n# Driver program to \n# test above function. \n \n# Let us evaluate value of \n# 2x3 - 6x2 + 2x - 1 for x = 3 \npoly = [2, -6, 2, -1] \nx = 3\nn = len(poly) \n \nprint(\"Value of polynomial is \" , horner(poly, n, x)) \n \n# This code is contributed \n# by Anant Agarwal. " }, { "alpha_fraction": 0.5333333611488342, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14, "blob_id": "d10de62271c74e61dd09e87542206182bef9d1f7", "content_id": "b94a5b8e5662b88c674e6853160d6f19e887c1ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15, "license_type": "no_license", "max_line_length": 14, "num_lines": 1, "path": "/README.md", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "# 323-projects\n" }, { "alpha_fraction": 0.5208804607391357, "alphanum_fraction": 0.5321950316429138, "avg_line_length": 29.16149139404297, "blob_id": "ddbfde3a0532221a50dd7294e28b2ba9c6568b63", "content_id": "4d4f3786ca00fb6ed3e62bad29478121656631e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4861, "license_type": "no_license", "max_line_length": 199, "num_lines": 161, "path": "/assignment4/main.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "import sys\nimport re\nimport codecs\nimport time\nimport subprocess\nimport binascii\nfrom subprocess import check_output\n\nimport rle, lzw, huffman\n\ndef read_file(filepath):\n with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:\n\n raw_txt = txt.read()\n \n return raw_txt\n \n \ndef tabulate(original_length,compressed_length,compression_rate,storage,time_taken,comparisons):\n\n\n print('|----------|-----------------|------------------|----------------------|----------------|-------------|')\n print('| raw size | compressed size | compression rate | storage requirements | comparisons | clock |')\n print('|----------|-----------------|------------------|----------------------|----------------|-------------|')\n\n print('| '+str(original_length)+' | '+str(compressed_length)+' | '+str(compression_rate)+' | '+str(storage)+' | '+str(comparisons)+' |'+str(time_taken)+' |')\n \n \n#test | driver\ndef main(argv):\n\n\n\n txt = read_file(argv[1])\n original_length = len(txt)*8\n 'SRC: https://www.rosettacode.org/wiki/Run-length_encoding'\n\n print(\"-----------------------------------------> ORIGINAL TXT...\\n\\n\")\n print(txt)\n print('\\n\\n')\n#==================================== clock for rle =====================\n start_time = time.time()\n value = rle.encode(txt)\n time_taken = format(round((time.time() - start_time),9),'11f')\n print(\"-----------------------------------------> COMPRESSED TXT...\\n\")\n print(value[0])\n value1 = txt\n \n print('\\n\\n')\n\n comparisons = value[2]\n compressed_length = len(value[0])*8\n compressed_rate = original_length - compressed_length\n compression_rate = original_length/compressed_length\n compression_rate = format(round(compression_rate,9),'11f')\n storage = original_length\n storage = storage / compressed_length*8\n storage = format(round(storage,9),'11f')\n tabulate(original_length,compressed_length,compression_rate,storage,time_taken,comparisons)\n print('\\n\\n')\n print(\"-----------------------------------------> DECOMPRESSED TXT...\\n\")\n print(rle.decode(value[0]))\n\n#==================================== clock for huffman =====================\n# src: https://rosettacode.org/wiki/Huffman_coding\n\n\n print(\"\\n\\n\\nHUFFMAN ENCODING...\")\n print(\"-----------------------------------------> ORIGINAL TXT...\\n\\n\")\n print(txt)\n # txt = \"go go gophers\"\n print('\\n\\n')\n\n\n start_time = time.time()\n value = huffman.encode(txt)\n time_taken = format(round((time.time() - start_time),9),'11f')\n print(\"-----------------------------------------> COMPRESSED TXT...\\n\")\n\n \n print(value)\n print('\\n\\n')\n\n print(len(value[0])*8)\n comparisons = value[1]\n compressed_length = 0\n\n for i in range(len(value[0])):\n # print(value[0][i][1])\n compressed_length += len(value[0][i][1])+ord(value[0][i][0])*3\n # print(compressed_length)\n\n\n\n \n\n compressed_rate = original_length - compressed_length\n\n \n\n compression_rate = original_length/compressed_length\n compression_rate = format(round(compression_rate,9),'11f')\n\n\n storage = original_length\n storage = storage / compressed_length\n storage = format(round(storage,9),'11f')\n tabulate(original_length,compressed_length,compression_rate,storage,time_taken,comparisons)\n print('\\n\\n')\n print(\"-----------------------------------------> DECOMPRESSED TXT...\\n\")\n\n print(value1)\n\n\n\n print(\"-----------------------------------------> ORIGINAL TXT...\\n\\n\")\n print(txt)\n print('\\n\\n')\n#==================================== clock for lzw =====================\n\n#src : https://rosettacode.org/wiki/Huffman_coding\n\n\n start_time = time.time()\n value = lzw.compress(txt)\n time_taken = format(round((time.time() - start_time),9),'11f')\n print(\"-----------------------------------------> COMPRESSED TXT...\\n\")\n print(value[0])\n \n\n\n \n print('\\n\\n')\n\n comparisons = value[1]\n compressed_length = len(value[0])*8\n\n compressed_length = float(compressed_length)\n\n compressed_rate = original_length - compressed_length\n compression_rate = original_length/compressed_length\n compression_rate = format(round(compression_rate,9),'10f')\n storage = original_length\n storage = storage / compressed_length\n storage = format(round(storage,9),'11f')\n tabulate(original_length,compressed_length,compression_rate,storage,time_taken,comparisons)\n print('\\n\\n')\n print(\"-----------------------------------------> DECOMPRESSED TXT...\\n\")\n print(lzw.decompress(value[0]))\n\n\n\n print('\\n\\nFirst Name: ',\"HERNAN\")\n print('Last Name: ',\"PESANTEZ\")\n\n print( f'SRC: https://www.rosettacode.org/wiki/Run-length_encoding')\n \n\nif __name__ == \"__main__\":\n\n main(sys.argv)\n\n " }, { "alpha_fraction": 0.46875, "alphanum_fraction": 0.4937500059604645, "avg_line_length": 23, "blob_id": "226d6cf357fc907d5ff091e2cf27d83db4dc4af8", "content_id": "bf461587fc9a6f1ac5c6e73d9a2ee1892b573d83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/algorithms/bin_packing/next_fit.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "# Python3 implementation for above approach \ndef nextfit(weight, c): \n res = 0\n rem = c \n for _ in range(len(weight)): \n if rem >= weight[_]: \n rem = rem - weight[_] \n else: \n res += 1\n rem = c - weight[_] \n return res \n \n# Driver Code \nweight = [2, 5, 4, 7, 1, 3, 8] \nc = 10\n \nprint(\"Number of bins required in Next Fit :\", \n nextfit(weight, c)) \n \n# This code is contributed by code_freak " }, { "alpha_fraction": 0.45434048771858215, "alphanum_fraction": 0.470969557762146, "avg_line_length": 17.647367477416992, "blob_id": "1668a51154038480fb159c20cb7ee975eeaf2088", "content_id": "a969b4a018c532b9b6eee1d5616719150a36c0be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3548, "license_type": "no_license", "max_line_length": 104, "num_lines": 190, "path": "/assignment6/dfs.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\n\n\n\n\n\nimport numpy as np\nimport queue\nimport time\nimport sys\n\nimport collections\n\n\n\n\nimport pprintpp\nimport pprint\nimport codecs\n\n\ndef read_file(filepath):\n with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:\n\n raw_txt = txt.read()\n \n raw_txt = raw_txt.upper()\n raw_txt.replace(' ','')\n raw_txt = raw_txt.strip()\n \n\n matrix = {}\n\n p = []\n m = raw_txt.split('\\n')\n \n print(m)\n\n for i in m:\n x = i.split('=')\n\n value = x[1] \n \n matrix = {x[0]:value}\n # print(matrix)\n p.append(matrix)\n\n width = 0\n height = 0\n source = 0\n target = 0\n kingmode = False\n\n person = []\n for i in range(len(p)):\n\n if 'WIDTH' in p[i].keys():\n \n # print(\"v\",p[i][\"WIDTH\"])\n width = p[i][\"WIDTH\"]\n\n elif 'HEIGHT' in p[i].keys():\n # print(\"v\",p[i][\"HEIGHT\"])\n height = p[i][\"HEIGHT\"]\n\n elif 'SOURCE' in p[i].keys():\n # print(\"v\",p[i][\"SOURCE\"])\n source = p[i][\"SOURCE\"]\n\n source = source.split(',')\n # print(source)\n source = (int(source[0]),int(source[1]))\n\n\n elif 'TARGET' in p[i].keys():\n # print('v',p[i]['TARGET'])\n target = p[i]['TARGET']\n target = target.split(',')\n # print(target)\n target = (int(target[0]),int(target[1]))\n\n elif 'KINGMODE' in p[i].keys():\n # print('v',p[i]['KINGMODE'])\n kingmode = p[i]['KINGMODE'].strip()\n \n if kingmode == 'TRUE':\n kingmode =True\n else:\n kingmode =False\n \n \n \n\n elif \"PERSON\" in p[i].keys():\n # print(\"v\",p[i][\"PERSON\"])s\n \n\n person.append(p[i]['PERSON'])\n###\n width = int(width)+1\n height = int(height)+1\n\n\n \n\n Matrix = [[0 for x in range(height)] for y in range(width)]\n\n\n\n # pprint.pprint(Matrix)\n\n for i in range(len(person)):\n\n man = person[i].split(',')\n x = int(man[0])\n y = int(man[1])\n Matrix[x-1][y-1] = 1 \n\n\n\n\n\n\n pprint.pprint(Matrix)\n\n return Matrix, target, source, kingmode, width, height,target\n\n\n\n\n\n\ngrid, target, source, kingmode, width, height, target = read_file(sys.argv[1])\n\nprint(grid[target[0]][target[1]])\n\n\ngrid[target[0]][target[1]] = 9\n\npprint.pprint(grid)\n\n\n\n\ndef bfs(grid, start):\n count = 0;\n queue = collections.deque([[start]])\n seen = set([start])\n while queue:\n path = queue.popleft()\n x, y = path[-1]\n\n count += 1\n \n if grid[y][x] == goal:\n return path\n for x2, y2 in ((x+1,y), (x-1,y), (x,y+1), (x,y-1)):\n count += 1\n \n if 0 <= x2 < height and 0 <= y2 < width and grid[y2][x2] != wall and (x2, y2) not in seen:\n queue.append(path + [(x2, y2)])\n seen.add((x2, y2))\n\nwall, clear, goal = 1, 0, 9\n\n\n\npath = bfs(grid, (0, 0))\n\nprint(path)\n\nmaze = grid\n\n \nfor step in path:\n maze[step[0]][step[1]] = 2\n\nfor row in maze:\n line = []\n for col in row:\n if col == 1:\n line.append(\"p\")\n elif col == 0:\n line.append(\"-\")\n elif col == 2:\n line.append(\"*\")\n print(\"\".join(line))\n\n\n\nstart_time = time.time()\nresult = example(argv) \ntime_taken = format(round((time.time() - start_time),9))\nresult = {'astar':{'comparisons':result,'clock':time_taken}}\n\nprint(result)" }, { "alpha_fraction": 0.4555555582046509, "alphanum_fraction": 0.4740740656852722, "avg_line_length": 25.712871551513672, "blob_id": "82fa6ca10d30e33a316c1729b6a1702348d24bd8", "content_id": "23c57b0fec8d7a0f7600a6b863a1c64d63a97de5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2700, "license_type": "no_license", "max_line_length": 86, "num_lines": 101, "path": "/assignment3/lps_dp.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "# A Dynamic Programming based Python \n# program for LPS problem Returns the length \n# of the longest palindromic subsequence in seq \n\n\n# This code is contributed by Bhavya Jain \n# Source: https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/\n\n\ndef lps_n2_n2(string): \n n = len(string) \n \n # Create a table to store results of subproblems \n L = [[0 for x in range(n)] for x in range(n)] \n count = 0 \n \n # stringings of length 1 are palindrome of length 1 \n for i in range(n): \n L[i][i] = 1\n \n # Build the table. Note that the lower \n # diagonal values of table are \n # useless and not filled in the process. \n # The values are filled in a \n # manner similar to Matrix Chain \n\n # cl is length of substring\n for cl in range(2, n+1): \n for i in range(n-cl+1): \n j = i+cl-1\n count = count + 1\n \n if string[i] == string[j] and cl == 2: \n L[i][j] = 2\n elif string[i] == string[j]:\n count = count +1\n L[i][j] = L[i+1][j-1] + 2\n else: \n count = count + 1\n L[i][j] = max(L[i][j-1], L[i+1][j]); \n return L[0][n-1], count\n\n#=====================================================================================\n# A Space optimized Dynamic Programming \n# based Python3 program for LPS problem \n\n# Returns the length of the longest \n# palindromic subsequence in str \ndef lps_n2_n(s): \n \n n = len(s) \n \n # a[i] is going to store length \n # of longest palindromic subsequence \n # of substring s[0..i] \n a = [0] * n \n count = 0\n # Pick starting point \n for i in range(n-1, -1, -1): \n \n back_up = 0\n \n # Pick ending points and see if s[i] \n # increases length of longest common \n # subsequence ending with s[j]. \n for j in range(i, n): \n \n # similar to 2D array L[i][j] == 1 \n # i.e., handling substrings of length \n # one. \n count = count + 1\n \n if j == i: \n a[j] = 1 \n \n # Similar to 2D array L[i][j] = L[i+1][j-1]+2 \n # i.e., handling case when corner characters \n # are same. \n \n elif s[i] == s[j]:\n count = count + 1\n temp = a[j] \n a[j] = back_up + 2\n back_up = temp \n \n # similar to 2D array L[i][j] = max(L[i][j-1], \n # a[i+1][j]) \n else: \n\n count = count + 1\n back_up = a[j] \n \n a[j] = max(a[j - 1], a[j])\n \n \n return a[n - 1], count\n \n\n \n \n# This code is contributed by Ansu Kumari. \n\n" }, { "alpha_fraction": 0.541918158531189, "alphanum_fraction": 0.5586854219436646, "avg_line_length": 28.235294342041016, "blob_id": "5f1d2df7077eb1153c01815e11744eccb5cbb063", "content_id": "a5f3981279bcf13554ef3349b74552e787c96a2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 60, "num_lines": 51, "path": "/algorithms/random/rbst.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "# Python3 program to implement recursive \n# randomized algorithm. \n# To generate random number \n# between x and y ie.. [x, y] \n \nimport random \ndef getRandom(x,y): \n tmp=(x + random.randint(0,100000) % (y-x+1)) \n return tmp \n \n# A recursive randomized binary search function. \n# It returns location of x in \n# given array arr[l..r] is present, otherwise -1 \n \ndef randomizedBinarySearch(arr,l,r,x) : \n if r>=l: \n \n # Here we have defined middle as \n # random index between l and r ie.. [l, r] \n mid=getRandom(l,r) \n \n # If the element is present at the \n # middle itself \n if arr[mid] == x: \n return mid \n \n # If element is smaller than mid, then \n # it can only be present in left subarray \n if arr[mid]>x: \n return randomizedBinarySearch(arr, l, mid-1, x) \n \n # Else the element can only be present \n # in right subarray \n return randomizedBinarySearch(arr, mid+1,r, x) \n \n # We reach here when element is not present \n # in array \n return -1\n \n# Driver code \nif __name__=='__main__': \n arr = [2, 3, 4, 10, 40] \n n=len(arr) \n x=10\n result = randomizedBinarySearch(arr, 0, n-1, x) \n if result==-1: \n print('Element is not present in array') \n else: \n print('Element is present at index ', result) \n \n# This code is contributes by sahilshelangia " }, { "alpha_fraction": 0.3392255902290344, "alphanum_fraction": 0.38383838534355164, "avg_line_length": 16.939393997192383, "blob_id": "4629a8a413e3266fc8fe6c361ea429e436ab4e4c", "content_id": "e8ddc219b2cfc9e305e63cc951acdbec94b4b4f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 55, "num_lines": 66, "path": "/assignment2/coding_question.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\n\ndef subtraction(l):\n max =0\n x =l[0]\n\n list_max = []\n for j in range(0,len(l)):\n \n for i in range(1,len(l)):\n max += x - l[i] \n print(max)\n x = j\n \n list_max = [max]\n max =x \n min_sub = min(list_max)\n max_sub = max(list_max)\n return max_sub, min_sub\n \nprint(subtraction([5, 1, 7, 9])) \n \n\n# def multiplication(l):\n# max =0\n# x =l[0]\n\n# list_max = []\n# for j in range(0,len(l)):\n \n# for i in range(1,len(l)):\n# max *= x * l[i] \n# print(max)\n# x = j\n \n# list_max = [max]\n# max =x \n# min_mul = min(list_max)\n# max_mul = max(list_max)\n# return max_mul, min_mul\n \n\n# T(n) = 25T(n/5) +5n\n\n# log_5(25) = 2 > k = 1\n\n# we use case 1: \n# which give us:\n# O(n^2)\n\n# T(n) = 25T(n/5) +5n\n# = 25^2[T(n/5^2) + n] +5n\n# ... \n# = 25^k T(n/5^2) + n*k\n\n# = assume t(n/5^k) =T(0) \n\n# = n/5^k = 1\n\n# = n^log_5(n)\n\n# = T(n) = 5^2(log_5(k))*T(5^k/5^k) + log_5(n)* 5n\n\n# ...\n\n# T(n) = 5n*log_5(n)\n\n# **note that log_5 indicates log base 5\n\n\n" }, { "alpha_fraction": 0.5316184163093567, "alphanum_fraction": 0.5452840328216553, "avg_line_length": 22.588607788085938, "blob_id": "6e3bc0f0e1699646eb51cbb758b0ca7833d79083", "content_id": "d6573d57a0ae2599ef1ff7429f43b6c60b348263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3732, "license_type": "no_license", "max_line_length": 156, "num_lines": 158, "path": "/assignment3/main.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "import sys\nimport re\nimport codecs\nimport time\nimport subprocess\nimport binascii\nfrom subprocess import check_output\n\n\n\nfrom lps_dp import lps_n2_n, lps_n2_n2\n\n#function to read and clean data from given files\ndef read_and_clean(filepath):\n raw_txt = None\n with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:\n \n raw_txt = txt.read()\n \n raw_data_size = len(raw_txt)\n rraw = raw_txt\n raw_txt = raw_txt.strip()\n raw_txt = raw_txt.replace(' ','')\n raw_txt = raw_txt.replace('\\n','')\n raw_txt = raw_txt.upper()\n clean_txt= re.findall('([A-Z])', raw_txt)\n\n txt = ''\n clean_data_size = len(clean_txt)\n for i in range(0, clean_data_size):\n txt =txt+str(clean_txt[i])\n\n\n \n \n return txt, rraw, raw_data_size, clean_data_size\n\n \ndef tabulate(clean_txt, raw_txt,raw_data_size,clean_data_size,time_taken,comparisons):\n\n\n print('|----------|------------|----------|---------------|-------------|')\n print('| raw size | clean size | lcs size | comparisons | clock |')\n print('|----------|------------|----------|---------------|-------------|')\n\n print('| '+str(raw_data_size)+' | '+str(clean_data_size)+' | '+str(comparisons[0])+' | '+str(comparisons[1])+' |'+time_taken+' |')\n\n \n#test | driver\ndef main(argv):\n\n\n\n \n clean_txt, raw_txt, raw_data_size, clean_data_size = read_and_clean(argv[1])\n # print((clean_txt))\n print('\\n')\n print(raw_txt)\n print('\\n')\n print(clean_txt)\n print('\\n')\n print('Implementation of DP algorithm that uses O(n^2) time and O(n^2) space')\n\n #calling n^2 n^2 version\n #============================ java O(n2) O(n2)================\n\n\n\n start_time = time.time()\n #src: https://www.geeksforgeeks.org/print-longest-palindromic-subsequence/\n out = check_output(['java', 'LPS_N2_N2',clean_txt])\n time_taken = format(round((time.time() - start_time),9),'11f')\n\n \n out = out.decode('utf-8')\n out = out.strip('\\x00\\n')\n \n\n out = out.split(',')\n \n\n \n\n lcs_size = out[1]\n\n\n comparisons = [lcs_size,out[0]]\n\n\n tabulate(clean_txt,raw_txt,raw_data_size,clean_data_size,time_taken, comparisons)\n\n \n\n\n#================================Java (n2) n(n)===============================\n\n print('\\n')\n print('Implementation of DP algorithm that uses O(n^2) time and O(n) space')\n \n #src: https://www.geeksforgeeks.org/print-longest-palindromic-subsequence/\n start_time = time.time()\n out = check_output(['java', 'LPS_N2_N',clean_txt])\n time_taken = format(round((time.time() - start_time),9),'11f')\n\n \n out = out.decode('utf-8')\n out = out.strip('\\x00\\n')\n \n\n out = out.split(',')\n \n\n \n\n lcs_size = out[1]\n\n\n comparisons = [lcs_size,out[0]]\n\n\n tabulate(clean_txt,raw_txt,raw_data_size,clean_data_size,time_taken, comparisons)\n\n\n#=================================JAVA O(n2) O(n) String=================================\n\n #src: https://www.geeksforgeeks.org/print-longest-palindromic-subsequence/\n\n start_time = time.time()\n out = check_output(['java', 'LPS_N2_N_STR',clean_txt])\n time_taken = format(round((time.time() - start_time),9),'11f')\n\n \n out = out.decode('utf-8')\n out = out.strip('\\x00\\n')\n\n out = out.split(',')\n\n print('\\n')\n print('Implementation of DP algorithm that uses O(n^2) time and O(n) space')\n #calling n^2 n^2 version\n\n\n lcs_size = len(out[1])\n\n comparisons = [lcs_size,out[0]]\n tabulate(clean_txt,raw_txt,raw_data_size,clean_data_size,time_taken, comparisons)\n\n print('\\n'+out[1])\n\n print('\\n\\nFirst Name: ',argv[2])\n print('Last Name: ',argv[3])\n\n\n \n\nif __name__ == \"__main__\":\n\n main(sys.argv)\n\n " }, { "alpha_fraction": 0.5625859498977661, "alphanum_fraction": 0.5777166485786438, "avg_line_length": 24.10344886779785, "blob_id": "3709ee183922a54e52ee067cfd40424934683d91", "content_id": "b80dd3e1b564a2c0a223b02466df36d952c250af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 727, "license_type": "no_license", "max_line_length": 122, "num_lines": 29, "path": "/algorithms/approximation/square_root.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# sqrt.py - find square root\n\ndef sqtest(num, orig, ind):\n sq = 0\n while sq <= orig:\n num = num + ind\n sq = num * num\n num = num - ind\n return num\n\nn = float(0) # this is our working number. We start at zero and increment.\n\ninnum = int(input(\"For what number would you like to get the square root? \"))\ni = int(input(\"To how many decimal places? \"))\n\ninc = float(10)\ni += 1\nif (innum < 0):\n i = 0\nwhile i:\n inc = inc * 0.1\n n = sqtest (n, innum, inc)\n i -= 1\nif (innum >= 0):\n sq = n * n\n print( \"Approximate square root of \" + str(innum)+ \" is \" + str(n) + \"\\n(Actual square of this would be \"+str(sq)+\")\")\nelse:\n print (\"This would be an imaginary number\")" }, { "alpha_fraction": 0.5363214612007141, "alphanum_fraction": 0.5525502562522888, "avg_line_length": 24.254901885986328, "blob_id": "6d2102803577a3a6ebbf55822a85e5b50ed276a1", "content_id": "e7d31ed181712f6a35036da4f0a4d97385424d39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1294, "license_type": "no_license", "max_line_length": 89, "num_lines": 51, "path": "/assignment2/qsmm.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\n# Python program for implementation of Insertion Sort \n\n# Function to do insertion sort\n\ndef insertion_sort(arr,COUNT):\n \n # Traverse through 1 to len(arr) \n for i in range(1, len(arr)): \n \n key = arr[i] \n \n # Move elements of arr[0..i-1], that are \n # greater than key, to one position ahead \n # of their current position \n j = i-1\n while j >=0 and key < arr[j] :\n arr[j+1] = arr[j] \n j -= 1\n COUNT +=1\n arr[j+1] = key\n \n return arr, COUNT\n\ndef median_of_medians(A, i,COUNT):\n\n #divide A into sublists of len 5\n sublists = [A[j:j+5] for j in range(0, len(A), 5)]\n\n\n \n medians = [insertion_sort(sublist,COUNT)[0][len(sublist)//2] for sublist in sublists]\n \n \n if len(medians) <= 5:\n \n pivot = insertion_sort(medians,COUNT)[0][len(medians)//2]\n else:\n #the pivot is the median of the medians\n pivot = median_of_medians(medians, len(medians)//2,COUNT)\n\n #partitioning step\n low = [j for j in A if j < pivot]\n high = [j for j in A if j > pivot]\n\n k = len(low)\n if i < k:\n return median_of_medians(low,i,COUNT)\n elif i > k:\n return median_of_medians(high,i-k-1,COUNT)\n else: #pivot = k\n return pivot\n \n" }, { "alpha_fraction": 0.48060837388038635, "alphanum_fraction": 0.5087452530860901, "avg_line_length": 18.64179039001465, "blob_id": "709c240ae92088461ddee6b003b1eefe42caf247", "content_id": "31d9db84e8b1a3bdb32a785997a97064cbb353cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "no_license", "max_line_length": 66, "num_lines": 67, "path": "/assignment4/huffman.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "from heapq import heappush, heappop, heapify\nfrom collections import defaultdict\n\n\ndef encode(txt):\n count = 0\n symb2freq = defaultdict(int)\n for ch in txt:\n symb2freq[ch] += 1\n count+=1\n\n\n\n \"\"\"Huffman encode the given dict mapping symbols to weights\"\"\"\n\n heap =[]\n for sym, wt in symb2freq.items():\n # print(sym,wt)\n x = [sym,\"\"]\n y = [wt,x]\n # print(y)\n heap.append(y)\n\n \n\n\n heapify(heap)\n # print(heap)\n\n heapify(heap)\n while len(heap) > 1:\n lo = heappop(heap)\n hi = heappop(heap)\n for pair in lo[1:]:\n count+=1\n pair[1] = '0' + pair[1]\n for pair in hi[1:]:\n count+=1\n pair[1] = '1' + pair[1]\n heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])\n\n x = sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))\n \n return x,count\n \n\n \n \n# txt = \"BCAADDD&(&)(CCACACAC\"\n# symb2freq = defaultdict(int)\n# for ch in txt:\n# symb2freq[ch] += 1\n# # in Python 3.1+:\n# # symb2freq = collections.Counter(txt)\n# huff = encode(txt)\n# print (huff)\n\n# print (\"BCAD\")\n# for p in huff:\n# print (\"%s\\t%s\\t%s\" % (p[0], symb2freq[p[0]], p[1]))\n\n# print(\"decoded\")\n\n# for p in huff:\n\n# for i in range(0,symb2freq[p[0]]):\n# print(p[0])" }, { "alpha_fraction": 0.46539223194122314, "alphanum_fraction": 0.47099539637565613, "avg_line_length": 25.561403274536133, "blob_id": "d0c70a20296bc2e98172cc9ce7107721ef5a938b", "content_id": "f85d7593f465d773cedfa4f9064fd85a95f005a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3034, "license_type": "no_license", "max_line_length": 117, "num_lines": 114, "path": "/algorithms/string_matching/main.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "import sys\nimport re\n\nimport time\nimport subprocess\nimport binascii\nimport naive\nimport kmp\nimport boyer_moore\nimport rabin_karp\n\n\nimport pprintpp\nimport pprint\nimport codecs\n\ndef read_file(filepath):\n with codecs.open(filepath, 'r', encoding='utf-8', errors='ignore') as txt:\n\n raw_txt = txt.read()\n \n return raw_txt.upper()\n\ndef tabulate_d(tabulate, pat):\n\n for i in range(len(tabulate)):\n\n # print(pat[i])\n # print('comparisons: ', tabulate[i][pat[i]]['comparisons'])\n\n # print('clock: ', tabulate[i][pat[i]]['clock'])\n\n # print('indexes: ', tabulate[i][pat[i]]['indexes'])\n\n \n print('\\n------------------------------------------------------------------------------------------------\\n')\n\n print(pat[i],\"--->\",tabulate[i][pat[i]])\n print('\\n------------------------------------------------------------------------------------------------')\n\n\n\n \n#test | driver\ndef main(argv):\n\n\n txt = read_file(argv[1])\n pat = ['FREE', 'BRAVE-----', 'NATIONjkhjkg']\n###\n tabulate = []\n print('\\n\\n======================================= NAIVE SEARCH ===========================================')\n for i in range(len(pat)):\n\n start_time = time.time()\n result = naive.search(pat[i], txt) \n time_taken = format(round((time.time() - start_time),9))\n result = {pat[i]:{'comparisons':result[1],'clock':time_taken,'indexes':result[0]}}\n\n tabulate+=[result]\n tabulate_d(tabulate,pat)\n \n\n\n###\n tabulate = []\n print('\\n\\n======================================= MKP SEARCH =============================================')\n for i in range(len(pat)):\n\n start_time = time.time()\n result = kmp.KMPSearch(pat[i], txt) \n time_taken = format(round((time.time() - start_time),9))\n result = {pat[i]:{'comparisons':result[1],'clock':time_taken,'indexes':result[0]}}\n\n tabulate+=[result]\n tabulate_d(tabulate,pat)\n \n\n\n###\n tabulate = []\n print('\\n\\n==================================== BOYER MOORE SEARCH ========================================')\n for i in range(len(pat)):\n\n start_time = time.time()\n result = boyer_moore.search(pat[i], txt) \n time_taken = format(round((time.time() - start_time),9))\n result = {pat[i]:{'comparisons':result[1],'clock':time_taken,'indexes':result[0]}}\n\n tabulate+=[result]\n tabulate_d(tabulate,pat)\n\n###\n tabulate = []\n print('\\n\\n================================= RABIN-KARP SEARCH =============================================')\n for i in range(len(pat)):\n\n start_time = time.time()\n result = rabin_karp.search(pat[i], txt,101) \n time_taken = format(round((time.time() - start_time),9))\n result = {pat[i]:{'comparisons':result[1],'clock':time_taken,'indexes':result[0]}}\n\n tabulate+=[result]\n tabulate_d(tabulate,pat)\n\n\n\n print('\\n\\nFirst Name: ',\"HERNAN\")\n print('Last Name: ',\"PESANTEZ\")\n \n\nif __name__ == \"__main__\":\n\n main(sys.argv)\n\n \n" }, { "alpha_fraction": 0.3841877579689026, "alphanum_fraction": 0.4366893172264099, "avg_line_length": 21.81690216064453, "blob_id": "9d54fc14891a048bb6c3011463619ae4445192ee", "content_id": "15e27374eef20735b6a47050bf0e205ec9bba3c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1619, "license_type": "no_license", "max_line_length": 56, "num_lines": 71, "path": "/examples/trees.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "from binarytree import tree, bst, heap, Node, build\n# Generate a random binary tree and return its root node\nmy_tree = tree(height=3, is_perfect=False)\n# Generate a random BST and return its root node\n\nx =build ([2,4,5,6,7])\nprint(dir(bst))\nmy_bst = bst(2)\n# Generate a random max heap and return its root node\nmy_heap = heap(height=3, is_max=True, is_perfect=False)\n\n# Pretty-print the trees in stdout\nprint(my_tree)\n#\n# _______1_____\n# / \\\n# 4__ ___3\n# / \\ / \\\n# 0 9 13 14\n# / \\ \\\n# 7 10 2\n#\nprint(my_bst)\n#\n# ______7_______\n# / \\\n# __3__ ___11___\n# / \\ / \\\n# 1 5 9 _13\n# / \\ / \\ / \\ / \\\n# 0 2 4 6 8 10 12 14\n#\nprint(my_heap)\n#\n# _____14__\n# / \\\n# ____13__ 9\n# / \\ / \\\n# 12 7 3 8\n# / \\ /\n# 0 10 6\n#\n\nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.left.right = Node(5)\n\nprint(root)\n#\n# __1\n# / \\\n# 2 3\n# / \\\n# 4 5\n#\nroot.inorder\nprint('inorder ',root.inorder)\n\nprint('preorder ',root.preorder)\n# [Node(1), Node(2), Node(4), Node(5), Node(3)]\n\nprint('postorder ',root.postorder)\n# [Node(4), Node(5), Node(2), Node(3), Node(1)]\n\nprint('levelorder ',root.levelorder)\n# [Node(1), Node(2), Node(3), Node(4), Node(5)]\n\nlist(root) # Equivalent to root.levelorder\n# [Node(1), Node(2), Node(3), Node(4), Node(5)]" }, { "alpha_fraction": 0.5040518641471863, "alphanum_fraction": 0.5170178413391113, "avg_line_length": 23.215686798095703, "blob_id": "d7e20dec9451ccfdbb56ca467ee1118a8423db57", "content_id": "d6314453546cab2ee1374087fbc44f0be3a59bd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 76, "num_lines": 51, "path": "/algorithms/parallel/fibonacci.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n \nimport time\nimport multiprocessing\n \ndef fib(n):\n if n < 0:\n raise ValueError\n if n < 2:\n return n\n return fib(n-1)+fib(n-2)\n \ndef fibonacci(in_queue, out_queue):\n while True:\n n = in_queue.get()\n if n == None: \n break\n start = time.time()\n res = fib(n)\n end = time.time()\n out_queue.put((n, res, end-start))\n out_queue.put((None, None, None))\n \ndef main():\n start = time.time()\n in_queue = multiprocessing.Queue()\n out_queue = multiprocessing.Queue()\n \n process_num = multiprocessing.cpu_count()\n for _ in range(process_num):\n multiprocessing.Process(target=fibonacci, \n args=(in_queue, out_queue)).start()\n \n for i in range(30, 37):\n in_queue.put(i)\n for _ in range(process_num):\n in_queue.put(None)\n \n while True:\n n, res, spend_time = out_queue.get()\n if n == None: \n process_num -= 1\n if process_num == 0: break\n else:\n print (\"fib(%3d) = %7d (took %0.3fs)\" % ( n, res, spend_time))\n \n end = time.time()\n print (\"Total time: %0.3fs\" % (end - start))\n \nif __name__ == \"__main__\":\n main()" }, { "alpha_fraction": 0.5139372944831848, "alphanum_fraction": 0.5245644450187683, "avg_line_length": 25.279815673828125, "blob_id": "217fdbd54cfa6d300093960932cfc705d026f32e", "content_id": "5414f1939a14cf2efe4d909d894ac1716d013c2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5740, "license_type": "no_license", "max_line_length": 96, "num_lines": 218, "path": "/assignment2/qsrp.py", "repo_name": "hernanpesantez/algorithms", "src_encoding": "UTF-8", "text": "\nimport random \nimport time\n#=========================================================\n#Implementation of the Median-finding Algorithm\n#src: https://brilliant.org/wiki/median-finding-algorithm/\n#modified by: Hernan \n\ncount_x = 0\ndef count():\n global count_x\n count_x+=1\n return count_x\n\ndef count_zero():\n global count_x\n count_x =0\n return count_x\n\ndef insertion_sort(arr):\n \n # Traverse through 1 to len(arr) \n for i in range(1, len(arr)): \n \n key = arr[i] \n \n # Move elements of arr[0..i-1], that are \n # greater than key, to one position ahead \n # of their current position \n j = i-1\n while j >=0 and key < arr[j]:\n arr[j+1] = arr[j] \n j -= 1\n count()\n \n arr[j+1] = key\n \n return arr\n\ndef median_of_medians(A, i):\n \n \n \n #divide A into sublists of len 5\n sublists = [A[j:j+5] for j in range(0, len(A), 5)]\n\n count()\n\n medians = [insertion_sort(sublist)[len(sublist)//2] for sublist in sublists]\n \n # print(medians)\n \n \n if len(medians) <= 5:\n \n pivot = insertion_sort(medians)[len(medians)//2]\n else:\n #the pivot is the median of the medians\n pivot = median_of_medians(medians, len(medians)//2)\n\n #partitioning step\n low = [j for j in A if j < pivot]\n high = [j for j in A if j > pivot]\n\n k = len(low)\n if i < k:\n # count()\n return median_of_medians(low,i)\n \n elif i > k:\n # count()\n return median_of_medians(high,i-k-1)\n else: #pivot = k\n return pivot\n \n\n#==================================================================\n#src: https://www.geeksforgeeks.org/quicksort-using-random-pivoting/\n# This code is contributed by soumyasaurav\n# Python implementation QuickSort using \n# Lomuto's partition Scheme\n# modified by: Hernan \n \n\n\nimport random \nimport time\n\n\n''' \nThe function which implements QuickSort. \narr :- array to be sorted. \nstart :- starting index of the array. \nstop :- ending index of the array. \n'''\n\ncount_t = 0\ndef quicksort(arr, start , stop):\n count_i = 0\n if(start < stop): \n \n # pivotindex is the index where \n # the pivot lies in the array \n pivotindex, count_i = partitionrand(arr, start, stop)\n \n \n # At this stage the array is partially sorted \n # around the pivot. Separately sorting the \n # left half of the array and the right half of the array. \n count_l = quicksort(arr , start , pivotindex - 1) \n count_r = quicksort(arr, pivotindex + 1, stop) \n count_i += count_t + count_l + count_r\n return count_i\n\n # This function generates random pivot, swaps the first \n # element with the pivot and calls the partition fucntion. \ndef partitionrand(arr , start, stop): \n\n # Generating a random number between the \n # starting index of the array and the \n # ending index of the array. \n randpivot = random.randrange(start, stop) \n\n # Swapping the starting element of the array and the pivot \n arr[start], arr[randpivot] = arr[randpivot], arr[start] \n \n return partition(arr, start, stop)\n\n''' \nThis function takes the first element as pivot, \nplaces the pivot element at the correct position \nin the sorted array. All the elements are re-arranged \naccording to the pivot, the elements smaller than the \npivot is places on the left and the elements \ngreater than the pivot is placed to the right of pivot. \n'''\ndef partition(arr,start,stop): \n pivot = start # pivot \n i = start + 1 # a variable to memorize where the \n # partition in the array starts from. \n count = 0\n for j in range(start + 1, stop + 1): \n \n # if the current element is smaller or equal to pivot, \n # shift it to the left side of the partition. \n if arr[j] <= arr[pivot]:\n count +=1\n arr[i] , arr[j] = arr[j] , arr[i] \n i = i + 1\n arr[pivot] , arr[i - 1] = arr[i - 1] , arr[pivot] \n pivot = i - 1\n return (pivot), count\n\n\n\n\n\n#funtion to create and ransomize list\ndef make_random_list(size):\n #create lsit \n lst = list(range(size))\n #shuffle list\n random.shuffle(lst)\n return lst, len(lst)\n\n\n# Driver Code\n\ndef main():\n global count_x\n\n\n print ('\\nQSRP...')\n\n\n\n print('|--------|----------|-----------|---------------|----------------|')\n print('| trial | size | median | comparisons | time |')\n for i in range(0,10):\n\n lst, n = make_random_list(10000)\n\n start_time = time.time()\n comparisons = quicksort(lst, 0, n - 1)\n # comparisons = median_of_medians(lst,n) \n time_taken = format(round((time.time() - start_time),9),'11f')\n\n\n median = lst[n//2]\n print('|--------|----------|-----------|---------------|----------------|')\n print('| ',i,' | ',n,' | ',median,' | ',comparisons,' |',time_taken,' |')\n \n \n \n\n \n print ('\\nQSMM...') #should be 5\n\n print('|--------|----------|-----------|---------------|----------------|')\n print('| trial | size | median | comparisons | time |')\n \n for i in range(0,10):\n \n lst, n = make_random_list(20001)\n start_time = time.time()\n \n median = median_of_medians(lst,n//2)\n \n time_taken = format(round((time.time() - start_time),9),'11f')\n \n print('|--------|----------|-----------|---------------|----------------|')\n print('| ',i,' | ',n,' | ',median,' | ',count(),' |',time_taken,' |')\n \n count_zero()\n\n\nif __name__ == '__main__':\n\n main()\n \n\n" } ]
20
maticalderini/NLP_twitter
https://github.com/maticalderini/NLP_twitter
7e3e44e382a92c18047a541ac84816967f7b04e0
80b4b5cc3057d923240cc0bb3692ff3493cd196e
6a3c235b4d80a409b5c6736c8b493c1775f20b91
refs/heads/master
2020-05-23T19:36:48.147126
2019-05-21T01:45:57
2019-05-21T01:45:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7782427072525024, "alphanum_fraction": 0.7949790954589844, "avg_line_length": 28.875, "blob_id": "fad87788e99c731533c87a7e1980f2c1685077cf", "content_id": "973789064b1e469874bca892c62a030a3af8db81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 239, "license_type": "no_license", "max_line_length": 76, "num_lines": 8, "path": "/README.md", "repo_name": "maticalderini/NLP_twitter", "src_encoding": "UTF-8", "text": "# NLP_twitter\n\nTwitter user classifier. Allows to:\n\n1. Define the twitter users from which we download a chosen number of tweets\n2. Clean the tweet database\n3. Build a classifier model trained to distinguish tweets across users\n4. Testing\n" }, { "alpha_fraction": 0.6490066051483154, "alphanum_fraction": 0.6490066051483154, "avg_line_length": 40.94444274902344, "blob_id": "cb29c952901b08339f263d6ac4847cbdce45ba6b", "content_id": "c2c8e2cab450c9753b50def9f706dad5f02b5144", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 142, "num_lines": 18, "path": "/MyStreamer.py", "repo_name": "maticalderini/NLP_twitter", "src_encoding": "UTF-8", "text": "import tweepy\nimport json\n\nclass Streamer():\n def __init__(self, credsFileName):\n \"\"\"Authenticates and access the API from json stored credentials\"\"\"\n # Get credentials\n with open(credsFileName +'.json', 'r') as file:\n creds = json.load(file)\n\n # Connect to API\n auth = tweepy.OAuthHandler(creds['CONSUMER_KEY'], creds['CONSUMER_SECRET'])\n auth.set_access_token(creds['ACCESS_TOKEN'], creds['ACCESS_TOKEN_SECRET'])\n self.api = tweepy.API(auth)\n\n def getTweets(self, screen_name, N):\n \"\"\"Gets the latest N tweets from user 'screen_name'\"\"\"\n return [status.full_text for status in tweepy.Cursor(self.api.user_timeline, screen_name=screen_name, tweet_mode=\"extended\").items(N)]\n" } ]
2
719034075/YiJiuBlog
https://github.com/719034075/YiJiuBlog
fe4430f728494b2f5c9c623e702da2edb17672f3
86e913675f30d3f94c3d08896e60fffccabf61c3
46d88352c06adc5a3b5a3fb94bc32e05bf828dd2
refs/heads/master
2020-03-24T06:05:37.846747
2018-10-22T11:25:57
2018-10-22T11:25:57
127,123,790
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6654991507530212, "alphanum_fraction": 0.6795096397399902, "avg_line_length": 26.190475463867188, "blob_id": "ee67ab8f17a0351485b416b1790213d41db4e878", "content_id": "ed4f6b22ed5d9c98a0fd9db0bf60297634395eb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/backend/config/prod_config.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from .base_config import BaseConfig\n\n\nclass ProdConfig(BaseConfig):\n \"\"\"Production config class.\"\"\"\n\n # Close the DEBUG\n DEBUG = False\n\n # MySQL connection\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:center135@localhost:3306/eggblog'\n SQLALCHEMY_NATIVE_UNICODE = 'utf8'\n\n # Safe settings\n JWT_SECRET_KEY = 'How are you?I am fine, thank you!'\n CSRF_ENABLED = True\n JWT_HEADER_NAME = 'X-TOKEN'\n JWT_HEADER_TYPE = 'Knock'\n JWT_BLACKLIST_ENABLED = True\n # JWT_ACCESS_TOKEN_EXPIRES = False\n" }, { "alpha_fraction": 0.6171079277992249, "alphanum_fraction": 0.6334012150764465, "avg_line_length": 27.882352828979492, "blob_id": "e01bd38bbcf76c2e625651c84b2824849f159ec7", "content_id": "5523cda61ad5e12930519ebe2e8a3ee549da982a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 491, "license_type": "no_license", "max_line_length": 73, "num_lines": 17, "path": "/backend/utils/json_serialize.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "import time\n\n\ndef obj_json_serialize(obj):\n if 'create_time' in obj.__dict__.keys():\n obj.create_time = time.mktime(obj.create_time.timetuple()) * 1000\n if 'update_time' in obj.__dict__.keys():\n obj.update_time = time.mktime(obj.update_time.timetuple()) * 1000\n obj.__dict__.pop('_sa_instance_state')\n return obj.__dict__\n\n\ndef list_json_serialize(list):\n result = []\n for element in list:\n result.append(obj_json_serialize(element))\n return result\n" }, { "alpha_fraction": 0.5299145579338074, "alphanum_fraction": 0.5790598392486572, "avg_line_length": 27.653060913085938, "blob_id": "7713a31db8fcb259733c8b14ad0a1dd7d7c59a65", "content_id": "ef134f6b56d0fd1978f08c28f3151a5f5f81cde3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1404, "license_type": "no_license", "max_line_length": 149, "num_lines": 49, "path": "/yijiublog.sql", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "/*\nNavicat MySQL Data Transfer\n\nSource Server : local\nSource Server Version : 50720\nSource Host : localhost:3306\nSource Database : yijiublog\n\nTarget Server Type : MYSQL\nTarget Server Version : 50720\nFile Encoding : 65001\n\nDate: 2018-08-02 23:42:58\n*/\n\nSET FOREIGN_KEY_CHECKS=0;\n\n-- ----------------------------\n-- Table structure for alembic_version\n-- ----------------------------\nDROP TABLE IF EXISTS `alembic_version`;\nCREATE TABLE `alembic_version` (\n `version_num` varchar(32) NOT NULL,\n PRIMARY KEY (`version_num`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n-- ----------------------------\n-- Records of alembic_version\n-- ----------------------------\nINSERT INTO `alembic_version` VALUES ('5f821ee6761e');\n\n-- ----------------------------\n-- Table structure for user\n-- ----------------------------\nDROP TABLE IF EXISTS `user`;\nCREATE TABLE `user` (\n `id` varchar(45) NOT NULL,\n `username` varchar(255) DEFAULT NULL,\n `password` varchar(255) DEFAULT NULL,\n `avatar` varchar(255) DEFAULT NULL,\n `roles` varchar(80) DEFAULT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `username` (`username`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n-- ----------------------------\n-- Records of user\n-- ----------------------------\nINSERT INTO `user` VALUES ('92cd2240-5105-11e8-8af1-e4f89ca885a8', 'temp-admin', '$2b$12$KClH83F..7.owDFPIFtd9.mH26lEQCnA/pSajDVT/vH0BBvIDoZLm', null, 'superuser');\n" }, { "alpha_fraction": 0.6078166961669922, "alphanum_fraction": 0.6078166961669922, "avg_line_length": 15.1304349899292, "blob_id": "efa09b0ee28c4ff1783e0a2a424dc20bba09bd0b", "content_id": "333b105c3cb78ea05c040a79fcebc31e9b7c6f8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 742, "license_type": "permissive", "max_line_length": 37, "num_lines": 46, "path": "/frontend/src/api/catalog.js", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "import request from '@/utils/request'\n\nexport function fetchList(data) {\n return request({\n url: '/catalog/list/all',\n method: 'post',\n data\n })\n}\n\nexport function fetchCatalogs() {\n return request({\n url: '/catalog/list/all',\n method: 'get',\n })\n}\n\nexport function fetchCatalog(id) {\n return request({\n url: `/catalog/detail/${id}`,\n method: 'get',\n })\n}\n\nexport function createCatalog(data) {\n return request({\n url: '/catalog/create',\n method: 'post',\n data\n })\n}\n\nexport function updateCatalog(data) {\n return request({\n url: '/catalog/update',\n method: 'post',\n data\n })\n}\n\nexport function deleteCatalog(id){\n return request({\n url: `/catalog/delete/${id}`,\n method: 'get',\n })\n}\n" }, { "alpha_fraction": 0.6253197193145752, "alphanum_fraction": 0.644501268863678, "avg_line_length": 29.076923370361328, "blob_id": "e5726bc0ded873c74585f8e76ec27e496d29140c", "content_id": "799b0409c7be8c5fd5c5fb208ca965b3270f8357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/backend/apps/user/models.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from uuid import uuid1\n\nfrom extensions import db, bcrypt\n\n\nclass User(db.Model):\n id = db.Column(db.String(45), primary_key=True)\n username = db.Column(db.String(255), unique=True)\n password = db.Column(db.String(255))\n avatar = db.Column(db.String(255))\n roles = db.Column(db.String(80))\n\n def __init__(self, username, password, roles):\n self.id = str(uuid1()),\n self.username = username,\n self.password = self.set_password(password),\n self.roles = roles\n\n def __repr__(self):\n return \"<Model User `{}`>\".format(self.username)\n\n def set_password(self, password):\n return bcrypt.generate_password_hash(password)\n\n def check_password(self, password):\n return bcrypt.check_password_hash(self.password, password)\n" }, { "alpha_fraction": 0.6407643556594849, "alphanum_fraction": 0.6547770500183105, "avg_line_length": 27.035715103149414, "blob_id": "4f0a07257047bfffd84b8b71a78e2c73f59835b9", "content_id": "b112dd87784696e40e5244bf58236f688dea1529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 785, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/backend/config/dev_config.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from .base_config import BaseConfig\n\n\nclass DevConfig(BaseConfig):\n \"\"\"Development config class.\"\"\"\n\n # Open the DEBUG\n DEBUG = True\n\n # MySQL connection\n SQLALCHEMY_TRACK_MODIFICATIONS = True\n SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:center135@localhost:3306/YiJiuBlog'\n SQLALCHEMY_NATIVE_UNICODE = 'utf8'\n\n # Safe settings\n JWT_SECRET_KEY = 'How are you?I am fine, thank you!'\n CSRF_ENABLED = True\n JWT_HEADER_NAME = 'X-TOKEN'\n JWT_HEADER_TYPE = 'Knock'\n JWT_BLACKLIST_ENABLED = True\n # JWT_ACCESS_TOKEN_EXPIRES = False\n\n # Swagger settings\n SWAGGER = {\n \"title\": \"YiJiuBlog backend API's Documents\",\n \"description\": \"This is an API's Documents about YiJiuBlog based on Swagger\",\n \"version\": \"0.0.2\",\n }\n" }, { "alpha_fraction": 0.777265727519989, "alphanum_fraction": 0.777265727519989, "avg_line_length": 22.25, "blob_id": "7cb0bee4b9e1d9a3cbc5897f9d1ce2a02fe24076", "content_id": "c628dbf94232d8740f670792ae638fc7fc179f7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 42, "num_lines": 28, "path": "/backend/extensions.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from flask_sqlalchemy import SQLAlchemy\nfrom flask_bcrypt import Bcrypt\nfrom flask_cors import CORS\nfrom flask_restful import Api\nfrom flask_httpauth import HTTPBasicAuth\nfrom flask_jwt_extended import JWTManager\n# from flasgger import Swagger\n\n# Create the Flask-SQLAlchemy's instance\ndb = SQLAlchemy()\n\n# Create the Flask-Bcrypt's instance\nbcrypt = Bcrypt()\n\n# Create the Flask-CORS's instance\ncors = CORS()\n\n# Create the Flask-Restful's instance\nrestful_api = Api()\n\n# Create the Flask-Httpauth's instance\nauth = HTTPBasicAuth()\n\n# Create the Flask-JWT-Extended's instance\njwt = JWTManager()\n\n# Create the flasgger's instance\n# swagger = Swagger()\n" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 8, "blob_id": "ac9259663e5bf2ceb0f5ac922494d398781a1cb4", "content_id": "1c7db75c565fc85810ca9c24afeecac5b696796b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 158, "license_type": "no_license", "max_line_length": 30, "num_lines": 14, "path": "/README.md", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "# YiJiuBlog\nYiJiuBlog used Vue.js on Flask\n\n## 2018-09-04\n\nversion:1.0\n\n[后端]\n1. 权限管理\n2. Catalog 和 Article\n\n[前端]\n1. 门户端\n2. 管理端\n" }, { "alpha_fraction": 0.7180301547050476, "alphanum_fraction": 0.7180301547050476, "avg_line_length": 20.70689582824707, "blob_id": "2e8dde13ea155c774be933dcc9519eb07dfa991e", "content_id": "60d0c38a3d0466d9596a2a9b81fa17885b6cf198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1325, "license_type": "no_license", "max_line_length": 86, "num_lines": 58, "path": "/backend/manage.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "# import Flask Script object\n\nfrom flask_script import Manager, Server\nfrom flask_migrate import Migrate, MigrateCommand\n\nfrom run import app\nfrom extensions import db\n\nfrom apps.user.models import User\nfrom apps.catalog.models import Catalog\n\n# init manager object via app object\nmanager = Manager(app)\n\n# init migrate object via app and db object\nmigrate = Migrate(app, db)\n\n# Create a new commands: server\n# This command will be run the Flask development_env server\nmanager.add_command('server', Server())\nmanager.add_command('db', MigrateCommand)\n\n\n# 更新数据迁移\[email protected]\ndef deploy():\n \"\"\"Run deployment tasks.\"\"\"\n # migrate database to latest revision\n from flask_migrate import migrate, upgrade\n migrate()\n upgrade()\n\n\n# 删除数据库里所有的表\[email protected]\ndef dropall():\n db.drop_all()\n print(\"all tables dropped! remember to delete directory: migrations\")\n\n\n# 创建admin用户,赋予superuser角色\[email protected]\ndef initrole():\n db.session.add(User(username=\"ZeuChan\", password=\"Knockthedoor\", roles='superuser'))\n db.session.commit()\n print(\"Roles added!\")\n\n\n# 初始化数据库\[email protected]\ndef initdb():\n db.session.add(Catalog(name='默认'))\n db.session.commit()\n print(\"Catalog added!\")\n\n\nif __name__ == '__main__':\n manager.run()\n" }, { "alpha_fraction": 0.7818182110786438, "alphanum_fraction": 0.7818182110786438, "avg_line_length": 21, "blob_id": "61f6e84b4c3e518c49508a4cad628890f14ca4bd", "content_id": "fa44750d81080722be5dc860a81147f9a6a74abf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 110, "license_type": "no_license", "max_line_length": 52, "num_lines": 5, "path": "/backend/test/test.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from apps.catalog.models import Catalog\n\ncatalog = Catalog.query.order_by(Catalog.name).all()\n\nprint(catalog)\n" }, { "alpha_fraction": 0.5319979190826416, "alphanum_fraction": 0.5331685543060303, "avg_line_length": 29.87550163269043, "blob_id": "29a5529b866d724c8f466b6a40c5ed0ea59d3e28", "content_id": "7edcae98dce6734f6ff896d1e2a05e5c3f3938a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7942, "license_type": "no_license", "max_line_length": 109, "num_lines": 249, "path": "/backend/apps/user/controllers.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from flask import Blueprint\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_jwt_extended import jwt_required, create_access_token, get_jwt_identity, jwt_optional, get_raw_jwt\nfrom utils.response_bean import ResponseBean\nfrom utils.protect_restful import requires_roles\nfrom extensions import jwt\nfrom .models import User\n\nuser = Blueprint('user', __name__,\n url_prefix='/user')\napi = Api(user)\n\nblacklist = set()\n\n\[email protected]_in_blacklist_loader\ndef check_if_token_in_blacklist(decrypted_token):\n jti = decrypted_token['jti']\n return jti in blacklist\n\n\n# class SignUp(Resource):\n# def __init__(self):\n# self.parser = reqparse.RequestParser()\n# self.parser.add_argument('username', type=str, location='json')\n# self.parser.add_argument('password', type=str, location='json')\n#\n# def post(self):\n# args = self.parser.parse_args()\n# username = args['username']\n# password = args['password']\n#\n# if not username:\n# response = ResponseBean().get_fail_instance()\n# response.message = '用户名为空'\n# return response.__dict__\n#\n# if not password:\n# response = ResponseBean().get_fail_instance()\n# response.message = '密码为空'\n# return response.__dict__\n#\n# new_user = User(username=username, password=password)\n# add_user(new_user)\n#\n# response = ResponseBean().get_success_instance()\n# response.message = '注册成功'\n# return response.__dict__\n\n\nclass Login(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('username', type=str, location='json', required=True)\n self.parser.add_argument('password', type=str, location='json', required=True)\n\n def post(self):\n \"\"\"\n 登录\n 用户登录接口\n ---\n tags:\n - user\n parameters:\n - in: body\n name: body\n schema:\n type: object\n required:\n - username\n - password\n properties:\n username:\n type: string\n default: temp-admin\n password:\n type: string\n default: temp-pwd\n responses:\n 200:\n description: an access_token\n schema:\n properties:\n success:\n type: boolean\n description: return a successful response or not\n default: True\n message:\n type: string\n description: return the response message\n default: 登录成功\n data:\n type: object\n description: return the response data\n default:\n token: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1MjU1NzUyNDEsIm5iZiI6MTUyNTU3NTI0MSwianRpIjoiZjlhYjg2YTktZmU1Ny00ZDQyLWEzMmUtOWRhNGU5NjA4YWJmIiwiZXhwIjoxNTI1NTc2MTQxLCJpZGVudGl0eSI6InRlbXAtYWRtaW4iLCJmcmVzaCI6ZmFsc2UsInR5cGUiOiJhY2Nlc3MifQ.9s9NbJsi21Kv5YbQaFuUXEqnFHsXd8FmAf2Q2wh_k6I\n\n \"\"\"\n args = self.parser.parse_args()\n username = args['username']\n password = args['password']\n\n if not username:\n response = ResponseBean().get_fail_instance()\n response.message = '用户名为空'\n return response.__dict__\n\n if not password:\n response = ResponseBean().get_fail_instance()\n response.message = '密码为空'\n return response.__dict__\n\n login_user = User.query.filter_by(username=username).first()\n\n if login_user is None or not login_user.check_password(password=password):\n response = ResponseBean().get_fail_instance()\n response.message = '用户名或密码错误。'\n return response.__dict__\n\n access_token = create_access_token(identity=username)\n response = ResponseBean().get_success_instance()\n response.message = '登录成功'\n response.data['token'] = access_token\n return response.__dict__\n\n\nclass Info(Resource):\n @jwt_required\n def get(self):\n \"\"\"\n 用户信息\n 登录之后通过token获取用户基本信息接口\n ---\n tags:\n - user\n parameters:\n - in: header\n name: X-TOKEN\n type: string\n required: true\n description: Knock <access_token>\n responses:\n 200:\n description: 包括roles在内的用户基本信息\n schema:\n properties:\n success:\n type: boolean\n description: return a successful response or not\n default: True\n message:\n type: string\n description: return the response message\n default: 获取用户信息成功\n data:\n type: object\n description: return the response data\n default:\n roles: superuser\n name: temp-admin\n avatar: nope\n \"\"\"\n jwt_user = get_jwt_identity()\n if jwt_user:\n current_user = User.query.filter_by(username=jwt_user).first()\n response = ResponseBean().get_success_instance()\n response.message = '获取用户信息成功'\n response.data['roles'] = [current_user.roles]\n response.data['name'] = current_user.username\n response.data['avatar'] = current_user.avatar\n return response.__dict__\n else:\n response = ResponseBean().get_fail_instance()\n response.message = '非法用戶'\n return response.__dict__\n\n\nclass Logout(Resource):\n @jwt_required\n def post(self):\n \"\"\"\n 登出\n 用户登出接口\n ---\n tags:\n - user\n parameters:\n - in: header\n name: X-TOKEN\n type: string\n required: true\n description: Knock <access_token>\n responses:\n 200:\n description: 无\n schema:\n properties:\n success:\n type: boolean\n description: return a successful response or not\n default: True\n message:\n type: string\n description: return the response message\n default: 登出成功\n \"\"\"\n jti = get_raw_jwt()['jti']\n blacklist.add(jti)\n response = ResponseBean().get_success_instance()\n response.message = '登出成功'\n return response.__dict__\n\n\n# Protect a view with jwt_required, which requires a valid access token\n# in the request to access.\nclass Protect(Resource):\n @jwt_required\n @requires_roles('superuser')\n def get(self):\n current_user = get_jwt_identity()\n response = ResponseBean().get_success_instance()\n response.message = '登录用户'\n response.data['logged_in_as'] = current_user\n return response.__dict__\n\n\nclass PartiallyProtected(Resource):\n @jwt_optional\n def get(self):\n # If no JWT is sent in with the request, get_jwt_identity()\n # will return None\n current_user = get_jwt_identity()\n if current_user:\n response = ResponseBean().get_success_instance()\n response.message = '登录用户'\n response.data['logged_in_as'] = current_user\n return response.__dict__\n else:\n response = ResponseBean().get_success_instance()\n response.message = '匿名用户'\n response.data['logged_in_as'] = 'anonymous user'\n return response.__dict__\n\n\napi.add_resource(Login, '/login')\napi.add_resource(Info, '/info')\napi.add_resource(Logout, '/logout')\napi.add_resource(Protect, '/protect')\napi.add_resource(PartiallyProtected, '/partially-protected')\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 29.85714340209961, "blob_id": "01cc1739e105aea6e10b666ce2df57fe9fcfbd6b", "content_id": "1aa7a0bae8fb0319aca87b6a41e0c7f400560a0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 656, "license_type": "no_license", "max_line_length": 74, "num_lines": 21, "path": "/backend/utils/protect_restful.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from functools import wraps\nfrom flask_jwt_extended import get_jwt_identity\nfrom .response_bean import ResponseBean\nfrom apps.user.models import User\n\n\ndef requires_roles(*roles):\n def wrapper(f):\n @wraps(f)\n def wrapped(*args, **kwargs):\n jwt_user = get_jwt_identity()\n current_user = User.query.filter_by(username=jwt_user).first()\n if current_user.roles not in roles:\n response = ResponseBean().get_fail_instance()\n response.message = '非法用戶'\n return response.__dict__\n return f(*args, **kwargs)\n\n return wrapped\n\n return wrapper\n" }, { "alpha_fraction": 0.6389826536178589, "alphanum_fraction": 0.6389826536178589, "avg_line_length": 30.735713958740234, "blob_id": "8ad37e859701fa0048fc94afa4dc2f571aea8e94", "content_id": "549a39c1c5f80f046a579a5f5045039b827dbb4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4527, "license_type": "no_license", "max_line_length": 87, "num_lines": 140, "path": "/backend/apps/catalog/controllers.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from flask import Blueprint\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_jwt_extended import jwt_required\n\nfrom apps.article.models import Article\nfrom utils.json_serialize import list_json_serialize\nfrom utils.response_bean import ResponseBean\nfrom utils.protect_restful import requires_roles\nfrom extensions import db\nfrom .models import Catalog\n\ncatalog = Blueprint('catalog', __name__,\n url_prefix='/catalog')\n\napi = Api(catalog)\n\n\nclass Create(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('name', type=str, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n name = args['name']\n\n if name == \"默认\":\n response = ResponseBean().get_fail_instance()\n response.message = '默认Catalog不可新建'\n return response.__dict__\n new_catalog = Catalog(name=name)\n db.session.add(new_catalog)\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '新建Catalog成功'\n return response.__dict__\n\n\nclass Delete(Resource):\n\n @jwt_required\n @requires_roles('superuser')\n def get(self, id):\n delete_catalog = Catalog.query.get(id)\n default_catalog = Catalog.query.filter_by(name=\"默认\").first()\n if delete_catalog.name == \"默认\":\n response = ResponseBean().get_fail_instance()\n response.message = '默认Catalog不可删除'\n return response.__dict__\n articles = Article.query.filter_by(catalog=id)\n\n for article in articles:\n article.catalog = default_catalog.id\n default_catalog.amount = default_catalog.amount + delete_catalog.amount\n db.session.delete(delete_catalog)\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '删除Catalog成功'\n return response.__dict__\n\n\nclass Update(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('id', type=str, location='json', required=True)\n self.parser.add_argument('name', type=str, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n id = args['id']\n name = args['name']\n\n edit_catalog = Catalog.query.filter_by(id=id).first()\n edit_catalog.name = name\n\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '编辑Catalog成功'\n return response.__dict__\n\n\nclass Detail(Resource):\n @jwt_required\n @requires_roles('superuser')\n def get(self, id):\n find_catalog = Catalog.query.get(id)\n\n response = ResponseBean().get_success_instance()\n response.message = '查询Catalog成功'\n response.data['id'] = find_catalog.id\n response.data['name'] = find_catalog.name\n response.data['amount'] = find_catalog.amount\n\n return response.__dict__\n\n\nclass ListAll(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', type=int, location='json', required=True)\n self.parser.add_argument('page_size', type=int, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n page = args['page']\n page_size = args['page_size']\n\n catalogs = Catalog.query.order_by(Catalog.name).paginate(page, page_size)\n\n response = ResponseBean().get_success_instance()\n response.message = '查询Catalog成功'\n response.data['total'] = catalogs.pages\n response.data['results'] = list_json_serialize(catalogs.items)\n return response.__dict__\n\n @jwt_required\n @requires_roles('superuser')\n def get(self):\n catalogs = Catalog.query.order_by(Catalog.name).all()\n\n response = ResponseBean().get_success_instance()\n response.message = '查询Catalog成功'\n response.data['results'] = list_json_serialize(catalogs)\n return response.__dict__\n\n\napi.add_resource(Create, '/create')\napi.add_resource(Delete, '/delete/<string:id>')\napi.add_resource(Update, '/update')\napi.add_resource(Detail, '/detail/<string:id>')\napi.add_resource(ListAll, '/list/all')\n" }, { "alpha_fraction": 0.5207100510597229, "alphanum_fraction": 0.5207100510597229, "avg_line_length": 20.0625, "blob_id": "01f11cc41b7cd2eb50622a97e22f21915040c0c3", "content_id": "86ca37d28a4ad2d97650298b14f0cf5ab904afd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 35, "num_lines": 16, "path": "/backend/utils/response_bean.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "class ResponseBean:\n success = False\n message = ''\n data = {}\n\n def get_success_instance(self):\n self.success = True\n self.message = ''\n self.data = {}\n return self\n\n def get_fail_instance(self):\n self.success = False\n self.message = ''\n self.data = {}\n return self\n\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 15.25, "blob_id": "520e10b8845904a1f3011639c1c46680b85ca9de", "content_id": "61082eee00b8865fa5457bb9e22aa40cbaa5ce07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 65, "license_type": "no_license", "max_line_length": 28, "num_lines": 4, "path": "/backend/config/base_config.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "class BaseConfig(object):\n \"\"\"Base config class.\"\"\"\n\n pass\n" }, { "alpha_fraction": 0.6484848260879517, "alphanum_fraction": 0.6484848260879517, "avg_line_length": 23.14634132385254, "blob_id": "e2e5b9283d749aa8e57436ee08b80ec1c65f74b8", "content_id": "400325b5c674e6e06ae4ce3a13cdbdb02af1bb62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 990, "license_type": "no_license", "max_line_length": 47, "num_lines": 41, "path": "/backend/run.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template\nfrom config.prod_config import ProdConfig\nfrom extensions import db, cors, jwt\nfrom apps.user.controllers import user\nfrom apps.article.controllers import article\nfrom apps.catalog.controllers import catalog\n\n\ndef create_app():\n # Create the Flask's instance.\n app = Flask(__name__,\n static_folder=\"../dist/static\",\n template_folder=\"../dist\")\n\n # Set the project's config.\n app.config.from_object(ProdConfig)\n\n # Register blueprint\n app.register_blueprint(user)\n app.register_blueprint(article)\n app.register_blueprint(catalog)\n\n # Init the extensions' app\n db.init_app(app)\n cors.init_app(app)\n jwt.init_app(app)\n # swagger.init_app(app)\n\n # Page jump\n @app.route('/', defaults={'path': ''})\n @app.route('/<path:path>')\n def catch_all(path):\n return render_template(\"index.html\")\n\n return app\n\n\napp = create_app()\n\nif __name__ == '__main__':\n app.run()\n" }, { "alpha_fraction": 0.5065122842788696, "alphanum_fraction": 0.6946454644203186, "avg_line_length": 15.853658676147461, "blob_id": "efdce5b571510090afbe0a6c65c91addf77cc004", "content_id": "409adff11763f16ee2356a0e6c0dcb6fb6845f00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 691, "license_type": "no_license", "max_line_length": 25, "num_lines": 41, "path": "/backend/requirements.txt", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "alembic==0.9.8\naniso8601==3.0.0\nBabel==2.5.3\nbcrypt==3.1.4\nblinker==1.4\ncffi==1.11.5\nclick==6.7\nflasgger==0.8.3\nFlask==1.0.1\nFlask-BabelEx==0.9.3\nFlask-Bcrypt==0.7.1\nFlask-Cache==0.13.1\nFlask-Cors==3.0.3\nFlask-HTTPAuth==3.2.3\nFlask-JWT-Extended==3.7.2\nFlask-Login==0.4.1\nFlask-Mail==0.9.1\nFlask-Migrate==2.1.1\nFlask-RESTful==0.3.6\nFlask-Script==2.0.6\nFlask-SQLAlchemy==2.3.2\nFlask-WTF==0.14.2\nitsdangerous==0.24\nJinja2==2.10\njsonschema==2.6.0\nMako==1.0.7\nMarkupSafe==1.0\nmistune==0.8.3\npasslib==1.7.1\npycparser==2.18\nPyJWT==1.4.2\nPyMySQL==0.8.0\npython-dateutil==2.7.0\npython-editor==1.0.3\npytz==2018.3\nPyYAML==3.12\nsix==1.11.0\nspeaklater==1.3\nSQLAlchemy==1.1.0\nWerkzeug==0.14.1\nWTForms==2.1\n" }, { "alpha_fraction": 0.6060935854911804, "alphanum_fraction": 0.6235038042068481, "avg_line_length": 30.689655303955078, "blob_id": "29d298afebc94856cdf7b16e817c47c628bd7d52", "content_id": "fda1d153f1f28de8ca9d1980aa617ecb3301c021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 919, "license_type": "no_license", "max_line_length": 100, "num_lines": 29, "path": "/backend/apps/article/models.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from uuid import uuid1\n\nfrom extensions import db\n\n\nclass Article(db.Model):\n id = db.Column(db.String(45), primary_key=True)\n title = db.Column(db.String(255))\n author = db.Column(db.String(20))\n catalog = db.Column(db.String(45))\n abstract = db.Column(db.String(255))\n content = db.Column(db.Text)\n create_time = db.Column(db.DateTime)\n update_time = db.Column(db.DateTime)\n status = db.Column(db.String(10))\n\n def __init__(self, title, author, catalog, abstract, content, create_time, update_time, status):\n self.id = str(uuid1()),\n self.title = title,\n self.author = author,\n self.catalog = catalog,\n self.abstract = abstract,\n self.content = content,\n self.create_time = create_time,\n self.update_time = update_time,\n self.status = status\n\n def __repr__(self):\n return \"<Model Article `{}`>\".format(self.title)\n" }, { "alpha_fraction": 0.6426106691360474, "alphanum_fraction": 0.6441110372543335, "avg_line_length": 36.23463821411133, "blob_id": "6dc5bd4a12ee97c32202f7f046917de08a0f1dd1", "content_id": "bfb5bec0cc57209dbba974ee8525c9aa0e959e7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6713, "license_type": "no_license", "max_line_length": 118, "num_lines": 179, "path": "/backend/apps/article/controllers.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "import time\nfrom datetime import datetime\nfrom flask import Blueprint\nfrom flask_restful import Resource, Api, reqparse\nfrom flask_jwt_extended import jwt_required\n\nfrom utils.json_serialize import list_json_serialize\nfrom utils.response_bean import ResponseBean\nfrom utils.protect_restful import requires_roles\nfrom extensions import db\nfrom .models import Article\nfrom apps.catalog.models import Catalog\n\narticle = Blueprint('article', __name__,\n url_prefix='/article')\n\napi = Api(article)\n\n\nclass Create(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('title', type=str, location='json', required=True)\n self.parser.add_argument('author', type=str, location='json', required=True)\n self.parser.add_argument('catalog', type=str, location='json', required=True)\n self.parser.add_argument('abstract', type=str, location='json')\n self.parser.add_argument('content', type=str, location='json')\n self.parser.add_argument('status', type=str, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n title = args['title']\n author = args['author']\n catalog = args['catalog']\n abstract = args['abstract']\n content = args['content']\n status = args['status']\n\n now_time = datetime.now()\n new_article = Article(title=title, author=author, catalog=catalog, abstract=abstract, content=content,\n create_time=now_time,\n update_time=now_time, status=status)\n db.session.add(new_article)\n find_catalog = Catalog.query.get(catalog)\n find_catalog.amount = find_catalog.amount + 1\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '新建Article成功'\n return response.__dict__\n\n\nclass Delete(Resource):\n\n @jwt_required\n @requires_roles('superuser')\n def get(self, id):\n delete_article = Article.query.get(id)\n db.session.delete(delete_article)\n\n find_catalog = Catalog.query.get(delete_article.catalog)\n find_catalog.amount = find_catalog.amount - 1\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '删除Article成功'\n return response.__dict__\n\n\nclass Update(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('id', type=str, location='json', required=True)\n self.parser.add_argument('title', type=str, location='json', required=True)\n self.parser.add_argument('author', type=str, location='json')\n self.parser.add_argument('catalog', type=str, location='json', required=True)\n self.parser.add_argument('abstract', type=str, location='json')\n self.parser.add_argument('content', type=str, location='json')\n self.parser.add_argument('status', type=str, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n id = args['id']\n title = args['title']\n author = args['author']\n catalog = args['catalog']\n abstract = args['abstract']\n content = args['content']\n status = args['status']\n\n edit_article = Article.query.filter_by(id=id).first()\n edit_article.title = title\n edit_article.author = author\n edit_article.catalog = catalog\n edit_article.abstract = abstract\n edit_article.content = content\n edit_article.update_time = datetime.now()\n edit_article.status = status\n db.session.commit()\n\n response = ResponseBean().get_success_instance()\n response.message = '编辑Article成功'\n return response.__dict__\n\n\nclass Detail(Resource):\n def get(self, id):\n find_article = Article.query.get(id)\n\n response = ResponseBean().get_success_instance()\n response.message = '查询Article成功'\n response.data['id'] = find_article.id\n response.data['title'] = find_article.title\n response.data['author'] = find_article.author\n response.data['catalog'] = find_article.catalog\n response.data['abstract'] = find_article.abstract\n response.data['content'] = find_article.content\n response.data['create_time'] = time.mktime(find_article.create_time.timetuple()) * 1000\n response.data['update_time'] = time.mktime(find_article.update_time.timetuple()) * 1000\n response.data['status'] = find_article.status\n\n return response.__dict__\n\n\nclass ListAll(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', type=int, location='json', required=True)\n self.parser.add_argument('page_size', type=int, location='json', required=True)\n\n @jwt_required\n @requires_roles('superuser')\n def post(self):\n args = self.parser.parse_args()\n page = args['page']\n page_size = args['page_size']\n\n articles = Article.query.order_by(Article.create_time).paginate(page, page_size)\n for item in articles.items:\n catalog = Catalog.query.get(item.catalog)\n item.catalog = catalog.name\n\n response = ResponseBean().get_success_instance()\n response.message = '查找Articles成功'\n response.data['total'] = articles.pages\n response.data['results'] = list_json_serialize(articles.items)\n return response.__dict__\n\n\nclass ListPublished(Resource):\n def __init__(self):\n self.parser = reqparse.RequestParser()\n self.parser.add_argument('page', type=int, location='json', required=True)\n self.parser.add_argument('page_size', type=int, location='json', required=True)\n\n def post(self):\n args = self.parser.parse_args()\n page = args['page']\n page_size = args['page_size']\n\n articles = Article.query.order_by(Article.create_time).filter_by(status='published').paginate(page, page_size)\n\n response = ResponseBean().get_success_instance()\n response.message = '查找Articles成功'\n response.data['total'] = articles.pages\n response.data['results'] = list_json_serialize(articles.items)\n return response.__dict__\n\n\napi.add_resource(Create, '/create')\napi.add_resource(Delete, '/delete/<string:id>')\napi.add_resource(Update, '/update')\napi.add_resource(Detail, '/detail/<string:id>')\napi.add_resource(ListAll, '/list/all')\napi.add_resource(ListPublished, '/list/published')\n" }, { "alpha_fraction": 0.5746835470199585, "alphanum_fraction": 0.594936728477478, "avg_line_length": 22.235294342041016, "blob_id": "d76ee953aa19822a2ed82793b1708194340f3c57", "content_id": "a48ec0e5af3d890cd96d3c2acdf6d84627671e20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/backend/apps/catalog/models.py", "repo_name": "719034075/YiJiuBlog", "src_encoding": "UTF-8", "text": "from uuid import uuid1\n\nfrom extensions import db\n\n\nclass Catalog(db.Model):\n id = db.Column(db.String(45), primary_key=True)\n name = db.Column(db.String(255))\n amount = db.Column(db.Integer)\n\n def __init__(self, name):\n self.id = str(uuid1()),\n self.name = name,\n self.amount = 0\n\n def __repr__(self):\n return \"<Model Catalog `{}`>\".format(self.name)\n" } ]
20
rvcristiand/losa-aproximacion
https://github.com/rvcristiand/losa-aproximacion
e9c24e5b3152ade6e2d9659fcc9bd79f8caa7bd9
a9ebec241cf4aa73f76a616214de9b6f75b319f6
e77ac12ccc802194767a4a1c052eb668278d79eb
refs/heads/main
2023-06-03T04:12:45.843952
2021-06-18T17:54:31
2021-06-18T17:54:31
378,228,072
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5573093295097351, "alphanum_fraction": 0.5997934937477112, "avg_line_length": 32.23737335205078, "blob_id": "53185892f0485fc0959f075e763fba8e78e29f82", "content_id": "2bbef21c421370a62469e1911b45fc0a2a524b2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13610, "license_type": "no_license", "max_line_length": 197, "num_lines": 396, "path": "/main.py", "repo_name": "rvcristiand/losa-aproximacion", "src_encoding": "UTF-8", "text": "from docxtpl import DocxTemplate\r\n\r\nif __name__ == \"__main__\":\r\n doc = DocxTemplate(\"DISEÑO DE LA LOSA DE APROXIMACION DEL PUENTE.docx\")\r\n\r\n context = {'nombre': \"Puente El Portillo\"}\r\n\r\n context ['departamento'] = \"Cesar\"\r\n context ['municipio'] = \"San Martín\"\r\n context ['coordenadas'] = \"7°59'57.2\\\"N 73°30'57.6\\\"W\"\r\n \r\n # Resistencia del Concreto\r\n fc = 28\r\n context['fc'] = fc \r\n \r\n # Resistecia del Acero\r\n fy = 420\r\n context['fy'] = fy\r\n \r\n #Dimensiones del Puente\r\n L = 5 \r\n context['L'] = L\r\n \r\n ancho_de_carril = 3.6\r\n context['ancho_de_carril'] = ancho_de_carril\r\n\r\n ancho_de_berma = 1.4\r\n context['ancho_de_berma'] = ancho_de_berma\r\n\r\n ancho_de_anden = 0\r\n context['ancho_de_anden'] = ancho_de_anden\r\n\r\n espesor_de_carpeta_asfaltica = 0.08\r\n context['espesor_carpeta_asfaltica'] = espesor_de_carpeta_asfaltica\r\n\r\n ancho_inferior_de_barrera = 0.0\r\n context['ancho_inferior_de_barrera'] = ancho_inferior_de_barrera\r\n\r\n ancho_superior_de_barrera = 0.0\r\n context['ancho_superior_de_barrera'] = ancho_superior_de_barrera\r\n \r\n altura_de_barrera = 0.0\r\n context['altura_de_barrera'] = altura_de_barrera\r\n \r\n num_carriles = 2\r\n \r\n ancho_total = round((((ancho_de_carril *num_carriles / 2 )+ ancho_de_berma + ancho_de_anden + ancho_inferior_de_barrera) * 2),2)\r\n context['ancho_total'] = ancho_total\r\n\r\n \r\n\r\n #Altura de la losa\r\n h = round(((1.2 * ( L + 3)) / 30),2)\r\n context['h'] = h\r\n\r\n #ancho de franja equivalente\r\n if ancho_total < 9 :\r\n \r\n anchofreq_uncarril = ancho_total\r\n \r\n else : anchofreq_uncarril = 9 \r\n \r\n if L < 18 :\r\n \r\n luzfreq_uncarril = L\r\n \r\n else : luzfreq_uncarril = 18 \r\n\r\n E_un_carril = round((0.25 + 0.42 * ( anchofreq_uncarril * luzfreq_uncarril ) ** 0.5),2)\r\n\r\n if E_un_carril > (ancho_total/num_carriles) :\r\n E_un_carril = (ancho_total/num_carriles)\r\n \r\n if ancho_total < 18 :\r\n \r\n anchofreq_doscarriles = ancho_total\r\n \r\n else : anchofreq_doscarriles = 18\r\n\r\n E_dos_carriles = round((2.1 + 0.12 * ( anchofreq_doscarriles * luzfreq_uncarril ) ** 0.5),2)\r\n \r\n if E_dos_carriles > (ancho_total/num_carriles) :\r\n E_dos_carriles = (ancho_total/num_carriles)\r\n \r\n if E_un_carril < E_dos_carriles :\r\n \r\n E_tomado = E_un_carril\r\n \r\n else : E_tomado = E_dos_carriles\r\n\r\n context['E_un_carril'] = E_un_carril\r\n context['E_dos_carriles'] = E_dos_carriles\r\n context['E_tomado'] = E_tomado\r\n \r\n espesor_relleno = context['espesor_relleno'] = context.get('espesor_relleno', 0.6)\r\n\r\n #Solicitaciones\r\n #Por carga muerta\r\n # pesos especificos en kN/m3\r\n pespecifico_concreto = 2.4 * 9.81\r\n pespecifico_carpeta_asfaltica = 2.2 * 9.81\r\n pespecifico_relleno = 1.8 * 9.81\r\n\r\n # Cargas distrbuidas muertas\r\n DC = pespecifico_concreto * h\r\n DW = round ((pespecifico_carpeta_asfaltica * espesor_de_carpeta_asfaltica),2)\r\n DEV = round(pespecifico_relleno * espesor_relleno, 2)\r\n \r\n context['pespecifico_carpeta_asfaltica'] = round(pespecifico_carpeta_asfaltica)\r\n context['pespecifico_concreto'] = round(pespecifico_concreto)\r\n context['DC'] = DC\r\n context['DW'] = DW\r\n context['DEV'] = DW\r\n \r\n #Momentos máximos\r\n # Cargas Permanentes\r\n # Unidades en kN/m\r\n MDC = round(((DC * L ** 2 / 8) ))\r\n MDW = round(((DW * L ** 2 / 8) ))\r\n MDEV = round(((DEV * L ** 2 / 8) ))\r\n context['MDC'] = MDC\r\n context['MDW'] = MDW\r\n context['MDEV'] = MDEV\r\n \r\n #Momento máximo debido al camión de diseño (360 kN) # Ecuación válida para luces mayores de 10.04 m \r\n\r\n MAcamion = 360 / L * (L / 2 + 0.717) ** 2 - 688\r\n context['MACamion'] = MAcamion\r\n\r\n # Momento máximo debido al tandem de diseño (250 kN) # Ecuación válida para luces mayores de 1.8 m \r\n Mtandem = round(250 / L * ( L / 2 + 0.3) ** 2 - 150)\r\n context['Mtandem'] = Mtandem\r\n\r\n if Mtandem > MAcamion:\r\n Mcviva = Mtandem\r\n else : Mcviva = MAcamion\r\n \r\n #Momento máximo debido al carril de diseño (10.33 kN/m)\r\n Mcarril = round(10.3 * L **2 / 8)\r\n context['Mcarril'] = Mcarril\r\n #Momento maximo debido a la carga vehicular de diseño con amplificación dinámica\r\n\r\n MLLIM = round(1.33 * Mcviva + Mcarril)\r\n context['MLLIM'] = MLLIM\r\n \r\n #Momento por carga viva por metro de ancho de franja equivalente\r\n\r\n MLLIMafequiv = round(MLLIM / E_tomado)\r\n context['MLLIMafequiv'] = MLLIMafequiv\r\n \r\n #Diseño a Flexión\r\n #Factores de modificación de carga 1.3.2\r\n #Factor relacionado con la ductilidad\r\n factor_ductilidad = 1\r\n\r\n #Factor relacionado con la redundancia\r\n factor_redundancia = 1\r\n\r\n #Factor relacionado con la importancia operativa\r\n factor_imp_operativa = 1\r\n\r\n factor_mod_carga = factor_ductilidad * factor_imp_operativa * factor_redundancia\r\n context['factor_mod_carga'] = factor_mod_carga\r\n\r\n # Momento ultimo\r\n Mu = factor_mod_carga * ( 1.25 * MDC + 1.5 * MDW +1.35 * MDEV + 1.75 * MLLIMafequiv )\r\n Mu_tonm = Mu / 9.81\r\n context['Mu'] = Mu\r\n\r\n # Recubrimiento de armadura principal no protegida TAbla 5.12.3.1\r\n recub = 0.09\r\n # factor phi para diseño a flexión\r\n phi = 0.9\r\n d = h - recub\r\n context['d'] = d \r\n\r\n K = round (Mu_tonm / (1 * d ** 2),1)\r\n context['K'] = K\r\n\r\n #cuantía de acero\r\n cuantia = round(0.0567 * (1 - ( 1- (35.3 * K / 37800)) ** 0.5 ), 5)\r\n context['cuantia'] = cuantia \r\n\r\n cuantia_kN = round(( 1 - ( 1 - ( 2 * Mu / ( phi * 1 * d ** 2 * 0.85 * fc * 1000 ) ) ) ** 0.5 ) * 0.85 * fc / fy, 5) \r\n context['cuantia_kN'] = cuantia_kN\r\n\r\n #Area de refuerzo de la losa en cm2\r\n As_flexion = round(cuantia_kN * d * 100 * 100, 2)\r\n context['As_flexion'] = As_flexion\r\n\r\n #Para barras #8 As = 5.1 cm2\r\n As_8 = 5.1 # definir al inicio\r\n No_barras_8_flexion = round(As_flexion / As_8)\r\n context['No_barras_8_flexion'] = No_barras_8_flexion\r\n context['As_8'] = As_8\r\n\r\n #Espaciamiento Armadura a flexión\r\n espac_arm_prin_flexion = round (100 / No_barras_8_flexion)\r\n context['espac_arm_prin_flexion'] = espac_arm_prin_flexion\r\n\r\n # Revisión del factor phi = 0.9 para el diseño a flexión\r\n\r\n a_f = round(cuantia * d * fy /( 0.85 * fc), 4)\r\n context['a_f'] = a_f\r\n #profundidad eje neutro\r\n\r\n betha_1 = 0.85\r\n c_f = round(a_f / betha_1 , 4) \r\n context['c_f'] = c_f\r\n #Relacion de deformaciones en la sección de concreto reforzado\r\n\r\n defor_total = round((d - c_f) * (0.003 / c_f), 4) \r\n context['defor_total'] = defor_total\r\n #Armadura dedistribución para losas con armadura principal paralela a la dirección del trafico (9.7.3.2)\r\n\r\n Armadura_de_distribucion = 55 / (L) ** 0.5 / 100\r\n context['Armadura_de_distribucion'] = Armadura_de_distribucion\r\n\r\n As_4 = 1.29\r\n As_Armadura_de_distribucion = round ( Armadura_de_distribucion * As_flexion , 2)\r\n context['As_Armadura_de_distribucion'] = As_Armadura_de_distribucion\r\n\r\n No_barras_4_dist = round( As_Armadura_de_distribucion / As_4 )\r\n context['No_barras_4_dist'] = No_barras_4_dist\r\n\r\n espac_arm_dist = round( 100 / No_barras_4_dist )\r\n context['espac_arm_dist'] = espac_arm_dist\r\n\r\n #Armadura minima\r\n #Modulo de rotura del concreto\r\n fr = round(0.62 * fc ** 0.5, 2)\r\n context['fr'] = fr \r\n # factor de variacion de l afisuracion por flexion 5.7.3.3.2 \r\n gamma_1 = 1.6\r\n\r\n #relacion entre la reistencia especificada a fluencia y la resistencia ultima atracción del refuerzo\r\n #refuerzo a706, Grado 60\r\n gamma_3 = 0.75\r\n\r\n #Modulo elastico de la seccion\r\n\r\n Sc = round(1 * h ** 2 / 6, 4 )\r\n context['Sc'] = Sc\r\n\r\n Mcr = round (gamma_1 ** 2 * gamma_3 * fr * Sc * 1000)\r\n context['Mcr'] = Mcr\r\n\r\n if Mcr > Mu :\r\n print ('No cumple Armadura mínima')\r\n \r\n # Control de fisuración\r\n # Factor de exposición clase 1. 5.7.3.4 \r\n gamma_e = 1.0\r\n\r\n #De acuerdo con 5.12.3-1, el espesor de recubrimiento de concreto medido desde la fibra extrema a tracción hasta el centro del refuerzo de flexión mas cercano, para losas vaciadas in situ 25 mm\r\n\r\n d_c = 0.025 + 0.0254 / 2\r\n\r\n if d_c < 0.050 : \r\n d_c = 0.050\r\n\r\n #De acuerdo con el Art 5.7.3.4, el coeficiente beta s \r\n beta_s = round (1 + d_c / (0.7 * (h - d_c)), 3)\r\n context['beta_s'] = beta_s\r\n\r\n #Calculo de fss: Esfuerzo actuante a tracción en el acero para estado limite de servicio I\r\n \r\n #Combinación para el estado limite de servicio tabla 3.4.1\r\n Msi = 1 * (MDC + MDW +MDEV +MLLIMafequiv)\r\n context['Msi'] = Msi\r\n\r\n # Modulo de elasticidad del concreto - densidad normal MPa\r\n\r\n E_concreto = round(0.043 * 2320 ** 1.5 * (fc) ** 0.5, 2)\r\n context['E_concreto'] = E_concreto\r\n\r\n # Modulo de elasticidad del acero MPa\r\n \r\n E_acero = 200000\r\n\r\n #Relación modular\r\n\r\n rel_mod = round(E_acero / E_concreto)\r\n context['rel_mod'] = rel_mod\r\n\r\n #Momento de primer orden de la sección fisurada, de 1m de ancho, con respecto al eje neutro\r\n\r\n #Tomando momentos con respecto al eje neutro de la sección:\r\n\r\n X_cf = round (( -(2 * rel_mod * As_flexion * 10 ** -4) + ((2 * rel_mod * As_flexion * 10 ** -4 ) ** 2 - (4 * 1 * -2 * rel_mod * As_flexion * 10 ** -4 * d )) ** 0.5 ) / (2 * 1), 2)\r\n context['X_cf'] = X_cf\r\n \r\n # Momento de inercia de la seccion fisurada\r\n\r\n I_c = round(X_cf ** 3 / 3 + rel_mod * As_flexion * 10 ** -4 * (d - X_cf) ** 2, 8)\r\n context['I_c'] = I_c\r\n\r\n fss = round (rel_mod * Msi * (d - X_cf) / I_c / 1000, 2)\r\n context['fss'] = fss\r\n\r\n # Reemplazando en la ecuación 5.7.3.4.1\r\n \r\n espac_control_fisuracion = round((123000 * gamma_e / (beta_s * fss) ) - (2 * d_c * 1000))\r\n context['espac_control_fisuracion'] = espac_control_fisuracion /10\r\n\r\n if espac_control_fisuracion / 100 > espac_arm_prin_flexion :\r\n print ('No cumple control de fisuración')\r\n\r\n # Separacion centro a centro de barras \r\n diametro_barra_8 = 2.54\r\n espac_libre = espac_arm_prin_flexion - diametro_barra_8 \r\n context['espac_libre'] = espac_libre\r\n\r\n # Espaciamiento minimo de la armadura vaciada in situ 5.10.3 \r\n \r\n #tamaño agregado 3/4in en cm\r\n tamaño_agregado = 1.905\r\n\r\n if espac_libre < 1.5 * diametro_barra_8 :\r\n print ('No cumple espaciamineto minimo 5.10.3')\r\n if espac_libre < 1.5 * tamaño_agregado :\r\n print ('No cumple espaciamineto minimo 5.10.3')\r\n if espac_libre < 3.8 :\r\n print ('No cumple espaciamineto minimo 5.10.3')\r\n\r\n #Armadura por retraccion de fraguado y temperatura\r\n As_retytemp = round(750 * ancho_total * h / (2 * (ancho_total + h) * fy) * 1000)\r\n\r\n if 234 > As_retytemp :\r\n print ('No cumple Retraccion y Temperatura')\r\n if As_retytemp > 1278:\r\n print ('No cumple Retraccion y Temperatura') \r\n context['As_retytemp'] = As_retytemp\r\n As_3 = context['As_3'] = 0.71\r\n No_barras_3_retytemp = round (As_retytemp /100 / As_3, 2) \r\n context ['No_barras_3_retytemp'] = No_barras_3_retytemp\r\n\r\n espa_arm_retytemp = round(100 / No_barras_3_retytemp)\r\n context['espa_arm_retytemp'] = espa_arm_retytemp\r\n h3 = 3 * h\r\n context['h3'] = h3 \r\n \r\n\r\n ##Verificación por fatiga\r\n # De acuerdo con 3.6.1.4.1 la carga de fatiga debe ser el camion de diseño 360 kN con un espaciamiento constante de 9 m entre ejes\r\n\r\n # Factor de carga especificado en 3.4.1-1 para la combinacion de carga de fatiga\r\n gamma_fatiga = context['gamma_fatiga'] = 1.5\r\n\r\n #MLL+IM Fatiga, camion de diseño kN\r\n\r\n if L > 14.48 :\r\n MLLIM_fatiga = round(1.15 * (360/L * (L/2 + 1.76) ** 2) - 1440, 2)\r\n else :\r\n print('ingrese valor de MLLIM_fatiga')\r\n MLLIM_fatiga = 230\r\n\r\n anchofreq_uncarril_fatiga = context['anchofreq_uncarril_fatiga'] = E_un_carril / 1.2\r\n MLLIM_fatiga_fraequiv = context['MLLIM_fatiga_fraequiv'] = round(MLLIM_fatiga / anchofreq_uncarril_fatiga)\r\n\r\n #Momento seccion no fisurada\r\n Mseccion_fisurada = context['Mseccion_fisurada'] = round(MDC + MDW+ MDEV + 1.5 * MLLIM_fatiga_fraequiv)\r\n\r\n # esfuerzo actuante seccion no fisurada\r\n\r\n Y_inf = h / 2\r\n I_seccion = 1 * h ** 3 / 12\r\n f_c_nofisurado = context['f_c_nofisurado'] = round(Mseccion_fisurada * Y_inf / (I_seccion) /1000)\r\n jd = d - X_cf/3\r\n\r\n condicion_esf_seccion_fisurada = round(0.25 * (fc) ** 0.5,1)\r\n if f_c_nofisurado > condicion_esf_seccion_fisurada :\r\n deltaf = MLLIM_fatiga_fraequiv / ( As_flexion * 10 ** -4 * jd)\r\n context['condicion_esf_seccion_fisurada'] = condicion_esf_seccion_fisurada\r\n \r\n #verificacion de esfuerzos sobre la seccion fisurada\r\n\r\n f_seccion_fisurada = context['f_seccion_fisurada'] = round(gamma_fatiga * deltaf /1000)\r\n\r\n #Esfuerzo minimo debido a la carga viva que resulta de la combinacion de carga de fatiga I,combinado con el esfuerzo mas severo de cargas permanentes\r\n #El minmo esfuerzo sobre el acero de refuerzo se produce cuando no actua carga viva\r\n f_min = context['f_min'] = round((MDC + MDW + MDEV) / (As_flexion * 10 ** -4 *jd) /1000)\r\n\r\n deltaF_TH = context['deltaF_TH'] = round(166 - 0.33 * f_min)\r\n\r\n if f_seccion_fisurada > deltaF_TH :\r\n print ('No cumple verificación por fatiga')\r\n \r\n print (f_seccion_fisurada,f_min, deltaF_TH, jd, X_cf, As_flexion)\r\n\r\n \r\n \r\n\r\n doc.render(context)\r\n\r\n doc.save(\"{}.docx\".format('Losa de aproximacion - ' + context['nombre']))\r\n" } ]
1
amacariola/PythonProjects
https://github.com/amacariola/PythonProjects
a2fd3767c8d1f7c922bf30df805a49db677855bb
088e1e0f5ceabfa2f4088367c84d48a1ca1c208a
9acddb4d9737d056d35b945f2282d629dab122d0
refs/heads/master
2023-02-17T21:00:05.924174
2021-01-15T07:48:37
2021-01-15T07:48:37
325,210,410
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6141479015350342, "alphanum_fraction": 0.6463022232055664, "avg_line_length": 23, "blob_id": "8c00219deeeb720e6baabbd009352e7f9f79e119", "content_id": "d48f89402c98235ad0a7baf77c3bb8f3e30b9d6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 311, "license_type": "no_license", "max_line_length": 43, "num_lines": 13, "path": "/addinteger.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# add integers without using BigInt libs\n\nnum1 = input('Input integers here:')\nnum2 = input('Input integers here:')\n\ndef solution(num1,num2):\n try:\n eval(num1) + eval(num2)\n return str(eval(num1) + eval(num2))\n except Exception as e:\n print('Error',str(e))\n\nprint(solution(num1,num2))" }, { "alpha_fraction": 0.719710648059845, "alphanum_fraction": 0.7287522554397583, "avg_line_length": 29.5, "blob_id": "f01f441a2858e904297bf5490565e37619140642", "content_id": "4961594db3edb37f99f2df94d3916540c1fa3482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 553, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/simplewebserver.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# simple HTTP(Web) Server using http.Server\n# and socket.server modules\n\nimport http.server\nimport socketserver\nfrom time import sleep\n\nPORT = 8080 # Our server default port\nHandler = http.server.SimpleHTTPRequestHandler\n\n# HTTP Server code\ntry:\n with socketserver.TCPServer((\"\",PORT),Handler) as httpd:\n print(\"[+] HTTP server now running at port\",PORT)\n httpd.serve_forever() # Initializes the server to accept connections\nexcept KeyboardInterrupt:\n print(\"[-] Server Shutting Down by user exit...\");sleep(5)\n " }, { "alpha_fraction": 0.554959774017334, "alphanum_fraction": 0.5656836628913879, "avg_line_length": 23.933332443237305, "blob_id": "dd72cebef69845dd26f996f42dfa3fe62f243a74", "content_id": "6ecf1c97a54ee648f5bad30ec673548c3096af0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/reverseinteger.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# Strings manipulation\n# given an integer, return the integer in reverse\n\ndef solution(x):\n try:\n string = str(x) # make x a string in order to manipulate it\n if string[0] == '-':\n return int('-' + string[:0:-1])\n else:\n return int(string[::-1])\n except:\n print('Error')\n\n\nprint(solution(input('Input String here:')))" }, { "alpha_fraction": 0.5567867159843445, "alphanum_fraction": 0.5706371068954468, "avg_line_length": 23.133333206176758, "blob_id": "fcee111a2384960f9c4e4d6efe976dd57c1d389e", "content_id": "de38fc780481572e96a688112f18066ba0659e2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 361, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/avewordlength.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# average word length\n\ns1 = input('Input your sentence here:')\n\ndef solution(s1):\n try:\n for p in \"!?';.\":\n s = s1.replace(p,'')\n words = s.split()\n return round(sum(len(word) for word in words)/len(words),2)\n except KeyboardInterrupt:\n print('Program Closing')\n except:\n print('Error')\nprint(solution(s1))" }, { "alpha_fraction": 0.6493150591850281, "alphanum_fraction": 0.6602739691734314, "avg_line_length": 42, "blob_id": "bb7816b6a4f0d0a290e20dacb5db8544840617ef", "content_id": "4fe3dcd456254eadaf78eef1b1a430a3df3de380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 365, "license_type": "no_license", "max_line_length": 88, "num_lines": 7, "path": "/README.md", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "This is my Python projects that im working on. in the Future im adding web applications \nmade by Django and Flask, Right Now, It only contains some simple Python applications\n\n1. Python Simple Web Server\n2. Python Email Client with Attachments\n3. Python NTP Query script\n4. Python Proxy server script\n\n \n" }, { "alpha_fraction": 0.5881226062774658, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 28.05555534362793, "blob_id": "ac4620890b6cdcd6573c1fc91584dea961d73d1c", "content_id": "6c6ca461432930c85b728bd9e68ae809d3137f90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 522, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/ntpquery.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# NTP Query script using Python3\nimport socket\nimport struct\nimport sys\nimport time\ndef RequestTimefromNTP(addr=\"0.de.pool.ntp.org\"):\n REF_TIME_1970 = 2208988800\n client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n data = b'\\x1b' + 47 * b'\\0'\n client.sendto(data,(addr,123))\n data,address = client.recvfrom(1024)\n if data:\n t = struct.unpack('!12I',data)[10]\n t -= REF_TIME_1970\n return time.ctime(t),t\n# invoke the script\nif __name__ == '__main__':\n print(RequestTimefromNTP())" }, { "alpha_fraction": 0.5250659584999084, "alphanum_fraction": 0.5329815149307251, "avg_line_length": 28.230770111083984, "blob_id": "7966a1a606693eca77c46d33dfee055f9c3fc082", "content_id": "38f35b10b3339012a78252ee23a0c3d0534322a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "no_license", "max_line_length": 99, "num_lines": 13, "path": "/palindrome.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# determine if the input string is a palindrome, a word that even spelled reverse is still the same\n\ndef solution(s):\n try:\n for i in range(len(s)):\n t = s[:i] + s[i + 1:]\n if t == t[::-1]:\n return True\n return s == s[::-1]\n except Exception as e:\n print('Error',str(e))\n\nprint(solution(input('Input word here: ')))" }, { "alpha_fraction": 0.4925689995288849, "alphanum_fraction": 0.5010615587234497, "avg_line_length": 25.22222137451172, "blob_id": "9c0b0512d8bc20c36b175bd30eef5bbaaebaf69a", "content_id": "cada909fabfaf831b45b87be27562b27aca94fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 82, "num_lines": 18, "path": "/firstuniquechar.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# given a string find the first non repeating character in it and return its index\n\ndef solution(s):\n try:\n frequency = {}\n for i in s:\n if i not in frequency:\n frequency[i] = 1\n else:\n frequency[i] += 1\n for i in range(len(s)):\n if frequency[s[i]] == 1:\n return i\n return -1\n except:\n print('Error')\n\nprint(solution(input('Input your string here: ')))" }, { "alpha_fraction": 0.5743848085403442, "alphanum_fraction": 0.5827740430831909, "avg_line_length": 32.75471878051758, "blob_id": "cd6652c0f4299c2b3caf34b6dfea6587a22d8951", "content_id": "114456916cc500f2b1115569833e0069923a8045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1788, "license_type": "no_license", "max_line_length": 75, "num_lines": 53, "path": "/proxyserver.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# Python3 Proxy server\n# using socket libraries\n\nfrom time import sleep\nimport socket\nimport signal\nimport threading\n\n# initialize \ndef __init__(self,config):\n signal.signal(signal.SIGINIT,self.shutdown)\n self.serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n self.serverSocket.setsockopt(socket.SOL_SOCKET,socket.SOCK_REUSEADDR,1)\n self.serverSocket.bind(config['HOST_NAME'],config['BIND_PORT'])\n self.serverSocket.listen(10)\n self.__clients = {}\n while True:\n (clientSocket,client_address) = self.serverSocket.accept()\n d = threading.Thread(name=self._getClientName(client_address))\n target = self.proxy_thread, args = (clientSocket, client_address)\n d.setDaemon(True)\n d.start\n request = conn.recv(config['MAX_REQUEST_LEN'])\n first_line = request.split('\\n')[0]\n url = first_line.split('')[1]\n\n http_pos = url.find('://')\n if (http_pos == -1):\n temp = url\n else:\n temp = url[(http_pos + 3):]\n port_pos = temp.find(':')\n\n webserver_pos = temp.find('/')\n if webserver_pos == -1:\n webserver_pos = len(temp)\n webserver = \"\"\n port = -1\n if (port_pos == -1 or webserver_pos < port_pos):git\n webserver = temp[:webserver_pos]\n else:\n port = int((temp[(port_pos+1):])[:webserver_pos-port_pos-1])\n webserver = temp[:port_pos]\n s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n s.settimeout(config['CONNECTION_TIMEOUT'])\n s.connect((webserver,port))\n s.sendall(request)\n while 1:\n data = s.recv(config['MAX_REQUEST_LEN'])\n if (len(data) > 0):\n conn.send(data)\n else:\n break" }, { "alpha_fraction": 0.5339080691337585, "alphanum_fraction": 0.5385057330131531, "avg_line_length": 24.985074996948242, "blob_id": "c4c25cd52d9fcb16f41337c0f3b1d0db194b9669", "content_id": "67d1c39745ff3ecf95d87ef76385f4584e11dbfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1740, "license_type": "no_license", "max_line_length": 58, "num_lines": 67, "path": "/inordertraversal.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# Left > Root > Right \n# in order traversal\n\nclass Node:\n def __init__(self,data):\n self.left = None\n self.right = None\n self.data = data\n # Insert the node\n def insert(self,data):\n if self.data:\n if data < self.data:\n if self.left is None:\n self.left = Node(data)\n else:\n self.left.insert(data)\n elif data > self.data:\n if self.right is None:\n self.right = Node(data)\n else:\n self.right.insert(data)\n else:\n self.data = data\n\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print(self.data),\n if self.right:\n self.right.PrintTree()\n\n def inorderTraversal(self,root):\n res = []\n if root:\n res = self.inorderTraversal(root.left)\n res.append(root.data)\n res = res + self.inorderTraversal(root.right)\n return res\n def preordertraversal(self,root):\n res = []\n if root:\n res.append(root.data)\n res= res + self.preordertraversal(root.left)\n res= res + self.preordertraversal(root.right)\n return res\n def postordertraversal(self,root):\n res = []\n if root:\n res= res + self.postordertraversal(root.left)\n res= res + self.postordertraversal(root.right)\n res.append(root.data)\n return res\n\n\n\nroot = Node(27)\nroot.insert(1)\nroot.insert(2)\nroot.insert(3)\nroot.insert(4)\nroot.insert(5)\nroot.insert(6)\n\n\nprint(root.inorderTraversal(root))\nprint(root.preordertraversal(root))\nprint(root.postordertraversal(root))" }, { "alpha_fraction": 0.7407975196838379, "alphanum_fraction": 0.7446318864822388, "avg_line_length": 30.047618865966797, "blob_id": "711a13dc36dd7bef1fde8714fc512a76cb9ddcad", "content_id": "00ae7cc4dead64a8c6b034971e419561e6b40566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 71, "num_lines": 42, "path": "/emailclient.py", "repo_name": "amacariola/PythonProjects", "src_encoding": "UTF-8", "text": "# Simple SMTP Client using Python \n# SMTP lib plus SSL\n\nimport smtplib\nimport ssl \nfrom time import sleep\n\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\n# Main body here\nsubject = input('Subject:')\nbody = input('')\nsender_email = input('Your Email:')\nreceiver_email = input('To:')\npassword = input('password:')\n# create the message \nmessage = MIMEMultipart()\nmessage[\"From:\"] = sender_email\nmessage[\"To:\"] = receiver_email\nmessage[\"Subject:\"] = subject\nmessage[\"BCC:\"] = receiver_email\nmessage.attach(MIMEText(body,\"plain\")) # Attach the text message here\nfilename = \"sample.txt\" # edit this on the file path of your attachment\nwith open(filename,'rb') as attachment:\n part = MIMEBase(\"application\",\"octet-stream\")\n part.set_payload(attachment.read())\nencoders.encode_base64(part)\npart.add_header(\n \"Content-Disposition\",\n \"attachment; filename = {filename}\",\n)\n# attach the attachment here\nmessage.attach(part)\ntext = message.as_string()\n# initialize connection to the email server\ncontext = ssl.create_default_context()\nwith smtplib.SMTP_SSL(\"smtp.gmail.com\",465,context=context) as server:\n server.login(sender_email,password)\n server.sendmail(sender_email,receiver_email,text)\n" } ]
11
Devjare/IWishTest
https://github.com/Devjare/IWishTest
2f9c778992dceaefc1cd05221f5201238c5ad305
3f04181abc5310c0eef04e165ef0b7019e6136d7
a8bb71ed4acbf4dd8dad3d9b984ef69bbd5f6f0c
refs/heads/master
2020-08-07T02:04:35.603859
2019-10-22T01:06:13
2019-10-22T01:06:13
213,253,362
0
0
null
2019-10-06T22:26:38
2019-10-16T03:45:16
2019-10-22T01:06:14
Python
[ { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 11, "blob_id": "860453ba423a4f95e5b58b43a23d4abcea6eeff8", "content_id": "5fa44d03e90fcfb1d7645b047ff01a8eae709914", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11, "license_type": "no_license", "max_line_length": 11, "num_lines": 1, "path": "/hellov4.py", "repo_name": "Devjare/IWishTest", "src_encoding": "UTF-8", "text": "print(\"V4\")" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "1255be17a3e0e1e161dffa5e43542b459c2e40b8", "content_id": "affe747a39f44bf6637869240e6671259baa3cf2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/hellov3.py", "repo_name": "Devjare/IWishTest", "src_encoding": "UTF-8", "text": "print(\"Gellov3\")" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.75, "avg_line_length": 16, "blob_id": "2ab21fba271b0da5747282a49e6b69390cb6a9dc", "content_id": "7745e44ee2ae732306de6b2f79724bb08cba30c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16, "license_type": "no_license", "max_line_length": 16, "num_lines": 1, "path": "/hellov1.py", "repo_name": "Devjare/IWishTest", "src_encoding": "UTF-8", "text": "print(\"Gellov1\")" } ]
3
SainaPatel/Price_Comparator
https://github.com/SainaPatel/Price_Comparator
ee5b17579e286b4d42cf796a3c1c4b1725685c3d
8c543d2e14e6e07d21185b491f7eccf845cddf48
277a94c60e6a0a9e8b781f9af1a830dc04c396e8
refs/heads/master
2020-12-31T07:09:26.461768
2016-09-16T05:32:52
2016-09-16T05:32:52
58,256,319
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49534451961517334, "alphanum_fraction": 0.5048882961273193, "avg_line_length": 32.0461540222168, "blob_id": "a1096a8379ad76a2bdbed480191bc23082c34238", "content_id": "55d509e19de5f0baf1012ee95c27ffc7a760e9bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4296, "license_type": "no_license", "max_line_length": 125, "num_lines": 130, "path": "/VoloUsers.py", "repo_name": "SainaPatel/Price_Comparator", "src_encoding": "UTF-8", "text": "from flask import Flask, jsonify, url_for, redirect, request\nfrom flask.ext.pymongo import PyMongo\nfrom flask_restful import Resource, Api\nimport json\n\napp = Flask(__name__)\n#mongo = PyMongo(app)\n\n# connect to another MongoDB server altogether\napp.config['MONGO_HOST'] = 'ds021701.mlab.com'\napp.config['MONGO_PORT'] = 21701\napp.config['MONGO_DBNAME'] = 'wishapp'\napp.config['MONGO_USERNAME'] = 'admin'\napp.config['MONGO_PASSWORD'] = 'password'\n\nmongo = PyMongo(app, config_prefix='MONGO')\n\nAPP_URL = \"http://127.0.0.1:5000\"\n\nclass Users(Resource):\n def get(self, username=None):\n data = []\n \n if username:\n user_info = mongo.db.user_details.find_one({\"user_name\": username}, {\"_id\": 0, \"update_time\": 0})\n\n if user_info:\n return {\"status\": \"ok\", \"data\": user_info}\n else:\n return {\"response\": \"no user found for {}\".format(username)}\n\n else:\n cursor = mongo.db.user_details.find({}, {\"_id\": 0, \"update_time\": 0}).limit(10)\n\n for user in cursor:\n print user\n data.append(user)\n\n return {\"data\": data}\n\n def post(self):\n \tdata = []\n \tdataStr = request.data\n data = json.loads(dataStr)\n print type(dataStr)\n print type(data)\n \n if not data:\n data = {\"response\": \"ERROR\"}\n return jsonify(data)\n else:\n username = data.get('user_name')\n print \"I'm here\", username\n if username:\n if mongo.db.user_details.find_one({\"user_name\": username}):\n return {\"response\": \"user already exists.\"}\n else:\n result = mongo.db.user_details.insert(data) \n return {\"status\": \"ok\"} \n return {\"response\": \"ERROR no username\"}\n\n def put(self):\n data = []\n datadic = request.data\n data = json.loads(datadic)\n \n if not data:\n data = {\"response\": \"ERROR\"}\n return jsonify(data)\n else:\n username = data.get('user_name')\n wishlist = data.get('wish_list')\n print \"I'm here in put---\", username\n print \"I'm here in put---\", wishlist\n if username:\n result = mongo.db.user_details.find_one({\"user_name\": username})\n if result:\n mongo.db.user_details.update({'user_name': username}, {'$push': {'wish_list': {'$each':wishlist}}}, True)\n return {\"status\": \"upserted ok\"}\n else:\n return {\"response\": \"User doesn't exist.\"}\n return {\"response\": \"ERROR no username\"}\n\n def delete(self):\n data = []\n datadic = request.data\n data = json.loads(datadic)\n \n if not data:\n data = {\"response\": \"ERROR\"}\n return jsonify(data)\n\t\n\tusername = data.get('user_name')\n\tsem3id = data.get('sem3id') \n result = mongo.db.user_details.find_one({\"user_name\": username})\n wishlist = result['wish_list']\n new_wishlist = []\n item_flag = 0\n \n print \"I'm here in delete---\", username\n print \"I'm here in delete---\", wishlist\n \n if result:\n for item in wishlist:\n if item['sem3id']!= sem3id:\n print \"=================================\"\n print \"item---\", item\n print \"sem3id---\", sem3id\n print \"=================================\"\n new_wishlist.append(item)\n else:\n item_flag = 1\n else:\n return {\"response\": \"ERROR no username\"}\n \n if item_flag == 1:\n print \"I'm here in delete---\", new_wishlist\n mongo.db.user_details.update({'user_name': username}, {'$set': {'wish_list': new_wishlist}})\n return {\"status\":\"ok\"}\n else:\n return{\"status\":\"Illegal delete. Record not present.\"}\n\n\napi = Api(app)\n\napi.add_resource(Users, \"/users/<string:username>\", endpoint=\"user_details2\")\napi.add_resource(Users, \"/users/\", endpoint=\"user_details\")\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', debug=True)\n" }, { "alpha_fraction": 0.6810654997825623, "alphanum_fraction": 0.6859251260757446, "avg_line_length": 27.787565231323242, "blob_id": "ba133a16d058d6cbf0e2f00477741c215c3dcb46", "content_id": "cfc6f290bd6cef4dbc064431db2b8d9392c95b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5556, "license_type": "no_license", "max_line_length": 100, "num_lines": 193, "path": "/Price_Change_App/src/main/java/Price_Change_App/Price_Change_App/MongoConnection.java", "repo_name": "SainaPatel/Price_Comparator", "src_encoding": "UTF-8", "text": "package Price_Change_App.Price_Change_App;\n\nimport java.io.IOException;\nimport java.net.URISyntaxException;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.List;\n\nimport org.bson.Document;\nimport org.json.JSONArray;\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport com.mongodb.BasicDBObject;\nimport com.mongodb.DB;\nimport com.mongodb.DBCollection;\nimport com.mongodb.DBCursor;\nimport com.mongodb.DBObject;\nimport com.mongodb.MongoClient;\nimport com.mongodb.MongoClientURI;\nimport com.mongodb.util.JSON;\n\nimport oauth.signpost.exception.OAuthCommunicationException;\nimport oauth.signpost.exception.OAuthExpectationFailedException;\nimport oauth.signpost.exception.OAuthMessageSignerException;\n\npublic class MongoConnection {\n\n\n\tpublic DB connectToMongo(){\n\t\tMongoClientURI uri = new MongoClientURI(\"mongodb://admin:[email protected]:13222/product_details\");\n\t\tMongoClient client = new MongoClient(uri);\n\t\tDB db = client.getDB(uri.getDatabase());\n\t\treturn db;\n\t}\n\n\tpublic String giveProduct(String searchvalue){\n\t\tDB db=connectToMongo();\n\t\tDBCollection product_details = db.getCollection(\"product_details\");\n\t\t//product_details.\n\t\tDBObject findquery=new BasicDBObject(\"product.name\",searchvalue);\n\t\tDBCursor docs=product_details.find(findquery);\n\t\t// result=null;\n\t\tJSONArray resArr=new JSONArray();\n\t\t\n\t\tif(docs.hasNext()==false)\n\t\t{\n\t\t\tJSONObject returnvalue=new JSONObject();\n\t\t\n\t\t\tresArr=callSem3(searchvalue);\n\t\t\t//System.out.println(\"docs \"+docs.hasNext());\n\t\t\treturnvalue.put(\"details\", sortJsonArray(resArr));\n\t\t\tSystem.out.println(returnvalue);\n\t\t\treturn returnvalue.toString();\n\t\t}else\n\t\t{\n\t\t\tJSONObject returnvalue=new JSONObject();\n\t\t\twhile(docs.hasNext())\n\t\t\t{\n\t\t\t\t\n\t\t\t\tresArr.put(JSONObject.wrap(docs.next().get(\"product\")));\n\t\t\t\t//System.out.println(resArr.get(0).getClass());\n\t\t\t\t//\tSystem.out.println(docs.next().get(\"product\"));\n\t\t\t}\n\t\t\treturnvalue.put(\"details\", sortJsonArray(resArr));\n\t\t\tSystem.out.println(returnvalue);\n\t\t\treturn returnvalue.toString();\n\t\t//\tSystem.out.println();\n\t\t\n\t\t\t\n\t\t//\t\tif(docs.hasNext()&&docs.next().get(\"iphone\")==null)\n\t\t//\t\t{\n\t\t//\t\t\tSystem.out.println(\"inside1\");\n\n\t\t//\t\t\tSemantics3Class s=new Semantics3Class();\n\t\t//\t\t\tSystem.out.println(\"inside2\");\n\t\t//\t \tJSONArray result=null;\n\t\t//\t \ttry {\n\t\t//\t\t\t\tresult=s.findProduct();\n\t\t//\t\t\t} catch (OAuthMessageSignerException e) {\n\t\t//\t\t\t\t// TODO Auto-generated catch block\n\t\t//\t\t\t\te.printStackTrace();\n\t\t//\t\t\t} catch (OAuthExpectationFailedException e) {\n\t\t//\t\t\t\t// TODO Auto-generated catch block\n\t\t//\t\t\t\te.printStackTrace();\n\t\t//\t\t\t} catch (OAuthCommunicationException e) {\n\t\t//\t\t\t\t// TODO Auto-generated catch block\n\t\t//\t\t\t\te.printStackTrace();\n\t\t//\t\t\t} catch (IOException e) {\n\t\t//\t\t\t\t// TODO Auto-generated catch block\n\t\t//\t\t\t\te.printStackTrace();\n\t\t//\t\t\t} catch (URISyntaxException e) {\n\t\t//\t\t\t\t// TODO Auto-generated catch block\n\t\t//\t\t\t\te.printStackTrace();\n\t\t//\t\t\t}\n\t\t//\t \t//System.out.println(result.getJSONObject(0).toString());\n\t\t//\t \tString ress=result.getJSONObject(0).toString();\n\t\t//\t \tDBObject dbo=(DBObject) JSON.parse(ress);\n\t\t//\t \tDBObject resultreturned=new BasicDBObject(\"product\",dbo);\n\t\t//\t \tproduct_details.insert(resultreturned);\n\t\t//\t \treturn result.toString();\n\t\t//\t \t//product_details.\n\t\t//\t\t}\n\t\t//\t\tif(docs.hasNext())\n\t\t//\t\t{\n\t\t//\t\treturn docs.next().get(\"product\").toString();\n\t\t//\t\t}\n\t\t//\t\telse\n\n\t\t//if(product_details.)\n\t}\n\t};\npublic JSONArray sortJsonArray(JSONArray resArr){\n\tList<JSONObject> jsonArr=new ArrayList<JSONObject>();\n\tfor(int k=0;k<resArr.length();k++)\n\t{\n\t\t\t\n\t\tjsonArr.add(resArr.getJSONObject(k));\n\t}\n\tCollections.sort(jsonArr, new Comparator<JSONObject>(){\n\t\tprivate static final String sort_field = \"price\";\n\t\tpublic int compare(JSONObject o1, JSONObject o2) {\n\n\t\t\tString valA = new String();\n\t\t\tString valB = new String();\n\n\t\t\ttry {\n\t\t\t\tvalA = (String) o1.get(sort_field);\n\t\t\t\tvalB = (String) o2.get(sort_field);\n\t\t\t} \n\t\t\tcatch (JSONException e) {\n\t\t\t\t//do something\n\t\t\t}\n\t\t\tif(Double.parseDouble(valA)<=Double.parseDouble(valB))\n\t\t\t{\n\t\t\t\treturn -1;\n\t\t\t}else\n\t\t\t{\n\t\t\t\treturn +1;\n\t\t\t}\n\t\t\t//\treturn valA.compareTo(valB);\n\t\t\t// TODO Auto-generated method stub\n\n\t\t}\n\t});\n\tJSONArray sorted=new JSONArray();\n\tfor(int h=0;h<jsonArr.size();h++)\n\t{\n\t\tsorted.put(jsonArr.get(h));\n\t\tSystem.out.println(jsonArr.get(h));\n\t\tSystem.out.println(\"\\n\");\n\t}\n\treturn sorted;\n}\n\t\t\n\t\t\n\tpublic JSONArray callSem3(String searchvalue){\n\t\tDB db=connectToMongo();\n\t\tDBCollection product_details = db.getCollection(\"product_details\");\n\t\tSemantics3Class s=new Semantics3Class();\n\t\tSystem.out.println(\"inside2\");\n\t\tJSONArray result=null;\n\t\ttry {\n\t\t\tresult=s.findProduct(searchvalue);\n\t\t} catch (OAuthMessageSignerException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (OAuthExpectationFailedException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (OAuthCommunicationException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} catch (URISyntaxException e) {\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t}\n\t\t//System.out.println(result.getJSONObject(0).toString());\n\t\tfor(int i=0;i<result.length();i++)\n\t\t{\n\t\t\tString ress=result.getJSONObject(i).toString();\n\t\t\tDBObject dbo=(DBObject) JSON.parse(ress);\n\t\t\tDBObject resultreturned=new BasicDBObject(\"product\",dbo);\n\t\t\tproduct_details.insert(resultreturned);\n\t\t}\n\t\treturn result;\n\t\t//return null;\n\t}\n}\n" }, { "alpha_fraction": 0.7861770987510681, "alphanum_fraction": 0.7883369326591492, "avg_line_length": 65.14286041259766, "blob_id": "b0cdb58114605ac07f75b663a65f667a0d282d12", "content_id": "0c99b20b998aea7657349bfca4b0b2df9adb412b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 463, "license_type": "no_license", "max_line_length": 116, "num_lines": 7, "path": "/README.md", "repo_name": "SainaPatel/Price_Comparator", "src_encoding": "UTF-8", "text": "# Price_Comparator\n\nTechnologies : Android, Google Cloud Messaging, Amazon Web Services, SemanticS3\n- An android application which makes a shopping hassle free for a user\n- For a searched product, a list of vendors in ascending order of a price is returned\n- It also allows users to keep a product in a wishlist, and give a price range in which he wants to buy that product\n- Once the price reduces, a push notification is sent to the user with details if vendor\n" } ]
3
Marisol610/catalog-app
https://github.com/Marisol610/catalog-app
6cb0ef12aaa5fc9a0b3dbc1be0f8ca02743cd863
8a4639b50ce1ad6a792bfa24f37af0d02b2ae72c
d361a7f6a62e1ccb57a5b6a1ea7f47c7a24a7da5
refs/heads/master
2023-02-26T08:21:13.953187
2021-02-02T19:38:51
2021-02-02T19:38:51
331,518,582
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6902984976768494, "alphanum_fraction": 0.7089552283287048, "avg_line_length": 14.823529243469238, "blob_id": "af7566cc5ffda2c243c73187f11a4315208c3e66", "content_id": "76ecba312842e74de77827f1dcdbf4fbc47e8be5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/app/__init__.py", "repo_name": "Marisol610/catalog-app", "src_encoding": "UTF-8", "text": "#!/products/bin/env python3\n# #coding-*- utf -*-\n\"\"\"THIS IS ASSIGNMENT 3 FOR FSDI-111\"\"\" \n\n\n\n\nfrom flask import Flask\nfrom flask_bootstrap import Bootstrap\n\napp = Flask(__name__)\nBootstrap(app)\n\napp.config[\"SECRET_KEY\"] = \"MYSUPERSECRETSTRING\"\n\n\nfrom app import routes" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 19, "blob_id": "2ebb20c3312c2bee9163d1c144ecbc56cc43a8fc", "content_id": "80d8913bc7c6d92292f3a23034972a44e29413ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22, "license_type": "no_license", "max_line_length": 19, "num_lines": 1, "path": "/crud.py", "repo_name": "Marisol610/catalog-app", "src_encoding": "UTF-8", "text": "\n\n\nfrom app import app" }, { "alpha_fraction": 0.7365989089012146, "alphanum_fraction": 0.7384473085403442, "avg_line_length": 40.653846740722656, "blob_id": "45d9f2cfc810a8aeb29b4f68186bd35a05f13a02", "content_id": "72a596943d171b59a9ad489c77361c7345e5b8d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1082, "license_type": "no_license", "max_line_length": 93, "num_lines": 26, "path": "/app/forms/product.py", "repo_name": "Marisol610/catalog-app", "src_encoding": "UTF-8", "text": "#!/products/bin/env python3\n#-*- coding utf8 -*-\n\"\"\" This is the app product definition\"\"\"\n\n\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\n\n\n\n\n\nclass ProductForm(FlaskForm):\n name = StringField(\"Enter the product's name\", validators=[DataRequired()])\n price = StringField(\"Enter the product' price\", validators=[DataRequired()])\n description = StringField(\"Enter the product's description\", validators=[DataRequired()])\n category = StringField(\"Enter the product's category\", validators=[DataRequired()])\n quantity = StringField(\"Enter a quantity\", validators=[DataRequired()])\n unique_tag = StringField(\"Enter the product's unique_tag\", validators=[DataRequired()])\n submit = SubmitField(\"Submit\")\n\nclass ProductReviewForm(FlaskForm):\n name = StringField(\"Enter your name\", validators=[DataRequired()])\n product_name = StringField(\"Enter the product's name\", validators=[DataRequired()])\n review = StringField(\"Enter your review for this product\", validators=[DataRequired()])" }, { "alpha_fraction": 0.6033149361610413, "alphanum_fraction": 0.6081767678260803, "avg_line_length": 21.95939064025879, "blob_id": "09f983c91001226adc018e598406cb7251c5425d", "content_id": "a6512343859ff46cb55549ecde5e746f892c79eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4525, "license_type": "no_license", "max_line_length": 115, "num_lines": 197, "path": "/app/routes.py", "repo_name": "Marisol610/catalog-app", "src_encoding": "UTF-8", "text": "#!/products/bin/env python3\n#-*- coding utf8 -*-\n\"\"\" This is the routes for product application \"\"\"\n\n\n\n\n\n\n\nfrom flask import request, render_template\nfrom app import app\nfrom app.database import create, read, update, delete, scan\nfrom datetime import datetime\nfrom flask import request\nfrom app.forms.product import ProductForm\n\n\n\n#product CRUD\[email protected](\"/\")\ndef index():\n serv_time = datetime.now().strftime(\"%F %H:%M:%S\")\n return {\n \"ok\": True,\n \"version\": \"1.0.0\",\n \"server_time\": serv_time\n }\n\[email protected](\"/product_form\", methods=[\"GET\", \"POST\"])\ndef product_form():\n if request.method == \"POST\":\n name = request.form.get(\"name\")\n price = request.form.get(\"price\")\n description = request.form.get(\"description\")\n category = request.form.get(\"category\")\n quantity = request.form.get(\"quantity\")\n unique_tag = request.form.get(\"unique_tag\")\n \n create(name, price, description, category, quantity, unique_tag)\n form = ProductForm()\n return render_template(\"form_example.html\", form=form)\n\n\[email protected](\"/prod_review\", methods=[\"GET\", \"POST\"])\ndef prod_review():\n if request.method == \"POST\":\n name = request.form.get(\"name\")\n product_name = request.form.get(\"product_name\")\n review = request.form.get(\"review\")\n \n create(name, product_name, review)\n form = ProductReviewForm()\n return render_template(\"review.html\", form=form)\n\n\[email protected](\"/catalog\")\ndef catalog():\n return render_template(\"catalog.html\")\n\n\[email protected](\"/products\")\ndef get_all_products():\n out = scan()\n out[\"ok\"] = True\n out[\"message\"] = \"Success\"\n #return out\n return render_template(\"products.html\", products=out[\"body\"])\n\n\[email protected](\"/products/<pid>\")\ndef get_one_product(pid):\n out = read(int(pid))\n out[\"ok\"] = True\n out[\"message\"] = \"Success\"\n return out\n\n\[email protected](\"/products\", methods = [\"POST\"])\ndef create_product():\n product_data = request.json\n new_id = create(\n product_data.get(\"name\"),\n product_data.get(\"price\"),\n product_data.get(\"description\"),\n product_data.get(\"category\"),\n product_data.get(\"quantity\"),\n product_data.get(\"unique_tag\")\n \n\n )\n\n return {\"ok\": True, \"message\": \"Success\", \"new_id\": new_id}\n\n\[email protected](\"/products/<pid>\", methods=[\"GET\", \"PUT\"])\ndef update_product(pid):\n #product_data = request.jason\n if request.method ==\"PUT\":\n update(pid, request.form)\n return {\"ok\": True, \"message\": \"Updated\"}\n out = read(int(pid))\n update_form = ProductForm()\n if out[\"body\"]:\n return render_template(\"single_product.html\", product=out[\"body\"][0], form=update_form)\n else:\n return render_template(\"404.html\"), 404\n\n\n\[email protected](\"/products/delete/<pid>\", methods=[\"GET\"])\ndef delete_product(pid):\n out = update(int(pid), {\"active\": 0})\n\n return {\"ok\": out, \"message\": \"Deleted\"}\n\n\n\n#@app.route(\"/products/delete/<pid>\", methods=[\"GET\"])\n#def delete_product(pid):\n # id= input(\"Enter the id for the item you wish to delete\")\n\n # for product in products:\n # if(str(prod.id) == id):\n # delete(pid, request.form)\n # return {\"ok\": True, \"message\": \"Updated\"}\n\n\n \n\n\n\n\n\n\n\[email protected]('/agent')\ndef agent():\n user_agent = request.headers.get(\"User-Agent\")\n return \"<p>Your user agent is %s</p>\" % user_agent\n\n\[email protected](\"/myroute\")\ndef my_view_function():\n return render_template(\"index.html\")\n\n\n\n\n# user CRUD\[email protected](\"/user/<name>\")\ndef user(name):\n return render_template(\"user.html\", name=name)\n\n\[email protected](\"/user/<name>\")\ndef show_user(name):\n return render_template(\"user.html\", name=name)\n\n\n\[email protected](\"/about\")\ndef about():\n return render_template(\"about.html\", first_name=\"Marisol\", last_name=\"Rodriguez\", hobbies=\"Crochet and Baking\")\n\n\[email protected](\"/users\")\ndef get_all_users():\n out = scan()\n out[\"ok\"] = True\n out[\"message\"] = \"Success\"\n return out\n\n\[email protected](\"/users/<uid>\")\ndef get_one_user(uid):\n out = read(int(uid))\n out[\"ok\"] = True\n out[\"message\"] = \"Success\"\n return out\n\n \[email protected](\"/users\", methods = [\"POST\"])\ndef create_user():\n user_data = request.json\n new_id = create(\n user_data.get(\"name\"),\n user_data.get(\"last name\"),\n user_data.get(\"hobbies\"),\n \n )\n\n return {\"ok\": True, \"message\": \"Success\", \"new_id\": new_id}\n\[email protected](404)\ndef page_not_found(e):\n return render_template(\"404.html\"), 404\n\n\n" } ]
4
helloprash/17July
https://github.com/helloprash/17July
20e5c6ebd38766eda4376577713e0833d415da68
f21c76b830f6b7bb3c283d87df76d4bf2a3a86f0
44f431ad7a0205b7ca9fea4e1b04530c9ea2f883
refs/heads/master
2020-06-21T07:25:51.553378
2019-07-17T12:11:53
2019-07-17T12:11:53
197,381,604
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6223055124282837, "alphanum_fraction": 0.6994689106941223, "avg_line_length": 43.271427154541016, "blob_id": "baacb11517446ae3e7e650f5f2ea8f1b41d7f9cc", "content_id": "09261574b84800b593058997fa37c52d203639ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3201, "license_type": "no_license", "max_line_length": 236, "num_lines": 70, "path": "/closedCount.py", "repo_name": "helloprash/17July", "src_encoding": "UTF-8", "text": "import pandas as pd\r\n\r\nclosed_count_url = 'http://cwprod/CATSWebNET/main.aspx?WCI=Main&WCE=SubmitQry&WCU=%7c*%7eq%3d8%7c*%7er%3d734bbf217d33486abb09808dd09c77df%7c*%7ef%3d-1%7c*%7eo%3d3%7c*%7ep%3dComplaint%20Folder%7c*%7es%3dVRIZRJV3PPE38BNIAEZPNIXVS9JDGSTC' \r\n\r\nworkflow_140_url = 'http://cwprod/CATSWebNET/main.aspx?WCI=Main&WCE=SubmitQry&WCU=%7c*%7eq%3d8%7c*%7er%3dWorkflow%20History%20140%7c*%7ef%3d-1%7c*%7eo%3d2%7c*%7ep%3dWorkflow%20History%7c*%7es%3dVRIZRJV3PPE38BNIAEZPNIXVS9JDGSTC'\r\n\r\ndef createDataframe(url):\r\n df_html = pd.read_html(url)\r\n data_table = df_html[1]\r\n\r\n col_names = list()\r\n\r\n for index, row in data_table.iloc[[0]].iterrows():\r\n for i in range(len(data_table.columns)):\r\n col_names.append(row[i])\r\n\r\n data_table.columns = col_names\r\n data_table = data_table.drop(data_table.index[0])\r\n #data_table = data_table.set_index('Complaint Number')\r\n return data_table\r\n\r\n\r\nclosedFiles_df = createDataframe(closed_count_url)\r\nclosedFiles_df['Complaint Number'] = closedFiles_df['Complaint Number'].astype('int64')\r\nprint('closedFiles_df')\r\nprint(closedFiles_df.info())\r\n\r\n\r\n######Creating New Workflow 140 list##########\r\nnew_df_140 = createDataframe(workflow_140_url)\r\nnew_df_140['Decision Date'] =pd.to_datetime(new_df_140['Decision Date'])\r\nnew_df_140['Workflow History Number'] = new_df_140['Workflow History Number'].astype('int64')\r\nnew_df_140['Complaint Folder'] = new_df_140['Complaint Folder'].astype('int64')\r\nnew_df_140['Next Step ID'] = new_df_140['Next Step ID'].astype('int64')\r\nprint('new_df_140')\r\nprint(new_df_140.info())\r\n\r\ndf_140 = pd.read_pickle('Overall_140.pickle')\r\ndf_140['Decision Date'] =pd.to_datetime(df_140['Decision Date'])\r\ndf_140 = df_140.append(new_df_140, ignore_index=True)\r\n\r\ndf_140_unique_all = df_140['Workflow History Number'].duplicated(keep= 'first') #Series\r\ndf_140_unique_all.rename('Duplicated', inplace=True)\r\ndf_140 = df_140.join(df_140_unique_all)\r\ndf_140 = df_140[df_140['Duplicated'] == False]\r\ndf_140.drop(['Duplicated',], axis=1, inplace=True)\r\ndf_140.sort_values('Decision Date', ascending=False, inplace = True)\r\nprint('df_140')\r\nprint(df_140.info())\r\n\r\n\r\n######Creating New Unique Workflow 140 list###########\r\ndf_140_unique = df_140['Complaint Folder'].duplicated(keep= 'first')\r\ndf_140_unique.rename('Duplicated', inplace=True)\r\n\r\nmerged_df_140 = df_140.join(df_140_unique)\r\nmerged_df_140 = merged_df_140[merged_df_140['Duplicated'] == False]\r\nmerged_df_140.drop(['Workflow History Number', 'Next Step ID', 'Decision Date','Duplicated'], axis=1, inplace=True)\r\nmerged_df_140.rename(columns={'Complaint Folder': 'Complaint Number'}, inplace=True)\r\n\r\n\r\ntotal_closed_df = pd.merge(closedFiles_df, merged_df_140, how='left', on='Complaint Number')\r\ntotal_closed_df['Matching'] = (total_closed_df['Complaint Owner'] == total_closed_df['Decision Maker'])\r\nprint('total_closed_df')\r\nprint(total_closed_df.info())\r\n\r\nwith pd.ExcelWriter('TATA Closed.xlsx') as writer: \r\n\ttotal_closed_df.to_excel(writer, sheet_name= 'TATA Closed')\r\n\tmerged_df_140.to_excel(writer, sheet_name='Overall 140 without duplicates')\r\n\tdf_140.to_excel(writer, sheet_name= 'Overall 140 with duplicates')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\t\t\r\n\r\n\r\n" } ]
1
georgedriver/django-role-booking-system
https://github.com/georgedriver/django-role-booking-system
6fd26079121d031bdd73a651f15202a2459e9609
382a43abc5ece2d8a257fe611f3595ddec99fc1a
6c9d6287bb35a1e29fcff84ba5bb5ab6a4e091f9
refs/heads/master
2020-04-04T10:12:09.846434
2018-11-07T08:50:43
2018-11-07T08:50:43
155,846,174
0
0
null
2018-11-02T09:49:18
2018-11-02T10:16:25
2018-11-02T10:18:28
Python
[ { "alpha_fraction": 0.7848101258277893, "alphanum_fraction": 0.7848101258277893, "avg_line_length": 25.33333396911621, "blob_id": "bde1ff00fb15ea7f6d3da0ad48d8263e8bf56680", "content_id": "f34caa262b67394a24eda2ff7159b48326b283b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 79, "license_type": "no_license", "max_line_length": 65, "num_lines": 3, "path": "/run.sh", "repo_name": "georgedriver/django-role-booking-system", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\npython /opt/django-role-booking-system/mysite/manage.py runserver\n" }, { "alpha_fraction": 0.6323907375335693, "alphanum_fraction": 0.7557840347290039, "avg_line_length": 24.933332443237305, "blob_id": "c62729a2b5d1f7b8f6be8068ae57de1e18cebe7e", "content_id": "ab8ca9e0e67a4f5b822ba34c392d39df47060216", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 389, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/requirements.txt", "repo_name": "georgedriver/django-role-booking-system", "src_encoding": "UTF-8", "text": "Django==1.10.5\ndjango-ajax-selects==1.3.5\ndjango-appconf==1.0.2\ndjango-bootstrap-form==3.2.1\ndjango-bootstrap-toolkit==2.15.0\ndjango-bootstrap3==8.1.0\ndjango-bootstrap3-datetimepicker==2.2.3\ndjango-compressor==1.5\ndjango-datetime-widget==0.9.3\ndjango-debug-toolbar==1.3.2\ndjango-environ==0.4.0\ndjango-extra-views==0.8.0\ndjango-grappelli==2.6.5\ndjango-guardian==1.4.6\ndjango-rosetta==0.7.8\n" }, { "alpha_fraction": 0.696177065372467, "alphanum_fraction": 0.7364184856414795, "avg_line_length": 22.66666603088379, "blob_id": "0cb27d009768d031514c88f7e87ec8eb4ce08463", "content_id": "27397c536cfff030b92cfe3aee63e6f797bbacfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 497, "license_type": "no_license", "max_line_length": 90, "num_lines": 21, "path": "/Dockerfile", "repo_name": "georgedriver/django-role-booking-system", "src_encoding": "UTF-8", "text": "FROM python:2.7\n\nLABEL maintainer=\"[email protected]\"\n\nRUN apt-get update -qq && apt-get install build-essential g++ flex bison gperf ruby perl \\\n mysql-client \\\n libsqlite3-dev libfontconfig1-dev libicu-dev libfreetype6 libssl-dev \\\n postgresql-client \\\n libpng-dev libjpeg-dev python libx11-dev libxext-dev -y\n\nENV PYTHONUNBUFFERED 1\n\nWORKDIR /opt/django-role-booking-system\n\nADD . .\n\nRUN pip install -r requirements.txt\n\nEXPOSE 8000\n\nCMD [\"python\", \"./mysite/manage.py\", \"runserver\", \"0.0.0.0:8000\"]\n" }, { "alpha_fraction": 0.5808081030845642, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 35, "blob_id": "9907d1b406cc7c8a86df868858b55e46b954b6ba", "content_id": "c32cdd542f2a4122587fde9e2573beb95a19ea40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "no_license", "max_line_length": 106, "num_lines": 11, "path": "/mysite/club/urls.py", "repo_name": "georgedriver/django-role-booking-system", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'club'\nurlpatterns = [\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'(?P<club_id>[0-9]+)/(?P<meeting_id>[0-9]+)/(?P<role_NAME>\\w+)/book/$', views.book, name='book'),\n url(r'^(?P<pk>[0-9]+)/update/$', views.ClubMeetingUpdate.as_view(), name='update'),\n url(r'^vpe/$', views.vpe_page, name='vpe_page'),\n]\n" } ]
4
Ranjith200/python_cybersecurity_project
https://github.com/Ranjith200/python_cybersecurity_project
8fc97cf9584d16796543c7b9ddab55e0860e73df
1fa32ac903dc621527ad06cf91a66e0d0b9ca53d
1d976a1539bbc0868a0bcc4c5e46c6457eceb5eb
refs/heads/main
2023-06-21T15:00:19.821220
2021-07-27T10:04:26
2021-07-27T10:04:26
389,933,927
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4384341537952423, "alphanum_fraction": 0.4555160105228424, "avg_line_length": 34.07692337036133, "blob_id": "fa11ca1538aa0a6b5bcfa817dbf85061ebf1a911", "content_id": "34b4de350804f974b48c9cb905b821a4abb97dc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1405, "license_type": "no_license", "max_line_length": 128, "num_lines": 39, "path": "/project1.py", "repo_name": "Ranjith200/python_cybersecurity_project", "src_encoding": "UTF-8", "text": "import requests,json\r\nfrom datetime import datetime\r\n\r\napi_key=\"dadbb8c1155971ad10ceeff83364e579\"\r\nbase_url=\"http://api.openweathermap.org/data/2.5/weather?\"\r\ncity_name=input(\"Enter city : \")\r\n\r\ncomplete_url=base_url + \"appid=\" + api_key + \"&q=\" + city_name\r\nresponse=requests.get(complete_url)\r\nx=response.json()\r\n\r\ndate_time=datetime.now().strftime(\"%d %b %y\")\r\n\r\nprint(\"-------------------------------------------------------------------------------------------------------------------\")\r\nprint(\"Weather stats for - {} || {}\".format(city_name.upper(),date_time))\r\nprint(\"-------------------------------------------------------------------------------------------------------------------\")\r\n\r\nif x[\"cod\"] != \"404\":\r\n\ty=x[\"main\"]\r\n\tcurrent_temperature=y[\"temp\"]\r\n\tcurrent_pressure=y[\"pressure\"]\r\n\tcurrent_humidity=y[\"humidity\"]\r\n\tz=x[\"weather\"]\r\n\tweather_description=z[0][\"description\"]\r\n\r\n\tprint(\"temperature (in kelvin unit) = \" +\r\n\t\t str(current_temperature) + \" k\" +\r\n\t\t \"\\n Atmospheric pressure (in hpa unit) = \" +\r\n\t\t str(current_pressure) + \" hpa\" +\r\n\t\t \"\\n Humidity (in percentage) = \" +\r\n\t\t str(current_humidity) + \" %\" +\r\n\t\t \"\\n Description = \" +\r\n\t\t str(weather_description))\r\n\r\n\r\nelse:\r\n\tprint(\"City Not Found!!! \")\r\n\r\nprint(\"=======================================================================================================================\")" } ]
1
JustusW/martyrbuild
https://github.com/JustusW/martyrbuild
a925d0026c5b7ed135645739b9913932c598fc1e
1fe50517cdbc20d52a06b1803412af9b59a7d81d
129080e242b6929963cd6e5e28f9867a6acb8878
refs/heads/master
2020-03-22T12:46:55.266191
2018-08-04T09:55:16
2018-08-04T09:55:16
140,061,909
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.42239028215408325, "alphanum_fraction": 0.4279981553554535, "avg_line_length": 31.806957244873047, "blob_id": "efaaee02cec1347b96d3db8b83be4800e5863fc6", "content_id": "96599632a6ebf40269fb3377e219f9e01587ea69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 19437, "license_type": "permissive", "max_line_length": 136, "num_lines": 575, "path": "/js/martyr.app.js", "repo_name": "JustusW/martyrbuild", "src_encoding": "UTF-8", "text": "angular.module('MartyrSkillEditor', ['angular.filter'])\r\n .filter('unsafe', function($sce) {\r\n return function(val) {\r\n return $sce.trustAsHtml(val);\r\n };\r\n })\r\n .filter('urlencode', function() {\r\n return function(input) {\r\n return window.encodeURIComponent(input);\r\n }\r\n })\r\n .controller('SkillSelectorController', function($scope, $location) {\r\n var ssc = this;\r\n ssc.description = {\r\n x: 0,\r\n y: 0,\r\n show: false,\r\n title: '',\r\n description: ''\r\n };\r\n \r\n ssc.perks = [{}, {}, {}];\r\n ssc.currentCount = 0;\r\n ssc.currentHash = '';\r\n ssc.fullLink = '';\r\n \r\n var langCache = {};\r\n\r\n function union_arrays (x, y) {\r\n var obj = {};\r\n for (var i = x.length-1; i >= 0; -- i)\r\n obj[x[i]] = x[i];\r\n for (var i = y.length-1; i >= 0; -- i)\r\n obj[y[i]] = y[i];\r\n var res = []\r\n for (var k in obj) {\r\n if (obj.hasOwnProperty(k)) // <-- optional\r\n res.push(obj[k]);\r\n }\r\n return res;\r\n }\r\n\r\n function replaceEffect(input, name, value, scale) {\r\n if (!scale) scale = 1;\r\n var search = new RegExp('{' + name + '[^}]*}', 'g')\r\n var matches = input.match(search);\r\n \r\n if (isNaN(value)) {\r\n if (matches) {\r\n input = input.replace(matches[0], value);\r\n }\r\n } else {\r\n \r\n value = value * scale;\r\n if (-1 < value && value < 1) {\r\n value = Math.round(value * 1000) / 10. + '%';\r\n }\r\n if (matches) {\r\n input = input.replace(matches[0], value);\r\n }\r\n }\r\n return input;\r\n }\r\n\r\n function getLangContainer(search) {\r\n for (name in lang) {\r\n var result = lang[name].getElementsByTagName(search);\r\n if (result.length == 1) {\r\n return result[0];\r\n }\r\n }\r\n for (name in lang) {\r\n var result = $(lang[name]).find('*').filter(function(index,elm) {\r\n return elm.nodeName.toLowerCase() == search.toLowerCase();\r\n });\r\n if (result.length == 1) {\r\n return result[0];\r\n }\r\n if (result.length >= 1) {\r\n for (r in result) {\r\n if (result[r].children.length > 0)\r\n return result[r];\r\n };\r\n }\r\n }\r\n }\r\n\r\n function decorateLang(string) {\r\n return string.split('[ff2bede6]').join('<b class=\"text-danger\">').split('[/ff2bede6]').join('</b>').split('\\\\n').join('\\n');\r\n }\r\n\r\n function getLang(search) {\r\n search = search.toLowerCase();\r\n if (langCache[search]) return langCache[search];\r\n \r\n container = getLangContainer(search);\r\n var result = {name: search};\r\n if (!container) {\r\n langCache[search] = result;\r\n return result;\r\n }\r\n \r\n for (child in container.children) {\r\n c = container.children[child];\r\n if (c.nodeType != 1) continue;\r\n \r\n if (c.nodeName == 'eng') {\r\n value = c.innerHTML;\r\n result['name'] = decorateLang(value);\r\n } else {\r\n var name = c.nodeName.toLowerCase();\r\n if (name.startsWith('desc')) name = 'desc';\r\n value = c.children[0].innerHTML;\r\n result[name] = decorateLang(value);\r\n }\r\n }\r\n langCache[search] = result;\r\n return result;\r\n }\r\n\r\n\r\n function getSpellLang(spell, lng) {\r\n \r\n var name = spell;\r\n var langData = getLang(name);\r\n \r\n if (langData.name == name.toLowerCase()) {\r\n return [name, null];\r\n }\r\n \r\n var engDescription,engName;\r\n if (langData.desc)\r\n engDescription = langData.desc;\r\n if (langData.name)\r\n engName = langData.name;\r\n \r\n engDescription = decorateLang(engDescription);\r\n \r\n return [engName, engDescription];\r\n }\r\n \r\n function getCategoryLang(cat) {\r\n var name = cat;\r\n var langData = getLang(name);\r\n \r\n if (langData.name == name.toLowerCase()) {\r\n return [null,null,null];\r\n }\r\n \r\n var engDescription,engName, engCategory;\r\n if (langData.desc)\r\n engDescription = langData.desc;\r\n if (langData.name)\r\n engName = langData.name;\r\n if (langData.category)\r\n engCategory = langData.category;\r\n \r\n engDescription = decorateLang(engDescription);\r\n \r\n return [engDescription, engName, engCategory];\r\n }\r\n \r\n function getSkillLang(skill, scale) {\r\n var name = skill.Skill;\r\n \r\n var langData = getLang(name);\r\n \r\n var engDescription = 'If you can read this, something is broken. ' + name, engName = '';\r\n \r\n if (langData.desc)\r\n engDescription = langData.desc;\r\n if (langData.name && langData.name != name.toLowerCase())\r\n engName = langData.name;\r\n \r\n var skillData = data[name];\r\n var effect = skillData.Effect;\r\n var bonus_effect = skillData.BonusEffect;\r\n \r\n if (effect) {\r\n engDescription = replaceEffect(engDescription, effect.property, effect.value, scale);\r\n }\r\n if (bonus_effect) {\r\n engDescription = replaceEffect(engDescription, bonus_effect.property, bonus_effect.value, scale);\r\n }\r\n \r\n engDescription = decorateLang(engDescription);\r\n \r\n return [engDescription, engName];\r\n }\r\n \r\n function getEnchantLang(enchant) {\r\n var name = enchant.NameID[0];\r\n \r\n var langData = getLang(name);\r\n \r\n var engDescription = 'If you can read this, something is broken. ' + name, engName = '';\r\n \r\n if (langData.desc)\r\n engDescription = langData.desc;\r\n if (langData.name && langData.name != name.toLowerCase())\r\n engName = langData.name;\r\n \r\n if (enchant.Property) {\r\n var value = enchant.Values.slice(-1)[0].replace('(','').replace(')','').split(';')[1];\r\n engDescription = replaceEffect(engDescription, enchant.Property[0], value);\r\n if (['ability_offensive', 'ability_survival', 'ability_special'].indexOf(enchant.Property[0]) > -1) {\r\n engDescription = replaceEffect(engDescription, 'ability', enchant.Property[0]);\r\n }\r\n }\r\n \r\n engDescription = decorateLang(engDescription);\r\n \r\n return {desc: engDescription, name: engName};\r\n }\r\n \r\n function getSkill(row, col) {\r\n var skills = ssc.currentSkills();\r\n for (name in skills) {\r\n var skill = skills[name];\r\n if (skill.col == col && skill[name].row == row) {\r\n return skill;\r\n }\r\n }\r\n }\r\n \r\n ssc.getCategoryLang = getCategoryLang;\r\n ssc.getSkillLang = getSkillLang;\r\n ssc.getSpellLang = getSpellLang;\r\n ssc.getEnchantLang = getEnchantLang;\r\n ssc.getLang = getLang;\r\n \r\n ssc.resetSkills = function () {\r\n for (name in ssc.currentSkills()) {\r\n var s = ssc.currentSkills()[name];\r\n if (s.selected) s.selected = false;\r\n };\r\n ssc.updateLink();\r\n };\r\n \r\n ssc.resetAllSkills = function () {\r\n for (catName in ssc.currentCategory()) {\r\n for (name in ssc.getSkills(catName)) {\r\n var s = ssc.getSkills(catName)[name];\r\n if (s.selected) s.selected = false;\r\n };\r\n }\r\n ssc.updateLink();\r\n };\r\n \r\n ssc.categoryHasActiveSkills = function (name) {\r\n var cat = ssc.getSkills(name);\r\n for (s in cat) {\r\n if (cat[s].selected) {\r\n return true;\r\n }\r\n }\r\n }\r\n \r\n ssc.categoryActiveSkills = function (name) {\r\n var skills = [];\r\n var cat = ssc.getSkills(name);\r\n for (s in cat) {\r\n if (cat[s].selected) {\r\n skills.push(cat[s]);\r\n }\r\n }\r\n return skills;\r\n }\r\n \r\n ssc.categoryActiveSkillCount = function (name) {\r\n var count = 0;\r\n var cat = ssc.getSkills(name);\r\n for (s in cat) {\r\n if (cat[s].selected) {\r\n count++;\r\n }\r\n }\r\n return count;\r\n }\r\n \r\n ssc.currentCategory = function () {\r\n return data[ssc.currentType];\r\n }\r\n \r\n ssc.currentSkills = function () {\r\n return ssc.getSkills(ssc.currentSkill);\r\n }\r\n \r\n ssc.getSkillsArray = function (tree) {\r\n var out = [];\r\n var obj = ssc.getSkills(tree);\r\n for (name in obj) {\r\n out.push(obj[name]);\r\n }\r\n return out;\r\n }\r\n \r\n ssc.getSkills = function (tree) {\r\n if (ssc.currentCategory())\r\n if (ssc.currentCategory()[tree])\r\n return ssc.currentCategory()[tree].data;\r\n }\r\n \r\n ssc.connectorLineStyle = function (skill, req) {\r\n var x1 = skill.col * 80 + 40;\r\n var y1 = skill.row * 80 + 40;\r\n \r\n var refSkill = ssc.currentSkills()[req];\r\n var x2 = refSkill.col * 80 + 40;\r\n var y2 = refSkill.row * 80 + 40;\r\n \r\n var length = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));\r\n var angle = Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;\r\n \r\n var transform = 'rotate('+angle+'deg)';\r\n\r\n var line = 'transform: ' + transform + ';';\r\n var line = line + 'width: ' + length + 'px;';\r\n var line = line + 'top: ' + y1 + 'px;';\r\n var line = line + 'left: ' + x1 + 'px;';\r\n\r\n return line;\r\n }\r\n \r\n ssc.setRawDescription = function (e, name, lng) {\r\n ssc.description.x = e.pageX;\r\n ssc.description.y = e.pageY;\r\n ssc.description.show = true;\r\n \r\n var lang = getSpellLang(name, lng);\r\n ssc.description.title = lang[0];\r\n ssc.description.description = lang[1];\r\n }\r\n \r\n ssc.setDescription = function (skill, e, cat) {\r\n if (!skill) {\r\n return ssc.description.show = false;\r\n }\r\n ssc.description.x = e.pageX;\r\n ssc.description.y = e.pageY;\r\n ssc.description.show = true;\r\n if (cat) {\r\n var lang = getCategoryLang(skill);\r\n ssc.description.description = lang[0];\r\n ssc.description.title = lang[1];\r\n } else {\r\n var lang = getSkillLang(skill);\r\n ssc.description.description = lang[0];\r\n ssc.description.title = lang[1];\r\n }\r\n };\r\n \r\n ssc.skillRequirementsMet = function (skill) {\r\n return !skill.Requirements || skill.Requirements.findIndex(function (s) {\r\n return s != '' && !ssc.currentSkills()[s].selected;\r\n }) == -1\r\n };\r\n \r\n ssc.updateLink = function () {\r\n var lnk = [ssc.currentType];\r\n for (catName in ssc.currentCategory()) {\r\n for (name in ssc.getSkills(catName)) {\r\n var s = ssc.getSkills(catName)[name];\r\n if (s.selected) lnk.push(catName + ',' + name);\r\n };\r\n }\r\n ssc.currentCount = lnk.length - 1;\r\n ssc.perks.forEach(function (perk) {\r\n if (perk.name) lnk.push(perk.name);\r\n else lnk.push('');\r\n });\r\n ssc.currentHash = lnk.join(';');\r\n \r\n var spells = [];\r\n \r\n ssc.spells.forEach(function (spell) {\r\n if (!spell.triac) {spell.triac = [{},{},{}];}\r\n spells.push([spell.name, spell.triac[0].name, spell.triac[1].name, spell.triac[2].name].join(':'));\r\n });\r\n \r\n var hash = ssc.currentHash + '|||' + JSON.stringify(spells);\r\n $location.hash(hash);\r\n ssc.fullLink = $location.$$absUrl;\r\n };\r\n \r\n ssc.initiateFromLink = function () {\r\n var lnk = $location.hash();\r\n ssc.currentCount = 0;\r\n ssc.currentHash = lnk;\r\n if (lnk == 'parse') {\r\n return extractSkillTreeData();\r\n }\r\n lnk = lnk.split('|||');\r\n lnkArr = lnk[0].split(';');\r\n \r\n ssc.currentType = lnk[0].split(';')[0];\r\n for (catName in ssc.currentCategory()) {\r\n for (name in ssc.getSkills(catName)) {\r\n var s = ssc.getSkills(catName)[name];\r\n s.selected = false;\r\n if (lnkArr.indexOf(catName + ',' + name) > -1) {\r\n s.selected = true;\r\n ssc.currentCount++;\r\n }\r\n };\r\n }\r\n lnkArr.slice(-3).forEach(function (perk, index) {\n for (p in ssc.perkData) {\r\n if (ssc.perkData[p].indexOf(perk) > -1) {\r\n ssc.perks[index].name = perk;\r\n return;\r\n }\r\n }\n });\r\n \r\n if (ssc.currentType == 'Psyker' && lnk[1]) {\r\n var spells = JSON.parse(lnk[1]);\r\n spells.forEach(function (entry, i) {\r\n var spell = ssc.spells[i];\r\n entry = entry.split(':');\r\n spell.name = entry[0];\r\n spell.triac = [{name: entry[1]},{name: entry[2]},{name: entry[3]}];\r\n });\r\n }\r\n };\r\n \r\n ssc.toggleSkill = function (skill) {\r\n if (!ssc.skillRequirementsMet(skill)) {\r\n skill.selected = false;\r\n ssc.updateLink();\r\n return;\r\n }\r\n if (skill.selected) {\r\n for (s in ssc.currentSkills()) {\r\n var cs = ssc.currentSkills()[s];\r\n if (cs.Requirements && cs.selected) {\r\n if (cs.Requirements.findIndex(function (rs) {\r\n var requiredSkill = ssc.currentSkills()[rs];\r\n return cs.selected && skill.name == rs;\r\n }) > -1) {\r\n return;\r\n }\r\n }\r\n }\r\n } else if (ssc.currentCount > 78) {\r\n alert(\"Too many skills selected!\");\r\n return;\r\n }\r\n skill.selected = !skill.selected;\r\n ssc.updateLink();\r\n };\r\n \r\n ssc.selectPerk = function (perk, slot) {\r\n slot.selecting = false;\r\n slot.name = perk;\r\n \r\n ssc.updateLink();\r\n ssc.setDescription();\r\n };\r\n \r\n ssc.selectSpell = function (spell, slot) {\r\n slot.selecting = false;\r\n slot.name = spell.name;\r\n slot.triac = [{}, {}, {}];\r\n \r\n ssc.updateLink();\r\n ssc.setDescription();\r\n };\r\n \r\n ssc.selectRune = function (rune, slot) {\r\n slot.selecting = false;\r\n slot.name = rune;\r\n \r\n ssc.updateLink();\r\n ssc.setDescription();\r\n };\r\n \r\n ssc.spellClasses = ['Biomancy', 'Pyromancy', 'Divination', 'Telekinesis'];\r\n ssc.spells = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];\r\n ssc.enchantData = enchantments.data;\r\n ssc.artifactTypes = [];\r\n ssc.enchantData.forEach(function (enchant) {\r\n ssc.artifactTypes = union_arrays(ssc.artifactTypes, enchant.ArtifactTypes);\r\n });\r\n ssc.spellData = spells.data;\r\n ssc.perkData = perks.data;\r\n \r\n ssc.initiateFromLink();\r\n ssc.ready2Roll = true;\r\n \r\n $scope.$watch('ssc.spells', function () {\r\n ssc.updateLink();\r\n });\r\n var initial = true;\r\n $scope.$watch('ssc.currentType', function () {\r\n ssc.currentSkill = '';\r\n if (!initial) {\r\n ssc.perks.forEach(function (perk) {\r\n perk.name = '';\r\n });\r\n }\r\n ssc.updateLink();\r\n initial = false;\r\n });\r\n $scope.$watch('ssc.currentCategory', function () {\r\n window.scrollTo(0,0);\r\n ssc.updateLink();\r\n });\r\n $scope.$watch('ssc.currentSkill', function () {\r\n window.scrollTo(0,0);\r\n ssc.updateLink();\r\n });\r\n \r\n $scope.$on('$locationChangeSuccess', function (e) {\r\n if($location.hash() != ssc.currentHash)\r\n ssc.initiateFromLink();\r\n });\r\n \r\n });\r\n\r\n$.ajax({\r\n url: 'gamefiles/Lang_Skilltree.xml', \r\n success: function (result) {\r\n lang.data = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/Lang_Skills.xml', \r\n success: function (result) {\r\n lang.skills = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/Lang_Perks.xml', \r\n success: function (result) {\r\n lang.perks = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/Lang_Artifacts.xml', \r\n success: function (result) {\r\n lang.artifacts = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/perks.json', \r\n success: function (result) {\r\n perks.data = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/spells.json', \r\n success: function (result) {\r\n spells.data = result;\r\n },\r\n async: false\r\n});\r\n\r\n$.ajax({\r\n url: 'gamefiles/enchantments.json', \r\n success: function (result) {\r\n enchantments.data = result;\r\n },\r\n async: false\r\n});\r\n" }, { "alpha_fraction": 0.8032786846160889, "alphanum_fraction": 0.8032786846160889, "avg_line_length": 19.33333396911621, "blob_id": "c74351cd8a06e94bf5f1da6db9616256f67ba139", "content_id": "dfe314af9026498d78ac8e39fe603d0bbf1a9145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "no_license", "max_line_length": 45, "num_lines": 3, "path": "/README.md", "repo_name": "JustusW/martyrbuild", "src_encoding": "UTF-8", "text": "# martyrbuild\n\nCommunity built system for all things Martyr.\n" }, { "alpha_fraction": 0.4447585344314575, "alphanum_fraction": 0.44805654883384705, "avg_line_length": 27.894365310668945, "blob_id": "52250206b41dd9be55c967d7c86daafbfc79cdfe", "content_id": "6e62f196cc61af08d8f70fea127f040337952b71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4245, "license_type": "no_license", "max_line_length": 78, "num_lines": 142, "path": "/parser/parser.py", "repo_name": "JustusW/martyrbuild", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nfrom pprint import pprint\r\nimport json\r\n\r\n\r\ndef parse_enchants():\r\n file_path = 'gamefiles/artifacts.n2pk'\r\n with open(file_path, 'rb') as f:\r\n active = False\r\n enchantments = []\r\n for line in f.readlines():\r\n line = line.strip()\r\n if line == 'Enchantment':\r\n active = True\r\n enchantment = {}\r\n enchantments.append(enchantment)\r\n if line == '}':\r\n active = False\r\n if not active or line == '' or line.startswith('#'):\r\n continue\r\n \r\n if '=' in line:\r\n name, value = line.split('=', 1)\r\n enchantment[name] = value.split(',')\r\n \r\n with open('gamefiles/enchantments.json', 'w') as f:\r\n f.write(json.dumps(\r\n enchantments, sort_keys=True, indent=4, separators=(',', ': ')\r\n ))\r\n\r\n\r\ndef parse_perks():\r\n file_path = 'gamefiles/data'\r\n with open(file_path, 'rb') as f:\r\n active = False\r\n perks = {}\r\n for line in f.readlines():\r\n line = line.strip()\r\n if line == 'Perks':\r\n active = True\r\n if line == '}':\r\n active = False\r\n if not active or line == '' or line.startswith('#'):\r\n continue\r\n if '=' in line:\r\n name, value = line.split('=', 1)\r\n perks[name] = value.split(',')\r\n \r\n with open('gamefiles/perks.json', 'w') as f:\r\n f.write(json.dumps(\r\n perks, sort_keys=True, indent=4, separators=(',', ': ')\r\n ))\r\n\r\n\r\ndef parse_single_config(data):\r\n out = {\r\n 'action': []\r\n }\r\n for line in data:\r\n if '=' not in line:\r\n continue\r\n try:\r\n target, value = line.strip().split('=', 1)\r\n except ValueError as e:\r\n print line\r\n raise(e)\r\n \r\n if target.startswith('action['):\r\n try:\r\n action_index = int(target[7:8])\r\n except ValueError:\r\n action_index = 0\r\n try:\r\n action = out['action'][action_index]\r\n except IndexError:\r\n action = {}\r\n out['action'].append(action)\r\n \r\n action[target[10:]] = value.split(',')\r\n else:\r\n out[target] = value.split(',')\r\n\r\n return out\r\n\r\n\r\ndef walker(walk_dir = 'gamefiles/psyker/'):\r\n spells = {}\r\n\r\n for root, subdirs, files in os.walk(walk_dir):\r\n\r\n for filename in files:\r\n file_path = os.path.join(root, filename)\r\n\r\n with open(file_path, 'rb') as f:\r\n f_content = f.readlines()\r\n try:\r\n spells[filename] = parse_single_config(f_content)\r\n except OSError as e:\r\n print f_content\r\n raise(e)\r\n \r\n with open('gamefiles/psyker.json', 'w') as f:\r\n f.write(json.dumps(\r\n spells#, sort_keys=True, indent=4, separators=(',', ': ')\r\n ))\r\n\r\n\r\ndef extract_multi_file(target_file='gamefiles/Config/psykerspells.cfg'):\r\n spells = {}\r\n with open(target_file, 'rb') as f:\r\n current_target = ''\r\n for line in f.readlines():\r\n line = line.strip()\r\n if line.startswith('#'):\r\n continue\r\n if line.startswith('}'):\r\n current_target = ''\r\n continue\r\n if line.startswith('{'):\r\n continue\r\n if current_target == '':\r\n current_target = line\r\n spells[current_target] = {'name': line}\r\n continue\r\n \r\n # if current_target.startswith('Force_'):\r\n # continue\r\n \r\n target, value = line.split('=', 1)\r\n spells[current_target][target] = value.split(',')\r\n \r\n with open('gamefiles/spells.json', 'w') as f:\r\n f.write(json.dumps(\r\n spells#, sort_keys=True, indent=4, separators=(',', ': ')\r\n ))\r\n\r\n\r\nwalker()\r\nextract_multi_file()\r\nparse_perks()\r\nparse_enchants()\r\n" } ]
3
fagan2888/Stock-Modeling
https://github.com/fagan2888/Stock-Modeling
b94a84dbf3b842b305605448cfda76926a3fc932
3e6731630fb480a69c42555ec1a2842fda37f391
f5733b077b1beda59df45fe9997fcf33408cfb37
refs/heads/master
2020-12-19T11:43:37.745284
2019-01-09T15:43:40
2019-01-09T15:43:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6020563840866089, "alphanum_fraction": 0.6137279272079468, "avg_line_length": 47.634483337402344, "blob_id": "c505737cbde8663b28fd5baff2ef1094a54dc70a", "content_id": "49b14c12624b7b630615c0f1ed9c26a4fdda202a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7197, "license_type": "no_license", "max_line_length": 127, "num_lines": 145, "path": "/process_reddit.py", "repo_name": "fagan2888/Stock-Modeling", "src_encoding": "UTF-8", "text": "\"\"\"\r\nThis script will process reddit news data downloaded from the Reddit Data Extractor into a csv file.\r\nPerform Sentiment Analysis on it using a separate R script\r\nCollect Stock data from yahoo finance\r\nJoin the sentiment analysis and yahoo finance data together\r\nTo modify data collection edit lines 33 and 41 with different ticker, line 55 with path to news data, 58 with path to \r\nwhere this script is saved, and line 79, 80 to path where Rscript.exe and sentiment_extraction.R are saved\r\nThis script can be run separately w/o Data_Mining_Analysis.py just for the data collection\r\n\"\"\"\r\nimport os\r\nfrom subprocess import call\r\nfrom datetime import datetime\r\nimport time\r\nimport shutil\r\n\r\n\r\n########################################################################################################################\r\n# execute yahoo-finance to get the DJIA data first\r\n# Parameters that can be changed: Stock Ticker and Data Timeframe for Extraction\r\n# Currently set to DJIA and Data for Today\r\ndef get_yahoo_data():\r\n from pandas_datareader import data as pdr\r\n from datetime import datetime, timedelta\r\n import fix_yahoo_finance as yf\r\n yf.pdr_override()\r\n\r\n now = datetime.now()\r\n end_day = now + timedelta(days=1)\r\n\r\n # download dataframe from yahoo (^DJI or BTCUSD=X)\r\n data = pdr.get_data_yahoo(\"^DJI\", start=now.strftime(\"%Y-%m-%d\"), end=end_day.strftime(\"%Y-%m-%d\"))\r\n try:\r\n data['change'] = (data['Close'].values.astype(int) - data['Open'].values.astype(int)) / data['Open'].values.astype(int)\r\n data['change'] = data['change'] * 100\r\n\r\n except KeyError:\r\n import fix_yahoo_finance as yf\r\n yf.pdr_override()\r\n data = pdr.get_data_yahoo(\"^DJI\", start=end_day.strftime(\"%Y-%m-%d\"), end=now.strftime(\"%Y-%m-%d\"))\r\n data['change'] = ((data['Close'].values).astype(int) - (data['Open'].values).astype(int)) / (\r\n data['Open'].values).astype(int)\r\n data['change'] = data['change'] * 100\r\n\r\n return data\r\n\r\n\r\nnew_djia_data = get_yahoo_data()\r\nnew_djia_data = new_djia_data.tail(1)\r\n########################################################################################################################\r\n# re-import pandas to reset the override that is needed for yahoo-finance\r\n# set the path to where the reddit news data is\r\n# set the paths to Rscript.exe from your R build and path to the sentiment_extraction.r file\r\nimport pandas as pd\r\n\r\n# set directory where scripts are\r\nos.chdir(r'E:\\Programming\\Data Science\\')\r\n\r\ndir_name = os.getcwd() + r'\\reddit_data\\worldnews' # change to where the reddit files are\r\ndata_path = os.listdir(dir_name)\r\ndate = time.strftime(\"%Y-%m-%d\")\r\ndf_cols = ['Date', 'News']\r\nmaster_df = pd.DataFrame(columns=df_cols)\r\n\r\n# This chunk process the reddit news data into one master csv file for sentiment analysis ##############################\r\nfor item in data_path:\r\n string = str(item)\r\n if string[-4:] == \".txt\" and len(string) > 10:\r\n news = string.replace('.txt', '')\r\n temp_data = {'Date': date,\r\n 'News': news}\r\n temp_df = pd.DataFrame(temp_data, columns=df_cols, index=[0])\r\n master_df = master_df.append(temp_data, ignore_index=True)\r\n\r\nmaster_df.to_csv('Today_News.csv', encoding='utf-8', index=False, sep=',')\r\n# The above file will be made where this python script is\r\n# The absolute path to this file must be used in the sentiment_extraction.R file (please revise the R file)\r\n\r\nshutil.rmtree(dir_name) # removes all the files collected from the reddit web scraper\r\n########################################################################################################################\r\n# run R script and return new_sentiment_data.csv\r\n# NOTE: param1 = path to Rscript.exe from the R build, param2 is the path to the R file to execute\r\ncall([\"C:/Users/Matt Wilchek/Documents/R/R-3.4.3/bin/Rscript\", \"E:/Programming/Data Science/sentiment_extraction.r\"])\r\n# E:/Programming/Data Mining/GitHub Data Mining Project/GWU-Data-Mining-Proposal-1/sentiment_extraction.r\r\nsentiment = pd.read_csv(\"new_sentiment_data.csv\")\r\nsentiment.drop('Unnamed: 0', axis=1, inplace=True)\r\n########################################################################################################################\r\n# Format DJIA dataframe to original dataset format\r\nnew_djia_data = new_djia_data.reset_index(drop=True)\r\nnow = datetime.now()\r\nnew_djia_data['Date'] = now.strftime(\"%m/%d/%Y\") # 8/8/2008\r\ncols = new_djia_data.columns.tolist()\r\ncols = cols[-1:] + cols[:-1]\r\nnew_djia_data = new_djia_data[cols]\r\n\r\n# Append Sentiment Dataframe columns to DJIA Dataframe columns\r\nnew_djia_data['Anger'] = sentiment['Anger']\r\nnew_djia_data['Anticipation'] = sentiment['Anticipation']\r\nnew_djia_data['Disgust'] = sentiment['Disgust']\r\nnew_djia_data['Fear'] = sentiment['Fear']\r\nnew_djia_data['Joy'] = sentiment['Joy']\r\nnew_djia_data['Sadness'] = sentiment['Sadness']\r\nnew_djia_data['Surprise'] = sentiment['Surprise']\r\nnew_djia_data['Trust'] = sentiment['Trust']\r\nnew_djia_data['Negative'] = sentiment['Negative']\r\nnew_djia_data['Positive'] = sentiment['Positive']\r\n\r\n# Calculate Sentiment Proportions of Original Data\r\nfeat_labels = new_djia_data.columns[8:18]\r\nsentiment_data = new_djia_data.iloc[:, 8:18].values\r\ntemp_df = pd.DataFrame(sentiment_data, columns=feat_labels, index=None)\r\ntemp_list = list()\r\nfor l, n in temp_df.iterrows():\r\n max_sentiment = n.idxmax()\r\n max_sentiment_value = ((n.max(axis=0)).astype(int)).max()\r\n total_values = sum(n)\r\n temp_list.append([str(max_sentiment), max_sentiment_value / total_values])\r\n\r\ntemp_df2 = pd.DataFrame(temp_list, columns=['Max_Sentiment', 'Sentiment_Proportion'], index=None)\r\nnew_djia_data = pd.concat([new_djia_data, temp_df2], axis=1)\r\nnew_djia_data.columns.values[5] = \"Adj.Close\"\r\nnew_djia_data = new_djia_data.reset_index(drop=True)\r\nnew_order = [0, 1, 2, 3, 4, 6, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\r\nnew_djia_data = new_djia_data[new_djia_data.columns[new_order]]\r\n\r\nnew_djia_data.to_csv('new_record.csv', encoding='utf-8', index=False, sep=',')\r\nos.remove('new_sentiment_data.csv') # removes the combined DJIA and sentiment data file\r\n\r\n########################################################################################################################\r\n# Add New Data if it exists to master dataset\r\nnew_record = os.path.exists('new_record.csv')\r\n\r\nif new_record:\r\n df_sentiment_dj = pd.read_csv('DJ_NEWS_SENTIMENT_DATA.csv')\r\n new_record_row = pd.read_csv('new_record.csv')\r\n df_sentiment_dj = df_sentiment_dj.append(new_record_row, ignore_index=True)\r\n df_sentiment_dj = df_sentiment_dj[['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj.Close', 'change', 'Anger',\r\n 'Anticipation', 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise', 'Trust',\r\n 'Negative', 'Positive', 'Max_Sentiment', 'Sentiment_Proportion']]\r\n os.remove('new_record.csv')\r\n\r\n # Update old dataset\r\n os.remove('DJ_NEWS_SENTIMENT_DATA.csv')\r\n df_sentiment_dj.to_csv('DJ_NEWS_SENTIMENT_DATA.csv', encoding='utf-8', index=False, sep=',')\r\n\r\n__author__ = 'Matt Wilchek'\r\n" }, { "alpha_fraction": 0.6964064240455627, "alphanum_fraction": 0.6976456046104431, "avg_line_length": 48.4375, "blob_id": "647630e9bd2b4d0449c034c888ef9d2192b160c1", "content_id": "c1a951876b52f30fc69e03fb4168435f58a562a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 807, "license_type": "no_license", "max_line_length": 132, "num_lines": 16, "path": "/sentiment_extraction.R", "repo_name": "fagan2888/Stock-Modeling", "src_encoding": "UTF-8", "text": "#! /usr/bin/Rscript\r\nrequire(syuzhet)\r\n\r\ntoday_news <- read.csv(\"E:/Programming/Data Science/Today_News.csv\") # CHANGE PATH TO DATA FILE\r\n\r\n#Sentiments words table:\r\nrecords <- as.character(today_news$News)\r\nsentiment <- get_nrc_sentiment(records)\r\n\r\nsent <- cbind(today_news$Date, sentiment)\r\ncolnames(sent)<-c(\"Date\",\"Anger\", \"Anticipation\", \"Disgust\", \"Fear\", \"Joy\", \"Sadness\", \"Surprise\", \"Trust\", \"Negative\", \"Positive\")\r\nsentiment_data <- as.data.frame(colSums(sent[,-1]))\r\nsentiment_df <- do.call(rbind, sentiment_data)\r\ncolnames(sentiment_df)<-c(\"Anger\", \"Anticipation\", \"Disgust\", \"Fear\", \"Joy\", \"Sadness\", \"Surprise\", \"Trust\", \"Negative\", \"Positive\")\r\nwrite.csv(sentiment_df, file = \"E:/Programming/Data Science/new_sentiment_data.csv\")\r\nfile.remove(\"E:/Programming/Data Science/Today_News.csv\")\r\n" }, { "alpha_fraction": 0.7478218674659729, "alphanum_fraction": 0.7633107304573059, "avg_line_length": 59.764705657958984, "blob_id": "7dc9b9a6269a4c4c67f4919dbdc01be2e41a4ba0", "content_id": "5e84a2125e011dd9073ccbe7dd32d73004c7978a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2066, "license_type": "no_license", "max_line_length": 226, "num_lines": 34, "path": "/README.md", "repo_name": "fagan2888/Stock-Modeling", "src_encoding": "UTF-8", "text": "# Predicting the Stock Market\n\nThis is a repo for Predicting stock market data using machine learning with sentiment data on related news.\nBelow are the steps in order to run models:\n\n## Step 1: Web Scrape News Data with Reddit Data Extractor\nThe reddit data extractor can be found here: https://github.com/NSchrading/redditDataExtractor\n\nThis will save text files into a directory of your choosing. The text files will be named with the headlines of the data collected.\n\n## Step 2: Update File references in the following scripts\n\nprocess_reddit.py\n- A. Line 31/40 - change the stock ticker in the first param of 'get_data_yahoo()' to what you need (Note: if the dataframe comes back empty, it means Yahoo has not updated the data yet for the API to collect; try again later)\n- B. Line 57 - change to the directory the reddit news data was saved to\n- C. Line 83 & 84 - change the file paths to where Rscript.exe is from your R build, and the path to the sentiment_extraction.r script saved in this repo\n- D. Line 135, 144, and 145 - change file name to name of stock data collected\n\nsentiment_extraction.R\n- A. Line 4 - change to the file path to where the file 'process_reddit.py' is saved to and append '.../Today_News.csv' to the end\n- B. Line 15 - change path to file made from line 86 in 'process_reddit.py'\n- C. Line 16 - Make sure path to file matches line 4\n\n## Step 3: Execute Stock_Modeling.ipynb\n- This notebook will process the existing stock data collected and joined sentiment data for modeling (e.g. DJ_NEWS_SENTIMENT_DATA.csv)\n- Then it will perform modeling on the High, Low, and Close to create a prediction for today's final stock values and the following day's values.\n- Note: Ensure data read-in for 'data' or 'data_tomorrow' are set to correct locations\n\n### Note:\nThe following Python Build was used in the development: Anaconda 3.6\n\nThe following are also necessary packages for this to work:\n- R: syuzhet\n- Python: numpy, pandas, statsmodels, pandas_datareader, matplotlib, subprocess, sklearn, shutil, fix_yahoo_finance, datetime, csv, os\n" }, { "alpha_fraction": 0.6044423580169678, "alphanum_fraction": 0.6222319006919861, "avg_line_length": 43.29438400268555, "blob_id": "826804a292d57999632c351f05161da8ee76c30d", "content_id": "b73493e56344c540ec6fd6c2670744e2e98d63d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29849, "license_type": "no_license", "max_line_length": 122, "num_lines": 659, "path": "/Stock_Data_Modeling.py", "repo_name": "fagan2888/Stock-Modeling", "src_encoding": "UTF-8", "text": "from __future__ import print_function\r\nimport os\r\nimport csv\r\nimport datetime\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport statsmodels.formula.api as smf\r\nimport statsmodels.api as sm\r\nimport warnings\r\nfrom subprocess import call\r\nfrom datetime import datetime, timedelta\r\nfrom pathlib import Path\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.svm import SVR\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.linear_model import RidgeCV, LinearRegression\r\nfrom sklearn.neural_network import MLPRegressor\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n# Execute script to get new data for today (after reddit web scraping)\r\ncall('python process_reddit.py')\r\nimport pandas as pd\r\n\r\n# Set Console formatting for panda prints\r\npd.set_option('display.height', 1000)\r\npd.set_option('display.max_rows', 10)\r\npd.set_option('display.width', 1000)\r\npd.options.mode.chained_assignment = None\r\n\r\n# **********************************************************************************************************************\r\n# Modeling / Prepare Data\r\ndata = pd.read_csv('https://raw.githubusercontent.com/mwilchek/Stock-Modeling/master/DJ_NEWS_SENTIMENT_DATA.csv')\r\ndata['Cycle_Change'] = data.Max_Sentiment.eq(data.Max_Sentiment.shift())\r\ndummies = pd.get_dummies(data.Cycle_Change)\r\ndata = data.join(dummies)\r\ndata_tomorrow = pd.read_csv('https://raw.githubusercontent.com/mwilchek/Stock-Modeling/master/DJ_NEWS_SENTIMENT_DATA.csv')\r\n\r\n# Move certain columns up by one row for data_tomorrow\r\ndata_tomorrow.Anger = data_tomorrow.Anger.shift(+1)\r\ndata_tomorrow.Anticipation = data_tomorrow.Anticipation.shift(+1)\r\ndata_tomorrow.Disgust = data_tomorrow.Disgust.shift(+1)\r\ndata_tomorrow.Fear = data_tomorrow.Fear.shift(+1)\r\ndata_tomorrow.Joy = data_tomorrow.Joy.shift(+1)\r\ndata_tomorrow.Sadness = data_tomorrow.Sadness.shift(+1)\r\ndata_tomorrow.Surprise = data_tomorrow.Surprise.shift(+1)\r\ndata_tomorrow.Trust = data_tomorrow.Trust.shift(+1)\r\ndata_tomorrow.Negative = data_tomorrow.Negative.shift(+1)\r\ndata_tomorrow.Positive = data_tomorrow.Positive.shift(+1)\r\ndata_tomorrow.Max_Sentiment = data_tomorrow.Max_Sentiment.shift(+1)\r\ndata_tomorrow.Sentiment_Proportion = data_tomorrow.Sentiment_Proportion.shift(+1)\r\n\r\n# Delete the first row of data_tomorrow\r\ndata_tomorrow.drop(data_tomorrow.head(1).index, inplace=True)\r\n\r\ntrain_data = data[:-1] # train data\r\ntoday_record = data.tail(1) # test data (validate current day and predict from following day)\r\n\r\n# Get train data's most recent date of data\r\ntrain_date_to = today_record['Date'].values\r\ntrain_date_to = datetime.strptime(train_date_to[0], '%m/%d/%Y') - timedelta(days=1)\r\ntrain_date_to = train_date_to.strftime(\"%m/%d/%Y\")\r\n\r\ntrain_data_tomorrow = data_tomorrow[:-1] # train data\r\ntomorrow_record = data_tomorrow.tail(1) # test data (validate current day and predict from following day)\r\ndata.tail(n=5)\r\n\r\n\r\n########################################################################################################################\r\n# TODAY: Local method to identify most significant feature in dataset compared to y\r\ndef identify_sig_feature_4_today(y_variable, graph_data):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # Split Data Into X, which are ALL the features\r\n x = data.iloc[:, 9:18].values\r\n\r\n # Split Data Into y, which are the associated targets/classifications; looking at Volume\r\n y = data[np.unicode(y_variable)].values\r\n\r\n # Get the Column Names for Sentiment, Ignore Index\r\n feat_labels = data.columns[9:19]\r\n\r\n # Randomly choose 20% of the data for testing; want a large train set (set random_state as 0)\r\n X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)\r\n\r\n # Declare the StandardScaler\r\n std_scaler = StandardScaler()\r\n\r\n # Standardize the features in the training data\r\n X_train = std_scaler.fit_transform(X_train)\r\n\r\n # Standardize the features in testing data\r\n X_test = std_scaler.transform(X_test)\r\n\r\n # Start The Random Forest Regressor\r\n treereg = RandomForestRegressor(n_estimators=100, max_depth=11, random_state=0)\r\n\r\n # Execute The Data With The Random Forest Regressor\r\n treereg.fit(X_train, y_train)\r\n\r\n print('The ' + str(y_variable) + ' accuracy of the random forest for today sentiment is: ' + str(\r\n treereg.score(X_test, y_test)))\r\n\r\n # Get The Important Features From The Regressor\r\n importances = treereg.feature_importances_\r\n\r\n # Sort The Features By The Most Important\r\n indices = np.argsort(importances)[::-1]\r\n\r\n # Return data\r\n df_cols = ['Sentiment', 'Importance']\r\n master_df = pd.DataFrame(columns=df_cols)\r\n\r\n for f in range(x.shape[1]):\r\n sentiment = feat_labels[f]\r\n importance = importances[indices[f]]\r\n temp_data = {'Sentiment': sentiment,\r\n 'Importance': importance}\r\n master_df = master_df.append(temp_data, ignore_index=True)\r\n\r\n highest_sentiment = master_df['Sentiment'].iloc[0]\r\n highest_importance = master_df['Importance'].iloc[0]\r\n\r\n if graph_data == \"TRUE\":\r\n # Output Data As A Plot for Overall Data set\r\n plt.title('Today Feature Importances ' + np.unicode(y_variable))\r\n plt.bar(range(x.shape[1]), importances[indices], color='lightblue', align='center')\r\n plt.xticks(range(x.shape[1]), feat_labels, rotation=90)\r\n plt.xlim([-1, x.shape[1]])\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n return highest_sentiment, highest_importance\r\n\r\n\r\n########################################################################################################################\r\n# TOMORROW: Local method to identify most significant feature in dataset compared to y\r\ndef identify_sig_feature_4_tomorrow(y_variable, graph_data):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # Split Data Into X, which are ALL the features\r\n x = data_tomorrow.iloc[:, 9:18].values\r\n\r\n # Split Data Into y, which are the associated targets/classifications; looking at Volume\r\n y = data_tomorrow[np.unicode(y_variable)].values\r\n\r\n # Get the Column Names for Sentiment, Ignore Index\r\n feat_labels = data_tomorrow.columns[9:19]\r\n\r\n # Randomly choose 20% of the data for testing; want a large train set (set random_state as 1)\r\n X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=1)\r\n\r\n # Declare the StandardScaler\r\n std_scaler = StandardScaler()\r\n\r\n # Standardize the features in the training data\r\n X_train = std_scaler.fit_transform(X_train)\r\n\r\n # Standardize the features in testing data\r\n X_test = std_scaler.transform(X_test)\r\n\r\n # Start The Random Forest Regressor\r\n treereg = RandomForestRegressor(n_estimators=100, max_depth=11, random_state=1)\r\n\r\n # Execute The Data With The Random Forest Regressor\r\n treereg.fit(X_train, y_train)\r\n\r\n print('The ' + str(y_variable) + ' accuracy of the random forest for tomorrow sentiment is: ' + str(\r\n treereg.score(X_test, y_test)))\r\n\r\n # Get The Important Features From The Regressor\r\n importances = treereg.feature_importances_\r\n\r\n # Sort The Features By The Most Important\r\n indices = np.argsort(importances)[::-1]\r\n\r\n # Return data\r\n df_cols = ['Sentiment', 'Importance']\r\n master_df = pd.DataFrame(columns=df_cols)\r\n\r\n for f in range(x.shape[1]):\r\n sentiment = feat_labels[f]\r\n importance = importances[indices[f]]\r\n temp_data = {'Sentiment': sentiment,\r\n 'Importance': importance}\r\n master_df = master_df.append(temp_data, ignore_index=True)\r\n\r\n highest_sentiment = master_df['Sentiment'].iloc[0]\r\n highest_importance = master_df['Importance'].iloc[0]\r\n\r\n if graph_data == \"TRUE\":\r\n # Output Data As A Plot for Overall Data set\r\n plt.title('Tomorrow Feature Importances ' + np.unicode(y_variable))\r\n plt.bar(range(x.shape[1]), importances[indices], color='lightblue', align='center')\r\n plt.xticks(range(x.shape[1]), feat_labels, rotation=90)\r\n plt.xlim([-1, x.shape[1]])\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n return highest_sentiment, highest_importance\r\n\r\n\r\n########################################################################################################################\r\n# Local method to correctly retrieve appropriate paramters for Regularized Fit Regression based on Ridge Regression\r\ndef get_fit_regression_params(significant_sentiment, target_variable, sentiment_value):\r\n warnings.filterwarnings(\"ignore\")\r\n\r\n # Define the data needed for this section, and as defined by highest_sentiment\r\n x = data[significant_sentiment].values.reshape(-1, 1)\r\n\r\n y = data[np.unicode(target_variable)].values # used to be just data.High\r\n\r\n # Standardize features\r\n scaler = StandardScaler()\r\n x_std = scaler.fit_transform(x)\r\n\r\n # Create ridge regression with alpha values from .1 to 10.0, in increments of 0.1\r\n regr_cv = RidgeCV(alphas=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0,\r\n 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0,\r\n 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0,\r\n 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 3.0,\r\n 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5.0,\r\n 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6.0,\r\n 6.1, 6.2, 6.3, 6.4, 6.5, 6.6, 6.7, 6.8, 6.9, 7.0,\r\n 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7, 7.8, 7.9, 8.0,\r\n 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9.0,\r\n 9.1, 9.2, 9.3, 9.4, 9.5, 9.6, 9.7, 9.8, 9.9, 10.0])\r\n\r\n # Place x and y variables in the proper format for model_cv.\r\n y = np.array(y)\r\n x_std = x_std.reshape((len(y), 1))\r\n y = y.reshape((len(y), 1))\r\n\r\n # Determine the best alpha value to use.\r\n model_cv = regr_cv.fit(x_std, y)\r\n alpha_val_today = model_cv.alpha_\r\n\r\n # Set the L1 value based on significant_sentiment_value\r\n if sentiment_value >= 0.7:\r\n weight_value = 0.4\r\n elif sentiment_value >= 0.4:\r\n weight_value = 0.5\r\n else:\r\n weight_value = 0.6\r\n\r\n return alpha_val_today, weight_value\r\n\r\n\r\n########################################################################################################################\r\n# Local method to get Margin of Error\r\ndef get_change(current, previous):\r\n if current == previous:\r\n return 100.0\r\n try:\r\n return (abs(current - previous) / previous) * 100.0\r\n except ZeroDivisionError:\r\n return 0\r\n\r\n########################################################################################################################\r\n# MODELING EXPLORATION #################################################################################################\r\n# Testing best model for f(x) = Close ~ Features\r\n\r\n# Get Feature values\r\nx = data[['Open', 'High', 'Low', False, True]].values\r\n\r\n# Get Target values\r\ny = data['Close'].values\r\n\r\nregression_models = {'lr': LinearRegression(n_jobs=-1),\r\n 'mlp': MLPRegressor(random_state=0),\r\n 'dt': DecisionTreeRegressor(random_state=0),\r\n 'rf': RandomForestRegressor(random_state=0, n_jobs=-1),\r\n 'svr': SVR(max_iter=-1)}\r\n\r\npipe_regrs = {}\r\n\r\n# Create list of pipeline models to test with that standardize the data\r\nfor name, regression_models in regression_models.items():\r\n pipe_regrs[name] = Pipeline([('StandardScaler', StandardScaler()), ('regr', regression_models)])\r\n\r\nparam_grids = {}\r\n\r\n# Linear Regression Parameter Options:\r\nparam_grid = [{'regr__normalize': [\"True\"]},\r\n {'regr__normalize': [\"False\"]}]\r\n\r\n# Add Linear Regression Parameters to dictionary grid\r\nparam_grids['lr'] = param_grid\r\n\r\n# MLP Parameter Options:\r\nalpha_range = [10 ** i for i in range(-4, 5)]\r\n\r\nparam_grid = [{'regr__hidden_layer_sizes': [10, 100, 200]}]\r\n\r\n# Add Multi-layer Perceptron Parameters to dictionary grid\r\nparam_grids['mlp'] = param_grid\r\n\r\n# Decision Tree Regression Parameter Options:\r\nparam_grid = [{'regr__criterion': ['mse', 'mae'],\r\n 'regr__min_samples_split': [2, 6, 10],\r\n 'regr__min_samples_leaf': [1, 6, 10],\r\n 'regr__max_features': ['auto', 'sqrt', 'log2']}]\r\n\r\n# Add Decision Tree Parameters to dictionary grid\r\nparam_grids['dt'] = param_grid\r\n\r\n# Random Forest Regression Parameter Options:\r\nparam_grid = [{'regr__n_estimators': [10, 100],\r\n 'regr__criterion': ['mse', 'mae'],\r\n 'regr__min_samples_split': [2, 6, 10],\r\n 'regr__min_samples_leaf': [1, 6, 10],\r\n 'regr__max_features': ['auto', 'sqrt', 'log2']}]\r\n\r\n# Add Random Forest Parameters to dictionary grid\r\nparam_grids['rf'] = param_grid\r\n\r\n# Support Vector Machine (SVM) Parameter Options:\r\nparam_grid = [{'regr__C': [0.1, 1, 10],\r\n 'regr__gamma': [0.1, 1, 10],\r\n 'regr__kernel': ['linear', 'poly', 'rbf', 'sigmoid']}]\r\n\r\n# Add SVM Parameters to dictionary grid\r\nparam_grids['svr'] = param_grid\r\n\r\n# The list of [best_score_, best_params_, best_estimator_]\r\nbest_score_param_estimators = []\r\n\r\n# Scoring Param: https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter\r\n# For each regression\r\nfor name in pipe_regrs.keys():\r\n # GridSearchCV\r\n gs = GridSearchCV(estimator=pipe_regrs[name],\r\n param_grid=param_grids[name],\r\n scoring='neg_mean_squared_error',\r\n n_jobs=1,\r\n cv=None)\r\n print(\"Modeling: \" + str(pipe_regrs[name]))\r\n # Fit the pipeline\r\n gs = gs.fit(x, y)\r\n\r\n # Update best_score_param_estimators\r\n best_score_param_estimators.append([gs.best_score_, gs.best_params_, gs.best_estimator_])\r\n print(\"Modeling Completed - Appending scores...\")\r\n\r\n# Sort best_score_param_estimators in descending order of the best_score_\r\nbest_score_param_estimators = sorted(best_score_param_estimators, key=lambda x: x[0], reverse=True)\r\n\r\n# For each [best_score_, best_params_, best_estimator_]\r\nfor best_score_param_estimator in best_score_param_estimators:\r\n # Print out [best_score_, best_params_, best_estimator_], where best_estimator_ is a pipeline\r\n # Since we only print out the type of classifier of the pipeline\r\n print([best_score_param_estimator[0], best_score_param_estimator[1],\r\n type(best_score_param_estimator[2].named_steps['regr'])], end='\\n\\n')\r\n\r\n# Declare best model from GridSearchCV where normalize set to True is the default parameter\r\nlr = LinearRegression(n_jobs=-1)\r\n\r\n# Fit the model with our data\r\nlr = lr.fit(x, y)\r\n\r\n# Predict on Today Close\r\ntoday_close = today_record[['Open', 'High', 'Low', False, True]].values\r\ny_pred = lr.predict(today_close)\r\n\r\n# Print Results\r\nprint(\"Actual Closing Value: \" + str(today_record['Close'].values[0]))\r\nprint(\"Predicted Closing Value: \" + str(y_pred[0]))\r\n\r\nerror = get_change(y_pred[0], today_record['Close'].values[0])\r\nprint(\"Accuracy error for prediction: \" + str(round(error, 4)) + \"%\")\r\n\r\n#SVR case\r\n# Declare best model from GridSearchCV where normalize set to True is the default parameter\r\nsv = SVR()\r\n\r\n# Fit the model with our data\r\nsv = sv.fit(x, y)\r\n\r\n# Predict on Today Close\r\ntoday_close = today_record[['Open', 'High', 'Low', False, True]].values\r\ny_pred = sv.predict(today_close)\r\n\r\n# Print Results\r\nprint(\"Actual Closing Value: \" + str(today_record['Close'].values[0]))\r\nprint(\"Predicted Closing Value: \" + str(y_pred[0]))\r\n\r\nerror = get_change(y_pred[0], today_record['Close'].values[0])\r\nprint(\"Accuracy error for prediction: \" + str(round(error, 4)) + \"%\")\r\n\r\n# **********************************************************************************************#\r\n# OLS Regression Test\r\n\r\n# Define formula string for Stats-model API\r\nformula = 'Close ~ Open + High + Low + Cycle_Change'\r\n\r\n# Define Training Data\r\ndta = train_data[['Close', 'Open', 'High', 'Low', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Cycle_Change', 'Sentiment_Proportion']].copy()\r\n\r\n# Set the Model\r\nols_today_close_model = smf.ols(formula=formula, data=dta).fit()\r\n\r\n# Print results\r\nprint(ols_today_close_model.summary())\r\n\r\n# Update Model with Regularized Fit to prevent over-fitting; alpha and weight values were set.\r\nolsUpdate_today_close = smf.ols(formula=formula, data=dta).fit_regularized(alpha=10, L1_wt=.6)\r\n\r\nprint(\"Predicting Close value on today's stock using train data up to \" + str(train_date_to) + \": \")\r\n\r\nolsUpdate_today_close_prediction = olsUpdate_today_close.predict(today_record)\r\n\r\nprint(\"Actual Closing Value for: \" + str(today_record['Close'].values[0]))\r\nprint(\"Predicted Closing Value: \" + str(round(olsUpdate_today_close_prediction.values[0], 3)))\r\n\r\n# Show Updated Model\r\nfig = plt.figure(figsize=(12, 8))\r\nfig = sm.graphics.plot_partregress_grid(ols_today_close_model, fig=fig)\r\n# Added try/except to avoid possible duplicate plot issue with graph output\r\ntry:\r\n fig[0]\r\nexcept TypeError:\r\n fig\r\n\r\n# OLS may be the best model; let's tune it\r\n\r\n########################################################################################################################\r\n# MODELING 4 TODAY #####################################################################################\r\n# Prepare formula to predict closing of stock data for today\r\n\r\n# Get the highest sentiment and most significant feature against 'Close' for today\r\nhighest_sentiment1_today, significant_value1_today = identify_sig_feature_4_today(\"Close\", \"False\")\r\n\r\n# Update our 'Close' formula with the most significant feature based on today's data\r\nformula = ('Close ~ Open + High + Low + ' + np.unicode(highest_sentiment1_today))\r\n\r\n# Update our training data for 'Close'\r\ndta = train_data[['Close', 'Open', 'High', 'Low', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Get best regularized fit paramters based on most significant sentiment feature for 'Close' and today.\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment1_today, \"Close\", significant_value1_today)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm1_today = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig1 = plt.figure(figsize=(12, 8))\r\nfig1 = sm.graphics.plot_partregress_grid(lm1_today, fig=fig1)\r\n#fig1\r\n#fig1.savefig('Today_Close_Regression.png')\r\n\r\n# Predicts closing value based on train data and model above\r\ntoday_close_prediction = lm1_today.predict(today_record)\r\n\r\n########################################################################################################################\r\n# Prepare formula to predict High of stock data for today\r\n\r\n# Get the highest sentiment and most significant feature against 'High' for today\r\nhighest_sentiment2_today, significant_value2_today = identify_sig_feature_4_today(\"High\", \"False\")\r\n\r\n# Update our 'High' formula with the most significant feature based on today's data\r\nformula = ('High ~ Open + Close + Low + ' + np.unicode(highest_sentiment2_today))\r\n\r\n# Update our training data for 'High'\r\ndta = train_data[['High', 'Open', 'Close', 'Low', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Get best regularized fit paramters based on most significant sentiment feature for 'High' and today.\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment2_today, \"High\", significant_value2_today)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm2_today = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig2 = plt.figure(figsize=(12, 8))\r\nfig2 = sm.graphics.plot_partregress_grid(lm2_today, fig=fig2)\r\n#fig2\r\n#fig2.savefig('Today_High_Regression.png') # Show Partial regression plot of model\r\n\r\n# Predicts high value based on train data and model above\r\ntoday_high_prediction = lm2_today.predict(today_record)\r\n\r\n########################################################################################################################\r\n# Prepare formula to predict Low of stock data for today\r\n\r\n# Get the highest sentiment and most significant feature against 'Low' for today\r\nhighest_sentiment3_today, significant_value3_today = identify_sig_feature_4_today(\"Low\", \"False\")\r\n\r\n# Update our 'Low' formula with the most significant feature based on today's data\r\nformula = ('Low ~ Open + Close + High + ' + np.unicode(highest_sentiment3_today))\r\n\r\n# Update our training data for 'Low'\r\ndta = train_data[['Low', 'Open', 'Close', 'High', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Get best regularized fit paramters based on most significant sentiment feature for 'Low' and today.\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment3_today, \"Low\", significant_value3_today)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm3_today = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig3 = plt.figure(figsize=(12, 8))\r\nfig3 = sm.graphics.plot_partregress_grid(lm3_today, fig=fig3)\r\n#fig3\r\n#fig3.savefig('Today_Low_Regression.png') # Show Partial regression plot of model\r\n\r\n# Predicts Low value based on train data and model above\r\ntoday_low_prediction = lm3_today.predict(today_record)\r\n\r\nprint(\"The Close value for today's stock is predicted to be: \" + str(today_close_prediction.iloc[0]))\r\nprint(\"The High value for today's stock is predicted to be: \" + str(today_high_prediction.iloc[0]))\r\nprint(\"The Low value for today's stock is predicted to be: \" + str(today_low_prediction.iloc[0]))\r\nprint(\"\")\r\nprint(\"ACTUAL Close value for today: \" + str(today_record['Close'].iloc[0]))\r\nprint(\"ACTUAL High value for today: \" + str(today_record['High'].iloc[0]))\r\nprint(\"ACTUAL Low value for today: \" + str(today_record['Low'].iloc[0]))\r\n\r\n########################################################################################################################\r\n# MODELING 4 NEXT DAY###################################################################################\r\n\r\n# Get the highest sentiment and most significant feature against 'Close' for tomorrow\r\nhighest_sentiment1_tom, significant_value1_tom = identify_sig_feature_4_tomorrow(\"Close\", \"False\")\r\n\r\n# Update our 'Close' formula with the most significant feature based on tomorrow\r\nformula = ('Close ~ Open + High + Low + ' + np.unicode(highest_sentiment1_tom))\r\n\r\n# Update our training data for 'Close'\r\ndta = train_data_tomorrow[['Close', 'Open', 'High', 'Low', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Get best regularized fit paramters based on most significant sentiment feature for 'Close' and tomorrow.\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment1_tom, \"Close\", significant_value1_tom)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm1_tom = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig4 = plt.figure(figsize=(12, 8))\r\nfig4 = sm.graphics.plot_partregress_grid(lm1_tom, fig=fig4)\r\n#fig4\r\n#fig4.savefig('Tomorrow_Close_Regression.png') # Show Partial regression plot of model\r\n\r\n# Predicts closing value based on train data and model above\r\nclose_prediction_tom = lm1_tom.predict(tomorrow_record)\r\n\r\n########################################################################################################################\r\n# Prepare formula to predict High of stock data for tomorrow\r\n\r\n# Get the highest sentiment and most significant feature against 'High' for tomorrow\r\nhighest_sentiment2_tom, significant_value2_tom = identify_sig_feature_4_tomorrow(\"High\", \"False\")\r\n\r\n# Update our 'High' formula with the most significant feature based on tomorrow\r\nformula = ('High ~ Open + Close + Low + ' + np.unicode(highest_sentiment2_tom))\r\n\r\n# Update our training data for 'High'\r\ndta = train_data_tomorrow[['High', 'Open', 'Close', 'Low', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Get best regularized fit paramters based on most significant sentiment feature for 'High' and tomorrow.\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment2_tom, \"High\", significant_value2_tom)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm2_tom = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig5 = plt.figure(figsize=(12, 8))\r\nfig5 = sm.graphics.plot_partregress_grid(lm2_tom, fig=fig5)\r\n#fig5\r\n#fig5.savefig('Tomorrow_High_Regression.png') # Show Partial regression plot of model\r\n\r\n# Predicts high value based on train data and model above\r\nhigh_prediction_tom = lm2_tom.predict(tomorrow_record)\r\n\r\n########################################################################################################################\r\n# Prepare formula to predict Low of stock data for tomorrow\r\n\r\n# Prepare formula to predict Low of stock data for today\r\nhighest_sentiment3_tom, significant_value3_tom = identify_sig_feature_4_tomorrow(\"Low\", \"False\")\r\n\r\n# Update our 'Low' formula with the most significant feature based on tomorrow\r\nformula = ('Low ~ Open + Close + High + ' + np.unicode(highest_sentiment3_tom))\r\n\r\n# Update our training data for 'Low'\r\ndta = train_data_tomorrow[['Low', 'Open', 'Close', 'High', 'Anger', 'Anticipation',\r\n 'Disgust', 'Fear', 'Joy', 'Sadness', 'Surprise',\r\n 'Trust', 'Negative', 'Positive', 'Sentiment_Proportion']].copy()\r\n\r\n# Update our training data for 'Low'\r\nalpha_val, weight_val = get_fit_regression_params(highest_sentiment3_tom, \"Low\", significant_value3_tom)\r\n\r\n# Create a Ordinary Least Squares regression model\r\nlm3_tom = smf.ols(formula=formula, data=dta).fit_regularized(alpha=alpha_val, L1_wt=weight_val)\r\n\r\n# Print regression graph\r\nfig6 = plt.figure(figsize=(12, 8))\r\nfig6 = sm.graphics.plot_partregress_grid(lm3_tom, fig=fig6)\r\n#fig6\r\n#fig6.savefig('Tomorrow_Low_Regression.png') # Show Partial regression plot of model\r\n\r\n# Predicts Low value based on train data and model above\r\nlow_prediction_tom = lm3_tom.predict(tomorrow_record)\r\n\r\nprint(\"The Close value for tomorrow's stock is estimated to be: \" + str(close_prediction_tom.iloc[0]))\r\nprint(\"The High value for tomorrow's stock is estimated to be: \" + str(high_prediction_tom.iloc[0]))\r\nprint(\"The Low value for tomorrow's stock is estimated to be: \" + str(low_prediction_tom.iloc[0]))\r\nprint(\"\")\r\n\r\n# Should We Buy or Sell? :)\r\n\r\nif float(today_close_prediction.iloc[0]) < float(close_prediction_tom.iloc[0]):\r\n print(\"Based on our algorithm, the Closing value for the stock tomorrow will: Increase\")\r\nelse:\r\n print(\"Based on our algorithm, the Closing value for the stock tomorrow will: Decrease\")\r\n\r\nif float(today_high_prediction.iloc[0]) < float(high_prediction_tom.iloc[0]):\r\n print(\"Based on our algorithm, the High value for the stock tomorrow will: Increase\")\r\nelse:\r\n print(\"Based on our algorithm, the High value for the stock tomorrow will: Decrease\")\r\n\r\nif float(today_low_prediction.iloc[0]) < float(low_prediction_tom.iloc[0]):\r\n print(\"Based on our algorithm, the Low value for the stock tomorrow will: Increase\")\r\nelse:\r\n print(\"Based on our algorithm, the Low value for the stock tomorrow will: Decrease\")\r\n\r\n# Record data today data and predictions to analyze accuracy:\r\nwith open('predictions_djia.csv', 'a') as csvfile:\r\n now = datetime.datetime.now()\r\n date = now.strftime(\"%m/%d/%Y\")\r\n names = ['Date', 'Actual Close Today', 'Actual High Today', 'Actual Low Today', 'Predicted Close Today',\r\n 'Predicted High Today', 'Predicted Low Today', 'Predicted Close Tomorrow', 'Predicted High Tomorrow',\r\n 'Predicted Low Tomorrow']\r\n w = csv.DictWriter(csvfile, fieldnames=names, lineterminator='\\n')\r\n w.writerow({'Date': str(date),\r\n 'Actual Close Today': today_record['Close'].iloc[0],\r\n 'Actual High Today': today_record['High'].iloc[0],\r\n 'Actual Low Today': today_record['Low'].iloc[0],\r\n 'Predicted Close Today': today_close_prediction.iloc[0],\r\n 'Predicted High Today': today_high_prediction.iloc[0],\r\n 'Predicted Low Today': today_low_prediction.iloc[0],\r\n 'Predicted Close Tomorrow': close_prediction_tom.iloc[0],\r\n 'Predicted High Tomorrow': high_prediction_tom.iloc[0],\r\n 'Predicted Low Tomorrow': low_prediction_tom.iloc[0]})\r\n\r\n csvfile.close()\r\n\r\n# **********************************************************************************************************************\r\n########################################################################################################################\r\n" }, { "alpha_fraction": 0.5659164190292358, "alphanum_fraction": 0.5756775140762329, "avg_line_length": 42.66666793823242, "blob_id": "fcd749285cc1270544c6b625fcafe2cab43f0f4e", "content_id": "ec87f35ab16d00061309c663423a8e3c0b6dc912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 8708, "license_type": "no_license", "max_line_length": 224, "num_lines": 195, "path": "/Results Dashboard/app.R", "repo_name": "fagan2888/Stock-Modeling", "src_encoding": "UTF-8", "text": "library(shiny)\r\nlibrary(dygraphs)\r\nlibrary(xts)\r\nlibrary(DT)\r\nlibrary(quantmod)\r\nlibrary(shinydashboard)\r\nlibrary(data.table)\r\n\r\n#### Setup Data Source References #############################################################################\r\nDJ_NEWS_SENTIMENT_DATA <- fread(\"https://raw.githubusercontent.com/mwilchek/GWU-Data-Mining-Proposal-1/master/DJ_NEWS_SENTIMENT_DATA.csv\")\r\npredicted_data <- fread(\"https://raw.githubusercontent.com/mwilchek/GWU-Data-Mining-Proposal-1/master/predictions_djia.csv\")\r\ndjia <- data.frame(DJ_NEWS_SENTIMENT_DATA)\r\npredictions <- data.frame(predicted_data)\r\npredictions_show <- data.frame(predicted_data)\r\nlast_prediction <- tail(predictions, 1)\r\nrownames(djia) <- djia$Date\r\nrownames(predictions) <- predictions$Date\r\npredictions$Date <- NULL\r\ndjia$Date <- NULL\r\ndjia <- xts(djia, order.by=as.Date(rownames(djia),\"%m/%d/%Y\"))\r\npredictions <- xts(predictions, order.by=as.Date(rownames(predictions),\"%m/%d/%Y\"))\r\ntoday_record <- tail(djia, 1)\r\n\r\n#### Placeholders for Left Navigation and Associated Icons #####################################################\r\nsidebar <-\r\n dashboardSidebar(\r\n sidebarMenu(\r\n menuItem(\r\n \"Closing Values\",\r\n tabName = \"closing\",\r\n icon = icon(\"bar-chart-o\")\r\n ),\r\n menuItem(\r\n \"Low Values\",\r\n tabName = \"low\",\r\n icon = icon(\"bar-chart-o\")\r\n ),\r\n menuItem(\r\n \"High Values\",\r\n tabName = \"high\",\r\n icon = icon(\"bar-chart-o\")\r\n ),\r\n menuItem(\r\n \"About Dashboard\",\r\n tabName = \"about\",\r\n icon = icon(\"dashboard\")\r\n )\r\n )\r\n )\r\n\r\n#### Content Placeholders for Graphics and Tables for All Tabs ##################################################\r\nbody <- dashboardBody(\r\n tabItems(\r\n # First tab content\r\n tabItem(tabName = \"closing\",\r\n \r\n fluidRow(\r\n \r\n box(title='Closing Price of DJI', width = 12, height = NULL, dygraphOutput(\"plot1\")),\r\n box(\"Note: There is a gap in available data from 7/2/2016 to 11/19/2017\", width = 12, height = NULL),\r\n valueBox(value=round(as.double(last_prediction$Predicted.Close.Tomorrow), digits=2),subtitle=\"Next Business Day Predicted Value\",color = 'green',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(last_prediction$Predicted.Close.Today), digits=2), subtitle = paste(\"Today Predicted Value (\", toString(index(today_record)), \")\"),color = 'blue',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(today_record$Close), digits=2), subtitle = paste(\"Actual Value (\", toString(index(today_record)), \")\"),color = 'yellow',icon=icon(\"dollar\"))\r\n ),\r\n \r\n fluidRow(\r\n h2(\"Historical Predictions\"),\r\n DT::dataTableOutput(\"closeTable\")\r\n )\r\n \r\n ),\r\n # Second tab content\r\n tabItem(tabName = \"low\",\r\n \r\n fluidRow(\r\n \r\n box(title='Lowest Price of DJI', width = 12, height = NULL, dygraphOutput(\"plot2\")),\r\n box(\"Note: There is a gap in available data from 7/2/2016 to 11/19/2017\", width = 12, height = NULL),\r\n valueBox(value=round(as.double(last_prediction$Predicted.Low.Tomorrow), digits=2),subtitle=\"Next Day Predicted Value\",color = 'green',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(last_prediction$Predicted.Low.Today), digits=2), subtitle = paste(\"Today Predicted Value (\", toString(index(today_record)), \")\"),color = 'blue',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(today_record$Low), digits=2), subtitle = paste(\"Actual Value (\", toString(index(today_record)), \")\"),color = 'yellow',icon=icon(\"dollar\"))\r\n ),\r\n \r\n fluidRow(\r\n h2(\"Historical Predictions\"),\r\n DT::dataTableOutput(\"lowTable\")\r\n )\r\n \r\n ),\r\n # Third tab content\r\n tabItem(tabName = \"high\",\r\n \r\n fluidRow(\r\n \r\n box(title='Highest Price of DJI', width = 12, height = NULL, dygraphOutput(\"plot3\")),\r\n box(\"Note: There is a gap in available data from 7/2/2016 to 11/19/2017\", width = 12, height = NULL),\r\n valueBox(value=round(as.double(last_prediction$Predicted.High.Tomorrow), digits=2),subtitle=\"Next Day Predicted Value\",color = 'green',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(last_prediction$Predicted.High.Today), digits=2), subtitle = paste(\"Today Predicted Value (\", toString(index(today_record)), \")\"),color = 'blue',icon=icon(\"dollar\")),\r\n infoBox(title=NULL,value = round(as.double(today_record$High), digits=2), subtitle = paste(\"Actual Value (\", toString(index(today_record)), \")\"),color = 'yellow',icon=icon(\"dollar\"))\r\n ),\r\n \r\n fluidRow(\r\n h2(\"Historical Predictions\"),\r\n DT::dataTableOutput(\"highTable\")\r\n )\r\n \r\n ),\r\n # Fourth tab content\r\n tabItem(tabName = \"about\",\r\n \r\n fluidRow(\r\n box(\"My name is Matt. I'm a graduate student at George Washington University in Data Science that enjoys being creative for data visualization. \r\n I made this dashboard to practice R Shiny Dashboards and show off the prediction results of a python program my project partner and I made. \r\n Our program collects stock data, and runs a sentiment algorithm over related news data for it. Then uses RandomForest to help create a train/test\r\n model to predict the open, high, and low values for the current and following day of that specified stock.\", width = 12, height = NULL),\r\n uiOutput(\"about\")\r\n )\r\n )\r\n \r\n )\r\n)\r\n\r\nui <- dashboardPage(dashboardHeader(title = 'Stock Predictions'), sidebar,body)\r\n\r\nserver <- shinyServer(function(input, output) {\r\n \r\n#### Tables and Graphs Output for Tab 1 ########################################################################## \r\n # Get Graph Timeline of Closing Values\r\n output$plot1 <- renderDygraph({\r\n \r\n # djia[\"DJI.Adjusted\"] <- round(djia$Close, digits = 2)\r\n close <- djia$Close\r\n predicted_close <- predictions$Predicted.Close.Tomorrow\r\n stock_close <- cbind(close, predicted_close)\r\n \r\n dygraph(stock_close) %>%\r\n dySeries(\"Close\", label = \"Actual Close\") %>%\r\n dySeries(\"Predicted.Close.Tomorrow\", label = \"Predicted Close\") %>%\r\n dyOptions(stackedGraph = FALSE) %>%\r\n dyRangeSelector()\r\n })\r\n \r\n output$closeTable = DT::renderDataTable({\r\n predictions_show[,c(\"Date\",\"Actual.Close.Today\",\"Predicted.Close.Today\", \"Predicted.Close.Tomorrow\")]\r\n })\r\n \r\n#### Tables and Graphs Output for Tab 2 ########################################################################## \r\n # Get Graph Timeline of Low Values\r\n output$plot2 <- renderDygraph({\r\n \r\n low <- djia$Low\r\n predicted_low <- predictions$Predicted.Low.Tomorrow\r\n stock_low <- cbind(low, predicted_low)\r\n \r\n dygraph(stock_low) %>%\r\n dySeries(\"Low\", label = \"Actual Low\") %>%\r\n dySeries(\"Predicted.Low.Tomorrow\", label = \"Predicted Low\") %>%\r\n dyOptions(stackedGraph = FALSE) %>%\r\n dyRangeSelector()\r\n })\r\n \r\n output$lowTable = DT::renderDataTable({\r\n predictions_show[,c(\"Date\",\"Actual.Low.Today\",\"Predicted.Low.Today\", \"Predicted.Low.Tomorrow\")]\r\n })\r\n\r\n#### Tables and Graphs Output for Tab 3 ##########################################################################\r\n # Get Graph Timeline of High Values\r\n output$plot3 <- renderDygraph({\r\n \r\n high <- djia$High\r\n predicted_high <- predictions$Predicted.High.Tomorrow\r\n stock_high <- cbind(high, predicted_high)\r\n \r\n dygraph(stock_high) %>%\r\n dySeries(\"High\", label = \"Actual High\") %>%\r\n dySeries(\"Predicted.High.Tomorrow\", label = \"Predicted High\") %>%\r\n dyOptions(stackedGraph = FALSE) %>%\r\n dyRangeSelector()\r\n })\r\n \r\n output$highTable = DT::renderDataTable({\r\n predictions_show[,c(\"Date\",\"Actual.High.Today\",\"Predicted.High.Today\", \"Predicted.High.Tomorrow\")]\r\n })\r\n \r\n#### Tables and Graphs Output for Tab 4 ##########################################################################\r\n \r\n url <- a(\"https://github.com/mwilchek/GWU-Data-Mining-Proposal-1\", href=\"https://github.com/mwilchek/GWU-Data-Mining-Proposal-1\")\r\n output$about <- renderUI({\r\n \r\n tagList(\"To learn more about the project or use our algorithm, go here:\", url)\r\n }) \r\n \r\n})\r\n\r\nshinyApp(ui = ui, server = server) # executes app" } ]
5
nio-blocks/queue
https://github.com/nio-blocks/queue
19dff663b42a25721108a3e94b8f143bd0ca74ba
02df66ec9756639ef9849ed7853d1a19676c8848
b691ba93ed7d09d2d81984a5dcf346515c9973e8
refs/heads/master
2020-04-06T05:26:31.779353
2019-07-25T16:56:24
2019-07-25T16:56:24
27,409,980
0
2
null
2014-12-02T01:54:23
2018-08-17T21:37:28
2019-07-25T16:53:49
Python
[ { "alpha_fraction": 0.739973247051239, "alphanum_fraction": 0.7409759163856506, "avg_line_length": 84.45714569091797, "blob_id": "d64de5205bd87507d8bad798ba4dd35d48f5e22d", "content_id": "c98de60bab237ccb89cd5850de3dbf001b4de627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2994, "license_type": "no_license", "max_line_length": 363, "num_lines": 35, "path": "/README.md", "repo_name": "nio-blocks/queue", "src_encoding": "UTF-8", "text": "Queue\n=====\nThe Queue block will gather incoming signals and emit a configurable 'chunk size' of signals at a configurable 'interval'. If incoming signals would overflow the queue 'capacity', the oldest signals are dropped from the queue and not emitted to the next block.\n\nProperties\n----------\n- **backup_interval**: Period at which queues are backed up to disk using persistance. Queues are also backed up on stop.\n- **capacity**: Size of each queue. When the queue exceeds `capacity`, the oldest signals are dropped from the queue and *not* notified.\n- **chunk_size**: Number of signals to emit at each `interval` or `emit` command.\n- **group_by**: Signal attribute that determines what queue to put the signal in. Defaults to group `null` if attribute does not exist or `group_by` is unspecified.\n- **interval**: Period at which signals are emitted from queues. If `0`, signals will not be emitted only after processing imcoming signals, rather than at an interval. Note: It may be necessary to enable `Auto Reload` for this to work as intended.\n- **load_from_persistence**: If `True`, after stopping the block, the previous state of the block (queue time remaining) will be loaded upon restart.\n- **reload**: If `True`, emitted signals immediately get reloaded back into the end of the queue.\n- **uniqueness**: If specified, each queue (i.e. `group_by`) will not allow multiple signals that evaluate to the same `uniqueness`. If a signal comes in that matches `group_by` and `uniqueness` with a signal already in the queue, then the new signal is dropped from the queue.\n- **update**: If `True` and a uniqueness expression is set, incoming signals that would have been rejected by the uniqueness expression instead replace the signal that was competing with the incoming signal for uniqueness.\n\nInputs\n------\n- **default**: Any list of signals.\n\nOutputs\n-------\n- **default**: List of signals emitted from queues each `interval` period and `emit` command.\n\nCommands\n--------\n- **emit**: Emit signals off the end of the queues.\n- **groups**: Returns a list of the block’s current signal groupings.\n- **remove**: Remove signals from the queue *group* where *query* evaluates to `True`. *Query* uses the Expression Property syntax for evaluatuation. For example, to remove all signals, use `{{True}}` or to remove signals with *val* equal to 1 use `{{$val == 1}}`. If no *group* is specified, then all groups are inspected. Signals are not notified.\n- **update_props**: Modify the value of a property on a started block. Parameter `props` is a dictionary where the `key` is a block property and the `value` is the new value. `interval` is the only property currently supported. When `interval` is updated, the recurring emit job will be cancelled and restarted, even if the new value is equal to the previous one.\n- **view**: View signals in the queue *group*. If *group* is not specified, all signals in all queues are returned. Signals are not notified.\n\nDependencies\n------------\nNone\n\n" }, { "alpha_fraction": 0.5605337023735046, "alphanum_fraction": 0.5622631907463074, "avg_line_length": 36.245399475097656, "blob_id": "652fd62363c708d9ce55fdbee6a8bf0f5618002d", "content_id": "6706e62ae68f783a410e564bdeb0ece720206559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12142, "license_type": "no_license", "max_line_length": 80, "num_lines": 326, "path": "/queue_block.py", "repo_name": "nio-blocks/queue", "src_encoding": "UTF-8", "text": "import json\nfrom collections import defaultdict\nfrom datetime import timedelta\nfrom threading import Lock\n\nfrom nio.block.base import Block\nfrom nio.block.mixins.group_by.group_by import GroupBy\nfrom nio.block.mixins.persistence.persistence import Persistence\nfrom nio.command import command\nfrom nio.command.params.dict import DictParameter\nfrom nio.command.params.string import StringParameter\nfrom nio.modules.scheduler import Job\nfrom nio.properties import IntProperty, BoolProperty, \\\n Property, TimeDeltaProperty, VersionProperty\nfrom nio.properties.util.evaluator import Evaluator\n\n\n@command(\"update_props\", DictParameter(\"props\", default=''))\n@command(\"view\",\n StringParameter(\"query\", default='{{ True }}'),\n StringParameter(\"group\", default=''))\n@command(\"remove\",\n StringParameter(\"query\", default=''),\n StringParameter(\"group\", default=''))\n@command(\"emit\")\nclass Queue(Persistence, GroupBy, Block):\n \"\"\" Queue block.\n\n A NIO block for queueing up signals. As signals pile up,\n the Queue block releases a configurable number at a configurable\n interval. If incoming signals would overflow the queue, signals\n are popped off the front as needed.\n\n If a 'group_by' string is configured, incoming signals are divided\n and grouped by the value of that attribute. The configured capacity\n applies to *each* such queue, not the block as a whole.\n\n \"\"\"\n version = VersionProperty(\"1.0.1\")\n interval = TimeDeltaProperty(title='Notification Interval',\n default={'seconds': 1},\n allow_none=True)\n capacity = IntProperty(default=100, title='Capacity')\n chunk_size = IntProperty(default=1, title='Chunk Size')\n reload = BoolProperty(default=False, title='Auto-Reload?')\n uniqueness = Property(title='Queue Uniqueness Expression',\n allow_none=True,\n default=\"{{ None }}\")\n update = BoolProperty(title='Update Non-Unique Signals', default=False)\n\n def persisted_values(self):\n return [\"_queues\"]\n\n def __init__(self):\n super().__init__()\n self._queues = defaultdict(list)\n self._queue_locks = defaultdict(Lock)\n self._meta_lock = Lock()\n self._emit_job = None\n\n def configure(self, context):\n super().configure(context)\n # Make sure perisisted queue capacity is less than current config\n for queue_name, queue_values in self._queues.items():\n self._queues[queue_name] = queue_values[:self.capacity()]\n # build _groups for groupby mixin\n self._groups = set(self._queues.keys())\n\n def start(self):\n super().start()\n self._start_emit_job()\n\n def stop(self):\n if self._emit_job is not None:\n self._emit_job.cancel()\n super().stop()\n\n def process_signals(self, signals):\n self.logger.debug(\"Processing {} signals\".format(len(signals)))\n self.for_each_group(self._push_group, signals)\n if not self.interval():\n self.emit()\n\n def pop(self, grp):\n ''' Remove the top n signals from the specified queue.\n\n Args:\n grp (str): The queue from which to pop.\n count (int): The number of signals to pop off.\n reload (bool): If True, put popped signals back on queue.\n\n Returns:\n top_n (list): 'Count' signals from the front of the queue.\n\n '''\n count = self.chunk_size()\n reload = self.reload()\n # lock the queue we're popping from\n self.logger.debug(\"pop: {} {} {}\".format(grp, count, reload))\n with self._get_lock(grp):\n # check out the front of the queue\n top_n = self._queues[grp][0:count]\n self.logger.debug(\n \"Removing %d signals from %s_queue\" % (len(top_n), grp))\n self._queues[grp][:] = self._queues[grp][len(top_n):]\n # If reloading, put signal back on queue.\n if reload:\n self.logger.debug(\"Reloading {}_queue\".format(grp))\n self._queues[grp].extend(top_n)\n return top_n\n\n def push(self, signal, grp):\n ''' Add a signal to the back of the queue.\n\n Args:\n signal (Signal): The signal to add.\n grp (str): Group to add signal to.\n\n Returns:\n None\n\n '''\n queue = self._queues[grp]\n\n # check for uniqueness if property is set\n try:\n unique_val = self.uniqueness(signal)\n self.logger.debug(\n \"Testing uniqueness for signal: {}\".format(unique_val))\n except Exception as e:\n unique_val = None\n self.logger.warning(\n \"Uniqueness expression failed. Using value of None.\")\n\n if unique_val is not None:\n for idx, sig in enumerate(queue):\n try:\n sig_val = self.uniqueness(sig)\n except Exception as e:\n sig_val = None\n if sig_val == unique_val:\n self.logger.debug(\n \"Signal {} already in {}_queue\".format(sig_val, grp)\n )\n if self.update():\n queue[idx] = signal\n return\n\n # pop one off the top of that queue if it's at capacity\n if len(queue) == self.capacity():\n self.logger.debug(\n \"Pushing signal and capactity of {}_signal is full: {}\".format(\n grp, self.capacity()\n )\n )\n queue.pop(0)\n\n self.logger.debug(\"Appending signal to {}_queue\".format(grp))\n queue.append(signal)\n\n def _push_group(self, signals, group):\n # lock the queue before appending\n with self._get_lock(group):\n for signal in signals:\n self.push(signal, group)\n\n def _get_lock(self, grp):\n ''' Returns the lock for a particular queue.\n\n Note that we're maintaining a synchronized dictionary of locks\n alongside our dict of queues.\n\n '''\n with self._meta_lock:\n self._queue_locks[grp] = self._queue_locks.get(grp, Lock())\n return self._queue_locks[grp]\n\n def _start_emit_job(self):\n ''' Start job that emits signals from the queue '''\n if self.interval() and self.interval().total_seconds() > 0:\n # only schedule if the interval is a positive number\n self._emit_job = Job(\n self.emit,\n self.interval(),\n True\n )\n\n def emit(self):\n ''' Notify the configured number of signals from the front of the queue.\n\n '''\n signals_to_notify = self.for_each_group(self.pop)\n if signals_to_notify:\n self.logger.debug(\n \"Notifying {} signals\".format(len(signals_to_notify))\n )\n self.notify_signals(signals_to_notify)\n\n def _inspect_group(self, response, group):\n response_group = {'count': 0, 'signals': []}\n query = response.get('query', '{{ True }}')\n ignored_signals = []\n for signal in self._queues.get(group, []):\n try:\n eval = Evaluator(query).evaluate(signal)\n except:\n eval = False\n if eval:\n response_group['signals'].append(\n json.loads(json.dumps(\n signal.to_dict(),\n indent=4, separators=(',', ': '),\n default=str))\n )\n response_group['count'] += 1\n response['count'] += 1\n else:\n ignored_signals.append(signal)\n response['groups'][group] = response_group\n return response, ignored_signals\n\n def view(self, query, group):\n ''' Command to view the signals that are in the queue.\n\n If no group parameter is specified, all queues are returned.\n '''\n self.logger.debug(\"Command: view\")\n response = {}\n response['query'] = query\n response['group'] = group\n response['count'] = 0\n response['groups'] = {}\n\n if group and group in self._queues:\n # if group exists, return only the specified group\n self._view_group(group, response)\n elif not group:\n # if no group is specifed in params return all groups\n self.for_each_group(self._view_group,\n **{'response': response})\n\n return response\n\n def _view_group(self, group, response):\n with self._get_lock(group):\n response, _ = self._inspect_group(response, group)\n\n def remove(self, query, group):\n ''' Remove signals from *group* where *query* is True.\n\n Signals are not notified.\n\n '''\n self.logger.debug(\"Command: remove\")\n response = {}\n response['query'] = query\n response['group'] = group\n response['count'] = 0\n response['groups'] = {}\n\n if group and group in self._queues:\n # if group exists, remove from only only the specified group\n self._remove_from_group(group, response, query)\n elif not group:\n # if no group is specifed in params return all groups\n self.for_each_group(self._remove_from_group,\n **{'response': response, 'query': query})\n return response\n\n def _remove_from_group(self, group, response, query):\n with self._get_lock(group):\n response, signals = self._inspect_group(response, group)\n # signals that don't match the query stay in the queue, but if\n # there are no signals remaining, delete the entire queue.\n if len(signals) > 0:\n self._queues[group] = signals\n else:\n # _queues is a dict with keys that make up the set _groups.\n # These must be kept in sync when removing keys in order to\n # maintain the true state of the block. If these objects are\n # not synced, a \"view\" or \"remove\" command for all groups will\n # show that groups which have previously been expired are still\n # present, due to the for_each_group() call, which uses the\n # _groups set to iterate over the groups.\n self.logger.debug(\"Deleting empty queue {}.\".format(group))\n self._queues.pop(group, None)\n self._groups.remove(group)\n\n def update_props(self, props):\n ''' Updates the *interval* property.\n\n The next scheduled emit job with be canceled and a new repeatable emit\n job is started.\n\n '''\n self.logger.debug(\"Command: update_props\")\n response = {}\n\n if props is None or not isinstance(props, dict):\n response['message'] = \\\n \"'props' needs to be a dictionary: {}\".format(props)\n return response\n\n # Update *interval*.\n interval = props.get('interval')\n if interval and isinstance(interval, dict) and \\\n (interval.get('days') or\n interval.get('seconds') or interval.get('microseconds')):\n days = interval.get('days', 0)\n seconds = interval.get('seconds', 0)\n microseconds = interval.get('microseconds', 0)\n interval = timedelta(days, seconds, microseconds)\n response['interval'] = interval\n response['prev_interval'] = self.interval\n # cancel emit job and restart with new interval\n if self._emit_job is not None:\n self._emit_job.cancel()\n self._start_emit_job()\n self.interval = interval\n self.logger.info(\n 'Interval has been updated to {}'.format(interval))\n elif interval:\n response['message'] = \\\n \"'interval' needs to be a timedelta dict: {}\".format(interval)\n\n return response\n" }, { "alpha_fraction": 0.5132684707641602, "alphanum_fraction": 0.5218367576599121, "avg_line_length": 31.4016170501709, "blob_id": "176f50a97814fa81ed9b1a80755adbf4fa78d897", "content_id": "43167c9e084300695c4ca22f5753d01ab83dccea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12021, "license_type": "no_license", "max_line_length": 76, "num_lines": 371, "path": "/tests/test_queue_block.py", "repo_name": "nio-blocks/queue", "src_encoding": "UTF-8", "text": "from collections import defaultdict\nfrom unittest.mock import MagicMock\n\nfrom nio.testing.block_test_case import NIOBlockTestCase\nfrom nio.signal.base import Signal\nfrom nio.testing.modules.scheduler.scheduler import JumpAheadScheduler\n\nfrom ..queue_block import Queue\n\n\nclass FlavorSignal(Signal):\n def __init__(self, flavor, meta='regular'):\n super().__init__()\n self.flavor = flavor\n self.meta = meta\n\n\nclass TestQueue(NIOBlockTestCase):\n\n def test_emit(self):\n signals = [Signal({})]\n blk = Queue()\n config = {\n \"interval\": {\n \"seconds\": 1\n },\n \"capacity\": 4,\n \"chunk_size\": 1,\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n JumpAheadScheduler.jump_ahead(2)\n\n # queue should be empty and only the input signal should be notified\n self.assertEqual(len(blk._queues[None]), 0)\n self.assert_num_signals_notified(1, blk)\n blk.stop()\n\n def test_negative_interval(self):\n \"\"\" Don't emit signals on any interval when it is negative \"\"\"\n signals = [Signal({})]\n blk = Queue()\n config = {\n \"interval\": {\n \"seconds\": -1\n },\n \"capacity\": 4,\n \"chunk_size\": 1,\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n JumpAheadScheduler.jump_ahead(2)\n\n # signal should still be in the queue, and no signals notified\n self.assertEqual(len(blk._queues[None]), 1)\n self.assert_num_signals_notified(0, blk)\n blk.stop()\n\n def test_zero_interval(self):\n \"\"\" Emit all queued signals on process_signals \"\"\"\n blk = Queue()\n config = {\n \"capacity\": 1,\n \"chunk_size\": 1,\n \"group_by\": \"{{ $group }}\",\n \"interval\": {\n \"seconds\": 0\n },\n \"reload\": True,\n }\n self.configure_block(blk, config)\n blk.start()\n\n blk.process_signals([\n Signal({\"group\": \"a\", \"number\": 1}),\n ])\n self.assertEqual(len(blk._queues), 1)\n self.assert_num_signals_notified(1, blk)\n self.assert_signal_list_notified([\n Signal({\"group\": \"a\", \"number\": 1}),\n ])\n\n blk.process_signals([\n Signal({\"group\": \"a\", \"number\": 2}),\n ])\n self.assertEqual(len(blk._queues), 1)\n self.assert_num_signals_notified(2, blk)\n self.assert_signal_list_notified([\n Signal({\"group\": \"a\", \"number\": 2}),\n ])\n\n blk.process_signals([\n Signal({\"group\": \"b\", \"number\": 1}),\n ])\n self.assertEqual(len(blk._queues), 2)\n self.assert_num_signals_notified(4, blk)\n self.assert_signal_list_notified([\n Signal({\"group\": \"a\", \"number\": 2}),\n Signal({\"group\": \"b\", \"number\": 1}),\n ])\n\n blk.stop()\n\n def test_group_by(self):\n signals = [\n FlavorSignal(None),\n FlavorSignal('apple'),\n FlavorSignal('cherry')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 100,\n \"group_by\": '{{$flavor}}'\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues[None]), 1)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n blk.stop()\n\n def test_full(self):\n signals = [\n FlavorSignal('cherry'),\n FlavorSignal('umami')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 1,\n \"log_level\": \"DEBUG\"\n }\n\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues[None]), 1)\n self.assertEqual(blk._queues[None][0].flavor, 'umami')\n blk.stop()\n\n def test_reload(self):\n signals = [\n FlavorSignal(flavor='apple'),\n FlavorSignal(flavor='cherry')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"seconds\": 1\n },\n \"capacity\": 100,\n \"group_by\": '{{$flavor}}',\n \"reload\": True\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n JumpAheadScheduler.jump_ahead(2.5)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n self.assert_num_signals_notified(4, blk)\n blk.stop()\n\n def test_unique(self):\n signals = [\n FlavorSignal(flavor='apple'),\n FlavorSignal(flavor='cherry', meta='regular'),\n FlavorSignal(flavor='cherry', meta='sour')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 4,\n \"uniqueness\": \"{{$flavor}}\"\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues[None]), 2)\n self.assertEqual(blk._queues[None][1].meta, 'regular')\n blk.stop()\n\n def test_unique_with_default_config(self):\n signals = [\n FlavorSignal(flavor='apple'),\n FlavorSignal(flavor='cherry', meta='regular'),\n FlavorSignal(flavor='cherry', meta='sour')\n ]\n blk = Queue()\n self.configure_block(blk, {})\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues[None]), 3)\n self.assertEqual(blk._queues[None][1].meta, 'regular')\n blk.stop()\n\n def test_unique_with_update(self):\n signals = [\n FlavorSignal(flavor='apple'),\n FlavorSignal(flavor='cherry', meta='regular'),\n FlavorSignal(flavor='cherry', meta='sour')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 4,\n \"uniqueness\": \"{{$flavor}}\",\n \"update\": True\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues[None]), 2)\n self.assertEqual(blk._queues[None][1].meta, 'sour')\n blk.stop()\n\n def test_all(self):\n signals = [\n FlavorSignal(flavor='apple'),\n FlavorSignal(flavor='cherry'),\n FlavorSignal(flavor='cherry'),\n FlavorSignal(flavor='cherry')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"seconds\": 1\n },\n \"capacity\": 2,\n \"group_by\": '{{$flavor}}',\n \"reload\": True,\n \"uniqueness\": \"{{$flavor}}\"\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n JumpAheadScheduler.jump_ahead(2)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n blk.process_signals([FlavorSignal('cherry')])\n self.assertEqual(len(blk._queues['cherry']), 1)\n blk.stop()\n\n def test_view_command(self):\n signals = [\n FlavorSignal(None),\n FlavorSignal('apple'),\n FlavorSignal('cherry')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 100,\n \"group_by\": '{{$flavor}}'\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n # view nothing from all groups\n resp = blk.view('', None)\n self.assertEqual(len(resp['groups'][None]['signals']), 0)\n self.assertEqual(resp['groups'][None]['count'], 0)\n self.assertEqual(resp['count'], 0)\n self.assertEqual(resp['query'], '')\n # viewing only None group is not possible because it becomes 'all'\n resp = blk.view('{{ True }}', None)\n self.assertEqual(len(resp['groups'][None]['signals']), 1)\n self.assertEqual(resp['groups'][None]['count'], 1)\n self.assertEqual(resp['count'], 3)\n self.assertEqual(resp['query'], '{{ True }}')\n # view all groups\n resp = blk.view('{{ True }}', '')\n self.assertEqual(resp['count'], 3)\n self.assertEqual(resp['query'], '{{ True }}')\n self.assertEqual(len(blk._queues[None]), 1)\n self.assertEqual(len(blk._queues['cherry']), 1)\n self.assertEqual(len(blk._queues['apple']), 1)\n blk.stop()\n\n def test_remove_command(self):\n signals = [\n FlavorSignal(None),\n FlavorSignal('apple'),\n FlavorSignal('cherry')\n ]\n blk = Queue()\n config = {\n \"interval\": {\n \"minutes\": 1\n },\n \"capacity\": 100,\n \"group_by\": '{{$flavor}}'\n }\n self.configure_block(blk, config)\n blk.start()\n blk.process_signals(signals)\n\n # don't remove anything from None\n resp = blk.remove('', None)\n self.assertEqual(len(resp['groups'][None]['signals']), 0)\n self.assertEqual(resp['groups'][None]['count'], 0)\n self.assertEqual(resp['count'], 0)\n self.assertEqual(resp['query'], '')\n self.assertEqual(len(blk._queues[None]), 1)\n self.assertTrue(None in blk._groups)\n\n # remove 'apple' group\n resp = blk.remove('{{ True }}', 'apple')\n self.assertEqual(len(resp['groups']['apple']['signals']), 1)\n self.assertEqual(resp['groups']['apple']['count'], 1)\n self.assertEqual(resp['count'], 1)\n self.assertEqual(resp['query'], '{{ True }}')\n self.assertFalse('apple' in blk._groups)\n self.assertFalse('apple' in blk._queues)\n\n # remove everything from all groups\n resp = blk.remove('{{ True }}', '')\n self.assertEqual(resp['count'], 2)\n self.assertEqual(resp['query'], '{{ True }}')\n self.assertEqual(len(blk._queues), 0)\n self.assertEqual(len(blk._groups), 0)\n blk.stop()\n\n def _check_persisted_values(self, blk, persisted_queues):\n blk._load.assert_called_once_with()\n # Make sure queues is a defaultdict\n self.assertEqual(defaultdict, type(blk._queues))\n # Check values of loaded queues\n for queue_name, queue_values in persisted_queues.items():\n self.assertEqual(queue_values[:blk.capacity()],\n blk._queues[queue_name])\n self.assertTrue(queue_name in blk._groups)\n\n def test_load_persistence(self):\n blk = Queue()\n persisted_queues = defaultdict(list, {'a': [1], 'b': [2, 3]})\n\n def side_effect():\n blk._queues = persisted_queues\n blk._load = MagicMock(side_effect=side_effect)\n self.configure_block(blk, {})\n self._check_persisted_values(blk, persisted_queues)\n\n def test_load_persistence_when_capacity_config_shrinks(self):\n blk = Queue()\n persisted_queues = defaultdict(list, {'a': [1], 'b': [2, 3]})\n\n def side_effect():\n blk._queues = persisted_queues\n blk._load = MagicMock(side_effect=side_effect)\n # Use a smaller capacity than is loaded from persistence\n self.configure_block(blk, {\"capacity\": 1})\n self._check_persisted_values(blk, persisted_queues)\n" } ]
3
sagarninave/tweepia-The-Tweet-Exctractor
https://github.com/sagarninave/tweepia-The-Tweet-Exctractor
84984d1781684afc417955cfe7da9989faa0be0d
12a005a23686e340e5e770fba73659339af854a8
ba01a7d84cf6c41f3a93f6603481a1ae2a905dfe
refs/heads/master
2020-04-23T19:58:52.131540
2019-02-19T07:07:06
2019-02-19T07:07:06
171,423,714
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7599999904632568, "alphanum_fraction": 0.7839999794960022, "avg_line_length": 30.25, "blob_id": "bfcf1593b0d457b8fd281158e79d53293fcdd1e3", "content_id": "39415301f3ecf466337bcd29934ae6c5750a20f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/Update tweet.py", "repo_name": "sagarninave/tweepia-The-Tweet-Exctractor", "src_encoding": "UTF-8", "text": "from tweepy import Stream\nfrom tweepy import OAuthHandler\nfrom tweepy.streaming import StreamListener\nimport time\n\n# Consumer keys and access tokens, used for OAuth\nconsumer_key = '7EyzTcAkINVS3T2pb165'\nconsumer_secret = 'a44R7WvbMW7L8I656Y4l'\naccess_token = 'z00Xy9AkHwp8vSTJ04L0'\naccess_token_secret = 'A1cK98w2NXXaCWMqMW6p'\n \n# OAuth process, using the keys and tokens\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n \n# Creation of the actual interface, using authentication\napi = tweepy.API(auth)\n \n# Sample method, used to update a status\napi.update_status('Hello Python Central!')\n" }, { "alpha_fraction": 0.5876840949058533, "alphanum_fraction": 0.6037483215332031, "avg_line_length": 23.09677505493164, "blob_id": "332458f36dee83f163116ba4c272f0acdc4d44e0", "content_id": "6de92b238bb69f4aa28b8c839b434e4b8c168687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 747, "license_type": "no_license", "max_line_length": 67, "num_lines": 31, "path": "/Last 2 Days Tweet.py", "repo_name": "sagarninave/tweepia-The-Tweet-Exctractor", "src_encoding": "UTF-8", "text": "import tweepy\nfrom tweepy import Stream\nfrom tweepy import OAuthHandler\nimport datetime, time\n\nckey=\"GT3xrIN0V85UdqPqUZ4E28egE\"\ncsecret=\"oBzZvyTApKHxP0GSqo9lbRJ1K93CJRIovRN8zdBaic5oANGRvN\"\natoken=\"740635692359950336-4rgBW9g1baTzcvX8rVzBBRbS08KIN39\"\nasecret=\"KgJ0LlsMeKvEIdJblamLN411HNGo3N3FezBHpJvgmu0Xa\"\n\nauth = tweepy.OAuthHandler(ckey, csecret)\nauth.set_access_token(atoken, asecret)\napi = tweepy.API(auth)\n\ndef get_tweets(api,username):\n page =1\n deadend = False\n while True:\n tweets = api.user_timeline(username, page = page)\n\n for tweet in tweets:\n if (datetime.datetime.now() - tweet.created_at).days<2:\n print(tweet.text.encode(\"utf-8\"))\n else:\n deadend = True\n return\n if not deadend:\n page+1\n time.sleep(500)\n \nget_tweets(api,\"narendramodi\")\n" }, { "alpha_fraction": 0.627106249332428, "alphanum_fraction": 0.6322344541549683, "avg_line_length": 28.673913955688477, "blob_id": "75087f542cb8501c8f06d0b58c12326f3895f30f", "content_id": "9c38a3952c6706bb51c4f49b0ed00021ac3d8b72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 162, "num_lines": 46, "path": "/project.py", "repo_name": "sagarninave/tweepia-The-Tweet-Exctractor", "src_encoding": "UTF-8", "text": "import tweepy \nfrom tweepy import Stream\nfrom tweepy import OAuthHandler\nfrom tweepy.streaming import StreamListener\nimport time\n\n# consumer key, consumer secret, access token, access secret.\nckey=\"GT3xrIN0V85UdqPqUZ4E28egE\"\ncsecret=\"oBzZvyTApKHxP0GSqo9lbRJ1K93CJRIovRN8zdBaic5oANGRvN\"\natoken=\"740635692359950336-4rgBW9g1baTzcvX8rVzBBRbS08KIN39\"\nasecret=\"KgJ0LlsMeKvEIdJblamLN411HNGo3N3FezBHpJvgmu0Xa\"\n\nauth = OAuthHandler(ckey, csecret)\nauth.set_access_token(atoken, asecret)\n\nclass listener(StreamListener):\n \n def on_data(self, data):\n tweet = data.split(',\"text\":\"')[1].split('\",\"source')[0]\n print(tweet + \"\\n\")\n savefile = str(time.time()) + \"::\" + tweet\n save = open('twitterDB4.csv', 'a')\n save.write(savefile)\n save.write(\"\\n\\n\")\n save.close()\n return (True)\n \n def mentioned_in_tweet(self):\n mystr=input(\"Enter Name to Find Person Mentioned In Paricular Tweets : \")\n twitterStream = Stream(auth, listener())\n twitterStream.filter(track=[mystr])\n\n def timeline_tweet(self):\n api = tweepy.API(auth)\n public_tweets = api.home_timeline()\n for tweet in public_tweets:\n print(tweet.text)\n\nobj=listener()\noption = int(input('\\n\\t\\t\\tWhich Tweets Would You Like To Read \\n\\t\\t\\t 1. My Timeline Tweets \\n\\t\\t\\t 2. Public Figure Mentioned Tweets\\n\\t\\t\\t >>'))\nif option==1:\n obj.timeline_tweet()\nelif option==2:\n obj.mentioned_in_tweet()\nelse:\n print (\"Invalid Choice\")\n" } ]
3
Bennycwai/d5e_monster
https://github.com/Bennycwai/d5e_monster
89c94af4c79d1c460e37a17f5e06355ad46a1e6f
01af9ea9c956ea65e44ba210593ac1c4823d35bd
dc94097d2e3eb1404edbf2ddd77339f2335a21df
refs/heads/main
2023-02-27T18:25:11.152778
2021-02-10T22:39:59
2021-02-10T22:39:59
335,052,382
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5960327386856079, "alphanum_fraction": 0.5991813540458679, "avg_line_length": 40.2337646484375, "blob_id": "49347b95ba3acc0e4b969d71d54e3ca90abfc990", "content_id": "2c9db3c0b613af215e39c6c9add8c2afd3b7c598", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 174, "num_lines": 77, "path": "/py_functions/gen_func.py", "repo_name": "Bennycwai/d5e_monster", "src_encoding": "UTF-8", "text": "import json\nimport numpy as np\nimport pandas as pd\nimport urllib.request\nfrom PIL import Image\nimport glob\n\ndef read_data(file_location, json_file):\n ## read the monsters from the SRD\n with open('raw_data/srd_5e_monsters.json') as f:\n raw_data = json.load(f)\n \n df = pd.json_normalize(raw_data)\n \n return df\n\ndef read_and_clean(file_location, json_file):\n \n ## read the monsters from jupyter notebook\n df = read_data(file_location, json_file)\n \n ### clean the name column (replacing spaces with '_'s) and break meta into 4 seperate columns\n\n ## get name, lower case and _ between words\n clean_df = pd.DataFrame(df['name'].str.lower().str.replace(' ','_').str.replace('/','_').str.replace('(','_')\n .str.replace(')','_'), columns = ['name'])\n\n ## split the size and type\n clean_df = pd.concat([clean_df,pd.DataFrame(\n pd.DataFrame(\n df['meta'].str.split(', ').tolist()\n , columns = ['creature_info','alignment'])\n ['creature_info'].str.split(' ').tolist()\n , columns = ['size','type'])], axis=1)\n\n ## create alignment column to be split later, first deal with outliers\n clean_df = pd.concat([clean_df,\n pd.DataFrame(pd.DataFrame(\n df['meta'].str.split(', ').tolist()\n , columns = ['creature_info','alignment'])['alignment'])], axis=1)\n when_conditions = [clean_df['alignment'] == 'unaligned',clean_df['alignment'] == 'any', clean_df['alignment'] == 'neutral', clean_df['alignment'] == 'any evil alignment']\n then_statements = ['unaligned unaligned','any any','neutral neutral','any evil']\n clean_df['alignment'] = np.select(when_conditions,then_statements, default=clean_df['alignment'])\n\n ## split the alignment column\n clean_df = pd.concat([clean_df,\n pd.DataFrame(\n clean_df['alignment'].str.split(' ').tolist()\n , columns = ['ethics','moral'])], axis=1)\n clean_df = clean_df.drop(['alignment'], axis = 1)\n\n ## lower case all current columns\n clean_df = clean_df.apply(lambda x: x.astype(str).str.lower())\n\n clean_df = pd.concat([clean_df,df.drop(['name','meta'],axis=1)],axis=1)\n \n \n return clean_df\n\n### define function for saving images into folder\ndef save_img_from_url(x):\n urllib.request.urlretrieve(x['img_url'], \"images/monsters/\"+x['name']+\".jpeg\")\n \n## create function to identify list monsters for to be replaced\ndef check_for_missing(monster_folder, template_folder):\n missing_name_list = []\n \n ## create list of all image names from both folders\n template_list = glob.glob(template_folder+\"*.jpeg\")\n monster_list = glob.glob(monster_folder+\"*.jpeg\")\n \n for monster_index in range(len(monster_list)):\n for template_index in range(len(template_list)):\n if (open(monster_list[monster_index],\"rb\").read() == open(template_list[template_index],\"rb\").read()):\n missing_name_list.append(monster_list[monster_index].split('\\\\')[1].split('.')[0])\n \n return missing_name_list\n\n" }, { "alpha_fraction": 0.7857142686843872, "alphanum_fraction": 0.8035714030265808, "avg_line_length": 27, "blob_id": "a41e0b0fbf569a3f03a5b907f67a3e0cd3d819da", "content_id": "8e4045c952dbc80ff0239300e71a3f0578116421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 56, "license_type": "no_license", "max_line_length": 41, "num_lines": 2, "path": "/README.md", "repo_name": "Bennycwai/d5e_monster", "src_encoding": "UTF-8", "text": "# d5e_monster\n dnd project for monster data exploration\n" } ]
2
arsenomadridabin/Anonymous
https://github.com/arsenomadridabin/Anonymous
5011cc2c1859e3444ffa759e1e69769bdf10474a
94f58169b2acd770e581d32062a9bb67e02ba011
2888a4e712fd1fc3003e762d9a6c9316f287f531
refs/heads/master
2020-03-28T22:52:40.462030
2017-06-20T09:44:26
2017-06-20T09:44:26
94,629,900
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 25.88888931274414, "blob_id": "218ba77092f6be7d6b4497b887ac4b5aae5791f5", "content_id": "779162e7d1374a0a7d055e1cba45bc72606da9fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/stock/views.py", "repo_name": "arsenomadridabin/Anonymous", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .models import Adbl\ndef home(request):\n\treturn render(request,\"index.html\",{})\n\ndef data(request):\n\tlist_data=Adbl.objects.all()\n\tcontext={'list':list_data}\n\treturn render(request,\"data.html\",context)\n\n\n\n\t\n" } ]
1
murilobdio/Atividade1-AED2
https://github.com/murilobdio/Atividade1-AED2
d568c3039f4a6bacbe9ba7b058efdc7400eda1b8
fe7b961bfb54271edfb4f62713448e93e4210712
f2f0d256eaa579060127587d042166a327173610
refs/heads/main
2023-03-26T22:40:20.260789
2021-03-21T21:09:36
2021-03-21T21:09:36
349,865,115
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6866196990013123, "alphanum_fraction": 0.7147887349128723, "avg_line_length": 20.923076629638672, "blob_id": "6556ebb471348544f8bb89ecdbeaf6f104f3edc8", "content_id": "f7aa84a9fab22995502bc3add9bbdce1e56e19be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 39, "num_lines": 13, "path": "/scripts/plotagem_graficos.py", "repo_name": "murilobdio/Atividade1-AED2", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.getcwd())\nimport matplotlib.pyplot as plt\nfrom exercicios import *\n\na= Exercicio2b()\n\nfig,axs = plt.subplots(figsize=(24,12))\naxs.bar(list(a.keys()), a.values())\naxs.margins(0.01)\naxs.set_xlabel('H(k)')\naxs.set_ylabel('Número de colisões')\nplt.show()" }, { "alpha_fraction": 0.7986463904380798, "alphanum_fraction": 0.8121827244758606, "avg_line_length": 21.730770111083984, "blob_id": "41ab12f3cf30a56a3ea3543fb65e0460477719d9", "content_id": "462703aa3e8ad0e3d625b35066dff1e9ed615fbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 608, "license_type": "no_license", "max_line_length": 142, "num_lines": 26, "path": "/README.md", "repo_name": "murilobdio/Atividade1-AED2", "src_encoding": "UTF-8", "text": "# Atividade1-AED2\n\n## Relatório\n\nO relatório do projeto está no diretório principal do git.\n\n## Execução dos códigos\n\nA pasta scripts pode ser importada como uma lib python contendo:\n\nfuncoes_espalhamento.py\n+ EspalhamentoPorDivisao\n+ EspalhamentoPorMultiplicacao\n\nexercicios.py\n+ Exercicio1a\n+ Exercicio1b\n+ Exercicio1c\n+ Exercicio2a\n+ Exercicio2b\n\nOs arquivos print_exercicios.py e plotagem_graficos.py não contém funções porém podem ser executados para visualização das funções anteriores.\n\nPara visualizar todos os exercícios da atividade, basta executar:\n\n`python3 print_exercicios.py`\n" }, { "alpha_fraction": 0.594495415687561, "alphanum_fraction": 0.6458715796470642, "avg_line_length": 20, "blob_id": "96a736c00f43e14147ec6103a9f4080958c037d2", "content_id": "8c289f030963ce55fe5db16cb710bb749ae52b78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 545, "license_type": "no_license", "max_line_length": 31, "num_lines": 26, "path": "/scripts/print_exercicios.py", "repo_name": "murilobdio/Atividade1-AED2", "src_encoding": "UTF-8", "text": "import os, sys\nsys.path.append(os.getcwd())\nfrom exercicios import *\n\nprint(120*'_')\nprint('Exercicio 1.a)')\nExercicio1a()\nprint(120*'_')\nprint('Exercicio 1.b)')\nExercicio1b()\nprint(120*'_')\nprint('Exercicio 1.c)')\nresult = Exercicio1c()\nfor k in result.keys():\n print(k,':',result[k])\nprint(120*'_')\nprint('Exercicio 2.a)')\nresult = Exercicio2a()\nfor k in sorted(result.keys()):\n print(k,':',result[k])\nprint(120*'_')\nprint('Exercicio 2.b)')\nresult = Exercicio2b()\nfor k in sorted(result.keys()):\n print(k,':',result[k])\nprint(120*'_')" }, { "alpha_fraction": 0.46859902143478394, "alphanum_fraction": 0.4975845515727997, "avg_line_length": 28.5, "blob_id": "28ca81d214caf452645cca60b375190f6c2c999b", "content_id": "98caa3cb49bd1ad6eb169f5a35ca96d9d03eeb75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 842, "license_type": "no_license", "max_line_length": 90, "num_lines": 28, "path": "/scripts/funcoes_emparelhamento.py", "repo_name": "murilobdio/Atividade1-AED2", "src_encoding": "UTF-8", "text": "# =============================================================================\n# Funções\n# =============================================================================\nimport os, sys\nsys.path.append(os.getcwd())\nimport numpy as np\nfrom decimal import *\n\n#Função de espalhamento por divisão\ndef EspalhamentoPorDivisao(key, m):\n if m == 0:\n print('Divisão por 0.')\n return 0\n return key % m \n\n#Função de espalhamento por multiplicação\ndef EspalhamentoPorMultiplicacao(key, m, a):\n if a<0 or a>1:\n print('Valor de A inválido.')\n return 0\n \n #Para garantir o arredondamento correto do número resultante da operação (key * a) % 1\n count = 0\n b = a\n while (b % 1 !=0):\n b = b*10\n count = count + 1\n return np.floor(m * round((key * a) % 1, count) +0.000000001)\n\n\n" }, { "alpha_fraction": 0.37775203585624695, "alphanum_fraction": 0.41714948415756226, "avg_line_length": 20.848100662231445, "blob_id": "cb5880775ce7e2344db2143f318f06b8e01143f3", "content_id": "443aac8dd15cea6521cea2073eb12eb3eed86cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1726, "license_type": "no_license", "max_line_length": 87, "num_lines": 79, "path": "/scripts/exercicios.py", "repo_name": "murilobdio/Atividade1-AED2", "src_encoding": "UTF-8", "text": "# =============================================================================\n# Exercicios\n# =============================================================================\nimport os, sys\nsys.path.append(os.getcwd())\nfrom funcoes_emparelhamento import EspalhamentoPorDivisao, EspalhamentoPorMultiplicacao\n\ndef Exercicio1a():\n hk = []\n \n for k in range(0,100):\n hki = EspalhamentoPorDivisao(k, 12)\n if(hki == 3):\n hk.append(k)\n print(k)\n \n return hk\n\ndef Exercicio1b(): \n hk = []\n \n for k in range(0,100):\n hki = EspalhamentoPorDivisao(k, 11)\n if(hki == 3):\n hk.append(k)\n print(k)\n \n return hk \n\ndef Exercicio1c(): \n hk = {}\n hkount = {}\n \n for k in range(0,10000):\n hki = EspalhamentoPorDivisao(k, 97)\n \n if(hki in hk):\n hk[hki].append(k)\n hkount[hki] += 1\n \n else:\n hk[hki] = [k]\n hkount[hki] = 0\n \n return hkount\n\ndef Exercicio2a(): \n hk = {}\n hkount = {}\n \n for k in range(0,500000):\n hki = EspalhamentoPorMultiplicacao(k, 200, 0.62)\n \n if(hki in hk):\n hk[hki].append(k)\n hkount[hki] += 1\n \n else:\n hk[hki] = [k]\n hkount[hki] = 0\n \n return hkount\n\ndef Exercicio2b(): \n hk = {}\n hkount = {}\n \n for k in range(0,500000):\n hki = EspalhamentoPorMultiplicacao(k, 200, 0.61803398875)\n \n if(hki in hk):\n hk[hki].append(k)\n hkount[hki] += 1\n \n else:\n hk[hki] = [k]\n hkount[hki] = 0\n \n return hkount\n" } ]
5
r7z7/bilibili
https://github.com/r7z7/bilibili
489876569306368f1f8a3fe4b4129764faa974b8
37bb6cbc7ee7e03f68fba96a72961baf8ecb2ca5
26f9e3401879b6e439ac4774b7380cfa68fea25b
refs/heads/main
2023-05-13T05:08:55.422398
2021-06-06T01:18:50
2021-06-06T01:18:50
374,242,828
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.8666666746139526, "avg_line_length": 14, "blob_id": "77d90e41248662eb7f08b91023d8bba890d12db8", "content_id": "c13333a0e7b7e04bf78ec2fa676fe96a9a07e2cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 62, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "r7z7/bilibili", "src_encoding": "UTF-8", "text": "# bilibili\n你可以使用此脚本观察指定up主的情况\n" }, { "alpha_fraction": 0.5848214030265808, "alphanum_fraction": 0.6049107313156128, "avg_line_length": 41.66666793823242, "blob_id": "ed126928c4c0f5b06d39da8b6238192ab2bb4d66", "content_id": "41ed6c5527cde4767c38f3a2243f55aed3bdeb7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2008, "license_type": "no_license", "max_line_length": 188, "num_lines": 42, "path": "/bilibili.py", "repo_name": "r7z7/bilibili", "src_encoding": "UTF-8", "text": "#Bilibili爬虫\nimport requests\nimport time\nimport os\n\nwhile True:\n os.system(\"clear\")\n print(\"本次查询时间为: %s\"%time.strftime(\"%Y-%m-%d %H:%M:%S\",time.localtime()))\n print(\"请输入你要查询的UP主的UID: \",end=\"\")\n upuid=str(input()) #你要查询的UP主的UID\n\n url_fans=\"https://api.bilibili.com/x/relation/stat?vmid=\"+upuid+\"&jsonp=jsonp\"\n url_power=\"https://api.bilibili.com/x/ugcpay-rank/elec/month/up?up_mid=\"+upuid\n url_info=\"https://api.bilibili.com/x/space/acc/info?mid=\"+upuid+\"&jsonp=jsonp\"\n url_video=\"https://api.bilibili.com/x/space/arc/search?mid=\"+upuid+\"&pn=1&ps=1&index=1&jsonp=jsonp\"\n\n h={\n \"User-Agent\":\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36\",\n \"Cookie\":\"None\"\n }\n\n r_fans=requests.get(url_fans,headers=h).json()\n r_power=requests.get(url_power,headers=h).json()\n r_info=requests.get(url_info,headers=h).json()\n r_video=requests.get(url_video,headers=h).json()\n upname=r_info['data']['name']\n\n print(\"以下为UP主信息...\")\n print(\"你查询的UP主[%s]目前的粉丝数为%s个,性别:[%s]\"%(upname,r_fans['data']['follower'],r_info['data']['sex']))\n if r_power['code']==0:\n print(\"是否开通充电: 是\")\n else:\n print(\"是否开通充电: 否\")\n print(\"简介: %s\"%r_info['data']['sign'])\n print(\"会员状态: %s\"%r_info['data']['vip']['label']['text'])\n print(\"使用的头像挂件是(为空的话代表没有使用): %s\"%r_info['data']['pendant']['name'])\n print(\"直播间链接[%s],标题[%s]\"%(r_info['data']['live_room']['url'],r_info['data']['live_room']['title']))\n print(\"[%s]目前最新一期视频是:[%s],av号[%s],BV号[%s]\"%(upname,r_video['data']['list']['vlist'][0]['title'],r_video['data']['list']['vlist'][0]['aid'],r_video['data']['list']['vlist'][0]['bvid']))\n print(\"Bilibili认证: %s\"%r_info['data']['official']['title'])\n \n time.sleep(30)\n exit()\n" } ]
2
obiito007/HungBK
https://github.com/obiito007/HungBK
5dd4fb6ac8ca6391b75b073e18d996917db62cc0
d63ed6c463976ffa7ce0bd45214b83066b092d9b
35e1a03662138afee81964751182f3d1f0638e9c
refs/heads/master
2020-09-12T00:53:00.528277
2019-11-17T12:43:29
2019-11-17T12:43:29
222,246,993
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5061095952987671, "alphanum_fraction": 0.523452877998352, "avg_line_length": 42, "blob_id": "44526dbb60c3e440ae1a84274c7b02dedec110b7", "content_id": "856a63a27088cb95a49940dadb672fbf1bdcc42b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2597, "license_type": "no_license", "max_line_length": 168, "num_lines": 59, "path": "/VCS/migrations/0001_initial.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-03 12:08\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='List',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Giaovien', models.CharField(max_length=100)),\n ('Pubkey', models.CharField(max_length=100)),\n ('PubN', models.CharField(max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Taokhoa',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('a', models.FloatField()),\n ('b', models.FloatField()),\n ('Ten', models.CharField(choices=[('Nguyễn Văn A', 'Nguyễn Văn A'), ('Trần Văn B', 'Trần Văn B'), ('Phạm Thị C', 'Phạm Thị C')], max_length=100)),\n ],\n ),\n migrations.CreateModel(\n name='Teach',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('KhoaE', models.FloatField()),\n ('KhoaN', models.FloatField()),\n ('Link', models.TextField(max_length=1000)),\n ('Ghichu', models.CharField(max_length=100)),\n ('MSSV', models.CharField(default='', max_length=25)),\n ],\n ),\n migrations.CreateModel(\n name='Teacher',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Giaovien', models.CharField(choices=[('Nguyễn Văn A', 'Nguyễn Văn A'), ('Trần Văn B', 'Trần Văn B'), ('Phạm Thị C', 'Phạm Thị C')], max_length=1000)),\n ('image', models.ImageField(blank=True, null=True, upload_to='images/%Y/%m/%d/')),\n ('date', models.DateTimeField(auto_now_add=True)),\n ],\n ),\n migrations.CreateModel(\n name='Xac',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Giaovien', models.CharField(choices=[('Nguyễn Văn A', 'Nguyễn Văn A'), ('Trần Văn B', 'Trần Văn B'), ('Phạm Thị C', 'Phạm Thị C')], max_length=1000)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6877358555793762, "alphanum_fraction": 0.6957547068595886, "avg_line_length": 29.299999237060547, "blob_id": "36149908371920a8d3e22e73ec6e65eba4d67907", "content_id": "7cd8f58e1739a0ed9b560f9d1d65981a763278f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "no_license", "max_line_length": 142, "num_lines": 70, "path": "/VCS/forms.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.forms import ModelForm,Textarea\nfrom .models import Taokhoa,Teach,Teacher,List,Xac\nimport re\nfrom django.contrib.auth.models import User\t\nfrom django.core.exceptions import ObjectDoesNotExist \n\nclass TeachForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Teach\n\t\tfields=['KhoaE','KhoaN','Ghichu','MSSV','Link']\n\t\twidgets = {\n\t\t\t'Link':Textarea(attrs={'cols':80,'rows':1})\t\t\n\t\t}\n\t\tlabels = {\n\t\t\t'KhoaE': ('Khóa bí mật'),\n\t\t\t'KhoaN': ('Khóa N'),\n\t\t\t'Link':('Path Image'),\n\t\t}\n\n\nclass TaokhoaForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = Taokhoa\n\t\tfields=['a','b','Ten','MSCB']\n\tdef clean_Ten(self):\n\t\tTen = self.cleaned_data['Ten']\t\t\n\t\tc=List.objects.filter(Giaovien=Ten)\n\t\tif 'Ten' in self.cleaned_data:\n\t\t\tTen = self.cleaned_data['Ten']\n\t\t\tif len(c)==0:\n\t\t\t\treturn Ten\n\t\traise forms.ValidationError('Mật khẩu không hợp lệ')\n \nclass UpForm(forms.ModelForm):\n class Meta:\n model = Teacher\n fields=['image','MSCB']\n\nclass ListForm(forms.ModelForm):\n class Meta:\n model = Xac\n fields=['MSCB']\n\nclass dangnhapForm(forms.Form):\n\tusername = forms.CharField(label='Taikhoan', max_length=30)\n\temail = forms.EmailField(label='Email')\n\tpassword1 = forms.CharField(label='Mật Khẩu',widget=forms.PasswordInput())\n\tpassword2 = forms.CharField(label='Nhập lại Mật Khẩu',widget=forms.PasswordInput())\n\n\tdef clean_password2(self):\n\t\tif 'password1' in self.cleaned_data:\n\t\t\tpassword1 = self.cleaned_data['password1']\n\t\t\tpassword2 = self.cleaned_data['password2'] \n\t\t\tif password1==password2 and password1:\n\t\t\t\treturn password2\n\t\traise forms.ValidationError('Mật khẩu không hợp lệ')\n\t\t\n\tdef clean_username(self):\n\t\tusername = self.cleaned_data['username']\n\t\tif not re.search(r'^\\w+$',username):\n\t\t\traise forms.ValidationError(\"Tên tài khoản có kí tự đặc biệt\")\n\t\ttry:\n\t\t\tUser.objects.get(username=username)\n\t\texcept ObjectDoesNotExist:\n\t\t\treturn username\n\t\traise forms.ValidationError('Tài khoản đã tồn tại')\n\n\tdef save(self):\n\t\tUser.objects.create_user(username=self.cleaned_data['username'], email=self.cleaned_data['email'], password=self.cleaned_data['password1'])" }, { "alpha_fraction": 0.6323529481887817, "alphanum_fraction": 0.6470588445663452, "avg_line_length": 33.25, "blob_id": "73649dc64054cc2ca37f42a8739bd9d6cd9aa69c", "content_id": "f353daf6e8289562086d8c0d95e5099c08948438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 145, "license_type": "no_license", "max_line_length": 62, "num_lines": 4, "path": "/VCS/templates/VCS/home1.html", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "{% extends \"VCS/index.html\" %}\n{% block content %}\n<h1><p class=\"text-danger\">Chào mừng đến web luận văn</p></h1>\n{% endblock content %}" }, { "alpha_fraction": 0.47273948788642883, "alphanum_fraction": 0.5045210123062134, "avg_line_length": 27.789947509765625, "blob_id": "a224ffe120f19df0da665659404e95c21e35a132", "content_id": "81a12e7ef2ed23155db8bf38ae1104613a79b515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22430, "license_type": "no_license", "max_line_length": 134, "num_lines": 776, "path": "/VCS/views.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect\nimport math\nfrom django.template import RequestContext\nfrom django.http import HttpResponse\nimport random\nfrom hashlib import sha1\nimport hashlib\nfrom .forms import TeachForm\nfrom .forms import TaokhoaForm,UpForm,ListForm,dangnhapForm\nfrom .models import Teach,Teacher,List,Thongtin\nimport cv2 \nimport numpy as np\nimport sys\nfrom django.template import loader\nfrom django.contrib.auth import authenticate,decorators,login\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import user_passes_test\nimport xlwt\nfrom django.contrib.auth.models import User\n\n\n\n# Create your views here.\n#@decorators.login_required(login_url= '/login/')\ndef staff_required(login_url=None):\n return user_passes_test(lambda u: u.is_staff, login_url=login_url)\n\ndef index(request):\n return render(request,'VCS/home.html')\n\ndef danh(request):\n allaccs= Thongtin.objects.all()\n \n context= {'allaccs': allaccs}\n return render(request,'VCS/linhtinh3.html',context)\n\ndef coprime(o, p):\n while p!= 0:\n o, p = p, o % p\n return o\n \n \ndef extended_gcd(aa, bb):\n lastremainder, remainder = abs(aa), abs(bb)\n x, lastx, y, lasty = 0, 1, 1, 0\n while remainder:\n lastremainder, (quotient, remainder) = remainder, divmod(lastremainder, remainder)\n x, lastx = lastx - quotient*x, x\n y, lasty = lasty - quotient*y, y\n return lastremainder, lastx * (-1 if aa < 0 else 1), lasty * (-1 if bb < 0 else 1)\n \ndef modinv(a, m):\n\tg, x, y = extended_gcd(a, m)\n\tif g != 1:\n\t\traise Exception('Modular inverse does not exist')\n\treturn x % m \n\n \ndef is_prime(num):\n if num == 2:\n return True\n if num < 2 or num % 2 == 0:\n return False\n for n in range(3, int(num**0.5)+2, 2):\n if num % n == 0:\n return False\n return True\n\n\ndef generate_keypair(p, q):\n if not (is_prime(p) and is_prime(q)):\n raise ValueError('Both numbers must be prime.')\n elif p == q:\n raise ValueError('p and q cannot be equal')\n\n n = p * q\n\n phi = (p-1) * (q-1)\n\n e = random.randrange(1, phi)\n\n g = coprime(e, phi)\n \n while g != 1:\n e = random.randrange(1, phi)\n g = coprime(e, phi)\n\n d = modinv(e, phi)\n pri=(e,n)\n pub=(d,n)\n return ((e), (d),n,pri,pub)\n \ndef hashFunction(message):\n hashed = sha1(message.encode(\"UTF-8\")).hexdigest()\n #hashed = hash(message)\n return hashed\n \ndef encrypt(privatek, plaintext):\n key, n = privatek\n key=int(key)\n n=int(n)\n numberRepr = [ord(char) for char in plaintext]\n cipher = [pow(ord(char),key,n) for char in plaintext]\n return cipher\ndef decrypt(publick, ciphertext):\n key, n = publick\n key=int(key)\n n=int(n) \n numberRepr = [pow(char, key, n) for char in ciphertext]\n plain = [chr(pow(char, key, n)) for char in ciphertext]\n\n #print(\"Decrypted number representation is: \", numberRepr)\n a=''.join(plain)\n #Return the array of bytes as a string\n return a\ndef hash_file(filename):\n h = hashlib.sha1()\n with open(filename,'rb') as file:\n chunk = 0\n while chunk != b'':\n chunk = file.read(1024)\n h.update(chunk)\n return h.hexdigest()\n\n\ndef taokhoa(form):\n a = form.a\n b = form.b\n Ten = form.Ten\n MSCB = form.MSCB\n public, private,n,t,y= generate_keypair(a, b) \n #User = get_user_model()\n #user = User.objects.get(id=self.user.id) \n user =Tennguoiky\n c = List(Giaovien=Ten,Pubkey = int(public),PubN= int(n),MSCB=MSCB,UserRegis=user)\n c.save()\n template = loader.get_template('VCS/linhtinh.html')\n context = {\n 'public': int(public),'private': int(private),'n': int(n)\n }\n #response=HttpResponse()\n #response.writelines( \"<h3>Khoa bi mat bang=%s </h3><br/>\" %(public))\n #response.writelines( \"<h3>khoa cong khai bang=%s</h3><br/>\" %(private))\n #response.writelines( \"<h3>n bằng tích của hai số nguyên tố:%s </h3><br/>\" %(n))\n #return response\n return HttpResponse(template.render(context))\n@staff_required(login_url= '/login/')\ndef teach(request): \n form = TeachForm(request.POST or None)\n if form.is_valid():\n form=form.save()\n return Ky(form)\n\n return render(request,'VCS/teach.html', {'form': form})\n\n\n@staff_required(login_url= '/login/')\ndef index1(request):\n form = TaokhoaForm(request.POST or None)\n user = User.objects.get(username=request.user.username)\n global Tennguoiky\n Tennguoiky = user\n if request.method == 'POST':\n if form.is_valid():\n form = form.save(commit=False)\n return taokhoa(form)\n else:\n form = TaokhoaForm()\n\n return render(request,'VCS/khoa.html', {'form': form})\n\ndef Ky(form):\n d=form.KhoaE\n n=form.KhoaN\n a = form.Link\n a1=form.MSSV\n a2=form.Ghichu\n y=(d,n)\n np.set_printoptions(threshold=sys.maxsize)\n img = cv2.imread(a,cv2.IMREAD_GRAYSCALE)\n hash_object = hashlib.sha1(img)\n hex_dig = hash_object.hexdigest()\n s=hash_file(a)\n print(hex_dig)\n #print(s)\n #encrypted_msg = encrypt(y, s)\n encrypted_msg = encrypt(y, hex_dig)\n encrypted_msg1 =str( encrypted_msg)\n #print(encrypted_msg1)\n z = nhung(a,encrypted_msg,a1,a2)\n #print(z)\n if not z=='Hình này không phù hợp cho việc nhúng':\n a1 ='-sign'\n a2=a[:len(a)-4]\n #a3 = a[len(a)-4:len(a)]\n a3='.bmp'\n a4 = a2+a1+a3\n cv2.imwrite(a4,z)\n template = loader.get_template('VCS/linhtinh2.html')\n return HttpResponse(template.render())\n #response=HttpResponse()\n #response.writelines( \"<h3>khoa bi mat bang=%s </h3><br/>\" %(encrypted_msg1))\n #return response \n else:\n template = loader.get_template('VCS/linhtinh4.html')\n return HttpResponse(template.render())\n\n \n\ndef list(request):\n Teachers = Teacher.objects.all()\n return render(request,'VCS/list.html',{'Teachers':Teachers})\n#def Poss(request, id):\n #post = Teacher.objects.get(id=id)\n #return render(request,'VCS/post.html', {'post' : post})\n\ndef upload_file(request):\n if request.method == 'POST': \n form = UpForm(request.POST , files = request.FILES ) \n if form.is_valid():\n form = form.save() \n return redirect('upload_file') \n else:\n form = UpForm()\n \n return render(request,'VCS/up.html',{'form':form})\n\ndef bang(request):\n allaccs= List.objects.all()\n \n context= {'allaccs': allaccs}\n\n \n return render(request, 'VCS/bang.html', context)\n\ndef xac(request):\n form = ListForm(request.POST or None)\n if form.is_valid():\n form = form.save()\n return xacthuc(form)\n\n return render(request,'VCS/xacthuc.html', {'form': form})\n\ndef xacthuc(form):\n b=form.MSCB\n a=Teacher.objects.filter(MSCB=b)\n c = List.objects.get(MSCB=b)\n c1=c.Pubkey\n c2=c.PubN\n pub=(float(c1),float(c2))\n for i in range(0,len(a)):\n try:\n [encrypted_msg,Ghichu,MSSV,im] = giainhung(a[i].image.path)\n date=a[i].date\n #print(encrypted_msg)\n d=decrypt(pub,encrypted_msg)\n hash_object = hashlib.sha1(im)\n hex_dig = hash_object.hexdigest()\n s=hex_dig\n #print('Giai mã chữ ký ra=',d)\n #print(encrypted_msg)\n #print('hash file gốc=',s)\n Ghichu=str(Ghichu)\n cv2.imwrite(r'D:\\luanvan 11-12\\filegoc.bmp',im)\n if s==d:\n Trangthai='File đc xác thực'\n else:\n Trangthai='File đã bị thay đổi'\n \n p=List.objects.get(MSCB=b)\n c = Thongtin(Giaovien=str(p.Giaovien),MSSV = str(MSSV),Trangthai=str(Trangthai) ,Ghichu=str(Ghichu),MSCB=b,date=str(date))\n c.save()\n\n except Exception:\n p=List.objects.get(MSCB=b)\n Giaovien=str(p.Giaovien)\n MSSV='None'\n MSCB=b\n Ghichu='None'\n date=a[i].date \n Trangthai ='File đã bị thay đổi' \n p=List.objects.get(MSCB=b)\n c = Thongtin(Giaovien=str(p.Giaovien),MSSV = str(MSSV),Trangthai=str(Trangthai) ,Ghichu=str(Ghichu),MSCB=b,date=str(date))\n c.save() \n #(encrypted_msg,Ghichu,MSSV,im) = giainhung(a[i].image.path)\n #d=decrypt(pub,encrypted_msg)\n #hash_object = hashlib.sha1(im)\n #hex_dig = hash_object.hexdigest()\n #s=hex_dig\n #Ghichu=str(Ghichu)\n\n #if s==d:\n #Trangthai='File đc xác thực'\n #p=List.objects.get(MSCB=b)\n #c = Thongtin(Giaovien=str(p.Giaovien),MSSV = str(MSSV),Trangthai=str(Trangthai) ,Ghichu=str(Ghichu),MSCB=b)\n #c.save()\n \n template = loader.get_template('VCS/linhtinh3.html')\n allaccs= Thongtin.objects.all()\n \n context= {'allaccs': allaccs}\n\n \n return HttpResponse(template.render(context))\n \n #response=HttpResponse()\n #if s==d:\n #response.writelines( \"<h4>file đã đc xác thực <br/>\" )\n #else:\n #response.writelines( \"<h4>file đã bị thay đổi <br/>\" ) \n #response.writelines( \"<h3>hash=%s </h3><br/>\" %(d) )\n #response.writelines( \"<h3>khoa bi mat bang=%s </h3><br/>\" %(c1) )\n #response.writelines( \"<h3>khoa bi mat bang=%s </h3><br/>\" %(c2) )\n #response.writelines( \"<h3>khoa bi mat bang=%s </h3><br/>\" %(p) )\n #return response \n#@decorators.login_required(login_url= '/login/')\ndef register(request):\n form = dangnhapForm()\n if request.method == 'POST':\n form = dangnhapForm(request.POST)\n if form.is_valid():\n form=form.save()\n return HttpResponseRedirect('/')\n return render(request,'VCS/register.html',{'form':form})\n\ndef export_users_xls(request):\n response = HttpResponse(content_type='application/ms-excel')\n response['Content-Disposition'] = 'attachment; filename=\"Danhsach.xls\"'\n\n wb = xlwt.Workbook(encoding='utf-8')\n ws = wb.add_sheet('Users')\n\n # Sheet header, first row\n row_num = 0\n\n font_style = xlwt.XFStyle()\n font_style.font.bold = True\n\n columns = ['MSCB','Giáo viên', 'MSSV', 'Trạng thái', 'Ghi chú', ]\n\n for col_num in range(len(columns)):\n ws.write(row_num, col_num, columns[col_num], font_style)\n\n # Sheet body, remaining rows\n font_style = xlwt.XFStyle()\n\n rows = Thongtin.objects.all().values_list('MSCB','Giaovien', 'MSSV', 'Trangthai', 'Ghichu')\n for row in rows:\n row_num += 1\n for col_num in range(len(row)):\n ws.write(row_num, col_num, row[col_num], font_style)\n\n wb.save(response)\n return response\n\ndef nhung(link,sign,MSSV,Ghichu):\n np.set_printoptions(threshold=sys.maxsize)\n img = cv2.imread(link,cv2.IMREAD_GRAYSCALE)\n im = cv2.imread(link,cv2.IMREAD_GRAYSCALE)\n size = im.shape\n histogram = [0] * 256\n #q=np.histogram(im,bins=1,range=None)\n for row in range(size[0]): # traverse by row (y-axis)\n for col in range(size[1]): # traverse by column (x-axis)\n histogram[im[row, col]] += 1\n a = histogram\n b = np.arange(256)\n #print(histogram)\n #print(b)\n j1 = im[0,0];\n j2 = im[0,1];\n j3 = im[0,2];\n j4 = im[0,3];\n j5 = im[0,4];\n j6 = im[0,5];\n j7 = im[0,6];\n j8 = im[0,7];\n a[j1]=a[j1]-1;\n a[j2]=a[j2]-1;\n a[j3]=a[j3]-1;\n a[j4]=a[j4]-1;\n a[j5]=a[j5]-1;\n a[j6]=a[j6]-1;\n a[j7]=a[j7]-1;\n a[j8]=a[j8]-1;\n #print(a)\n \n #Tim peak va toa do peak\n max = a[0] + a[1]\n for i in range(1,255):\n if max<(a[i] + a[i+1]):\n max = (a[i]+a[i+1])\n peak = i\n giatripeak=a[i]\n giatriketiep=a[i+1]\n #print(peak)\n # chia histogram thanh 2 mien\n sub1 = a[0:peak+1]\n sub2=a[peak:256]\n\n #Tim minL,R va toa do minL,R\n sub11 = np.flip(sub1)\n q1 = min(sub11)\n w1 = np.argmin(sub11)\n w1 = len(sub11)-w1-1\n q2 = min(sub2)\n w2 = np.argmin(sub2)\n\n \n #Bieu dien gia tri nhi phan mien I1\n i1 = '{0:08b}'.format(im[0,0])\n i2 = '{0:08b}'.format(im[0,1])\n i3 = '{0:08b}'.format(im[0,2])\n i4 = '{0:08b}'.format(im[0,3])\n i5 = '{0:08b}'.format(im[0,4])\n i6 = '{0:08b}'.format(im[0,5])\n i7 = '{0:08b}'.format(im[0,6])\n i8 = '{0:08b}'.format(im[0,7])\n #Tap thong tin bo tro:\n #8 bit thap cua I1\n V = i1[7]+i2[7]+i3[7]+i4[7]+i5[7]+i6[7]+i7[7]+i8[7]\n #print(V)\n\n #Gia tri nhi phan diem cuc tieu ben trai peak\n minL = '{0:08b}'.format(w1)\n #print(minL)\n\n #So diem cuc tieu ben trai peak\n CL = '{0:08b}'.format(q1)\n #print(CL)\n \n #Vi tri cac diem co gia tri minL\n for i in range(0,8):\n im[0][i] = 257\n \n ML = np.argwhere(im == w1)\n #print(ML)\n \n #Gia tri nhi phan diem cuc tieu ben phai peak\n minR = '{0:08b}'.format(w2+peak)\n #print(minR)\n\n # So diem cuc tieu ben phai peak\n CR = '{0:08b}'.format(q2)\n #print(CR)\n\n #Vi tri cac diem co gia tri minR\n MR = np.argwhere(im == w2+peak)\n #print(MR)\n bin9 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(9)] ) )\n chieudaiB = giatripeak + giatriketiep\n xixo1 = ''\n xixo2 = ''\n for i in range(1,len(ML)+1):\n xixo1 = xixo1 + bin9(ML[i-1,0]) + bin9(ML[i-1,1])\n\n for i in range(1,len(MR)+1):\n xixo2 = xixo2 + bin9(MR[i-1,0]) + bin9(MR[i-1,1])\n \n MLL = xixo1\n MRR = xixo2\n #print(MLL,MRR)\n thongtinphu= V + minL + CL + MLL + minR + CR + MRR \n chieudainhung = chieudaiB - len(thongtinphu)\n #print('chieu dai nhung la :',chieudainhung)\n\n if chieudainhung > 750:\n chuki=sign\n MSSV=MSSV\n Ghichu=Ghichu\n bin7 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(7)] ) )\n bin10 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(10)] ) )\n MSSV=[ord(c) for c in MSSV]\n MSSV=[(bin7(a)) for a in MSSV]\n MSSV=''.join(MSSV)\n a= [ord(c) for c in Ghichu]\n a=[(bin7(a)) for a in a]\n a=''.join(a)\n b=len(a)\n b1=b\n b=bin10(b)\n a=a+b\n Ghichu=a\n bin14 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(14)] ) )\n W=''\n for i in range(0,40):\n W = W + bin14(chuki[i])\n\n zeros = [0] * (chieudainhung-560-b1-49-10)\n zeros = ''.join(str(e) for e in zeros)\n #print(MSSV)\n #print(Ghichu)\n W = zeros +MSSV+Ghichu+ W\n #print(W)\n B= thongtinphu + W\n #print(thongtinphu)\n #Tao cac cap histogram(peak,peak-1) và (peak+1,peak+2)bang dich chuyen histogram\n for i in range(0,size[0]):\n for j in range(0,size[1]):\n if im[i,j] in range(w1+1,peak):\n im[i,j] = im[i,j]-1\n\n for i in range(0,size[0]):\n for j in range(0,size[1]):\n if im[i,j] in range(peak+2,w2+peak):\n im[i,j] = im[i,j]+1\n\n #nhung day bit B\n k=-1\n for i in range(0,size[0]):\n for j in range(0,size[1]):\n if im[i,j] in range(peak,peak+2):\n k = k+1\n #print(k)\n if int(B[k]) == 0:\n im[i,j] = im[i,j]\n elif int(B[k]) == 1:\n if im[i,j] == peak:\n im[i,j] = im[i,j]-1\n else:\n im[i,j] = im[i,j]+1\n \n for i in range(0,8):\n im[0,i] = img[0,i]\n\n\n\n\n #nhung peak vao i1\n mask = 1 << 0 \n peak = '{0:08b}'.format(peak)\n for i in range(0,8):\n im[0,i] = (im[0,i] & ~mask) | ((int(peak[i]) << 0) & mask)\n\n #cv2.imwrite('lan2.tiff',im)\n #print(size)\n #print(len(B))\n #cv2.imshow('image',im)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n return im\n else:\n a='Hình này không phù hợp cho việc nhúng'\n return a\n \n\ndef giainhung(anh):\n np.set_printoptions(threshold=sys.maxsize)\n img = cv2.imread(anh,cv2.IMREAD_GRAYSCALE)\n im = cv2.imread(anh,cv2.IMREAD_GRAYSCALE)\n size = im.shape\n\n #buoc2\n i1 = '{0:08b}'.format(im[0,0])\n i2 = '{0:08b}'.format(im[0,1])\n i3 = '{0:08b}'.format(im[0,2])\n i4 = '{0:08b}'.format(im[0,3])\n i5 = '{0:08b}'.format(im[0,4])\n i6 = '{0:08b}'.format(im[0,5])\n i7 = '{0:08b}'.format(im[0,6])\n i8 = '{0:08b}'.format(im[0,7])\n\n peak = i1[7] + i2[7] + i3[7] + i4[7] + i5[7] + i6[7] + i7[7] + i8[7] \n peak = int(peak,2)\n #print(peak)\n\n\n for i in range(0,8):\n im[0,i] = 256\n\n #buoc3\n B=''\n k=-1\n for i in range(0,size[0]):\n for j in range(0,size[1]):\n if im[i,j] in range(peak-1,peak+3):\n k = k+1\n if im[i,j] in range(peak,peak+2):\n B = B + '0'\n else:\n B = B + '1'\n\n #print('day nhung B la',B)\n #buoc4\n #tim V\n V=''\n for i in range(0,8):\n V=V + B[i]\n #print('Gia tri của V',V)\n\n #tim minL\n minL=''\n for i in range(8,16):\n minL=minL + B[i]\n #print('Gia tri của minL',minL)\n\n #tim CL\n CL=''\n for i in range(16,24):\n CL=CL + B[i]\n #print('Gia tri của CL',CL)\n\n #tim ML\n lem = 9*2*int(CL,2)\n ML =''\n for i in range(24,24+lem):\n ML=ML + B[i]\n #print('Gia tri của ML',ML)\n\n #tim minR\n BL=''\n for i in range(24+lem,len(B)):\n BL=BL + B[i]\n \n minR = ''\n for i in range(0,8):\n minR=minR + BL[i]\n #print('Gia tri của minR',minR)\n\n #tim CR\n CR = ''\n for i in range(8,16):\n CR=CR + BL[i]\n #print('Gia tri của CR',CR)\n\n #tim MR\n lemm = 9*2*int(CR,2)\n MR =''\n for i in range(16,16+lemm):\n MR=MR + BL[i]\n #print('Gia tri của MR',MR)\n #print(len(MR))\n\n # tim W\n W=''\n for i in range(16+lemm,len(BL)):\n W=W + BL[i]\n\n #print(len(W))\n\n minL = int(minL,2)\n minR = int(minR,2)\n #print(len(W))\n #buoc 5,2\n for i in range(0,8):\n im[0,i] =999\n\n for i in range(0,size[0]):\n for j in range(0,size[1]):\n if im[i,j] in range(minL+1,minR):\n if im[i,j] < peak:\n im[i,j] = im[i,j] +1\n elif im[i,j] > (peak +1):\n im[i,j] = im[i,j] -1 \n\n\n MLL = ''\n LM1 = ','\n LM=''\n for i in range(0,len(ML),9):\n MLL1 =MLL + ML[i]+ML[i+1]+ML[i+2]+ML[i+3]+ML[i+4]+ML[i+5]+ML[i+6]+ML[i+7]+ML[i+8]\n LM = LM +LM1 + str(int(MLL1,2))\n \n LM = LM[1:]\n LM = LM.split(',')\n #print(LM)\n\n\n MRR = ''\n RM1 = ','\n RM = ''\n for i in range(0,len(MR),9):\n MRR1 =MRR + MR[i]+MR[i+1]+MR[i+2]+MR[i+3]+MR[i+4]+MR[i+5]+MR[i+6]+MR[i+7]+MR[i+8]\n RM = RM + RM1 + str(int(MRR1,2))\n RM = RM[1:]\n RM = RM.split(',')\n #print(RM)\n\n #buoc 5.3 khoi phuc cac diem anh co gia tri minL\n tet = np.argwhere(im == minL)\n #print(tet)\n for i in range(0,len(tet)):\n im[tet[i,0],tet[i,1]] = im[tet[i,0],tet[i,1]]+1\n if LM != ['']:\n for i in range(0,len(LM),2):\n im[int(LM[i]),int(LM[i+1])] = im[int(LM[i]),int(LM[i+1])]-1\n\n\n #buoc 5.3 khoi phuc cac diem anh co gia tri minR\n tet = np.argwhere(im == minR)\n #print(tet)\n #print(len(tet))\n for i in range(0,len(tet)):\n im[tet[i,0],tet[i,1]] = im[tet[i,0],tet[i,1]]-1\n if RM != ['']:\n for i in range(0,len(RM),2):\n im[int(RM[i]),int(RM[i+1])] = im[int(RM[i]),int(RM[i+1])]+1\n \n tet = np.argwhere(im == minR)\n #print(tet)\n #print(len(tet))\n\n for i in range(0,8):\n im[0,i] = img[0,i]\n mask = 1 << 0 \n\n for i in range(0,8):\n im[0,i] = (im[0,i] & ~mask) | ((int(V[i]) << 0) & mask)\n\n\n \n sign=W[len(W)-560:]\n lenG=W[len(W)-560-10:len(W)-560]\n lenG=int(lenG,2)\n #print(lenG)\n Ghichu=W[len(W)-560-10-lenG:len(W)-560-10]\n MSSV=W[len(W)-560-10-lenG-49:len(W)-560-10-lenG]\n W1=Ghichu\n WWW=MSSV\n #print(len(W1))\n #print(WWW)\n\n\n W=sign\n \n e=''\n p=''\n q=','\n for i in range(0,560,14):\n e = W[i]+W[i+1]+W[i+2]+W[i+3]+W[i+4]+W[i+5]+W[i+6]+W[i+7]+W[i+8]+W[i+9]+W[i+10]+W[i+11]+W[i+12]+W[i+13]\n p = p + str(int(e,2))+q\n p = p.split(',')\n p = p[:40]\n p= [int(i) for i in p]\n chuki=p\n #print(p)\n\n e=''\n p=''\n q=','\n for i in range(0,len(W1),7):\n e = W1[i]+W1[i+1]+W1[i+2]+W1[i+3]+W1[i+4]+W1[i+5]+W1[i+6]\n p = p + str(int(e,2))+q\n p = p.split(',')\n p = p[:int(len(W1)/7)]\n p= [int(i) for i in p]\n p= [chr(p) for p in p]\n e=''\n for i in range(0,len(p)):\n e=e+str(p[i])\n Ghichu=e\n\n e=''\n p=''\n q=','\n for i in range(0,len(WWW),7):\n e = WWW[i]+WWW[i+1]+WWW[i+2]+WWW[i+3]+WWW[i+4]+WWW[i+5]+WWW[i+6]\n p = p + str(int(e,2))+q\n p = p.split(',')\n p = p[:int(len(WWW)/7)]\n p= [int(i) for i in p]\n p= [chr(p) for p in p]\n e=''\n for i in range(0,len(p)):\n e=e+str(p[i])\n MSSV=e\n\n \n #cv2.imwrite(r'D:\\luanvan 11-12\\hinh4trich.bmp',im)\n #cv2.imshow('image',im)\n #cv2.waitKey(0)\n #cv2.destroyAllWindows()\n return (chuki,Ghichu,MSSV,im)\n\ndef ok(request):\n return render(request,'VCS/login.html')" }, { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.5687830448150635, "avg_line_length": 20, "blob_id": "de2a2b78ff2328fd877590129d28e0e93a00b168", "content_id": "7f450a20598ba2ab12dc9040cc107a99b7c2d405", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 378, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/VCS/migrations/0003_teach_file.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-05 12:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('VCS', '0002_thongtin'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='teach',\n name='File',\n field=models.ImageField(null=True, upload_to=''),\n ),\n ]\n" }, { "alpha_fraction": 0.4837905168533325, "alphanum_fraction": 0.4984413981437683, "avg_line_length": 33.83695602416992, "blob_id": "e27751f97a0c63120fd2b0b026c86eba9254b285", "content_id": "0de890d24092249e05e6f6a934768dda40322185", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3298, "license_type": "no_license", "max_line_length": 148, "num_lines": 92, "path": "/VCS/templates/VCS/base1.html", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "<!DOCTYPE HTML>\n<html lang=\"vi\">\n\n<head>\n {% load staticfiles %}\n <title>LVTN</title>\n <meta charset=\"utf-8\" />\n <meta name=\"description\" content=\"website description\" />\n <meta name=\"keywords\" content=\"website keywords, website keywords\" />\n <meta http-equiv=\"content-type\" content=\"text/html; charset=windows-1252\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"{%static 'style.css' %}\" title=\"style\" />\n \n</head>\n\n<body>\n <div id=\"main\">\n <div id=\"header\">\n <div id=\"logo\">\n <div id=\"logo_text\">\n <!-- class=\"logo_colour\", allows you to change the colour of the text -->\n <h1><a href=\"/\">CHỮ KÝ SỐ<span class=\"logo_colour\">VÀ ỨNG DỤNG</span></a></h1>\n <h2>Khoa Điện-Điện tử, Bộ môn Viễn thông</h2>\n </div>\n </div>\n <div id=\"menubar\">\n <ul id=\"menu\">\n <!-- put class=\"selected\" in the li tag for the selected page - to highlight which page you're on -->\n <li class=\"selected\"><a href=\"/\">Trang chủ</a></li>\n <li><a href=\"/tao\">Tạo khóa</a></li>\n <li><a href=\"/bang\">Danh sách chữ ký</a></li>\n <li><a href=\"/kianh\">Ký ảnh</a></li>\n <li><a href=\"/list\">Diễn đàn</a></li>\n <li><a href=\"/xacthuc\">Xác thực ảnh</a></li>\n </ul>\n </div>\n </div>\n <div class=\"container-fluid\" >\n <div class=\"row\">\n <div class=\"col-sm-2\">\n hello teacher\n </div>\n <div class=\"col-sm-8\">\n <div id=\"site_content\">\n <div class=\"sidebar\">\n <!-- insert your sidebar items here -->\n <h3>Tin mới nhất</h3>\n <h4>Cập nhật lần cuối</h4>\n <h5>November 16th, 2019</h5>\n <p>Cải tiến các tính năng của web<br /><a href=\"#\">Read more</a></p>\n <p></p>\n <h4>Thông tin quản trị viên</h4>\n <h5>Tên: Nguyễn Huỳnh Hùng</h5>\n <p>Khoa: Điện-Điện tử<br /><a href=\"http://www.dee.hcmut.edu.vn/\" target=\"_blank\">Xem</a></p>\n <p>Bộ môn: Viễn thông<br /><a href=\"http://dte.dee.hcmut.edu.vn/\" target=\"_blank\">Xem</a></p>\n <p>Email: [email protected] </p>\n <ul>\n <li><a href=\"#\">link 1</a></li>\n <li><a href=\"#\">link 2</a></li>\n <li><a href=\"#\">link 3</a></li>\n <li><a href=\"#\">link 4</a></li>\n </ul>\n <h3>Search</h3>\n <form method=\"post\" action=\"#\" id=\"search_form\">\n <p>\n {% csrf_token %}\n <input class=\"search\" type=\"text\" name=\"search_field\" value=\"\" />\n <input name=\"search\" type=\"image\" style=\"border: 0; margin: 0 0 -9px 5px;\" src=\"{%static 'search.png' %}\" alt=\"Search\" title=\"Search\" />\n </p>\n </form>\n </div>\n<div id=\"content\" class =\"show_2\">\n <!-- insert the page content here -->\n {% block content %}\n \n {% endblock content %}\n </div>\n </div>\n <div class=\"col-sm-2\">\n hello techer\n </div>\n </div>\n</div>\n \n </div>\n \n <div id=\"content_footer\"></div>\n <div id=\"footer\">\n Copyright 2019 Nguyễn Huỳnh Hùng <a href=\"https://www.facebook.com/huynh.hung.370\" target=\"_blank\"> Liên hệ:Facebook</a>\n </div>\n </div>\n</body>\n</html>\n\n\n\n" }, { "alpha_fraction": 0.6051813364028931, "alphanum_fraction": 0.6093264222145081, "avg_line_length": 59.34375, "blob_id": "b6e8997c3e58b02a8adc2a50fd27b9802597adca", "content_id": "cc1aaa2fe86eab8e82850149091e34a85af4cf7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2289, "license_type": "no_license", "max_line_length": 206, "num_lines": 32, "path": "/VCS/templates/VCS/home.html", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "{% extends \"VCS/base.html\" %}\n{% block content %}\n<h1>Chào mừng tới web luận văn</h1>\n <p>Trang web được viết bằng framework Django bằng ngôn ngữ python kết hợp với các ngôn ngữ web như HTML,CSS,JavaScript,...</p>\n <p>Đề tài được hướng dẫn bởi thầy <strong>Nguyễn Thanh Tuấn</strong> và thực hiện trong 5 tháng</p>\n <p>Trang web được lấy ý tưởng từ một số công việc cụ thể trong văn phòng khoa như việc sinh viên nộp các giấy tờ cho bộ môn có chữ ký của giáo viên </p>\n <p>Việc ký giấy tờ bằng tay có thể được thay thế bằng ký số giúp tăng tính an toàn,rút gọn thời gian cho giáo viên, sinh viên,thư ký bộ môn ,giảm thiểu văn bản giấy cũng như tạo tính đồng bộ</p>\n <h2>Các chức năng của web</h2>\n <ul>\n <li>Người dùng tạo chữ ký số</li>\n <li>Người dùng ký vào ảnh số </li>\n <li>Chữ ký được nhúng vào ảnh kèm theo các ghi chú của người dùng </li>\n <li>Đăng ảnh lên diễn đàn</li>\n <li>Người dùng xác thực các ảnh được đăng lên</li>\n </ul>\n <p>Hiện tại web chỉ hỗ trợ việc ký vào ảnh có kích thước chiều dài và rộng nhỏ hơn 510 pixel và không hỗ trợ việc ký các định dạng file khác . Quý khách lưu ý nhằm mang lại trải nghiệm tốt nhất </p>\n <p>Chức năng tạo khóa và ký ảnh chỉ khả dụng khi đăng nhập và được cấp quyền truy cập bởi quản trị viên </p>\n{% endblock content %}\n\n{% block menubar %}\n<div id=\"menubar\">\n <ul id=\"menu\">\n <!-- put class=\"selected\" in the li tag for the selected page - to highlight which page you're on -->\n <li class=\"selected\"><a href=\"/\">Trang chủ</a></li>\n <li><a href=\"/tao\">Tạo khóa</a></li>\n <li><a href=\"/bang\">Danh sách chữ ký</a></li>\n <li><a href=\"/kianh\">Ký ảnh</a></li>\n <li><a href=\"/list\">Diễn đàn</a></li>\n <li><a href=\"/xacthuc\">Xác thực ảnh</a></li>\n </ul> \n</div> \n{% endblock menubar %}" }, { "alpha_fraction": 0.5050251483917236, "alphanum_fraction": 0.5829145908355713, "avg_line_length": 21.11111068725586, "blob_id": "a118a3c4052a6db18188d161a7153629ca7d19aa", "content_id": "a84006ed128bba47e1aa7acca02c367c341cf6bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/VCS/migrations/0005_auto_20191106_1411.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-06 07:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('VCS', '0004_auto_20191105_2024'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='teach',\n name='File',\n field=models.ImageField(null=True, upload_to='Taokhoa/'),\n ),\n ]\n" }, { "alpha_fraction": 0.5571428537368774, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 27.200000762939453, "blob_id": "92352c7d4227734af1657e6efb8b55ac6eeb2b4d", "content_id": "dae4a753f384658f83750b88721fc6f3e3b999e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 140, "license_type": "no_license", "max_line_length": 53, "num_lines": 5, "path": "/VCS/templates/VCS/post.html", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "{% extends \"VCS/base.html\" %}\n{% block content %}\n<h4><a href='/VCS/{{post.id}}'>{{post.MSSV}}</a></h4>\n{{post.Link}}\n{% endblock content %}" }, { "alpha_fraction": 0.6292452812194824, "alphanum_fraction": 0.652830183506012, "avg_line_length": 33.209678649902344, "blob_id": "70f8b7e70b33132c22935b532da2cb4697750b5a", "content_id": "3899887265f30820a9e9055deaa8fffd30fc2a21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2180, "license_type": "no_license", "max_line_length": 85, "num_lines": 62, "path": "/VCS/models.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Taokhoa(models.Model):\n teach_choice = (\n ('Nguyễn Văn A','Nguyễn Văn A'),\n ('Trần Văn B','Trần Văn B'),\n ('Phạm Thị C','Phạm Thị C'),\n )\n a = models.FloatField()\n b = models.FloatField()\n Ten = models.CharField(max_length=100,choices=teach_choice)\n MSCB = models.CharField(null=True,max_length=7)\n\n\nclass Teach(models.Model):\n KhoaE = models.FloatField()\n KhoaN = models.FloatField()\n Link = models.TextField(max_length=1000)\n Ghichu=models.CharField(max_length=100)\n MSSV = models.CharField(max_length=25,default='')\n File = models.ImageField(null=True,upload_to='Taokhoa/')\n\n \nclass Teacher(models.Model):\n teach_choice = (\n ('Nguyễn Văn A','Nguyễn Văn A'),\n ('Trần Văn B','Trần Văn B'),\n ('Phạm Thị C','Phạm Thị C'),\n )\n Giaovien = models.CharField(max_length=1000,choices=teach_choice)\n image= models.ImageField(upload_to='images/%Y/%m/%d/', blank=True, null=True ) #1\n date=models.DateTimeField(auto_now_add=True)\n MSCB = models.CharField(max_length=7,null=True)\n def __str__(self):\n return self.MSCB\n\nclass List(models.Model):\n Giaovien = models.CharField(max_length= 100)\n Pubkey = models.CharField(max_length=100)\n PubN = models.CharField(max_length= 100)\n MSCB = models.CharField(max_length=7,null=True)\n UserRegis = models.CharField(max_length=100,null=True)\n def __str__(self):\n return self.Giaovien\n \nclass Xac(models.Model):\n teach_choice = (\n ('Nguyễn Văn A','Nguyễn Văn A'),\n ('Trần Văn B','Trần Văn B'),\n ('Phạm Thị C','Phạm Thị C'),\n )\n Giaovien = models.CharField(max_length=1000,choices=teach_choice)\n MSCB = models.CharField(max_length=7,null=True)\n\nclass Thongtin(models.Model):\n Giaovien=models.CharField(max_length=100)\n MSSV = models.CharField(max_length=100)\n Trangthai =models.CharField(max_length=20)\n Ghichu = models.CharField(max_length=7)\n MSCB = models.CharField(max_length=7,null=True)\n date = models.CharField(max_length=100,null=True)" }, { "alpha_fraction": 0.6515775322914124, "alphanum_fraction": 0.6529492735862732, "avg_line_length": 37.421051025390625, "blob_id": "e3e9378efff4bbd1a0ad47803caf64dedd3dae2a", "content_id": "84ddc07d44467396df04f7f6e5ededd52e9f102d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 94, "num_lines": 19, "path": "/VCS/urls.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\nurlpatterns = [\n path('', views.index),\n path('kianh/',views.teach),\n path('tao/',views.index1),\n path('list/',views.list),\n #path('VCS/<int:id>/',views.Poss),\n path('up/',views.upload_file, name='upload_file'),\n path('bang/',views.bang),\n path('xacthuc/',views.xac),\n path('login/',auth_views.LoginView.as_view(template_name=\"VCS/login.html\"), name=\"login\"),\n path('logout/',auth_views.LogoutView.as_view(next_page='/'),name='logout'),\n path('register/',views.register,name='register'),\n path('danh/',views.danh),\n path('export/xls/$', views.export_users_xls, name='export_users_xls'),\n\n]" }, { "alpha_fraction": 0.5159474611282349, "alphanum_fraction": 0.5572232604026794, "avg_line_length": 22.173913955688477, "blob_id": "025c555ef73dcebf5c940acc70ccd270d4848f0e", "content_id": "3d1d5f602d5bfd47b1347ac38f6d4c771780a830", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 533, "license_type": "no_license", "max_line_length": 50, "num_lines": 23, "path": "/VCS/migrations/0004_auto_20191105_2024.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-05 13:24\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('VCS', '0003_teach_file'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='thongtin',\n name='Ghichu',\n field=models.CharField(max_length=7),\n ),\n migrations.AlterField(\n model_name='thongtin',\n name='Trangthai',\n field=models.CharField(max_length=20),\n ),\n ]\n" }, { "alpha_fraction": 0.4987277388572693, "alphanum_fraction": 0.5852417349815369, "avg_line_length": 20.83333396911621, "blob_id": "89f881201611adeca77fd1302a7b7f6839e5cc91", "content_id": "25c6a29d511f663e8460bc533f05ccacb310f33b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/VCS/migrations/0010_list_userregis.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-16 03:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('VCS', '0009_auto_20191106_1556'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='list',\n name='UserRegis',\n field=models.CharField(max_length=100, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5101156234741211, "alphanum_fraction": 0.5549132823944092, "avg_line_length": 29.086956024169922, "blob_id": "744eff2bd1adcc27a7b5b2f446fa5a21d79ebb37", "content_id": "09a07cf4bb734c0deb9be406fca5f5079809e189", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 114, "num_lines": 23, "path": "/VCS/migrations/0002_thongtin.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2019-11-05 02:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('VCS', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Thongtin',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('Giaovien', models.CharField(max_length=100)),\n ('MSSV', models.CharField(max_length=100)),\n ('Trangthai', models.CharField(max_length=100)),\n ('Ghichu', models.CharField(max_length=100)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.8149465918540955, "alphanum_fraction": 0.8149465918540955, "avg_line_length": 30.22222137451172, "blob_id": "d0ee4bcd5b96b5f98261b3165274ef521f7c78b7", "content_id": "9d508857a790fd21f365f25bb053495c957110f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 281, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/VCS/admin.py", "repo_name": "obiito007/HungBK", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Taokhoa\nfrom .models import Teach,Teacher,List,Thongtin\n# Register your models here.\n#admin.site.register(Teach)\n#admin.site.register(Taokhoa)\nadmin.site.register(Teacher)\nadmin.site.register(List)\nadmin.site.register(Thongtin)\n" } ]
15
Nanoribbon/Stock
https://github.com/Nanoribbon/Stock
20148880bbae0f8345e74f226c92d241a4f3508f
9c7d496e19a1deed4155f097e731df59235c3493
0cb354bc2222d2020192afb9b3a9276e4cd9d7bc
refs/heads/master
2023-03-04T01:35:32.363188
2021-02-10T16:42:10
2021-02-10T16:42:10
336,860,620
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6633185148239136, "alphanum_fraction": 0.704640805721283, "avg_line_length": 54.387325286865234, "blob_id": "ea7fb62cada028a36881f1f7cee37b3918e54457", "content_id": "5159864538432557d7ba3e184ac02af0259fb0ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7865, "license_type": "no_license", "max_line_length": 79, "num_lines": 142, "path": "/backup/StockerGui.py", "repo_name": "Nanoribbon/Stock", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'StockerGui.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.2\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(954, 687)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.layoutWidget = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget.setGeometry(QtCore.QRect(310, 10, 416, 33))\n self.layoutWidget.setObjectName(\"layoutWidget\")\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.layoutWidget)\n self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.pushButton_2 = QtWidgets.QPushButton(self.layoutWidget)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout_3.addWidget(self.pushButton_2)\n self.label_3 = QtWidgets.QLabel(self.layoutWidget)\n self.label_3.setObjectName(\"label_3\")\n self.horizontalLayout_3.addWidget(self.label_3)\n self.lineEdit = QtWidgets.QLineEdit(self.layoutWidget)\n self.lineEdit.setMinimumSize(QtCore.QSize(60, 0))\n self.lineEdit.setMaximumSize(QtCore.QSize(60, 16777215))\n self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit.setClearButtonEnabled(True)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.horizontalLayout_3.addWidget(self.lineEdit)\n self.progressBar_1 = QtWidgets.QProgressBar(self.layoutWidget)\n self.progressBar_1.setProperty(\"value\", 0)\n self.progressBar_1.setObjectName(\"progressBar_1\")\n self.horizontalLayout_3.addWidget(self.progressBar_1)\n self.label_2 = QtWidgets.QLabel(self.layoutWidget)\n self.label_2.setMinimumSize(QtCore.QSize(50, 0))\n self.label_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label_2.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.label_2.setText(\"\")\n self.label_2.setObjectName(\"label_2\")\n self.horizontalLayout_3.addWidget(self.label_2)\n self.layoutWidget_2 = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget_2.setGeometry(QtCore.QRect(20, 50, 621, 33))\n self.layoutWidget_2.setObjectName(\"layoutWidget_2\")\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout(self.layoutWidget_2)\n self.horizontalLayout_4.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget_2)\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.horizontalLayout_4.addWidget(self.pushButton_3)\n self.checkBox = QtWidgets.QCheckBox(self.layoutWidget_2)\n self.checkBox.setObjectName(\"checkBox\")\n self.horizontalLayout_4.addWidget(self.checkBox)\n self.label = QtWidgets.QLabel(self.layoutWidget_2)\n self.label.setObjectName(\"label\")\n self.horizontalLayout_4.addWidget(self.label)\n self.lineEdit_2 = QtWidgets.QLineEdit(self.layoutWidget_2)\n self.lineEdit_2.setMinimumSize(QtCore.QSize(60, 0))\n self.lineEdit_2.setMaximumSize(QtCore.QSize(60, 16777215))\n self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit_2.setClearButtonEnabled(True)\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.horizontalLayout_4.addWidget(self.lineEdit_2)\n self.progressBar_2 = QtWidgets.QProgressBar(self.layoutWidget_2)\n self.progressBar_2.setProperty(\"value\", 0)\n self.progressBar_2.setObjectName(\"progressBar_2\")\n self.horizontalLayout_4.addWidget(self.progressBar_2)\n self.label_4 = QtWidgets.QLabel(self.layoutWidget_2)\n self.label_4.setMinimumSize(QtCore.QSize(50, 0))\n self.label_4.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label_4.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.label_4.setText(\"\")\n self.label_4.setObjectName(\"label_4\")\n self.horizontalLayout_4.addWidget(self.label_4)\n self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)\n self.textBrowser.setGeometry(QtCore.QRect(20, 90, 61, 571))\n self.textBrowser.setObjectName(\"textBrowser\")\n self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget1.setGeometry(QtCore.QRect(20, 10, 271, 32))\n self.layoutWidget1.setObjectName(\"layoutWidget1\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.layoutWidget1)\n self.horizontalLayout_2.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.pushButton_1 = QtWidgets.QPushButton(self.layoutWidget1)\n self.pushButton_1.setObjectName(\"pushButton_1\")\n self.horizontalLayout_2.addWidget(self.pushButton_1)\n self.label_1 = QtWidgets.QLabel(self.layoutWidget1)\n self.label_1.setMinimumSize(QtCore.QSize(50, 0))\n self.label_1.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label_1.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.label_1.setText(\"\")\n self.label_1.setObjectName(\"label_1\")\n self.horizontalLayout_2.addWidget(self.label_1)\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(730, 10, 113, 32))\n self.pushButton.setObjectName(\"pushButton\")\n self.layoutWidget2 = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget2.setGeometry(QtCore.QRect(91, 91, 851, 571))\n self.layoutWidget2.setObjectName(\"layoutWidget2\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget2)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.label_5 = QtWidgets.QLabel(self.layoutWidget2)\n self.label_5.setMinimumSize(QtCore.QSize(0, 25))\n self.label_5.setMaximumSize(QtCore.QSize(16777215, 25))\n self.label_5.setText(\"\")\n self.label_5.setObjectName(\"label_5\")\n self.verticalLayout.addWidget(self.label_5)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.widget_1 = QtWidgets.QWidget(self.layoutWidget2)\n self.widget_1.setObjectName(\"widget_1\")\n self.horizontalLayout.addWidget(self.widget_1)\n self.widget_2 = QtWidgets.QWidget(self.layoutWidget2)\n self.widget_2.setObjectName(\"widget_2\")\n self.horizontalLayout.addWidget(self.widget_2)\n self.verticalLayout.addLayout(self.horizontalLayout)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"Limit List\"))\n self.label_3.setText(_translate(\"MainWindow\", \"max Value:\"))\n self.lineEdit.setText(_translate(\"MainWindow\", \"2\"))\n self.pushButton_3.setText(_translate(\"MainWindow\", \"Analyze\"))\n self.checkBox.setText(_translate(\"MainWindow\", \"testdata\"))\n self.label.setText(_translate(\"MainWindow\", \"factor:\"))\n self.lineEdit_2.setText(_translate(\"MainWindow\", \"2\"))\n self.pushButton_1.setText(_translate(\"MainWindow\", \"Load NASDAQ Data\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"test\"))\n" }, { "alpha_fraction": 0.5475810766220093, "alphanum_fraction": 0.561084508895874, "avg_line_length": 37.19583511352539, "blob_id": "37d0561e49d5f5d77f2dda963eb125c0a3f8410c", "content_id": "b197671ad29a7c9b04a3945f770e43e6e329cab0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9409, "license_type": "no_license", "max_line_length": 149, "num_lines": 240, "path": "/backup/Stocker.py", "repo_name": "Nanoribbon/Stock", "src_encoding": "UTF-8", "text": "\"\"\"\r\n@author: Dr. Martin Hell\r\n\"\"\"\r\n\r\nimport glob\r\nimport json\r\nimport time\r\nimport sys\r\nimport os\r\nimport re\r\nimport math\r\nimport numpy as np\r\nimport pandas as pd\r\nimport yfinance as yf\r\nimport ftplib\r\nimport datetime\r\n\r\nimport pyqtgraph as pg\r\nimport pyqtgraph.opengl as gl\r\nimport pyqtgraph.exporters\r\nfrom plotly.offline import plot as plo\r\n#import plotly.plotly as py\r\nimport plotly.graph_objs as go\r\nimport plotly.express as px\r\nimport matplotlib.pyplot as plt\r\nfrom plotly.graph_objs import Scatter, Layout\r\nfrom matplotlib.figure import Figure\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib import dates, pyplot\r\nfrom PyQt5 import QtGui,QtCore\r\nfrom PyQt5.QtCore import QCoreApplication\r\nfrom PyQt5 import QtCore, uic, QtWidgets, QtWebEngineWidgets\r\nfrom PyQt5.QtWidgets import QMainWindow, QApplication,QSlider, QWidget, QPushButton, QAction, QLineEdit, QMessageBox, QMenu, QVBoxLayout, QSizePolicy\r\nfrom PyQt5.QtGui import QIcon\r\nfrom PyQt5.QtGui import QPixmap, QScreen\r\nfrom PyQt5.QtWidgets import QFileDialog\r\nfrom pyqtgraph.Qt import QtCore, QtGui\r\nfrom pyqtgraph import PlotWidget, plot\r\nfrom time import time\r\nfrom datetime import date\r\nfrom matplotlib.ticker import MaxNLocator\r\nfrom pathlib import Path\r\nfrom yahoo_fin.stock_info import get_data\r\nfrom yahoo_fin import stock_info as si\r\nfrom pathlib import Path\r\nfrom StockerGui import Ui_MainWindow\r\n\r\nclass MainWindow(QtWidgets.QMainWindow):\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(MainWindow, self).__init__(*args, **kwargs)\r\n self.setWindowIcon(QtGui.QIcon('hellicon.png'))\r\n self.setWindowTitle('Stocker')\r\n \r\n uic.loadUi('StockerGui.ui', self)\r\n \r\n self.pushButton_1.clicked.connect(self.symbollister)\r\n self.pushButton_2.clicked.connect(self.pennystocks)\r\n self.pushButton_3.clicked.connect(self.analysis)\r\n # self.pushButton_4.clicked.connect(self.plotter)\r\n\r\n self.pushButton.clicked.connect(self.test)\r\n\r\n self.fig1 = Figure() \r\n self.canvas1 = FigureCanvas(self.fig1) \r\n self.verticalLayout.replaceWidget(self.widget_1, self.canvas1)\r\n\r\n self.fig2 = Figure() \r\n self.canvas2 = FigureCanvas(self.fig2) \r\n self.verticalLayout.replaceWidget(self.widget_2, self.canvas2)\r\n\r\n \r\n self.today=datetime.date.today() \r\n self.past = self.today + datetime.timedelta(-30)\r\n self.now = self.today + datetime.timedelta(-2)\r\n \r\n def barcounter(self,bar,symbols, counter):\r\n pb = getattr(self,bar)\r\n pb.setMaximum(len(symbols))\r\n pb.setValue(counter)\r\n\r\n def get_symbol_df(self, ticka):\r\n \r\n ticka.reset_index(drop=True)\r\n ticka[\"index\"] = pd.to_datetime(ticka[\"index\"])\r\n return ticka\r\n\r\n def symbollister(self):\r\n url = \"ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt\"\r\n df=pd.read_csv(url, sep=\"|\")\r\n export={'Symbols':[]}\r\n for i in df['Symbol']:\r\n export['Symbols'].append(i)\r\n json.dump( export, open(\"Tickers.json\", 'w' ) ) \r\n self.label_1.setText(\"done\")\r\n\r\n def pennystocks(self):\r\n pennystocks=[]\r\n with open('Tickers.json') as f:\r\n symbols = json.load(f)\r\n counter=1\r\n for x in symbols: \r\n self.barcounter('progressBar_1',symbols, counter)\r\n ticka = yf.Ticker(x)\r\n hist = ticka.history(start_date=str(self.past), end_date=str(self.today))\r\n print(str(x) +\" -->> \"+str(np.mean(hist[\"Close\"])))\r\n if np.mean(hist[\"Close\"])<float(self.lineEdit.text()):\r\n pennystocks.append(x) \r\n else:\r\n pass\r\n counter+=1\r\n json.dump( pennystocks, open(\"pennystocks.json\", 'w' ) ) \r\n self.label_2.setText(\"done\")\r\n\r\n def analysis(self):\r\n self.textBrowser.clear()\r\n self.hotlist={}\r\n self.ticklist=[]\r\n \r\n gain=float(self.lineEdit_2.text())\r\n if self.checkBox.isChecked(): \r\n datafile='pennystock_test.json'\r\n else:\r\n datafile='pennystock.json'\r\n \r\n with open(datafile) as f: \r\n symbols = json.load(f) \r\n counter=1\r\n for x in symbols: \r\n ticka = yf.Ticker(str(x)) \r\n ref = ticka.history(start=str(self.past), end=str(self.now), index_as_date = True) \r\n ref.reset_index(inplace=True) \r\n op_val=ref['Open'] \r\n cl_val=ref['Close'] \r\n live_data = si.get_live_price(x)\r\n \r\n if np.mean(op_val)*gain<=live_data:\r\n self.textBrowser.append(str(x)) \r\n self.hotlist[str(x)]= [op_val]\r\n self.ticklist.append(x)\r\n \r\n self.barcounter('progressBar_2',symbols, counter)\r\n QCoreApplication.processEvents()\r\n counter+=1\r\n self.Tot=len(self.ticklist)\r\n self.Cols=1\r\n # self.Rows=self.Tot//self.Cols\r\n \r\n # if self.Tot%self.Cols!=0:\r\n # self.Rows+=1\r\n self.label_4.setText('done')\r\n self.label_4.setStyleSheet(\"\"\"QLineEdit { background-color: green; color: white }\"\"\")\r\n self.past_plotter()\r\n self.present_plotter()\r\n \r\n def recorder(self):\r\n for key in self.hotlist:\r\n live_data = si.get_live_price(key)\r\n self.hotlist[key].append(live_data)\r\n \r\n def test(self):\r\n ticka = yf.Ticker(\"NAKD\") \r\n hist = ticka.history(period=\"1d\", interval=\"5m\", index_as_date = True)\r\n hist.reset_index(inplace=True)\r\n print(hist['Datetime'][0])\r\n t=hist['Datetime'][0]\r\n t= t.strftime(\"%H:%M:%S\")\r\n #s= datetime.datetime.strptime(t, \"%Y-%m-%d\")\r\n print(t)\r\n # ticka = yf.Ticker(\"AACQW\") \r\n # hist =get_data(\"AACQW\", start_date=\"10/04/2019\", end_date=\"12/04/2019\", index_as_date = True)\r\n # hist.reset_index(inplace=True)\r\n # get_data(ticker, start_date = None, end_date = None, index_as_date = True, interval = “1d”)\r\n #hist = yf.download(str(ticka), start=\"2020-02-01\", end=\"2020-02-04\")\r\n # hist = ticka.history(period=\"1d\", index_as_date = True)\r\n # hist = ticka.history(period=\"1d\", index_as_date = False)\r\n #hist = yf.download(str(ticka), start=\"2017-02-01\", end=\"2017-02-04\")\r\n #hist = ticka.history(start_date=str(self.past), end_date=str(self.today)) \r\n # print(hist)\r\n \r\n def past_plotter(self):\r\n self.fig1.clear()\r\n k=1\r\n for tick in self.ticklist:\r\n ticka = yf.Ticker(str(tick)) \r\n ref = ticka.history(period=\"1mo\", index_as_date = True)\r\n op_val=ref['Open'] \r\n cl_val=ref['Close']\r\n x=np.arange(len(op_val)-1,-1,-1)\r\n ax = self.fig1.add_subplot(self.Tot,self.Cols,k)\r\n ax.set_xlim(len(op_val)-1,-1) \r\n ax.tick_params(axis='x', which='top', bottom=False, labelbottom=False) \r\n ax.plot(x,op_val, label='open',c='tab:purple') \r\n ax.plot(x,cl_val, label='close',c='tab:brown' )\r\n ax.axvline(x=1)\r\n if k==self.Tot:\r\n ax.tick_params(axis='x', which='top', bottom=False, labelbottom=True)\r\n ax.legend(loc='upper left', shadow=True)\r\n ax.fill_between(x, op_val, cl_val, where=cl_val >= op_val, facecolor='green', interpolate=True)\r\n ax.fill_between(x, op_val, cl_val, where=cl_val <= op_val, facecolor='red', interpolate=True)\r\n ax.set_title( str(tick), loc='center')\r\n ax.xaxis.set_major_locator(MaxNLocator(integer=True))\r\n k+=1\r\n self.fig1.tight_layout() \r\n self.canvas1.draw() \r\n \r\n def present_plotter(self):\r\n self.fig2.clear()\r\n k=1\r\n for tick in self.ticklist:\r\n ticka = yf.Ticker(str(tick)) \r\n hist = ticka.history(period=\"1d\", interval=\"5m\", index_as_date = True)\r\n print(hist)\r\n hist.reset_index(inplace=True)\r\n hist['Datetime']= [s.strftime(\"%H:%M:%S\") for s in hist['Datetime']]\r\n ax2 = self.fig2.add_subplot(self.Tot,self.Cols,k) \r\n ax2.tick_params(axis='x', which='both', bottom=True, labelbottom=False)\r\n if k==self.Tot:\r\n ax2.tick_params(axis='x', which='both', bottom=True, labelbottom=True) \r\n ax2.plot(hist['Datetime'],hist['Close'])\r\n ax2.set_title(str(tick), loc='center')\r\n # ax2.tick_params(labelrotation=90)\r\n ax2.xaxis.set_major_locator(plt.MaxNLocator(5))\r\n k+=1\r\n self.fig2.tight_layout() \r\n self.canvas2.draw() \r\n\r\n#%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\r\ndef main():\r\n #app = QtGui.QApplication(sys.argv)\r\n \r\n\r\n app = QtWidgets.QApplication(sys.argv)\r\n app.setStyle('Fusion')\r\n app.setAttribute(QtCore.Qt.AA_Use96Dpi)\r\n main = MainWindow()\r\n main.show()\r\n sys.exit(app.exec_())\r\nif __name__ == '__main__': \r\n main()" }, { "alpha_fraction": 0.6727126240730286, "alphanum_fraction": 0.7080478072166443, "avg_line_length": 56.47490310668945, "blob_id": "1a2509945aa8318ea8aa5ef756064f7fee6dca99", "content_id": "a986ec1aeeb85f710b96e7ba90412a915a60d620", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14886, "license_type": "no_license", "max_line_length": 115, "num_lines": 259, "path": "/StockerGui.py", "repo_name": "Nanoribbon/Stock", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'StockerGui.ui'\n#\n# Created by: PyQt5 UI code generator 5.15.2\n#\n# WARNING: Any manual changes made to this file will be lost when pyuic5 is\n# run again. Do not edit this file unless you know what you are doing.\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(954, 687)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.textBrowser = QtWidgets.QTextBrowser(self.centralwidget)\n self.textBrowser.setGeometry(QtCore.QRect(20, 90, 71, 571))\n self.textBrowser.setObjectName(\"textBrowser\")\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\n self.pushButton.setGeometry(QtCore.QRect(730, 10, 113, 32))\n self.pushButton.setObjectName(\"pushButton\")\n self.layoutWidget = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget.setGeometry(QtCore.QRect(101, 91, 841, 571))\n self.layoutWidget.setObjectName(\"layoutWidget\")\n self.verticalLayout = QtWidgets.QVBoxLayout(self.layoutWidget)\n self.verticalLayout.setContentsMargins(0, 0, 0, 0)\n self.verticalLayout.setObjectName(\"verticalLayout\")\n self.horizontalLayout_9 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_9.setObjectName(\"horizontalLayout_9\")\n self.line_6 = QtWidgets.QFrame(self.layoutWidget)\n self.line_6.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_6.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_6.setObjectName(\"line_6\")\n self.horizontalLayout_9.addWidget(self.line_6)\n spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_9.addItem(spacerItem)\n self.radioButton = QtWidgets.QRadioButton(self.layoutWidget)\n self.radioButton.setObjectName(\"radioButton\")\n self.horizontalLayout_9.addWidget(self.radioButton)\n self.radioButton_2 = QtWidgets.QRadioButton(self.layoutWidget)\n self.radioButton_2.setChecked(True)\n self.radioButton_2.setObjectName(\"radioButton_2\")\n self.horizontalLayout_9.addWidget(self.radioButton_2)\n self.radioButton_3 = QtWidgets.QRadioButton(self.layoutWidget)\n self.radioButton_3.setObjectName(\"radioButton_3\")\n self.horizontalLayout_9.addWidget(self.radioButton_3)\n self.radioButton_4 = QtWidgets.QRadioButton(self.layoutWidget)\n self.radioButton_4.setObjectName(\"radioButton_4\")\n self.horizontalLayout_9.addWidget(self.radioButton_4)\n self.radioButton_5 = QtWidgets.QRadioButton(self.layoutWidget)\n self.radioButton_5.setObjectName(\"radioButton_5\")\n self.horizontalLayout_9.addWidget(self.radioButton_5)\n self.line_7 = QtWidgets.QFrame(self.layoutWidget)\n self.line_7.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_7.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_7.setObjectName(\"line_7\")\n self.horizontalLayout_9.addWidget(self.line_7)\n self.refreshbutton = QtWidgets.QPushButton(self.layoutWidget)\n self.refreshbutton.setObjectName(\"refreshbutton\")\n self.horizontalLayout_9.addWidget(self.refreshbutton)\n self.line_8 = QtWidgets.QFrame(self.layoutWidget)\n self.line_8.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_8.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_8.setObjectName(\"line_8\")\n self.horizontalLayout_9.addWidget(self.line_8)\n self.horizontalLayout_7 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_7.setObjectName(\"horizontalLayout_7\")\n self.pushButton_4 = QtWidgets.QPushButton(self.layoutWidget)\n self.pushButton_4.setText(\"\")\n icon = QtGui.QIcon()\n icon.addPixmap(QtGui.QPixmap(\"left.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_4.setIcon(icon)\n self.pushButton_4.setObjectName(\"pushButton_4\")\n self.horizontalLayout_7.addWidget(self.pushButton_4)\n self.pushButton_5 = QtWidgets.QPushButton(self.layoutWidget)\n self.pushButton_5.setText(\"\")\n icon1 = QtGui.QIcon()\n icon1.addPixmap(QtGui.QPixmap(\"right.png\"), QtGui.QIcon.Normal, QtGui.QIcon.Off)\n self.pushButton_5.setIcon(icon1)\n self.pushButton_5.setObjectName(\"pushButton_5\")\n self.horizontalLayout_7.addWidget(self.pushButton_5)\n self.horizontalLayout_9.addLayout(self.horizontalLayout_7)\n spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_9.addItem(spacerItem1)\n self.verticalLayout.addLayout(self.horizontalLayout_9)\n self.horizontalLayout = QtWidgets.QHBoxLayout()\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.widget_1 = QtWidgets.QWidget(self.layoutWidget)\n self.widget_1.setObjectName(\"widget_1\")\n self.horizontalLayout.addWidget(self.widget_1)\n self.widget_2 = QtWidgets.QWidget(self.layoutWidget)\n self.widget_2.setObjectName(\"widget_2\")\n self.horizontalLayout.addWidget(self.widget_2)\n self.verticalLayout.addLayout(self.horizontalLayout)\n self.layoutWidget1 = QtWidgets.QWidget(self.centralwidget)\n self.layoutWidget1.setGeometry(QtCore.QRect(20, 50, 921, 37))\n self.layoutWidget1.setObjectName(\"layoutWidget1\")\n self.horizontalLayout_8 = QtWidgets.QHBoxLayout(self.layoutWidget1)\n self.horizontalLayout_8.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_8.setObjectName(\"horizontalLayout_8\")\n self.horizontalLayout_4 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_4.setObjectName(\"horizontalLayout_4\")\n self.pushButton_3 = QtWidgets.QPushButton(self.layoutWidget1)\n self.pushButton_3.setObjectName(\"pushButton_3\")\n self.horizontalLayout_4.addWidget(self.pushButton_3)\n self.line = QtWidgets.QFrame(self.layoutWidget1)\n self.line.setFrameShape(QtWidgets.QFrame.VLine)\n self.line.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line.setObjectName(\"line\")\n self.horizontalLayout_4.addWidget(self.line)\n self.checkBox = QtWidgets.QCheckBox(self.layoutWidget1)\n self.checkBox.setObjectName(\"checkBox\")\n self.horizontalLayout_4.addWidget(self.checkBox)\n self.line_2 = QtWidgets.QFrame(self.layoutWidget1)\n self.line_2.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_2.setObjectName(\"line_2\")\n self.horizontalLayout_4.addWidget(self.line_2)\n self.label = QtWidgets.QLabel(self.layoutWidget1)\n self.label.setMinimumSize(QtCore.QSize(50, 0))\n self.label.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label.setObjectName(\"label\")\n self.horizontalLayout_4.addWidget(self.label)\n self.lineEdit_2 = QtWidgets.QLineEdit(self.layoutWidget1)\n self.lineEdit_2.setMinimumSize(QtCore.QSize(60, 0))\n self.lineEdit_2.setMaximumSize(QtCore.QSize(60, 16777215))\n self.lineEdit_2.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit_2.setClearButtonEnabled(True)\n self.lineEdit_2.setObjectName(\"lineEdit_2\")\n self.horizontalLayout_4.addWidget(self.lineEdit_2)\n self.line_3 = QtWidgets.QFrame(self.layoutWidget1)\n self.line_3.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_3.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_3.setObjectName(\"line_3\")\n self.horizontalLayout_4.addWidget(self.line_3)\n self.horizontalLayout_5 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_5.setObjectName(\"horizontalLayout_5\")\n self.label_4 = QtWidgets.QLabel(self.layoutWidget1)\n self.label_4.setMinimumSize(QtCore.QSize(40, 0))\n self.label_4.setMaximumSize(QtCore.QSize(40, 16777215))\n self.label_4.setObjectName(\"label_4\")\n self.horizontalLayout_5.addWidget(self.label_4)\n self.lineEdit_3 = QtWidgets.QLineEdit(self.layoutWidget1)\n self.lineEdit_3.setMinimumSize(QtCore.QSize(40, 0))\n self.lineEdit_3.setMaximumSize(QtCore.QSize(40, 16777215))\n self.lineEdit_3.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit_3.setObjectName(\"lineEdit_3\")\n self.horizontalLayout_5.addWidget(self.lineEdit_3)\n self.horizontalLayout_4.addLayout(self.horizontalLayout_5)\n self.horizontalLayout_6 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_6.setObjectName(\"horizontalLayout_6\")\n self.label_6 = QtWidgets.QLabel(self.layoutWidget1)\n self.label_6.setMinimumSize(QtCore.QSize(30, 0))\n self.label_6.setMaximumSize(QtCore.QSize(30, 16777215))\n self.label_6.setObjectName(\"label_6\")\n self.horizontalLayout_6.addWidget(self.label_6)\n self.lineEdit_4 = QtWidgets.QLineEdit(self.layoutWidget1)\n self.lineEdit_4.setMinimumSize(QtCore.QSize(40, 0))\n self.lineEdit_4.setMaximumSize(QtCore.QSize(40, 16777215))\n self.lineEdit_4.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit_4.setObjectName(\"lineEdit_4\")\n self.horizontalLayout_6.addWidget(self.lineEdit_4)\n self.horizontalLayout_4.addLayout(self.horizontalLayout_6)\n self.line_4 = QtWidgets.QFrame(self.layoutWidget1)\n self.line_4.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_4.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_4.setObjectName(\"line_4\")\n self.horizontalLayout_4.addWidget(self.line_4)\n self.progressBar_2 = QtWidgets.QProgressBar(self.layoutWidget1)\n self.progressBar_2.setMinimumSize(QtCore.QSize(200, 0))\n self.progressBar_2.setMaximumSize(QtCore.QSize(200, 16777215))\n self.progressBar_2.setProperty(\"value\", 0)\n self.progressBar_2.setObjectName(\"progressBar_2\")\n self.horizontalLayout_4.addWidget(self.progressBar_2)\n self.horizontalLayout_8.addLayout(self.horizontalLayout_4)\n spacerItem2 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)\n self.horizontalLayout_8.addItem(spacerItem2)\n self.line_5 = QtWidgets.QFrame(self.layoutWidget1)\n self.line_5.setFrameShape(QtWidgets.QFrame.VLine)\n self.line_5.setFrameShadow(QtWidgets.QFrame.Sunken)\n self.line_5.setObjectName(\"line_5\")\n self.horizontalLayout_8.addWidget(self.line_5)\n self.widget = QtWidgets.QWidget(self.centralwidget)\n self.widget.setGeometry(QtCore.QRect(20, 10, 639, 35))\n self.widget.setObjectName(\"widget\")\n self.horizontalLayout_10 = QtWidgets.QHBoxLayout(self.widget)\n self.horizontalLayout_10.setContentsMargins(0, 0, 0, 0)\n self.horizontalLayout_10.setObjectName(\"horizontalLayout_10\")\n self.horizontalLayout_2 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_2.setObjectName(\"horizontalLayout_2\")\n self.pushButton_1 = QtWidgets.QPushButton(self.widget)\n self.pushButton_1.setObjectName(\"pushButton_1\")\n self.horizontalLayout_2.addWidget(self.pushButton_1)\n self.label_1 = QtWidgets.QLabel(self.widget)\n self.label_1.setMinimumSize(QtCore.QSize(50, 0))\n self.label_1.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label_1.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.label_1.setText(\"\")\n self.label_1.setObjectName(\"label_1\")\n self.horizontalLayout_2.addWidget(self.label_1)\n self.horizontalLayout_10.addLayout(self.horizontalLayout_2)\n self.horizontalLayout_3 = QtWidgets.QHBoxLayout()\n self.horizontalLayout_3.setObjectName(\"horizontalLayout_3\")\n self.pushButton_2 = QtWidgets.QPushButton(self.widget)\n self.pushButton_2.setObjectName(\"pushButton_2\")\n self.horizontalLayout_3.addWidget(self.pushButton_2)\n self.label_3 = QtWidgets.QLabel(self.widget)\n self.label_3.setObjectName(\"label_3\")\n self.horizontalLayout_3.addWidget(self.label_3)\n self.lineEdit = QtWidgets.QLineEdit(self.widget)\n self.lineEdit.setMinimumSize(QtCore.QSize(60, 0))\n self.lineEdit.setMaximumSize(QtCore.QSize(60, 16777215))\n self.lineEdit.setAlignment(QtCore.Qt.AlignCenter)\n self.lineEdit.setClearButtonEnabled(True)\n self.lineEdit.setObjectName(\"lineEdit\")\n self.horizontalLayout_3.addWidget(self.lineEdit)\n self.progressBar_1 = QtWidgets.QProgressBar(self.widget)\n self.progressBar_1.setProperty(\"value\", 0)\n self.progressBar_1.setObjectName(\"progressBar_1\")\n self.horizontalLayout_3.addWidget(self.progressBar_1)\n self.label_2 = QtWidgets.QLabel(self.widget)\n self.label_2.setMinimumSize(QtCore.QSize(50, 0))\n self.label_2.setMaximumSize(QtCore.QSize(50, 16777215))\n self.label_2.setStyleSheet(\"background-color: rgb(255, 255, 255);\")\n self.label_2.setText(\"\")\n self.label_2.setObjectName(\"label_2\")\n self.horizontalLayout_3.addWidget(self.label_2)\n self.horizontalLayout_10.addLayout(self.horizontalLayout_3)\n MainWindow.setCentralWidget(self.centralwidget)\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\"))\n self.pushButton.setText(_translate(\"MainWindow\", \"test\"))\n self.radioButton.setText(_translate(\"MainWindow\", \"1 day\"))\n self.radioButton_2.setText(_translate(\"MainWindow\", \"5 days\"))\n self.radioButton_3.setText(_translate(\"MainWindow\", \"1 month\"))\n self.radioButton_4.setText(_translate(\"MainWindow\", \"1 year\"))\n self.radioButton_5.setText(_translate(\"MainWindow\", \"max\"))\n self.refreshbutton.setText(_translate(\"MainWindow\", \"refresh\"))\n self.pushButton_3.setText(_translate(\"MainWindow\", \"Analyze\"))\n self.checkBox.setText(_translate(\"MainWindow\", \"testdata\"))\n self.label.setText(_translate(\"MainWindow\", \"factor:\"))\n self.lineEdit_2.setText(_translate(\"MainWindow\", \"2\"))\n self.label_4.setText(_translate(\"MainWindow\", \"from:\"))\n self.lineEdit_3.setText(_translate(\"MainWindow\", \"-30\"))\n self.label_6.setText(_translate(\"MainWindow\", \"to:\"))\n self.lineEdit_4.setText(_translate(\"MainWindow\", \"-2\"))\n self.pushButton_1.setText(_translate(\"MainWindow\", \"Load NASDAQ Data\"))\n self.pushButton_2.setText(_translate(\"MainWindow\", \"Limit List\"))\n self.label_3.setText(_translate(\"MainWindow\", \"max Value:\"))\n self.lineEdit.setText(_translate(\"MainWindow\", \"2\"))\n" } ]
3
root13920/360Quake
https://github.com/root13920/360Quake
efb84c8ef9949fe49fee66430794824d49c89e3a
a9ed6aaa8097b802e60527e85b7401566bd95865
0368b5c0fb500599d0b98be3c9e1cb9a30e509c7
refs/heads/main
2023-06-20T09:57:39.394753
2021-07-20T14:22:03
2021-07-20T14:22:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6162790656089783, "alphanum_fraction": 0.8255813717842102, "avg_line_length": 27.66666603088379, "blob_id": "a1d444735817eeafb613521852caf83902e5653f", "content_id": "0d562b958dc7906c232d20dbe4e6957f315339f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 604, "license_type": "no_license", "max_line_length": 111, "num_lines": 15, "path": "/README.md", "repo_name": "root13920/360Quake", "src_encoding": "UTF-8", "text": "# 360Quake\n360 QuakeAPI批量查询工具\n\n首先在后台处 :https://quake.360.cn/quake/#/personal?tab=userInfo\n![image](https://user-images.githubusercontent.com/50769953/126339512-3f248dbd-3a96-46b2-9537-011caf21918a.png)\n把API KEY复制到脚本中\n\n\n接下来就直接运行脚本即可,输入查询语法,语法与quake.360.cn网页版一致\n\n搜索结果会实时自动保存成txt\n![image](https://user-images.githubusercontent.com/50769953/126340026-f643c332-6b82-4887-bc03-4c829cd573fa.png)\n\n保存结果会自动区分是结果http还是https,自动加协议\n或者是ip主机形式\n" }, { "alpha_fraction": 0.4975757598876953, "alphanum_fraction": 0.5148484706878662, "avg_line_length": 38.759037017822266, "blob_id": "e10acb98317acf62f60c24c3751e8fdd4660becc", "content_id": "d894a0c05b567d1fd385324f2ce6f30fbe1d7ee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3494, "license_type": "no_license", "max_line_length": 183, "num_lines": 83, "path": "/360-QUAKE.py", "repo_name": "root13920/360Quake", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nimport requests\nimport sys\nversion = sys.version_info\nif version < (3, 0):\n print('The current version is not supported, you need to use python3+')\n sys.exit()\nimport json\nimport os\nimport datetime\nnowtime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M')\nnowtime='result-'+str(nowtime).replace(' ','-').replace(':','-')+'.txt'\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\nttt = \"\"\"360-QUAKE-API批量查询工具 v1.0\n作者微信:TWluR2Vla3k=\n\"\"\"\nprint(ttt)\n\n\n\n\nemail = '[email protected]'#账号,可不填\nkey = 'sxxxxx' #360 API KEY:\nmaxcount=10000 #100~10000, 每次最多检索数量,积分多可忽略\n\n\n\nheaders = {'Content-Type': 'application/json',\"X-QuakeToken\": key}\ncount=0\nstarts=0\ntext=str(input('请输入查询语法:'))\nopen(nowtime,'a',encoding='utf-8').write(text+'\\n')\nkeyword=text\nwhile True:\n try:\n data = {\"query\": keyword, \"start\": starts, \"size\": 100}\n url = 'https://quake.360.cn/api/v3/search/quake_service'\n req = requests.post(url,data=json.dumps(data),verify=False,headers=headers,timeout=50)\n rsp = json.loads(req.text)\n #print(rsp)\n starts=starts+100\n if len(rsp['data'])>=1:\n for xxx in rsp['data']:\n try:\n if 'http/ssl' == xxx['service']['name']:\n count=count+1\n print('https://'+xxx['service']['http']['host'] + ':' + str(xxx['port']), xxx['service']['http']['title'],'\\t第:'+str(count))\n open(nowtime, 'a', encoding='utf-8').write(str('https://'+xxx['service']['http']['host'])+':'+ str(xxx['port'])+'\\t'+str(xxx['service']['http']['title'])+'\\n')\n elif 'http' == xxx['service']['name']:\n count = count + 1\n print('http://' + xxx['service']['http']['host'] + ':' + str(xxx['port']), xxx['service']['http']['title'],'\\t第:'+str(count))\n open(nowtime, 'a', encoding='utf-8').write(str('https://'+xxx['service']['http']['host'])+':'+ str(xxx['port'])+'\\t'+str(xxx['service']['http']['title'])+'\\n')\n else:#非HTTP相关,协议数据\n count = count + 1\n print(str(xxx['service']['name']) + '\\t' + str(xxx['ip'])+ '\\t'+str(xxx['hostname'])+str(xxx['port']),'\\t第:'+str(count))\n open(nowtime, 'a', encoding='utf-8').write(str(xxx['service']['name']) + '\\t' + str(xxx['ip'])+ '\\t'+str(xxx['hostname'])+str(xxx['port'])+'\\t'+'\\n')\n except Exception as e:\n #print(e)\n pass\n else:\n if count !=0:\n print('本次检索到',count,'条数据,结果保存在'+nowtime)\n sys.exit()\n elif count ==0:\n print('本次检索到', count, '条数据')\n os.remove(nowtime)\n sys.exit()\n if count>=maxcount:\n print('本次检索到', count, '条数据,结果保存在' + nowtime)\n sys.exit()\n except Exception as e:\n try:\n if req.status_code==401:\n print('无效的key')\n os.remove(nowtime)\n sys.exit()\n except Exception as e2:\n pass\n os.remove(nowtime)\n print('出错啦',e)\n sys.exit()\n" } ]
2
marcoeqms/classicassistmacrocopy
https://github.com/marcoeqms/classicassistmacrocopy
5cfc3421270623d850c46f4ffd035e91fd56178a
e00cc23d34b722c5b2a0c2f6668a52a2eee6ae08
20ffcf659d71c70dd61ea043ea79f172eb451801
refs/heads/master
2023-06-24T12:32:46.640400
2021-07-22T14:06:47
2021-07-22T14:06:47
388,484,002
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7795823812484741, "alphanum_fraction": 0.781902551651001, "avg_line_length": 25.9375, "blob_id": "54c218527f706f2bc18d79c38adb6c23d3deb3a2", "content_id": "4588d24a0e8e2435b35c4bf329fbaffca14a37ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 107, "num_lines": 16, "path": "/Macros/Advanced/Examples/hide_all_houses.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Hide All Multis\n# Description: Issues a remove object on all multis in range, useful for looking inside the walls of houses\n# Author: Reetus\n# Era: Any\n\nimport clr\nimport System\nclr.AddReference('System.Core')\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\nfrom ClassicAssist.UO.Commands import RemoveObject\n\nmultis = Engine.Items.Where(lambda i: i.ArtDataID == 2)\n\nfor x in multis:\n\tRemoveObject(x.Serial)\n" }, { "alpha_fraction": 0.5457249283790588, "alphanum_fraction": 0.5605947971343994, "avg_line_length": 20.015625, "blob_id": "8c90438efa58517e72baabd14cc293e405b9c8e1", "content_id": "ba80ff71dbb7ab07c69663de3623eafdc0dc8b77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1345, "license_type": "no_license", "max_line_length": 80, "num_lines": 64, "path": "/Macros/Common/check_durability.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Durability check\n# Description: Checks all items for durability and show alerts\n# Author: Mordor\n# Era: AOS\n\nfrom Assistant import Engine\nlayers = [\n 'OneHanded',\n 'TwoHanded',\n 'Shoes',\n 'Pants',\n 'Shirt',\n 'Helm',\n 'Gloves',\n 'Ring',\n 'Talisman',\n 'Neck',\n 'Waist',\n 'InnerTorso',\n 'Bracelet',\n 'MiddleTorso',\n 'Earrings',\n 'Arms',\n 'Cloak',\n 'OuterTorso',\n 'OuterLegs',\n 'InnerLegs',\n]\n\n# Amount of durability to alert\nminDurability = 20\n# Checks every 5 secs\ncheckDelay = 1000 * 60 # every 1 min\n\n\ndef property_exists(serial, cliloc):\n item = Engine.Items.GetItem(serial)\n\n if (item == None or item.Properties == None):\n return False\n\n for x in item.Properties:\n if x.Cliloc == cliloc:\n return True\n\n return False\n\n\ndef check_durability():\n while not Dead('self'):\n for layer in layers:\n if FindLayer(layer) and property_exists(GetAlias('found'), 1060639):\n durability = PropertyValue[int]('found', 'durability')\n Pause(500)\n\n if durability < minDurability:\n HeadMsg(\"ATTENTION!! \\\"\" + layer + \"\\\": \" +\n str(durability), 'self')\n MoveItem('found', 'self')\n\n Pause(checkDelay)\n\n\ncheck_durability()\n" }, { "alpha_fraction": 0.6488941311836243, "alphanum_fraction": 0.7093207240104675, "avg_line_length": 22.44444465637207, "blob_id": "1ef1ee205c3734edc5b1870ac2cc765d0578a794", "content_id": "dd4294785c76d4376a5cfd054d7ccfdda3e900ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2532, "license_type": "no_license", "max_line_length": 101, "num_lines": 108, "path": "/Macros/Crafting/Alchemy/potion_crafter.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Potion Factory\n# Description: Crafts the selected potion up to the selected maximum amount\n# Author: Reetus\n# Shard: UO Heritage\n\nimport clr\nimport System\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\n\nmakeMax = 2500\nmakeCount = 0\ncraftGumpId = 0x38920abd\n\nif not FindAlias('resChest'):\n\tresChest = PromptAlias('resChest')\n\ndef Tinker(category, button):\n\tUseType(0x1eb8)\t\n\tReplyGump(craftGumpId, category)\n\tWaitForGump(craftGumpId, 5000)\n\tReplyGump(craftGumpId, button)\n\tWaitForGump(craftGumpId, 5000)\n\nclass PotionInfo:\n\tdef __init__(self, name, itemid, hue, gumpButton1, gumpButton2, reagent):\n\t\tself.name = name\n\t\tself.itemid = itemid\n\t\tself.hue = hue\n\t\tself.gumpButton1 = gumpButton1\n\t\tself.gumpButton2 = gumpButton2\n\t\tself.reagent = reagent\n\npotionInfo = [\n\tPotionInfo(\"Greater Cure\", 0xf07, 0, 1, 51, 0xf84),\n\tPotionInfo(\"Greater Heal\", 0xf0c, 0, 1, 30, 0xf85),\n\tPotionInfo(\"Greater Poison\", 0xf0a, 0, 15, 16, 0xf88),\n\tPotionInfo(\"Greater Refreshment\", 0xf0b, 0, 1, 9, 0xf7a)\n]\n\n(res, selection) = SelectionPrompt(potionInfo.Select(lambda i: i.name))\n\nif not res:\n\tStop()\n\ninfo = potionInfo[selection]\n\n(res, name) = MessagePrompt(\"Amount?\", str(makeMax))\n\nif not res:\n\tStop()\n\nmakeMax = int(name)\n\nmakeCount = CountType(info.itemid, \"backpack\")\nmakeCount = makeCount + CountType(info.itemid, GetAlias('resChest'))\n\nwhile makeCount < makeMax:\n\t\n\tprint makeCount\n\t\n\tcount = CountType(info.reagent, \"backpack\")\n\t\n\t# Reagent\n\tif count < 100:\n\t\tMoveType(info.reagent, GetAlias('resChest'), \"backpack\", -1, -1, -1, 0, 100)\n\t\n\t# Tinker Tools\n\tcount = CountType(0x1eb8, 'backpack')\n\t\n\tif count < 3:\n\t\tTinker(15, 23)\n\t\n\t# Mortar and pestal\n\tcount = CountType(0xe9b, 'backpack')\n\n\tif count < 3:\n\t\tTinker(15, 9)\n\t\t\n\t# Bottles\n\tcount = CountType(0xf0e, 'backpack')\n\t\n\tif count < 20:\n\t\tMoveType(0xf0e, GetAlias('resChest'), 'backpack', -1, -1, -1, 0, 20)\n\t\tPause(1000)\n\t\t\n\tUseType(0xe9b)\n\tWaitForGump(craftGumpId, 5000)\n\tReplyGump(craftGumpId, info.gumpButton1)\n\tWaitForGump(craftGumpId, 5000)\n\tReplyGump(craftGumpId, info.gumpButton2)\n\tWaitForGump(craftGumpId, 5000)\n\t\n\tres,gump = Engine.Gumps.GetGump(craftGumpId)\n\t\n\tif res:\n\t\t#X: 170, Y: 295, Type: xmfhtmlgumpcolor, Cliloc: 500279, Text: You pour the potion into a bottle...\n\t\tele = gump.Pages[0].GetElementByXY(170, 295)\n\t\t\n\t\tif ele != None and ele.Cliloc == 500279:\n\t\t\tmakeCount = makeCount + 1\n\t\t\t\n\tif Weight() > MaxWeight() - 100:\n\t\tMoveType(info.itemid, \"backpack\", GetAlias('resChest'))\n\t\tPause(2000)\n\t\t\nprint 'Finished'\n" }, { "alpha_fraction": 0.5776499509811401, "alphanum_fraction": 0.6353327631950378, "avg_line_length": 27.434579849243164, "blob_id": "883b5d8ef983c4e50f1a70866a7aaca73d6968c5", "content_id": "4b0a0079b0d8fd4e3ead3f20fb17ea9ed33151e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6085, "license_type": "no_license", "max_line_length": 131, "num_lines": 214, "path": "/Macros/PVM/bandage_pets.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Bandage Dual & Solo Pets\n# Description: Auto bandage pets\n# Author: qk\n# Era: Any\n# Date: Mon Feb 01 2021\n\n#// create pet list if not exist\nRemoveList(\"petlist\")\nif not ListExists(\"petlist\"):\n\tCreateList(\"petlist\")\n\t#// add an entry for each pet you hunt with:\n\tPushList(\"petlist\", 0x000001) #// Meta\n\tPushList(\"petlist\", 0x000001) #// Meta\n\tPushList(\"petlist\", 0x000001) #// Spider\n\tPushList(\"petlist\", 0x000001) #// Spider\n\n#// removes pets if mounted, stabled or you get too far away\nif not FindAlias(\"pet1\") or not FindObject(\"pet1\", 30):\n\tUnsetAlias(\"pet1\")\n\tHeadMsg(\"Cleared Pet1\", \"self\", 33)\n#if FindAlias(\"pet2\") or not FindObject(\"pet2\", 30):\n#\tUnsetAlias(\"pet2\")\n#\tHeadMsg(\"Cleared Pet2\", \"self\", 33)\n\t\n#// makes sure the pets never equal each other\nif FindAlias(\"pet1\") and FindAlias(\"pet2\"):\n\tif GetAlias(\"pet1\") == GetAlias(\"pet2\"):\n\t\tUnsetAlias(\"pet2\")\n \t\n#// search pets\nfor i in GetList(\"petlist\"): \n\tif FindObject(i, 30):\n\t\t#if not FindObject(\"pet1\"):\n\t\t#SysMessage(\"SetAlias pet1 \" + hex(i))\n\t\t\t#SetAlias(\"pet1\", i)\n\t\tSetAlias(\"pet1\", i)\n\t\t\t\nfor i in GetList(\"petlist\"): \n\tSetAlias(\"petTemp\", i)\n\tif (FindObject(i, 30) and GetAlias(\"petTemp\") != GetAlias(\"pet1\")):\n\t\t#if not FindObject(\"pet2\"):\n\t\t#SysMessage(\"SetAlias pet2 \" + hex(i))\n\t\t\t#SetAlias(\"pet2\", i)\n\t\tSetAlias(\"pet2\", i)\t\n\t\t\t\t\n#// clear target queue\n#ClearTargetQueue()\n#// clear journal\n#ClearJournal()\n\n#// check if player dead\nif Dead(\"self\"):\n\tStop()\n\t\nif not FindType(0xe21, -1, \"backpack\"):\n\tHeadMsg(\"Out of Bandages\", \"self\", 33)\n\tStop()\n\n#// bandage timer\nif not TimerExists(\"VetBandage\"):\n\tCreateTimer(\"VetBandage\")\n\t\n#// Select timer timeout\nif not TimerExists(\"SelectTimer\"):\n\tCreateTimer(\"SelectTimer\")\n\t\nif not FindAlias(\"pet1\"):\n\tHeadMsg(\"Select First Pet\", \"self\", 33)\n\tPromptAlias(\"pet1\")\n\tSetTimer(\"SelectTimer\", 0)\n\twhile WaitingForTarget() and Timer(\"SelectTimer\") < 9999:\n\t\tPause(100)\n\t\t\n\tif ((GetAlias(\"pet1\") == GetAlias(\"self\")) or (GetAlias(\"pet1\") == False)):\n\t\tUnsetAlias(\"pet1\")\n\t\tHeadMsg(\"No Valid Target\", \"self\", 33)\n\t\tStop()\n\t\nif not GetAlias(\"pet2\") == 0x40000001 and not FindAlias(\"pet2\") :\n\tHeadMsg(\"Select Second Pet\", \"self\", 33)\n\tPromptAlias(\"pet2\")\n\tSetTimer(\"SelectTimer\", 0)\n\twhile WaitingForTarget() and Timer(\"SelectTimer\") < 9999:\n\t\tPause(100)\n\t\t\n\tif ((GetAlias(\"pet2\") == GetAlias(\"self\")) or (GetAlias(\"pet2\") == False)):\n\t\t#UnsetAlias(\"pet2\")\n\t\tHeadMsg(\"No Valid Target\", \"self\", 33)\n\t\tSetAlias(\"pet2\", 0x40000001) # solo pet\n\t\n#if not FindAlias(\"pet1\") or not FindAlias(\"pet2\"):\n#\tHeadMsg(\"No Pets Found\", \"self\", 33)\n#\tStop()\n\t\nif not FindObject(GetAlias(\"pet1\")):\n\tHeadMsg(\"No Pet1 Found\", \"self\", 33)\n\tStop()\n\t\nif GetAlias(\"pet2\") == True and not FindObject(GetAlias(\"pet2\")):\n\tHeadMsg(\"No Pet2 Found\", \"self\", 33)\n\tStop()\n\n##// Bless self if overweight\n#if ( Hits(\"pet1\") == MaxHits(\"pet1\") and Hits(\"pet2\") == MaxHits(\"pet2\") ) and ( Weight() > 390 ) and not ( BuffExists(\"Bless\") ):\n#\tCancelTarget()\n#\tCast(\"Bless\", \"self\")\n#\tWaitForTarget(2000)\n#\tTarget(\"self\")\n\nif (GetAlias(\"pet2\") == 0x40000001):\n\t#// Bandage Solo Pet\n\tif Hits(\"pet1\") > ( MaxHits(\"pet1\") - 5 ):\n\t\t#HeadMsg(\"Full Healed - Stop\", \"self\", 33)\n\t\tStop()\n\t\t\n\tif InRange(\"pet1\", 1) and Timer(\"VetBandage\") >= 6100:\n\t\tif not InRange(\"pet1\", 2): #and Timer(\"VetBandage\") >= 6100:\n\t\t\tHeadMsg(\"Get Closer 1\", \"self\", 33)\n\t\t\t#Stop()\n\t\t\tPause(500)\n\t\telse:\n\t\t\tif Hits(\"pet1\") < ( MaxHits(\"pet1\") - 1 ):\n\t\t\t\tCancelTarget()\n\t\t\t\tUseType(0xe21, -1, \"backpack\")\n\t\t\t\tWaitForTarget(2000)\n\t\t\t\tTarget(\"pet1\")\n\t\t\t\tSetTimer(\"VetBandage\", 0)\n\t\t\t\t#HeadMsg(\"Heal Start Pet1\", \"self\", 80)\n\t\t\t\tHeadMsg(\"Healing \" + Name(\"pet1\"), \"self\", 33)\n\t\t\t\tPlayMacro(\"Client Timer Pet Bandage\")\n\t\t\telse:\n\t\t\t\tStop()\nelse:\n\t#// Bandage Dual Pets\n\tif Hits(\"pet1\") > ( MaxHits(\"pet1\") - 5 ) and Hits(\"pet2\") > ( MaxHits(\"pet2\") - 5 ):\n\t\t#HeadMsg(\"Full Healed - Stop\", \"self\", 33)\n\t\tStop()\n\t\n\tif Hits(\"pet1\") != MaxHits(\"pet1\") or Hits(\"pet2\") != MaxHits(\"pet2\"):\n\t\t#// Bandage Pet1\n\t\tif DiffHits(\"pet1\") > DiffHits(\"pet2\"):\n\t\t\tif not InRange(\"pet1\", 2): #and Timer(\"VetBandage\") >= 6100:\n\t\t\t\tHeadMsg(\"Get Closer 1\", \"self\", 33)\n\t\t\t\tPause(500)\n\t\t\telse:\n\t\t\t\tif Hits(\"pet1\") < ( MaxHits(\"pet1\") - 1 ):\n\t\t\t\t\tCancelTarget()\n\t\t\t\t\tUseType(0xe21, -1, \"backpack\")\n\t\t\t\t\tWaitForTarget(2000)\n\t\t\t\t\tTarget(\"pet1\")\n\t\t\t\t\tSetTimer(\"VetBandage\", 0)\n\t\t\t\t\tHeadMsg(\"Healing \" + Name(\"pet1\"), \"self\", 33)\n\t\t\t\t\tPlayMacro(\"Client Timer Pet Bandage\")\n\t\telse:\n\t\t#// Bandage Pet2\n\t\t\tif not InRange(\"pet2\", 2): #and Timer(\"VetBandage\") >= 6100:\n\t\t\t\tHeadMsg(\"Get Closer 2\", \"self\", 33)\n\t\t\t\tPause(500)\n\t\t\telse:\n\t\t\t\tif Hits(\"pet2\") < ( MaxHits(\"pet2\") - 1 ):\n\t\t\t\t\tCancelTarget()\n\t\t\t\t\tUseType(0xe21, -1, \"backpack\")\n\t\t\t\t\tWaitForTarget(2000)\n\t\t\t\t\tTarget(\"pet2\")\n\t\t\t\t\tSetTimer(\"VetBandage\", 0)\n\t\t\t\t\tHeadMsg(\"Healing \" + Name(\"pet2\"), \"self\", 33)\n\t\t\t\t\tPlayMacro(\"Client Timer Pet Bandage\")\n\t\t\t\t\n#// Ress Pet\nif GumpExists(0x4da72c0) and InGump(0x4da72c0, \"Wilt thou sanctify the resurrection of\"):\n\tReplyGump(0x4da72c0, 1)\n\tHeadMsg(\"Pet Ressed\", \"self\", 60)\n\tPause(50)\n\tHeadMsg(\"Pet Ressed\", \"self\", 70)\n\tPause(50)\n\tHeadMsg(\"Pet Ressed\", \"self\", 80)\n\tPause(50)\n\t\n#// Auto Protection Self\nif not TimerExists(\"Protect\"):\n\tCreateTimer(\"Protect\")\n\tSetTimer(\"Protect\", 250000)\n\nif Timer(\"Protect\") >= 250000:\n\tCast(\"Protection\", \"self\")\n\tSetTimer(\"Protect\", 0)\n\n#// Auto Bless Self\n#if not BuffExists(\"Bless\") and Timer(\"VetBandage\") <= 6100:\n#\tCancelTarget()\n#\tCast(\"Bless\", \"self\")\n#\t#WaitForTarget(5000)\n# #WaitForTargetOrFizzle(5000):\n \nClearJournal()\nif Timer(\"VetBandage\") <= 6100:\n\twhile Timer(\"VetBandage\") <= 6100:\n\t\tif InJournal(\"finish applying the bandage\", \"system\"):\n\t\t\tHeadMsg(\"Heal Complete\", \"self\", 88)\n\t\t\tbreak\n\t\tif InJournal(\"too far away\", \"system\"):\n\t\t\tHeadMsg(\"Too Far Away\", \"self\", 33)\n\t\t\tbreak\n\t\tif InJournal(\"stay close enough\", \"system\"):\n\t\t\tHeadMsg(\"Stay Close\", \"self\", 33)\n\t\t\tbreak\n\t\tif InJournal(\"you are able to resurrect\", \"system\"):\n\t\t\tHeadMsg(\"Ress Detected\", \"self\", 33)\n\t\t\tbreak\n\t\tif InJournal(\"you fail to resurrect\", \"system\"):\n\t\t\tHeadMsg(\"Ress Fail\", \"self\", 33)\n\t\t\tbreak\n\t\t\t\nSetTimer(\"VetBandage\", 9999)\n" }, { "alpha_fraction": 0.6896024346351624, "alphanum_fraction": 0.6957186460494995, "avg_line_length": 25.200000762939453, "blob_id": "f0a61fd70d4b489eadab6fdfddf67fbe90cd4fbf", "content_id": "a0a0674fb0ae56444e1d4b0dc4e97376b8d41ce7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 86, "num_lines": 25, "path": "/Macros/Advanced/Movement/faster_run.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Faster Run\n# Description: Run without waiting for movement accepted packets to speed up movement\n# Author: Reetus\n# Era: Any\n\nfrom Assistant import Engine\nfrom ClassicAssist.UO import UOMath\nfrom ClassicAssist.UO.Data import Direction\n\ndef DirectionTo(alias):\n mobile = Engine.Mobiles.GetMobile(GetAlias(alias))\n \n if mobile == None:\n return Direction.Invalid\n\n return UOMath.MapDirection( Engine.Player.X, Engine.Player.Y, mobile.X, mobile.Y )\n \ndef FRun(dir):\n if dir == Direction.Invalid:\n return\n Engine.Move(dir, True) \n \nwhile Distance('enemy') > 1: \n FRun(DirectionTo('enemy'))\n Pause(100)" }, { "alpha_fraction": 0.5827725529670715, "alphanum_fraction": 0.5972409248352051, "avg_line_length": 34.380950927734375, "blob_id": "ea148981674136ecb1882648320f0a7a59e89816", "content_id": "5c6b4004c543b0b6eaa8242a9887a08ac8f474df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2972, "license_type": "no_license", "max_line_length": 118, "num_lines": 84, "path": "/Macros/Skills/Peacemaking/train_peacemaking.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Peacemaking training\n# Description: Uses the Peacemaking skill on the player to train Peacemaking to GM\n# Author: Mordor\n# Era: Any\n\n# Script variables configuration\npeacemaking_timer_milliseconds = 10000\njournal_entry_delay_milliseconds = 1000\nskill_cap = SkillCap('Peacemaking')\n\n\ndef train_peacemaking():\n '''\n Trains Peacemaking to GM\n '''\n # Script variables\n global peacemaking_timer_milliseconds\n global journal_entry_delay_milliseconds\n global skill_cap\n\n instruments = [0x2805, 0x0e9c, 0x0eb3, 0xeb2, 0x0eb1, 0x0e9e, 0x0e9d]\n\n if Skill('Peacemaking') == skill_cap:\n MessageBox(\"Done\", 'You\\'ve already maxed out Peacemaking!')\n return\n\n # Initialize skill timers\n SetTimer('peacemaking_timer', peacemaking_timer_milliseconds)\n\n # Initialize the journal\n ClearJournal()\n\n while not Dead('self') and Skill('Peacemaking') < skill_cap:\n if Timer('peacemaking_timer') >= peacemaking_timer_milliseconds:\n # Clean skill timers and jornal\n SetTimer('peacemaking_timer', 0)\n ClearJournal()\n\n UseSkill('Peacemaking')\n\n Pause(journal_entry_delay_milliseconds)\n\n # Handle the Journal response\n if InJournal('What instrument shall you play?'):\n for i in instruments:\n if FindType(i, -1, \"backpack\"):\n break\n\n if not FindAlias('found'):\n MessageBox(\"Error\", \"No instrument to peacemake with.\")\n return\n\n WaitForTarget(1000)\n Target('found')\n\n WaitForTarget(1000)\n Target('self')\n\n # Wait for the journal entry to come up\n while Timer('peacemaking_timer') < peacemaking_timer_milliseconds:\n\n if (InJournal('You play hypnotic music, calming your target.', 'regular') or\n InJournal('You play your hypnotic music, stopping the battle.', 'regular') or\n InJournal('You attempt to calm everyone, but fail.', 'regular') or\n InJournal('You play hypnotic music, but there is nothing in range for you to calm.', 'regular') or\n InJournal('You attempt to calm your target, but fail.', 'regular') or\n InJournal('You have no chance of calming that creature', 'regular') or\n InJournal(\n 'You play poorly, and there is no effect.', 'regular')\n ):\n # Skill was used successfully, even if the enemy was not successfully put to peace\n SetTimer('peacemaking_timer',\n peacemaking_timer_milliseconds)\n\n Pause(journal_entry_delay_milliseconds)\n\n ClearJournal()\n\n # Wait a little bit so that the while loop doesn't consume as much CPU\n Pause(50)\n\n\n# Start Peacemaking training\ntrain_peacemaking()\n" }, { "alpha_fraction": 0.5907407402992249, "alphanum_fraction": 0.6265432238578796, "avg_line_length": 35, "blob_id": "e3f041d26e26bc9fb8e516566650822bd1c6e95a", "content_id": "b45e43c17f8c376e5b38659d59a26977fdb28038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1620, "license_type": "no_license", "max_line_length": 119, "num_lines": 45, "path": "/Macros/Skills/Magery/train_magery.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Magery training to cap\n# Description: Train Magery to cap\n# Author: Mordor\n# Era: Any\n\nclass SpellInfo:\n def __init__(self, name, mana_cost, min_skill, delay_in_ms, target=None):\n self.name = name\n self.mana_cost = mana_cost\n self.min_skill = min_skill\n self.delay_in_ms = delay_in_ms\n self.target = target\n\n\n# When training, target an inanimate object such as anything on the ground or in your backpack to avoid causing damage.\nPromptAlias('spell_target')\nmagery_cap = SkillCap('Magery')\nping = 800\n\nwhile not Dead('self') and Skill('Magery') < magery_cap:\n # Set mana and spell cast according to your stats\n spells = [\n SpellInfo('Fireball', 7, 30, 1000, GetAlias('spell_target')),\n SpellInfo('Lightning', 10, 45, 1250, GetAlias('spell_target')),\n SpellInfo('Paralyze', 12, 55, 1500, GetAlias('spell_target')),\n SpellInfo('Invisibility', 18, 65, 1750, GetAlias('self')),\n SpellInfo('Flame Strike', 30, 75, 2000, GetAlias('spell_target')),\n SpellInfo('Earthquake', 40, 90, 2250, GetAlias('spell_target')),\n ]\n\n current_spell = None\n\n for spell in spells:\n if spell.min_skill <= Skill('Magery'):\n current_spell = spell\n\n if Mana('self') > current_spell.mana_cost:\n Cast(current_spell.name, current_spell.target)\n Pause(current_spell.delay_in_ms + ping)\n else:\n while not BuffExists('Active Meditation') or not Mana('self') == MaxMana('self'):\n UseSkill('Meditation')\n Pause(4000)\n while Mana('self') < MaxMana('self'):\n Pause(1000)\n" }, { "alpha_fraction": 0.6313868761062622, "alphanum_fraction": 0.6861313581466675, "avg_line_length": 21.83333396911621, "blob_id": "f107a5a7b6636c9d0ee856ad3159ddee57a32fe0", "content_id": "4c30d3d8a1755a2e15f49cc4280f4d2ca73aebe8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 822, "license_type": "no_license", "max_line_length": 71, "num_lines": 36, "path": "/Macros/Crafting/Mining/smelt_ore.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Smelt Ore\n# Description: Smelt ore from a container and put ingots into container\n# Author: Reetus\n# Era: Any\n\nfrom Assistant import Engine\n\nif not FindObject('ore chest'):\n\tPromptAlias('ore chest')\n\nif not FindObject('forge'):\n\tPromptAlias('forge')\n\noreTypes = [0x19b7, 0x19b8, 0x19b9, 0x19ba]\n\nClearIgnoreList()\n\nfor ore in oreTypes:\n\twhile FindType(ore, -1, 'ore chest'):\n\t\tif Graphic('found') == 0x19b7:\n\t\t\titem = Engine.Items.GetItem(GetAlias('found'))\n\t\t\tif item.Count <= 1:\n\t\t\t\tIgnoreObject('found')\n\t\t\t\tcontinue\n\t\tUseObject('found')\n\t\tWaitForTarget(5000)\n\t\tTarget('forge')\n\t\tPause(1000)\n\t\twhile FindType(0x1bf2, 3):\n\t\t\tMoveItem('found', 'ore chest')\n\t\t\tPause(1000)\n\t\t\tIgnoreObject('found')\n\t\twhile FindType(0x1bf2, -1, 'backpack'):\n\t\t\tMoveItem('found', 'ore chest')\n\t\t\tPause(1000)\n\t\t\tIgnoreObject('found')\n" }, { "alpha_fraction": 0.6865671873092651, "alphanum_fraction": 0.7505330443382263, "avg_line_length": 30.266666412353516, "blob_id": "f2ea8885d0721ab883feb32d47dba863f53524ad", "content_id": "c03cec00f416b752928fce61451e1f07bb088ac5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 233, "num_lines": 15, "path": "/Macros/Skills Crafting/simpleminer.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Simple Miner\n# Description: A simple miner i have made that mines until a certain weight is met then just recalls to the blacksmith area in luna to smelt the ore and bank then the script stops and will start when i make it back the my mining area\n# Author: HellForge\n# Era: Any\n# Date: Sun Mar 21 2021\n\nUseType(0xf39)\nWaitForTarget(5000)\nTargetTileRelative(\"self\", 1, False)\n\nif Weight() >= 415:\n\tCast(\"Recall\")\n\tWaitForTarget(5000)\n\tTarget(0x40047054)\n\tStop()\n" }, { "alpha_fraction": 0.7287449240684509, "alphanum_fraction": 0.7570850253105164, "avg_line_length": 27.090909957885742, "blob_id": "569e8fd8f94bd9a9124c49cafe8be6a0af2013e5", "content_id": "37f29bf416784738113af6dc8bfdb6fbfd25ebaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 161, "num_lines": 44, "path": "/Macros/Utility/combinestacks.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Combine Stacks\n# Description: Combine multiple stacks of the same item id into one (or more) stacks of 60000\n# Author: Reetus\n# Era: Any\n# Date: Wed Jan 27 2021\n\nimport clr\nimport System\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\nfrom ClassicAssist.UO.Data import TileData, TileFlags\n\nif PromptAlias('container') == 0:\n\tStop()\n\nif not WaitForContents('container', 5000):\n\tprint 'No contents'\n\tStop()\n\ncontainer = Engine.Items.GetItem(GetAlias('container')).Container\n\nwhile True:\n\tdestStack = container.SelectEntity(lambda i: i.Count < 60000 and TileData.GetStaticTile(i.ID).Flags.HasFlag(TileFlags.Stackable) and not InIgnoreList(i.Serial))\n\n\tif destStack == None:\n\t\tStop()\n\n\tprint destStack\n\n\tneeded = 60000 - destStack.Count\n\n\tsourceStack = container.SelectEntities( lambda i: i.ID == destStack.ID and i.Hue == destStack.Hue and i.Serial != destStack.Serial and i.Count != 60000 )\n\t\n\tif sourceStack == None:\n\t\tIgnoreObject(destStack.Serial)\n\t\tcontinue;\n\t\t\n\tsourceStack = sourceStack.OrderBy( lambda i: i.Count ).FirstOrDefault()\n\t\n\tprint sourceStack\n\n\tMoveItem(sourceStack.Serial, destStack.Serial, sourceStack.Count if needed > sourceStack.Count else needed)\n\tPause(1000)" }, { "alpha_fraction": 0.5615050792694092, "alphanum_fraction": 0.5875542759895325, "avg_line_length": 21.29032325744629, "blob_id": "b5e4b803e0c2f7d355a5a68f6d29745cbfc8532b", "content_id": "30a376e59a65fca988d006b786a74120a3b5522c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 74, "num_lines": 31, "path": "/Macros/Advanced/Gumps/extract_hp_alore_gump.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Animal Lore Gump HP\n# Description: Use gump parser to extract hp / maxhp from animal lore gump\n# Author: Reetus\n# Shard: OSI\n\nfrom Assistant import Engine\nimport re\n\ndef GetLoreGumpHP():\n if not GumpExists(0x1db):\n return (0, 0)\n \n res,gump = Engine.Gumps.GetGump(0x1db)\n element = gump.Pages[1].GetElementByXY(180,92)\n \n if element == None:\n return (0, 0)\n \n matches = re.match('.*>(\\d+)/(\\d+)<.*', element.Text)\n \n if matches == None:\n return (0, 0)\n \n hp = int(matches.group(1))\n maxhp = int(matches.group(2))\n \n return (hp, maxhp)\n\n(hp, maxhp) = GetLoreGumpHP()\n\nHeadMsg(str(hp) + ' / ' + str(maxhp), 'self')\n" }, { "alpha_fraction": 0.7390457391738892, "alphanum_fraction": 0.7419669032096863, "avg_line_length": 19.959182739257812, "blob_id": "8af4d43c0d28f08ba8773b38a1a8585fb3516fc9", "content_id": "989c018ff972d99b717ed950b496013c3eb6ff19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1027, "license_type": "no_license", "max_line_length": 203, "num_lines": 49, "path": "/README.md", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# ClassicAssist Macro Repository\n\n### Contributing\n\n[Video Instructional](https://www.youtube.com/watch?v=KqCGBJo-O_I&feature=youtu.be)\n\n[Video Instructional using new share button in Macros tab](https://www.youtube.com/watch?v=wfOUYc4iF0g)\n\nTo contribute to this repository, send a pull request with your macro placed in the 'Macros' directory with a directory structure that describes the category of your macro, such as 'Skills\\Animal Taming'\n\n### File Header\n\nInclude the following information at the start of your macro to provide metadata, such as the following\n\nIf you macro is shard specific:\n\n```py\n# Name: Delucia Bulls\n# Description: Walks around delucia taming bulls\n# Author: Reetus\n# Shard: OSI\n```\n\nOr if it era specific:\n\n```py\n# Name: Delucia Bulls\n# Description: Walks around delucia taming bulls\n# Author: Reetus\n# Era: TOL\n```\n\nThe following fields are required:\n* Name\n* Description\n* Author\n\nAnd must include one of the following:\n* Shard\n* Era\n\nEra may be one of the following:\n* T2A\n* UOR\n* AOS\n* SA\n* HS\n* TOL\n* Any\n" }, { "alpha_fraction": 0.558650553226471, "alphanum_fraction": 0.5714127421379089, "avg_line_length": 29.54576301574707, "blob_id": "e9c6eb6a67e33961f114421682d9af0bde6645d0", "content_id": "463f2ca7efaa0ff4bf86757f539ef19232e82a03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9011, "license_type": "no_license", "max_line_length": 163, "num_lines": 295, "path": "/Macros/Advanced/Sampire/sampire_ai.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Sampire AI 0.1.2\n# Description: Automate Sampire build to cast proper abilities, move, loot and e.t.c\n# Author: Mordor\n# Era: TOL\n\nfrom ClassicAssist.UO.Data import Direction\nfrom ClassicAssist.UO import UOMath\nimport System\nfrom Assistant import Engine\nimport clr\n\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\n\nWAITING = 500 # Set depending on your ping\nHEAL_AT = 90 # HP\nONE_ENEMY_FARM = False # Set to True if you fight with one type on enemies\nPUNCH_RANGE = 1\nPLAYER_STUCK_TIMER_MILLISECONDS = 5000\nHOME_RUNE_OR_BOOK = PromptAlias(\n 'home_rune_or_book') # set rune or book to recall\n\n\nclass SpellFn:\n BUSHIDO = Cast\n VIRTUE = InvokeVirtue\n CHIVALRY = Cast\n ATTACK = 'ATTACK'\n CLICKING = 'CLICKING'\n MOVE = 'MOVE'\n CLEAR_TARGET = 'CLEAR_TARGET'\n SECONDARY_ATTACK = 'SECONDARY_ATTACK'\n HOME_RECALL = 'HOME_RECALL'\n\n\nclass SpellInfo:\n def __init__(self, name, mana_cost, min_skill, delay_in_ms, priority, when_to_cast, spell_fn, targeting=None):\n self._name = name\n self._mana_cost = mana_cost\n self.min_skill = min_skill\n self._delay_in_ms = delay_in_ms\n self.priority = priority\n self.when_to_cast = when_to_cast\n self._spell_fn = spell_fn\n self._targeting = targeting\n\n def cast(self, target=None):\n if self._spell_fn == SpellFn.ATTACK:\n attack(target)\n elif self._spell_fn == SpellFn.SECONDARY_ATTACK:\n secondary_ability()\n elif self._spell_fn == SpellFn.HOME_RECALL:\n home_recall()\n elif self._spell_fn == SpellFn.CLEAR_TARGET:\n clear_target()\n elif self._spell_fn == SpellFn.CLICKING:\n UseObject(target)\n elif self._spell_fn == SpellFn.MOVE:\n go_to_target(target)\n else:\n self._spell_fn(self._name)\n if self._targeting != None:\n WaitForTarget(WAITING)\n Target(self._targeting)\n Pause(WAITING + self._delay_in_ms)\n\n def has_mana(self, current_mana):\n return int(self._mana_cost) <= int(current_mana)\n\n\nclass Enemies:\n def __init__(self):\n IgnoreObject(\"self\")\n self.refresh()\n\n def refresh(self, search_distance=1):\n self._mobiles = self._find_enemies(search_distance)\n\n def are_amount_eq(self, number):\n return self._mobiles.Count() == number\n\n def are_amount_more(self, number):\n return self._mobiles.Count() > number\n\n def boss_here(self):\n for mob in self._mobiles:\n if Enemy(mob).is_boss:\n return True\n return False\n\n def current_target(self):\n if self.are_amount_eq(0):\n return None\n\n target = self._mobiles.First().Serial\n if target == GetAlias('self'):\n return None\n else:\n return target\n\n def _find_enemies(self, distance=1):\n return Engine.Mobiles.Where(lambda m: m != None\n and (str(m.Notoriety) == 'Attackable' or str(m.Notoriety) == 'Murderer')\n and m.Distance <= distance\n and not InIgnoreList(m.Serial)\n ).OrderBy(lambda m: m.Distance)\n\n\nclass Enemy:\n def __init__(self, mobile):\n self._mobile = mobile\n self.is_boss = MaxHits(mobile) > 10000\n\n def is_low_hp(self):\n return Hits(self._mobile) < (MaxHits(self._mobile) * 0.01)\n\n def is_full_hp(self):\n return DiffHits(self._mobile) == 0\n\n\nclass Sampire_AI:\n def __init__(self, enemies):\n self._enemies = enemies\n self._target = None\n self._query = []\n self.search_distance = 1\n self._rotation = sorted([\n SpellInfo('Home Recall', 20, 0, WAITING, 1,\n self._home_recall_check,\n SpellFn.HOME_RECALL),\n SpellInfo('Confidence', 10, 25, WAITING, 1,\n self._cast_confidence_heal,\n SpellFn.BUSHIDO),\n SpellInfo('Close Wounds', 10, 0, 1000, 1,\n self._cast_heal,\n SpellFn.CHIVALRY, GetAlias('self')),\n SpellInfo('Honor', 0, 0, WAITING, 2,\n self._cast_honor,\n SpellFn.VIRTUE, self._target),\n SpellInfo('Enemy Of One', 20, 45, WAITING, 4,\n self._cast_enemy_of_one,\n SpellFn.CHIVALRY),\n SpellInfo('Consecrate Weapon', 10, 15, 1000, 5,\n self._cast_consecrate_weapon,\n SpellFn.CHIVALRY),\n SpellInfo('Whirlwind', 30, 90, WAITING, 6,\n self._cast_whirlwind,\n SpellFn.SECONDARY_ATTACK),\n SpellInfo('Lightning Strike', 10, 50, WAITING, 6,\n self._cast_lighting_strike,\n SpellFn.BUSHIDO),\n SpellInfo('Momentum Strike', 10, 70, WAITING, 6,\n self._cast_momentum_strike,\n SpellFn.BUSHIDO),\n SpellInfo('Clicking', 0, 0, WAITING, 98,\n self._clicking,\n SpellFn.CLICKING),\n SpellInfo('Attack', 0, 0, WAITING, 3,\n self._attack,\n SpellFn.ATTACK),\n SpellInfo('Move', 0, 0, WAITING, 3,\n self._move,\n SpellFn.MOVE),\n SpellInfo('Clear Target', 0, 0, WAITING, 0,\n self._clear_target,\n SpellFn.CLEAR_TARGET),\n ], key=lambda spell: spell.priority)\n\n def tick(self):\n self._enemies.refresh(self.search_distance)\n self._target = self._enemies.current_target()\n self._build_query()\n self._run_query()\n self._search_for_enemies()\n Pause(WAITING)\n\n def _search_for_enemies(self):\n if self._enemies.are_amount_eq(0):\n if self.search_distance < 10:\n self.search_distance += 1\n else:\n self.search_distance = 1\n\n def _build_query(self):\n self._query = []\n for item in self._rotation:\n if item.when_to_cast():\n self._query.append(item)\n\n def _run_query(self):\n for item in self._query:\n if not item.has_mana(Mana('self')):\n return\n\n item.cast(self._target)\n\n def _clear_target(self):\n return Dead(self._target)\n\n def _move(self):\n return not InRange(self._target, PUNCH_RANGE)\n\n def _attack(self):\n return not self._enemies.are_amount_eq(0) and not Dead(self._target)\n\n def _clicking(self):\n return self._target is not None and not self._enemies.are_amount_eq(0) and Enemy(self._target).is_low_hp()\n\n def _cast_heal(self):\n return Hits('self') <= HEAL_AT and self._enemies.are_amount_eq(0)\n\n def _cast_confidence_heal(self):\n return Hits('self') <= HEAL_AT and self._enemies.are_amount_more(0) and not BuffExists('Confidence')\n\n def _cast_honor(self):\n return self._enemies.are_amount_more(0) and Enemy(self._target).is_full_hp() and not BuffExists('Honored')\n\n def _cast_enemy_of_one(self):\n return self._target is not None and (ONE_ENEMY_FARM or (self._enemies.are_amount_eq(1) and Enemy(self._target).is_boss)) and not BuffExists('Enemy Of One')\n\n def _cast_consecrate_weapon(self):\n return not BuffExists('Consecrate Weapon') and not self._enemies.are_amount_eq(0)\n\n def _cast_lighting_strike(self):\n return self._enemies.are_amount_eq(1) and (not BuffExists('Lightning Strike') or not BuffExists('Momentum Strike'))\n\n def _cast_momentum_strike(self):\n return self._enemies.are_amount_eq(2) and (not BuffExists('Momentum Strike') or not BuffExists('Lightning Strike'))\n\n def _cast_whirlwind(self):\n return self._enemies.are_amount_more(2)\n\n def _home_recall_check(self):\n return self._enemies.are_amount_eq(0) and DiffWeight() <= 20\n\n\n# Helper functions\n\n\ndef direction_to(mobile, shift_x=0, shift_y=0):\n mobile = Engine.Mobiles.GetMobile(mobile)\n\n if mobile == None:\n return Direction.Invalid\n\n return UOMath.MapDirection(Engine.Player.X, Engine.Player.Y, mobile.X + shift_x, mobile.Y + shift_y)\n\n\ndef fast_run(dir):\n if dir == Direction.Invalid:\n return\n Engine.Move(dir, True)\n\n\ndef go_to_target(mobile, max_distance_to_target=2):\n fast_run(direction_to(mobile))\n Pause(50)\n\n return True\n\n\ndef attack(target):\n if not War('self'):\n WarMode('on')\n\n Target(target)\n Attack(target)\n\n\ndef clear_target():\n CancelTarget()\n ClearTargetQueue()\n\n\ndef secondary_ability():\n SetAbility(\"secondary\")\n\n\ndef home_recall():\n Cast('Sacred Journey', HOME_RUNE_OR_BOOK)\n Pause(5000)\n\n\n# MAIN function\n\n\ndef main():\n enemies = Enemies()\n sampire_ai = Sampire_AI(enemies)\n\n while not Dead('self'):\n sampire_ai.tick()\n\n\nmain()\n" }, { "alpha_fraction": 0.5300202965736389, "alphanum_fraction": 0.607187032699585, "avg_line_length": 35.73272705078125, "blob_id": "a66fff01eb877517ac11abcb0667175035d67bd8", "content_id": "2a8d5b26b33645e276ab6aa9b2fc2ca50c927860", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20203, "license_type": "no_license", "max_line_length": 129, "num_lines": 550, "path": "/Macros/Skills/Animal Taming/train_animal_taming.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Animal Taming training\n# Description: Tames nearby animals to train Animal Taming to GM (to 90 by default) with healing, killing and basic pathfinding\n# Author: Mordor\n# Era: Any\n\nfrom ClassicAssist.UO.Data import Direction\nfrom ClassicAssist.UO import UOMath\nimport System\nfrom Assistant import Engine\nfrom System.Collections.Generic import List\n\n## Script options ##\n# Change to the name that you want to rename the tamed animals to\nrename_tamed_animals_to = 'M'\n# Add any name of pets to ignore\npets_to_ignore = [\n rename_tamed_animals_to,\n]\n# Change to the number of followers you'd like to keep.\n# The script will auto-kill the most recently tamed animal\n# Set to the maximum number of times to attempt to tame a single animal. 0 == attempt until tamed\nmaximum_tame_attempts = 10\n# Set the minimum taming difficulty to use when finding animals to tame\nminimum_taming_difficulty = 30\n# Set this to how you would like to heal your character if they take damage\n# Options are:\n# 'Magery' = uses the Heal and Greater Heal ability depending on how much health is missing\n# 'None' = do not auto-heal\nheal_using = 'Magery'\n# True or False to track the animal being tamed\nenable_follow_animal = True\n# Distance to animal before start\nmax_distance_to_target = 3\nmax_search_distance = 30\n# Set your skill cap\ntaming_cap = 90 # SkillCap('Animal Taming')\n# Change depending on the latency to your UO shard\njournal_entry_delay_milliseconds = 500\nplayer_stuck_timer_milliseconds = 15000\ntaming_attemp_timer_milliseconds = 20000\nneed_to_recall = 300000\n\n\nclass Animal:\n def __init__(self, name, mobile_id, color, min_taming_skill, max_taming_skill):\n self.name = name\n self.mobile_id = mobile_id\n self.color = color\n self.min_taming_skill = min_taming_skill\n self.max_taming_skill = max_taming_skill\n\n\nanimals = {\n # Organized based on taming difficulty with no previous owners according to uo.com, then alphabetically by and within species\n # https://uo.com/wiki/ultima-online-wiki/skills/animal-taming/tameable-creatures/#mobs\n\n ### Min skill 0, Max skill 10 ###\n 'dog': Animal('dog', 0x00D9, 0x0000, 0, 10),\n 'gorilla': Animal('gorilla', 0x001D, 0x0000, 0, 10),\n 'parrot': Animal('parrot', 0x033F, 0x0000, 0, 10),\n\n # Rabbits\n 'rabbit (brown)': Animal('rabbit', 0x00CD, 0x0000, 0, 10),\n 'rabbit (black)': Animal('rabbit', 0x00CD, 0x090E, 0, 10),\n 'jack rabbit': Animal('jack rabbit', 0x00CD, 0x01BB, 0, 10),\n\n 'skittering hopper': Animal('skittering hopper', 0x012E, 0x0000, 0, 10),\n 'squirrel': Animal('squirrel', 0x0116, 0x0000, 0, 10),\n\n ### Min skill 0, Max skill 20 ###\n 'mongbat': Animal('mongbat', 0x0027, 0x0000, 0, 20),\n\n ### Min skill 10, Max skill 20 ###\n # Birds\n # Note: the following share a color code:\n # 0x0835: Finch, hawk\n # 0x0847: Tern, Towhee\n # 0x0851: Nuthatch, woodpecker\n # 0x0901: Crow, Magpie, raven\n 'chickadee': Animal('chickadee', 0x0006, 0x0840, 10, 20),\n 'crossbill': Animal('crossbill', 0x0006, 0x083A, 10, 20),\n 'crow': Animal('crow', 0x0006, 0x0901, 10, 20),\n 'finch': Animal('finch', 0x0006, 0x0835, 10, 20),\n 'hawk': Animal('hawk', 0x0006, 0x0835, 10, 20),\n 'kingfisher': Animal('kingfisher', 0x0006, 0x083F, 10, 20),\n 'lapwing': Animal('lapwing', 0x0006, 0x0837, 10, 20),\n 'magpie': Animal('magpie', 0x0006, 0x0901, 10, 20),\n 'nuthatch': Animal('nuthatch', 0x0006, 0x0851, 10, 20),\n 'plover': Animal('plover', 0x0006, 0x0847, 10, 20),\n 'raven': Animal('raven', 0x0006, 0x0901, 10, 20),\n 'skylark': Animal('skylark', 0x0006, 0x083C, 10, 20),\n 'starling': Animal('starling', 0x083E, 0x0845, 10, 20),\n 'swift': Animal('swift', 0x0006, 0x0845, 10, 20),\n 'tern': Animal('tern', 0x0006, 0x0847, 10, 20),\n 'towhee': Animal('towhee', 0x0006, 0x0847, 10, 20),\n 'woodpecker': Animal('woodpecker', 0x0006, 0x0851, 10, 20),\n 'wren': Animal('wren', 0x0006, 0x0850, 10, 20),\n 'cat': Animal('cat', 0x00C9, 0x0000, 10, 20),\n 'chicken': Animal('chicken', 0x00D0, 0x0000, 10, 20),\n 'mountain goat': Animal('mountain goat', 0x0058, 0x0000, 10, 20),\n 'rat': Animal('rat', 0x00EE, 0x0000, 10, 20),\n 'sewer rat': Animal('sewer rat', 0x00EE, 0x0000, 10, 20),\n\n ### Min skill 20, Max skill 30 ###\n 'cow (brown)': Animal('cow', 0x00E7, 0x0000, 20, 30),\n 'cow (black)': Animal('cow', 0x00D8, 0x0000, 20, 30),\n 'goat': Animal('goat', 0x00D1, 0x0000, 20, 30),\n 'pig': Animal('pig', 0x00CB, 0x0000, 20, 30),\n 'sheep': Animal('sheep', 0x00CF, 0x0000, 20, 30),\n\n ### Min skill 20, Max skill 50 ###\n 'giant beetle': Animal('giant beetle', 0x0317, 0x0000, 20, 50),\n 'slime': Animal('slime', 0x0033, 0x0000, 20, 50),\n\n ### Min skill 30, Max skill 40 ###\n 'eagle': Animal('eagle', 0x0005, 0x0000, 30, 40),\n 'bouraRuddy': None,\n\n ### Min skill 40, Max skill 50 ###\n 'boar': Animal('boar', 0x0122, 0x0000, 40, 50),\n 'bullfrog': Animal('bullfrog', 0x0051, 0x0000, 40, 50),\n 'lowland boura': None,\n 'ferret': Animal('ferret', 0x0117, 0x0000, 40, 50),\n 'giant rat': Animal('giant rat', 0x00D7, 0x0000, 40, 50),\n 'hind': Animal('hind', 0x00ED, 0x0000, 40, 50),\n\n # Horses\n 'horse': Animal('horse', 0x00C8, 0x0000, 40, 50),\n 'horse2': Animal('horse', 0x00E2, 0x0000, 40, 50),\n 'horse3': Animal('horse', 0x00CC, 0x0000, 40, 50),\n 'horse4': Animal('horse', 0x00E4, 0x0000, 40, 50),\n 'horsePack': Animal('pack horse', 0x0123, 0x0000, 40, 50),\n 'horsePalomino': None,\n 'horseWar': None,\n\n # Llamas\n 'pack llama': Animal('pack llama', 0x0124, 0x0000, 40, 50),\n 'llamaRideable': None,\n\n # Ostards\n 'ostard': Animal('desert ostard', 0x00D2, 0x0000, 40, 50),\n 'forest ostard (green)': Animal('forest ostard', 0x00DB, 0x88A0, 40, 50),\n 'forest ostard (red)': Animal('forest ostard', 0x00DB, 0x889D, 40, 50),\n\n 'timber wolf': Animal('timber wolf', 0x00E1, 0x0000, 40, 50),\n 'rideable wolf': Animal('rideable wolf', 0x0115, 0x0000, 40, 50),\n\n ### Min skill 50, Max skill 60 ###\n 'black bear': Animal('black bear', 0x00D3, 0x0000, 50, 60),\n 'polar bear': Animal('polar bear', 0x00D5, 0x0000, 50, 60),\n 'deathwatch beetle': None,\n 'llama': Animal('llama', 0x00DC, 0x0000, 50, 60),\n 'walrus': Animal('walrus', 0x00DD, 0x0000, 50, 60),\n\n ### Min skill 60, Max skill 70 ###\n 'alligator': Animal('alligator', 0x00CA, 0x0000, 60, 70),\n 'brown bear': Animal('brown bear', 0x00A7, 0x0000, 60, 70),\n 'high plains boura': None,\n 'cougar': Animal('cougar', 0x003F, 0x0000, 60, 70),\n 'paralithode': None,\n 'scorpion': Animal('scorpion', 0x0030, 0x0000, 60, 70),\n\n ### Min skill 70, Max skill 80 ###\n 'rideable polar bear': Animal('rideable polar bear', 0x00D5, 0x0000, 70, 80),\n 'grizzly bear': Animal('grizzly bear', 0x00D4, 0x0000, 70, 80),\n 'young dragon': Animal('young dragon', 0x003C, 0x0000, 70, 80),\n\n 'great hart': Animal('great hart', 0xea, 0x0000, 70, 80),\n\n 'snow leopard': Animal('snow leopard', 0x0040, 0x0000, 70, 80),\n 'snow leopard2': Animal('snow leopard', 0x0041, 0x0000, 70, 80),\n 'panther': Animal('panther', 0x00D6, 0x0000, 70, 80),\n 'snake': Animal('snake', 0x0034, 0x0000, 70, 80),\n 'giant spider': Animal('giant spider', 0x001C, 0x0000, 70, 80),\n 'grey wolf (light grey)': Animal('grey wolf', 0x0019, 0x0000, 70, 80),\n 'grey wolf (dark grey)': Animal('grey wolf', 0x001B, 0x0000, 70, 80),\n\n ### Min skill 80, Max skill 90 ###\n 'gaman': None,\n 'slithStone': None,\n 'white wolf (dark grey)': Animal('white wolf', 0x0022, 0x0000, 80, 90),\n 'white wolf (light grey)': Animal('white wolf', 0x0025, 0x0000, 80, 90),\n\n ### Min skill 90, Max skill 100 ###\n 'bull (solid, brown)': Animal('bull', 0x00E8, 0x0000, 90, 100),\n 'bull (solid, black)': Animal('bull', 0x00E8, 0x0901, 90, 100),\n 'bull (spotted, brown)': Animal('bull', 0x00E9, 0x0000, 90, 100),\n 'bull (spotted, black)': Animal('bull', 0x00E9, 0x0901, 90, 100),\n 'foxBlood': None,\n 'hellcat (small)': Animal('hellcat', 0x00C9, 0x0647, 90, 100),\n 'mongbatGreater': None,\n 'frenzied ostard': Animal('frenzied ostard', 0x00DA, 0x0000, 90, 100),\n 'osseinRam': None,\n 'frost spider': Animal('frost spider', 0x0014, 0x0000, 90, 100),\n 'giant toad': Animal('giant toad', 0x0050, 0x0000, 90, 100),\n 'giant ice worm': Animal('giant ice worm', 0x0050, 0x0000, 90, 100),\n\n ### Min skill 100, Max skill 110 ###\n # Drakes\n # pathaleo drake: 0x003C\n 'drake (brown)': Animal('drake', 0x003C, 0x0000, 100, 110),\n 'drake (red)': Animal('drake', 0x003D, 0x0000, 100, 110),\n 'drakeCrimson': None,\n 'drakePlatinum': None,\n 'drakeStygian': None,\n\n 'hellcat (large)': Animal('hellcat', 0x007F, 0x0000, 100, 110),\n 'hellhound': Animal('hellhound', 0x0062, 0x0000, 100, 110),\n 'imp': Animal('imp', 0x004A, 0x0000, 100, 110),\n 'kitsuneBake': None,\n 'lava lizard': Animal('lava lizard', 0x00CE, 0x0000, 100, 110),\n\n # ridgebacks\n 'ridgeback': Animal('ridgeback', 0x00BB, 0x0000, 100, 110),\n 'savage ridgeback': Animal('savage ridgeback', 0x00BC, 0x0000, 100, 110),\n\n 'slith': None,\n 'dire wolf': Animal('dire wolf', 0x0017, 0x0000, 100, 110),\n\n ### Min skill 110, Max skill 120 ###\n 'beetleDeath': None,\n 'beetleFire': None,\n 'rune beetle': Animal('rune beetle', 0x00F4, 0x0000, 110, 120),\n 'dragon': Animal('dragon', 0x003B, 0x0000, 110, 120),\n 'dragonSwamp': None,\n 'dragonWater': None,\n 'dragonDeepWater': None,\n 'drakeCold': None,\n 'hiryu': None,\n 'hiryuLesser': None,\n 'lion': None,\n 'kiRin': None,\n 'nightbear': None,\n 'nightdragon': None,\n 'nightfrenzy': None,\n 'nightmare': None,\n 'nightllama': None,\n 'nightridge': None,\n 'nightwolf': None,\n 'skree': None,\n 'dread spider': Animal('dread spider', 0x000B, 0x0000, 110, 120),\n 'unicorn': None,\n 'wolfTsuki': None,\n 'white wyrm': Animal('white wyrm', 0x00B4, 0x0000, 110, 120),\n\n ### Challenging ###\n 'cuSidhe': None,\n 'dimetrosaur': None,\n\n # Dragons\n 'dragonBane': None,\n 'dragonFrost': None,\n 'a greater dragon': None,\n 'dragonSerpentine': None,\n 'gallusaurus': None,\n\n # Horses\n 'steedFire': None,\n 'steedSkeletal': None,\n 'horseDreadWar': None,\n\n 'miteFrost': None,\n 'najasaurus': None,\n 'phoenix': None,\n 'raptor': None,\n 'reptalon': None,\n 'saurosurus': None,\n\n # Tigers\n 'tigerWild': None,\n 'tigerSabreToothed': None,\n\n 'triceratops': None,\n 'turtleHatchlingDragon': None,\n 'wolfDragon': None,\n 'shadow wyrm': Animal('shadow wyrm', 0x006A, 0x0000, 120, 120)\n}\n\n\ndef get_animal_ids_at_or_over_taming_difficulty(minimumTamingDifficulty):\n '''\n Looks through the list of tameables for animals at or over the minimum taming level\n '''\n global animals\n\n animal_list = List[int]()\n for animal in animals:\n if (not animals[animal] == None and\n not animal_list.Contains(animals[animal].mobile_id) and\n animals[animal].min_taming_skill >= minimumTamingDifficulty):\n animal_list.Add(animals[animal].mobile_id)\n\n return animal_list\n\n\ndef find_animal_to_tame():\n '''\n Finds the nearest tameable animal nearby\n '''\n global rename_tamed_animals_to\n global minimum_taming_difficulty\n global max_search_distance\n global pets_to_ignore\n\n import clr\n\n clr.AddReference(\"System.Core\")\n clr.ImportExtensions(System.Linq)\n\n animal_ids = get_animal_ids_at_or_over_taming_difficulty(\n minimum_taming_difficulty)\n\n Pause(50)\n\n tameable_mobile = Engine.Mobiles.Where(lambda m: m != None\n and animal_ids.Contains(m.ID)\n and m.Distance <= max_search_distance\n and not InIgnoreList(m.Serial)\n and not pets_to_ignore.Contains(m.Name)\n ).OrderBy(lambda m: m.Distance).FirstOrDefault()\n\n if tameable_mobile == None:\n return None\n\n return tameable_mobile.Serial\n\n\ndef direction_to(mobile, shift_x=0, shift_y=0):\n mobile = Engine.Mobiles.GetMobile(mobile)\n\n if mobile == None:\n return Direction.Invalid\n\n return UOMath.MapDirection(Engine.Player.X, Engine.Player.Y, mobile.X + shift_x, mobile.Y + shift_y)\n\n\ndef fast_run(dir):\n if dir == Direction.Invalid:\n return\n Engine.Move(dir, True)\n\n\ndef follow_mobile(mobile, max_distance_to_target=2):\n '''\n Uses the X and Y coordinates of the animal and player to follow the animal around the map\n Returns True if player is not stuck, False if player is stuck\n '''\n\n global player_stuck_timer_milliseconds\n\n SetTimer('player_stuck_timer', 0)\n stuck_counter = 0\n\n while not InRange(mobile, max_distance_to_target):\n if stuck_counter > 5:\n return False\n\n fast_run(direction_to(mobile))\n Pause(50)\n\n if Timer('player_stuck_timer') > player_stuck_timer_milliseconds:\n stuck_counter += 1\n shift_x = -15\n shift_y = -15\n fast_run(direction_to(mobile, shift_x, shift_y))\n SetTimer('player_stuck_timer', 0)\n\n return True\n\n\ndef train_animal_taming():\n '''\n Trains Animal Taming to GM\n '''\n # User variables\n global rename_tamed_animals_to\n global maximum_tame_attempts\n global enable_follow_animal\n global journal_entry_delay_milliseconds\n global max_distance_to_target\n global max_search_distance\n global heal_using\n global taming_cap\n global need_to_recall\n\n if Skill('Animal Taming') == taming_cap:\n MessageBox(\"Done\", 'You\\'ve already maxed out Animal Taming!')\n return\n\n # Initialize variables\n animal_being_tamed = None\n tame_handled = False\n tame_ongoing = False\n times_tried = 0\n current_followers = Followers()\n\n # Initialize the journal and ignore object list\n ClearJournal()\n ClearIgnoreList()\n\n # Toggle war mode to make sure the player isn't going to kill the animal being tamed\n if War('self'):\n WarMode('off')\n\n while not Dead('self') and Skill('Animal Taming') < taming_cap:\n # Cast heal\n if heal_using == 'Magery' and DiffHits('self') > 30:\n Cast('Greater Heal', 'self')\n Pause(1000)\n # If there is no animal being tamed, try to find an animal to tame\n SetTimer('need_to_recall', 0)\n while animal_being_tamed == None:\n animal_being_tamed = find_animal_to_tame()\n Pause(1000)\n if Timer('need_to_recall') > need_to_recall:\n SetTimer('need_to_recall', 0)\n # recall to rune logic\n Pause(100)\n\n if animal_being_tamed > 0 and not tame_ongoing:\n SetTimer('need_to_recall', 0)\n HeadMsg('Found animal to tame', animal_being_tamed)\n\n if enable_follow_animal and animal_being_tamed > 0 and Distance(animal_being_tamed) <= max_search_distance:\n stuck = not follow_mobile(\n animal_being_tamed, max_distance_to_target)\n if stuck:\n IgnoreObject(animal_being_tamed)\n animal_being_tamed = None\n\n elif animal_being_tamed > 0 and Distance(animal_being_tamed) > max_search_distance:\n HeadMsg('Animal moved too far away, ignoring for now',\n animal_being_tamed)\n animal_being_tamed = None\n continue\n\n if not maximum_tame_attempts == 0 and times_tried > maximum_tame_attempts:\n HeadMsg('Tried more than %i times to tame. Ignoring animal' %\n maximum_tame_attempts, animal_being_tamed)\n IgnoreObject(animal_being_tamed)\n animal_being_tamed = None\n times_tried = 0\n\n # Tame the animal if a tame is not currently being attempted and enough time has passed since last using Animal Taming\n if not tame_ongoing:\n # Clear any previously selected target and the target queue\n CancelTarget()\n ClearTargetQueue()\n ClearJournal()\n\n # Hey, were finally using the Animal Taming skill! 'bout time!\n UseSkill('Animal Taming')\n WaitForTarget(1000)\n Target(animal_being_tamed)\n Pause(journal_entry_delay_milliseconds)\n\n # Check if Animal Taming was successfully triggered\n if InJournal('Tame which animal?'):\n times_tried += 1\n\n # Set tame_ongoing to true to start the journal checks that will handle the result of the taming\n if InJournal('*You start to tame the creature.*'):\n tame_ongoing = True\n SetTimer('taming_attemp_timer', 0)\n\n if InJournal('You have no chance of taming this creature'):\n # Ignore the object and set to None so that another animal can be found\n IgnoreObject(animal_being_tamed)\n\n ClearJournal()\n tame_handled = False\n tame_ongoing = False\n times_tried = 0\n animal_being_tamed = None\n\n if Followers() > current_followers or (not maximum_tame_attempts == 0 and times_tried > maximum_tame_attempts):\n follow_rename_and_kill(animal_being_tamed)\n\n ClearJournal()\n tame_handled = False\n tame_ongoing = False\n times_tried = 0\n animal_being_tamed = None\n SetTimer('taming_attemp_timer', 0)\n\n else:\n continue\n\n if tame_ongoing:\n Pause(journal_entry_delay_milliseconds)\n\n if (InJournal('It seems to accept you as master.') or\n InJournal('That wasn\\'t even challenging.') or\n Followers() > current_followers):\n # Animal was successfully tamed\n tame_handled = True\n elif (InJournal('You fail to tame the creature.') or\n InJournal('You must wait a few moments to use another skill.') or\n InJournal('That is too far away.') or\n InJournal('You are too far away to continue taming.') or\n InJournal('Someone else is already taming this') or\n InJournal('You have no chance of taming this creature') or\n InJournal('Target cannot be seen') or\n InJournal('You can\\'t see that.') or\n InJournal('This animal has had too many owners and is too upset for you to tame.') or\n InJournal('That animal looks tame already.') or\n InJournal(\n 'You do not have a clear path to the animal you are taming, and must cease your attempt.') or\n Timer(\n 'taming_attemp_timer') > taming_attemp_timer_milliseconds\n ):\n tame_ongoing = False\n SetTimer('taming_attemp_timer', 0)\n\n if tame_handled:\n follow_rename_and_kill(animal_being_tamed)\n\n ClearJournal()\n tame_handled = False\n tame_ongoing = False\n times_tried = 0\n animal_being_tamed = None\n SetTimer('taming_attemp_timer', 0)\n\n # Wait a little bit so that the while loop doesn't consume as much CPU\n Pause(50)\n\n\ndef follow_rename_and_kill(animal_being_tamed):\n Msg('all follow me')\n Pause(1000)\n Rename(animal_being_tamed, rename_tamed_animals_to)\n Pause(1000)\n # Release pet\n WaitForContext(animal_being_tamed, 8, 15000)\n WaitForGump(0x909cc741, 5000)\n ReplyGump(0x909cc741, 2)\n Pause(1000)\n\n while Mana('self') < 40:\n Pause(1000)\n\n while Hits(animal_being_tamed) > 0 and Cast('Flame Strike', animal_being_tamed):\n Pause(3000)\n\n IgnoreObject(animal_being_tamed)\n\n\n# Start Animal Taming\ntrain_animal_taming()\n" }, { "alpha_fraction": 0.5423542261123657, "alphanum_fraction": 0.560689389705658, "avg_line_length": 31.85542106628418, "blob_id": "34bf59046fe5264d6d762e75de09c65f130c82c5", "content_id": "821535203afca975dc961f87955b91dd555bac78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2727, "license_type": "no_license", "max_line_length": 121, "num_lines": 83, "path": "/Macros/Skills/Provocation/train_provocation.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Provocation training\n# Description: Uses the Provocation skill on the player to train Provocation to GM\n# Author: Mordor\n# Era: Any\nfrom Assistant import Engine\nimport System\nimport clr\n\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\n# Script variables configuration\nskill_cap = SkillCap('Provocation')\n\n\ndef train_provocation():\n '''\n Trains Provocation to GM\n '''\n # Script variables\n global skill_cap\n\n instruments = [0x2805, 0x0e9c, 0x0eb3, 0xeb2, 0x0eb1, 0x0e9e, 0x0e9d]\n\n if Skill('Provocation') == skill_cap:\n MessageBox(\"Done\", 'You\\'ve already maxed out Peacemaking!')\n return\n\n while not Dead('self') and Skill('Provocation') < skill_cap:\n found_targets = False\n first_target = None\n second_target = None\n ClearJournal()\n\n if DiffHits(\"self\") > 2:\n UseSkill('Peacemaking')\n WaitForTarget(1000)\n Target('self')\n\n while not found_targets:\n enemies = Engine.Mobiles.Where(lambda m: m != None\n and m.Serial != GetAlias('self')\n and m.Distance <= 10\n and not InIgnoreList(m.Serial)\n ).OrderBy(lambda m: m.Distance)\n first_target = enemies.FirstOrDefault()\n second_target = enemies.Skip(1).FirstOrDefault()\n\n if first_target != None and second_target != None and first_target != second_target:\n found_targets = True\n\n UseSkill('Provocation')\n\n # Handle the Journal response\n if WaitForJournal('What instrument shall you play the music on?', 500):\n UnsetAlias('found')\n for i in instruments:\n if FindType(i, -1, \"backpack\"):\n break\n\n if not FindAlias('found'):\n MessageBox(\"Error\", \"No instrument to playing with.\")\n return\n\n WaitForTarget(2000)\n Target('found')\n\n WaitForTarget(5000)\n if TargetExists():\n Target(first_target)\n if InJournal('You can\\'t incite that!') or InJournal('You cannot perform negative acts on your target.'):\n IgnoreObject(first_target)\n continue\n WaitForTarget(5000)\n if TargetExists():\n Target(second_target)\n if InJournal('You can\\'t incite that!') or InJournal('You cannot perform negative acts on your target.'):\n IgnoreObject(second_target)\n continue\n Pause(8000)\n\n\n# Start Provocation training\ntrain_provocation()\n" }, { "alpha_fraction": 0.6104651093482971, "alphanum_fraction": 0.6366279125213623, "avg_line_length": 37.22222137451172, "blob_id": "693715177af5fbe4cf48f8704a38c3221d794f27", "content_id": "5d1e8da4457d5fec9c6baf13f482d07b36414ab6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 688, "license_type": "no_license", "max_line_length": 96, "num_lines": 18, "path": "/Macros/Skills/Animal Taming/train_animal_taming_mastery.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Animal Taming training from 90 to cap\n# Description: Uses Animal Taming master ability on target to train Animal Taming from 90 to cap\n# Author: Mordor\n# Era: TOL\n\nwhile not Dead('self') and Skill('Animal Taming') < SkillCap('Animal Taming'):\n target = PromptAlias(\"skill_target\") # target for training\n spell_mana_cost = 32 # spell mana cost\n\n if Mana('self') > spell_mana_cost:\n Cast('Combat Training', target)\n Pause(1000)\n else:\n while not BuffExists('Active Meditation') or not Mana('self') == MaxMana('self'):\n UseSkill('Meditation')\n Pause(4000)\n while Mana('self') < MaxMana('self'):\n Pause(1000)\n" }, { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7444717288017273, "avg_line_length": 26.133333206176758, "blob_id": "066eb9de79c9cd8f612a7722acae268842ba0f06", "content_id": "bfa7c36ca244a3bf496a4e3db58121e243b7a4fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 90, "num_lines": 15, "path": "/Macros/Advanced/Examples/playsound_trade_window.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Packet wait play sound\n# Description: Add a packet wait entry to play a sound when trade window is opened\n# Author: Reetus\n# Era: Any\n\nfrom Assistant import Engine\nfrom ClassicAssist.UO.Network.PacketFilter import *\n \npwe = Engine.PacketWaitEntries.Add(PacketFilterInfo(0x6F), PacketDirection.Incoming, True)\n\npwe.Lock.WaitOne()\n\nwhile True:\n PlaySound(\"Bike Horn.wav\")\n Pause(1000)\n" }, { "alpha_fraction": 0.6131907105445862, "alphanum_fraction": 0.638146162033081, "avg_line_length": 36.400001525878906, "blob_id": "0c85c2a5a4e920b1feb174e89b1f09724ae8d392", "content_id": "858660dc0b120afa3826661c3273d62299c7cc69", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "no_license", "max_line_length": 98, "num_lines": 15, "path": "/Macros/Skills/Evaluating Intelligence/train_evaluating_intelligence.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Evaluating Intelligence training to cap\n# Description: Uses Reactive Armor to train Evaluating Intelligence to the cap\n# Author: Mordor\n# Era: Any\n\nwhile not Dead('self') and Skill('Evaluating Intelligence') < SkillCap('Evaluating Intelligence'):\n if Mana('self') > 20:\n Cast('Reactive Armor')\n Pause(1000)\n else:\n while not BuffExists('Active Meditation') or not Mana('self') == MaxMana('self'):\n UseSkill('Meditation')\n Pause(4000)\n while Mana('self') < MaxMana('self'):\n Pause(1000)\n" }, { "alpha_fraction": 0.6841698884963989, "alphanum_fraction": 0.7057915329933167, "avg_line_length": 22.981481552124023, "blob_id": "442059cae6330502c32c3eac1e93caab21dbcb2f", "content_id": "a773ffadd7545c7ff93810f2783c442af4397a40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1295, "license_type": "no_license", "max_line_length": 112, "num_lines": 54, "path": "/Macros/Crafting/Blacksmith/AddToDeedCreatedItems.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Add to deed created items\n# Description: Search and add items corresponding to prompted deed. Gumps for deed may vary in different shards.\n# Author: Aru\n# Era: AOS\n\nimport clr\nimport System\nclr.AddReference('System.Core')\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\n\ndef GetBackpackItems(filter = None):\n if Engine.Player == None:\n return []\n SysMessage(\"checking\")\n\n if Engine.Player.Backpack.Container == None:\n UseObject('backpack')\n WaitForContents('backpack', 5000)\n\n items = Engine.Player.Backpack.Container.SelectEntities(lambda i: filter == None or i.Name.Contains(filter))\n\n if (items == None):\n return []\n\n return items.Select(lambda i: i.Serial)\n\ndef GetLastProperty(serial):\n item = Engine.Items.GetItem(serial)\n\n if (item == None or item.Properties == None):\n return '';\n\n return item.Properties[item.Properties.Length-1].Text\n\n\nPromptAlias('deed')\nserial = GetAlias('deed')\n\ndeedGoal = GetLastProperty(serial).split(\":\")[0]\n\nSysMessage(deedGoal)\n\nbackpackfoundList = GetBackpackItems(deedGoal)\n\nUseObject('deed')\nWaitForGump(0x5afbd742, 6000)\n\nfor x in backpackfoundList:\n ReplyGump(0x5afbd742, 2)\n WaitForTarget(6000)\n Target(x)\n SysMessage(\"Adding item to deed\")\n Pause(200)\n" }, { "alpha_fraction": 0.5718450546264648, "alphanum_fraction": 0.6555601954460144, "avg_line_length": 24.817203521728516, "blob_id": "0008589117a5ef6fcd00d5de61f164ccea5ba660", "content_id": "2a5719de9d0ef4132b472cb37adf338a683eb614", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2401, "license_type": "no_license", "max_line_length": 88, "num_lines": 93, "path": "/Macros/Crafting/HUO-Lumberjacker.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Lumberjacker \n# Description: Use runic atlas (3 or 4) with 48 runes on each, 1 hatchet, full LRC suit\n# Author: ziox-b (inspired by \"Cray\" script)\n# Shard: UO Heritage\n\nfrom Assistant import Engine\nfrom ClassicAssist.UO.Commands import UO3DEquipItems\nfrom System import Array\n\n# settings\nhand = 'TwoHanded'\naxes = [0x0f43,0x1443]\nlogs = [0x1bdd,0x07da,0x04a7,0x04a8,0x04a9,0x04aa,0x047f] # colors\nto_cont = [0x1bdd,0x1bd7,0x1bd7,0x2f5f,0x318f,0x3190,0x3191,0x3199,0x5738] # dump\ncont_serial = 0x40159b2d # add your container serial to drop stuff\nrunic_atlas = [0x400b631d, 0x4003a799] # home rune must be the first one in first serial\nrunes = range(1, 48)\n# end settings\n\ndef recall(runebook,r):\n ClearJournal()\n while Mana('self') < 10:\n \tPause(100)\n x = X('self')\n y = Y('self')\n rune_button = r + 100\n rune_recall = 4\n atlas_shit = r / 16\n UseObject(runebook)\n for i in range(atlas_shit):\n WaitForGump(0x1f2, 5000)\n ReplyGump(0x1f2, 1150)\n WaitForGump(0x1f2, 5000)\n ReplyGump(0x1f2, rune_button)\n WaitForGump(0x1f2, 5000)\n ReplyGump(0x1f2, rune_recall)\n while X('self') == x and Y('self') == y:\n \tif InJournal(\"blocking\", \"system\"):\n \t\trecall(runebook,r)\n Pause(500)\n Pause(500)\n\ndef cut_logs():\n\tfor log in logs:\n\t\twhile FindType(log, -1, 'backpack'):\n\t\t\tPause(500)\n\t\t\tUseLayer(hand)\n\t\t\tWaitForTarget(5000)\n\t\t\tTarget('found')\n\t\t\tPause(1000)\n\ndef\tdrop_to_home():\n\tif Weight() <= MaxWeight() - 200:\n\t\tPause(100)\n\t\treturn\n\trecall(runic_atlas[0],0)\n\tfor items in to_cont:\n\t\twhile FindType(items, -1, 'backpack'):\n\t\t\tMoveItem('found', cont_serial)\n\t\t\tPause(1000)\n\ndef lumber(runebook):\n\tif InJournal(\"blocking\", \"system\"):\n\t\trecall(runebook, r)\n\t\tlumber(runebook)\n\tif FindLayer(hand):\n\t\tSysMessage('axe in hand')\n\t\treturn\n\tfor axe in axes:\n\t\tif FindType(axe, -1, 'backpack'):\n\t\t\tUO3DEquipItems(Array[int]([GetAlias('found')]))\n\t\t\tPause(750)\n\tClearJournal()\n\tSetTimer(\"lumber\", 8000)\n\twhile Weight() <= MaxWeight():\n\t\tif not TimerExists(\"lumber\"):\n\t\t\tbreak\n\t\tif InJournal(\"not enough\", \"system\"):\n\t\t\tbreak\n\t\tCancelTarget()\n\t\tPause(100)\n\t\tSetAlias('hatchet',0x40159b2a)\n\t\tTargetByResource('hatchet', 'Wood')\n\t\tPause(1000)\n\nwhile not Dead('self'):\n for books in runic_atlas:\n for r in runes:\n cut_logs()\n drop_to_home()\n recall(books, r)\n lumber(books)\n Pause(100)\n" }, { "alpha_fraction": 0.6974564790725708, "alphanum_fraction": 0.7121820449829102, "avg_line_length": 23.899999618530273, "blob_id": "62105092d6c48a5d21577dfe697e19339278663c", "content_id": "199ee7b5674ec37c610e9656745d1837117db429", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1494, "license_type": "no_license", "max_line_length": 186, "num_lines": 60, "path": "/Macros/Crafting/Blacksmith/SmeltPromptedItems.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Smelt all items by prompted type\n# Description: Search and smelt all items (by type) from backpack. Uses prompt for get item type. Change {hammer_name} to current name in shard of hammer. Gumps may vary in other shards.\n# Author: Aru\n# Era: AOS\n\nimport clr\nimport System\nclr.AddReference('System.Core')\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\n\ndef GetBackpackItems(filter = None):\n if Engine.Player == None:\n return []\n SysMessage(\"checking\")\n\n if Engine.Player.Backpack.Container == None:\n UseObject('backpack')\n WaitForContents('backpack', 5000)\n\n items = Engine.Player.Backpack.Container.SelectEntities(lambda i: filter == None or i.Name.Contains(filter))\n\n if (items == None):\n return []\n\n return items.Select(lambda i: i.Serial)\n\ndef GetLastProperty(serial):\n item = Engine.Items.GetItem(serial)\n\n if (item == None or item.Properties == None):\n return '';\n\n return item.Properties[item.Properties.Length-1].Text\n\ndef GetFirst(l):\n for item in l:\n return item\n\nPromptAlias('typeToSmelt')\nserial = GetAlias('typeToSmelt')\n\ntmpItem = Engine.Items.GetItem(serial)\n\ntoSmeltList = GetBackpackItems(tmpItem.Name)\nhammerList = GetBackpackItems(\"{hammer_name}\")\n\nhammer = GetFirst(hammerList)\n\nSysMessage(\"Hammer serial: \" + hex(hammer))\n\nUseObject(hammer)\nWaitForGump(0x1cc, 5000)\n\nfor x in toSmeltList:\n\tReplyGump(0x1cc, 14)\n\tWaitForTarget(5000)\n\tTarget(x)\n\tSysMessage(\"Smelting\")\n\tPause(200)\n" }, { "alpha_fraction": 0.7091221809387207, "alphanum_fraction": 0.7263339161872864, "avg_line_length": 21.346153259277344, "blob_id": "1110cac635d1e4d459a6ede1b0ba6c526eb38cb7", "content_id": "54c54de008a94096837a2a6f778816eda28619c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 87, "num_lines": 26, "path": "/Macros/Advanced/Examples/find_items_by_name.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Find Items By Name\n# Description: Find all items within a container containing the given text in it's name\n# Author: Reetus\n# Era: Any\n\nfrom Assistant import Engine\n\ndef FindItemsByName(name, container):\n\titems = []\n\t\n\tcont = Engine.Items.GetItem(container)\n\t\n\tif cont == None:\n\t\tprint 'Cannot find container'\n\t\treturn\n\t\t\n\tif cont.Container == None:\n\t\tWaitForContents(container, 5000)\n\t\t\n\tfor item in cont.Container.GetItems():\n\t\tif item.Name.ToLower().Contains(name.ToLower()):\n\t\t\titems.append(item.Serial)\t\n\t\n\treturn items\n\t\nprint FindItemsByName('Mythical', 0x418caa10)\n" }, { "alpha_fraction": 0.7224770784378052, "alphanum_fraction": 0.7431192398071289, "avg_line_length": 21.947368621826172, "blob_id": "6b1d16d48f44592bef78cf89506705663ed2877a", "content_id": "250cbfbb50c73f98d8730d1008cbc615e1dc6d4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/Macros/Common/mobile_query.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Mobile Query\n# Description: Use as a background macro to refresh health bars\n# Author: Reetus\n# Shard: OSI\n\nfrom ClassicAssist.UO.Commands import MobileQuery\nfrom Assistant import Engine\n\ndef QueryAllMobiles():\n\tmobiles = Engine.Mobiles.GetMobiles()\n\t\n\tfor x in range(len(mobiles)):\n\t\tmobile = mobiles[x]\n\t\tif (mobile != None and mobile.Distance < 5):\n\t\t\tMobileQuery(mobile.Serial)\n\t\t\tPause(1000)\n\nQueryAllMobiles()\nPause(2000)\n" }, { "alpha_fraction": 0.6548672318458557, "alphanum_fraction": 0.6965866088867188, "avg_line_length": 33.39130401611328, "blob_id": "763a0aea2b25608a1562af36a7705d2fe1d033cb", "content_id": "ef7f30c255c1fefe6dd89b955b82cdeae1cf9e30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 110, "num_lines": 23, "path": "/Macros/Skills/Healing/healingtrainer.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Healing Trainer\n# Description: A simple to use healing trainer that uses magic arrow to damage yourself then heal use bandages\n# Author: vertex101\n# Era: Any\n# Date: Thu Apr 01 2021\n\nSetQuietMode(True) # this is so the chat in-game is not spammed with Object found updated\nwhile not Dead(\"self\"):\n\tif not FindType(0xe21, -1, \"backpack\"):\n\t\tHeadMsg(\"Out of Bandages\", \"self\", 33)\n\t\tStop()\n\tif Skill(\"Healing\") == SkillCap(\"Healing\"):\n\t\tHeadMsg(\"Heal training finished !!!\", \"self\", 1194)\n\t\tStop()\n\tif Hits(\"self\") <= 20: #adjust this based of your HP\n\t\twhile Hits('self') < MaxHits(\"self\"):\n\t\t\tBandageSelf()\n\t\t\tPause(7000) # adjust this based on your character stats\n\telse:\n\t\tCast(\"Magic Arrow\")\n\t\tWaitForTarget(5000)\n\t\tTarget(\"self\")\n\t\tPause(2000) # adjust this based on your FC/FCR\n" }, { "alpha_fraction": 0.5346453189849854, "alphanum_fraction": 0.5580155849456787, "avg_line_length": 29.11111068725586, "blob_id": "c6495285238b4a4d353f28da091dbfc211fc129a", "content_id": "5efd2926eb8beaf9150d97902da1d2d5faec3027", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2439, "license_type": "no_license", "max_line_length": 139, "num_lines": 81, "path": "/Macros/Skills/Discordance/train_discordance.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Discordance training\n# Description: Uses the Discordance skill on the player to train Discordance to GM\n# Author: Mordor\n# Era: Any\nfrom Assistant import Engine\nimport System\nimport clr\n\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\n# Script variables configuration\nskill_cap = SkillCap('Discordance')\n\n\ndef train_discordance():\n '''\n Trains Discordance to GM\n '''\n # Script variables\n global skill_cap\n SetTimer('discord_timer', 0)\n\n instruments = [0x2805, 0x0e9c, 0x0eb3, 0xeb2, 0x0eb1, 0x0e9e, 0x0e9d]\n\n if Skill('Discordance') == skill_cap:\n MessageBox(\"Done\", 'You\\'ve already maxed out Discordance!')\n return\n\n while not Dead('self') and Skill('Discordance') < skill_cap:\n found_targets = False\n first_target = None\n ClearJournal()\n\n if Timer('discord_timer') > 1000 * 60 * 5:\n SetTimer('discord_timer', 0)\n ClearIgnoreList()\n\n if DiffHits(\"self\") > 2:\n UseSkill('Peacemaking')\n WaitForTarget(1000)\n Target('self')\n\n while not found_targets:\n enemies = Engine.Mobiles.Where(lambda m: m != None\n and m.Serial != GetAlias('self')\n and m.Distance <= 10\n and not InIgnoreList(m.Serial)\n ).OrderBy(lambda m: m.Distance)\n first_target = enemies.FirstOrDefault()\n\n if first_target != None:\n found_targets = True\n\n UseSkill('Discordance')\n\n # Handle the Journal response\n if WaitForJournal('What instrument shall you play?', 500):\n UnsetAlias('found')\n for i in instruments:\n if FindType(i, -1, \"backpack\"):\n break\n\n if not FindAlias('found'):\n MessageBox(\"Error\", \"No instrument to playing with.\")\n return\n\n WaitForTarget(2000)\n Target('found')\n\n WaitForTarget(5000)\n if TargetExists():\n Target(first_target)\n if WaitForJournal('That creature is already in discord.', 500) or InJournal('A song of discord would have no effect on that.'):\n IgnoreObject(first_target)\n continue\n\n Pause(8000)\n\n\n# Start Discordance training\ntrain_discordance()\n" }, { "alpha_fraction": 0.7780748605728149, "alphanum_fraction": 0.7789661288261414, "avg_line_length": 39.07143020629883, "blob_id": "fbb8523c273f7dad5817a22f249eba75f7ead93d", "content_id": "bf5be3f042b58776ed490771143560d5751f0045", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 117, "num_lines": 28, "path": "/Macros/Advanced/Examples/external_services.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Discord/PushBullet send message\n# Description: Example functions to send message to Discord/PushBullet\n# Author: Reetus\n# Era: Any\n\nimport clr\nclr.AddReference('System.Net.Http')\nfrom System.Net.Http import HttpClient, FormUrlEncodedContent\nfrom System.Net.Http.Headers import AuthenticationHeaderValue\nfrom System.Collections.Generic import Dictionary\n\ndef Discord(message):\n\twebhook = '<webhook url here>'\n\tdict = {\"content\": message}\n\tresponse = HttpClient().PostAsync( webhook, FormUrlEncodedContent(Dictionary[str,str](dict)))\n\treturn response.Result.IsSuccessStatusCode\n\ndef PushBullet(title, message):\n\t# generate access token @ https://www.pushbullet.com/#settings/account\n\taccessToken = '<access token here>'\n\thttp = HttpClient()\n\tdict = {\"type\": \"note\", \"title\":title, \"body\": message}\n\thttp.DefaultRequestHeaders.Authorization = AuthenticationHeaderValue( \"Bearer\", accessToken );\n\tresponse = http.PostAsync( \"https://api.pushbullet.com/v2/pushes\", FormUrlEncodedContent(Dictionary[str,str](dict)))\n\treturn response.Result.IsSuccessStatusCode\n\t\nprint Discord('hello')\nprint PushBullet('title', 'hello')\n" }, { "alpha_fraction": 0.5721153616905212, "alphanum_fraction": 0.6033653616905212, "avg_line_length": 31.842105865478516, "blob_id": "49ba7f9edaaf58bbbcb729d249d49845d42d9829", "content_id": "116124e551a7dd41c5c6fc0426c445ccf3c6a149", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1248, "license_type": "no_license", "max_line_length": 89, "num_lines": 38, "path": "/Macros/Skills/Mysticism/train_mysticism.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Mysticism training to cap\n# Description: Train Mysticism to cap\n# Author: Mordor\n# Era: TOL\n\nclass SpellInfo:\n def __init__(self, name, mana_cost, min_skill, delay_in_ms, target=None):\n self.name = name\n self.mana_cost = mana_cost\n self.min_skill = min_skill\n self.delay_in_ms = delay_in_ms\n self.target = target\n\n\nwhile not Dead('self') and Skill('Mysticism') < SkillCap('Mysticism'):\n # Set mana and spell cast according to your stats\n spells = [\n SpellInfo('Stone Form', 8, 40, 1500),\n SpellInfo('Cleansing Winds', 12, 63, 3000, GetAlias('self')),\n SpellInfo('Hail Storm', 30, 80, 4000, GetAlias('self')),\n SpellInfo('Nether Cyclone', 30, 95, 4000),\n ]\n\n current_spell = None\n\n for spell in spells:\n if spell.min_skill <= Skill('Mysticism'):\n current_spell = spell\n\n if Mana('self') > current_spell.mana_cost:\n Cast(current_spell.name, current_spell.target)\n Pause(current_spell.delay_in_ms)\n else:\n while not BuffExists('Active Meditation') or not Mana('self') == MaxMana('self'):\n UseSkill('Meditation')\n Pause(4000)\n while Mana('self') < MaxMana('self'):\n Pause(1000)\n" }, { "alpha_fraction": 0.6653445959091187, "alphanum_fraction": 0.6757560968399048, "avg_line_length": 36.314815521240234, "blob_id": "9b6833c74a35421e85feb56d30d0dde7a13a56ee", "content_id": "02491eaf51e40550e13287ddd575faa6cff3084a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2017, "license_type": "no_license", "max_line_length": 145, "num_lines": 54, "path": "/Macros/Advanced/Examples/linq_enumerate_mobiles.py", "repo_name": "marcoeqms/classicassistmacrocopy", "src_encoding": "UTF-8", "text": "# Name: Linq Enumerate Mobiles\n# Description: Using Linq with Python to get mobiles with a bunch of conditions...\n# Author: Reetus\n# Era: Any\n\nimport clr\nimport System\nclr.AddReference(\"System.Core\")\nclr.ImportExtensions(System.Linq)\nfrom Assistant import Engine\n\n# Possible notorieties\n# Innocent, Ally, Attackable, Criminal, Enemy, Murderer, Invulnerable\n\nhumans = [0x190, 0x191]\n\ndef GetMobiles(ids = None, notorieties = None, includeFriends = False, includeIgnored = False, maxDistance = 32, orderBy = lambda m: m.Distance):\n\tmobiles = Engine.Mobiles.Where(lambda m: (ids == None or ids.Contains(m.ID))\n \tand m.Distance < maxDistance\n \tand m.Serial != Engine.Player.Serial\n \tand (notorieties == None or notorieties.Contains(m.Notoriety.ToString()))\n\t\t\t\t\t\tand (includeFriends or not InFriendList(m.Serial))\n\t\t\t\t\t\tand (includeIgnored or not InIgnoreList(m.Serial))).OrderBy(orderBy)\n\treturn mobiles\n\n# Get 1 \nmobile = GetMobiles(ids = humans, notorieties = ['Murderer'], maxDistance = 10).First()\nHeadMsg(mobile.Name, 'self')\n\n# Get 2\nmobiles = GetMobiles(ids = humans, notorieties = ['Murderer', 'Innocent'], maxDistance = 10, includeFriends = True).Take(2)\n\nfor m in mobiles:\n\tHeadMsg(m.Name, 'self')\n\n# Order by Hits\nmobile = GetMobiles(orderBy = lambda m: m.Hits, notorieties = ['Innocent']).First()\nHeadMsg(mobile.Name + ' - ' + str(mobile.Hits), 'self')\n\n# Order by Hits, ThenBy alphabetical\nmobile = GetMobiles(orderBy = lambda m: m.Hits).ThenBy(lambda m: m.Name).First()\nHeadMsg(mobile.Name + ' - ' + str(mobile.Hits), 'self')\n\n# Get all less than 5, and select just the serials\nmobiles = GetMobiles(maxDistance = 5, includeFriends = True).Select(lambda m: m.Serial)\n\nfor m in mobiles:\n\tHeadMsg(hex(m), 'self')\n\n# Only friends\nmobiles = GetMobiles(maxDistance = 15, includeFriends = True).Where(lambda m: InFriendList(m.Serial))\n\nfor m in mobiles:\n\tHeadMsg(m.Name, 'self')\n\n\n" } ]
28
Mironova66/module_test
https://github.com/Mironova66/module_test
0b7ea715644d3ea33526413893abdf922fba1906
5b65d7b8c05e0578301325bc5949f25e4387638d
0e910e761ce4f28570330dc1c421b306d787e348
refs/heads/main
2023-09-04T04:39:55.819984
2021-10-12T21:55:30
2021-10-12T21:55:30
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.582619309425354, "alphanum_fraction": 0.6572827696800232, "avg_line_length": 27.172412872314453, "blob_id": "4d82f02345b9ab511b5cbfab3a9a3782d91978f9", "content_id": "3cd0a9bf37772c9cabd69435b136f64dac18cc0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 817, "license_type": "no_license", "max_line_length": 65, "num_lines": 29, "path": "/test_module3.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "import unittest\nimport module3\n\nclass Test1(unittest.TestCase):\n def test1(self):\n self.assertEqual(module3.module3(3111), 6)\n def test2(self):\n self.assertEqual(module3.module3(16), 7)\n\nclass Test2(unittest.TestCase):\n def test1(self):\n self.assertEqual(module3.module3(-101235), 12)\n def test2(self):\n self.assertEqual(module3.module3(456), 15)\n\nclass Test3(unittest.TestCase):\n def test1(self):\n self.assertEqual(module3.module3(-123456), 21)\n def test2(self):\n self.assertEqual(module3.module3(\"4vfdf\"), \"Input Error\")\n\nclass Test4(unittest.TestCase):\n def test1(self):\n self.assertEqual(module3.module3(1), 1)\n def test2(self):\n self.assertEqual(module3.module3(\"----\"), \"Input Error\")\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5126436948776245, "alphanum_fraction": 0.5333333611488342, "avg_line_length": 20.700000762939453, "blob_id": "2fb7e5ab49b5f2d51dd667ddf1d621f5352b6281", "content_id": "9fc5e52e4b997862f2dae066c4ea2d5fafc65d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 521, "license_type": "no_license", "max_line_length": 100, "num_lines": 20, "path": "/module4.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "# Написать функцию,которая заключает целое число в рамку из символов char и возвращает данную строку\n# Пример:\n# frame(16, '+') ==>\n# ++++++\n# + 16 +\n# ++++++\n\ndef module4(num, char):\n\n if type(num) != int:\n return \"Input Error\"\n else:\n s = str(num)\n top=len(s)+4\n Stroka=top*char\n Stroka+=\"\\n\"+char+\" \"+s+\" \"+char\n Stroka+=\"\\n\"+top*char\n return Stroka\n\nprint(module4(-56, '/'))\n\n" }, { "alpha_fraction": 0.509471595287323, "alphanum_fraction": 0.5682951211929321, "avg_line_length": 33.58620834350586, "blob_id": "0dcd1227bc4bc54b1901ec7a04d051e8d77009ec", "content_id": "955e4802b24d39f474194fe5e55a8b79324c1417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1003, "license_type": "no_license", "max_line_length": 96, "num_lines": 29, "path": "/test_module4.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "import unittest\nimport module4\n\nclass Test1(unittest.TestCase):\n def test1(self):\n self.assertEqual(module4.module4(16, '+'), '++++++\\n+ 16 +\\n++++++')\n def test2(self):\n self.assertEqual(module4.module4(\"vgrve\", '+'), \"Input Error\")\n\nclass Test2(unittest.TestCase):\n def test1(self):\n self.assertEqual(module4.module4(1234567, '-'), '-----------\\n- 1234567 -\\n-----------')\n def test2(self):\n self.assertEqual(module4.module4(\"...........\", '+'), \"Input Error\")\n\nclass Test3(unittest.TestCase):\n def test1(self):\n self.assertEqual(module4.module4(-89, '/'), '///////\\n/ -89 /\\n///////')\n def test2(self):\n self.assertEqual(module4.module4(\"fff44\", '.'), \"Input Error\")\n\nclass Test4(unittest.TestCase):\n def test1(self):\n self.assertEqual(module4.module4(-56, '/'), '///////\\n/ -56 /\\n///////')\n def test2(self):\n self.assertEqual(module4.module4(\"56ggd\", '+'), \"Input Error\")\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5951557159423828, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 28.89655113220215, "blob_id": "5bcb55803c8913358317b2b550a1dc930ea60eba", "content_id": "1a8e883e84fc04fe4637d9169be0f76f27f43cf9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 867, "license_type": "no_license", "max_line_length": 69, "num_lines": 29, "path": "/test_module2.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "import unittest\nimport module2\n\nclass Test1(unittest.TestCase):\n def test1(self):\n self.assertEqual(module2.module2(3111), \"Input Error\")\n def test2(self):\n self.assertEqual(module2.module2(713524), True)\n\nclass Test2(unittest.TestCase):\n def test1(self):\n self.assertEqual(module2.module2(101235), False)\n def test2(self):\n self.assertEqual(module2.module2(456), \"Input Error\")\n\nclass Test3(unittest.TestCase):\n def test1(self):\n self.assertEqual(module2.module2(123456), False)\n def test2(self):\n self.assertEqual(module2.module2(\"vgrer4w4\"), \"Input Error\")\n\nclass Test4(unittest.TestCase):\n def test1(self):\n self.assertEqual(module2.module2(185536), True)\n def test2(self):\n self.assertEqual(module2.module2(\"/////////\"), \"Input Error\")\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.6092090010643005, "alphanum_fraction": 0.6670601963996887, "avg_line_length": 28.20689582824707, "blob_id": "76cb67e793ba905fbbb039e3f8c553f0effe5b9f", "content_id": "5e6b0c1ce6cb02815b445f26bea7afd19af3a046", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/test_module1.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "import unittest\nimport module1\n\nclass Test1(unittest.TestCase):\n def test1(self):\n self.assertEqual(module1.module1(156), True)\n def test2(self):\n self.assertEqual(module1.module1(34), True)\n\nclass Test2(unittest.TestCase):\n def test1(self):\n self.assertEqual(module1.module1(1), False)\n def test2(self):\n self.assertEqual(module1.module1(\"vgrvd\"), \"Input Error\")\n\nclass Test3(unittest.TestCase):\n def test1(self):\n self.assertEqual(module1.module1(\"ккккк\"), \"Input Error\")\n def test2(self):\n self.assertEqual(module1.module1(4444444447), False)\n\nclass Test4(unittest.TestCase):\n def test1(self):\n self.assertEqual(module1.module1(\"..не62\"), \"Input Error\")\n def test2(self):\n self.assertEqual(module1.module1(-98), True)\n\nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5049833655357361, "alphanum_fraction": 0.5282391905784607, "avg_line_length": 24.16666603088379, "blob_id": "468e93134052b27d47a9aa9efa7941206152b758", "content_id": "2f91acd28831a7f03513aff650ea7a5b81c69629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/module3.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "# Написать функцию, которая считает сумму всех цифр целого числа\n\ndef module3(num):\n if type(num) != int: return \"Input Error\"\n else:\n sum = 0\n num=abs(num)\n k = len(str(num))+1\n for i in range (k):\n sum += num%10\n num=num//10\n return sum" }, { "alpha_fraction": 0.6227757930755615, "alphanum_fraction": 0.6334519386291504, "avg_line_length": 30.11111068725586, "blob_id": "77bebb8ba7acc8dba51a1fa59422d4f5f0e9807e", "content_id": "d6215ea53b2cb792d4b6b5b94434301063279dbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 69, "num_lines": 9, "path": "/module1.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "# Написать функцию, которая определяет является ли целое число четным\n# При ошибочном вводе вывести \"Input Error\"\n\ndef module1(num):\n if type(num) != int: return \"Input Error\"\n else:\n num = abs(num)\n if ((num % 2) == 0): return True\n else: return False\n\n" }, { "alpha_fraction": 0.553816020488739, "alphanum_fraction": 0.6301369667053223, "avg_line_length": 35.28571319580078, "blob_id": "e87523945f6159e4e9fc218d860692b2d178c392", "content_id": "c7f487b576026c9186ec388d2c143a480b134fb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 82, "num_lines": 14, "path": "/module2.py", "repo_name": "Mironova66/module_test", "src_encoding": "UTF-8", "text": "# Написать функцию, которая определяет является ли шестизначное число \"счастливым\"\n# (сумма первых трех цифр равна сумме последних трех цифр)\n# При ошибочном вводе вывести \"Input Error\"\n\n\n\ndef module2(number):\n if type(number) != int:\n return \"Input Error\"\n else:\n if len(str(number)) != 6: return \"Input Error\"\n sum1 = number // 100000 + number // 10000 % 10 + number // 1000 % 10\n sum2 = number % 1000 // 100 + number % 100 // 10 + number % 10\n return sum1 == sum2\n\n\n\n" } ]
8
smo737/Blog-Project
https://github.com/smo737/Blog-Project
916de5fc889882b390555cf15acc31bfb14da1c0
17e63478ee9c650c9e8a6f346b988990f51f98ea
ca34c8d8df9291c173516cae44792d7f39cd0bed
refs/heads/master
2023-04-16T15:45:21.611236
2021-04-25T17:33:11
2021-04-25T17:33:11
361,491,309
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6479524374008179, "alphanum_fraction": 0.6512549519538879, "avg_line_length": 34.046295166015625, "blob_id": "72b915e08dda569765b9614f588ecb8d658ba813", "content_id": "aab8ee3fc8f42544f4b3f295bdae735723b2afa3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7570, "license_type": "no_license", "max_line_length": 120, "num_lines": 216, "path": "/main.py", "repo_name": "smo737/Blog-Project", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, redirect, url_for, flash, request\nfrom flask_bootstrap import Bootstrap\nfrom flask_ckeditor import CKEditor\nfrom datetime import date\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom flask_sqlalchemy import SQLAlchemy\n#from sqlalchemy import Table, Integer, ForeignKey\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nfrom flask_login import UserMixin, login_user, LoginManager, login_required, current_user, logout_user\nfrom forms import CreatePostForm, RegisterForm, LoginForm, CommentForm\nfrom flask_gravatar import Gravatar\nfrom functools import wraps\nimport os\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')\nckeditor = CKEditor(app)\nBootstrap(app)\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n##CONNECT TO DB\n\n#app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'\napp.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL', 'sqlite:///blog.db')\n\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\n##CONFIGURE TABLES\nclass User(UserMixin, db.Model):\n __tablename__ = \"users\"\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), nullable=False)\n email = db.Column(db.String(100), unique=True, nullable=False)\n password = db.Column(db.String(150), nullable=False)\n blogs = relationship(\"BlogPost\", back_populates=\"author\")\n comments = relationship(\"Comment\", back_populates=\"author\")\n\nclass BlogPost(db.Model):\n __tablename__ = \"blog_posts\"\n id = db.Column(db.Integer, primary_key=True)\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n author = relationship(\"User\", back_populates=\"blogs\")\n title = db.Column(db.String(250), unique=True, nullable=False)\n subtitle = db.Column(db.String(250), nullable=False)\n date = db.Column(db.String(250), nullable=False)\n body = db.Column(db.Text, nullable=False)\n img_url = db.Column(db.String(250), nullable=False)\n comments = relationship(\"Comment\", back_populates=\"blog\")\n\nclass Comment(db.Model):\n __tablename__ = \"comments\"\n id = db.Column(db.Integer, primary_key=True)\n blog_id = db.Column(db.Integer, db.ForeignKey('blog_posts.id'))\n user_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n body = db.Column(db.Text, nullable=False)\n author = relationship(\"User\", back_populates=\"comments\")\n blog = relationship(\"BlogPost\", back_populates=\"comments\")\n\n#db.create_all()\n\n@login_manager.user_loader\ndef load_user(user_id):\n return db.session.query(User).get(user_id)\n\n\ndef admin_only(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(\"Admin check\")\n if not current_user.is_authenticated or current_user.id != 1:\n return \"Forbidden. You do not have administrator access.\", 403\n return func(*args, **kwargs)\n return wrapper\n\n\n\[email protected]('/')\ndef get_all_posts():\n posts = BlogPost.query.all()\n return render_template(\"index.html\", all_posts=posts, logged_in=current_user.is_authenticated)\n\n\[email protected]('/register', methods=[\"GET\", \"POST\"])\ndef register():\n reg_form = RegisterForm()\n if request.method == \"POST\":\n if reg_form.validate_on_submit():\n check_user = db.session.query(User).filter_by(email=reg_form.email.data).first()\n if check_user:\n flash(\"Email already exists. Please login.\")\n return redirect(\"/login\")\n new_user = User()\n new_user.name = reg_form.name.data\n new_user.email = reg_form.email.data\n new_user.password = generate_password_hash(reg_form.password.data)\n db.session.add(new_user)\n db.session.commit()\n login_user(new_user)\n return redirect('/')\n else:\n return redirect('/register', logged_in=current_user.is_authenticated)\n else:\n return render_template(\"register.html\", form=reg_form)\n\[email protected]('/login', methods=[\"GET\", \"POST\"])\ndef login():\n login_form = LoginForm()\n if request.method == \"POST\":\n if login_form.validate_on_submit():\n req_user = db.session.query(User).filter_by(email=login_form.email.data).first()\n if not req_user:\n flash(\"User not found\")\n return redirect(\"/login\")\n if check_password_hash(req_user.password, login_form.password.data):\n login_user(req_user)\n return redirect(\"/\")\n else:\n flash(\"Incorrect password\")\n return redirect(\"/login\")\n\n\n return render_template(\"login.html\", logged_in=current_user.is_authenticated, form=login_form)\n\n\[email protected]('/logout')\ndef logout():\n logout_user()\n return redirect(url_for('get_all_posts'))\n\n\[email protected](\"/post/<int:post_id>\", methods=['GET', 'POST'])\ndef show_post(post_id):\n requested_post = BlogPost.query.get(post_id)\n comment_form = CommentForm()\n if comment_form.validate_on_submit() and comment_form.body != \"\":\n new_comment = Comment(user_id = current_user.id,\n blog_id = requested_post.id,\n body = comment_form.body.data)\n db.session.add(new_comment)\n db.session.commit()\n return redirect (f\"/clear-post/{post_id}\")\n\n return render_template(\"post.html\", post=requested_post, logged_in=current_user.is_authenticated, form=comment_form)\n\[email protected](\"/clear-post/<int:post_id>\")\ndef clear_post(post_id):\n print(\"redirecting\")\n return redirect(f\"/post/{post_id}\")\n\[email protected](\"/about\")\ndef about():\n return render_template(\"about.html\", logged_in=current_user.is_authenticated)\n\n\[email protected](\"/contact\")\ndef contact():\n return render_template(\"contact.html\", logged_in=current_user.is_authenticated)\n\[email protected](\"/new-post\", methods=['GET', 'POST'])\n@admin_only\ndef add_new_post():\n form = CreatePostForm()\n if form.validate_on_submit():\n new_post = BlogPost(\n title=form.title.data,\n subtitle=form.subtitle.data,\n body=form.body.data,\n img_url=form.img_url.data,\n author=current_user,\n date=date.today().strftime(\"%B %d, %Y\"),\n user_id = current_user.id\n )\n db.session.add(new_post)\n db.session.commit()\n return redirect(url_for(\"get_all_posts\"))\n return render_template(\"make-post.html\", form=form, logged_in=current_user.is_authenticated)\n\[email protected](\"/edit-post/<int:post_id>\")\n@admin_only\ndef edit_post(post_id):\n post = BlogPost.query.get(post_id)\n edit_form = CreatePostForm(\n title=post.title,\n subtitle=post.subtitle,\n img_url=post.img_url,\n author=post.author,\n body=post.body\n )\n if edit_form.validate_on_submit():\n post.title = edit_form.title.data\n post.subtitle = edit_form.subtitle.data\n post.img_url = edit_form.img_url.data\n post.author = edit_form.author.data\n post.body = edit_form.body.data\n db.session.commit()\n return redirect(url_for(\"show_post\", post_id=post.id))\n\n return render_template(\"make-post.html\", form=edit_form, logged_in=current_user.is_authenticated)\n\n\[email protected](\"/delete/<int:post_id>\")\n@admin_only\ndef delete_post(post_id):\n post_to_delete = BlogPost.query.get(post_id)\n db.session.delete(post_to_delete)\n db.session.commit()\n return redirect(url_for('get_all_posts'))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n" } ]
1
RF5/lmao
https://github.com/RF5/lmao
5760d3996a5f5566e56cf1e4f12582d40d2052ab
f6cfebc9a61a4f254d916274b417bc106d2278e5
8203d70275a24589711861b3f0a6d86808f36149
refs/heads/master
2023-05-12T17:01:17.557560
2023-05-02T14:24:06
2023-05-02T14:24:06
223,787,378
12
3
null
2019-11-24T18:03:25
2022-12-12T02:46:49
2023-05-02T14:20:50
CSS
[ { "alpha_fraction": 0.5141388177871704, "alphanum_fraction": 0.5214836597442627, "avg_line_length": 38.17266082763672, "blob_id": "fac13d3ca5729123fc31ab5ee915b65fb8ad4f1d", "content_id": "1c50c532f3f8cefc56120c2d4f34e19ec3f26eee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5446, "license_type": "no_license", "max_line_length": 118, "num_lines": 139, "path": "/lmao_integrator/background.js", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "chrome.runtime.onInstalled.addListener(function() {\n chrome.storage.sync.set({lm_inference_state: 'off', pred_len: 4, context_len: 200}, function() {\n console.log(\"LMAO reset xD\");\n });\n chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {\n chrome.declarativeContent.onPageChanged.addRules([{\n conditions: [new chrome.declarativeContent.PageStateMatcher({\n pageUrl: {urlMatches: '.*overleaf\\.com\\\\/project/.*'},\n })\n ],\n actions: [\n new chrome.declarativeContent.ShowPageAction(),\n ]\n }]);\n });\n });\n\nconst endpoint_name = \"lmao-test-01\";\nconst url = chrome.runtime.getURL('config.json');\nlet _api_key = null;\nfunction setAPI(incoming) {\n _api_key = incoming[\"x-api-key\"];\n}\n\nfetch(url)\n .then((response) => response.json()) //assuming file contains json\n .then((json) => setAPI(json));\n\nfunction get_word_count(str_arr) {\n var wcnt = 0;\n for (let i = 0; i < str_arr.length; i++) {\n wcnt = wcnt + str_arr[i].split(\" \").length\n }\n return wcnt;\n}\n\nfunction prune_comments_and_trim(str_arr, ctx_len) {\n function _remove_commented_lines(line) {\n const hashInd = line.indexOf('%');\n if(hashInd === 0) return false\n if(hashInd === 1 && line[hashInd - 1] != '\\\\') return false \n \n return true\n }\n str_arr = str_arr.filter(_remove_commented_lines);\n for (let i = 0; i < str_arr.length; i++) {\n const hashInd = str_arr[i].search(/[^\\\\]%/);\n if(hashInd != -1 && hashInd != null) {\n str_arr[i] = str_arr[i].substring(0, hashInd);\n }\n }\n var tmp = str_arr.slice(1);\n if(get_word_count(str_arr) > ctx_len) {\n while(get_word_count(tmp) > ctx_len) {\n str_arr.shift();\n tmp = str_arr.slice(1);\n }\n }\n return str_arr;\n}\n\nchrome.runtime.onMessageExternal.addListener(\nfunction(request, sender, sendResponse) {\n if(request.lines === null) {\n return;\n }\n\n // note: lm_inference_state is either \"off\", \"on_local\", or \"on_cloud\"\n chrome.storage.sync.get(['lm_inference_state', 'pred_len', 'context_len'], function(data) {\n if (data.lm_inference_state === 'off') {\n // console.log(\"Inference is off\");\n sendResponse(null);\n return;\n } else if(data.lm_inference_state === 'on_local') {\n // console.log(\"Getting inference from local machine\")\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", \"http://127.0.0.1:8000/infer\", true);\n xhr.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n xhr.onload = function (e) {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n // console.log(xhr.responseText);\n var response = JSON.parse(xhr.responseText);\n chrome.storage.sync.set({local_offline: false}, function() {});\n sendResponse({prediction: response.prediction});\n } else {\n sendResponse(null);\n msg_popup_offline('local');\n console.log(xhr.statusText);\n }\n }\n };\n xhr.onerror = function (e) {\n sendResponse(null);\n msg_popup_offline('local');\n console.log(xhr.statusText);\n };\n // console.log(\"sending \" + JSON.stringify(request.lines))\n var lines = prune_comments_and_trim(request.lines, data.context_len);\n xhr.send(JSON.stringify({lines: lines, pred_length: data.pred_len}));\n } else if(data.lm_inference_state === 'on_cloud') {\n var xhr = new XMLHttpRequest();\n xhr.open(\"POST\", \"https://h0sywlk4gh.execute-api.eu-west-1.amazonaws.com/test-lmao-en/invoke-lmao\", true);\n xhr.setRequestHeader('x-api-key', _api_key);\n xhr.setRequestHeader(\"Content-Type\", \"application/json;charset=UTF-8\");\n xhr.onload = function (e) {\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n // console.log(xhr.responseText);\n var response = JSON.parse(xhr.responseText);\n chrome.storage.sync.set({local_offline: false}, function() {});\n sendResponse({prediction: response.prediction});\n } else {\n sendResponse(null);\n msg_popup_offline('cloud');\n console.log(xhr.statusText);\n }\n }\n };\n xhr.onerror = function (e) {\n sendResponse(null);\n msg_popup_offline('cloud');\n console.log(xhr.statusText);\n };\n var lines = prune_comments_and_trim(request.lines, data.context_len);\n xhr.send(JSON.stringify({\"data\":{\"lines\": lines, \"pred_length\": data.pred_len, n_seqs: 3}}));\n }\n });\n});\n\nfunction msg_popup_offline(service) {\n if(service === 'local') {\n chrome.storage.sync.set({local_offline: true}, function() {\n });\n } else if(service === 'cloud') {\n chrome.storage.sync.set({cloud_offline: true}, function() {\n });\n }\n}\n\n" }, { "alpha_fraction": 0.49468085169792175, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 16.090909957885742, "blob_id": "b98bb848be56cd4a8f8e9a2b15a57a50638c9103", "content_id": "a01c70e5c33eacbd59f5f756835e9fdf6e82db48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 188, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/lmao/requirements.txt", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "Django==3.1.14\ndjangorestframework==3.11.2\nMarkdown==3.1.1\nnumpy==1.22.0\nPillow>=7.1.0\npytz==2019.3\nsix==1.13.0\nsqlparse==0.4.4\ntorch==1.3.1+cpu\ntorchvision==0.4.2+cpu\ntransformers==3.5.1\n" }, { "alpha_fraction": 0.7758186459541321, "alphanum_fraction": 0.7770780920982361, "avg_line_length": 98.3125, "blob_id": "4bee5e5d32d64955d58ffc68578526d4076d21d5", "content_id": "dbdf19975a4c3f47fb6668c3ce107e06ece64a3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 429, "num_lines": 16, "path": "/privacy_policy.md", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "# LMAO Privacy Policy\nLMAO does not store any data of any kind. The only information it ever interacts with is the last several of lines of text in an Overleaf document. It processes them in real time and then discards them. i.e no predictions, historical text, or anything at all is ever stored.\n\n- LMAO has no home server (only an inference endpoint if you choose to use cloud hosted predictions).\n- LMAO doesn't embed any kind of analytic hooks in its code.\n- LMAO doesn't cost anything and no feature of it is behind any paywall. \n- The only time LMAO connects to a remote server is \n - (a) by Chrome when it automatically updates the extension, and \n - (b) if you choose to use the cloud hosted predictions (and the prediction server is up and running), then whenever you start a prediction in an Overlead document, the last several lines of text in the current `.tex` file you are editing is sent via HTTPS to an AWS server, which runs it through GPT2 and returns the predictions. The sent text and computed predictions are ephemeral -- they are immidately discarded after use.\n\nThe project is currently hosted on github.com, which is owned by GitHub Inc. (now a subsidiary of Microsoft Corporation), and thus is unrelated to LMAO.\n\n### Changes to the privacy policy\nSince LMAO does not collect any information on users at all, there is no way to notify you of changes. But I will always update the privacy policy at least 3 months before they go into effect, so if you are concered just check back here a few times a year. But I don't have plants to ever change it.\n\nThat is all." }, { "alpha_fraction": 0.7029411792755127, "alphanum_fraction": 0.7029411792755127, "avg_line_length": 33, "blob_id": "c17c2892346717f72adf73a83d8cbad234a81925", "content_id": "fa69afa96006d8167e9faba5658b18ba15df8444", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 340, "license_type": "no_license", "max_line_length": 103, "num_lines": 10, "path": "/lmao/endpoints/urls.py", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "from . import views \nfrom django.urls import path\nfrom django.conf.urls import url, include\nfrom rest_framework.urlpatterns import format_suffix_patterns\n# urlpatterns = []\n\nurlpatterns = [\n # path('url_checker', views.check_url),\n *format_suffix_patterns([url(r'^infer$', views.Infer.as_view())], allowed=['json', 'html', 'api']),\n]\n" }, { "alpha_fraction": 0.6214575171470642, "alphanum_fraction": 0.6214575171470642, "avg_line_length": 37, "blob_id": "d5e88e58b76c068e12e595335b2bce6a4391574f", "content_id": "6345ca9c158e147ef38de9e6fa37585ce62c6fda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 494, "license_type": "no_license", "max_line_length": 68, "num_lines": 13, "path": "/lmao_integrator/contentScript.js", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "if(document.getElementById('lmao_injector_script') === null) {\n var s = document.createElement('script');\n s.id = \"lmao_injector_script\"\n s.src = chrome.runtime.getURL('injector.js');\n // s.onload = function() {\n // console.log(this)\n // this.remove();\n // };\n (document.head || document.documentElement).appendChild(s);\n\n chrome.storage.sync.set({local_offline: false}, function() {});\n chrome.storage.sync.set({cloud_offline: false}, function() {});\n}\n" }, { "alpha_fraction": 0.6227586269378662, "alphanum_fraction": 0.6259770393371582, "avg_line_length": 32.43077087402344, "blob_id": "fb26a17db6db146f660346719efc18c76fc03574", "content_id": "be7198af95190e8ad2883fad8d9b8ae56e4d0ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4350, "license_type": "no_license", "max_line_length": 76, "num_lines": 130, "path": "/lmao_integrator/popup.js", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "\nfunction inject_script() {\n console.log(\"Running injector script\")\n setTimeout(() => {\n chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {\n chrome.tabs.executeScript(tabs[0].id, {file: 'contentScript.js'});\n });\n }, 50);\n}\n\ndocument.addEventListener('DOMContentLoaded', (event) => {\n var offRadio = document.getElementById('offRadio');\n var onLocal = document.getElementById('onLocalHosted');\n var onCloud = document.getElementById('onCloudHosted');\n\n var offRadioLbl = document.getElementById('offRadioLbl');\n var onLocalLbl = document.getElementById('onLocalLbl');\n var onCloudLbl = document.getElementById('onHostedLbl');\n\n var prev = null;\n\n chrome.storage.sync.get('lm_inference_state', function(data) {\n if (data.lm_inference_state === 'off') {\n console.log(\"Inference is off\")\n offRadio.checked = true\n setTimeout(() => {\n offRadioLbl.MaterialRadio.check()\n }, 40);\n\n prev = offRadio\n } else if(data.lm_inference_state === 'on_local') {\n console.log(\"Getting inference from local machine\")\n onLocal.checked = true\n setTimeout(() => {\n onLocalLbl.MaterialRadio.check()\n }, 40);\n inject_script()\n prev = onLocal\n } else if(data.lm_inference_state === 'on_cloud') {\n console.log(\"Getting inference from cloud\")\n onCloud.checked = true\n setTimeout(() => {\n onCloudLbl.MaterialRadio.check()\n }, 40);\n inject_script()\n prev = onCloud\n }\n offRadio.addEventListener('change', function() {\n if (this !== prev) {prev = this;}\n chrome.storage.sync.set({lm_inference_state: this.value}, function() {\n console.log(\"lm_inference_state has been set to\", prev.value);\n });\n });\n \n onLocal.addEventListener('change', function() {\n if (this !== prev) {prev = this;}\n chrome.storage.sync.set({lm_inference_state: this.value}, function() {\n console.log(\"lm_inference_state has been set to\", prev.value);\n inject_script()\n });\n });\n \n onCloud.addEventListener('change', function() {\n if (this !== prev) {prev = this;}\n chrome.storage.sync.set({lm_inference_state: this.value}, function() {\n console.log(\"lm_inference_state has been set to\", prev.value);\n inject_script()\n });\n });\n });\n\n var links = document.getElementsByTagName(\"a\");\n for (var i = 0; i < links.length; i++) {\n (function () {\n var ln = links[i];\n var location = ln.href;\n ln.onclick = function () {\n chrome.tabs.create({active: true, url: location});\n };\n })();\n }\n\n chrome.storage.sync.get('local_offline', function(data) {\n console.log(data)\n if(data.local_offline === true) {\n var spon = document.getElementById('local_status');\n spon.textContent = \"[OFFLINE]\"\n }\n });\n chrome.storage.sync.get('cloud_offline', function(data) {\n if(data.cloud_offline === true) {\n var spon = document.getElementById('cloud_status');\n spon.textContent = \"[OFFLINE]\"\n }\n });\n\n // stuff for prediction length slider\n var predlenSlider = document.getElementById('pred_len_slider');\n var predlenLbl = document.getElementById('pred_len_lbl');\n predlenSlider.addEventListener('change', function() {\n const new_val = this.value;\n chrome.storage.sync.set({pred_len: new_val}, function() {\n console.log(\"pred_len has been set to\", new_val);\n predlenLbl.textContent = new_val;\n });\n });\n\n chrome.storage.sync.get('pred_len', function(data) {\n predlenLbl.textContent = data.pred_len;\n setTimeout(() => {\n predlenSlider.MaterialSlider.change(data.pred_len);\n }, 40);\n });\n // stuff for context length slider\n var ctxlenSlider = document.getElementById('context_len_slider');\n var ctxlenLbl = document.getElementById('context_len_lbl');\n ctxlenSlider.addEventListener('change', function() {\n const new_val = this.value;\n chrome.storage.sync.set({context_len: new_val}, function() {\n console.log(\"context_len has been set to\", new_val);\n ctxlenLbl.textContent = new_val;\n });\n });\n\n chrome.storage.sync.get('context_len', function(data) {\n ctxlenLbl.textContent = data.context_len;\n setTimeout(() => {\n ctxlenSlider.MaterialSlider.change(data.context_len);\n }, 40);\n });\n})\n\n\n\n" }, { "alpha_fraction": 0.7705416083335876, "alphanum_fraction": 0.7788088321685791, "avg_line_length": 101.18965148925781, "blob_id": "99445333fb142c8f2b7c7e704e3a3afd1c1076f6", "content_id": "aeef950d082b002b1e7b93ab453a819f8694d40b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5927, "license_type": "no_license", "max_line_length": 579, "num_lines": 58, "path": "/README.md", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "# LMAO - Language model accessor object\nWhat? A chrome extension that adds a neural auto-complete function to LaTeX documents in any Overleaf project. Concretely, it is a GPT2 language model server which hooks into Overleaf's editor to add 'gmail smart compose' or '[write with transformer](https://transformer.huggingface.co/)'-like functionlity, but for LaTeX and it works seamlessly on top of Overleaf's editor :).\n\nSome more info:\n- Works with all existing Overleaf setups (all color themes, existing hotkeys...)\n- Autocompletes the next few words given the historical context in the current document.\n- Here is what some of the predictions look like in the editor:\n\n![gif of live predictions](lmao_zoomed.gif)\n\n**STATUS UPDATE Feb 2021: on haitus**. Please get in contact if you would like to help test out the extension or take the project further. Due to time and other constraints, I haven't been able to continue development of this project. Following the rest of this readme might not work exactly as some libraries have been updated and API calls have changed, so you might need to fiddle around to get things to work. Nevertheless, it is still quite fun once one gets it working, and if anyone wants to continue work on it feel free to fork the repo or just see how I've done things.\n\n**STATUS UPDATE May 2023: indefinite haitus**. I am archiving the repository since it is very inactive and many of the libraries it is based on have had substantial changes and upgrades in the intervening years. If anyone wishes to pick up this project please let me know. \n\n## TL;DR: how it works\nA chrome extension interfaces with Overleaf to, whenever a certain hotkey is pressed, send an HTTPS request to an external inference server (running the GPT2 model) passing along the recent text history around the cursor. The server then returns a few predictions for the next few words, and the chrome extension adds these as autocompletions in the Overleaf editor. [Feel free to read more about it, and how the GPT2 models were fine-tuned here](https://rf5.github.io/2019/12/09/lmao-overleaf.html).\n\nThis external server can either be a local python Django server or the external cloud server that I would like to host. Currently only the local option is available until I find enough funds to host a persistent GPU server (as any CPU instance takes waaay to long for autocompletes). If you are in a position to help fund this project, please get in [contact with me here](https://rf5.github.io/about.html).\n\nNote: this project is in no way associated with Overleaf or their team. It's just a cool extension that hooks into Overleaf because their service and editor is quite nice.\n\n### Customization\nThe various settings of LMAO can be adjusted by clicking on the icon when in Overleaf, which brings up a menu that looks something like\n\n<p align=\"center\"><img src=\"popup.jpg\"></p>\n\nThe settings are:\n- **Prediction length** is the number of words to auto-complete for each prediction. i.e a value of 4 means that predictions for the next 4 words will be generated. Extremely high values of this may increase prediction times a little.\n- **Context length** is the number of words before the current cursor position to use as historical context to condition the text generation on. So a value of 200 means \"use the last 200 words to predict the next word\". Extremely high values of this may increase prediction times a little (still <800ms even at 600 words with a GPU).\n\n## Installation\nSimply go to the Google chrome web store and navigate to this extension and hit 'install'. Then next time you go to an overleaf project, click the icon and it should be pretty obvious what to do :). \n\n## Setting up python Django server for local inference\nIf you have a reasonable Nvidia GPU and have python installed, then you can host the server locally with django! So, in addition to getting the chrome extension, you need to:\n- Clone this repo\n- Create a new python environment (3.6 or newer)\n- Open a new terminal with the new python environment activated, cd into `lmao/` folder.\n- Install pip requirements (`pip install -r requirements.txt`). You might need to run a separate command to install pytorch correctly on your system. See [Pytorch's installation guide for more info](https://pytorch.org/get-started/locally/).\n- Create a folder in this directory called `models/`. Download the GPT2 model/config zip file `gpt2-small.zip` under the 'Releases' tab and extract it into the `models/` folder. So now there should be a `lmao/models/gpt2-small` folder.\n- Now run `python manage.py runserver`. It should start up the server and just idle in the background. Leave this terminal running while you are using the extension on Overleaf. If you want to run the local server again, just start up the terminal and activate your python environment, and run `python manage.py runserver` again. PS: you might need to run `python manage.py migrate` the first time you try run the server, depending on the Django version.\n\n## Setting up cloud hosting on AWS\nDon't worry, only I need to do this. Currently just trying to gather enough funds for a persistent GPU inference server.\n\n## Current leads\n- Aquire funding for GPU cloud server.\n- Allow custom hotkey setup for inference\n- Allow inference if user does not type for a certain number of seconds\n- Train and use bigger GPT2 models for better predictions + get more quality LaTeX source files to train on.\n\n## Past explored leads:\n- [Links to host the model with GPU support](https://pytorch.org/blog/model-serving-in-pyorch/)\n- find where `base` of `editor.completer.base` is set during each call.... It defines the start position of the prefix (where the last '\\' is ). \n- Alternatively, try find a way to change the prefix behavior calculation. See line 1508/1542 of ext-language-tools.\n\n## Known bugs\n- ~~Does not work so well if large portions of the document are commented out.~~ Fixed.\n" }, { "alpha_fraction": 0.6485584378242493, "alphanum_fraction": 0.6634294390678406, "avg_line_length": 40.433963775634766, "blob_id": "a85956b58b274a9b11743f97363a4feb81563410", "content_id": "f139244d2916828aea93571ffca33e31cc228627", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6590, "license_type": "no_license", "max_line_length": 119, "num_lines": 159, "path": "/lmao/endpoints/views.py", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "import os, time\nimport urllib.request\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.views.generic import View\nfrom rest_framework.authentication import (SessionAuthentication,\n TokenAuthentication)\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.decorators import action\nfrom rest_framework import status\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nimport torch\nimport torch.nn.functional as F\nfrom transformers import GPT2LMHeadModel, GPT2Tokenizer\nfrom transformers import WEIGHTS_NAME, CONFIG_NAME\n\n'''\nLMAO [Language Model Accessor Orchestrator views\n'''\n\noutput_dir = \"./models/gpt2-small\"\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(\"Loading model into memory from dir \", output_dir)\n# Step 1: Save a model, configuration and vocabulary that you have fine-tuned\n\n# If we have a distributed model, save only the encapsulated model\n# (it was wrapped in PyTorch DistributedDataParallel or DataParallel)\n# model_to_save = model.module if hasattr(model, 'module') else model\n\n# If we save using the predefined names, we can load using `from_pretrained`\n# output_model_file = os.path.join(output_dir, WEIGHTS_NAME)\n# output_config_file = os.path.join(output_dir, CONFIG_NAME)\n\n# torch.save(model_to_save.state_dict(), output_model_file)\n# model_to_save.config.to_json_file(output_config_file)\n# tokenizer.save_vocabulary(output_dir)\n\n# Step 2: Re-load the saved model and vocabulary\nmodel = GPT2LMHeadModel.from_pretrained(output_dir)\ntokenizer = GPT2Tokenizer.from_pretrained(output_dir)\nmodel.eval()\nmodel.to(device)\nprint(\"Done!\")\nprint(\"Is on GPU: \", next(model.parameters()).is_cuda)\n\ndef gpt2_infer(historical_context, pred_length=10, repetition_penalty=1.0, num_samples=3):\n top_p = 0.5\n temperature = 0.9 # more temperature -> more entropy\n\n original_context_tokens = torch.tensor(tokenizer.encode(historical_context)).to(device)\n generated = original_context_tokens.unsqueeze(0).repeat(num_samples, 1)\n context = generated\n # context = torch.tensor([generated]).to(device).repeat(num_samples, 1)\n past = None\n\n for i in range(pred_length):\n output, past = model(context, past=past)\n\n next_token_logits = output[:, -1, :]\n next_token_logits /= (temperature if temperature > 0 else 1.)\n \n filtered_logits = top_k_top_p_filtering(next_token_logits, top_p=top_p)\n if temperature == 0: # greedy sampling:\n next_token = torch.argmax(filtered_logits, dim=-1).unsqueeze(-1)\n else:\n next_token = torch.multinomial(F.softmax(filtered_logits, dim=-1), num_samples=1)\n # print(next_token, token, next_token.squeeze(), token.unsqueeze(0))\n # generated += [next_token.squeeze().tolist()]\n generated = torch.cat((generated, next_token), dim=1)\n context = next_token\n # print(past[0][0].shape) # WATCH OUT TODO: the shape of past grows a lot as u generate more tokens\n\n gen_seqs = []\n gen_lists = generated[:, len(original_context_tokens):].tolist()\n for o in gen_lists:\n sequence = tokenizer.decode(o, clean_up_tokenization_spaces=True)\n # print('>> ', sequence[-500:], 'TRIMMED', sequence[len(historical_context):])\n # gen_seqs.append(sequence[len(historical_context):])\n if historical_context[-1] == ' ' and sequence[0] == ' ':\n gen_seqs.append(sequence[1:])\n else:\n gen_seqs.append(sequence)\n\n \n return gen_seqs\n \n\ndef top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):\n \"\"\" Filter a distribution of logits using top-k and/or nucleus (top-p) filtering\n Args:\n logits: logits distribution shape (batch size x vocabulary size)\n top_k > 0: keep only top k tokens with highest probability (top-k filtering).\n top_p > 0.0: keep the top tokens with cumulative probability >= top_p (nucleus filtering).\n Nucleus filtering is described in Holtzman et al. (http://arxiv.org/abs/1904.09751)\n From: https://gist.github.com/thomwolf/1a5a29f6962089e871b94cbd09daf317\n \"\"\"\n top_k = min(top_k, logits.size(-1)) # Safety check\n if top_k > 0:\n # Remove all tokens with a probability less than the last token of the top-k\n indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]\n logits[indices_to_remove] = filter_value\n\n if top_p > 0.0:\n sorted_logits, sorted_indices = torch.sort(logits, descending=True)\n cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)\n\n # Remove tokens with cumulative probability above the threshold\n sorted_indices_to_remove = cumulative_probs > top_p\n # Shift the indices to the right to keep also the first token above the threshold\n sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()\n sorted_indices_to_remove[..., 0] = 0\n\n # scatter sorted tensors to original indexing\n indices_to_remove = sorted_indices_to_remove.scatter(dim=1, index=sorted_indices, src=sorted_indices_to_remove)\n logits[indices_to_remove] = filter_value\n return logits\n\n\"\"\"\nVIEWS\n\"\"\"\n\nclass Infer(APIView):\n \"\"\" Logout view; only applicable to token authentication \"\"\"\n authentication_classes = (TokenAuthentication, )\n permission_classes = (AllowAny, )\n\n def post(self, request, format=None):\n try:\n lines = request.data['lines']\n except Exception as e:\n return Response(\"Error: Invalid parameters.\", \n status=status.HTTP_400_BAD_REQUEST)\n\n if 'pred_length' in request.data:\n try: \n pred_length = int(request.data['pred_length'])\n except Exception as e:\n return Response(\"Error: prediction length specified but in wrong format\",\n status=status.HTTP_400_BAD_REQUEST)\n else:\n pred_length = 5\n\n start = time.time()\n pred_text = gpt2_infer('\\n'.join(lines), pred_length=pred_length)\n end = time.time()\n print(f\">>>>> Took {end-start} seconds.\")\n print(\">>>>> Predicted text: \", pred_text)\n response = {\n 'message': 'Success',\n 'prediction': pred_text,\n }\n\n return Response(response, \n status=status.HTTP_200_OK)\n\n\n" }, { "alpha_fraction": 0.5727518200874329, "alphanum_fraction": 0.5796989798545837, "avg_line_length": 35.751773834228516, "blob_id": "1635949511818118a4b6b3cf3b1c80bf32e2ea4e", "content_id": "9b67342d0103fc67f424e9bef3551b20b264381c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5182, "license_type": "no_license", "max_line_length": 113, "num_lines": 141, "path": "/lmao_integrator/injector.js", "repo_name": "RF5/lmao", "src_encoding": "UTF-8", "text": "util = ace.require('ace/autocomplete/util')\nconst aceSnippetManager55 = ace.require('ace/snippets').snippetManager\nconst { Autocomplete } = ace.require('ace/autocomplete')\n\nconsole.log(\"Content script initializing...\");\nvar editorExtensionId = \"iolciglhoknmnacbfjgccoibbcffofhk\";\nvar editor_proxy = _debug_editors[0];\n\n// inserting text at current position:\n// var cursorPosition = editor_proxy.getCursorPosition();\n// editor_proxy.session.insert(cursorPosition, \"MEME REVIEW\");\n\n// gets the last 26 lines\n// var lines = editor_proxy.session.getLines(cursorPosition[\"row\"]-25, cursorPosition[\"row\"])\n// lines[lines.length - 1] = lines[lines.length - 1].substring(0, cursorPosition[\"column\"])\nvar lm_prediction_flag = false;\n\nvar languageModelCompleter = {\n identifierRegexps: [/.+/],\n getCompletions: function(editor, session, pos, prefix, callback) {\n // console.log(pos, prefix);\n\n // don't try autocomplete if we are already doing commands...\n if(prefix.startsWith('\\\\') && prefix.length == 1) return\n if(prefix.startsWith('\\\\') && (prefix.includes(\" \") == false) && (prefix.includes(\"{\") == false)) return\n if(lm_prediction_flag == false) return\n\n // gather last n lines\n const grab_n_lines = 100;//50;\n var lines = editor_proxy.session.getLines(pos[\"row\"] - grab_n_lines, pos[\"row\"])\n\n lines[lines.length - 1] = lines[lines.length - 1].substring(0, pos[\"column\"]+1)\n\n console.log(\">>> Getting predictions with last 5 lines \", lines.slice(lines.length-5))\n\n // dispatch message to background script\n var resp = \"None\";\n chrome.runtime.sendMessage(editorExtensionId, \n {lines: lines}, \n function(response) {\n if(response === null) {\n callback(null, []);\n lm_prediction_flag = false;\n return;\n }\n resp = response.prediction;\n console.log(\"Inserting text:\\t\", resp);\n const result = resp.map(function(x) { \n return {\n caption: x, // what is shown in the preview bar\n value: x, // what goes onto the line if u smash tab\n // snippet: '>>'+x,\n completer: {\n insertMatch: function (editor, data) {\n editor.completer.insertMatch({value: data.value})\n Autocomplete.prototype.insertMatch = Autocomplete.prototype._overleafInsertMatch;\n }\n },\n meta: 'gpt2',\n score: 90\n }\n })\n callback(null, result)\n lm_prediction_flag = false;\n }); \n }\n};\n\nfunction getLastCommandFragment(lineUpToCursor) {\n let index\n if ((index = getLastCommandFragmentIndex(lineUpToCursor)) > -1) {\n return lineUpToCursor.slice(index)\n } else {\n return null\n }\n};\n\nfunction getLastCommandFragmentIndex(lineUpToCursor) {\n let m\n const blankArguments = lineUpToCursor.replace(/\\[([^\\]]*)\\]/g, args =>\n Array(args.length + 1).join('.')\n )\n if ((m = blankArguments.match(/(\\\\[^\\\\]*)$/))) {\n return m.index\n } else {\n return -1\n }\n};\n\nutil.retrievePrecedingIdentifier = function(text, pos, regex) {\n let currentLineOffset = 0\n for (let i = pos - 1; i <= 0; i++) {\n if (text[i] === '\\n') {\n currentLineOffset = i + 1\n break\n }\n }\n const currentLine = text.slice(currentLineOffset, pos) // problem 2: this fucks up\n var fragment = getLastCommandFragment(currentLine) || '';\n if (lm_prediction_flag) {\n fragment = ''\n }\n return fragment\n};\n\neditor_proxy.completers.push(languageModelCompleter);\n\nAutocomplete.prototype._overleafInsertMatch = Autocomplete.prototype.insertMatch\nAutocomplete.prototype._lmaoInsertMatch = function(data) {\n if (!data)\n data = this.popup.getData(this.popup.getRow());\n if (!data)\n return false;\n\n if (data.completer && data.completer.insertMatch) {\n data.completer.insertMatch(this.editor, data);\n } else {\n // TODO add support for options.deleteSuffix\n if (this.completions.filterText) {\n var ranges = this.editor.selection.getAllRanges();\n for (var i = 0, range; range = ranges[i]; i++) {\n range.start.column -= this.completions.filterText.length;\n this.editor.session.remove(range);\n }\n }\n if (data.snippet)\n aceSnippetManager55.insertSnippet(this.editor, data.snippet);\n else\n this.editor.execCommand(\"insertstring\", data.value || data);\n }\n this.detach();\n};\n\ndocument.addEventListener(\"keyup\", function (zEvent) {\n // console.log\n if (zEvent.shiftKey && zEvent.key === \"Tab\") { // case sensitive\n lm_prediction_flag = true;\n Autocomplete.prototype.insertMatch = Autocomplete.prototype._lmaoInsertMatch\n editor_proxy.execCommand(\"startAutocomplete\");\n }\n});\n" } ]
9
Anju3245/Sample-example
https://github.com/Anju3245/Sample-example
b9e5a14e24ba897287e7b62da26f9efa2009e72a
6c8befb838250e9ecb3aceca51a99a9aee4770eb
fc2ae464f36e749faa365fca5bc2e375bbc9374a
refs/heads/master
2021-01-20T14:22:33.564904
2017-05-08T10:26:13
2017-05-08T10:26:13
90,594,940
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6206896305084229, "alphanum_fraction": 0.6436781883239746, "avg_line_length": 20.75, "blob_id": "5e657473f3e22c26916f4c06631b42ae44b3f07c", "content_id": "0ae68f1a917d8560488240d015489263fea69f0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 36, "num_lines": 4, "path": "/test2.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "name=[\"anju\",\"anitha\",\"aparna\"]\nprint(frist_name array is: name[1])\n#print(name[1])\n#\n" }, { "alpha_fraction": 0.773809552192688, "alphanum_fraction": 0.773809552192688, "avg_line_length": 15.800000190734863, "blob_id": "d3a22c85920a424735ea360b522497eea2a4a24d", "content_id": "e009553ff6998e7065a20b4fb5d4cc1374cecc55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 84, "license_type": "no_license", "max_line_length": 16, "num_lines": 5, "path": "/README.md", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "# Sample-example\n# sample-example\n# Sample-example\n sample-example\n# Sample-example\n" }, { "alpha_fraction": 0.6319018602371216, "alphanum_fraction": 0.6319018602371216, "avg_line_length": 26.16666603088379, "blob_id": "d4bb533973f1a3ed300b97b5873d92978efadec7", "content_id": "c4a81cb9332cb2f29e98810fdd6583337d4648d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 56, "num_lines": 6, "path": "/e.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "def sample(first_line,second_line):\n print(first_line)\n input()\n print(second_line)\n input ()\n #print(f\"his full name is {first_name} {last_name}\")\n" }, { "alpha_fraction": 0.6882591247558594, "alphanum_fraction": 0.692307710647583, "avg_line_length": 21.454545974731445, "blob_id": "37c5bfa0e0b465b9c0982ac85a8d150f61a632c9", "content_id": "c0ad4caa3727ab8c1edadb5cda729eaab44b223f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 45, "num_lines": 11, "path": "/ex60.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,from_file,to_file = argv\n\ndef rewind(f):\n f.seek(5)\n#print(f\"Copying from {from_file} {to_file}\")\nin_file=open(from_file)\nindata=in_file.read()\n#name=input()\nout_file=open(to_file,'w')\nout_file.write(indata+#+ name)\n" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6111111044883728, "avg_line_length": 26, "blob_id": "61227facd627f263e4c83063679acea4d69c4190", "content_id": "da68f4508a0fe727676531d18435fcfa92e073b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "no_license", "max_line_length": 55, "num_lines": 6, "path": "/ex61.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "def sample(frist_name,last_name):\n print(\"first_name\")\n input()\n print(\"last_name\")\n input ()\n print(f\"his full name is {first_name} {last_name}\")\n" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 22.100000381469727, "blob_id": "ede074b028ce1ec206b14e3e9bf13af93b1172ac", "content_id": "a0ac7f5b0777f0290745243f0532f65d3e64ae5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 37, "num_lines": 10, "path": "/ex15.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "from sys import argv\n\nscript, filename = argv\ntxt= open(filename)\nprint(f\"here's your file{filename}:\")\nprint(txt.read())\nprint(\"type the filename again:\")\nfile_again=input(\">\")\ntext_again=open(file_again)\nprint(text_again.read())\n" }, { "alpha_fraction": 0.691629946231842, "alphanum_fraction": 0.691629946231842, "avg_line_length": 27.375, "blob_id": "eb2124dff18508962f7f2161e54f45b1897cbb94", "content_id": "9a2cc4f4cf320241991f9e2f7d3aef57e4ca2f97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 227, "license_type": "no_license", "max_line_length": 43, "num_lines": 8, "path": "/ex13.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "from sys import argv\n# read the WYSS section for how to run this\na, b, c, d = argv\n\nprint(\"The script is called:\", a)\nprint(\"Your first variable is:\", b)\nprint(\"Your second variable is:\", c)\nprint(\"Your third variable is:\", d)\n" }, { "alpha_fraction": 0.6480447053909302, "alphanum_fraction": 0.6536312699317932, "avg_line_length": 21.375, "blob_id": "ee75fcee58055c8ccadc711228f785eb4bb7759b", "content_id": "80ec05b4755b9ed7b5c8265f60b49643eacb76db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 36, "num_lines": 8, "path": "/sssssss.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,first_file,second_file = argv\ndef print_all(f):\n print(f.read())\ndef rewind(f):\n f.seek(5)\n in_file = open(first_file):\n print(first_file)\n" }, { "alpha_fraction": 0.6005089282989502, "alphanum_fraction": 0.6005089282989502, "avg_line_length": 23.5625, "blob_id": "9444dff462f8659dd24b92f896d5e4726f72cd93", "content_id": "15c438fa9f1e4875bd8c7510eb17177d6f997f3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 393, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/ex66.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "print(\"enter number frist:\")\nfrist = input()\nprint(\"enter second number:\")\nsecond = input()\nprint(\"enter third number:\")\nthird = input()\nif frist > second:\n if frist > third:\n print(f\"{frist} is the largest\")\n else:\n print(f\"{third} is the largest \")\nelse:\n if second > third:\n print(f\"{second} the largest\")\n else:\n print(f\"{third} is the largest \")\n" }, { "alpha_fraction": 0.7440758347511292, "alphanum_fraction": 0.7440758347511292, "avg_line_length": 34.16666793823242, "blob_id": "f8acbdfa7d9a93b3030606ae9ceeb7538e1d2ac4", "content_id": "a6448a1cfd39b985d50969c137c8cffb7af572cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 211, "license_type": "no_license", "max_line_length": 40, "num_lines": 6, "path": "/test.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "from sys import argv\nscript,frist, second,third = argv\nprint(\"the script is called:\",script)\nprint(\"Your frist varible is:\",frist)\nprint(\" your second varible is:\",second)\nprint(\" your third varible is:\",third)\n" }, { "alpha_fraction": 0.6733871102333069, "alphanum_fraction": 0.6733871102333069, "avg_line_length": 30, "blob_id": "f6ebbfd9e978b8965e7c6ddba8fa0f2d89a9c0aa", "content_id": "8932cb10a8c818c1f57e0a542ad6e81e41b4c7f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 51, "num_lines": 8, "path": "/functions.py", "repo_name": "Anju3245/Sample-example", "src_encoding": "UTF-8", "text": "print(\"enter your first name:\")\nfirst_name = input()\nprint(\"enter your last name:\")\nlast_name = input()\nprint(f\"his full name is {first_name} {last_name}\")\nout_file = open(\"c.txt\", 'w')\nout_file.write(indata+ \"his full name is \"+)\nout_file.close()\n" } ]
11
724994750/My-first-Github-test
https://github.com/724994750/My-first-Github-test
bfd4f375bae99331729cd37e264649862da3fed4
4e1bc7446cf1b7481c4a3416a5f343ba90deb02e
c7c4f129c9f60b0a7b3a5697277ef12ca29a1f57
refs/heads/master
2022-04-24T03:03:49.639031
2020-04-25T04:06:35
2020-04-25T04:06:35
258,681,295
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 20, "blob_id": "4b6f4afb9b4a882bb19588271b4311c78a172ecc", "content_id": "7faf25b1ac1e9d1a107c465ce32ea418b4e5a54a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 78, "license_type": "no_license", "max_line_length": 22, "num_lines": 2, "path": "/README.md", "repo_name": "724994750/My-first-Github-test", "src_encoding": "UTF-8", "text": "# My-first-Github-test\n这里是项目描述,仓库名称一般为项目名\n" }, { "alpha_fraction": 0.6785714030265808, "alphanum_fraction": 0.6785714030265808, "avg_line_length": 8.333333015441895, "blob_id": "5b8cd53d1b23225c13fe937dbf843e1bba1350e0", "content_id": "40f76ffde0e0843ef6f6f0f3b6761e84735bb34f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 36, "license_type": "no_license", "max_line_length": 20, "num_lines": 3, "path": "/text1(创建的文件名,需要后缀).py", "repo_name": "724994750/My-first-Github-test", "src_encoding": "UTF-8", "text": "print(\"Hello World\")\n\n#修改一次\n" } ]
2
alexxsub/server-run-python
https://github.com/alexxsub/server-run-python
c997b4c1978706f8f84c7fd80ea69057695e4317
d139ee00c2cef0f9af197999cc642ea730055910
0d682e1c4aefd5998ae927b56346b4a6ccca7bd7
refs/heads/master
2023-08-05T04:16:18.516250
2021-09-16T08:48:56
2021-09-16T08:48:56
406,257,922
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7097361087799072, "alphanum_fraction": 0.7179253697395325, "avg_line_length": 16.725807189941406, "blob_id": "d497d167b56e71c5343a549ffe8c34047ff88dbb", "content_id": "801bc55bc60108789d7d8594f8dd1db7ae45d527", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1099, "license_type": "no_license", "max_line_length": 90, "num_lines": 62, "path": "/README.md", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "# Quasar, Vue,Apollo,GraphQL,MongoDB App and Python\n\nA Quasar Framework app and Apollo with GraphQL SPA template\n\nSee Python menu item for example to run python script on server\n\n## copy local src of app\n\n```bash\ngit clone https://github.com/alexxsub/server-run-python.git\n```\n\n## Install MongoDB\n\nsee manual (https://docs.mongodb.com/manual/installation/)\n\n## Install the dependencies\n\n```bash\ncd server-run-python\nnpm i\n```\n\n### Configure your app in .env, for example\n\n```bash\n\nPORT = 4001\nBASE_URL=http://localhost:${PORT}/\nMONGO_URI=mongodb://localhost:27017/demo_app\nGRAPHQL_URI=${BASE_URL}api\nDEBUG = false\nSECRET=i_love_apollo\n```\n\n### Start the backend app in development mode (hot-code reloading, error reporting, etc.)\n\n```bash\nnpm run server\n```\n\n### Start the frontend app in development mode (hot-code reloading, error reporting, etc.)\n\n```bash\nnpm run client\n```\n\n### Lint the files\n\n```bash\nnpm run lint\n```\n\n### Build the app for production\n\n```bash\nquasar build\n```\n\n### Customize the configuration\n\nSee [Configuring quasar.conf.js](https://quasar.dev/quasar-cli/quasar-conf-js).\n" }, { "alpha_fraction": 0.5024711489677429, "alphanum_fraction": 0.5052168965339661, "avg_line_length": 22.33333396911621, "blob_id": "2dc4bd831065a6540d35ef451677e3ca1a5df57e", "content_id": "1f4648ca120974a5bc639e6f7684ca9e9ca940de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1821, "license_type": "no_license", "max_line_length": 65, "num_lines": 78, "path": "/src/router/routes.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "\nconst routes = [\n {\n path: '/',\n component: () => import('layouts/MainLayout.vue'),\n children: [\n { path: '', component: () => import('pages/loading.vue') }\n ]\n },\n {\n path: '/home',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/Index.vue') }\n ]\n },\n {\n path: '/login',\n component: () => import('layouts/LoginLayout.vue'),\n children: [\n { path: '', component: () => import('pages/login.vue') }\n ]\n },\n {\n path: '/profile',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/profile.vue') }\n ]\n },\n {\n path: '/director',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/director.vue') }\n ]\n },\n {\n path: '/manager',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/manager.vue') }\n ]\n },\n {\n path: '/users',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/users.vue') }\n ]\n },\n {\n path: '/users2',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/users2.vue') }\n ]\n },\n {\n path: '/table',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/table.vue') }\n ]\n },\n {\n path: '/python',\n component: () => import('layouts/HomeLayout.vue'),\n children: [\n { path: '', component: () => import('pages/python.vue') }\n ]\n },\n {\n path: '*',\n component: () => import('pages/Error404.vue')\n }\n]\n\nexport default routes\n" }, { "alpha_fraction": 0.574999988079071, "alphanum_fraction": 0.5790908932685852, "avg_line_length": 15.541353225708008, "blob_id": "23229371ddbc7dc56d0a51bef40dc2b484a92e15", "content_id": "73aafc29187a198ae87e857e7231d1e47471877a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2201, "license_type": "no_license", "max_line_length": 75, "num_lines": 133, "path": "/src/queries/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nimport gql from 'graphql-tag'\n\nexport const fragment = gql`\n fragment User on User {\n _id\n avatar\n username\n fullname\n email\n roles\n enabled\n createdDate\n }\n`\nexport const CURRENT_USER = gql`\n query getCurrentUser {\n getCurrentUser {\n ...User\n }\n }\n ${fragment}\n`\nexport const USERS = gql`\n query getUsers {\n getUsers {\n ...User\n }\n }\n ${fragment}\n`\nexport const USERS2 = gql`\n query getUsers2 {\n getUsers2 {\n docs{\n ...User\n }\n page\n rowsPerPage\n rowsNumber\n }\n }\n ${fragment}\n`\nexport const MODIFY_USER = gql`\n mutation modifyUser($input: inputUser!) {\n modifyUser(input: $input) {\n ...User\n }\n }\n ${fragment}\n`\nexport const MODIFY_PROFILE = gql`\n mutation modifyProfile($input: inputProfile!) {\n modifyProfile(input: $input) {\n ...User\n }\n }\n ${fragment}\n`\nexport const ENABLED_USER = gql`\n mutation enabledUser($id: ID!,$enabled: Boolean!) {\n enabledUser(_id: $id, enabled: $enabled) {\n ...User\n }\n }\n ${fragment}\n`\nexport const DELETE_USER = gql`\n mutation deleteUser($id: ID!) {\n deleteUser(id: $id) {\n ...User\n }\n }\n ${fragment}\n`\nexport const SIGNIN = gql`\n mutation signIn($username: String!, $password: String!) {\n signIn(username: $username, password: $password) {\n token\n }\n }\n`\nexport const SIGNUP = gql`\n mutation signUp($username: String!,$email: String!, $password: String!) {\n signUp(username: $username, email: $email, password: $password) {\n ...User\n }\n }\n ${fragment}\n`\nexport const GET_COLUMNS = gql`\n query getColumns($model: String!) {\n getColumns(model: $model) {\n name\n sortable\n }\n }\n`\nexport const MENU = gql`\n query getMenu{\n getMenu {\n name\n icon\n link\n }\n }\n`\nexport const DATA = gql`\n query getData{\n getData {\n name\n admin\n director\n manager\n }\n }\n`\nexport const DATA2 = gql`\n query getData2{\n getData {\n name\n admin\n director\n manager\n }\n }\n`\nexport const CHECK_ACCESS = gql`\n query checkAccess($res: String!){\n checkAccess(res: $res)\n }\n`\n" }, { "alpha_fraction": 0.7396963238716125, "alphanum_fraction": 0.7396963238716125, "avg_line_length": 37.41666793823242, "blob_id": "494fbb92e0ac72d1e14cd5d7f05ec1b64b3362dd", "content_id": "78a71ff9773d44eca06c071f8181aef5edc96e47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 461, "license_type": "no_license", "max_line_length": 117, "num_lines": 12, "path": "/src/apollo/apollo-client-hooks.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// eslint-disable-next-line no-unused-vars\nimport { link } from './my-apollo-link'\n\nexport function apolloClientBeforeCreate ({ apolloClientConfigObj }) {\n // { apolloClientConfigObj, app, router, store, ssrContext, urlPath, redirect } */\n apolloClientConfigObj.link = link\n}\n\nexport function apolloClientAfterCreate (/* { apolloClient, app, router, store, ssrContext, urlPath, redirect } */) {\n // if needed you can modify here the created apollo client\n\n}\n" }, { "alpha_fraction": 0.5607028603553772, "alphanum_fraction": 0.5670926570892334, "avg_line_length": 28.761905670166016, "blob_id": "4aef86b8d92b13a96ecd49a52a6db0b317a33d15", "content_id": "6dcb9be126a498ac46b8892f95c4b329e13c7dfc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 627, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/src/server/resolvers/AccessResolver.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "\n// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst { AuthenticationError } = require('apollo-server-express')\nconst { rights } = require('../data/rights')\nmodule.exports = {\n Query: {\n checkAccess: async (_, { res }, { User, currentUser }) => {\n const roles = await User.findOne({ _id: currentUser._id })\n .then(res => res.roles)\n\n let result = false\n if (roles) {\n roles.forEach(role => {\n if (rights[role].includes(res) || rights[role].includes('*')) result = true\n else throw new AuthenticationError()\n })\n }\n return result\n }\n },\n Mutation: {}\n}\n" }, { "alpha_fraction": 0.6329113841056824, "alphanum_fraction": 0.6425912380218506, "avg_line_length": 34.31578826904297, "blob_id": "945cec492ff67e46237e768a015cb119408beb02", "content_id": "37dafb91da8be8faf897dd84b46fc00d8e809da6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1592, "license_type": "no_license", "max_line_length": 89, "num_lines": 38, "path": "/src/server/scripts/calc.py", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "import sys,argparse,time,locale\nversion = \"1.0.0\"\nparser = argparse.ArgumentParser(\n prog = 'calc',\n description = '''Это простая программа, которая выводит сумму a и b, a+b=''',\n epilog = '''© aLexx Sub, 2021. Автор программы, как всегда,\nне несет никакой ответственности ни за что.''',\n add_help = False\n)\n\nbase_group = parser.add_argument_group (title='Обязательные параметры')\nbase_group.add_argument(\"-a\", help=\"первое слагаемое a\")\nbase_group.add_argument(\"-b\", help=\"второе слагаемое b\")\noptional_group = parser.add_argument_group (title='Дополнительные параметры')\noptional_group.add_argument ('--help', '-h', action='help', help='Показывает эту помощь')\noptional_group.add_argument ('--version','-v',\n action='version',\n help = 'Вывод текущей версии',\n version='Текущая версия %(prog)s {}'.format (version))\ntry:\n args = parser.parse_args()\nexcept:\n parser.print_help()\n sys.exit(0)\n\nif len(sys.argv)==1:\n parser.print_help()\n sys.exit(0)\n\nlocale.setlocale(locale.LC_TIME, \"ru_ru\")\nprint(\"Старт : %s\" % time.strftime(\"%a, %d %b %Y %H:%M:%S\"))\ntime.sleep( 1 )\nprint(\"Аргумент a = %s\" % args.a)\ntime.sleep( 1 )\nprint(\"Аргумент b = %s\" % args.b)\ntime.sleep( 1 )\nprint(\"a+b = %s\" % str(args.a+args.b))\nprint(\"Конец : %s\" % time.strftime(\"%a, %d %b %Y %H:%M:%S\"),flush = True)\n\n" }, { "alpha_fraction": 0.6512702107429504, "alphanum_fraction": 0.6605080962181091, "avg_line_length": 29.928571701049805, "blob_id": "e2660a34a8258a83700668af235e4d54f754934b", "content_id": "504400f5c40d69e19e4592d9d2ef9da795b3149f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 434, "license_type": "no_license", "max_line_length": 104, "num_lines": 14, "path": "/src/server/models/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst fs = require('fs'),\n path = require('path')\nvar Models = {}\nconst modelsPath = path.resolve(__dirname, '')\nfs.readdirSync(modelsPath).forEach(file => {\n const Model = require(path.join(modelsPath, file))\n\n if (typeof Model !== 'object' && typeof Model.modelName !== 'undefined' && Model.modelName !== null) {\n Models[Model.modelName] = Model\n }\n})\n\nmodule.exports = Models\n" }, { "alpha_fraction": 0.5149545073509216, "alphanum_fraction": 0.5201560258865356, "avg_line_length": 23.80645179748535, "blob_id": "1347d42ed7018befc83d32c4978f85fc0c868b1a", "content_id": "7182b7e35aa5e894f79b441f11fd152c7d7f3c7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 770, "license_type": "no_license", "max_line_length": 59, "num_lines": 31, "path": "/src/server/resolvers/ColumnResolver.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst { UserInputError } = require('apollo-server-express')\nconst hiddenFields = ['_id', '__v',\n 'password', 'createdDate'\n]\nmodule.exports = {\n Query: {\n getColumns: async (_, { model }, ctx) => {\n if (ctx[model] === undefined) {\n throw new UserInputError('Model name is invalid', {\n invalidArgs: model\n })\n }\n const myschema = ctx[model].schema\n var res = []\n myschema.eachPath((path) => {\n // do not show all fields\n if (!hiddenFields.includes(path)) {\n res.push({\n name: path,\n sortable: true,\n type: myschema.paths[path].instance\n })\n }\n })\n\n return res\n }\n },\n Mutation: {}\n}\n" }, { "alpha_fraction": 0.5851528644561768, "alphanum_fraction": 0.5851528644561768, "avg_line_length": 13.3125, "blob_id": "82e5dbcb2d5fa82aaf575a6ee2f8f7c72c20ae1a", "content_id": "267bd6d9c0794207bee835d1b7dfe6b0bd6d8de9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 229, "license_type": "no_license", "max_line_length": 33, "num_lines": 16, "path": "/src/components/TypeRoles.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "export default [{\n value: 'admin',\n icon: 'mdi-crown',\n color: 'orange'\n\n},\n{\n value: 'manager',\n icon: 'mdi-account-hard-hat',\n color: 'green'\n},\n{\n value: 'director',\n icon: 'mdi-account-cowboy-hat',\n color: 'blue'\n}]\n" }, { "alpha_fraction": 0.5394708514213562, "alphanum_fraction": 0.5416218638420105, "avg_line_length": 28.611465454101562, "blob_id": "c86ec0658a9c84eb821b23716006bcb559a3b861", "content_id": "6a26c330b0a2a5400bfa0638796bc9009e73f626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4650, "license_type": "no_license", "max_line_length": 101, "num_lines": 157, "path": "/src/server/resolvers/UserResolver.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst bcrypt = require('bcrypt'),\n jwt = require('jsonwebtoken'),\n { UserInputError } = require('apollo-server-express'),\n setPagination = require('./pagination.js')\n\nconst createToken = (user, secret, expiresIn) => {\n const { _id, username } = user\n return jwt.sign({ _id, username }, secret, { expiresIn })\n}\n\nmodule.exports = {\n User: {\n\n createdDate: (rec) => {\n const d = new Date(String(rec.createdDate))\n return d.toLocaleString()\n }\n },\n\n Query: {\n getUsers: async (_, args, { User }) => {\n const users = await User.find().sort({ createdDate: 'desc' })\n return users\n },\n getUsers2: async (_, args, { User, pagination, filter }) => {\n const { query, options } = setPagination(pagination, filter, ['username', 'fullname', 'email'])\n\n return await User.paginate(query, options, (err, result) => {\n if (err) console.log(err)\n return result\n })\n },\n getCurrentUser: async (_, args, { User, currentUser }) => {\n if (!currentUser) {\n return null\n }\n const user = await User.findOne({\n username: currentUser.username\n })\n return user\n }\n },\n Mutation: {\n // authentication and generates token\n signIn: async (_, { username, password }, { User }) => {\n const user = await User.findOne({ username })\n if (!user) throw new Error('Incorrect username or password')\n if (!user.enabled) throw new Error('Access denied! Your authorization disabled.')\n if (user.password !== undefined) {\n const isValidPassword = await bcrypt.compare(password, user.password)\n if (!isValidPassword) throw new Error('Incorrect username or password')\n } else { throw new Error('The user doest\\' set password') }\n\n // token's lifetime 1 day\n return { token: createToken(user, process.env.SECRET, '24hr') }\n },\n\n signUp: async (_, { email, username, password, avatar }, { User }) => {\n // check user in database\n const user = await User.findOne({ username })\n // fire error event if user exists\n if (user) {\n throw new UserInputError(`This user '${username}' already exists`, {\n invalidArgs: username\n })\n }\n const count = await User.find().count(),\n defaultRoles = count === 0 ? ['admin'] : ['manager'],\n defaultEnabled = (count === 0)\n // add new user\n const newUser = await new User({\n avatar,\n username,\n fullname: '',\n email,\n password,\n roles: defaultRoles,\n enabled: defaultEnabled\n }).save()\n\n return newUser\n },\n modifyProfile: async (_, { input }, { User }) => {\n const set = {\n avatar: input.avatar,\n username: input.username,\n fullname: input.fullname,\n email: input.email\n }\n const user = await User.findOne({ _id: input._id })\n if (!user) throw new Error('Cant\\' find user!')\n else {\n if (!user.enabled) throw new Error('Access denied! Your authorization disabled.')\n if (input.changepassword) {\n const isValidPassword = await bcrypt.compare(input.oldpassword, user.password)\n if (!isValidPassword) throw new Error('Incorrect old password')\n set.password = input.newpassword\n }\n }\n const res = await User.findOneAndUpdate({ _id: input._id }, { $set: set }, { new: true })\n return res\n },\n modifyUser: async (_, { input }, { User }) => {\n if (input._id === '') {\n const res = await new User({\n avatar: input.avatar,\n username: input.username,\n name: input.name,\n email: input.email,\n roles: input.roles,\n password: '',\n enabled: input.enabled\n }).save()\n\n return res\n } else {\n const res = await User.findOneAndUpdate({\n _id: input._id\n }, {\n $set: {\n avatar: input.avatar,\n username: input.username,\n name: input.name,\n email: input.email,\n roles: input.roles,\n enabled: input.enabled\n }\n }, {\n new: true\n }\n )\n return res\n }\n },\n enabledUser: async (_, { _id, enabled }, { User }) => {\n const res = await User.findOneAndUpdate({\n _id\n }, {\n $set: {\n enabled\n }\n }, {\n new: true\n }\n )\n return res\n },\n deleteUser: async (_, { _id }, { User }) => {\n const res = await User.findByIdAndRemove({\n _id\n }).then()\n return res\n }\n\n }\n}\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5, "avg_line_length": 9.8421049118042, "blob_id": "4e2d8374490f2031d4f24b1968733db9cb267130", "content_id": "a503b4dc86bc7ae8317f9c0e9819746fd66a9917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 213, "license_type": "no_license", "max_line_length": 26, "num_lines": 19, "path": "/src/i18n/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "import enUS from './en-us'\nimport ru from './ru'\n\nexport default {\n 'en-us': enUS,\n ru\n}\nexport const langs = [\n\n {\n id: 'ru',\n name: 'Русский'\n },\n {\n id: 'en-us',\n name: 'English'\n }\n\n]\n" }, { "alpha_fraction": 0.6474500894546509, "alphanum_fraction": 0.6481891870498657, "avg_line_length": 26.059999465942383, "blob_id": "e2da6f7d6a05026966f35c37419e3a2c333d3594", "content_id": "f6f2db07f245b6bf3eec61d4012d307cb2d6c9a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3746, "license_type": "no_license", "max_line_length": 77, "num_lines": 100, "path": "/src/i18n/ru/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "export default {\n copyright: 'Все права защищены',\n title: 'Одностраничное приложение с примером аутентификации и авторизации',\n username: 'Имя пользователя',\n fullname: 'Полное имя',\n name: 'Название',\n email: 'Электронная почта',\n enabled: 'Доступен',\n roles: 'Роли',\n addrecord: 'Добавить пользователя',\n updaterecord: 'Править пользователя',\n save: 'Сохранить',\n admin: 'Администратор',\n director: 'Директор',\n manager: 'Менеджер',\n managerctx: 'Контекст для менеджера',\n directorctx: 'Контекст для директора',\n datatable: 'Таблица с данными',\n userstable: 'Таблица пользователей',\n cantloadimg: 'Ошибка загрузки аватара',\n add: 'Добавить',\n clear: 'Очистить',\n upload: 'Загрузить',\n norole: 'Нет роли',\n custom: 'Свой компонент',\n edit: 'Править',\n delete: 'Удалить',\n warning: 'ВНИМАНИЕ!',\n deleterecord: 'Вы уверены, что хотите УДАЛИТЬ ЗАПИСЬ?',\n yes: 'Да, я уверен',\n no: 'Нет',\n recorddeleted: 'Запись удалена',\n recordupdated: 'Запись обновлена',\n recordadded: 'Запись добавлена',\n havetoauth: 'НЕ УДОСТОВЕРЕНЫ! Вам следует ввести логин и пароль!',\n checkfields: 'Проверьте правильность заполнения полей',\n signuped: 'Вы зарегистрировались! Теперь можете входить',\n disabled: 'Недоступен',\n userenabled: 'Пользователь активирован!',\n userdisabled: 'Пользователь заблокирован!',\n cancel: 'Отмена',\n reset: 'Сбросить',\n oldpassword: 'Старый пароль',\n newpassword: 'Новый пароль',\n changepassword: 'Сменить пароль',\n search: 'Поиск',\n python: 'Python',\n run: 'Выполнить',\n menu: {\n home: {\n title: 'В начало',\n caption: 'Стартовая страница'\n },\n users: {\n title: 'Пользователи',\n caption: 'Список пользователей и ролей'\n },\n users2: {\n title: 'Пользователи2',\n caption: 'Сервер-сайд пагинация'\n },\n manager: {\n title: 'Для меджера',\n caption: 'Контекст для роли меджера'\n },\n director: {\n title: 'Для директора',\n caption: 'Контекст для роли директора'\n },\n data: {\n title: 'Данные',\n caption: 'Таблица с данными по ролям'\n },\n python: {\n title: 'Python',\n caption: 'Запуск питона на серверной стороне'\n }\n },\n messages: {\n uploaded: 'Файл успешно загружен!',\n notuploaded: 'Файл не загружен!'\n },\n auth: {\n forgotpass: 'Забыли пароль?',\n signin: 'ВХОД',\n signup: 'РЕГИСТРАЦИЯ',\n auth: 'Авторизация',\n newuser: 'Новый пользователь',\n username: 'Пользователь',\n email: 'Email',\n password: 'Пароль',\n repassword: 'Повторить пароль'\n },\n validate: {\n required: 'Поле должно быть заполнено',\n short: 'Значение слишком короткое',\n isemail: 'Введите корректный email',\n match: 'Пароли не совпадают'\n }\n}\n" }, { "alpha_fraction": 0.6855345964431763, "alphanum_fraction": 0.698113203048706, "avg_line_length": 38.75, "blob_id": "8b4283bb92bc045c047c4426f07a9c795c8332b3", "content_id": "0e41d1a319cf5fffac27690f110391b8cbe6f78b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 319, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/src/server/resolvers/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst path = require('path'),\n { loadFilesSync } = require('@graphql-tools/load-files'),\n { mergeResolvers } = require('@graphql-tools/merge'),\n resolversArray = loadFilesSync(\n path.join(__dirname, '*Resolver.js'))\n\nmodule.exports = mergeResolvers(resolversArray)\n" }, { "alpha_fraction": 0.6059602499008179, "alphanum_fraction": 0.6059602499008179, "avg_line_length": 12.681818008422852, "blob_id": "02c64cde4f0587558ab572803cae7e75cf8ad3a5", "content_id": "621c9b98d1c97b77bf41cbaf6a5088024a5bffe6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 302, "license_type": "no_license", "max_line_length": 51, "num_lines": 22, "path": "/src/server/models/DataModel.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "\nconst mongoose = require('mongoose')\n\nconst UserSchema = new mongoose.Schema({\n\n admin: {\n type: String\n\n },\n director: {\n type: String\n },\n manager: {\n type: String\n },\n createdDate: {\n type: Date,\n default: Date.now\n }\n\n})\n\nmodule.exports = mongoose.model('Data', UserSchema)\n" }, { "alpha_fraction": 0.5836751461029053, "alphanum_fraction": 0.5920153260231018, "avg_line_length": 25.988929748535156, "blob_id": "02db89b532a5511f3e5a62562e823598790153cc", "content_id": "70dccee817181b78b00caa53fb10d56f7cff9ce9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 7324, "license_type": "no_license", "max_line_length": 116, "num_lines": 271, "path": "/src/server/index.js", "repo_name": "alexxsub/server-run-python", "src_encoding": "UTF-8", "text": "// © 2021 Alexx Sub, https://github.com/alexxsub/\nconst app = require('express')(),\n express = require('express'),\n fileUpload = require('express-fileupload'),\n cors = require('cors'),\n morgan = require('morgan'),\n path = require('path'),\n { ApolloServer, AuthenticationError } = require('apollo-server-express'),\n mongoose = require('mongoose'),\n jwt = require('jsonwebtoken'),\n typeDefs = require('./types'),\n resolvers = require('./resolvers'),\n context = require('./models'),\n http = require('http'),\n WebSocket = require('ws')\n\nrequire('dotenv').config({ path: '../../.env' })\nconst port = process.env.PORT || 8080\nmongoose\n .connect(\n process.env.MONGO_URI,\n {\n useCreateIndex: true,\n useNewUrlParser: true,\n retryWrites: true,\n useFindAndModify: false,\n useUnifiedTopology: true\n }\n )\n .then(() => console.log(`🎉 Mongo connected ${process.env.MONGO_URI}`))\n .catch((err) => console.error(err))\n\n// Verify JWT Token passed from client\nconst getUser = async (token, signin) => {\n if (signin) return ''\n if (token) {\n try {\n return await jwt.verify(token, process.env.SECRET)\n } catch (err) {\n throw new AuthenticationError(\n 'Authentication error: Please login again!'\n )\n }\n } else {\n throw new AuthenticationError(\n 'Authentication error: You are not logged in!'\n )\n }\n}\n// enable files upload\napp.use(fileUpload({\n createParentPath: true\n}))\n// Create Apollo/GraphQL Server using typeDefs, resolvers\n\nconst apollo = new ApolloServer({\n typeDefs,\n resolvers,\n tracing: true,\n formatError: (error) => {\n const rep = new Map([\n ['GraphQL error:', ''],\n ['Context creation failed:', ''],\n ['ENOENT:', '']\n ])\n\n rep.forEach((val, key) => {\n const msg = error.message\n error.message = msg.replace(key, val).trim()\n })\n\n if (process.env.DEBUG !== 'true') {\n if (Object.prototype.hasOwnProperty.call(error.extensions, 'exception')) { delete error.extensions.exception }\n }\n return error\n },\n context: async ({ req }) => {\n // list of queries without autentifacation\n const noAuth = ['IntrospectionQuery',\n 'signIn',\n 'signUp'],\n token = req.headers.token,\n query = req.body.operationName,\n signed = noAuth.includes(query)\n context.currentUser = await getUser(token, signed)\n context.pagination = req.body.variables.pagination\n context.filter = req.body.variables.filter\n context.userIP = req.ip.split(':').pop()\n return context\n }\n})\n// replace code 400 over 401 (correct)\nconst contextAuthError = (req, res, next) => {\n const origSend = res.send\n\n res.send = (content) => {\n if (res.statusCode === 400) {\n const errInfo = JSON.parse(content)\n if (errInfo.errors[0].extensions.code === 'UNAUTHENTICATED') {\n res.statusCode = 401\n }\n }\n return origSend.call(res, content)\n }\n next()\n}\n\nconst server = http.createServer(app)\n\n// add other middleware\napp.use(express.static('uploads'))\napp.use(cors())\napp.use('/api', contextAuthError)// add 401 error code\napp.get('/', function (req, res) {\n res.sendFile(path.join(__dirname, 'index.html'))\n})\n// app.use(morgan('dev'))\n// custom logger\napp.use(morgan(function (tokens, req, res) {\n return [\n tokens.date(req, res, 'clf'),\n tokens['remote-addr'](req, res),\n tokens.method(req, res),\n // req.body.operationName,\n tokens.url(req, res),\n tokens.status(req, res),\n tokens.res(req, res, 'content-length'), '-',\n tokens['response-time'](req, res), 'ms'\n ].join(' ')\n}))\n\napp.post('/upload', async (req, res) => {\n try {\n if (!req.files) {\n res.send({\n status: false,\n message: 'No file uploaded'\n })\n } else {\n const uploadfile = req.files\n\n Object.keys(uploadfile).forEach(key => {\n const dst = path.join(__dirname, 'uploads/', uploadfile[key].name)\n uploadfile[key].mv(dst, err => console.log(err))\n })\n\n // send response\n res.send({\n status: true,\n message: 'Files is uploaded'\n })\n }\n } catch (err) {\n res.status(500).send(err)\n }\n})\n\napp.post('/upload2', async (req, res, next) => {\n if (!req.files) {\n res.status(500).send('No file uploaded')\n } else {\n const uploadfile = req.files,\n fileID = `${(+new Date()).toString(16)}`,\n ext = uploadfile.file.name.split('.').pop(),\n filename = fileID + '.' + ext,\n dst = path.join(__dirname, 'uploads/', filename)\n\n uploadfile.file.mv(dst, err => console.log(err))\n\n // send response\n res.send({\n status: true,\n file: filename\n })\n }\n})\nconst SCRIPT_PATH = path.join(__dirname, 'scripts/calc.py')\n\napp.get('/sse', function (req, res) {\n res.writeHead(200, {\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Origin': 'http://localhost:8080',\n 'Content-Type': 'text/event-stream; charset=utf-8',\n 'Cache-Control': 'no-cache'\n })\n\n var options = ['-u', SCRIPT_PATH]\n options.push('-a', req.query.a, '-b', req.query.b)\n const child = spawn('python', options)\n\n child.stdout.on('data', function (data) {\n if (platform === 'win32') { data = iconv.decode(data, 'cp1251') }\n res.write(`data:${data} \\n\\n`)\n })\n\n child.stderr.on('data', function (data) {\n res.write(`event: error\\ndata: Error ${data} \\n\\n`)\n })\n child.on('close', function () {\n console.log('done ')\n res.write('event: done\\ndata: \\n\\n')\n res.end()\n })\n child.on('exit', function (code, signal) {\n if (code !== 0) {\n res.write(`data: Exit code ${code}\\n\\n`)\n res.write(`data: Exit signal ${signal}\\n\\n`)\n }\n })\n})\n\napp.get('/run', function (req, res) {\n const scriptProcess = spawn('python', [\n SCRIPT_PATH,\n '-a', req.query.a, '-b', req.query.b\n ])\n\n res.set('Content-Type', (platform === 'win32' ? 'text/plain; charset=cp1251' : 'text/plain'))\n scriptProcess.stdout.pipe(res)\n scriptProcess.stderr.pipe(res)\n})\n// start app ------------------------------------------------\napollo.applyMiddleware({ app, path: '/api' })\nserver.listen(port, () =>\n console.log(`🚀 Started at http://localhost:${port}${apollo.graphqlPath}`)\n)\n\n// websocket -------------------------------------------------\nconst wss = new WebSocket.Server({ server })\n\nconst iconv = require('iconv-lite'),\n { platform } = require('process'),\n { spawn } = require('child_process')\n\nfunction runScriptInWebsocket (ws, a, b) {\n var options = ['-u', SCRIPT_PATH]\n options.push('-a', a, '-b', b)\n\n const child = spawn('python', options)\n\n child.stdout.on('data', function (data) {\n if (platform === 'win32') { data = iconv.decode(data, 'cp1251') }\n ws.send(`${data}`)\n })\n child.stderr.on('data', function (data) {\n ws.send(`${data}`)\n })\n child.on('close', function () {\n ws.send('done')\n })\n child.on('exit', function (code, signal) {\n if (code !== 0) {\n ws.send(`\\nExit code: ${code}`)\n ws.send(`\\nExit signal: ${signal}\\n`)\n }\n })\n}\n\nwss.on('connection', (ws) => {\n console.log('😁 WebSocket server connected ')\n\n ws.on('message', (msg) => {\n ws.send(`You sent -> ${msg}\\n`)\n msg = JSON.parse(msg)\n\n if (msg.cmd === 'run') {\n runScriptInWebsocket(ws, msg.a, msg.b)\n }\n })\n ws.send('Connection with WebSocket server initialized\\n')\n})\n" } ]
15
guoqi233/JMadOnion
https://github.com/guoqi233/JMadOnion
df6c0114ea79f65293a5a25300b39fb03dff13e0
482427ffb6bfbe4a380fcea4fc9949a87f43ae56
f22bf57598b9474a555be4b2d99c39db53428d34
refs/heads/master
2020-04-15T03:56:02.404086
2019-01-04T05:14:57
2019-01-04T05:14:57
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7440000176429749, "alphanum_fraction": 0.7519999742507935, "avg_line_length": 30.25, "blob_id": "b10a3ff2232d8d364c78216b530a64898593d947", "content_id": "3f8e99e02a1eb4a16de820e23e8d623c98e78771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 125, "license_type": "no_license", "max_line_length": 40, "num_lines": 4, "path": "/scripts/maya/JpyModules/public/__init__.py", "repo_name": "guoqi233/JMadOnion", "src_encoding": "UTF-8", "text": "# -*- coding:utf-8 -*-\nfrom J_deleteNode import *\nfrom J_deleteUnknownNode import *\nfrom J_renameDefaultRenderLayer import *\n" } ]
1
Edreih/Python-Learning
https://github.com/Edreih/Python-Learning
ec1b1c8465825007bcf3f4c929021edb54b62fde
a739c03469d0e468ae805ab0551ad441807909bb
1ae27f6a93fefa32a6f9c0c7ed881ce482e9af86
refs/heads/master
2021-06-28T10:08:47.576618
2017-09-15T06:07:54
2017-09-15T06:08:19
103,620,477
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5647059082984924, "alphanum_fraction": 0.5815126299858093, "avg_line_length": 37.733333587646484, "blob_id": "02e09d2941b1defeb3235f066ac9db65f0f4629b", "content_id": "892edd50cae46201d31ee7c9cfc098f78edee143", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1190, "license_type": "permissive", "max_line_length": 113, "num_lines": 30, "path": "/simpleMath/main.py", "repo_name": "Edreih/Python-Learning", "src_encoding": "UTF-8", "text": "# ---------------------------------------------\r\n# | Description: This program shows how to use|\r\n# | for loops, range, and getting the product |\r\n# | and sum of a list through an if statement |\r\n# | |\r\n# | Created by: Edreih Aldana |\r\n# ---------------------------------------------\r\n\r\naList = [] # The first list that will hold the numbers less than 25 which are to be multiplied together\r\nbList = [] # The second list that will hold the numbers greater than or equal to 25 which will be added together\r\nproduct = 1\r\n\r\nprint(\"\"\"This program will ask you to input 5 numbers. Out of those numbers\r\n the ones that are less than 25 will be multiplied together. The numbers\r\n that are greater than or equal to 25 will be added together.\"\"\")\r\n\r\nfor x in range(0, 5):\r\n number = int(input(\"Enter a number:\\n\"))\r\n if number < 25:\r\n aList.append(number)\r\n if number >= 25:\r\n bList.append(number)\r\n\r\nprint(\"The product of the numbers less than 25 are:\")\r\nfor n in aList:\r\n product *= n\r\nprint(product)\r\n\r\nprint(\"The sum of the numbers greater than or equal to 25 that were entered are:\")\r\nprint(sum(bList))" }, { "alpha_fraction": 0.7923076748847961, "alphanum_fraction": 0.7923076748847961, "avg_line_length": 63, "blob_id": "ef76df53951b545cf7ac9ee4716c94c5ab03edc2", "content_id": "9d3a1f2e4ea15d2ec32babebbf09a9a31380282f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 130, "license_type": "permissive", "max_line_length": 114, "num_lines": 2, "path": "/simpleMath/README.md", "repo_name": "Edreih/Python-Learning", "src_encoding": "UTF-8", "text": "# simpleMath\r\nPython program that multiplies and adds user-input integers in a list based on criteria (my first python program).\r\n" } ]
2
guskovgithub/lab6
https://github.com/guskovgithub/lab6
77be1b0c6c221e9b5346e7eb4a1882c9980f1f4c
f0e4d94b37de36543b10aea2aa536a5799058ffb
3a14f3dee9418c7102b6d0d39b39d30151dcd00d
refs/heads/master
2020-12-30T22:55:33.429757
2015-12-08T20:03:59
2015-12-08T20:03:59
43,738,253
0
0
null
2015-10-06T08:21:51
2015-10-05T16:38:47
2015-10-05T17:13:34
null
[ { "alpha_fraction": 0.6313284039497375, "alphanum_fraction": 0.6516659259796143, "avg_line_length": 41.796295166015625, "blob_id": "5fcf001727d8d7bb0b71aaf225d66b427cc797a3", "content_id": "4f2da11529a4bb3050bece244e70d15be9eec455", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3582, "license_type": "no_license", "max_line_length": 120, "num_lines": 54, "path": "/E.py", "repo_name": "guskovgithub/lab6", "src_encoding": "UTF-8", "text": "'''\nЗадача E\n++++++++\n\nВ одном карточном клубе состоит N джентльменов. Иногда азарт некоторых из них берет верх над благоразумием, и кто-то\nпроигрывает больше денег, чем у него есть с собой. В этом случае проигравший обычно берет в долг у кого-то из\nпосетителей клуба, чтобы расплатиться с партнерами по игре. Чтобы начать новый год “с чистого листа”, джентльмены решили\nсобраться в клубе и оплатить все долговые расписки, которые накопились у них друг к другу. Однако выяснилось, что иногда\nодни и те же джентльмены в разные дни выступали как в роли должников, так и в роли кредиторов. Поскольку истинные\nджентльмены считают мелочный подсчет денег ниже своего достоинства, то расчетами придется заняться вам.\n\nНапишите программу, которая по заданным распискам вычислит, сколько всего должен каждый джентльмен выплатить другим (или\nполучить с других).\n\nПервая строка входных данных содержит сначала число N — количество джентльменов (натуральное, не превышает 100, не менее\n2), и число K — количество долговых расписок (натуральное, не превышает 10000), после этого следует K троек чисел: номер\nджентльмена взявшего в долг, номер джентльмена давшего деньги и сумма. Номера джентльменов в расписках — натуральные\nчисла, не превышающие N. Сумма — натуральное число, не превышает 100. Гарантируется, что ни один джентльмен не брал в\nдолг сам у себя.\n\nВыведите N чисел — суммы, которые должны получить соответствующие джентльмены. Выведите положительное число, если этот\nджентльмен должен получить деньги от других, отрицательное — если он должен отдать деньги другим.\n\n+---------+------------+\n| Ввод | Вывод |\n+=========+============+\n| 2 3 | -50 50 |\n+---------+------------+\n| 1 2 10 | |\n+---------+------------+\n| 1 2 20 | |\n+---------+------------+\n| 1 2 20 | |\n+---------+------------+\n+---------+------------+\n| 3 1 | 100 0 -100 |\n+---------+------------+\n| 3 1 100 | |\n+---------+------------+\n'''\n\nf = open('input.txt')\nblocnot = open('output.txt','w')\nN, K = tuple([int(i) for i in f.readline().split()])\nbalance = [0 for i in range(N)]\n\nfor i in range(K):\n d,c,m = tuple([int(j) for j in f.readline().split()])\n balance[d-1] -= m\n balance[c-1] += m\nblocnot.write(' '.join([str(i) for i in balance]))\n\nblocnot.close()\nf.close()\n" }, { "alpha_fraction": 0.5719237327575684, "alphanum_fraction": 0.5935875177383423, "avg_line_length": 32.94117736816406, "blob_id": "a537967dd4ba53673ef3d1d2983f1e9bc39d03d4", "content_id": "25371da3c931c226594d24f02663a5ce9a2852af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1650, "license_type": "no_license", "max_line_length": 120, "num_lines": 34, "path": "/D.py", "repo_name": "guskovgithub/lab6", "src_encoding": "UTF-8", "text": "'''\nЗадача D\n++++++++\n\nМетеорологи ведут многолетние наблюдения за тем, в каком году была минимальная температура в данный день года. Например,\nабсолютный минимум температуры в Москве 8 марта был -32 градуса (1890).\n\nВ течение k лет метеорологи вели наблюдения за n днями года. Для каждого из этих n дней укажите минимальную температуру,\nкоторая была в этот день за k лет наблюдений.\n\nПервая строка входных данных содержит два числа k и n. Далее идет k строк, i-я строка содержит n чисел: значения\nтемператур для n дней наблюдений i-го года.\n\nПрограмма должна вывести n чисел: миниальное значение температуры для каждого из дней наблюдений.\n\n+---------+-----------+\n| Ввод | Вывод |\n+=========+===========+\n| 3 | 4 3 2 4 3 |\n+---------+-----------+\n| 8 6 4 7 | |\n+---------+-----------+\n| 3 2 5 4 | |\n+---------+-----------+\n| 6 4 6 3 | |\n+---------+-----------+\n'''\n\nf=open('input.txt')\nblocnot=open('output.txt','w')\nk, n = tuple([int(i) for i in f.readline().split()])\nblocnot.write(' '.join([str(min(l)) for l in zip(*[[int(j) for j in f.readline().split()] for i in range(k)])]))\nblocnot.close()\nf.close()\n" }, { "alpha_fraction": 0.7394958138465881, "alphanum_fraction": 0.756302535533905, "avg_line_length": 117, "blob_id": "e02fa2d7e362edf6de547829308cc37870765e84", "content_id": "9099ba37ad4798e0f19a345e7b8daa9fb8d93c90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 119, "license_type": "no_license", "max_line_length": 117, "num_lines": 1, "path": "/README.md", "repo_name": "guskovgithub/lab6", "src_encoding": "UTF-8", "text": "[![Build Status](https://travis-ci.org/guskovgithub/lab6.svg?branch=master)](https://travis-ci.org/guskovgithub/lab6)\n\n" } ]
3
zero323-attic/ipi-wsdmp-ex7
https://github.com/zero323-attic/ipi-wsdmp-ex7
a7e7d3140a132d839910a4293a728f0eba21291f
291a750f5f51096fe9742f20f1123f76726edac4
40357a607a05e51d3394e6f31200b33aacea3f2c
refs/heads/master
2016-03-11T03:45:18.831838
2015-01-22T02:18:30
2015-01-22T02:18:30
29,107,412
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.39933350682258606, "alphanum_fraction": 0.5309635996818542, "avg_line_length": 24.38624382019043, "blob_id": "246b9d982f34338caa5f3104e3350cbe83c7a88a", "content_id": "5ddc6a1e3d576dd57ce300ab5968510a88a1e66a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 14420, "license_type": "no_license", "max_line_length": 91, "num_lines": 567, "path": "/hw7.md", "repo_name": "zero323-attic/ipi-wsdmp-ex7", "src_encoding": "UTF-8", "text": "\n## Author: Maciej Szymkiewicz\n\nFollowing datasets have been used:\n\n- biology.stackexchange.com\n- datascience.stackexchange.com\n- homebrew.stackexchange.com\n- opendata.stackexchange.com\n- robotics.stackexchange.com\n\nThese datasets are small and relatively sparse and some results can be\nmisleading. It is particularly obvious when we look at recommender output.\n\nDatasets have been downloaded from https://archive.org/details/stackexchange and\nextracted using 7-Zip 9.20.\n\n\n\n\n from __future__ import division, print_function\n import lxml\n import igraph\n import pandas as pd\n import re\n import os\n import itertools\n from scipy.spatial.distance import pdist, cdist, squareform\n from scipy.cluster.hierarchy import linkage, dendrogram\n import rpy2.robjects as robjects\n import pandas.rpy.common as com\n from IPython.display import Image\n \n pylab.rcParams['figure.figsize'] = (17.0, 8.0)\n\n\n def f_asymetric(x, y):\n return sum(x & y) / sum(x)\n \n \n def get_edges(questions, threshold, min_tagged=5):\n questions = questions.loc[:, questions.sum(0) > 5]\n tags = list(questions.columns.values)\n pairs = ((t1, t2) for t1, t2 in itertools.product(tags, tags) if t1 != t2)\n dists = ((t1, t2, f_asymetric(questions[t1], questions[t2])) for t1, t2 in pairs)\n return [x for x in dists if x[2] >= threshold]\n \n \n def create_graph(edges):\n g = igraph.Graph(directed = True)\n edges = [(x, y) for x, y, d in edges]\n vertices = list({_ for _ in itertools.chain(*edges)})\n g.add_vertices(vertices)\n g.vs['label'] = vertices\n g.add_edges(edges)\n return g\n \n \n def parse_answers(input_file):\n def to_dict(path):\n return {'_uid_': x.xpath('@OwnerUserId')[0], x.xpath('@ParentId')[0]: 1}\n \n root = lxml.etree.parse(input_file)\n answers = root.xpath(\"/posts/row[@PostTypeId=2 and @OwnerUserId and @ParentId]\")\n parsed = [to_dict(x) for x in answers]\n unique_parents = list({x.xpath('@ParentId')[0] for x in answers})\n \n return pd.DataFrame(parsed, columns=['_uid_'] + unique_parents).fillna(0)\n \n \n def parse_questions(input_file, all_tags):\n def to_dict(path, all_tags):\n qid = int(x.xpath('@Id')[0])\n score = int(x.xpath('@Score')[0])\n tags = {_ for _ in re.split('<|>', x.xpath(\"@Tags\")[0]) if _}\n return dict(zip(\n ['_qid_', '_score_'] + all_tags,\n [qid, score] + [tag in tags for tag in all_tags]\n ))\n \n root = lxml.etree.parse(input_file)\n questions = [to_dict(x, all_tags) for x in root.xpath(\"/posts/row[@PostTypeId=1]\")]\n return pd.DataFrame(questions, columns = ['_qid_', '_score_'] + all_tags)\n \n \n def parse_tags(input_file):\n root = lxml.etree.parse(input_file)\n return root.xpath('/tags/row/@TagName')\n \n \n def recommend(df, min_obs=5, min_given=1):\n df.to_csv('temp.csv', index=False)\n # Code based on:\n # Bolikowski, Dendek, Kursa, Web-scale data mining and processing\n # Big data in R with StackExchange case study\n recommend = robjects.r('''\n library(recommenderlab)\n recommend <- function(f, min_obs=1, given=1) {\n m <- as.matrix(read.csv(f))\n brm <- as(m[, colSums(m) >= min_obs], 'binaryRatingMatrix')\n image_file <- paste(tempfile(), 'png', sep='.')\n \n algos<-list(\n baseline=list(name='RANDOM', param=NULL),\n JaccardCF_5=list(name='UBCF', param=list(method='Jaccard', nn=5)),\n JaccardCF_10=list(name='UBCF', param=list(method='Jaccard', nn=10)),\n JaccardCF_30=list(name='UBCF', param=list(method='Jaccard', nn=30)),\n JaccardCF_50=list(name='UBCF', param=list(method='Jaccard', nn=50))\n )\n es <- evaluationScheme(brm, 'cross-validation', k=10, given=given)\n results <- evaluate(es, algos, n=c(1, 3, 5, 10, 30))\n \n tryCatch({\n png(image_file, width = 960, height = 960)\n plot(results)\n dev.off()\n image_file\n }, error = function(e) \"\")\n }''')\n return recommend('temp.csv', min_obs, min_given)\n \n \n def process(directory, threshold=0.75, min_tagged=5):\n tags = parse_tags(os.path.join(directory, 'Tags.xml'))\n questions = parse_questions(os.path.join(directory, 'Posts.xml'), tags)\n answers = parse_answers(os.path.join(directory, 'Posts.xml'))\n dm = pdist(questions.iloc[:, 3:].as_matrix().transpose(), 'jaccard')\n edges = get_edges(questions.iloc[:, 3:], threshold, min_tagged)\n return tags, questions, dm, edges, answers\n\n### biology\n\n\n tags, questions, dm, edges, answers = process('data/biology/')\n dendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n![png](hw7_files/hw7_4_0.png)\n\n\n\n g = create_graph(edges)\n igraph.plot(g, layout = g.layout(\"kk\"))\n\n\n\n\n![svg](hw7_files/hw7_5_0.svg)\n\n\n\n\n f = recommend(answers, min_obs=4)[0]\n Image(f)\n\n Loading required package: Matrix\n Loading required package: registry\n Loading required package: arules\n \n Attaching package: ‘arules’\n \n The following objects are masked from ‘package:base’:\n \n %in%, write\n \n Loading required package: proxy\n \n Attaching package: ‘proxy’\n \n The following objects are masked from ‘package:stats’:\n \n as.dist, dist\n \n RANDOM run \n \t 1 [0.008sec/0.564sec] \n \t 2 [0.004sec/0.536sec] \n \t 3 [0sec/0.54sec] \n \t 4 [0sec/0.524sec] \n \t 5 [0.004sec/0.516sec] \n \t 6 [0sec/0.516sec] \n \t 7 [0.004sec/0.516sec] \n \t 8 [0sec/0.516sec] \n \t 9 [0.004sec/0.52sec] \n \t 10 [0.004sec/0.52sec] \n UBCF run \n \t 1 [0.004sec/7.54sec] \n \t 2 [0sec/7.66sec] \n \t 3 [0sec/7.38sec] \n \t 4 [0sec/7.34sec] \n \t 5 [0.004sec/7.284sec] \n \t 6 [0sec/7.288sec] \n \t 7 [0.004sec/7.164sec] \n \t 8 [0sec/7.308sec] \n \t 9 [0sec/7.288sec] \n \t 10 [0sec/7.184sec] \n UBCF run \n \t 1 [0.004sec/7.34sec] \n \t 2 [0.004sec/7.516sec] \n \t 3 [0.004sec/7.712sec] \n \t 4 [0sec/7.644sec] \n \t 5 [0sec/7.392sec] \n \t 6 [0sec/7.412sec] \n \t 7 [0sec/7.968sec] \n \t 8 [0sec/7.456sec] \n \t 9 [0.004sec/7.32sec] \n \t 10 [0sec/7.5sec] \n UBCF run \n \t 1 [0sec/7.66sec] \n \t 2 [0.004sec/7.28sec] \n \t 3 [0sec/7.512sec] \n \t 4 [0sec/7.464sec] \n \t 5 [0sec/7.512sec] \n \t 6 [0sec/7.36sec] \n \t 7 [0.004sec/7.456sec] \n \t 8 [0sec/7.572sec] \n \t 9 [0sec/7.86sec] \n \t 10 [0.004sec/7.976sec] \n UBCF run \n \t 1 [0.004sec/8.104sec] \n \t 2 [0sec/7.452sec] \n \t 3 [0.004sec/7.416sec] \n \t 4 [0.004sec/7.62sec] \n \t 5 [0.004sec/7.584sec] \n \t 6 [0sec/7.528sec] \n \t 7 [0.004sec/7.544sec] \n \t 8 [0sec/7.264sec] \n \t 9 [0sec/7.536sec] \n \t 10 [0sec/7.656sec] \n\n\n\n\n\n![png](hw7_files/hw7_6_1.png)\n\n\n\n### datascience\n\n\n tags, questions, dm, edges, answers = process('data/datascience/', min_tagged = 3)\n dendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n![png](hw7_files/hw7_8_0.png)\n\n\n\n g = create_graph(edges)\n igraph.plot(g, layout = g.layout(\"kk\"))\n\n\n\n\n![svg](hw7_files/hw7_9_0.svg)\n\n\n\n\n f = recommend(answers, min_obs=5)[0]\n Image(f)\n\n RANDOM run \n \t 1 [0.004sec/0.028sec] \n \t 2 [0sec/0.024sec] \n \t 3 [0.004sec/0.028sec] \n \t 4 [0sec/0.028sec] \n \t 5 [0sec/0.032sec] \n \t 6 [0.004sec/0.028sec] \n \t 7 [0sec/0.028sec] \n \t 8 [0.004sec/0.028sec] \n \t 9 [0.004sec/0.032sec] \n \t 10 [0.004sec/0.024sec] \n UBCF run \n \t 1 [0.004sec/0.508sec] \n \t 2 [0.004sec/0.464sec] \n \t 3 [0sec/0.504sec] \n \t 4 [0sec/0.488sec] \n \t 5 [0sec/0.492sec] \n \t 6 [0.004sec/0.496sec] \n \t 7 [0sec/0.488sec] \n \t 8 [0sec/0.504sec] \n \t 9 [0sec/0.52sec] \n \t 10 [0sec/0.488sec] \n UBCF run \n \t 1 [0sec/0.492sec] \n \t 2 [0sec/0.504sec] \n \t 3 [0sec/0.504sec] \n \t 4 [0.004sec/0.5sec] \n \t 5 [0sec/0.484sec] \n \t 6 [0sec/0.48sec] \n \t 7 [0.004sec/0.5sec] \n \t 8 [0sec/0.516sec] \n \t 9 [0sec/0.512sec] \n \t 10 [0sec/0.468sec] \n UBCF run \n \t 1 [0.004sec/0.464sec] \n \t 2 [0sec/0.488sec] \n \t 3 [0.004sec/0.504sec] \n \t 4 [0sec/0.476sec] \n \t 5 [0sec/0.484sec] \n \t 6 [0sec/0.5sec] \n \t 7 [0.004sec/0.504sec] \n \t 8 [0.004sec/0.484sec] \n \t 9 [0sec/0.504sec] \n \t 10 [0sec/0.5sec] \n UBCF run \n \t 1 [0sec/0.576sec] \n \t 2 [0sec/0.496sec] \n \t 3 [0.004sec/0.504sec] \n \t 4 [0sec/0.484sec] \n \t 5 [0sec/0.492sec] \n \t 6 [0sec/0.492sec] \n \t 7 [0sec/0.468sec] \n \t 8 [0.004sec/0.468sec] \n \t 9 [0.004sec/0.468sec] \n \t 10 [0sec/0.468sec] \n\n\n\n\n\n![png](hw7_files/hw7_10_1.png)\n\n\n\n### homebrew\n\n\n tags, questions, dm, edges, answers = process('data/homebrew/')\n dendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n![png](hw7_files/hw7_12_0.png)\n\n\n\n f = recommend(answers, min_obs=5)[0]\n Image(f)\n\n RANDOM run \n \t 1 [0.004sec/0.752sec] \n \t 2 [0sec/0.956sec] \n \t 3 [0sec/0.804sec] \n \t 4 [0.004sec/0.776sec] \n \t 5 [0sec/0.768sec] \n \t 6 [0sec/0.752sec] \n \t 7 [0sec/0.74sec] \n \t 8 [0sec/0.76sec] \n \t 9 [0sec/0.744sec] \n \t 10 [0sec/0.884sec] \n UBCF run \n \t 1 [0sec/8.9sec] \n \t 2 [0.004sec/8.388sec] \n \t 3 [0.004sec/8.252sec] \n \t 4 [0sec/7.992sec] \n \t 5 [0sec/7.944sec] \n \t 6 [0sec/7.876sec] \n \t 7 [0sec/7.944sec] \n \t 8 [0.004sec/7.976sec] \n \t 9 [0sec/8.312sec] \n \t 10 [0sec/7.972sec] \n UBCF run \n \t 1 [0sec/8.136sec] \n \t 2 [0sec/8.236sec] \n \t 3 [0sec/8.312sec] \n \t 4 [0.004sec/8.048sec] \n \t 5 [0.004sec/8.34sec] \n \t 6 [0.004sec/8.096sec] \n \t 7 [0.004sec/8.144sec] \n \t 8 [0sec/8sec] \n \t 9 [0.004sec/8.084sec] \n \t 10 [0.004sec/7.908sec] \n UBCF run \n \t 1 [0sec/8sec] \n \t 2 [0sec/7.976sec] \n \t 3 [0sec/7.984sec] \n \t 4 [0sec/8.036sec] \n \t 5 [0.004sec/7.984sec] \n \t 6 [0.004sec/7.988sec] \n \t 7 [0sec/7.964sec] \n \t 8 [0sec/8.024sec] \n \t 9 [0.004sec/8.024sec] \n \t 10 [0sec/7.988sec] \n UBCF run \n \t 1 [0.004sec/7.988sec] \n \t 2 [0.004sec/8.004sec] \n \t 3 [0sec/7.98sec] \n \t 4 [0sec/7.952sec] \n \t 5 [0sec/8.06sec] \n \t 6 [0sec/7.992sec] \n \t 7 [0sec/7.98sec] \n \t 8 [0sec/7.888sec] \n \t 9 [0sec/8.052sec] \n \t 10 [0sec/8.168sec] \n\n\n\n\n\n![png](hw7_files/hw7_13_1.png)\n\n\n\n### opendata\n\n\n tags, questions, dm, edges, answers = process('data/opendata/')\n dendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n![png](hw7_files/hw7_15_0.png)\n\n\n\n g = create_graph(edges)\n igraph.plot(g, layout = g.layout(\"kk\"))\n\n\n\n\n![svg](hw7_files/hw7_16_0.svg)\n\n\n\n\n f = recommend(answers, min_obs=5)[0]\n Image(f)\n\n RANDOM run \n \t 1 [0sec/0.084sec] \n \t 2 [0sec/0.08sec] \n \t 3 [0.004sec/0.08sec] \n \t 4 [0.004sec/0.08sec] \n \t 5 [0.004sec/0.08sec] \n \t 6 [0.004sec/0.08sec] \n \t 7 [0.004sec/0.08sec] \n \t 8 [0sec/0.08sec] \n \t 9 [0.004sec/0.08sec] \n \t 10 [0.004sec/0.084sec] \n UBCF run \n \t 1 [0.004sec/1.216sec] \n \t 2 [0sec/1.204sec] \n \t 3 [0sec/1.232sec] \n \t 4 [0sec/1.236sec] \n \t 5 [0sec/1.212sec] \n \t 6 [0sec/1.2sec] \n \t 7 [0sec/1.236sec] \n \t 8 [0sec/1.196sec] \n \t 9 [0.004sec/1.34sec] \n \t 10 [0.004sec/1.196sec] \n UBCF run \n \t 1 [0sec/1.22sec] \n \t 2 [0sec/1.276sec] \n \t 3 [0.004sec/1.268sec] \n \t 4 [0.004sec/1.204sec] \n \t 5 [0sec/1.192sec] \n \t 6 [0.004sec/1.212sec] \n \t 7 [0sec/1.224sec] \n \t 8 [0sec/1.228sec] \n \t 9 [0sec/1.216sec] \n \t 10 [0.004sec/1.32sec] \n UBCF run \n \t 1 [0sec/1.212sec] \n \t 2 [0sec/1.216sec] \n \t 3 [0sec/1.292sec] \n \t 4 [0sec/1.248sec] \n \t 5 [0.004sec/1.232sec] \n \t 6 [0sec/1.364sec] \n \t 7 [0sec/1.248sec] \n \t 8 [0.004sec/1.188sec] \n \t 9 [0.004sec/1.196sec] \n \t 10 [0sec/1.196sec] \n UBCF run \n \t 1 [0sec/1.304sec] \n \t 2 [0sec/1.196sec] \n \t 3 [0sec/1.22sec] \n \t 4 [0sec/1.232sec] \n \t 5 [0.004sec/1.24sec] \n \t 6 [0sec/1.204sec] \n \t 7 [0sec/1.212sec] \n \t 8 [0.004sec/1.232sec] \n \t 9 [0sec/1.244sec] \n \t 10 [0sec/1.196sec] \n\n\n\n\n\n![png](hw7_files/hw7_17_1.png)\n\n\n\n### robotics\n\n\n tags, questions, dm, edges, answers = process('data/robotics/', min_tagged = 1)\n dendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n![png](hw7_files/hw7_19_0.png)\n\n\n\n f = recommend(answers, min_obs=3)[0]\n Image(f)\n\n RANDOM run \n \t 1 [0.004sec/0.172sec] \n \t 2 [0sec/0.172sec] \n \t 3 [0.004sec/0.164sec] \n \t 4 [0.004sec/0.172sec] \n \t 5 [0.004sec/0.176sec] \n \t 6 [0sec/0.172sec] \n \t 7 [0.004sec/0.172sec] \n \t 8 [0.004sec/0.172sec] \n \t 9 [0sec/0.168sec] \n \t 10 [0.004sec/0.164sec] \n UBCF run \n \t 1 [0.004sec/1.6sec] \n \t 2 [0sec/1.612sec] \n \t 3 [0.004sec/1.64sec] \n \t 4 [0sec/1.572sec] \n \t 5 [0sec/1.64sec] \n \t 6 [0sec/1.64sec] \n \t 7 [0sec/1.532sec] \n \t 8 [0sec/1.632sec] \n \t 9 [0.004sec/1.548sec] \n \t 10 [0sec/1.596sec] \n UBCF run \n \t 1 [0.004sec/1.652sec] \n \t 2 [0.004sec/1.568sec] \n \t 3 [0.004sec/1.58sec] \n \t 4 [0sec/1.548sec] \n \t 5 [0sec/1.6sec] \n \t 6 [0.004sec/1.528sec] \n \t 7 [0sec/1.632sec] \n \t 8 [0sec/1.584sec] \n \t 9 [0.004sec/1.604sec] \n \t 10 [0sec/1.568sec] \n UBCF run \n \t 1 [0.004sec/1.552sec] \n \t 2 [0sec/1.588sec] \n \t 3 [0sec/1.536sec] \n \t 4 [0.004sec/1.556sec] \n \t 5 [0sec/1.528sec] \n \t 6 [0sec/1.652sec] \n \t 7 [0sec/1.58sec] \n \t 8 [0sec/1.632sec] \n \t 9 [0.004sec/1.668sec] \n \t 10 [0sec/1.568sec] \n UBCF run \n \t 1 [0.004sec/1.548sec] \n \t 2 [0sec/1.572sec] \n \t 3 [0sec/1.576sec] \n \t 4 [0sec/1.556sec] \n \t 5 [0.004sec/1.74sec] \n \t 6 [0.004sec/1.592sec] \n \t 7 [0sec/1.596sec] \n \t 8 [0.004sec/1.664sec] \n \t 9 [0.004sec/1.6sec] \n \t 10 [0sec/1.556sec] \n\n\n\n\n\n![png](hw7_files/hw7_20_1.png)\n\n\n\n\n \n" }, { "alpha_fraction": 0.6098169684410095, "alphanum_fraction": 0.6276206374168396, "avg_line_length": 26.43379020690918, "blob_id": "7528937d9e49b4ae32d8ae631da97466beae7ec1", "content_id": "5a65670598977a2fbc0a39f62a82df4725c20ec3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6010, "license_type": "no_license", "max_line_length": 147, "num_lines": 219, "path": "/hw7.py", "repo_name": "zero323-attic/ipi-wsdmp-ex7", "src_encoding": "UTF-8", "text": "\n# coding: utf-8\n\n# ## Author: Maciej Szymkiewicz\n# \n# Following datasets have been used:\n# \n# - biology.stackexchange.com\n# - datascience.stackexchange.com\n# - homebrew.stackexchange.com\n# - opendata.stackexchange.com\n# - robotics.stackexchange.com\n# \n# These datasets are small and relatively sparse and some results can be misleading. It is particularly obvious when we look at recommender output.\n# \n# Datasets have been downloaded from https://archive.org/details/stackexchange and extracted using 7-Zip 9.20.\n# \n# \n\n# In[1]:\n\nfrom __future__ import division, print_function\nimport lxml\nimport igraph\nimport pandas as pd\nimport re\nimport os\nimport itertools\nfrom scipy.spatial.distance import pdist, cdist, squareform\nfrom scipy.cluster.hierarchy import linkage, dendrogram\nimport rpy2.robjects as robjects\nimport pandas.rpy.common as com\nfrom IPython.display import Image\n\npylab.rcParams['figure.figsize'] = (17.0, 8.0)\n\n\n# In[2]:\n\ndef f_asymetric(x, y):\n return sum(x & y) / sum(x)\n\n\ndef get_edges(questions, threshold, min_tagged=5):\n questions = questions.loc[:, questions.sum(0) > 5]\n tags = list(questions.columns.values)\n pairs = ((t1, t2) for t1, t2 in itertools.product(tags, tags) if t1 != t2)\n dists = ((t1, t2, f_asymetric(questions[t1], questions[t2])) for t1, t2 in pairs)\n return [x for x in dists if x[2] >= threshold]\n\n\ndef create_graph(edges):\n g = igraph.Graph(directed = True)\n edges = [(x, y) for x, y, d in edges]\n vertices = list({_ for _ in itertools.chain(*edges)})\n g.add_vertices(vertices)\n g.vs['label'] = vertices\n g.add_edges(edges)\n return g\n\n\ndef parse_answers(input_file):\n def to_dict(path):\n return {'_uid_': x.xpath('@OwnerUserId')[0], x.xpath('@ParentId')[0]: 1}\n\n root = lxml.etree.parse(input_file)\n answers = root.xpath(\"/posts/row[@PostTypeId=2 and @OwnerUserId and @ParentId]\")\n parsed = [to_dict(x) for x in answers]\n unique_parents = list({x.xpath('@ParentId')[0] for x in answers})\n\n return pd.DataFrame(parsed, columns=['_uid_'] + unique_parents).fillna(0)\n\n\ndef parse_questions(input_file, all_tags):\n def to_dict(path, all_tags):\n qid = int(x.xpath('@Id')[0])\n score = int(x.xpath('@Score')[0])\n tags = {_ for _ in re.split('<|>', x.xpath(\"@Tags\")[0]) if _}\n return dict(zip(\n ['_qid_', '_score_'] + all_tags,\n [qid, score] + [tag in tags for tag in all_tags]\n ))\n\n root = lxml.etree.parse(input_file)\n questions = [to_dict(x, all_tags) for x in root.xpath(\"/posts/row[@PostTypeId=1]\")]\n return pd.DataFrame(questions, columns = ['_qid_', '_score_'] + all_tags)\n\n\ndef parse_tags(input_file):\n root = lxml.etree.parse(input_file)\n return root.xpath('/tags/row/@TagName')\n\n\ndef recommend(df, min_obs=5, min_given=1):\n df.to_csv('temp.csv', index=False)\n # Code based on:\n # Bolikowski, Dendek, Kursa, Web-scale data mining and processing\n # Big data in R with StackExchange case study\n recommend = robjects.r('''\n library(recommenderlab)\n recommend <- function(f, min_obs=1, given=1) {\n m <- as.matrix(read.csv(f))\n brm <- as(m[, colSums(m) >= min_obs], 'binaryRatingMatrix')\n image_file <- paste(tempfile(), 'png', sep='.')\n\n algos<-list(\n baseline=list(name='RANDOM', param=NULL),\n JaccardCF_5=list(name='UBCF', param=list(method='Jaccard', nn=5)),\n JaccardCF_10=list(name='UBCF', param=list(method='Jaccard', nn=10)),\n JaccardCF_30=list(name='UBCF', param=list(method='Jaccard', nn=30)),\n JaccardCF_50=list(name='UBCF', param=list(method='Jaccard', nn=50))\n )\n es <- evaluationScheme(brm, 'cross-validation', k=10, given=given)\n results <- evaluate(es, algos, n=c(1, 3, 5, 10, 30))\n\n tryCatch({\n png(image_file, width = 960, height = 960)\n plot(results)\n dev.off()\n image_file\n }, error = function(e) \"\")\n }''')\n return recommend('temp.csv', min_obs, min_given)\n\n\ndef process(directory, threshold=0.75, min_tagged=5):\n tags = parse_tags(os.path.join(directory, 'Tags.xml'))\n questions = parse_questions(os.path.join(directory, 'Posts.xml'), tags)\n answers = parse_answers(os.path.join(directory, 'Posts.xml'))\n dm = pdist(questions.iloc[:, 3:].as_matrix().transpose(), 'jaccard')\n edges = get_edges(questions.iloc[:, 3:], threshold, min_tagged)\n return tags, questions, dm, edges, answers\n\n\n# ### biology\n\n# In[3]:\n\ntags, questions, dm, edges, answers = process('data/biology/')\ndendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n# In[4]:\n\ng = create_graph(edges)\nigraph.plot(g, layout = g.layout(\"kk\"))\n\n\n# In[5]:\n\nf = recommend(answers, min_obs=4)[0]\nImage(f)\n\n\n# ### datascience\n\n# In[6]:\n\ntags, questions, dm, edges, answers = process('data/datascience/', min_tagged = 3)\ndendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n# In[7]:\n\ng = create_graph(edges)\nigraph.plot(g, layout = g.layout(\"kk\"))\n\n\n# In[8]:\n\nf = recommend(answers, min_obs=5)[0]\nImage(f)\n\n\n# ### homebrew\n\n# In[9]:\n\ntags, questions, dm, edges, answers = process('data/homebrew/')\ndendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n# In[10]:\n\nf = recommend(answers, min_obs=5)[0]\nImage(f)\n\n\n# ### opendata\n\n# In[11]:\n\ntags, questions, dm, edges, answers = process('data/opendata/')\ndendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n# In[12]:\n\ng = create_graph(edges)\nigraph.plot(g, layout = g.layout(\"kk\"))\n\n\n# In[13]:\n\ng = create_graph(edges)\nigraph.plot(g, layout = g.layout(\"kk\"))\n\n\n# ### robotics\n\n# In[14]:\n\ntags, questions, dm, edges, answers = process('data/robotics/', min_tagged = 1)\ndendr = dendrogram(linkage(dm, metric='jaccard'), labels = tags, no_labels=True)\n\n\n# In[15]:\n\nf = recommend(answers, min_obs=3)[0]\nImage(f)\n\n" }, { "alpha_fraction": 0.5177364945411682, "alphanum_fraction": 0.5268580913543701, "avg_line_length": 29.673574447631836, "blob_id": "9d7c4263f249c16fa3b6032ec07ae3590ac822cd", "content_id": "cfe48f1d8ec4fc9b72aed36dab87511f315e8a57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 5920, "license_type": "no_license", "max_line_length": 112, "num_lines": 193, "path": "/hw7.Rmd", "repo_name": "zero323-attic/ipi-wsdmp-ex7", "src_encoding": "UTF-8", "text": "\n```{r}\nlibrary(stringi)\nlibrary(data.table)\nlibrary(XML)\nlibrary(cluster)\n```\n\n```{r}\nlocal({\n base_url <- 'https://archive.org/download/stackexchange'\n files <- list(\n list(main = 'biology.stackexchange.com.7z'),\n list(main = 'datascience.stackexchange.com.7z'),\n list(main = 'homebrew.stackexchange.com.7z'),\n list(main = 'robotics.stackexchange.com.7z'),\n list(main = 'opendata.stackexchange.com.7z')\n )\n \n # Extract question id, score, and tags from question\n parse_questions <- function(lines, alltags) {\n parsed <- stri_match_all_regex(\n Filter(function(l) grepl('^\\\\s*<row.*Tags', l), lines),\n ' Id=\"([0-9]*)\" .* Score=\"([0-9]*)\" .* Tags=\"([^\"]*)\"'\n )\n \n do.call(rbind, lapply(\n parsed,\n function(x) {\n c(\n as.integer(x[2:3]),\n alltags %in% stri_split_regex(x[4], '&lt;|&gt;', omit_empty = TRUE)\n )\n }\n ))\n }\n \n # Extract question id and answer author from answer\n parse_answers <- function(lines) {\n parsed <- stri_match_all_regex(\n Filter(function(l) grepl('^\\\\s*<row.*ParentId', l), lines),\n ' ParentId=\"([0-9]*)\" .* OwnerUserId=\"([0-9]*)\"'\n )\n \n do.call(rbind, parsed)[, 2:3]\n }\n \n \n for(f in files) {\n f <- f$main\n \n destfile <- paste('data', f, sep = '/')\n \n # Download file\n if(!file.exists(destfile)) {\n download.file(\n url = paste(base_url, f, sep = '/'),\n destfile = destfile,\n method = 'wget'\n )\n }\n \n # Prepare file names\n xml_name <- paste('data/', gsub('(-Posts)?\\\\.7z', '', f), sep = '')\n tsv_name <- paste(xml_name, 'tsv', sep = '.')\n tags_name <- paste(xml_name, 'tags', sep = '.')\n answers_name <- paste(xml_name, 'answers.tsv', sep = '.')\n \n # Extract archives\n if(!file.exists(xml_name) & !file.exists(tsv_name)) {\n system(command = paste('7z e', destfile, '-odata'))\n file.rename('data/Posts.xml', xml_name)\n file.rename('data/Tags.xml', tags_name)\n unlink('data/*xml')\n }\n \n # Create tag matrices\n if(!file.exists(tsv_name)) {\n \n # Extract all tags\n counts <- as.integer(xpathSApply(xmlParse(tags_name), '//row[@TagName]', xmlGetAttr, 'Count'))\n tags <- sort(xpathSApply(xmlParse(tags_name), '//row[@TagName]', xmlGetAttr, 'TagName')[counts > 1])\n \n \n \n # Since I cannot parse large XML due to limited memory\n # I'll process files manualy line by line\n in_con <- file(description = xml_name, open = 'r')\n out_con <- file(description = tsv_name, open = 'w')\n out_answers_con <- file(description = answers_name, open = 'w')\n \n writeLines(text = paste(c('id', 'score', tags), collapse = '\\t'), out_con)\n writeLines(text = paste(c('qid', 'uid'), collapse = '\\t'), out_answers_con)\n \n repeat {\n lines <- readLines(in_con, 1000, warn = FALSE)\n if (length(lines) == 0) break\n questions <- parse_questions(lines, tags)\n write.table(\n questions, file = out_con,\n row.names = FALSE, col.names = FALSE,\n sep = \"\\t\", quote = FALSE\n ) \n \n answers <- parse_answers(lines)\n write.table(\n answers, file = out_answers_con,\n row.names = FALSE, col.names = FALSE,\n sep = '\\t', quote = FALSE\n ) \n }\n close(in_con)\n close(out_con)\n close(out_answers_con)\n unlink('data/*com')\n }\n }\n})\n```\n\n## biology.stackexchange.com\n\n### Tags\n\n```{r biology_tags, cache=TRUE}\nbiology_tags <- fread('data/biology.stackexchange.com.tsv')\nbiology_dists <- dist(t(biology_tags[, -c(1, 2), with=FALSE]), method=\"binary\")\n```\n\n```{r biology_dendrogram, fig.width=12}\nplot(agnes(biology_dists), which=2)\n```\n\n### Recommendations\n\n## datascience.stackexchange.com\n\n```{r datascience_tags, cache=TRUE}\ndatascience_tags <- fread('data/datascience.stackexchange.com.tsv')\ndatascience_dists <- dist(t(datascience_tags[, -c(1, 2), with=FALSE]), method=\"binary\")\n```\n\n```{r datascience_dendrogram, fig.width=12}\nplot(agnes(datascience_dists), which=2)\n```\n\n## homebrew.stackexchange.com\n\n```{r homebrew_tags, cache=TRUE}\nhomebrew_tags <- fread('data/homebrew.stackexchange.com.tsv')\nhomebrew_dists <- dist(t(homebrew_tags[, -c(1, 2), with=FALSE]), method=\"binary\")\n```\n\n```{r homebrew_dendrogram, fig.width=12}\nplot(agnes(homebrew_dists), which=2)\n```\n\n## robotics.stackexchange.com\n\n\n```{r robotics_tags, cache=TRUE}\nrobotics_tags <- fread('data/robotics.stackexchange.com.tsv')\nrobotics_dists <- dist(t(robotics_tags[, -c(1, 2), with=FALSE]), method=\"binary\")\n```\n\n```{r robotics_dendrogram, fig.width=12}\nplot(agnes(robotics_dists), which=2)\n```\n\n## opendata.stackexchange.com\n\n```{r opendata_tags, cache=TRUE}\nopendata_tags <- fread('data/opendata.stackexchange.com.tsv')\nopendata_dists <- dist(t(opendata_tags[, -c(1, 2), with=FALSE]), method=\"binary\")\n```\n\n```{r opendata_dendrogram, fig.width=12}\nplot(agnes(opendata_dists), which=2)\n```\n\n```{r}\nfunction(tags) {\n get_score <- function(x, y) {\n tags_x <- tags[, x, with = FALSE]\n tags_y <- tags[, y, with = FALSE]\n list(sum(tags_x & tags_y), sum(tags_x))\n }\n \n pairs_dt <- as.data.table(expand.grid(colnames(tags), colnames(tags)))\n \n apply(pairs_dt, 1, function(x) get_score(x[1], x[2]))\n \n}\n```" } ]
3
xWuWux/systemy_kontroli
https://github.com/xWuWux/systemy_kontroli
1acc4f0c1240f499e7c019a1dfabff6d71f67e64
b9f7e756447fea8818eb5386a5913066d2c78aa1
8bd553e380c700fe9e403caf11930b4de72352c2
refs/heads/master
2020-11-26T01:25:49.487521
2019-12-20T10:08:08
2019-12-20T10:08:08
228,921,975
2
0
null
2019-12-18T21:09:09
2019-12-17T21:46:02
2019-12-17T21:41:57
null
[ { "alpha_fraction": 0.4114285707473755, "alphanum_fraction": 0.44952380657196045, "avg_line_length": 17.10344886779785, "blob_id": "5e7ac301517ab04eb08bd55ded5cae9b991ae262", "content_id": "2ad9b1a287a59f456a44ff71e4e8360323875562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 525, "license_type": "no_license", "max_line_length": 40, "num_lines": 29, "path": "/zad.py", "repo_name": "xWuWux/systemy_kontroli", "src_encoding": "UTF-8", "text": "def menu():\n print(\"Menu:\")\n print(\"1\")\n print(\"2\")\n print(\"3\")\n print(\"4\")\n print(\"5\")\n print(\"6\")\n print(\"7\")\n choice= int(input(\"Enter choice: \"))\n if choice==1:\n print(\"one\")\n elif choice==2:\n print(\"2\")\n elif choice==3:\n print(\"3\")\n elif choice==4:\n print(\"4\")\n elif choice==5:\n print(\"5\")\n elif choice==6:\n print(\"6\")\n elif choice==7:\n print(\"7\")\n exit()\n else:\n print(\"Invalid choice\")\n menu()\nmenu()\n" } ]
1
dogukanevcil/munisite
https://github.com/dogukanevcil/munisite
256ecf7714015f4e4969f5415718ed38b6bf64da
70a69299cea4e0c2947938244a61a4b134fc4258
8900caa671755dfbd94b008f56c8aee9334fb9cf
refs/heads/master
2022-01-26T22:09:38.278426
2019-03-01T13:01:52
2019-03-01T13:01:52
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5684671998023987, "alphanum_fraction": 0.5780620574951172, "avg_line_length": 44.880435943603516, "blob_id": "d9d19444c8b2a7213d7bf801ec405fd84a370807", "content_id": "4e5f33ff833c91d042a5d8f79ad6eeaccc3db1ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8442, "license_type": "no_license", "max_line_length": 150, "num_lines": 184, "path": "/start/migrations/0001_initial.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.5 on 2019-02-22 10:10\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 ]\n\n operations = [\n migrations.CreateModel(\n name='Archives',\n fields=[\n ('archive_id', models.AutoField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='CitizenRequests',\n fields=[\n ('citizenRequest_id', models.AutoField(primary_key=True, serialize=False)),\n ('citizenName', models.CharField(max_length=200)),\n ('location', models.CharField(max_length=200)),\n ('details', models.CharField(max_length=200)),\n ('summary', models.CharField(max_length=200)),\n ('status', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='Departments',\n fields=[\n ('department_id', models.AutoField(primary_key=True, serialize=False)),\n ('archiveid', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Archives')),\n ('citizenrequest_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.CitizenRequests')),\n ],\n ),\n migrations.CreateModel(\n name='DepDocArchives',\n fields=[\n ('depDocArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='DepProjectArchives',\n fields=[\n ('depProjectArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ],\n ),\n migrations.CreateModel(\n name='DepRequests',\n fields=[\n ('depRequest_id', models.AutoField(primary_key=True, serialize=False)),\n ('details', models.CharField(max_length=200)),\n ('reason', models.CharField(max_length=200)),\n ('status', models.CharField(max_length=200)),\n ('department_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Departments')),\n ],\n ),\n migrations.CreateModel(\n name='DocumentArchives',\n fields=[\n ('documentArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ('depDocArchive_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.DepDocArchives')),\n ],\n ),\n migrations.CreateModel(\n name='Documents',\n fields=[\n ('document_id', models.AutoField(primary_key=True, serialize=False)),\n ('keywords', models.CharField(max_length=200)),\n ('description', models.CharField(max_length=200)),\n ('date', models.DateTimeField(auto_now_add=True)),\n ('status', models.CharField(max_length=200)),\n ],\n ),\n migrations.CreateModel(\n name='MyUser',\n fields=[\n ('password', models.CharField(max_length=128, verbose_name='password')),\n ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),\n ('user_id', models.AutoField(primary_key=True, serialize=False)),\n ('username', models.CharField(max_length=200)),\n ('level', models.CharField(max_length=200)),\n ('permissions', models.CharField(max_length=200)),\n ('department_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Departments')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='ProjectArchives',\n fields=[\n ('projectArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ('depProjectArchive_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.DepProjectArchives')),\n ],\n ),\n migrations.CreateModel(\n name='Projects',\n fields=[\n ('project_id', models.AutoField(primary_key=True, serialize=False)),\n ('executiveSummary', models.CharField(max_length=200)),\n ('details', models.CharField(max_length=200)),\n ('projectFeasibility', models.CharField(max_length=200)),\n ('socioEconomicImpact', models.CharField(max_length=200)),\n ('budgetControl', models.CharField(max_length=200)),\n ('targetDates', models.CharField(max_length=200)),\n ('canEdit', models.CharField(max_length=200)),\n ('createdBy', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.MyUser')),\n ],\n ),\n migrations.CreateModel(\n name='SharedDocArchive',\n fields=[\n ('sharedDocArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ('document_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Documents')),\n ],\n ),\n migrations.CreateModel(\n name='SharedProjectArchive',\n fields=[\n ('sharedProjectArchive_id', models.AutoField(primary_key=True, serialize=False)),\n ('project_id', models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Projects')),\n ],\n ),\n migrations.AddField(\n model_name='projectarchives',\n name='sharedProjectArchive_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.SharedProjectArchive'),\n ),\n migrations.AddField(\n model_name='documents',\n name='addedby',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.MyUser'),\n ),\n migrations.AddField(\n model_name='documentarchives',\n name='sharedDocArchive_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.SharedDocArchive'),\n ),\n migrations.AddField(\n model_name='deprequests',\n name='sendFrom',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='sender', to='start.MyUser'),\n ),\n migrations.AddField(\n model_name='deprequests',\n name='sendTo',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, related_name='receiver', to='start.MyUser'),\n ),\n migrations.AddField(\n model_name='depprojectarchives',\n name='project_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Projects'),\n ),\n migrations.AddField(\n model_name='depdocarchives',\n name='document_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Documents'),\n ),\n migrations.AddField(\n model_name='departments',\n name='departmentrequest_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.DepRequests'),\n ),\n migrations.AddField(\n model_name='citizenrequests',\n name='department_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.Departments'),\n ),\n migrations.AddField(\n model_name='archives',\n name='documentArchive_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.DocumentArchives'),\n ),\n migrations.AddField(\n model_name='archives',\n name='projectArchive_id',\n field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.PROTECT, to='start.ProjectArchives'),\n ),\n ]\n" }, { "alpha_fraction": 0.7803278565406799, "alphanum_fraction": 0.7803278565406799, "avg_line_length": 32.66666793823242, "blob_id": "de553acf1ac08a552d0bc973bb95123e6a4930a8", "content_id": "e7283a847f791b1ee19fd26130a637b27b484435", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 305, "license_type": "no_license", "max_line_length": 64, "num_lines": 9, "path": "/department/views.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import loader\n\n# Create your views here.\ndef department(request):\n template = loader.get_template('department/department.html')\n context = None\n return HttpResponse(template.render(context, request))\n\n\n" }, { "alpha_fraction": 0.6370656490325928, "alphanum_fraction": 0.6370656490325928, "avg_line_length": 22.454545974731445, "blob_id": "34408f8a701aa00798667b50c04d1bacc007a000", "content_id": "ee59d1404d8953f5924551df828b2ffd872a2d77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/munisite/urls.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "\nfrom django.urls import include, path\nfrom django.contrib import admin\n\nurlpatterns = [\n path('', include('start.urls')),\n path('login/', include('start.urls')),\n path('dep', include('department.urls')),\n path('admin/', admin.site.urls),\n \n\n]\n" }, { "alpha_fraction": 0.6974790096282959, "alphanum_fraction": 0.6974790096282959, "avg_line_length": 16.14285659790039, "blob_id": "a178d8b6a3ca499294e06674754eb6f28e6afc1d", "content_id": "76637a9667bc0df567852bc654fb4d3c9c77ddcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 119, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/department/urls.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.department, name='department'),\n]" }, { "alpha_fraction": 0.7005400061607361, "alphanum_fraction": 0.7108492851257324, "avg_line_length": 39.21052551269531, "blob_id": "7f2e43bd7aa4372b474e10d7818595c901971e4a", "content_id": "c3777b24419751ab5656d32af1e18719d7086446", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6111, "license_type": "no_license", "max_line_length": 115, "num_lines": 152, "path": "/start/models.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom django.contrib.auth.models import (\n BaseUserManager, AbstractBaseUser\n)\n\n\n\n\nclass MyUserManager(BaseUserManager):\n def create_user(self, username, level, department_id_id, password=None):\n \"\"\" \n Creates abd saves a User with given details\n \"\"\"\n\n if not username:\n raise ValueError('Users must have a username')\n\n user = self.model (\n username=username,\n level=level,\n department_id_id=department_id_id,\n )\n\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_superuser(self, username, password, level, department_id_id):\n \"\"\"\n Creates and saves a superuser with given details\n \"\"\"\n\n user = self.create_user(\n username, \n level,\n int(department_id_id),\n password = password,\n\n )\n user.is_admin = True\n user.save(using=self._db)\n return user\n\nclass MyUser(AbstractBaseUser):\n user_id = models.AutoField(primary_key=True)\n username = models.CharField(max_length=200, unique=True)\n level = models.CharField(max_length=200)\n permissions = models.CharField(max_length=200)\n department_id = models.ForeignKey(\"Departments\", on_delete=models.PROTECT, default=None)\n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n\n objects = MyUserManager()\n\n USERNAME_FIELD = 'username'\n REQUIRED_FIELDS = ['level', 'department_id_id']\n def __str__(self):\n return self.username\n\n def has_perm(self, perm, obj=None):\n \"Does the user have a specific permission?\"\n return True\n\n def has_module_perms(self, app_label):\n \"Does the user have a permission to view the app `app_label`?\"\n return True\n \n def is_staff(self):\n \"Is the user a member of staff?\"\n # All adming are staff\n return self.is_admin\n\n\n\nclass Departments(models.Model):\n department_id = models.AutoField(primary_key=True)\n departmentrequest_id = models.ForeignKey(\"DepRequests\", on_delete=models.PROTECT, default=None)\n citizenrequest_id = models.ForeignKey(\"CitizenRequests\", on_delete=models.PROTECT, default=None)\n archiveid = models.ForeignKey(\"Archives\", on_delete=models.PROTECT, default=None)\n\nclass DepRequests(models.Model):\n depRequest_id = models.AutoField(primary_key=True)\n department_id = models.ForeignKey(\"Departments\", on_delete=models.PROTECT, default=None)\n sendFrom = models.ForeignKey(\"MyUser\", on_delete=models.PROTECT, related_name=\"sender\", default=None)\n sendTo = models.ForeignKey(\"MyUser\", on_delete=models.PROTECT,related_name=\"receiver\", default=None)\n details = models.CharField(max_length=200)\n reason = models.CharField(max_length=200)\n status = models.CharField(max_length=200)\n\nclass CitizenRequests(models.Model):\n citizenRequest_id = models.AutoField(primary_key=True)\n department_id = models.ForeignKey(\"Departments\", on_delete=models.PROTECT, default=None)\n citizenName = models.CharField(max_length=200)\n location = models.CharField(max_length=200)\n details = models.CharField(max_length=200)\n summary = models.CharField(max_length=200)\n citizenIdNo = models.DecimalField\n status = models.CharField(max_length=200) \n\nclass Archives(models.Model):\n archive_id = models.AutoField(primary_key=True)\n documentArchive_id = models.ForeignKey(\"DocumentArchives\", on_delete=models.PROTECT, default=None)\n projectArchive_id = models.ForeignKey(\"ProjectArchives\", on_delete=models.PROTECT, default=None)\n\nclass DocumentArchives(models.Model):\n documentArchive_id = models.AutoField(primary_key=True)\n depDocArchive_id = models.ForeignKey(\"DepDocArchives\", on_delete=models.PROTECT, default=None)\n sharedDocArchive_id = models.ForeignKey(\"SharedDocArchive\", on_delete=models.PROTECT, default=None)\n\nclass ProjectArchives(models.Model):\n projectArchive_id = models.AutoField(primary_key=True)\n depProjectArchive_id = models.ForeignKey(\"DepProjectArchives\", on_delete=models.PROTECT, default=None)\n sharedProjectArchive_id = models.ForeignKey(\"SharedProjectArchive\", on_delete=models.PROTECT, default=None) \n\nclass DepDocArchives(models.Model):\n depDocArchive_id = models.AutoField(primary_key=True)\n document_id = models.ForeignKey(\"Documents\", on_delete=models.PROTECT, default=None)\n\nclass SharedDocArchive(models.Model):\n sharedDocArchive_id = models.AutoField(primary_key=True)\n document_id = models.ForeignKey(\"Documents\", on_delete=models.PROTECT, default=None)\n\nclass Documents(models.Model):\n document_id = models.AutoField(primary_key=True)\n addedby = models.ForeignKey(\"MyUser\", on_delete=models.PROTECT, default=None)\n keywords = models.CharField(max_length=200)\n description = models.CharField(max_length=200)\n date = models.DateTimeField(auto_now_add=True)\n status = models.CharField(max_length=200)\n isShared = models.BooleanField\n\nclass DepProjectArchives(models.Model):\n depProjectArchive_id = models.AutoField(primary_key=True)\n project_id = models.ForeignKey(\"Projects\", on_delete=models.PROTECT, default=None)\n\nclass SharedProjectArchive(models.Model):\n sharedProjectArchive_id = models.AutoField(primary_key=True)\n project_id = models.ForeignKey(\"Projects\", on_delete=models.PROTECT, default=None)\n\nclass Projects(models.Model):\n project_id = models.AutoField(primary_key=True)\n executiveSummary = models.CharField(max_length=200)\n details = models.CharField(max_length=200)\n projectFeasibility = models.CharField(max_length=200)\n socioEconomicImpact = models.CharField(max_length=200)\n budgetControl = models.CharField(max_length=200)\n targetDates = models.CharField(max_length=200)\n approvalAdministative = models.BooleanField\n approvalFinanceDir = models.BooleanField\n createdBy = models.ForeignKey(\"MyUser\", on_delete=models.PROTECT, default=None)\n canEdit = models.CharField(max_length=200)" }, { "alpha_fraction": 0.6737766861915588, "alphanum_fraction": 0.6750313639640808, "avg_line_length": 41, "blob_id": "ba32996c1f29a1d743e73552466145172840da0c", "content_id": "ceb3828732e80016bf476a47c35e5caf34b53a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 797, "license_type": "no_license", "max_line_length": 84, "num_lines": 19, "path": "/start/views.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.template import loader\nfrom start.models import MyUser\n\n\ndef login(request):\n if(request.method == \"POST\"):\n if(MyUser.objects.get(username=request.POST['login_username'])):\n user = MyUser.objects.filter(username=request.POST['login_username'])[0]\n if(request.POST['login_password'] == user.password):\n request.session['id'] = user.user_id\n template = loader.get_template('department/department.html')\n context = None\n return HttpResponse(template.render(context, request))\n\n template = loader.get_template('start/registration/login.html')\n context = None\n return HttpResponse(template.render(context, request))" }, { "alpha_fraction": 0.5192582011222839, "alphanum_fraction": 0.5506419539451599, "avg_line_length": 24.035715103149414, "blob_id": "e827e4942f25c5e44d8bfe5b534c23592c251dd3", "content_id": "f70e8b971373ad8060802014e88de2332a5d189e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/start/migrations/0002_auto_20190222_1219.py", "repo_name": "dogukanevcil/munisite", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.5 on 2019-02-22 12:19\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('start', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='myuser',\n name='is_active',\n field=models.BooleanField(default=True),\n ),\n migrations.AddField(\n model_name='myuser',\n name='is_admin',\n field=models.BooleanField(default=False),\n ),\n migrations.AlterField(\n model_name='myuser',\n name='username',\n field=models.CharField(max_length=200, unique=True),\n ),\n ]\n" } ]
7
esteve-ship-it/serc
https://github.com/esteve-ship-it/serc
a0dbb2c5ec9f988b9052c67fc7000687f511d284
1103ff5d67c47cc03a9ca39a9eb4f870910a6fd4
5bf93adbf221824c0ba71d8898dcc32a8b4d2908
refs/heads/main
2023-04-05T03:05:59.557231
2021-04-15T16:31:28
2021-04-15T16:31:28
332,622,655
0
3
null
2021-01-25T03:43:27
2021-04-03T23:39:10
2021-04-06T04:18:05
Jupyter Notebook
[ { "alpha_fraction": 0.5261282920837402, "alphanum_fraction": 0.5344418287277222, "avg_line_length": 27.827587127685547, "blob_id": "6fcd430d1f2873995e7b15b156bdc7e66ba10452", "content_id": "e08aacbe4ae02d713bee195a68b051977150cf7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 842, "license_type": "no_license", "max_line_length": 112, "num_lines": 29, "path": "/script.py", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "import os\n\n\n\nwavDirectory = \"C:\\\\Users\\\\brend\\\\Desktop\\\\serc\\\\audio\\\\fold1\"\n\n#os.mkdir(\"C:\\\\Users\\\\brend\\\\Desktop\\\\serc\\\\copies\")\ncopytoDirectory =\"C:\\\\Users\\\\brend\\\\Desktop\\\\serc\\\\copies\" \ncsvPath = \"C:\\\\Users\\\\brend\\\\Desktop\\\\serc\\\\UrbanSound8k.csv\"\nfd = open(csvPath, \"r\")\ntuples = fd.readlines()\n\nfd.close()\n\ncount = 0\nfor i in os.listdir(wavDirectory):\n for j in tuples:\n if(i in j):\n strings = j.split(\",\")\n print(\"XXXXXXXX\")\n print(i)\n \n print(strings[7].strip() + str(count))\n count = count + 1\n #print(wavDirectory + \"\\\\\" + i)\n #print(copytoDirectory + \"\\\\\" + strings[7].strip() + \".wav\")\n #os.rename(wavDirectory + \"\\\\\" + i,copytoDirectory + \"\\\\\" + strings[7].strip()+ str(count) + \".wav\")\n \n #hmnm\n\n\n " }, { "alpha_fraction": 0.72265625, "alphanum_fraction": 0.72265625, "avg_line_length": 33.20000076293945, "blob_id": "c861384cba31bd370d5b947394921eb64571d4d2", "content_id": "84fa517ffb1d58e4931f9113b9f25d694ab79ab7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 512, "license_type": "no_license", "max_line_length": 116, "num_lines": 15, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/model/SERCSoundDatabase.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.model\n\nimport edu.mtu.sercsoundsampler.services.SERCSampler\n\n\nclass SERCSoundDatabase(val s: String, val sampler: SERCSampler) {\n val activeSet = HashSet<String>()\n val badEntry = SERCSoundEntry(s)\n fun getEntry(sound: String?): SERCSoundEntry { return if (sound != null) SERCSoundEntry(sound!!) else badEntry }\n\n fun sourceChanged(src: String, onOff: Boolean) {\n if (onOff) activeSet.add(src) else activeSet.remove(src)\n sampler.mark(activeSet)\n }\n}" }, { "alpha_fraction": 0.6218233108520508, "alphanum_fraction": 0.62505042552948, "avg_line_length": 36.75, "blob_id": "067b266776cc367e4d07b48fd71811b70384e9f1", "content_id": "a0b4385f1e9a6c7c916edf94ab99527ce09a72a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 4958, "license_type": "no_license", "max_line_length": 128, "num_lines": 128, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/SampleActivity.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler\r\n\r\nimport android.Manifest\r\nimport android.location.Location\r\nimport android.media.AudioFormat\r\nimport android.media.AudioRecord\r\nimport android.media.MediaRecorder\r\nimport android.os.Bundle\r\nimport android.os.Environment\r\nimport android.os.Handler\r\nimport android.os.Looper\r\nimport android.util.Log\r\nimport android.view.View\r\nimport androidx.appcompat.app.AppCompatActivity\r\nimport com.karumi.dexter.Dexter\r\nimport com.karumi.dexter.MultiplePermissionsReport\r\nimport com.karumi.dexter.PermissionToken\r\nimport com.karumi.dexter.listener.PermissionRequest\r\nimport com.karumi.dexter.listener.multi.MultiplePermissionsListener\r\nimport kotlinx.android.synthetic.main.sample_layout.*\r\nimport java.io.File\r\nimport java.io.PrintWriter\r\nimport java.text.SimpleDateFormat\r\nimport java.util.*\r\n\r\nclass SampleActivity : AppCompatActivity() {\r\n val TAG = \"SampleActivity\"\r\n val multiListener: MultiListener = MultiListener()\r\n var audioDirPath: String? = null\r\n var mappingFile: File? = null\r\n var dateFilename = \"\"\r\n var sd: File? = null\r\n override fun onCreate(savedInstanceState: Bundle?) {\r\n super.onCreate(savedInstanceState)\r\n setContentView(R.layout.sample_layout)\r\n ensureDataFolderAndMappingFile()\r\n Dexter.withContext(this)\r\n .withPermissions(\r\n Manifest.permission.WRITE_EXTERNAL_STORAGE,\r\n Manifest.permission.ACCESS_FINE_LOCATION,\r\n Manifest.permission.RECORD_AUDIO)\r\n .withListener(multiListener)\r\n .check()\r\n if (multiListener.proceed) {\r\n Log.i(TAG, \"Premissions granted, here we go...\")\r\n }\r\n record_button.setOnClickListener( View.OnClickListener {\r\n try {\r\n var recorder = MyRecorder();\r\n var location = Location(\"me\")\r\n if (multiListener.proceed && record_button.text == \"Record\") {\r\n var date = SimpleDateFormat(\"yyyy_MM_dd_HH_mm_ss\").format(Date())\r\n var capturedSound = audioFileName.text.toString()\r\n dateFilename = date.toString() + \".pcm\"\r\n Log.i(TAG, \"Recording \" + dateFilename)\r\n sd = File(audioDirPath + \"/\" + dateFilename)\r\n record_button.text = \"Recording\";\r\n recorder.run(sd!!, TAG)\r\n addEntry(mappingFile!!, capturedSound, dateFilename, location)\r\n// mappingFile!!.appendText(temporyTitleForButton + \",\" + audioFile + \"\\n\")\r\n\r\n } else {\r\n record_button.text = \"Record\"\r\n recorder.interrupt()\r\n audioFileName.setText(\"\")\r\n }\r\n } catch (e: java.lang.Exception){\r\n Log.d(TAG, e.toString());\r\n }\r\n })\r\n }\r\n\r\n private fun addEntry(mappingFile: File, capturedSound: String, audioFilename: String, location: Location) {\r\n val w: PrintWriter = PrintWriter(mappingFile)\r\n w.append(audioFilename)\r\n .append(\",\")\r\n .append(capturedSound)\r\n .append(\",\")\r\n .append(location.latitude.toString())\r\n .append(\",\")\r\n .append(location.longitude.toString())\r\n .append(\"\\n\")\r\n w.close()\r\n }\r\n\r\n fun ensureDataFolderAndMappingFile() {\r\n Log.d(TAG, Environment.getExternalStorageDirectory().toString())\r\n val externalStorage: File = Environment.getExternalStorageDirectory()\r\n audioDirPath = externalStorage.absolutePath + \"/audioData\";\r\n val directory = File(audioDirPath)\r\n directory.mkdir()\r\n mappingFile = File(audioDirPath + \"/MappingFile.csv\")\r\n Log.d(TAG, \"Ensured existence of: \" + mappingFile!!.canonicalPath)\r\n }\r\n}\r\n\r\nclass MyRecorder : Thread() {\r\n private val bufferSize = 8192\r\n private val aformat = AudioFormat.Builder().setSampleRate(32000).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(\r\n AudioFormat.CHANNEL_IN_MONO).build();\r\n private val audioRecorder = AudioRecord.Builder().setBufferSizeInBytes(bufferSize).setAudioFormat(aformat).setAudioSource(\r\n MediaRecorder.AudioSource.MIC).build();\r\n\r\n var x = 0\r\n //comment\r\n fun run(filename: File, tag: String) {\r\n var data = ByteArray(bufferSize);\r\n\r\n audioRecorder.startRecording();\r\n\r\n audioRecorder.read(data,0,bufferSize);\r\n\r\n filename.writeBytes(data);\r\n if (x >= 3) {\r\n Log.d(tag, \"REMEMBER WE ONLY RAN 3 TIMES\");\r\n return;\r\n }\r\n x = x + 1;\r\n\r\n }\r\n}\r\n\r\nclass MultiListener : MultiplePermissionsListener {\r\n var proceed: Boolean = false\r\n override fun onPermissionsChecked(prt: MultiplePermissionsReport) { proceed = true }\r\n override fun onPermissionRationaleShouldBeShown(permissions: List<PermissionRequest>, token: PermissionToken) {\r\n }\r\n}" }, { "alpha_fraction": 0.6836715340614319, "alphanum_fraction": 0.6996017694473267, "avg_line_length": 26.586387634277344, "blob_id": "387b6e0fc2a4f2d5ae4bc7ba857a0a9dce24ba9e", "content_id": "2fdb0e3c7b2924289c05772e23c8b90a53414853", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5273, "license_type": "no_license", "max_line_length": 112, "num_lines": 191, "path": "/audio-characterizer/ModelTrainer.py", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\n# Nicholas Whisman: 29 Jan 2021\n# This Script takes the preprocessor and processor from the 8k Audio project and mashes them into one script\n#\n# Ideally, end-game, this script will look over the audio files in the server (be it by file system or database)\n# analyze them, and train/re-train the model completely over again. \n\n#-----------------------------------------------------------------------------------------------------------#\n# Import libraries and dependencies. ML is scary, so there's a lot. Keep it simple.\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom tqdm import tqdm\nfrom librosa import display\nimport librosa\nfrom tensorflow.keras.utils import to_categorical\nfrom numpy import genfromtxt\nfrom tensorflow.keras import Sequential\nimport tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout\nfrom tensorflow.keras import Model\n\n\n# In[6]:\n\n\n###PRE-PROCESSOR###\n#-----------------------------------------------------------------#\n\n#forming a panda dataframe from the metadata file\ndata=pd.read_csv(\"UrbanSound8K/metadata/UrbanSound8K.csv\")\n\n#head of the dataframe\ndata.head()\n\n#count of datapoints in each of the folders\ndata[\"fold\"].value_counts()\n\n#preprocessing using only mfcc\nx_train=[]\nx_test=[]\ny_train=[]\ny_test=[]\npath=\"UrbanSound8K/audio/fold\"\nfor i in tqdm(range(len(data))):\n fold_no=str(data.iloc[i][\"fold\"])\n file=data.iloc[i][\"slice_file_name\"]\n label=data.iloc[i][\"classID\"]\n filename=path+fold_no+\"/\"+file\n #print(filename)\n y,sr=librosa.load(filename)\n mfccs = np.mean(librosa.feature.mfcc(y, sr, n_mfcc=40).T,axis=0)\n #print(mfccs.shape,mfccs.max(),mfccs.min())\n if(fold_no!='10'):\n x_train.append(mfccs)\n y_train.append(label)\n else:\n x_test.append(mfccs)\n y_test.append(label)\n \nlen(x_train)+len(x_test)\nlen(data)\n\n#converting the lists into numpy arrays\nx_train=np.array(x_train)\nx_test=np.array(x_test)\ny_train=np.array(y_train)\ny_test=np.array(y_test)\nx_train.shape,x_test.shape,y_train.shape,y_test.shape\n\n#saving the data numpy arrays\nnp.savetxt(\"train_data.csv\", x_train, delimiter=\",\")\nnp.savetxt(\"test_data.csv\",x_test,delimiter=\",\")\nnp.savetxt(\"train_labels.csv\",y_train,delimiter=\",\")\nnp.savetxt(\"test_labels.csv\",y_test,delimiter=\",\")\n\nx_test[0].shape\n\n\n# In[7]:\n\n\n### Processing/ Training ###\n#------------------------------------------------#\n\n#extracting data from csv files into numpy arrays\nx_train = genfromtxt('train_data.csv', delimiter=',')\ny_train = genfromtxt('train_labels.csv', delimiter=',')\nx_test = genfromtxt('test_data.csv', delimiter=',')\ny_test = genfromtxt('test_labels.csv', delimiter=',')\n\n#shape\nx_train.shape,x_test.shape,y_train.shape,y_test.shape\n\n#converting to one hot\ny_train = to_categorical(y_train, num_classes=10)\ny_test = to_categorical(y_test, num_classes=10)\ny_train.shape,y_test.shape\n\n#reshaping to shape required by CNN\nx_train=np.reshape(x_train,(x_train.shape[0], 40,1,1))\nx_test=np.reshape(x_test,(x_test.shape[0], 40,1,1))\n\n#shapes\nx_train.shape,x_test.shape\n\n#forming model\nmodel=Sequential()\n\n#adding layers and forming the model\nmodel.add(Conv2D(64,kernel_size=5,strides=1,padding=\"Same\",activation=\"relu\",input_shape=(40,1,1)))\nmodel.add(MaxPooling2D(padding=\"same\"))\n\nmodel.add(Conv2D(128,kernel_size=5,strides=1,padding=\"same\",activation=\"relu\"))\nmodel.add(MaxPooling2D(padding=\"same\"))\nmodel.add(Dropout(0.3))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(256,activation=\"relu\"))\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(512,activation=\"relu\"))\nmodel.add(Dropout(0.3))\n\nmodel.add(Dense(10,activation=\"softmax\"))\n\n#compiling\nmodel.compile(optimizer=\"adam\",loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])\n\n#training the model\nmodel.fit(x_train,y_train,batch_size=50,epochs=30,validation_data=(x_test,y_test))\n\n#train and test loss and scores respectively\ntrain_loss_score=model.evaluate(x_train,y_train)\ntest_loss_score=model.evaluate(x_test,y_test)\nprint(train_loss_score)\nprint(test_loss_score)\n\nmodel.summary()\n\nmodel.save('urbanClassifier')\n\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\ntflite_model = converter.convert()\n\n# Save the TF Lite model.\nwith tf.io.gfile.GFile('model.tflite', 'wb') as f:\n f.write(tflite_model)\n\nx_test[0].shape\n\ntestData = np.expand_dims(x_test[5],axis=0)\nprediction = model.predict_classes(testData)\nprediction\ny_test[5]\n\n# Load the TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_path=\"model.tflite\")\ninterpreter.allocate_tensors()\n\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\ninput_details\n\ntestData = np.expand_dims(x_test[5],axis=0)\natData = np.float32(testData)\n\ninput_shape = input_details[0]['shape']\ninput_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)\ninterpreter.set_tensor(input_details[0]['index'], atData)\nprint(input_data.dtype)\nprint(testData.shape)\ninterpreter.invoke()\n\n# The function `get_tensor()` returns a copy of the tensor data.\n# Use `tensor()` in order to get a pointer to the tensor.\noutput_data = interpreter.get_tensor(output_details[0]['index'])\nprint(output_data)\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.6434821486473083, "alphanum_fraction": 0.6465964913368225, "avg_line_length": 36.67597579956055, "blob_id": "c54d8e23ba438ec6f31ca593b0c64c07b6944047", "content_id": "795f1c3a5a73a52d896215569cf21668f043820a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 6743, "license_type": "no_license", "max_line_length": 135, "num_lines": 179, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/services/SERCSampler.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.services\n\nimport android.Manifest\nimport android.app.Application\nimport android.content.SharedPreferences\nimport android.location.Location\nimport android.media.AudioFormat\nimport android.media.AudioRecord\nimport android.media.MediaRecorder\nimport android.os.Environment\nimport android.util.Log\nimport com.karumi.dexter.Dexter\nimport com.karumi.dexter.MultiplePermissionsReport\nimport com.karumi.dexter.PermissionToken\nimport com.karumi.dexter.listener.PermissionRequest\nimport com.karumi.dexter.listener.multi.MultiplePermissionsListener\nimport edu.mtu.sercsoundsampler.MultiListener\nimport edu.mtu.sercsoundsampler.model.SERCPreferencesHelper\nimport kotlinx.android.synthetic.main.sample_layout.*\nimport kotlinx.coroutines.*\n\nimport java.io.File\nimport java.io.FileOutputStream\nimport java.io.PrintWriter\nimport java.lang.StringBuilder\nimport java.text.SimpleDateFormat\nimport java.util.*\nimport kotlin.collections.HashSet\n\nclass SERCSampler(val prefs: SharedPreferences\n , val helper: SERCPreferencesHelper\n , val multiListener: MultiListener, val dataPath: String) {\n var sources: HashSet<String> = HashSet()\n companion object {\n val TAG = \"Sampler\"\n val KEY_SAMPLE_LENGTH = \"serc.sample.len.msecs\"\n val KEY_SAMPLE_INTERVAL = \"serc.sample.interval.msecs\"\n val DEFAULT_SAMPLE_LENGTH_SECONDS: Long = 4\n val DEFAULT_SAMPLE_INTERVAL_SECONDS: Long = 60\n val DEFAULT_SAMPLE_RATE: Int = 44100\n var isSampling = false\n //var sampleLengthInMilliseconds = DEFAULT_SAMPLE_LENGTH_MS\n //var sampleIntervalInMilliseconds = DEFAULT_SAMPLE_INTERVAL_MS\n }\n val emptySet = HashSet<String>()\n var enableSampling = true\n init { GlobalScope.launch { performSampling() } }\n\n suspend fun performSampling() {\n Log.i(TAG, \"Coroutine to collect sample started...\")\n while (enableSampling) {\n delay((getSampleSecondInterval() - getSampleSecondLength()) * 1000)\n sample(getSampleSecondLength())\n }\n Log.i(TAG, \"Coroutine to collect sample stopped...\")\n }\n\n fun getMappingFile(): File {\n val dateStr = SimpleDateFormat(\"yyyy_MM_dd_HH\").format(Date())\n val dailyMappingFilename = \"${dateStr}.lson\"\n val f = File(dataPath, dailyMappingFilename)\n if (!f.exists()) f.createNewFile()\n return f\n }\n private fun addEntry(sounds: Set<String>, audioFilename: String, location: Location) {\n val w: PrintWriter = PrintWriter(FileOutputStream(getMappingFile(), true))\n w.append(\"{\\\"file\\\":\\\"\")\n .append(audioFilename)\n .append(\"\\\",\\\"srcs\\\":[\")\n .append(csvOf(sounds))\n .append(\"],\\\"lat\\\":\\\"\")\n .append(location.latitude.toString())\n .append(\"\\\",\\\"lng\\\":\\\"\")\n .append(location.longitude.toString())\n .append(\"\\\"}\\n\")\n .flush()\n w.close()\n }\n\n fun csvOf(sounds: Set<String>): String {\n val sb = StringBuilder()\n sounds.map { sb.append(\",\").append(\"\\\"\").append(it).append(\"\\\"\")}\n return if (sounds.size > 0) sb.toString().substring(1) else \"\"\n }\n\n /** When we sample, we want the sound in a *.wav file and an entry added to the metadata file\n * including the sounds that are noted by the user as being active.\n */\n private fun sample(sampleLengthSeconds: Long) {\n\n var dateFilename = \"\"\n var sd: File? = null\n try {\n isSampling = true\n var recorder = MyRecorder(sampleLengthSeconds.toInt(), DEFAULT_SAMPLE_RATE)\n var location = Location(\"me\")\n if (multiListener.proceed) {\n val date = SimpleDateFormat(\"yyyy_MM_dd_HH_mm_ss\").format(Date())\n dateFilename = date.toString() + \".pcm\"\n Log.i(TAG, \"Recording \" + dateFilename)\n sd = File(dataPath, dateFilename)\n recorder.run(sd, TAG)\n addEntry(sources, dateFilename, location)\n// mappingFile!!.appendText(temporyTitleForButton + \",\" + audioFile + \"\\n\")\n\n } else {\n recorder.interrupt()\n }\n } catch (e: java.lang.Exception){\n Log.d(TAG, e.toString());\n } finally {\n isSampling = false\n }\n }\n\n /** mark - mark the current sample as contains the sources sent in as the 'srcs' argument.\n * If in between samples start one immediately\n *\n */\n fun mark(srcs: Set<String>) {\n sources.clear()\n sources.addAll(srcs)\n takeSample()\n }\n\n fun getSampleSecondLength(): Long {\n return prefs.getLong(KEY_SAMPLE_LENGTH, DEFAULT_SAMPLE_LENGTH_SECONDS)\n }\n\n fun getSampleSecondInterval(): Long {\n return prefs.getLong(KEY_SAMPLE_INTERVAL, DEFAULT_SAMPLE_INTERVAL_SECONDS)\n }\n\n fun setSampleSecondLength(len: Long) {\n if (len > 0 && len < getSampleSecondInterval())\n helper.preserveLong(KEY_SAMPLE_LENGTH, len)\n }\n fun setSampleSecondInterval(i: Long) {\n if (i > 0) helper.preserveLong(KEY_SAMPLE_INTERVAL, i)\n if (getSampleSecondLength() >= getSampleSecondInterval())\n helper.preserveLong(KEY_SAMPLE_LENGTH, getSampleSecondInterval() - 1)\n }\n\n /** If the app is not active, then we can't know if samples taken while running in the background\n * have *any* designated sources.\n */\n fun onDestroy() { mark(emptySet) }\n\n fun takeSample() {\n if (!isSampling) {\n sample(getSampleSecondLength())\n }\n }\n}\n\nclass MyRecorder(val sampleLengthSeconds: Int, val sampleRateHz: Int) : Thread() {\n private val bufferSize = sampleLengthSeconds * sampleRateHz\n private val aformat = AudioFormat.Builder().setSampleRate(sampleRateHz).setEncoding(AudioFormat.ENCODING_PCM_16BIT).setChannelMask(\n AudioFormat.CHANNEL_IN_MONO).build();\n private val audioRecorder = AudioRecord.Builder().setBufferSizeInBytes(bufferSize).setAudioFormat(aformat).setAudioSource(\n MediaRecorder.AudioSource.MIC).build();\n\n var x = 0\n //comment\n fun run(file: File?, tag: String) {\n var data = ByteArray(bufferSize)\n audioRecorder.startRecording()\n audioRecorder.read(data,0,bufferSize)\n file!!.writeBytes(data)\n //audioRecorder.stop()\n }\n}\n\nclass MultiListener : MultiplePermissionsListener {\n var proceed: Boolean = false\n override fun onPermissionsChecked(prt: MultiplePermissionsReport) { proceed = true }\n override fun onPermissionRationaleShouldBeShown(permissions: List<PermissionRequest>, token: PermissionToken) {\n }\n}" }, { "alpha_fraction": 0.6312033534049988, "alphanum_fraction": 0.6328251957893372, "avg_line_length": 34.44827651977539, "blob_id": "e70c6c6ebd864c0aa75ce5d3b68252cbb031ed0b", "content_id": "17fc8bc65c37ffe2ade5741fddcda7010a1e9207", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 3083, "license_type": "no_license", "max_line_length": 90, "num_lines": 87, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/SourceInputDialog.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler\n\nimport android.app.Activity;\nimport android.content.DialogInterface;\nimport android.widget.EditText\nimport android.widget.LinearLayout;\nimport android.widget.Toast\n\nimport androidx.appcompat.app.AlertDialog;\nimport edu.mtu.sercsoundsampler.model.SourceListKeeper\n\nclass SourceInputDialog(val activity: Activity, val keeper: SourceListKeeper) {\n val context = activity.applicationContext\n val title = context.resources.getString(R.string.addSound)\n val prompt = context.resources.getString(R.string.prompt_for_name)\n val ok = context.resources.getString(R.string.ok)\n val cancel = context.resources.getString(R.string.cancel)\n val already = context.resources.getString(R.string.soundAlreadyAdded)\n\n fun show() {\n val rv = AlertDialog.Builder(activity)\n val input = EditText(activity)\n val inputLayout = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT\n , LinearLayout.LayoutParams.MATCH_PARENT)\n input.layoutParams = inputLayout\n rv.setView(input)\n .setTitle(title)\n .setMessage(prompt)\n .setNegativeButton(cancel, { d , i -> {}} )\n .setPositiveButton(ok, { d, i -> add(input) } )\n .show()\n }\n\n fun add(i: EditText) {\n val s = i.text.toString().trim();\n if (keeper.contains(s)) {\n Toast.makeText(context, already, Toast.LENGTH_SHORT).show()\n i.setText(R.string.empty)\n } else if (s.length > 0) keeper.add(s)\n }\n\n /*\n AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);\n alertDialog.setTitle(\"PASSWORD\");\n alertDialog.setMessage(\"Enter Password\");\n\n final EditText input = new EditText(MainActivity.this);\n LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(\n LinearLayout.LayoutParams.MATCH_PARENT,\n LinearLayout.LayoutParams.MATCH_PARENT);\n input.setLayoutParams(lp);\n alertDialog.setView(input);\n alertDialog.setIcon(R.drawable.key);\n\n alertDialog.setPositiveButton(\"YES\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n password = input.getText().toString();\n if (password.compareTo(\"\") == 0) {\n if (pass.equals(password)) {\n Toast.makeText(getApplicationContext(),\n \"Password Matched\", Toast.LENGTH_SHORT).show();\n Intent myIntent1 = new Intent(view.getContext(),\n Show.class);\n startActivityForResult(myIntent1, 0);\n } else {\n Toast.makeText(getApplicationContext(),\n \"Wrong Password!\", Toast.LENGTH_SHORT).show();\n }\n }\n }\n });\n\n alertDialog.setNegativeButton(\"NO\",\n new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int which) {\n dialog.cancel();\n }\n });\n\n alertDialog.show();\n}\n\n});\n\n */\n}" }, { "alpha_fraction": 0.6936745047569275, "alphanum_fraction": 0.695095956325531, "avg_line_length": 44.41935348510742, "blob_id": "0d1d1434f64dc0d20396559842397d38df6165f0", "content_id": "9c823762eca135fa64dc8d3be412f1710ca4878e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 99, "num_lines": 31, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/model/SERCSourceAdapter.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.model\n\nimport android.content.Context\nimport android.content.SharedPreferences\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.ArrayAdapter\nimport android.widget.Switch\nimport android.widget.TextView\nimport edu.mtu.sercsoundsampler.R\n\nclass SERCSourceAdapter(val cText: Context\n , val prefs: SharedPreferences\n , val helper: SERCPreferencesHelper\n , val keeper: SourceListKeeper, val db: SERCSoundDatabase)\n : ArrayAdapter<SERCSoundEntry>(cText, R.layout.source_item_layout) {\n override fun getCount(): Int { return keeper.getCount() }\n override fun getItem(p0: Int): SERCSoundEntry { return db.getEntry(keeper.getItem(p0)) }\n override fun getView(position: Int, view: View?, parent: ViewGroup): View {\n val rowView = if (view != null) view else\n LayoutInflater.from(context).inflate(R.layout.source_item_layout\n , null, false)\n var entry = db.getEntry(keeper.getItem(position))\n val nameView = rowView.findViewById<TextView>(R.id.srcTextView)\n nameView.text = entry.name\n val switch = rowView.findViewById<Switch>(R.id.srcOnOff)\n switch.setOnCheckedChangeListener { _, b -> db.sourceChanged(nameView.text.toString(), b) }\n return rowView\n }\n}" }, { "alpha_fraction": 0.8492063283920288, "alphanum_fraction": 0.8492063283920288, "avg_line_length": 125, "blob_id": "aac4e444c2cc347e2ef30d9cf655d22d8e2faefc", "content_id": "068c720daafca0b06bad1d6f2938161bfbd4d7ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 126, "license_type": "no_license", "max_line_length": 125, "num_lines": 1, "path": "/Android_Tensorflow_AudioClassifier-master/Android_Tensorflow_AudioClassifier-master/Readme.md", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "Android app that helps in music classification based on Tensorflow models with the application of MFCC processing techniques.\n" }, { "alpha_fraction": 0.6547085046768188, "alphanum_fraction": 0.6600896716117859, "avg_line_length": 22.63829803466797, "blob_id": "9934ef2e74d7075374989f2667abcc7f83debe0b", "content_id": "fddef728d3308ebdffda7d09c049c5a247075250", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 92, "num_lines": 47, "path": "/audio-characterizer/denoiser.py", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[8]:\n\n\nimport IPython\nfrom scipy.io import wavfile\nimport noisereduce as nr\nimport soundfile as sf\nfrom noisereduce.generate_noise import band_limited_noise\nimport matplotlib.pyplot as plt\nimport urllib.request\nimport numpy as np\nimport io\nimport os\n\nimport noisereduce as nr\nfrom scipy.io import wavfile\n\nfrom pydub import AudioSegment\n\n\nfor filename in os.listdir(\"test\"):\n if filename.endswith(\".wav\"):\n # Turn the sound into mono\n sound = AudioSegment.from_wav(filename)\n sound = sound.set_channels(1)\n sound.export(filename, format=\"wav\")\n\n #load data \n rate, data = wavfile.read(filename) \n data = data / 1.0\n print(len(data))\n # select section of data that is noise \n noisy_part = data[0:len(data)] \n # perform noise reduction \n reduced_noise = nr.reduce_noise(audio_clip=data,noise_clip=noisy_part, verbose=True)\n\n #load the new version into a file\n wavfile.write(\"out_\" + filename, rate, reduced_noise)\n continue\n else:\n continue\n\n\n# In[ ]:\n\n\n\n\n" }, { "alpha_fraction": 0.704026460647583, "alphanum_fraction": 0.7058293223381042, "avg_line_length": 40.0987663269043, "blob_id": "20bfb5ae8539c059336e7dd17586ac45714ce2c9", "content_id": "f27d78b13fb33262cb6bfc0501e8269ccd42287c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 3328, "license_type": "no_license", "max_line_length": 114, "num_lines": 81, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/SERCSamplingAllInOneActivity.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler\n\nimport android.Manifest\nimport android.content.Context\nimport android.content.SharedPreferences\nimport android.os.Bundle\nimport android.os.Environment\nimport android.util.Log\nimport androidx.appcompat.app.AppCompatActivity\nimport com.karumi.dexter.Dexter\nimport edu.mtu.sercsoundsampler.model.SERCPreferencesHelper\nimport edu.mtu.sercsoundsampler.model.SERCSoundDatabase\nimport edu.mtu.sercsoundsampler.model.SERCSourceAdapter\nimport edu.mtu.sercsoundsampler.model.SourceListKeeper\nimport edu.mtu.sercsoundsampler.services.SERCSampler\nimport kotlinx.android.synthetic.main.sample_and_rate_ctl_layout.*\nimport java.io.File\n\n/** SampleTypeManagerActivity - Manage a list of sounds you want to capture\n *\n * 04 Feb 2021\n *\n *\n */\nclass SERCSamplingAllInOneActivity : AppCompatActivity() {\n companion object {\n val TAG = SERCSamplingAllInOneActivity::class.java.simpleName\n val KEY_PREFS = \"${TAG}.PREFS\"\n }\n lateinit var prefs: SharedPreferences\n lateinit var helper: SERCPreferencesHelper\n lateinit var sampler: SERCSampler\n lateinit var db: SERCSoundDatabase\n lateinit var keeper: SourceListKeeper\n lateinit var adapter: SERCSourceAdapter\n val multiListener: MultiListener = MultiListener()\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n Log.d(TAG, \"onCreate...\")\n Dexter.withContext(this)\n .withPermissions(\n Manifest.permission.WRITE_EXTERNAL_STORAGE,\n Manifest.permission.ACCESS_FINE_LOCATION,\n Manifest.permission.RECORD_AUDIO)\n .withListener(multiListener)\n .check()\n if (multiListener.proceed) {\n Log.i(TAG, \"Premissions granted, here we go...\")\n }\n prefs = applicationContext.getSharedPreferences(KEY_PREFS, Context.MODE_PRIVATE)\n helper = SERCPreferencesHelper(prefs)\n val useAppFolder = false\n var serc: File? = null\n if (useAppFolder) {\n serc = File(applicationInfo.dataDir, \"serc\")\n } else {\n// var download: File? = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)\n var download: String? = Environment.getExternalStorageDirectory().toString()\n serc = File(download!!, \"serc\")\n download = null\n }\n serc!!.mkdir()\n sampler = SERCSampler(prefs, helper, multiListener, serc!!.canonicalPath)\n serc = null\n keeper = SourceListKeeper(applicationContext.resources.getString(R.string.bad_item), sampler, helper)\n db = SERCSoundDatabase(applicationContext.resources.getString(R.string.bad_item), sampler)\n adapter = SERCSourceAdapter(applicationContext, prefs, helper, keeper, db)\n //requestWindowFeature(Window.FEATURE_NO_TITLE)\n setContentView(R.layout.sample_and_rate_ctl_layout_ref)\n samplingSources.adapter = adapter\n \"${sampler!!.getSampleSecondLength()}\".also { sampleLength.setText(it) }\n \"${sampler!!.getSampleSecondInterval()}\".also { sampleInterval.setText(it) }\n addSource.setOnClickListener { SourceInputDialog(this, keeper).show() }\n //sampleLength.setOnClickListener { sampleLength.setText(\"\"); }\n }\n\n fun showNameDialog() {\n\n }\n}" }, { "alpha_fraction": 0.6100746393203735, "alphanum_fraction": 0.6156716346740723, "avg_line_length": 36.41860580444336, "blob_id": "6ac0df911d57ab7a971e4c03becf662ffba0ba98", "content_id": "6b05f290c2365cd7278421708c4dd1a70e967213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1608, "license_type": "no_license", "max_line_length": 100, "num_lines": 43, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/model/SERCPreferencesHelper.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.model\n\nimport android.content.SharedPreferences\nimport java.util.*\nimport kotlin.collections.ArrayList\n\nclass SERCPreferencesHelper(val prefs: SharedPreferences) {\n fun preserveString(key: String, value: String) { prefs.edit().putString(key, value)!!.commit() }\n fun preserveLong(key: String, value: Long) { prefs.edit().putLong(key, value)!!.commit() }\n\n fun recallIndex(pref: String, arr: List<String>, defaultInt: Int): Int {\n var value: String? = prefs.getString(pref, \"\")\n return if (value != \"\") indexWithDefault(value!!, arr, defaultInt) else defaultInt\n }\n fun indexWithDefault(value: String, arr: List<String>, defaultInt: Int): Int {\n var rv: Int = if (arr.indexOf(value) >= 0) arr.indexOf(value) else defaultInt\n return rv\n }\n\n /*\n add: key.fan -> fan,0\n add key.lawnmower -> lawnmower,0; fan,1\n 0,fan\n 0,lawnmower; 1,fan\n */\n fun preserveList(key: String, array: List<String>) {\n array.forEachIndexed { i, s -> prefs.edit().putInt(\"${key}.${s}\",i)!!.commit() }\n val ts = TreeSet<String>(array)\n prefs.edit().putStringSet(key, ts)!!.commit()\n }\n fun recallList(key: String): ArrayList<String> {\n var rv = ArrayList<String>()\n var ts = TreeSet<String>(prefs.getStringSet(key, TreeSet<String>()))\n val tm = TreeMap<Int, String>()\n for (s in ts) {\n val i = prefs.getInt(\"${key}.${s}\", -1)\n if (i != -1) tm.put(i, s)\n }\n return ArrayList(tm.values)\n }\n fun clearAll() { prefs.edit().clear().apply() }\n\n}" }, { "alpha_fraction": 0.708376944065094, "alphanum_fraction": 0.7120419144630432, "avg_line_length": 32.52631759643555, "blob_id": "0c505e406969c42235760eb7440ba5ea2e5b8d7a", "content_id": "b2d660756072915018180d60491e532eb58dd094", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1910, "license_type": "no_license", "max_line_length": 119, "num_lines": 57, "path": "/SERCSoundSampler/app/src/androidTest/java/edu/mtu/sercsoundsampler/TestSourceListKeeper.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler\n\nimport android.content.Context\nimport android.content.SharedPreferences\nimport androidx.test.platform.app.InstrumentationRegistry\nimport androidx.test.ext.junit.runners.AndroidJUnit4\nimport edu.mtu.sercsoundsampler.model.SERCPreferencesHelper\nimport edu.mtu.sercsoundsampler.model.SERCSoundDatabase\nimport edu.mtu.sercsoundsampler.model.SERCSourceAdapter\nimport edu.mtu.sercsoundsampler.model.SourceListKeeper\n\nimport org.junit.Test\nimport org.junit.runner.RunWith\n\nimport org.junit.Assert.*\nimport org.junit.Before\n\n/**\n * Instrumented test, which will execute on an Android device.\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\n@RunWith(AndroidJUnit4::class)\nclass TestSourceListKeeper {\n val prefs: SharedPreferences\n val adapter: SERCSourceAdapter\n val helper: SERCPreferencesHelper\n val keeper: SourceListKeeper\n val db: SERCSoundDatabase\n init {\n val appContext = InstrumentationRegistry.getInstrumentation().targetContext\n prefs = appContext.getSharedPreferences(SERCSamplingAllInOneActivity.KEY_PREFS + \"_TEST\", Context.MODE_PRIVATE)\n helper = SERCPreferencesHelper(prefs)\n keeper = SourceListKeeper(helper)\n db = SERCSoundDatabase(appContext.resources.getString(R.string.bad_item))\n adapter = SERCSourceAdapter(appContext, prefs, helper, keeper, db)\n }\n @Before\n fun setUp() {\n helper.clearAll()\n }\n @Test\n fun ignoreDuplicateAdd() {\n keeper.add(\"Fan\")\n keeper.add(\"Fan\")\n keeper.add(\"Lawnmower\")\n assertEquals(\"Expect 2\", 2, keeper.list().size)\n }\n @Test\n fun preserveOrder() {\n keeper.add(\"C\")\n keeper.add(\"B\")\n keeper.add(\"A\")\n assertEquals(\"Expect A as the zeroth element\", \"A\", keeper.list()[0])\n assertTrue(\"a-b-c\", \"B\" == keeper.list()[1] && \"C\" == keeper.list()[2])\n }\n}" }, { "alpha_fraction": 0.805084764957428, "alphanum_fraction": 0.805084764957428, "avg_line_length": 13.875, "blob_id": "08c2a0a48234528aaee1c87971dcefca37dd9d5c", "content_id": "1ad535d7d747bd8f8d248a315a227f5623237326", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 118, "license_type": "no_license", "max_line_length": 41, "num_lines": 8, "path": "/SERCSoundSampler/app/src/test/java/edu/mtu/sercsoundsampler/services/TestSERCSampler.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.services\n\nimport org.junit.Test\n\nimport org.junit.Assert.*\n\nclass TestSERCSampler {\n}" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7833333611488342, "avg_line_length": 29.125, "blob_id": "61a2e097c06aa2535bf61b4ff77cec9d61ce9388", "content_id": "a0467282449c29c3f939e03f3303ccd1a6a7d3b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 240, "license_type": "no_license", "max_line_length": 42, "num_lines": 8, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/model/SERCSoundEntry.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.model\n\nclass SERCSoundEntry(val name: String) {\n var countMarkedSamples = 0\n var countPotentialDetectedSamples = 0\n var countConfirmedDetectedSamples = 0\n var countConfirmedIncorrectSamples = 0\n}" }, { "alpha_fraction": 0.5916515588760376, "alphanum_fraction": 0.5934664011001587, "avg_line_length": 28.810810089111328, "blob_id": "2bb7590b7fd57d08ac34812e60ebb4d44cbad2dc", "content_id": "938b80d4ec3920bf352392348a966cc274fe7bbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 100, "num_lines": 37, "path": "/SERCSoundSampler/app/src/main/java/edu/mtu/sercsoundsampler/model/SERCSourceListKeeper.kt", "repo_name": "esteve-ship-it/serc", "src_encoding": "UTF-8", "text": "package edu.mtu.sercsoundsampler.model\n\nimport edu.mtu.sercsoundsampler.services.SERCSampler\n\nclass SourceListKeeper(val s: String, val sampler: SERCSampler, val helper: SERCPreferencesHelper) {\n var adapter: SERCSourceAdapter? = null\n companion object {\n val TAG = \"SourceListKeeper\"\n val KEY_SOURCE_LIST = \"edu.mtu.src.list\"\n }\n fun add(source: String) {\n var array: ArrayList<String> = helper.recallList(KEY_SOURCE_LIST)\n if (!contains(source)) {\n array.add(0, source)\n helper.preserveList(KEY_SOURCE_LIST, array)\n adapter?.notifyDataSetChanged()\n }\n }\n fun getCount(): Int {\n return list().size\n }\n fun getItem(i: Int): String? {\n val el = list()\n return if (i >= 0 && i < el.size) el[i] else null\n }\n fun contains(s: String): Boolean {\n var rv = false\n list().map { if (it.equals(s, true)) rv = true }\n return rv\n }\n fun list(): List<String> {\n return helper.recallList(KEY_SOURCE_LIST)\n }\n fun clear() {\n helper.clearAll()\n }\n}" } ]
15
Real-VeerSandhu/Computational-Conversions
https://github.com/Real-VeerSandhu/Computational-Conversions
be7272e6c4071e1dcb8e25cb91728727f8ec04af
2cff0242009bb807441a14009916669706de7d22
678a61446e32c4a32d68ae1ace953a214d7c31ff
refs/heads/master
2023-06-16T09:22:37.529102
2021-07-13T15:23:00
2021-07-13T15:23:00
385,648,908
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.8284313678741455, "alphanum_fraction": 0.8284313678741455, "avg_line_length": 101, "blob_id": "cabb441146d7b8eaa1b2bae44669d1810e418c39", "content_id": "60787c510f7196db11579d75392042f2f9663986", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 204, "license_type": "no_license", "max_line_length": 175, "num_lines": 2, "path": "/README.md", "repo_name": "Real-VeerSandhu/Computational-Conversions", "src_encoding": "UTF-8", "text": "# Computational Conversions\nThis repository contains python programs that perform conversions through decimal, binary, hexadecimal, ASCII, and more. In the future, encryption programs will also be built. " }, { "alpha_fraction": 0.5366834402084351, "alphanum_fraction": 0.5457286238670349, "avg_line_length": 22.5238094329834, "blob_id": "ba320fb91a210b1ec56eec879f4c6169241fe41c", "content_id": "82933092cd08cd6d727e328e75deacc8275dcb32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 995, "license_type": "no_license", "max_line_length": 58, "num_lines": 42, "path": "/binary-decimal.py", "repo_name": "Real-VeerSandhu/Computational-Conversions", "src_encoding": "UTF-8", "text": "def binary_decimal(input):\n total = 0\n str_binary = str(input)[::-1]\n for i in range(len(str_binary)):\n total += 2**int(i) * int(str_binary[i])\n return total\n\ndef decimal_binary(input):\n if input >= 1:\n decimal_binary(input // 2)\n global x\n x.append(input % 2)\n return x\n\n# Inputs\n\nfirst = input('\\nInput integer (I) or binary (B): ')\n\ncheck = False\nwhile check == False:\n if (first == 'I' or first == 'B'):\n check == True\n print('-'*50)\n break\n else:\n check == False\n print('\\n*Invalid, enter again*\\n')\n first = input('Input decimal (I) or binary (B): ')\n\n\n# Find route\nif first == 'B':\n binary = int(input('Enter binary value: '))\n print('Decimal/Integer value: ', end='')\n print(binary_decimal(binary))\nelse:\n integer = int(input('Enter integer value: '))\n print('Binary value: ', end='')\n x = []\n for i in (decimal_binary(integer)[1:]):\n print(i, end='')\n print('')\n \n\n\n" } ]
2
NikoriakViktot/task_16
https://github.com/NikoriakViktot/task_16
6f306da2b489fc041aed09a4fd945f033e8adfbe
b0a8536a3e08c01043ffbc933465819caac51c99
689180d15f59aa0479d6ba2634650f56d2d27d77
refs/heads/main
2023-08-07T14:44:58.069176
2021-08-19T08:24:45
2021-08-19T08:24:45
397,870,112
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6304198503494263, "alphanum_fraction": 0.6455609202384949, "avg_line_length": 23.875, "blob_id": "ce29d4f806801c71c1d2295804b37ee7e247cabc", "content_id": "b24fb0062040b489c73309e141549e7c99c2bdeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1496, "license_type": "no_license", "max_line_length": 92, "num_lines": 56, "path": "/task_16.py", "repo_name": "NikoriakViktot/task_16", "src_encoding": "UTF-8", "text": "#task1\r\n# Create your own implementation of a built - in function enumerate, named\r\n# `with_index`, which takes two parameters: `iterable` and `start`, default is 0.\r\n# Tips: see the documentation for the enumerate function\r\n\r\nl1 = ['один','два','три']\r\nstart = 1\r\ndef with_index(iterable, start):\r\n a_list = []\r\n for i in range(len(iterable)):\r\n a_list.append((i + start, iterable[i]))\r\n return a_list\r\nprint(with_index(l1, start))\r\nprint('Я функція enumerate')\r\nprint(list(enumerate(l1, 1)))\r\n\r\n\r\n#task2\r\n# Create your own implementation of a built-in function range, named in_range(), which takes\r\n# three parameters: `start`, `end`, and optional step.\r\n# Tips: See the documentation for `range` function\r\n\r\ndef in_range(start,end,step):\r\n print(start)\r\n while start + step < end:\r\n start += step\r\n print(start)\r\nin_range(10,20,1)\r\nprint('Я функція range')\r\nx = range(10, 20, 1)\r\nfor n in x:\r\n print(n)\r\n\r\n\r\n\r\n\r\n#task3\r\n# Create your own implementation of an iterable, which could be used inside for-in loop.\r\n# Also, add logic for retrieving elements using square brackets syntax.\r\nprint('Я функція iter')\r\ndef iterable(low, high):\r\n current = low\r\n while current < high:\r\n yield current\r\n current += 1\r\n\r\nfor c in iter(iterable(1, 4)):\r\n print(c)\r\n\r\nmy = (\"oдин\", \"два\", \"три\")\r\nfor x in my:\r\n print(x)\r\nmy_iter = iter(my)\r\nprint(next(my_iter))\r\nprint(next(my_iter))\r\nprint(next(my_iter))\r\n\r\n\r\n" } ]
1
FranciscoCasado/calan_utils
https://github.com/FranciscoCasado/calan_utils
acdba35ccb2897f8c1a8cbe3bf8f637de23945d5
9a710c962ce5a10a81098a367dd4a385500ca464
da2986ef4ff777871a3701e67ba7e932f9114582
refs/heads/master
2021-07-24T09:16:36.812307
2017-10-28T03:01:16
2017-10-28T03:01:16
107,342,418
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.622710645198822, "alphanum_fraction": 0.6300366520881653, "avg_line_length": 21.75, "blob_id": "8b803173741cc8e1660486a7ae2499aa8b581527", "content_id": "ff3ead55256fd8ff6d147e1e6d52b2e0229b46a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/setup.py", "repo_name": "FranciscoCasado/calan_utils", "src_encoding": "UTF-8", "text": "from distutils.core import setup\n\nsetup(\n name='calan_utils',\n version='0.1',\n packages=['calan_utils','calan_utils.rf_sources'],\n url='',\n license='rob_license',\n author='Roberto Fuentes',\n author_email='[email protected]',\n description='clases usadas comunmente',\n)\n" }, { "alpha_fraction": 0.5965040326118469, "alphanum_fraction": 0.6117990016937256, "avg_line_length": 29.53333282470703, "blob_id": "a61b8ae4991140945d0f07a01bcaa2201ab552a1", "content_id": "536df8565d3adc7326aeb7da5fc0211f7ac54e73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1373, "license_type": "no_license", "max_line_length": 98, "num_lines": 45, "path": "/calan_utils/rf_sources/generic.py", "repo_name": "FranciscoCasado/calan_utils", "src_encoding": "UTF-8", "text": "import socket\nimport telnetlib\n\nimport time\n\n\nclass Source(object):\n \"\"\"this class has some method to interac whit the calan_utils\"\"\"\n def __init__(self, ip, port=5025, power=-100):\n\n \"\"\"\n\n :param ip: the ip of the equipment, be sure to be able to do a successfull ping (at least)\n :param port: the port where the protocol is implemnted. This is no always the same\n :param power: the initial power value in dBm, ny defaut it's -100 dB\n \"\"\"\n self.ip = ip\n self.port = port\n self.power = power\n\n try:\n self.connection = telnetlib.Telnet(self.ip, self.port) # for test purpuses timeout=3)\n except socket.error, exc:\n raise Exception('Connection fail, to ip:{equipment_ip}'.format(equipment_ip=self.ip))\n\n self.connection.write('power %s dbm\\r\\n' % self.power)\n\n def turn_on(self):\n self.connection.write('outp on\\r\\n')\n time.sleep(0.1)\n\n def change_frequency_hz(self, frequency):\n freq = max(frequency, 9000)\n self.connection.write('freq %s\\r\\n' % str(freq))\n time.sleep(0.5)\n\n def turn_off(self):\n self.connection.write('outp off\\r\\n')\n time.sleep(0.1)\n\n def stop_source(self):\n self.connection.close()\n\n def set_power(self, new_power):\n self.connection.write('power %s dbm\\r\\n' % new_power)" }, { "alpha_fraction": 0.760765552520752, "alphanum_fraction": 0.760765552520752, "avg_line_length": 19.899999618530273, "blob_id": "82998d1eac28c9ade4d812f10fdc940ba8e0cae9", "content_id": "449bb7e15a2d86679708c7461df2830db0593416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 209, "license_type": "no_license", "max_line_length": 50, "num_lines": 10, "path": "/README.md", "repo_name": "FranciscoCasado/calan_utils", "src_encoding": "UTF-8", "text": "This library is thought to make ur work easier.\n\nFor now it contains:\n -Connection to the sources\n\nUsage:\n\n\tfrom calan_utils.rf_sources.generic import Source\n\nEvery piece of code has been written by Roberto Fuentes\n" } ]
3
Spudar-Men/Hang_man
https://github.com/Spudar-Men/Hang_man
16938dd3f14211fa84f9f73529872d00b882ea7c
9d5b45e6b0cf40ae3a6549735a0bc70fc744025b
5babbc5cadc2fad816a85a18dc07fed52baafafa
refs/heads/master
2020-09-21T00:35:43.597496
2019-12-06T10:45:54
2019-12-06T10:45:54
224,630,011
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6888726353645325, "alphanum_fraction": 0.6939970850944519, "avg_line_length": 29.377777099609375, "blob_id": "3e37a3ad8f4e449efb144c91f1376affe091db37", "content_id": "b6920dc561f6aa525aa1d83460e4245f152bb412", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 91, "num_lines": 45, "path": "/main.py", "repo_name": "Spudar-Men/Hang_man", "src_encoding": "UTF-8", "text": "from string_of_words import list_of_words\nfrom string_of_words import print_playfield\nfrom string_of_words import find\nfrom more_itertools import locate\nimport random\nimport replit\n\n\nrand_word = random.choice(list_of_words) #draws random word from list out 49 possible words\nprint(\"Cheat mode on. Word is: \" + rand_word)\n\nindexPosList = 0\nplayfield = []\nfor letter in rand_word:\n playfield.append(\"[_]\")\nprint_playfield(playfield)\nprint()\n\nplayer_guess = \"\" #create empty string that will contain imput from player\nwin = False #Starts at False and is changed when win state is achieved\nplayer_attempts = 3\nprint(\"Len of playfield is \" + str(len(playfield)))\nplayer_guess = \"\"\nwhile player_attempts > 0 and win == False:\n print(\"Player Attempts: \" + str(player_attempts))\n while len(player_guess) != 1 or player_guess == \"\":\n player_guess = input(\"Please guess one letter from the secret Hangman word: \")\n for letter in rand_word:\n if letter == player_guess:\n indexPosList = list(locate(rand_word, lambda a: a == letter))\n for item in indexPosList:\n playfield[item] = letter\n if player_guess not in rand_word:\n player_attempts -= 1\n replit.clear()\n print_playfield(playfield)\n print()\n player_guess = \"\"\n if \"[_]\" not in playfield:\n win = True\nelse:\n if win == True:\n print(\"You Won!\")\n else:\n print(\"You Lost!\")" }, { "alpha_fraction": 0.7783251404762268, "alphanum_fraction": 0.7807881832122803, "avg_line_length": 12.112903594970703, "blob_id": "2f50177722c07cde08b4748a4e0855d5c076ddfc", "content_id": "fcd0b4281d9b4351b87dbf0c9f179c19030ed0ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 812, "license_type": "no_license", "max_line_length": 98, "num_lines": 62, "path": "/string_of_words.py", "repo_name": "Spudar-Men/Hang_man", "src_encoding": "UTF-8", "text": "#Contains string and list of 49 words and functions\nwords = \"\"\"\nAwkward\nBagpipes\nBanjo\nBungler\nCroquet\nCrypt\nDwarves\nFervid\nFishhook\nFjord\nGazebo\nGypsy\nHaiku\nHaphazard\nHyphen\nIvory\nJazzy\nJiffy\nJinx\nJukebox\nKayak\nKiosk\nKlutz\nMemento\nMystify\nNumbskull\nOstracize\nOxygen\nPajama\nPhlegm\nPixel\nPolka\nQuad\nQuip\nRhythmic\nRogue\nSphinx\nSquawk\nSwivel\nToady\nTwelfth\nUnzip\nWaxy\nWildebeest\nYacht\nZealous\nZigzag\nZippy\nZombie\n\"\"\"\nwords = words.lower() #removes uppercase characters\nlist_of_words = words.split() #creates list from string and sets each word into a separate element\n\ndef print_playfield(playfield):\n for i in playfield:\n print(i, end = \" \")\n\n#creates function that returns the indices of each instance of a specific character in in string\ndef find(s, ch):\n return [i for i, ltr in enumerate(s) if ltr == ch]" } ]
2
academiaeh05-2019/d303-exercicio-oo
https://github.com/academiaeh05-2019/d303-exercicio-oo
1419c457cf74ee58cd6f57e0a8e58a9d4fc5dcc4
49ce8263420e189be8c9d6d78b0af4dd537ad1e1
8d62a9e2e4a5e66c8b33dbbb381b2ca59766a020
refs/heads/master
2022-02-25T09:00:10.952115
2019-07-25T16:55:49
2019-07-25T16:55:49
197,794,018
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.5338645577430725, "alphanum_fraction": 0.5484727621078491, "avg_line_length": 21.75757598876953, "blob_id": "b5e4c1df2bb75abccc9cbf3b857281a71eb9f511", "content_id": "57adf75ba0e3d31ed9f7ccb3057e4b228ea3fd4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 753, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/classes.py", "repo_name": "academiaeh05-2019/d303-exercicio-oo", "src_encoding": "UTF-8", "text": "from random import randint\n\n\nclass Cliente:\n def __init__(self, nome, cpf):\n self.nome = nome\n self.cpf = cpf\n\nclass Conta:\n def __init__(self, cliente):\n self.titular = cliente\n self.numero = self._gerar()\n self._saldo = 0\n\n def extrato(self):\n print(f'Numero: {self.numero}\\nSaldo: {self._saldo}')\n\n def depositar(self, valor):\n self._saldo += valor\n\n def sacar(self, valor):\n if(self._saldo < valor):\n return False\n else:\n self._saldo -= valor\n return True\n\n def consultar_saldo(self):\n return self._saldo\n\n def _gerar(self):\n self.random_num = f'{randint(1000, 9999)}-{randint(1, 9)}'\n return self.random_num\n\n\n" }, { "alpha_fraction": 0.8260869383811951, "alphanum_fraction": 0.8260869383811951, "avg_line_length": 22.16666603088379, "blob_id": "f8b942ea86fe1e690e62dca7d2eff47ec962f4be", "content_id": "29f7ad93692b0ab6d2ac730a37f12f119b96220b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/main.py", "repo_name": "academiaeh05-2019/d303-exercicio-oo", "src_encoding": "UTF-8", "text": "from interface import CaixaEletronico\n\ncaixa_eletronico = CaixaEletronico()\n\ncaixa_eletronico.exibir_menu()\ncaixa_eletronico.exibir_menu()" }, { "alpha_fraction": 0.6042240858078003, "alphanum_fraction": 0.6097337007522583, "avg_line_length": 23.772727966308594, "blob_id": "298c801f2234d4c5c474612744e698f04ef22276", "content_id": "5088270086cde3744907bf8a09eae73d5655db15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1098, "license_type": "no_license", "max_line_length": 79, "num_lines": 44, "path": "/interface.py", "repo_name": "academiaeh05-2019/d303-exercicio-oo", "src_encoding": "UTF-8", "text": "from classes import Cliente, Conta\n\n\nclass CaixaEletronico():\n def __init__(self):\n nome = input('Digite seu nome: ')\n cpf = input('Digite seu CPF: ')\n\n cliente = Cliente(nome, cpf)\n self._conta = Conta(cliente)\n\n print(f'Olá, {self._conta.titular.nome}, sua conta é {self._conta.numero}')\n\n def exibir_menu(self):\n print(f'1- Consultar saldo\\n2- Depositar\\n3- Sacar')\n escolha = input('Escolha uma opção: ')\n\n if escolha == '1':\n self.exibir_saldo()\n elif escolha == '2':\n self.depositar()\n elif escolha == '3':\n self.sacar()\n else:\n print('Opção inválida.')\n\n def exibir_saldo(self):\n valor = str(self._conta.consultar_saldo())\n print(f'Seu saldo é R$ {valor}.')\n\n def depositar(self):\n valor = float(input('Digite o valor: '))\n self._conta.depositar(valor)\n print('Depósito efetuado.')\n self.exibir_saldo()\n\n def sacar(self):\n valor = float(input('Digite o valor: '))\n \n if self._conta.sacar(valor):\n print('Saque efetuado.')\n self.exibir_saldo()\n else:\n print('Saldo insuficiente.')" }, { "alpha_fraction": 0.627135694026947, "alphanum_fraction": 0.6532663106918335, "avg_line_length": 17.44444465637207, "blob_id": "3d476f9373941f1e6441b3bf9077b703e486c9ab", "content_id": "414de9fdeba8163d5e0ff067a5860f9653be6da9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1018, "license_type": "no_license", "max_line_length": 88, "num_lines": 54, "path": "/readme.md", "repo_name": "academiaeh05-2019/d303-exercicio-oo", "src_encoding": "UTF-8", "text": "## Criar um sistema que simula o funcionamento de um banco\nO sistema deve ser criar usando os conceitos de orientação à objetos aprendidos em aula.\n\nPode ser feito em dupla ou individualmente.\n\nO exercício terá sua correção publicado no dia 23/07.\n\n### 1. O sistema permite que o cliente se cadastre:\n \n```\n \"Digite seu nome:\"\n \"Digite seu cpf:\"\n```\n\n### 2. O sistema cria uma conta automaticamente para o cliente\n\n```\n \"Olá João, sua conta é 1234-1\"\n```\n\n### 3. Após a criação da conta, o sistema exibe um menu:\n\n```\n \"1- Consultar saldo\"\n \"2- Depositar\"\n \"3- Sacar\"\n```\n\n### Caso o cliente escolha a opção 1:\n\n```\n \"Seu saldo é R$ 0\"\n```\n\n### Caso o cliente escolha a opção 2:\n\n```\n \"Digite o valor: \"\n \"Depósito efetuado. Seu novo saldo é R$ 500\"\n```\n\n### Caso o cliente escolha a opção 3:\n\n```\n \"Digite o valor: \"\n \"Saque efetuado. Seu novo saldo é R$ 100\"\n```\n\n### Caso o cliente escolha a opção 3 e o saldo seja insuficiente:\n\n``` \n \"Digite o valor: \"\n \"Saldo insuficiente\"\n```" } ]
4
andreacavagna01/fedex-day-multi-function
https://github.com/andreacavagna01/fedex-day-multi-function
031958b7dbc24b5b1e5d74783b4e9173aee2de46
0f30394f519267f24b5952449f27acf48114c778
48491630c52bf37bced475d7cccc786f3fef7aab
refs/heads/main
2022-12-31T23:12:24.564293
2020-10-16T14:42:55
2020-10-16T14:42:55
304,563,301
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7509225010871887, "alphanum_fraction": 0.7749077677726746, "avg_line_length": 30.941177368164062, "blob_id": "fe70c385251468dfe6c5c35f201c27ec5492b62f", "content_id": "454a0a75308c10a47ce07c18e3b5c9ab653642bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C#", "length_bytes": 542, "license_type": "no_license", "max_line_length": 101, "num_lines": 17, "path": "/src/azure/function.csx", "repo_name": "andreacavagna01/fedex-day-multi-function", "src_encoding": "UTF-8", "text": "#r \"Newtonsoft.Json\"\n\nusing System.Net;\nusing Microsoft.AspNetCore.Mvc;\nusing Microsoft.Extensions.Primitives;\nusing Newtonsoft.Json;\nusing System.Net.Http;\nusing System.Net.Http.Headers;\n\nprivate static readonly HttpClient client = new HttpClient();\n\npublic static async Task<IActionResult> Run(HttpRequest req, ILogger log)\n{\n client.DefaultRequestHeaders.Add(\"X-Vault-Token\", \"s.wS59C22PZF83UMD1pukYWJ4m\");\n var responseString = await client.GetStringAsync(\"http://34.245.5.31:8200/v1/cubbyhole/besharp\");\n return new OkObjectResult(responseString);\n}" }, { "alpha_fraction": 0.5603216886520386, "alphanum_fraction": 0.6219838857650757, "avg_line_length": 23.600000381469727, "blob_id": "bb046c8581d4daabc9b92b0dbfbdeabd70a110df", "content_id": "832cb4155c851c6238cf901a4010b96d7653fb71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 93, "num_lines": 15, "path": "/src/function.py", "repo_name": "andreacavagna01/fedex-day-multi-function", "src_encoding": "UTF-8", "text": "import json\nimport requests\n\ndef lambda_handler(event, context):\n headers = {\n 'X-Vault-Token': 's.wS59C22PZF83UMD1pukYWJ4m',\n }\n\n response = requests.get('http://34.245.5.31:8200/v1/cubbyhole/besharp', headers=headers)\n print(response.json())\n # TODO implement\n return {\n 'statusCode': 200,\n 'body': response.json()\n }\n\n\n\n\n" }, { "alpha_fraction": 0.761904776096344, "alphanum_fraction": 0.761904776096344, "avg_line_length": 9.5, "blob_id": "71ae1752e479fda40818c854bc646192c46d6302", "content_id": "154f77c2eb98de0c530dc485e4f6747d0159ccc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 42, "license_type": "no_license", "max_line_length": 26, "num_lines": 4, "path": "/README.md", "repo_name": "andreacavagna01/fedex-day-multi-function", "src_encoding": "UTF-8", "text": "# fedex-day-multi-function\n\n#claudio\ntest\n" } ]
3
olgarozhdestvina/dataRepresentation
https://github.com/olgarozhdestvina/dataRepresentation
7415685c1f3592ddaba32ca68fece25cc71ab0c1
d113255f8917fda9046b6a762ac83e9be0f06aba
99be5a7cbc7d6be93fb262a6de27ebe4900d12a4
refs/heads/master
2023-01-11T01:44:58.007484
2020-11-13T02:27:59
2020-11-13T02:27:59
298,201,812
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5965909361839294, "alphanum_fraction": 0.6278409361839294, "avg_line_length": 18.054054260253906, "blob_id": "9c63c1aba80f64224ea7204b475506397d0b9c16", "content_id": "6e5c8046fce40bf0207625efb538a96037b5c07c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 704, "license_type": "permissive", "max_line_length": 36, "num_lines": 37, "path": "/Labs/week06/Lab-06.01-access-server.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "# Use Python to access Server\nimport requests\nimport json\nfrom xlwt import *\n\nurl = 'http://127.0.0.1:5000/cars'\n\nresponse = requests.get(url)\ndata = response.json()\n#print(data)\n\n# print cars individually\nfor car in data['cars']:\n print(car)\n\nfile = 'cars.json'\nif file:\n # writing jason data\n with open(file,'w') as f:\n json.dump(data, f, indent=4)\n\nw = Workbook()\nws = w.add_sheet('cars')\nrow = 0\nws.write(row,0,\"reg\")\nws.write(row,1,\"make\")\nws.write(row,2,\"model\")\nws.write(row,3,\"price\")\nrow += 1\n\nfor car in data[\"cars\"]:\n ws.write(row,0,car[\"reg\"])\n ws.write(row,1,car[\"make\"])\n ws.write(row,2,car[\"model\"])\n ws.write(row,3,car[\"price\"])\n row += 1\nw.save('cars.xls')" }, { "alpha_fraction": 0.7392995953559875, "alphanum_fraction": 0.7509727478027344, "avg_line_length": 27.66666603088379, "blob_id": "5d53535c226a0d92595586db272dc7a513fc864a", "content_id": "19a0585515e8ce999d9e70cc79b9b9a472579cd0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "permissive", "max_line_length": 83, "num_lines": 9, "path": "/Exercises/e3.1.testRequest.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\npage = requests.get(\"https://dataquestio.github.io/web-scraping-pages/simple.html\")\nprint(page)\nprint(\"\\n________\")\nprint(page.content)\nsoup1 = BeautifulSoup(page.content, 'html.parser')\nprint(soup1.prettify())" }, { "alpha_fraction": 0.7220843434333801, "alphanum_fraction": 0.7245657444000244, "avg_line_length": 21.44444465637207, "blob_id": "34907a032db6b329d5e3c21362094e24f11e7da9", "content_id": "385320ae91b622b6603f524ca36744821123aebf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "permissive", "max_line_length": 69, "num_lines": 18, "path": "/Labs/week06/Lab-06.01-read-from-github.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests, json\nfrom xlwt import *\nimport pandas as pd\n\nurl = 'https://api.github.com/users/andrewbeattycourseware/followers'\n\nresponse = requests.get(url)\ndata = response.json()\n#print(data)\n\n# save as a JSON file\nfile = 'followers.json'\nwith open(file,'w') as f:\n json.dump(data,f, indent=4)\n\n# save as s spreadsheet\ndf_json = pd.read_json('followers.json')\ndf_json.to_excel('followers.xlsx')" }, { "alpha_fraction": 0.5537189841270447, "alphanum_fraction": 0.6404958963394165, "avg_line_length": 16.35714340209961, "blob_id": "accf500987763b985fdd858bbb098fbb33755c90", "content_id": "7b7bf242f33f48b2d47d8de7b924cc67d34f7e8b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "permissive", "max_line_length": 46, "num_lines": 14, "path": "/Labs/week06/Lab-06.01-create-car-API.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\ndataString = {\n 'reg': '46 OE 4567',\n 'make':'Ford',\n 'model': 'Galaxy',\n 'price':76543\n}\n\nurl = 'http://127.0.0.1:5000/cars'\nresponse = requests.post(url, json=dataString)\n\nprint(response.status_code)" }, { "alpha_fraction": 0.7618243098258972, "alphanum_fraction": 0.7618243098258972, "avg_line_length": 24.782608032226562, "blob_id": "51f343c4b047a2374b9c25e60e67ce192793aefb", "content_id": "b7f11423db2b40d23a1997e798fa77f03bad197f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 592, "license_type": "permissive", "max_line_length": 92, "num_lines": 23, "path": "/Labs/week06/lab06.03.01-githubbymodule.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nfrom github import Github\n\ng = Github(\"apikey\")\n#for repo in g.get_user().get_repos():\n# print(repo.name)\n\nrepo = g.get_repo(\"olgarozhdestvina/datarepresentationstudent\")\n#print(repo.clone_url)\n\nfileInfo = repo.get_contents(\"README.md\")\nurlOfFile = fileInfo.download_url\n#print(urlOfFile)\n\nresponse = requests.get(urlOfFile)\ncontentOfFile = response.text\n# print(contentOfFile)\n\nnewContent = contentOfFile + \"\\n## Another header added \\n\"\n#print(newContent)\n\ngitHubResponse = repo.update_file(fileInfo.path, \"update by prog\", newContent, fileInfo.sha)\nprint(gitHubResponse)" }, { "alpha_fraction": 0.6323529481887817, "alphanum_fraction": 0.6813725233078003, "avg_line_length": 19.450000762939453, "blob_id": "afab9fa64f732cc1cc63f365f795e7de16f9b4b4", "content_id": "e524cbe6740234c399fa92ed80cf6eb0b0104a21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "permissive", "max_line_length": 39, "num_lines": 20, "path": "/Exercises/requestpackage.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nfrom requests.models import Response\n\n#url = 'http://www.gmit.ie'\n#response = requests.get(url)\n\n#print(response.status_code)\n#print(response.content)\n#print(response.headers)\n\nurl = 'http://127.0.0.1:5000/cars'\ndata = {\n 'reg': '123',\n 'make': 'blah',\n 'model': 'blah2',\n 'price':123456\n}\nresponse = requests.post(url,json=data)\nprint(response.status_code)\nprint(response.json())" }, { "alpha_fraction": 0.673097550868988, "alphanum_fraction": 0.6773847937583923, "avg_line_length": 36.31999969482422, "blob_id": "aa0e0091ddc54bdeb0c677b0296aaee9043102d7", "content_id": "18ac3f6574266b53f14037ed611d4c646fc73e13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "permissive", "max_line_length": 119, "num_lines": 25, "path": "/Labs/trains.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport csv\n\nretrieveTags = ['TrainStatus','TrainLatitude','TrainLongitude', 'TrainCode', 'TrainDate', 'Direction', 'PublicMessage']\nurl = \"http://api.irishrail.ie/realtime/realtime.asmx/getCurrentTrainsXML\"\n\npage = requests.get(url)\nsoup = BeautifulSoup(page.content, 'xml')\n#print(soup.prettify())\n\n\nwith open('currentTrains.csv', 'w') as ct:\n train_writer = csv.writer(ct, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n listings = soup.findAll(\"objTrainPositions\")\n for listing in listings:\n #print(listing.prettify())\n #print(listing.TrainLatitude.string)\n trainLatitude = float(listing.TrainLatitude.string)\n if trainLatitude < 53.4:\n print(\"South train\")\n entryList = []\n for tag in retrieveTags:\n entryList.append(listing.find(tag).string)\n train_writer.writerow(entryList)\n" }, { "alpha_fraction": 0.6852173805236816, "alphanum_fraction": 0.7060869336128235, "avg_line_length": 24, "blob_id": "72bab64d60f3028c3b62e121b15f9f7114650b5b", "content_id": "59e338258c10acbce2deb62da8a655058d710c9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 575, "license_type": "permissive", "max_line_length": 179, "num_lines": 23, "path": "/README.md", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "## Data Representation Module GMIT 2020\n\nThe repository consists of:\n\n- ***Assignments***\n\n- ***Exercises***\n\n- ***Labs***: covering topics on XML, HTML, DOM, JavaScript, Consuming XML and HTML from the web, JSON, AJAX and REST, Using python to consume API, Flask and Virtual Environments.\n\n\n*Submitted by:* Olga Rozhdestvina (Student No: G00387844) \n\n*Lecturer:* Andrew Beatty \n\n*Programming Language used:* [JavaScript](https://www.javascript.com/)[Python](https://www.python.org/)\n\n\n------\n\n#### License\n\nThis project is licensed under the MIT License - see the LICENSE.md file for details\n" }, { "alpha_fraction": 0.6181818246841431, "alphanum_fraction": 0.7757575511932373, "avg_line_length": 22.714284896850586, "blob_id": "1204b083e2f9238c4043520a7db9eb183e71f490", "content_id": "bd27649eabbd20a52ba62dc6d4935ab7b026a327", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 165, "license_type": "permissive", "max_line_length": 55, "num_lines": 7, "path": "/Labs/week06/Lab-06.01-delete-car-API.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\nurl = 'http://127.0.0.1:5000/cars/46%20OE%204567'\nresponse = requests.delete(url)\nprint(response.status_code)\nprint(response.text)" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7304075360298157, "avg_line_length": 25.66666603088379, "blob_id": "79f5abc3912d0a4cb936a089c4da81b07be1c751", "content_id": "da933f05590ea13bb4f1f579b05710d134d7605e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "permissive", "max_line_length": 74, "num_lines": 12, "path": "/Labs/week06/Lab-06.02-accessGitHub.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests, json\n\nfile = 'aPrivateOne.json'\napiKey = 'apiKey'\nurl = 'https://api.github.com/repos/datarepresentationstudent/aPrivateOne'\n\nresponse = requests.get(url, auth=('token', apiKey))\nrepoJSON = response.json()\n\n#save as json file\nwith open(file,\"w\") as new_file:\n json.dump(repoJSON, new_file, indent=4)" }, { "alpha_fraction": 0.617521345615387, "alphanum_fraction": 0.6367521286010742, "avg_line_length": 22.450000762939453, "blob_id": "adbea08e3dc1f6b5fc9f4104de824ef9cc278a5b", "content_id": "a2b2da2acbf1854e688b4ac9ca656d948c03a43d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "permissive", "max_line_length": 56, "num_lines": 20, "path": "/Labs/week06/Lab-06.02-convertToPDF.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests, json\n\nfile = '../carviewer_lab2.html'\napiKey = 'apiKey'\nurl = 'https://api.html2pdf.app/v1/generate'\n\n# open carviewer\nwith open(file,'r') as f:\n html= f.read()\n #print(html)\n data = {\n 'html': html,\n 'apiKey': apiKey\n }\n response = requests.post(url, json=data)\n #print(response.status_code)\n\n#save as pdf (note binary data)\nwith open(\"lab06.02.01.htmlaspdf.pdf\",\"wb\") as new_file:\n new_file.write(response.content)" }, { "alpha_fraction": 0.6150000095367432, "alphanum_fraction": 0.6299999952316284, "avg_line_length": 15.75, "blob_id": "160b94fc8b56775f11b07f7082dfbe14f0ecb055", "content_id": "5b41a16eec630da7c39c5f48e704cc9b444891eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "permissive", "max_line_length": 31, "num_lines": 12, "path": "/Exercises/jsonPackage.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import json\ndata = {\n 'name': 'Joe',\n 'age':21,\n 'student': True\n}\n#print(data)\n\nfile = open(\"simple.json\", 'w')\n#json.dump(data,file,indent=4)\njsonString = json.dumps(data)\nprint(jsonString)" }, { "alpha_fraction": 0.7246835231781006, "alphanum_fraction": 0.7278481125831604, "avg_line_length": 25.41666603088379, "blob_id": "07609d80c10e1ca1102c20b7a40e9e0fec5482da", "content_id": "250ae959829d2f9641ac808d017271e7be5986c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "permissive", "max_line_length": 79, "num_lines": 12, "path": "/Labs/week06/Lab-06.02-accessMyGitHub.py", "repo_name": "olgarozhdestvina/dataRepresentation", "src_encoding": "UTF-8", "text": "import requests, json\n\nfile = 'myRepo.json'\napiKey = 'key'\nurl = 'https://api.github.com/repos/olgarozhdestvina/datarepresentationstudent'\n\nresponse = requests.get(url, auth=('token', apiKey))\nrepoJSON = response.json()\n\n#save as json file\nwith open(file,\"w\") as new_file:\n json.dump(repoJSON, new_file, indent=4)" } ]
13
bionanoimaging/Tensorflow_MultipleScattering
https://github.com/bionanoimaging/Tensorflow_MultipleScattering
d3fbfaf0749e3d650b24754212281f854d58d756
9492322ccc72bca491f5c8244ee363bb960f17f6
555a04d2ffb47e7edfcf77d8e0e6ead44f17668e
refs/heads/master
2020-06-11T08:22:22.548070
2020-02-20T12:56:29
2020-02-20T12:56:29
193,902,888
2
1
null
null
null
null
null
[ { "alpha_fraction": 0.6717171669006348, "alphanum_fraction": 0.7171717286109924, "avg_line_length": 22.700000762939453, "blob_id": "3e55b458334bee377a37820abf467a8fd9fa9202", "content_id": "c3702da55fbaa8db01cd6bcd9ca7cb2cab554c8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 89, "num_lines": 50, "path": "/BPM_test_2D2D.py", "repo_name": "bionanoimaging/Tensorflow_MultipleScattering", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 25 17:05:50 2019\n\n@author: bene\n\"\"\"\n\n# test BPM class\nfrom src import BPM as bpm\nimport tensorflow as tf\nimport numpy as np\nimport NanoImagingPack as nip\nimport InverseModelling as im\n\n'''TEST SCRIPT for the BPM algorithm\nB.Diederich, 26.06.2019\n\nThe input field ist aranged as follows:\n Nx, Ny, Nillu\n \n'''\n\n# define some parameters\nmysize = (20,128,128) # Z;XY\nNillu = 10\nmypixelsize = (.65/4, .65/4, .65/4)\n# create a pseudo input field\nmyinputfield = nip.ones((mysize[1],mysize[2]))+0j # plane wave\nmyinputfield = nip.ones((mysize[1],mysize[2],Nillu))+0j # plane wave\n\nTF_A_input = tf.constant(myinputfield)\n\n# load some object slice \nmyobjslice = .1*nip.extract(nip.readim(), ROIsize=mysize)+0j\nTF_obj_input = tf.constant(myobjslice)\n\n# create the BPM object with default parameters\nmyBPM = bpm.BPM(mysize = mysize, pixelsize=mypixelsize) \n\nmyBPM.printvar()\nmyBPM.propagate(TF_A_input=myinputfield, TF_obj_input = TF_obj_input, proptype = '2D_2D')\n\n# visualize the kernel\nmyBPM.visKernel()\n# compute the result\nmyres = myBPM.compute()\n\nprint('Display the result')\nnip.v5(myres,showPhases=True,gamma=1.0)\n\n\n\n" }, { "alpha_fraction": 0.5369246006011963, "alphanum_fraction": 0.5503754615783691, "avg_line_length": 43.24566650390625, "blob_id": "e862022f3fd46c9cbedb2c396e83ee665e400700", "content_id": "3f4e4b2b229a494055f5c3e3707f61674a226ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15316, "license_type": "no_license", "max_line_length": 184, "num_lines": 346, "path": "/src/BPM.py", "repo_name": "bionanoimaging/Tensorflow_MultipleScattering", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jun 24 17:46:26 2019\n\n@author: bene\n\"\"\"\n\nimport NanoImagingPack as nip\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport InverseModelling as im\n#import InverseModelling as im \n\nclass BPM(object):\n def __init__(self, lambda_0 = .65, n_embb = 1., mysize = ((1,128,128)), pixelsize = None, z_start = None, z_end = None):\n \n #TODO: We should take care of padding the object\n #TODO: Creating the input beam inside this class is best practice\n #TODO: Take care of the refrcoseffective\n \n ''' Class for creating a propagation step á la BPM\n lambda_0 = wavelength in background\n n_0 = background RI\n mysize = integer number of pixels\n pixelsize = pixelsize in same measures as wavelength\n order of pixels is Z,X,Y'''\n \n print('Initializing the BPM class')\n \n self.lambda_0 = lambda_0\n # refractive index immersion and embedding\n self.n_embb = n_embb\n self.lambda_m = self.lambda_0/self.n_embb; # wavelength in the medium\n\n\n if pixelsize is None :\n # assume lambda/4 sampling\n self.dz = self.lambda_m/4\n self.dx = self.lambda_m/4\n self.dy = self.lambda_m/4\n\n else: \n if pixelsize[0] is None:\n self.dz = self.lambda_m/4\n else:\n self.dz = pixelsize[0]\n \n if pixelsize[1] is None:\n self.dx = self.lambda_m/4\n else:\n self.dx = pixelsize[1]\n \n if pixelsize[2] is None:\n self.dy = self.lambda_m/4\n else:\n self.dy = pixelsize[2]\n\n # define size\n self.mysize = mysize\n \n if len(mysize)==3:\n # we have only one illumination direction to propagate \n self.Nx = mysize[1]\n self.Ny = mysize[2]\n self.Nz = mysize[0]\n self.Nillu = 1\n print('We propagate one illumination mode')\n \n elif len(mysize)==4:\n # we have only one illumination direction to propagate \n self.Nx = mysize[1]\n self.Ny = mysize[2]\n self.Nz = mysize[0]\n self.Nillu = mysize[-1]\n print('We propagate '+str(self.Nillu)+ ' illumination modes')\n \n # define some values\n self.my_n = self.n_embb+np.zeros(self.mysize)\n self.input_field = 0j + np.ones((self.Nx, self.Ny, self.Nillu))\n \n # compute the distances we want stuff to be propagated \n if z_start is None:\n z_start = 0.\n if z_end is None:\n z_end = self.dz*self.Nz\n \n self.z_start = z_start\n self.z_end = z_end\n if self.z_end == self.dz:\n self.dz_steps = self.dz\n else:\n self.dz_steps = np.linspace(self.z_start, self.z_end, self.Nz)\n \n\n \n def compute_generic_propagator(self):\n ''' Forward propagator for 2D and 3D\n (Ewald sphere based) DO NOT USE NORMALIZED COORDINATES HERE\n Basically following the Fresnel Kernel '''\n \n # compute the frequency grid\n self.kxysqr= (nip.abssqr(nip.xx((self.mysize[1], self.mysize[2]), freq='ftfreq') / self.dx) + \n nip.abssqr(nip.yy((self.mysize[1], self.mysize[2]), freq='ftfreq') / self.dy)) + 0j\n self.k0=1/self.lambda_m\n self.kzsqr= nip.abssqr(self.k0) - self.kxysqr\n self.kz=np.sqrt(self.kzsqr)\n self.kz[self.kzsqr < 0]=0 # get rid of evanescent components\n self.dphi = 2*np.pi*self.kz# propagator for one slice\n self.dphi *= (self.dphi > 0) \n self.Allprop = 1j * np.expand_dims(self.dphi,-1) * self.dz_steps\n self.Allprop = np.exp(np.transpose(self.Allprop,(-1,0,1)))\n\n def compute_2D_propagator(self):\n #self.A_input = self.intensityweights *np.exp((2*np.pi*1j) *\n # (self.kxcoord * tf_helper.repmat4d(tf_helper.xx((self.mysize[1], self.mysize[2])), self.Nc) \n # + self.kycoord * tf_helper.repmat4d(tf_helper.yy((self.mysize[1], self.mysize[2])), self.Nc))) # Corresponds to a plane wave under many oblique illumination angles - bfxfun\n \n # effect of the illumination angle is kep as zero for now\n self.RefrCos = 1.\n print('Beware that we do not take care of the inclination angle yet!!')\n \n # compute the generic propagator\n self.compute_generic_propagator()\n\n # Precalculate the oblique effect on OPD to speed it up\n self.RefrEffect = 1j * self.k0 * self.RefrCos\n\n \n def propagate(self, TF_A_input = None, TF_obj_input = None, proptype = '2D_2D'):\n '''\n This is the generic propagator \n \n \n TF_A_input - the n-dimensional electrical input field \n TF_obj_input - the n-dimensional refractive index distribution \n proptype - Want to map 2D->2D, 2D->3D\n '''\n \n if TF_A_input is None:\n TF_A_input = tf.constant(self.input_field)\n print('We use the default input field - which is a plane wave!')\n \n \n self.compute_2D_propagator()\n if proptype=='2D_2D':\n # only propagate a 2D slice to a 2D slice at certain distance\n self.TF_A_output = self.__propagate2D2D(TF_A_input, TF_obj_input)\n elif proptype=='2D_3D':\n # propagate a 2D slice to a 3D volume\n\n self.TF_A_output = self.__propagate2D3D(TF_A_input)\n elif proptype=='MultipleScaterring':\n # propagate a 2D slice to a 3D volume\n self.TF_A_output = self.__propagate2D3D(TF_A_input) \n \n return self.TF_A_output\n\n def __propagate2D2D(self, TF_A_input, TF_obj_input):\n ''' This propagates the inputfield to a full 3D stack'''\n \n # Porting numpy to Tensorflow\n # Define slice-wise propagator (i.e. Fresnel kernel)\n self.TF_Allprop = tf.cast(tf.complex(np.real(np.squeeze(self.Allprop)),np.imag(np.squeeze(self.Allprop))), dtype=tf.complex64)\n self.TF_RefrEffect = tf.cast(self.RefrEffect, tf.complex64)\n self.TF_obj_input = tf.cast(TF_obj_input, tf.complex64)\n \n # This corresponds to the input illumination modes\n is_not_tf = True\n if is_not_tf:\n TF_A_input = tf.cast(tf.complex(np.real(TF_A_input),np.imag(TF_A_input)), dtype=tf.complex64)\n self.TF_A_input = TF_A_input \n #self.TF_RefrEffect = tf.constant(self.RefrEffect, dtype=tf.complex64)\n\n # Split Step Fourier Method\n with tf.name_scope('Fwd_Propagate'):\n if TF_obj_input is not None:\n with tf.name_scope('Refract'):\n # beware the \"i\" is in TF_RefrEffect already!\n self.TF_f = tf.exp(self.TF_RefrEffect*self.TF_obj_input)\n self.TF_A_prop = self.TF_A_input * self.TF_f # refraction step\n else:\n self.TF_A_prop = self.TF_A_input \n with tf.name_scope('Propagate'):\n self.TF_A_output = im.ift2d(im.ft2d(tf.expand_dims(self.TF_A_prop,0))* self.TF_Allprop) # diffraction step\n\n return self.TF_A_output\n \n \n def visKernel(self):\n ''' THis function visualizes the Propagation-Kernel'''\n #plt.subplot(121), plt.title('Kernel (Magn.)'), plt.imshow(np.abs(self.myprop))\n #plt.subplot(122), plt.title('Kernel (Angle.)'), plt.imshow(np.angle(self.myprop))\n nip.view(np.abs(self.Allprop))\n nip.view(np.angle(self.Allprop))\n \n def visInputfield(self):\n ''' THis function visualizes the INput Field'''\n nip.view(self.dphi)\n\n \n def compute(self):\n ''' this is a helper function to evaluate the result from the BPM class \n it computes the TF graph into a numpy object'''\n print('Open A TF session object')\n sess = tf.Session()\n self.NP_A_output = sess.run(self.TF_A_output)\n return self.NP_A_output \n \n def printvar(self):\n ''' PRint all variables - only for debugging puposes'''\n try:\n print('The following parameters were set: ')\n print('lambda_0: '+str(self.lambda_0))\n print('lambda_m: '+str(self.lambda_m)) \n print('dx: '+str(self.dx))\n print('dy: '+str(self.dy))\n print('dz: '+str(self.dz))\n print('Nx: '+str(self.Nx))\n print('Ny: '+str(self.Ny))\n print('Nz: '+str(self.Nz))\n print('z_start '+str(self.z_start))\n print('z_end: '+str(self.z_end))\n print('n_embb: '+str(self.n_embb))\n print('dz_steps: ' +str(self.dz_steps))\n except:\n print('Did you initialize the class correclty?')\n\n\n def __propagate2D3D(self, TF_A_input, TF_obj_input):\n ''' This propagates the inputfield by one step'''\n \n # Porting numpy to Tensorflow\n # Define slice-wise propagator (i.e. Fresnel kernel)\n self.TF_Allprop = tf.cast(tf.complex(np.real(np.squeeze(self.myprop)),np.imag(np.squeeze(self.myprop))), dtype=tf.complex64)\n self.TF_RefrEffect = tf.cast(self.RefrEffect, tf.complex64)\n self.TF_obj_input = tf.cast(TF_obj_input, tf.complex64)\n \n # This corresponds to the input illumination modes\n is_not_tf = True\n if is_not_tf:\n TF_A_input = tf.cast(tf.complex(np.real(TF_A_input),np.imag(TF_A_input)), dtype=tf.complex64)\n self.TF_A_input = TF_A_input \n #self.TF_RefrEffect = tf.constant(self.RefrEffect, dtype=tf.complex64)\n\n\n with tf.name_scope('Refract'):\n # beware the \"i\" is in TF_RefrEffect already!\n if(self.is_padding):\n tf_paddings = tf.constant([[self.mysize_old[1]//2, self.mysize_old[1]//2], [self.mysize_old[2]//2, self.mysize_old[2]//2]])\n TF_real = tf.pad(TF_real_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_real_pad')\n TF_imag = tf.pad(TF_imag_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_imag_pad')\n else:\n TF_real = (TF_real_3D[-pz,:,:])\n TF_imag = (TF_imag_3D[-pz,:,:])\n \n\n self.TF_f = tf.exp(self.TF_RefrEffect*tf.complex(TF_real, TF_imag))\n self.TF_A_prop = self.TF_A_prop * self.TF_f # refraction step\n with tf.name_scope('Propagate'):\n self.TF_A_prop = tf.ifft2d(tf.fft2d(self.TF_A_prop) * self.TF_Allprop) # diffraction step\n if(is_debug): self.TF_A_prop = tf.Print(self.TF_A_prop, [], 'Performing Slice Propagation') \n\n for pz in range(0, self.mysize[0]):\n # Split Step Fourier Method\n with tf.name_scope('Fwd_Propagate'):\n if TF_obj_input is not None:\n with tf.name_scope('Refract'):\n # beware the \"i\" is in TF_RefrEffect already!\n self.TF_f = tf.exp(self.TF_RefrEffect*self.TF_obj_input)\n self.TF_A_prop = self.TF_A_input * self.TF_f # refraction step\n else:\n self.TF_A_prop = self.TF_A_input \n with tf.name_scope('Propagate'):\n self.TF_A_output = im.ift(im.ft(self.TF_A_prop) * self.TF_Allprop) # diffraction step\n \n return self.TF_A_output\n\n '''\n def __propagate3D(self, TF_A_input):\n This propagates the inputfield by one step''\n \n ## propagate the field through the entire object for all angles simultaneously\n #self.A_prop = np.transpose(self.A_input,[3, 0, 1, 2]) # ??????? what the hack is happening with transpose?!\n ''\n \n \n ' Porting numpy to Tensorflow '\n # Define slice-wise propagator (i.e. Fresnel kernel)\n self.TF_Allprop = tf.cast(tf.complex(np.real(np.squeeze(self.myprop)),np.imag(np.squeeze(self.myprop))), dtype=tf.complex64)\n\n # A propagator for all slices (2D->3D)\n self.TF_myAllSlicePropagator = tf.cast(tf.complex(np.real(self.myAllSlicePropagator), np.imag(self.myAllSlicePropagator)), tf.complex64)\n\n \n # This corresponds to the input illumination modes\n is_not_tf = True\n if is_not_tf:\n TF_A_input = tf.cast(tf.complex(np.real(self.TF_A_input),np.imag(self.TF_A_input)), dtype=tf.complex64)\n self.TF_A_input = TF_A_input \n #self.TF_RefrEffect = tf.constant(self.RefrEffect, dtype=tf.complex64)\n\n # simulate multiple scattering through object\n with tf.name_scope('Fwd_Propagate'):\n with tf.name_scope('Refract'):\n # beware the \"i\" is in TF_RefrEffect already!\n if(self.is_padding):\n tf_paddings = tf.constant([[self.mysize_old[1]//2, self.mysize_old[1]//2], [self.mysize_old[2]//2, self.mysize_old[2]//2]])\n TF_real = tf.pad(TF_real_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_real_pad')\n TF_imag = tf.pad(TF_imag_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_imag_pad')\n else:\n TF_real = (TF_real_3D[-pz,:,:])\n TF_imag = (TF_imag_3D[-pz,:,:])\n \n\n self.TF_f = tf.exp(self.TF_RefrEffect*tf.complex(TF_real, TF_imag))\n self.TF_A_prop = self.TF_A_prop * self.TF_f # refraction step\n with tf.name_scope('Propagate'):\n self.TF_A_prop = tf.ifft2d(tf.fft2d(self.TF_A_prop) * self.TF_Allprop) # diffraction step\n if(is_debug): self.TF_A_prop = tf.Print(self.TF_A_prop, [], 'Performing Slice Propagation') \n\n\n \n\n with tf.name_scope('Fwd_Propagate'):\n #print('---------ATTENTION: We are inverting the RI!')\n for pz in range(0, self.mysize[0]):\n with tf.name_scope('Refract'):\n # beware the \"i\" is in TF_RefrEffect already!\n if(self.is_padding):\n tf_paddings = tf.constant([[self.mysize_old[1]//2, self.mysize_old[1]//2], [self.mysize_old[2]//2, self.mysize_old[2]//2]])\n TF_real = tf.pad(TF_real_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_real_pad')\n TF_imag = tf.pad(TF_imag_3D[-pz,:,:], tf_paddings, mode='CONSTANT', name='TF_obj_imag_pad')\n else:\n TF_real = (TF_real_3D[-pz,:,:])\n TF_imag = (TF_imag_3D[-pz,:,:])\n \n\n self.TF_f = tf.exp(self.TF_RefrEffect*tf.complex(TF_real, TF_imag))\n self.TF_A_prop = self.TF_A_prop * self.TF_f # refraction step\n with tf.name_scope('Propagate'):\n self.TF_A_prop = tf.ifft2d(tf.fft2d(self.TF_A_prop) * self.TF_Allprop) # diffraction step\n if(is_debug): self.TF_A_prop = tf.Print(self.TF_A_prop, [], 'Performing Slice Propagation') \n\n '''\n \n" }, { "alpha_fraction": 0.7686781883239746, "alphanum_fraction": 0.7686781883239746, "avg_line_length": 26.760000228881836, "blob_id": "ad99c9aef8a4f9bd256cd521a60f33056c319a6b", "content_id": "943f05d470b2dafd220e78fe329c2a59290aaba1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 699, "license_type": "no_license", "max_line_length": 138, "num_lines": 25, "path": "/README.md", "repo_name": "bionanoimaging/Tensorflow_MultipleScattering", "src_encoding": "UTF-8", "text": "# Toolbox to test different multiple scattering algorithm on GPU using Tensorflow\n\n## Installation\nInstall the following toolboxes:\n\n```\npip install tensorflow-gpu \npip install NanoImagingToolbox\npip install InverseModelling\npip install numpy\n´´´\n\nIn order to use the NanoImagingToolbox and InverseModelling Toolbox, please contact use, since it has not been oficially published yet. \n\n## BPM - Split-Step Fourier Method\nFollowing the idea of U. Kamilov et al. \nTo test the code, please execute the file [BPM_test.py](BPM_test.py).\n\n## SEAGLE\nFollowing the idea of U. Kamilov and L. Waller et al. \n=> comming soonish\n\n## Vellekoop \nFollowing the idea of Osnabrugge et al. \n=> comming soonish\n\n\n" } ]
3
NEECIST/neecist.org
https://github.com/NEECIST/neecist.org
7f0b3c3054b80aff76570614c0bd32f69c1cbd99
21fb75f9328e74c373e1fde7765ac57d811f5527
119e47a1b7db1473ce33333b61323ca2b9aeadb8
refs/heads/master
2022-12-03T03:08:47.941012
2022-11-28T19:55:41
2022-11-28T19:55:41
113,031,217
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5639633536338806, "alphanum_fraction": 0.5877163410186768, "avg_line_length": 25.549549102783203, "blob_id": "3baff63f8b00698360bf432599c926ec3b325981", "content_id": "7076449179a08db133c41050239a7a9264122585", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2947, "license_type": "no_license", "max_line_length": 93, "num_lines": 111, "path": "/ws/ulisboa/tiroNEEC.ino", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "/* including needed external libraries */\n\n/* defining CONSTANT values */\n#define MIN 1\n#define MAX 8\n#define DURATION 30\n#define TARGETNUM 2 //number of sensors\n\n/* GLOBAL variables declaration */\n\n/* and variables to our game functioning*/\n/* declare timer variables */\nlong off_time[TARGETNUM] = {0}, off_start[TARGETNUM] = {0}, start_time; \n/* auxiliary */\nint i, j, pontos = 0;\n/* led and sensor state */\nint led[TARGETNUM] = {0}, lux[TARGETNUM] = {0};\n\n/* THE SETUP only runs ONCE when the arduino starts */\nvoid setup()\n{\n /* for serial communication */\n Serial.begin(9600); // https://www.arduino.cc/en/serial/begin\n /* to provide random seed with NOISE from an unused analog */\n randomSeed(analogRead(5)); // https://en.wikipedia.org/wiki/Random_seed\n\n /* to set pins as INPUTS for sensors and OUTPUTS for leds */\n // NOTE: making it more scalable don't use the ledsets\n for(i=0, i<TARGETNUM; i++)\n pinMode(i+2,OUTPUT); // digital 1 and 0 are for serial\n \n\n /* set initial states */\n for(i=0; i<TARGETNUM; i++)\n {\n /* all leds are stated to be off */\n led[i] = 0;\n digitalWrite(i+2 , LOW);\n /* and the state started now - millis */\n off_start[i] = millis();\n /* until a random decided value */\n off_time[i] = random(MIN, MAX) * 1000; //Defines off time for the LED\n }\n /* the game started now */\n start_time = millis();\n\n}\n\n/* THE LOOP runs in a PERMANENT MODE repeating it's code sequencially */\nvoid loop() \n{\n\n /* if the 30 seconds elapsed show an end game animation */\n if(millis() - start_time >= DURATION * 1000)\n {\n /* turn on and off 3 times */\n for (j = 0; j < 3; ++j)\n {\n for(i=0;i<TARGETNUM;i++)\n digitalWrite(i+2 , HIGH);\n delay(100);\n for(i=0;i<TARGETNUM;i++)\n digitalWrite(i+2 , LOW);\n delay(100);\n }\n /* and wait for game reset with some passive waiting */\n while(1)\n {\n Serial.println(pontos); \n delay(DURATION*1000);\n }\n }\n\n /* if leds timer has finished, turn them on! */\n for (i = 0; i < TARGETNUM; i++)\n {\n if (led[i] == 0 && millis() - off_start[i] >= off_time[i])\n {\n digitalWrite(i+2 , HIGH);\n led[i] = 1;\n }\n }\n\n /* check if sensor was hit by laser */\n for (i = 0; i < TARGETNUM; i++)\n {\n /*NOTE: while analogRead(A0) is more correct, analogRead(0) translates to read from A0 */\n Serial.println(lux[i]); /* adjust sensors */\n lux[i] = analogRead(i);\n }\n\n /* if it was hit while available, register points*/ \n for (i = 0; i < TARGETNUM; i++)\n {\n if (lux[i] < 100 && led[i] == 1)\n {\n /* it was hit, so turn it off again */\n digitalWrite(i+2 , LOW);\n led[i] = 0;\n\n /* the state started now - millis */\n off_start[i] = millis(); \n /* with new random waiting time*/\n off_time[i] = random(MIN, MAX) * 1000;\n \n /* count points and log them to console */\n pontos += 1;\n Serial.println(pontos);\n }\n }\n}\n" }, { "alpha_fraction": 0.6230936646461487, "alphanum_fraction": 0.6410675644874573, "avg_line_length": 23.479999542236328, "blob_id": "d22ce62cfc94be2b0045c35e1940fd13f0a25eb9", "content_id": "8aaf4dc42446f84b133d663c4974ef0de02d7d98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1840, "license_type": "no_license", "max_line_length": 81, "num_lines": 75, "path": "/games/reactiontime/script.js", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "const logoNeec = document.getElementById(\"logo-neec\");\nconst printTime = document.getElementById(\"reaction-time\");\nconst startButton = document.getElementById(\"start-button\");\nconst countdown = document.getElementById(\"countdown\");\nconst clickBox = document.getElementById(\"click-box\");\nconst total = document.getElementById(\"total-clickes\");\n\nvar startTime = 0;\nvar clickedTime = 0;\nvar reactionTime = 0;\nvar gameStart = false;\nvar total_clicks = 0;\n\n/**\n * creates a box with random coordinates and records its creation time\n */\n\nfunction makeBox() {\n var time = Math.random();\n time = time * 3000 + 500;\n\n setTimeout(() => {\n var top = Math.random();\n var left = Math.random() - 0.5;\n top *= 20;\n left *= 30;\n\n logoNeec.style.top = top + \"vh\";\n logoNeec.style.left = left + \"vw\";\n\n startTime = Date.now();\n\n logoNeec.style.display = \"block\";\n }, time);\n}\n\nclickBox.onclick = () => {\n if (startTime === 0 && gameStart) {\n alert(\"Espera até a imagem aparecer para clicares!\");\n total_clicks++;\n total.innerHTML = `Clicks fora do tempo: ${total_clicks}`;\n }\n};\n\nlogoNeec.onclick = () => {\n clickedTime = Date.now();\n reactionTime = (clickedTime - startTime) / 1000;\n\n printTime.innerHTML = \"O teu tempo de reação é: \" + reactionTime + \" segundos\";\n logoNeec.style.display = \"none\";\n startButton.style.display = \"inline\";\n};\n\nstartButton.onclick = function () {\n this.style.display = \"none\";\n printTime.innerHTML = \"\";\n\n gameStart = true;\n startTime = 0;\n clickedTime = 0;\n reactionTime = 0;\n total_clicks = 0;\n total_clicks = 0;\n total.innerHTML = `Clicks fora do tempo: ${total_clicks}`;\n\n var t = 3;\n var timer = setInterval(() => {\n countdown.innerHTML = t--;\n if (t < 0) {\n countdown.innerHTML = \"\";\n makeBox();\n clearInterval(timer);\n }\n }, 1000);\n};\n" }, { "alpha_fraction": 0.5238596796989441, "alphanum_fraction": 0.5410206317901611, "avg_line_length": 32.58854293823242, "blob_id": "2606e83991e324ad1505cd2d6b885a7d9954653c", "content_id": "6dacdceebd9ee84be45843c9d3a1562ffaf34e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 6643, "license_type": "no_license", "max_line_length": 124, "num_lines": 192, "path": "/games/memory/games.js", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "var moves = 0;\r\nvar picks = [];\r\nvar ids = [];\r\nvar pairs = 0;\r\nvar cards = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11];\r\ninitial_time = Date.now();\r\nfinal_time = 0;\r\nfinal_moves = 0;\r\nhide_time = true;\r\n\r\nfunction increment_move(card, id) {\r\n if (ids.length == 0 || (ids.length == 1 && id != ids[0])) {\r\n moves += 1;\r\n document.getElementById(\"movimentos\").innerHTML = moves;\r\n picks.push(card);\r\n ids.push(id);\r\n if (picks.length == 2) {\r\n if (picks[0] == picks[1]) {\r\n matched = true;\r\n pairs++;\r\n } else {\r\n matched = false;\r\n }\r\n board_state(matched, pairs, ids);\r\n picks = [];\r\n ids = [];\r\n }\r\n }\r\n}\r\n\r\nasync function board_state(matched, pairs, ids) {\r\n if (matched == true) {\r\n var item = document.getElementById(ids[0]);\r\n item.classList.toggle(\"flipped\");\r\n item.classList.add(\"paired\");\r\n item.removeEventListener('click', transform);\r\n item.removeEventListener('click', increment_move);\r\n var item = document.getElementById(ids[1]);\r\n item.classList.toggle(\"flipped\");\r\n item.classList.add(\"paired\");\r\n item.removeEventListener('click', transform);\r\n item.removeEventListener('click', increment_move);\r\n } else {\r\n for (var i = 0; i < cards.length; i++) {\r\n var item = document.getElementById(i);\r\n if (i != ids[0] && i != ids[1]) {\r\n item.style.pointerEvents = \"none\";\r\n }\r\n }\r\n await sleep(800);\r\n for (var i = 0; i < cards.length; i++) {\r\n var item = document.getElementById(i);\r\n if (i != ids[0] && i != ids[1]) {\r\n item.style.pointerEvents = null;\r\n }\r\n }\r\n transform(ids[0]);\r\n transform(ids[1]);\r\n }\r\n if (pairs == 12) {\r\n clearInterval(temporizador);\r\n final_time = Date.now() - initial_time;\r\n final_moves = moves;\r\n var item = document.getElementsByClassName(\"stats\");\r\n item[item.length - 1].innerHTML += '<div class=\"final\">RESULTADO FINAL: ' + final_time + ' ms</div>';\r\n document.getElementById(\"tempo\").innerHTML = timeToString(final_time);\r\n document.getElementById(\"movimentos\").innerHTML = final_moves;\r\n document.getElementById(\"legenda_tempo\").innerHTML = \"\";\r\n }\r\n}\r\n\r\nfunction start_card_game() {\r\n shuffle(cards);\r\n var i = 0;\r\n for (var i = 0; i < 2; i++) {\r\n document.getElementById('game').innerHTML += '<div class=\"row\" name=\"row\">';\r\n for (var j = 0; j < 12; j++) {\r\n var item = document.getElementsByName(\"row\");\r\n item[item.length - 1].innerHTML += '<div class=\"column\"><div class=\"card\">';\r\n var item = document.getElementsByClassName(\"card\");\r\n item[item.length - 1].id = (i * 12) + j;\r\n item[item.length - 1].innerHTML += '<p name=\"marca\" id=\"p0\">NEEC</p>';\r\n item[item.length - 1].innerHTML += '<img src=\"./assets/cards/0.png\" style=\"display: none;\" id=\"i0\" name=\"img\">';\r\n var item = document.getElementsByName(\"img\");\r\n item[item.length - 1].src = \"./assets/cards/\" + cards[(i * 12) + j] + \".png\";\r\n var item = document.getElementsByName(\"row\");\r\n item[item.length - 1].innerHTML += '</div></div>';\r\n }\r\n document.getElementById('game').innerHTML += '</div>';\r\n }\r\n var item = document.getElementsByName(\"marca\");\r\n for (var i = 0; i < cards.length; i++) {\r\n item[i].id = \"p\" + i;\r\n }\r\n var item = document.getElementsByName(\"img\");\r\n for (var i = 0; i < cards.length; i++) {\r\n item[i].id = \"i\" + i;\r\n }\r\n\r\n document.querySelectorAll('.card').forEach(item => {\r\n item.addEventListener('click', event => {\r\n transform(item.id)\r\n increment_move(cards[item.id], item.id)\r\n })\r\n });\r\n\r\n for (var i = 0; i < cards.length; i++) {\r\n var item = document.getElementById(i);\r\n if (i != ids[0] && i != ids[1]) {\r\n item.style.pointerEvents = \"none\";\r\n }\r\n }\r\n}\r\n\r\nfunction transform(id) {\r\n var item = document.getElementById(id);\r\n item.classList.toggle(\"card\");\r\n item.classList.toggle(\"flipped\");\r\n var item = document.getElementById(\"p\" + id);\r\n if (item.style.display === \"none\") {\r\n item.style.display = \"block\";\r\n } else {\r\n item.style.display = \"none\";\r\n }\r\n var item = document.getElementById(\"i\" + id);\r\n if (item.style.display === \"none\") {\r\n item.style.display = \"block\";\r\n } else {\r\n item.style.display = \"none\";\r\n }\r\n}\r\n\r\nfunction shuffle(array) {\r\n var currentIndex = array.length, temporaryValue, randomIndex;\r\n\r\n while (currentIndex !== 0) {\r\n randomIndex = Math.floor(Math.random() * currentIndex);\r\n currentIndex -= 1;\r\n temporaryValue = array[currentIndex];\r\n array[currentIndex] = array[randomIndex];\r\n array[randomIndex] = temporaryValue;\r\n }\r\n return array;\r\n}\r\n\r\nfunction start_time() {\r\n initial_time = Date.now();\r\n for (var i = 0; i < cards.length; i++) {\r\n var item = document.getElementById(i);\r\n if (i != ids[0] && i != ids[1]) {\r\n item.style.pointerEvents = null;\r\n }\r\n }\r\n var item = document.getElementById(\"start_btn\");\r\n item.style.display = \"none\";\r\n hide_time = false;\r\n}\r\n\r\nvar temporizador = setInterval(function printTime() {\r\n let elapsedTime = Date.now() - initial_time;\r\n var item = document.getElementById(\"tempo\");\r\n if (hide_time == false) {\r\n document.getElementById(\"tempo\").innerHTML = Math.floor(elapsedTime / 1000);\r\n }\r\n}, 1000);\r\n\r\nfunction sleep(ms) {\r\n return new Promise(resolve => setTimeout(resolve, ms));\r\n}\r\n\r\nfunction timeToString(time) {\r\n let diffInHrs = time / 3600000;\r\n let hh = Math.floor(diffInHrs);\r\n\r\n let diffInMin = (diffInHrs - hh) * 60;\r\n let mm = Math.floor(diffInMin);\r\n\r\n let diffInSec = (diffInMin - mm) * 60;\r\n let ss = Math.floor(diffInSec);\r\n\r\n let diffInMiliSec = (diffInSec - ss) * 10000;\r\n let ms = Math.floor(diffInMiliSec);\r\n\r\n let formattedHH = hh.toString().padStart(2, \"0\");\r\n let formattedMM = mm.toString().padStart(2, \"0\");\r\n let formattedSS = ss.toString().padStart(2, \"0\");\r\n\r\n return `${formattedMM}:${formattedSS}:${ms}`;\r\n}\r\n\r\ndocument.getElementById(\"movimentos\").innerHTML = moves;\r\ndocument.getElementById(\"legenda_tempo\").innerHTML = \" segundos\";\r\n\r\n" }, { "alpha_fraction": 0.676906406879425, "alphanum_fraction": 0.6830502152442932, "avg_line_length": 43.872928619384766, "blob_id": "906a3c87c12f66b6dd4b1fb4448dcae60d28ffa2", "content_id": "7b448a8a431b651f229f743f3947693c06a01746", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 8365, "license_type": "no_license", "max_line_length": 228, "num_lines": 181, "path": "/games/typingcontest/games.js", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "/*\r\n * The animation at the start, made from my previous pen\r\n * https://codepen.io/EightArmsHQ/pen/HJsav\r\n */\r\n\r\nvar typing_text_pt = [\r\n \"O NEEC é uma associação sem fins lucrativos que reúne os estudantes de MEEC do IST. Somos formados por alunos que, através do seu trabalho voluntário, proporcionam diversas atividades aos seus colegas.\",\r\n \"No NEEC procuramos ajudar os alunos a integrarem-se no mercado de trabalho e dar formação extra-curricular. Organizamos workshops, estágios de verão, OpenDays, organizamos uma hackathon e muito mais!\",\r\n \"O NEEC quer ajudar a complementar o normal percurso escolar, não só dos alunos de Eletrotecnia, como também de todos do IST. Começámos em 2003, e já por quase década e meia temos vindo a crescer para te ajudar.\",\r\n \"As NEECTalks são um projeto que consiste na realização de podcasts, sobre tecnologia, inovação e empreendedorismo na engenharia. Pretendemos apresentar alunos, professores, investigadores, empresários, entre outros.\",\r\n \"O IST Summer Internships foi implementado tendo em vista facilitar a aproximação entre os alunos do IST e as empresas. Este programa conta com o apoio do Técnico através do Núcleo de Parcerias Empresariais.\",\r\n \"Um estágio constitui uma inegável mais-valia no percurso académico de um estudante do Ensino Superior, capacitando-o de valências distintas e complementares à formação adquirida no Instituto Superior Técnico.\",\r\n \"Os núcleos que pertencem ao IST Summer Internships têm como principal objetivo a dinamização de várias atividades que visam reforçar a formação curricular dos estudantes, através de, formações, programas de estágios, etc.\",\r\n \"Um grupo de estudantes do IST, cujo principal objetivo é organizar um evento gratuito e aberto a uma forte comunidade de estudantes, com a intenção de diminuir a distância entre o mundo empresarial e a vida universitária.\",\r\n \"A NEECathon é uma competição cujo objetivo é simular o mundo das start-ups. Os participantes vão ser avaliados não só pelo seu projeto como também pela forma como vendem a sua ideia e como gerem os seus recursos.\"\r\n]\r\n\r\nvar typing_text = [\r\n \"NEEC is a non-profit association that brings together MEEC students from IST. We are made up of students who, through their voluntary work, provide various activities to their colleagues.\",\r\n \"At NEEC we seek to help students integrate into the job market and provide extra-curricular training. We organize workshops, summer internships, OpenDays, we organize a hackathon and much more!\",\r\n \"NEEC wants to help complement the normal school path, not only for Electrotechnical students, but also for everyone at IST. We started in 2003, and for almost a decade and a half we have been growing to help you.\",\r\n \"NEECTalks is a project that consists of making podcasts about technology, innovation and entrepreneurship in engineering. We intend to present students, teachers, researchers, entrepreneurs, among others.\",\r\n \"IST Summer Internships was implemented in order to facilitate the rapprochement between IST students and companies. This program has the support of Técnico through the Center for Business Partnerships.\",\r\n \"An internship is an undeniable added value to the academic career of a student of Higher Education, enabling you with different and complementary skills to the training acquired at Instituto Superior Tecnico.\",\r\n \"The main objectives of the IST Summer Internships are to stimulate various activities aimed at reinforcing the curricular training of students, through training, internship programs, etc.\",\r\n \"A group of students from IST, whose main objective is to organize a free and open event to a strong student community, with the intention of closing the gap between the business world and university life.\",\r\n \"NEECathon is a competition whose objective is to simulate the world of start-ups. Participants will be evaluated not only for their project but also for how they sell their idea and how they manage their resources.\"\r\n]\r\n\r\n// The base speed per character\r\ntime_setting = 30;\r\n// How much to 'sway' (random * this-many-milliseconds)\r\nrandom_setting = 100;\r\n// The text to use NB use \\n not real life line breaks!\r\ninput_text = \"Quão rápido consegues escrever?\";\r\n// Where to fill up\r\ntarget_setting = $(\"#output\");\r\n\r\n$(\"#input_text\").text(typing_text[Math.floor(Math.random() * typing_text.length)]);\r\n\r\n// Launch that function!\r\ntype(input_text, target_setting, 0, time_setting, random_setting);\r\n\r\nfunction type(input, target, current, time, random){\r\n // If the current count is larger than the length of the string, then for goodness sake, stop\r\n\tif(current > input.length){\r\n // Write Complete\r\n\t\tconsole.log(\"Complete.\");\r\n\t}\r\n\telse{\r\n\t // console.log(current)\r\n // Increment the marker\r\n\t\tcurrent += 1;\r\n // fill the target with a substring, from the 0th character to the current one\r\n\t\ttarget.text(input.substring(0,current));\r\n // Wait ...\r\n\t\tsetTimeout(function(){\r\n // do the function again, with the newly incremented marker\r\n\t\t\ttype(input, target, current, time, random);\r\n // Time it the normal time, plus a random amount of sway\r\n\t\t},time + Math.random()*random);\r\n\t}\r\n}\r\n\r\n/*\r\n * The typing test stuff\r\n */\r\n\r\nvar character_length = 31;\r\nvar index = 0;\r\nvar letters = $(\"#input_text\").val();\r\nvar started = false;\r\nvar ended = false;\r\nvar current_string = letters.substring(index, index + character_length);\r\n\r\nvar charcount = 0;\r\n\r\n$(\"#target\").text(current_string);\r\n$(window).keypress(function(evt){\r\n if (!ended){\r\n if(!started){\r\n start();\r\n started = true;\r\n }\r\n evt = evt || window.event;\r\n var charCode = evt.which || evt.keyCode;\r\n var charTyped = String.fromCharCode(charCode);\r\n if(charTyped == letters.charAt(index) && current_errors == 0){\r\n charcount ++;\r\n $(\"#charcount\").text(charcount);\r\n\r\n index ++;\r\n current_string = letters.substring(index, index + character_length);\r\n $(\"#target\").text(current_string);\r\n $(\"#your-attempt\").append(charTyped);\r\n if(index == letters.length){\r\n $(\"#timer\").text(timer);\r\n if(timer == 0){\r\n timer = 1;\r\n }\r\n cpm = Math.round(charcount / (timer / 60));\r\n $(\"#cpm\").text(cpm);\r\n stop();\r\n finished();\r\n }\r\n }else{\r\n $(\"#your-attempt\").append(\"<span class='wrong'>\" + charTyped + \"</span>\");\r\n errors ++;\r\n current_errors ++;\r\n $(\"#errors\").text(errors);\r\n }\r\n }\r\n});\r\n\r\n$(window).keydown(function(evt){\r\n if(started){\r\n evt = evt || window.event;\r\n var charCode = evt.which || evt.keyCode;\r\n if(charCode == 8 && current_errors > 0){\r\n current_errors --;\r\n current_text = $(\"#your-attempt\").text().slice(0, -1);\r\n $(\"#your-attempt\").text(current_text.substring(0, current_text.length-current_errors));\r\n $(\"#your-attempt\").append(\"<span class='wrong'>\" + current_text.substring(current_text.length-current_errors, current_text.length) + \"</span>\")\r\n }\r\n }\r\n});\r\n\r\nvar timer = 0;\r\nvar cpm = 0;\r\nvar errors = 0;\r\nvar current_errors = 0;\r\nvar interval_timer;\r\n\r\n$(\"#new\").click(function(){\r\n reset();\r\n});\r\n\r\n$(\"#pause\").click(function(){\r\n stop();\r\n});\r\n\r\nfunction start(){\r\n interval_timer = setInterval(function(){\r\n timer ++;\r\n $(\"#timer\").text(timer);\r\n cpm = Math.round(charcount / (timer / 60));\r\n $(\"#cpm\").text(cpm);\r\n }, 1000)\r\n}\r\n\r\nfunction stop(){\r\n clearInterval(interval_timer);\r\n started = false;\r\n}\r\n\r\nfunction reset(){\r\n $(\"#input_text\").blur().hide();;\r\n $(\"#your-attempt\").text(\"\");\r\n $(\"#input_text\").text(typing_text[Math.floor(Math.random() * typing_text.length)]);\r\n index = 0;\r\n errors = 0;\r\n current_errors = 0;\r\n clearInterval(interval_timer);\r\n started = false;\r\n ended = false;\r\n letters = $(\"#input_text\").val();\r\n $(\"#errors\").text(\"0\");\r\n $(\"#cpm\").text(\"0\");\r\n $(\"#timer\").text(\"0\");\r\n $(\"#charcount\").text(\"0\");\r\n timer = 0;\r\n charcount = 0;\r\n cpm = 0;\r\n current_string = letters.substring(index, index + character_length);\r\n $(\"#target\").text(current_string);\r\n}\r\n\r\nfunction finished(){\r\n alert(\"Congratulations!\\nCharacters per minute: \" + cpm + \"\\nCharcount: \" + charcount + \"\\nErrors:\" + errors);\r\n ended = true;\r\n}" }, { "alpha_fraction": 0.5080440044403076, "alphanum_fraction": 0.5613886713981628, "avg_line_length": 19.870370864868164, "blob_id": "6ef71d2a34b32caf2988585c9be9ddba175eb089", "content_id": "4ddf6282b58735d422ae4aa1e29dc9483e606d8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1193, "license_type": "no_license", "max_line_length": 97, "num_lines": 54, "path": "/ws/ulisboa/banaNEEC_blank.ino", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "// define as portas analógicas de 0 a 3 como as bananas 0 a 3\r\nint banana0 = A0;\r\nint banana1 = A1;\r\nint banana2 = A2;\r\nint banana3 = A3;\r\nint buzzer = 10;\r\n\r\n// a rotina de setup corre uma vez no início do programa e sempre que o botão reset é pressionado\r\nvoid setup() {\r\n Serial.begin(9600);\r\n\r\n // define as bananas como portas INPUT_PULLUP\r\n ?\r\n ?\r\n ?\r\n ?\r\n}\r\n\r\n// a rotina loop corre infinitamente até que o o botão reset seja pressionado\r\nvoid loop() {\r\n // obter leituras dos pinos analógicos\r\n ?\r\n ?\r\n ?\r\n ?\r\n\r\n // converter as leituras analógicas (valores de 0 a 1023) para tensões (0 a 5V):\r\n float voltage0 = reading0 * (5.0 / 1023.0);\r\n float voltage1 = reading1 * (5.0 / 1023.0);\r\n float voltage2 = reading2 * (5.0 / 1023.0);\r\n float voltage3 = reading3 * (5.0 / 1023.0);\r\n\r\n // print da leitura da banana0:\r\n Serial.println(voltage0);\r\n \r\n // verificação das tensões para ver qual banana foi pressionada e tocar o som de cada uma\r\n //if ( ? ) {\r\n // ?\r\n //}\r\n //else if ( ? ) {\r\n // ?\r\n //}\r\n //else if ( ? ) {\r\n // ?\r\n //}\r\n //else if ( ? ) {\r\n // ?\r\n //}\r\n //else {\r\n // noTone(buzzer);\r\n //}\r\n\r\n \r\n}\r\n" }, { "alpha_fraction": 0.5458548665046692, "alphanum_fraction": 0.5755313038825989, "avg_line_length": 50.22999954223633, "blob_id": "4bed049075702ec87a3fc961be57dadba6376de7", "content_id": "89bc2e64683c11edff06cb4e0370b84149df74b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5225, "license_type": "no_license", "max_line_length": 225, "num_lines": 100, "path": "/ws/python/4emlinha_incompleto.py", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "#importes\r\nimport numpy as np\r\nimport pygame\r\nimport sys\r\nimport math\r\nimport time\r\n\r\n#variaveis globais\r\n\r\n\r\n# definição de cores em RGB\r\nAZUL_NEEC = (0, 157, 224)\r\nPRETO = (0, 0, 0)\r\nBRANCO = (255, 255, 255)\r\nPECA1 = (225, 0, 0)\r\nPECA2 = (0, 225, 225)\r\nVERDE = (0, 255, 0)\r\nROXO = (255, 0, 255)\r\nCINZENTO = (150,150,150)\r\n\r\ndef criar_tabuleiro():\r\n pass\r\n\r\ndef imprimir_tabuleiro(tabuleiro):\r\n pass\r\n\r\ndef colocar_peca_no_tabuleiro(tabuleiro, col, player, linha):\r\n pass\r\n\r\ndef vitoria(tabuleiro, linha, coluna):\r\n pass\r\n\r\ndef desenhar_tabuleiro(tabuleiro, janela, altura):\r\n for c in range(NUM_COLUNAS):\r\n for l in range(NUM_LINHAS):\r\n pygame.draw.rect(janela, AZUL_NEEC, (c*MEDIDA_POR_QUADRADO, (l+1)*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n pygame.draw.circle(janela, PRETO, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n\r\n for c in range(NUM_COLUNAS):\r\n for l in range(NUM_LINHAS):\r\n if tabuleiro[l][c] == 1:\r\n pygame.draw.circle(janela, PECA1, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), altura-int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n elif tabuleiro[l][c] == 2:\r\n pygame.draw.circle(janela, PECA2, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), altura-int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n\r\n pygame.display.update()\r\n\r\ndef main():\r\n\r\n while not(game_over):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n sys.exit()\r\n if event.type == pygame.MOUSEMOTION:\r\n posx = event.pos[0]\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n if vez_de == 0:\r\n pygame.draw.circle(janela, PECA1, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n else:\r\n pygame.draw.circle(janela, PECA2, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n pygame.display.update()\r\n\r\n\r\n if game_over:\r\n time.sleep(1)\r\n time_start = time.time()\r\n #print(time_start)\r\n pygame.draw.rect(janela, PRETO, (int((largura-5*MEDIDA_POR_QUADRADO)/2), int((altura-MEDIDA_POR_QUADRADO)/2), 5*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n while time.time() < time_start+5:\r\n k = int(math.floor(6-(time.time()-time_start)))\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2), int((altura+MEDIDA_POR_QUADRADO)/2) , 5*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n time_str = myfont.render(str(k), 1, PRETO)\r\n janela.blit(time_str, (int(largura/2),int((altura+MEDIDA_POR_QUADRADO)/2)))\r\n for event in pygame.event.get() :\r\n if event.type == pygame.MOUSEMOTION :\r\n pos = pygame.mouse.get_pos()\r\n if int((largura-5*MEDIDA_POR_QUADRADO)/2) < pos[0] and int((altura-MEDIDA_POR_QUADRADO)/2) < pos[1] and pos[0] < int((largura+5*MEDIDA_POR_QUADRADO)/2) and pos[1] < int((altura+MEDIDA_POR_QUADRADO)/2):\r\n pygame.draw.rect(janela, CINZENTO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n else:\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n if event.type == pygame.MOUSEBUTTONDOWN :\r\n pos = pygame.mouse.get_pos()\r\n if int((largura-5*MEDIDA_POR_QUADRADO)/2) < pos[0] and int((altura-MEDIDA_POR_QUADRADO)/2) < pos[1] and pos[0] < int((largura+5*MEDIDA_POR_QUADRADO)/2) and pos[1] < int((altura+MEDIDA_POR_QUADRADO)/2):\r\n game_over = False\r\n tabuleiro = criar_tabuleiro()\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n time_start = 0\r\n\r\n pygame.display.update()\r\n #print(time.time())\r\n desenhar_tabuleiro(tabuleiro, janela, altura)\r\n\r\nmain()\r\n" }, { "alpha_fraction": 0.48904410004615784, "alphanum_fraction": 0.5150703191757202, "avg_line_length": 42.67094039916992, "blob_id": "55a8c24a9cfac4f585df7ebc60e856dae06472c2", "content_id": "187ce136a7572d6ceb391034b13e69d256f71527", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10473, "license_type": "no_license", "max_line_length": 225, "num_lines": 234, "path": "/ws/python/4emlinha.py", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "#importes\r\nimport numpy as np\r\nimport pygame\r\nimport sys\r\nimport math\r\nimport time\r\n\r\n#variaveis globais\r\n#numeros magicos\r\nNUM_COLUNAS = 7\r\nNUM_LINHAS = 6\r\nMEDIDA_POR_QUADRADO = 100 #isto está em pixeis\r\nRAIO = int(MEDIDA_POR_QUADRADO/2 - 5)\r\n# definição de cores\r\nAZUL_NEEC = (0, 157, 224)\r\nPRETO = (0, 0, 0)\r\nBRANCO = (255, 255, 255)\r\nPECA1 = (225, 0, 0)\r\nPECA2 = (0, 225, 225)\r\nVERDE = (0, 255, 0)\r\nROXO = (255, 0, 255)\r\nCINZENTO = (150,150,150)\r\n\r\n#esta função está a criar uma matriz de zeros, isto para simular o nosso tabuleiro com x colunas e y linhas\r\ndef criar_tabuleiro():\r\n tabuleiro = np.zeros((NUM_LINHAS,NUM_COLUNAS))\r\n return tabuleiro\r\n\r\n#esta função serve para imprimir o tabuleiro/matriz no terminar da forma como é suposto a vermos (ou seja com o [0][0] no canto inferior esquerdo, se fizesse só print este estaria no canto superior)\r\ndef imprimir_tabuleiro(tabuleiro):\r\n print(np.flip(tabuleiro, 0))\r\n\r\n#esta função vê qual é a casa da matriz em que a peça vai ficar e posiciona a peça no tabuleiro\r\ndef colocar_peca_no_tabuleiro(tabuleiro, col, player, linha):\r\n for linha[0] in range(NUM_LINHAS):\r\n if tabuleiro[linha[0]][col] == 0:\r\n tabuleiro[linha[0]][col] = player\r\n return True\r\n return False\r\n\r\n\r\n#esta função retorna True se for feito 4 em linha\r\ndef vitoria(tabuleiro, linha, coluna):\r\n h = 1\r\n d1 = 1\r\n d2 = 1\r\n try:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha-1][coluna] == tabuleiro[linha-2][coluna] == tabuleiro[linha-3][coluna]):\r\n return True\r\n except:\r\n pass\r\n try:\r\n for x in [1,2,3]:\r\n if coluna-x >= 0:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha][coluna-x]):\r\n h = h+1\r\n #print('1:',h)\r\n if(h == 4):\r\n return True\r\n else:\r\n break\r\n else:\r\n break\r\n for x in [1,2,3]:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha][coluna+x]):\r\n h = h+1\r\n #print ('1b:',h)\r\n if(h == 4):\r\n return True\r\n else:\r\n break\r\n except:\r\n pass\r\n try:\r\n for x in [1,2,3]:\r\n if linha-x>=0 and coluna-x>=0:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha-x][coluna-x]):\r\n d1 = d1+1\r\n #print('d1:',d1)\r\n if(d1 == 4):\r\n return True\r\n else:\r\n break\r\n else:\r\n break\r\n for x in [1,2,3]:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha+x][coluna+x]):\r\n d1 = d1+1\r\n #print ('d1.:',d1)\r\n if(d1 == 4):\r\n return True\r\n else:\r\n break\r\n except:\r\n pass\r\n\r\n try:\r\n for x in [1,2,3]:\r\n if linha-x >= 0:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha-x][coluna+x]):\r\n d2 = d2+1\r\n #print('d2.:',d2)\r\n if(d2 == 4):\r\n return True\r\n else:\r\n break\r\n else:\r\n break\r\n for x in [1,2,3]:\r\n if coluna-x >=0:\r\n if(tabuleiro[linha][coluna] == tabuleiro[linha+x][coluna-x]):\r\n d2 = d2+1\r\n #print('d2..:',d2)\r\n if(d2 == 4):\r\n return True\r\n else:\r\n break\r\n else:\r\n break\r\n except:\r\n pass\r\n return False\r\n\r\n#esta funão desenha o tabuleiro em pygame\r\ndef desenhar_tabuleiro(tabuleiro, janela, altura):\r\n for c in range(NUM_COLUNAS):\r\n for l in range(NUM_LINHAS):\r\n pygame.draw.rect(janela, AZUL_NEEC, (c*MEDIDA_POR_QUADRADO, (l+1)*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n pygame.draw.circle(janela, PRETO, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n\r\n for c in range(NUM_COLUNAS):\r\n for l in range(NUM_LINHAS):\r\n if tabuleiro[l][c] == 1:\r\n pygame.draw.circle(janela, PECA1, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), altura-int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n elif tabuleiro[l][c] == 2:\r\n pygame.draw.circle(janela, PECA2, (int(c*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2), altura-int(l*MEDIDA_POR_QUADRADO+MEDIDA_POR_QUADRADO/2)), RAIO)\r\n\r\n pygame.display.update()\r\n\r\n#esta função é onde vai correr o jogo\r\ndef main():\r\n tabuleiro = criar_tabuleiro()\r\n game_over = False\r\n vez_de = 0\r\n\r\n pygame.init()\r\n largura = NUM_COLUNAS * MEDIDA_POR_QUADRADO\r\n altura = (NUM_LINHAS+1) * MEDIDA_POR_QUADRADO\r\n tamanho = (largura, altura)\r\n janela = pygame.display.set_mode(tamanho)\r\n desenhar_tabuleiro(tabuleiro, janela, altura)\r\n myfont = pygame.font.SysFont(\"monospace\", 75)\r\n\r\n while not(game_over):\r\n for event in pygame.event.get():\r\n\r\n if event.type == pygame.QUIT :\r\n sys.exit()\r\n\r\n if event.type == pygame.MOUSEMOTION :\r\n posx = event.pos[0]\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n if vez_de == 0:\r\n pygame.draw.circle(janela, PECA1, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n else:\r\n pygame.draw.circle(janela, PECA2, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n pygame.display.update()\r\n\r\n if event.type == pygame.MOUSEBUTTONDOWN :\r\n posx = event.pos[0]\r\n col = int(math.floor(posx/MEDIDA_POR_QUADRADO))\r\n linha = [0]\r\n if vez_de == 0:\r\n if not(colocar_peca_no_tabuleiro(tabuleiro, col, 1, linha)):\r\n vez_de += 1\r\n elif vitoria(tabuleiro, linha[0], col):\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n label = myfont.render(\"Player 1 wins!!\", 1, PECA1)\r\n janela.blit(label, (40,10))\r\n game_over = True\r\n else:\r\n pygame.draw.circle(janela, PECA2, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n else:\r\n if not(colocar_peca_no_tabuleiro(tabuleiro, col, 2, linha)):\r\n vez_de += 1\r\n elif vitoria(tabuleiro, linha[0], col):\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n label = myfont.render(\"Player 2 wins!!\", 1, PECA2)\r\n janela.blit(label, (40,10))\r\n game_over = True\r\n else:\r\n pygame.draw.circle(janela, PECA1, (posx, int(MEDIDA_POR_QUADRADO/2)), RAIO)\r\n vez_de += 1\r\n vez_de = vez_de%2\r\n desenhar_tabuleiro(tabuleiro, janela, altura)\r\n #imprimir_tabuleiro(tabuleiro)\r\n\r\n if game_over:\r\n time.sleep(1)\r\n time_start = time.time()\r\n #print(time_start)\r\n pygame.draw.rect(janela, PRETO, (int((largura-5*MEDIDA_POR_QUADRADO)/2), int((altura-MEDIDA_POR_QUADRADO)/2), 5*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n while time.time() < time_start+5:\r\n k = int(math.floor(6-(time.time()-time_start)))\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2), int((altura+MEDIDA_POR_QUADRADO)/2) , 5*MEDIDA_POR_QUADRADO, MEDIDA_POR_QUADRADO))\r\n time_str = myfont.render(str(k), 1, PRETO)\r\n janela.blit(time_str, (int(largura/2),int((altura+MEDIDA_POR_QUADRADO)/2)))\r\n for event in pygame.event.get() :\r\n if event.type == pygame.MOUSEMOTION :\r\n pos = pygame.mouse.get_pos()\r\n if int((largura-5*MEDIDA_POR_QUADRADO)/2) < pos[0] and int((altura-MEDIDA_POR_QUADRADO)/2) < pos[1] and pos[0] < int((largura+5*MEDIDA_POR_QUADRADO)/2) and pos[1] < int((altura+MEDIDA_POR_QUADRADO)/2):\r\n pygame.draw.rect(janela, CINZENTO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n else:\r\n pygame.draw.rect(janela, BRANCO, (int((largura-5*MEDIDA_POR_QUADRADO)/2)+4, int((altura-MEDIDA_POR_QUADRADO)/2)+4, 5*MEDIDA_POR_QUADRADO-8, MEDIDA_POR_QUADRADO-8))\r\n label = myfont.render(\"Restart!\", 1, PRETO)\r\n janela.blit(label, (int((largura-3*MEDIDA_POR_QUADRADO)/2)+2, int((largura-3*MEDIDA_POR_QUADRADO)/2+MEDIDA_POR_QUADRADO)+2))\r\n if event.type == pygame.MOUSEBUTTONDOWN :\r\n pos = pygame.mouse.get_pos()\r\n if int((largura-5*MEDIDA_POR_QUADRADO)/2) < pos[0] and int((altura-MEDIDA_POR_QUADRADO)/2) < pos[1] and pos[0] < int((largura+5*MEDIDA_POR_QUADRADO)/2) and pos[1] < int((altura+MEDIDA_POR_QUADRADO)/2):\r\n game_over = False\r\n tabuleiro = criar_tabuleiro()\r\n pygame.draw.rect(janela, PRETO, (0, 0, largura, MEDIDA_POR_QUADRADO))\r\n time_start = 0\r\n\r\n pygame.display.update()\r\n #print(time.time())\r\n desenhar_tabuleiro(tabuleiro, janela, altura)\r\n\r\nmain()" }, { "alpha_fraction": 0.6313315033912659, "alphanum_fraction": 0.6422505378723145, "avg_line_length": 35.43646240234375, "blob_id": "19d585adcf0a96adabbab5fdab45daf2bee7345f", "content_id": "7eb66f6bfd77ccfa4cf69d7a06d16a249fcd90fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6594, "license_type": "no_license", "max_line_length": 160, "num_lines": 181, "path": "/ws/python/masterMind.py", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "# ! /usr/bin/python3\n\nfrom os import system as system\nfrom random import randint\n\n'''\n\tContains functions to print board and save game variables\n'''\nclass Board:\n\tdef __init__(self):\t\t\t\t# happens when a board is created\n\t\tself.center = 24\t\t\t# used to center printing the game board \t\t\n\t\tself.numColors = 4\t\t\t# size of secret\n\t\tself.numMaxColors = 8\t\t# size of pool of colors to guess\n\t\tself.board = [\" \".join([ \"><\" for c in range(0, self.numColors)]) for i in range(0, self.numMaxColors) ]\t# starts board guess array with attempts as ><\n\t\tself.key = generateSecret()\t# generates a secret\n\n\t'''\n\t\tPrints a line\n\t\t\t- input : string, string, string\n\t\t\t\t- s : center text\n\t\t\t\t- c : filler char\n\t\t\t\t- f : start and finish char\n\t'''\n\tdef printElement(self, s='', c='-', f='-'):\t\n\t\tprint(f+s.center(self.center,c)+f)\t\n\n\t'''\n\t\tPrints game board\n\t\t\t- input : object { int, int }\n\t\t\t\t- r : dictionary with result from guess\n\t\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t\t- placed : number of digits placed in the right position\n\t'''\n\tdef printBoard(self, r={\"right\":-1,\"placed\":-1}):\n\t\tn = r.get(\"right\")\n\t\tp = r.get(\"placed\")\n\t\tself.printElement('', f='+')\n\t\tself.printElement('Master Mind'.upper(),c=' ', f='|')\n\t\tself.printElement('', f='+')\n\t\tself.printElement( self.getColorStr([str(x) for x in range(1,9)], 18, elem='n',sep =''), c=' ', f='|')\n\t\tself.printElement('', f='+')\n\t\tfor i in self.board:\n\t\t\tself.printElement(i, c=' ', f='|')\t\t\t\t\t# prints all guesses\n\n\t\tself.printElement('', f='+')\n\t\tresult='Matched colors: '+ (str(n) if n != -1 else 'X')\t\n\t\tself.printElement( result , c=' ', f='|')\n\t\tresult='Placed colors: '+ (str(p) if p != -1 else 'X')\n\t\tself.printElement( result , c=' ', f='|')\n\t\tself.printElement('', f='+')\n\n\t'''\n\t\tCreates string from sequence of numbers with corresponding colors\n\t\t\t- input : tuple, int, string, string, string, string\n\t\t\t\t- sequence : sequence of numbers to be printed with corresponding colors\n\t\t\t\t- l : variable to help center print\n\t\t\t\t- elem : toggle to display color with corresponding number\n\t\t\t\t- sep : string to separate color prints\n\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t- placed : number of digits placed in the right position\n\t\t\t- output : string\n\t\t\t\t- sep : formated string to be printed\n\t'''\n\tdef getColorStr(self, sequence, l=16, elem = ' ',sep=' ', right= ' ', placed=' '):\n\t\tf= '\\033[{};5;{}m{}\\033[0m'\n\t\tright = f.format('1;38',7,right) \t# right in white color\n\t\tplaced = f.format('1;38',1,placed)\t# placed in red color\n\n\t\tsep = sep.join([f.format('1;48',x,' '+ (str(x) if elem =='n' else ' ')) for x in sequence])\n\n\t\trhs=((self.center-l)//2)+(0 if self.center%2==0 else 1)\t# right formating spacing\n\t\tlhs= self.center-l-rhs\t\t\t\t\t\t\t\t\t# left formating spacing\n\t\tsep=right+\" \"*rhs+sep+\" \"*lhs+placed\n\t\treturn sep\n\n\t'''\n\t\tUpdates board guess array with new guess\n\t\t\t- input : int, tuple, object { int, int }\n\t\t\t\t- i : index of guess to be updated\n\t\t\t\t- t : inputed attempt from the player\n\t\t\t\t- r : dictionary with result from guess\n\t\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t\t- placed : number of digits placed in the right position\n\t'''\n\tdef updateBoard(self, i, t, r):\n\t\tself.board[i]= self.getColorStr(t,16, right= str(r.get(\"right\")), placed=str(r.get(\"placed\")))\n\n\t'''\n\t\tUses match function to update board values and print new board\n\t\t\t- input : tuple, int\n\t\t\t\t- attempt : valid input play from terminal\n\t\t\t\t- iteration : number of current try\n\t\t\t- output : boolean\n\t\t\t\t- t : test if guess is correct\n\t'''\n\tdef Guess(self, attempt, iteration ):\n\t\tanswer = match(attempt, self.key) \t\t\t\t# dictionary with {right:'',placed:''}\n\t\tself.updateBoard(iteration, attempt , answer)\n\t\tself.printBoard(r=answer)\n\t\tt = answer[\"placed\"] == self.numColors\n\t\treturn t\n\n\t'''\n\t\tPrints result of the game\n\t'''\n\tdef printResult(self, result):\n\t\tself.printElement(\"You won!\" if result else \"You lost!\", c=' ',f='|')\n\t\tself.printElement(self.getColorStr(self.key), c=' ',f='|')\n\t\tself.printElement('', c='-',f='+')\n\t\t\n# 1st - generateSecret\n'''\n\tGenerates a 4 digit long str tuple secret without repeating numbers from 1-8\n\t\t- output : tuple\n\t\t\t- t : valid inputed attempt \n'''\ndef generateSecret():\n\tr = randint\n\tl = list(range(1,9))\t\t\t\t# list with possible numbers\n\tf = []\t\t\t\t\t\t\t\t# list to save picked secret\n\tfor i in range(4):\t\t\t\t\t# picks 4 random numbers from l and appends them to f\n\t\tv = str(l.pop(r(0,len(l)-1)))\t# picks number from list and turns it into string\n\t\tf.append(v) \t\t\t\t\t# appends picked number in string form to f\n\t\n\tt = tuple(f)\t\t\t\t\t\t# turns f list to an immutable tuple\n\treturn t\n\n# 2nd - getInput\n'''\n\tGets valid input from terminal ( 4 digit long str tuple without repeating numbers from 1-8 )\n\t\t- output : tuple\n'''\ndef getInput(allowed = ''.join([str(i) for i in range(1,9)]), numMax=4):\t\t\t\t\t\t# sets allowed as a string of numbers 1-8 and max size of input as 4\n\twhile True:\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# continues to try to get valid input\n\t\ttry:\n\t\t\ts = tuple(input('Select the colors by their number: '))\t\t\t\t\t\t\t\t# gets input from terminal as a tuple\n\t\t\tif len(set(s)) == numMax and len(s) == len(set(s)) and set(s).issubset(allowed):\t# checks if input is the right size, has no repeats and is a number from 1-8\n\t\t\t\treturn s\n\t\texcept ValueError:\n\t\t\tpass\n\n# 3nd - match\n'''\n\tChecks how many digits are right and in the the right place\n\t\t- input : tuple, tuple\n\t\t\t- t : attempt\n\t\t\t- k : secret\n\t\t- output : object { int, int } \n\t\t\t- placed : number of digits placed in the right position\n\t\t\t- right : number of digits that exist in the secret\n'''\ndef match(t, k):\n\treturn\t{ \n\t\t\"placed\":[ t[x]==k[x] for x in range(0,len(k)) ].count(True),\t# goes to k and checks ou many elements are equal to t with the same index\n\t\t\"right\":len(set(k).intersection(set(t)))\t\t\t\t\t\t# chekcs intersection between k and t\n\t}\n\n# 4th - game \n'''\n\tKeeps track of game state\n'''\ndef game():\n\n\titeration = 0\t\t\t\t\t\t# variable used to keep track of the number of tries \n\tboard = Board()\t\t\t\t\t\t# creates a board secret and necessary funtions to print the game in the terminal\n\tsystem('clear')\t\t\t\t\t\t# clears the terminal\n\tboard.printBoard()\t\t\t\t\t\n\twhile iteration < 8:\t\t\t\t# gives player 8 tries\n\t\tt=getInput()\t\t\t\t\t# gets valid input from terminal\n\t\tsystem('clear')\t\t\t\t\t# clears the terminal\n\t\tif board.Guess(t, iteration):\t# breaks if player guesses the secret\n\t\t\tbreak\n\t\titeration = iteration+1\t\t\t\n\telse:\t\t\t\t\t\t\t\t# while completes without breaking then player lost\n\t\tboard.printResult(False)\t\t# prints losing message\n\t\treturn\n\n\tboard.printResult(True)\t\t\t\t# prints winning message\n\t\t\nif __name__ == \"__main__\":\n\tgame()" }, { "alpha_fraction": 0.5859375, "alphanum_fraction": 0.650390625, "avg_line_length": 26.44444465637207, "blob_id": "0ecb0bab3e8809e491732c56c51aba93b4b7177b", "content_id": "65c86aeaf0ec070feadf787500cd644b9d7ec91b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1548, "license_type": "no_license", "max_line_length": 97, "num_lines": 54, "path": "/ws/ulisboa/banaNEEC.ino", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "// define as portas analógicas de 0 a 3 como as bananas 0 a 3\r\n// define o buzzer\r\nint banana0 = A0;\r\nint banana1 = A1;\r\nint banana2 = A2;\r\nint banana3 = A3;\r\nint buzzer = 10;\r\n\r\n// a rotina de setup corre uma vez no início do programa e sempre que o butão reset é pressionado\r\nvoid setup() {\r\n Serial.begin(9600);\r\n \r\n // define as bananas como portas INPUT_PULLUP\r\n pinMode(banana0, INPUT_PULLUP);\r\n pinMode(banana1, INPUT_PULLUP);\r\n pinMode(banana2, INPUT_PULLUP);\r\n pinMode(banana3, INPUT_PULLUP);\r\n pinMode(buzzer, OUTPUT);\r\n}\r\n\r\n// a rotina loop corre infinitamente até que o o botão reset seja pressionado\r\nvoid loop() {\r\n // obter leituras dos pinos analógicos\r\n int reading0 = analogRead(banana0);\r\n int reading1 = analogRead(banana1);\r\n int reading2 = analogRead(banana2);\r\n int reading3 = analogRead(banana3);\r\n \r\n // converter as leituras analógicas (valores de 0 a 1023) para tensões (0 a 5V):\r\n float voltage0 = reading0 * (5.0 / 1023.0);\r\n float voltage1 = reading1 * (5.0 / 1023.0);\r\n float voltage2 = reading2 * (5.0 / 1023.0);\r\n float voltage3 = reading3 * (5.0 / 1023.0);\r\n \r\n // verificação das tensões para ver qual banana foi pressionada e tocar o som de cada uma\r\n if(voltage0 < 4.9){\r\n tone(buzzer, 264);\r\n }\r\n else if(voltage1 < 4.9){\r\n tone(buzzer, 297);\r\n }\r\n else if(voltage2 < 4.9){\r\n tone(buzzer, 330);\r\n }\r\n else if(voltage3 < 4.9){\r\n tone(buzzer, 352);\r\n }\r\n else{\r\n noTone(buzzer);\r\n }\r\n\r\n // print da leitura da banana0:\r\n Serial.println(voltage0);\r\n}\r\n" }, { "alpha_fraction": 0.6201273798942566, "alphanum_fraction": 0.6308280229568481, "avg_line_length": 36.75, "blob_id": "7be167baab20766540ba15141790e39a76294702", "content_id": "5f0026b45a4ecc601043b92256692b8fa83d2044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3925, "license_type": "no_license", "max_line_length": 154, "num_lines": 104, "path": "/ws/python/printBoard.py", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "'''\n\tContains functions to print board and save game variables\n'''\nclass Board:\n\tdef __init__(self):\t\t\t\t# happens when a board is created\n\t\tself.center = 24\t\t\t# used to center printing the game board \t\t\n\t\tself.numColors = 4\t\t\t# size of secret\n\t\tself.numMaxColors = 8\t\t# size of pool of colors to guess\n\t\tself.board = [\" \".join([ \"><\" for c in range(0, self.numColors)]) for i in range(0, self.numMaxColors) ]\t# starts board guess array with attempts as ><\n\t\tself.key = generateSecret()\t# generates a secret\n\n\t'''\n\t\tPrints a line\n\t\t\t- input : string, string, string\n\t\t\t\t- s : center text\n\t\t\t\t- c : filler char\n\t\t\t\t- f : start and finish char\n\t'''\n\tdef printElement(self, s='', c='-', f='-'):\t\n\t\tprint(f+s.center(self.center,c)+f)\t\n\n\t'''\n\t\tPrints game board\n\t\t\t- input : object { int, int }\n\t\t\t\t- r : dictionary with result from guess\n\t\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t\t- placed : number of digits placed in the right position\n\t'''\n\tdef printBoard(self, r={\"right\":-1,\"placed\":-1}):\n\t\tn = r.get(\"right\")\n\t\tp = r.get(\"placed\")\n\t\tself.printElement('', f='+')\n\t\tself.printElement('Master Mind'.upper(),c=' ', f='|')\n\t\tself.printElement('', f='+')\n\t\tself.printElement( self.getColorStr([str(x) for x in range(1,9)], 18, elem='n',sep =''), c=' ', f='|')\n\t\tself.printElement('', f='+')\n\t\tfor i in self.board:\n\t\t\tself.printElement(i, c=' ', f='|')\t\t\t\t\t# prints all guesses\n\n\t\tself.printElement('', f='+')\n\t\tresult='Matched colors: '+ (str(n) if n != -1 else 'X')\t\n\t\tself.printElement( result , c=' ', f='|')\n\t\tresult='Placed colors: '+ (str(p) if p != -1 else 'X')\n\t\tself.printElement( result , c=' ', f='|')\n\t\tself.printElement('', f='+')\n\n\t'''\n\t\tCreates string from sequence of numbers with corresponding colors\n\t\t\t- input : tuple, int, string, string, string, string\n\t\t\t\t- sequence : sequence of numbers to be printed with corresponding colors\n\t\t\t\t- l : variable to help center print\n\t\t\t\t- elem : toggle to display color with corresponding number\n\t\t\t\t- sep : string to separate color prints\n\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t- placed : number of digits placed in the right position\n\t\t\t- output : string\n\t\t\t\t- sep : formated string to be printed\n\t'''\n\tdef getColorStr(self, sequence, l=16, elem = ' ',sep=' ', right= ' ', placed=' '):\n\t\tf= '\\033[{};5;{}m{}\\033[0m'\n\t\tright = f.format('1;38',7,right) \t# right in white color\n\t\tplaced = f.format('1;38',1,placed)\t# placed in red color\n\n\t\tsep = sep.join([f.format('1;48',x,' '+ (str(x) if elem =='n' else ' ')) for x in sequence])\n\n\t\trhs=((self.center-l)//2)+(0 if self.center%2==0 else 1)\t# right formating spacing\n\t\tlhs= self.center-l-rhs\t\t\t\t\t\t\t\t\t# left formating spacing\n\t\tsep=right+\" \"*rhs+sep+\" \"*lhs+placed\n\t\treturn sep\n\n\t'''\n\t\tUpdates board guess array with new guess\n\t\t\t- input : int, tuple, object { int, int }\n\t\t\t\t- i : index of guess to be updated\n\t\t\t\t- t : inputed attempt from the player\n\t\t\t\t- r : dictionary with result from guess\n\t\t\t\t\t- right : number of digits that exist in the secret\n\t\t\t\t\t- placed : number of digits placed in the right position\n\t'''\n\tdef updateBoard(self, i, t, r):\n\t\tself.board[i]= self.getColorStr(t,16, right= str(r.get(\"right\")), placed=str(r.get(\"placed\")))\n\n\t'''\n\t\tUses match function to update board values and print new board\n\t\t\t- input : tuple, int\n\t\t\t\t- attempt : valid input play from terminal\n\t\t\t\t- iteration : number of current try\n\t\t\t- output : boolean\n\t\t\t\t- t : test if guess is correct\n\t'''\n\tdef Guess(self, attempt, iteration ):\n\t\tanswer = match(attempt, self.key) \t\t\t\t# dictionary with {right:'',placed:''}\n\t\tself.updateBoard(iteration, attempt , answer)\n\t\tself.printBoard(r=answer)\n\t\tt = answer[\"placed\"] == self.numColors\n\t\treturn t\n\n\t'''\n\t\tPrints result of the game\n\t'''\n\tdef printResult(self, result):\n\t\tself.printElement(\"You won!\" if result else \"You lost!\", c=' ',f='|')\n\t\tself.printElement(self.getColorStr(self.key), c=' ',f='|')\n\t\tself.printElement('', c='-',f='+')" }, { "alpha_fraction": 0.5103573203086853, "alphanum_fraction": 0.5242701172828674, "avg_line_length": 32.34462356567383, "blob_id": "6956f6d243bd03e2069572c7f3c93056f89c36e8", "content_id": "b8f533d5f5bbc3cdca358134e16873dd4a6be5e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 22641, "license_type": "no_license", "max_line_length": 153, "num_lines": 679, "path": "/games/scoreboard/assets/main.js", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "function isOdd(num) {\n return num % 2;\n}\n\nfunction sort(a, b) {\n return a.points > b.points ? -1 : a.points == b.points ? 0 : 1;\n}\nfunction logger(a) {\n //console.log(a);\n}\n\nfunction show(dia) {\n var lista = document.getElementsByTagName(\"h2\");\n var size = lista.length;\n for (a = 0; a < size; a++) {\n lista[a].setAttribute(\"class\", \"invisible\");\n }\n document.getElementById(dia).classList.remove(\"invisible\");\n\n document.getElementsByClassName(\"semana\")[0].classList.add(\"invisible\");\n document.getElementsByClassName(\"segunda\")[0].classList.add(\"invisible\");\n document.getElementsByClassName(\"terca\")[0].classList.add(\"invisible\");\n document.getElementsByClassName(\"quarta\")[0].classList.add(\"invisible\");\n document.getElementsByClassName(\"quinta\")[0].classList.add(\"invisible\");\n document.getElementsByClassName(\"sexta\")[0].classList.add(\"invisible\");\n\n document.getElementsByClassName(dia)[0].classList.remove(\"invisible\");\n}\nfunction push(Dia, RT, TR, Mem, Quiz) {\n var size = Dia.length;\n for (a = 0; a < size; a++) {\n if (Dia[a].RT != 0) {\n RT.push({ name: Dia[a].name, name2: Dia[a].name2, RT: Dia[a].RT });\n }\n if (Dia[a].TR != 0) {\n TR.push({ name: Dia[a].name, name2: Dia[a].name2, TR: Dia[a].TR });\n }\n if (Dia[a].Mem != 0) {\n Mem.push({ name: Dia[a].name, name2: Dia[a].name2, Mem: Dia[a].Mem });\n }\n if (Dia[a].Quiz != 0) {\n Quiz.push({ name: Dia[a].name, name2: Dia[a].name2, Quiz: Dia[a].Quiz });\n }\n }\n}\n\nfunction week_socores(geral, jogo) {\n var size = jogo.length;\n if (size != 0) {\n var k = 0;\n while (k < size && k < 10) {\n switch (k) {\n case 0:\n var found = geral.find((element) => element.name == jogo[k].name);\n var dex = geral\n .map(function (e) {\n return e.name;\n })\n .indexOf(jogo[k].name);\n if (found != undefined) {\n geral[dex].points = geral[dex].points + 30;\n } else {\n geral.push({ name: jogo[k].name, name2: jogo[k].name2, points: 30 });\n }\n break;\n case 1:\n var found = geral.find((element) => element.name == jogo[k].name);\n var dex = geral\n .map(function (e) {\n return e.name;\n })\n .indexOf(jogo[k].name);\n if (found != undefined) {\n geral[dex].points = geral[dex].points + 25;\n } else {\n geral.push({ name: jogo[k].name, name2: jogo[k].name2, points: 25 });\n }\n break;\n case 2:\n var found = geral.find((element) => element.name == jogo[k].name);\n var dex = geral\n .map(function (e) {\n return e.name;\n })\n .indexOf(jogo[k].name);\n if (found != undefined) {\n geral[dex].points = geral[dex].points + 20;\n } else {\n geral.push({ name: jogo[k].name, name2: jogo[k].name2, points: 20 });\n }\n break;\n case 3:\n case 4:\n var found = geral.find((element) => element.name == jogo[k].name);\n var dex = geral\n .map(function (e) {\n return e.name;\n })\n .indexOf(jogo[k].name);\n if (found != undefined) {\n geral[dex].points = geral[dex].points + 15;\n } else {\n geral.push({ name: jogo[k].name, name2: jogo[k].name2, points: 15 });\n }\n break;\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n var found = geral.find((element) => element.name == jogo[k].name);\n var dex = geral\n .map(function (e) {\n return e.name;\n })\n .indexOf(jogo[k].name);\n if (found != undefined) {\n geral[dex].points = geral[dex].points + 10;\n } else {\n geral.push({ name: jogo[k].name, name2: jogo[k].name2, points: 10 });\n }\n break;\n }\n k++;\n }\n }\n}\n\nfunction final_scores(Dia, final_RT, final_TR, final_Mem, final_Quiz) {\n var size = Dia.length;\n //console.log(size);\n for (c = 0; c < size; c++) {\n var found, dex;\n\n found = final_RT.find((element) => element.name == Dia[c].name);\n dex = final_RT\n .map(function (e) {\n return e.name;\n })\n .indexOf(Dia[c].name);\n //console.log(found);\n if (found != undefined) {\n console.log(\"Reaction Time Teste\", found.name2, found.RT);\n if (found.RT != 0) {\n //console.log(\"New Value\");\n if (Dia[c].RT != 0) {\n var higher = found.RT < Dia[c].RT ? found : Dia[c];\n console.log(\"Reaction Time\", higher.name2, higher.RT, Dia[c].RT, found.RT);\n final_RT[dex].RT = higher.RT;\n }\n }\n } else {\n if (Dia[c].RT != 0) final_RT.push({ name: Dia[c].name, name2: Dia[c].name2, RT: Dia[c].RT });\n }\n\n found = final_TR.find((element) => element.name == Dia[c].name);\n dex = final_TR\n .map(function (e) {\n return e.name;\n })\n .indexOf(Dia[c].name);\n if (found != undefined) {\n if (found.TR != 0) {\n if (Dia[c].TR != 0) {\n var higher = found.TR < Dia[c].TR ? Dia[c] : found;\n console.log(\"Typing Race\", higher.name2, higher.TR, Dia[c].TR, found.TR);\n final_TR[dex].TR = higher.TR;\n }\n }\n } else {\n if (Dia[c].TR != 0) final_TR.push({ name: Dia[c].name, name2: Dia[c].name2, TR: Dia[c].TR });\n }\n\n found = final_Mem.find((element) => element.name == Dia[c].name);\n dex = final_Mem\n .map(function (e) {\n return e.name;\n })\n .indexOf(Dia[c].name);\n if (found != undefined) {\n if (found.Mem != 0) {\n if (Dia[c].Mem != 0) {\n var higher = found.Mem < Dia[c].Mem ? found : Dia[c];\n console.log(\"Memoria\", higher.name2, higher.Mem, Dia[c].Mem, found.Mem);\n final_Mem[dex].Mem = higher.Mem;\n }\n }\n } else {\n if (Dia[c].Mem != 0) final_Mem.push({ name: Dia[c].name, name2: Dia[c].name2, Mem: Dia[c].Mem });\n }\n\n found = final_Quiz.find((element) => element.name == Dia[c].name);\n dex = final_Quiz\n .map(function (e) {\n return e.name;\n })\n .indexOf(Dia[c].name);\n if (found != undefined) {\n if (found.Quiz != 0) {\n if (Dia[c].Quiz != 0) {\n var higher = parseInt(found.Quiz) < parseInt(Dia[c].Quiz) ? Dia[c] : found;\n console.log(\"Quiz\", higher.name2, higher.Quiz, Dia[c].Quiz, found.Quiz);\n final_Quiz[dex].Quiz = higher.Quiz;\n }\n }\n } else {\n if (Dia[c].Quiz != 0) final_Quiz.push({ name: Dia[c].name, name2: Dia[c].name2, Quiz: Dia[c].Quiz });\n }\n }\n}\n\nfunction creator_geral(array, Parent_obj) {\n size = array.length;\n if (size < 3) {\n var k = 0;\n for (c = 0; c < size; c++) {\n let element = document.createElement(\"a\");\n if (k == 0) {\n element.setAttribute(\"class\", \"first\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c].points}`;\n k++;\n Parent_obj.appendChild(element);\n } else {\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c].points}`;\n k++;\n Parent_obj.appendChild(element);\n }\n }\n while (k < 3) {\n var element = document.createElement(\"a\");\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}.`;\n k++;\n Parent_obj.appendChild(element);\n }\n } else {\n var k = 0;\n for (c = 0; c < size; c++) {\n let element = document.createElement(\"a\");\n if (k == 0) {\n element.setAttribute(\"class\", \"first\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c].points}`;\n k++;\n Parent_obj.appendChild(element);\n } else {\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c].points}`;\n k++;\n Parent_obj.appendChild(element);\n }\n }\n }\n}\n\nfunction creator_jogos(array, Parent_obj, jogo) {\n size = array.length;\n if (size < 3) {\n var k = 0;\n for (c = 0; c < size; c++) {\n let element = document.createElement(\"a\");\n if (k == 0) {\n element.setAttribute(\"class\", \"first\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c][jogo]}`;\n k++;\n Parent_obj.appendChild(element);\n } else {\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c][jogo]}`;\n k++;\n Parent_obj.appendChild(element);\n }\n }\n while (k < 3) {\n var element = document.createElement(\"a\");\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}.`;\n k++;\n Parent_obj.appendChild(element);\n }\n } else {\n var k = 0;\n for (c = 0; c < size; c++) {\n let element = document.createElement(\"a\");\n if (k == 0) {\n element.setAttribute(\"class\", \"first\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c][jogo]}`;\n k++;\n Parent_obj.appendChild(element);\n } else {\n element.setAttribute(\"class\", \"next\");\n element.innerText = `${k + 1}. ${array[c].name2} - ${array[c][jogo]}`;\n k++;\n Parent_obj.appendChild(element);\n }\n }\n }\n}\n\nfunction loadFile(ip) {\n var today = new Date();\n var dd = String(today.getDate()).padStart(2, \"0\");\n //console.log(dd);\n switch (dd) {\n case \"15\":\n //console.log(document.getElementById(\"seg_live\"));\n document.getElementById(\"seg_live\").classList.remove(\"d_none\");\n break;\n case \"16\":\n document.getElementById(\"ter_live\").classList.remove(\"d_none\");\n break;\n case \"17\":\n document.getElementById(\"qua_live\").classList.remove(\"d_none\");\n break;\n case \"18\":\n document.getElementById(\"qui_live\").classList.remove(\"d_none\");\n break;\n case \"19\":\n document.getElementById(\"sex_live\").classList.remove(\"d_none\");\n break;\n\n default:\n break;\n }\n\n var result = null;\n var xmlhttp = new XMLHttpRequest();\n var filePath = \"\";\n xmlhttp.open(\"GET\", filePath, false);\n xmlhttp.send();\n var seg = [],\n ter = [],\n qua = [],\n qui = [],\n sex = [];\n var final_RT = [],\n final_TR = [],\n final_Mem = [],\n final_Quiz = [];\n\n var seg_RT = [],\n seg_TR = [],\n seg_Mem = [],\n seg_Quiz = [];\n var ter_RT = [],\n ter_TR = [],\n ter_Mem = [],\n ter_Quiz = [];\n var qua_RT = [],\n qua_TR = [],\n qua_Mem = [],\n qua_Quiz = [];\n var qui_RT = [],\n qui_TR = [],\n qui_Mem = [],\n qui_Quiz = [];\n var sex_RT = [],\n sex_TR = [],\n sex_Mem = [],\n sex_Quiz = [];\n\n var geral = [];\n\n if (xmlhttp.status == 200) {\n result = xmlhttp.responseText;\n result = result.replace(/\"/gm, \"\");\n //console.log(result);\n //document.getElementById(\"text\").innerText = result;\n var splitted = result.split(/,|\\n/gm);\n var size = splitted.length;\n var a = 8;\n var b = 1;\n\n while (splitted[a] != undefined) {\n switch (b) {\n case 1:\n seg.push({ name: splitted[a + 1], name2: splitted[a], RT: splitted[a + 2], TR: splitted[a + 3], Mem: splitted[a + 4], Quiz: splitted[a + 5] });\n break;\n case 2:\n ter.push({ name: splitted[a + 1], name2: splitted[a], RT: splitted[a + 2], TR: splitted[a + 3], Mem: splitted[a + 4], Quiz: splitted[a + 5] });\n break;\n case 3:\n qua.push({ name: splitted[a + 1], name2: splitted[a], RT: splitted[a + 2], TR: splitted[a + 3], Mem: splitted[a + 4], Quiz: splitted[a + 5] });\n break;\n case 4:\n qui.push({ name: splitted[a + 1], name2: splitted[a], RT: splitted[a + 2], TR: splitted[a + 3], Mem: splitted[a + 4], Quiz: splitted[a + 5] });\n break;\n case 5:\n sex.push({ name: splitted[a + 1], name2: splitted[a], RT: splitted[a + 2], TR: splitted[a + 3], Mem: splitted[a + 4], Quiz: splitted[a + 5] });\n break;\n\n default:\n break;\n }\n a = a + 6;\n //console.log(a);\n if (splitted[a] == undefined) {\n continue;\n } else if (splitted[a].startsWith(\"###\")) {\n a++;\n b++;\n //console.log(\"Day Skip\");\n continue;\n } else if (splitted[a].startsWith(\"*\")) {\n a++;\n //console.log(\"Next\");\n }\n //console.log(a);\n }\n\n var size = seg.length;\n for (c = 0; c < size; c++) {\n if (seg[c].RT != 0) {\n final_RT.push({ name: seg[c].name, name2: seg[c].name2, RT: seg[c].RT });\n seg_RT.push({ name: seg[c].name, name2: seg[c].name2, RT: seg[c].RT });\n }\n if (seg[c].TR != 0) {\n final_TR.push({ name: seg[c].name, name2: seg[c].name2, TR: seg[c].TR });\n seg_TR.push({ name: seg[c].name, name2: seg[c].name2, TR: seg[c].TR });\n }\n if (seg[c].Mem != 0) {\n final_Mem.push({ name: seg[c].name, name2: seg[c].name2, Mem: seg[c].Mem });\n seg_Mem.push({ name: seg[c].name, name2: seg[c].name2, Mem: seg[c].Mem });\n }\n if (seg[c].Quiz != 0) {\n final_Quiz.push({ name: seg[c].name, name2: seg[c].name2, Quiz: seg[c].Quiz });\n seg_Quiz.push({ name: seg[c].name, name2: seg[c].name2, Quiz: seg[c].Quiz });\n }\n }\n\n push(ter, ter_RT, ter_TR, ter_Mem, ter_Quiz);\n push(qua, qua_RT, qua_TR, qua_Mem, qua_Quiz);\n push(qui, qui_RT, qui_TR, qui_Mem, qui_Quiz);\n push(sex, sex_RT, sex_TR, sex_Mem, sex_Quiz);\n\n //////////////////////////////\n\n seg_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n seg_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n seg_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n seg_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n\n size = seg_RT.length;\n if (size != 0) {\n var k = 0;\n while (k < size && k < 10) {\n //console.log(k, seg_RT[k].name2);\n switch (k) {\n case 0:\n geral.push({ name: seg_RT[k].name, name2: seg_RT[k].name2, points: 30 });\n break;\n case 1:\n geral.push({ name: seg_RT[k].name, name2: seg_RT[k].name2, points: 25 });\n break;\n case 2:\n geral.push({ name: seg_RT[k].name, name2: seg_RT[k].name2, points: 20 });\n break;\n case 3:\n case 4:\n geral.push({ name: seg_RT[k].name, name2: seg_RT[k].name2, points: 15 });\n break;\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n geral.push({ name: seg_RT[k].name, name2: seg_RT[k].name2, points: 10 });\n break;\n }\n k++;\n }\n }\n week_socores(geral, seg_TR);\n week_socores(geral, seg_Mem);\n week_socores(geral, seg_Quiz);\n\n //////////////////////////////\n\n //////////////////////////////\n\n ter_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n ter_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n ter_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n ter_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n\n week_socores(geral, ter_RT);\n week_socores(geral, ter_TR);\n week_socores(geral, ter_Mem);\n week_socores(geral, ter_Quiz);\n\n //////////////////////////////\n\n //////////////////////////////\n\n qua_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n qua_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n qua_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n qua_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n\n week_socores(geral, qua_RT);\n week_socores(geral, qua_TR);\n week_socores(geral, qua_Mem);\n week_socores(geral, qua_Quiz);\n //////////////////////////////\n\n //////////////////////////////\n\n qui_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n qui_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n qui_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n qui_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n\n week_socores(geral, qui_RT);\n week_socores(geral, qui_TR);\n week_socores(geral, qui_Mem);\n week_socores(geral, qui_Quiz);\n //////////////////////////////\n\n //////////////////////////////\n\n sex_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n sex_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n sex_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n sex_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n\n week_socores(geral, sex_RT);\n week_socores(geral, sex_TR);\n week_socores(geral, sex_Mem);\n week_socores(geral, sex_Quiz);\n\n ///////////////////////\n final_scores(ter, final_RT, final_TR, final_Mem, final_Quiz);\n final_scores(qua, final_RT, final_TR, final_Mem, final_Quiz);\n final_scores(qui, final_RT, final_TR, final_Mem, final_Quiz);\n final_scores(sex, final_RT, final_TR, final_Mem, final_Quiz);\n //////////////////////////\n\n final_RT.sort(function (a, b) {\n return parseFloat(a.RT) < parseFloat(b.RT) ? -1 : parseFloat(a.RT) == parseFloat(b.RT) ? 0 : 1;\n });\n final_TR.sort(function (a, b) {\n return parseInt(a.TR) > parseInt(b.TR) ? -1 : parseInt(a.TR) == parseInt(b.TR) ? 0 : 1;\n });\n final_Mem.sort(function (a, b) {\n return parseFloat(a.Mem) < parseFloat(b.Mem) ? -1 : parseFloat(a.Mem) == parseFloat(b.Mem) ? 0 : 1;\n });\n final_Quiz.sort(function (a, b) {\n return parseInt(a.Quiz) > parseInt(b.Quiz) ? -1 : parseInt(a.Quiz) == parseInt(b.Quiz) ? 0 : 1;\n });\n geral.sort(function (a, b) {\n return parseInt(a.points) > parseInt(b.points) ? -1 : parseInt(a.points) == parseInt(b.points) ? 0 : 1;\n });\n //console.log(final_RT);\n //console.log(final_TR);\n //console.log(final_Mem);\n //console.log(final_Quiz);\n\n var RT_obj = document.getElementById(\"RT_semana\");\n var TR_obj = document.getElementById(\"TR_semana\");\n var Mem_obj = document.getElementById(\"Mem_semana\");\n var Quiz_obj = document.getElementById(\"Quiz_semana\");\n var Geral_obj = document.getElementById(\"GERAL\");\n\n var seg_RT_obj = document.getElementById(\"RT_seg\");\n var seg_TR_obj = document.getElementById(\"TR_seg\");\n var seg_Mem_obj = document.getElementById(\"Mem_seg\");\n var seg_Quiz_obj = document.getElementById(\"Quiz_seg\");\n\n var ter_RT_obj = document.getElementById(\"RT_ter\");\n var ter_TR_obj = document.getElementById(\"TR_ter\");\n var ter_Mem_obj = document.getElementById(\"Mem_ter\");\n var ter_Quiz_obj = document.getElementById(\"Quiz_ter\");\n\n var qua_RT_obj = document.getElementById(\"RT_qua\");\n var qua_TR_obj = document.getElementById(\"TR_qua\");\n var qua_Mem_obj = document.getElementById(\"Mem_qua\");\n var qua_Quiz_obj = document.getElementById(\"Quiz_qua\");\n\n var qui_RT_obj = document.getElementById(\"RT_qui\");\n var qui_TR_obj = document.getElementById(\"TR_qui\");\n var qui_Mem_obj = document.getElementById(\"Mem_qui\");\n var qui_Quiz_obj = document.getElementById(\"Quiz_qui\");\n\n var sex_RT_obj = document.getElementById(\"RT_sex\");\n var sex_TR_obj = document.getElementById(\"TR_sex\");\n var sex_Mem_obj = document.getElementById(\"Mem_sex\");\n var sex_Quiz_obj = document.getElementById(\"Quiz_sex\");\n\n creator_geral(geral, Geral_obj);\n\n creator_jogos(final_RT, RT_obj, \"RT\");\n creator_jogos(final_TR, TR_obj, \"TR\");\n creator_jogos(final_Mem, Mem_obj, \"Mem\");\n creator_jogos(final_Quiz, Quiz_obj, \"Quiz\");\n\n ////////////////////////////////\n\n creator_jogos(seg_RT, seg_RT_obj, \"RT\");\n creator_jogos(seg_TR, seg_TR_obj, \"TR\");\n creator_jogos(seg_Mem, seg_Mem_obj, \"Mem\");\n creator_jogos(seg_Quiz, seg_Quiz_obj, \"Quiz\");\n\n ////////////////////////////////\n\n creator_jogos(ter_RT, ter_RT_obj, \"RT\");\n creator_jogos(ter_TR, ter_TR_obj, \"TR\");\n creator_jogos(ter_Mem, ter_Mem_obj, \"Mem\");\n creator_jogos(ter_Quiz, ter_Quiz_obj, \"Quiz\");\n\n ////////////////////////////////\n\n creator_jogos(qua_RT, qua_RT_obj, \"RT\");\n creator_jogos(qua_TR, qua_TR_obj, \"TR\");\n creator_jogos(qua_Mem, qua_Mem_obj, \"Mem\");\n creator_jogos(qua_Quiz, qua_Quiz_obj, \"Quiz\");\n\n ////////////////////////////////\n\n creator_jogos(qui_RT, qui_RT_obj, \"RT\");\n creator_jogos(qui_TR, qui_TR_obj, \"TR\");\n creator_jogos(qui_Mem, qui_Mem_obj, \"Mem\");\n creator_jogos(qui_Quiz, qui_Quiz_obj, \"Quiz\");\n\n ///////////////////////////////\n\n creator_jogos(sex_RT, sex_RT_obj, \"RT\");\n creator_jogos(sex_TR, sex_TR_obj, \"TR\");\n creator_jogos(sex_Mem, sex_Mem_obj, \"Mem\");\n creator_jogos(sex_Quiz, sex_Quiz_obj, \"Quiz\");\n\n ///////////////////////////////\n\n document.getElementById(\"outer_box\").setAttribute(\"class\", \"d_none\");\n document.getElementById(\"semana\").classList.remove(\"invisible\");\n document.getElementById(\"gif\").setAttribute(\"class\", \"d_none\");\n var elements = document.getElementsByClassName(\"semana\");\n elements[0].classList.remove(\"invisible\");\n }\n}\n" }, { "alpha_fraction": 0.695652186870575, "alphanum_fraction": 0.695652186870575, "avg_line_length": 22.14285659790039, "blob_id": "1b9aebaeee4b2b029dc56af486110167445d6f88", "content_id": "932d82bee0067617f2ba0c709f0328cafc26c54b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 161, "license_type": "no_license", "max_line_length": 58, "num_lines": 7, "path": "/games/script.js", "repo_name": "NEECIST/neecist.org", "src_encoding": "UTF-8", "text": "function setGif(image) {\n document.body.style.backgroundImage = `url(${image})`;\n}\n\nfunction removeGif() {\n document.body.style.backgroundImage = \"none\";\n}" } ]
12
fourmajor/perfectabstractionsjsonconversion
https://github.com/fourmajor/perfectabstractionsjsonconversion
af4060fe81578d8747d65ed0e06d0d44adc4800f
74ce855b0dc26b3f66876a421f31f834cabeff63
f5ff794fcbf02adb620fc6a7659518c7e731d170
refs/heads/master
2021-01-16T21:43:15.608444
2016-09-22T04:07:25
2016-09-22T04:07:25
68,318,299
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.620673656463623, "alphanum_fraction": 0.635307788848877, "avg_line_length": 33.59504318237305, "blob_id": "fde551a049d4358eb4a2c0cee41bb5c14908cef3", "content_id": "b9084fb97e437fcbdc92a71f7be18f83040f0b8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4305, "license_type": "no_license", "max_line_length": 79, "num_lines": 121, "path": "/convert.py", "repo_name": "fourmajor/perfectabstractionsjsonconversion", "src_encoding": "UTF-8", "text": "import re\r\nimport string\r\nimport sys\r\n\r\n# simplejson should be in your working directory as specified below\r\nsys.path.append(\"./json/\")\r\nimport simplejson as json\r\n\r\n# separate the headers from the bodies\r\nformat2 = re.split(\"S([0-9]*)F([0-9]*)\\s*\\naccept reply: (.*)\", \\\r\nopen(\"format1.txt\", \"r\").read())\r\n\r\n#get rid of extra whitespace, get rid of first line containing \"data\"\r\nformat2 = [item.strip() for item in format2]\r\nformat2 = format2[1:]\r\n\r\n# each item contains SF code, reply, level, and body, which is four things\r\n# therefore we need to divide total length of format2 by four to get total\r\n# number of items\r\nnumitems = len(format2) / 4\r\n\r\nlistofdicts = list()\r\ni = 0\r\n\r\n# now we take our messy list with different data types smooshed together\r\n# and organize it in a list of dictionaries\r\nwhile i < numitems:\r\n\tlistofdicts.append({\"header\":{\"stream\":format2[i * 4], \\\r\n\t\"function\":format2[i * 4 + 1], \"reply\":format2[i * 4 + 2]}, \\\r\n\t\"body\":format2[i * 4 + 3]})\r\n\ti += 1\r\n\r\n# main workhorse function. nests items based on level (\"L#\" in format1)\r\n# via some recursive action. Also properly formats the body data based on\r\n# the type of data it is, and renamed variable types.\r\ndef createnestedbody(itembody, level):\r\n\ti = 0\r\n\tnewbody = list()\r\n\tregexstring = \"(?:float|integer|asc|bool).+?(?=(?:float|integer|asc|bool|\\Z))\"\r\n\twhile i < len(itembody):\r\n\t\t# the following if/elif/else takes different action depending on if\r\n\t\t# this item is on the current level or not.\r\n\t\tif (int(itembody[i]) == level):\r\n\t\t\tlistofitems = list()\r\n\t\t\tif len(itembody[i+1]) > 1:\r\n\t\t\t\t# splits out the individual body entries based on starting \r\n\t\t\t\t# with keywords, followed by anything (including newlines), \r\n\t\t\t\t# and up to but not including another keyword or end of string\r\n\t\t\t\t# re.S allows multiline searching\r\n\t\t\t\tfor line in re.findall(regexstring, itembody[i+1], \\\r\n\t\t\t\tre.S | re.IGNORECASE):\r\n\t\t\t\t\t# now that we have individual body entries we have to \r\n\t\t\t\t\t# split around the commas\r\n\t\t\t\t\titemsplit = line.split(\",\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t# depending on the data type we convert differently\r\n\t\t\t\t\tif(itemsplit[0].lower() == \"float\") :\r\n\t\t\t\t\t\titemsplit[0] = \"F4\"\r\n\t\t\t\t\t\titemsplit[1:] = map(float, itemsplit[1:])\r\n\t\t\t\t\telif(itemsplit[0].lower() == \"integer\") :\r\n\t\t\t\t\t\titemsplit[0] = \"U4\"\r\n\t\t\t\t\t\titemsplit[1:] = map(int, itemsplit[1:])\r\n\t\t\t\t\telif(itemsplit[0].lower() == \"asc\") :\r\n\t\t\t\t\t\titemsplit[0] = \"A\"\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# strip both newlines and quotes from beginning and end\r\n\t\t\t\t\t\t# of the strings\r\n\t\t\t\t\t\titemsplit[1:] = \\\r\n\t\t\t\t\t\t[string.strip(x, \"\\\"\\n\") for x in itemsplit[1:]]\r\n\t\t\t\t\telif(itemsplit[0].lower() == \"bool\") :\r\n\t\t\t\t\t\titemsplit[0] = \"Boolean\"\r\n\t\t\t\t\t\titemsplit[1:] = \\\r\n\t\t\t\t\t\t[(lambda x: \"true\" in x)(x) for x in itemsplit[1:]]\r\n\t\t\t\t\t\r\n\t\t\t\t\t# if myvalue is only one item long, we make it not a list\r\n\t\t\t\t\tmyvalue = itemsplit[1:]\r\n\t\t\t\t\tif(len(myvalue) == 1): myvalue = myvalue[0]\r\n\t\t\t\t\t\r\n\t\t\t\t\tlistofitems.append({\"format\" : itemsplit[0], \"value\" : myvalue})\r\n\t\t\t\r\n\t\t\t# again of the list of format:values is only one, we make it not a \r\n\t\t\t# list\r\n\t\t\tif(len(listofitems) == 1): listofitems = listofitems[0]\r\n\t\t\tnewbody.append(listofitems)\r\n\t\t\t\r\n\t\t\t# iterate by two, because in this list one value is the level, \r\n\t\t\t# the next is the body\r\n\t\t\ti += 2\r\n\t\t\t\r\n\t\t# if the level of this item is higher than our current level, we \r\n\t\t# return to get to previous recursion level\t\r\n\t\telif (int(itembody[i]) > level):\r\n\t\t\treturn (newbody, i)\r\n\t\t\r\n\t\t# if level is less than current level, we recurse\r\n\t\telse:\r\n\t\t\t(itemstoappend, iterations) = createnestedbody(itembody[i:], \\\r\n\t\t\tint(itembody[i]))\r\n\t\t\tnewbody.append(itemstoappend)\r\n\t\t\ti += iterations\r\n\t\r\n\t# we return i so we know how many items we have gone through, this being\r\n\t# a recursive function\r\n\treturn (newbody, i)\r\n\r\n# for each header/body combo\t\r\nfor item in listofdicts:\r\n\t# get the item levels\r\n\titem[\"body\"] = re.split(\"L,([0-9])\", item[\"body\"])[1:]\r\n\t\r\n\t# clean up white space from our bodies\r\n\titem[\"body\"] = [x.strip() for x in item[\"body\"]]\r\n\t\r\n\t# create our nested body\r\n\tif(len(item[\"body\"]) > 0):\r\n\t\t(item[\"body\"], trash) = createnestedbody(item[\"body\"],\\\r\n\t\tint(item[\"body\"][0]))\r\n\telse: item[\"body\"] = list()\r\n\r\n# use JSON library to make our output pretty and valid\r\nprint json.dumps(listofdicts, indent=4, separators=(',', ': '))" } ]
1
simgeekiz/FashionChallenge
https://github.com/simgeekiz/FashionChallenge
0308fa63ea8fbeb5c2721b7d9b732f189d19b8a6
15516ecbbccd1249993bc8f49542eb8373acd38b
65a337b3c205a7543699db0d3f8c35bd78c38f22
refs/heads/master
2022-12-20T12:25:50.823539
2018-06-25T20:11:05
2018-06-25T20:11:05
132,666,409
0
0
null
2018-05-08T21:18:40
2018-06-25T20:11:07
2022-11-22T02:31:01
Jupyter Notebook
[ { "alpha_fraction": 0.626838207244873, "alphanum_fraction": 0.6312500238418579, "avg_line_length": 22.504505157470703, "blob_id": "43bfa12266393bd9be64afb9deab7a2d28e77e7c", "content_id": "10f2aaf931c8802b6b57302510f849985591a88d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2720, "license_type": "no_license", "max_line_length": 130, "num_lines": 111, "path": "/data_preparation/testbatchgeneratortrain.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nfrom keras.preprocessing import sequence\r\nimport sklearn\r\nimport argparse\r\nimport cPickle\r\nimport gzip \r\nimport json\r\nfrom tensorflow.python.lib.io import file_io\r\nimport random\r\n\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, Embedding, LSTM, Activation, BatchNormalization, Conv2D, MaxPooling2D, Dropout, Flatten, MaxPool2D\r\nfrom keras import optimizers\r\n\r\nfrom batch_generator import BatchGenerator, BatchSequence\r\n\r\nfrom PIL import Image\r\n\r\nimport tensorflow as tf\r\n\r\n\t\r\n\t\r\n\r\n\r\n\r\n\r\ndef load_data(path):\r\n\r\n # Load images\r\n\t\r\n \r\n # Load and decompress training labels\r\n with file_io.FileIO(path + 'data/y_train.pickle', mode='rb') as fp:\r\n data = gzip.GzipFile(fileobj=fp)\r\n y_train = cPickle.load(data)\r\n \r\n # Load and decompress validation labels\r\n with file_io.FileIO(path + 'data/y_validation.pickle', mode='rb') as fp:\r\n data = gzip.GzipFile(fileobj=fp)\r\n y_validation = cPickle.load(data)\r\n \r\n return y_train, y_validation\r\n\t\r\n\r\ndef preprocessing(dir):\r\n return None\r\n\r\ndef create_model():\r\n model = Sequential()\r\n model.add(Dense(42, activation='relu'))\r\n model.add((Dense(6, activation='sigmoid')))\r\n\r\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\r\n\r\n model.summary()\r\n\r\n return model\r\n\r\n\r\ndef main(train_file, test_file, job_dir):\r\n y_train, y_validation = load_data(train_file)\r\n print(\"test1\")\r\n training_gen = BatchGenerator(\r\n input_dir=images_path_train,\r\n y=y_train,\r\n batch_size=32,\r\n shuffle=False,\r\n img_size=290\r\n )\r\n\r\n for batch_x, batch_y in training_gen:\r\n print(batch_x.shape)\r\n print(batch_y.shape)\r\n break\r\n \r\n print(\"succes\")\r\n print(y_train.shape,y_validation.shape)\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n The argparser can also be extended to take --n-epochs or --batch-size arguments\r\n \"\"\"\r\n parser = argparse.ArgumentParser()\r\n \r\n # Input Arguments\r\n parser.add_argument(\r\n '--train-file',\r\n help='GCS or local paths to training data',\r\n required=True\r\n )\r\n\r\n parser.add_argument(\r\n '--test-file',\r\n help='GCS or local paths to test data',\r\n required=False\r\n )\r\n\r\n parser.add_argument(\r\n '--job-dir',\r\n help='GCS location to write checkpoints and export models',\r\n required=True\r\n )\r\n args = parser.parse_args()\r\n arguments = args.__dict__\r\n print('args: {}'.format(arguments))\r\n\r\n main(args.train_file, args.test_file, args.job_dir)\r\n" }, { "alpha_fraction": 0.6131687164306641, "alphanum_fraction": 0.6502057909965515, "avg_line_length": 33.71428680419922, "blob_id": "4963256134dab4cc3e25f02813209557152f7d35", "content_id": "769d2e783cec2869431e6cd04e345d901310a2e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 80, "num_lines": 14, "path": "/model/trainer/confusion_matrix.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "import numpy as np\n\n# Computes the confusion matrix given 'many-hot' encoded predictions and labels.\n# Rows in the confusion matrix are in the following order: tp, fp, tn, fn.\ndef confusion_matrix(y_true, y_pred):\n\tconfusion = np.zeros(228,4)\n\n\tfor i in range(228):\n\t\tconfusion[0][0] = sum(y_true[i] & y_pred[i])\n\t\tconfusion[0][1] = sum((1 - y_true[i]) & y_pred)\n\t\tconfusion[0][2] = sum(1 - (y_true[i] & y_pred[i]))\n\t\tconfusion[0][3] = sum(y_true[i] & (1 - y_pred))\n\t\n\treturn confusion\n" }, { "alpha_fraction": 0.6833406090736389, "alphanum_fraction": 0.702914297580719, "avg_line_length": 26.382715225219727, "blob_id": "fe7f653121ad7375e1026d40842b7836b5abe35c", "content_id": "03e43caec7ae519c69d590a731abf58636a3af6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4598, "license_type": "no_license", "max_line_length": 103, "num_lines": 162, "path": "/model/trainer/train.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport tensorflow as tf\r\n\r\nimport sklearn\r\nimport argparse\r\nimport cPickle\r\nimport gzip \r\nimport json\r\nimport random\r\nimport os\r\n\r\nfrom tensorflow.python.lib.io import file_io\r\nfrom keras.models import Model\r\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout\r\nfrom keras.applications import Xception, VGG16, VGG19, ResNet50, InceptionV3\r\n\r\nfrom data_preparation.batchgenerator import BatchGenerator, BatchSequence\r\nfrom exception_callbacks.callbacks import all_call_backs \r\n\r\ndef load_data(path):\r\n\t# Load and decompress training labels\r\n\twith file_io.FileIO(path + 'data/y_train.pickle', mode='rb') as fp:\r\n\t\tdata = gzip.GzipFile(fileobj=fp)\r\n\t\ty_train = cPickle.load(data)\r\n\t\r\n\t# Load and decompress validation labels\r\n\twith file_io.FileIO(path + 'data/y_validation.pickle', mode='rb') as fp:\r\n\t\tdata = gzip.GzipFile(fileobj=fp)\r\n\t\ty_validation = cPickle.load(data)\r\n\t\r\n\treturn y_train, y_validation\t\r\n\r\ndef preprocessing(dir):\r\n\treturn None\r\n\r\ndef fine_tune_model(base_model):\r\n\t# Adding the last two fully-connected layers\r\n\tx = base_model.output\r\n\tx = GlobalAveragePooling2D()(x) \t\t# global average pooling (flatten)\r\n\tx = Dense(1024, activation='relu')(x) \t# should be rather large with 228 output labels\r\n\ty = Dense(228, activation='softmax')(x)\t# sigmoid instead of softmax to have independent probabilities\r\n\r\n\tmodel = Model(inputs=base_model.input, outputs=y)\r\n\t\r\n\t# Unfreeze last few layers\r\n\tfor layer in base_model.layers[:-4]:\r\n\t\tlayer.trainable = False\r\n\tfor layer in base_model.layers[-4:]:\r\n\t\tlayer.trainable = True\r\n\r\n\t# Use binary loss instead of categorical loss to penalize each output independently\r\n\tmodel.compile(optimizer='adam', loss='binary_crossentropy')\r\n\r\n\treturn model\r\n\r\ndef get_models():\r\n\t\"\"\"Get all five pretrained models.\"\"\"\r\n\tmodels = []\r\n\t\r\n\txception_base = Xception(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\txception = fine_tune_model(xception_base)\r\n\tmodels.append(xception)\r\n\t\r\n\tvgg16_base = VGG16(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\tvgg16 = fine_tune_model(vgg16_base)\r\n\tmodels.append(vgg16)\r\n\r\n\tvgg19_base = VGG19(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\tvgg19 = fine_tune_model(vgg19_base)\r\n\tmodels.append(vgg19)\r\n\r\n\tresnet_base = ResNet50(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\tresnet = fine_tune_model(resnet_base)\r\n\tmodels.append(resnet)\r\n\r\n\tinception_base = InceptionV3(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\tinception = fine_tune_model(inception_base)\r\n\tmodels.append(inception)\r\n\r\n\treturn models\r\n\r\ndef main(train_file, test_file, job_dir, n_epochs):\r\n\ty_train, y_validation = load_data(train_file)\r\n\r\n\timages_path_train = os.path.join(train_file, 'data/train/')\r\n\timages_path_validation = os.path.join(train_file, 'data/validation/')\r\n\t\r\n\tepochs = 30\r\n\tcallbacks = all_call_backs()\r\n\tbatch_size = 128\r\n\r\n\ttraining_gen = BatchGenerator(\r\n\t\tinput_dir=images_path_train,\r\n\t\ty=y_train,\r\n\t\tbatch_size=batch_size,\r\n\t\tshuffle=True,\r\n\t\timg_size=290\r\n\t)\r\n\r\n\tvalidation_gen = BatchSequence(\r\n\t\tinput_dir=images_path_validation,\r\n\t\ty=y_validation,\r\n\t\tbatch_size=batch_size,\r\n\t\tshuffle=True,\r\n\t\timg_size=290\r\n\t)\r\n\r\n\t# Initialize some pretrained keras model, add more models if want to stack/ensemble them\r\n\tmodels = get_models()\r\n\t\r\n\t# Train all models\r\n\tfor model in models:\r\n\t\t# Need to still define keras.utils.Sequence to use fit_generator\r\n\t\tmodel.fit_generator(\r\n\t\t\tgenerator=training_gen,\r\n\t\t\tcallbacks=callbacks,\r\n\t\t\tsteps_per_epoch=int(len(y_train)/batch_size),\r\n\t\t\tepochs=epochs,\r\n\t\t\tvalidation_data=validation_gen,\r\n\t\t\tvalidation_steps=int(len(y_validation)/batch_size)\r\n\t\t)\r\n\t\t\t\r\n\tprint(\"main success\")\r\n\r\nif __name__ == '__main__':\r\n\t\"\"\"\r\n\tThe argparser can also be extended to take --n-epochs or --batch-size arguments\r\n\t\"\"\"\r\n\tparser = argparse.ArgumentParser()\r\n\t\r\n\t# Input Arguments\r\n\tparser.add_argument(\r\n\t '--train-file',\r\n\t help='GCS or local paths to training data',\r\n\t required=True\r\n\t)\r\n\r\n\tparser.add_argument(\r\n\t '--test-file',\r\n\t help='GCS or local paths to test data',\r\n\t required=True\r\n\t)\r\n\r\n\tparser.add_argument(\r\n\t\t'--job-dir',\r\n\t\thelp='GCS location to write checkpoints and export models',\r\n\t\trequired=True\r\n\t)\r\n\r\n\tparser.add_argument(\r\n\t\t'--n-epochs',\r\n\t\thelp='Number of epochs to train the model for',\r\n\t\trequired=True\r\n\t)\r\n\targs = parser.parse_args()\r\n\targuments = args.__dict__\r\n\tprint('args: {}'.format(arguments))\r\n\r\n\tmain(args.train_file, args.test_file, args.job_dir, args.n_epochs)\r\n" }, { "alpha_fraction": 0.717377245426178, "alphanum_fraction": 0.7386950850486755, "avg_line_length": 30.92783546447754, "blob_id": "7bb60d0e98321d6ff48edd64da525068f321f6fe", "content_id": "a2368a2a8f11dbcfc02fcb9f96d0e609586f16fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3096, "license_type": "no_license", "max_line_length": 102, "num_lines": 97, "path": "/pretrained_network/Pretrained-networks/ResNet50/ResNet50.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "from os.path import join\n\nfrom keras.applications import ResNet50\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout\nfrom keras.models import Model, load_model\nfrom keras.utils.np_utils import to_categorical\n\nimport pandas as pd\nimport csv\nimport os\nimport numpy as np\nimport json\n\nfrom matplotlib import pyplot as plt\nimport sys\nsys.path.append(\"../../data_preparation/\")\n\nfrom batch_generator import BatchGenerator, BatchSequence\n\nfrom sklearn.metrics import recall_score, precision_score, f1_score\n\n\n#datadir = os.getcwd()\ninput_path = os.path.abspath('../../../mlipdata/')\n\ntrain={}\ntest={}\nvalidation={}\nwith open(os.path.join(input_path, 'train.json')) as json_data:\n train= json.load(json_data)\nwith open(os.path.join(input_path, 'test.json')) as json_data:\n test= json.load(json_data)\nwith open(os.path.join(input_path, 'validation.json')) as json_data:\n validation = json.load(json_data)\n\nprint('Train No. of images: %d'%(len(train['images'])))\nprint('Test No. of images: %d'%(len(test['images'])))\nprint('Validation No. of images: %d'%(len(validation['images'])))\n\n# JSON TO PANDAS DATAFRAME\n# train data\ntrain_img_url=train['images']\ntrain_img_url=pd.DataFrame(train_img_url)\ntrain_ann=train['annotations']\ntrain_ann=pd.DataFrame(train_ann)\ntrain=pd.merge(train_img_url, train_ann, on='imageId', how='inner')\n\n# test data\ntest=pd.DataFrame(test['images'])\n\n# Validation Data\nval_img_url=validation['images']\nval_img_url=pd.DataFrame(val_img_url)\nval_ann=validation['annotations']\nval_ann=pd.DataFrame(val_ann)\nvalidation=pd.merge(val_img_url, val_ann, on='imageId', how='inner')\n\ndatas = {'Train': train, 'Test': test, 'Validation': validation}\nfor data in datas.values():\n data['imageId'] = data['imageId'].astype(np.uint32)\n \n \nimages_path_train = os.path.abspath('../../../mlipdata/files/train/')\n\nfrom sklearn.preprocessing import MultiLabelBinarizer\nmlb = MultiLabelBinarizer()\n# loading labels\ny_train = np.array(train.labelId)\ny_validation = np.array(validation.labelId)\n\ny_train1000 = mlb.fit_transform(y_train)[:1000]\ny_validation500 = mlb.fit_transform(y_validation)[:500]\n\n# load the generator\ntraining_gen = BatchGenerator(input_dir=images_path_train, y=y_train1000, batch_size=64)\n\nbase_model = ResNet50(weights='imagenet', include_top=False, input_shape=(290,290,3))\n\n# Adding the last two fully-connected layers\nx = base_model.output\nx = GlobalAveragePooling2D()(x) # global average pooling (flatten)\nx = Dense(1024, activation='relu')(x) # should be rather large with 228 output labels\n#x = Dropout(0.5)(x)\ny = Dense(228, activation='softmax')(x) # sigmoid instead of softmax to have independent probabilities\n\nmodel = Model(inputs=base_model.input, outputs=y)\n# Train only the top layer\nfor layer in base_model.layers:\n layer.trainable = False\n \n# Use binary loss instead of categorical loss to penalize each output independently\nmodel.compile(optimizer='adam', loss='binary_crossentropy')\n\n# 1000 steps = 640000 random images per epoch\nmodel.fit_generator(training_gen, steps_per_epoch=100, epochs=10)\n\nmodel.save('./ResNet50.h5')" }, { "alpha_fraction": 0.5910980701446533, "alphanum_fraction": 0.593788206577301, "avg_line_length": 34.672645568847656, "blob_id": "d8bf666d47e31fe5222168974afa4c7dff788306", "content_id": "cb96668803ebd2d7992b83d0ba91a08e313e78f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8178, "license_type": "no_license", "max_line_length": 154, "num_lines": 223, "path": "/data_preparation/batchgeneratorv2.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "\"\"\"\r\nModule to generate batches for both the training and validation set.\r\nFor training, use the BatchGenerator.\r\nFor validation, use the BatchSequence.\r\n\"\"\"\r\n\r\nfrom os import listdir\r\nfrom os.path import join\r\n\r\nfrom math import ceil, floor\r\nimport numpy as np\r\n\r\nimport sklearn\r\n\r\nfrom keras.utils import Sequence\r\nfrom keras.preprocessing import image\r\nimport tensorflow as tf\r\n\r\n#from PIL import Image\r\n#from google.appengine.api import images\r\n\r\n# standard input of exception\r\nDESIRED_IMAGE_SIZE = 290\r\n\r\ndef image_to_ndarray(path, session, desired_size=DESIRED_IMAGE_SIZE):\r\n \"\"\"\r\n Load a .jpg image.\r\n \r\n Arguments:\r\n path {string} -- file location.\r\n \r\n Keyword Arguments:\r\n desired_size {int} -- the returned image needs to be a square, this denotes the number of pixels on each side. (default: {DESIRED_IMAGE_SIZE})\r\n \r\n Returns:\r\n ndarray -- image in numpy array.\r\n \"\"\"\r\n\t#session = tf.Session()\r\n\t\r\n file = tf.read_file(path)\r\n img = tf.image.decode_image(file)\r\n \r\n\t\r\n return get_right_format(img, session, desired_size=desired_size)\r\n\r\ndef get_right_format(img, session, desired_size=DESIRED_IMAGE_SIZE, color=(255, 255, 255)):\r\n \"\"\"\r\n Getting the image in the correct format.\r\n This is done by either downsampling pictures that are too big, or by padding images that are too small.\r\n\r\n Arguments:\r\n img {obj} -- an image in image format still.\r\n\r\n Keyword Arguments:\r\n desired_size {int} -- the returned image needs to be a square, this denotes the number of pixels on each side. (default: {DESIRED_IMAGE_SIZE})\r\n color {(int, int, int)} -- the desired RGB values for padding.\r\n\r\n Returns:\r\n [obj] -- image in the desired size.\r\n \"\"\"\r\n \r\n imgrun = session.run(tfimg)\r\n old_size = imgrun.shape[0:-1]\r\n\r\n # create new image in desired size, totally white\r\n ratio = float(desired_size)/max(old_size)\r\n new_size = tuple([int(x*ratio) for x in old_size])\r\n \r\n im = tf.image.resize_images(imgrun, new_size, method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\r\n right_format = tf.image.resize_image_with_crop_or_pad(im, desired_size, desired_size)\r\n x = session.run(right_format)\r\n\t\r\n\r\n return x\r\n\r\nclass BatchGenerator(object):\r\n \"\"\"\r\n This class generates batches that can be provided to a neural network.\r\n It can be used for training only. For validation use the BatchSequence class.\r\n \"\"\"\r\n def __init__(self, input_dir, y, batch_size, session, shuffle=True, random=False, img_size=DESIRED_IMAGE_SIZE, augmentation_fn=None):\r\n \"\"\"\r\n Constructor of the BatchGenerator.\r\n \r\n Arguments:\r\n input_dir {string} -- directory in which the images are stored.\r\n y {[rows=indices, cols=labels]} -- labels corresponding to the images in input_dir, in multilabel notation.\r\n batch_size {int} -- expected size of the generated batches.\r\n\r\n Keyword Arguments:\r\n shuffle {boolean} -- if the dataset should be shuffled (default: {True})\r\n random {boolean} -- if the batches should pick random images from the dataset, or in a fixed order (default: {False})\r\n img_size {int} -- the returned image needs to be a square, this denotes the number of pixels on each side. (default: {DESIRED_IMAGE_SIZE})\r\n augmentation_fn {function} -- augmentor function for the data (default: {None})\r\n \"\"\"\r\n self.input_dir = input_dir\r\n self.session = session #tf.Session()\r\n self.random = random\r\n self.desired_size = img_size\r\n self.batch_size = batch_size # number of patches per batch\r\n self.augmentation_fn = augmentation_fn # augmentation function\r\n self.idx = 0 # to know what part of the data set to return in next()\r\n \r\n data = ['{}.jpg'.format(i+1) for i in range(y.shape[0])]\r\n labels = y\r\n if shuffle:\r\n data, labels = sklearn.utils.shuffle(data, labels)\r\n self.x = data\r\n self.y = labels\r\n\r\n def __iter__(self):\r\n \"\"\"\r\n Make the object iterable.\r\n\r\n Returns:\r\n self.\r\n \"\"\"\r\n return self\r\n\r\n def __next__(self):\r\n \"\"\"\r\n Next iteration.\r\n\r\n Returns:\r\n function -- builds a mini-batch.\r\n \"\"\"\r\n return self.next()\r\n\r\n def __len__(self):\r\n \"\"\"\r\n Denotes the number of batches per epoch.\r\n\r\n Returns:\r\n int -- the number of batches possible such that every sample of the class with the least samples is seen once.\r\n \"\"\"\r\n return int(np.ceil(len(self.x) / float(self.batch_size)))\r\n\r\n def next(self):\r\n \"\"\"\r\n Build a mini-batch.\r\n\r\n Returns:\r\n (ndarray, ndarray) -- a batch with training samples and a batch with the corresponding labels.\r\n \"\"\"\r\n if self.random:\r\n # pick random values from the training set\r\n idxs = np.random.randint(0, len(self.x), self.batch_size)\r\n else:\r\n # check if end is reached\r\n if self.idx * self.batch_size >= len(self.x):\r\n self.x, self.y = sklearn.utils.shuffle(self.x, self.y)\r\n self.idx = 0\r\n # create indices\r\n idx_min = self.idx * self.batch_size\r\n # make sure to never go out of bounds\r\n idx_max = np.min([idx_min + self.batch_size, len(self.x)])\r\n idxs = np.arange(idx_min, idx_max)\r\n self.idx += 1\r\n\r\n batch_x = [self.x[i] for i in idxs]\r\n batch_y = [self.y[i] for i in idxs]\r\n\r\n return np.array([\r\n image_to_ndarray(join(self.input_dir, x), self.session, desired_size=self.desired_size) for x in batch_x]), np.array(batch_y)\r\n\r\nclass BatchSequence(Sequence):\r\n \"\"\"\r\n This class generates batches that can be provided to a neural network.\r\n It can be used for validation only. For training use the BatchGenerator class.\r\n \r\n Arguments:\r\n Sequence {class} -- a sequence never repeats items.\r\n \"\"\"\r\n\r\n def __init__(self, input_dir, y, batch_size, desired_size=DESIRED_IMAGE_SIZE):\r\n \"\"\"\r\n Constructor of the BatchSequence.\r\n\r\n Arguments:\r\n input_dir {string} -- directory in which the images are stored.\r\n y {[rows=indices, cols=labels]} -- labels corresponding to the images in input_dir, in multilabel notation.\r\n batch_size {int} -- expected size of the generated batches.\r\n \r\n Keyword arguments:\r\n desired_size {int} -- the returned image needs to be a square, this denotes the number of pixels on each side. (default: {DESIRED_IMAGE_SIZE})\r\n \"\"\"\r\n self.input_dir = input_dir\r\n self.desired_size = desired_size\r\n self.x = ['{}.jpg'.format(i+1) for i in range(y.shape[0])]\r\n self.y = y\r\n self.batch_size = batch_size # number of patches per batch\r\n\r\n def __len__(self):\r\n \"\"\"\r\n Denotes the number of batches per epoch.\r\n\r\n Returns:\r\n int -- the number of batches possible such that every sample of the class with the least samples is seen once.\r\n \"\"\"\r\n return int(np.ceil(len(self.x) / float(self.batch_size)))\r\n \r\n def __getitem__(self, idx):\r\n \"\"\"\r\n Get the next batch from the validation set. Since it is a sequence, it will never give records twice.\r\n \r\n Arguments:\r\n idx {int} -- offset\r\n \r\n Returns:\r\n (ndarray, ndarray) -- a batch with validation samples and a batch with the corresponding labels.\r\n \"\"\"\r\n # create indices\r\n idx_min = idx * self.batch_size\r\n # make sure to never go out of bounds\r\n idx_max = np.min([idx_min + self.batch_size, len(self.x)])\r\n idxs = np.arange(idx_min, idx_max)\r\n \r\n batch_x = [self.x[i] for i in idxs]\r\n batch_y = [self.y[i] for i in idxs]\r\n \r\n return np.array([\r\n image_to_ndarray(join(self.input_dir, x), self.session, desired_size=self.desired_size)\r\n for x in batch_x]), np.array(batch_y)\r\n" }, { "alpha_fraction": 0.7209190726280212, "alphanum_fraction": 0.7443752884864807, "avg_line_length": 32.69355010986328, "blob_id": "ffb31f95f5ce49897a59937eae7f1293f6b12180", "content_id": "ecc6aff3628a47b89de0f7823ecbbb72a6899739", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2090, "license_type": "no_license", "max_line_length": 102, "num_lines": 62, "path": "/pretrained_network/Pretrained-networks/vgg16/vgg16.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nimport sys\nsys.path.append(\"../../data_preparation/\")\nimport json\nimport pickle\nimport numpy as np\nimport pandas as pd\n\nfrom keras.applications import VGG16\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout\nfrom keras.models import Model, load_model\n\nfrom batch_generator import BatchGenerator, BatchSequence\n\n# Set the paths\ninput_path = os.path.abspath('../../../mlipdata/')\nimages_path_train = os.path.join(input_path, 'files/train/')\n\n# Load the multilabel binarizer\nwith open('../binarizer.pickle', 'rb') as pickle_file:\n binarizer = pickle.load(pickle_file)\n\n# Load training data from file\ntrain={}\nwith open(os.path.join(input_path, 'train.json')) as json_data:\n train= json.load(json_data)\n\ntrain_img_url = train['images']\ntrain_img_url = pd.DataFrame(train_img_url)\ntrain_ann = train['annotations']\ntrain_ann = pd.DataFrame(train_ann)\ntrain = pd.merge(train_img_url, train_ann, on='imageId', how='inner')\ntrain['imageId'] = train['imageId'].astype(np.uint32)\n\ny_train = np.array(train.labelId)\ny_train_bin = binarizer.transform(y_train)\n\n# Load the generator\ntraining_gen = BatchGenerator(input_dir=images_path_train, y=y_train_bin, batch_size=64)\n\n# Init pre-trained network\nbase_model = VGG16(weights='imagenet', include_top=False, input_shape=(290,290,3))\n\n# Adding the last two fully-connected layers\nx = base_model.output\nx = GlobalAveragePooling2D()(x) # global average pooling (flatten)\nx = Dense(1024, activation='relu')(x) # should be rather large with 228 output labels\ny = Dense(228, activation='softmax')(x) # sigmoid instead of softmax to have independent probabilities\n\nmodel = Model(inputs=base_model.input, outputs=y)\n# Train only the top layer\nfor layer in base_model.layers:\n layer.trainable = False\n\n# Use binary loss instead of categorical loss to penalize each output independently\nmodel.compile(optimizer='adam', loss='binary_crossentropy')\n\n# 1000 steps = 640000 random images per epoch\nmodel.fit_generator(training_gen, steps_per_epoch=int(3000/64), epochs=10)\n\nmodel.save('./vgg16_cloud_model.h5')\n" }, { "alpha_fraction": 0.6473388075828552, "alphanum_fraction": 0.6499350666999817, "avg_line_length": 25.261363983154297, "blob_id": "111e9deb7be9adb674fed71e49d99398c7e1822a", "content_id": "c2072218af1a050239ce5be3384bc38c7103d70b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2311, "license_type": "no_license", "max_line_length": 85, "num_lines": 88, "path": "/model/trainer/exception.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding, LSTM\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing import sequence\nimport sklearn\nimport argparse\nimport cPickle\nimport gzip \nimport json\nfrom tensorflow.python.lib.io import file_io\n\n\ndef load_data(path):\n\n # Load images\n \n # Load and decompress training labels\n with file_io.FileIO(path + 'data/y_train.pickle', mode='rb') as fp:\n data = gzip.GzipFile(fileobj=fp)\n y_train = cPickle.load(data)\n \n # Load and decompress validation labels\n with file_io.FileIO(path + 'data/y_validation.pickle', mode='rb') as fp:\n data = gzip.GzipFile(fileobj=fp)\n y_validation = cPickle.load(data)\n \n return y_train, y_validation\n\ndef preprocessing():\n return None\n\ndef create_model():\n model = Sequential()\n model.add(Dense(42, activation='relu'))\n model.add((Dense(6, activation='sigmoid')))\n\n model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n model.summary()\n\n return model\n\n\ndef main(train_file, test_file, job_dir):\n y_train, y_validation = load_data(train_file)\n \n # Save model weights\n model.save('model.h5')\n\n # Save model on google storage\n with file_io.FileIO('model.h5', mode='r') as input_f:\n with file_io.FileIO(job_dir + '/model.h5', mode='w+') as output_f:\n output_f.write(input_f.read())\n \n print(y_train.shape,y_validation.shape)\n\nif __name__ == '__main__':\n \"\"\"\n The argparser can also be extended to take --n-epochs or --batch-size arguments\n \"\"\"\n parser = argparse.ArgumentParser()\n \n # Input Arguments\n parser.add_argument(\n '--train-file',\n help='GCS or local paths to training data',\n required=True\n )\n\n parser.add_argument(\n '--test-file',\n help='GCS or local paths to test data',\n required=False\n )\n\n parser.add_argument(\n '--job-dir',\n help='GCS location to write checkpoints and export models',\n required=True\n )\n args = parser.parse_args()\n arguments = args.__dict__\n print('args: {}'.format(arguments))\n\n main(args.train_file, args.test_file, args.job_dir)\n" }, { "alpha_fraction": 0.6926981806755066, "alphanum_fraction": 0.7087075114250183, "avg_line_length": 48.25, "blob_id": "89fb889b1aaf7365ad7472f82cc82b1b315db4ca", "content_id": "252d9feedb8b8af415afa9c7f534ecd7662ff903", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2561, "license_type": "no_license", "max_line_length": 302, "num_lines": 52, "path": "/README.md", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "# Machine Learning In Practice\n\n## How to Run 2: VM\n\n- Start the VM: https://console.cloud.google.com/compute/instances?project=mlip-team-mmndpm\n- SSH into VM: ```gcloud compute --project \"mlip-team-mmndpm\" ssh --zone \"europe-west1-b\" \"fashion\"```\n- ```sudo bash``` to get root\n- ```export LD_LIBRARY_PATH=/usr/local/cuda/lib64``` (else cudnn is not found)\n- ```export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64``` (else cudnn is not found)\n- ^ There is supposed to be a way in linux to save exports and not do this every time\n- ```cd /home/dljva/``` this is where the current files are stored (you need to run the notebook from here)\n- ```jupyter-notebook --no-browser --port=5000 --allow-root``` to run jupyter notebook\n- Navigate to http://35.195.202.233:5000 (password: fashion)\n- Stop VM after use (https://console.cloud.google.com/compute/instances?project=mlip-team-mmndpm)\n \n\n## How to Run\n\n- Download ```model``` directory from github (e.g. to ```C:/python/mip/model/```). Edit ```train.py``` to change the model.\n\n- Install Google Cloud SDK (https://cloud.google.com/sdk/docs/)\n\n- Change ```job_name``` and run the following command in the command prompt:\n\n ```\n gcloud ml-engine jobs submit training job_name --stream-logs --runtime-version 1.4 --job-dir gs://mmndpm-europe-west --package-path C:/python/mip/model/trainer --module-name trainer.train --region europe-west1 --config C:/python/mip/model/trainer/config.yaml -- --train-file gs://mmndpm-europe-west/\n ```\n \n- View the list of jobs here: https://console.cloud.google.com/mlengine/jobs?project=mlip-team-mmndpm\n- <b> Reading and writing files on the google bucket only works with ```file_io``` from ```tensorflow.python.lib.io```</b> \n- We are using python 2\n\n## Google Bucket structure\n```gs://mmndpm-europe-west/```\n\n```- data```\n\n```-- train``` directory with separate training image (jpg) files\n\n```-- test``` directory with separate test image (jpg) files\n\n```-- validation``` directory with separate validation image (jpg) files\n\n```-- train.json``` contains image URLS and label annotiations for training set\n\n```-- test.json``` contains image URLS and label annotiations for test set\n\n```-- validation.json``` contains image URLS and label annotiations for validation set\n\n```-- y_train.pickle``` gzip compressed pickle file with one-hot encoded labels (column 0 is imageId, columns 1-229 indicate label presence)\n\n```-- y_validation.pickle``` gzip compressed pickle file with one-hot encoded labels (column 0 is imageId, columns 1-229 indicate label presence)\n" }, { "alpha_fraction": 0.5400176048278809, "alphanum_fraction": 0.5510114431381226, "avg_line_length": 28.16666603088379, "blob_id": "08524ea7bad6374d066779f0b9c8915dc9966e3e", "content_id": "93f7edb6f4653dc4c6e5e02b372c30e0b6d0789e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2278, "license_type": "no_license", "max_line_length": 94, "num_lines": 78, "path": "/exception_callbacks/callbacks.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "import numpy as np\nimport keras\n# these have to be defined in a notebook\n\n# class Metrics(Callback):\n# def on_train_begin(self, logs={}):\n# self.mean_f1s = []\n# self.recalls = []\n# self.precisions = []\n\n# def on_epoch_end(self, epoch, logs={}):\n# y_pred = (np.asarray(self.model.predict(self.validation_data[0]))).round()\n# y_true = self.validation_data[1]\n\n# mean_f1 = f1_score(y_true, y_pred, average='macro')\n# recall = recall_score(y_true, y_pred, average='macro')\n# precision = precision_score(y_true, y_pred, average='macro')\n# self.mean_f1s.append(mean_f1)\n# self.recalls.append(recall)\n# self.precisions.append(precision)\n\n# print('mean_F1: {} — precision: {} — recall: {}'.format(mean_f1, precision, recall))\n\n# class PlotLosses(keras.callbacks.Callback):\n# def on_train_begin(self, logs={}):\n# self.i = 0\n# self.x = []\n# self.losses = []\n# self.val_losses = []\n# self.fig = plt.figure()\n# self.logs = []\n\n# def on_epoch_end(self, epoch, logs={}):\n# self.logs.append(logs)\n# self.x.append(self.i)\n# self.losses.append(logs.get('loss'))\n# self.val_losses.append(logs.get('val_loss'))\n# self.i += 1\n\n# clear_output(wait=True)\n# plt.plot(self.x, self.losses, label=\"loss\")\n# plt.plot(self.x, self.val_losses, label=\"val_loss\")\n# plt.grid()\n# plt.legend()\n# plt.show()\n\ndef all_call_backs():\n callbacks_list = []\n\n a = keras.callbacks.ReduceLROnPlateau(\n monitor='val_loss',\n factor=0.15,\n patience=3,\n min_lr=0.0001\n )\n\n b = keras.callbacks.EarlyStopping(\n monitor='val_loss',\n min_delta=0,\n patience=8,\n verbose=0,\n mode='auto'\n )\n\n c = keras.callbacks.ModelCheckpoint(\n filepath='/model-checkpoints/',\n monitor='val_loss',\n verbose=0,\n save_best_only=True,\n save_weights_only=False,\n mode='auto',\n period=1\n )\n\n # callbacks_list = [a, b, c]\n # callbacks_list = callbacks_list + [PlotLosses()]\n # callbacks_list = callbacks_list + [Metrics()]\n return callbacks_list[a, b, c]" }, { "alpha_fraction": 0.7473683953285217, "alphanum_fraction": 0.7473683953285217, "avg_line_length": 27.5, "blob_id": "1a4b5f6d01ce3cf3d6d7ddf5a59a282e070f6523", "content_id": "a08d615b0f8743ab5a5cd8d1bf81f4ce8fa82960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 95, "num_lines": 10, "path": "/data_preparation/multilabel_functions.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "'''\n Module to import multilabels. It assumes that you have run the corresponding Notebook once.\n Notebook: ./MultiLabelProcessor.ipynb\n'''\n\ndef get_multilabels_train(filename):\n return np.load(filename)\n\ndef get_multilabels_validation(filename):\n return np.load(filename)\n" }, { "alpha_fraction": 0.5990534424781799, "alphanum_fraction": 0.6064908504486084, "avg_line_length": 30.625, "blob_id": "a920af178c1e5d2a758c68a5ff2018faef3957b5", "content_id": "5a769dd59c03c7f1efb20f02dad4745e1c9abb73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4437, "license_type": "no_license", "max_line_length": 106, "num_lines": 136, "path": "/pretrained_network/model/trainer/train.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\nfrom __future__ import absolute_import\r\nimport sys\r\nsys.path.append('../')\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom keras.models import Model\r\nfrom keras.layers import GlobalAveragePooling2D, Dense, Dropout\r\nfrom keras.applications import VGG16\r\nimport sklearn\r\nimport argparse\r\nimport cPickle\r\nimport gzip\r\nimport json\r\nimport logging\r\nimport tensorflow as tf\r\nfrom tensorflow.python.lib.io import file_io\r\n\r\ntry:\r\n from batch_generator import BatchGenerator, BatchSequence\r\nexcept:\r\n from .batch_generator import BatchGenerator, BatchSequence\r\n\r\ndef load_data(path):\r\n\r\n # Load images\r\n\r\n # Load and decompress training labels\r\n with file_io.FileIO(path + 'data/y_train.pickle', mode='rb') as fp:\r\n data = gzip.GzipFile(fileobj=fp)\r\n y_train = cPickle.load(data)\r\n\r\n # Load and decompress validation labels\r\n with file_io.FileIO(path + 'data/y_validation.pickle', mode='rb') as fp:\r\n data = gzip.GzipFile(fileobj=fp)\r\n y_validation = cPickle.load(data)\r\n\r\n # with file_io.FileIO(path + 'data/binarizer.pickle', mode='rb') as fp:\r\n # #data = gzip.GzipFile(fileobj=fp)\r\n # binarizer = cPickle.load(fp)\r\n\r\n# y_train = binarizer.transform(y_train)\r\n# y_validation = binarizer.transform(y_validation)\r\n\r\n return y_train, y_validation\r\n\r\ndef preprocessing():\r\n return None\r\n\r\ndef create_model():\r\n # Init pre-trained network\r\n base_model = VGG16(weights='imagenet', include_top=False, input_shape=(290,290,3))\r\n\r\n # Adding the last two fully-connected layers\r\n x = base_model.output\r\n x = GlobalAveragePooling2D()(x) # global average pooling (flatten)\r\n x = Dense(1024, activation='relu')(x) # should be rather large with 228 output labels\r\n y = Dense(228, activation='sigmoid')(x) # sigmoid instead of softmax to have independent probabilities\r\n\r\n model = Model(inputs=base_model.input, outputs=y)\r\n # Train only the top layer\r\n for layer in base_model.layers:\r\n layer.trainable = False\r\n\r\n # Use binary loss instead of categorical loss to penalize each output independently\r\n model.compile(optimizer='adam', loss='binary_crossentropy')\r\n\r\n return model\r\n\r\n\r\ndef main(train_file, test_file, job_dir, session):\r\n y_train, y_validation = load_data(train_file)\r\n y_train = np.array([j[1:] for j in y_train])\r\n y_validation = np.array([j[1:] for j in y_validation])\r\n\r\n epochs = 10\r\n batch_size = 64\r\n\r\n #input_dir=job_dir+'data/train'\r\n training_gen = BatchGenerator(input_dir=job_dir+'data/train',\r\n y=y_train,\r\n epochs=epochs,\r\n batch_size=batch_size,\r\n session=session)\r\n validation_gen = BatchSequence(input_dir=job_dir+'data/validation',\r\n y=y_validation,\r\n batch_size=batch_size,\r\n session=session)\r\n\r\n model = create_model()\r\n\r\n #model.fit_generator(generator=training_gen,\r\n# steps_per_epoch=int(len(y_train)/batch_size),\r\n# epochs=epochs,\r\n# validation_data=validation_gen,\r\n# validation_steps=int(len(y_validation)/batch_size))\r\n\r\n for i in range(epochs):\r\n for batch_x, batch_y in training_gen:\r\n model.fit(batch_x, batch_y)\r\n\r\n model.save(job_dir + 'models/vgg16.h5')\r\n\r\nif __name__ == '__main__':\r\n \"\"\"\r\n The argparser can also be extended to take --n-epochs or --batch-size arguments\r\n \"\"\"\r\n parser = argparse.ArgumentParser()\r\n\r\n LOGGER = logging.getLogger('trainer')\r\n LOGGER.info('TESTING LOGGER ITSELF')\r\n\r\n # Input Arguments\r\n parser.add_argument(\r\n '--train-file',\r\n help='GCS or local paths to training data',\r\n required=True\r\n )\r\n\r\n parser.add_argument(\r\n '--test-file',\r\n help='GCS or local paths to test data',\r\n required=False\r\n )\r\n\r\n parser.add_argument(\r\n '--job-dir',\r\n help='GCS location to write checkpoints and export models',\r\n required=True\r\n )\r\n args = parser.parse_args()\r\n arguments = args.__dict__\r\n print('args: {}'.format(arguments))\r\n# This works\r\n with tf.Session() as session:\r\n session.run(main(args.train_file, args.test_file, args.job_dir, session))\r\n" }, { "alpha_fraction": 0.6518691778182983, "alphanum_fraction": 0.677570104598999, "avg_line_length": 30.923076629638672, "blob_id": "09a32747739ed424a981f8122f80842153de2e07", "content_id": "af5de30dcdd8cb2446c89f82f89596db46ee9ded", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 121, "num_lines": 13, "path": "/pretrained_network/model/setup.py", "repo_name": "simgeekiz/FashionChallenge", "src_encoding": "UTF-8", "text": "from setuptools import find_packages\r\nfrom setuptools import setup\r\n\r\nREQUIRED_PACKAGES = ['sklearn', 'numpy>=1.13.3', 'pandas', 'keras', 'tensorflow', 'h5py', 'pillow', 'google-gax<=0.13.0']\r\n\r\nsetup(\r\n name='trainer',\r\n version='0.1',\r\n install_requires=REQUIRED_PACKAGES,\r\n packages=find_packages(),\r\n include_package_data=True,\r\n description='iMaterialist Challenge (Fashion) model on Cloud ML Engine'\r\n)\r\n" } ]
12
aq1/telegram_voice_to_trello_card
https://github.com/aq1/telegram_voice_to_trello_card
210b034a1711d1bb7f7929b87848d606aa82eb97
cb8e7eae3b9775f8d29c52cd0854c7ccd723618a
2deaa9351ad6978b450f45a16a052c0ad5449ab8
refs/heads/master
2020-03-11T16:13:37.076191
2018-04-18T19:40:18
2018-04-18T19:40:18
130,109,941
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7021791934967041, "alphanum_fraction": 0.7021791934967041, "avg_line_length": 24.8125, "blob_id": "4d94cd1afe4a34152d60d14b42c1e338d108aa9e", "content_id": "3666f1cbe2171950dd23959f54e16d29f1559b6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/main/external_api/telegram_api.py", "repo_name": "aq1/telegram_voice_to_trello_card", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\nimport requests\n\n\nURL = 'https://api.telegram.org/bot{}/{{}}'.format(settings.TELEGRAM_TOKEN)\nFILE_URL = 'https://api.telegram.org/file/bot{}/{{}}'.format(settings.TELEGRAM_TOKEN)\n\n\ndef call(api_method, data=None):\n data = data or {}\n return requests.post(URL.format(api_method), data=data)\n\n\ndef get_file(path):\n return requests.get(FILE_URL.format(path), stream=True)\n" }, { "alpha_fraction": 0.8461538553237915, "alphanum_fraction": 0.8717948794364929, "avg_line_length": 6.800000190734863, "blob_id": "adfcb0625c293633a820a586d0f314506a407027", "content_id": "acf0074ad5fa5cbdf7b30dbcd669ce84b053840f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 39, "license_type": "no_license", "max_line_length": 8, "num_lines": 5, "path": "/requirements.txt", "repo_name": "aq1/telegram_voice_to_trello_card", "src_encoding": "UTF-8", "text": "django\nrequests\nawsebcli\nchalice\nboto3\n" }, { "alpha_fraction": 0.5324015021324158, "alphanum_fraction": 0.62770015001297, "avg_line_length": 24.387096405029297, "blob_id": "7b35c1e90f0e536d533a3d1f7adb56bf6f37912d", "content_id": "3f93f0060bac2d97284cdc1f9c0bb1ff20b45af8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 84, "num_lines": 31, "path": "/main/external_api/trello_api.py", "repo_name": "aq1/telegram_voice_to_trello_card", "src_encoding": "UTF-8", "text": "import requests\n\n\nTRELLO_KEY = '0a2169778555b41e80b615399d83541f'\nTRELLO_TOKEN = '776cea39c4013e6b8b94c47d7e7e56ac6122255587bad81ce8c6959d8859b8c7'\nTRELLO_URL = 'https://api.trello.com/1/'\n\n\ndef call(method, name, resource_id='', nested='', data=None, params=None, **kwargs):\n url = TRELLO_URL + name\n if resource_id:\n url += '/' + resource_id\n if nested:\n url += '/' + nested\n\n data = data or {}\n params = params or {}\n\n params.update({\n 'key': TRELLO_KEY,\n 'token': TRELLO_TOKEN,\n })\n\n response = requests.request(method, url, data=data, params=params, **kwargs)\n if 200 < response.status_code < 300:\n raise ValueError()\n\n try:\n return response.json()\n except (TypeError, KeyError):\n raise ValueError()\n" }, { "alpha_fraction": 0.5736371278762817, "alphanum_fraction": 0.5748575925827026, "avg_line_length": 25.43010711669922, "blob_id": "e3f0842269bce692151a7396f2e4c96dc6c22346", "content_id": "8bddf5e256eb1dca4d7bdde59c18c17b49c72fce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2458, "license_type": "no_license", "max_line_length": 95, "num_lines": 93, "path": "/main/views.py", "repo_name": "aq1/telegram_voice_to_trello_card", "src_encoding": "UTF-8", "text": "import time\n\nimport json\n\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom main.external_api import telegram_api, trello_api\n\n\ndef send_message_to_telegram(telegram_user_id, text):\n return telegram_api.call(\n 'sendMessage',\n data={\n 'chat_id': telegram_user_id,\n 'text': text,\n 'parse_mode': 'HTML',\n 'disable_web_page_preview': True,\n }\n )\n\n\n@csrf_exempt\ndef telegram_webhook(request):\n try:\n data = json.loads(request.body.decode())\n except json.JSONDecodeError:\n return HttpResponse(status=400)\n\n if not data.get('message'):\n return HttpResponse()\n\n telegram_user_id = data['message']['from']['id']\n\n try:\n voice = data['message']['voice']\n except KeyError:\n send_message_to_telegram(telegram_user_id, 'This bot is expecting only voice messages')\n return HttpResponse()\n\n try:\n voice_file_path = telegram_api.call(\n 'getFile',\n data={\n 'file_id': voice['file_id'],\n }\n ).json()['result']['file_path']\n except (ValueError, KeyError):\n send_message_to_telegram(telegram_user_id, 'Failed to get info about voice file')\n return HttpResponse()\n\n try:\n voice_file = telegram_api.get_file(voice_file_path)\n except:\n send_message_to_telegram(telegram_user_id, 'Failed to get file')\n return HttpResponse()\n\n list_id = settings.TRELLO_LIST_ID\n\n filename = str(int(time.time()))\n\n try:\n response = trello_api.call(\n 'post',\n 'cards',\n data={\n 'name': filename,\n 'idList': list_id\n }\n )\n except ValueError:\n send_message_to_telegram(telegram_user_id, 'Failed to create card')\n return HttpResponse()\n\n card_url = response.get('url')\n\n try:\n trello_api.call(\n 'post',\n 'cards',\n response['id'],\n 'attachments',\n files={\n 'file': (filename + '.ogg', voice_file.content, voice['mime_type'])}\n )\n except ValueError:\n send_message_to_telegram(telegram_user_id, 'Failed to upload file to trello')\n return HttpResponse()\n\n send_message_to_telegram(telegram_user_id, 'Card created.\\n{}'.format(card_url))\n\n return HttpResponse()\n" } ]
4
abdulrauf8788uni/AstarPathFinding-mini
https://github.com/abdulrauf8788uni/AstarPathFinding-mini
f1cd0dea92c256210c71c4af70161b5298c38672
4ec7b47cc8a1006e3ab46013d3c1ff1d06a0b68a
d3ef4cf52081d10cf763f2043bd809873531b6f2
refs/heads/master
2023-01-23T22:15:29.263466
2020-12-06T11:40:43
2020-12-06T11:40:43
319,016,656
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6355977058410645, "alphanum_fraction": 0.6471827030181885, "avg_line_length": 20.337078094482422, "blob_id": "7c2b289794dcbf8e01cb60364bfa08f56b5d77ec", "content_id": "b2e9e0e043b69909693e6dfea86279dad83e8146", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1899, "license_type": "no_license", "max_line_length": 87, "num_lines": 89, "path": "/mygame/node.py", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "import pygame\nfrom . import settings\n\n# Node class\n\nclass Node:\n\tdef __init__(self, x, y, width):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.x_pos = self.x * width\n\t\tself.y_pos = self.y * width\n\t\tself.width = width\n\t\tself.color = settings.SILVER\n\t\tself.heuristic = float(\"inf\")\n\t\tself.neighbours = []\n\n\n\n\tdef pos(self):\n\t\treturn (self.x, self.y)\n\n\tdef get_h(self):\n\t\treturn self.heuristic \n\n\tdef clac_heuristic(self, p2):\n\t\tp1x, p1y = self.x, self.y\n\t\tp2x, p2y = p2\n\n\t\tself.heuristic = abs(p2x - p1x) + abs(p2y - p1y)\n\n\tdef calc_neighbours(self, grid):\n\n\t\tif self.x > 0: # LEFT\n\t\t\tif not grid[self.y][self.x - 1].is_barrier():\n\t\t\t\tself.neighbours.append(grid[self.y][self.x - 1])\n\n\t\tif self.x < settings.NUM_X - 1:\n\t\t\tif not grid[self.y][self.x + 1].is_barrier():\n\t\t\t\tself.neighbours.append(grid[self.y][self.x + 1])\n\n\t\tif self.y > 0:\n\t\t\tif not grid[self.y - 1][self.x].is_barrier():\n\t\t\t\tself.neighbours.append(grid[self.y - 1][self.x])\n\n\t\tif self.y < settings.NUM_X - 1:\n\t\t\tif not grid[self.y + 1][self.x].is_barrier():\n\t\t\t\tself.neighbours.append(grid[self.y + 1][self.x])\n\n\tdef draw_node(self, win):\n\t\tpygame.draw.rect(win, self.color, (self.x_pos , self.y_pos, self.width, self.width)) \n\n\t# Is fuctions\n\n\tdef is_barrier(self):\n\t\treturn self.color == settings.BLACK\n\n\tdef is_start(self):\n\t\treturn self.color == settings.GREEN\n\t\n\tdef is_end(self):\n\t\treturn self.color == settings.RED\n\n\tdef is_path(self):\n\t\treturn self.color == settings.YELLOW\n\n\tdef is_explored(self):\n\t\treturn self.color == settings.SKIN\n\t# Setters \n\n\tdef make_barrier(self):\n\t\tself.color = settings.BLACK\n\n\tdef reset(self):\n\t\tself.color = settings.SILVER\n\n\tdef make_start(self):\n\t\tself.color = settings.GREEN\n\n\tdef make_end(self):\n\t\tself.color = settings.RED\n\n\tdef make_path(self):\n\t\tself.color = settings.YELLOW\n\n\tdef make_explored(self):\n\t\tself.color = settings.DARK_SILVER\n\n\tdef __str__(self):\n\t\treturn f\"Node at ({self.x}, {self.y})\"\n" }, { "alpha_fraction": 0.6711370348930359, "alphanum_fraction": 0.6723031997680664, "avg_line_length": 22.50684928894043, "blob_id": "09c404677582389beabd4f073eb9c99d71f6c032", "content_id": "009f7c32dd20f543baea671247c918f5e65308a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "no_license", "max_line_length": 70, "num_lines": 73, "path": "/main.py", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "import pygame\nfrom mygame.functions import makeGrid, drawGrid, getClickedNode, Astar\nfrom mygame import settings\n\n# Pygame settings\n\nWIN = pygame.display.set_mode(settings.SCREEN)\npygame.display.set_caption(settings.CAPTION)\n\n\n# Local variables\nrun = True\nstarted = False\ngrid = makeGrid()\n\nstart_node = None\nend_node = None\n\nwhile run:\n\n\tWIN.fill(settings.BLACK)\n\tdrawGrid(WIN, grid)\n\n\n\tfor event in pygame.event.get():\n\t\t# Exiting fuction \n\t\tif event.type == pygame.QUIT:\n\t\t\trun = False\n\t\t\tprint(f\"Exiting '{settings.CAPTION}'\")\n\t\t# Reset screen\n\t\tif not started:\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_ESCAPE:\n\t\t\t\t\tgrid = makeGrid()\n\t\t\t\t\tstart_node = None\n\t\t\t\t\tend_node = None\n\n\t\t\t\tif event.key == pygame.K_SPACE:\n\t\t\t\t\tstarted = True\n\n\t\t\t# Mouse left click functionality \n\t\t\tif pygame.mouse.get_pressed()[0]:\n\t\t\t\t# Start node, end node and barrier node logic\n\t\t\t\tclicked_node = getClickedNode(grid)\n\t\t\t\tif not start_node and not end_node:\n\t\t\t\t\tstart_node = clicked_node\n\t\t\t\t\tstart_node.make_start()\n\t\t\t\telif not end_node and clicked_node != start_node:\n\t\t\t\t\tend_node = clicked_node\n\t\t\t\t\tend_node.make_end()\n\t\t\t\telif clicked_node != start_node and clicked_node != end_node:\n\t\t\t\t\tclicked_node.make_barrier()\n\n\t\t\t# Mouse right click functionality\n\t\t\telif pygame.mouse.get_pressed()[2]:\n\t\t\t\tclicked_node = getClickedNode(grid)\n\t\t\t\tif clicked_node == end_node:\n\t\t\t\t\tend_node = None\n\n\t\t\t\telif clicked_node == start_node:\n\t\t\t\t\tif end_node:\n\t\t\t\t\t\tend_node.make_start()\n\t\t\t\t\t\tstart_node = end_node\n\t\t\t\t\t\tend_node = None\n\t\t\t\tclicked_node.reset() \n\tif started:\n\t\tprint(\"Running A* algorithm.\")\n\t\tAstar(WIN, grid, start_node, end_node)\n\t\tstarted = False\t\t\n\n\tpygame.display.update()\n\n# pygame.quit()" }, { "alpha_fraction": 0.4759192168712616, "alphanum_fraction": 0.4821335971355438, "avg_line_length": 24.077922821044922, "blob_id": "bf79a1c0c6bb2da0e22953acb21fc70e33ef7ff5", "content_id": "92e88816e6fd18bbbf4a504e8913d9dea4f85a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1931, "license_type": "no_license", "max_line_length": 89, "num_lines": 77, "path": "/mygame/myqueue.py", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "class myPriorityQueue():\n\n def __init__(self):\n self.queue = []\n\n def insert(self, value, priority):\n item = (value, priority) \n self.queue.append(item)\n\n def get(self):\n item = self.get_least()\n if item[0]:\n self.queue.remove(item)\n return item\n\n def get_highest_priority(self):\n item = self.get_heighest()\n return item[0]\n\n def delete_highest_priority(self):\n item = self.get_heighest()\n if item[0]:\n self.queue.remove(item)\n\n # helper functions\n\n def get_least(self):\n if not self.is_empty():\n min_val = float(\"inf\")\n min_item = None\n\n for val, prior in self.queue:\n if prior < min_val:\n min_val = prior\n\n for item in self.queue:\n if item[1] == min_val:\n return item\n else:\n return None, None\n\n def get_heighest(self):\n if not self.is_empty():\n max_val = 0\n max_item = None\n for val, prior in self.queue:\n if prior > max_val:\n max_val = prior\n\n # return the latest item (item recently inserted), in case of same priority. \n # for item in self.queue:\n # if item[1] == max_val:\n # max_item = item \n # return max_item \n\n # returns the item which was added first (in case of same proirity). \n for item in self.queue:\n if item[1] == max_val:\n return item\n else:\n return None, None\n \n\n def is_empty(self):\n return len(self.queue) == 0\n\n\n\nif __name__ == \"__main__\":\n q = myPriorityQueue()\n q.insert(\"Apple\", 4)\n q.insert(\"Mango\", 4)\n q.insert(\"grapes\", 3)\n q.insert(\"banana\", 5)\n print(q.get())\n print(q.get())\n print(q.get())\n" }, { "alpha_fraction": 0.678947389125824, "alphanum_fraction": 0.7245613932609558, "avg_line_length": 18.65517234802246, "blob_id": "f02994bac21dea2a7126b253bf6ae242c12bb678", "content_id": "c159d75e1b896be34ea7e748389c3bda773435d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 106, "num_lines": 58, "path": "/README.md", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "# Welcome to A* visualization tool\n\nThis is a simple tool, in which you can visualize the working of A* path finding algoritm.\n\n### How to run\n\n* **Activate virtulenv**\n\nNavigate to the root directory of the code in terminal and write the following code.\n\n\nFor windows: \n\n\tenv\\scrips\\activate \n\n\nFor mac and linux: \n\n\tsource env\\bin\\activate \n\n\n* **Run main.py**\n\nRun main.py with the code: \n\n\tpython main.py\n\n<br>\n\n\n### Instructions\n\nStart color: *Green* ![#c5f015](https://via.placeholder.com/15/c5f015/000000?text=+)\n\nEnd color: *Red* ![#f03c15](https://via.placeholder.com/15/f03c15/000000?text=+)\n\nBarrier: *Black* ![#000000](https://via.placeholder.com/15/000000/000000?text=+)\n\n\n> Right click on the block to draw starting position, ending position and barriers.\n\n> Left click to clear the block\n\n> Escape to reset the screen (If the algorith is running you have to wait till the algorithm is finished) \n\n> Space to start the algorithm \n\n\n**More details**\n\n* The blocks which are highlighted in silver represents the blocks which are explored during the search\n\n* Yellow path represents the path found.\n\n--- \n\n\nFEEDBACK ON: [email protected]\n" }, { "alpha_fraction": 0.41124260425567627, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 16.842105865478516, "blob_id": "b59d5af3c0a839c769b4f4099e72608b99592dc4", "content_id": "a10f803212a10dbf1ed697813c09393bd6300b9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 33, "num_lines": 19, "path": "/mygame/settings.py", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "# Settings \n\nSCREEN = WIDTH, HEIGHT = 800, 800\n\n# Number of blocks x, and y\nNUM_X = 50\n\n# Caption of the window\nCAPTION = \"Visualiztion tool\"\n\n# Colors \nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\nSILVER = (194, 194, 194)\nDARK_SILVER = (166, 166, 166)\nRED = (237, 36, 36)\nGREEN = (26, 237, 46)\nYELLOW = (237, 224, 36)\nSKIN = (227, 194, 129)" }, { "alpha_fraction": 0.6496062874794006, "alphanum_fraction": 0.6525590419769287, "avg_line_length": 21.58888816833496, "blob_id": "8bb9b989a86738197fc98f27d766bd62d3d6fe4f", "content_id": "03067a79dc9ee95519f77d3f8dcd75ac5c8ee4f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2032, "license_type": "no_license", "max_line_length": 52, "num_lines": 90, "path": "/mygame/functions.py", "repo_name": "abdulrauf8788uni/AstarPathFinding-mini", "src_encoding": "UTF-8", "text": "import pygame\nfrom . import settings\nimport time\nfrom .myqueue import myPriorityQueue\n\nfrom .node import Node\n\n# All Fuctions \ndef makeGrid():\n\tnode_width = settings.WIDTH // settings.NUM_X\n\tgrid = []\n\tfor row in range(settings.NUM_X):\n\t\tgrid.append([])\n\t\tfor node in range(settings.NUM_X):\n\t\t\tnew_node = Node(node, row, node_width)\n\t\t\tgrid[row].append(new_node)\n\n\treturn grid\n\ndef drawGrid(win, grid):\n\tfor row in grid:\n\t\tfor node in row:\n\t\t\tnode.draw_node(win)\n\ndef getClickedNode(grid):\n\tnode_width = settings.WIDTH // settings.NUM_X\n\tclicked_x, clicked_y = pygame.mouse.get_pos()\n\tpos_x = clicked_x // node_width\n\tpos_y = clicked_y // node_width\n\n\treturn grid[pos_y][pos_x]\n\ndef recalculate_nodes(grid, end_node):\n\tfor row in grid:\n\t\tfor node in row:\n\t\t\tnode.clac_heuristic(end_node.pos())\n\n\tfor row in grid:\n\t\tfor node in row:\n\t\t\tnode.calc_neighbours(grid)\n\n\n\ndef Astar(win, grid, start_node, end_node):\n\trecalculate_nodes(grid, end_node)\n\n\tqueue = myPriorityQueue()\n\texplored = []\n\tbest_path_item = ([], float(\"inf\"))\n\tqueue.insert(([start_node], 0), start_node.get_h())\n\n\n\twhile not queue.is_empty():\n\n\t\titem, local_f_score = queue.get()\n\t\texploring = item[0][-1]\n\n\t\texploring.make_explored()\n\t\texploring.draw_node(win)\n\t\tpygame.display.update()\n\t\texplored.append(exploring)\n\n\t\tchildren = exploring.neighbours\n\t\tfor child in children:\n\t\t\tif not child in explored:\n\t\t\t\tnode_list, path_cost = item\n\t\t\t\tnew_path_cost = path_cost + 1\n\n\t\t\t\tnew_list = list(node_list)\n\n\t\t\t\tif child.get_h() == 0:\n\t\t\t\t\tfor node in new_list:\n\t\t\t\t\t\tif node != start_node and node != end_node:\n\t\t\t\t\t\t\tnode.make_path()\n\t\t\t\t\t\t\tnode.draw_node(win)\n\t\t\t\t\t\t\tpygame.display.update()\n\t\t\t\t\treturn \n\n\t\t\t\tf_score = new_path_cost + child.get_h() * 4\n\n\t\t\t\tnew_list.append(child)\n\t\t\t\texplored.append(child)\n\t\t\t\t# print(\"adding\", end=\" \")\n\t\t\t\t# for path in new_list:\n\t\t\t\t# \tprint(path.pos(), end=' ')\n\t\t\t\t# print(\"with f score\", f_score)\n\t\t\t\t# print(f\"inserting {child.pos()}\")\n\t\t\t\tqueue.insert((new_list, new_path_cost), f_score)\n\n\tprint(\"No possible path found. \")" } ]
6
srypher/Wintermute
https://github.com/srypher/Wintermute
8aa4f32fb3ae02c2b55ca56bef57d74f4a84550e
a376acb9946cebf76bba2fe93626d7231c736ec5
eb444782087fa51b9e6c547556714fa7945ecbae
refs/heads/master
2022-11-23T05:38:44.612217
2020-07-28T04:56:25
2020-07-28T04:56:25
283,057,551
0
0
null
2020-07-28T00:59:33
2020-07-28T01:11:36
2020-07-28T04:56:26
Python
[ { "alpha_fraction": 0.647249162197113, "alphanum_fraction": 0.6532593369483948, "avg_line_length": 24.904191970825195, "blob_id": "c8e11aef94827e370f610fd51bfb17ae1ed841d0", "content_id": "93eeec156a5d776c33ff5a59668428d0753c2a5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4326, "license_type": "no_license", "max_line_length": 147, "num_lines": 167, "path": "/bot.py", "repo_name": "srypher/Wintermute", "src_encoding": "UTF-8", "text": "import os\nimport random\nimport ssl\n\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\nimport emoji\n\n\nload_dotenv()\nTOKEN = os.getenv('DISCORD_TOKEN')\nSERVER = os.getenv('SERVER_NAME')\n\nnum2emojis = {1: 'POGGERS', 2: 'KEKW', 3: '5Head', 4: '3Head', 5: 'Coomer', 6: 'FeelsRainMan', 7: 'HACKERMANS', 8: 'PartyKirby', 9: 'ricardoFlick'}\n\nmovie_list = {}\nkillers = []\nmovie_nominated = {}\nkiller_counts = {}\n\nclient = commands.Bot(command_prefix='$')\n\n## TODO:\n# Host this shit on AWS, Read in API Key in a safe way\n\n\[email protected]\nasync def on_ready():\n server = discord.utils.get(client.guilds, name=SERVER)\n\n print(\n f'{client.user} is connected to the following guild: \\n'\n f'{server.name}(id: {server.id})'\n )\n\n members = '\\n - '.join([member.name for member in server.members])\n print(f'Guild members:\\n - {members}')\n\n # keep track of how many times every player in the server has been killer\n for member in server.members:\n killer_counts[member.name] = 0\n movie_nominated[member.name] = False\n\n\[email protected]\nasync def on_member_join(member):\n killer_counts[member.name] = 0\n movie_nominated[member.name] = False\n\n\[email protected]\nasync def on_member_update(before, after):\n # update DbD tracking\n killer_counts[after.name] = killer_counts[before.name]\n del(killer_counts[before.name])\n\n if before.name in killers:\n killers.append(after.name)\n for killer in killers:\n if killer == before.name:\n del(killer)\n\n # update Movie Night tracking\n movie_nominated[after.name] = movie_nominated[before.name]\n del(movie_nominated[before.name])\n\n if before.name in movie_list.keys():\n movie_list[after.name] = movie_list[before.name]\n del(movie_list[before.name])\n\n\[email protected](name='nominate')\nasync def nominate(ctx, movie):\n user = ctx.message.author.name\n if movie_nominated[user]:\n await ctx.send(\"Sorry! You've already nominated a movie. You can undo your nomination with `$undo`\")\n return\n if movie not in movie_list and not movie_nominated[user]:\n movie_list[user] = movie\n movie_nominated[user] = True\n\n\[email protected](name='undo')\nasync def undo(ctx):\n user = ctx.message.author.name\n if not movie_nominated[user]:\n await ctx.send(\"Hmmm...looks like you haven't nominated a movie!\")\n return\n else:\n movie_nominated[user] = False\n del(movie_list[user])\n\n\[email protected](name='movies')\nasync def movies(ctx):\n if len(movie_list) == 0:\n return\n\n vote_movies = ''\n for movie in movie_list.values():\n vote_movies = vote_movies + f'{movie}\\n'\n\n await ctx.send(vote_movies)\n\n\[email protected](name='vote')\nasync def vote(ctx):\n server = discord.utils.get(client.guilds, name=SERVER)\n\n poll = '**Movie to Watch:**\\n'\n count = 1\n\n for movie in movie_list.values():\n poll += f'{discord.utils.get(server.emojis, name=num2emojis[count])} - {movie}\\n'\n count += 1\n\n message = await ctx.send(poll)\n\n for i in range(1, len(movie_list) + 1):\n emoji = discord.utils.get(server.emojis, name=num2emojis[i])\n await message.add_reaction(emoji)\n\n\[email protected](name='new')\nasync def new(ctx):\n movie_list.clear()\n\n for member in movie_nominated.keys():\n movie_nominated[member] = False\n\n\[email protected](name='killer')\nasync def killer(ctx):\n killer = ctx.message.author.name\n if killer not in killers:\n killers.append(killer)\n\n\[email protected](name='choose')\nasync def choose(ctx):\n if len(killers) == 0:\n await ctx.send(\"No-one has volunteered for killer. Have someone volunteeer with `$killer` then try again!\")\n return\n\n potential_killers = _find_killers(0)\n\n killer = potential_killers[random.choice(range(len(potential_killers)))]\n killer_counts[killer] = killer_counts[killer] + 1\n await ctx.send(f'{killer} is the killer!')\n killers.clear()\n\n\ndef _find_killers(kill_count):\n potential_killers = []\n\n for killer in killers:\n if killer_counts[killer] == kill_count:\n potential_killers.append(killer)\n\n if len(potential_killers) == 0:\n potential_killers = _find_killers(kill_count + 1)\n\n return potential_killers\n\n\nclient.run(TOKEN)\n" } ]
1
Hysham/DataEngChallenge
https://github.com/Hysham/DataEngChallenge
4ff6a7e8ce7a9eb8f1c3e50115a17ff95000b015
d4551e79a41a80a2c644ebab57a2fc36b0021578
6949d6087620b6290b973874701b729b39fdc274
refs/heads/master
2021-06-29T13:17:35.992261
2019-04-26T06:22:56
2019-04-26T06:22:56
183,351,969
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.7602040767669678, "avg_line_length": 17.714284896850586, "blob_id": "fa437bfbe8197a423eca3195c67a67525dcb5033", "content_id": "03f84c5799699d91ab8ca619c925cb96c2dde264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 392, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/README.md", "repo_name": "Hysham/DataEngChallenge", "src_encoding": "UTF-8", "text": "# Statistics Calculator From Github Repositories\n\nThis is a python script to calculate some statistics from 100,000 public github repositories\n\n## Requirements\n- python3\n- pip3\n\n\n## Installation\n\nUse the package manager [pip3](https://pip.pypa.io/en/stable/) to install pygithub.\n\n```bash\npip3 install pygithub\n```\n\n## Usage\n\n```bash\npython3 PyCodeStats.py <github-username> <github-password>" }, { "alpha_fraction": 0.47735485434532166, "alphanum_fraction": 0.48530474305152893, "avg_line_length": 42.875675201416016, "blob_id": "6f970fff75170257c4d2d3b9c46c37d2b01c62d9", "content_id": "bd0e8f6a640ad0e713fe646d5fa2108335e28928", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8302, "license_type": "no_license", "max_line_length": 144, "num_lines": 185, "path": "/PyCodeStats.py", "repo_name": "Hysham/DataEngChallenge", "src_encoding": "UTF-8", "text": "from github import Github\r\nimport urllib.request\r\nimport re\r\nimport ssl\r\nimport sys\r\nfrom concurrent.futures import ThreadPoolExecutor\r\n\r\ngcontext = ssl.SSLContext()\r\ng = Github(sys.argv[1], sys.argv[2], base_url=\"https://api.github.com\")\r\n\r\n\r\n\"\"\"\r\nFunc: get_stats_from_a_repo\r\n\r\ninput params:\r\nrepository_url: String\r\n\r\noutput:\r\nresult: dict [containing the statistics of the repository]\r\n\"\"\"\r\n\r\ndef get_stats_from_a_repo(repository_url):\r\n\r\n try:\r\n # Initial variables to calculate the stats\r\n line_count = 0\r\n imports = []\r\n func_params = []\r\n variables = 0\r\n loop_depths = []\r\n depth_level = 0\r\n loop_start_spaces = 0\r\n current_spaces = 0\r\n duplicates = []\r\n\r\n # Get the part of repo from the url which will be used to fetch its components\r\n repo = g.get_repo(str(repository_url.split(\".com/\", 1)[1].rstrip(\"\\n\\r\")))\r\n\r\n # Get all contents from the repo thus the empty string a param\r\n contents = repo.get_contents(\"\")\r\n\r\n while len(contents) > 1:\r\n file_content = contents.pop(0)\r\n if file_content.type == \"dir\": # Open up further if it is a directory\r\n contents.extend(repo.get_contents(file_content.path))\r\n elif file_content.download_url:\r\n if file_content.download_url.endswith(\".py\"): # If we have found a code file\r\n all_code_lines = []\r\n for line in urllib.request.urlopen(file_content.download_url, context=gcontext): # Loading the file from remote url\r\n string_line = line.decode(\"utf-8\") # Converting the encoded line into string making it readable for the python code\r\n\r\n\r\n \"\"\"\r\n Checking if it is a real line of code, all empty lines are ignored,\r\n multi-line comments not supported\r\n \"\"\"\r\n if string_line and string_line[0] != \"\\n\" and string_line.lstrip() and \\\r\n string_line.lstrip()[0] != \"#\":\r\n all_code_lines.append(string_line.replace(\" \", \"\").split('#', 1)[0].rstrip(\"\\n\\r\"))\r\n if string_line.lstrip().partition(' ')[0] == \"import\" or \\\r\n string_line.lstrip().partition(' ')[0] == \"from\":\r\n imports.append(\r\n string_line.lstrip().split(' ', 1)[1].rstrip(\"\\n\\r\").split(' ', 1)[0])\r\n if \" = \" in string_line:\r\n variables += 1\r\n line_count += 1\r\n\r\n \"\"\"\r\n To calculate the nesting factor if a loop is found\r\n initial starting point is saved and the end of loop\r\n is searched\r\n \"\"\"\r\n\r\n if string_line.lstrip().partition(' ')[0] == \"for\": # If there is a loop in this line\r\n if depth_level == 0: # Start of a loop found\r\n depth_level += 1\r\n current_spaces = len(string_line) - len(string_line.lstrip())\r\n loop_start_spaces = current_spaces # Saving current depth of the nesting factoring\r\n else:\r\n new_spaces = len(string_line) - len(string_line.lstrip()) # Checking for new depth of nesting factor\r\n if new_spaces > current_spaces:\r\n current_spaces = new_spaces\r\n depth_level += 1\r\n\r\n # Check if the outer most loop has ended\r\n if len(string_line) - len(string_line.lstrip()) <= loop_start_spaces and depth_level > 0 \\\r\n and string_line.lstrip().partition(' ')[0] != \"for\":\r\n loop_depths.append(depth_level)\r\n depth_level = 0\r\n\r\n # Function definition found\r\n if string_line.lstrip().partition(' ')[0] == \"def\":\r\n params = string_line.split('(', 1)[1].split(')', 1)[0]\r\n # Catch the params in the definition\r\n if params:\r\n func_params.append(len(string_line.split('(', 1)[1].split(')', 1)[0].split(',')))\r\n else:\r\n func_params.append(0)\r\n\r\n \"\"\"\r\n Take a chunk of four lines every time and then look for it\r\n in the rest of the file\r\n \"\"\"\r\n for i in range(0, len(all_code_lines)):\r\n duplication = 0\r\n four_lines = []\r\n if i + 4 <= len(all_code_lines):\r\n for j in range(i, i + 4):\r\n four_lines.append(all_code_lines[j])\r\n \"\"\"\r\n Sum the matches found for 4 lines chunk and decrement by 1\r\n to make sure that chunk is not matching to itself\r\n \"\"\"\r\n duplication = sum(\r\n all_code_lines[k:k + len(four_lines)] == four_lines for k in range(len(all_code_lines))) - 1\r\n if duplication > 0:\r\n duplicates.append(duplication)\r\n\r\n # If the file ends with a loop then add this depth_level for nesting factor\r\n if depth_level > 0:\r\n loop_depths.append(depth_level)\r\n depth_level = 0\r\n\r\n\r\n\r\n # Calculating stats from raw results\r\n duplication_avg = 0\r\n if len(duplicates) > 0:\r\n duplication_avg = sum(duplicates)/len(duplicates)\r\n\r\n func_params_avg = 0\r\n if len(func_params) > 0:\r\n func_params_avg = sum(func_params)/len(func_params)\r\n\r\n nesting_factor = 0\r\n if len(loop_depths) > 0:\r\n nesting_factor = sum(loop_depths)/len(loop_depths)\r\n\r\n average_variables = 0\r\n if line_count > 0:\r\n average_variables = variables / line_count\r\n\r\n # Creating a dictionary of results for the repository\r\n result = {\r\n 'repository_url': repository_url.rstrip(\"\\n\\r\"),\r\n 'number of lines': line_count,\r\n 'libraries': imports,\r\n 'nesting factor': nesting_factor,\r\n 'code duplication': duplication_avg,\r\n 'average parameters': func_params_avg,\r\n 'average variables': average_variables\r\n }\r\n\r\n # return the resultant statistics for the repo\r\n return result\r\n except:\r\n return {\r\n 'repository_url': repository_url.rstrip(\"\\n\\r\"),\r\n 'status': 'unable to process with repo'\r\n }\r\n\r\n\r\n# The file to read all the repository URLs from\r\nrepos_list = urllib.request.urlopen(\"https://raw.githubusercontent.com/monikturing/turing-data-challenge/master/url_list.csv\", context=gcontext)\r\n\r\n# First line of the file is a header, so to ignore it\r\nnext(repos_list)\r\n\r\nmaster_stats = []\r\n\r\noutput_file = open(\"output.txt\", \"w\")\r\noutput_file.write(\"[\")\r\n# Create a pool of threads to carry out the complete job, pool size is random\r\nwith ThreadPoolExecutor(max_workers=25) as executor:\r\n for repo in repos_list:\r\n if repo.decode(\"utf-8\") != \"https://github.com/braingineer/ikelos\\n\" and \\\r\n repo.decode(\"utf-8\") != \"https://github.com/congresso-em-numeros/congresso\\n\" and \\\r\n repo.decode(\"utf-8\") != \"https://github.com/bjut-hz/SAO\\n\":\r\n print(\"=== Repository Url ===\")\r\n print(repo.decode(\"utf-8\"))\r\n stats = executor.submit(get_stats_from_a_repo, repo.decode(\"utf-8\")).result()\r\n output_file.write(str(stats) + \",\\n\")\r\n master_stats.append(stats)\r\noutput_file.write(\"]\")\r\noutput_file.close()\r\n" } ]
2
rakosg/cs261-tdd-queue
https://github.com/rakosg/cs261-tdd-queue
d78ba93939686d10004814a1e954f4a8c55cfceb
39ef66f481e5bcc17096e65504cbedcd4fa4b656
c51de0689a6eea2e5a053e562a7819ca59130b15
refs/heads/master
2022-01-04T19:15:55.303383
2019-11-02T07:55:29
2019-11-02T07:55:29
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7093023061752319, "alphanum_fraction": 0.7151162624359131, "avg_line_length": 16.100000381469727, "blob_id": "e8397fd8408de412f789edd4cef4b4f704910cf2", "content_id": "f401e974a0bb18c613d80ef321fb3b55d2700e94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 172, "license_type": "no_license", "max_line_length": 61, "num_lines": 10, "path": "/queue.py", "repo_name": "rakosg/cs261-tdd-queue", "src_encoding": "UTF-8", "text": "# Queue: A queue.\n# Your implementation should pass the tests in test_queue.py.\n# YOUR NAME\n\n# Hint: pip3 install llist\n# from llist import sllist\n\nclass Queue:\n\n pass\n\n" } ]
1
bzator/ASE2022_AOT_artifacts
https://github.com/bzator/ASE2022_AOT_artifacts
d66e41622b965bcf8db3c6b79b907bb0b2a9be65
8f6751f907e8010093f4ac4eb72664341ec8a3cf
9520ca481fad01e70ef8deb49bbc189f5f391766
refs/heads/master
2023-04-08T07:44:16.816676
2022-09-07T07:03:19
2022-09-07T07:03:19
519,195,555
0
0
Apache-2.0
2022-07-29T11:48:58
2022-07-30T16:29:32
2022-08-29T14:47:24
Python
[ { "alpha_fraction": 0.6601178646087646, "alphanum_fraction": 0.6635559797286987, "avg_line_length": 27.29166603088379, "blob_id": "ba3768db8206423b34354f452f19038ec70e5bc5", "content_id": "12170b6f2f5c69d63952b49b104af5884e6b6e04", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2036, "license_type": "permissive", "max_line_length": 149, "num_lines": 72, "path": "/extract-lk-info-for-ftdb", "repo_name": "bzator/ASE2022_AOT_artifacts", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport sys\nimport libetrace\nimport json\nimport re\n\nnfsdb = libetrace.nfsdb()\nnfsdb.load(sys.argv[1],quiet=True)\n\n# Getting linked lk path\nL = [e.linked_file for e in nfsdb if e.is_linking() and e.linked_file.endswith(\"lk.elf\")]\n\n# Getting file dependencies for vmlinux kernel module and all loadable modules\nmdeps = {}\nfor f in L:\n\texcl_patterns = [\"/dev/*\"]\n\tmdeps[f]=set(nfsdb.fdeps(f,exclude_patterns=excl_patterns)[1])\ndeps = set()\nfor x in mdeps.values():\n\tdeps|=x\nprint (\"Total dependencies: %d\"%(len(deps)))\n\ncmap = {}\nh = re.compile(\"^/dev/.*\")\nfor e in nfsdb:\n\tif e.has_compilations():\n\t\tfor cf in e.compilation_info.files:\n\t\t\tif not h.match(cf):\n\t\t\t\tif cf not in cmap:\n\t\t\t\t\tcmap[cf] = e\n\ncomps = set()\nfor f in deps:\n\tif f in cmap:\n\t\tcomps.add((cmap[f].eid.pid,cmap[f].eid.index))\t\t\t\nprint (\"Number of compilations: %d\"%(len(comps)))\n\n# Generate compilation database\ndef json_command(cmd):\n\treturn json.dumps(\" \".join([x.rstrip().replace(\"\\\\\",\"\\\\\\\\\").replace(\"\\\"\",\"\\\\\\\"\").replace(\" \",\"\\\\ \") for x in cmd]))\n\njson_vals = list()\nfor C in comps:\n\te = nfsdb[C]\n\tjson_vals.append( \"{\\\"directory\\\":%s,\\\"command\\\":%s,\\\"file\\\":%s}\"%(json.dumps(e.cwd),json_command(e.argv),json.dumps(e.compilation_info.files[0])) )\nwith open(\"compile_commands.json\",\"w\") as f:\n\tf.write(json.dumps(json.loads(\"[%s]\"%\",\".join(json_vals)), indent=4, sort_keys=False))\nprint (\"created compilation database file (compile_commands.json)\")\n\n# Generate compilation dependency map\ncdm = {}\nfor m,deplist in mdeps.items():\n\tcdm[m] = []\n\tfor f in deplist:\n\t\tif f in cmap:\n\t\t\tcdm[m].append(f)\nwith open(\"cdm.json\",\"w\") as f:\n\tf.write(json.dumps(cdm, indent=4, sort_keys=False))\nprint (\"created compilation dependency map file (cdm.json)\")\n\n# Generate reverse dependency map file\nrdm = {}\nfor m,deplist in mdeps.items():\n\tfor f in deplist:\n\t\tif f in rdm:\n\t\t\trdm[f].append(m)\n\t\telse:\n\t\t\trdm[f] = [m]\nwith open(\"rdm.json\",\"w\") as f:\n\tf.write(json.dumps(rdm, indent=4, sort_keys=False))\nprint (\"created reverse dependency map file (rdm.json)\")" }, { "alpha_fraction": 0.7480975985527039, "alphanum_fraction": 0.7705326676368713, "avg_line_length": 72.29808044433594, "blob_id": "a286138d813457495ea88a52215d51aafb462481", "content_id": "6cf713479f9cf4d33b4a6d1184fb2c381bdc123b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7622, "license_type": "permissive", "max_line_length": 1185, "num_lines": 104, "path": "/README.md", "repo_name": "bzator/ASE2022_AOT_artifacts", "src_encoding": "UTF-8", "text": "## Introduction\n\nThis repository contains information regarding artifacts generated for the purpose of the \"Auto Off-Target: Enabling Thorough and Scalable Testing for Complex Software Systems\" paper written by Tomasz Kuchta and Bartosz Zator. This paper describes experiments with off-target (OT) generation for four target systems: Android Linux kernel running on Pixel 6 device, the Little Kernel Embedded Operating System (`lk`), Das U-Boot (`uboot`) - a bootloader bootloader for embedded devices and the IUH module of the Osmocom project implementing the IUH interface for femtocell communication from a 3GPP standard. Although originally artifacts were generated for all target systems this repository contains information only about artifacts for the `lk` project. This is due to the enormous size of the artifact directories. The directory for the `lk` project itself (which is the smallest of the four) contains 12GB of data in its original form (unpacked). The principles of how the artifacts are used or what they represent don't change across the projects therefore it is assumed that the artifacts from the `lk` project can serve as a representative example to the paper understanding and verification.\n\n## Artifact repository\n\nThe public repository that contains the `lk` artifacts can be found at the following link: [aot_lk_artifact.tar.gz](https://figshare.com/s/c464484f996b9e49b835). It can be downloaded and extracted with the following Linux commands:\n```bash\nwget \"https://figshare.com/ndownloader/files/35010967?private_link=c464484f996b9e49b835\" -O aot_lk_artifact.tar.gz\ntar -xf aot_lk_artifact.tar.gz\n```\n\nAfter extraction the repository contains the following files:\n\n* cdm.json : compilation dependency map, which is a list of compiled files for all relevant modules (single linked lk binary in this case)\n* compile_commands.json : a list of commands used to compile each source file\n* ndb.json : Code DB for the `lk` linked module\n* rdm.json : reverse dependency map, which maps all relevant files to the corresponding modules that used them\n* results : a directory with the generated 1000 off-target programs for `lk`\n\nThe `results` directory contains all the Off-target code generated for all functions evaluated for the `lk` target system which is the primary artifact to be verified as the main theme of the paper is extraction and generation of a correct C code from a larger S/W system. Additionally there are also results from the testing campaigns (fuzzer logs and artifacts) executed to properly evaluate the `AoT` usefulness (summary of the collected data from all test sessions are also available in the form of `.csv` files). All the Off-targets code was generated using two tools recently released to open source, i.e.:\n* [Auto Off-Target](https://github.com/Samsung/auto_off_target)\n* [CAS](https://github.com/Samsung/CAS)\n\nThese are the core engines that were release to open source and are also artifacts for the paper. The test management scripts are not present as it was not included in the open sourced packages.\n\nThe description below provides a guide to generate off-target (OT) for selected functions. The expected result of the OT generation is the directory with created source code that is ready to be built. The build process creates OT executables with various code instrumentations embedded which can be used for different purposes (i.e. fuzzing, coverage tracking, debugging etc.).\n\n## Off-target generation\n\nThe Auto Off-Target project is able to generate off-target (OT) code for a given function automatically. More information can be found on the [AoT](https://github.com/Samsung/auto_off_target) project page. In order for the `AoT` project to work properly it needs Code Database (CodeDB) for a given project we're working on. Code Database can be generated using the Code Aware Services ([CAS](https://github.com/Samsung/CAS)) project. Please refer to the [README.md](https://github.com/Samsung/CAS/blob/master/README.md) file for more information how to setup and use the `CAS` project. Having the `CAS` setup properly the Code DB for the `lk` project can be created as follows.\n\nFirst clone and build the repository under `CAS` tracer:\n```bash\ngit clone https://github.com/littlekernel/lk.git && cd lk\nexport LK_DIR=$(pwd)\ngit checkout 77fa084cd05459a1f360a2b825e14ea6e60518e5\netrace scripts/make-parallel qemu-virt-arm32-test\n````\n\nNext create the Build Database:\n```bash\nexport CAS_DIR=<path_to_CAS_repository>\n${CAS_DIR}/etrace_parser .nfsdb\npython3 ${CAS_DIR}/bas/postprocess.py .nfsdb.json\n${CAS_DIR}/bas/postprocess.py --create-nfsdb-cache .nfsdb.json\n```\n\nIn the next step we have to prepare some files needed for the Code Database creation:\n```bash\nexport PYTHONPATH=${CAS_DIR}\ngit clone https://github.com/bzator/ASE2022_AOT_artifacts.git\nASE2022_AOT_artifacts/extract-lk-info-for-ftdb .nfsdb.json.img\n```\n\nNow create the Code Database:\n```bash\nexport CLANG_PROC=${CAS_DIR}/clang-proc/clang-proc\n${CAS_DIR}/clang-proc/create_json_db -P ${CLANG_PROC} -p fops -o fops.json\n${CAS_DIR}/clang-proc/create_json_db -p db -o db.json -P $CLANG_PROC -F fops.json -m lk -V \"77fa084cd05459a1f360a2b825e14ea6e60518e5\" -A -cdm cdm.json -j4\n${CAS_DIR}/tests/ftdb_cache_test --only-ftdb-create db.json\n```\n\nFinally setup the `AoT` project repository as described in the [Readme.md](https://github.com/Samsung/auto_off_target/blob/master/README.md) file. Make sure that the `AOT_DIR` environmental variable points to the proper `AOT` repository. First create some required configuration files (inside the `lk` project source code):\n```bash\necho \"{ \\\"BASserver\\\": \\\"https://localhost\\\" }\" > cfg.json\ncp ${AOT_DIR}/src/known_functions .\ncp ${AOT_DIR}/src/lib_functions .\ncp ${AOT_DIR}/src/always_include .\necho \"[]\" > init.json\n````\n\nNext import the Code Database for the `lk` product to be used by `AoT`:\n```bash\n${AOT_DIR}/src/aot.py --config=cfg.json --product=lk --version=77fa084cd05459a1f360a2b825e14ea6e60518e5 --build-type=eng --import-json=db.json --rdm-file=rdm.json --known-funcs-file=known_functions --lib-funcs-file=lib_functions --always-inc-funcs-file=always_include --init-file=init.json --source-root=${LK_DIR}\n```\n\nNow you can generate off-target (OT) for a given function (let's take the `minip_parse_ipaddr` function as an example):\n```bash\n${AOT_DIR}/src/aot.py --config=cfg.json --product=lk --version=77fa084cd05459a1f360a2b825e14ea6e60518e5 --build-type=eng --db=db.img --output-dir out_minip_parse_ipaddr --functions minip_parse_ipaddr --external-inclusion-margin 1 --init --verify-struct-layout\n```\nNow the OT for the `minip_parse_ipaddr` function should have been created in the `out_minip_parse_ipaddr` directory.\n\n## Testing the off-target\n\nIn order to test the generated off-target the first thing to do is to compile the OT sources:\n```bash\n(cd out_minip_parse_ipaddr && make)\n```\n\nThis will produce the `native` binary with the compiled (and linked) off-target code. Adding `AFL` instrumentation requires a different target to build:\n```bash\n(cd out_minip_parse_ipaddr && make afl)\n```\n\nThere are other targets like `asan`, `msan`, `ubasn`, `dfsan`, `klee` etc. Please consult the generated `Makefile` for details (building some of the targets might require latest clang version 15 installed). After the build of the `afl` target completes the OT is ready to be fuzzed.\n\n```bash\ncd out_minip_parse_ipaddr\nmkdir -p testcase && dd if=/dev/zero of=testcase/zero bs=4 count=1\nafl-fuzz -m none -i testcase -o findings -- ./afl @@\n```\n\nOther testing techniques (like symbolic execution by using the `KLEE`) can be used on other targets as appropriate." } ]
2
fabiopuddu77/Paypal
https://github.com/fabiopuddu77/Paypal
f34b21692a104740fdd8b8c74a17948c52b35b30
1059247f87136b3213525e134881a4e397f226a1
ed70f3ce138005dce3331ffe256cefcc420a89a0
refs/heads/master
2023-03-18T07:20:05.994488
2021-10-08T08:33:11
2021-10-08T08:33:11
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8644067645072937, "alphanum_fraction": 0.8644067645072937, "avg_line_length": 5.666666507720947, "blob_id": "f418909fae48f5a62c99d829c96f0cc147ead6fb", "content_id": "ea9c00714f28c25510141c5d2f6ec11ce73605fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 59, "license_type": "no_license", "max_line_length": 10, "num_lines": 9, "path": "/requirements.txt", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "wheel\nnumpy\npandas\nnltk\nmatplotlib\nnetworkx\nseaborn\n\nPillow" }, { "alpha_fraction": 0.6754807829856873, "alphanum_fraction": 0.676682710647583, "avg_line_length": 25.870967864990234, "blob_id": "f49528c88810a73ae316cfbb2261e5e2c305e07c", "content_id": "0252daa25b26df0040b96a190aaf2484c8780eb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 832, "license_type": "no_license", "max_line_length": 119, "num_lines": 31, "path": "/Inventor.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "import string\n\nimport matplotlib\nimport nltk\nimport pandas as pd\nimport network2 as nx\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\n\nimport csv\n\nimport itertools\n\ndf = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\ndf_cities = pd.read_csv(\"./Abstract/uscities.csv\", error_bad_lines=False, sep=',')\n\nlista_inv = [i.replace(\"|\",\",\").replace('.','').replace(' ','') for i in df[\"Inventor - w/address\"]]\n\nparole = \",\".join(lista_inv).split(',')\n\nlista_cit = [i for i in df_cities['city']]\nlista_county = [i for i in df_cities['county_name']]\n\n#diz = [(city,county,parole.count(city)) for city in parole if city in lista_cit if county in df_cities['county_name']]\n\n#print(diz.keys())\n\n# df = pd.DataFrame(diz.items(), columns=['City', 'Frequency'])\n#\n#\n# df.to_csv('cities_freq.csv', index=False)" }, { "alpha_fraction": 0.6449438333511353, "alphanum_fraction": 0.6576778888702393, "avg_line_length": 29.340909957885742, "blob_id": "247aeb531acbc0462f88b2541aec98407ec7a499", "content_id": "41d8b2f85e3585c75a37e0dbc929141e618b723f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1335, "license_type": "no_license", "max_line_length": 115, "num_lines": 44, "path": "/network2.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "\nimport matplotlib\nimport nltk\nimport pandas as pd\nimport networkx as nx\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\n\nimport itertools\n\n\ndf = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\n\ndef get_edges(data, column):\n series = data[column].dropna().apply(lambda x: x.split(\", \"))\n\n cross = series.apply(lambda x: list(itertools.combinations(x, 2)))\n\n lists = [item for sublist in cross for item in sublist]\n\n source = [i[0] for i in lists]\n target = [i[1] for i in lists]\n edges = pd.DataFrame({\"source\": source, \"target\": target})\n edges[\"weight\"] = 1\n return edges.groupby(by=[\"source\", \"target\"], as_index=False)[\"weight\"].sum()\n\n\ndf_edges = get_edges(data=df, column=\"CPC Class - DWPI\")\n\nG = nx.from_pandas_edgelist(df_edges, source=\"source\", target=\"target\", edge_attr=[\"weight\"],create_using=nx.Graph)\n\npos = nx.spring_layout(G) # positions for all nodes\n\nnode_color = [G.degree(v) for v in G]\nnode_size = [0.0005 * nx.get_node_attributes(G, 'target')[v] for v in G]\nedge_width = [0.0015 * G[u][v]['weight'] for u, v in G.edges()]\n\nnx.draw_networkx(G, node_size=node_size,\n node_color=node_color, alpha=0.7,\n with_labels=True, width=edge_width,\n edge_color='.4', cmap=plt.cm.Blues)\n\nplt.axis('off')\nplt.tight_layout()\nplt.show()" }, { "alpha_fraction": 0.6050847172737122, "alphanum_fraction": 0.6173728704452515, "avg_line_length": 29.256410598754883, "blob_id": "24a97f4363838e514144bca5ceb860eb04a31790", "content_id": "aa2faf99fc81384771b6e7dcaea13cf830aa35c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2361, "license_type": "no_license", "max_line_length": 114, "num_lines": 78, "path": "/Wordcloud.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "\nimport nltk\nimport PIL\nfrom PIL import Image\nimport numpy as np\n\nimport matplotlib\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords, CategorizedPlaintextCorpusReader\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet\nimport pandas as pd\nfrom wordcloud import WordCloud\n\nclass Document():\n\n def __init__(self, dir, doc):\n self.doc = doc\n self.dir = dir\n self.eng_stopw = stopwords.words('english')\n\n\n text_corpus = CategorizedPlaintextCorpusReader(\n './%s/' % self.dir,\n r'.*\\.txt', # leggo solamente i file che terminato con .csv\n cat_pattern=r'(\\w+)/*', # prendi tutto quello che c'è dopo la directory\n encoding='latin-1'\n )\n\n self.text = nltk.Text(text_corpus.words(self.doc))\n\n def freq_dist(self):\n return nltk.FreqDist([w for w in self.text if len(w) >= 2])\n\n def parole(self):\n return [(i) for i in self.freq_dist().most_common()]\n\n def tokenize(self):\n return ([w for w in self.text if len(w) >= 4 and w not in self.eng_stopw])\n\n def wordcloud(self,stopword,mask_k):\n\n list = (\" \").join(self.tokenize())\n wordcloud = WordCloud(max_font_size=50, max_words=100, background_color=\"white\",stopwords=stopword,\n collocations=False,\n repeat=False, contour_width=3, contour_color='firebrick',mask=mask_k).generate(list)\n plt.figure(figsize=[20,10])\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n return\n\n\nif __name__ == \"__main__\":\n file3 = Document(\"./Abstract\", \"Stati2015.txt\")\n\n\n print(file3.parole())\n ###### WORDCLOUD ######\n paypal_mask = np.array(Image.open(\"./Abstract/paypal.png\"))\n def transform_format(val):\n if val.any() == 0:\n return 255\n else:\n return val\n\n transformed_pp_mask = np.ndarray((paypal_mask.shape[0], paypal_mask.shape[1]), np.int32)\n\n for i in range(len(paypal_mask)):\n transformed_pp_mask = list(map(transform_format, paypal_mask[i]))\n\n\n stopword = set()\n stopword.update([\"system\"])\n\n file2 = Document(\"./Abstract\",\"pp_tit_dwpi.csv\")\n print(\"WordCloud\",file2.wordcloud(stopword,paypal_mask))" }, { "alpha_fraction": 0.6711496710777283, "alphanum_fraction": 0.6863340735435486, "avg_line_length": 27.09756088256836, "blob_id": "4deff7d0984dfb30604196d82afb50c7cc821425", "content_id": "7bdb686f18fd9b69a05933e84bf551b8e4071765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2305, "license_type": "no_license", "max_line_length": 115, "num_lines": 82, "path": "/network.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "import matplotlib\nimport nltk\nimport pandas as pd\nimport networkx as nx\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\n\n\nimport itertools\n\n\ndf = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\n\ndef get_edges(data, column):\n series = data[column].dropna().apply(lambda x: x.split(\", \"))\n\n cross = series.apply(lambda x: list(itertools.combinations(x, 2)))\n\n lists = [item for sublist in cross for item in sublist]\n source = [i[0] for i in lists]\n target = [i[1] for i in lists]\n edges = pd.DataFrame({\"source\": source, \"target\": target})\n edges[\"weight\"] = 1\n return edges.groupby(by=[\"source\", \"target\"], as_index=False)[\"weight\"].sum()\n\n\ndf_edges = get_edges(data=df, column=\"CPC Class - DWPI\")\n\n\ng = nx.from_pandas_edgelist(df_edges, source=\"source\", target=\"target\", edge_attr=[\"weight\"],create_using=nx.Graph)\n\ndf = df_edges\n\nclubs = list(df.source.unique())\n\npeople = list(df.target.unique())\n\ndict(zip(clubs, clubs))\n\nplt.figure(figsize=(12, 12))\n\n# 1. Create the graph\n\n# 2. Create a layout for our nodes\nlayout = nx.spring_layout(g,iterations=100)\n\n# 3. Draw the parts we want\n# Edges thin and grey\n# People small and grey\n# Clubs sized according to their number of connections\n# Clubs blue\n# Labels for clubs ONLY\n# People who are highly connected are a highlighted color\n\n# Go through every club name, ask the graph how many\n# connections it has. Multiply that by 80 to get the circle size\nclub_size = [g.degree(club) * 90 for club in clubs]\nnx.draw_networkx_nodes(g,\n layout,\n nodelist=clubs,\n node_size=club_size, # a LIST of sizes, based on g.degree\n node_color='lightblue')\n\n# Draw EVERYONE\nnx.draw_networkx_nodes(g, layout, nodelist=people, node_color='lightblue', node_size=300)\n\n# Draw POPULAR PEOPLE\npopular_people = [person for person in people if g.degree(person) > 10]\nnx.draw_networkx_nodes(g, layout, nodelist=popular_people, node_color='#F4D03F', node_size=520)\n\nnx.draw_networkx_edges(g, layout, width=1, edge_color=\"#D0D3D4\")\n\nnode_labels = dict(zip(clubs,clubs))\nnx.draw_networkx_labels(g, layout)\n\n# 4. Turn off the axis because I know you don't want it\nplt.axis('off')\n\nplt.title(\"Class Patents\")\n\n# 5. Tell matplotlib to show it\nplt.show()\n\n" }, { "alpha_fraction": 0.6138002276420593, "alphanum_fraction": 0.6230689883232117, "avg_line_length": 25.16216278076172, "blob_id": "357a9a526ca5f1c4d219de324d34cac12f00914a", "content_id": "1eaf5c036be511c821ebe680635583c682af9f5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 74, "num_lines": 37, "path": "/main.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "import network2 as nx\nimport pylab as plt\n\nfrom crawler import Crawler, Page, Document, Corpus\n\nif __name__ == '__main__':\n start_page = Page('http://info.cern.ch/hypertext/WWW/TheProject.html')\n crawler = Crawler(start_page)\n crawler.crawl()\n\n\n web_graph = nx.DiGraph()\n edges = []\n edges2 = []\n\n for page in crawler.web:\n for link in page.links:\n edges.append((hash(page.address), hash(link)))\n\n web_graph.add_edges_from(edges)\n nx.draw(web_graph)\n plt.show()\n pageRanks = nx.pagerank(web_graph)\n for page in crawler.web:\n page.page_rank = pageRanks[hash(page.address)]\n pages = sorted(crawler.web, key=lambda p: p.page_rank, reverse=True)\n\n corpus = []\n for page in pages:\n corpus.append((page.address, page.text))\n\n corpus2 = []\n for corp in corpus[0:3]:\n corpus2.append((Document(corp[0], corp[1])))\n\n corp = Corpus(corpus2)\n print(corp.rank(query=\"World-Wide Web\"))\n\n\n\n" }, { "alpha_fraction": 0.5691990852355957, "alphanum_fraction": 0.5827444195747375, "avg_line_length": 25.100000381469727, "blob_id": "b51738cba810738cf6d3c871f97f0928aa2f4137", "content_id": "60f7b2434112c085b04c126102c88898efc0735b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3396, "license_type": "no_license", "max_line_length": 117, "num_lines": 130, "path": "/paypal_data.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "import matplotlib\nimport seaborn as sns\nimport nltk\nimport math\n\n\nmatplotlib.use('TkAgg')\nfrom matplotlib import pyplot as plt\nimport pandas as pd\n\n\n#df = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\ndf3 = pd.read_csv(\"./Abstract/AppDate15.csv\", error_bad_lines=False, sep=';')\n\n\n# class Dataframe():\n#\n# def __init__(self, df, nome):\n#\n# self.df = df\n# self.nome = self.df[\"DWPIManualCodes\"]\n# print(self.nome)\n#\n#\n# def lista_col(self):\n# a = [i for i in self.nome if str(i) != \"nan\"]\n# return (\",\").join(a).replace(\" \",\"\").split(\",\")\n#\n#\n#\n# def freq_dist(self):\n# # lista = nltk.Text(self.lista_col())\n# return nltk.FreqDist([w for w in nltk.Text(self.lista_col())])\n#\n# def parole(self):\n# return [i for i in self.freq_dist()]\n\n# def get_edges(data, column):\n# series = data[column].dropna().apply(lambda x: x.split(\", \"))\n# cross = series.apply(lambda x: [i for i in combinations(x, 2)])\n# lists = [item for sublist in cross for item in sublist]\n# source = [i[0] for i in lists]\n# target = [i[1] for i in lists]\n# edges = pd.DataFrame({\"source\": source, \"target\": target})\n# edges[\"weight\"] = 1\n# return edges.groupby(by=[\"source\", \"target\"], as_index=False)[\"weight\"].sum()\n#\n#\n# df_edges = get_edges(data=brevetti_y[brevetti_y[\"Publication Year\"]==2015], column=\"CPC Class\")\n#\n# G = nx.from_pandas_edgelist(df_edges, source=\"source\", target=\"target\", edge_attr=[\"weight\"],create_using=nx.Graph)\n# pos = nx.spring_layout(G, k=2.5)\n\n#\n# class Frequenza():\n# def __init__(self, lista, stato, anno):\n# self.lista = lista\n# self.stato = stato\n# self.anno = anno\n#\n#\n# def numeri(self):\n# return [(i,self.lista.count(i)) for i in self.lista]\n#\n# def stati(self):\n# pass\n#\n#\n# def finale(self):\n# l = []\n# for i in self.numeri():\n# if i not in l:\n# l.append(i)\n# return sorted(l)\n#\n# def conteggio(self):\n# l = [(i,j[0]) for i in lista_anni for j in lista_state_pub]\n# return [i for i in l if i[1] == self.stato and i[0] == self.anno]\n#\n#\n#\n# f1 = Frequenza(lista_anni,\"US\",2020)\n#\n#\n# print((f1.conteggio()))\n\n\n\n\n\n\n\n# print(df['Publication Year'])\n# plt.figure(figsize=(10,8))\n# sns.countplot(df[\"Publication Year\"], color=\"blue\")\n# plt.tight_layout()\n# plt.show()\n\n# df['Publication Year'].value_counts().sort_index().plot.bar()\n# plt.show()\n\n# sns.distplot(df['Publication Year'], bins=10, kde=True)\n# plt.show()\n\n# with sns.axes_style('white'):\n# g = sns.factorplot(\"Publication Year\", data=df, aspect=2,\n# kind=\"count\", color='steelblue')\n# g.set_xticklabels(step=5)\n# plt.show()\n\n# with sns.axes_style('white'):\n# g = sns.factorplot(\"Publication Year\", aspect=4.0, kind='count',\n# hue='Publication Country Code', order=range(2000, 2021))\n# g.set_ylabels('Number of Class Discovered')\n# plt.show()\n\nif __name__ == \"__main__\":\n\n #df = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\n\n #D = Dataframe(df3,\"DWPIManualCodes\")\n\n\n #df2 = pd.DataFrame(D.lista_col(),columns=[\"class\"])\n\n #print(df2)\n plt.figure(figsize=(10, 8))\n sns.countplot(sorted(df3[\"ApplicationDate\"]), color=\"darkred\")\n plt.tight_layout()\n plt.show()\n\n\n\n" }, { "alpha_fraction": 0.804347813129425, "alphanum_fraction": 0.804347813129425, "avg_line_length": 63.20000076293945, "blob_id": "97a9a27617bc01beb90e5f6c7c9b247888a42922", "content_id": "ef636091c81243eba2418379c8d2e548d1d81e1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 322, "license_type": "no_license", "max_line_length": 129, "num_lines": 5, "path": "/README.md", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "\n# Description Patent analysis Paypal #\n\nThe patents of the Paypal Company were analysed in order to understand\nin which direction the company was going from the point of view of innovation. \nIn which areas it is investing more and in which areas it should invest. With an analysis of patent abstracts and network theory.\n" }, { "alpha_fraction": 0.6163234114646912, "alphanum_fraction": 0.6249682307243347, "avg_line_length": 28.571428298950195, "blob_id": "17e91f22d40ee8d9523842333e3fe8d92a64e728", "content_id": "162acbf125469b704498616c86553715c9bf62da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3936, "license_type": "no_license", "max_line_length": 233, "num_lines": 133, "path": "/paypal_testi.py", "repo_name": "fabiopuddu77/Paypal", "src_encoding": "UTF-8", "text": "import numpy as np\nimport PIL\nfrom PIL import Image\n#import pandas as pd\n\nimport nltk\n\n# import matplotlib\n# matplotlib.use('TkAgg')\n# from matplotlib import pyplot as plt\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords, CategorizedPlaintextCorpusReader\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.corpus import wordnet\nfrom wordcloud import WordCloud\n\n# doc1 = (\n# \"\"\"Era un oggetto troppo grande per chiamarlo spada. Troppo spesso, troppo pesante e grezzo.\n# Non era altro che un enorme blocco di ferro ferro ferro ferro ferro ferro ferro ferroferro ferro ferro ferro ferro ferro ferro ferroferro ferro ferro ferro ferro ferro ferro ferroferro ferro ferro ferro ferro ferro ferro ferro.\n# \"\"\"\n# )\n\n# max valore più grande nella lista, ogni valore è il conteggio di un token\n\n# class Document(object):\n#\n# def __init__(self, text):\n# self.text = text\n# self.tokens = self.tokenize()\n# self.max_freq = max([self.tokens.count(t) for t in self.tokens])\n#\n# def tokenize(self):\n# return [w.lower() for w in re.split(r'\\W+', self.text) if w]\n#\n# def tf(self, token):\n# return self.tokens.count(token) / self.max_freq\n\n#df = pd.read_csv(\"./Abstract/paypal_dv.csv\", error_bad_lines=False, sep=';')\n\n\nclass Document():\n\n def __init__(self, dir, doc):\n self.doc = doc\n self.dir = dir\n self.eng_stopw = stopwords.words('english')\n\n\n text_corpus = CategorizedPlaintextCorpusReader(\n './%s/' % self.dir,\n r'.*\\.csv', # leggo solamente i file che terminato con .csv\n cat_pattern=r'(\\w+)/*', # prendi tutto quello che c'è dopo la directory\n encoding='latin-1'\n )\n\n self.text = nltk.Text(text_corpus.words(self.doc))\n\n def freq_dist(self):\n return nltk.FreqDist([w for w in self.text if len(w) >= 4 and w not in self.eng_stopw])\n\n def parole(self):\n return [(i) for i in self.freq_dist().most_common(500)]\n\n def tokenize(self):\n return ([w for w in self.text if len(w) >= 4 and w not in self.eng_stopw])\n\n def wordcloud(self,stopword,mask_k):\n\n list = (\" \").join(self.tokenize())\n wordcloud = WordCloud(max_font_size=50, max_words=100, background_color=\"white\",stopwords=stopword,\n collocations=False,\n repeat=False, contour_width=3, contour_color='firebrick',mask=mask_k).generate(list)\n plt.figure(figsize=[20,10])\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n return\n\n\n#\n# df = pd.read_excel(\"/Users/utente/PycharmProjects/WAAT-2020_new/Abstract/Abstract.xlsx\",skiprows=[0])\n# print(df)\n#\n# df['Abstract - DWPI Detailed Description']\n# testi = [testi for testi in df['Abstract']]\n# stop_words = set(stopwords.words('english'))\n#\n# tokens = [word_tokenize(text) for text in testi if type(text)==str ]\n#\n#\n# tokens_tot = [tokens.append(token) for lista in tokens for token in lista]\n#\n# tokens_tot\n\n# with open(\"./Abstract/Abstract.csv\", \"r\") as f:\n# read = f.readlines()\n\n\n\nif __name__ == \"__main__\":\n\n ###### WORDCLOUD ######\n # paypal_mask = np.array(Image.open(\"./Abstract/paypal.png\"))\n # def transform_format(val):\n # if val.any() == 0:\n # return 255\n # else:\n # return val\n #\n # transformed_pp_mask = np.ndarray((paypal_mask.shape[0], paypal_mask.shape[1]), np.int32)\n #\n # for i in range(len(paypal_mask)):\n # transformed_pp_mask = list(map(transform_format, paypal_mask[i]))\n\n\n #\n # stopword = set()\n # stopword.update([\"system\"])\n\n #file2 = Document(\"./Abstract\",\"pp_tit_dwpi.csv\")\n # print(\"WordCloud\",file2.wordcloud(stopword,paypal_mask))\n\n file3 = Document(\"\", \"pp_man_c.csv\")\n\n # print(file.wordcloud())\n print(file3.parole())\n\n\n\n\n\n\n #file_dv = Document(\"./Abstract\",\"paypal_dv.csv\")\n" } ]
9
sunuilhamp/RenameFiles-In-Folder
https://github.com/sunuilhamp/RenameFiles-In-Folder
643c083678ede861eacb3c5bd57c827ff5550ead
06becb230d362df89313c4d5240fe97a4737f02e
fdd47c690d168e0608a6ffe41718a1c8062284b4
refs/heads/master
2023-01-22T12:44:56.062971
2020-11-19T13:15:27
2020-11-19T13:15:27
287,044,279
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4211711585521698, "alphanum_fraction": 0.4211711585521698, "avg_line_length": 31.925926208496094, "blob_id": "28905104ef2699d31b9aada4a87fac610e29eadf", "content_id": "ae7a4a1b2e6b35c4b99543c60a31dd31abf4aa06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 888, "license_type": "permissive", "max_line_length": 70, "num_lines": 27, "path": "/changeName.py", "repo_name": "sunuilhamp/RenameFiles-In-Folder", "src_encoding": "UTF-8", "text": "import os \n\ndef main(): \n folders = [ 'aien', 'alif', 'ba', 'ta', 'dal', 'dhod', 'dzal',\n 'dzho', 'fa', 'ghoin', 'ha', 'ha\\'', 'hamzah', 'jiem',\n 'kaf', 'kho', 'lam', 'lamalief', 'miem', 'nun', 'qof',\n 'ro', 'shod', 'sien', 'syien', 'ta', 'tho', 'tsa', \n 'wawu', 'ya', 'zain']\n #folder = input(\"Masukkan nama folder sekaligus file: \")\n for folder in folders:\n for count, filename in enumerate(os.listdir(folder)): \n try:\n dst = folder + \"_\" + str(count) + \".jpg\"\n # dst = 'eka' + \"_\" + str(count) + \".jpg\"\n src = folder + '\\\\' + filename \n dst = folder + '\\\\' + dst\n\n os.rename(src, dst) \n except:\n print(\"File Sudah Ada\")\n\nif __name__ == '__main__': \n main() \n\n# Folder\n# --alif\n# -changeName.py" } ]
1
pije76/scportal
https://github.com/pije76/scportal
401e38d4dd9debb5bccd004362521cbfea0a3f4a
2c13c94504e07c673d333db4212c5c03ba80c20d
3c6562047fece137b66665eb78406944e6b0999a
refs/heads/master
2023-03-06T20:29:52.461816
2020-01-02T07:42:13
2020-01-02T07:42:13
227,796,927
1
0
null
2019-12-13T08:54:19
2019-12-13T09:03:35
2019-12-13T09:04:07
Python
[ { "alpha_fraction": 0.7127659320831299, "alphanum_fraction": 0.7234042286872864, "avg_line_length": 14.666666984558105, "blob_id": "55113f4248f5a1aff98968ef6bdb7b910bd6e283", "content_id": "6e635f1e768cda5007dbcef1495cd25de39acc0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 94, "license_type": "no_license", "max_line_length": 37, "num_lines": 6, "path": "/gridagentserver/start.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd `dirname $0`\n\ntwistd -y agentserver.tac\nrm -f $HOME/gas-stopped-intentionally\n" }, { "alpha_fraction": 0.6775583624839783, "alphanum_fraction": 0.6779174208641052, "avg_line_length": 37.68055725097656, "blob_id": "c700248e9146be7cb9d79dca4929159a8dfb9218", "content_id": "e4c9e7acfcee4fc18b5a2544911b9a9ca5c5e7f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2785, "license_type": "no_license", "max_line_length": 74, "num_lines": 72, "path": "/legacy/manage_measurementpoints/forms/imported.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport pytz\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.proxies import ImportedMeasurementPoint\nfrom gridplatform.utils import units\nfrom gridplatform.utils import utilitytypes\n\nfrom .consumption import ConsumptionMeasurementPointForm\n\n\nclass ImportedMeasurementPointForm(ConsumptionMeasurementPointForm):\n upload_file = forms.FileField(required=True)\n consumption_column = forms.IntegerField()\n timezone = forms.TypedChoiceField(\n choices=[(x, x) for x in pytz.common_timezones],\n coerce=pytz.timezone)\n unit = forms.ChoiceField()\n\n class Meta:\n model = ImportedMeasurementPoint\n fields = ('name', 'parent', 'billing_meter_number',\n 'billing_installation_number', 'relay',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n class ProxyMeta(ConsumptionMeasurementPointForm.ProxyMeta):\n fields = ConsumptionMeasurementPointForm.ProxyMeta.fields + \\\n ('upload_file', 'consumption_column', 'timezone', 'unit')\n\n def __init__(self, *args, **kwargs):\n super(ImportedMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n utility_type = self.instance.utility_type\n\n if utility_type == utilitytypes.METER_CHOICES.electricity:\n self.fields['unit'].choices = units.WATT_HOUR_ENERGY_CHOICES\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n self.fields['unit'].choices = units.ENERGY_CHOICES\n elif utility_type in [utilitytypes.METER_CHOICES.gas,\n utilitytypes.METER_CHOICES.water,\n utilitytypes.METER_CHOICES.oil]:\n self.fields['unit'].choices = units.VOLUME_CHOICES\n else:\n raise ValueError('Unsupported utility type %r' % utility_type)\n\n def _get_new_electricity_headline_display(self):\n return _(u'New Imported Electricity Measurement Point')\n\n def _get_new_heat_headline_display(self):\n return _(u'New Imported Heat Measurement Point')\n\n def _get_new_water_headline_display(self):\n return _(u'New Imported Water Measurement Point')\n\n def _get_new_gas_headline_display(self):\n return _(u'New Imported Gas Measurement Point')\n\n def _get_new_oil_headline_display(self):\n return _(u'New Imported Oil Measurement Point')\n\n\nclass ImportedMeasurementPointUpdateForm(ConsumptionMeasurementPointForm):\n def _get_new_electricity_headline_display(self):\n return _(u'Edit Imported Electricity Measurement Point')\n" }, { "alpha_fraction": 0.5876923203468323, "alphanum_fraction": 0.5984615087509155, "avg_line_length": 31.5, "blob_id": "ba913ad5bf8a00aaebc352a077d24e17373746e1", "content_id": "e97d4c75c5e197075ed1dbd4c13ebb92e030cd4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 650, "license_type": "no_license", "max_line_length": 70, "num_lines": 20, "path": "/legacy/display_indexes/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'legacy.display_indexes.views',\n url('^$', 'index',\n name='display_indexes-index'),\n url('^(?P<pk>\\d+)/', 'detail',\n name='display_indexes-detail'),\n url('^graph/(?P<pk>\\d+)/', 'graph',\n name='display_indexes-graph'),\n url('^async_graph/(?P<pk>\\d+)/$', 'async_graph',\n name='display_indexes-async_graph'),\n url('^async_graph_last_24h/(?P<pk>\\d+)/$', 'async_graph_last_24h',\n name='display_indexes-async_graph_last_24h'),\n)\n" }, { "alpha_fraction": 0.6590389013290405, "alphanum_fraction": 0.6608695387840271, "avg_line_length": 36.67241287231445, "blob_id": "449a6b5a3eb5a492ed1e9fcdad7fef0858f686f4", "content_id": "4213cf1b12c2ed019b5a30aca630ba1bfce2ccd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2185, "license_type": "no_license", "max_line_length": 79, "num_lines": 58, "path": "/legacy/measurementpoints/models/multiplication.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils import condense\n\nfrom .dataseries import DataSeries\n\n\nclass Multiplication(DataSeries):\n \"\"\"\n A C{Multiplication} is a data series, where the data samples are defined in\n terms of a C{source_data_series} multiplied with a C{multiplier}.\n \"\"\"\n multiplier = models.DecimalField(decimal_places=3, max_digits=10)\n source_data_series = models.ForeignKey(\n DataSeries, on_delete=models.PROTECT,\n related_name='multiplied_data_series_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('mulitplication')\n verbose_name_plural = _('multiplications')\n app_label = 'measurementpoints'\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{Multiplication} implementation of\n L{DataSeries.get_raw_data_samples()}.\n \"\"\"\n for sample in self.source_data_series.subclass_instance.\\\n get_samples(from_timestamp, to_timestamp):\n yield sample._replace(\n physical_quantity=(sample.physical_quantity * self.multiplier))\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n for sample in self.source_data_series.subclass_instance.\\\n get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp):\n yield sample._replace(\n physical_quantity=(sample.physical_quantity * self.multiplier))\n\n def depends_on(self):\n \"\"\"\n C{Multiplication} implementation of L{DataSeries.depends_on()}.\n \"\"\"\n result = list(self.source_data_series.subclass_instance.depends_on())\n result.append(self.source_data_series.subclass_instance)\n return result\n\n def get_recursive_condense_resolution(self, resolution):\n if condense.is_finer_resolution(resolution, condense.HOURS):\n return None\n else:\n return condense.next_resolution(resolution)\n" }, { "alpha_fraction": 0.6464890837669373, "alphanum_fraction": 0.658595621585846, "avg_line_length": 33.41666793823242, "blob_id": "afd2522584afdefddb1f76a0360f87d95ac80a85", "content_id": "1f1fc2ba1f2a4ab8bfcca7d77212526c70aef730", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2891, "license_type": "no_license", "max_line_length": 95, "num_lines": 84, "path": "/gridplatform/bootstrap/static/qunit/bootstrap/ui.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "test('Test ui is an object', function () {\n equal(typeof(ui), \"object\");\n});\n\ntest('Test ui.parseNumber', function () {\n thousandSeparator = get_format('THOUSAND_SEPARATOR'),\n decimalSeparator = get_format('DECIMAL_SEPARATOR');\n unit = ui.parseNumber(\"10\" + thousandSeparator + \"000\" + decimalSeparator + \"42\");\n equal(unit, 10000.42);\n});\n\ntest('Test ui.formatNumber', function () {\n thousandSeparator = get_format('THOUSAND_SEPARATOR'),\n decimalSeparator = get_format('DECIMAL_SEPARATOR');\n unit = ui.formatNumber(10000.421337, 2);\n equal(unit, \"10\" + thousandSeparator + \"000\" + decimalSeparator + \"42\");\n});\n\ntest('Test ui.getQueryStrings', function () {\n unit = ui.getQuerystrings('test.html?because=internet&get=beer');\n equal('internet', unit['because']);\n equal('beer', unit['get']);\n});\n\ntest('Test ui.updateLocationHash with empty hash', function () {\n window.location.hash = \"\";\n\n\tui.updateLocationHash({something: 'test'});\n unit = JSON.parse(decodeURIComponent(window.location.hash.replace(/^#/, '')));\n equal('test', unit['something']);\n window.location.hash = \"\";\n});\n\ntest('Test ui.updateLocationHash no override', function () {\n window.location.hash = encodeURIComponent(JSON.stringify({testing: 'beer'}));\n\n\tui.updateLocationHash({something: 'test'});\n unit = JSON.parse(decodeURIComponent(window.location.hash.replace(/^#/, '')));\n equal('test', unit['something']);\n equal('beer', unit['testing']);\n window.location.hash = \"\";\n\n});\n\ntest('Test ui.updateLocationHash override', function () {\n window.location.hash = encodeURIComponent(JSON.stringify({testing: 'beer'}));\n\n\tui.updateLocationHash({something: 'test'}, true);\n unit = JSON.parse(decodeURIComponent(window.location.hash.replace(/^#/, '')));\n equal('test', unit['something']);\n equal(undefined, unit['testing']);\n window.location.hash = \"\";\n\n});\n\ntest('Test ui.getHashValueFromKey', function () {\n ui.updateLocationHash({something: 'test'}, true);\n unit = ui.getHashValueFromKey('something');\n equal('test', unit);\n window.location.hash = \"\";\n});\n\ntest('Test ui.generateStringHash generates same hash for qual strings', function () {\n equal(ui.generateStringHash('string'), ui.generateStringHash('string'));\n});\n\ntest('Test ui.generateStringHash generates different hash for different strings', function () {\n notEqual(ui.generateStringHash('string1'), ui.generateStringHash('string2'));\n});\n\ntest('Test ui.icon no size no spin', function () {\n unit = ui.icon('times');\n equal('<i class=\"fa fa-times\"></i>', unit);\n});\n\ntest('Test ui.icon with size', function () {\n unit = ui.icon('times', 'xl');\n equal('<i class=\"fa fa-times fa-xl\"></i>', unit);\n});\n\ntest('Test ui.icon with spin', function () {\n unit = ui.icon('times', undefined, true);\n equal('<i class=\"fa fa-times fa-spin\"></i>', unit);\n});\n" }, { "alpha_fraction": 0.7086743116378784, "alphanum_fraction": 0.7152209281921387, "avg_line_length": 31.157894134521484, "blob_id": "b86cdaa60cf1aa91c53fe4815f7b939dbbea017f", "content_id": "e8604afc85e2928dca430d5e5f11919bba8b774b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "no_license", "max_line_length": 55, "num_lines": 19, "path": "/gridplatform/rest/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db.models.deletion import ProtectedError\nfrom rest_framework.views import exception_handler\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\ndef gridplatform_rest_api_exception_handler(exception):\n response = exception_handler(exception)\n\n if response is None:\n if isinstance(exception, ProtectedError):\n return Response(\n {'detail': unicode(exception)},\n status=status.HTTP_409_CONFLICT)\n\n return response\n" }, { "alpha_fraction": 0.5963214039802551, "alphanum_fraction": 0.6118102669715881, "avg_line_length": 27.69444465637207, "blob_id": "7a470cd9064e273f9321b7955057e02780be5413", "content_id": "2b5c91df590c1519692b585e4b52bacb7fd34f81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 70, "num_lines": 36, "path": "/legacy/indexes/models/period.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\ndef normalize_periods(periods):\n \"\"\"\n Normalize periods.\n\n @param periods: A list of 2-tuples [(t0, t1),...], where t0 and t1\n are datetime objects, defining nonoverlapping, but possibly\n adjacent periods (t0 marking the start of the period and t1\n marking the end of the period).\n\n @return: Returns a sorted list of periods [p1, p2,...], where\n no p_i and p_i+1 are adjacent.\n \"\"\"\n if periods == []:\n return\n\n sorted_periods = sorted(periods)\n new_start = sorted_periods[0][0]\n new_stop = sorted_periods[0][1]\n for old_start, old_stop in sorted_periods[1:]:\n assert old_start <= old_stop\n assert new_start <= new_stop\n assert new_stop <= old_start\n\n if new_stop < old_start:\n # periods are not adjacent\n yield (new_start, new_stop)\n new_start = old_start\n\n new_stop = old_stop\n\n yield (new_start, new_stop)\n" }, { "alpha_fraction": 0.579857587814331, "alphanum_fraction": 0.5820193290710449, "avg_line_length": 28.675472259521484, "blob_id": "8ab09a5e0847bdc5633fb2b75f13453e8906f8b1", "content_id": "94fcccfcd37542ea553d44d3a4abe63a303cf5b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7864, "license_type": "no_license", "max_line_length": 77, "num_lines": 265, "path": "/legacy/manage_locations/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.forms import ModelForm\nfrom django.http import HttpResponseForbidden\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.html import escape\n\nfrom gridplatform.utils.views import (\n render_to,\n json_response,\n json_list_options,\n)\nfrom legacy.measurementpoints.models import Location\nfrom gridplatform.users.decorators import (\n auth_or_error,\n customer_admin_or_error,\n)\nfrom legacy.devices.models import Agent, Meter\n\n\ndef can_delete(request, location):\n agents = location.agent_set.all()\n meters = location.meter_set.all()\n locations = location.children.all()\n dependents = []\n if agents:\n dependents.append(_(\"Agents:\"))\n dependents.append('<ul>')\n for agent in agents:\n dependents.append('<li>%s</li>' % (escape(unicode(agent)),))\n dependents.append('</ul>')\n if meters:\n dependents.append(_(\"Meters:\"))\n dependents.append('<ul>')\n for meter in meters:\n dependents.append('<li>%s</li>' % (escape(unicode(meter)),))\n dependents.append('</ul>')\n if locations:\n dependents.append(_(\"Locations:\"))\n dependents.append('<ul>')\n for location in locations:\n dependents.append('<li>%s</li>' % (escape(unicode(location)),))\n dependents.append('</ul>')\n if dependents:\n # @bug: Use ngettext for plural forms.\n reason = _(\"This location cannot be deleted because the following \"\n \"depends on it:\") + \"<br />\" + \"\".join(dependents)\n else:\n reason = \"\"\n return {\n 'reason': reason\n }\n\n\n@customer_admin_or_error\n@json_response\ndef location_delete(request):\n instance = get_object_or_404(Location, pk=request.GET['pk'])\n instance.delete()\n return {\n 'success': True,\n 'statusText': _('The location has been deleted'),\n }\n\n\n@auth_or_error\n@json_response\ndef location_list_json(request):\n options = json_list_options(request)\n customer = request.customer\n if options['search']:\n data = list(Location.objects.filter(customer=customer))\n else:\n data = list(Location.objects.filter(customer=customer, level=0))\n\n if options['search']:\n data = filter(\n lambda location:\n location.satisfies_search(options['search']), data)\n\n data.sort(key=lambda location: location.name_plain.lower())\n\n if options['search']:\n rendered = [\n render_to_string(\n 'manage_locations/location_normal_block.html',\n {'location': location},\n RequestContext(request))\n for location in data\n ]\n else:\n rendered = [\n render_to_string(\n 'manage_locations/location_block.html',\n {'locations': location.get_descendants(include_self=True)},\n RequestContext(request))\n for location in data\n ]\n\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass LocationForm(ModelForm):\n class Meta:\n model = Location\n fields = ('name', 'parent',)\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(LocationForm, self).__init__(*args, **kwargs)\n if self.instance.id:\n children = [descendant.id for descendant\n in self.instance.get_descendants(include_self=True)]\n else:\n children = []\n\n self.fields['parent'].queryset = \\\n Location.objects.all().exclude(pk__in=children)\n\n\n@customer_admin_or_error\n@render_to('manage_locations/location_form.html')\ndef location_form(request, pk=None):\n customer = request.customer\n if pk:\n instance = get_object_or_404(Location, pk=pk)\n if instance.customer != customer:\n return HttpResponseForbidden()\n delete = can_delete(request, instance)\n else:\n instance = None\n delete = False\n\n form = LocationForm(instance=instance, auto_id=False)\n\n return {\n 'form': form,\n 'object': instance,\n 'location': instance,\n 'delete': delete,\n }\n\n\n# parent = 0 means no change in parent.\n# parent > 0 is the id of the parent\n# parent = None means no parent\n@customer_admin_or_error\n@json_response\ndef location_update(request, pk=None):\n if pk:\n instance = get_object_or_404(Location, pk=pk)\n old_parent = instance.parent\n else:\n instance = None\n old_parent = None\n\n form = LocationForm(request.POST, instance=instance, auto_id=False)\n if form.is_valid():\n location = form.save()\n\n if old_parent == location.parent:\n parent = 0\n else:\n if location.parent is not None:\n parent = location.parent.id\n else:\n parent = None\n\n return {\n 'success': True,\n 'statusText': _('The location has been saved'),\n 'html': render_to_string(\n 'manage_locations/location_normal_block.html',\n {'location': location},\n RequestContext(request)\n ),\n 'parent': parent,\n }\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_locations/location_form.html',\n {\n 'form': form,\n 'object': instance,\n 'agent': instance,\n },\n RequestContext(request)\n ),\n }\n\n\n@auth_or_error\n@json_response\ndef agent_list_json(request, location):\n options = json_list_options(request)\n data = list(Agent.objects.filter(location=location).select_related(\n 'location'))\n\n if options['search']:\n data = filter(\n lambda agent: agent.satisfies_search(options['search']), data)\n order_map = {\n 'location': lambda agent: unicode(agent.location),\n 'mac': lambda agent: unicode(agent.mac),\n }\n if options['order_by'] and options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_devices/agent_block.html',\n {'agent': agent},\n RequestContext(request))\n for agent in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\n@auth_or_error\n@json_response\ndef meter_list_json(request, location):\n options = json_list_options(request)\n data = list(Meter.objects.filter(location=location).select_related(\n 'agent', 'location'))\n\n if options['search']:\n data = filter(\n lambda meter: meter.satisfies_search(options['search']), data)\n order_map = {\n 'name': lambda meter: meter.name_plain.lower(),\n 'location': lambda meter: unicode(meter.location),\n 'agent': lambda meter: unicode(meter.agent),\n }\n if options['order_by'] and options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_devices/meter_block.html',\n {'meter': meter},\n RequestContext(request))\n for meter in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n" }, { "alpha_fraction": 0.6312848925590515, "alphanum_fraction": 0.6312848925590515, "avg_line_length": 27.870967864990234, "blob_id": "7c62c1eddc3fb730e9943b2f3e45e8d971645d5e", "content_id": "2a74630fb6b7682662daade3921b3c6de88bcdd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "no_license", "max_line_length": 76, "num_lines": 31, "path": "/gridagentserver/all_messages.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport pika\n\n\nmqhost = 'localhost'\n\n\ndef callback(ch, method, properties, body):\n print '%s: %s' % (method.routing_key, body)\n\n\ndef all_agent_messages():\n connection = pika.BlockingConnection(pika.ConnectionParameters(\n host=mqhost))\n channel = connection.channel()\n channel.exchange_declare(exchange='agentservers', exchange_type='topic')\n result = channel.queue_declare(exclusive=True)\n queue_name = result.method.queue\n channel.queue_bind(exchange='agentservers',\n queue=queue_name,\n routing_key='agentserver')\n channel.queue_bind(exchange='agentservers',\n queue=queue_name,\n routing_key='agent.*')\n channel.basic_consume(callback, queue=queue_name, no_ack=True)\n channel.start_consuming()\n\n\nif __name__ == '__main__':\n all_agent_messages()\n" }, { "alpha_fraction": 0.5995279550552368, "alphanum_fraction": 0.6042486429214478, "avg_line_length": 30, "blob_id": "212b1ee8b939686ea0b1af4f1f8ac6edcf6a927a", "content_id": "635f60c6b74a51e05f8606cbb63c1038f0e5b15a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1271, "license_type": "no_license", "max_line_length": 74, "num_lines": 41, "path": "/legacy/rules/management/commands/send_rules.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport pytz\n\nfrom django.core.management.base import BaseCommand\n\nfrom legacy.rules import engine\nfrom legacy.rules.util import send_agent_rules\nfrom legacy.rules.models import UserRule, AgentRule\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\n\n\nclass Command(BaseCommand):\n args = \"\"\n help = \"Send Agent rules to AgentServer\"\n\n def handle(self, *args, **kwargs):\n now = datetime.datetime.now(pytz.utc)\n hour = now.replace(minute=0, second=0, microsecond=0)\n\n tainted = engine.get_tainted_meter_ids()\n\n agent_rules = []\n\n for user_rule in UserRule.objects.filter(enabled=True).exclude(\n relayaction__meter__in=tainted).distinct().select_related(\n 'relayaction'):\n try:\n agent_rules.extend([\n rule for rule\n in user_rule.generate_rules(\n hour - RelativeTimeDelta(days=1),\n days=7)\n if isinstance(rule, AgentRule)\n ])\n except Exception as e:\n print e\n send_agent_rules(agent_rules)\n" }, { "alpha_fraction": 0.5728932023048401, "alphanum_fraction": 0.5758939981460571, "avg_line_length": 32.32500076293945, "blob_id": "12a833bb88fea2531fdb7ab969d60c05f34d22af", "content_id": "197841d9142e5e6ee76f9bbdd75098eb5a7b48e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3999, "license_type": "no_license", "max_line_length": 204, "num_lines": 120, "path": "/legacy/manage_indexes/templates/manage_indexes/form_base.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% load i18n %}\n{% load l10n %}\n{% load widget_tweaks %}\n{% load staticfiles %}\n\n{% block page_js %}\n<script type=\"text/javascript\">\n jQuery(function() {\n // Clicking the .populate_default_values button should populate\n // the .value_at_hour input fields of the same period with the value\n // kept in the .default_value_at_hour field.\n $('.populate_default_values').click(function() {\n var li = $(this).closest('li'),\n\t default_value = li.find('.default_value_at_hour').val();\n\n li.find('.value_at_hour input').each(function() {\n var value_at_hour_input = $(this);\n if (value_at_hour_input.val() === '') {\n\t\t value_at_hour_input.val(default_value);\n }\n });\n });\n\n // Clicking the .clear_values button should clear all\n // .editable_input inputs for the same period.\n $('.clear_values').click(function() {\n $(this).closest('li').find('.editable_input input').val('');\n });\n {% if messages %}\n {% for message in messages %}\n gridportal.website.notify('{{ message.tag }}', '{{ message }}');\n {% endfor %}\n {% endif %}\n\n $('.date:not(.empty-form .date)').datepicker();\n $('input[name=delete]').each(function () {\n var btn = $(this);\n btn.tooltip({\n content: btn.data('reason')\n });\n });\n $('input[name=delete]').click(function (event) {\n event.preventDefault();\n event.stopPropagation();\n gridportal.website.synchroneousDelete(\n \"{% url 'manage_indexes-delete' %}\",\n \"{{ form.instance.id|unlocalize }}\",\n \"{% url 'manage_indexes-listing' %}\");\n });\n\n $('select:not(.empty-form select)').chosen({enable_split_word_search: true});\n $('button.add-form').click(function (event) {\n event.preventDefault();\n var parent = $(this).closest('div'),\n emptyForm = parent.find('.empty-form'),\n newForm = emptyForm.clone(),\n totalForms = parent.find('input[name$=\"TOTAL_FORMS\"]'),\n newId = totalForms.val();\n newForm.find('div, input, select, li').each(function () {\n var input = $(this);\n if (input.attr(\"name\")) {\n newPrefix = input.attr('name').replace('__prefix__', newId);\n input.attr('name', newPrefix);\n }\n if (input.attr(\"id\")) {\n newPrefix = input.attr('id').replace('__prefix__', newId);\n input.attr('id', newPrefix);\n }\n });\n newForm.find('.date').datepicker();\n newForm.removeClass('empty-form').show();\n totalForms.val(parseInt(totalForms.val(), 10) + 1);\n newForm.insertBefore(emptyForm);\n newForm.find('select').chosen({enable_split_word_search: true});\n });\n });\n</script>\n{% endblock %}\n\n{% block page_id %}indexsettings-page{% endblock %}\n\n{% block title %}\n{% trans \"Settings: Indexes\" %}\n{% endblock title %}\n\n{% block content_heading %}\n{% trans \"Settings: Indexes\" %}\n{% endblock content_heading%}\n\n{% block left_content %}\n<div id=\"index\" class=\"content-element\">\n <div class=\"header clearfix\">\n <h2>{{ view.headline }}</h2>\n </div>\n <form method=\"POST\">\n {% csrf_token %}\n <input type=\"hidden\" name=\"item_id\" value=\"{{ form.instance.id|unlocalize }}\">\n {% block fields %}\n {% endblock fields %}\n\n {% with inlines.0 as formset %}\n <h6> {% trans \"Periods\" %} </h6>\n {% block formset %}\n {% endblock formset %}\n {{ form.non_field_errors }}\n {{ formset.non_form_errors }}\n {% endwith %}\n\n <div class=\"clearfix\"></div>\n <button class=\"add-form btn\">Add another</button>\n <div class=\"clearfix\"></div>\n {{ form.non_field_errors }}\n <input type=\"submit\" value=\"{% trans \"Save and return to list\" %}\" />\n {% if form.instance.id %}\n <input type=\"button\" name=\"delete\" {% if form.instance.get_delete_prevention_reason %} data-reason=\"{{ form.instance.get_delete_prevention_reason }}\" {% endif %} title=\"\" value=\"{% trans 'Delete' %}\">\n {% endif %}\n </form>\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.6565554141998291, "alphanum_fraction": 0.6592517495155334, "avg_line_length": 34.746986389160156, "blob_id": "0424eb3cc48221f95963f4dec8047723dfa48f73", "content_id": "d92866b6f0042357305ae22feb5eb6e3c9b22f8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2967, "license_type": "no_license", "max_line_length": 85, "num_lines": 83, "path": "/gridplatform/energyperformances/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import link\nfrom rest_framework.response import Response\nimport rest_framework.reverse\n\nfrom . import models\nfrom . import serializers\n\n\ndef _parse_date(date_string):\n return datetime.datetime.strptime(date_string, '%Y-%m-%d').date()\n\ndef _compute(model, request, pk=None, format=None):\n performance = get_object_or_404(model, pk=pk)\n tz = performance.customer.timezone\n day = datetime.timedelta(days=1)\n try:\n from_date = _parse_date(request.GET['from_date'])\n to_date = _parse_date(request.GET['to_date'])\n except (KeyError, ValueError):\n from_date = datetime.datetime.now(tz=tz).date()\n to_date = from_date\n from_timestamp = tz.localize(\n datetime.datetime.combine(from_date, datetime.time()))\n to_timestamp = tz.localize(\n datetime.datetime.combine(\n to_date + day, datetime.time()))\n result = performance.compute_performance(from_timestamp, to_timestamp)\n if result is not None:\n num = float(performance.unit_converter.extract_value(result))\n else:\n num = None\n delta = to_date - from_date\n previous_period_end = from_date - day\n previous_period_start = previous_period_end - delta\n next_period_start = to_date + day\n next_period_end = next_period_start + delta\n return Response({\n 'previous': '%s?from_date=%s&to_date=%s' % (\n rest_framework.reverse.reverse(\n 'api:energyperformances:productionenergyperformance-compute', # noqa\n args=[pk], request=request),\n previous_period_start,\n previous_period_end),\n 'next': '%s?from_date=%s&to_date=%s' % (\n rest_framework.reverse.reverse(\n 'api:energyperformances:productionenergyperformance-compute', # noqa\n args=[pk], request=request),\n next_period_start,\n next_period_end),\n 'from_date': from_date,\n 'to_date': to_date,\n 'unit': performance.unit,\n 'display_unit': performance.unit_converter.get_display_unit(),\n 'value': num,\n })\n\n\nclass ProductionEnergyPerformance(viewsets.ModelViewSet):\n model = models.ProductionEnergyPerformance\n serializer_class = serializers.ProductionEnergyPerformance\n filter_fields = ('name', 'customer')\n\n @link()\n def compute(self, request, pk=None, format=None):\n return _compute(self.model, request, pk, format)\n\n\nclass TimeEnergyPerformance(viewsets.ModelViewSet):\n model = models.TimeEnergyPerformance\n serializer_class = serializers.TimeEnergyPerformance\n filter_fields = ('name', 'customer')\n\n @link()\n def compute(self, request, pk=None, format=None):\n return _compute(self.model, request, pk, format)\n" }, { "alpha_fraction": 0.848024308681488, "alphanum_fraction": 0.848024308681488, "avg_line_length": 31.899999618530273, "blob_id": "e1a2fb03bc7febb5ed7a9a9d79c324ddae28496e", "content_id": "ae3b15ee17dbe819cfed558b4f05adfd0310399c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/energymanager/price_relay_site/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework import viewsets\n\nfrom energymanager.price_relay_site import serializers\nfrom .models import PriceRelayProject\n\n\nclass RelaySettingsViewSet(viewsets.ReadOnlyModelViewSet):\n model = PriceRelayProject\n serializer_class = serializers.PriceRelayProjectSerializer\n" }, { "alpha_fraction": 0.6421787738800049, "alphanum_fraction": 0.6466480493545532, "avg_line_length": 38.340660095214844, "blob_id": "c17df83189657e3c2f158e5ba1cead34475103f3", "content_id": "d17b611a5df0343b51a48ee3c5f7b8cf3eecbe14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3580, "license_type": "no_license", "max_line_length": 79, "num_lines": 91, "path": "/legacy/nordpool/legacy.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport itertools\n\nfrom isoweek import Week\n\nfrom legacy.indexes.models import SpotMapping\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\n\nfrom . import ftpclient\nfrom . import parser\n\n\ndef update_entries(from_date, to_date, index, preliminary, final, timezone):\n entry_qs = index.entry_set.filter(\n from_timestamp__gte=from_date,\n from_timestamp__lt=to_date)\n existing_entries = {entry.from_timestamp: entry for entry in entry_qs}\n final_dates = set([date for date, hourly in final])\n preliminary_entries = []\n for date, hourly in preliminary:\n if date not in final_dates:\n preliminary_entries.extend(\n parser.day_entries(date, hourly, timezone))\n final_entries = []\n for date, hourly in final:\n final_entries.extend(parser.day_entries(date, hourly, timezone))\n for from_timestamp, to_timestamp, value in itertools.chain(\n preliminary_entries, final_entries):\n if value is None:\n # As of October 19th 2014 Nordpool started to document the prices\n # using 25 hours for each day, to (in their opinion) better support\n # the one day every year where 03:00 is two hours long. They could\n # of course just have documented hourly prices with UTC timestamps\n # and thus have completely avoided the daylight savings issues!\n # Nordpool news about the format change:\n # http://www.nordpoolspot.com/TAS/Power-Data-Services/PDS-news/\n continue\n if from_timestamp in existing_entries:\n entry = existing_entries[from_timestamp]\n assert entry.from_timestamp == from_timestamp\n assert entry.to_timestamp == to_timestamp\n if entry.value != value:\n entry.value = value\n entry.save()\n else:\n index.entry_set.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=value)\n\n\ndef import_week(data):\n year, week, _day, _hour, _total_hours, _clock, _date = data['ST'][0]\n year = int(year)\n week = int(week)\n naive_week_start = datetime.datetime.combine(\n Week(year, week).monday(), datetime.time())\n naive_week_end = datetime.datetime.combine(\n naive_week_start + datetime.timedelta(days=7), datetime.time())\n for mapping in SpotMapping.objects.all().select_related('index'):\n tz = mapping.timezone\n week_start = tz.localize(naive_week_start)\n week_end = tz.localize(naive_week_end)\n preliminary, final = parser.extract_prices(\n data, mapping.area, mapping.currency)\n update_entries(week_start, week_end, mapping.index,\n preliminary, final, mapping.timezone)\n\n\ndef fetch_import_week(year, week):\n lines = ftpclient.fetch_spot(year, week)\n data = parser.parse_lines(lines)\n import_week(data)\n\n\ndef prices_today():\n prices_exists = []\n for mapping in SpotMapping.objects.all().select_related('index'):\n today = condense.floor(\n datetime.datetime.now(mapping.timezone),\n condense.DAYS,\n mapping.timezone)\n tomorrow = today + RelativeTimeDelta(days=1)\n prices_exists.append(mapping.index.entry_set.filter(\n from_timestamp__gt=today, to_timestamp__lt=tomorrow).exists())\n return all(prices_exists)\n" }, { "alpha_fraction": 0.7449361085891724, "alphanum_fraction": 0.7450230121612549, "avg_line_length": 38.94097137451172, "blob_id": "2b13a7d5675cd6b38c07f8bfbd81f89e9e0dd6a0", "content_id": "eeb0f3a4dc2edd32d12fe0590ba5107b004170fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11503, "license_type": "no_license", "max_line_length": 90, "num_lines": 288, "path": "/gridplatform/api.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import OrderedDict\n\nimport rest_framework.viewsets\nimport rest_framework.reverse\n\nimport gridplatform.rest.routers\nimport gridplatform.consumptions.viewsets\nimport gridplatform.cost_compensations.viewsets\nimport gridplatform.customer_datasources.viewsets\nimport gridplatform.customers.viewsets\nimport gridplatform.datasequences.viewsets\nimport gridplatform.energyperformances.viewsets\nimport gridplatform.energyperformances.views\nimport gridplatform.global_datasources.viewsets\nimport gridplatform.productions.viewsets\nimport gridplatform.provider_datasources.viewsets\nimport gridplatform.tariffs.viewsets\nimport energymanager.price_relay_site.viewsets\n\n\nclass EnergyPerformances(rest_framework.viewsets.ViewSet):\n _ignore_model_permissions = True\n\n def list(self, request, format=None):\n return rest_framework.response.Response(OrderedDict(sorted([\n ('production_energyperformances', rest_framework.reverse.reverse(\n 'api:energyperformances:productionenergyperformance-list',\n request=request, format=format)),\n ('time_energyperformances', rest_framework.reverse.reverse(\n 'api:energyperformances:timeenergyperformance-list',\n request=request, format=format)),\n ])))\n\n\nclass DataSequences(rest_framework.viewsets.ViewSet):\n _ignore_model_permissions = True\n\n def list(self, request, format=None):\n return rest_framework.response.Response(OrderedDict(sorted([\n ('main_consumptions', rest_framework.reverse.reverse(\n 'api:consumptions:mainconsumption-list',\n request=request, format=format)),\n ('consumption_groups', rest_framework.reverse.reverse(\n 'api:consumptions:consumptiongroup-list',\n request=request, format=format)),\n ('consumption_datasequences', rest_framework.reverse.reverse(\n 'api:consumptions:consumption-list',\n request=request, format=format)),\n ('production_groups', rest_framework.reverse.reverse(\n 'api:productions:productiongroup-list',\n request=request, format=format)),\n ('production_datasequences', rest_framework.reverse.reverse(\n 'api:productions:production-list',\n request=request, format=format)),\n ('energy_per_volume_datasequences', rest_framework.reverse.reverse(\n 'api:datasequences:energypervolumedatasequence-list',\n request=request, format=format)),\n ('nonaccumulation_datasequences', rest_framework.reverse.reverse(\n 'api:datasequences:nonaccumulationdatasequence-list',\n request=request, format=format)),\n ('energy_tariff_datasequences', rest_framework.reverse.reverse(\n 'api:tariffs:energytariff-list',\n request=request, format=format)),\n ('volume_tariff_datasequences', rest_framework.reverse.reverse(\n 'api:tariffs:volumetariff-list',\n request=request, format=format)),\n ('cost_compensation_datasequences', rest_framework.reverse.reverse(\n 'api:cost_compensations:costcompensation-list',\n request=request, format=format)),\n ])))\n\n\nclass DataSources(rest_framework.viewsets.ViewSet):\n _ignore_model_permissions = True\n\n def list(self, request, format=None):\n return rest_framework.response.Response(OrderedDict(sorted([\n ('global_datasources', rest_framework.reverse.reverse(\n 'api:global_datasources:globaldatasource-list',\n request=request, format=format)),\n ('provider_datasources', rest_framework.reverse.reverse(\n 'api:provider_datasources:providerdatasource-list',\n request=request, format=format)),\n ('customer_datasources', rest_framework.reverse.reverse(\n 'api:customer_datasources:customerdatasource-list',\n request=request, format=format)),\n ])))\n\n\nroot_routes = gridplatform.rest.routers.DefaultRouter()\nroot_routes.description = \"\"\"\n# Welcome to the GridPlatform API.\n\nThe URL\n[https://portal.grid-manager.com/api/current](https://portal.grid-manager.com/api/current)\nwill always redirect to the current version of the API.\n\nAuthentication is either done by logging in with username and password, which\nis practical when navigating the browsable API to familiarise oneself with the\navailable resources, or it can be done using an authentication token, which is\nthe normal way of accessing the API programmatically.\n\nTo get an authentication token you must contact your GridPlatform access\nprovider and make then issue you a suitable one.\n\nThe token must be part of the header of every HTTP request. The HTTP headers\nshould be extended with the following line:\n\n Authorization: token <token>\n\nwhere <token> is the API authentication token. A token is just a text string\nand might look something like this:\n\n 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b\n\n\n## Filter Fields\n* GET list resource data has a property called `filterFields` containing\n a list of field names. Each name is this list can be used a querystring\n parameter for filtering the list results on equality for the that fields\n value.\n* OPTIONS for a list resource shows all the possible actions for that\n resource, and more. One of the properties for each field is `filterField`.\n It is either `null` (i.e. the field is not a filter field) or contains the\n query string parameter name corresponding to that field. The query string\n parameter can be used for filtering the list, checking for equality on that\n field.\n\n## Bulk Actions\n* OPTIONS for list a resource may contain a `bulkActions` property containing a\n list of HTTP actions that support bulk operation. Currently only bulk\n creation (POST) is supported, and that is only on the various data source\n `rawData` list resources. To perform a `rawData` bulk creation simply POST an\n array of `rawData` objects to the relevant `rawData` list resource.\n\n# API Root\n\"\"\"\nroot_routes.register(\n r'customers', gridplatform.customers.viewsets.CustomerViewSet)\n\nenergyperformance_routes = root_routes.register(\n r'energy_performances', EnergyPerformances, base_name='energyperformances')\nenergyperformance_routes.register(\n r'production_energy_performances',\n gridplatform.energyperformances.viewsets.ProductionEnergyPerformance)\nenergyperformance_routes.register(\n r'time_energy_performances',\n gridplatform.energyperformances.viewsets.TimeEnergyPerformance)\n\ndatasequence_routes = root_routes.register(\n r'datasequences', DataSequences, base_name='datasequences')\ndatasequence_routes.register(\n r'main_consumptions',\n gridplatform.consumptions.viewsets.MainConsumption)\ndatasequence_routes.register(\n r'consumption_groups',\n gridplatform.consumptions.viewsets.ConsumptionGroup)\ndatasequence_routes.register(\n r'production_groups',\n gridplatform.productions.viewsets.ProductionGroup)\n\nconsumption_routes = datasequence_routes.register(\n r'consumption_datasequences',\n gridplatform.consumptions.viewsets.Consumption)\nconsumption_routes.register(\n r'offline_tolerances',\n gridplatform.consumptions.viewsets.OfflineTolerance,\n filter_by='datasequence_id')\nconsumption_routes.register(\n r'nonpulse_periods',\n gridplatform.consumptions.viewsets.NonpulsePeriod,\n filter_by='datasequence_id')\nconsumption_routes.register(\n r'pulse_periods',\n gridplatform.consumptions.viewsets.PulsePeriod,\n filter_by='datasequence_id')\nconsumption_routes.register(\n r'single_value_periods',\n gridplatform.consumptions.viewsets.SingleValuePeriod,\n filter_by='datasequence_id')\n\nproduction_routes = datasequence_routes.register(\n r'production_datasequences',\n gridplatform.productions.viewsets.Production)\nproduction_routes.register(\n r'offline_tolerances',\n gridplatform.productions.viewsets.OfflineTolerance,\n filter_by='datasequence_id')\nproduction_routes.register(\n r'nonpulse_periods',\n gridplatform.productions.viewsets.NonpulsePeriod,\n filter_by='datasequence_id')\nproduction_routes.register(\n r'pulse_periods',\n gridplatform.productions.viewsets.PulsePeriod,\n filter_by='datasequence_id')\nproduction_routes.register(\n r'single_value_periods',\n gridplatform.productions.viewsets.SingleValuePeriod,\n filter_by='datasequence_id')\n\nenergypervolume_routes = datasequence_routes.register(\n r'energy_per_volume_datasequences',\n gridplatform.datasequences.viewsets.EnergyPerVolumeDataSequence)\nenergypervolume_routes.register(\n r'energy_per_volume_periods',\n gridplatform.datasequences.viewsets.EnergyPerVolumePeriod,\n filter_by='datasequence_id')\n\nnonaccumulation_routes = datasequence_routes.register(\n r'nonaccumulation_datasequences',\n gridplatform.datasequences.viewsets.NonaccumulationDataSequence)\nnonaccumulation_routes.register(\n r'nonaccumulation_periods',\n gridplatform.datasequences.viewsets.NonaccumulationPeriod,\n filter_by='datasequence_id')\nnonaccumulation_routes.register(\n r'offline_tolerances',\n gridplatform.datasequences.viewsets.NonaccumulationOfflineTolerance,\n filter_by='datasequence_id')\n\nenergytariff_routes = datasequence_routes.register(\n r'energytariffs',\n gridplatform.tariffs.viewsets.EnergyTariff)\nenergytariff_routes.register(\n 'fixed_price_periods',\n gridplatform.tariffs.viewsets.FixedPricePeriod,\n filter_by='datasequence_id')\nenergytariff_routes.register(\n 'spot_price_periods',\n gridplatform.tariffs.viewsets.SpotPricePeriod,\n filter_by='datasequence_id')\n\nvolumetariff_routes = datasequence_routes.register(\n r'volumetariffs',\n gridplatform.tariffs.viewsets.VolumeTariff)\nvolumetariff_routes.register(\n 'fixed_price_periods',\n gridplatform.tariffs.viewsets.FixedPricePeriod,\n filter_by='datasequence_id')\nvolumetariff_routes.register(\n 'spot_price_periods',\n gridplatform.tariffs.viewsets.SpotPricePeriod,\n filter_by='datasequence_id')\n\n\ncost_compensation_routes = datasequence_routes.register(\n r'cost_compensation',\n gridplatform.cost_compensations.viewsets.CostCompensation)\ncost_compensation_routes.register(\n 'fixed_compensation_period',\n gridplatform.cost_compensations.viewsets.FixedCompensationPeriod,\n filter_by='datasequence_id')\n\n\ndatasource_routes = root_routes.register(\n r'datasources', DataSources, base_name='datasources')\ndatasource_routes.register(\n r'raw_data',\n gridplatform.datasources.viewsets.RawDataViewSet,\n filter_by='datasource_id')\ndatasource_routes.register(\n r'datasource',\n gridplatform.datasources.viewsets.DataSourceViewSet)\n\nglobal_datasource_routes = datasource_routes.register(\n r'global_datasources',\n gridplatform.global_datasources.viewsets.GlobalDataSourceViewSet)\n\nprovider_datasource_routes = datasource_routes.register(\n r'provider_datasources',\n gridplatform.provider_datasources.viewsets.ProviderDataSourceViewSet)\n\ncustomer_datasource_routes = datasource_routes.register(\n r'customer_datasources',\n gridplatform.customer_datasources.viewsets.CustomerDataSourceViewSet)\n\nroot_routes.register(\n r'pricerelays',\n energymanager.price_relay_site.viewsets.RelaySettingsViewSet,\n base_name='pricerelays'\n)\n\nurlpatterns = root_routes.urls\n" }, { "alpha_fraction": 0.6478174328804016, "alphanum_fraction": 0.6502976417541504, "avg_line_length": 40.14285659790039, "blob_id": "a7e5ef9a5a1c16b0614344f682d25e8110aa8405", "content_id": "4ef07cfe5cbbf31ce88cc3cd9f190bab345c033e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8108, "license_type": "no_license", "max_line_length": 78, "num_lines": 196, "path": "/gridplatform/energyperformances/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\n\nimport pytz\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .models import TimeEnergyPerformance\nfrom .models import EnergyPerformance\nfrom .models import ProductionEnergyPerformance\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass EnergyPerformanceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n def test_encryption_integration(self):\n enpi = EnergyPerformance.objects.create(\n customer=self.customer,\n name_plain='base enpi',\n description_plain='base enpi test')\n loaded = EnergyPerformance.objects.get(id=enpi.id)\n self.assertEqual(enpi.name_plain, loaded.name_plain)\n self.assertEqual(enpi.description_plain, loaded.description_plain)\n\n def test_unicode(self):\n enpi = EnergyPerformance.objects.create(\n customer=self.customer,\n name_plain='base enpi',\n description_plain='base enpi test')\n self.assertIn(enpi.name_plain, unicode(enpi))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionEnergyPerformanceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n production_a_unit_plain='kg is',\n timezone=pytz.timezone('Europe/Copenhagen'))\n\n def test_clean_illegal_production_unit(self):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte er '\n 'involveret i produktion',\n production_unit='production_b')\n with self.assertRaises(ValidationError):\n enpi.full_clean()\n\n def test_clean_illegal_production_unit_exclude(self):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte er '\n 'involveret i produktion',\n production_unit='production_b')\n enpi.full_clean(exclude='production_unit')\n\n def test_clean_legal_production_unit(self):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte er '\n 'involveret i produktion',\n production_unit='production_a')\n enpi.full_clean()\n\n def test_production_dataneed_is_added_upon_creation(self):\n ProductionEnergyPerformance.objects.create(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte er '\n 'involveret i produktion',\n production_unit='production_a')\n\n def test_unit_converter_a(self):\n self.customer.production_a_unit_plain = 'Pöp Cørn'\n with replace_customer(self.customer):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte '\n 'er involveret i produktion',\n production_unit='production_a')\n self.assertEqual(\n 'kWh/Pöp Cørn', enpi.unit_converter.get_display_unit())\n\n def test_unit_converter_b(self):\n self.customer.production_b_unit_plain = 'Sändwætch'\n with replace_customer(self.customer):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte '\n 'er involveret i produktion',\n production_unit='production_b')\n self.assertEqual(\n 'kWh/Sändwætch', enpi.unit_converter.get_display_unit())\n\n def test_unit_converter_c(self):\n self.customer.production_c_unit_plain = 'Håmbürgør'\n with replace_customer(self.customer):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte '\n 'er involveret i produktion',\n production_unit='production_c')\n self.assertEquals(\n 'kWh/Håmbürgør', enpi.unit_converter.get_display_unit())\n\n def test_unit_converter_d(self):\n self.customer.production_d_unit_plain = 'Fränch Friæs'\n with replace_customer(self.customer):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte '\n 'er involveret i produktion',\n production_unit='production_d')\n self.assertEquals(\n 'kWh/Fränch Friæs', enpi.unit_converter.get_display_unit())\n\n def test_unit_converter_e(self):\n self.customer.production_e_unit_plain = 'Pän Cåkes'\n with replace_customer(self.customer):\n enpi = ProductionEnergyPerformance(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte '\n 'er involveret i produktion',\n production_unit='production_e')\n self.assertEquals(\n 'kWh/Pän Cåkes', enpi.unit_converter.get_display_unit())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer(production_a_unit_plain='kg is')\n self.customer.save()\n self.enpi = ProductionEnergyPerformance.objects.create(\n customer=self.customer,\n name_plain='Øvrige energianvendelser pr kg is',\n description_plain='Dækker energianvendelser der ikke direkte er '\n 'involveret i produktion',\n production_unit='production_a')\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass HistoricalProductionTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TimeEnergyPerformanceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.energy_performance = TimeEnergyPerformance.objects.create(\n customer=self.customer,\n name_plain='årligt totalforbrug',\n description_plain='all energianvændelser samlet',\n unit='kilowatt*hour*year^-1')\n\n def test_compute_performance_compute_total_energy_integration(self):\n self.assertEqual(\n self.energy_performance.compute_performance(\n datetime.datetime(2014, 1, 1, tzinfo=pytz.utc),\n datetime.datetime(2015, 1, 1, tzinfo=pytz.utc)),\n PhysicalQuantity(0, 'watt'))\n\n def test_unit_converter(self):\n self.assertEqual(\n self.energy_performance.unit_converter.extract_value(\n PhysicalQuantity(42, 'kilowatt*hour*year^-1')),\n 42)\n" }, { "alpha_fraction": 0.7544247508049011, "alphanum_fraction": 0.7566371560096741, "avg_line_length": 29.133333206176758, "blob_id": "a5128b7584fc2dc8f6b6282de1647947cadcc4c7", "content_id": "4ef6fd1c43b73db5d5ad278ab760fc89970be028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 72, "num_lines": 15, "path": "/legacy/website/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db.models.signals import post_save\n\nfrom gridplatform.users.models import User\nfrom legacy.legacy_utils.models import UserProfile\n\n\ndef create_user_profile(sender, instance, created, raw=False, **kwargs):\n if created and not raw:\n UserProfile.objects.create(user=instance)\n\npost_save.connect(create_user_profile, sender=User)\n" }, { "alpha_fraction": 0.713274359703064, "alphanum_fraction": 0.7150442600250244, "avg_line_length": 24.68181800842285, "blob_id": "47045ace2d57998952c2fd607884f28ba791b9a5", "content_id": "987b8330654a3401f0b7b927b17ce70fae9e216d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 565, "license_type": "no_license", "max_line_length": 61, "num_lines": 22, "path": "/gridplatform/customers/mixins.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import models\n\nfrom gridplatform.trackuser import get_customer\n\nfrom .models import Customer\n\n\nclass EncryptionCustomerFieldMixin(models.Model):\n customer = models.ForeignKey(\n Customer, editable=False, verbose_name=_('customer'),\n default=get_customer)\n\n class Meta:\n abstract = True\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n" }, { "alpha_fraction": 0.6137519478797913, "alphanum_fraction": 0.6152995824813843, "avg_line_length": 35.475807189941406, "blob_id": "3487c7b90ad69c8a6c708b847e8f3a048dc83c7a", "content_id": "07b83fce3e3aa6b6ef598ad78c8cdc98af150963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4523, "license_type": "no_license", "max_line_length": 78, "num_lines": 124, "path": "/energymanager/start_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport urlparse\n\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import REDIRECT_FIELD_NAME\nfrom django.contrib.auth import login as auth_login\nfrom django.contrib.sites.models import get_current_site\nfrom django.views.generic import FormView\nfrom django.views.generic import TemplateView\nfrom django.utils.translation import ugettext as _\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\n\nfrom gridplatform.trackuser import get_provider_id\nfrom gridplatform.trackuser import replace_selected_customer\n\n\ndef applist(request, user):\n \"\"\"\n Returns a list off apps that the loggedin user has access to\n \"\"\"\n\n with replace_selected_customer(None):\n app_selection = []\n\n app_selection.append(\n {'name': _('SC-Portal 2.0'), 'url': reverse('website-home'),\n 'icon': static('start_site/images/portal2_icon.png')})\n\n if user is None:\n return app_selection\n\n if user.has_perm('users.access_provider_site') and get_provider_id():\n app_selection.append(\n {'name': _('Administration'),\n 'url': reverse('provider_site:home'),\n 'icon': static('start_site/images/administration_icon.png')})\n\n app_selection.append(\n {'name': _('Configuration'),\n 'url': reverse('configuration_site:home'),\n 'icon': static('start_site/images/administration_icon.png')})\n\n if user.has_perm('users.access_led_light_site'):\n app_selection.append(\n {'name': _('LED Light'),\n 'url': reverse('led_light_site:home'),\n 'icon': static('start_site/images/led_light_icon.png')})\n\n if user.has_perm('users.access_project_site'):\n app_selection.append(\n {'name': _('ESCo Lite'),\n 'url': reverse('project_site:home'),\n 'icon': static('start_site/images/energy_manager_icon.png')})\n\n if user.has_perm('users.access_price_relay_site'):\n app_selection.append(\n {'name': _('Price Relay'),\n 'url': reverse('price_relay_site:home'),\n 'icon': static('start_site/images/energy_manager_icon.png')})\n\n if user.has_perm('users.access_datahub_site'):\n app_selection.append(\n {'name': _('Datahub'),\n 'url': reverse('datahub_site:home'),\n 'icon': static('start_site/images/energy_manager_icon.png')})\n\n return app_selection\n\n\nclass LoginView(FormView):\n template_name = \"start_site/login.html\"\n form_class = AuthenticationForm\n\n def dispatch(self, request, *args, **kwargs):\n self.redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')\n request.session.set_test_cookie()\n self.current_site = get_current_site(request)\n\n return super(\n LoginView, self).dispatch(request, *args, **kwargs)\n\n def form_valid(self, form):\n # login user\n user = form.get_user()\n auth_login(self.request, user)\n\n netloc = urlparse.urlparse(self.redirect_to)[1]\n\n # Use applist or default setting if self.redirect_to is empty\n if not self.redirect_to:\n app_selection = applist(self.request, user)\n if len(app_selection) == 1:\n self.redirect_to = app_selection[0]['url']\n else:\n self.redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Heavier security check -- don't allow redirection to a different\n # host.\n elif netloc and netloc != self.request.get_host():\n self.redirect_to = settings.LOGIN_REDIRECT_URL\n\n if self.request.session.test_cookie_worked():\n self.request.session.delete_test_cookie()\n\n return HttpResponseRedirect(self.redirect_to)\n\n def render_to_response(self, context, **response_kwargs):\n context.update(\n {'REDIRECT_FIELD_NAME': self.redirect_to,\n 'site': self.current_site,\n 'site_name': self.current_site.name, })\n\n return super(\n LoginView, self).render_to_response(context, **response_kwargs)\n\n\nclass AppsView(TemplateView):\n template_name = \"start_site/apps.html\"\n" }, { "alpha_fraction": 0.6315270662307739, "alphanum_fraction": 0.6394088864326477, "avg_line_length": 27.5112361907959, "blob_id": "7c2e23d88ae50c2ebc83a8768253effb0dc1edad", "content_id": "16a99e7b44acfc5e15607a4b0aeba9a2b8aa9305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5075, "license_type": "no_license", "max_line_length": 79, "num_lines": 178, "path": "/gridplatform/reports/templatetags/reports.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport os.path\nfrom fractions import Fraction\n\nfrom django import template\nfrom django.utils.safestring import mark_safe\nfrom django.conf import settings\nfrom django.templatetags import i18n\nfrom django.template.defaultfilters import floatformat as django_floatformat\n\nregister = template.Library()\n\n\[email protected]_tag\ndef media_file(path):\n \"\"\"\n Get an absolute file path from a relative \"media\" file path.\n \"\"\"\n return mark_safe(os.path.abspath(os.path.join(settings.MEDIA_ROOT, path)))\n\n\[email protected]_tag\ndef static_file(path):\n \"\"\"\n Get an absolute file path from a relative \"static\" file path.\n \"\"\"\n # Find files in app directories, STATICFILES_DIRS and wherever else the\n # development static files server and collectstatic would find them.\n # (Unlike \"media\", each app may have its own \"static\" files, and we want to\n # be able to use them during development, without explicitly running\n # \"manage.py collectstatic\".)\n from django.contrib.staticfiles import finders\n return mark_safe(finders.find(path))\n\n\nrewrite_rules = (\n ('\\\\', r'\\\\'),\n ('{', r'\\{'),\n ('}', r'\\}'),\n ('\\\\\\\\', r'\\textbackslash{}'),\n ('#', r'\\#'),\n ('$', r'\\$'),\n ('%', r'\\%'),\n ('&', r'\\&'),\n ('~', r'\\~'),\n ('_', r'\\_'),\n ('^', r'{$\\hat{~}$}'),\n ('\\r', ''),\n ('\\n', r'\\newline{}'),\n)\n\n\[email protected]\ndef texescape(value):\n \"\"\"\n Escape/replace characters with special meanings in (La)TeX.\n \"\"\"\n result = unicode(value)\n for (string, replacement) in rewrite_rules:\n result = result.replace(string, replacement)\n return mark_safe(result)\n\n\nclass TexTranslateNode(i18n.TranslateNode):\n \"\"\"\n Specialisation of translation node; escaping output for TeX.\n \"\"\"\n def render(self, context):\n value = super(TexTranslateNode, self).render(context)\n if self.asvar:\n context[self.asvar] = texescape(context[self.asvar])\n return texescape(value)\n\n\nclass TexBlockTranslateNode(i18n.BlockTranslateNode):\n \"\"\"\n Specialisation of block translation node; escaping output for TeX.\n \"\"\"\n def render(self, context):\n return texescape(super(TexBlockTranslateNode, self).render(context))\n\n\[email protected]\ndef trans(parser, token):\n \"\"\"\n Specialisation of translation tag; escaping output for TeX.\n\n NOTE: Same tag name as the standard Django tag, to ensure that they are\n included in translation as normal.\n \"\"\"\n node = i18n.do_translate(parser, token)\n node.__class__ = TexTranslateNode\n return node\n\n\[email protected]\ndef blocktrans(parser, token):\n \"\"\"\n Specialisation of block translation tag; escaping output for TeX.\n\n NOTE: Same tag name as the standard Django tag, to ensure that they are\n included in translation as normal.\n\n @param notexescape: If this argument is given texescaping will be\n disabled::\n\n {% blocktrans notexescape with page as \"\\thePage{}\" %}\n Page {{ page }}\n {% endblocktrans %}\n\n @bug: If the string C{'notexescape'} is part of any of the other arguments,\n it will be removed, and interpreted as the notexescape option.\n \"\"\"\n if 'notexescape' in token.contents:\n token.contents = token.contents.replace('notexescape', '')\n node = i18n.do_block_translate(parser, token)\n else:\n node = i18n.do_block_translate(parser, token)\n node.__class__ = TexBlockTranslateNode\n return node\n\n\[email protected]\ndef pgfcolor(value):\n \"\"\"\n Translate a HTML style hexadecimal color to something that works with LaTeX\n pgf. For instance::\n\n #8A52E8\n\n should be converted to::\n\n {rgb:red,138;green,82;blue,232}\n \"\"\"\n try:\n red = int(value[1:3], base=16)\n green = int(value[3:5], base=16)\n blue = int(value[5:7], base=16)\n return mark_safe('{rgb:red,%d;green,%d;blue,%d}' % (red, green, blue))\n except:\n # from the docs: Filter functions should always return something. They\n # shouldn't raise exceptions. They should fail silently. In case of\n # error, they should return either the original input or an empty\n # string - whichever makes more sense.\n #\n # https://docs.djangoproject.com/en/dev/howto/custom-template-tags/\n return value\n\n\[email protected]\ndef seqsplit(value, arg=10):\n \"\"\"\n Wrap \"long\" words in \\seqsplit{}, in order to allow linebreaks at any place\n inside them.\n \"\"\"\n parts = value.split(' ')\n\n def do_split(s):\n if len(s) > arg:\n return '\\seqsplit{%s}' % s\n else:\n return s\n result = ' '.join(map(do_split, parts))\n return mark_safe(result)\n\n\[email protected](is_safe=True)\ndef floatformat(text, arg=-1):\n \"\"\"\n Work-around for bug in Python Decimal. See L{FloatFormatTest} for details.\n \"\"\"\n try:\n return django_floatformat(float(Fraction(str(text))), arg)\n except:\n return django_floatformat(text, arg)\n" }, { "alpha_fraction": 0.6614389419555664, "alphanum_fraction": 0.665440559387207, "avg_line_length": 42.633155822753906, "blob_id": "5f6f4295b5db7c93326e2620c4844712534df887", "content_id": "04a63ffaff91f69b80de2e24acc0d9f2e58ff68a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24740, "license_type": "no_license", "max_line_length": 87, "num_lines": 567, "path": "/gridplatform/condensing/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. data:: CACHABLE_UNITS\n\n Set of units of various accumulations that may have been used as unit for\n :class:`DataSources<.DataSource>`.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\nimport datetime\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.db.models.signals import post_delete\nfrom django.dispatch import receiver\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customer_datasources.models import DataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import ACCUMULATION_BASE_UNITS\nfrom gridplatform.utils.units import IMPULSE_BASE_UNITS\nfrom gridplatform.utils.samples import Sample\n\n\nCACHABLE_UNITS = set(ACCUMULATION_BASE_UNITS + IMPULSE_BASE_UNITS)\n\n\ndef validate_hour(timestamp):\n \"\"\"\n Validator that ensures given ``timestamp`` is on the hour.\n\n :raise ValidationError: If given ``timestamp`` is not on the hour.\n :raise ValidationError: If given ``timestamp`` does not have a timezone.\n \"\"\"\n if timestamp.tzinfo is None:\n raise ValidationError(\n 'Missing timezone for timestamp %s.' % (timestamp,))\n if (timestamp.minute, timestamp.second, timestamp.microsecond) != \\\n (0, 0, 0):\n raise ValidationError(\n 'Timestamp %s does not match clock hour.' % (timestamp,))\n\n\ndef validate_five_minutes(timestamp):\n \"\"\"\n Validator that ensures given ``timestamp`` is a five minute multiplum.\n\n :raise ValidationError: If given ``timestamp`` is not a five minute multiplum.\n :raise ValidationError: If given ``timestamp`` does not have a timezone.\n \"\"\"\n if timestamp.tzinfo is None:\n raise ValidationError(\n 'Missing timezone for timestamp %s.' % (timestamp,))\n if (timestamp.second, timestamp.microsecond) != (0, 0) or \\\n timestamp.minute % 5 != 0:\n raise ValidationError(\n 'Timestamp %s does not match five minute interval.' % (timestamp,))\n\n\nclass AccumulatedData(models.Model):\n \"\"\"\n Abstract base model for accumulated data.\n\n :ivar datasource: The :class:`.DataSource` whose data is being accumulated.\n :ivar value: The accumulated value.\n \"\"\"\n datasource = models.ForeignKey(DataSource, db_index=False)\n value = models.BigIntegerField()\n\n class Meta:\n abstract = True\n # NOTE: unique_together creates an index; index_together would create\n # would create an extra, redundant index\n unique_together = ('datasource', 'timestamp')\n ordering = ['timestamp']\n\n\nclass HourAccumulatedData(AccumulatedData):\n \"\"\"\n Concrete specialization of :class:`.AccumulatedData` for hourly accumulations.\n\n :ivar timestamp: The leading timestamp of the hour this accumulation data\n belongs to.\n \"\"\"\n timestamp = models.DateTimeField(validators=[validate_hour])\n\n class Meta(AccumulatedData.Meta):\n verbose_name = _('hour accumulated data')\n verbose_name_plural = _('hour accumulated data')\n\n def __unicode__(self):\n return u\"%s, %s\" % (self.timestamp, self.value)\n\n def save(self, *args, **kwargs):\n \"\"\"\n :precondition: ``self.timestamp`` is on the hour and has a timezone.\n \"\"\"\n validate_hour(self.timestamp)\n super(HourAccumulatedData, self).save(*args, **kwargs)\n\n\nclass FiveMinuteAccumulatedData(AccumulatedData):\n \"\"\"\n Concrete specialization of :class:`.AccumulatedData` for five-minute accumulations.\n\n :ivar timestamp: The leading timestamp of the five minutes this\n accumulation data belongs to.\n \"\"\"\n timestamp = models.DateTimeField(validators=[validate_five_minutes])\n\n class Meta(AccumulatedData.Meta):\n verbose_name = _('five minutes accumulated data')\n verbose_name_plural = _('five minutes accumulated data')\n\n def __unicode__(self):\n return u\"%s, %s\" % (self.timestamp, self.value)\n\n def save(self, *args, **kwargs):\n \"\"\"\n :precondition: ``self.timestamp`` is a five minute multiplum and has a\n timezone.\n \"\"\"\n validate_five_minutes(self.timestamp)\n super(FiveMinuteAccumulatedData, self).save(*args, **kwargs)\n\n\n@receiver(post_delete, sender=RawData)\ndef cleanup_cache_for_rawdata_delete(sender, instance, **kwargs):\n \"\"\"\n Signal handler called when a :class:`.RawData` is deleted.\n\n The time period between between the :class:`RawData` just before the\n deleted and the RawData just after the deleted is considered tainted. (Use\n timestamp from deleted for edge case of no data before or no data after.)\n Cache data whose time period starts or ends within this period will be\n deleted.\n \"\"\"\n datasource_id = instance.datasource_id\n previous_timestamp = RawData.objects.filter(\n datasource_id=datasource_id,\n timestamp__lt=instance.timestamp,\n ).order_by('timestamp').values_list('timestamp', flat=True).last()\n range_start = previous_timestamp or instance.timestamp\n next_timestamp = RawData.objects.filter(\n datasource_id=datasource_id,\n timestamp__gt=instance.timestamp,\n ).order_by('timestamp').values_list('timestamp', flat=True).first()\n range_end = next_timestamp or instance.timestamp\n if range_start == range_end:\n # There was only a single data point in data sequence --- no cache\n # could have been computed from that.\n assert range_start == instance.timestamp == range_end\n # The sanity check is perhaps a bit expensive --- but optimising this\n # special case by avoiding it would not be worthwhile; the normal case\n # will query both cache tables anyway.\n assert not HourAccumulatedData.objects.filter(\n datasource_id=datasource_id).exists()\n assert not FiveMinuteAccumulatedData.objects.filter(\n datasource_id=datasource_id).exists()\n return\n # Hours that start or end inside range; the first hour that ends inside\n # range may have started an hour before...\n hour_range_start = range_start - datetime.timedelta(hours=1)\n HourAccumulatedData.objects.filter(\n datasource_id=datasource_id,\n timestamp__gte=hour_range_start,\n timestamp__lte=range_end).delete()\n five_minute_range_start = range_start - datetime.timedelta(minutes=5)\n FiveMinuteAccumulatedData.objects.filter(\n datasource_id=datasource_id,\n timestamp__gte=five_minute_range_start,\n timestamp__lte=range_end).delete()\n\n\ndef get_hourly_accumulated(datasource, from_timestamp, to_timestamp):\n \"\"\"\n Get hourly accumulated data as ranged `Sample` instances; using existing\n cached values when possible.\n \"\"\"\n validate_hour(from_timestamp)\n validate_hour(to_timestamp)\n return get_accumulated(\n datasource, datasource.houraccumulateddata_set,\n from_timestamp, to_timestamp, datetime.timedelta(hours=1))\n\n\ndef get_five_minute_accumulated(datasource, from_timestamp, to_timestamp):\n \"\"\"\n Get hourly accumulated data as ranged `Sample` instances; using existing\n cached values when possible.\n \"\"\"\n validate_five_minutes(from_timestamp)\n validate_five_minutes(to_timestamp)\n return get_accumulated(\n datasource, datasource.fiveminuteaccumulateddata_set,\n from_timestamp, to_timestamp, datetime.timedelta(minutes=5))\n\n\ndef get_accumulated(\n datasource, cache_queryset,\n from_timestamp, to_timestamp, period_length):\n \"\"\"\n Shared logic for `get_hourly_accumulated()` and\n `get_five_minute_accumulated()`. Try to read from cache; if necessary,\n supplement by computing missing entries, return result as list of `Sample`\n objects.\n \"\"\"\n entries = list(cache_queryset.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', 'value'))\n period_count = (to_timestamp - from_timestamp).total_seconds() / \\\n period_length.total_seconds()\n interpolate_fn = datasource._get_interpolate_fn()\n assert period_count == round(period_count)\n assert len(entries) <= period_count\n if len(entries) < period_count:\n # We skip logic for finding/generating missing periods if cached data\n # is present for all of the requested. That should hopefully be the\n # common case, making optimising it worthwhile.\n timestamps = [timestamp for timestamp, value in entries]\n missing = missing_periods(\n from_timestamp, to_timestamp, timestamps, period_length)\n for missing_from, missing_to in missing:\n data = raw_data_for_cache(datasource, missing_from, missing_to)\n generated = generate_period_data(\n data, missing_from, missing_to, period_length, interpolate_fn)\n entries.extend(generated)\n entries.sort()\n assert len(entries) <= period_count\n unit = datasource.unit\n return [\n Sample(timestamp, timestamp + period_length,\n PhysicalQuantity(value, unit), False, False)\n for timestamp, value in entries\n ]\n\n\nINT64_MIN = -2**63\nINT64_MAX = 2**63-1\n\n\ndef generate_cache(datasource, from_timestamp, to_timestamp):\n \"\"\"\n Generate and store `HourAccumulatedData` and `FiveMinuteAccumulatedData`.\n \"\"\"\n validate_hour(from_timestamp)\n validate_hour(to_timestamp)\n assert datasource.unit in CACHABLE_UNITS\n\n ONE_HOUR = datetime.timedelta(hours=1)\n FIVE_MINUTES = datetime.timedelta(minutes=5)\n interpolate_fn = datasource._get_interpolate_fn()\n present_five_minutes = list(\n datasource.fiveminuteaccumulateddata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', flat=True))\n missing_five_minutes = set(missing_periods(\n from_timestamp, to_timestamp, present_five_minutes, FIVE_MINUTES))\n present_hours = list(datasource.houraccumulateddata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', flat=True))\n missing_hours = set(missing_periods(\n from_timestamp, to_timestamp, present_hours, ONE_HOUR))\n # Combine RawData reading when both missing the same periods. We only\n # optimise for the case of them missing the exact same periods, as we would\n # expect cache generation to have been run for the same periods for both\n # if/when run; other cases of missing periods should be less common, and\n # are handled but not optimised.\n missing_both = missing_five_minutes & missing_hours\n missing_five_minutes_only = missing_five_minutes - missing_both\n missing_hour_only = missing_hours - missing_both\n five_minute_data = []\n hour_data = []\n for missing_from, missing_to in missing_both:\n data = raw_data_for_cache(datasource, missing_from, missing_to)\n five_minute_data.extend(generate_period_data(\n data, missing_from, missing_to, FIVE_MINUTES, interpolate_fn))\n hour_data.extend(generate_period_data(\n data, missing_from, missing_to, ONE_HOUR, interpolate_fn))\n\n for missing_from, missing_to in missing_five_minutes_only:\n data = raw_data_for_cache(datasource, missing_from, missing_to)\n five_minute_data.extend(generate_period_data(\n data, missing_from, missing_to, FIVE_MINUTES, interpolate_fn))\n for missing_from, missing_to in missing_hour_only:\n data = raw_data_for_cache(datasource, missing_from, missing_to)\n hour_data.extend(generate_period_data(\n data, missing_from, missing_to, ONE_HOUR, interpolate_fn))\n if five_minute_data:\n five_minute_objects = []\n for timestamp, value in five_minute_data:\n obj = FiveMinuteAccumulatedData(\n datasource=datasource,\n timestamp=timestamp,\n value=int(Fraction(value).limit_denominator(1)))\n if obj.value <= INT64_MIN:\n obj.value = INT64_MIN\n if obj.value >= INT64_MAX:\n obj.value = INT64_MAX\n five_minute_objects.append(obj)\n FiveMinuteAccumulatedData.objects.bulk_create(five_minute_objects)\n if hour_data:\n hour_objects = []\n for timestamp, value in hour_data:\n obj = HourAccumulatedData(\n datasource=datasource,\n timestamp=timestamp,\n value=int(Fraction(value).limit_denominator(1)))\n if obj.value <= INT64_MIN:\n obj.value = INT64_MIN\n if obj.value >= INT64_MAX:\n obj.value = INT64_MAX\n hour_objects.append(obj)\n HourAccumulatedData.objects.bulk_create(hour_objects)\n\n\ndef missing_periods(from_timestamp, to_timestamp, present, period_length):\n \"\"\"\n Find contiguous periods within `from_timestamp`, `to_timestamp` not\n represented by timestamps from `present`. Each element in `present`\n represents a time period of length `period_length` by its starting point.\n\n This function, and how it is used, may be considered a \"brute force\"\n approach, but if we work with datasets/period where iterating over the\n condensed representation becomes problematic, we'll have other problems\n too...\n \"\"\"\n assert from_timestamp <= to_timestamp\n assert (to_timestamp - from_timestamp).total_seconds() % \\\n period_length.total_seconds() == 0\n if present == []:\n # Everything missing.\n yield (from_timestamp, to_timestamp)\n return\n if from_timestamp < present[0]:\n # Missing data before first present.\n yield from_timestamp, present[0]\n for a, b in pairwise(present):\n if a + period_length < b:\n # Missing data between present elements.\n yield (a + period_length, b)\n if present[-1] + period_length < to_timestamp:\n # Missing data after last present.\n yield (present[-1] + period_length, to_timestamp)\n\n\ndef generate_period_data(\n data, from_timestamp, to_timestamp, period_length, interpolate_fn):\n \"\"\"\n Transform ordered list of `(timestamp, accumulated_value)` from `data` into\n sequence of `(timestamp, increase)`, where `increase` represents the growth\n in accumulated value between `timestamp` and `timestamp + period_length`.\n\n Only periods within both the range represented by elements in `data` and\n the range represented by [`from_timestamp`, `to_timestamp`] are included.\n `from_timestamp` and `to_timestamp` should be aligned to `period_length`.\n \"\"\"\n adjusted_from, adjusted_to = adjust_from_to(\n data, from_timestamp, to_timestamp, period_length)\n if adjusted_from is None or adjusted_to is None:\n return\n aligned = period_aligned(\n data, adjusted_from, adjusted_to, period_length, interpolate_fn)\n for (timestamp_a, value_a), (timestamp_b, value_b) in pairwise(aligned):\n assert timestamp_b - timestamp_a == period_length\n yield (timestamp_a, value_b - value_a)\n\n\ndef raw_data_for_cache(\n datasource, from_timestamp, to_timestamp,\n border=datetime.timedelta(minutes=1)):\n \"\"\"\n Obtain raw data for the requested period, and, if possible, also a few\n samples outside the requested, in order to be able to use the result to\n interpolate the values at `from_timestamp` and `to_timestamp`.\n\n Returns empty list if no data inside specified range is found *and* finding\n data outside the range to enable interpolation failed. (I.e. empty list if\n insufficient data to specify or interpolate any points in closed range\n [`from_timestamp`, `to_timestamp`]. This will occur if no data is\n available for the data source, or all available data is outside the\n specified range in the same direction.)\n \"\"\"\n assert border >= datetime.timedelta()\n before_from = from_timestamp - border\n after_to = to_timestamp + border\n data = list(datasource.rawdata_set.filter(\n timestamp__gte=before_from,\n timestamp__lte=after_to).order_by('timestamp').values_list(\n 'timestamp', 'value'))\n TIMESTAMP = 0\n # VALUE = 1\n if data == [] or data[-1][TIMESTAMP] < to_timestamp:\n # If no data *or* last data element before to_timestamp, attempt to\n # load next data element after. (If no data present, loading\n # \"after\"-data here and \"before\"-data subsequently may still provide\n # sufficient data for interpolation.)\n after = datasource.rawdata_set.filter(\n timestamp__gte=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', 'value').first()\n if after is not None:\n # Stuff will break in other places if we don't maintain the order\n # in data.\n assert data == [] or data[-1][TIMESTAMP] < after[TIMESTAMP]\n data.append(after)\n if data != [] and data[0][TIMESTAMP] > from_timestamp:\n # If data present *and* first data element after from_timestamp,\n # attempt to load last data element before. (If no data present, then\n # we failed to load \"after\"-data, and querying the database here would\n # be pointless; even if we succeed in loading \"before\"-data, that would\n # not be enough.)\n before = datasource.rawdata_set.filter(\n timestamp__lte=from_timestamp).order_by('timestamp').values_list(\n 'timestamp', 'value').last()\n if before is not None:\n # Stuff will break in other places if we don't maintain the order\n # in data.\n assert data == [] or data[0][TIMESTAMP] > before[TIMESTAMP]\n data.insert(0, before)\n if data == [] or data[0][TIMESTAMP] > to_timestamp or \\\n data[-1][TIMESTAMP] < from_timestamp:\n # No data, or all data fourd after to_timestamp, or all data found\n # before from_timestamp. (As we obtain some data outside the range to\n # help interpolation, data is not necessarily empty for these cases.)\n return []\n # Ideally, at this point we have\n # data[0][TIMESTAMP] <= from_timestamp <= \\\n # to_timestamp <= data[-1][TIMESTAMP]\n # but we might have\n # from_timestamp <= data[0][TIMESTAMP] <= \\\n # data[-1][TIMESTAMP] <= to_timestamp\n # or other variations, depending on available data.\n assert data[0][TIMESTAMP] <= to_timestamp\n assert from_timestamp <= data[-1][TIMESTAMP]\n return data\n\n\ndef adjust_from_to(data, from_timestamp, to_timestamp, period_length):\n \"\"\"\n Compute new from/to timestamps such that the resulting range is a subset of\n the range of [`from_timestamp`, `to_timestamp`] and *also* a subset of the\n time range represented in `data`, while keeping the alignment to\n `period_length` of `from_timestamp` and `to_timestamp`.\n\n The greatest such range is returned as a pair; if no such range exists,\n `(None, None)` is returned.\n\n With the current implementation, `period_length` must be a divisor of\n `datetime.timedelta(days=1)`. (At least conceptually --- division is not\n directly defined for timedelta objects.)\n \"\"\"\n assert from_timestamp <= to_timestamp\n # Period_length must be a divisor of datetime.timedelta(days=1) --- or the\n # attempt to be clever and jump days at a time will fail.\n assert datetime.timedelta(days=1).total_seconds() % \\\n period_length.total_seconds() == 0\n if not data:\n # If there is no data, then the resulting range is empty. (Return\n # *after* input validation --- other parameters should be well-formed\n # even if there is no data.)\n return (None, None)\n TIMESTAMP = 0\n # VALUE = 1\n if from_timestamp < data[0][TIMESTAMP]:\n # Skip the appropriate number of whole days before adjusting\n # hour-by-hour, to ensure a limited number of loop iterations even in\n # the worst case.\n difference_days = (data[0][TIMESTAMP] - from_timestamp).days\n from_timestamp += datetime.timedelta(days=difference_days)\n # Day adjustment should not overshoot ...\n assert from_timestamp <= data[0][TIMESTAMP]\n # ... nor leave us further than a day away from the correct value.\n assert (data[0][TIMESTAMP] - from_timestamp) < \\\n datetime.timedelta(days=1)\n # We avoid trying to be clever with the seconds/microseconds fields of\n # timedelta; adding one hour at a time is straightforward, and we'll\n # need to add at most 23 hours.\n while from_timestamp < data[0][TIMESTAMP]:\n from_timestamp += period_length\n assert from_timestamp >= data[0][TIMESTAMP]\n if to_timestamp > data[-1][TIMESTAMP]:\n # As for from_timestamp; skip days before adjusting hour-by-hour.\n difference_days = (to_timestamp - data[-1][TIMESTAMP]).days\n to_timestamp -= datetime.timedelta(days=difference_days)\n # Did not overshoot, did not miss a whole day.\n assert to_timestamp >= data[-1][TIMESTAMP]\n assert (to_timestamp - data[-1][TIMESTAMP]) < \\\n datetime.timedelta(days=1)\n while to_timestamp > data[-1][TIMESTAMP]:\n to_timestamp -= period_length\n assert to_timestamp <= data[-1][TIMESTAMP]\n if from_timestamp > to_timestamp:\n # Not a single period-length aligned point present inside data.\n return (None, None)\n return (from_timestamp, to_timestamp)\n\n\ndef period_aligned(\n data, from_timestamp, to_timestamp, period_length, interpolate_fn):\n \"\"\"\n Transform sequence of `(timestamp, value)`-tuples to sequence of\n `(timestamp, value)`-tuples aligned to `period_length`, starting from\n `from_timestamp`, using interpolation to determine value if timestamp\n between entries in input.\n\n `data` a list of `(timestamp, value)`-tuples, sorted by timestamp.\n\n First data element must be before or at `from_timestamp`, last data element\n must be at or after `to_timestamp`.\n\n `from_timestamp` and `to_timestamp` must represent absolute timestamps\n aligned to `period_length`. `from_timestamp` must be before or the same as\n `to_timestamp`. Adding `period_length` some number of times to\n `from_timestamp` must eventually lead to `to_timestamp`.\n \"\"\"\n TIMESTAMP = 0\n VALUE = 1\n assert from_timestamp <= to_timestamp\n # Partial check only --- both might be equally misaligned.\n assert (to_timestamp - from_timestamp).total_seconds() % \\\n period_length.total_seconds() == 0\n assert data[0][TIMESTAMP] <= from_timestamp\n assert data[-1][TIMESTAMP] >= to_timestamp\n next_timestamp = from_timestamp\n # Yield one interpolated value per hour-point, including the endpoints at\n # from_timestamp, to_timestamp.\n for point_a, point_b in pairwise(data):\n # Initially; from data[0][TIMESTAMP] <= from_timestamp\n # In loop; from point_a being point_b from previous iteration where\n # point_b[TIMESTAMP] <= next_timestamp\n assert point_a[TIMESTAMP] <= next_timestamp\n # From (unchecked) precondition for function; that data is sorted\n assert point_a[TIMESTAMP] < point_b[TIMESTAMP]\n while point_a[TIMESTAMP] <= next_timestamp < point_b[TIMESTAMP]:\n # One or more period-aligned points between the current pair; yield\n # for each of those.\n yield (next_timestamp, interpolate_fn(\n next_timestamp, point_a, point_b))\n next_timestamp += period_length\n if next_timestamp > to_timestamp:\n return\n assert point_a[TIMESTAMP] < point_b[TIMESTAMP] <= next_timestamp\n # We know that\n # data[-1][TIMESTAMP] >= to_timestamp\n # and that if\n # data[-1][TIMESTAMP] > to_timestamp\n # then the function have retured after yielding a value for `to_timestamp`\n # from inside the loop. Hence we have:\n assert data[-1][TIMESTAMP] == to_timestamp\n # Also, any `next_timestamp` fulfilling\n # next_timestamp < data[-1][TIMESTAMP]\n # would have been yielded from the inner loop; hence:\n assert next_timestamp == to_timestamp\n # Intentionally avoiding use of point_a/point_b here --- to implicitly\n # handle the edge case of\n # from_timestamp == to_timestamp == data[0][TIMESTAMP] and \\\n # len(data) == 1\n # where `point_a` and `point_b` would be uninitialised.\n yield (next_timestamp, Fraction(data[-1][VALUE]))\n" }, { "alpha_fraction": 0.6122022867202759, "alphanum_fraction": 0.6140754818916321, "avg_line_length": 38.419830322265625, "blob_id": "8ce37a19dad82bdbf1e39fcedbb3765760a0cb42", "content_id": "de1b8354985864f3f6003025eb20564d09076327", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18685, "license_type": "no_license", "max_line_length": 79, "num_lines": 474, "path": "/legacy/measurementpoints/proxies/consumptionmeasurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints import default_unit_for_data_series\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Co2Calculation\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import DegreeDayCorrection\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.measurementpoints.models import Link\nfrom legacy.measurementpoints.models import RateConversion\nfrom legacy.measurementpoints.models import Utilization\nfrom gridplatform.utils.models import raise_if_none\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import utilitytypes\n\nfrom legacy.measurementpoints.models import Collection\nfrom .measurementpoint import MeasurementPoint\n\n\nclass cached_lookup_property(object):\n \"\"\"\n Like C{django.utils.functional.cached_property} with short-circuit to\n return C{None} on missing C{self.id} and on C{ObjectDoesNotExist}\n exceptions. While this might not be useful in general, it can be used to\n remove a lot of boilerplate in this file...\n \"\"\"\n def __init__(self, func):\n self.func = func\n\n def __get__(self, instance, type):\n res = None\n if instance.id:\n try:\n res = self.func(instance)\n except ObjectDoesNotExist:\n pass\n instance.__dict__[self.func.__name__] = res\n return res\n\n\nclass ConsumptionMeasurementPoint(MeasurementPoint):\n \"\"\"\n ConsumptionMeasurementPoint\n ===========================\n\n A C{ConsumptionMeasurementPoint} is a L{MeasurementPoint} that measures\n consumptions, i.e. has a C{consumption} L{DataSeries}.\n\n Rate\n ----\n\n From C{consumption} a C{rate} can be derived. To do this, just set\n the C{enable_rate} to C{True}. The rate may also be set explicitly\n through the C{rate} property, but that is deprecated since the\n C{enable_rate} property was introduced.\n\n Heating Degree Days Corrected Consumption\n -----------------------------------------\n\n When the C{standard_heating_degree_days} and C{heating_degree_days}\n properties are both set, a heating degree days corrected\n consumption graph will be defined for this\n C{ConsumptionMeasurementPoint}. Setting both to C{None} will remove\n the heating degree days corrected graph again. L{clean()} will\n complain if these are not either both set or both C{None}.\n\n Consumption Utilization According to Area\n -----------------------------------------\n\n When C{area} is set, a consumption utilization according to area\n graph will be defined for this C{ConsumptionMeasurementPoint}.\n\n Consumption Utilization According to Number of Employees\n --------------------------------------------------------\n\n When C{employees} is set, a consumption utilization according to\n the number of employees graph will be defined for this\n C{ConsumptionMeasurementPoint}.\n\n\n @ivar consumption_graph: The consumption graph of this C{MeasurementPoint}.\n The C{consumption_graph} is a read-only property, and is implicitly created\n upon setting the C{consumption} property.\n\n @ivar consumption: The consumption data series, typically a\n L{LogicalInput}, visualized in the consumption graph.\n\n @ivar rate_graph: The rate graph of this C{MeasurementPoint}. The\n C{rate_graph} is a read-only property, and is implicitly created upon\n setting the C{rate} property.\n\n @ivar rate: The rate data series, typically a L{LogicalInput}, visualized\n in the rate graph.\n\n @ivar cost: The cost data series.\n\n @ivar enable_rate: When true, C{rate} is automatically derived from\n C{consumption}.\n\n @bug: not explicitly setting C{enable_rate} causes existing rate graphs to\n be deleted.\n\n @ivar standard_heating_degree_days: A DataSeries that defines the standard\n heating degree days used in heating degree days corrected consumption.\n\n @ivar heating_degree_days: A DataSeries that defines the actual heating\n degree days used in heating degree days corrected consumption.\n \"\"\"\n\n UTILITY_TYPE_TO_CONSUMPTION_RATE_ROLE = {\n utilitytypes.METER_CHOICES.electricity: DataRoleField.POWER,\n utilitytypes.METER_CHOICES.district_heating: DataRoleField.POWER,\n utilitytypes.METER_CHOICES.gas: DataRoleField.VOLUME_FLOW,\n utilitytypes.METER_CHOICES.water: DataRoleField.VOLUME_FLOW,\n utilitytypes.METER_CHOICES.oil: DataRoleField.VOLUME_FLOW\n }\n\n def __init__(self, *args, **kwargs):\n super(ConsumptionMeasurementPoint, self).__init__(*args, **kwargs)\n self._rate_conversion = None\n self.enable_rate = True\n\n class Meta:\n proxy = True\n verbose_name = _('Consumption measurement point')\n verbose_name_plural = _('Consumption measurement points')\n app_label = 'customers'\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save the various components of this C{MeasurementPoint}\n \"\"\"\n assert self.consumption, \\\n \"A MeasurementPoint must have a consumption DataSeries\"\n assert self.consumption_graph, \\\n \"A MeasurementPoint must have a consumption Graph\"\n\n if self.role is None:\n self.role = Collection.CONSUMPTION_MEASUREMENT_POINT\n\n super(ConsumptionMeasurementPoint, self).save(*args, **kwargs)\n assert self is self.consumption_graph.collection\n\n # Django bug\n self.consumption_graph.collection = self.consumption_graph.collection\n assert self.consumption_graph.collection_id\n\n self.consumption_graph.save()\n\n # Django bug:\n self.consumption.graph = self._consumption.graph\n assert self.consumption.graph_id\n\n self.consumption.save()\n\n if self.enable_rate and self.rate is None:\n self.rate = RateConversion(\n role=self.UTILITY_TYPE_TO_CONSUMPTION_RATE_ROLE[\n self.consumption.utility_type],\n unit=default_unit_for_data_series(\n self.UTILITY_TYPE_TO_CONSUMPTION_RATE_ROLE[\n self.consumption.utility_type],\n self.consumption.utility_type),\n utility_type=self.consumption.utility_type,\n consumption=self.consumption,\n customer=self.customer)\n elif not self.enable_rate and self.rate is not None:\n if self.rate_graph.id:\n self.rate_graph.delete()\n from legacy.display_widgets.models import DashboardWidget\n widgets = DashboardWidget.objects.filter(\n collection=self.id,\n widget_type__in=[\n DashboardWidget.GAUGE, DashboardWidget.RATE_GRAPH])\n widgets.delete()\n self._rate = None\n self.rate_graph = None\n\n if self.co2 and not self.co2_graph.dataseries_set.exists():\n self._co2_graph = Graph.objects.create(\n collection=self,\n role=DataRoleField.CO2)\n self.co2calculation = Co2Calculation.objects.create(\n role=DataRoleField.CO2,\n utility_type=self.consumption.utility_type,\n unit='gram',\n index=self.co2,\n consumption=self.consumption,\n graph=self._co2_graph)\n elif self.co2 and self.co2calculation.index != self.co2:\n self.co2calculation.index = self.co2\n self.co2calculation.save()\n\n if not self.__dict__.get('co2', None) and \\\n self.co2_graph.dataseries_set.exists():\n self.co2_graph.delete()\n\n if self.rate_graph and self.rate:\n if self._rate_conversion:\n self._rate_conversion.save()\n\n # Django bug:\n self.rate_graph.collection = self.rate_graph.collection\n assert self.rate_graph.collection_id\n\n self.rate_graph.save()\n\n # Django bug:\n self.rate.graph = self.rate.graph\n assert self.rate.graph_id\n\n self.rate.save()\n\n ##\n # heating degree days corrected consumption\n ##\n if self.standard_heating_degree_days is not None and\\\n self.heating_degree_days is not None:\n # enable heating degree days corrected consumption\n if self.heating_degree_days_corrected_consumption is None:\n # construct if missing\n heating_degree_days_graph = self.graph_set.create(\n role=DataRoleField.\n HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION)\n assert heating_degree_days_graph.id\n self.heating_degree_days_corrected_consumption = \\\n DegreeDayCorrection(\n graph=heating_degree_days_graph,\n role=DataRoleField.\n HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utility_type=self.utility_type)\n # delegate properties\n assert self.heating_degree_days_corrected_consumption is not None\n self.heating_degree_days_corrected_consumption.\\\n consumption = self.consumption\n self.heating_degree_days_corrected_consumption.\\\n standarddegreedays = self.standard_heating_degree_days\n self.heating_degree_days_corrected_consumption.\\\n degreedays = self.heating_degree_days\n self.heating_degree_days_corrected_consumption.\\\n unit = self.consumption.unit\n self.heating_degree_days_corrected_consumption.save()\n elif self.heating_degree_days_corrected_consumption:\n # disable heating degree days corrected consumption: remove if\n # exists\n assert self.heating_degree_days_corrected_consumption.graph.id\n self.heating_degree_days_corrected_consumption.graph.delete()\n self.heating_degree_days_corrected_consumption = None\n\n ##\n # consumption utilization according to number of employees and\n # consumption utilization according to area\n ##\n for attribute_name, role, unit_extension in \\\n [('employees',\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n 'person^-1*hour^-1'),\n ('area',\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n 'meter^-2*hour^-1')]:\n if getattr(self, attribute_name):\n assert (1 / PhysicalQuantity(1, unit_extension)).\\\n compatible_unit(\n getattr(self, attribute_name).unit + '*hour'), \\\n 'unit_extension: %s, unit: %s' % (\n unit_extension,\n getattr(self, attribute_name).unit + '*hour')\n utilization_unit = '{}*{}'.format(\n self.consumption.unit,\n unit_extension)\n graph = Graph.objects.get_or_create(\n role=role,\n collection=self)[0]\n utilization, created = Utilization.objects.get_or_create(\n customer=self.customer, role=role, graph=graph,\n defaults={\n 'unit': utilization_unit,\n 'consumption': self.consumption,\n 'needs': getattr(self, attribute_name),\n 'utility_type': self.utility_type})\n if not created:\n utilization.unit = utilization_unit\n utilization.consumption = self.consumption\n utilization.needs = getattr(self, attribute_name)\n utilization.utility_type = self.utility_type\n utilization.save()\n else:\n Graph.objects.filter(role=role, collection=self).delete()\n\n def clean(self):\n \"\"\"\n Check heating degree days corrected consumption: either both are\n C{None} or neither can be C{None}.\n \"\"\"\n super(ConsumptionMeasurementPoint, self).clean()\n\n if self.hidden_on_reports_page and self.used_in_report():\n raise ValidationError(\n _(u'You are not allowed to to hide this measurement point '\n 'from reports while it is used in a report'))\n\n if self.consumption:\n self.consumption.subclass_instance.clean()\n\n if bool(self.standard_heating_degree_days is None) ^ \\\n bool(self.heating_degree_days is None):\n raise ValidationError(\n _(u'Both standard heating degree days and heating degree days '\n 'must be set for heating degree days corrected consumption '\n 'to be enabled. To disable, deselect both.'))\n\n @cached_lookup_property\n def area(self):\n utilization = Utilization.objects.get(\n graph__collection=self.id,\n role=DataRoleField.CONSUMPTION_UTILIZATION_AREA)\n return utilization.needs.subclass_instance\n\n @cached_property\n def co2_graph(self):\n try:\n raise_if_none(self.id, Graph.DoesNotExist)\n return self.graph_set.get(role=DataRoleField.CO2)\n except Graph.DoesNotExist:\n return Graph(collection=self, role=DataRoleField.CO2)\n\n @cached_property\n def co2calculation(self):\n try:\n return DataSeries.objects.get(\n graph=self.co2_graph).subclass_instance\n except DataSeries.DoesNotExist:\n return None\n\n @cached_lookup_property\n def co2(self):\n return Co2Calculation.objects.get(\n graph__collection=self.id,\n role=DataRoleField.CO2).index.subclass_instance\n\n @cached_lookup_property\n def employees(self):\n utilization = Utilization.objects.get(\n graph__collection=self.id,\n role=DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES)\n return utilization.needs.subclass_instance\n\n @cached_property\n def consumption_graph(self):\n try:\n raise_if_none(self.id, Graph.DoesNotExist)\n return self.graph_set.get(\n hidden=False,\n role=DataRoleField.CONSUMPTION)\n except Graph.DoesNotExist:\n return Graph(collection=self, role=DataRoleField.CONSUMPTION)\n\n _consumption = None\n\n def _get_consumption(self):\n # ... this property may make sense to use when not a logical input...?\n if not self._consumption and self.consumption_graph.id:\n try:\n self._consumption = self.consumption_graph.\\\n dataseries_set.get().subclass_instance\n except DataSeries.DoesNotExist:\n pass\n return self._consumption\n\n def _set_consumption(self, consumption):\n if self.consumption_graph.id:\n self.consumption_graph.dataseries_set.delete()\n consumption.graph = self.consumption_graph\n self._consumption = consumption\n\n consumption = property(_get_consumption, _set_consumption)\n\n def _get_consumption_input(self):\n if self.consumption is None:\n return None\n return self.consumption.target.subclass_instance\n\n def _set_consumption_input(self, consumption_input):\n if consumption_input is None:\n return\n if not self.consumption:\n self.consumption = Link(\n utility_type=self.utility_type,\n role=DataRoleField.CONSUMPTION,\n unit=consumption_input.unit)\n self._consumption.target = consumption_input\n\n consumption_input = property(\n _get_consumption_input, _set_consumption_input)\n\n @cached_property\n def rate_graph(self):\n try:\n raise_if_none(self.id, Graph.DoesNotExist)\n return self.graph_set.get(\n role__in=self.UTILITY_TYPE_TO_CONSUMPTION_RATE_ROLE.values())\n except Graph.DoesNotExist:\n return Graph(collection=self)\n\n _rate = None\n\n def _get_rate(self):\n if not self._rate and self.rate_graph.id:\n try:\n self._rate = \\\n self.rate_graph.dataseries_set.get().subclass_instance\n except DataSeries.DoesNotExist:\n pass\n return self._rate\n\n def _set_rate(self, data_series):\n assert data_series.role in \\\n self.UTILITY_TYPE_TO_CONSUMPTION_RATE_ROLE.values()\n if self.rate_graph.id:\n self.rate_graph.dataseries_set.all().delete()\n self.rate_graph.role = data_series.role\n data_series.graph = self.rate_graph\n self._rate = data_series\n\n rate = property(_get_rate, _set_rate)\n\n def get_gauge_data_series(self):\n \"\"\"\n This method defines which L{DataSeries} (if any) should be displayed in\n a gauge widget, if any.\n \"\"\"\n return self.rate\n\n @property\n def cost(self):\n try:\n return DataSeries.objects.get(\n graph__collection=self,\n role=DataRoleField.COST).subclass_instance\n except DataSeries.DoesNotExist:\n return None\n\n @cached_property\n def standard_heating_degree_days(self):\n if self.heating_degree_days_corrected_consumption:\n return self.heating_degree_days_corrected_consumption.\\\n standarddegreedays\n else:\n return None\n\n @cached_property\n def heating_degree_days(self):\n if self.heating_degree_days_corrected_consumption:\n return self.heating_degree_days_corrected_consumption.degreedays\n else:\n return None\n\n @cached_lookup_property\n def heating_degree_days_corrected_consumption(self):\n \"\"\"\n Helper property for implementing C{standard_heating_degree_days} and\n C{heating_degree_days} properties.\n \"\"\"\n return DegreeDayCorrection.objects.get(\n graph__collection_id=self.id,\n role=DataRoleField.\n HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION)\n" }, { "alpha_fraction": 0.5823706984519958, "alphanum_fraction": 0.6068722009658813, "avg_line_length": 37.72079849243164, "blob_id": "f1ded26b51dae0104a7de0a9e87d88541781121e", "content_id": "56ca79a64efc88d3039726c547d46e62f64d5040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13591, "license_type": "no_license", "max_line_length": 79, "num_lines": 351, "path": "/gridplatform/tariffs/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom decimal import Decimal\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\nimport pytz\n\nfrom gridplatform import trackuser\nimport gridplatform.customers.models\nimport gridplatform.global_datasources.models\nimport gridplatform.providers.models\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.utils import units\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.datasources.models import RawData\n\nfrom . import forms\nfrom .models import SubscriptionMixin\nfrom .models import EnergyTariff\nfrom .models import VolumeTariff\nfrom .models import FixedPricePeriod\nfrom .models import SpotPricePeriod\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass SpotPricePeriodFormTest(TestCase):\n def setUp(self):\n self.provider = gridplatform.providers.models.Provider.objects.create()\n self.customer = gridplatform.customers.models.Customer.objects.create(\n provider=self.provider,\n timezone='Europe/Copenhagen'\n )\n self.tariff = EnergyTariff.objects.create(\n customer=self.customer,\n name_plain='test tariff'\n )\n self.spotprice = gridplatform.global_datasources.models. \\\n GlobalDataSource.objects.create(\n name='test spot price',\n app_label='nordpool',\n codename='test',\n country='DK',\n unit='currency_dkk*gigawatt^-1*hour^-1',\n )\n\n def test_creation(self):\n with trackuser.replace_selected_customer(self.customer):\n forms.SpotPricePeriodForm(tariff=self.tariff)\n\n def test_spot_price_choices(self):\n with trackuser.replace_selected_customer(self.customer):\n form = forms.SpotPricePeriodForm(tariff=self.tariff)\n spotpricechoices = list(form.fields['spotprice'].choices)\n self.assertTrue(\n any(value == self.spotprice.id\n for value, display in spotpricechoices))\n\n\nclass SubscriptionMock(SubscriptionMixin):\n currency_unit = 'currency_dkk'\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass SubscriptionMixinTest(TestCase):\n def test_time_quantity_monthly(self):\n self.assertEqual(\n SubscriptionMixin.time_quantity(\n SubscriptionMixin.SUBSCRIPTION_PERIODS.monthly),\n PhysicalQuantity(1, 'month'))\n\n def test_time_quantity_quarterly(self):\n self.assertEqual(\n SubscriptionMixin.time_quantity(\n SubscriptionMixin.SUBSCRIPTION_PERIODS.quarterly),\n PhysicalQuantity(1, 'quarteryear'))\n\n def test_time_quantity_year(self):\n self.assertEqual(\n SubscriptionMixin.time_quantity(\n SubscriptionMixin.SUBSCRIPTION_PERIODS.yearly),\n PhysicalQuantity(1, 'year'))\n\n def test_subscription_cost_sum(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n from_timestamp = timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = timezone.localize(datetime.datetime(2015, 1, 1))\n\n subscription = SubscriptionMock(\n subscription_fee=Decimal('1234.5678'),\n subscription_period=(\n SubscriptionMixin.SUBSCRIPTION_PERIODS.quarterly))\n\n self.assertEqual(\n PhysicalQuantity(4) *\n PhysicalQuantity('1234.5678', 'currency_dkk'),\n subscription._subscription_cost_sum(\n from_timestamp,\n to_timestamp))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass EnergyTariffTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n currency_unit='currency_dkk')\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.tariff = EnergyTariff.objects.create(\n customer=self.customer)\n\n def test_unit(self):\n self.assertTrue(PhysicalQuantity.compatible_units(\n self.tariff.unit, 'currency_dkk*joule^-1'))\n self.assertIn(self.tariff.unit, units.UNIT_DISPLAY_NAMES)\n\n def test_subscription_cost_sum_no_periods(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2015, 1, 1))\n\n self.assertIsNone(\n self.tariff.period_set.subscription_cost_sum(\n from_timestamp, to_timestamp))\n\n def test_subscription_cost_sum(self):\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2013, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 1)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.tariff,\n subscription_fee=100,\n subscription_period=SubscriptionMixin.SUBSCRIPTION_PERIODS.yearly)\n\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.tariff,\n subscription_fee=42,\n subscription_period=SubscriptionMixin.SUBSCRIPTION_PERIODS.yearly)\n\n self.assertEqual(\n PhysicalQuantity(142, 'currency_dkk'),\n self.tariff.period_set.subscription_cost_sum(\n self.timezone.localize(datetime.datetime(2012, 1, 1)),\n self.timezone.localize(datetime.datetime(2015, 1, 1))))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VolumeTariffTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n currency_unit='currency_eur')\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.tariff = VolumeTariff.objects.create(\n customer=self.customer)\n\n def test_unit(self):\n self.assertTrue(PhysicalQuantity.compatible_units(\n self.tariff.unit, 'currency_eur*meter^-3'))\n self.assertIn(self.tariff.unit, units.UNIT_DISPLAY_NAMES)\n\n def test_subscription_cost_sum_no_periods(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2015, 1, 1))\n\n self.assertIsNone(\n self.tariff.period_set.subscription_cost_sum(\n from_timestamp, to_timestamp))\n\n def test_subscription_cost_sum(self):\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2013, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 1)),\n value=10,\n unit='currency_eur*meter^-3',\n datasequence=self.tariff,\n subscription_fee=100,\n subscription_period=SubscriptionMixin.SUBSCRIPTION_PERIODS.yearly)\n\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n value=10,\n unit='currency_eur*meter^-3',\n datasequence=self.tariff,\n subscription_fee=42,\n subscription_period=SubscriptionMixin.SUBSCRIPTION_PERIODS.yearly)\n\n self.assertEqual(\n PhysicalQuantity(142, 'currency_eur'),\n self.tariff.period_set.subscription_cost_sum(\n self.timezone.localize(datetime.datetime(2012, 1, 1)),\n self.timezone.localize(datetime.datetime(2015, 1, 1))))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass SpotPricePeriodTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n self.tariff = EnergyTariff.objects.create(\n customer=self.customer)\n\n self.spotprice = gridplatform.global_datasources.models. \\\n GlobalDataSource.objects.create(\n name='test spot price',\n app_label='nordpool',\n codename='test',\n country='DK',\n unit='currency_dkk*gigawatt^-1*hour^-1',\n )\n\n def test_clean_good_units(self):\n period = SpotPricePeriod(\n datasequence=self.tariff,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2015, 1, 1)),\n spotprice=self.spotprice,\n coefficient='123.456',\n unit_for_constant_and_ceiling='currency_dkk*kilowatt^-1*hour^-1',\n constant='123.456',\n ceiling='123.456')\n period.clean()\n\n def test_clean_bad_tariff_unit(self):\n self.tariff.unit = 'currency_dkk*meter^-3'\n self.tariff.save()\n period = SpotPricePeriod(\n datasequence=self.tariff,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2015, 1, 1)),\n spotprice=self.spotprice,\n coefficient='123.456',\n unit_for_constant_and_ceiling='currency_dkk*kilowatt^-1*hour^-1',\n constant='123.456',\n ceiling='123.456')\n with self.assertRaises(ValidationError):\n period.clean()\n\n def test_clean_bad_spot_unit(self):\n self.spotprice.unit = 'currency_dkk*meter^-3'\n self.spotprice.save()\n period = SpotPricePeriod(\n datasequence=self.tariff,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2015, 1, 1)),\n spotprice=self.spotprice,\n coefficient='123.456',\n unit_for_constant_and_ceiling='currency_dkk*kilowatt^-1*hour^-1',\n constant='123.456',\n ceiling='123.456')\n with self.assertRaises(ValidationError):\n period.clean()\n\n def test_value_sequence_with_ceiling(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n SpotPricePeriod.objects.create(\n datasequence=self.tariff,\n from_timestamp=from_timestamp,\n to_timestamp=self.timezone.localize(datetime.datetime(2015, 1, 1)),\n spotprice=self.spotprice,\n subscription_fee=500,\n subscription_period=SpotPricePeriod.SUBSCRIPTION_PERIODS.yearly,\n coefficient=2,\n unit_for_constant_and_ceiling='currency_dkk*kilowatt^-1*hour^-1',\n constant=3,\n ceiling=7)\n\n self.spotprice.rawdata_set.bulk_create(\n [\n RawData(\n datasource=self.spotprice,\n timestamp=from_timestamp + datetime.timedelta(\n hours=h),\n value=1000000 * (h % 10))\n for h in range(12)])\n\n self.assertEqual(\n [\n Sample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(\n min(2 * (h % 10) + 3, 7),\n 'currency_dkk*kilowatt^-1*hour^-1',),\n False, False)\n for h in range(12)\n ],\n list(\n self.tariff.period_set.value_sequence(\n from_timestamp,\n from_timestamp + datetime.timedelta(days=1))))\n\n def test_value_sequence_without_ceiling(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n SpotPricePeriod.objects.create(\n datasequence=self.tariff,\n from_timestamp=from_timestamp,\n to_timestamp=self.timezone.localize(datetime.datetime(2015, 1, 1)),\n spotprice=self.spotprice,\n subscription_fee=500,\n subscription_period=SpotPricePeriod.SUBSCRIPTION_PERIODS.yearly,\n coefficient=2,\n unit_for_constant_and_ceiling='currency_dkk*kilowatt^-1*hour^-1',\n constant=3)\n\n self.spotprice.rawdata_set.bulk_create(\n [\n RawData(\n datasource=self.spotprice,\n timestamp=from_timestamp + datetime.timedelta(\n hours=h),\n value=1000000 * (h % 10))\n for h in range(12)])\n\n self.assertEqual(\n [\n Sample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(\n 2 * (h % 10) + 3,\n 'currency_dkk*kilowatt^-1*hour^-1',),\n False, False)\n for h in range(12)\n ],\n list(\n self.tariff.period_set.value_sequence(\n from_timestamp,\n from_timestamp + datetime.timedelta(days=1))))\n" }, { "alpha_fraction": 0.5663113594055176, "alphanum_fraction": 0.5708544254302979, "avg_line_length": 32.565982818603516, "blob_id": "3559480cb9ae979cf36daec20a6fe3bf9b6f0353", "content_id": "ce9ddcc362bb53f545dc00db30bfbdf25f0464cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11446, "license_type": "no_license", "max_line_length": 114, "num_lines": 341, "path": "/energymanager/led_light_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport calendar\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext_lazy\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom django.db.models.fields import BLANK_CHOICE_DASH\n\nfrom gridplatform.utils import generic_views\nfrom gridplatform.utils import units\nfrom gridplatform.utils.breadcrumbs import Breadcrumb\nfrom gridplatform.utils.breadcrumbs import Breadcrumbs\nfrom gridplatform.utils.views import ChooseCustomerBase\nfrom gridplatform.utils.views import CustomerInKwargsMixin\nfrom gridplatform.utils.views import CustomerListMixin\nfrom gridplatform.utils.views import CustomerViewBase\nfrom gridplatform.utils.views import HomeViewBase\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.utils.forms import YearWeekPeriodForm\nfrom gridplatform.utils.forms import this_week_initial_values\n\n\nfrom energymanager.energy_projects.models import LedLightProject\n\n\nclass HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'led_light_site:dashboard',\n kwargs={'customer_id': customer_id})\n\n def get_choose_customer_url(self):\n return reverse(\n 'led_light_site:choose-customer')\n\n\nclass ChooseCustomer(ChooseCustomerBase):\n template_name = 'led_light_site/choose_customer.html'\n\n\nclass CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'led_light_site:dashboard',\n kwargs={'customer_id': customer_id})\n\n\nclass DashboardDetailView(\n CustomerListMixin, generic_views.DetailView):\n model = Customer\n template_name = \\\n 'led_light_site/dashboard.html'\n\n def get_breadcrumbs(self):\n return (\n (_('Dashboard'), ''),\n )\n\n def get_object(self, queryset=None):\n return self.model.objects.get(pk=self.kwargs['customer_id'])\n\n def get_context_data(self, **kwargs):\n context = super(DashboardDetailView, self).get_context_data(**kwargs)\n\n projects = self.object.ledlightproject_set.all()\n projects_width_savings = []\n\n total_saved = None\n total_previous_price = None\n total_led_price = None\n\n year = int(self.request.GET.get(\n 'year', datetime.datetime.today().year))\n month_number = int(self.request.GET.get(\n 'month_number', datetime.datetime.today().month))\n\n from_time = None\n to_time = None\n\n month_options = (\n '...',\n _('January'),\n _('February'),\n _('March'),\n _('April'),\n _('May'),\n _('June'),\n _('Juli'),\n _('August'),\n _('September'),\n _('October'),\n _('November'),\n _('December'),\n )\n\n if month_number == 0:\n from_time = datetime.datetime(year, 1, 1, 0, 0, 0).replace(tzinfo=self.object.timezone)\n to_time = datetime.datetime(year + 1, 1, 1, 0, 0, 0).replace(tzinfo=self.object.timezone)\n else:\n from_time = datetime.datetime(year, month_number, 1, 0, 0, 0).replace(tzinfo=self.object.timezone)\n to_time = datetime.datetime(\n year, month_number, calendar.monthrange(\n year, month_number)[1], 23, 59, 59).replace(tzinfo=self.object.timezone) + datetime.timedelta(\n seconds=1)\n\n for project in projects:\n previous_price = project.calculated_previous_price(\n from_time=from_time, to_time=to_time)\n\n led_price = project.measured_price(\n from_time=from_time, to_time=to_time)\n\n saved = project.calculate_savings(\n from_time=from_time, to_time=to_time)\n if saved:\n if total_saved:\n total_saved += saved\n total_previous_price += previous_price\n total_led_price += led_price\n else:\n total_previous_price = previous_price\n total_led_price = led_price\n total_saved = saved\n\n projects_width_savings.append({\n 'name': project.name_plain,\n 'saved': saved,\n 'previous_price': previous_price,\n 'led_price': led_price\n })\n else:\n projects_width_savings.append({\n 'name': project.name_plain,\n 'saved': '-',\n 'previous_price': '-',\n 'led_price': '-'\n })\n\n context['year'] = year\n context['month_number'] = month_number\n context['month'] = month_options[month_number]\n context['total_saved'] = total_saved\n context['total_previous_price'] = total_previous_price\n context['total_led_price'] = total_led_price\n context['projects'] = projects_width_savings\n context['chart_form'] = YearWeekPeriodForm(\n this_week_initial_values())\n return context\n\n\nclass DashboardBurnDetailView(\n CustomerListMixin, generic_views.DetailView):\n model = Customer\n template_name = \\\n 'led_light_site/dashboard_burn.html'\n\n def get_breadcrumbs(self):\n return (\n (_('Dashboard Burn Hours'), ''),\n )\n\n def get_object(self, queryset=None):\n return self.model.objects.get(pk=self.kwargs['customer_id'])\n\n def get_context_data(self, **kwargs):\n context = super(\n DashboardBurnDetailView, self).get_context_data(**kwargs)\n\n projects = self.object.ledlightproject_set.all()\n projects_width_savings = []\n\n total_burned = None\n\n year = int(self.request.GET.get(\n 'year', datetime.datetime.today().year))\n month_number = int(self.request.GET.get(\n 'month_number', datetime.datetime.today().month))\n\n from_time = None\n to_time = None\n\n month_options = (\n '...',\n _('January'),\n _('February'),\n _('March'),\n _('April'),\n _('May'),\n _('June'),\n _('Juli'),\n _('August'),\n _('September'),\n _('October'),\n _('November'),\n _('December'),\n )\n\n if month_number == 0:\n from_time = datetime.datetime(year, 1, 1, 0, 0, 0).replace(\n tzinfo=self.object.timezone)\n to_time = datetime.datetime(year + 1, 1, 1, 0, 0, 0).replace(\n tzinfo=self.object.timezone)\n else:\n from_time = datetime.datetime(\n year, month_number, 1, 0, 0, 0).replace(\n tzinfo=self.object.timezone)\n to_time = datetime.datetime(\n year, month_number, calendar.monthrange(\n year, month_number)[1], 23, 59, 59).replace(\n tzinfo=self.object.timezone) + datetime.timedelta(\n seconds=1)\n\n for project in projects:\n burned = project.calculate_burn_hours(\n from_time=from_time, to_time=to_time)\n\n if burned:\n if total_burned:\n total_burned += burned\n else:\n total_burned = burned\n\n projects_width_savings.append({\n 'name': project.name_plain,\n 'burned': burned,\n })\n else:\n projects_width_savings.append({\n 'name': project.name_plain,\n 'burned': '-',\n })\n\n context['year'] = year\n context['month_number'] = month_number\n context['month'] = month_options[month_number]\n context['total_burned'] = total_burned\n context['projects'] = projects_width_savings\n return context\n\n\nclass LedLightProjectList(CustomerListMixin, generic_views.TemplateView):\n template_name = 'led_light_site/led_light_project_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Led Light Projects'),\n reverse(\n 'led_light_site_projects:led-light-project-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass LedLightProjectListContentView(\n CustomerListMixin,\n generic_views.ListView):\n search_fields = ['name_plain', ]\n sort_fields = ['name_plain', ]\n model = LedLightProject\n paginate_by = 100\n template_name = 'led_light_site/_led_light_project_list_content.html'\n\n\nclass LedLightProjectForm(forms.ModelForm):\n\n class Meta:\n model = LedLightProject\n fields = (\n 'name', 'previous_tube_count', 'previous_consumption_per_tube',\n 'led_tube_count', 'led_consumption_per_tube', 'price',\n 'datasource',\n )\n\n\nclass LedLightProjectCreateView(CustomerListMixin,\n generic_views.CreateView):\n model = LedLightProject\n template_name = 'led_light_site/led_light_project_form.html'\n form_class = LedLightProjectForm\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n result = super(LedLightProjectCreateView, self).form_valid(form)\n assert self.object.id\n self._customer.ledlightproject_set.add(self.object)\n return result\n\n def get_success_url(self):\n return reverse('led_light_site_projects:led-light-project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return LedLightProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create LED Light Project'))\n\n\nclass LedLightProjectUpdateView(CustomerListMixin,\n generic_views.UpdateView):\n model = LedLightProject\n template_name = 'led_light_site/led_light_project_form.html'\n form_class = LedLightProjectForm\n\n def get_success_url(self):\n return reverse('led_light_site_projects:led-light-project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_delete_url(self):\n return reverse('led_light_site_projects:led-light-project-delete',\n kwargs={'customer_id':\n self._customer.id,\n 'pk':\n self.object.id})\n\n def get_breadcrumbs(self):\n return LedLightProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n\nclass LedLightProjectDeleteView(\n CustomerListMixin, generic_views.DeleteView):\n model = LedLightProject\n\n def get_success_url(self):\n return reverse('led_light_site_projects:led-light-project-list',\n kwargs={'customer_id':\n self._customer.id})\n" }, { "alpha_fraction": 0.48964256048202515, "alphanum_fraction": 0.4951259195804596, "avg_line_length": 38.391998291015625, "blob_id": "a23ef0e7fff6fa8871340dae0529d712e69e0635", "content_id": "76d73d1e90377f26b1a1bde1533c5fbd7a3666dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4924, "license_type": "no_license", "max_line_length": 153, "num_lines": 125, "path": "/legacy/manage_reports/static/manage_reports.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true */\n/*global $, jQuery, gettext */\n\n\nvar gridportal = window.gridportal || {};\ngridportal.manageReports = gridportal.manageReports || {};\n\n\ngridportal.manageReports.requestReport = function (data, container, startUrl, finalizeUrl, resultElem, statusUrl, spinnerUrl, progressBar, noticeField) {\n // This function now requires a progressbar.\n // Pass on a <div> container with width and height set\n // to 0 pixels, if a progressbar is unwanted.\n 'use strict';\n\n var requestStatus,\n startSpinner = function () {\n resultElem.html('<img src=\"' + spinnerUrl + '\">');\n },\n stopSpinner = function () {\n resultElem.empty();\n },\n hideNoticeField = function () {\n if (typeof(noticeField) !== 'undefined') {\n noticeField.hide();\n }\n },\n showNoticeField = function () {\n if (typeof(noticeField) !== 'undefined') {\n noticeField.show();\n }\n },\n disableCancel = function () {\n container.find('input, checkbox, button:not(.cancel)').removeAttr('disabled');\n container.find('.cancel').attr('disabled', 'disabled');\n },\n startFail = function (xhr) {\n container.find('.errorlist').remove();\n var errorDict = JSON.parse(xhr.responseText);\n jQuery.each(errorDict, function (key, val) {\n container.find('.reportErrors').append('<ul class=\"errorlist\"><li>' + val[0] + '</li></ul>');\n });\n stopSpinner();\n hideNoticeField();\n disableCancel();\n },\n statusFail = function (jqXHR, textStatus) {\n stopSpinner();\n hideNoticeField();\n if (textStatus === 'timeout') {\n gridportal.website.notify(\n 'error',\n gettext(\"Lost contact to the server. Please check your internet connetion.\"),\n false);\n } else {\n gridportal.website.notify('error', gettext(\"Background task failed\"), false);\n }\n disableCancel();\n },\n downloadFile = function (data) {\n var link = $('<a href=\"' + data.url + '\"></a>');\n link.text(data.title);\n stopSpinner();\n hideNoticeField();\n disableCancel();\n window.open(data.url, '_blank');\n },\n finalize = function (taskId) {\n jQuery.post(finalizeUrl, {task_id: taskId}).done(downloadFile).fail(statusFail);\n progressBar.progressbar(\"value\", 100);\n container.find('.cancel').attr('disabled', 'disabled');\n },\n running = function (data) {\n var taskId = data.task_id,\n status = data.status,\n result = data.result,\n procent = 0,\n task_id_element = container.find('.task_id');\n if (task_id_element.val() !== taskId) {\n task_id_element.val(taskId);\n }\n\n progressBar.progressbar({ value: 0 });\n container.find('.errorlist').remove();\n if (taskId) {\n if (status === 'SUCCESS') {\n progressBar.progressbar(\"value\", 80);\n finalize(taskId);\n } else if (status === 'PENDING' || status === 'STARTED' ||\n status === 'RETRY' || (status === 'PROGRESS' && result === undefined)) {\n container.find('input, checkbox, button:not(.cancel)').attr('disabled', 'disabled');\n container.find('.cancel').removeAttr('disabled');\n\n window.setTimeout(jQuery.proxy(requestStatus, {}, data.task_id), 1000);\n } else if (status === 'PROGRESS') {\n procent = result.current / result.total * 100 * 0.8;\n progressBar.progressbar(\"value\", procent);\n window.setTimeout(jQuery.proxy(requestStatus, {}, data.task_id), 1000);\n } else if (status === 'FAILURE') {\n statusFail();\n } else if (status === 'REVOKED') {\n stopSpinner();\n progressBar.progressbar(\"destroy\");\n hideNoticeField();\n disableCancel();\n } else {\n // unknown status\n statusFail();\n }\n } else {\n // no task id\n statusFail();\n }\n };\n requestStatus = function (taskId) {\n jQuery.ajax({\n url: statusUrl,\n data: {task_id: taskId},\n type: 'POST',\n timeout: 30000\n }).done(running).fail(statusFail);\n };\n startSpinner();\n showNoticeField();\n jQuery.post(startUrl, data).done(running).fail(startFail);\n};\n" }, { "alpha_fraction": 0.5599164366722107, "alphanum_fraction": 0.5711244344711304, "avg_line_length": 40.69681930541992, "blob_id": "a66e342738bffb3192299a1ee462823efcf16e54", "content_id": "78db5c66d7fc04b540a695dea965d64e5fa998b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24911, "license_type": "no_license", "max_line_length": 79, "num_lines": 597, "path": "/legacy/energy_use_reports/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom datetime import time\nfrom datetime import timedelta\n\nfrom collections import namedtuple\nfrom operator import attrgetter\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.formats import get_format\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.reports.pdf import generate_pdf\nfrom gridplatform.reports.templatetags.reports import texescape\nfrom gridplatform.reports.views import FinalizeReportView\nfrom gridplatform.reports.views import ReportInfo\nfrom gridplatform.reports.views import StartReportView\nfrom gridplatform.utils import condense\nfrom gridplatform.trackuser import get_customer\n\nfrom .models import EnergyUseReport\nfrom .forms import GenerateEnergyUseReportForm\nfrom .tasks import EnergyUseGraph\nfrom .tasks import EnergyUseReportTask\n\n\ndef flotr2_to_gnuplot(graph_data, output_name,\n # 17.465246375cm appears to be the \\the\\textwidth\n terminal='epslatex color solid size 17.465246375cm,6cm',\n sample_resolution=None):\n \"\"\"\n Translate a flotr2 dictionary to the corresponding gnuplot script.\n\n @param graph_data: The flotr2 dictionary; say output from\n L{Graph.get_graph_data()}.\n\n @param output_name: The name of the plot file generated when running the\n returned gnuplot script. If the terminal parameter is not changed, this\n will usually need to end in C{.tex}.\n\n @param terminal: The C{set terminal} argument to gnuplot. The default\n creates a LaTeX file accompanied with an EPS file in colors and something\n close to text width.\n\n @return: A GNU plot script that can generate a gnu plot file named\n C{output_name}.\n \"\"\"\n result = u'set output \"%s\"\\n' % output_name\n result += u'set terminal %s\\n' % terminal\n\n if sample_resolution:\n # Note that clustered histograms assume that the x-axis is just labels,\n # and not numeric. We use a trick inspired from\n # http://gnuplot-surprising.blogspot.dk/2011/09/\n # plot-histograms-using-boxes.html to do a normal plotting with boxes,\n # but where the boxes are shifted to place them in clusters centered\n # above their numeric x value.\n if sample_resolution == condense.MINUTES:\n resolution = 60\n elif sample_resolution == condense.FIVE_MINUTES:\n resolution = 5 * 60\n elif sample_resolution == condense.HOURS:\n resolution = 60 * 60\n elif sample_resolution == condense.DAYS:\n resolution = 60 * 60 * 24\n elif sample_resolution == condense.MONTHS:\n resolution = 60 * 60 * 24 * 31\n elif sample_resolution == condense.QUARTERS:\n resolution = 60 * 60 * 24 * 365 / 4\n else:\n assert sample_resolution == condense.YEARS\n resolution = 60 * 60 * 24 * 365\n\n bar_datasets = [dataset for dataset in graph_data['data'] if\n 'bars' in dataset]\n\n gap = 1 if len(bar_datasets) > 1 else 0 # only set for clusters\n boxwidth = resolution / (len(bar_datasets) + gap)\n cluster_width = boxwidth * len(bar_datasets)\n\n result += u'set boxwidth %d\\n' % boxwidth\n\n yaxistitle = graph_data['options']['yaxis']['title']\n xaxistitle = graph_data['options']['xaxis']['title']\n\n def replace_production_unit(s, l):\n return s.replace(\n 'production_%s' % l, getattr(\n get_customer(), 'production_%s_unit_plain' % l))\n for letter in ['a', 'b', 'c', 'd', 'e']:\n xaxistitle = replace_production_unit(xaxistitle, letter)\n yaxistitle = replace_production_unit(yaxistitle, letter)\n\n result += u'unset key\\n'\n result += u'set key below\\n'\n result += u'set border 3\\n' # bottom(1) + left(2)\n\n # Hack/workaround: If at least one dataset included has \"much\" data, don't\n # draw borders on bar graphs. Having the threshold at 200 elements\n # appeared to work OK for whatever border width we implicitly have now;\n # might look completely wrong otherwise... For plots displaying multiple\n # datasets, adjusting the appearance of *all* bar charts based on the\n # number if elements in whatever dataset has the most elements (which might\n # not even be/be used as a bar chart) may be problematic --- but \"set\n # style\" appears to be \"global\" per plot in gnuplot; if we want multiple\n # datasets in the same output figure, they are forced to use the same\n # style...\n if any([len(dataset['data']) > 200 for dataset in graph_data['data'] if\n dataset['data']]):\n result += u'set style fill solid noborder\\n'\n else:\n result += u'set style fill solid border -1\\n'\n result += u'set ylabel \"%s\"\\n' % texescape(yaxistitle).replace(\n '\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n result += u'set xlabel \"%s\"\\n' % texescape(xaxistitle).replace(\n '\\\\', '\\\\\\\\').replace('\"', '\\\\\"')\n result += u'set xtic nomirror\\n'\n result += u'set ytic nomirror\\n'\n result += u'set xtics out\\n'\n result += u'set xtic (%s)\\n' % (\n ', '.join(map(lambda x: u'\"{1}\" {0}'.format(*x),\n graph_data['options']['xaxis']['ticks'])))\n\n if graph_data['options']['colors']:\n for i, color in enumerate(graph_data['options']['colors'], start=1):\n result += u'set linetype %d lc rgb \"%s\" lw 1\\n' % (i, color)\n result += u'set linetype cycle %d\\n' % len(\n graph_data['options']['colors'])\n\n def plot_dataset(dataset, index):\n \"\"\"\n Returns plot arguments to plot a given C{dataset} with the given\n C{index}.\n \"\"\"\n if 'lines' in dataset and dataset['lines']['show']:\n return u'\"-\" using 1:2 title \"%s\" with lines' % (\n dataset.get('label', ''))\n elif 'bars' in dataset and dataset['bars']['show']:\n assert sample_resolution is not None\n return u'\"-\" using ($1+%f):2 title \"%s\" with boxes' % (\n index * boxwidth - (cluster_width - boxwidth) / 2.0,\n dataset.get('label', ''))\n else:\n assert False\n\n if any(dataset['data'] for dataset in graph_data['data']):\n # the plot command require at least one argument, and each argument\n # requires some data.\n result += (\n u'plot ' + (\n u', '.join(\n [\n plot_dataset(dataset, i) for\n i, dataset in enumerate(\n dataset_ for dataset_ in graph_data['data'] if\n dataset_)\n if dataset['data']])) +\n u'\\n')\n\n for dataset in graph_data['data']:\n if dataset['data']:\n for sample in dataset['data']:\n result += u'%f %f\\n' % (float(sample[0]), float(sample[1]))\n\n # e means end of graph data.\n result += u'e\\n'\n\n # flushes write buffer\n result += u'set output'\n return result\n\n\nclass ErrorCollector(object):\n \"\"\"\n Collects errors for a specific subjects of distribution.\n \"\"\"\n def __init__(self, errors):\n self.errors = errors\n self.show_pie_chart = True\n self.show = True\n\n def area_negative(self, area):\n \"\"\"\n Tell the C{ErrorCollector} that an area of energy use is negative for\n the particular subject of distribution.\n\n This will prevent the associated pie chart from being displayed.\n \"\"\"\n self.show_pie_chart = False\n\n def accounted_gt_total(self):\n \"\"\"\n Tell the C{ErrorCollector} that we have accounted for a larger quantity\n than the total of this particular subject of distribution.\n\n This will prevent the associated pie chart from being displayed.\n \"\"\"\n\n self.show_pie_chart = False\n\n def total_negative(self):\n \"\"\"\n Tell the C{ErrorCollector} that the total of this particular subject of\n distribution is negative.\n\n This will prevent the associated pie chart from being displayed, as\n well as the entire section about to this subject of distribution.\n \"\"\"\n self.show_pie_chart = False\n self.show = False\n\n\nclass ConsumptionErrorCollector(ErrorCollector):\n \"\"\"\n Collects errors for distribution of consumption.\n \"\"\"\n def area_negative(self, area):\n super(ConsumptionErrorCollector, self).area_negative(area)\n self.errors.append(\n _('Consumption is negative for the area of energy use '\n '{energy_use_area}. This prevents the '\n 'consumption pie chart from being displayed.').\n format(energy_use_area=area))\n\n def accounted_gt_total(self):\n super(ConsumptionErrorCollector, self).accounted_gt_total()\n self.errors.append(\n _('Total consumption for main measurement points is less than '\n 'the total consumption of the areas of energy use in '\n 'current period. No pie chart for consumption will be shown'))\n\n def total_negative(self):\n super(ConsumptionErrorCollector, self).total_negative()\n self.errors.append(\n _('Total consumption is negative. Energy use by consumption is '\n 'excluded from the report'))\n\n\nclass CostErrorCollector(ErrorCollector):\n \"\"\"\n Collects errors for distribution of costs.\n \"\"\"\n\n def area_negative(self, area):\n super(CostErrorCollector, self).area_negative(area)\n self.errors.append(\n _('Costs are negative for the area of energy use '\n '{energy_use_area}. This prevents the '\n 'costs pie chart from being displayed.').\n format(energy_use_area=area))\n\n def accounted_gt_total(self):\n super(CostErrorCollector, self).accounted_gt_total()\n self.errors.append(\n _('Total costs for main measurement points are less than '\n 'the total costs of the areas of energy use in current '\n 'period. No pie chart for costs will be shown.'))\n\n def total_negative(self):\n super(CostErrorCollector, self).total_negative()\n self.errors.append(\n _('Total costs are negative. Energy use by cost is '\n 'excluded from the report'))\n\n\nclass Co2ErrorCollector(ErrorCollector):\n \"\"\"\n Collects errors for distribution of CO2 emissions.\n \"\"\"\n\n def area_negative(self, area):\n super(Co2ErrorCollector, self).area_negative(area)\n self.errors.append(\n _(u'CO₂ emissions are negative for the area of energy use '\n u'{energy_use_area}. This prevents the '\n u'CO₂ emissions pie chart from being displayed.').\n format(energy_use_area=area))\n\n def accounted_gt_total(self):\n super(Co2ErrorCollector, self).accounted_gt_total()\n self.errors.append(\n _(u'Total CO₂ emissions for main measurement points are less '\n u'than the total CO₂ emissions of the areas of energy use '\n u'in current period. No pie chart for CO₂ emissions will '\n u'be shown.'))\n\n def total_negative(self):\n super(Co2ErrorCollector, self).total_negative()\n self.errors.append(\n _(u'Total CO₂ emissions are negative. Energy use by CO₂ emissions '\n u'is excluded from the report'))\n\n\nEnergyUseAreaTuple = namedtuple(\n 'EnergyUseAreaTuple',\n 'name, previous_value, value, percent, change_percent, has_errors,')\nColoredEnergyUseAreaTuple = namedtuple(\n 'ColoredEnergyUseAreaTuple',\n 'name, previous_value, value, percent, change_percent, has_errors, color')\n\n\ndef change_percent(current, previous):\n if previous:\n return (current - previous) * 100.0 / previous\n else:\n return ''\n\n\nclass FinalizeEnergyUseReportView(FinalizeReportView):\n COLOR_SEQUENCE = (\n '3366A4',\n 'A83734',\n '83A440',\n '684C8B',\n '3093AE',\n 'EB9659',\n '9CBEFD',\n 'FD9A99',\n 'D4F89F',\n 'C2ADE2',\n '96E5FD',\n 'FFB579',\n 'A9C8FC',\n 'FCA7A6',\n 'DEFCAD',\n 'CFBBED',\n '8BD8ED',\n 'FFA868',\n 'B2C4E4',\n 'E5B2B1',\n 'D0E3B4',\n 'C5BAD6',\n )\n\n def generate_report(self, data, timestamp):\n \"\"\"\n Implementation of L{FinalizeReportView.generate_report}.\n\n @param data: Output from L{EnergyUseReportTask} Celery task.\n\n @param timestamp: The time the report is being build.\n \"\"\"\n energy_use_report = get_object_or_404(\n EnergyUseReport, id=data['energy_use_report'])\n areas = list(energy_use_report.energyusearea_set.all())\n\n # Creates function suitable for reduce()\n def create_accounter(name, error_collector):\n # Collects accounted consumptions, costs, emissions,...\n def accounter(value_pair, area):\n total_accounted_value, total_accounted_previous_value = \\\n value_pair\n value = data['data'][area.id][name]\n total_accounted_value += value\n total_accounted_previous_value += data['data'][area.id][\n 'previous_%s' % name]\n if data['data'][area.id][name] < 0:\n error_collector.area_negative(area)\n return total_accounted_value, total_accounted_previous_value\n return accounter\n\n def create_tuple_converter(name, total):\n def converter(area):\n return EnergyUseAreaTuple(\n name=area.name_plain,\n previous_value=data['data'][area.id][\n 'previous_%s' % name],\n value=data['data'][area.id][name],\n percent=data['data'][area.id][\n name] * 100.0 / total,\n change_percent=change_percent(\n current=data['data'][area.id][name],\n previous=data['data'][area.id][\n 'previous_%s' % name]),\n has_errors=next((True for x in data['errors'] if\n getattr(x, 'energy_use_area_id', None) ==\n area.id), False))\n return converter\n\n has_main_measurement_points = \\\n energy_use_report.main_measurement_points.exists()\n\n consumption_error_collector = ConsumptionErrorCollector(data['errors'])\n total_accounted_consumption, total_accounted_previous_consumption = \\\n reduce(create_accounter('consumption',\n consumption_error_collector), areas,\n (0, 0))\n if has_main_measurement_points:\n total_consumption = data['total_consumption']\n total_previous_consumption = data['total_previous_consumption']\n else:\n total_consumption = total_accounted_consumption\n total_previous_consumption = total_accounted_previous_consumption\n if total_accounted_consumption > total_consumption:\n consumption_error_collector.accounted_gt_total()\n if total_consumption <= 0:\n consumption_error_collector.total_negative()\n unaccounted_consumption = \\\n total_consumption - total_accounted_consumption\n unaccounted_previous_consumption = \\\n total_previous_consumption - total_accounted_previous_consumption\n\n if total_consumption > 0:\n consumptions = map(\n create_tuple_converter('consumption', total_consumption),\n areas)\n consumptions.append(\n EnergyUseAreaTuple(\n _('Unaccounted Consumption'),\n unaccounted_previous_consumption,\n unaccounted_consumption,\n unaccounted_consumption * 100.0 / total_consumption,\n change_percent=change_percent(\n unaccounted_consumption,\n unaccounted_previous_consumption),\n has_errors=next((True for x in data['errors'] if\n getattr(x, 'energy_use_area_id', None) is\n None), False)))\n consumptions.sort(key=attrgetter('value'), reverse=True)\n else:\n consumption_error_collector.total_negative()\n consumptions = []\n colored_consumptions = [\n ColoredEnergyUseAreaTuple._make(t + ('FFFFFF', )) if\n t.name == _('Unaccounted Consumption') else\n ColoredEnergyUseAreaTuple._make(t + (c, )) for t, c in zip(\n consumptions, self.COLOR_SEQUENCE)]\n\n if data['include_cost']:\n cost_error_collector = CostErrorCollector(data['errors'])\n total_accounted_cost, total_accounted_previous_cost = reduce(\n create_accounter('cost', cost_error_collector),\n areas, (0, 0))\n if has_main_measurement_points:\n total_cost = data['total_cost']\n total_previous_cost = data['total_previous_cost']\n else:\n total_cost = total_accounted_cost\n total_previous_cost = total_accounted_previous_cost\n unaccounted_cost = total_cost - total_accounted_cost\n unaccounted_previous_cost = \\\n total_previous_cost - total_accounted_previous_cost\n if total_accounted_cost > total_cost:\n cost_error_collector.accounted_gt_total()\n if total_cost <= 0:\n cost_error_collector.total_negative()\n colored_costs = []\n else:\n costs = map(create_tuple_converter('cost', total_cost), areas)\n costs.append(\n EnergyUseAreaTuple(\n _('Unaccounted Cost'),\n unaccounted_previous_cost,\n unaccounted_cost,\n unaccounted_cost * 100.0 / total_cost,\n change_percent=change_percent(\n unaccounted_cost,\n unaccounted_previous_cost),\n has_errors=next(\n (True for x in data['errors'] if\n getattr(x, 'energy_use_area_id', None) is\n None), False)))\n costs.sort(key=attrgetter('value'), reverse=True)\n colored_costs = [\n ColoredEnergyUseAreaTuple._make(t + ('FFFFFF', )) if\n t.name == _('Unaccounted Cost') else\n ColoredEnergyUseAreaTuple._make(t + (c, )) for t, c in zip(\n costs, self.COLOR_SEQUENCE)]\n\n if data['include_co2']:\n co2_error_collector = Co2ErrorCollector(data['errors'])\n total_accounted_co2, total_accounted_previous_co2 = reduce(\n create_accounter('co2', co2_error_collector),\n areas, (0, 0))\n if has_main_measurement_points:\n total_co2 = data['total_co2']\n total_previous_co2 = data['total_previous_co2']\n else:\n total_co2 = total_accounted_co2\n total_previous_co2 = total_accounted_previous_co2\n unaccounted_co2 = total_co2 - total_accounted_co2\n unaccounted_previous_co2 = total_previous_co2 - \\\n total_accounted_previous_co2\n if total_accounted_co2 > total_co2:\n co2_error_collector.accounted_gt_total()\n if total_co2 <= 0:\n co2_error_collector.total_negative()\n colored_co2 = []\n else:\n co2 = map(create_tuple_converter('co2', total_co2), areas)\n co2.append(\n EnergyUseAreaTuple(\n _(u'Unaccounted CO₂ Emissions'),\n unaccounted_previous_co2,\n unaccounted_co2,\n unaccounted_co2 * 100.0 / total_co2,\n change_percent=change_percent(\n unaccounted_co2,\n unaccounted_previous_co2),\n has_errors=next(\n (True for x in data['errors'] if\n getattr(x, 'energy_use_area_id', None) is\n None), False)))\n co2.sort(key=attrgetter('value'), reverse=True)\n colored_co2 = [\n ColoredEnergyUseAreaTuple._make(t + ('FFFFFF', )) if\n t.name == _(u'Unaccounted CO₂ Emissions') else\n ColoredEnergyUseAreaTuple._make(t + (c, )) for t, c in zip(\n co2, self.COLOR_SEQUENCE)]\n\n from_timestamp = energy_use_report.customer.timezone.localize(\n datetime.combine(data['from_date'], time(0, 0)))\n to_timestamp = energy_use_report.customer.timezone.localize(\n datetime.combine(data['to_date'] + timedelta(days=1), time(0, 0)))\n sample_resolution = EnergyUseGraph.get_sample_resolution(\n from_timestamp, to_timestamp)\n\n generate_pdf_data = {\n 'show_consumption_pie_chart': (\n consumption_error_collector.show_pie_chart),\n 'colored_consumptions': colored_consumptions,\n 'total_consumption': total_consumption,\n 'total_consumption_change_percent': change_percent(\n total_consumption, total_previous_consumption),\n 'total_previous_consumption': total_previous_consumption,\n 'energy_use_report': energy_use_report,\n 'from_date': data['from_date'],\n 'to_date': data['to_date'],\n 'previous_from_date': data['previous_from_date'],\n 'previous_to_date': data['previous_to_date'],\n 'errors': data['errors'],\n 'graph_data': data['graph_data'],\n 'DECIMAL_SEPARATOR': get_format('DECIMAL_SEPARATOR'),\n 'THOUSAND_SEPARATOR': get_format('THOUSAND_SEPARATOR'),\n 'include_co2': data['include_co2'],\n }\n\n if data['include_cost']:\n generate_pdf_data['show_cost_pie_chart'] = \\\n cost_error_collector.show_pie_chart,\n generate_pdf_data['colored_costs'] = colored_costs\n generate_pdf_data['total_cost'] = total_cost\n generate_pdf_data['total_cost_change_percent'] = \\\n change_percent(total_cost, total_previous_cost)\n generate_pdf_data['total_previous_cost'] = total_previous_cost\n\n if data['include_co2']:\n generate_pdf_data['show_co2_pie_chart'] = \\\n co2_error_collector.show_pie_chart\n generate_pdf_data['colored_co2'] = colored_co2\n generate_pdf_data['total_co2'] = total_co2\n generate_pdf_data['total_co2_change_percent'] = \\\n change_percent(total_co2, total_previous_co2)\n generate_pdf_data['total_previous_co2'] = total_previous_co2\n\n gnuplots = [\n flotr2_to_gnuplot(\n data['graph_data'], 'consumption.tex',\n sample_resolution=sample_resolution)]\n\n if data['include_co2']:\n gnuplots.append(\n flotr2_to_gnuplot(\n data['co2_graph_data'],\n 'co2-emission.tex',\n sample_resolution=sample_resolution))\n\n return ReportInfo(\n '{}.pdf'.format(\n energy_use_report.title_plain.encode('ascii', 'ignore')),\n 'application/pdf',\n generate_pdf(\n template='energy_use_reports/report.tex',\n data=generate_pdf_data,\n title=energy_use_report.get_utility_type_report_name(),\n report_type='energy_use_report',\n customer=energy_use_report.customer,\n gnuplots=gnuplots))\n\n\nclass StartEnergyUseReportView(StartReportView):\n form_class = GenerateEnergyUseReportForm\n task = EnergyUseReportTask\n\n def get_task_data(self, form):\n data = form.cleaned_data\n return {\n 'energy_use_report_id': data['energy_use_report'].id,\n 'from_date': data['from_date'],\n 'to_date': data['to_date'],\n 'previous_period_from_date': data['previous_period_from_date'],\n 'previous_period_to_date': data['previous_period_to_date'],\n 'include_cost': data['include_cost'],\n 'include_co2': data['include_co2'],\n }\n" }, { "alpha_fraction": 0.5789257287979126, "alphanum_fraction": 0.5816011428833008, "avg_line_length": 30.147436141967773, "blob_id": "e7ebfa2ff1cceeca5e2103260f4bb987f151a604", "content_id": "f82f198a0ccb99209c4bf84fda83ade9a77f2456", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4859, "license_type": "no_license", "max_line_length": 77, "num_lines": 156, "path": "/legacy/setup_agents/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.shortcuts import get_object_or_404\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext as _\nfrom django.db.models.fields import BLANK_CHOICE_DASH\n\nfrom gridplatform.utils.views import (\n render_to,\n json_response,\n json_list_options,\n)\nfrom gridplatform.users.decorators import admin_or_error\nfrom legacy.devices.models import Agent, SoftwareImage\nfrom legacy.ipc import agentserver\n\n\n@admin_or_error\n@json_response\ndef agent_list_json(request):\n options = json_list_options(request)\n data = list(Agent.objects.select_related(\n 'location', 'customer', 'customer'))\n if options['search']:\n data = filter(\n lambda agent: agent.satisfies_search(options['search']), data)\n order_map = {\n 'location': lambda agent: unicode(agent.location),\n 'mac': lambda agent: unicode(agent.mac),\n 'customer': lambda agent: (\n (agent.customer and unicode(agent.customer)) or '')\n }\n if options['order_by'] and options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'setup_agents/agent_block.html', {'agent': agent},\n RequestContext(request))\n for agent in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass AgentForm(forms.ModelForm):\n class Meta:\n model = Agent\n fields = ('mac', 'customer')\n\n\nclass UpgradeForm(forms.Form):\n software_image = forms.ChoiceField(\n required=True, choices=BLANK_CHOICE_DASH)\n\n\n@admin_or_error\n@render_to('setup_agents/agent_form.html')\ndef agent_form(request, pk=None):\n if pk:\n instance = get_object_or_404(Agent, pk=pk)\n upgrade_form = UpgradeForm(auto_id=False)\n # the form instance has local copies of the field instances,\n # i.e. modifying is safe\n upgrade_form.fields['software_image'].choices = BLANK_CHOICE_DASH + [\n (image.id, image.get_sw_version_display())\n for image in instance.compatible_software()]\n else:\n instance = None\n upgrade_form = None\n form = AgentForm(instance=instance, auto_id=False)\n return {\n 'form': form,\n 'upgrade_form': upgrade_form,\n 'object': instance,\n 'agent': instance,\n }\n\n\n@admin_or_error\n@json_response\ndef agent_update(request, pk=None):\n if pk:\n instance = get_object_or_404(Agent, pk=pk)\n original_customer = instance.customer\n else:\n instance = None\n original_customer = None\n form = AgentForm(request.POST, instance=instance, auto_id=False)\n if form.is_valid():\n agent = form.save(commit=False)\n if agent.customer != original_customer:\n agent.location = None\n for meter in agent.meter_set.all():\n meter.joined = False\n meter.save()\n agent.save()\n return {\n 'success': True,\n 'statusText': _('The agent has been saved'),\n 'html': render_to_string(\n 'setup_agents/agent_block.html',\n {'agent': agent},\n RequestContext(request)\n ),\n }\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'setup_agents/agent_form.html',\n {\n 'form': form,\n 'object': instance,\n 'agent': instance,\n },\n RequestContext(request)\n ),\n }\n\n\n@admin_or_error\n@json_response\ndef agent_swupgrade(request, pk):\n agent = get_object_or_404(Agent, pk=pk)\n form = UpgradeForm(request.POST, auto_id=False)\n form.fields['software_image'].choices = BLANK_CHOICE_DASH + [\n (image.id, image.get_sw_version_display())\n for image in agent.compatible_software()]\n if form.is_valid():\n if agent.online:\n sw_image = SoftwareImage.objects.get(\n pk=form.cleaned_data['software_image'])\n agentserver.agent_swupdate(agent.mac, sw_image)\n return {\n 'success': True,\n 'statusText': _('Sending software update'),\n }\n else:\n return {\n 'success': False,\n 'statusText': _('Agent currently offline'),\n }\n else:\n return {\n 'success': False,\n 'statusText': _('Invalid version for agent')\n }\n" }, { "alpha_fraction": 0.6326251029968262, "alphanum_fraction": 0.6333104968070984, "avg_line_length": 37.56387710571289, "blob_id": "04f3a70a87b07f4f50c1e9fb6b19cc80bc54f2d4", "content_id": "889d826c0c72bdced1efac3c525de89fc9780f6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8754, "license_type": "no_license", "max_line_length": 79, "num_lines": 227, "path": "/gridplatform/token_auth/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport binascii\nimport mock\nimport os\n\nfrom django.http import HttpRequest\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils.encoding import force_bytes\n\nfrom rest_framework.exceptions import AuthenticationFailed\n\nfrom gridplatform.users.models import User\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform import trackuser\nfrom gridplatform import encryption\nfrom gridplatform.encryption.testutils import encryption_context\n\nfrom .authentication import EncryptionTokenAuthentication\nfrom .models import TOKEN_LENGTH\nfrom .models import HMAC_HEX_LENGTH\nfrom .models import TokenData\nfrom .models import create_token\n\n\nclass TokenDataTestCase(TestCase):\n def setUp(self):\n with encryption_context():\n self.user = User.objects.create_user(\n 'user', 'password',\n user_type=User.CUSTOMER_USER)\n\n def test_create_token_obscures_password(self):\n password = '0123456789abcdef'\n token_string = create_token(self.user, password)\n self.assertNotIn(password, token_string)\n token_bytes = binascii.unhexlify(token_string)\n self.assertNotIn(force_bytes(password), token_bytes)\n\n def test_decode_token(self):\n password = '0123456789abcdef'\n token_string = create_token(self.user, password)\n token_data = TokenData.lookup_token(token_string)\n self.assertEqual(token_data.user_id, self.user.id)\n self.assertEqual(token_data.user, self.user)\n decrypted = token_data.decrypt_password(token_string)\n self.assertEqual(decrypted, password)\n\n def test_user_multiple_tokens(self):\n self.assertEqual(len(TokenData.objects.all()), 0)\n password = '0123456789abcdef'\n token_a = create_token(self.user, password)\n token_b = create_token(self.user, password)\n self.assertEqual(len(TokenData.objects.all()), 1)\n self.assertNotEqual(token_a, token_b)\n decrypted_a = TokenData.lookup_token(token_a).decrypt_password(token_a)\n decrypted_b = TokenData.lookup_token(token_b).decrypt_password(token_b)\n self.assertEqual(decrypted_a, password)\n self.assertEqual(decrypted_b, password)\n\n def test_multiple_users(self):\n with encryption_context():\n other_user = User.objects.create_user(\n 'other_user', 'some_password',\n user_type=User.CUSTOMER_USER)\n self.assertEqual(len(TokenData.objects.all()), 0)\n password_a = '0123456789abcdef'\n password_b = '0123456789abcdef'\n token_a = create_token(self.user, password_a)\n token_b = create_token(other_user, password_b)\n self.assertEqual(len(TokenData.objects.all()), 2)\n self.assertNotEqual(token_a, token_b)\n decrypted_a = TokenData.lookup_token(token_a).decrypt_password(token_a)\n decrypted_b = TokenData.lookup_token(token_b).decrypt_password(token_b)\n self.assertEqual(decrypted_a, password_a)\n self.assertEqual(decrypted_b, password_b)\n\n\n@override_settings(SECURE_PROXY_SSL_HEADER=None)\nclass EncryptionTokenAuthenticationTestCase(TestCase):\n def setUp(self):\n self.unit = EncryptionTokenAuthentication()\n os.environ['HTTPS'] = 'on'\n\n def tearDown(self):\n trackuser._set_user(None)\n trackuser._set_customer(None)\n encryption._set_ephemeral_private_key(None)\n del os.environ['HTTPS']\n\n def test_header_not_https(self):\n os.environ['HTTPS'] = 'off'\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token'\n auth = self.unit.authenticate(request)\n self.assertIsNone(auth)\n # NOTE: \"same\" request, but *with* HTTPS, to demonstrate difference...\n os.environ['HTTPS'] = 'on'\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token'\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_header_missing(self):\n request = HttpRequest()\n auth = self.unit.authenticate(request)\n self.assertIsNone(auth)\n\n def test_header_empty(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = ''\n auth = self.unit.authenticate(request)\n self.assertIsNone(auth)\n\n def test_not_token(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'stuff'\n auth = self.unit.authenticate(request)\n self.assertIsNone(auth)\n\n def test_empty(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token'\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_extra_parts(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token password more'\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_wrong_length(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token tokenstring'\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_non_existing(self):\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = 'Token ' + 'a' * TOKEN_LENGTH\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_user_deactivated(self):\n with encryption_context():\n password = '0123456789abcdef'\n user = User.objects.create_user(\n 'username',\n password,\n user_type=User.CUSTOMER_USER)\n token_string = create_token(user, password)\n user.is_active = False\n user.save()\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = b'Token ' + token_string\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_non_hex(self):\n with encryption_context():\n password = '0123456789abcdef'\n user = User.objects.create_user(\n 'username',\n password,\n user_type=User.CUSTOMER_USER)\n token_string = create_token(user, password)\n broken_token = token_string[:HMAC_HEX_LENGTH] + \\\n (TOKEN_LENGTH - HMAC_HEX_LENGTH) * 'x'\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = b'Token ' + broken_token\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_wrong_password(self):\n with encryption_context():\n password = '0123456789abcdef'\n user = User.objects.create_user(\n 'username',\n password,\n user_type=User.CUSTOMER_USER)\n wrong_password = 'x' + password[1:]\n token_string = create_token(user, wrong_password)\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = b'Token ' + token_string\n with self.assertRaises(AuthenticationFailed):\n self.unit.authenticate(request)\n\n def test_success(self):\n with encryption_context():\n password = '0123456789abcdef'\n user = User.objects.create_user(\n 'username',\n password,\n user_type=User.CUSTOMER_USER)\n token_string = create_token(user, password)\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = b'Token ' + token_string\n auth_user, auth = self.unit.authenticate(request)\n self.assertEqual(auth_user, user)\n\n def test_success_context(self):\n with encryption_context():\n Provider.objects.create()\n customer = Customer()\n customer.save()\n password = '0123456789abcdef'\n user = User.objects.create_user(\n 'username',\n password,\n user_type=User.CUSTOMER_USER,\n customer=customer)\n user.set_password(password)\n user.save()\n token_string = create_token(user, password)\n request = HttpRequest()\n request.META['HTTP_AUTHORIZATION'] = b'Token ' + token_string\n with mock.patch('gridplatform.token_auth.authentication.'\n '_set_ephemeral_private_key') as x:\n auth_user, auth = self.unit.authenticate(request)\n self.assertEqual(user, trackuser.get_user())\n self.assertEqual(customer, trackuser.get_customer())\n x.assert_called_with(user.decrypt_private_key(password))\n" }, { "alpha_fraction": 0.6323757767677307, "alphanum_fraction": 0.6335403919219971, "avg_line_length": 37.44776153564453, "blob_id": "f084bd5d10850c7a7ca87161cb516f58c62b7810", "content_id": "3d5a5b758ad4e6ab72303d78c1de523bc6eed88b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2576, "license_type": "no_license", "max_line_length": 78, "num_lines": 67, "path": "/legacy/energy_use_reports/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.reports.views import is_queue_too_long\n\nfrom .models import EnergyUseReport\n\n\nclass GenerateEnergyUseReportForm(forms.Form):\n \"\"\"\n A C{Form} for generating a particular energy use report.\n\n Such a report is generated from a L{EnergyUseReport} instance,\n C{energy_use_report}, a C{from_date} and a C{to_date}.\n \"\"\"\n energy_use_report = forms.ModelChoiceField(\n queryset=EnergyUseReport.objects.none())\n from_date = forms.DateField()\n to_date = forms.DateField()\n\n previous_period_from_date = forms.DateField()\n previous_period_to_date = forms.DateField()\n\n include_cost = forms.BooleanField(required=False)\n include_co2 = forms.BooleanField(required=False)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Expands the valid choices of L{EnergyUseReport} instances to all those\n available to current customer.\n \"\"\"\n super(GenerateEnergyUseReportForm, self).__init__(*args, **kwargs)\n self.fields['energy_use_report'].queryset = \\\n EnergyUseReport.objects.filter(customer=get_customer())\n\n def clean(self):\n \"\"\"\n Checks that C{from_date} is before C{to_date} if both are set.\n \"\"\"\n super(GenerateEnergyUseReportForm, self).clean()\n if 'from_date' in self.cleaned_data and \\\n 'to_date' in self.cleaned_data and \\\n self.cleaned_data['from_date'] > self.cleaned_data['to_date']:\n raise ValidationError(\n _(u'The start date must be before the end date.'))\n\n if 'previous_period_from_date' in self.cleaned_data and \\\n 'previous_period_to_date' in self.cleaned_data and \\\n (\n self.cleaned_data['previous_period_from_date'] >\n self.cleaned_data['previous_period_to_date']):\n raise ValidationError(\n _('The start date of the previous period must be before '\n 'the end date of the previous period.'))\n\n if is_queue_too_long(\n 4, 'legacy.energy_use_reports.tasks.EnergyUseReportTask'):\n raise ValidationError(\n _(u'Report generation queue is to long,'\n ' please try again later'))\n return self.cleaned_data\n" }, { "alpha_fraction": 0.628664493560791, "alphanum_fraction": 0.628664493560791, "avg_line_length": 11.279999732971191, "blob_id": "2e41e64d792c30c44116b2d0369dd040d4a8c710", "content_id": "8ad528b0a5ccf7d568c3d4f909cf87d98b66be3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 307, "license_type": "no_license", "max_line_length": 45, "num_lines": 25, "path": "/documentation/source/apps/gridplatform/rest.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "****\nREST\n****\n\nSettings\n========\n\n.. automodule:: gridplatform.rest.conf\n\nRouters\n=======\n\n.. automodule:: gridplatform.rest.routers\n :members:\n\nViewsets\n========\n\n.. automodule:: gridplatform.rest.viewsets\n :members:\n\nSerializers\n===========\n.. automodule:: gridplatform.rest.serializers\n :members:\n" }, { "alpha_fraction": 0.7187711000442505, "alphanum_fraction": 0.7221472263336182, "avg_line_length": 31.549449920654297, "blob_id": "ec1dec9245b91ae9b0ea07084ca987122625bec8", "content_id": "a413f3e7832b7f08506dd69e15c9c8eba11c8da0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2962, "license_type": "no_license", "max_line_length": 77, "num_lines": 91, "path": "/gridplatform/productions/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.decorators import link\nimport rest_framework.reverse\n\nfrom gridplatform.datasequences.views import HourlyDataView\nfrom gridplatform.rest.viewsets import NestedMixin\n\nfrom . import models\nfrom . import serializers\n\n\nclass HourlyProductionView(NestedMixin, HourlyDataView):\n method_name = 'development_sequence'\n\n def get(self, request, production_id=None, format=None):\n production = get_object_or_404(models.Production, pk=production_id)\n timezone = production.customer.timezone\n return self._get(request, production, timezone)\n\n\nclass Production(viewsets.ModelViewSet):\n model = models.Production\n serializer_class = serializers.Production\n filter_fields = ('name', 'unit', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyProductionView.as_view()\n return view_fn(request, production_id=pk)\n\n\nclass HourlyProductionGroupView(NestedMixin, HourlyDataView):\n method_name = 'production_sequence'\n\n def get(self, request, production_id=None, format=None):\n production = get_object_or_404(\n models.ProductionGroup, pk=production_id)\n timezone = production.customer.timezone\n return self._get(request, production, timezone)\n\n\nclass ProductionGroup(viewsets.ModelViewSet):\n model = models.ProductionGroup\n serializer_class = serializers.ProductionGroup\n filter_fields = ('name', 'customer')\n\n @link()\n def hourly(self, request, pk=None):\n view_fn = HourlyProductionGroupView.as_view()\n return view_fn(request, production_id=pk)\n\n\nclass ProductionParentMixin(object):\n def create(self, request, *args, **kwargs):\n request.DATA['datasequence'] = rest_framework.reverse.reverse(\n viewname='api:productions:production-detail',\n kwargs={\n 'pk': kwargs.pop('datasequence_id'),\n }\n )\n return super(ProductionParentMixin, self).create(\n request, *args, **kwargs)\n\n\nclass NonpulsePeriod(\n NestedMixin, ProductionParentMixin, viewsets.ModelViewSet):\n model = models.NonpulsePeriod\n serializer_class = serializers.NonpulsePeriod\n\n\nclass PulsePeriod(NestedMixin, ProductionParentMixin, viewsets.ModelViewSet):\n model = models.PulsePeriod\n serializer_class = serializers.PulsePeriod\n\n\nclass SingleValuePeriod(\n NestedMixin, ProductionParentMixin, viewsets.ModelViewSet):\n model = models.SingleValuePeriod\n serializer_class = serializers.SingleValuePeriod\n\n\nclass OfflineTolerance(\n NestedMixin, ProductionParentMixin, viewsets.ModelViewSet):\n model = models.OfflineTolerance\n serializer_class = serializers.OfflineTolerance\n" }, { "alpha_fraction": 0.642816960811615, "alphanum_fraction": 0.6461905837059021, "avg_line_length": 39.65142822265625, "blob_id": "07d8cfed773cc7db491cd6645c9aa5f9d6af37d9", "content_id": "053544ca05dc8580e0f9fa84b544ada5dfc5979b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7118, "license_type": "no_license", "max_line_length": 78, "num_lines": 175, "path": "/legacy/indexes/models/datasourceadapter.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport pytz\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom gridplatform.utils import units\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.datasequences.models import CurrencyUnitMixin\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\n\nfrom .index import Index\n\n\nclass DataSourceIndexAdapter(CurrencyUnitMixin, Index):\n datasource = models.ForeignKey(\n DataSource, limit_choices_to=models.Q(\n unit__in=units.TARIFF_BASE_UNITS +\n units.CO2_CONVERSION_BASE_UNITS))\n\n class Meta:\n verbose_name = _('data source index adapter')\n verbose_name_plural = _('data source index adapters')\n app_label = 'indexes'\n\n sample_resolution = None\n\n def __unicode__(self):\n return '%s (%s)' % (\n self.datasource,\n self.get_preferred_unit_converter().get_display_unit())\n\n def _get_samples(self, from_timestamp, to_timestamp):\n assert self.sample_resolution is not None\n rawdata = self.datasource.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp).order_by(\n 'timestamp').values_list('timestamp', 'value')\n for timestamp, value in rawdata:\n yield self.create_range_sample(\n timestamp,\n timestamp + self.sample_resolution,\n PhysicalQuantity(value, self.datasource.unit))\n\n\nclass DataSourceTariffAdapter(DataSourceIndexAdapter):\n class Meta:\n verbose_name = _('data source tariff adapter')\n verbose_name_plural = _('data source tariff adapters')\n proxy = True\n\n sample_resolution = condense.HOURS\n\n def get_preferred_unit_converter(self):\n ENERGY_TARIFF_UNIT = self.currency_unit + '*kilowatt^-1*hour^-1'\n VOLUME_TARIFF_UNIT = self.currency_unit + '*meter^-3'\n\n if PhysicalQuantity.compatible_units(self.unit, ENERGY_TARIFF_UNIT):\n return PhysicalUnitConverter(ENERGY_TARIFF_UNIT)\n else:\n assert PhysicalQuantity.compatible_units(\n self.unit, VOLUME_TARIFF_UNIT)\n return PhysicalUnitConverter(VOLUME_TARIFF_UNIT)\n\n\nclass DataSourceCo2ConversionAdapter(DataSourceIndexAdapter):\n class Meta:\n verbose_name = _('data source CO₂ conversion adapter')\n verbose_name_plural = _('data source CO₂ conversion adapters')\n proxy = True\n\n sample_resolution = condense.FIVE_MINUTES\n\n\n@receiver(post_save)\ndef autocreate_datasourceadapter(\n sender, instance, created, raw=False, **kwargs):\n if not issubclass(sender, DataSource):\n return\n\n if created and not raw:\n if any(PhysicalQuantity.compatible_units(instance.unit, tariff_unit)\n for tariff_unit in units.ENERGY_TARIFF_BASE_UNITS):\n # create energy tariff adapters\n DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.HEAT_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.\n district_heating)\n\n elif any(PhysicalQuantity.compatible_units(instance.unit, tariff_unit)\n for tariff_unit in units.VOLUME_TARIFF_BASE_UNITS):\n # create volume tariff adapters\n DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.GAS_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas)\n\n DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.OIL_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil)\n\n DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.WATER_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water)\n\n elif PhysicalQuantity.compatible_units(\n instance.unit, units.VOLUME_CO2_CONVERSION_BASE_UNIT):\n # create volume co2 conversion adapters\n DataSourceCo2ConversionAdapter.objects.create(\n data_format=DataSourceCo2ConversionAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas)\n\n DataSourceCo2ConversionAdapter.objects.create(\n data_format=DataSourceCo2ConversionAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil)\n\n elif PhysicalQuantity.compatible_units(\n instance.unit, units.ENERGY_CO2_CONVERSION_BASE_UNIT):\n # create energy co2 conversion adapters\n DataSourceCo2ConversionAdapter.objects.create(\n data_format=DataSourceCo2ConversionAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n DataSourceCo2ConversionAdapter.objects.create(\n data_format=DataSourceCo2ConversionAdapter.DATASOURCEADAPTER,\n datasource=instance,\n unit=instance.unit,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.\n district_heating)\n" }, { "alpha_fraction": 0.5840708017349243, "alphanum_fraction": 0.596238911151886, "avg_line_length": 30.443477630615234, "blob_id": "443d60cbdcd79696ee02d6a5d9f7f470205fc64b", "content_id": "e344995d1c4817da24ef5ab96ad275bfe369f201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3619, "license_type": "no_license", "max_line_length": 79, "num_lines": 115, "path": "/legacy/energinet_co2/parser.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport csv\nimport datetime\nimport itertools\nimport string\nimport pytz\n\n\ndef parse_forecast(lines):\n \"\"\"\n Parse a CO2 forecast file in the format implied by\n \"20130529_CO2prognose.txt\".\n\n @return: A dictionary with entries \"date\" a datetime.date, \"header\" the CSV\n header elements and \"data\" a list of (from_hour, to_hour, value) entries.\n\n @note: The numeric value is apparently grams of CO2 per kWh.\n \"\"\"\n it = iter(lines)\n dateline = next(it).strip()\n date = datetime.datetime.strptime(dateline, '%Y%m%d').date()\n reader = csv.reader(it, delimiter=b';')\n header = tuple(next(reader))\n\n def parse_hour(hour_str):\n return datetime.datetime.strptime(\n hour_str.replace('24:', '00:'),\n '%H:%M').time()\n\n def parse_interval(interval_str):\n from_hour, to_hour = interval_str.split('-')\n return (parse_hour(from_hour), parse_hour(to_hour))\n\n result = [parse_interval(interval) + (int(amount),)\n for interval, amount in reader]\n return {\n 'date': date,\n 'header': header,\n 'data': result,\n }\n\n\ndef parse_online(lines):\n \"\"\"\n Parse an \"online data\" file in the format implied by\n \"20130529_onlinedata.txt\".\n\n @return: A dictionary with \"header\" the CSV header elements and \"data\" a\n list of (timestamp, value, ...) entries.\n\n @note: CO2 is apparently the last column/column 16, with a value in grams\n of CO2 per kWh. (... and header \"CO2 udledning\".)\n \"\"\"\n it = iter(lines)\n\n def line_not_empty(line):\n return line.strip() != b''\n\n # eats up to and including the blank line from iterator\n header_lines = itertools.takewhile(line_not_empty, it)\n # [' 1 Centrale kraftværker DK1', ...] ->\n # {'1': 1 Centrale kraftværker DK1'' ...}\n header_strings = dict([line.strip().split(b' ', 1)\n for line in header_lines])\n\n def strip_elems(elems):\n return map(string.strip, elems)\n\n def drop_empty_last(elems):\n if elems[-1] == b'':\n return elems[:-1]\n else:\n return elems\n\n # non-CSV header lines and blank line already skipped in iterator\n reader = csv.reader(it, delimiter=b';')\n # get rid of extra whitespace inside elements\n reader = itertools.imap(strip_elems, reader)\n # get rid of whitespace after last/handle use of ; as terminator rather\n # than separator\n reader = itertools.imap(drop_empty_last, reader)\n\n header = next(reader)\n\n # Dato og tid ; 1 ; ... ->\n # ['Dato og tid', 'Centrale kraftværker DK1', ...]\n header = (header[0],) + tuple([header_strings[nr] for nr in header[1:]])\n\n timezone = pytz.timezone('Europe/Copenhagen')\n\n def parse_line(line_items):\n try:\n timestamp = timezone.localize(\n datetime.datetime.strptime(line_items[0], '%Y-%m-%d %H:%M'),\n is_dst=True)\n except ValueError:\n # Apparently the non DST timestamps are encoded using N between the\n # hour and minutes instead of : for the single hour that is\n # ambiguous.\n timestamp = timezone.localize(\n datetime.datetime.strptime(\n line_items[0], '%Y-%m-%d %HN%M'),\n is_dst=False)\n data = map(int, line_items[1:])\n return (timestamp,) + tuple(data)\n\n result = [parse_line(line_items) for line_items in reader]\n\n return {\n 'header': header,\n 'data': result,\n }\n" }, { "alpha_fraction": 0.6911596059799194, "alphanum_fraction": 0.6913892030715942, "avg_line_length": 35.29166793823242, "blob_id": "b3b6af39c050fa16bb866770a92a2890705d025f", "content_id": "dbac79e5a2e279df08c5f070d9d72717b005da1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4355, "license_type": "no_license", "max_line_length": 80, "num_lines": 120, "path": "/gridplatform/datasequences/models/piecewiseconstant.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.models import StoredSubclassManager\nfrom gridplatform.utils.samples import RangedSample\n\nfrom .base import DataSequenceBase\nfrom .base import PeriodBase\nfrom .base import PeriodBaseManager\n\n\nclass PiecewiseConstantBase(DataSequenceBase):\n \"\"\"\n :class:`.DataSequenceBase` specialization for sequences of conversion\n :class:`RangedSample`.\n\n :see: :ref:`sequences-of-conversion-ranged-samples`\n \"\"\"\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n\nclass PiecewiseConstantPeriodManagerBase(PeriodBaseManager):\n \"\"\"\n Specialization of :class:`PeriodBaseManager` for\n :class:`.PiecewiseConstantPeriod`, adding\n :meth:`PiecewiseConstantPeriodManagerBase.value_sequence` to reverse\n relations (and unfortunately therefore also to the default manager). See\n :class:`.TariffPeriodManager` for clarification and examples.\n \"\"\"\n use_for_related_fields = True\n\n def value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Returns a sequence of :class:`RangedSamples<RangedSample>` in within the\n given timespan.\n\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n\n :note: specializations may guarantee a particular duration of each\n :class:`RangedSample` yielded.\n \"\"\"\n periods = self.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp')\n\n for period in periods:\n period_from, period_to = period.overlapping(\n from_timestamp, to_timestamp)\n for sample in period._value_sequence(\n period_from, period_to):\n yield sample\n\n\nclass PiecewiseConstantPeriodManager(\n PiecewiseConstantPeriodManagerBase, StoredSubclassManager):\n \"\"\"\n Default manager for :class:`.PiecewiseConstantPeriodBase`. Inherits from\n both :class:`PiecewiseConstantPeriodManagerBase` and\n :class:`.StoredSubclassManager` (because the former must be used for\n reverse relations, and the later can't be used for reverse relations).\n \"\"\"\n pass\n\n\nclass PiecewiseConstantPeriodBase(StoreSubclass, PeriodBase):\n \"\"\"\n :class:`.PeriodBase` specialization for\n :class:`.PiecewiseConstantDataSequenceBase` specializations.\n :class:`.StoreSubclass` has been mixed into this model.\n \"\"\"\n objects = PiecewiseConstantPeriodManager()\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n @virtual\n def _value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Abstract delegate of\n :meth:`.PiecewiseConstantPeriodManagerBase.value_sequence` within\n timespan of this period.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n\nclass FixedPiecewiseConstantPeriodValueSequenceMixin(object):\n \"\"\"\n Mixes\n :meth:`FixedPiecewiseConstantPeriodValueSequenceMixin._value_sequence` into\n a :class:`.PiecewiseConstantPeriodBase` specialization that should give\n only fixed-value samples.\n\n The fixed piecewise constant period models must implement\n ``self._quantity`` which returns a :class:`.PhysicalQuantity`. Also it must\n define ``self.resolution``.\n\n :note: This must be a mixin as opposed to an abstract specialization of\n PiecewiseConstantPeriodBase, to allow for polymorphic periods.\n \"\"\"\n def _value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :meth:`.PiecewiseConstantPeriodBase._value_sequence`\n yielding sequences of conversion ranged samples all having the same\n value, namely that given by ``self._quantity``.\n \"\"\"\n sample_from_timestamp = from_timestamp\n sample_to_timestamp = sample_from_timestamp + self.resolution\n while sample_to_timestamp <= to_timestamp:\n yield RangedSample(\n sample_from_timestamp,\n sample_to_timestamp,\n self._quantity)\n sample_from_timestamp, sample_to_timestamp = \\\n sample_to_timestamp, sample_to_timestamp + self.resolution\n" }, { "alpha_fraction": 0.6809815764427185, "alphanum_fraction": 0.699386477470398, "avg_line_length": 19.375, "blob_id": "4c49ef8af029c9dadeb160642bd0fcb940b5a4ee", "content_id": "c491dd7de43ea24140f86e141c657dcba3b31d35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 43, "num_lines": 8, "path": "/gridagentserver-protocol/setup.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nsetup(\n name='GridAgentServerProtocol',\n version='2.3.0',\n packages=find_packages(),\n)\n" }, { "alpha_fraction": 0.781737208366394, "alphanum_fraction": 0.781737208366394, "avg_line_length": 43.900001525878906, "blob_id": "fc29f4bb3d7ff187c01d9248a2b2ee2c4ef82aa5", "content_id": "05011a1ed6ce71eb85bcc6bba3ac807e0147a011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 449, "license_type": "no_license", "max_line_length": 78, "num_lines": 10, "path": "/documentation/source/apps/gridplatform/customer_datasources.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Customer Data Sources\n=====================\n\nThis app defines :class:`~gridplatform.datasources.models.DataSource` owned by\n:class:`~gridplatform.customers.models.Customer`\n(:class:`~gridplatform.customer_datasources.models.CustomerDataSource`) and\nshared among the :class:`~gridplatform.customers.models.Customer` of that\n:class:`~gridplatform.customers.models.Customer`.\n\n.. autoclass:: gridplatform.customer_datasources.models.CustomerDataSource\n" }, { "alpha_fraction": 0.6868008971214294, "alphanum_fraction": 0.699478030204773, "avg_line_length": 28.15217399597168, "blob_id": "02699607f846a45af6703e0378a1b64fae4b2d4f", "content_id": "97f09310532166728242e69b21ac4571b1bff1e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "no_license", "max_line_length": 91, "num_lines": 46, "path": "/gridplatform/bootstrap/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. py:data:: settings.BOOTSTRAP_THEME\n\n Defaults to 'base'. Templates used by Bootstrap tags in this app are\n loaded from the template path 'bootstrap/<theme>/'. See also\n :meth:`gridplatform.bootstrap.templatetags.bootstrap_tags.BootstrapNode.get_templates`.\n\n.. py:data:: settings.BOOTSTRAP_FORM_LAYOUT\n\n Layout applied by default to forms using\n :func:`gridplatform.bootstrap.templatetags.bootstrap_tags.do_form` (``{%\n form ... %}``) template tag. Must be one of \"horizontal\", \"inline\" and\n \"basic\".\n\nBootstrap uses a grid-layout so that cells in each row take up a total of 12\ncolumns. The following two settings are used to balance these 12 columns\nbetween the label and the input field:\n\n.. py:data:: settings.BOOSTRAP_LABEL_COLUMNS\n\n Defaults to 2.\n\n.. py:data:: settings.BOOSTRAP_INPUT_COLUMNS\n\n Defaults to 10.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\n\nfrom appconf import AppConf\n\n\n__all__ = ['settings', 'BootstrapConf']\n\n\nclass BootstrapConf(AppConf):\n THEME = 'base'\n # Default layout: \"horizontal\", \"inline\", \"basic\"\n FORM_LAYOUT = 'horizontal'\n # Default columns for label [1..12]:\n FORM_LABEL_COLUMNS = 2\n # Default columns for field [1..12]:\n FORM_INPUT_COLUMNS = 10\n" }, { "alpha_fraction": 0.5923224687576294, "alphanum_fraction": 0.6055662035942078, "avg_line_length": 27.94444465637207, "blob_id": "2a3f604ae0e75e558fcca068784a045728149c5a", "content_id": "e5b65005536f59782a149090e42757534cc65096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10440, "license_type": "no_license", "max_line_length": 96, "num_lines": 360, "path": "/gridplatform/utils/units.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module defines physical units as they are to be identified in the code,\nand as they are to be shown to the user.\n\n:note: Not all buckingham units will have defined a user-friendly name\n in this module. And likewise, not all units that get their\n user-friendly name defined in this module are buckingham units; in\n particular celsius. All units that should ever be shown to the\n user must be defined in this module.\n\n:see: :class:`gridplatform.utils.preferredunits.UnitConverter` and its\n subclasses for abstractions related to displaying physical\n quantities with human readable units.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom model_utils import Choices\n\nfrom .unitconversion import PhysicalQuantity\nfrom .unitconversion import UnitParseError\nfrom .unitconversion import register_unit\n\nWATT_POWER_CHOICES = (\n (\"milliwatt\", _('mW')),\n (\"watt\", _('W')),\n (\"kilowatt\", _('kW')),\n (\"megawatt\", _('MW')))\n\nJOULE_PR_HOUR_POWER_CHOICES = (\n (\"millijoule*hour^-1\", _('mJ/h')),\n (\"joule*hour^-1\", _('J/h')),\n (\"kilojoule*hour^-1\", _('kJ/h')),\n (\"megajoule*hour^-1\", _('MJ/h')))\n\nPOWER_CHOICES = WATT_POWER_CHOICES + JOULE_PR_HOUR_POWER_CHOICES\n\nWATT_HOUR_ENERGY_CHOICES = (\n (\"milliwatt*hour\", _('mWh')),\n (\"watt*hour\", _('Wh')),\n (\"kilowatt*hour\", _('kWh')),\n (\"megawatt*hour\", _('MWh')))\n\nJOULE_ENERGY_CHOICES = (\n (\"millijoule\", _('mJ')),\n (\"joule\", _('J')),\n (\"kilojoule\", _('kJ')),\n (\"megajoule\", _('MJ')))\n\nENERGY_CHOICES = WATT_HOUR_ENERGY_CHOICES + JOULE_ENERGY_CHOICES\n\nVOLUME_CHOICES = (\n (\"liter\", _('L')),\n (\"milliliter\", _('mL')),\n (\"meter*meter*meter\", _(u'm³')))\n\nVOLUME_FLOW_CHOICES = (\n (\"liter*second^-1\", _(\"L/s\")),\n (\"liter*minute^-1\", _(\"L/min\")),\n (\"liter*hour^-1\", _(\"L/h\")),\n (\"milliliter*hour^-1\", _(\"mL/h\")),\n (\"meter*meter*meter*second^-1\", _(u\"m³/s\")),\n (\"meter*meter*meter*minute^-1\", _(u\"m³/min\")),\n (\"meter*meter*meter*hour^-1\", _(u\"m³/h\")))\n\n# Be aware buckingham (and any other unit conversion library) does\n# not recognize celsius and fahrenheit as physical units, because\n# neither are basisvectors in a metrical space. In fact, you\n# can't convert celsius to fahrenheit because you don't know if\n# its a relative temperature or an absolute temperature. This\n# always depend on the application.\n#\n# Luckily, these units will raise exceptions if used with\n# Buckingham, so the mistake will be discovered in due time.\nTEMPERATURE_CHOICES = (\n (\"celsius\", _(u\"°C\")),\n (\"fahrenheit\", _(u\"°F\")),\n (\"millikelvin\", _(u\"mK\")),\n (\"kelvin\", _(u\"K\")),\n)\n\nTIME_UNITS = (\n ('second', _('s')),\n ('minute', _('m')),\n ('hour', _('h')),\n)\n\nVOLTAGE_CHOICES = (\n ('volt', _('V')),\n ('millivolt', _('mV')),\n)\n\nCURRENT_CHOICES = (\n ('ampere', _('A')),\n ('milliampere', _('mA')),\n)\n\nENERGY_TARIFF_CHOICES = (\n (\"currency_eur*kilowatt^-1*hour^-1\", _(u\"EUR/kWh\")),\n (\"currency_eur*megawatt^-1*hour^-1\", _(u\"EUR/MWh\")),\n (\"currency_dkk*kilowatt^-1*hour^-1\", _(u\"DKK/kWh\")),\n (\"currency_dkk*megawatt^-1*hour^-1\", _(u\"DKK/MWh\")),\n)\n\nVOLUME_TARIFF_CHOICES = (\n (\"currency_eur*liter^-1\", _(u\"EUR/l\")),\n (\"currency_eur*meter^-3\", _(u\"EUR/m³\")),\n (\"currency_dkk*liter^-1\", _(u\"DKK/l\")),\n (\"currency_dkk*meter^-3\", _(u\"DKK/m³\")),\n)\n\nTARIFF_CHOICES = ENERGY_TARIFF_CHOICES + VOLUME_TARIFF_CHOICES\n\nCOST_COMPENSATION_CHOICES = (\n ('currency_eur*kilowatt^-1*hour^-1', _('EUR/kWh')),\n ('currency_eur*megawatt^-1*hour^-1', _('EUR/MWh')),\n ('currency_dkk*kilowatt^-1*hour^-1', _('DKK/kWh')),\n ('currency_dkk*megawatt^-1*hour^-1', _('DKK/MWh')),\n)\n\nINPUT_CHOICES = POWER_CHOICES + ENERGY_CHOICES + \\\n VOLUME_CHOICES + VOLUME_FLOW_CHOICES + TEMPERATURE_CHOICES + \\\n VOLTAGE_CHOICES + CURRENT_CHOICES\n\nDEGREE_DAYS_CHOICES = (\n ('kelvin*day', _(u'degree days')),)\n\nMISC_INDEX_CHOICES = (\n ('gram*kilowatt^-1*hour^-1', 'g/kWh'),\n ('gram*meter^-3', 'g/m³'),\n ('meter^2', 'm²'),\n ('person', _('Person')),\n ('tonne', _('tonne')),\n ('kilogram', 'kg'),\n)\n\nCURRENCY_CHOICES = (\n ('currency_eur', 'EUR'),\n ('currency_dkk', 'DKK'),\n)\n\nENPI_CHOICES = (\n ('watt*kelvin^-1', 'W/K'),\n)\n\nCO2_CONVERSION_CHOICES = (\n ('gram*kilowatt^-1*hour^-1', 'g/kWh'),\n ('kilogram*kilowatt^-1*hour^-1', 'kg/kWh'),\n ('tonne*megawatt^-1*hour^-1', _('tonne/MWh')),\n\n ('gram*meter^-3', 'g/m³'),\n ('gram*liter^-1', 'g/l'),\n ('kilogram*meter^-3', 'kg/m³'),\n ('kilogram*liter^-1', 'kg/l'),\n)\n\nregister_unit('year', (365, 'day'))\nassert PhysicalQuantity(365, 'day') == PhysicalQuantity(1, 'year')\n\nregister_unit('month', (30, 'day'))\nassert PhysicalQuantity(30, 'day') == PhysicalQuantity(1, 'month')\n\nregister_unit('week', (7, 'day'))\nassert PhysicalQuantity(7, 'day') == PhysicalQuantity(1, 'week')\n\nCONSUMPTION_PER_TIME_CHOICES = (\n ('kilowatt*hour*year^-1', _('kWh/year')),\n ('kilowatt*hour*quarteryear^-1', _('kWh/quarter')),\n ('kilowatt*hour*month^-1', _('kWh/month')),\n ('kilowatt*hour*week^-1', _('kWh/week')),\n ('kilowatt*hour*day^-1', _('kWh/day')),\n ('kilowatt*hour*hour^-1', _('kWh/hour')),\n)\n\nIMPULSE_CHOICE = (\n ('impulse', _('impulse')),\n)\n\nPOWER_FACTOR_CHOICE = (\n ('millinone', ''),\n)\n\nUNIT_CHOICES = INPUT_CHOICES + TARIFF_CHOICES + \\\n DEGREE_DAYS_CHOICES + MISC_INDEX_CHOICES + CURRENCY_CHOICES + \\\n ENPI_CHOICES + CONSUMPTION_PER_TIME_CHOICES + VOLTAGE_CHOICES + \\\n CURRENT_CHOICES + ENERGY_TARIFF_CHOICES + IMPULSE_CHOICE + \\\n POWER_FACTOR_CHOICE + TIME_UNITS\n\npreferred_unit_bases = {}\nfor lst, base in [(POWER_CHOICES, 'millijoule*hour^-1'),\n (ENERGY_CHOICES, 'millijoule'),\n (VOLUME_CHOICES, 'milliliter'),\n (VOLUME_FLOW_CHOICES, 'milliliter*hour^-1')]:\n for unit, string in lst:\n preferred_unit_bases[unit] = base\n\n\nACCUMULATION_BASE_UNITS = [\n 'milliwatt*hour',\n 'milliliter',\n 'gram',\n]\nTIME_BASE_UNITS = [\n 'second',\n]\nIMPULSE_BASE_UNITS = [\n 'impulse',\n]\nNONACCUMULATION_BASE_UNITS = [\n 'milliwatt',\n 'milliliter*hour^-1',\n 'millikelvin',\n 'millivolt',\n 'milliampere',\n 'millibar',\n 'millinone',\n]\nENERGY_PER_VOLUME_BASE_UNITS = [\n 'milliwatt*hour/meter^3',\n]\nENERGY_PER_MASS_BASE_UNITS = [\n 'milliwatt*hour/tonne',\n]\n\nPRODUCTION_UNITS = ['production_%s' % c for c in 'abcde']\n\nENERGY_TARIFF_BASE_UNITS = [\n 'currency_dkk*gigawatt^-1*hour^-1',\n 'currency_eur*gigawatt^-1*hour^-1',\n]\n\nVOLUME_TARIFF_BASE_UNITS = [\n 'millicurrency_eur*meter^-3',\n 'millicurrency_dkk*meter^-3',\n]\n\n\nTARIFF_BASE_UNITS = VOLUME_TARIFF_BASE_UNITS + ENERGY_TARIFF_BASE_UNITS\n\nVOLUME_CO2_CONVERSION_BASE_UNIT = 'gram*meter^-3'\n\nENERGY_CO2_CONVERSION_BASE_UNIT = 'gram*kilowatt^-1*hour^-1'\n\nCO2_CONVERSION_BASE_UNITS = [\n VOLUME_CO2_CONVERSION_BASE_UNIT,\n ENERGY_CO2_CONVERSION_BASE_UNIT\n]\n\nBASE_UNITS = ACCUMULATION_BASE_UNITS + IMPULSE_BASE_UNITS + \\\n NONACCUMULATION_BASE_UNITS + ENERGY_PER_VOLUME_BASE_UNITS + \\\n ENERGY_PER_MASS_BASE_UNITS + TARIFF_BASE_UNITS + CO2_CONVERSION_BASE_UNITS + TIME_BASE_UNITS\n\n# Note: names should not be internationalized. They are supposed to be the\n# prober SI unit names.\nUNIT_DISPLAY_NAMES = {\n 'kilowatt*hour': 'kWh',\n 'watt*hour': 'Wh',\n 'milliwatt*hour': 'mWh',\n 'kilowatt': 'kW',\n 'watt': 'W',\n 'milliwatt': 'mW',\n 'meter*meter*meter': 'm³',\n 'liter': 'L',\n 'milliliter': 'mL',\n 'gram': 'g',\n 'milliliter*hour^-1': 'mL/h',\n 'millikelvin': 'mK',\n 'kelvin': 'K',\n 'volt': 'V',\n 'millivolt': 'mV',\n 'ampere': 'A',\n 'milliampere': 'mA',\n 'kilowatt*hour/meter^3': 'kWh/m³',\n 'watt*hour/meter^3': 'Wh/m³',\n 'milliwatt*hour/meter^3': 'mWh/m³',\n 'joule': 'J',\n # http://en.wikipedia.org/wiki/Tonne#Symbol_and_abbreviations\n 'milliwatt*hour/tonne': 'mWh/t',\n 'currency_eur*gigawatt^-1*hour^-1': 'EUR/GWh',\n 'currency_eur*kilowatt^-1*hour^-1': 'EUR/kWh',\n 'currency_eur*megawatt^-1*hour^-1': 'EUR/MWh',\n 'currency_dkk*gigawatt^-1*hour^-1': 'DKK/GWh',\n 'currency_dkk*kilowatt^-1*hour^-1': 'DKK/kWh',\n 'currency_dkk*megawatt^-1*hour^-1': 'DKK/MWh',\n 'millicurrency_dkk*meter^-3': 'DKK/1000m³',\n 'millicurrency_eur*meter^-3': 'EUR/1000m³',\n 'currency_dkk*meter^-3': 'DKK/m³',\n 'currency_eur*meter^-3': 'EUR/m³',\n # Impulse cannot have a proper SI name, so it gets internationalized\n # anyway.\n 'impulse': _('impulse'),\n 'millibar': 'mBar',\n 'gram*kilowatt^-1*hour^-1': 'g/kWh',\n 'gram*meter^-3': 'g/m3',\n 'none': '',\n 'millinone': '',\n 'second': 's',\n 'minute': 'm',\n 'hour': 'h',\n}\nassert set(BASE_UNITS) <= set(UNIT_DISPLAY_NAMES.keys())\n\nACCUMULATION_BASE_UNIT_CHOICES = Choices(*[\n (unit, UNIT_DISPLAY_NAMES[unit])\n for unit in ACCUMULATION_BASE_UNITS\n])\nNONACCUMULATION_BASE_UNIT_CHOICES = Choices(*[\n (unit, UNIT_DISPLAY_NAMES[unit])\n for unit in NONACCUMULATION_BASE_UNITS\n])\nENERGY_PER_VOLUME_BASE_UNIT_CHOICES = Choices(*[\n (unit, UNIT_DISPLAY_NAMES[unit])\n for unit in ENERGY_PER_VOLUME_BASE_UNITS\n])\nENERGY_PER_MASS_BASE_UNIT_CHOICES = Choices(*[\n (unit, UNIT_DISPLAY_NAMES[unit])\n for unit in ENERGY_PER_MASS_BASE_UNITS\n])\nBASE_UNIT_CHOICES = Choices(*[\n (unit, UNIT_DISPLAY_NAMES[unit])\n for unit in BASE_UNITS\n])\n\n\nclass _UnitConversionCacheDict(dict):\n \"\"\"\n unit string -> base unit string mapping; populated on use.\n \"\"\"\n\n def __missing__(self, key):\n \"\"\"\n Try to find compatible base unit when queried for unknown/uncached key.\n \"\"\"\n try:\n for base_unit in BASE_UNITS:\n if PhysicalQuantity.compatible_units(base_unit, key):\n self[key] = base_unit\n return base_unit\n except UnitParseError:\n # not a valid unit string (we assume base units to be valid)\n raise KeyError(key)\n # not compatible with any known base unit\n raise KeyError(key)\n\n def __contains__(self, item):\n \"\"\"\n Auto-populate also on `in` and `not in` checks. (This allows cleaner\n code in serializer validation for units.)\n \"\"\"\n try:\n self[item]\n return True\n except KeyError:\n return False\n\n\nunit_conversion_map = _UnitConversionCacheDict()\n" }, { "alpha_fraction": 0.692414402961731, "alphanum_fraction": 0.6928769946098328, "avg_line_length": 33.870967864990234, "blob_id": "8c82e6f658837cb471fabb28effc542be9aa6f10", "content_id": "90ceb4973dd5c212ba52d2dd70ecbf1a93c0cf5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2162, "license_type": "no_license", "max_line_length": 77, "num_lines": 62, "path": "/legacy/manage_measurementpoints/forms/production.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import ProductionMeasurementPoint\nfrom legacy.measurementpoints.models import Collection\n\nfrom .measurementpointform import MeasurementPointForm\n\nfrom gridplatform.productions.models import Production\n\n\nclass ProductionMeasurementPointForm(MeasurementPointForm):\n \"\"\"\n A C{ProductionMeasurementPointForm} sets properties on a\n L{ProductionMeasurementPoint} that can be both set when creating and when\n updating.\n \"\"\"\n class Meta:\n model = ProductionMeasurementPoint\n fields = ('name', 'parent',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(ProductionMeasurementPointForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n def _get_edit_headline_display(self):\n return _(u'Edit Production Measurement Point')\n\n\nclass InputProductionMeasurementPointForm(ProductionMeasurementPointForm):\n \"\"\"\n An C{InputProductionMeasurementPointForm} is a\n L{TemperatureMeasurementPointForm}, that in addition also sets properties\n that can only be set when creating a L{TemperatureMeasurementPoint}.\n \"\"\"\n input_configuration = forms.ModelChoiceField(\n required=True,\n queryset=Production.objects.none())\n\n class ProxyMeta:\n fields = ('input_configuration', )\n\n def __init__(self, *args, **kwargs):\n super(InputProductionMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['input_configuration'].queryset = \\\n ProductionMeasurementPoint.get_input_configuration_choices()\n\n def _get_new_headline_display(self):\n return _(u'New Production Measurement Point')\n" }, { "alpha_fraction": 0.6215226650238037, "alphanum_fraction": 0.6317716240882874, "avg_line_length": 32.317073822021484, "blob_id": "b354f5b005dace2cad68e2fcdd676fcc113687eb", "content_id": "aa0db0972df0131b3af3a1b516dbc90aa4bfb28d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1366, "license_type": "no_license", "max_line_length": 73, "num_lines": 41, "path": "/gridagentserver/agent_software.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# dry-run example command:\n# ./agent_software.py 3C970E1E8E4E 2.1.0 4.4.0 -v -n\n\nimport argparse\n\nfrom client import normalise_mac, normalise_version, send_message\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('agent', help='target agent (MAC address)')\nparser.add_argument('sw_version', help='software version (n.n.n[extra])')\nparser.add_argument('-m', '--model',\n help='hardware model', default=1)\nparser.add_argument('target_hw_version',\n help='compatible hardware version (n.n.n[extra])')\nparser.add_argument('-v', '--verbose', action='store_true',\n help='increase output verbosity')\nparser.add_argument('-n', '--dry-run', action='store_true',\n help='don\\'t actually send command')\n\n\ndef agent_swupdate(args):\n mac = normalise_mac(args.agent)\n sw_version = normalise_version(args.sw_version)\n hw_model = int(args.model)\n hw_version = normalise_version(args.target_hw_version)\n routing_key = 'agent.%s' % (mac,)\n message = {\n 'command': 'gridagent_software',\n 'agent': mac,\n 'sw_version': sw_version,\n 'hw_model': hw_model,\n 'target_hw_version': hw_version,\n }\n send_message(routing_key, message, args.verbose, args.dry_run)\n\n\nif __name__ == '__main__':\n agent_swupdate(parser.parse_args())\n" }, { "alpha_fraction": 0.6771771907806396, "alphanum_fraction": 0.6786786913871765, "avg_line_length": 23.66666603088379, "blob_id": "5ebea14093f7425ec1ad2294e2c1c2fa4a1e7b90", "content_id": "f73ef6864ed71e244d0e9584a40067108d23aa72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/legacy/website/templatetags/action.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom django.core.urlresolvers import reverse\n\nregister = template.Library()\n\n\[email protected]_tag\ndef action(urlname, instance, *args, **kwargs):\n \"\"\"\n Returnes the url for the action based on wether it's a create or update\n\n @ivar urlname: The name of the view.\n\n @ivar instance: An instance\n\n Usage: {% action 'manage-groups-update' form.instance pk=group.id %}\n \"\"\"\n if instance.id is not None:\n url = reverse(urlname, args=args, kwargs=kwargs)\n else:\n url = reverse(urlname)\n\n return url\n" }, { "alpha_fraction": 0.6477000117301941, "alphanum_fraction": 0.6498801112174988, "avg_line_length": 35.549800872802734, "blob_id": "883c09968ee890fefe4c7b0303838358207cd9e9", "content_id": "126c091f6ff715ebe0e9c51d7fc9d09f0f844949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18348, "license_type": "no_license", "max_line_length": 79, "num_lines": 502, "path": "/legacy/manage_reports/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport base64\nimport contextlib\nimport datetime\nimport operator\nfrom cStringIO import StringIO\nimport gzip\n\nfrom django import forms\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.forms.models import BaseInlineFormSet\nfrom django.forms.models import inlineformset_factory\nfrom django.forms.widgets import CheckboxSelectMultiple\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseForbidden\nfrom django.http.response import HttpResponseRedirectBase\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import redirect\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.http import require_http_methods\n\nimport pytz\nfrom celery.result import AsyncResult\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.energy_use_reports.forms import GenerateEnergyUseReportForm\nfrom legacy.energy_use_reports.models import EnergyUseArea\nfrom legacy.energy_use_reports.models import EnergyUseReport\nfrom legacy.enpi_reports.models import ENPIReport\nfrom legacy.enpi_reports.forms import GenerateENPIReportForm\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.reports.consumption import consumption_csv\nfrom gridplatform.reports.consumption import consumption_pdf\nfrom gridplatform.reports.consumption import extend_consumption_data\nfrom gridplatform.reports.models import Report\nfrom gridplatform.reports.views import FinalizeReportView\nfrom gridplatform.reports.views import ReportInfo\nfrom gridplatform.reports.views import StartReportView\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.users.decorators import auth_or_redirect\nfrom gridplatform.users.decorators import customer_admin_or_admin_or_error\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.iter_ext import flatten\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import render_to\nfrom legacy.display_measurementpoints.views import PeriodForm\nfrom gridplatform.utils.formsets import SurvivingFormsModelFormSetMixin\nfrom .tasks import collect_consumption_data\nfrom .tasks import graphdata_download_task\n\n\nclass HttpResponseTemporaryRedirect(HttpResponseRedirectBase):\n status_code = 307\n\n\nclass GenerateReportForm(forms.Form):\n from_date = forms.DateField()\n to_date = forms.DateField()\n\n collections = forms.ModelMultipleChoiceField(\n # choices=[],\n queryset=Collection.objects.none(),\n required=True,\n widget=CheckboxSelectMultiple)\n\n include_cost = forms.BooleanField(initial=False, required=False)\n\n VALID_ROLES = [\n Collection.CONSUMPTION_GROUP,\n Collection.CONSUMPTION_MEASUREMENT_POINT,\n Collection.GROUP,\n ]\n\n def __init__(self, *args, **kwargs):\n super(GenerateReportForm, self).__init__(*args, **kwargs)\n self.fields['collections'].queryset = Collection.objects.filter(\n role__in=self.VALID_ROLES, hidden_on_reports_page=False)\n\n def get_collections(self):\n \"\"\"\n Returns a list of all the collections for a customer or the ones\n that the current user is restricted to.\n \"\"\"\n root_groups = get_user().userprofile.collections.all()\n if not root_groups:\n root_groups = Collection.objects.root_nodes().filter(\n customer=get_customer())\n collection_root_list = [\n collection_root.get_descendants(include_self=True)\n .filter(role__in=self.VALID_ROLES,\n hidden_on_reports_page=False)\n for collection_root in root_groups]\n return collection_root_list\n\n def clean(self):\n cleaned_data = super(GenerateReportForm, self).clean()\n from_date = cleaned_data.get('from_date')\n to_date = cleaned_data.get('to_date')\n\n if isinstance(from_date, datetime.date) and \\\n isinstance(to_date, datetime.date) and \\\n from_date > to_date:\n raise forms.ValidationError(\n _('From time should be before to time'))\n if not cleaned_data.get('collections'):\n raise forms.ValidationError(\n _('Select at least one measurement point'))\n\n return cleaned_data\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef request_consumption_report(request):\n \"\"\"\n Start the consumption report background task.\n \"\"\"\n customer = get_customer()\n tz = customer.timezone\n form = GenerateReportForm(request.POST)\n if form.is_valid():\n # start celery task, return ID\n collections = form.cleaned_data['collections']\n mp_ids = [collection.id for collection in collections]\n include_cost = form.cleaned_data['include_cost']\n from_date = form.cleaned_data['from_date']\n to_date = form.cleaned_data['to_date']\n from_timestamp = tz.localize(\n datetime.datetime.combine(from_date, datetime.time()))\n to_timestamp = tz.localize(\n datetime.datetime.combine(\n to_date + datetime.timedelta(days=1), datetime.time()))\n async = collect_consumption_data.delay(\n mp_ids, from_timestamp, to_timestamp, from_date, to_date,\n include_cost)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n else:\n return {\n 'form_errors': form.errors,\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef finalize_consumption_report(request):\n task_id = request.POST['task_id']\n async = AsyncResult(task_id)\n assert async.successful()\n collected = async.result\n data = extend_consumption_data(collected)\n errors = collected['errors']\n from_date = collected['from_date']\n to_date = collected['to_date']\n include_degree_days_corrected = collected['include_degree_days_corrected']\n include_cost = collected['include_cost']\n now = datetime.datetime.now(pytz.utc)\n try:\n # we extract the customer from the first Collection\n customer = Collection.objects.get(id=collected['mp_ids'][0]).customer\n except:\n customer = None\n\n pdf = consumption_pdf(\n from_date, to_date, data, include_degree_days_corrected, include_cost,\n customer, errors=errors)\n csv = consumption_csv(\n from_date, to_date, data, include_degree_days_corrected, include_cost)\n pdfreport = Report(\n customer=get_customer(),\n title_plain=unicode(_('Consumption report')),\n generation_time=now,\n data_format=Report.PDF,\n data_plain=base64.encodestring(pdf),\n size=len(pdf))\n pdfreport.save()\n csvreport = Report(\n customer=get_customer(),\n title_plain=unicode(_('Consumption report')),\n generation_time=now,\n data_format=Report.CSV,\n data_plain=base64.encodestring(csv),\n size=len(csv))\n csvreport.save()\n return {\n 'pdf': {\n 'id': pdfreport.id,\n 'title': pdfreport.title_plain,\n 'size': pdfreport.size,\n 'url': reverse(\n 'manage_reports-serve_pdf',\n kwargs={'pdf_id': pdfreport.id, 'title': pdfreport.title_plain}\n ),\n },\n 'csv': {\n 'id': csvreport.id,\n 'title': csvreport.title_plain,\n 'size': csvreport.size,\n 'url': reverse(\n 'manage_reports-serve_csv',\n kwargs={'csv_id': csvreport.id, 'title': csvreport.title_plain}\n )\n }\n }\n\n\n@auth_or_error\ndef serve_pdf(request, pdf_id, title=None):\n report = get_object_or_404(Report, id=pdf_id, data_format=Report.PDF)\n return HttpResponse(base64.decodestring(report.data_plain),\n content_type='application/pdf')\n\n\n@auth_or_error\ndef serve_csv(report, csv_id, title=None):\n report = get_object_or_404(Report, id=csv_id, data_format=Report.CSV)\n return HttpResponse(base64.decodestring(report.data_plain),\n content_type='text/csv')\n\n\n@auth_or_redirect\n@render_to('manage_reports/index.html')\ndef index(request):\n customer = get_customer()\n month = RelativeTimeDelta(months=1)\n\n now = customer.now()\n from_date = (\n condense.floor(now, month, customer.timezone) -\n month).date()\n to_date = condense.floor(\n now, month, customer.timezone).date() - \\\n datetime.timedelta(days=1)\n\n previous_from_date = (\n condense.floor(now, month, customer.timezone) -\n 2 * month).date()\n previous_to_date = from_date - datetime.timedelta(days=1)\n\n energy_use_reports = EnergyUseReport.objects.filter(\n customer=customer).prefetch_related(\n 'energyusearea_set', 'main_measurement_points')\n\n user_groups = get_user().userprofile.collections.all()\n\n if user_groups:\n mp_ids = [group.get_descendants(include_self=True)\n .filter(role__in=Collection.DATA_POINTS)\n .exclude(hidden_on_details_page=True)\n .values_list('id', flat=True)\n for group in user_groups]\n\n mp_ids_flattened = set(flatten(mp_ids))\n\n energy_use_reports = [report for report in energy_use_reports\n if set(report.get_all_measurementpoint_ids())\n .issubset(mp_ids_flattened)]\n energy_use_reports = sorted(\n energy_use_reports, key=operator.attrgetter('title_plain'))\n\n for r in energy_use_reports:\n r.form = GenerateEnergyUseReportForm(\n initial={\n 'energy_use_report': r.id,\n 'from_date': from_date,\n 'to_date': to_date,\n 'previous_period_from_date': previous_from_date,\n 'previous_period_to_date': previous_to_date},\n auto_id=False)\n\n enpi_reports = ENPIReport.objects.filter(\n customer=customer).prefetch_related(\n 'enpiusearea_set')\n for r in enpi_reports:\n r.form = GenerateENPIReportForm(\n initial={\n 'enpi_report': r.id,\n 'from_date': from_date,\n 'to_date': to_date},\n auto_id=False)\n return {\n 'reports': list(energy_use_reports) + list(enpi_reports),\n 'energy_driver_choices': ENPIReport.get_energy_driver_choices(),\n }\n\n\n@auth_or_redirect\n@render_to('manage_reports/generate_report.html')\ndef create_consumption_report(request):\n form = GenerateReportForm()\n return {\n 'form': form,\n 'collections': form.get_collections(),\n 'selected_collections': form['collections'].value,\n }\n\n\nclass EnergyUseReportForm(forms.ModelForm):\n class Meta:\n model = EnergyUseReport\n fields = ('title', 'currency_unit', 'main_measurement_points')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @keyword utility_type: If instance is not given, this keyword argument\n must be given. It should be one of the integer values defined in\n L{utilitytypes.METER_CHOICES}.\n \"\"\"\n utility_type = kwargs.pop('utility_type', None)\n super(EnergyUseReportForm, self).__init__(*args, **kwargs)\n if utility_type is not None and self.instance.utility_type is None:\n self.instance.utility_type = utility_type\n\n self.fields['currency_unit'].initial = get_customer().currency_unit\n self.fields['main_measurement_points'].queryset = \\\n ConsumptionMeasurementPoint.objects.subclass_only().filter(\n customer=get_customer(),\n utility_type=self.instance.utility_type,\n hidden_on_reports_page=False).decrypting_order_by('name')\n\n\nclass EnergyUseAreaForm(forms.ModelForm):\n measurement_points = forms.ModelMultipleChoiceField(\n queryset=ConsumptionMeasurementPoint.objects.none())\n\n class Meta:\n model = EnergyUseArea\n fields = ('name', 'measurement_points')\n localized_fields = '__all__'\n\n\ndef make_base_energy_areay_formset(utility_type):\n class BaseEnergyUseAreaFormSet(SurvivingFormsModelFormSetMixin,\n BaseInlineFormSet):\n def __init__(self, *args, **kwargs):\n self.measurement_point_queryset = ConsumptionMeasurementPoint.\\\n objects.subclass_only().filter(\n customer=get_customer(),\n utility_type=utility_type,\n hidden_on_reports_page=False).decrypting_order_by('name')\n super(BaseEnergyUseAreaFormSet, self).__init__(*args, **kwargs)\n\n def add_fields(self, form, index):\n \"\"\"\n Set sorted options and queryset on all forms, also any\n C{empty_form} created.\n \"\"\"\n super(BaseEnergyUseAreaFormSet, self).add_fields(form, index)\n form.fields['measurement_points'].queryset = \\\n self.measurement_point_queryset\n\n def clean(self):\n super(BaseEnergyUseAreaFormSet, self).clean()\n if any(self.errors):\n return\n\n if not self.surviving_forms():\n raise forms.ValidationError(\n _('Include at least one area of energy use'))\n\n mps = []\n faulty_stuff = []\n for form in self.forms:\n if form.cleaned_data:\n for mp in form.cleaned_data['measurement_points']:\n if mp in mps and unicode(mp) not in faulty_stuff:\n faulty_stuff.append(unicode(mp))\n mps.append(mp)\n if faulty_stuff:\n raise forms.ValidationError(\n _('The following measurement points can '\n 'only be included once: {measurement_points}').\n format(measurement_points=', '.join(faulty_stuff)))\n return BaseEnergyUseAreaFormSet\n\n\n@customer_admin_or_admin_or_error\n@render_to('manage_reports/energy_use_report_form.html')\ndef create_energy_use_report(request, utility_type):\n utility_type_key = getattr(\n utilitytypes.OPTIONAL_METER_CHOICES, utility_type)\n report_form = EnergyUseReportForm(\n request.POST or None, utility_type=utility_type_key)\n AreaFormset = inlineformset_factory(\n EnergyUseReport, EnergyUseArea, form=EnergyUseAreaForm,\n formset=make_base_energy_areay_formset(utility_type_key), extra=1)\n area_formset = AreaFormset(request.POST or None)\n\n if all((report_form.is_valid(), area_formset.is_valid())):\n report_form.instance.utility_type = utility_type_key\n report_instance = report_form.save()\n area_formset = AreaFormset(request.POST, instance=report_instance)\n area_formset.is_valid()\n area_formset.save()\n return redirect('manage_reports-index')\n return {\n 'form': report_form,\n 'area_formset': area_formset,\n }\n\n\n@customer_admin_or_admin_or_error\n@render_to('manage_reports/energy_use_report_form.html')\ndef update_energy_use_report(request, pk):\n instance = get_object_or_404(\n EnergyUseReport, customer=get_customer(), pk=pk)\n report_form = EnergyUseReportForm(request.POST or None, instance=instance)\n\n AreaFormset = inlineformset_factory(\n EnergyUseReport, EnergyUseArea, form=EnergyUseAreaForm,\n formset=make_base_energy_areay_formset(instance.utility_type), extra=1)\n area_formset = AreaFormset(request.POST or None, instance=instance)\n\n if request.method == 'POST':\n if all((report_form.is_valid(), area_formset.is_valid())):\n report_instance = report_form.save()\n area_formset = AreaFormset(request.POST, instance=report_instance)\n area_formset.is_valid()\n area_formset.save()\n return redirect('manage_reports-index')\n return {\n 'form': report_form,\n 'area_formset': area_formset,\n }\n\n\n@require_http_methods([\"POST\"])\n@auth_or_redirect\ndef delete(request):\n \"\"\"\n This method is called from legacy.website.synchroneousDelete.\n The synchroneousDelete function is handling the redirection\n to the appropirate index page.\n \"\"\"\n pk = request.POST.get('pk', None)\n customer = get_customer()\n instance = get_object_or_404(EnergyUseReport, pk=pk)\n if instance.customer != customer:\n return HttpResponseForbidden()\n instance.delete()\n messages.success(request, _('The report has been deleted'))\n return HttpResponse()\n\n\n@require_http_methods([\"POST\"])\n@auth_or_redirect\ndef enpi_delete(request):\n \"\"\"\n This method is called from legacy.website.synchroneousDelete.\n The synchroneousDelete function is handling the redirection\n to the appropirate index page.\n \"\"\"\n pk = request.POST.get('pk', None)\n customer = get_customer()\n print 'here'\n instance = get_object_or_404(ENPIReport, pk=pk)\n if instance.customer != customer:\n return HttpResponseForbidden()\n instance.delete()\n messages.success(request, _('The report has been deleted'))\n return HttpResponse()\n\n\nclass GraphdataDownloadForm(PeriodForm):\n graph = forms.IntegerField()\n\n\nclass StartGraphdataDownloadView(StartReportView):\n form_class = GraphdataDownloadForm\n task = graphdata_download_task\n\n def get_task_data(self, form):\n from_timestamp, to_timestamp = form.get_period()\n return {\n 'graph': form.cleaned_data['graph'],\n 'from_timestamp': from_timestamp,\n 'to_timestamp': to_timestamp,\n }\n\n\nclass FinalizeGraphdataDownloadView(FinalizeReportView):\n def generate_report(self, data, timestamp):\n with contextlib.closing(StringIO(data['gzippedfile'])) as f:\n csvfilename = data['csvfilename']\n gz = gzip.GzipFile(mode='rb', fileobj=f)\n csv = gz.read()\n gz.close()\n return ReportInfo(csvfilename, 'text/csv', csv)\n" }, { "alpha_fraction": 0.5792682766914368, "alphanum_fraction": 0.6006097793579102, "avg_line_length": 32.79393768310547, "blob_id": "e9682069b10ab072809545508be3b08bb47955ea", "content_id": "f7642bfa2d127c853799348f20db74e5dfa6be7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5580, "license_type": "no_license", "max_line_length": 79, "num_lines": 165, "path": "/legacy/measurementpoints/fields.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom south.modelsinspector import add_introspection_rules\n\n\nclass DataRoleField(models.IntegerField):\n \"\"\"\n A C{DataRoleField} holds the role of some data, such as a L{DataSeries} or\n a L{Graph}.\n \"\"\"\n\n CONSUMPTION = 0\n POWER = 1\n # 2 is taken! Scroll down!\n COST = 3\n VOLUME_FLOW = 4\n VOLTAGE = 5\n CURRENT = 6\n FREQUENCY = 7\n MASS = 8\n PRESSURE = 9\n TIME = 10\n STATE = 11\n HEAT_TARIFF = 12\n GAS_TARIFF = 13\n ELECTRICITY_TARIFF = 14\n WATER_TARIFF = 15\n CO2_QUOTIENT = 16\n EMPLOYEES = 17\n CACHE = 18\n # 19 is taken! Scroll down!\n # No, really; scroll down; it's not just 19; the list actually continues...\n #\n # All temperatures can be stored in Kelvin, but unit conversions change\n # depending on the temperature being relative or absolute. Mostly because\n # Celsius and Fahrenheit are bogus units.\n #\n # For relative temperatures: Kelvin == Celsius == (5/9) * Fahrenheit\n RELATIVE_TEMPERATURE = 2 # < must equal 2 for historical reasons.\n #\n # For absolute temperatures: Kelvin == Celsius + 273.15 == (5/9) *\n # (Fahrenheit + 459.67)\n ABSOLUTE_TEMPERATURE = 19\n STANDARD_HEATING_DEGREE_DAYS = 20\n HEATING_DEGREE_DAYS = 21\n HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION = 22\n #\n AREA = 23\n CO2 = 24\n VOLUME = 25 # < if volume consumed, use CONSUMPTION instead.\n MEAN_COOLDOWN_TEMPERATURE = 26 # < relative temp. that is piecewise const.\n OIL_TARIFF = 27\n ENERGY_DRIVER = 28\n PRODUCTION = 29\n REACTIVE_POWER = 30\n REACTIVE_ENERGY = 31\n POWER_FACTOR = 32\n\n HIDDEN = 100\n HIDDEN_ELECTRICITY_TARIFF = 101\n HIDDEN_GAS_TARIFF = 102\n HIDDEN_HEAT_TARIFF = 103\n HIDDEN_WATER_TARIFF = 104\n HIDDEN_OIL_TARIFF = 105\n\n CONSUMPTION_UTILIZATION_EMPLOYEES = 200\n CONSUMPTION_UTILIZATION_AREA = 201\n PRODUCTION_ENPI = 202\n HEAT_LOSS_COEFFICIENT = 203\n\n LINEAR_REGRESSION = 300\n\n EFFICIENCY = 400\n\n CHOICES = (\n (CONSUMPTION, _(u\"Consumption\")),\n (POWER, _(u\"Power\")),\n (REACTIVE_POWER, _(u\"Reactive power\")),\n (REACTIVE_ENERGY, _(u\"Reactive energy\")),\n (POWER_FACTOR, _(u\"Power factor\")),\n (RELATIVE_TEMPERATURE, _(u\"Relative temperature\")),\n (ABSOLUTE_TEMPERATURE, _(u'Absolute temperature')),\n (COST, _(u\"Cost\")),\n (VOLUME, _(u'Volume')),\n (VOLUME_FLOW, _(u\"Volume flow\")),\n (VOLTAGE, _(u\"Voltage\")),\n (CURRENT, _(u\"Current\")),\n (FREQUENCY, _(u\"Frequency\")),\n (MASS, _(u\"Mass\")),\n (PRESSURE, _(u\"Pressure\")),\n (TIME, _(u\"Time\")),\n (STATE, _(u\"State\")),\n (HEAT_TARIFF, _('Heat tariff')),\n (GAS_TARIFF, _('Gas tariff')),\n (ELECTRICITY_TARIFF, _('Electricity tariff')),\n (WATER_TARIFF, _('Water tariff')),\n (CO2_QUOTIENT, _(u'CO₂ quotient')),\n (EMPLOYEES, _('Employees')),\n (CACHE, _('Cached data series')),\n (HIDDEN, _('Hidden data series')),\n (STANDARD_HEATING_DEGREE_DAYS, _('Standard heating degree days')),\n (HEATING_DEGREE_DAYS, _('Heating degree days')),\n (HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n _(u'Heating degree days corrected consumption')),\n (AREA, _('Area')),\n (CO2, _('CO₂')),\n (HIDDEN_ELECTRICITY_TARIFF, _('Hidden electricity tariff')),\n (HIDDEN_GAS_TARIFF, _('Hidden gas tariff')),\n (HIDDEN_HEAT_TARIFF, _('Hidden heat tariff')),\n (HIDDEN_WATER_TARIFF, _('Hidden water tariff')),\n (CONSUMPTION_UTILIZATION_EMPLOYEES,\n _('Consumption utilisation according to number of employees')),\n (CONSUMPTION_UTILIZATION_AREA,\n _('Consumption utilisation according to area')),\n (PRODUCTION_ENPI, _('Production EnPI')),\n (MEAN_COOLDOWN_TEMPERATURE, _(u'Mean cool-down temperature')),\n (OIL_TARIFF, _(u'Oil tariff')),\n (HIDDEN_OIL_TARIFF, _(u'Hidden oil tariff')),\n (LINEAR_REGRESSION, _(u'Linear regression')),\n (ENERGY_DRIVER, _(u'Energy driver')),\n (PRODUCTION, _(u'Production')),\n (HEAT_LOSS_COEFFICIENT, _('Heat loss coefficient')),\n (EFFICIENCY, _('Efficiency')),\n )\n\n TARIFFS = [HEAT_TARIFF, GAS_TARIFF,\n ELECTRICITY_TARIFF, WATER_TARIFF, OIL_TARIFF]\n\n def __init__(self, verbose_name=_(u\"Role\"), choices=CHOICES,\n *args, **kwargs):\n \"\"\"\n Construct a C{DataRoleField} as an C{IntegerField} with certain default\n arguments.\n \"\"\"\n super(DataRoleField, self).__init__(\n verbose_name, *args, choices=choices, **kwargs)\n\n @staticmethod\n def hidden_tariff_for_role(role):\n \"\"\"\n Return hidden tariff role\n\n @param role: DataRoleField tariff role\n \"\"\"\n hidden_tariffs = {\n DataRoleField.ELECTRICITY_TARIFF:\n DataRoleField.HIDDEN_ELECTRICITY_TARIFF,\n DataRoleField.HEAT_TARIFF:\n DataRoleField.HIDDEN_HEAT_TARIFF,\n DataRoleField.GAS_TARIFF:\n DataRoleField.HIDDEN_GAS_TARIFF,\n DataRoleField.WATER_TARIFF:\n DataRoleField.HIDDEN_WATER_TARIFF,\n DataRoleField.OIL_TARIFF:\n DataRoleField.HIDDEN_OIL_TARIFF,\n }\n return hidden_tariffs[role]\n\n\nadd_introspection_rules([], [\n \"^legacy\\.measurementpoints\\.fields\\.DataRoleField\"])\n" }, { "alpha_fraction": 0.5064377784729004, "alphanum_fraction": 0.5236051678657532, "avg_line_length": 25, "blob_id": "60563e2c703393056de0787072ebd4ebbb88e266", "content_id": "42b78c4e7a6348732bd15b08db9580f2502e0b21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 233, "license_type": "no_license", "max_line_length": 37, "num_lines": 9, "path": "/wifiagent/uwsgi.ini", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "[uwsgi]\nchdir = /home/pi/wifiagent\nmodule = wifiagent.wsgi\nhome = /home/pi/ve\nmaster = true\nprocesses = 1\nsocket = /tmp/wifiagent.sock\nvacuum = true\nchmod-socket = 777" }, { "alpha_fraction": 0.6267662048339844, "alphanum_fraction": 0.6282002329826355, "avg_line_length": 32.96704864501953, "blob_id": "c13a29c6244f906ff6f5d983a6737d12a76fd925", "content_id": "051f84be0d2ee9865682a207753a27ba387db3ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23709, "license_type": "no_license", "max_line_length": 91, "num_lines": 698, "path": "/energymanager/configuration_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.functional import cached_property\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.formats import date_format\n\nfrom gridplatform.utils import generic_views\nfrom gridplatform.utils.breadcrumbs import Breadcrumb\nfrom gridplatform.utils.breadcrumbs import Breadcrumbs\nfrom gridplatform.utils.views import ChooseCustomerBase\nfrom gridplatform.utils.views import CustomerInKwargsMixin\nfrom gridplatform.utils.views import CustomerListMixin\nfrom gridplatform.utils.views import CustomerViewBase\nfrom gridplatform.utils.views import HomeViewBase\nfrom gridplatform.consumptions.tasks import consumptions_weekly_utility_task # noqa\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.utils.forms import HalfOpenTimePeriodModelForm\nfrom gridplatform.consumptions.models import NonpulsePeriod\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_TO_DISPLAY_UNIT_MAP # noqa\nfrom gridplatform.utils.views import StartTaskView\nfrom gridplatform.utils.forms import YearWeekPeriodForm\nfrom gridplatform.utils.forms import this_week_initial_values\nfrom gridplatform.utils.views import FinalizeTaskView\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.views import JsonResponse\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom legacy.devices.models import Agent, Meter, PhysicalInput\n\nfrom .forms import MeterModelForm\n\nclass HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': customer_id})\n\n def get_choose_customer_url(self):\n return reverse(\n 'configuration_site:choose-customer')\n\n\nclass ChooseCustomer(ChooseCustomerBase):\n template_name = 'configuration_site/choose_customer.html'\n\n\nclass CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': customer_id})\n\n\nclass CustomerDataSourceList(\n CustomerListMixin, generic_views.TemplateView):\n template_name = 'configuration_site/customer_datasource_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Customer Data Sources'),\n reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass CustomerDataSourceListContentView(\n CustomerListMixin, generic_views.ListView):\n model = CustomerDataSource\n template_name = 'configuration_site/_customer_datasource_list_content.html'\n paginate_by = 40\n sort_fields = ['name_plain', 'unit', 'hardware_id', ]\n search_fields = ['name_plain', 'unit', 'hardware_id', ]\n\n\nclass CustomerDataSourceCreateView(\n CustomerListMixin, generic_views.CreateView):\n model = CustomerDataSource\n template_name = 'configuration_site/customer_datasource_form.html'\n fields = ('name', 'unit', 'hardware_id')\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n return super(CustomerDataSourceCreateView, self).form_valid(\n form)\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return CustomerDataSourceList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create LED Light Project'))\n\n\nclass CustomerDataSourceUpdateView(\n CustomerListMixin, generic_views.UpdateView):\n model = CustomerDataSource\n template_name = 'configuration_site/customer_datasource_form.html'\n fields = (\n 'name', 'hardware_id',\n )\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_delete_url(self):\n if not self.object.rawdata_set.all():\n return reverse('configuration_site:customer-datasource-delete',\n kwargs={'customer_id':\n self._customer.id,\n 'pk':\n self.object.id})\n\n def get_breadcrumbs(self):\n return CustomerDataSourceList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n\nclass CustomerDataSourceDeleteView(\n CustomerListMixin, generic_views.DeleteView):\n model = CustomerDataSource\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:customer-datasource-list',\n kwargs={'customer_id': self._customer.id})\n\n\nclass ConsumptionList(\n CustomerListMixin, generic_views.TemplateView):\n template_name = 'configuration_site/consumption_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Consumptions'),\n reverse(\n 'configuration_site:consumption-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass ConsumptionListContentView(\n CustomerListMixin, generic_views.ListView):\n model = Consumption\n template_name = \\\n 'configuration_site/_consumption_list_content.html'\n paginate_by = 40\n search_fields = ['name', ]\n\n\nclass ChartFormViewMixin(object):\n def get_context_data(self, **kwargs):\n if 'chart_form' not in kwargs:\n kwargs['chart_form'] = YearWeekPeriodForm(\n this_week_initial_values())\n return super(ChartFormViewMixin, self).get_context_data(**kwargs)\n\n\nclass ConsumptionDetailView(\n CustomerListMixin, ChartFormViewMixin, generic_views.DetailView):\n model = Consumption\n template_name = \\\n 'configuration_site/consumption_detail.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id, consumption_id):\n return ConsumptionList.build_breadcrumbs(customer_id) + \\\n Breadcrumb(\n _('Consumption Detail'),\n reverse(\n 'configuration_site:consumption-detail',\n kwargs={'customer_id': customer_id, 'pk': consumption_id}))\n\n def get_context_data(self, **kwargs):\n context = super(\n ConsumptionDetailView,\n self).get_context_data(**kwargs)\n context['panel_title'] = \\\n _('Consumption: %(name)s' % {\n 'name': self.object})\n\n if 'utility_unit' not in kwargs:\n context['utility_unit'] = 'watt*hours'\n\n return context\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id, self.object.id)\n\n\nclass PeriodForm(HalfOpenTimePeriodModelForm):\n class Meta:\n fields = ('datasequence',)\n localized_fields = '__all__'\n\n\nclass PeriodViewMixin(object):\n @cached_property\n def _datasequence(self):\n datasequence_model = self.model._meta.get_field('datasequence').rel.to\n return get_object_or_404(\n datasequence_model, id=self.kwargs['datasequence_id'])\n\n def get_form(self, form_class):\n form = super(PeriodViewMixin, self).get_form(form_class)\n form.instance.datasequence = self._datasequence\n datasource_choices = [\n (ds.id, unicode(ds)) for ds in\n form.fields['datasource'].queryset.all()\n if PhysicalQuantity.compatible_units(\n ds.unit, self._datasequence.unit)\n ]\n datasource_choices.sort(key=operator.itemgetter(1))\n form.fields['datasource'].choices = ((None, '---------'),) + tuple(\n datasource_choices)\n return form\n\n\nclass StartWeekConsumptionUtilityBarChartView(\n CustomerInKwargsMixin, StartTaskView):\n task = consumptions_weekly_utility_task\n finalize_url_name = 'configuration_site:utility-bar-chart-finalize'\n form_class = YearWeekPeriodForm\n\n def get_task_kwargs(self, form):\n from_timestamp, to_timestamp = form.get_timestamps()\n result = {}\n result['consumption_ids'] = [self.kwargs['consumption_id']]\n result['from_timestamp'] = from_timestamp\n result['to_timestamp'] = to_timestamp\n return result\n\n def get_finalize_url(self):\n return reverse(\n self.finalize_url_name,\n kwargs={'customer_id': self._customer.id})\n\n\nclass FinalizeWeekUtilityBarChartView(CustomerInKwargsMixin, FinalizeTaskView):\n def finalize_task(self, task_result):\n unit = ENERGY_UTILITY_TYPE_TO_DISPLAY_UNIT_MAP[\n 2000]\n print unit\n self.unit_converter = PhysicalUnitConverter('watt*hour')\n\n def format_label(timestamp):\n return date_format(\n timestamp.astimezone(self._customer.timezone),\n 'SHORT_DATETIME_FORMAT')\n\n result = {\n 'labels': [],\n 'week_selected': [],\n }\n\n selected_sequence = iter(task_result['week_selected'])\n\n selected = next(selected_sequence, None)\n\n while selected is not None:\n\n result['labels'].append(format_label(selected.from_timestamp))\n result['week_selected'].append(\n float(self.unit_converter.extract_value(\n selected.physical_quantity)))\n selected = next(selected_sequence, None)\n\n return JsonResponse(result)\n\n\nclass ConsumptionNonpulsePeriodForm(PeriodForm):\n class Meta(PeriodForm.Meta):\n model = NonpulsePeriod\n fields = ('datasource',)\n\n\nclass ConsumptionNonpulsePeriodCreateView(\n CustomerListMixin, PeriodViewMixin, generic_views.CreateView):\n model = NonpulsePeriod\n template_name = \\\n 'configuration_site/nonpulseperiod_form.html'\n form_class = ConsumptionNonpulsePeriodForm\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.kwargs['datasequence_id'],\n 'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:consumption-detail',\n kwargs={'pk': self.kwargs['datasequence_id'],\n 'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return ConsumptionDetailView.build_breadcrumbs(\n self._customer.id, self.kwargs['datasequence_id']) + \\\n Breadcrumb(_('Create input period'))\n\n\nclass ConsumptionNonpulsePeriodUpdateView(\n CustomerListMixin, PeriodViewMixin, generic_views.UpdateView):\n model = NonpulsePeriod\n template_name = \\\n 'configuration_site/nonpulseperiod_form.html'\n form_class = ConsumptionNonpulsePeriodForm\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.object.datasequence_id,\n 'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:consumption-detail',\n kwargs={'pk': self.object.datasequence_id,\n 'customer_id': self._customer.id})\n\n def get_delete_url(self):\n return reverse('configuration_site:consumptionnonpulseperiod-delete',\n kwargs={'pk': self.object.id,\n 'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return ConsumptionDetailView.build_breadcrumbs(\n self._customer.id, self.kwargs['datasequence_id']) + \\\n Breadcrumb(_('Edit input period'))\n\n\nclass ConsumptionNonpulsePeriodDeleteView(\n CustomerListMixin, generic_views.DeleteView):\n model = NonpulsePeriod\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.object.datasequence_id,\n 'customer_id': self._customer.id})\n\n\nclass ConsumptionCreateView(\n CustomerListMixin, generic_views.CreateView):\n model = Consumption\n template_name = \\\n 'configuration_site/consumption_form.html'\n fields = ('name', 'unit',)\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.object.id, 'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:consumption-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return ConsumptionList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create Consumption Datasequence'))\n\n\nclass ConsumptionUpdateView(\n CustomerListMixin, generic_views.UpdateView):\n model = Consumption\n template_name = \\\n 'configuration_site/consumption_form.html'\n fields = ('name', )\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.object.id, 'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return (\n (_('Data Sequences'),\n reverse(\n 'configuration_site:consumption-list',\n kwargs={'customer_id': self._customer.id})),\n (self.object,\n reverse(\n 'configuration_site:consumption-detail',\n kwargs={'pk': self.object.id,\n 'customer_id': self._customer.id})),\n (_('Edit consumption data sequence'), ''),\n )\n\n def get_cancel_url(self):\n return reverse('configuration_site:consumption-detail',\n kwargs={'pk': self.object.id,\n 'customer_id': self._customer.id})\n\n def get_delete_url(self):\n return reverse('configuration_site:consumption-delete',\n kwargs={'pk': self.object.id,\n 'customer_id': self._customer.id})\n\n\nclass ConsumptionDeleteView(\n CustomerListMixin, generic_views.DeleteView):\n model = Consumption\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:consumption-list',\n kwargs={'customer_id': self._customer.id})\n\n\nclass TariffList(\n CustomerListMixin, generic_views.TemplateView):\n template_name = 'configuration_site/tariff_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Tariffs'),\n reverse(\n 'configuration_site:tariff-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass TariffListContentView(\n CustomerListMixin, generic_views.ListView):\n model = EnergyTariff\n template_name = \\\n 'configuration_site/_tariff_list_content.html'\n paginate_by = 40\n search_fields = ['name', ]\n\n\nclass TariffCreateView(\n CustomerListMixin, generic_views.CreateView):\n model = EnergyTariff\n template_name = \\\n 'configuration_site/tariff_form.html'\n fields = ('name',)\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:tariff-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:tariff-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return TariffList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create Energy Tariff'))\n\n\nclass TariffUpdateView(\n CustomerListMixin, generic_views.UpdateView):\n model = EnergyTariff\n template_name = \\\n 'configuration_site/tariff_form.html'\n fields = ('name', )\n\n def get_breadcrumbs(self):\n return TariffList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Update Energy Tariff'))\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:tariff-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:tariff-list',\n kwargs={'customer_id': self._customer.id})\n\n\nclass AgentList(\n CustomerListMixin, generic_views.TemplateView):\n template_name = 'configuration_site/agent_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Agents'),\n reverse(\n 'configuration_site:agent-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass AgentListContentView(\n CustomerListMixin, generic_views.ListView):\n model = Agent\n template_name = 'configuration_site/_agent_list_content.html'\n paginate_by = 40\n sort_fields = ['mac', 'location', ]\n search_fields = ['mac', 'location', ]\n\n\nclass AgentCreateView(\n CustomerListMixin, generic_views.CreateView):\n model = Agent\n template_name = \\\n 'configuration_site/agent_form.html'\n fields = ('mac', 'location')\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n return super(AgentCreateView, self).form_valid(\n form)\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:agent-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:agent-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return AgentList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create Agent'))\n\n\nclass AgentUpdateView(\n CustomerListMixin, generic_views.UpdateView):\n model = Agent\n template_name = \\\n 'configuration_site/agent_form.html'\n fields = ('location', )\n\n def get_breadcrumbs(self):\n return AgentList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Update Agent'))\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:agent-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:agent-list',\n kwargs={'customer_id': self._customer.id})\n\n\nclass MeterList(\n CustomerListMixin, generic_views.TemplateView):\n template_name = 'configuration_site/meter_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Meters'),\n reverse(\n 'configuration_site:meter-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass MeterListContentView(\n CustomerListMixin, generic_views.ListView):\n model = Meter\n template_name = 'configuration_site/_meter_list_content.html'\n paginate_by = 40\n sort_fields = ['name', 'connection_type', \"hardware_id\", \"location\"]\n search_fields = ['name', 'connection_type', \"hardware_id\", \"location\"]\n\n\nclass MeterCreateView(\n CustomerListMixin, generic_views.CreateView):\n model = Meter\n template_name = \\\n 'configuration_site/meter_form.html'\n fields = ('name', 'agent', 'connection_type', 'location', 'hardware_id')\n form_class = MeterModelForm\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n form.instance.agent_id = self.request.POST.get('agent')\n form.instance.connection_type = Meter.WIBEEE\n form.instance.manufactoring_id = 0\n\n response = super(MeterCreateView, self).form_valid(form)\n meter = form.instance\n meter_type = int(self.request.POST.get('meter_type'))\n if meter_type == MeterModelForm.WIBEEE:\n PhysicalInput.objects.create(\n meter=meter,\n order=0,\n hardware_id=\"e1\",\n name_plain=\"Energy Phase 1\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n PhysicalInput.objects.create(\n meter=meter,\n order=1,\n hardware_id=\"e2\",\n name_plain=\"Energy Phase 2\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n PhysicalInput.objects.create(\n meter=meter,\n order=2,\n hardware_id=\"e3\",\n name_plain=\"Energy Phase 3\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n PhysicalInput.objects.create(\n meter=meter,\n order=3,\n hardware_id=\"et\",\n name_plain=\"Energy Total\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n elif meter_type == MeterModelForm.DATAHUB:\n PhysicalInput.objects.create(\n meter=meter,\n order=0,\n name_plain=\"Datahub\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n\n return response\n\n def get_form_kwargs(self):\n kwargs = super(MeterCreateView, self).get_form_kwargs()\n kwargs.update({'customer_id': self._customer.id})\n return kwargs\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:meter-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:meter-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_breadcrumbs(self):\n return MeterList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create Meter'))\n\n\nclass MeterUpdateView(\n CustomerListMixin, generic_views.UpdateView):\n model = Meter\n template_name = \\\n 'configuration_site/meter_form.html'\n fields = ('name', 'location', 'hardware_id')\n\n def get_breadcrumbs(self):\n return MeterList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Update Meter'))\n\n def get_success_url(self):\n return reverse(\n 'configuration_site:meter-list',\n kwargs={'customer_id': self._customer.id})\n\n def get_cancel_url(self):\n return reverse('configuration_site:meter-list',\n kwargs={'customer_id': self._customer.id})\n" }, { "alpha_fraction": 0.6244815587997437, "alphanum_fraction": 0.6359758377075195, "avg_line_length": 34.30962371826172, "blob_id": "bfe4f99f39908f19810d3133b55b7cc91da30530", "content_id": "6c3a1b96ae4c4525e59d76dc611724449caa7d47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8439, "license_type": "no_license", "max_line_length": 93, "num_lines": 239, "path": "/legacy/devices/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom datetime import timedelta\n\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\nfrom django.db.models import ProtectedError\n\nimport pytz\n\nfrom .models import Agent\nfrom .models import Meter\nfrom .models import PhysicalInput\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform import trackuser\nfrom gridplatform.providers.models import Provider\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom legacy.measurementpoints.models import Location\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestDevices(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n self.location = Location.objects.create(\n name_plain='test location',\n customer=self.customer)\n self.location2 = Location.objects.create(\n name_plain='test location',\n customer=self.customer)\n\n self.agent = Agent(\n mac=\"AB:CD:DE:F0:12:34\",\n online=True,\n location=self.location,\n customer=self.customer)\n self.agent.save()\n\n self.meter = Meter(\n agent=self.agent,\n manufactoring_id=\"1234567891234\",\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n name_plain=\"test meter\",\n customer=self.customer,\n location=self.location2)\n self.meter.save()\n\n self.input = self.meter.physicalinput_set.create(\n customer=self.customer,\n name_plain=\"input on test meter\",\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n order=0)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_meter_dependency(self):\n self.assertRaises(\n ProtectedError, lambda: self.location2.delete())\n\n def test_agent_dependency(self):\n self.assertRaises(\n ProtectedError, lambda: self.location.delete())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass MeterTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n self.location = Location.objects.create(\n name_plain='test location',\n customer=self.customer)\n self.location2 = Location.objects.create(\n name_plain='test location',\n customer=self.customer)\n\n self.agent = Agent(\n mac=\"AB:CD:DE:F0:12:34\",\n online=True,\n location=self.location,\n customer=self.customer)\n self.agent.save()\n\n self.meter = Meter(\n agent=self.agent,\n manufactoring_id=\"1234567891234\",\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n name_plain=\"test meter\",\n customer=self.customer,\n location=self.location2)\n self.meter.save()\n\n self.input = self.meter.physicalinput_set.create(\n customer=self.customer,\n name_plain=\"input on test meter\",\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n order=0)\n\n # Added data for another meter to verify that connection_state only\n # checks latest data for itself. A bugfix solved this issue!\n self.another_meter = Meter(\n agent=self.agent,\n manufactoring_id=\"123123123\",\n connection_type=Meter.GRIDPOINT,\n name_plain=\"another test meter\",\n customer=self.customer,\n location=self.location)\n self.another_meter.save()\n\n self.another_input = self.another_meter.physicalinput_set.create(\n customer=self.customer,\n name_plain=\"input on another test meter\",\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n order=0)\n self.another_input.rawdata_set.create(\n value=1, timestamp=datetime.now(pytz.utc))\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_connection_state_6_days_since_last_measurement(self):\n # Latest update is over 6 days old\n timestamp = datetime.now(pytz.utc) - timedelta(days=6)\n self.input.rawdata_set.create(\n value=1, timestamp=timestamp)\n self.assertEqual(\n self.meter._measurements_info,\n Meter.MEASUREMENTS_INFO.no_measurements_within_24_hours)\n\n latest_update = self.meter.latest_update\n self.assertEqual(latest_update, timestamp)\n\n def test_connection_state_15_minutes_since_last_measurement(self):\n # Warning, when least measurement is more than 24 hours old.\n self.input.rawdata_set.create(\n value=1, timestamp=datetime.now(pytz.utc) - timedelta(hours=24))\n self.assertEqual(\n self.meter._measurements_info,\n Meter.MEASUREMENTS_INFO.no_measurements_within_24_hours)\n\n def test_connection_state_24h_of_equal_measurements(self):\n # measurements for last 24 hours are all equal\n for i in range(24):\n self.input.rawdata_set.create(\n value=1, timestamp=datetime.now(pytz.utc)-timedelta(hours=i))\n self.assertEqual(self.meter._measurements_info,\n Meter.MEASUREMENTS_INFO.no_change)\n\n def test_connection_state_agent_offline(self):\n # When agent is offline\n self.agent.online = False\n self.assertEqual(self.meter._connection_state,\n Meter.CONNECTION_STATES.agent_offline)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass AutocreateDataSequenceTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n\n self.agent = Agent.objects.create(\n mac='AB:CD:DE:F0:12:34',\n online=True,\n customer=self.customer)\n\n self.meter = Meter.objects.create(\n agent=self.agent,\n manufactoring_id='1234567891234',\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n name_plain='test meter',\n customer=self.customer)\n\n def test_millibar_autocreates_nonaccumulationadapter(self):\n physicalinput = self.meter.physicalinput_set.create(\n customer=self.customer,\n name_plain='input on test meter',\n unit='millibar',\n type=PhysicalInput.ELECTRICITY,\n order=0)\n\n # will raise if the adapter wasn't created\n nonaccumulationadapter = NonaccumulationAdapter.objects.filter(\n datasequence__period_set__datasource=physicalinput).get()\n\n # check that the created adapters unicode doesn't crash\n unicode(nonaccumulationadapter)\n\n # check that the intermediate nonaccumulationadapters unicode doesn't\n # crash\n unicode(nonaccumulationadapter.datasequence)\n\n def test_milliwatthour_autocreates_consumptionaccumulationadapter(self):\n physicalinput = self.meter.physicalinput_set.create(\n customer=self.customer,\n name_plain='input on test meter',\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n order=0)\n\n # will raise if the adapter wasn't created\n consumptionaccumulationadapter = \\\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__nonpulseperiod__datasource=physicalinput).get() # noqa\n\n # check that the created adapters unicode doesn't crash\n unicode(consumptionaccumulationadapter)\n\n # check that the intermediate nonaccumulationadapters unicode doesn't\n # crash\n unicode(consumptionaccumulationadapter.datasequence)\n" }, { "alpha_fraction": 0.6544916033744812, "alphanum_fraction": 0.6589338779449463, "avg_line_length": 37.96154022216797, "blob_id": "9057cfd04e1ab2d2acaaafd04bcaa2b6f001fca5", "content_id": "16c923def4705e0e0bd11660017f667be0c048a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "no_license", "max_line_length": 79, "num_lines": 52, "path": "/gridplatform/datasequences/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom rest_framework.response import Response\nfrom rest_framework.templatetags.rest_framework import replace_query_param\nfrom rest_framework.views import APIView\n\nfrom gridplatform.utils.paginator import parse_date_or_404\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.serializers import RangedSampleSerializer\n\n\nclass HourlyDataView(APIView):\n permission_classes = ()\n method_name = None\n unit_field = 'unit'\n\n def _get(self, request, datasequence, timezone):\n unit = getattr(datasequence, self.unit_field)\n date_query_param = request.QUERY_PARAMS.get('date')\n date = date_query_param or timezone.normalize(\n datetime.datetime.now(timezone)).date()\n date = parse_date_or_404(date)\n from_timestamp = timezone.localize(\n datetime.datetime.combine(date, datetime.time()))\n to_timestamp = timezone.localize(\n datetime.datetime.combine(\n date + datetime.timedelta(days=1), datetime.time()))\n method = getattr(datasequence, self.method_name)\n data = method(from_timestamp, to_timestamp, RelativeTimeDelta(hours=1))\n serializer = RangedSampleSerializer(\n data, many=True, context={'unit': unit})\n\n base_url = request and request.build_absolute_uri() or ''\n next_date = datasequence.next_valid_date(date, timezone)\n if next_date:\n next_url = replace_query_param(base_url, 'date', next_date)\n else:\n next_url = None\n previous_date = datasequence.previous_valid_date(date, timezone)\n if previous_date:\n previous_url = replace_query_param(base_url, 'date', previous_date)\n else:\n previous_url = None\n return Response({\n 'next': next_url,\n 'previous': previous_url,\n 'results': serializer.data,\n })\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6747967600822449, "avg_line_length": 12.666666984558105, "blob_id": "e5436681cb430a228cf707239844efb2a376d781", "content_id": "a848533458a30a3325d87b2164e0ca3f171f9fc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 123, "license_type": "no_license", "max_line_length": 37, "num_lines": 9, "path": "/gridagentserver/stop.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd `dirname $0`\n\nif [ -e twistd.pid ]\nthen\n kill `cat twistd.pid`\nfi\ntouch $HOME/gas-stopped-intentionally\n" }, { "alpha_fraction": 0.7510656714439392, "alphanum_fraction": 0.7800511717796326, "avg_line_length": 17.328125, "blob_id": "a77e0dde51f0ec88f0c786d159db88d1a4ed148a", "content_id": "c7e10e64c84cdb4d4d1cda1525e851c2df3cd3b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 72, "num_lines": 64, "path": "/gridagentserver/logging.ini", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "[loggers]\nkeys=root,agentserver,protocol,twisted\n\n[handlers]\nkeys=warn,info,debug,debug_stderr\n\n[formatters]\nkeys=default\n\n[logger_root]\nlevel=WARNING\nhandlers=warn\n\n[logger_agentserver]\nlevel=DEBUG\n# running as daemon redirects stderr to /dev/null...\n# handlers=debug_stderr,debug,info\nhandlers=debug,info\n# handlers=info\npropagate=1\nqualname=agentserver\n\n[logger_protocol]\nlevel=DEBUG\n# running as daemon redirects stderr to /dev/null...\n# handlers=debug_stderr,debug,info\nhandlers=debug,info\n# handlers=info\npropagate=1\nqualname=gridagentserver_protocol\n\n[logger_twisted]\nlevel=DEBUG\nhandlers=debug,info\npropagate=1\nqualname=twisted\n\n[handler_debug_stderr]\nclass=StreamHandler\nlevel=DEBUG\nformatter=default\nargs=()\n\n[handler_debug]\nclass=handlers.RotatingFileHandler\nlevel=DEBUG\nformatter=default\nargs=('debug.log', 'a', 16*1024*1024, 9)\n\n[handler_info]\nclass=handlers.RotatingFileHandler\nlevel=INFO\nformatter=default\nargs=('info.log', 'a', 1024*1024, 9)\n\n[handler_warn]\nclass=handlers.RotatingFileHandler\nlevel=WARNING\nformatter=default\nargs=('warn.log', 'a', 1024*1024, 9)\n\n\n[formatter_default]\nformat=%(asctime)-15s %(levelname)s: %(message)s (%(name)s %(funcName)s)\n" }, { "alpha_fraction": 0.5139405727386475, "alphanum_fraction": 0.5499728322029114, "avg_line_length": 30.770252227783203, "blob_id": "b04fc1dd1df5bf1bc632066e0b92d6462ae81835", "content_id": "43855943bd6f7dbabe0940460fe1edfb2022d9b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23923, "license_type": "no_license", "max_line_length": 105, "num_lines": 753, "path": "/gridplatform/utils/unitconversion.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nUnit conversion library.\n\nThis is base on/inspired by the Python Buckingham module, available at\nhttps://code.google.com/p/buckingham/ (though that thing crashes when\ntrying to convert a zero-valued quantity, because of obscure notion of\nrelative error).\n\nFraction is used for numbers. This allows us to specify non-base units\nconcisely in terms of other non-base units without loss of precision, and means\nthat we avoid introducing errors beyond those present in the input. (Most\n\"relevant\" units are *defined* in terms of SI base units, and can be expressed\naccurately --- but not necessarily as a Python Decimal or float value; there\nare funny units like the survey foot, defined as 1200/3937 meter...)\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nimport numbers\nimport warnings\nfrom fractions import Fraction\nfrom decimal import Decimal\nfrom collections import OrderedDict, namedtuple\nfrom exceptions import UserWarning\n\n\n__all__ = ['UnitConversionError', 'UnitParseError', 'IncompatibleUnitsError',\n 'PhysicalQuantity', 'register_unit', 'simple_convert']\n\n\nclass UnitConversionError(ValueError):\n pass\n\n\nclass UnitParseError(UnitConversionError):\n pass\n\n\nclass IncompatibleUnitsError(UnitConversionError):\n pass\n\n\nclass UnitConversionTypeError(UnitConversionError, TypeError):\n pass\n\n\nclass NotPhysicalQuantityError(UnitConversionTypeError):\n pass\n\n\nclass UnitConversionWarning(UserWarning):\n pass\n\n\nBASE_UNITS = OrderedDict([\n # http://en.wikipedia.org/wiki/SI_base_unit\n ('none', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('meter', (1, (1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('gram', (1, (0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('second', (1, (0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('ampere', (1, (0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('kelvin', (1, (0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('mole', (1, (0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('candela', (1, (0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0))),\n # useful non-SI units\n ('currency_eur', (1, (0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0))),\n ('currency_dkk', (1, (0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0))),\n ('person', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0))),\n ('impulse', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0))),\n # customizable production units\n ('production_a', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0))),\n ('production_b', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0))),\n ('production_c', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0))),\n ('production_d', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0))),\n ('production_e', (1, (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1))),\n])\n\n\nUNIT_NAMES = tuple(BASE_UNITS.keys()[1:])\n\n\nSCALES = (\n ('yocto', Fraction(10)**-24),\n ('zepto', Fraction(10)**-21),\n ('atto', Fraction(10)**-18),\n ('femto', Fraction(10)**-15),\n ('pico', Fraction(10)**-12),\n ('nano', Fraction(10)**-9),\n ('micro', Fraction(10)**-6),\n ('milli', Fraction(10)**-3),\n ('centi', Fraction(10)**-2),\n ('deci', Fraction(10)**-1),\n ('deca', Fraction(10)**1),\n ('hecto', Fraction(10)**2),\n ('kilo', Fraction(10)**3),\n ('mega', Fraction(10)**6),\n ('giga', Fraction(10)**9),\n ('tera', Fraction(10)**12),\n ('peta', Fraction(10)**15),\n ('exa', Fraction(10)**18),\n ('zetta', Fraction(10)**21),\n ('yotta', Fraction(10)**24),\n\n ('quarter', Fraction(1, 4)),\n)\n\n\nUNITS = {}\n\n\n__PhysicalQuantityBase = namedtuple(\n '__PhysicalQuantityBase', ('value', 'unit_vector'))\n\n\ndef _parse_unit_part(unit, elem):\n x = elem.split('^')\n try:\n base_unit = UNITS[x[0]]\n except KeyError:\n raise UnitParseError(\n \"Error parsing unit string '%s' (unknown on '%s')\" % (unit, x))\n if len(x) == 1:\n return base_unit\n elif len(x) == 2:\n try:\n power = int(x[1])\n except ValueError:\n raise UnitParseError(\n \"Error parsing unit string '%s' \"\n \"(non-integer power '%s' for unit '%s')\" % (\n unit, x[1], x[0]))\n return base_unit._replace(\n value=base_unit.value**power,\n unit_vector=tuple([n * power for n in base_unit.unit_vector]))\n else:\n raise UnitParseError(\n \"Error parsing unit string '%s' (error on '%s')\" % (unit, x))\n\n\ndef _parse_unit(unit):\n divparts = unit.rsplit('/', 1)\n numerator = divparts[0]\n if len(divparts) == 2:\n denominator = divparts[1]\n else:\n denominator = None\n parts = []\n for elem in numerator.split('*'):\n part = _parse_unit_part(unit, elem)\n parts.append(part)\n if denominator:\n denominator_part = _parse_unit_part(unit, denominator)\n parts.append(part._replace(\n value=Fraction(1) / denominator_part.value,\n unit_vector=tuple([-n for n in denominator_part.unit_vector])))\n\n multiplier = reduce(operator.mul, [p.value for p in parts], 1)\n unit_vector = tuple(map(sum, zip(*[p.unit_vector for p in parts])))\n return PhysicalQuantity._make((multiplier, unit_vector))\n\n\nclass _UnitCacheDict(dict):\n def __missing__(self, key):\n val = _parse_unit(key)\n self[key] = val\n return val\n\n\n# cache of PhysicalQuantity(scaling_factor, unit_vector) for unit strings; to\n# speed up parsing unit strings...\n_unit_cache = _UnitCacheDict()\n\n\nclass PhysicalQuantity(__PhysicalQuantityBase):\n \"\"\"\n A numeric value with a unit.\n\n Normal aritmmetic works, provided that units are compatible; i.e.\n\n >>> PhysicalQuantity(1, 'kilometer') + \\\n PhysicalQuantity(1, 'decimeter') == \\\n PhysicalQuantity(Decimal('1000.1'), 'meter')\n True\n\n >>> PhysicalQuantity(1, 'kelvin') - PhysicalQuantity(1, 'ampere')\n Traceback (most recent call last):\n ...\n IncompatibleUnitsError: Incompatible Dimensions 'kelvin' and 'ampere'\n\n >>> PhysicalQuantity(10, 'meter') * PhysicalQuantity(2, 'meter') == \\\n PhysicalQuantity(20, 'meter^2')\n True\n >>> PhysicalQuantity(100, 'gram') / PhysicalQuantity(2, 'meter') == \\\n PhysicalQuantity(50, 'gram*meter^-1')\n True\n\n Internally, values are scaled to SI base units where possible. The numeric\n value and unit vector are accessible as members ``value`` and\n ``unit_vector``; the unit vector as a human readable string in ``units``.\n\n >>> PhysicalQuantity(1, 'kilometer').value == 1000\n True\n >>> PhysicalQuantity(1, 'kilometer').units == 'meter'\n True\n\n For presentation, ``convert`` should be used to get a numeric\n value scaled to some specified unit --- the unit directly\n accessible from the :class:`.PhysicalQuantity` is unlikely to be\n the desired for presentation...\n\n >>> PhysicalQuantity(150, 'watt').units == 'meter^2*gram*second^-3'\n True\n >>> PhysicalQuantity(150, 'watt').convert('kilowatt') == Fraction('0.150')\n True\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, value, unit='none'):\n \"\"\"\n >>> a = PhysicalQuantity(10, 'meter*second^-1')\n >>> b = PhysicalQuantity(2, 'yard*minute^-1')\n >>> c = a + b\n >>> print(float(c.convert('kilometer*hour^-1')))\n 36.109728\n\n >>> float(PhysicalQuantity(1, 'joule').convert('electronvolt'))\n 6.241509343260179e+18\n\n >>> print(\"%s %s\" % (float(c.value), c.units))\n 10.03048 meter*second^-1\n\n >>> a = PhysicalQuantity(1, 'decimeter^3')\n >>> b = PhysicalQuantity(2, 'liter')\n >>> c = PhysicalQuantity(5, 'gram*centimeter^-3')\n >>> d = (a + b)*c\n >>> print(d.convert('kilogram'))\n 15\n\n Example of formula validation\n\n >>> a = PhysicalQuantity(10, 'meter*second^-1')\n >>> b = PhysicalQuantity(2, 'yard^3')\n >>> c = a + b\n ... # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n IncompatibleUnitsError: Incompatible Dimensions 'meter*second^-1'\n and 'meter^3'\n\n Examples of more complex formulas\n\n >>> a = PhysicalQuantity(10, 'meter*second^-1')\n >>> b = PhysicalQuantity(5, 'hour')\n >>> c = a**4 / (7*b)\n >>> print(c)\n 5/63 meter^4*second^-5\n\n Financial application example\n\n >>> coupon = PhysicalQuantity(200, 'currency_dkk*day^-1')\n >>> expiration = PhysicalQuantity(365, 'day')\n >>> payoff = coupon*expiration\n >>> print(float(payoff.convert('currency_dkk')))\n 73000.0\n\n >>> a = PhysicalQuantity(10, 'meter*second^-2')\n >>> b = PhysicalQuantity(10, 'meter/second^2')\n >>> a == b\n True\n\n >>> PhysicalQuantity(10, 'meter/second/liter')\n ... # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n UnitParseError: Error parsing unit string 'meter/second/liter'\n (unknown on '[u'meter/second']')\n\n >>> PhysicalQuantity(10, 'meter/second*liter')\n ... # doctest: +NORMALIZE_WHITESPACE\n Traceback (most recent call last):\n ...\n UnitParseError: Error parsing unit string 'meter/second*liter'\n (unknown on '[u'second*liter']')\n \"\"\"\n if isinstance(value, float) and value != int(value):\n warnings.warn(\n 'Constructing PhysicalQuantity from float value %s' % value,\n UnitConversionWarning,\n stacklevel=2)\n if isinstance(unit, tuple):\n # Fix for serialisation/deserialisation issue...\n return PhysicalQuantity._make((Fraction(value), unit))\n base = _unit_cache[unit]\n value = base.value * Fraction(value)\n return base._replace(value=value)\n\n def __check_unit(self, other):\n if not isinstance(other, PhysicalQuantity):\n raise NotPhysicalQuantityError('%r is not a PhysicalQuantity' % (\n other,))\n if self.unit_vector != other.unit_vector:\n raise IncompatibleUnitsError(\n \"Incompatible Dimensions '%s' and '%s'\" %\n (self.units, other.units))\n\n def __add__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(2)\n >>> b = PhysicalQuantity(3)\n >>> print(a + b)\n 5 none\n\n >>> print(a + 5)\n Traceback (most recent call last):\n ...\n NotPhysicalQuantityError: 5 is not a PhysicalQuantity\n \"\"\"\n self.__check_unit(other)\n value = self.value + other.value\n return self._replace(value=value)\n\n def __neg__(self):\n \"\"\"\n >>> -PhysicalQuantity(1, 'joule') == PhysicalQuantity(-1, 'joule')\n True\n \"\"\"\n return self._replace(value=-self.value)\n\n def __radd__(self, other):\n # NOTE: will currently raise exception...\n return self.__add__(other)\n\n def __sub__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(2)\n >>> b = PhysicalQuantity(3)\n >>> print(a-b)\n -1 none\n \"\"\"\n self.__check_unit(other)\n value = self.value - other.value\n return self._replace(value=value)\n\n def __rsub__(self, other):\n # NOTE: will currently raise exception...\n return self.__sub__(other) * (-1)\n\n def __mul__(self, other):\n \"\"\"\n >>> print(PhysicalQuantity(2, 'meter') * 1)\n 2 meter\n\n >>> print(PhysicalQuantity(4, 'gram') * PhysicalQuantity(7, 'gram'))\n 28 gram^2\n \"\"\"\n if not isinstance(other, PhysicalQuantity):\n value = self.value * Fraction(other)\n return self._replace(value=value)\n value = self.value * other.value\n unit_vector = map(operator.add, self.unit_vector, other.unit_vector)\n return self._make((value, tuple(unit_vector)))\n\n def __rmul__(self, other):\n \"\"\"\n >>> print(3 * PhysicalQuantity(2, 'ampere'))\n 6 ampere\n \"\"\"\n return self.__mul__(other)\n\n def __div__(self, other):\n \"\"\"\n >>> print(PhysicalQuantity(2) / 1)\n 2 none\n\n >>> print(PhysicalQuantity(4) / PhysicalQuantity(7, 'second'))\n 4/7 second^-1\n\n >>> print(PhysicalQuantity(4, 'meter') / PhysicalQuantity(2, 'meter'))\n 2 none\n \"\"\"\n if not isinstance(other, PhysicalQuantity):\n value = self.value / Fraction(other)\n return self._replace(value=value)\n elif self.unit_vector == other.unit_vector:\n return PhysicalQuantity(self.value / other.value)\n else:\n value = self.value / other.value\n unit_vector = map(\n operator.sub, self.unit_vector, other.unit_vector)\n return self._make((value, tuple(unit_vector)))\n\n def __truediv__(self, other):\n return self.__div__(other)\n\n def __rdiv__(self, other):\n \"\"\"\n >>> print(1 / PhysicalQuantity(2))\n 1/2 none\n \"\"\"\n return PhysicalQuantity(other) / self\n\n def __rtruediv__(self, other):\n return PhysicalQuantity(other) / self\n\n def __pow__(self, other):\n \"\"\"\n >>> print(PhysicalQuantity(2, 'meter^2')**2)\n 4 meter^4\n \"\"\"\n if not isinstance(other, numbers.Integral):\n raise UnitConversionTypeError(\"Non-integer power '%r'\" % (other,))\n n = int(other)\n unit_vector = [v * n for v in self.unit_vector]\n value = self.value ** n\n return self._make((value, tuple(unit_vector)))\n\n def __lt__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(2, 'meter')\n >>> b = PhysicalQuantity(1, 'kilometer')\n >>> c = PhysicalQuantity(3, 'meter^2')\n >>> a < b\n True\n >>> a < c\n Traceback (most recent call last):\n ...\n IncompatibleUnitsError: Incompatible Dimensions 'meter' and 'meter^2'\n \"\"\"\n self.__check_unit(other)\n return self.value < other.value\n\n def __le__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(1000, 'meter')\n >>> b = PhysicalQuantity(1, 'kilometer')\n >>> a <= b\n True\n \"\"\"\n self.__check_unit(other)\n return self.value <= other.value\n\n def __gt__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(1000, 'meter')\n >>> b = PhysicalQuantity(1, 'kilometer')\n >>> a > b\n False\n \"\"\"\n self.__check_unit(other)\n return self.value > other.value\n\n def __ge__(self, other):\n \"\"\"\n >>> a = PhysicalQuantity(1000, 'meter')\n >>> b = PhysicalQuantity(1, 'kilometer')\n >>> a >= b\n True\n \"\"\"\n self.__check_unit(other)\n return self.value >= other.value\n\n # note: using inherited __eq__, __ne__ from tuple\n\n def __nonzero__(self):\n \"\"\"\n >>> bool(PhysicalQuantity(10, 'meter'))\n True\n >>> bool(PhysicalQuantity(0, 'liter'))\n False\n \"\"\"\n return bool(self.value)\n\n @property\n def units(self):\n \"\"\"\n A human-readable representation of the objects (normalised) unit.\n \"\"\"\n if all([v == 0 for v in self.unit_vector]):\n return u'none'\n\n def f(name, n):\n if n == 0:\n return ''\n elif n == 1:\n return name\n else:\n return u'%s^%s' % (name, n)\n\n return u'*'.join(filter(None, map(f, UNIT_NAMES, self.unit_vector)))\n\n def convert(self, unit):\n \"\"\"\n Convert value to a possibly non-normalised but compatible unit,\n returning the resulting numeric value.\n\n >>> print(PhysicalQuantity(0, 'meter*second^-1').convert('kilometer*hour^-1')) # noqa\n 0\n\n Note that the result is a unitless Fraction, not a PhysicalQuantity\n\n >>> print(PhysicalQuantity(1, 'kilometer*hour^-1').convert('kilometer*hour^-1').__class__) # noqa\n <class 'fractions.Fraction'>\n\n >>> PhysicalQuantity(1, 'kilometer').convert('kelvin')\n Traceback (most recent call last):\n ...\n IncompatibleUnitsError: Incompatible Dimensions 'meter' and 'kelvin'\n\n \"\"\"\n other = _unit_cache[unit]\n self.__check_unit(other)\n return self.value / other.value\n\n def compatible_unit(self, unit):\n \"\"\"\n Check whether the specified unit is a valid conversion target for this\n object, i.e. whether they have the same base units.\n\n >>> PhysicalQuantity(1, 'meter').compatible_unit('foot')\n True\n\n >>> PhysicalQuantity(1, 'kilometer').compatible_unit('watt')\n False\n \"\"\"\n other = _unit_cache[unit]\n return self.unit_vector == other.unit_vector\n\n @staticmethod\n def compatible_units(unit_a, unit_b):\n \"\"\"\n Check whether two units specifications are compatible.\n\n >>> PhysicalQuantity.compatible_units('meter', 'foot')\n True\n\n >>> PhysicalQuantity.compatible_units('meter', 'watt')\n False\n \"\"\"\n return _unit_cache[unit_a].unit_vector == \\\n _unit_cache[unit_b].unit_vector\n\n @staticmethod\n def same_unit(unit_a, unit_b):\n \"\"\"\n Check whether to unit specifications specify the same unit.\n\n >>> PhysicalQuantity.same_unit('meter*meter', 'meter^2')\n True\n\n >>> PhysicalQuantity.same_unit('meter', 'foot')\n False\n\n >>> PhysicalQuantity.same_unit('meter', 'kelvin')\n False\n \"\"\"\n a = _unit_cache[unit_a]\n b = _unit_cache[unit_b]\n return a.unit_vector == b.unit_vector and a.value == b.value\n\n def __repr__(self):\n if self.value.denominator == 1:\n n = self.value.numerator\n else:\n n = self.value\n return 'PhysicalQuantity(%r, %r)' % (n, self.units)\n\n def __str__(self):\n return '%s %s' % (self.value, self.units)\n\n def __reduce__(self):\n return (PhysicalQuantity, (str(self.value), self.unit_vector))\n\n\ndef register_unit(name, value):\n \"\"\"\n Define a new input unit, equal to some expression in already existing\n units.\n\n @param name: Name of new unit.\n @param value: Pair of (number, dimensions), where dimensions is (as)\n interpreted by the PhysicalQuantity constructor.\n\n @precondition: Unit ``name`` not already registered.\n\n Example use:\n register_unit('lightyear', (9460730472580800, 'meter'))\n PhysicalQuantity(200, 'lightyear').convert('mile')\n \"\"\"\n if name in UNITS:\n return\n for prefix, scale in SCALES:\n assert not name.startswith(prefix), \\\n 'Unit %s appears to include prefix %s' % (name, prefix)\n n, unit = value\n\n if isinstance(unit, basestring):\n # new unit from existing\n v = PhysicalQuantity(n, unit)\n else:\n assert isinstance(unit, tuple)\n # base unit\n v = PhysicalQuantity._make((Fraction(n), unit))\n\n UNITS[name] = v\n for prefix, scale in SCALES:\n UNITS[prefix + name] = v._replace(value=v.value*scale)\n\n\nfor name, value in BASE_UNITS.items():\n register_unit(name, value)\n\n\n# http://en.wikipedia.org/wiki/SI_derived_unit\nSI_DERIVED_UNITS = OrderedDict([\n ('hertz', (1, 'second^-1')),\n ('radian', (1, 'none')),\n ('steradian', (1, 'none')),\n ('newton', (1, 'kilogram*meter*second^-2')),\n ('pascal', (1, 'newton*meter^-2')),\n ('joule', (1, 'newton*meter')),\n ('watt', (1, 'joule*second^-1')),\n ('coulomb', (1, 'second*ampere')),\n ('volt', (1, 'watt*ampere^-1')),\n ('farad', (1, 'coulomb*volt^-1')),\n ('ohm', (1, 'volt*ampere^-1')),\n ('siemens', (1, 'ohm^-1')),\n ('weber', (1, 'joule*ampere^-1')),\n ('tesla', (1, 'volt*second*meter^-2')),\n ('henry', (1, 'volt*second*ampere^-1')),\n # degree celsius not added...\n ('lumen', (1, 'candela*steradian')),\n ('lux', (1, 'lumen*meter^-2')),\n ('becquerel', (1, 'second^-1')),\n ('gray', (1, 'joule*kilogram^-1')),\n ('sievert', (1, 'joule*kilogram^-1')),\n ('katal', (1, 'mole*second^-1')),\n])\n\n\nfor name, value in SI_DERIVED_UNITS.items():\n register_unit(name, value)\n\n\n# http://en.wikipedia.org/wiki/Non-SI_units_accepted_for_use_with_SI\nCOMMON_UNITS = OrderedDict([\n # widely used\n ('minute', (60, 'second')),\n ('hour', (60, 'minute')),\n ('day', (24, 'hour')),\n ('hectare', (1, 'hectometer^2')),\n ('litre', (1, 'decimeter^3')),\n ('liter', (1, 'decimeter^3')),\n ('tonne', (1000, 'kilogram')),\n # experimentally determined\n ('electronvolt', (Decimal('1.602176565e-19'), 'joule')),\n ('dalton', (Decimal('1.66053886e-27'), 'kilogram')),\n ('astronomical_unit', (Decimal('1.4959787069e11'), 'meter')),\n # not officially sanctioned\n ('angstrom', (Decimal('1e-10'), 'meter')),\n ('are', (100, 'meter^2')),\n ('barn', (Decimal('1e-28'), 'meter^2')),\n ('bar', (10**5, 'pascal')),\n ('atmosphere', (101325, 'pascal')),\n ('barye', (Decimal('0.1'), 'pascal')),\n ('torr', (Fraction(1, 760), 'atmosphere')),\n])\n\n\nfor name, value in COMMON_UNITS.items():\n register_unit(name, value)\n\n\n# http://en.wikipedia.org/wiki/United_States_customary_units\nOTHER_UNITS = OrderedDict([\n # International\n ('inch', (Decimal('2.54'), 'centimeter')),\n ('foot', (12, 'inch')),\n ('yard', (3, 'foot')),\n ('mile', (1760, 'yard')),\n # US Survey\n ('survey_foot', (Fraction(1200, 3937), 'meter')),\n ('link', (Fraction(33, 50), 'survey_foot')),\n ('rod', (25, 'link')),\n ('chain', (4, 'rod')),\n ('furlong', (10, 'chain')),\n ('survey_mile', (8, 'furlong')),\n ('league', (3, 'survey_mile')),\n # Nautical\n ('fathom', (2, 'yard')),\n ('cable', (1, 'fathom')),\n ('nautical_mile', (Decimal('1.852'), 'kilometer')),\n # Area\n ('acre', (10, 'chain^2')),\n ('section', (1, 'survey_mile^2')),\n ('survey_township', (4, 'league^2')),\n # Fluid Volume\n ('minim', (Decimal('61.611519921875'), 'microlitre')),\n ('us_fluid_dram', (60, 'minim')),\n ('teaspoon', (80, 'minim')),\n ('tablespoon', (3, 'teaspoon')),\n ('us_fluid_ounce', (2, 'tablespoon')),\n ('us_shot', (3, 'tablespoon')),\n ('us_gill', (4, 'us_fluid_ounce')),\n ('us_cup', (2, 'us_gill')),\n ('liquid_us_pint', (2, 'us_cup')),\n ('liquid_us_quart', (2, 'liquid_us_pint')),\n ('liquid_us_gallon', (4, 'liquid_us_quart')),\n ('liquid_barrel', (Decimal('31.5'), 'liquid_us_gallon')),\n ('oil_barrel', (42, 'liquid_us_gallon')),\n ('hogshead', (63, 'liquid_us_gallon')),\n # Dry Volume\n ('dry_gallon', (Decimal('268.8025'), 'inch^3')),\n ('dry_quart', (Fraction(1, 4), 'dry_gallon')),\n ('dry_pint', (Fraction(1, 2), 'dry_quart')),\n ('peck', (2, 'dry_gallon')),\n ('bushel', (4, 'peck')),\n ('dry_barrel', (7056, 'inch^3')),\n # Mass (avoirdupois)\n ('pound', (Decimal('453.59237'), 'gram')),\n ('ounce', (Fraction(1, 16), 'pound')),\n ('dram', (Fraction(1, 16), 'ounce')),\n ('grain', (Fraction(1, 7000), 'pound')),\n ('us_hundredweight', (100, 'pound')),\n ('long_hundredweight', (112, 'pound')),\n ('short_ton', (20, 'us_hundredweight')),\n ('long_ton', (20, 'long_hundredweight')),\n # ...\n ('rankine', (Fraction(5, 9), 'kelvin')),\n ('percent', (Fraction(1, 100), 'none')),\n])\n\n\nfor name, value in OTHER_UNITS.items():\n register_unit(name, value)\n\n\n_unit_cache[''] = _unit_cache['none']\n\n\ndef simple_convert(number, from_unit, to_unit):\n \"\"\"\n >>> simple_convert(1000, 'meter', 'kilometer')\n Fraction(1, 1)\n \"\"\"\n return PhysicalQuantity(number, from_unit).convert(to_unit)\n\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n" }, { "alpha_fraction": 0.6980568170547485, "alphanum_fraction": 0.6995515823364258, "avg_line_length": 30.85714340209961, "blob_id": "65e37925074e0ff8b3a6129396b7cf00d58e19c4", "content_id": "77ed4e0f46d3acdfeaaaee2d4385b4e922294eaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/gridplatform/customer_datasources/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.datasources.serializers import DataSourceSerializerBase\n\nfrom gridplatform.rest import serializers\nfrom .models import CustomerDataSource\n\n\nclass CustomerDataSourceSerializer(DataSourceSerializerBase):\n name = serializers.CharField(source='name_plain')\n raw_data = serializers.HyperlinkedIdentityField(\n view_name='api:datasources:rawdata-list')\n\n class Meta:\n model = CustomerDataSource\n fields = (\n 'url', 'id', 'customer', 'name', 'unit', 'display_unit',\n 'hardware_id', 'raw_data'\n )\n" }, { "alpha_fraction": 0.7325783967971802, "alphanum_fraction": 0.7848432064056396, "avg_line_length": 56.400001525878906, "blob_id": "09ecc82a59390dbe563e6060b7f66ed706a83724", "content_id": "ef5258e2e4eec78ec8737e885520ee339c6f5824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1148, "license_type": "no_license", "max_line_length": 92, "num_lines": 20, "path": "/gridagentserver/requirements.txt", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Django==1.6.5 # high-level Python Web framework\ndjango-configurations==0.1 # more flexible settings.py configuration\ndjango-durationfield==0.4.0 # field type representing datetime.timedelta\ndjango-historicalrecords==1.0 # generic history for Django models.\ndjango-mptt==0.5.5 # implementing Modified Preorder Tree Traversal with Django Models\ndjango-timezones2==1.0.4 # helper for pytz\nisoweek==1.2.0 # translating ISO week numbers to datetime dates\npika==0.9.13 # AMQP (message queue) client library\npsycopg2==2.5 # PostgreSQL driver\npycrypto==2.6 # cryptography toolkit\npython-dateutil==2.1 # real month deltas\npytz==2013b # brings the Olson timezone database into Python\nsouth==0.8.4 # database migrations\nTwisted==13.0.0 # cooperative multithreading/network server\ntxAMQP==0.6.1 # async message queue client integrating with Twisted\ndjango-model-utils==2.0.2 # utilities for models and managers\ncelery==3.1.8 # Python background task queue/runner\nPillow==2.4.0 # Python Image Library distribution; may require libjpeg-dev for JPEG support\npilkit==1.1.6 # dependency of django-imagekit\ndjango-imagekit==3.0.1 # ProcessedImageField for Django\n" }, { "alpha_fraction": 0.7096154093742371, "alphanum_fraction": 0.7115384340286255, "avg_line_length": 23.186046600341797, "blob_id": "89350af09c6c41301603603e0ed2fae5bfc22427", "content_id": "c1741b1bc0298653effafaa0bd013fd6c453d78c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 102, "num_lines": 43, "path": "/emonhub/install", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\necho \"Emonhub installation script for emonPi\"\n\n### set git cloned location\nGIT_PATH=/home/pi/emonhub\n\nif [ ! -d /home/pi ] ; then\n {\n echo \"Directory /home/pi does not exist, this installation script is for raspberrypi installation\"\n exit\n }\nfi\n\n\n### set location to install emonhub.py etc\nINST_PATH=/usr/share/emonhub\n\n### create linked directory for emonhub.py etc\nsudo rm -r -f $INST_PATH\nsudo ln -s $GIT_PATH/src $INST_PATH\n\n### link init script\nsudo rm -f /etc/init.d/emonhub\nsudo ln -s $GIT_PATH/service/emonhub /etc/init.d/emonhub\n\n### link default locations file\nsudo rm -f /etc/default/emonhub\nsudo ln -s $GIT_PATH/conf/default/emonhub /etc/default/emonhub\n\n### create folder and move settings file (unless it exists already)\nif [ ! -f /home/pi/data/emonhub.conf ] ; then\n {\n sudo mv $GIT_PATH/conf/emonpi.default.emonhub.conf /home/pi/data/emonhub.conf\n }\nfi\n\n# launch at start-ip\nsudo update-rc.d emonhub defaults 99\n\n\n### create \"emonhub\" user\nsudo useradd -M -r -G dialout,tty -c \"emonHub user\" emonhub\n" }, { "alpha_fraction": 0.6731958985328674, "alphanum_fraction": 0.673711359500885, "avg_line_length": 35.60377502441406, "blob_id": "9c55e8d145137a6b2b271c7dddce1d099a277e04", "content_id": "b1a7d768a8140916d50b6c38f773d58d671e2557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1940, "license_type": "no_license", "max_line_length": 76, "num_lines": 53, "path": "/legacy/projects/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.reports.views import StartReportView\nfrom gridplatform.reports.views import FinalizeReportView\nfrom gridplatform.reports.views import ReportInfo\nfrom gridplatform.reports.pdf import generate_pdf\nfrom gridplatform.trackuser import get_customer\n\nfrom .forms import AnnualSavingsPotentialReportGenerationForm\nfrom .tasks import AnnualSavingsPotentialReportTask\nfrom .models import BenchmarkProject\n\n\nclass StartAnnualSavingsPotentialReportView(StartReportView):\n task = AnnualSavingsPotentialReportTask\n form_class = AnnualSavingsPotentialReportGenerationForm\n\n def get_task_data(self, form):\n result = {\n \"projects\": dict()\n }\n\n for project_id in form.cleaned_data['projects'].values_list(\n 'id', flat=True):\n result['projects'][project_id] = dict()\n\n return result\n\n\nclass FinalizeAnnualSavingsPotentialReportView(FinalizeReportView):\n def generate_report(self, data, timestamp):\n for project in BenchmarkProject.objects.filter(\n id__in=data['projects'].keys()):\n data['projects'][project.id]['name'] = unicode(project)\n data['projects'][project.id]['get_consumption_unit_display'] = \\\n project.get_preferred_consumption_unit_converter().\\\n get_display_unit()\n\n data['currency'] = get_customer().get_currency_unit_display()\n\n return ReportInfo(\n 'annual_savings_potential.pdf',\n 'application/pdf',\n generate_pdf(\n template='projects/annual_savings_potential_report.tex',\n data=data,\n title=_('Annual Savings Potential'),\n report_type='annual_savings_potential',\n customer=get_customer()))\n" }, { "alpha_fraction": 0.6129692792892456, "alphanum_fraction": 0.6395904421806335, "avg_line_length": 33.880950927734375, "blob_id": "350dfb083f6f5a6e9c0e4ee1cc69aa7bef8a3f5d", "content_id": "e51f9aa8d47b309ab8c6e67ea3853a5df947befc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1465, "license_type": "no_license", "max_line_length": 77, "num_lines": 42, "path": "/gridagentserver/control_mode.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# dry-run example command:\n# ./control_mode.py -n -v 00:24:21:0e:8f:cd --manual \\\n# aa:bb:cc:dd:11:22:33:44 11:22:33:44:aa:bb:cc:dd\n\nimport argparse\n\nfrom client import normalise_mac, send_message, gridpoint_id\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('agent', help='target agent (MAC address)')\nparser.add_argument('meters', nargs='+',\n help='target meters (ZigBee MAC addresses)')\nparser.add_argument('-v', '--verbose', action='store_true',\n help='increase output verbosity')\nparser.add_argument('-n', '--dry-run', action='store_true',\n help='don\\'t actually send command')\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument('-a', '--auto', action='store_true', help='auto mode')\ngroup.add_argument('-m', '--manual', action='store_true', help='manual mode')\n\n\ndef control_mode(args):\n agent_mac = normalise_mac(args.agent)\n meters = [gridpoint_id(normalise_mac(meter, bytes=8))\n for meter in args.meters]\n routing_key = 'agent.%s' % (agent_mac,)\n assert args.manual != args.auto\n control_manual = args.manual\n message = {\n 'command': 'control_mode',\n 'agent': agent_mac,\n 'control_manual': control_manual,\n 'meters': meters,\n }\n send_message(routing_key, message, args.verbose, args.dry_run)\n\n\nif __name__ == '__main__':\n control_mode(parser.parse_args())\n" }, { "alpha_fraction": 0.5632272958755493, "alphanum_fraction": 0.565554678440094, "avg_line_length": 28.295454025268555, "blob_id": "7574a3a25e6dc098804a093218debcbcd1f54052", "content_id": "f35dad26dc6e73b21cd454756553dde659e4d22c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1289, "license_type": "no_license", "max_line_length": 110, "num_lines": 44, "path": "/forecast-daemon/request_handler.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import requests\nimport dateutil.parser\nfrom requests.auth import AuthBase\n\n\nclass TokenAuth(AuthBase):\n \"\"\"Attaches HTTP Token Authentication to the given Request object.\"\"\"\n\n def __init__(self, token):\n # setup any auth-related data here\n self.token = token\n\n def __call__(self, r):\n # modify and return the request\n r.headers['Authorization'] = \"token %s\" % self.token\n return r\n\n\nclass RequestHandler:\n def __init__(self, configuration):\n self.configuration = configuration\n self.auth = TokenAuth(self.configuration['api_key'])\n\n def fetch_forecast(self):\n\n try:\n r = requests.get(self.configuration['url'], auth=self.auth, timeout=1)\n except Exception as e:\n print e.message\n return None\n\n if r.status_code == requests.codes.ok:\n response = r.json()\n\n if response['count'] == 1:\n settings = []\n for setting in response['results'][0]['relaySettings']:\n settings.append(\n {'timestamp': dateutil.parser.parse(setting['timestamp']), 'relay': setting['relay']})\n return settings\n else:\n return None\n else:\n return None\n" }, { "alpha_fraction": 0.6397616267204285, "alphanum_fraction": 0.6446370482444763, "avg_line_length": 30.288135528564453, "blob_id": "5b233435d61d863268c1d0dcc0ee82d41fa681ac", "content_id": "aa0b6a5e2d0d2e2843d9bbcfebdf4963fc621ac1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1846, "license_type": "no_license", "max_line_length": 77, "num_lines": 59, "path": "/legacy/display_widgets/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.users.models import User\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.indexes.models import Index\nfrom gridplatform.trackuser.managers import CustomerBoundManager\n\n\nclass UserCustomerBoundManager(CustomerBoundManager):\n _field = 'user__customer'\n\n\nclass DashboardWidget(models.Model):\n LEFT_COLUMN = 0\n RIGHT_COLUMN = 1\n COLUMN_CHOICES = (\n (LEFT_COLUMN, _('Left')),\n (RIGHT_COLUMN, _('Right')),\n )\n CONSUMPTION_GRAPH = 0\n GAUGE = 1\n INDEX_GRAPH = 2\n RATE_GRAPH = 3\n COOLDOWN_GRAPH = 4\n PRODUCTION_GRAPH = 5\n\n WIDGET_TYPE_CHOICES = (\n (CONSUMPTION_GRAPH, _('Consumption Graph')),\n (GAUGE, _('Gauge')),\n (INDEX_GRAPH, _('Index Graph')),\n (RATE_GRAPH, _('Rate Graph')),\n (COOLDOWN_GRAPH, _('Mean Cool-down Temperature Graph')),\n (PRODUCTION_GRAPH, _('Production Graph')),\n )\n\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n column = models.IntegerField(_('Column'), choices=COLUMN_CHOICES)\n row = models.IntegerField()\n collection = models.ForeignKey(Collection, on_delete=models.CASCADE,\n null=True)\n index = models.ForeignKey(Index, on_delete=models.CASCADE, null=True)\n widget_type = models.IntegerField(_('Type'), choices=WIDGET_TYPE_CHOICES)\n\n objects = UserCustomerBoundManager()\n\n def get_icon(self):\n \"\"\"\n Returns icon string for this C{DashboardWidget}.\n \"\"\"\n if self.collection_id:\n return self.collection.get_icon()\n else:\n assert self.index_id\n return self.index.get_icon()\n" }, { "alpha_fraction": 0.5074403285980225, "alphanum_fraction": 0.5381375551223755, "avg_line_length": 36.62323760986328, "blob_id": "bf53e62f47ed7e53c52047165856e1a1b07ad318", "content_id": "854bc0dc9f0f62f2d5899d8c2ff82356690f66c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10685, "license_type": "no_license", "max_line_length": 77, "num_lines": 284, "path": "/gridplatform/datasequences/test_utils.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.test import SimpleTestCase\n\nimport pytz\n\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .utils import _pad_ranged_sample_sequence\nfrom .utils import add_ranged_sample_sequences\nfrom .utils import aggregate_sum_ranged_sample_sequence\nfrom .utils import subtract_ranged_sample_sequences\n\n\nclass AggregateSumRangedSampleSequenceTest(SimpleTestCase):\n def test_noop(self):\n \"\"\"\n Sanity check; grouping hours to hours should not alter data.\n \"\"\"\n start = datetime.datetime(2014, 4, 14, 12, 0, tzinfo=pytz.utc)\n data = [\n RangedSample(\n start,\n start + datetime.timedelta(hours=1),\n PhysicalQuantity(1, 'liter')),\n RangedSample(\n start + datetime.timedelta(hours=1),\n start + datetime.timedelta(hours=2),\n PhysicalQuantity(2, 'liter')),\n RangedSample(\n start + datetime.timedelta(hours=2),\n start + datetime.timedelta(hours=3),\n PhysicalQuantity(5, 'liter')),\n ]\n resolution = condense.HOURS\n timezone = pytz.utc\n self.assertEqual(\n list(\n aggregate_sum_ranged_sample_sequence(\n data, resolution, timezone)),\n data)\n\n def test_timezone(self):\n \"\"\"\n Grouping by days should match days in specified timezone rather than\n input data timezone.\n \"\"\"\n start = datetime.datetime(2014, 1, 14, 21, 0, tzinfo=pytz.utc)\n data = [\n RangedSample(\n start,\n start + datetime.timedelta(hours=1),\n PhysicalQuantity(1, 'liter')),\n RangedSample(\n start + datetime.timedelta(hours=1),\n start + datetime.timedelta(hours=2),\n PhysicalQuantity(2, 'liter')),\n RangedSample(\n start + datetime.timedelta(hours=2),\n start + datetime.timedelta(hours=3),\n PhysicalQuantity(5, 'liter')),\n ]\n resolution = condense.DAYS\n timezone = pytz.timezone('Europe/Copenhagen')\n expected = [\n RangedSample(\n datetime.datetime(2014, 1, 14, tzinfo=timezone),\n datetime.datetime(2014, 1, 15, tzinfo=timezone),\n PhysicalQuantity(3, 'liter')),\n RangedSample(\n datetime.datetime(2014, 1, 15, tzinfo=timezone),\n datetime.datetime(2014, 1, 16, tzinfo=timezone),\n PhysicalQuantity(5, 'liter')),\n ]\n self.assertEqual(\n list(\n aggregate_sum_ranged_sample_sequence(\n data, resolution, timezone)),\n expected)\n\n\nclass PadSampleSequenceTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.sequence = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, h)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, h + 1)),\n PhysicalQuantity(1, 'joule')) for h in range(3)]\n self.from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n self.to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1, 3))\n\n def test_none_missing(self):\n self.assertEqual(\n self.sequence,\n list(_pad_ranged_sample_sequence(\n self.sequence, self.from_timestamp, self.to_timestamp,\n condense.HOURS)))\n\n def test_start_missing(self):\n self.sequence[0] = None\n self.assertEqual(\n self.sequence,\n list(_pad_ranged_sample_sequence(\n (sample for sample in self.sequence if sample is not None),\n self.from_timestamp, self.to_timestamp, condense.HOURS)))\n\n def test_middle_missing(self):\n self.sequence[1] = None\n self.assertEqual(\n self.sequence,\n list(_pad_ranged_sample_sequence(\n (sample for sample in self.sequence if sample is not None),\n self.from_timestamp, self.to_timestamp, condense.HOURS)))\n\n def test_end_missing(self):\n self.sequence[-1] = None\n self.assertEqual(\n self.sequence,\n list(_pad_ranged_sample_sequence(\n (sample for sample in self.sequence if sample is not None),\n self.from_timestamp, self.to_timestamp, condense.HOURS)))\n\n\nclass AddRangedSampleSequencesTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_empty(self):\n self.assertEqual(\n [],\n list(\n add_ranged_sample_sequences(\n [],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n condense.DAYS)))\n\n def test_one_empty_datasequence(self):\n self.assertEqual(\n [],\n list(\n add_ranged_sample_sequences(\n [[]],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n condense.DAYS)))\n\n def test_more_datasequences(self):\n sequence = iter(\n add_ranged_sample_sequences(\n [\n [\n RangedSample(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(7, 'joule'))],\n [\n RangedSample(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(42, 'joule'))]],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n condense.DAYS))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(49, 'joule')),\n next(sequence))\n\n with self.assertRaises(StopIteration):\n next(sequence)\n\n\nclass SubtractRangedSampleSequencesTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_empty(self):\n sequence = iter(subtract_ranged_sample_sequences([], []))\n with self.assertRaises(StopIteration):\n next(sequence)\n\n def test_matching_samples(self):\n sequence = iter(subtract_ranged_sample_sequences(\n [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(19, 'joule')),\n ], [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(13, 'joule')),\n ]))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(6, 'joule')),\n next(sequence))\n\n with self.assertRaises(StopIteration):\n next(sequence)\n\n def test_a_before_b(self):\n sequence = iter(subtract_ranged_sample_sequences(\n [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(19, 'joule')),\n ], [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone.localize(datetime.datetime(2014, 1, 3)),\n PhysicalQuantity(13, 'joule')),\n ]))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(19, 'joule')),\n next(sequence))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone.localize(datetime.datetime(2014, 1, 3)),\n -PhysicalQuantity(13, 'joule')),\n next(sequence))\n\n with self.assertRaises(StopIteration):\n next(sequence)\n\n def test_b_before_a(self):\n sequence = iter(subtract_ranged_sample_sequences(\n [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone.localize(datetime.datetime(2014, 1, 3)),\n PhysicalQuantity(19, 'joule')),\n ], [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n PhysicalQuantity(13, 'joule')),\n ]))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n -PhysicalQuantity(13, 'joule')),\n next(sequence))\n\n self.assertEqual(\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone.localize(datetime.datetime(2014, 1, 3)),\n PhysicalQuantity(19, 'joule')),\n next(sequence))\n\n with self.assertRaises(StopIteration):\n next(sequence)\n" }, { "alpha_fraction": 0.5011214017868042, "alphanum_fraction": 0.5243452191352844, "avg_line_length": 38.045196533203125, "blob_id": "bcf3c6efe446e2d4ff31eee27ae58684d829b83e", "content_id": "6cdf012383a46e06f1c9b797ed08ad7c0864a6dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27644, "license_type": "no_license", "max_line_length": 79, "num_lines": 708, "path": "/legacy/energy_use_reports/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\nfrom datetime import datetime\nfrom datetime import date\nfrom mock import patch\nimport unittest\n\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\n\nimport pytz\n\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.tests import TestDataSeries\nfrom legacy.measurementpoints.models import CostCalculation\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.users.models import User\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform import trackuser\nfrom gridplatform.providers.models import Provider\n\nfrom .forms import GenerateEnergyUseReportForm\nfrom .tasks import EnergyUseReportTask\nfrom .tasks import AreaErrorCollector\nfrom .models import EnergyUseArea\nfrom .models import EnergyUseReport\nfrom .views import FinalizeEnergyUseReportView\n\n\nclass mock_scheduled(object):\n def values(self):\n return []\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass GenerateEnergyUseReportFormTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.energy_use_report = EnergyUseReport.objects.create(\n customer=self.customer,\n title_plain='Test energy use report',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.energy_use_area = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coffee production')\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_validation_failure(self):\n form = GenerateEnergyUseReportForm(\n {'energy_use_report': None,\n 'from_date': None,\n 'to_date': None})\n\n with patch('celery.task.control.inspect.scheduled',\n new=mock_scheduled):\n self.assertFalse(form.is_valid())\n\n def test_date_validation_failure(self):\n form = GenerateEnergyUseReportForm(\n {'energy_use_report': self.energy_use_report.id,\n 'from_date': '2013-02-01',\n 'to_date': '2013-01-01'})\n\n with patch('legacy.energy_use_reports.forms._') as mock:\n self.assertFalse(form.is_valid())\n mock.assert_called_with(\n u'The start date must be before the end date.')\n\n def test_validation_success(self):\n form = GenerateEnergyUseReportForm(\n {\n 'energy_use_report': self.energy_use_report.id,\n 'from_date': '2013-01-01',\n 'to_date': '2013-02-01',\n 'previous_period_from_date': '2012-12-01',\n 'previous_period_to_date': '2012-12-31',\n }\n )\n\n with patch('celery.task.control.inspect.scheduled',\n new=mock_scheduled):\n self.assertTrue(form.is_valid())\n\n def test_single_day_validation_success(self):\n form = GenerateEnergyUseReportForm(\n {\n 'energy_use_report': self.energy_use_report.id,\n 'from_date': '2013-01-01',\n 'to_date': '2013-01-01',\n 'previous_period_from_date': '2012-12-31',\n 'previous_period_to_date': '2012-12-31',\n }\n )\n\n with patch('celery.task.control.inspect.scheduled',\n new=mock_scheduled):\n self.assertTrue(form.is_valid())\n\n\n@override_settings(\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory',\n ENCRYPTION_TESTMODE=True)\nclass StartReportGenerationViewTest(TestCase):\n fixtures = [\"super_user_and_customer.json\"]\n\n def setUp(self):\n self.customer = Customer.objects.get()\n Provider.objects.create()\n\n self.energy_use_report = EnergyUseReport.objects.create(\n customer=self.customer,\n title_plain='Test energy use report',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.energy_use_area = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coffee production')\n\n self.client.post(\n '/login/',\n {\n 'username': 'super',\n 'password': '123'})\n\n def test_validation_failure(self):\n \"\"\"\n Responds with a C{JsonResponseBadRequest} if invalid form is submitted.\n \"\"\"\n response = self.client.post(\n '/energy_use_reports/start_report/',\n data={\n 'energy_use_report': self.energy_use_report.id,\n 'from_date': '2013-02-01',\n 'to_date': '2013-01-01'})\n self.assertNotContains(response, 'XYZXYZXYZ', status_code=400)\n\n def test_validation_success(self):\n with patch('celery.task.control.inspect.scheduled',\n new=mock_scheduled):\n response = self.client.post(\n '/energy_use_reports/start_report/',\n data={\n 'energy_use_report': self.energy_use_report.id,\n 'from_date': '2013-01-01',\n 'to_date': '2013-02-01',\n 'previous_period_from_date': '2012-12-01',\n 'previous_period_to_date': '2012-12-31'})\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n\n@override_settings(\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory',\n ENCRYPTION_TESTMODE=True)\nclass CollectEnergyUseReportDataTaskTest(TestCase):\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n trackuser._set_customer(self.customer)\n self.user = User.objects.create_user(\n 'username', 'password', user_type=User.CUSTOMER_USER,\n customer=self.customer)\n\n self.energy_use_report = EnergyUseReport.objects.create(\n customer=self.customer,\n title_plain='Test energy use report',\n currency_unit='currency_dkk',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.energy_use_area = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coffee production')\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_empty_report(self):\n with replace_customer(self.customer), replace_user(self.user):\n task_status = EnergyUseReportTask.delay(\n {\n 'energy_use_report_id': self.energy_use_report.id,\n 'from_date': date(2013, 1, 1),\n 'to_date': date(2013, 1, 2),\n 'previous_period_from_date': date(2012, 12, 31),\n 'previous_period_to_date': date(2012, 12, 31),\n 'include_cost': True,\n 'include_co2': True})\n\n self.assertTrue(task_status.successful())\n\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['cost'], 0)\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['consumption'],\n 0)\n\n self.assertTrue(task_status.result['include_cost'])\n self.assertTrue(task_status.result['include_co2'])\n\n @unittest.skip(\n 'Condensing/caching currently does not provide the \"incomplete\" error')\n def test_non_empty_report(self):\n mp1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp1.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp1.save()\n mp2 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP2',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp2.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp2.save()\n\n # 0.42 DKK/kWh\n tariff = TestDataSeries.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n tariff.stored_data.create(\n timestamp=datetime(2013, 1, 1, tzinfo=self.customer.timezone),\n value=420)\n\n mp2.save()\n\n cost_graph = mp2.graph_set.create(\n role=DataRoleField.COST)\n cost = CostCalculation(\n graph=cost_graph,\n role=DataRoleField.COST,\n consumption=mp2.consumption,\n index=tariff,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n cost.full_clean(exclude=['unit'])\n cost.save()\n\n # 2 kWh extrapolated.\n mp2.consumption.stored_data.create(\n timestamp=datetime(2013, 1, 1, 1, tzinfo=self.customer.timezone),\n value=0)\n mp2.consumption.stored_data.create(\n timestamp=datetime(2013, 1, 2, tzinfo=self.customer.timezone),\n value=2000000)\n\n mp3 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP3',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp3.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp3.save()\n\n self.energy_use_area.measurement_points.add(mp1)\n self.energy_use_area.measurement_points.add(mp2)\n\n energy_use_area2 = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coke production')\n energy_use_area2.measurement_points.add(mp3)\n\n with replace_customer(self.customer), replace_user(self.user):\n task_status = EnergyUseReportTask.delay(\n {\n 'energy_use_report_id': self.energy_use_report.id,\n 'from_date': date(2013, 1, 1),\n 'to_date': date(2013, 1, 2),\n 'include_cost': True,\n 'include_co2': True})\n\n self.assertTrue(task_status.successful())\n\n # should be 2 kWh\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['consumption'],\n 2)\n\n # should cost 0.84 DKK = 0.42 DKK/kWh * 2 kWh\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['cost'],\n Fraction(84, 100))\n\n self.assertEqual(\n task_status.result['data'][energy_use_area2.id]['cost'], 0)\n self.assertEqual(\n task_status.result['data'][energy_use_area2.id]['consumption'], 0)\n\n unicode_errors = map(unicode, task_status.result['errors'])\n\n expected_errors = []\n error_collector = AreaErrorCollector(\n expected_errors, mp1, self.energy_use_area)\n error_collector.extrapolated_consumption_current_period()\n error_collector.extrapolated_consumption_previous_period()\n error_collector.no_tariff()\n\n error_collector = AreaErrorCollector(\n expected_errors, mp2, self.energy_use_area)\n error_collector.extrapolated_consumption_current_period()\n error_collector.extrapolated_consumption_previous_period()\n error_collector.extrapolated_cost_current_period()\n error_collector.extrapolated_cost_previous_period()\n\n for expected_error in map(unicode, expected_errors):\n self.assertIn(expected_error, unicode_errors)\n\n @unittest.skip(\n 'Condensing/caching currently does not provide the \"incomplete\" error')\n def test_non_empty_report_with_main_measurement_points(self):\n mp1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp1.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp1.save()\n\n mp2 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP2',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp2.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp2.save()\n\n # 0.42 DKK/kWh\n tariff = TestDataSeries.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n tariff.stored_data.create(\n timestamp=datetime(2013, 1, 1, tzinfo=self.customer.timezone),\n value=420)\n\n cost_graph = mp2.graph_set.create(role=DataRoleField.COST)\n cost = CostCalculation(\n graph=cost_graph,\n consumption=mp2.consumption,\n index=tariff,\n utility_type=mp2.utility_type,\n role=DataRoleField.COST)\n cost.full_clean(exclude=['unit'])\n cost.save()\n\n # 2 kWh extrapolated.\n mp2.consumption.stored_data.create(\n timestamp=datetime(2013, 1, 1, 1, tzinfo=self.customer.timezone),\n value=0)\n mp2.consumption.stored_data.create(\n\n timestamp=datetime(2013, 1, 2, tzinfo=self.customer.timezone),\n value=2000000)\n\n mp3 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='MP3',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp3.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n mp3.save()\n\n # 4 kWh extrapolated\n mp3.consumption.stored_data.create(\n timestamp=datetime(2013, 1, 1, 1, tzinfo=self.customer.timezone),\n value=0)\n mp3.consumption.stored_data.create(\n timestamp=datetime(2013, 1, 2, tzinfo=self.customer.timezone),\n value=4000000)\n\n cost_graph = mp3.graph_set.create(role=DataRoleField.COST)\n cost = CostCalculation(\n graph=cost_graph,\n consumption=mp3.consumption,\n index=tariff,\n utility_type=mp3.utility_type,\n role=DataRoleField.COST)\n cost.full_clean(exclude=['unit'])\n cost.save()\n\n self.energy_use_area.measurement_points.add(mp1)\n self.energy_use_area.measurement_points.add(mp2)\n\n self.energy_use_report.main_measurement_points.add(mp3)\n\n with replace_customer(self.customer), replace_user(self.user):\n task_status = EnergyUseReportTask.delay(\n {\n 'energy_use_report_id': self.energy_use_report.id,\n 'from_date': date(2013, 1, 1),\n 'to_date': date(2013, 1, 2),\n 'include_cost': True,\n 'include_co2': True})\n\n self.assertTrue(task_status.successful())\n\n # should be 2 kWh\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['consumption'],\n 2)\n\n # should be 4 kWh\n self.assertEqual(\n task_status.result['total_consumption'], 4)\n\n self.assertEqual(\n task_status.result['total_previous_consumption'], 0)\n\n # should cost 0.84 DKK = 0.42 DKK/kWh * 2 kWh\n self.assertEqual(\n task_status.result['data'][self.energy_use_area.id]['cost'],\n Fraction(84, 100))\n\n # should cost 1.68 DKK = 0.42 DKK/kWh * 4 kWh\n self.assertEqual(\n task_status.result['total_cost'], Fraction(168, 100))\n\n self.assertEqual(\n task_status.result['total_previous_cost'], 0)\n\n unicode_errors = map(unicode, task_status.result['errors'])\n\n expected_errors = []\n error_collector = AreaErrorCollector(\n expected_errors, mp1, self.energy_use_area)\n error_collector.extrapolated_consumption_current_period()\n error_collector.extrapolated_consumption_previous_period()\n error_collector.no_tariff()\n\n error_collector = AreaErrorCollector(\n expected_errors, mp2, self.energy_use_area)\n error_collector.extrapolated_consumption_current_period()\n error_collector.extrapolated_consumption_previous_period()\n error_collector.extrapolated_cost_current_period()\n error_collector.extrapolated_cost_previous_period()\n\n for expected_error in map(unicode, expected_errors):\n self.assertIn(expected_error, unicode_errors)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass FinalizeEnergyUseReportViewTest(TestCase):\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.energy_use_report = EnergyUseReport.objects.create(\n customer=self.customer,\n title_plain='Test energy use report',\n currency_unit='currency_dkk',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.energy_use_area1 = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coffee production')\n\n self.energy_use_area2 = EnergyUseArea.objects.create(\n report=self.energy_use_report,\n name_plain='coke production')\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_generate_report(self):\n view = FinalizeEnergyUseReportView()\n view.generate_report(\n {\n 'energy_use_report': self.energy_use_report.id,\n 'data': {\n self.energy_use_area1.id: {\n 'consumption': Fraction(2, 3),\n 'cost': Fraction(1, 3),\n 'co2': Fraction(1, 4),\n 'previous_consumption': Fraction(22, 30),\n 'previous_cost': Fraction(11, 3),\n 'previous_co2': Fraction(11, 4),\n },\n self.energy_use_area2.id: {\n 'consumption': Fraction(4, 7),\n 'cost': Fraction(7, 11),\n 'co2': Fraction(5, 4),\n 'previous_consumption': Fraction(2, 7),\n 'previous_cost': Fraction(65, 110),\n 'previous_co2': Fraction(3, 4),\n },\n },\n 'errors': [\n 'There is less coffeine in coke than in coffee',\n 'There is too little coke in coke',\n 'And here comes a long error message, which describe in'\n 'great detail why coffee is broke, and in particular the'\n 'cost of coffee is undefined. '\n 'It appears that coffee tends'\n 'to just evaporate before our eyes, and as such our coffee'\n 'demands cannot be met by any amount of coffee supply. '\n 'Come '\n 'to think of it --- coffee should really be a utility type'\n 'of its own.'],\n 'from_date': date(2013, 8, 1),\n 'to_date': date(2013, 8, 30),\n 'previous_from_date': date(2013, 7, 1),\n 'previous_to_date': date(2013, 7, 31),\n 'graph_data': {\n 'options': {\n 'colors': ['#BEEEFF'],\n 'yaxis': {\n 'title': 'kWh',\n },\n 'xaxis': {\n 'title': 'Total 46 kWh',\n 'ticks': [(0.33, '1/3')],\n 'min': 0,\n 'max': 47,\n },\n },\n 'data': [\n {\n 'bars': {'show': True},\n 'data': [(0, 1), (2, 5)],\n },\n ],\n },\n 'include_cost': False,\n 'include_co2': False,\n },\n datetime.now(pytz.utc))\n\n def test_generate_report_with_cost(self):\n view = FinalizeEnergyUseReportView()\n view.generate_report(\n {\n 'energy_use_report': self.energy_use_report.id,\n 'data': {\n self.energy_use_area1.id: {\n 'consumption': Fraction(2, 3),\n 'cost': Fraction(1, 3),\n 'co2': Fraction(1, 4),\n 'previous_consumption': Fraction(22, 30),\n 'previous_cost': Fraction(11, 3),\n 'previous_co2': Fraction(11, 4),\n },\n self.energy_use_area2.id: {\n 'consumption': Fraction(4, 7),\n 'cost': Fraction(7, 11),\n 'co2': Fraction(5, 4),\n 'previous_consumption': Fraction(2, 7),\n 'previous_cost': Fraction(65, 110),\n 'previous_co2': Fraction(3, 4),\n },\n },\n 'errors': [\n 'There is less coffeine in coke than in coffee',\n 'There is too little coke in coke',\n 'And here comes a long error message, which describe in'\n 'great detail why coffee is broke, and in particular the'\n 'cost of coffee is undefined. '\n 'It appears that coffee tends'\n 'to just evaporate before our eyes, and as such our coffee'\n 'demands cannot be met by any amount of coffee supply. '\n 'Come '\n 'to think of it --- coffee should really be a utility type'\n 'of its own.'],\n 'from_date': date(2013, 8, 1),\n 'to_date': date(2013, 8, 30),\n 'previous_from_date': date(2013, 7, 1),\n 'previous_to_date': date(2013, 7, 31),\n 'graph_data': {\n 'options': {\n 'colors': ['#BEEEFF'],\n 'yaxis': {\n 'title': 'kWh',\n },\n 'xaxis': {\n 'title': 'Total 46 kWh',\n 'ticks': [(0.33, '1/3')],\n 'min': 0,\n 'max': 47,\n },\n },\n 'data': [\n {\n 'bars': {'show': True},\n 'data': [(0, 1), (2, 5)],\n },\n ],\n },\n 'include_cost': True,\n 'include_co2': False,\n },\n datetime.now(pytz.utc))\n\n def test_generate_report_with_co2(self):\n view = FinalizeEnergyUseReportView()\n view.generate_report(\n {\n 'energy_use_report': self.energy_use_report.id,\n 'data': {\n self.energy_use_area1.id: {\n 'consumption': Fraction(2, 3),\n 'cost': Fraction(1, 3),\n 'co2': Fraction(1, 4),\n 'previous_consumption': Fraction(22, 30),\n 'previous_cost': Fraction(11, 3),\n 'previous_co2': Fraction(11, 4),\n },\n self.energy_use_area2.id: {\n 'consumption': Fraction(4, 7),\n 'cost': Fraction(7, 11),\n 'co2': Fraction(5, 4),\n 'previous_consumption': Fraction(2, 7),\n 'previous_cost': Fraction(65, 110),\n 'previous_co2': Fraction(3, 4),\n },\n },\n 'errors': [\n 'There is less coffeine in coke than in coffee',\n 'There is too little coke in coke',\n 'And here comes a long error message, which describe in'\n 'great detail why coffee is broke, and in particular the'\n 'cost of coffee is undefined. '\n 'It appears that coffee tends'\n 'to just evaporate before our eyes, and as such our coffee'\n 'demands cannot be met by any amount of coffee supply. '\n 'Come '\n 'to think of it --- coffee should really be a utility type'\n 'of its own.'],\n 'from_date': date(2013, 8, 1),\n 'to_date': date(2013, 8, 30),\n 'previous_from_date': date(2013, 7, 1),\n 'previous_to_date': date(2013, 7, 31),\n 'graph_data': {\n 'options': {\n 'colors': ['#BEEEFF'],\n 'yaxis': {\n 'title': 'kWh',\n },\n 'xaxis': {\n 'title': 'Total 46 kWh',\n 'ticks': [(0.33, '1/3')],\n 'min': 0,\n 'max': 47,\n },\n },\n 'data': [\n {\n 'bars': {'show': True},\n 'data': [(0, 1), (2, 5)],\n },\n ],\n },\n 'co2_graph_data': {\n 'options': {\n 'colors': ['#BEEEFF'],\n 'yaxis': {\n 'title': 'kg',\n },\n 'xaxis': {\n 'title': 'Total 46 kg',\n 'ticks': [(0.33, '1/3')],\n 'min': 0,\n 'max': 47,\n },\n },\n 'data': [\n {\n 'bars': {'show': True},\n 'data': [(0, 1), (2, 5)],\n },\n ],\n },\n 'include_cost': False,\n 'include_co2': True,\n },\n datetime.now(pytz.utc))\n" }, { "alpha_fraction": 0.773809552192688, "alphanum_fraction": 0.773809552192688, "avg_line_length": 36.33333206176758, "blob_id": "5699619762cef555ef435efdae5b6b9e712023aa", "content_id": "308c20798f8077b67788e947c315f84f95e3b671", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 336, "license_type": "no_license", "max_line_length": 74, "num_lines": 9, "path": "/documentation/source/apps/gridplatform/global_datasources.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Global Data Sources\n=====================\n\nThis app defines a :class:`~gridplatform.datasources.models.DataSource`\nspecialization\n(:class:`~gridplatform.global_datasources.models.GlobalDataSource`) shared\namong all :class:`~gridplatform.customers.models.Customer`\n\n.. autoclass:: gridplatform.global_datasources.models.GlobalDataSource\n" }, { "alpha_fraction": 0.6355623006820679, "alphanum_fraction": 0.6377912759780884, "avg_line_length": 38.01185607910156, "blob_id": "529656fe95fdd1955991a6915cbfcb24f333af7e", "content_id": "328445d89f2e876a10099b0cea3db27e1fa5d0ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9870, "license_type": "no_license", "max_line_length": 84, "num_lines": 253, "path": "/gridagentserver-protocol/gridagentserver_protocol/twisted_protocol.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import random\nfrom struct import Struct\nimport logging\n\nfrom twisted.internet.protocol import Protocol, ServerFactory, connectionDone\nfrom twisted.internet.defer import DeferredQueue, CancelledError\n\nfrom . import PROTOCOL_VERSION, SECRET\nfrom encryption import Encrypter\nfrom messages import Header, BufferReader, UnknownMessageTypeError\n\nlogger = logging.getLogger(__name__)\n\n# protocol version, ID/nonce\nhandshake_struct = Struct('!IQ')\nuint64 = Struct('!Q')\nuint32 = Struct('!I')\n\n\nclass EncryptedProtocol(Protocol):\n \"\"\"\n A protocol with ARC-4 encryption.\n\n After handshake, messages start with a 4-byte (network byte order) length\n field, and subclasses may receive/parse only complete messages.\n\n (The encryption initialisation protocol is far from perfect, but should\n work...)\n \"\"\"\n\n def __init__(self):\n self.other_id = None\n self.version = None\n\n def connectionMade(self):\n logger.debug('Connection from %s', self.transport.getPeer().host)\n self._handshake_done = False\n self._buffer = ''\n self._nonce = random.randint(0, 2 ** 64)\n self.send_handshake()\n\n def send_handshake(self):\n handshake_data = handshake_struct.pack(PROTOCOL_VERSION, self._nonce)\n logger.debug('Writing handshake %r %s', handshake_data,\n len(handshake_data))\n self.transport.write(handshake_data)\n\n def dataReceived(self, data):\n logger.debug('Received data (%s)', len(data))\n if not self._handshake_done:\n self._buffer += data\n self.receive_handshake()\n else:\n self._buffer += self._decrypt(data)\n while self.receive_message():\n pass\n\n def connectionLost(self, reason=connectionDone):\n logger.debug('Connection lost, reason: %s', reason)\n self.unregister()\n\n def receive_handshake(self):\n assert not self._handshake_done\n if len(self._buffer) < handshake_struct.size:\n return\n logger.debug('Handshake data received')\n handshake_data = self._buffer[0:handshake_struct.size]\n extra_data = self._buffer[handshake_struct.size:]\n self._buffer = ''\n self.version, self.other_id = handshake_struct.unpack(handshake_data)\n logger.info('Connection from %X, protocol %d',\n self.other_id, self.version)\n if self.version > PROTOCOL_VERSION or self.version <= 0:\n logger.info('Protocol %d not supported; disconnecting %X',\n self.version, self.other_id)\n self.transport.loseConnection()\n return\n self.init_encryption()\n self._handshake_done = True\n self.register()\n if extra_data != '':\n self.dataReceived(extra_data)\n\n def init_encryption(self):\n # initialise encryption state with nonce + secret + incoming data\n key_bytes = bytearray(SECRET)\n id_bytes = bytearray(uint64.pack(self.other_id))\n nonce_bytes = bytearray(uint64.pack(self._nonce))\n for i in range(len(nonce_bytes)):\n key_bytes[i] = key_bytes[i] ^ id_bytes[i] ^ nonce_bytes[i]\n self._encrypt = Encrypter(key_bytes)\n self._decrypt = Encrypter(key_bytes)\n\n def receive_message(self):\n if len(self._buffer) < uint32.size:\n return False\n length, = uint32.unpack_from(self._buffer)\n if len(self._buffer) < length:\n return False\n message = self._buffer[:length]\n self._buffer = self._buffer[length:]\n self.message_received(message)\n return True\n\n def write_encrypted(self, bytes):\n self.transport.write(self._encrypt(bytes))\n\n # Override this.\n def message_received(self, data):\n pass\n\n # Override this. Called after processing handshake.\n def register(self):\n pass\n\n # Override this. Called from connectionLost.\n def unregister(self):\n pass\n\n\n# gets a \"factory\" member set to the factory used to obtain it\n# connection from: self.transport.getPeer().host (ip addr as string)\nclass BaseAgentProtocol(EncryptedProtocol):\n def __init__(self):\n EncryptedProtocol.__init__(self)\n self.agent_mac = None\n # We serialise incoming/outgoing messages in these queues...\n # (Serialise as in \"order sequentially\"...)\n self.outgoing = DeferredQueue(backlog=1)\n self.incoming = DeferredQueue(backlog=1)\n\n # Called after handshake, when encryption is initialised and we have an\n # identifier (MAC address) for the other end. (Overridden + called from\n # implementation in GridAgent Server.)\n def register(self):\n \"\"\"\n Registers self in the factory handlers dictionary; disconnecting any\n currently present handler for the same agent MAC. Return True if old\n handler removed, False if no old handler existed.\n \"\"\"\n logger.debug('Adding %X to handler map', self.other_id)\n self.agent_mac = self.other_id\n return self.factory.register(self)\n\n # Called on disconnect. Return true if agent has already reconnected,\n # i.e. new connection for same id exist. (Overridden + called from\n # implementation in GridAgent Server.)\n def unregister(self):\n \"\"\"\n Stops sending messages from the outgoing queue and removes self from\n the factory handlers dictionary; return True if already replaced, False\n otherwise.\n \"\"\"\n if self.other_id:\n logger.debug('Removing %X from handler map', self.other_id)\n for deferred in self.outgoing.waiting:\n deferred.cancel()\n return self.factory.unregister(self)\n\n # Called when a complete message is arrived (the base class decrypts and\n # reads the length field at the start of each message).\n def message_received(self, data):\n \"\"\"\n Parses a complete, decrypted message and puts it on the incoming queue.\n Resumes the sending of messages from the outgoing queue if indicated by\n resume_sending_after().\n \"\"\"\n header_read = BufferReader(data[:Header.struct.size])\n try:\n header = Header.unpack(header_read, self.version)\n read = BufferReader(data[Header.struct.size:])\n message = header.MessageType.unpack(header, read, self.version)\n logger.debug('Received message of type %s', message.__class__.__name__)\n self.incoming.put(message)\n if self.transport.connected and self.resume_sending_after(message):\n # process next message when available...\n # no-op error handler to allow cancel\n self.outgoing.get().addCallbacks(self.send_message, lambda ex: None)\n except UnknownMessageTypeError as e:\n logger.info(e.message)\n\n def send_message(self, message):\n \"\"\"\n Serialises and sends a message; pauses the sending of messages\n afterwards if indicated by pause_sending_after(); otherwise, sets up\n handling/sending of the next message from the outgoing queue.\n \"\"\"\n logger.debug('Sending message of type %s', message.__class__.__name__)\n bytes = message.pack(self.version)\n self.write_encrypted(bytes)\n if self.transport.connected and not self.pause_sending_after(message):\n # process next message when available...\n # no-op error handler to allow cancel\n self.outgoing.get().addCallbacks(self.send_message, lambda ex: None)\n\n # Some messages --- software updates in particular --- demand the complete\n # attention of the GridAgent. After sending such a message, writing\n # mesages is paused/delayed until we receive an acknowledgement.\n # Override in subclass.\n def pause_sending_after(self, message):\n \"\"\"\n Specifies whether sending messages should be paused after sending a\n specific message --- by default always False; override in subclass.\n \"\"\"\n return False\n\n # See pause_sending_after\n # Override in subclass.\n def resume_sending_after(self, message):\n \"\"\"\n Specifies whether sending messages should be resumed after receiving\n (not processing) a specific message --- by default always False;\n override in subclass.\n \"\"\"\n return False\n\n\nclass BaseAgentProtocolFactory(ServerFactory):\n protocol = BaseAgentProtocol\n\n def __init__(self):\n self.handlers = {}\n\n def register(self, handler):\n \"\"\"\n Return True if this replaces an existing connection; i.e. this is a\n reconnect before/without a disconnect; False if this is a \"new\"\n connection.\n \"\"\"\n previous = self.handlers.pop(handler.agent_mac, None)\n self.handlers[handler.agent_mac] = handler\n if previous is not None:\n assert previous is not handler\n previous.transport.loseConnection()\n # handling/sending outgoing messages now safe; start processing\n if handler.transport.connected:\n # no-op error handler to allow cancel\n # (reading from the queue shouldn't \"fail\" otherwise, so this\n # shouldn't mask real errors...)\n handler.outgoing.get().addCallbacks(handler.send_message,\n lambda ex: None)\n return (previous is not None)\n\n def unregister(self, handler):\n \"\"\"\n Return True if another handler is registered for this connection,\n i.e. a reconnect has occurred before this disconnect; False if this is\n a \"normal\" disconnect.\n \"\"\"\n current = self.handlers.get(handler.agent_mac, None)\n if current is handler:\n del self.handlers[handler.agent_mac]\n return (current is not handler) and (current is not None)\n" }, { "alpha_fraction": 0.5739250183105469, "alphanum_fraction": 0.5931670665740967, "avg_line_length": 36.44852828979492, "blob_id": "dd3ce4ec4f0f7e4f4247ace60ecef5ea97c171aa", "content_id": "191217e0a9b75d8fc4fee7fd65acda9448456c77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5093, "license_type": "no_license", "max_line_length": 76, "num_lines": 136, "path": "/legacy/nordpool/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport os.path\n\nimport pytz\nfrom django.test import TestCase\n\nfrom gridplatform.global_datasources.models import GlobalDataSource\nfrom legacy.indexes.models import Index, SpotMapping\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\n\nfrom . import parser\nfrom . import importer\nfrom . import legacy\n\n\ndef week_filename(date):\n base = os.path.abspath(os.path.dirname(__file__))\n year, week, _weekday = date.isocalendar()\n return os.path.join(base, 'spot%02d%02d.sdv' % (year % 100, week))\n\n\ndef parse_file(filename):\n with open(filename, 'rb') as f:\n lines = f.readlines()\n return parser.parse_lines(lines)\n\n\nclass TestParsing(TestCase):\n def setUp(self):\n self.days = {\n 'normal': datetime.date(2012, 1, 3),\n 'switch_to_dst': datetime.date(2012, 3, 25),\n 'switch_from_dst': datetime.date(2012, 10, 28),\n 'week_partial': datetime.date(2012, 11, 12),\n }\n\n def test_parse_csv(self):\n for day in self.days.values():\n parse_file(week_filename(day))\n\n def test_extract_prices(self):\n area = 'DK1'\n currency = 'DKK'\n for day in (self.days['normal'],\n self.days['switch_to_dst'],\n self.days['switch_from_dst']):\n data = parse_file(week_filename(day))\n preliminary, final = parser.extract_prices(data, area, currency)\n self.assertEqual(len(final), 7)\n\n def test_day_entries(self):\n area = 'DK1'\n currency = 'DKK'\n tz = pytz.timezone('Europe/Copenhagen')\n\n def day_final_entries(day):\n data = parse_file(week_filename(day))\n preliminary, final = parser.extract_prices(data, area, currency)\n day_data, = filter(lambda entry: entry[0] == day, final)\n date, hourly = day_data\n return parser.day_entries(date, hourly, tz)\n\n self.assertEqual(\n len(day_final_entries(self.days['normal'])), 24)\n self.assertEqual(\n len(day_final_entries(self.days['switch_to_dst'])), 23)\n entries = day_final_entries(self.days['switch_from_dst'])\n self.assertEqual(len(entries), 25)\n # hour from 2--3 repeated with/without DST; price repeated\n self.assertEqual(entries[2][2], entries[3][2])\n self.assertEqual(entries[2][0].hour, entries[3][0].hour)\n day = self.days['week_partial']\n data = parse_file(week_filename(day))\n preliminary, final = parser.extract_prices(data, area, currency)\n day_data, = filter(lambda entry: entry[0] == day, preliminary)\n date, hourly = day_data\n self.assertEqual(len(parser.day_entries(date, hourly, tz)), 24)\n\n def test_import(self):\n spotprices = (\n {\n 'CODENAME': 'denmark_west',\n 'NORDPOOL_UNIT': 'currency_dkk*gigawatt^-1*hour^-1',\n 'UNIT': 'currency_dkk*megawatt^-1*hour^-1',\n 'NAME': 'Nordpool Denmark West DKK',\n 'CURRENCY': 'DKK',\n 'COUNTRY': 'DK',\n 'TIMEZONE': 'Europe/Copenhagen',\n 'AREA': 'DK1',\n },\n )\n ds = GlobalDataSource.objects.create(\n name='test',\n app_label='nordpool',\n codename='denmark_west',\n country='DK')\n data = parse_file(week_filename(self.days['normal']))\n importer.import_week(data, spotprices)\n self.assertEqual(ds.rawdata_set.count(), 7 * 24)\n\n data = parse_file(week_filename(self.days['week_partial']))\n importer.import_week(data, spotprices)\n self.assertEqual(ds.rawdata_set.count(), 7 * 24 + 3 * 24)\n # importing again for same week should have no effect\n importer.import_week(data, spotprices)\n self.assertEqual(ds.rawdata_set.count(), 7 * 24 + 3 * 24)\n\n def test_legacy_import(self):\n tz = pytz.timezone('Europe/Copenhagen')\n index = Index(\n unit=\"currency_dkk*megawatt^-1*hour^-1\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SPOT, name='Denmark West DKK',\n timezone=tz,\n customer=None,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n index.save()\n mapping = SpotMapping(index=index, area='DK1', currency='DKK',\n unit='currency_dkk', timezone=tz)\n mapping.save()\n\n data = parse_file(week_filename(self.days['normal']))\n legacy.import_week(data)\n self.assertEqual(index.entry_set.count(), 7 * 24)\n\n data = parse_file(week_filename(self.days['week_partial']))\n legacy.import_week(data)\n self.assertEqual(index.entry_set.count(), 7 * 24 + 3 * 24)\n # importing again for same week should have no effect\n legacy.import_week(data)\n self.assertEqual(index.entry_set.count(), 7 * 24 + 3 * 24)\n" }, { "alpha_fraction": 0.5226510167121887, "alphanum_fraction": 0.5260066986083984, "avg_line_length": 31.216217041015625, "blob_id": "576b500dd1e4dc0d348e0c27084195204065c208", "content_id": "1251f5a807e6881d421f4c15788984c9176636fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1192, "license_type": "no_license", "max_line_length": 82, "num_lines": 37, "path": "/legacy/manage_customers/templates/manage_customers/customer_block.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% spaceless %}\n{% load i18n %}\n{% load url from future %}\n{% load static from staticfiles %}\n\n<div class=\"clearfix\" data-url=\"{% url 'manage_customers-form' pk=customer.id %}\">\n {% with profile=customer %}\n <h3>\n <a href=\"{% url 'manage_customers-detail' pk=customer.id %}\">\n <img src=\"{% static 'images/detail.png' %}\" class=\"left detail-icon\">\n <span>{{ profile.name_plain }}</span>\n </a>\n </h3>\n <dl>\n <dt>{% trans \"Address:\" %}</dt>\n <dd>{{ profile.address_plain }}</dd>\n <dt>{% trans \"Postal code:\" %}</dt>\n <dd>{{ profile.postal_code_plain }}</dd>\n <dt>{% trans \"Country code:\" %}</dt>\n <dd>{{ profile.country_code_plain }}</dd>\n </dl>\n <dl>\n <dt>{% trans \"Agents:\" %}</dt>\n <dd>{{ customer.agent_set.count }}</dd>\n <dt>{% trans \"Meters:\" %}</dt>\n <dd>{{ customer.meter_set.count }}</dd>\n <dt>{% trans \"Measurement Points:\" %}</dt>\n <dd>{{ customer.count_measurementpoints }}</dd>\n </dl>\n {% endwith %}\n <span class=\"right\">\n <a class=\"open\" href=\"#\">\n <img src=\"{% static 'images/arrow-left.png' %}\" alt=\"{% trans 'Edit' %}\">\n </a>\n </span>\n</div>\n{% endspaceless %}\n" }, { "alpha_fraction": 0.650909960269928, "alphanum_fraction": 0.6568187475204468, "avg_line_length": 35.162391662597656, "blob_id": "8b8c02c83466ad15ff40a865e7a9b25e2fc9ddfb", "content_id": "cdb1e6673f2aa90d6841921df58661bb43ceba16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4231, "license_type": "no_license", "max_line_length": 71, "num_lines": 117, "path": "/gridplatform/provider_datasources/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.users.models import User\n\nfrom .models import ProviderDataSource\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProviderDataSourceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.datasource = ProviderDataSource.objects.create(\n provider=self.provider,\n unit='currency_eur*gigawatt^-1*hour^-1',\n hardware_id='provider tariff',\n )\n\n def test_unicode(self):\n unicode(self.datasource)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DataSourceManagerProviderTest(TestCase):\n def setUp(self):\n self.provider1 = Provider.objects.create()\n self.provider2 = Provider.objects.create()\n\n self.customer1 = Customer.objects.create(\n provider=self.provider1)\n self.customer2 = Customer.objects.create(\n provider=self.provider2)\n\n self.datasource = ProviderDataSource.objects.create(\n provider=self.provider1)\n\n self.user = User()\n self.user.is_authenticated = lambda: True\n\n def test_customer_can_see_own_providers_datasources(self):\n with replace_user(self.user), replace_customer(self.customer1):\n self.assertTrue(\n DataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_customer_cannot_see_other_providers_datasources(self):\n with replace_user(self.user), replace_customer(self.customer2):\n self.assertFalse(\n DataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_provider_can_see_own_datasources(self):\n self.user.provider = self.provider1\n with replace_user(self.user):\n self.assertTrue(\n DataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_provider_cannot_see_other_datasources(self):\n self.user.provider = self.provider2\n with replace_user(self.user):\n self.assertFalse(\n DataSource.objects.filter(\n id=self.datasource.id).exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProviderDataSourceManagerTest(TestCase):\n def setUp(self):\n self.provider1 = Provider.objects.create()\n self.provider2 = Provider.objects.create()\n\n self.customer1 = Customer.objects.create(\n provider=self.provider1)\n self.customer2 = Customer.objects.create(\n provider=self.provider2)\n\n self.datasource = ProviderDataSource.objects.create(\n provider=self.provider1)\n\n self.user = User()\n self.user.is_authenticated = lambda: True\n\n def test_customer_can_see_own_providers_datasources(self):\n with replace_user(self.user), replace_customer(self.customer1):\n self.assertTrue(\n ProviderDataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_customer_cannot_see_other_providers_datasources(self):\n with replace_user(self.user), replace_customer(self.customer2):\n self.assertFalse(\n ProviderDataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_provider_can_see_own_datasources(self):\n self.user.provider = self.provider1\n with replace_user(self.user):\n self.assertTrue(\n ProviderDataSource.objects.filter(\n id=self.datasource.id).exists())\n\n def test_provider_cannot_see_other_datasources(self):\n self.user.provider = self.provider2\n with replace_user(self.user):\n self.assertFalse(\n ProviderDataSource.objects.filter(\n id=self.datasource.id).exists())\n" }, { "alpha_fraction": 0.6107590794563293, "alphanum_fraction": 0.6183147430419922, "avg_line_length": 36.25032424926758, "blob_id": "d02a596d19c4d071d7385354ff27c54f3c1ca03c", "content_id": "b13525b82933fe0ec2d942ef6d6b3a68711bc250", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28720, "license_type": "no_license", "max_line_length": 90, "num_lines": 771, "path": "/legacy/devices/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport logging\nimport datetime\n\nfrom django.db import models\nfrom django.db.models import Max\nfrom django.db.models import Min\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext\nfrom django.utils.translation import ugettext_lazy as _\n\nimport pytz\nfrom model_utils import Choices\n\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.fields import MacAddressField\nfrom gridplatform.utils.format_id import format_mac, format_mbus_enhanced\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import UNIT_CHOICES\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Location\n\n\nlogger = logging.getLogger(__name__)\n\n\nUNKNOWN = 0\nGRIDAGENT = 1\nGRIDPOINT1PH = 2\nGRIDPOINT3PH = 3\nGRIDLINK = 4\nGRIDPOINT_S01 = 5\nKAMSTRUP_382 = 6\nKAMSTRUP_602 = 7\nDEIF_4002 = 8\nSCHNEIDER_PM9C = 9\nMITSUBISHI_FX1S = 10\nTEMPERATURE_SENSOR = 11\nMODBUS = 12\nMBUS = 13\nGRIDREPEATER = 14\n\n\nDEVICE_TYPE_CHOICES = (\n (UNKNOWN, _('Unknown')),\n (GRIDAGENT, _('GridAgent')),\n (GRIDPOINT1PH, _('1 phase GridPoint')),\n (GRIDPOINT3PH, _('3 phase GridPoint')),\n (GRIDLINK, _('GridLink')),\n (GRIDPOINT_S01, _('GridPoint S01 Legacy')),\n (KAMSTRUP_382, _('Kamstrup 382')),\n (KAMSTRUP_602, _('Kamstrup 602')),\n (DEIF_4002, _('DEIF 4002')),\n (SCHNEIDER_PM9C, _('Schneider PM9C')),\n (MITSUBISHI_FX1S, _('Mitsubishi FX1S')),\n (TEMPERATURE_SENSOR, _('Temperature Sensor')),\n (MODBUS, _('Modbus')),\n (MBUS, _('MBus')),\n (GRIDREPEATER, _('GridRepeater')),\n)\n\n\nclass VersionsMixin(models.Model):\n \"\"\"\n Common software/hardware version information for GridManager meters and\n agents.\n \"\"\"\n device_type = models.IntegerField(\n _('Device type'), choices=DEVICE_TYPE_CHOICES,\n default=UNKNOWN, editable=False)\n device_serial = models.IntegerField(\n _('Device serial number'), null=True, editable=False)\n hw_major = models.PositiveIntegerField(\n _('Hardware major version'), null=True, editable=False)\n hw_minor = models.PositiveIntegerField(\n _('Hardware minor version'), null=True, editable=False)\n hw_revision = models.PositiveIntegerField(\n _('Hardware revision'), null=True, editable=False)\n hw_subrevision = models.CharField(\n _('Hardware extra revision string'), max_length=12, editable=False)\n sw_major = models.PositiveIntegerField(\n _('Software major version'), null=True, editable=False)\n sw_minor = models.PositiveIntegerField(\n _('Software minor version'), null=True, editable=False)\n sw_revision = models.PositiveIntegerField(\n _('Software revision'), null=True, editable=False)\n sw_subrevision = models.CharField(\n _('Software extra revision string'), max_length=12, editable=False)\n\n class Meta:\n abstract = True\n\n def compatible_software(self):\n \"\"\"\n Finds SoftwareImage instances for the hardware model/version. If\n hardware model/version information is missing, returns an empty\n queryset.\n \"\"\"\n hw_version = (self.hw_major, self.hw_minor, self.hw_revision)\n if self.device_type == UNKNOWN or any([v is None for v in hw_version]):\n return SoftwareImage.objects.none()\n else:\n return SoftwareImage.objects.filter(\n device_type=self.device_type, hw_major=self.hw_major,\n hw_minor=self.hw_minor, hw_revision=self.hw_revision,\n hw_subrevision=self.hw_subrevision)\n\n def get_hw_version_display(self):\n hw_version = (self.hw_major, self.hw_minor, self.hw_revision)\n if any([v is None for v in hw_version]):\n return None\n else:\n version = u'{:02d}.{:02d}.{:02d}'.format(*hw_version)\n if self.hw_subrevision:\n version += u'({})'.format(self.hw_subrevision)\n return version\n\n def get_sw_version_display(self):\n sw_version = (self.sw_major, self.sw_minor, self.sw_revision)\n if any([v is None for v in sw_version]):\n return None\n else:\n version = u'{:02d}.{:02d}.{:02d}'.format(*sw_version)\n if self.sw_subrevision:\n version += u'-{}'.format(self.sw_subrevision)\n return version\n\n\nclass Agent(VersionsMixin):\n \"\"\"\n Represents a GridManager GridAgent. Not directly interesting for\n customers/users, but important to the system as all communication with\n meters is via agents.\n \"\"\"\n customer = models.ForeignKey(Customer, on_delete=models.PROTECT)\n location = models.ForeignKey(Location, on_delete=models.PROTECT,\n blank=True, null=True)\n mac = MacAddressField(_('MAC address'), unique=True)\n online = models.BooleanField(\n _('online'), default=False, editable=False)\n online_since = models.DateTimeField(\n _('online since'), null=True, editable=False)\n add_mode = models.BooleanField(\n _('in add mode'), default=False, editable=False)\n\n no_longer_in_use = models.BooleanField(\n _('no longer in use'), default=False)\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('agent')\n verbose_name_plural = _('agents')\n ordering = ['location', 'mac']\n\n def __unicode__(self):\n return unicode(self.mac)\n\n def _set_online(self, online, timestamp):\n # helper for GAS\n change = self.online != online\n if change:\n self.online = bool(online)\n if online:\n self.online_since = timestamp\n else:\n self.online_since = None\n self.save(update_fields=['online', 'online_since'])\n\n def _set_add_mode(self, add_mode, timestamp):\n # helper for GAS\n change = self.add_mode != add_mode\n if change:\n self.add_mode = add_mode\n self.save(update_fields=['add_mode'])\n\n def _set_info(self, serial, device_type, hw_version, sw_version):\n # helper for GAS\n self.device_type = device_type\n self.hw_major, self.hw_minor, self.hw_revision, self.hw_subrevision = \\\n hw_version\n self.sw_major, self.sw_minor, self.sw_revision, self.sw_subrevision = \\\n sw_version\n self.device_serial = serial\n self.save(update_fields=[\n 'device_type',\n 'hw_major', 'hw_minor', 'hw_revision', 'hw_subrevision',\n 'sw_major', 'sw_minor', 'sw_revision', 'sw_subrevision',\n 'device_serial'])\n\n def satisfies_search(self, search):\n elems = [\n self.location,\n self.mac,\n self.connection_state,\n ]\n if self.customer:\n elems.append(self.customer)\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n @property\n def connection_state(self):\n if self.online:\n return _('Online')\n else:\n return _('Offline')\n\n\nclass AgentStateChange(models.Model):\n \"\"\"\n Changelog/history for Agent.\n \"\"\"\n agent = models.ForeignKey(Agent, editable=False, on_delete=models.CASCADE)\n timestamp = models.DateTimeField(_('timestamp'), editable=False)\n online = models.BooleanField(\n _('online'), editable=False, default=False)\n add_mode = models.BooleanField(\n _('in add mode'), editable=False, default=False)\n\n\nclass AgentEvent(models.Model):\n agent = models.ForeignKey(Agent, on_delete=models.CASCADE)\n timestamp = models.DateTimeField()\n code = models.SmallIntegerField()\n message = models.CharField(max_length=128)\n\n class Meta:\n ordering = ['timestamp']\n\n\nclass Meter(EncryptedModel, VersionsMixin):\n \"\"\"\n Represents a meter, GridMeter or otherwise. Meters are automatically\n created in the system by the GridAgentServer when reported by GridAgents.\n Only location ande name are editable by users --- all other properties are\n automatically set based on reported information from agents.\n \"\"\"\n UNKNOWN = 0\n GRIDPOINT = 1\n GRIDPOINT_S01 = 2\n GRIDLINK = 3\n MITSUBISHI_FX1S = 4\n RESERVED = 5\n MBUS = 6\n MODBUS = 7\n MODBUS_ZWAVE = 8\n TEMPERATURE_SENSOR = 9\n GRIDREPEATER = 10\n GRIDPOINT_LVL2 = 11\n WIBEEE = 12\n\n CONNECTION_TYPE_CHOICES = (\n (UNKNOWN, _('Unknown')),\n (GRIDPOINT, _('GridPoint')),\n (GRIDPOINT_S01, _('GridPoint S01 Legacy')),\n (GRIDLINK, _('GridLink')),\n (MITSUBISHI_FX1S, _('Mitsubishi FX1S')),\n (RESERVED, _('Reserved')),\n (MBUS, _('MBus')),\n (MODBUS, _('Modbus')),\n (MODBUS_ZWAVE, _('Modbus via Z-wave')),\n (TEMPERATURE_SENSOR, _('Temperature sensor')),\n (GRIDREPEATER, _('GridRepeater')),\n (GRIDPOINT_LVL2, _('GridPoint Level 2')),\n (WIBEEE, _('Wibeee')),\n )\n MEASUREMENTS_INFO = Choices(\n (0, 'all_is_well', ''),\n (1, 'no_measurements_ever', _('No measurements ever.')),\n (2, 'no_measurements_within_24_hours',\n _('No measurements within the last 24 hours or more.')),\n (3, 'no_change', _('Measurements for last 24 hours are all equal.')),\n )\n CONNECTION_STATES = Choices(\n (0, 'agent_offline', _('Agent offline.')),\n (1, 'agent_online', _('Agent online.')),\n )\n ERROR_STATES = Choices(\n (0, 'no_error', ''),\n (1, 'warning', ''),\n (2, 'error', ''),\n )\n agent = models.ForeignKey(Agent, editable=False, on_delete=models.PROTECT)\n customer = models.ForeignKey(Customer, on_delete=models.PROTECT,\n editable=False)\n manufactoring_id = models.BigIntegerField(editable=False)\n connection_type = models.IntegerField(\n _('connection type'),\n choices=CONNECTION_TYPE_CHOICES,\n editable=False)\n manual_mode = models.BooleanField(\n _('in manual mode'), editable=False, default=False)\n relay_on = models.BooleanField(\n _('relay on'), editable=False, default=False)\n online = models.BooleanField(\n _('online'), editable=False, default=False)\n online_since = models.DateTimeField(\n _('online since'), null=True, editable=False)\n joined = models.BooleanField(_('joined'), editable=False, default=True)\n location = models.ForeignKey(\n Location, on_delete=models.PROTECT, blank=True, null=True)\n relay_enabled = models.BooleanField(default=False)\n name = EncryptedCharField(_('name'), max_length=50, blank=True)\n hardware_id = models.CharField(\n _('hardware id'), max_length=120, blank=True)\n\n objects = CustomerBoundManager()\n\n objects_encrypted = models.Manager()\n\n class Meta:\n verbose_name = _('meter')\n verbose_name_plural = _('meters')\n ordering = ['connection_type', 'manufactoring_id', 'id']\n\n def __unicode__(self):\n name = unicode(self.name_plain or self.name)\n if name == '' or name is None:\n name = unicode(self.get_manufactoring_id_display())\n return name\n\n def _set_state(self, control_manual, relay_on, online, timestamp):\n # helper for GAS\n change = (self.manual_mode != control_manual or\n self.relay_on != relay_on or\n self.online != online)\n if change:\n if online != self.online:\n if online:\n self.online_since = timestamp\n else:\n self.online_since = None\n self.control_manual = control_manual\n self.relay_on = relay_on\n self.online = online\n self.save(update_fields=[\n 'manual_mode', 'relay_on', 'online', 'online_since'])\n\n def satisfies_search(self, search):\n elems = [\n self,\n self.get_connection_type_display(),\n self.get_manufactoring_id_display(),\n self.agent,\n self.location,\n self.get_control_mode_display(),\n self.get_relay_state_display(),\n self.connection_state,\n ]\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n\n def get_manufactoring_id_display(self):\n # Everything is formatted like 8-byte MAC adresses --- because in\n # reality, everything is in various custom formats defined by the\n # GridAgent...\n return format_mac(self.manufactoring_id, 8)\n if self.connection_type == self.ZIGBEE or \\\n self.connection_type == self.MBUS:\n return format_mac(self.manufactoring_id, 8)\n elif self.connection_type == self.KAMSTRUP_UTILIDRIVER:\n return format_mac(self.manufactoring_id, 6)\n elif self.connection_type == self.MBUS_ENHANCED:\n return format_mbus_enhanced(self.manufactoring_id)\n else:\n return str(self.manufactoring_id)\n\n def get_control_mode_display(self):\n if self.manual_mode:\n return _('Manual')\n else:\n return _('Automatic')\n\n def get_relay_state_display(self):\n if self.relay_on:\n return _('On')\n else:\n return _('Off')\n\n @cached_property\n def latest_update(self):\n \"\"\"\n Returns the latest measurement update timestamp.\n \"\"\"\n input_ids = list(\n self.physicalinput_set.values_list('id', flat=True))\n result = None\n for input_id in input_ids:\n try:\n input_updated = RawData.objects.filter(\n datasource_id=input_id\n ).latest('timestamp').timestamp\n if not result or\\\n result < input_updated:\n result = input_updated\n except RawData.DoesNotExist:\n pass\n\n return result\n\n @cached_property\n def _measurement_change_within_24_hours(self):\n \"\"\"\n This method returns True if change has been measured\n within last 24 hours, False otherwise.\n \"\"\"\n now = datetime.datetime.now(pytz.utc)\n input_ids = list(\n self.physicalinput_set.values_list('id', flat=True))\n for input_id in input_ids:\n aggregates = RawData.objects.filter(\n datasource_id=input_id,\n timestamp__gt=now - datetime.timedelta(hours=24)).\\\n aggregate(\n min_value=Min('value'),\n max_value=Max('value'))\n if aggregates['min_value'] != aggregates['max_value']:\n return True\n return False\n\n @cached_property\n def _connection_state(self):\n if not self.agent.online:\n return Meter.CONNECTION_STATES.agent_offline\n else:\n return Meter.CONNECTION_STATES.agent_online\n\n @cached_property\n def _measurements_info(self):\n now = datetime.datetime.now(pytz.utc)\n if self.latest_update is None:\n return Meter.MEASUREMENTS_INFO.no_measurements_ever\n elif self.latest_update <= now - datetime.timedelta(days=1):\n return Meter.MEASUREMENTS_INFO.no_measurements_within_24_hours\n elif not self._measurement_change_within_24_hours:\n return Meter.MEASUREMENTS_INFO.no_change\n else:\n return Meter.MEASUREMENTS_INFO.all_is_well\n\n @cached_property\n def _error_state(self):\n if self._measurements_info in [\n Meter.MEASUREMENTS_INFO.no_measurements_ever,\n Meter.MEASUREMENTS_INFO.no_measurements_within_24_hours,\n ]:\n return Meter.ERROR_STATES.error\n elif self._measurements_info == Meter.MEASUREMENTS_INFO.no_change:\n return Meter.ERROR_STATES.warning\n elif self._connection_state in [\n Meter.CONNECTION_STATES.agent_offline,\n ]:\n return Meter.ERROR_STATES.warning\n else:\n return Meter.ERROR_STATES.no_error\n\n @cached_property\n def connection_state(self):\n if self._error_state == Meter.ERROR_STATES.error:\n return _('Error: %s %s') % (\n Meter.CONNECTION_STATES[self._connection_state],\n Meter.MEASUREMENTS_INFO[self._measurements_info])\n elif self._error_state == Meter.ERROR_STATES.warning:\n return _('Warning: %s %s') % (\n Meter.CONNECTION_STATES[self._connection_state],\n Meter.MEASUREMENTS_INFO[self._measurements_info])\n else:\n return Meter.CONNECTION_STATES[self._connection_state]\n\n def get_pulse_inputs(self):\n return self.physicalinput_set.filter(unit='impulse')\n\n def get_non_pulse_inputs(self):\n return self.physicalinput_set.exclude(unit='impulse')\n\n\nclass MeterStateChange(models.Model):\n \"\"\"\n Changelog/history for Meter.\n \"\"\"\n meter = models.ForeignKey(Meter, editable=False, on_delete=models.CASCADE)\n timestamp = models.DateTimeField(_('timestamp'), editable=False)\n manual_mode = models.BooleanField(\n _('in manual mode'), editable=False, default=False)\n relay_on = models.BooleanField(\n _('relay'), editable=False, default=False)\n online = models.BooleanField(\n _('online'), editable=False, default=False)\n\n\nclass MeterCustomerBoundManager(CustomerBoundManager):\n _field = 'meter__customer'\n\n\nclass PhysicalInput(CustomerDataSource):\n \"\"\"\n Represent an \"input\" on a meter. A physical meter may report several\n different values; e.g. current power and accumulated consumption or volume\n flow and temperature --- these must be separately selectable for use in\n monitored equipment.\n\n @ivar order: An integer that along with type helps make a physical\n input unique for any L{Meter}. For instance, on a three-phased\n Meter, each phase have similar physical input, and it makes sense\n to track which is which.\n\n @note: UNKNOWN_UNIT and UNKNOWN_TYPE are used when the GridAgent reports\n that it does not know the unit or type. This is conceptually different\n from what would be expressed by NULL/None --- \"UNKNOWN\" is here treated as\n a normal/actual value on the server side.\n \"\"\"\n UNKNOWN_ORIGIN = 0\n ELECTRICITY = 1\n DISTRICT_HEATING = 2\n TEMPERATURE = 3\n INPUT_STATES = 4\n OUTPUT_STATES = 5\n GAS = 6\n WATER = 7\n\n TYPE_CHOICES = (\n (UNKNOWN_ORIGIN, _('unknown type')),\n (ELECTRICITY, _('electricity')),\n (WATER, _('water')),\n (GAS, _('gas')),\n (DISTRICT_HEATING, _('heat')),\n (TEMPERATURE, _('temperature')),\n (INPUT_STATES, _('input states')),\n (OUTPUT_STATES, _('output states')),\n )\n type = models.IntegerField(choices=TYPE_CHOICES, editable=False)\n meter = models.ForeignKey(Meter, editable=False, on_delete=models.PROTECT)\n order = models.IntegerField(editable=False)\n store_measurements = models.BooleanField(default=True)\n\n objects = MeterCustomerBoundManager()\n objects_encrypted = models.Manager()\n\n class Meta:\n # unique_together = ((\"type\", \"unit\", \"meter\", \"order\"))\n ordering = ['order', 'type']\n verbose_name = _('physical input')\n verbose_name_plural = _('physical inputs')\n\n def __unicode__(self):\n order_to_input_map = {\n 0: ugettext('Consumption all phases'),\n 1: ugettext('Consumption phase 1'),\n 2: ugettext('Consumption phase 2'),\n 3: ugettext('Consumption phase 3'),\n 4: ugettext('Power phase 1'),\n 5: ugettext('Power phase 2'),\n 6: ugettext('Power phase 3'),\n 7: ugettext('Voltage phase 1'),\n 8: ugettext('Voltage phase 2'),\n 9: ugettext('Voltage phase 3'),\n 10: ugettext('Current phase 1'),\n 11: ugettext('Current phase 2'),\n 12: ugettext('Current phase 3'),\n }\n if self.name_plain:\n return _(u'%(meter_name)s: %(input_name)s') % {\n 'meter_name': self.meter,\n 'input_name': self.name_plain,\n }\n elif self.meter.connection_type == Meter.GRIDPOINT_LVL2 and \\\n self.order in order_to_input_map:\n return '{}: {}'.format(self.meter, order_to_input_map[self.order])\n\n else:\n return _(u'%(meter_name)s: (%(unit)s #%(order)s)') % {\n 'meter_name': self.meter,\n 'unit': self.get_unit_display(),\n 'order': self.order,\n }\n\n def save(self, *args, **kwargs):\n self.check_invariant()\n super(PhysicalInput, self).save(*args, **kwargs)\n\n def get_encryption_id(self):\n return (Customer, self.meter.customer_id)\n\n ACCUMULATION_UNITS = ('milliwatt*hour', 'impulse', 'milliliter',\n 'gram', 'second')\n\n NONACCUMULATION_UNITS = ('milliwatt', 'millikelvin', 'millivolt',\n 'milliampere', 'millihertz', 'milliliter*hour^-1',\n 'millibar', 'millinone')\n\n UNKNOWN_UNITS = ('none', )\n\n def is_accumulation(self):\n return any(\n PhysicalQuantity.compatible_units(self.unit, unit)\n for unit in self.ACCUMULATION_UNITS)\n\n @property\n def is_pulse(self):\n return PhysicalQuantity.compatible_units(self.unit, 'impulse')\n\n def get_unit_display(self):\n return dict(UNIT_CHOICES).get(self.unit, self.unit)\n\n def check_invariant(self):\n assert self.unit in self.ACCUMULATION_UNITS or \\\n self.unit in self.NONACCUMULATION_UNITS or \\\n self.unit in self.UNKNOWN_UNITS, \\\n '%s not in %s + %s + %s' % (\n self.unit, self.ACCUMULATION_UNITS,\n self.NONACCUMULATION_UNITS, self.UNKNOWN_UNITS)\n\n def get_utility_type(self):\n if self.type == self.ELECTRICITY:\n return utilitytypes.METER_CHOICES.electricity\n elif self.type == self.DISTRICT_HEATING:\n return utilitytypes.METER_CHOICES.district_heating\n elif self.type == self.GAS:\n return utilitytypes.METER_CHOICES.gas\n elif self.type == self.WATER:\n return utilitytypes.METER_CHOICES.water\n return None\n\n\n# Same fields as in the VersionsMixin abstract model --- but all fields are\n# required here; not editable and may be null there...\nclass SoftwareImage(models.Model):\n \"\"\"\n An indication that a specific software release exists.\n \"\"\"\n device_type = models.IntegerField(\n _('Device type'), choices=DEVICE_TYPE_CHOICES)\n hw_major = models.PositiveIntegerField(_('Hardware major version'))\n hw_minor = models.PositiveIntegerField(_('Hardware minor version'))\n hw_revision = models.PositiveIntegerField(_('Hardware revision'))\n hw_subrevision = models.CharField(\n _('Hardware extra revision string'), max_length=12)\n sw_major = models.PositiveIntegerField(_('Software major version'))\n sw_minor = models.PositiveIntegerField(_('Software minor version'))\n sw_revision = models.PositiveIntegerField(_('Software revision'))\n sw_subrevision = models.CharField(\n _('Software extra revision string'), max_length=12)\n\n class Meta:\n verbose_name = _('software image')\n verbose_name_plural = _('software images')\n ordering = ['device_type',\n 'hw_major', 'hw_minor', 'hw_revision', 'hw_subrevision',\n 'sw_major', 'sw_minor', 'sw_revision', 'sw_subrevision']\n\n def get_hw_version_display(self):\n version = u'{:02d}.{:02d}.{:02d}'.format(\n self.hw_major, self.hw_minor, self.hw_revision)\n if self.hw_subrevision:\n version += u'({})'.format(self.hw_subrevision)\n return version\n\n def get_sw_version_display(self):\n version = u'{:02d}.{:02d}.{:02d}'.format(\n self.sw_major, self.sw_minor, self.sw_revision)\n if self.sw_subrevision:\n version += u'({})'.format(self.sw_subrevision)\n return version\n\n\n# NOTE: copy from datasequences/models/__init__.py --- but makes more sense\n# here...\nTYPE_UNIT_PAIR_TO_ROLE_MAP = {\n (PhysicalInput.ELECTRICITY, 'milliwatt*hour'): DataRoleField.CONSUMPTION,\n (PhysicalInput.ELECTRICITY, 'milliwatt'): DataRoleField.POWER,\n (PhysicalInput.ELECTRICITY, 'millivolt'): DataRoleField.VOLTAGE,\n (PhysicalInput.ELECTRICITY, 'milliampere'): DataRoleField.CURRENT,\n (PhysicalInput.ELECTRICITY, 'millinone'): DataRoleField.POWER_FACTOR,\n\n (PhysicalInput.DISTRICT_HEATING, 'milliwatt*hour'): (\n DataRoleField.CONSUMPTION),\n (PhysicalInput.DISTRICT_HEATING, 'milliwatt'): DataRoleField.POWER,\n (PhysicalInput.DISTRICT_HEATING, 'milliliter'): DataRoleField.VOLUME,\n (PhysicalInput.DISTRICT_HEATING, 'milliliter*hour^-1'): (\n DataRoleField.VOLUME_FLOW),\n\n (PhysicalInput.GAS, 'milliliter'): DataRoleField.CONSUMPTION,\n (PhysicalInput.GAS, 'milliliter*hour^-1'): DataRoleField.VOLUME_FLOW,\n\n (PhysicalInput.WATER, 'milliliter'): DataRoleField.CONSUMPTION,\n (PhysicalInput.WATER, 'milliliter*hour^-1'): DataRoleField.VOLUME_FLOW,\n\n (PhysicalInput.TEMPERATURE, 'millikelvin'): (\n DataRoleField.ABSOLUTE_TEMPERATURE),\n\n # UGLY-HACK: While we wait for agent to support unspecified register values\n # for modbus, we cheat and use millibar for efficiency.\n (PhysicalInput.ELECTRICITY, 'millibar'): DataRoleField.EFFICIENCY,\n}\n\n\n@receiver(post_save, sender=PhysicalInput)\ndef autocreate_datasequence(sender, instance, created, raw=False, **kwargs):\n from gridplatform.consumptions.models import Consumption\n from gridplatform.consumptions.models import NonpulsePeriod\n from gridplatform.datasequences.models import NonaccumulationDataSequence\n from gridplatform.datasequences.models import NonaccumulationPeriod\n from legacy.datasequence_adapters.models import NonaccumulationAdapter\n from legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter # noqa\n\n type_unit_pair = (instance.type, instance.unit)\n\n if created and not raw and type_unit_pair in TYPE_UNIT_PAIR_TO_ROLE_MAP:\n customer = instance.meter.customer\n if not customer:\n return\n\n role = TYPE_UNIT_PAIR_TO_ROLE_MAP[type_unit_pair]\n utility_type = instance.get_utility_type()\n from_timestamp = datetime.datetime.now(pytz.utc).replace(\n minute=0, second=0, microsecond=0)\n\n fake_iv = bytearray(b'\\x00' * 16)\n\n if instance.is_accumulation():\n if utility_type is None:\n return\n datasequence = Consumption.\\\n objects.create(\n customer=customer,\n unit=instance.unit,\n encryption_data_initialization_vector=fake_iv,\n name='')\n NonpulsePeriod.objects.create(\n from_timestamp=from_timestamp,\n datasequence=datasequence,\n datasource=instance)\n ConsumptionAccumulationAdapter.objects.create(\n customer=customer,\n datasequence=datasequence,\n utility_type=utility_type,\n role=role,\n unit=datasequence.unit)\n else:\n # non-accumulations\n if utility_type is None:\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.unknown\n datasequence = NonaccumulationDataSequence.objects.create(\n customer=customer,\n unit=instance.unit,\n encryption_data_initialization_vector=fake_iv,\n name='')\n NonaccumulationPeriod.objects.create(\n from_timestamp=from_timestamp,\n datasequence=datasequence,\n datasource=instance)\n NonaccumulationAdapter.objects.create(\n customer=customer,\n datasequence=datasequence,\n utility_type=utility_type,\n role=role,\n unit=instance.unit)\n" }, { "alpha_fraction": 0.634973406791687, "alphanum_fraction": 0.6356382966041565, "avg_line_length": 26.851852416992188, "blob_id": "33b2f31cffc4e027b884cb19d8b1da48f3f664fe", "content_id": "2a1b9b7fb7f16c48f34c51a647251f26cbe1ce2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 76, "num_lines": 54, "path": "/gridplatform/reports/csv.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport cStringIO\nfrom contextlib import closing\n\nimport unicodecsv\nfrom django.http import HttpResponse\n\n__all__ = ['generate_csv', 'serve_csv']\n\n\nclass _excel_semicolon(unicodecsv.excel):\n delimiter = b';'\n\n\ndef generate_csv(data, header=None):\n \"\"\"\n Format provided data as CSV and return it as a byte string.\n\n :param data: Iterable yielding data for each CSV row.\n\n :param header: Optional header row data.\n\n :return: Bytestring with Excel-compatible CSV-formatted data.\n \"\"\"\n with closing(cStringIO.StringIO()) as outfile:\n # BOM included for Excel-compatibility --- assuming that this is the\n # \"start of the file\"\n bom = b'\\xef\\xbb\\xbf'\n outfile.write(bom)\n writer = unicodecsv.writer(outfile, dialect=_excel_semicolon)\n if header is not None:\n writer.writerow(header)\n if isinstance(data, list):\n for line in data:\n writer.writerow(line)\n else:\n for utility_type, values in data.iteritems():\n for line in values['data']:\n writer.writerow(line)\n\n return outfile.getvalue()\n\n\ndef serve_csv(data, header=None):\n \"\"\"\n Format provided data as CSV and return it as a text/csv HttpResponse.\n\n :see: :func:`.generate_csv`.\n \"\"\"\n csv = generate_csv(data, header)\n return HttpResponse(csv, content_type='text/csv')\n" }, { "alpha_fraction": 0.6130183339118958, "alphanum_fraction": 0.6174371242523193, "avg_line_length": 37.966888427734375, "blob_id": "8cb7424ad1d9dc1f00e9339b82cbf902a3a60d40", "content_id": "9a0fb8905a18ef7b1a05383ee297bb60d4705f13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5884, "license_type": "no_license", "max_line_length": 79, "num_lines": 151, "path": "/gridplatform/datasources/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework import status\nfrom rest_framework.response import Response\nimport pytz\n\nfrom gridplatform.rest.viewsets import NestedMixin\nfrom gridplatform.utils.paginator import parse_date_or_404\nfrom gridplatform.utils.serializers import PointSampleSerializer\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom rest_framework.templatetags.rest_framework import replace_query_param\n\nfrom . import models\nfrom . import serializers\n\n\ndef _unit_check(unit, expected_unit):\n if PhysicalQuantity.compatible_units(unit, expected_unit):\n return {}\n else:\n return {\n 'unit': [b'unit %s is not compatible with data source unit %s' % (\n unit, expected_unit)],\n }\n\n\nclass RawDataViewSetBase(viewsets.ModelViewSet):\n method_name = 'raw_sequence'\n\n def list(self, request, *args, **kwargs):\n if 'datasource_id' in kwargs:\n # DataSource instance\n owner_id = kwargs.get('datasource_id')\n owner_model = getattr(self.model, 'datasource').field.rel.to\n else:\n # NonaccumulationDataSequence\n owner_id = kwargs.get('datasequence_id')\n owner_model = models.NonaccumulationDataSequence\n owner = get_object_or_404(owner_model, pk=owner_id)\n # NOTE: Same view used by both provider and customer users, so\n # get_customer() is not well-defined. Also same view is used for both\n # global as well as customer data sources' raw data, so fetching \"the\n # customer\" via some relation is not possible either.\n timezone = pytz.utc\n return self._list(request, owner, timezone)\n\n def _list(self, request, owner, timezone):\n unit = owner.unit\n date_query_param = request.QUERY_PARAMS.get('date')\n date = date_query_param or timezone.normalize(\n datetime.datetime.now(timezone)).date()\n date = parse_date_or_404(date)\n from_timestamp = timezone.localize(\n datetime.datetime.combine(date, datetime.time()))\n to_timestamp = timezone.localize(\n datetime.datetime.combine(\n date + datetime.timedelta(days=1), datetime.time()))\n method = getattr(owner, self.method_name)\n data = method(from_timestamp, to_timestamp)\n serializer = PointSampleSerializer(\n data, many=True, context={'unit': unit})\n\n base_url = request and request.build_absolute_uri() or ''\n next_date = owner.next_valid_date(date, timezone)\n if next_date:\n next_url = replace_query_param(base_url, 'date', next_date)\n else:\n next_url = None\n previous_date = owner.previous_valid_date(date, timezone)\n if previous_date:\n previous_url = replace_query_param(base_url, 'date', previous_date)\n else:\n previous_url = None\n return Response({\n 'next': next_url,\n 'previous': previous_url,\n 'results': serializer.data,\n })\n\n def create(self, request, *args, **kwargs):\n bulk = isinstance(request.DATA, list)\n if bulk:\n return self._bulk_create(request, *args, **kwargs)\n else:\n return self._create(request, *args, **kwargs)\n\n def _create(self, request, *args, **kwargs):\n serializer = self.serializer_class(\n data=request.DATA,\n files=request.FILES,\n context={'request': request})\n\n if serializer.is_valid():\n datasource = \\\n self.model._meta.get_field('datasource').rel.to.objects.get(\n id=request.parser_context['kwargs']['datasource_id'])\n errors = _unit_check(request.DATA['unit'], datasource.unit)\n if errors:\n serializer._errors = errors\n else:\n serializer.save(force_insert=True)\n headers = self.get_success_headers(serializer.data)\n return Response(\n serializer.data, status=status.HTTP_201_CREATED,\n headers=headers)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def _bulk_create(self, request, *args, **kwargs):\n serializer = self.serializer_class(\n data=request.DATA,\n files=request.FILES,\n many=True)\n if serializer.is_valid():\n datasource = \\\n self.model._meta.get_field('datasource').rel.to.objects.get(\n id=request.parser_context['kwargs']['datasource_id'])\n errors = []\n for data in request.DATA:\n errors.append(_unit_check(data['unit'], datasource.unit))\n if any(errors):\n serializer._errors = errors\n else:\n for obj in serializer.object:\n obj.datasource_id = datasource.id\n serializer.save(force_insert=True)\n headers = self.get_success_headers(serializer.data)\n return Response(\n serializer.data, status=status.HTTP_201_CREATED,\n headers=headers)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def metadata(self, request):\n res = super(RawDataViewSetBase, self).metadata(request)\n res['bulk_actions'] = ['POST']\n return res\n\n\nclass RawDataViewSet(NestedMixin, RawDataViewSetBase):\n model = models.RawData\n serializer_class = serializers.RawDataWithUnitSerializer\n\n\nclass DataSourceViewSet(NestedMixin, viewsets.ModelViewSet):\n model = models.DataSource\n serializer_class = serializers.DataSourceSerializer\n" }, { "alpha_fraction": 0.6899224519729614, "alphanum_fraction": 0.6937984228134155, "avg_line_length": 20.5, "blob_id": "2147222bbb25ac1d996e23e956af4cc886ea3758", "content_id": "94ca5c6fa83410519ca464723012c27a08093a6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 64, "num_lines": 12, "path": "/legacy/indexes/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport exceptions\n\n\nclass IndexWarning(exceptions.UserWarning):\n \"\"\"\n Warnings from the index app is issued through this category.\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.6408839821815491, "alphanum_fraction": 0.6408839821815491, "avg_line_length": 29.16666603088379, "blob_id": "d4d473858eacdc70d8f1d1d3c5fd0a9083c1dfef", "content_id": "392685ab68584063dcb1d51896db4ec6e8d89808", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "no_license", "max_line_length": 79, "num_lines": 12, "path": "/gridplatform/encryption/filters.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import django_filters\n\n\nclass DecryptingSearchFilter(django_filters.CharFilter):\n \"\"\"\n A :class:`django_filters.CharFilter` specialization that supports searching\n in encrypted char fields.\n \"\"\"\n def filter(self, qs, value):\n if value in ([], (), {}, None, ''):\n return qs\n return qs.decrypting_search(value, [self.name])\n" }, { "alpha_fraction": 0.7386934757232666, "alphanum_fraction": 0.7437185645103455, "avg_line_length": 18.899999618530273, "blob_id": "b7dbfa33fa8e945f53c1777fc9a1830c96b6fa25", "content_id": "9680a96d88464debf5a37f2db2bd0fbc2b624168", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 199, "license_type": "no_license", "max_line_length": 39, "num_lines": 10, "path": "/gridplatform/providers/admin.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\n\nfrom .models import Provider\n\n\nadmin.site.register(Provider)\n" }, { "alpha_fraction": 0.6561693549156189, "alphanum_fraction": 0.6578471660614014, "avg_line_length": 39.145076751708984, "blob_id": "ad1a2e65672771ebe37f801faa196d9a894f0468", "content_id": "9a6fd09c47791811739e23bbedc7052f0414dc93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7750, "license_type": "no_license", "max_line_length": 79, "num_lines": 193, "path": "/legacy/enpi_reports/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\n\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\nfrom model_utils import Choices\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.preferredunits import ProductionAENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionBENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionCENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionDENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionEENPIUnitConverter\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.legacy_utils.preferredunits import get_preferred_unit_converter\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import DataSeries\n\n\nclass ENPIReport(EncryptionCustomerFieldMixin, EncryptedModel):\n title = EncryptedCharField(_('title'), max_length=50)\n\n ENERGY_DRIVER_UNIT_CHOICES = Choices(\n ('person', 'person', _('person')),\n ('meter^2', 'square_meter', _('m²')),\n ('watt*kelvin^-1', _('W/K')),\n 'production_a',\n 'production_b',\n 'production_c',\n 'production_d',\n 'production_e')\n\n energy_driver_unit = BuckinghamField(\n _('energy driver type'),\n choices=ENERGY_DRIVER_UNIT_CHOICES)\n\n objects = CustomerBoundManager()\n\n def __unicode__(self):\n return self.title_plain\n\n @cached_property\n def energy_unit(self):\n \"\"\"\n @precondition: At least one L{ENPIUseArea} with at least one\n L{ConsumptionMeasurementPoint} must exist for this C{ENPIReport}\n \"\"\"\n return DataSeries.objects.filter(\n role=DataRoleField.CONSUMPTION,\n graph__hidden=False,\n graph__collection__in=ConsumptionMeasurementPoint.objects.filter(\n enpiusearea__report_id=self.id).values_list(\n 'id', flat=True))[0:1].get().unit\n\n @cached_property\n def energy_driver_role(self):\n \"\"\"\n @precondition: At least one L{ENPIUseArea} must exist for this\n C{ENPIReport}\n \"\"\"\n return DataSeries.objects.filter(\n enpiusearea__report_id=self.id)[0:1].get().role\n\n @property\n def enpi_role(self):\n if self.energy_driver_role == DataRoleField.EMPLOYEES:\n return DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES\n elif self.energy_driver_role == DataRoleField.AREA:\n return DataRoleField.CONSUMPTION_UTILIZATION_AREA\n elif self.energy_driver_role == DataRoleField.PRODUCTION:\n return DataRoleField.PRODUCTION_ENPI\n elif self.energy_driver_role == DataRoleField.HEATING_DEGREE_DAYS:\n return DataRoleField.HEAT_LOSS_COEFFICIENT\n\n raise ValueError(\n 'An ENPI role for energi driver role %d is not defined' %\n self.energy_driver_role)\n\n @property\n def enpi_unit_converter(self):\n \"\"\"\n @precondition: At least one L{ENPIUseArea} must exist for this\n C{ENPIReport}\n\n @bug: Assumes utility type being electricity. Utility type may infact\n be mixed, but in particular, it may not need to be energy at some point\n in the future.\n \"\"\"\n if self.energy_driver_role == DataRoleField.EMPLOYEES:\n return get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n customer=self.customer)\n elif self.energy_driver_role == DataRoleField.AREA:\n return get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n customer=self.customer)\n elif self.energy_driver_role == DataRoleField.PRODUCTION:\n energy_unit_converter = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n if self.energy_driver_unit == 'production_a':\n return ProductionAENPIUnitConverter(\n energy_unit_converter.physical_unit)\n elif self.energy_driver_unit == 'production_b':\n return ProductionBENPIUnitConverter(\n energy_unit_converter.physical_unit)\n elif self.energy_driver_unit == 'production_c':\n return ProductionCENPIUnitConverter(\n energy_unit_converter.physical_unit)\n elif self.energy_driver_unit == 'production_d':\n return ProductionDENPIUnitConverter(\n energy_unit_converter.physical_unit)\n elif self.energy_driver_unit == 'production_e':\n return ProductionEENPIUnitConverter(\n energy_unit_converter.physical_unit)\n elif self.energy_driver_role == DataRoleField.HEATING_DEGREE_DAYS:\n return get_preferred_unit_converter(\n DataRoleField.HEAT_LOSS_COEFFICIENT)\n\n raise ValueError(\n 'An ENPI unit converter for energi driver role %d and energy '\n 'driver unit %s is not defined' %\n (self.energy_driver_role, self.energy_driver_unit))\n\n @property\n def enpi_unit(self):\n \"\"\"\n @precondition: At least one L{ENPIUseArea} must exist for this\n C{ENPIReport}\n \"\"\"\n return self.enpi_unit_converter.physical_unit\n\n @classmethod\n def get_energy_driver_choices(cls):\n return itertools.chain(\n (\n (cls.ENERGY_DRIVER_UNIT_CHOICES.person,\n _('person')),\n (cls.ENERGY_DRIVER_UNIT_CHOICES.square_meter,\n _('m²')),\n ),\n get_customer().get_production_unit_choices(),\n (('kelvin*day', _('degree days')),))\n\n\nclass ReportCustomerBoundManager(CustomerBoundManager):\n _field = 'report__customer'\n\n\nclass ENPIUseArea(EncryptedModel):\n report = models.ForeignKey(ENPIReport)\n name = EncryptedCharField(max_length=50)\n measurement_points = models.ManyToManyField(ConsumptionMeasurementPoint)\n energy_driver = models.ForeignKey(DataSeries)\n\n objects = ReportCustomerBoundManager()\n\n def clean(self):\n if self.energy_driver_id and self.report and \\\n not PhysicalQuantity.compatible_units(\n self.energy_driver.unit,\n self.report.energy_driver_unit):\n raise ValidationError(\n _(\n 'Energy driver with unit \"%s\" is invalid for this ENPI '\n 'report with unit \"%s\".' % (\n self.energy_driver.unit,\n self.report.energy_driver_unit)))\n\n def get_encryption_id(self):\n if self.report_id:\n return (Customer, self.report.customer_id)\n else:\n return (Customer, None)\n\n def __unicode__(self):\n return self.name_plain\n" }, { "alpha_fraction": 0.596545934677124, "alphanum_fraction": 0.5975854992866516, "avg_line_length": 40.359222412109375, "blob_id": "9e730b90921bdb10b3526b4e7e9a03021531e6d6", "content_id": "907ba24e595beef7773f894fc9896eed0ab6325f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 59640, "license_type": "no_license", "max_line_length": 82, "num_lines": 1442, "path": "/legacy/measurementpoints/models/dataseries.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nData Series\n==========\n\n This module defines L{DataSeries} as the base model for all data series.\n\n Interdependencies\n -----------------\n\n L{DataSeries} may be defined in terms of other L{DataSeries}, thus\n creating a dependency releation, forming a directed, acyclic dependency\n graph among L{DataSeries}. Various operations require traversing this\n dependency graph following the dependencies in one direction or the\n other.\n\n To avoid infinite recursion, circular dependencies are not\n allowed, i.e. no L{DataSeries} that this particular L{DataSeries}\n depends on is allowed to depend on this particular L{DataSeries}. See\n the L{DataSeries.depends_on()} method.\n\"\"\"\n\nfrom fractions import Fraction\nimport itertools\nfrom operator import attrgetter\n\nfrom django.db import models\nfrom django.db.models.query_utils import Q\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.managers import DecryptingManager\nfrom gridplatform.encryption.managers import DecryptingQuerySet\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_provider_id\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser.managers import FilteringQuerySetMixinBase\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.iter_ext import count_extended\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.iter_ext import pairwise_extended\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.models import StoredSubclassManager\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.legacy_utils.preferredunits import get_preferred_unit_converter\n\nfrom ..fields import DataRoleField\nfrom .graph import Graph\n\n\nclass UndefinedSamples(Exception):\n \"\"\"\n Exception raised when samples are supposed to be undefined, even inside the\n domain of a L{DataSeries}.\n\n Some DataSeries are interval aggregates of other DataSeries. These may not\n be well-defined if the requested period is odd-ended or too short: For\n instance if the aggregate is something pr. day and the requested period\n starts and/or ends at something different than a midnight or only spans a\n few hours.\n\n @seealso: L{HeatingDegreeDays} and L{MeanTemperatureChange}.\n \"\"\"\n pass\n\n\nclass DataSeriesQuerySetMixin(FilteringQuerySetMixinBase):\n \"\"\"\n QuerySet limiting result set according to whether the current user is\n allowed to see the customer with specified ID.\n \"\"\"\n\n def _apply_filtering(self):\n user = get_user()\n if user is None:\n return\n if not user.is_authenticated():\n self.query.set_empty()\n return\n customer = get_customer()\n ACCEPTABLE_CUSTOMER_IS_NULL_INDEX_ROLES = [\n DataRoleField.ELECTRICITY_TARIFF,\n DataRoleField.CO2_QUOTIENT,\n ]\n if customer is not None:\n if not customer.is_active:\n self.query.set_empty()\n return\n id_field = '{}_id'.format(self._filter_field)\n kwargs = {id_field: customer.id}\n self.query.add_q(Q(**kwargs) | Q(**{\n '{}__isnull'.format(id_field): True,\n 'role__in': ACCEPTABLE_CUSTOMER_IS_NULL_INDEX_ROLES,\n }))\n return\n provider_id = get_provider_id()\n if provider_id:\n provider_id_field = '{}__provider_id'.format(self._filter_field)\n kwargs = {provider_id_field: provider_id}\n self.query.add_q(Q(**kwargs) | Q(**{\n '{}__isnull'.format(provider_id_field): True,\n 'role__in': ACCEPTABLE_CUSTOMER_IS_NULL_INDEX_ROLES,\n }))\n return\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n return\n\n\nclass DataSeriesManager(DecryptingManager, StoredSubclassManager):\n _field = 'customer'\n use_for_related_fields = True\n\n class _QuerySet(DataSeriesQuerySetMixin, DecryptingQuerySet):\n pass\n\n class _ValuesQuerySet(DataSeriesQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(DataSeriesQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(DataSeriesQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(DataSeriesQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(DataSeriesManager, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_filter_field': self._field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n\n\nclass DataSeriesBase(models.Model):\n objects = DataSeriesManager()\n\n class Meta:\n abstract = True\n\n\nclass DataSeries(DataSeriesBase, StoreSubclass):\n \"\"\"\n A C{DataSeries} samples an underlying function. Knowing this\n underlying function is important when interpreting and visualizing\n these data.\n\n For instance, if the C{DataSeries} samples an accumulation, you\n will usually want to compare the destilled development of the\n sample values inside a number of similar periods. If the data\n series, on the other hand, samples a rate, it is easy to visualize\n even large sets of undestiled sequential data; for instance with\n upper and lower bounds graphs.\n\n Also, there exist many techniques for interpolating U{continuous\n functions<http://mathworld.wolfram.com/ContinuousFunction.html>},\n such as U{linear\n interpolation<http://en.wikipedia.org/wiki/Linear_interpolation>}.\n For discontinuous functions, however, these techniques do not\n apply. Specifically, we will often meet the piecewise constant\n function, where each sample represent the constant value since the\n previous sample (discrete states, mean values and so on).\n\n @cvar PIECEWISE_CONSTANT_ACCUMULATION: Piecewise constant\n accumulation. For example accumulated unit production count.\n\n @cvar PIECEWISE_CONSTANT_RATE: Piecewise constant rate. For\n example mean power.\n\n @cvar CONTINUOUS_ACCUMULATION: Continuous accumulation. For\n example accumulated energy consumption.\n\n @cvar CONTINUOUS_RATE: Continuous rate. For example power,\n temperature, frequency or current.\n\n @cvar INTERVAL_FUNCTION: Interval function, i.e. a function that is\n computed across time intervals and not for any particular point in time;\n i.e. a function that is only well-defined when condensed.\n\n @ivar role: The role of this C{DataSeries} object.\n\n @ivar graph: The graph that this C{DataSeries} belongs to. This\n may be NULL for C{DataSeries} such as L{Index} (it may still be\n rendered to a graph, but its main purpose is not to be drawn on\n any graph in particular).\n\n @ivar customer: A customer which the C{DataSeries} belongs to, if null it's\n a global C{DataSeries} (e.g. a spot tariff or similar).\n\n @ivar utility_type: The type of resource that this C{DataSeries} is\n related to. For non-L{Index} C{DataSeries}, C{utility_type} is genericly\n available through C{graph__collection__resource__type}. I.e. moving the\n field to the L{Index} class would make it impossible to query for all\n DataSeries with a given resource type (and once you figure out how to do\n that anyway, feel free to move the C{utility_type} field to the L{Index}\n class.\n\n You can collect data for similar aspects of different resources, for\n instance energy consumption on both ELECTRICITY and DISTRICT_HEATING, cost\n on everything and temperature in a DISTRICT_HEATING installation. but also\n just room temperature, which is not related to any resource type in\n particular, i.e. UNKNOWN.\n \"\"\"\n customer = models.ForeignKey(Customer, on_delete=models.PROTECT,\n blank=True, null=True, default=get_customer)\n role = DataRoleField()\n\n graph = models.ForeignKey(Graph, on_delete=models.CASCADE,\n null=True, blank=True)\n\n unit = BuckinghamField(blank=True)\n\n utility_type = models.IntegerField(\n _('utility type'), choices=utilitytypes.OPTIONAL_METER_CHOICES)\n\n PIECEWISE_CONSTANT_ACCUMULATION = 0\n PIECEWISE_CONSTANT_RATE = 1\n CONTINUOUS_ACCUMULATION = 2\n CONTINUOUS_RATE = 3\n INTERVAL_FUNCTION = 4\n\n UNDERLYING_FUNCTION_CHOICES = (\n (PIECEWISE_CONSTANT_ACCUMULATION,\n _(u\"Piecewise constant accumulation\")),\n (PIECEWISE_CONSTANT_RATE,\n _(u\"Piecewise constant rate\")),\n (CONTINUOUS_ACCUMULATION,\n _(u\"Continuous accumulation\")),\n (CONTINUOUS_RATE,\n _(u\"Continuous rate\")),\n (INTERVAL_FUNCTION,\n _(u'Interval function')),\n )\n\n class Meta(StoreSubclass.Meta):\n verbose_name = _('dataseries')\n verbose_name_plural = _('dataseries')\n ordering = ['role', 'id']\n app_label = 'measurementpoints'\n\n _exclude_field_from_validation = []\n\n def __unicode__(self):\n if self.subclass.model_class() != self.__class__:\n # This operator is used for ModelChoiceFields, where the queryset\n # does not return concrete instances, but only raw DataSeries\n # instances. If so, delegate to the subclass_instance.\n return unicode(self.subclass_instance)\n elif self.graph and self.graph.collection and self.customer:\n # This is the default implementation for all subclasses.\n return u'{collection_name} -- {role} ({unit})'.format(\n collection_name=self.graph.collection.name_plain,\n role=self.get_role_display(),\n unit=self.get_preferred_unit_converter().get_display_unit())\n else:\n return self.get_role_display()\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n\n def get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Yields (or returns a list of) raw samples covering the interval\n M{[C{from_timestamp}; C{to_timestamp}]}.\n\n Subclasses that don't store their data directly as StoredData, should\n reimplement the C{_get_samples()} method.\n\n @precondition: C{from_timestamp <= to_timestamp}\n\n @postcondition: For rates, both end-points are included if possible\n through interpolation. If insufficient data is available, nothing is\n yielded/the empty list is returned.\n\n @postcondition: For accumulations, both end-points are included\n (possibly using interpolation or extrapolation). If insufficient data\n is available, nothing is yielded/the empty list is returned.\n\n @postcondition: All yielded samples are contained within the interval.\n\n @postcondition: Each sample yielded represent time after the previously\n yielded sample.\n\n @raise UndefinedSamples: If subclass is not supposed to be defined for\n the particular combination of C{from_timestamp} and C{to_timestamp}.\n \"\"\"\n assert from_timestamp <= to_timestamp\n\n if self.get_underlying_function() == self.INTERVAL_FUNCTION:\n raise UndefinedSamples(\n 'Raw samples for interval functions are not well-defined.')\n\n first_sample = None\n final_sample = None\n previous_timestamp = None\n for sample in self.subclass_instance._get_samples(\n from_timestamp, to_timestamp):\n assert isinstance(sample, Sample), \\\n '%r is not an instance of Sample (self.__class__ == %s)' % (\n sample, self.__class__)\n if first_sample is None:\n first_sample = sample\n elif sample.is_point:\n assert previous_timestamp < sample.timestamp\n elif sample.is_range:\n assert previous_timestamp <= sample.from_timestamp\n\n final_sample = sample\n assert from_timestamp <= sample.from_timestamp, \\\n '%r > %r (self.__class__ == %s)' % (\n from_timestamp, sample.from_timestamp, self.__class__)\n assert to_timestamp >= sample.to_timestamp, \\\n '%r < %r (self.__class__ == %s)' % (\n to_timestamp, sample.to_timestamp, self.__class__)\n yield sample\n\n previous_timestamp = sample.to_timestamp\n\n if self.is_rate() and first_sample is not None and \\\n final_sample is not None:\n assert not first_sample.extrapolated, str(self.__class__)\n assert not final_sample.extrapolated, str(self.__class__)\n\n if self.is_accumulation():\n if first_sample is not None and final_sample is not None:\n assert first_sample.from_timestamp == from_timestamp, str(\n self.__class__)\n assert final_sample.to_timestamp == to_timestamp, str(\n self.__class__)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Yields (or returns a list of) raw samples covering the interval\n M{[C{from_timestamp}; C{to_timestamp}]}.\n\n Subclasses that don't store their data directly as StoredData, should\n reimplement this method.\n\n @precondition: C{from_timestamp <= to_timestamp}\n\n @postcondition: For rates, both end-points are included if possible\n through interpolation. If insufficient data is available, nothing is\n yielded/the empty list is returned.\n\n @postcondition: For accumulations, both end-points are included\n (possibly using interpolation or extrapolation). If insufficient data\n is available, nothing is yielded/the empty list is returned.\n\n @postcondition: All yielded samples are contained within the interval.\n\n @note: The returned samples will be in the time interval\n M{[C{from_timestamp}, C{to_timestamp}]}, where C{from_timestamp} and\n C{to_timestamp} will be linear interpolation values if enough data is\n available.\n \"\"\"\n assert from_timestamp <= to_timestamp\n if self.__class__ != self.subclass.model_class():\n return self.subclass_instance.get_samples(\n from_timestamp, to_timestamp)\n\n tz = from_timestamp.tzinfo\n\n if self.is_continuous():\n dataset = list(self.stored_data.filter(\n timestamp__gte=from_timestamp,\n timestamp__lte=to_timestamp).\n order_by('timestamp'))\n\n result = [\n self.create_point_sample(\n data.timestamp,\n PhysicalQuantity(data.value, self.unit))\n for data in dataset]\n\n # result may be empty if nothing is found in range. Extrapolation\n # is necessary anyway.\n if result:\n if result[0].from_timestamp != from_timestamp:\n first_sample = self._interpolate_extrapolate_sample(\n from_timestamp, data_after=dataset[0])\n if self.is_accumulation() or not first_sample.extrapolated:\n result.insert(0, first_sample)\n if result[-1].to_timestamp != to_timestamp:\n end_sample = self._interpolate_extrapolate_sample(\n to_timestamp, data_before=dataset[-1])\n if self.is_accumulation() or not end_sample.extrapolated:\n result.append(end_sample)\n else:\n first_sample = self._interpolate_extrapolate_sample(\n from_timestamp)\n if first_sample is None or (self.is_rate() and\n first_sample.extrapolated):\n return []\n elif from_timestamp == to_timestamp:\n return [first_sample]\n else:\n end_sample = self._interpolate_extrapolate_sample(\n to_timestamp)\n return [first_sample, end_sample]\n\n # Check post-condition\n if self.is_accumulation():\n assert result == [] or \\\n result[0].from_timestamp == from_timestamp\n assert result == [] or result[-1].to_timestamp == to_timestamp\n\n return result\n else:\n result = []\n\n # RangeSamples are stored as (from_timestamp, value), with\n # to_timestamp being the timestamp of the next stored data.\n # Therefore we need to consider the most recent StoredData before\n # the (from_timestamp, to_timestamp) range.\n try:\n first_sample = [\n self.stored_data.filter(timestamp__lte=from_timestamp).\n order_by('-timestamp').\n values_list('timestamp', 'value')[0]]\n except IndexError:\n first_sample = []\n\n stored_data = first_sample + \\\n list(self.stored_data.filter(\n timestamp__gt=from_timestamp,\n timestamp__lt=to_timestamp).\n order_by('timestamp').\n values_list('timestamp', 'value'))\n\n for current_data, next_data in pairwise_extended(stored_data):\n if next_data:\n assert current_data[0] < next_data[0], \\\n 'unexpected range for sample (%r < %r)' % \\\n (current_data[0], next_data[0])\n result.append(\n self.create_range_sample(\n tz.normalize(\n max(from_timestamp,\n current_data[0]).astimezone(tz)),\n tz.normalize(next_data[0]).astimezone(tz),\n PhysicalQuantity(current_data[1], self.unit)))\n else:\n assert current_data[0] < to_timestamp\n result.append(\n self.create_range_sample(\n tz.normalize(\n max(from_timestamp,\n current_data[0])).astimezone(tz),\n tz.normalize(to_timestamp).astimezone(tz),\n PhysicalQuantity(current_data[1], self.unit)))\n\n # Check post-condition\n assert result[-1].from_timestamp >= from_timestamp\n assert result[-1].to_timestamp <= to_timestamp\n\n # Check post-condition\n if self.is_accumulation():\n assert result == [] or \\\n result[0].from_timestamp == from_timestamp\n assert result == [] or result[-1].to_timestamp == to_timestamp\n\n return result\n\n def get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Get list of L{Sample}s defined by this C{DataSeries}.\n\n If the underlying function is a continuous rate the\n samples will have a given symbolic timespan distance.\n Otherwise the samples will cover intervals with the given\n symbolic timespan (not quite the same)\n\n @param from_timestamp: The earliest time used in the returned samples.\n\n @param sample_resolution: A L{RelativeTimeDelta} that define the sample\n resolution.\n\n @param to_timestamp: The final time included in the samples.\n\n @return: Returns an list of point L{Sample}s if the underlying function\n is a continuous rate. Otherwise a list of ranged L{Sample} is\n returned.\n\n @see: L{_get_condensed_samples}.\n\n @precondition: C{from_timestamp == condense.floor(\n from_timestamp, sample_resolution, from_timestamp.tzinfo)}\n\n @precondition: C{to_timestamp == condense.floor(\n to_timestamp, sample_resolution, to_timestamp.tzinfo)}\n\n @precondition: C{from_timestamp.tzinfo is not None}\n\n @precondition: C{to_timestamp.tzinfo is not None}\n\n @precondition: C{sample_resolution in condense.RESOLUTIONS}\n \"\"\"\n assert from_timestamp.tzinfo is not None\n assert to_timestamp.tzinfo is not None\n timezone = from_timestamp.tzinfo\n\n assert from_timestamp == condense.floor(\n from_timestamp, sample_resolution, timezone), \\\n 'from_timestamp=%r != ' \\\n 'floor(from_timestamp, sample_resolution=%r, timezone=%r)=%r' % (\n from_timestamp, sample_resolution, timezone, condense.floor(\n from_timestamp, sample_resolution, timezone))\n\n assert to_timestamp == condense.floor(\n to_timestamp, sample_resolution, timezone)\n\n assert sample_resolution in condense.RESOLUTIONS\n\n for sample in self.subclass_instance._get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp):\n assert from_timestamp <= sample.from_timestamp, \\\n 'error in %s: from_timestamp = %r > sample.from_timestamp = %r ' \\\n '(sample resolution = %s)' % (\n self.subclass_instance.__class__,\n from_timestamp, sample.from_timestamp, sample_resolution)\n\n assert sample.to_timestamp <= to_timestamp\n yield sample\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n data_samples = self._condense_data_samples_recursive(\n from_timestamp, sample_resolution, to_timestamp=to_timestamp)\n next_timestamp = from_timestamp\n for sample_a, sample_b in pairwise_extended(data_samples):\n if sample_b is None:\n yield sample_a\n else:\n while next_timestamp < sample_a.from_timestamp:\n next_timestamp += sample_resolution\n while sample_a.from_timestamp <= next_timestamp < \\\n sample_b.from_timestamp:\n if sample_a.from_timestamp == next_timestamp:\n yield sample_a\n elif sample_a.is_point and sample_b.is_point:\n yield self._interpolate_extrapolate_sample(\n next_timestamp, sample_a, sample_b)\n next_timestamp += sample_resolution\n\n def _condense_accumulation_data_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Condense accumulation data samples within an interval defined by\n C{from_timestamp; to_timestamp]}, with C{sample_resolution} as the\n given resolution.\n\n Yields condensed range samples.\n \"\"\"\n def resolution_aligned_acc():\n # convert the sequence of \"raw\" samples from\n # get_samples() to a sequence of samples aligned to\n # the requested sample_resolution\n raw_accumulation = \\\n self.get_samples(from_timestamp, to_timestamp)\n next_timestamp = from_timestamp\n for sample1, sample2 in pairwise(raw_accumulation):\n while sample1.timestamp <= next_timestamp <= \\\n sample2.timestamp:\n yield self._interpolate_extrapolate_sample(\n next_timestamp,\n data_before=sample1, data_after=sample2)\n next_timestamp += sample_resolution\n\n for range_begin, range_end in pairwise(\n resolution_aligned_acc()):\n assert range_begin.timestamp >= from_timestamp\n assert range_end.timestamp <= to_timestamp\n yield self.create_range_sample(\n range_begin.timestamp,\n range_end.timestamp,\n range_end.physical_quantity -\n range_begin.physical_quantity,\n uncachable=(range_begin.uncachable or\n range_end.uncachable),\n extrapolated=(range_begin.extrapolated or\n range_end.extrapolated))\n\n def _condense_rate_data_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Rate specific L{get_condensed_samples()} implementation.\n Arguments are the same (or left out).\n\n Splits the multiframe ranged rate sample into smaller ranged rate\n samples (C{sample_slices}) that fit inside each requested sample frame.\n While this is visually redundant, it supports caching performance (or\n at least is intended to).\n\n @return: Returns a list of samples. For each frame (of length\n C{sample_resolution}) the minimum and maximum samples are included in\n the result.\n\n @postcondition: The samples in the returned list are ordered by their\n timestamps.\n\n @precondition: C{self.is_rate()} returns C{True}.\n \"\"\"\n assert self.is_rate()\n\n raw_data_samples = list(self.get_samples(from_timestamp, to_timestamp))\n\n if not raw_data_samples:\n # short-circuit: absolutely no values in this data series.\n return []\n\n result = []\n next_time = from_timestamp + sample_resolution\n minimum_sample = None\n maximum_sample = None\n\n def flush_min_max():\n if minimum_sample is not None and maximum_sample is not None:\n if minimum_sample.to_timestamp < maximum_sample.to_timestamp:\n result.extend([minimum_sample, maximum_sample])\n elif minimum_sample == maximum_sample:\n result.append(minimum_sample)\n else:\n assert minimum_sample.to_timestamp > \\\n maximum_sample.to_timestamp\n result.extend([maximum_sample, minimum_sample])\n return (None, None)\n return (minimum_sample, maximum_sample)\n\n def update_min_max():\n # work-around while we wait for 'nonlocal' Python 3 keyword\n r1 = minimum_sample\n r2 = maximum_sample\n if minimum_sample is None or \\\n minimum_sample.physical_quantity > \\\n sample.physical_quantity:\n r1 = sample\n if maximum_sample is None or \\\n maximum_sample.physical_quantity < \\\n sample.physical_quantity:\n r2 = sample\n return (r1, r2)\n\n for sample in raw_data_samples:\n if sample.uncachable:\n # don't condense using uncachable samples (end-points are\n # included after this loop).\n continue\n\n flush = False\n sample_slices = []\n\n if sample.is_range and \\\n sample.from_timestamp < next_time and\\\n sample.to_timestamp > next_time:\n sample_slices.append(sample._replace(to_timestamp=next_time))\n\n while sample.to_timestamp > next_time:\n flush = True\n if sample.is_range and not sample.in_closed_interval(\n next_time, next_time + sample_resolution) and \\\n sample.from_timestamp < next_time + sample_resolution:\n assert max(next_time, sample.from_timestamp) < min(\n next_time + sample_resolution, sample.to_timestamp), \\\n 'next_time=%r, sample=%r, sample_resolution=%r' % (\n next_time, sample, sample_resolution)\n sample_slices.append(sample._replace(\n from_timestamp=max(next_time, sample.from_timestamp),\n to_timestamp=min(\n next_time + sample_resolution,\n sample.to_timestamp)))\n next_time += sample_resolution\n\n if sample_slices:\n assert len(sample_slices) >= 2\n assert flush\n sample = sample_slices[0]\n minimum_sample, maximum_sample = update_min_max()\n minimum_sample, maximum_sample = flush_min_max()\n result.extend(sample_slices[1:-1])\n sample = sample_slices[-1]\n elif flush:\n minimum_sample, maximum_sample = flush_min_max()\n\n minimum_sample, maximum_sample = update_min_max()\n\n minimum_sample, maximum_sample = flush_min_max()\n\n return result\n\n def get_recursive_condense_resolution(self, resolution):\n \"\"\"\n Get the recursive condense resolution for the given C{resolution}.\n\n @return: A resolution to be used for condensing C{resolution}\n recursively or C{None}. If C{None} is returned, condensation for the\n given resolution will not be calculated recursively.\n\n This method is abstract so subclasses must implement it. The following\n implementation would work for most DataSeries specializations. However\n it would often be verry inefficient for small condense resolutions,\n which is why it is not the default::\n\n def get_recursive_condense_resolution(self, resolution):\n return condense.next_resolution(resolution)\n\n @see L{condense.next_resolution()}\n \"\"\"\n raise NotImplementedError(\n \"%s did't implement this method\" % self.__class__)\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Method with similar arguments and result as\n L{get_condensed_samples()}, but intended for being implemented in\n L{DataSeries} specializations that wish to utilize the implicit caching\n implemented in L{DataSeries.get_condensed_samples()}.\n\n Not intended to be called from outside\n L{DataSeries.get_condensed_samples()}, except for testing of the\n concrete C{_condense_data_samples_recursive()} implementation.\n \"\"\"\n timezone = from_timestamp.tzinfo\n assert from_timestamp == condense.floor(\n from_timestamp, sample_resolution, timezone)\n to_timestamp = condense.floor(\n to_timestamp, sample_resolution, timezone)\n\n refined_resolution = self.get_recursive_condense_resolution(\n sample_resolution)\n\n if refined_resolution is None:\n if self.is_accumulation():\n condensed_samples = self._condense_accumulation_data_samples(\n from_timestamp, sample_resolution, to_timestamp)\n else:\n assert self.is_rate()\n condensed_samples = self._condense_rate_data_samples(\n from_timestamp, sample_resolution, to_timestamp)\n\n for sample in condensed_samples:\n yield sample\n else:\n if self.is_accumulation():\n def extract_target_from_time(sample):\n return condense.floor(\n sample.from_timestamp, sample_resolution, timezone)\n\n for current_from_time, current_samples in itertools.groupby(\n self.get_condensed_samples(\n from_timestamp, refined_resolution, to_timestamp),\n key=extract_target_from_time):\n current_to_time = current_from_time + sample_resolution\n assert current_from_time >= from_timestamp\n assert current_to_time <= to_timestamp\n\n for condensed_sample in self.condense_accumulation(\n current_from_time,\n current_to_time,\n list(current_samples)):\n yield condensed_sample\n\n else:\n assert self.is_rate()\n\n condensed_samples = list(\n self.get_condensed_samples(\n from_timestamp, refined_resolution, to_timestamp))\n\n for frame_start, frame_end in pairwise(\n count_extended(from_timestamp, sample_resolution)):\n\n if frame_start == to_timestamp:\n break\n\n for condensed_sample in self.condense_rate(\n list(\n itertools.takewhile(\n lambda s: s.to_timestamp <= frame_end,\n condensed_samples))):\n yield condensed_sample\n\n condensed_samples = list(\n itertools.dropwhile(\n lambda s: s.to_timestamp < frame_end,\n condensed_samples))\n\n CONTINUOUS_ACCUMULATION_ROLES = (\n DataRoleField.CONSUMPTION,\n DataRoleField.CO2,\n DataRoleField.COST,\n DataRoleField.MASS,\n DataRoleField.TIME,\n DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n DataRoleField.HEATING_DEGREE_DAYS,\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n DataRoleField.VOLUME,\n DataRoleField.ENERGY_DRIVER,\n DataRoleField.PRODUCTION,\n DataRoleField.REACTIVE_ENERGY,\n )\n\n PIECEWISE_CONSTANT_ACCUMULATION_ROLES = ()\n\n ACCUMULATION_ROLES = CONTINUOUS_ACCUMULATION_ROLES + \\\n PIECEWISE_CONSTANT_ACCUMULATION_ROLES\n\n PIECEWISE_CONSTANT_RATE_ROLES = (\n DataRoleField.STATE,\n DataRoleField.HEAT_TARIFF,\n DataRoleField.GAS_TARIFF,\n DataRoleField.ELECTRICITY_TARIFF,\n DataRoleField.WATER_TARIFF,\n DataRoleField.OIL_TARIFF,\n DataRoleField.CO2_QUOTIENT,\n DataRoleField.EMPLOYEES,\n DataRoleField.AREA,\n DataRoleField.HIDDEN_ELECTRICITY_TARIFF,\n DataRoleField.HIDDEN_GAS_TARIFF,\n DataRoleField.HIDDEN_HEAT_TARIFF,\n DataRoleField.HIDDEN_WATER_TARIFF,\n DataRoleField.HIDDEN_OIL_TARIFF,\n )\n\n CONTINUOUS_RATE_ROLES = (\n DataRoleField.POWER,\n DataRoleField.REACTIVE_POWER,\n DataRoleField.POWER_FACTOR,\n DataRoleField.ABSOLUTE_TEMPERATURE,\n DataRoleField.RELATIVE_TEMPERATURE,\n DataRoleField.VOLUME_FLOW,\n DataRoleField.VOLTAGE,\n DataRoleField.CURRENT,\n DataRoleField.FREQUENCY,\n DataRoleField.PRESSURE,\n DataRoleField.LINEAR_REGRESSION,\n DataRoleField.EFFICIENCY,\n )\n\n RATE_ROLES = PIECEWISE_CONSTANT_RATE_ROLES + CONTINUOUS_RATE_ROLES\n\n INTERVAL_FUNCTION_ROLES = (\n DataRoleField.MEAN_COOLDOWN_TEMPERATURE,\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n DataRoleField.PRODUCTION_ENPI,\n DataRoleField.HEAT_LOSS_COEFFICIENT,\n )\n\n HIDDEN_ROLES = (\n DataRoleField.HIDDEN_ELECTRICITY_TARIFF,\n DataRoleField.HIDDEN_GAS_TARIFF,\n DataRoleField.HIDDEN_HEAT_TARIFF,\n DataRoleField.HIDDEN_WATER_TARIFF,\n DataRoleField.HIDDEN_OIL_TARIFF,\n DataRoleField.HIDDEN,\n )\n\n def get_underlying_function(self):\n \"\"\"\n Method for retrieving a description of the underlying function of the\n samples kept in this C{DataSeries}.\n\n @return: One of C{UNDERLYING_FUNCTION_CHOICES}.\n\n @note: It is always more efficient to check for role inclusion in the\n relevant constant list. This is useful to know when querying for a\n particular kind of underlying functions.\n\n @bug: May run clean, though this method returns a result and therefore\n should not be expected to have destructive side-effects.\n \"\"\"\n if self.role is None:\n self.clean()\n\n assert self.role is not None\n if self.role in self.CONTINUOUS_ACCUMULATION_ROLES:\n return self.CONTINUOUS_ACCUMULATION\n elif self.role in self.PIECEWISE_CONSTANT_RATE_ROLES:\n return self.PIECEWISE_CONSTANT_RATE\n elif self.role in self.CONTINUOUS_RATE_ROLES:\n return self.CONTINUOUS_RATE\n elif self.role in self.PIECEWISE_CONSTANT_ACCUMULATION_ROLES:\n return self.PIECEWISE_CONSTANT_ACCUMULATION\n elif self.role in self.INTERVAL_FUNCTION_ROLES:\n return self.INTERVAL_FUNCTION\n\n assert False, \"Underlying function for %d is undefined\" % self.role\n\n def is_rate(self):\n \"\"\"\n Check if this C{DataSeries} is a rate.\n\n @return: Return C{True} if this C{DataSeries} is a rate.\n \"\"\"\n return self.get_underlying_function() in [self.CONTINUOUS_RATE,\n self.PIECEWISE_CONSTANT_RATE]\n\n def is_accumulation(self):\n \"\"\"\n Check if this C{DataSeries} is an accumulation.\n\n @return: Returns C{True} if this C{DataSeries} is an\n accumulation. C{False} otherwise.\n \"\"\"\n return self.get_underlying_function() in [\n self.CONTINUOUS_ACCUMULATION, self.PIECEWISE_CONSTANT_ACCUMULATION]\n\n def is_continuous(self):\n \"\"\"\n Check if this C{DataSereis} is continuous.\n \"\"\"\n return self.get_underlying_function() in [\n self.CONTINUOUS_ACCUMULATION,\n self.CONTINUOUS_RATE]\n\n def is_piecewise_constant(self):\n \"\"\"\n Check if this C{DataSeries} has a piecewise constant underlying\n function.\n\n @return: Returns C{True} if this C{DataSeries} is piecewise constant,\n C{False} otherwise.\n \"\"\"\n\n return self.get_underlying_function() in [\n self.PIECEWISE_CONSTANT_RATE, self.PIECEWISE_CONSTANT_ACCUMULATION]\n\n def is_tariff(self):\n \"\"\"\n Check if this C{DataSeries} is a tariff\n\n @return: Returns C{True} if this C{DataSeries} is a tariff C{False}\n otherwise.\n \"\"\"\n return self.role in DataRoleField.TARIFFS\n\n def _interpolate_extrapolate_sample(self, timestamp,\n data_before=None, data_after=None):\n \"\"\"\n Get potentially extarpolated or linear interpolated sample at given\n C{timestamp}.\n\n @keyword data_before: A StoredData or point Sample before C{timestamp}.\n If C{None}, the a query will be made to construct a C{data_before}.\n\n @keyword data_after: A StoredData or point Sample after C{timestamp}.\n If C{None}, the a query will be made to construct a C{data_after}.\n\n @return: If a sample at the exact timestamp requested is found, it is\n returned. If samples on both sides of the timestamp requested are\n found, an interpolated value is computed and returned. If samples on\n only one side are available, the value from the closest sample is used\n and returned (uncachable and extrapolated). If no samples are\n available, neither before nor after the requested timestamp, None is\n returned.\n\n @note: The interpolation used is linear for continuous underlying\n functions, and trivial for piecewise constant underlying functions.\n\n @note: Extrapolation used is always trivial, i.e. extending with copy\n of end-point value.\n\n @note: This method is only intended for use with C{DataSeries} that\n actually store their data as L{StoredData}, unless both C{data_before}\n and C{data_after} are given.\n \"\"\"\n if data_before is not None:\n if isinstance(data_before, StoredData):\n data_before = self.create_point_sample(\n data_before.timestamp,\n PhysicalQuantity(data_before.value, self.unit))\n assert isinstance(data_before, Sample)\n assert data_before.timestamp <= timestamp\n\n if data_after is not None:\n if isinstance(data_after, StoredData):\n data_after = self.create_point_sample(\n data_after.timestamp,\n PhysicalQuantity(data_after.value, self.unit))\n assert isinstance(data_after, Sample)\n assert data_after.timestamp >= timestamp\n\n if self.is_continuous():\n try:\n if data_before is None:\n stored_data_before = self.stored_data.filter(\n timestamp__lte=timestamp).order_by('-timestamp')[0]\n data_before = self.create_point_sample(\n stored_data_before.timestamp,\n PhysicalQuantity(stored_data_before.value, self.unit))\n # short circuit; if \"before\" matches timestamp exactly, return\n # that.\n if data_before.timestamp == timestamp:\n assert isinstance(data_before, Sample)\n return data_before\n except IndexError:\n data_before = None\n try:\n if data_after is None:\n stored_data_after = self.stored_data.filter(\n timestamp__gte=timestamp).order_by('timestamp')[0]\n data_after = self.create_point_sample(\n stored_data_after.timestamp,\n PhysicalQuantity(stored_data_after.value, self.unit))\n # short circuit; if \"after\" matches timestamp exactly, return\n # that\n if data_after.timestamp == timestamp:\n assert isinstance(data_after, Sample)\n return data_after\n except IndexError:\n data_after = None\n if data_before is not None and data_after is not None:\n assert data_before.timestamp < data_after.timestamp\n timespan_total = (data_after.timestamp -\n data_before.timestamp).total_seconds()\n timespan_before = (timestamp -\n data_before.timestamp).total_seconds()\n delta_value = data_after.physical_quantity - \\\n data_before.physical_quantity\n rate = delta_value / Fraction(timespan_total)\n val = data_before.physical_quantity + rate * \\\n Fraction(timespan_before)\n\n # interpolate\n return self.create_point_sample(\n timestamp, val,\n uncachable=data_before.uncachable or data_after.uncachable,\n extrapolated=data_before.extrapolated or\n data_after.extrapolated)\n\n elif data_before is not None:\n assert data_after is None\n # extrapolate\n return self.create_point_sample(\n timestamp, data_before.physical_quantity,\n uncachable=True, extrapolated=True)\n elif data_after is not None:\n assert data_before is None\n # extrapolate\n return self.create_point_sample(\n timestamp,\n data_after.physical_quantity,\n uncachable=True, extrapolated=True)\n else:\n assert data_before is None and data_after is None\n return None\n\n else:\n assert self.is_piecewise_constant()\n try:\n if data_before is None:\n stored_data_before = self.stored_data.filter(\n timestamp__lte=timestamp).order_by('-timestamp')[0]\n data_before = self.create_point_sample(\n stored_data_before.timestamp,\n PhysicalQuantity(stored_data_before.value, self.unit))\n # short circuit; if \"before\" matches timestamp exactly, return\n # that\n if data_before.timestamp == timestamp:\n assert isinstance(data_before, Sample)\n return data_before\n uncachable = extrapolated = not (\n data_after is not None and\n self.stored_data.filter(timestamp__gt=timestamp).exists())\n return self.create_point_sample(\n timestamp, PhysicalQuantity(data_before.value, self.unit),\n uncachable=uncachable, extrapolated=extrapolated)\n except IndexError:\n try:\n if data_after is None:\n data_after = self.stored_data.filter(\n timestamp__gt=timestamp).order_by('timestamp')[0]\n return self.create_point_sample(\n timestamp,\n PhysicalQuantity(data_after.value, self.unit),\n uncachable=True, extrapolated=True)\n except IndexError:\n return None\n\n def calculate_development(self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate the development between two points in time. Extrapolates if\n not enough data.\n\n @param from_timestamp: The first timestamp.\n\n @param to_timestamp: The last timestamp.\n\n @return: Return a L{Range} sample holding the development between\n C{from_timestamp} and C{to_timestamp}. If no data was available at\n all, None is returned.\n\n @postcondition: If C{None} is returned, the domain of this\n C{DataSeries} is empty.\n \"\"\"\n assert self.is_accumulation()\n\n try:\n from_sample = next(iter(\n self.get_samples(from_timestamp, from_timestamp)))\n to_sample = next(iter(\n self.get_samples(to_timestamp, to_timestamp)))\n\n return self.create_range_sample(\n from_timestamp, to_timestamp,\n to_sample.physical_quantity - from_sample.physical_quantity,\n uncachable=(\n from_sample.uncachable or\n to_sample.uncachable),\n extrapolated=(\n from_sample.extrapolated or\n to_sample.extrapolated))\n except StopIteration:\n return None\n\n def depends_on(self):\n \"\"\"\n Recursively collects a list of C{DataSeries} that this C{DataSeries}\n depends on.\n\n @see L{dataseries}\n\n @return: A list of L{DataSeries} that this C{DataSeries} depends upon.\n \"\"\"\n return []\n\n def latest_sample(self, from_timestamp, to_timestamp):\n \"\"\"\n The latest sample in the given time interval, M{[C{from_timestamp},\n C{to_timestamp})} for this C{DerivedDataSeries}.\n\n @precondition: C{self.is_rate()}.\n\n @return: Return a L{PointSample}, L{PointSampleCurrency} if samples\n are available in the given time interval, or C{None} if no sample is\n available.\n \"\"\"\n assert self.is_rate()\n raw_data = self.get_samples(from_timestamp, to_timestamp)\n\n for sample in reversed(list(raw_data)):\n if sample.cachable:\n return sample\n\n return None\n\n def aggregated_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n The average sample, minimum sample and maximum sample of the given time\n interval, M{[C{from_timestamp}, C{to_timestamp}]}\n\n @precondition: C{self.is_rate()}\n\n @return: A tripple C{(avg, min, max)}, where:\n\n - C{avg} is a L{RangeSample} or a L{RangeSampleCurrency} holding the\n average value of the given timespan. If insuficient values were\n available to interpolate at the end-points, the returned C{avg},\n may indicate a subinterval of the given time interval. If\n insuficient values for calculating an average in the given time\n interval, C{avg} is C{None}.\n\n - C{min, max} are L{PointSample}s or L{PointSampleCurrency}s holding\n the minimum and maximum value in the given timespan. If it is not\n even possible to interpolate a single value in the timespan, C{min,\n max} will be C{None, None}. If there are multiple extremes only\n the earliest minimum and the earliest maximum will be included in\n the result.\n\n @postcondition: If the domain overlaps the given time interval, neither\n element in the returned tuple shall be None.\n\n @note: The term aggregates is in this context taken from the SQL\n terminology, where C{AVG}, C{MIN}, C{MAX} (and even C{COUNT}) are\n aggregates of a query result, not to be confused with the object\n oriented programming term spelled the same way. However, there is an\n important semantic differense between the SQL C{AVG} and the average\n returned by this method. In particular, the SQL C{AVG} does nothing to\n mimic the average of the underlying function, whereas, the average\n included in the result of this method is the mean value of the curve\n defined by the linear interpolation between the points of this data\n series across the given interval. But also, the SQL C{MIN} and C{MAX}\n might be wrong, as interpolation values at the end-points of the\n interval should also be considered in case actual StoredData is not\n available at these timestamps.\n\n @note: This method is implemented strictly on top of\n L{get_samples()}, and so any valid override of\n L{get_samples()} should leave this C{aggregated_samples()}\n method in a working state.\n \"\"\"\n assert self.is_rate()\n consumption = None\n minimum = None\n maximum = None\n for current_sample, next_sample in \\\n pairwise_extended(itertools.ifilter(\n lambda s: not s.extrapolated,\n self.get_samples(from_timestamp, to_timestamp))):\n\n final_timestamp = current_sample.to_timestamp\n\n if minimum is None or \\\n current_sample.physical_quantity < \\\n minimum.physical_quantity:\n minimum = current_sample\n\n if maximum is None or \\\n current_sample.physical_quantity > \\\n maximum.physical_quantity:\n maximum = current_sample\n\n if self.is_piecewise_constant():\n # Area under horizontal line (piecewise constant)\n delta_consumption = (\n PhysicalQuantity(\n (current_sample.to_timestamp -\n current_sample.from_timestamp).\n total_seconds(), 'second') *\n current_sample.physical_quantity)\n else:\n if next_sample is None:\n break\n\n # Area under slope (interpolation of continuous)\n delta_consumption = (\n PhysicalQuantity(\n (next_sample.timestamp -\n current_sample.timestamp).\n total_seconds(), 'second') *\n (\n current_sample.physical_quantity +\n next_sample.physical_quantity) /\n PhysicalQuantity(2, 'none'))\n\n if consumption is not None:\n consumption += delta_consumption\n else:\n first_timestamp = current_sample.from_timestamp\n consumption = delta_consumption\n\n if minimum is not None and maximum is not None:\n if consumption is not None:\n average_value = consumption / PhysicalQuantity(\n (final_timestamp - first_timestamp).total_seconds(),\n 'second')\n average_sample = self.create_range_sample(\n first_timestamp, final_timestamp,\n average_value)\n else:\n average_sample = maximum\n else:\n # Nothing at all yielded from self.get_samples(), or\n # everything yielded was extrapolated. If there is a\n # non-zero-length overlap between requested period and domain, this\n # should not occur.\n minimum = None\n maximum = None\n average_sample = None\n\n return (average_sample, minimum, maximum)\n\n def create_point_sample(\n self, timestamp, physical_quantity,\n uncachable=False, extrapolated=False):\n \"\"\"\n Factory method for creating a L{PointSample} or L{PointSampleCurrency}\n depending on what will suit this C{DataSeries}.\n\n @param timestamp: The timestamp of the created sample.\n\n @param physical_quantity: The value of the created sample.\n\n @param uncachable: If C{True} the returned point sample will never be\n cached.\n\n @param extrapolated: If C{True} the returned point sample is marked as\n extrapolated.\n\n @return: A L{PointSample} or L{PointSampleCurrency} with unit and\n possibly currency set to C{self.unit} and C{self.currency}\n respectively.\n \"\"\"\n assert physical_quantity.compatible_unit(self.unit), \\\n '%s not compatible with %s' % (physical_quantity.units, self.unit)\n\n return Sample(\n timestamp, timestamp, physical_quantity,\n not uncachable, extrapolated)\n\n def create_range_sample(\n self, from_timestamp, to_timestamp, physical_quantity,\n uncachable=False, extrapolated=False):\n \"\"\"\n @param from_timestamp: The start-point of the range of the created\n sample.\n\n @param to_timestamp: The end-point of the range of the created sample.\n\n @param physical_quantity: The value of the created sample.\n\n @param uncachable: If C{True} the returned range sample will never be\n cached.\n\n @return: A L{RangeSample} or L{RangeSampleCurrency} with unit and\n possibly currency set to C{self.unit} and C{self.currency}\n respectively.\n \"\"\"\n assert physical_quantity.compatible_unit(self.unit), \\\n '%s not compatible with %s' % (physical_quantity.units, self.unit)\n\n return Sample(\n from_timestamp, to_timestamp, physical_quantity,\n not uncachable, extrapolated)\n\n def convert(self, value, target_unit):\n \"\"\"\n Convert C{value} to C{target_unit}, assuming the unit of C{value} is\n C{self.unit}.\n\n @precondition: C{PhysicalQuantity.compatible_units(target_unit,\n self.unit)} is C{True} or C{target_unit in ['celsius'] and\n PhysicalQuantity.compatible_units('kelvin', self.unit)}.\n \"\"\"\n quantity = PhysicalQuantity(value, self.unit)\n if target_unit == 'celsius':\n assert PhysicalQuantity.compatible_units('kelvin', self.unit)\n if self.role == DataRoleField.ABSOLUTE_TEMPERATURE:\n quantity -= PhysicalQuantity(Fraction(\"273.15\"), 'kelvin')\n else:\n assert self.role == DataRoleField.RELATIVE_TEMPERATURE\n return quantity.convert('kelvin')\n else:\n assert PhysicalQuantity.compatible_units(target_unit, self.unit)\n return quantity.convert(target_unit)\n\n def condense_accumulation(self, from_timestamp, to_timestamp, samples):\n return [\n self.create_range_sample(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n physical_quantity=sum(\n (sample.physical_quantity for sample in samples),\n PhysicalQuantity(0, self.unit)),\n uncachable=(\n (not samples) or\n from_timestamp != samples[0].from_timestamp or\n to_timestamp != samples[-1].to_timestamp or\n any((not sample.cachable for sample in samples))),\n extrapolated=any((sample.extrapolated for sample in samples)))]\n\n def condense_rate(self, samples):\n \"\"\"\n Condense rate by returning up to two samples that are local extremes\n (minimum, and maximum) within the given C{samples}.\n\n If there are more than two such local extremes it is not specified\n which valid pair of them will be returned in particular, only that some\n valid pair will be returned.\n \"\"\"\n if samples:\n # The literal set serves to ensure that the same sample is not\n # yielded twice.\n return sorted(\n {\n min(samples, key=attrgetter('physical_quantity')),\n max(samples, key=attrgetter('physical_quantity'))},\n key=attrgetter('from_timestamp'))\n else:\n return []\n\n def get_preferred_unit_converter(self):\n \"\"\"\n Get preferred unit converter.\n\n @see: L{preferredunits.get_preferred_unit_converter}.\n\n @precondition: C{self.customer is not None}\n \"\"\"\n assert self.customer is not None or get_customer() is not None\n\n return get_preferred_unit_converter(\n self.role, utility_type=self.utility_type,\n customer=self.customer, unit=self.unit)\n\n def is_absolute_temperature(self):\n return self.role == DataRoleField.ABSOLUTE_TEMPERATURE\n\n\nclass StoredData(models.Model):\n \"\"\"\n C{StoredData} is a class for storing data belonging to a\n L{DataSeries}, or a specialization of such.\n\n @ivar data_series: The L{DataSeries} this C{StoredData} belongs to.\n\n @ivar value: The integer value held by this C{StoredData}. The unit of\n this value is found in C{data_series.unit}.\n\n @ivar timestamp: A timestamp that this C{StoredData} belongs to. If this\n C{StoredData} represents a L{PointSample}, the C{timestamp} obviously\n correspond to L{PointSample.timestamp}. If this C{StoredData} represents a\n L{RangeSample}, the C{timestamp} correspond to\n L{RangeSample.from_timestamp}, and the next C{StoredData} define the\n L{RangeSample.to_timestamp}.\n \"\"\"\n data_series = models.ForeignKey(DataSeries, on_delete=models.CASCADE,\n related_name=\"stored_data\")\n value = models.BigIntegerField(_('value'))\n timestamp = models.DateTimeField(_('timestamp'))\n\n class Meta:\n verbose_name = _('stored data')\n verbose_name_plural = _('stored data')\n unique_together = (\"data_series\", \"timestamp\")\n index_together = [\n ['data_series', 'timestamp'],\n ]\n ordering = [\"timestamp\"]\n app_label = 'measurementpoints'\n\n def __unicode__(self):\n return u\"%s, %s\" % (self.timestamp, self.value)\n" }, { "alpha_fraction": 0.6282641887664795, "alphanum_fraction": 0.6282641887664795, "avg_line_length": 23.11111068725586, "blob_id": "3c769d38d4c8ac81f6364df4c2a54962add481d3", "content_id": "84f4f2c09cc9d14713b0eafbc94f9b957df6ce1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 651, "license_type": "no_license", "max_line_length": 66, "num_lines": 27, "path": "/gridagentserver/current_agents.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# dry-run example command:\n# ./current_agents.py -n -v\n\nimport argparse\n\nfrom client import send_message\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-v', '--verbose', action='store_true',\n help='increase output verbosity')\nparser.add_argument('-n', '--dry-run', action='store_true',\n help='don\\'t actually send command')\n\n\ndef current_agents(args):\n routing_key = 'agentserver'\n message = {\n 'command': 'current_agents',\n }\n send_message(routing_key, message, args.verbose, args.dry_run)\n\n\nif __name__ == '__main__':\n current_agents(parser.parse_args())\n" }, { "alpha_fraction": 0.6173585057258606, "alphanum_fraction": 0.6177358627319336, "avg_line_length": 35.80555725097656, "blob_id": "6cf1dee884c2d4e5b31838a7db75bddbf1a714be", "content_id": "c1ddc65fa28633a244788d0a862ff430444b0106", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2650, "license_type": "no_license", "max_line_length": 68, "num_lines": 72, "path": "/legacy/manage_collections/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView, DetailView\n\nfrom gridplatform.users.decorators import auth_or_redirect\nfrom gridplatform.utils.views import FileView\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.manage_collections.models import Floorplan\n\nurlpatterns = patterns(\n 'legacy.manage_collections.views',\n url(r'^$',\n auth_or_redirect(TemplateView.as_view(\n template_name='manage_collections/group_list.html')),\n name='manage-groups-list'),\n url(r'^form/$',\n 'group_form',\n name='manage-groups-form'),\n url(r'^form/(?P<pk>\\d+)$',\n 'group_form',\n name='manage-groups-form'),\n url(r'^json/groups/$',\n 'group_list_json',\n name='manage-groups-list-json'),\n url(r'^update/$',\n 'group_update',\n name='manage-groups-update'),\n url(r'^update/(?P<pk>\\d+)$',\n 'group_update',\n name='manage-groups-update'),\n url(r'^delete/$',\n 'group_delete',\n name='manage-groups-delete'),\n url(r'^(?P<pk>\\d+)$',\n auth_or_redirect(DetailView.as_view(\n model=Collection,\n template_name='manage_collections/group_details.html')),\n name='manage-groups-details'),\n url(r'^json/measurementpoints/(?P<group_id>\\d+)$',\n 'measurementpoints_list_json',\n name='manage-groups-measurementpoints-list-json'),\n url(r'^floorplan/(?P<pk>\\d+)$',\n 'floorplan',\n name='manage-groups-floorplan'),\n url(r'^floorplan/(?P<pk>\\d+)/image$',\n FileView.as_view(model=Floorplan, field='image'),\n name='manage-groups-floorplan_image'),\n url(r'^collection/(?P<pk>\\d+)/image$',\n FileView.as_view(model=Collection, field='image'),\n name='manage-groups-collection_image'),\n url(r'^collection/(?P<pk>\\d+)/thumbnail$',\n FileView.as_view(model=Collection, field='thumbnail'),\n name='manage-groups-collection_thumbnail'),\n url(r'^floorplan/additem/(?P<pk>\\d+)$',\n 'place_item',\n name='manage-groups-place_item'),\n url(r'^floorplan/addinfoitem/(?P<pk>\\d+)$',\n 'place_infoitem',\n name='manage-groups-place_infoitem'),\n url(r'^floorplan/updateplacement/$',\n 'update_placement',\n name='manage-groups-update_placement'),\n url(r'^floorplan/removeitem$',\n 'remove_item',\n name='manage-groups-remove_item'),\n url(r'^floorplan/saveinfoitem$',\n 'save_info_item',\n name='manage-groups-save_info_item'),\n)\n" }, { "alpha_fraction": 0.5875139236450195, "alphanum_fraction": 0.5875139236450195, "avg_line_length": 32.185184478759766, "blob_id": "8e1ebd4d2d9eb844c71facea2dc3945df18b299b", "content_id": "09bfd64b3c55a43df8defc19f552435e2de9ab27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 897, "license_type": "no_license", "max_line_length": 79, "num_lines": 27, "path": "/wifiagent/wifiagent/relay/management/commands/sendsaved.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand, CommandError\nfrom wifiagent.relay.request_handler import RequestHandler\nfrom wifiagent.relay.models import Measurement\n\nclass Command(BaseCommand):\n help = 'Tries to send all saved measurements'\n\n def handle(self, *args, **options):\n measurements = Measurement.objects.all()\n request_handler = RequestHandler()\n ok = True\n\n for measurement in measurements:\n try:\n if request_handler.send_measurement(measurement):\n measurement.delete()\n else:\n ok = False\n break\n except:\n ok = False\n break\n\n if ok:\n self.stdout.write(self.style.SUCCESS('Saved measurements send...'))\n else:\n self.stdout.write(self.style.ERROR(\"Can't reach server\"))\n\n" }, { "alpha_fraction": 0.5716353058815002, "alphanum_fraction": 0.5745296478271484, "avg_line_length": 29.04347801208496, "blob_id": "7801ad2d46682c76594b991536b84f5f4c0c5712", "content_id": "2d69b5c0ff400b6a671bb99b26b0b23c77ce913a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1382, "license_type": "no_license", "max_line_length": 59, "num_lines": 46, "path": "/legacy/devices/management/commands/get_agent_events.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nimport pytz\nfrom django.core.management.base import BaseCommand\n\nfrom legacy.devices.models import AgentEvent\n\nTIMESTAMP_FORMAT = '%Y-%m-%d-%H:%M:%S'\n\n\nclass Command(BaseCommand):\n args = '<mac> [from] [to]'\n help = 'Get event log for GridAgent with <mac>. ' + \\\n 'Timestamp format YYYY-MM-DD-hh:mm:ss.'\n\n def handle(self, *args, **options):\n timezone = pytz.utc\n mac = args[0]\n try:\n timestamp_from = datetime.datetime.strptime(\n args[1],\n TIMESTAMP_FORMAT).replace(tzinfo=timezone)\n except IndexError:\n timestamp_from = None\n try:\n timestamp_to = datetime.datetime.strptime(\n args[2],\n TIMESTAMP_FORMAT).replace(tzinfo=timezone)\n except IndexError:\n timestamp_to = None\n\n qs = AgentEvent.objects.filter(agent__mac=mac)\n if timestamp_from is not None:\n qs.filter(timestamp__gte=timestamp_from)\n if timestamp_to is not None:\n qs.filter(timestamp__lte=timestamp_to)\n for event in qs:\n print '%s %i %s' % (\n event.timestamp.strftime(TIMESTAMP_FORMAT),\n event.code,\n event.message,\n )\n" }, { "alpha_fraction": 0.6440439224243164, "alphanum_fraction": 0.6470008492469788, "avg_line_length": 40.052024841308594, "blob_id": "755efb7218f26e3b4a1f15c9ad815ccd6b355720", "content_id": "c77e632cda3dab6f5699d138a63f1d00e78f8fe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7102, "license_type": "no_license", "max_line_length": 97, "num_lines": 173, "path": "/legacy/measurementpoints/models/costcalculation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.datasequences.utils import aggregate_sum_ranged_sample_sequence # noqa\nfrom gridplatform.datasequences.utils import multiply_ranged_sample_sequences\nfrom gridplatform.utils.samples import wrap_ranged_sample_sequence\nfrom gridplatform.datasequences.models.base import is_five_minute_multiplum\nfrom gridplatform.utils import condense\nfrom gridplatform.datasequences.models.energyconversion import _break_into_hourly_samples # noqa\nfrom .indexcalculation import IndexCalculation\n\n\ndef _break_into_fiveminutes_samples(\n ranged_samples, from_timestamp, to_timestamp):\n \"\"\"\n Yield five-minutes subsamples of each sample in ranged_samples.\n \"\"\"\n assert is_five_minute_multiplum(from_timestamp), \\\n '%r is not a 5 minute multiplum' % from_timestamp\n assert is_five_minute_multiplum(to_timestamp), \\\n '%r is not a 5 minute multiplum' % to_timestamp\n timestamp = from_timestamp\n for sample in ranged_samples:\n while timestamp < sample.from_timestamp:\n timestamp += condense.FIVE_MINUTES\n while timestamp < sample.to_timestamp:\n subsample = sample._replace(\n from_timestamp=timestamp,\n to_timestamp=timestamp + condense.FIVE_MINUTES)\n assert subsample.from_timestamp >= sample.from_timestamp\n assert subsample.to_timestamp <= sample.to_timestamp\n yield subsample\n timestamp += condense.FIVE_MINUTES\n\n\nclass CostCalculation(IndexCalculation):\n \"\"\"\n A C{Costcalculation} is a L{DataSeries} derived from a consumption\n L{DataSeries} and a tariff L{DataSeries}.\n\n @ivar tariff: The tariff L{DataSeries} used in the cost calculation.\n\n @ivar consumption: The consumption L{DataSeries} used in the consumption\n calculation.\n \"\"\"\n class Meta:\n proxy = True\n verbose_name = _('cost calculation')\n verbose_name_plural = _('cost calculations')\n app_label = 'measurementpoints'\n\n def _get_tariff(self):\n return self.index\n\n def _set_tariff(self, value):\n self.index = value\n\n tariff = property(_get_tariff, _set_tariff)\n\n def _get_tariff_id(self):\n return self.index\n\n def _set_tariff_id(self, value):\n self.index = value\n\n tariff_id = property(_get_tariff_id, _set_tariff_id)\n\n RATE_RESOLUTION = RelativeTimeDelta(hours=1)\n\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n assert self.RATE_RESOLUTION == RelativeTimeDelta(hours=1)\n\n tariff_samples = _break_into_hourly_samples(\n self._get_rate().get_samples(\n from_timestamp, to_timestamp), from_timestamp, to_timestamp)\n consumption_samples = self._get_accumulation().get_condensed_samples(\n from_timestamp, condense.HOURS, to_timestamp)\n\n return multiply_ranged_sample_sequences(\n consumption_samples, tariff_samples)\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n consumption_seq = iter(self._get_accumulation().get_condensed_samples(\n from_timestamp, RelativeTimeDelta(minutes=5), to_timestamp))\n price_seq = _break_into_fiveminutes_samples(\n iter(self._get_rate().get_samples(from_timestamp, to_timestamp)),\n from_timestamp,\n to_timestamp)\n price = next(price_seq)\n while True:\n consumption = next(consumption_seq)\n while price.to_timestamp < consumption.to_timestamp:\n price = next(price_seq)\n assert consumption.from_timestamp >= price.from_timestamp\n assert consumption.to_timestamp <= price.to_timestamp\n yield consumption._replace(\n physical_quantity=consumption.physical_quantity *\n price.physical_quantity)\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n # NOTE: API from DataSeries\n data = self._hourly_accumulated(from_timestamp, to_timestamp)\n if sample_resolution == RelativeTimeDelta(hours=1):\n return data\n else:\n return wrap_ranged_sample_sequence(\n aggregate_sum_ranged_sample_sequence(\n data, sample_resolution, self.customer.timezone))\n\n def calculate_development(self, from_timestamp, to_timestamp):\n from gridplatform.datasequences.models.base import is_five_minute_multiplum # noqa\n assert is_five_minute_multiplum(from_timestamp), \\\n '%r is not a 5 minute multiplum' % from_timestamp\n assert is_five_minute_multiplum(to_timestamp), \\\n '%r is not a 5 minute multiplum' % to_timestamp\n assert from_timestamp <= to_timestamp\n\n if from_timestamp.minute != 0:\n period_end_timestamp = min(\n to_timestamp,\n from_timestamp + datetime.timedelta(\n minutes=60 - from_timestamp.minute))\n leading_five_minute_period = (from_timestamp, period_end_timestamp)\n else:\n leading_five_minute_period = None\n\n if to_timestamp.minute != 0 and (\n leading_five_minute_period is None or\n leading_five_minute_period[1] != to_timestamp):\n period_begin_timestamp = \\\n to_timestamp - RelativeTimeDelta(minutes=to_timestamp.minute)\n following_five_minute_period = (\n period_begin_timestamp, to_timestamp)\n else:\n following_five_minute_period = None\n\n if leading_five_minute_period is None:\n hour_from_time = from_timestamp\n else:\n hour_from_time = leading_five_minute_period[1]\n if following_five_minute_period is None:\n hour_to_time = to_timestamp\n else:\n hour_to_time = following_five_minute_period[0]\n\n value = PhysicalQuantity(0, self.unit)\n if leading_five_minute_period is not None:\n samples = self._five_minute_accumulated(\n leading_five_minute_period[0],\n leading_five_minute_period[1])\n value = sum((s.physical_quantity for s in samples), value)\n\n if following_five_minute_period is not None:\n samples = self._five_minute_accumulated(\n following_five_minute_period[0],\n following_five_minute_period[1])\n value = sum((s.physical_quantity for s in samples), value)\n\n if hour_from_time < hour_to_time:\n samples = self._hourly_accumulated(\n hour_from_time,\n hour_to_time)\n value = sum((s.physical_quantity for s in samples), value)\n return Sample(from_timestamp, to_timestamp, value, False, False)\n" }, { "alpha_fraction": 0.5820895433425903, "alphanum_fraction": 0.5841174721717834, "avg_line_length": 39.82119369506836, "blob_id": "d9069bafc66ab803a6ac7c5c1719531b0a50e6eb", "content_id": "41be43f46a1f70f2044295c1ab1dd8702c14dd04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12328, "license_type": "no_license", "max_line_length": 79, "num_lines": 302, "path": "/legacy/measurementpoints/proxies/importedmeasurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport unicodecsv\nfrom datetime import datetime\nfrom itertools import islice\nfrom itertools import izip\nfrom itertools import count\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom fractions import Fraction\n\nfrom legacy.measurementpoints import default_unit_for_data_series\nfrom legacy.measurementpoints.models import StoredDataSeries\nfrom legacy.measurementpoints.models import StoredData\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform import trackuser\n\nfrom .consumptionmeasurementpoint import ConsumptionMeasurementPoint\n\n\nclass ImportedMeasurementPoint(ConsumptionMeasurementPoint):\n \"\"\"\n Measurement point for importing consumption data from a CSV file.\n\n @ivar uploaded_file: The CSV file containing the consumption data.\n\n @ivar consumption_column: Consumption values will be extracted from this\n column (0 indexed). This field is by default set to '1', but it is\n suggested to let the user choose.\n\n @ivar first_consumption_row: The CSV file may contain a headline along with\n other irrelevant formatting. This integer defines where to start parsing\n consumption. This field has a default value is set to '2' This works well\n with the example files we were given as acceptance criteria.\n\n @ivar column_delimiter: In Europe a semi-colon ';' is used to seperate the\n values in a CSV file , but in the US a comma ',' is used (comma separated\n values). This field default value it set to ';'\n\n @ivar decimal_delimiter: In some parts of the world a comma ',' is used,\n whereas in others a dot '.' is used.\n See U{http://en.wikipedia.org/wiki/Decimal_mark}, and note that this is not\n simple US vs Europe issue. This field default value is to to ','\n\n @ivar unit: The unit that the consumption data in the C{uploaded_file} is\n stored in. This field is required.\n\n @ivar timezone: The timezone that the time stamps in the C{uploaded_file}\n are stored in. This field is required.\n\n @note: The time column values will be extracted from the first column\n in the oploaded file. The time column is hardcoded to '0'.\n \"\"\"\n upload_file = None\n consumption_column = 1\n first_consumption_row = 2\n column_delimiter = b';'\n decimal_delimiter = ','\n parsed_csv = None\n unit = None\n timezone = None\n\n class Meta:\n proxy = True\n verbose_name = _('Imported measurement point')\n verbose_name_plural = _('Imported measurement points')\n app_label = 'customers'\n\n def __init__(self, *args, **kwargs):\n super(ImportedMeasurementPoint, self).__init__(*args, **kwargs)\n if trackuser.get_customer() is not None:\n self.timezone = trackuser.get_customer().timezone\n self.unit = trackuser.get_customer().electricity_consumption\n\n def save(self, *args, **kwargs):\n \"\"\"\n Specialization of L{ConsumptionMeasurementPoint.save()}.\n\n Save uploaded CSV if not previously defined.\n \"\"\"\n if not self.id:\n assert self.parsed_csv\n self.consumption = StoredDataSeries(\n utility_type=self.utility_type,\n unit=default_unit_for_data_series(\n DataRoleField.CONSUMPTION, self.utility_type),\n role=DataRoleField.CONSUMPTION)\n super(ImportedMeasurementPoint, self).save(*args, **kwargs)\n accumulated_value = 0\n stored_data = [StoredData(timestamp=self.parsed_csv[0][0],\n value=0,\n data_series_id=self.consumption.id)]\n\n for from_timestamp, to_timestamp, value in self.parsed_csv:\n accumulated_value += PhysicalQuantity(\n value, self.unit).convert(self.consumption.unit)\n stored_data.append(StoredData(\n timestamp=to_timestamp, value=accumulated_value,\n data_series_id=self.consumption.id))\n\n StoredData.objects.bulk_create(stored_data)\n else:\n super(ImportedMeasurementPoint, self).save(*args, **kwargs)\n\n def clean(self):\n \"\"\"\n Parse C{uploaded_file} if possible.\n\n @raise ValidationError: When the uploaded file cannot be parsed, a\n relevant C{ValidationError} specialization is raised, explaining what\n is wrong.\n \"\"\"\n if self.upload_file is not None and \\\n self.timezone is not None and \\\n self.unit is not None:\n self._parse_csv()\n\n class EmptyFileError(ValidationError):\n \"\"\"\n The C{uploaded_file} did not contain any consumption data.\n \"\"\"\n def __init__(self, filename):\n \"\"\"\n @param filename: The name of the uploaded file that did not contain\n any consumption data.\n \"\"\"\n super(ImportedMeasurementPoint.EmptyFileError, self).__init__(\n _(\"{filename} contains no consumption data\").format(\n filename=filename))\n self.filename = filename\n\n class FileValidationError(ValidationError):\n \"\"\"\n Error on a particular line in the C{uploaded_file}\n \"\"\"\n def __init__(self, filename, lineno, message):\n \"\"\"\n @param filename: The C{uploaded_file} that contains the error.\n\n @param lineno: The line number that contains the error.\n\n @param message: A localized human readable description of the\n error.\n \"\"\"\n super(ImportedMeasurementPoint.FileValidationError, self).__init__(\n u'%s:%s: %s' % (filename, lineno, message))\n self.filename = filename\n self.lineno = lineno\n\n class TimeValueError(FileValidationError):\n \"\"\"\n A time cell could not be parsed on a particular line in the\n C{uploaded_file}\n \"\"\"\n def __init__(self, filename, lineno, time_cell):\n \"\"\"\n @param filename: The C{uploaded_file} that contains the error.\n\n @param lineno: The line number that contains the error.\n\n @param time_cell: The textual contents of the time cell that did\n not parse.\n \"\"\"\n super(ImportedMeasurementPoint.TimeValueError, self).__init__(\n filename, lineno,\n _(\"Time value {time_value} did not parse\").format(\n time_value=time_cell))\n\n class TimeSequenceError(FileValidationError):\n def __init__(self, filename, lineno, time_cell):\n super(ImportedMeasurementPoint.TimeSequenceError, self).__init__(\n filename, lineno,\n _(\n 'Time stamps are not sequential ({time_value}), '\n 'check timezone').format(time_value=time_cell))\n\n class ConsumptionColumnDoesNotExist(FileValidationError):\n \"\"\"\n A given consumption column does not exist at a given row on a\n particular line in the C{uploaded_file}\n \"\"\"\n def __init__(self, filename, lineno, consumption_column):\n \"\"\"\n @param filename: The C{uploaded_file} that contains the error.\n\n @param lineno: The line number that contains the error.\n\n @param consumption_column: The column number that was not found on\n this particular line number.\n \"\"\"\n super(\n ImportedMeasurementPoint.ConsumptionColumnDoesNotExist, self).\\\n __init__(\n filename, lineno,\n _('Column {consumption_column} does not exist').format(\n consumption_column=consumption_column))\n self.consumption_column = consumption_column\n\n class ConsumptionParseError(FileValidationError):\n \"\"\"\n A consumption value could not be parsed on a particular line in the\n C{uploaded_file}\n \"\"\"\n def __init__(self, filename, lineno, value_cell):\n \"\"\"\n @param filename: The C{uploaded_file} that contains the error.\n\n @param lineno: The line number that contains the error.\n\n @param value_cell: The textual contents of the value cell that\n could not be parsed.\n \"\"\"\n super(\n ImportedMeasurementPoint.ConsumptionParseError, self).__init__(\n filename, lineno,\n _('Consumption value ({value_cell}) did not parse').format(\n value_cell=value_cell))\n\n def _parse_csv(self):\n \"\"\"\n Parse CSV file. This method is intended to be called from C{clean()}\n\n @precondition: C{self.upload_file is not None}\n @precondition: C{self.timezone is not None}\n\n @postcondition: C{self.parsed_csv} is non-emtpy\n\n @raise EmptyFileError: When the C{uploaded_file} did not contain any\n consumption data.\n\n @raise TimeParseError: When a time cell could not be parsed.\n\n @raise ConsumptionColumnDoesNotExist: When the C{consumption_column}\n does not exist.\n\n @raise ConsumptionParseError: When the contents of a consumption cell\n could not be parsed.\n \"\"\"\n assert self.upload_file is not None\n reader = unicodecsv.reader(\n self.upload_file,\n delimiter=self.column_delimiter,\n encoding='iso8859-1')\n self.parsed_csv = []\n\n row_counter = 0\n try:\n for row_counter, row in islice(izip(count(), reader),\n self.first_consumption_row, None):\n if len(row) == 0:\n continue\n time_cell = row[0]\n try:\n from_timestamp, to_timestamp = [\n self.timezone.localize(\n datetime.strptime(s, '%d-%m-%Y %H:%M')) for\n s in time_cell.split(' - ')]\n if from_timestamp > to_timestamp:\n raise self.TimeSequenceError(\n self.upload_file.name, row_counter, time_cell)\n # Rows must be in a sequence of each other.\n # Raise error if from_timestamp is not equal to_timestamp\n # on previous row.\n if self.parsed_csv and \\\n from_timestamp != self.parsed_csv[-1][1]:\n raise self.TimeSequenceError(\n self.upload_file.name,\n row_counter,\n '({previous_from_time} - {previous_fo_time}) '\n '({from_timestamp} - {to_timestamp})'.format(\n previous_from_time=self.parsed_csv[-1][0],\n previous_fo_time=self.parsed_csv[-1][1],\n to_timestamp=to_timestamp,\n from_timestamp=from_timestamp))\n except ValueError:\n raise self.TimeValueError(\n self.upload_file.name, row_counter, time_cell)\n\n if self.consumption_column < len(row):\n value_cell = row[self.consumption_column]\n else:\n raise self.ConsumptionColumnDoesNotExist(\n self.upload_file.name, row_counter,\n self.consumption_column)\n try:\n value = Fraction(\n '.'.join(value_cell.split(self.decimal_delimiter)))\n except:\n raise self.ConsumptionParseError(\n self.upload_file.name,\n row_counter, value_cell)\n self.parsed_csv.append((from_timestamp, to_timestamp, value))\n except unicodecsv.Error as e:\n raise self.FileValidationError(\n self.upload_file.name, row_counter, e)\n\n if not self.parsed_csv:\n raise self.EmptyFileError(self.upload_file.name)\n" }, { "alpha_fraction": 0.7118998169898987, "alphanum_fraction": 0.7306889295578003, "avg_line_length": 28.9375, "blob_id": "a5338121c3b5ece50a1d7d916e499c100c4cdba0", "content_id": "8abe76a891a8eed21ca5b3076cd80035ab486501", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 479, "license_type": "no_license", "max_line_length": 58, "num_lines": 16, "path": "/wifiagent/wifiagent/relay/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import requests\n\nfrom django.db import models\n\n\nclass Measurement(models.Model):\n\tmac = models.CharField(\"mac\", max_length=50)\n\tip = models.CharField(\"source ip\", max_length=50)\n\ttimestamp = models.DateTimeField() # TODO: No timezone...\n\tvrms_total = models.FloatField(\"Volt\");\n\t\t\n\nclass EndpointCache(models.Model):\n\tmac = models.CharField(\"mac\", max_length=50)\n\tendpoint = models.CharField(\"endpoint\", max_length=256)\n\ttimestamp = models.DateTimeField() # TODO: No timezone...\n" }, { "alpha_fraction": 0.7072310447692871, "alphanum_fraction": 0.7072310447692871, "avg_line_length": 26, "blob_id": "745431716397b88869b45a94d12eaf2c7f6c6d51", "content_id": "a11e063d75c4b5dae34895a78d22e9d727895c13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 567, "license_type": "no_license", "max_line_length": 76, "num_lines": 21, "path": "/gridplatform/cost_compensations/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from django import forms\n\nfrom gridplatform.utils import units\nfrom gridplatform.utils.forms import TimePeriodModelForm\n\nfrom . import models\n\n\nclass CostCompensationForm(forms.ModelForm):\n unit = forms.ChoiceField(choices=units.COST_COMPENSATION_CHOICES)\n\n class Meta:\n model = models.CostCompensation\n fields = ('name', 'unit')\n\n\nclass FixedCompensationPeriodForm(TimePeriodModelForm):\n class Meta:\n model = models.FixedCompensationPeriod\n fields = (\n 'from_date', 'from_hour', 'to_date', 'to_hour', 'value', 'unit')\n" }, { "alpha_fraction": 0.6355360746383667, "alphanum_fraction": 0.6416048407554626, "avg_line_length": 31.2391300201416, "blob_id": "83d03fd2bb2f8228c336ee08b77773ddb4da8f8e", "content_id": "33ad86b2e4f82a739f14120b5349ed0b633840e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2966, "license_type": "no_license", "max_line_length": 79, "num_lines": 92, "path": "/gridplatform/utils/relativetimedelta.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module defines the :class:`.RelativeTimeDelta` class, which\ndeprecates :class:`dateutil.relativedelta` and does what we always\nwished that :class:`datetime.timedelta` did.\n\n.. data:: DATETIME_MIN\n\n A largest lower bound for timezone aware datetimes.\n\n.. data:: DATETIME_MAX\n\n A least upper bound for timezone aware datetimes.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom dateutil.relativedelta import relativedelta\nimport pytz\n\nfrom . import DATETIME_MIN, DATETIME_MAX\n\n__all__ = ['RelativeTimeDelta', 'DATETIME_MIN', 'DATETIME_MAX']\n\n\ndef wrap(attr):\n \"\"\"\n Wrap operator methods of\n :class:`dateutil.relativedelta.relativedelta` so that they return\n a :class:`.RelativeTimeDelta` instance where they would otherwise\n return a :class:`dateutil.relativedelta.relativedelta` instance.\n And otherwise ensure that daylight saving time is handled as one\n would expect.\n\n :see: :class:`.RelativeTimeDelta`\n \"\"\"\n def wrapper(self, other):\n method = getattr(super(RelativeTimeDelta, self), attr)\n if isinstance(other, datetime.date) and \\\n isinstance(other.tzinfo, pytz.tzinfo.BaseTzInfo):\n tzinfo = other.tzinfo\n if self.years != 0 or self.months != 0 or self.days != 0:\n # normalize + localize handles edge case wrt. the\n # timestamps with two different hour representations\n # on DST switch...\n return tzinfo.normalize(\n tzinfo.localize(method(other.replace(tzinfo=None))))\n else:\n return tzinfo.normalize(method(other))\n\n res = method(other)\n if isinstance(res, relativedelta):\n res.__class__ = self.__class__\n return res\n return wrapper\n\n\nclass RelativeTimeDelta(relativedelta):\n \"\"\"\n Timezone aware :class:`dateutil.relativedelta.relativedetla`\n specialization.\n\n :class:`datetime.timedelta` thinks that timespans are always a\n number of seconds. This ofcourse does not hold for timespans such\n as days, months, and years.\n\n :class:`dateutil.relativedelta.relativedelta` almost got it right, although\n it thinks that timespans are not needed across daylight saving\n time transitions, i.e. a month after march 1st 00:00:00 is\n ofcourse april 1st 01:00:00.\n\n The :class:`.RelativeTimeDelta` class deprecates\n :class:`dateutil.relativedelta.relativedelta`.\n \"\"\"\n\n __add__ = wrap(\"__add__\")\n __radd__ = wrap(\"__radd__\")\n __sub__ = wrap(\"__sub__\")\n __rsub__ = wrap(\"__rsub__\")\n __mul__ = wrap(\"__mul__\")\n __rmul__ = wrap(\"__rmul__\")\n __div__ = wrap(\"__div__\")\n\n def __neg__(self):\n res = super(RelativeTimeDelta, self).__neg__()\n res.__class__ = self.__class__\n return res\n\n def __hash__(self):\n return hash((self.hours, self.days, self.months, self.year))\n" }, { "alpha_fraction": 0.7005987763404846, "alphanum_fraction": 0.7065868377685547, "avg_line_length": 19.875, "blob_id": "514d23e25495375df76eccc67a4c23d756e99e58", "content_id": "39b0ec98f107dcd277984e299b274ff1ee1efe68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 167, "license_type": "no_license", "max_line_length": 69, "num_lines": 8, "path": "/scripts/production/stop_uwsgi.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsource $(dirname $0)/base.sh\n\nPIDFILE=$PID_DIR/uwsgi.pid\n\n# the default signal for kill is TERM, which causes uWSGI to \"reload\"\nkill -INT $(cat $PIDFILE)\n" }, { "alpha_fraction": 0.6223870515823364, "alphanum_fraction": 0.6258549094200134, "avg_line_length": 27.997207641601562, "blob_id": "062c432698d809bb8a2508a026e382fc64fef3c0", "content_id": "941d9f569b81e265f86e2489237ffec2f8cab714", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10381, "license_type": "no_license", "max_line_length": 79, "num_lines": 358, "path": "/legacy/manage_collections/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.forms import ModelForm, ImageField\nfrom django.http import HttpResponseForbidden\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.http import require_POST\nfrom django.forms.widgets import ClearableFileInput\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.manage_collections.models import CollectionItem\nfrom legacy.manage_collections.models import Floorplan\nfrom legacy.manage_collections.models import InfoItem\nfrom legacy.manage_collections.models import Item\nfrom legacy.manage_measurementpoints.forms import CollectionForm\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.users.decorators import customer_admin_or_error\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import render_to\n\n\n@customer_admin_or_error\n@json_response\ndef group_delete(request):\n instance = get_object_or_404(Collection, pk=request.GET['pk'])\n customer = request.customer\n if instance.customer != customer or not instance.is_deletable():\n return HttpResponseForbidden()\n\n instance.delete()\n return {\n 'success': True,\n 'statusText': _('The group has been deleted'),\n }\n\n\n@auth_or_error\n@json_response\ndef group_list_json(request):\n options = json_list_options(request)\n customer = request.customer\n if options['search']:\n data = list(Collection.objects.filter(\n customer=customer, role=Collection.GROUP))\n else:\n data = list(Collection.objects.filter(\n customer=customer, role=Collection.GROUP, level=0))\n\n if options['search']:\n data = filter(\n lambda c: c.satisfies_search(options['search']), data)\n\n if options['search']:\n rendered = [\n render_to_string(\n 'manage_collections/group_normal_block.html',\n {'group': group},\n RequestContext(request))\n for group in data\n ]\n else:\n rendered = [\n render_to_string(\n 'manage_collections/group_block.html',\n {'groups': group.get_descendants(include_self=True)\n .filter(role=Collection.GROUP)},\n RequestContext(request))\n for group in data\n ]\n\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\n@customer_admin_or_error\n@render_to('manage_collections/group_form.html')\ndef group_form(request, pk=None):\n customer = request.customer\n if pk:\n instance = get_object_or_404(Collection, pk=pk)\n if instance.customer != customer:\n return HttpResponseForbidden()\n reason = instance.get_delete_prevention_reason()\n else:\n reason = None\n instance = None\n\n form = CollectionForm(instance=instance, auto_id=False)\n\n return {\n 'form': form,\n 'delete_prevention_reason': reason\n }\n\n\n# parent = 0 means no change in parent.\n# parent > 0 is the id of the parent\n# parent = None means no parent\n@customer_admin_or_error\n@json_response\ndef group_update(request, pk=None):\n if pk:\n instance = get_object_or_404(\n Collection.objects.filter(role=Collection.GROUP), pk=pk)\n old_parent = instance.parent\n else:\n instance = None\n old_parent = None\n\n form = CollectionForm(request.POST, instance=instance, auto_id=False)\n if form.is_valid():\n group = form.save(commit=False)\n group.role = Collection.GROUP\n group.utility_type = utilitytypes.OPTIONAL_METER_CHOICES.unknown\n group.save()\n\n if old_parent == group.parent:\n parent = 0\n else:\n if group.parent is not None:\n parent = group.parent.id\n else:\n parent = None\n\n return {\n 'success': True,\n 'statusText': _('The group has been saved'),\n 'html': render_to_string(\n 'manage_collections/group_normal_block.html',\n {'group': group},\n RequestContext(request)\n ),\n 'parent': parent,\n }\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_collections/group_form.html',\n {\n 'form': form,\n },\n RequestContext(request)\n ),\n }\n\n\n@auth_or_error\n@json_response\ndef measurementpoints_list_json(request, group_id):\n group = get_object_or_404(Collection, pk=group_id)\n options = json_list_options(request)\n data = list(group.children.filter(\n graph__isnull=False).distinct().select_related('collection'))\n if options['search']:\n data = filter(\n lambda mp: mp.satisfies_search(options['search']), data)\n order_map = {\n 'group': lambda coll: unicode(coll.parent),\n 'name': lambda coll: unicode(coll.name),\n }\n if options['order_by'] and options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_measurementpoints/block.html',\n {'graph_collection': measurementpoints, },\n RequestContext(request))\n for measurementpoints in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass NoUrlClearableFileInput(ClearableFileInput):\n template_with_initial = '%(clear_template)s<br />%(input_text)s: %(input)s'\n\n\nclass FloorplanForm(ModelForm):\n image = ImageField(\n widget=NoUrlClearableFileInput,\n error_messages={'required': _('Browse and select an image first')})\n\n class Meta:\n model = Floorplan\n fields = ('image',)\n localized_fields = '__all__'\n\n\n@render_to('manage_collections/group_floorplan.html')\ndef floorplan(request, pk):\n \"\"\"\n Renders an image upload form, L{FloorPlanForm}.\n\n If a floor plan has previously been created for the group with id C{pk}, a\n list of measurement points (C{collections}) that can be placed on the floor\n plan, and a list of measurement points that has already been placed on the\n floor plan (C{placed_collections}) is rendered too.\n\n Placement of measurement points is handled in another view.\n \"\"\"\n group = get_object_or_404(Collection, pk=pk)\n\n floorplan = group.get_floorplan()\n if floorplan:\n items = [item.subclass_instance for item in floorplan.item_set.all()]\n else:\n items = []\n\n collections = group.get_descendants(\n include_self=False).\\\n exclude(collectionitem__floorplan__collection=group)\n\n if request.method == 'POST':\n form = FloorplanForm(\n request.POST, request.FILES,\n instance=floorplan)\n if form.is_valid():\n floorplan = form.save(commit=False)\n floorplan.collection = group\n floorplan.save()\n else:\n form = FloorplanForm(instance=floorplan)\n\n return {\n 'object': group,\n 'form': form,\n 'collections': collections,\n 'placed_items': items\n }\n\n\nclass UpdateInfoItemForm(forms.ModelForm):\n class Meta:\n model = InfoItem\n fields = ['info']\n localized_fields = '__all__'\n\n\n@require_POST\n@json_response\ndef save_info_item(request):\n item = get_object_or_404(InfoItem, pk=request.POST['pk'])\n form = UpdateInfoItemForm(request.POST, instance=item)\n if form.is_valid():\n item.save()\n\n return {\n 'id': item.id\n }\n\n\nclass AddCollectionItemForm(forms.ModelForm):\n\n class Meta:\n model = CollectionItem\n fields = ['x', 'y', 'z', 'collection']\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n group = kwargs.pop('group', None)\n super(AddCollectionItemForm, self).__init__(*args, **kwargs)\n self.instance.floorplan = group.floorplan\n self.fields['collection'].queryset = group.get_descendants(\n include_self=False)\n\n\nclass AddInfoItemForm(forms.ModelForm):\n\n class Meta:\n model = InfoItem\n fields = ['x', 'y', 'z']\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n group = kwargs.pop('group', None)\n super(AddInfoItemForm, self).__init__(*args, **kwargs)\n self.instance.floorplan = group.floorplan\n\n\n@require_POST\n@json_response\ndef place_item(request, pk):\n group = get_object_or_404(Collection, pk=pk)\n if group.customer != get_customer():\n return HttpResponseForbidden()\n form = AddCollectionItemForm(request.POST, group=group)\n item = form.save()\n item.save()\n\n return {\n 'id': item.id\n }\n\n\nclass UpdateItemForm(forms.ModelForm):\n\n class Meta:\n model = Item\n fields = ['x', 'y']\n localized_fields = '__all__'\n\n\n@require_POST\n@json_response\ndef update_placement(request):\n item = get_object_or_404(Item, pk=request.POST['pk'])\n form = UpdateItemForm(request.POST, instance=item)\n form.save()\n\n return {\n 'id': item.id\n }\n\n\n@require_POST\n@json_response\ndef place_infoitem(request, pk):\n group = get_object_or_404(Collection, pk=pk)\n if group.customer != get_customer():\n return HttpResponseForbidden()\n form = AddInfoItemForm(request.POST, group=group)\n item = form.save()\n return {\n 'id': item.id\n }\n\n\n@json_response\ndef remove_item(request):\n\n removedItem = Item.objects.get(pk=int(request.GET['item']))\n if removedItem.floorplan.collection.customer != get_customer():\n return HttpResponseForbidden()\n items = removedItem.floorplan.item_set.filter(z__gt=removedItem.z)\n removedItem.delete()\n for item in items:\n item.z = item.z - 1\n item.save()\n\n return {\n 'success': True,\n }\n" }, { "alpha_fraction": 0.6144028902053833, "alphanum_fraction": 0.6180492043495178, "avg_line_length": 26.424999237060547, "blob_id": "e80c4bfc82455ec87008bb6b79ccf015830233b2", "content_id": "822af4022acc592051c7f63bb774c5f92707e167", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1097, "license_type": "no_license", "max_line_length": 61, "num_lines": 40, "path": "/energymanager/configuration_site/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy\nfrom django.utils.translation import ugettext as _\nfrom django import forms\n\nfrom legacy.devices.models import Meter, Agent\n\n\nclass MeterModelForm(forms.ModelForm):\n WIBEEE = 0\n WIBEEE_MAX = 1\n DATAHUB = 2\n TYPE_CHOICES = (\n (WIBEEE, _('Wibeee Box')),\n # (WIBEEE_MAX, _('Wibeee Max')),\n (DATAHUB, _('Datahub')),\n )\n\n meter_type = forms.ChoiceField(\n label=ugettext_lazy('Type'),\n choices=TYPE_CHOICES\n )\n\n agent = forms.ModelChoiceField(\n label=ugettext_lazy('Agent'),\n queryset=Agent.objects.none, empty_label=None\n )\n\n class Meta:\n model = Meter\n fields = ['name', 'location', 'hardware_id']\n\n def __init__(self, *args, **kwargs):\n customer_id = kwargs.pop('customer_id', '')\n super(MeterModelForm, self).__init__(*args, **kwargs)\n self.fields['agent'].queryset = Agent.objects.filter(\n customer_id=customer_id)\n" }, { "alpha_fraction": 0.6818347573280334, "alphanum_fraction": 0.6826841235160828, "avg_line_length": 39.5960578918457, "blob_id": "35c26b93e03a2c1aa8cfbcb8491dd28edabced60", "content_id": "a9dbe1fb0e2061817d0be5b001ff94ee19a367ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8241, "license_type": "no_license", "max_line_length": 78, "num_lines": 203, "path": "/gridplatform/energyperformances/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.consumptions.models import ConsumptionGroup\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.productions.models import ProductionGroup\nfrom gridplatform.trackuser.managers import StoredSubclassCustomerBoundManager\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionAENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionBENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionCENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionDENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionEENPIUnitConverter\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import CONSUMPTION_PER_TIME_CHOICES\nfrom gridplatform.utils.fields import BuckinghamField\n\n\nclass EnergyPerformance(\n EncryptionCustomerFieldMixin, EncryptedModel, StoreSubclass):\n \"\"\"\n Base model for energy performances.\n\n :ivar name: The name of the energy performance.\n :ivar description: The description of the energy performance.\n \"\"\"\n name = EncryptedCharField(_('name'), max_length=255)\n description = EncryptedTextField(_('description'))\n\n objects = StoredSubclassCustomerBoundManager()\n\n class Meta:\n verbose_name = _('energy performance')\n verbose_name_plural = _('energy performances')\n\n def __unicode__(self):\n return self.name_plain\n\n @virtual\n def compute_performance(self, from_timestamp, to_timestamp):\n \"\"\"\n Pure virtual method for computing the energy performance across the\n given period.\n\n :param from_timestamp: The start of the given period.\n :param to_time: The end of the given period.\n :rtype: A `PhysicalQuantity` or `None`\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n @cached_property\n def unit_converter(self):\n return self._get_unit_converter()\n\n @virtual\n def _get_unit_converter(self):\n raise NotImplementedError(self.__class__)\n\n\nclass ProductionEnergyPerformance(EnergyPerformance):\n \"\"\"\n Production based energy performance defined from given energy consumptions\n and given productions.\n\n :ivar production_unit: The production unit must be shared among all\n participating productions. Choices depend on associated customer and\n should be defined on runtime in terms of\n :py:meth:`~gridplatform.customers.models.Customer\n .get_production_unit_choices`.\n :ivar consumptiongroups: The\n :py:class:`~gridplatform.consumptions.models.ConsumptionGroup` that\n define the given energy consumptions.\n :ivar productiongroups: The\n :py:class:`~gridplatform.productions.models.ProductionGroup` that\n define the given productions.\n \"\"\"\n\n # NOTE: Use get_production_unit_choices() from get_customer() or\n # instance.customer as choices for the `production_unit` field.\n production_unit = BuckinghamField(_('production unit'))\n consumptiongroups = models.ManyToManyField(\n ConsumptionGroup, verbose_name=_('consumption groups'), blank=True)\n productiongroups = models.ManyToManyField(\n ProductionGroup,\n verbose_name=_('production groups'),\n blank=True)\n\n class Meta:\n verbose_name = _('production energy performance')\n verbose_name_plural = _('production energy performances')\n\n def clean_fields(self, exclude=None):\n \"\"\"\n :raises ValidationError: if ``self.production_unit`` is not among the\n units returned by ``self.customer.get_production_unit_choices()``\n \"\"\"\n if exclude is None or 'production_unit' not in exclude:\n if self.production_unit not in \\\n self.customer.get_production_unit_choices():\n raise ValidationError(\n {'production_unit': [_('Illegal choice')]})\n\n def compute_performance(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :py:meth:`.EnergyPerformance.compute_performance`.\n\n :return: the total energy consumption across the given period divided\n by the total production across the given period. Division-by-zero\n is handled by returning ``None``.\n \"\"\"\n total_energy = sum(\n (\n energy for energy in (\n consumptiongroup.energy_sum(\n from_timestamp, to_timestamp)\n for consumptiongroup in self.consumptiongroups.all())\n if energy is not None),\n PhysicalQuantity(0, 'watt*hour'))\n\n total_production = sum(\n (\n production for production in (\n productiongroup.development_sum(\n from_timestamp, to_timestamp)\n for productiongroup in self.productiongroups.all())\n if production is not None),\n PhysicalQuantity(0, self.production_unit))\n if total_production:\n return total_energy / total_production\n else:\n return None\n\n def _get_unit_converter(self):\n energy_unit = 'kilowatt*hour'\n if self.production_unit == 'production_a':\n return ProductionAENPIUnitConverter(energy_unit, self.customer)\n elif self.production_unit == 'production_b':\n return ProductionBENPIUnitConverter(energy_unit, self.customer)\n elif self.production_unit == 'production_c':\n return ProductionCENPIUnitConverter(energy_unit, self.customer)\n elif self.production_unit == 'production_d':\n return ProductionDENPIUnitConverter(energy_unit, self.customer)\n elif self.production_unit == 'production_e':\n return ProductionEENPIUnitConverter(energy_unit, self.customer)\n\n @property\n def unit(self):\n return self.production_unit\n\n\nclass TimeEnergyPerformance(EnergyPerformance):\n \"\"\"\n Time adjustment based energy performance (mean power) for given energy\n consumptions.\n\n :ivar consumptiongroups: The\n :py:class:`~gridplatform.consumptions.models.ConsumptionGroup` that\n define the given energy consumptions.\n :ivar unit: The mean-power unit. Must be one of\n :py:data:`~gridplatform.utils.units.CONSUMPTION_PER_TIME_CHOICES`.\n \"\"\"\n consumptiongroups = models.ManyToManyField(\n ConsumptionGroup, verbose_name=_('consumption groups'), blank=True)\n unit = BuckinghamField(_('unit'), choices=CONSUMPTION_PER_TIME_CHOICES)\n\n class Meta:\n verbose_name = _('consumption performance')\n verbose_name_plural = _('consumption performances')\n\n def compute_performance(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :py:meth:`.EnergyPerformance.compute_performance`.\n\n :return: the mean-power calculated from the total energy consumption\n across the given period.\n \"\"\"\n assert from_timestamp < to_timestamp\n total_energy = sum(\n (\n energy for energy in (\n consumptiongroup.energy_sum(\n from_timestamp, to_timestamp)\n for consumptiongroup in self.consumptiongroups.all())\n if energy is not None),\n PhysicalQuantity(0, 'watt*hour'))\n return total_energy / \\\n PhysicalQuantity(\n (to_timestamp - from_timestamp).total_seconds(), 'second')\n\n @virtual\n def _get_unit_converter(self):\n return PhysicalUnitConverter(self.unit)\n" }, { "alpha_fraction": 0.6880281567573547, "alphanum_fraction": 0.689906120300293, "avg_line_length": 33.35483932495117, "blob_id": "5e6e5f50de29dc44e0235ecb90031f7c1dcac7c1", "content_id": "d15731d96dde1584f3278cc6eb09a76e6114f1b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4260, "license_type": "no_license", "max_line_length": 79, "num_lines": 124, "path": "/legacy/rules/engine.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nStrategy:\n\nEvery hour, reload set of active rules.\n(... may give scalability problems later --- but not anytime soon.)\n\nContinuously check currently active rules.\n(... rules that do not depend on current inputs and thus will only do something\nat a predetermined time may be a bit silly to recheck --- but it's also cheap\nto do so; avoiding it takes a bigger change than necessary now...)\n\n\nGet active rules for timestamp:\n* Iterate over all UserRule objects\n* Get timestamp in userrule timezone\n* Include if from_time < to_time and from_time <= timestamp <= to_time and rule\n* active for timestamp.weekday (rule does not span day change; simple check)\n* Also include if to_time <= from_time and timestamp >= from_time and rule\n* active for timestamp.weekday (rule spans day; after start today; before stop\n* tomorrow)\n* Also include if to_time <= from_time and timestamp <= to_time and rule active\n* for timestamp.weekday - 1 (rule spans day; after start yesterday; before\n* stop today)\n\n... for now, generate_rules is modified to be conservative; include rules\nstarting at current date and rules starting at previous date when they span\nover midnigt...\n... and, we take timezones into account...\n\"\"\"\n\nimport datetime\nimport time\n\nimport pytz\n\nfrom legacy.rules.models import UserRule, EngineRule\nfrom legacy.devices.models import Meter\n\n\ndef get_tainted_meter_ids():\n \"\"\"\n Tainted L{Meters}, are L{Meters} whose relays are controlled by\n anything different than static time schedules, and therefore needs to\n be handled by this Engine.\n\n @return: Returns a list of ids of Meters that are considered tainted.\n \"\"\"\n # Meters with RelayActions of TriggeredRules having Invariants are\n # considered tainted.\n return Meter.objects.filter(\n relayaction__rule__triggeredrule__inputinvariant__isnull=False).\\\n distinct().values_list('id', flat=True)\n\n\ndef get_engine_rules(date):\n \"\"\"\n Rules to be processed by this C{Engine} at a given date.\n\n @param date: The given date.\n\n @return: A list of L{EngineRule}s and L{AgentRules} to be processed by\n this C{Engine} at the given C{date}.\n \"\"\"\n assert isinstance(date, datetime.datetime)\n assert date.tzinfo is not None\n tainted_meters = get_tainted_meter_ids()\n\n engine_rules = []\n\n rules = UserRule.objects.filter(enabled=True).select_related('relayaction')\n\n # Both AgentRules and EngineRules that have RelayActions that work on\n # the relays of tainted Meters must be processed by the Engine.\n for user_rule in rules.filter(\n relayaction__meter__in=tainted_meters).distinct():\n engine_rules.extend(user_rule.generate_rules(date))\n\n # For all other rules, only the actual EngineRules should be handled by\n # the engine.\n for user_rule in rules.exclude(\n relayaction__meter__in=tainted_meters).distinct():\n for rule in user_rule.generate_rules(date):\n if isinstance(rule, EngineRule):\n engine_rules.append(rule)\n\n return engine_rules\n\n\ndef refresh_rules(rules, hour):\n \"\"\"\n HACK: figure out what rules have become active/inactive, in order to\n construct a set of currently active rules --- but keep the objects from the\n old set where possible, to let the value of the process_again property\n survive...\n \"\"\"\n hour_rules = set(get_engine_rules(hour))\n new_rules = hour_rules - rules\n removed_rules = rules - hour_rules\n return (rules - removed_rules) | new_rules\n\n\ndef run():\n last_hour = None\n rules = set()\n\n while True:\n now = datetime.datetime.now(pytz.utc).replace(microsecond=0)\n hour = now.replace(minute=0, second=0, microsecond=0)\n\n # NOTE: new rules are taken in on next iteration --- we need to handle\n # \"obsoleted\" rules before updating the rule set to ensure that their\n # final action is executed.\n for rule in rules:\n if rule.process_again:\n map(lambda action: action.execute(), rule.process(now))\n\n if hour != last_hour:\n rules = refresh_rules(rules, hour)\n last_hour = hour\n\n time.sleep(10)\n" }, { "alpha_fraction": 0.7011204361915588, "alphanum_fraction": 0.7020399570465088, "avg_line_length": 38.626182556152344, "blob_id": "62179b3d259f9aa58a57297bbc60550144844530", "content_id": "a6bd3a147f34b3a0f93e4c8102cf7466ae4a6738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29363, "license_type": "no_license", "max_line_length": 89, "num_lines": 741, "path": "/legacy/manage_measurementpoints/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom django.http import HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext as _\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic.edit import CreateView\nfrom django.views.generic.edit import UpdateView\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.core.exceptions import ValidationError\nfrom django.http import HttpResponse\nfrom django.forms.models import BaseInlineFormSet\n\nfrom extra_views import InlineFormSet\nfrom extra_views import UpdateWithInlinesView\nfrom extra_views import CreateWithInlinesView\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPointSummation # noqa\nfrom legacy.measurementpoints.proxies import ConsumptionMultiplicationPoint\nfrom legacy.measurementpoints.proxies import CurrentMeasurementPoint\nfrom legacy.measurementpoints.proxies import DistrictHeatingMeasurementPoint\nfrom legacy.measurementpoints.proxies import MeasurementPoint\nfrom legacy.measurementpoints.proxies import PowerMeasurementPoint\nfrom legacy.measurementpoints.proxies import ReactivePowerMeasurementPoint\nfrom legacy.measurementpoints.proxies import ReactiveEnergyMeasurementPoint\nfrom legacy.measurementpoints.proxies import PowerFactorMeasurementPoint\nfrom legacy.measurementpoints.proxies import ProductionMeasurementPoint\nfrom legacy.measurementpoints.proxies import TemperatureMeasurementPoint\nfrom legacy.measurementpoints.proxies import VoltageMeasurementPoint\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.users.decorators import customer_admin_or_error\nfrom gridplatform.utils import DATETIME_MIN\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.formsets import SurvivingFormsModelFormSetMixin\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.utils.views import json_response\nfrom legacy.efficiencymeasurementpoints.models import EfficiencyMeasurementPoint # noqa\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Chain\nfrom legacy.measurementpoints.models import ChainLink\nfrom legacy.measurementpoints.models import CostCalculation\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import Graph\n\nfrom .forms import ConsumptionMeasurementPointUpdateForm\nfrom .forms import ConsumptionMeasurementPointSummationForm\nfrom .forms import InputConsumptionMeasurementPointForm\nfrom .forms import MultiplicationConsumptionMeasurementPointForm\nfrom .forms import DistrictHeatingMeasurementPointCreateForm\nfrom .forms import DistrictHeatingMeasurementPointEditForm\nfrom .forms import TariffPeriodForm\nfrom .forms import TemperatureMeasurementPointForm\nfrom .forms import InputTemperatureMeasurementPointForm\nfrom .forms import ProductionMeasurementPointForm\nfrom .forms import InputProductionMeasurementPointForm\nfrom .forms import InputCurrentMeasurementPointForm\nfrom .forms import CurrentMeasurementPointForm\nfrom .forms import InputVoltageMeasurementPointForm\nfrom .forms import InputPowerMeasurementPointForm\nfrom .forms import InputReactivePowerMeasurementPointForm\nfrom .forms import InputReactiveEnergyMeasurementPointForm\nfrom .forms import InputPowerFactorMeasurementPointForm\nfrom .forms import VoltageMeasurementPointForm\nfrom .forms import PowerMeasurementPointForm\nfrom .forms import ReactivePowerMeasurementPointForm\nfrom .forms import ReactiveEnergyMeasurementPointForm\nfrom .forms import PowerFactorMeasurementPointForm\nfrom .forms import EfficiencyMeasurementPointForm\nfrom .forms import InputEfficiencyMeasurementPointForm\n\n\n# for reuse in admin interface\ndef list_data(request, customer, template, data=None):\n options = json_list_options(request)\n\n if data is None:\n data = [mp.subclass_instance for mp in\n MeasurementPoint.objects.subclass_only().filter(\n role__in=Collection.DATA_POINTS,\n customer=customer).distinct().select_related('parent')]\n\n if options['search']:\n data = filter(\n lambda graph_collection: graph_collection.satisfies_search(\n options['search']), data)\n\n order_map = {\n 'group': lambda graph_collection: unicode(\n graph_collection.parent),\n 'name': lambda graph_collection: unicode(\n graph_collection.name_plain.lower()),\n }\n if options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n\n data_slice = data[options['offset']:options['offset'] + options['count']]\n\n rendered = [\n render_to_string(\n template,\n {'graph_collection': graph_collection, },\n RequestContext(request))\n for graph_collection in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\n@customer_admin_or_error\ndef measurementpoint_form(request, pk):\n instance = get_object_or_404(\n MeasurementPoint.objects.subclass_only(),\n customer=request.customer, id=pk).subclass_instance\n\n if isinstance(instance, ConsumptionMeasurementPointSummation):\n return ConsumptionMeasurementPointSummationUpdateView.as_view()(\n request, pk=pk)\n elif isinstance(instance, ConsumptionMultiplicationPoint):\n return ConsumptionMultiplicationPointUpdateView.as_view()(\n request, pk=pk)\n elif isinstance(instance, DistrictHeatingMeasurementPoint):\n return DistrictHeatingMeasurementPointUpdateView.as_view()(\n request, pk=pk)\n elif isinstance(instance, ConsumptionMeasurementPoint):\n return ConsumptionMeasurementPointUpdateView.as_view(\n form_class=ConsumptionMeasurementPointUpdateForm)(request, pk=pk)\n elif isinstance(instance, TemperatureMeasurementPoint):\n return temperature_measurement_point_update_form(request, instance)\n elif isinstance(instance, ProductionMeasurementPoint):\n return ProductionMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, CurrentMeasurementPoint):\n return CurrentMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, EfficiencyMeasurementPoint):\n return EfficiencyMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, VoltageMeasurementPoint):\n return VoltageMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, PowerMeasurementPoint):\n return PowerMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, ReactivePowerMeasurementPoint):\n return ReactivePowerMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, ReactiveEnergyMeasurementPoint):\n return ReactiveEnergyMeasurementPointUpdate.as_view()(request, pk=pk)\n elif isinstance(instance, PowerFactorMeasurementPoint):\n return PowerFactorMeasurementPointUpdate.as_view()(request, pk=pk)\n\n\n@customer_admin_or_error\n@json_response\ndef measurementpoint_delete(request):\n instance = get_object_or_404(Collection, pk=request.GET['pk'])\n customer = trackuser.get_customer()\n if instance.customer != customer or \\\n not instance.subclass_instance.is_deletable():\n return HttpResponseForbidden()\n instance.delete()\n return {\n 'success': True,\n 'statusText': _('The measurement point has been deleted'),\n }\n\n\n@auth_or_error\n@json_response\ndef list_json(request):\n customer = trackuser.get_customer()\n return list_data(\n request, customer, 'manage_measurementpoints/block.html')\n\n\nclass BaseMeasurementPointSlideIn(object):\n \"\"\"\n Mixin for measurement point slide-in views.\n\n Provides means to render normal respones aswell as json responses. The\n former is useful for slide-in form rendering, and the later is useful for\n slide-in form validation.\n \"\"\"\n\n @method_decorator(customer_admin_or_error)\n def dispatch(self, request, *args, **kwargs):\n return super(BaseMeasurementPointSlideIn, self).dispatch(\n request, *args, **kwargs)\n\n def render_valid_to_json_response(self, context):\n data = {\n 'success': True,\n 'statusText': self.status_text,\n 'html': render_to_string(\n 'manage_measurementpoints/block.html',\n context,\n RequestContext(self.request)),\n 'parent': self.object.parent_id or None,\n }\n json_data = json.dumps(data, cls=DjangoJSONEncoder)\n return HttpResponse(json_data, content_type='application/json')\n\n def render_invalid_to_json_response(self, context):\n data = {\n 'success': False,\n 'html': render_to_string(\n self.template_name,\n context,\n RequestContext(self.request))\n }\n json_data = json.dumps(data, cls=DjangoJSONEncoder)\n return HttpResponse(json_data, content_type='application/json')\n\n def get_context_data(self, **kwargs):\n if self.object:\n kwargs['delete_prevention_reason'] = \\\n self.object.get_delete_prevention_reason()\n return super(\n BaseMeasurementPointSlideIn,\n self).get_context_data(**kwargs)\n\n\nclass MeasurementPointSlideInFormMixin(BaseMeasurementPointSlideIn):\n \"\"\"\n Mixin for measurement point slide-in form views.\n\n Works by:\n\n - displaying initial form if method is GET\n - displaying validated form if method is POST and form is invalid (JSON)\n - displaying success message and MP block if method is POST and form is\n valid (JSON)\n \"\"\"\n def form_invalid(self, form):\n return self.render_invalid_to_json_response(\n self.get_context_data(form=form))\n\n def form_valid(self, form):\n self.object = form.save()\n return self.render_valid_to_json_response(\n self.get_context_data(graph_collection=self.object))\n\n\nclass MeasurementPointSlideInFormWithInlinesMixin(BaseMeasurementPointSlideIn):\n \"\"\"\n Mixin for measurement point slide-in form views that also has inlines.\n\n Works by:\n\n - displaying initial form if method is GET\n - displaying validated form if method is POST and form is invalid (JSON)\n - displaying success message and MP block if method is POST and form is\n valid (JSON)\n \"\"\"\n\n def forms_invalid(self, form, inlines):\n return self.render_invalid_to_json_response(\n self.get_context_data(form=form, inlines=inlines))\n\n def forms_valid(self, form, inlines):\n self.object = form.save()\n for formset in inlines:\n formset.save()\n return self.render_valid_to_json_response(\n self.get_context_data(graph_collection=self.object))\n\n\nclass CurrentMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = CurrentMeasurementPoint\n form_class = InputCurrentMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass CurrentMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = CurrentMeasurementPoint\n form_class = CurrentMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass EfficiencyMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = EfficiencyMeasurementPoint\n form_class = InputEfficiencyMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass EfficiencyMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = EfficiencyMeasurementPoint\n form_class = EfficiencyMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass VoltageMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = VoltageMeasurementPoint\n form_class = InputVoltageMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass VoltageMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = VoltageMeasurementPoint\n form_class = VoltageMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass PowerMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = PowerMeasurementPoint\n form_class = InputPowerMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass PowerMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = PowerMeasurementPoint\n form_class = PowerMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass ReactivePowerMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = ReactivePowerMeasurementPoint\n form_class = InputReactivePowerMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass ReactivePowerMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = ReactivePowerMeasurementPoint\n form_class = ReactivePowerMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass ReactiveEnergyMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = ReactiveEnergyMeasurementPoint\n form_class = InputReactiveEnergyMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass ReactiveEnergyMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = ReactiveEnergyMeasurementPoint\n form_class = ReactiveEnergyMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass PowerFactorMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = PowerFactorMeasurementPoint\n form_class = InputPowerFactorMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass PowerFactorMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = PowerFactorMeasurementPoint\n form_class = PowerFactorMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass ProductionMeasurementPointCreate(\n MeasurementPointSlideInFormMixin, CreateView):\n model = ProductionMeasurementPoint\n form_class = InputProductionMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n\n\nclass ProductionMeasurementPointUpdate(\n MeasurementPointSlideInFormMixin, UpdateView):\n model = ProductionMeasurementPoint\n form_class = ProductionMeasurementPointForm\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n\nclass TariffPeriodFormSet(SurvivingFormsModelFormSetMixin, BaseInlineFormSet):\n \"\"\"\n Tariffs attached to a consumption measurement point are stored in a\n horrible complicated relation, namely in terms of number of intermediate\n data series, all needing to be kept up to date.\n \"\"\"\n def _construct_form(self, i, **kwargs):\n form = super(TariffPeriodFormSet, self)._construct_form(i, **kwargs)\n if i == 0:\n form.fields.pop('valid_from')\n form.instance.valid_from = DATETIME_MIN\n return form\n\n def clean(self):\n surviving_forms = self.surviving_forms()\n\n # ChainLinks can validate themselves given a Chain instance. However,\n # that chain instance is part of the intermediate data series frawned\n # upon in the docstring of this class, and may therefore need to be\n # created on the fly.\n if not self.instance.id and len(surviving_forms) > 0 and \\\n surviving_forms[0].is_valid():\n tariff_role = surviving_forms[0].cleaned_data['data_series'].role\n tariff_unit = surviving_forms[0].cleaned_data['data_series'].unit\n\n self.instance = Chain(\n role=DataRoleField.hidden_tariff_for_role(tariff_role),\n unit=tariff_unit,\n utility_type=self.measurement_point.utility_type)\n\n for form in surviving_forms:\n form.instance.chain = self.instance\n\n dates_seen = []\n for form in surviving_forms:\n if 'valid_from' in form.cleaned_data:\n if form.cleaned_data['valid_from'] in dates_seen:\n raise ValidationError(_('Valid-from dates must be unique'))\n dates_seen.append(form.cleaned_data['valid_from'])\n\n super(TariffPeriodFormSet, self).clean()\n\n def save_intermediate_data_series(self):\n surviving_forms = self.surviving_forms()\n\n if len(surviving_forms) > 0:\n # intermediate data series are needed\n if not self.instance.graph_id:\n # all intermediate data series are missing\n self.instance.graph = Graph.objects.get_or_create(\n collection=self.measurement_point,\n role=DataRoleField.HIDDEN,\n hidden=True)[0]\n self.instance.save()\n\n cost_graph = Graph.objects.create(\n collection=self.measurement_point,\n role=DataRoleField.COST)\n\n cost = CostCalculation(\n role=DataRoleField.COST,\n utility_type=self.measurement_point.utility_type,\n consumption=self.measurement_point.consumption,\n index=self.instance,\n graph=cost_graph)\n cost.full_clean(exclude=['unit']) # sets the right unit\n cost.save()\n\n elif len(surviving_forms) == 0 and self.instance.id:\n # intermediate data series are no longer needed\n CostCalculation.objects.filter(\n graph__collection=self.measurement_point,\n utility_type=self.measurement_point.utility_type,\n consumption=self.measurement_point.consumption,\n index=self.instance).delete()\n Graph.objects.filter(\n collection=self.measurement_point,\n role=DataRoleField.COST).delete()\n\n def save(self, commit=True):\n surviving_forms = self.surviving_forms()\n\n if commit:\n self.save_intermediate_data_series()\n result = super(TariffPeriodFormSet, self).save(commit=True)\n if len(surviving_forms) == 0 and self.instance.id:\n self.instance.delete()\n else:\n result = super(TariffPeriodFormSet, self).save(commit=False)\n super_save_m2m = self.save_m2m\n\n def save_m2m():\n self.save_intermediate_data_series()\n super_save_m2m()\n if len(surviving_forms) == 0 and self.instance.id:\n self.instance.delete()\n\n self.save_m2m = save_m2m\n\n return result\n\n\nclass TariffChainLinkInline(InlineFormSet):\n model = ChainLink\n form_class = TariffPeriodForm\n fk_name = 'chain'\n formset_class = TariffPeriodFormSet\n extra = 1\n\n def construct_formset(self):\n result = super(TariffChainLinkInline, self).construct_formset()\n result.measurement_point = self.view.object\n return result\n\n def formfield_callback(self, f, **kwargs):\n \"\"\"\n @precondition: C{self.view.utility_type} is set.\n \"\"\"\n if f.name == 'data_series':\n kwargs['queryset'] = DataSeries.objects.filter(\n utility_type=self.view.utility_type,\n role__in=DataRoleField.TARIFFS)\n kwargs['initial'] = trackuser.get_customer().\\\n get_preffered_tariff(self.view.utility_type)\n\n return f.formfield(**kwargs)\n\n\nclass TariffPeriodInlineMixin(object):\n def construct_inlines(self):\n inline_formsets = super(\n TariffPeriodInlineMixin, self).construct_inlines()\n\n # Note: This particular inline instance needs to be instantiated on top\n # of self.object.cost.tariff.subclass_instance rather than self.object.\n if self.object and self.object.cost:\n chain = self.object.cost.tariff.subclass_instance\n else:\n chain = None\n inline_instance = TariffChainLinkInline(\n Chain, self.request, chain, self.kwargs, self)\n inline_formset = inline_instance.construct_formset()\n inline_formsets.append(inline_formset)\n\n return inline_formsets\n\n\nclass ConsumptionMeasurementPointCreateView(\n MeasurementPointSlideInFormWithInlinesMixin,\n TariffPeriodInlineMixin,\n CreateWithInlinesView):\n form_class = InputConsumptionMeasurementPointForm\n model = ConsumptionMeasurementPoint\n template_name = \\\n \"manage_measurementpoints/measurementpoint_create_form.html\"\n status_text = _('The measurement point has been created')\n utility_type = None\n\n def get_form_kwargs(self):\n kwargs = super(\n ConsumptionMeasurementPointCreateView, self).get_form_kwargs()\n kwargs['utility_type'] = self.utility_type\n return kwargs\n\n\nclass ConsumptionMeasurementPointUpdateView(\n MeasurementPointSlideInFormWithInlinesMixin,\n TariffPeriodInlineMixin,\n UpdateWithInlinesView):\n form_class = ConsumptionMeasurementPointUpdateForm\n model = ConsumptionMeasurementPoint\n template_name = \\\n \"manage_measurementpoints/measurementpoint_update_form.html\"\n status_text = _('The measurement point has been updated')\n\n @property\n def utility_type(self):\n \"\"\"\n Needed by TariffChainLinkInline.formfield_callback\n \"\"\"\n return self.object.utility_type\n\n\nclass ConsumptionMultiplicationPointCreateView(\n ConsumptionMeasurementPointCreateView):\n form_class = MultiplicationConsumptionMeasurementPointForm\n model = ConsumptionMultiplicationPoint\n template_name = \\\n 'manage_measurementpoints/multiplication_measurement_point_form.html'\n\n\nclass ConsumptionMultiplicationPointUpdateView(\n ConsumptionMeasurementPointUpdateView):\n form_class = MultiplicationConsumptionMeasurementPointForm\n model = ConsumptionMultiplicationPoint\n template_name = \\\n 'manage_measurementpoints/multiplication_measurement_point_form.html'\n\n\nclass DistrictHeatingMeasurementPointCreateView(\n ConsumptionMeasurementPointCreateView):\n form_class = DistrictHeatingMeasurementPointCreateForm\n model = DistrictHeatingMeasurementPoint\n template_name = \\\n 'manage_measurementpoints/district_heating_measurement_point_form.html'\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.district_heating\n\n\nclass DistrictHeatingMeasurementPointUpdateView(\n ConsumptionMeasurementPointUpdateView):\n form_class = DistrictHeatingMeasurementPointEditForm\n model = DistrictHeatingMeasurementPoint\n template_name = \\\n 'manage_measurementpoints/district_heating_measurement_point_form.html'\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.district_heating\n\n\n@customer_admin_or_error\n@json_response\ndef temperaturepoint_create_form(request):\n \"\"\"\n Render form for creating TemperatureMeasurementPoint by:\n\n - display initial form if method is GET\n - display validated form if method is POST and form is invalid (JSON)\n - display success message and MP block if method is POST and form is\n valid (JSON)\n \"\"\"\n # display initial form if method is GET\n if request.method == 'GET':\n form = InputTemperatureMeasurementPointForm()\n # override json_response by manually returning a HttpResponse.\n return render(\n request, 'manage_measurementpoints/temperature_create_form.html',\n {'form': form})\n else:\n assert request.method == 'POST'\n form = InputTemperatureMeasurementPointForm(request.POST)\n if form.is_valid():\n # display success message and MP block if method is POST and form\n # is valid (JSON)\n measurementpoint = form.save()\n return {\n 'success': True,\n 'statusText': _('The measurement point has been saved'),\n 'html': render_to_string(\n 'manage_measurementpoints/block.html',\n {'graph_collection': measurementpoint, },\n RequestContext(request))}\n else:\n # display validated form if method is POST and form is invalid\n # (JSON)\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_measurementpoints/temperature_create_form.html',\n {'form': form},\n RequestContext(request))}\n\n\n@customer_admin_or_error\n@json_response\ndef temperature_measurement_point_update_form(request, instance):\n \"\"\"\n Render form for updating TemperatureMeasurementPoint by:\n\n - display initial form if method is GET\n - display validated form if method is POST and form is invalid (JSON)\n - display success message and MP block if method is POST and form is\n valid (JSON)\n \"\"\"\n\n # display initial form if method is GET\n if request.method == 'GET':\n form = TemperatureMeasurementPointForm(instance=instance)\n # override json_response by manually returning a HttpResponse.\n return render(\n request, 'manage_measurementpoints/temperature_update_form.html',\n {'form': form,\n 'delete_prevention_reason':\n instance.get_delete_prevention_reason()})\n else:\n assert request.method == 'POST'\n form = TemperatureMeasurementPointForm(request.POST, instance=instance)\n if form.is_valid():\n # display success message and MP block if method is POST and form\n # is valid (JSON)\n measurementpoint = form.save()\n return {\n 'success': True,\n 'statusText': _('The measurement point has been saved'),\n 'html': render_to_string(\n 'manage_measurementpoints/block.html', {\n 'graph_collection': measurementpoint, },\n RequestContext(request))}\n else:\n # display validated form if method is POST and form is invalid\n # (JSON)\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_measurementpoints/temperature_update_form.html',\n {'form': form,\n 'delete_prevention_reason':\n instance.get_delete_prevention_reason()},\n RequestContext(request))}\n\n\nclass ConsumptionMeasurementPointSummationCreateView(\n ConsumptionMeasurementPointCreateView):\n form_class = ConsumptionMeasurementPointSummationForm\n model = ConsumptionMeasurementPointSummation\n template_name = 'manage_measurementpoints/' \\\n 'consumption_measurement_point_summation_form.html'\n\n\nclass ConsumptionMeasurementPointSummationUpdateView(\n ConsumptionMeasurementPointUpdateView):\n form_class = ConsumptionMeasurementPointSummationForm\n model = ConsumptionMeasurementPointSummation\n template_name = 'manage_measurementpoints/' \\\n 'consumption_measurement_point_summation_form.html'\n" }, { "alpha_fraction": 0.5460420250892639, "alphanum_fraction": 0.5600430965423584, "avg_line_length": 29.442623138427734, "blob_id": "c1b223b44e54bc6a61ec9ec159e70f33536a44b8", "content_id": "14288fd0f83f47c17d6c55542eac0cd61b5d5fc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1857, "license_type": "no_license", "max_line_length": 73, "num_lines": 61, "path": "/gridagentserver-protocol/gridagentserver_protocol/encryption_test.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom binascii import a2b_hex\n\nfrom encryption import Encryption\nfrom StringIO import StringIO\n\n\n# RC4 test vectors from http://en.wikipedia.org/wiki/RC4#Test_vectors ...\nexamples = [\n {\n 'key': 'Key',\n 'plain': 'Plaintext',\n 'cipher': a2b_hex('BBF316E8D940AF0AD3'),\n },\n {\n 'key': 'Wiki',\n 'plain': 'pedia',\n 'cipher': a2b_hex('1021BF0420'),\n },\n {\n 'key': 'Secret',\n 'plain': 'Attack at dawn',\n 'cipher': a2b_hex('45A01F645FC35B383552544B9BF5'),\n }\n]\n\n\nclass TestEncryption(unittest.TestCase):\n def test_encrypt(self):\n for e in examples:\n encrypt = Encryption(e['key'], None)\n self.assertEqual(encrypt._crypt(e['plain']), e['cipher'])\n self.assertNotEqual(encrypt._crypt(e['plain']), e['cipher'])\n\n def test_decrypt(self):\n for e in examples:\n encrypt = Encryption(e['key'], None)\n self.assertEqual(encrypt._crypt(e['cipher']), e['plain'])\n self.assertNotEqual(encrypt._crypt(e['cipher']), e['plain'])\n\n def test_stream_decrypt(self):\n for e in examples:\n encrypt = Encryption(e['key'], StringIO(e['cipher']))\n self.assertEqual(encrypt.read(len(e['plain'])), e['plain'])\n\n def test_stream_encrypt(self):\n for e in examples:\n stream = StringIO()\n encrypt = Encryption(e['key'], stream)\n encrypt.write(e['plain'])\n self.assertEqual(stream.getvalue(), e['cipher'])\n\n def test_recursive(self):\n # encrypt, then decrypt with same key...\n for e in examples:\n stream = StringIO()\n estream = Encryption(e['key'], stream)\n encrypt = Encryption(e['key'], estream)\n encrypt.write(e['plain'])\n self.assertEqual(stream.getvalue(), e['plain'])\n" }, { "alpha_fraction": 0.7581018805503845, "alphanum_fraction": 0.7581018805503845, "avg_line_length": 28.288135528564453, "blob_id": "bea7937659cc5b6cdcc36d8dd496aab9d72911f4", "content_id": "e3c9650b575a06d7753ba29802f3a40939ab4b41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1728, "license_type": "no_license", "max_line_length": 85, "num_lines": 59, "path": "/documentation/source/apps/gridplatform/users.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Users\n=====\n\nThis app defines the :py:class:`~gridplatform.users.models.User` model which is\nused for user authentication and authorization.\n\n.. autoclass:: gridplatform.users.models.User\n :members: clean_fields, save, _decrypt, get_username, set_password,\n reset_password, is_admin, is_customer_superuser,\n get_encryption_id, satisfies_search\n\n\nEncryption Key Signal Handlers\n------------------------------\n\nA number of signal handlers take care of encryption key generation and sharing.\n\n.. autofunction:: gridplatform.users.models.create_user_key\n\n.. autofunction:: gridplatform.users.models.auto_grant_to_admins\n\n.. autofunction:: gridplatform.users.models.auto_grant_user_self_key\n\n.. autofunction:: gridplatform.users.models.auto_grant_user_key_to_superusers\n\n.. autofunction:: gridplatform.users.models.auto_grant_customer_superuser_user_keys\n\n.. autofunction:: gridplatform.users.models.auto_grant_provideruser_provider_key\n\n.. autofunction:: gridplatform.users.models.auto_grant_provideruser_customer_keys\n\n.. autofunction:: gridplatform.users.models.auto_grant_provideruser_provideruser_keys\n\n\nViews\n-----\n\n.. autoclass:: gridplatform.users.views.CustomerAdminOrAdminRequiredMixin\n :members: dispatch\n\n.. autoclass:: gridplatform.users.views.UserProfileForm\n :members: clean\n\n.. autoclass:: gridplatform.users.views.UserProfileView\n :members: get_form_kwargs, form_valid\n\n\nManagers\n--------\n\n.. autofunction:: gridplatform.users.managers.hash_username\n\n.. autoclass:: gridplatform.users.managers.UserManager\n :members: create_user\n\n.. autoclass:: gridplatform.users.managers.UserQuerySetMixin\n :members: _apply_filtering\n\n.. autoclass:: gridplatform.users.managers.BoundUserManager\n" }, { "alpha_fraction": 0.5935084819793701, "alphanum_fraction": 0.59531170129776, "avg_line_length": 36.6893196105957, "blob_id": "4f8fdb892380aaf9faf161778b906c31a7d6c455", "content_id": "8097793c3407474b6d72ca5122b0ae9d9e2e3236", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3882, "license_type": "no_license", "max_line_length": 79, "num_lines": 103, "path": "/legacy/measurementpoints/models/rateconversion.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\n\n\nclass RateConversion(DataSeries):\n \"\"\"\n A C{RateConversion} converts a consumption data series to a rate data\n series.\n\n @ivar consumption: The consumption data series that this C{RateConversion}\n is defined in terms of.\n \"\"\"\n consumption = models.ForeignKey(\n DataSeries, on_delete=models.CASCADE,\n related_name='rate_conversion_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('rate conversion')\n verbose_name_plural = _('rate conversions')\n app_label = 'measurementpoints'\n\n def get_recursive_condense_resolution(self, resolution):\n # Whatever is efficient for the consumption, ought to be efficient for\n # the derived rate.\n return self.consumption.subclass_instance.\\\n get_recursive_condense_resolution(resolution)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{RateConversion} implementation of\n L{DataSeries.get_raw_data_samples()}.\n \"\"\"\n if from_timestamp == to_timestamp:\n # Usually will not happen. But possible for a user to provoke this\n # by having one stage much smaller than another in benchmark\n # projects. Also note that the precondition inherited from\n # DataSeries.get_samples() is only that from_timestamp <=\n # to_timestamp, and we are not allowed to strengthen preconditions.\n return []\n\n # if from_timestamp == to_timestamp the remainder of this function may\n # raise ZeroDivisionError, because timespan is zero.\n assert from_timestamp < to_timestamp\n assert self.consumption.is_accumulation()\n\n result = []\n raw_consumption = self.consumption.subclass_instance.\\\n get_samples(from_timestamp, to_timestamp)\n\n for first_sample, next_sample in pairwise(raw_consumption):\n if not first_sample.extrapolated and not next_sample.extrapolated:\n timespan = PhysicalQuantity(\n Fraction(\n (\n next_sample.timestamp -\n first_sample.timestamp).\n total_seconds()),\n 'second')\n physical_quantity = (\n (\n next_sample.physical_quantity -\n first_sample.physical_quantity) /\n timespan)\n\n result.append(\n self.create_point_sample(\n next_sample.timestamp, physical_quantity,\n uncachable=(\n next_sample.uncachable or\n first_sample.uncachable)))\n\n # Check post-condition\n assert result[-1].from_timestamp >= from_timestamp\n assert result[-1].to_timestamp <= to_timestamp\n\n if result == []:\n # insufficient samples to convert to rate.\n return []\n\n assert result[0].timestamp != from_timestamp\n result.insert(0, self.create_point_sample(\n from_timestamp,\n result[0].physical_quantity,\n uncachable=True))\n\n # follows from post condition of consumption.get_samples\n assert len(result) >= 2, \\\n 'consumption.get_samples() violates its post condition ' \\\n '(consumption is an instance of %s)' % \\\n self.consumption.__class__.__name__\n\n return result\n" }, { "alpha_fraction": 0.5697616934776306, "alphanum_fraction": 0.5794438719749451, "avg_line_length": 34.02608871459961, "blob_id": "b5fdd4394ed41c6160e25311ea7db62d2b33e70d", "content_id": "38a653555e6e43b16522fa9f41ca9020db1e20cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4028, "license_type": "no_license", "max_line_length": 77, "num_lines": 115, "path": "/legacy/manage_users/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform import trackuser\nfrom gridplatform.users.models import User\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ManageUserTest(TestCase):\n \"\"\"\n Test that super user can view and edit users.\n \"\"\"\n fixtures = [\"super_user_and_customer.json\"]\n\n def setUp(self):\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n self.user = User.objects.get(id=self.client.session[\"_auth_user_id\"])\n self.customer = self.user.customer\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_users_list(self):\n \"\"\"\n Test that super user can view a list of users.\n \"\"\"\n response = self.client.get('/users/json/users/')\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_user_create_form_get(self):\n \"\"\"\n Test that super user can get create user view.\n \"\"\"\n response = self.client.get('/users/form/')\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertNotContains(response, 'data-reason')\n self.assertContains(response, 'name=\"user_type\"')\n self.assertContains(response, 'submit')\n\n def test_user_create_form_empty_fails(self):\n \"\"\"\n Test that admin can't create an empty customer.\n \"\"\"\n response = self.client.post('/users/update/')\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, 'errorlist', count=3)\n\n def test_user_create_form_success(self):\n \"\"\"\n Test that super user can create new user.\n \"\"\"\n response = self.client.post(\n '/users/update/',\n {\n 'name': 'New test user',\n 'e_mail': '[email protected]',\n 'phone': '12345678',\n 'mobile': '87654321'\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertNotContains(response, 'errorlist')\n self.assertContains(response, 'New test user')\n\n def test_user_update_form_get(self):\n user = self.get_test_user()\n response = self.client.get('/users/form/%s' % user.id)\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, user.name_plain)\n self.assertContains(response, 'name=\"user_type\"')\n self.assertContains(response, 'submit')\n\n def test_user_update_form_success(self):\n user = self.get_test_user()\n response = self.client.post(\n '/users/update/%s' % user.id,\n {\n 'name': 'New test user',\n 'e_mail': '[email protected]',\n 'phone': '12345678',\n 'mobile': '87654321'\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, 'New test user')\n new_user = User.objects.latest('id')\n self.assertEqual(new_user.customer_id, self.user.customer_id)\n\n def test_user_update_form_empty_fail(self):\n user = self.get_test_user()\n response = self.client.post(\n '/users/update/%s' % user.id,\n {\n 'name': '',\n 'e_mail': '',\n 'phone': '',\n 'mobile': '',\n 'user_type': '3'\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, 'errorlist', count=3)\n\n def test_user_cannot_edit_own_user_type(self):\n response = self.client.get('/users/form/%s' % self.user.id)\n self.assertContains(response, 'name=\"user_type\" type=\"hidden\"')\n\n def get_test_user(self):\n self.test_user_create_form_success()\n return User.objects.latest('id')\n" }, { "alpha_fraction": 0.721848726272583, "alphanum_fraction": 0.7226890921592712, "avg_line_length": 31.16216278076172, "blob_id": "9b8a348a40b83f51a44142359e58a6d25f7d7282", "content_id": "afd6968f94f18979a916f02a037c5f9326d7cd54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1190, "license_type": "no_license", "max_line_length": 69, "num_lines": 37, "path": "/gridplatform/datasequences/test_nonaccumulation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\n\nfrom .models import NonaccumulationDataSequence\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass NonaccumulationDataSequenceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n\n def test_clean_happy(self):\n nonaccumulation = NonaccumulationDataSequence.objects.create(\n customer=self.customer,\n unit='milliwatt')\n nonaccumulation.clean()\n\n def test_clean_prevents_updating_unit(self):\n nonaccumulation = NonaccumulationDataSequence.objects.create(\n customer=self.customer,\n unit='milliwatt')\n\n nonaccumulation.unit = 'millikelvin'\n\n with self.assertRaises(ValidationError) as ctx:\n nonaccumulation.clean()\n\n self.assertIn('unit', ctx.exception.message_dict)\n" }, { "alpha_fraction": 0.5450180172920227, "alphanum_fraction": 0.5498199462890625, "avg_line_length": 32.31999969482422, "blob_id": "fff08ebb0f255d2e7dd4388978aa50f4a2d77f73", "content_id": "f8714f68d75c700415ec32d71ea6f5664c79f7ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 833, "license_type": "no_license", "max_line_length": 135, "num_lines": 25, "path": "/legacy/website/templates/overlay_base.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% spaceless %}\n{% load static from staticfiles %}\n{% load i18n %}\n\n<div class=\"clearfix slide-in slide-in-overlay\">\n <form {% if form.is_multipart %} enctype=\"multipart/form-data\" {% endif %} method=\"POST\" action=\"{% block action %}{% endblock %}\">\n <div class=\"overlay-header clearfix\">\n <div class=\"left\"><h4>{% block title %}{% endblock %}</h4></div>\n <div class=\"right\">\n {% block buttons %}\n <input type=\"submit\" value=\"{% trans \"Save\" %}\" />\n {% endblock buttons %}\n </div>\n </div>\n <span class=\"left\">\n <a class=\"close\" href=\"#\">\n <img src=\"{% static 'images/arrow-right.png' %}\" alt=\"{% trans 'Close' %}\">\n </a>\n </span>\n {% block content %}{% endblock %}\n </form>\n {% block extra_content %}{% endblock extra_content %}\n</div>\n\n{% endspaceless %}\n" }, { "alpha_fraction": 0.6321960091590881, "alphanum_fraction": 0.634189248085022, "avg_line_length": 31.184906005859375, "blob_id": "b9b62001dfd673636025364c9f83fdf999aa626d", "content_id": "0079b16cb99b1a24382f1efec13b752f378a5482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8529, "license_type": "no_license", "max_line_length": 79, "num_lines": 265, "path": "/gridplatform/reports/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nimport base64\nimport datetime\n\nfrom celery import Task\nfrom celery.result import AsyncResult\nfrom django import forms\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.views.decorators.http import require_POST\nfrom django.views.decorators.http import require_GET\nfrom django.views.generic import FormView\nfrom celery.task.control import inspect\nimport pytz\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import JsonResponse\nfrom gridplatform.utils.views import JsonResponseBadRequest\n\nfrom .models import Report\n\n\ndef is_queue_too_long(max_tasks, task_name):\n \"\"\"\n Are too many tasks with a given name enqueued?\n\n Some tasks risk taking long to process. For good measure users\n tend to reenqueue tasks that take too long. Having the respective\n views introduce a maximum ensures that all successfully enqueued\n tasks are eventually processed, and there will eventually be room\n for enqueuing more tasks.\n\n :param max_tasks: The threshold of too many tasks.\n :param task_name: The name of the tasks to query.\n\n :return: ``True`` if the scheduled task queue holds more than\n ``max_tasks`` tasks with the name ``task_name``. Otherwise\n returns ``False``\n \"\"\"\n i = inspect()\n scheduled = i.scheduled()\n queue_length = 0\n for tasks in scheduled.values():\n for task in tasks:\n if task['name'] == task_name:\n queue_length += 1\n\n return queue_length > max_tasks\n\n\n@python_2_unicode_compatible\nclass CeleryError(Exception):\n \"\"\"\n Wrapper for exceptions from Celery --- Celery provides an Exception object\n and a string representation of a traceback.\n \"\"\"\n def __init__(self, wrapped, traceback):\n self.wrapped = wrapped\n self.traceback = traceback\n\n def __str__(self):\n return '{}\\n{}'.format(self.wrapped, self.traceback)\n\n\nReportInfo = namedtuple('ReportInfo', ['title', 'content_type', 'data'])\n\n\nclass StartReportView(FormView):\n \"\"\"\n Generic view to, when configured with a form class and a Celery task, start\n the Celery task with data from the form.\n\n :cvar task: A Celery task set by concrete start view.\n \"\"\"\n task = None\n\n def get_task(self):\n \"\"\"\n Return the Celery task to run.\n \"\"\"\n if self.task:\n return self.task\n else:\n raise ImproperlyConfigured('No task to run. Provide a task.')\n\n def get_task_data(self, form):\n \"\"\"\n Must be overwritten by subclass. This methods returns the data for\n the task itself, it must not contain any sensitive data! The\n data must be serializable.\n\n NOTE: Django querysets are not serializable.\n \"\"\"\n raise NotImplementedError('Subclass must implement this method')\n\n def start_task(self, data):\n \"\"\"\n Start the Celery task.\n\n :param data: Single argument delegated to ``delay()`` method\n of task.\n \"\"\"\n task = self.get_task()\n\n if not isinstance(task, Task):\n raise ImproperlyConfigured('Provided task is not a Celery Task.')\n\n return task.delay(data)\n\n def form_valid(self, form):\n \"\"\"\n Start Celery task with data from given form; called when the form\n is found valid.\n\n :param form: The given form\n \"\"\"\n data = self.get_task_data(form)\n async = self.start_task(data)\n return JsonResponse({\n 'task_id': async.id,\n 'status': async.status,\n })\n\n def form_invalid(self, form):\n \"\"\"\n Format form errors as JSON error response.\n \"\"\"\n return JsonResponseBadRequest(form.errors)\n\n\nclass TaskForm(forms.Form):\n \"\"\"\n Form for identifying a task.\n\n :ivar task_id: The id of the task identified.\n \"\"\"\n task_id = forms.CharField()\n\n\nclass FinalizeReportView(FormView):\n \"\"\"\n A :class:`~django.views.generic.FormView` for generating a report\n from the result of a :class:`celery.Task`.\n\n The report is likely to contain encrypted information wich is not\n available outside the request context, so the task could not have\n done the compilation itself.\n \"\"\"\n form_class = TaskForm\n\n def generate_report(self, data, timestamp):\n \"\"\"\n Generate a report and return as ReportInfo. Subclasses must implement\n this.\n \"\"\"\n raise NotImplementedError('Subclass must implement this method')\n\n def form_valid(self, form):\n \"\"\"\n Generate the report for the task output.\n \"\"\"\n task_id = form.cleaned_data['task_id']\n async = AsyncResult(task_id)\n if not async.successful():\n return JsonResponseBadRequest({'task_status': async.status})\n now = datetime.datetime.now(pytz.utc)\n generated = self.generate_report(async.result, now)\n if not isinstance(generated, ReportInfo):\n raise ImproperlyConfigured(\n 'Generated not an instance of ReportInfo.')\n data_formats = {content_type: n\n for n, content_type in Report.DATA_FORMAT_CHOICES}\n report = Report.objects.create(\n customer=get_customer(),\n title_plain=generated.title,\n generation_time=now,\n data_format=data_formats[generated.content_type],\n data_plain=base64.encodestring(generated.data),\n size=len(generated.data)\n )\n return JsonResponse({\n 'id': report.id,\n 'title': report.title_plain,\n 'size': report.size,\n 'url': reverse(\n 'reports-serve',\n kwargs={'id': report.id, 'title': report.title_plain})\n })\n\n def form_invalid(self, form):\n \"\"\"\n Format form errors as JSON error response.\n \"\"\"\n return JsonResponseBadRequest(form.errors)\n\n\n@auth_or_error\n@require_GET\ndef serve(request, id, title=None):\n \"\"\"\n View for serving an existing :class:`.Report` as a file for\n download.\n \"\"\"\n report = get_object_or_404(Report, id=id)\n content_type = dict(Report.DATA_FORMAT_CHOICES)[report.data_format]\n return HttpResponse(base64.decodestring(report.data_plain),\n content_type=content_type)\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef status(request):\n \"\"\"\n View for querying the status of a scheduled task.\n\n :param request: :class:`TaskForm` is used to extract the task id from\n ``request.POST``.\n\n :raise CeleryError: If any exception was raised by the task.\n Effectively this means that an error inside the task will be\n reported as an error during the given request.\n\n :return: A JSON response containing a dictionary with status\n information about the given task. If status is\n ``\"PROGRESS\"``, the JSON object will have the members\n ``task_id``, ``status``, ``result``. For other non failed\n statuses the ``result`` member is absent. The contents of\n ``result`` is task specific, but may be used to report\n progress. If the submitted :class:`TaskForm` did not\n validate, its ``errors`` member is returned as a JSON object.\n\n See also the :func:`gridplatform.utils.views.json_response` decorator.\n \"\"\"\n form = TaskForm(request.POST)\n if form.is_valid():\n task_id = form.cleaned_data['task_id']\n async = AsyncResult(task_id)\n if async.failed():\n # NOTE: The available \"traceback\" is a string, not a\n # traceback-object, hence \"re-raising\" with that as traceback\n # context will not work\n raise CeleryError(async.result, async.traceback)\n if async.status == \"PROGRESS\":\n return {\n 'task_id': async.id,\n 'status': async.status,\n 'result': async.result,\n }\n else:\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n else:\n return form.errors\n" }, { "alpha_fraction": 0.7527714967727661, "alphanum_fraction": 0.7533601522445679, "avg_line_length": 26.926027297973633, "blob_id": "5e43a76f9bdd9e10a090c6214166219eee7195de", "content_id": "d0a067cadef4832c777e21227633e16117d572de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 10193, "license_type": "no_license", "max_line_length": 100, "num_lines": 365, "path": "/documentation/source/apps/gridplatform/utils.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Utillities\n==========\n\nThe ``utils`` app contains various utility abstractions. The primary\npurpose is to contain the clutter.\n\nMiscelaneous Functions\n----------------------\n\n.. autofunction:: gridplatform.utils.unix_timestamp\n\n.. autofunction:: gridplatform.utils.first_last\n\n.. autofunction:: gridplatform.utils.fraction_to_decimal\n\n.. autofunction:: gridplatform.utils.choices_extract_python_identifier\n\n.. autofunction:: gridplatform.utils.development_sum\n\n.. autofunction:: gridplatform.utils.sum_or_none\n\nBreadcrumbs\n-----------\n\nBreadcrumbs are somewhat easier to work with given the following two\nclasses:\n\n.. autoclass:: gridplatform.utils.breadcrumbs.Breadcrumb\n\n.. autoclass:: gridplatform.utils.breadcrumbs.Breadcrumbs\n :members: __add__\n\n\nID Formatters\n-------------\n\n.. autofunction:: gridplatform.utils.format_id.format_mac\n.. autofunction:: gridplatform.utils.format_id.format_mbus_manufacturer\n.. autofunction:: gridplatform.utils.format_id.format_mbus_enhanced\n\n\nFTP client\n----------\n\n.. autofunction:: gridplatform.utils.ftpclient.ftpconnection\n\nIterator Extensions\n-------------------\n\n.. automodule:: gridplatform.utils.iter_ext\n :members: nwise, triplewise, pairwise, pairwise_extended, flatten,\n tee_lookahead, count_extended\n\nAPI\n---\n\nUtility functions for previous and next links in REST API for\nresources that are defined in terms of data sequences.\n\n.. autofunction:: gridplatform.utils.api.next_valid_date_for_datasequence\n.. autofunction:: gridplatform.utils.api.previous_valid_date_for_datasequence\n\n\nContext Managers\n----------------\n\n.. autofunction:: gridplatform.utils.contextmanagers.global_context\n\n\nCondense\n--------\n\n.. automodule:: gridplatform.utils.condense\n :members: next_resolution, is_finer_resolution,\n is_coarser_resolution, floor, ceil, get_date_formatter\n\nDecorators\n----------\n\n.. autofunction:: gridplatform.utils.decorators.deprecated\n.. autofunction:: gridplatform.utils.decorators.virtual\n.. autofunction:: gridplatform.utils.decorators.permission_required\n\n\nFields\n------\n\n.. autofunction:: gridplatform.utils.fields.parse_mac\n\n.. autoclass:: gridplatform.utils.fields.MacAddress\n.. autoclass:: gridplatform.utils.fields.MacAddressFormField\n.. autoclass:: gridplatform.utils.fields.MacAddressField\n :members: to_python, get_internal_type, formfield\n\n.. autoclass:: gridplatform.utils.fields.JSONEncoder\n :members: default\n\n.. autoclass:: gridplatform.utils.fields.JSONField\n :members: __init__, to_python, get_prep_value, value_to_string,\n value_from_object\n\n.. autoclass:: gridplatform.utils.fields.SplitHourMinuteWidget\n :members: decompress\n\n.. autoclass:: gridplatform.utils.fields.SplitHiddenHourMinuteWidget\n\n.. autoclass:: gridplatform.utils.fields.DurationFormField\n :members: compress\n\n.. autoclass:: gridplatform.utils.fields.DurationField\n :members: formfield\n\n.. autoclass:: gridplatform.utils.fields.PercentField\n :members: __init__\n\n.. autoclass:: gridplatform.utils.fields.ImageFieldWithLoadCheck\n :members: to_python\n\n.. autoclass:: gridplatform.utils.fields.ImageModelFieldWithLoadCheck\n :members: formfield\n\n.. autoclass:: gridplatform.utils.fields.BigAutoField\n\n.. autoclass:: gridplatform.utils.fields.BuckinghamField\n :members: validate, get_prep_value\n\n\nForms\n-----\n\n.. autoclass:: gridplatform.utils.forms.TimePeriodFormMixin\n :members: __init__, clean\n\n.. autoclass:: gridplatform.utils.forms.TimePeriodForm\n\n.. autoclass:: gridplatform.utils.forms.TimePeriodModelForm\n :members: __init__, clean\n\n.. autoclass:: gridplatform.utils.forms.HalfOpenTimePeriodModelForm\n :members: clean\n\n.. autofunction:: gridplatform.utils.forms.previous_month_initial_values\n\n.. autofunction:: gridplatform.utils.forms.this_week_initial_values\n\n.. autoclass:: gridplatform.utils.forms.YearWeekPeriodForm\n :members: __init__, clean, get_timestamps\n\n\nFormsets\n--------\n\n.. autoclass:: gridplatform.utils.formsets.SurvivingFormsModelFormSetMixin\n :members: surviving_forms\n\n\nGeneric Views\n-------------\n\n.. automodule:: gridplatform.utils.generic_views\n :members: ListView, DetailView, CreateView, DeleteView, UpdateView,\n InlineFormSet, ModelFormSetView, InlineFormSetView,\n CreateWithInlinesView, UpdateWithInlinesView, View,\n TemplateView, SearchableListMixin, FormView\n\nAccess Control\n^^^^^^^^^^^^^^\n\n.. autoclass:: gridplatform.utils.generic_views.access_control.CheckAJAXMixin\n\n.. autoclass:: gridplatform.utils.generic_views.access_control.LoginRequiredMixin\n\n.. autoclass:: gridplatform.utils.generic_views.access_control.ModelPermissionRequiredMixin\n\n.. autoclass:: gridplatform.utils.generic_views.access_control.MultipleModelPermissionsRequiredMixin\n\n.. autoclass:: gridplatform.utils.generic_views.access_control.CustomerBoundMixin\n\n\nLocalized\n^^^^^^^^^\n\n.. autoclass:: gridplatform.utils.generic_views.localized.LocalizedModelFormMixin\n :members: get_form_class\n\n.. autoclass:: gridplatform.utils.generic_views.localized.LocalizedModelFormSetMixin\n :members: get_factory_kwargs\n\n.. autoclass:: gridplatform.utils.generic_views.localized.LocalizedInlineFormSetMixin\n :members: get_factory_kwargs\n\nCommands\n--------\n\n.. automodule:: gridplatform.utils.management.commands.check_db_connection\n\n.. automodule:: gridplatform.utils.management.commands.fix_contenttypes_and_permissions\n\n\nManagers\n--------\n\n.. autoclass:: gridplatform.utils.managers.DateRangeManagerMixin\n :members: in_range\n\n.. autoclass:: gridplatform.utils.managers.TimestampRangeManagerMixin\n :members: in_range\n\n\nMiddleware\n----------\n\n.. autoclass:: gridplatform.utils.middleware.ExceptionRemoveInfoMiddleware\n.. autoclass:: gridplatform.utils.middleware.ExceptionAddInfoMiddleware\n.. autoclass:: gridplatform.utils.middleware.TimezoneMiddleware\n\nModels\n------\n\n.. autoclass:: gridplatform.utils.models.StoredSubclassManager\n :members: get_query_set, subclass_only, _model_subclasses\n\n.. autoclass:: gridplatform.utils.models.StoreSubclass\n :members: clean\n\n.. autoclass:: gridplatform.utils.models.DateRangeModelMixin\n :members: clean, timestamp_range_intersection\n\n.. autoclass:: gridplatform.utils.models.TimestampRangeModelMixin\n :members: clean, format_timestamp_range_unicode, overlapping\n\nPaginator\n---------\n\n.. automodule:: gridplatform.utils.paginator\n :members: parse_date, Http404ApiException, parse_date_or_404\n\nUnit Converters\n---------------\n\n.. automodule:: gridplatform.utils.preferredunits\n :members: UnitConverter, PhysicalUnitConverter, KvarUnitConverter,\n KvarhUnitConverter, PowerFactorUnitConverter,\n DisplayCelsiusMixin, RelativeCelsiusUnitConverter,\n AbsoluteCelsiusUnitConverter, DisplayFahrenheitMixin,\n RelativeFahrenheitUnitConverter,\n AbsoluteFahrenheitUnitConverter,\n AbstractENPIUnitConverter, PersonsENPIUnitConverter,\n AreaENPIUnitConverter,\n AbstractProductionENPIUnitConverter,\n ProductionAENPIUnitConverter,\n ProductionBENPIUnitConverter,\n ProductionCENPIUnitConverter,\n ProductionDENPIUnitConverter,\n ProductionEENPIUnitConverter, ProductionUnitConverter,\n EfficiencyUnitConverter\n\nRelative Time Delta\n-------------------\n\n.. automodule:: gridplatform.utils.relativetimedelta\n :members: wrap, RelativeTimeDelta\n\nSamples\n-------\n\n.. automodule:: gridplatform.utils.samples\n :members: Sample, wrap_ranged_sample, wrap_ranged_sample_sequence\n\nSerializers\n-----------\n\n.. autoclass:: gridplatform.utils.serializers.SampleBase\n :members: get_unit, get_display_unit, get_value\n\n.. autoclass:: gridplatform.utils.serializers.PointSampleSerializer\n.. autoclass:: gridplatform.utils.serializers.RangedSampleSerializer\n\nTemplate Tags\n-------------\n\n.. autofunction:: gridplatform.utils.templatetags.utils.insertnbsp\n.. autofunction:: gridplatform.utils.templatetags.utils.jsonify\n.. autofunction:: gridplatform.utils.templatetags.utils.buckingham_display\n\nUnit Conversion\n---------------\n\n.. automodule:: gridplatform.utils.unitconversion\n :members: PhysicalQuantity, simple_convert\n\nUnits\n-----\n\n.. automodule:: gridplatform.utils.units\n\nUtility Types\n-------------\n\n.. automodule:: gridplatform.utils.utilitytypes\n\n\nValidators\n----------\n\n.. autofunction:: gridplatform.utils.validators.nonzero_validator\n.. autofunction:: gridplatform.utils.validators.in_the_past_validator\n.. autofunction:: gridplatform.utils.validators.clean_overlapping\n\n\nViews\n-----\n\n.. autofunction:: gridplatform.utils.views.json_response\n.. autofunction:: gridplatform.utils.views.json_list_response\n\n.. autoclass:: gridplatform.utils.views.JsonResponse\n :members: data\n\n.. autoclass:: gridplatform.utils.views.JsonResponseBadRequest\n\n.. autoclass:: gridplatform.utils.views.DateLocalEpoch\n :members: default\n\n.. autofunction:: gridplatform.utils.views.date_epoch_json_response\n\n.. autofunction:: gridplatform.utils.views.render_to\n\n.. autofunction:: gridplatform.utils.views.json_list_options\n\n.. autoclass:: gridplatform.utils.views.FileView\n :members: get\n\n.. autoclass:: gridplatform.utils.views.NoCustomerMixin\n\n.. autoclass:: gridplatform.utils.views.CustomerContextMixin\n :members: get_context_data\n\n.. autoclass:: gridplatform.utils.views.CustomerInKwargsMixin\n\n.. autoclass:: gridplatform.utils.views.CustomersContextMixin\n :members: get_context_data\n\n.. autoclass:: gridplatform.utils.views.CustomerListMixin\n :members: _customer\n\n.. autofunction:: gridplatform.utils.views.task_status\n\n.. autoclass:: gridplatform.utils.views.StartTaskView\n :members: get_task_kwargs, get_task, get_status_url,\n get_finalize_url, start_task, form_valid, form_invalid\n\n.. autoclass:: gridplatform.utils.views.TaskForm\n\n.. autoclass:: gridplatform.utils.views.FinalizeTaskView\n :members: finalize_task, form_valid, form_invalid\n\n.. autoclass:: gridplatform.utils.views.HomeViewBase\n :members: get_redirect_url\n\n.. autoclass:: gridplatform.utils.views.ChooseCustomerBase\n :members: get_context_data\n\n.. autoclass:: gridplatform.utils.views.CustomerViewBase\n :members: get_redirect_url, get_redirect_with_customer_url\n" }, { "alpha_fraction": 0.7617260813713074, "alphanum_fraction": 0.7617260813713074, "avg_line_length": 34.53333282470703, "blob_id": "b9371199221f40a514839c047d47d9141eec43f2", "content_id": "a330b60d71d4aeffb7623d8de529e18b9eab9d7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 533, "license_type": "no_license", "max_line_length": 74, "num_lines": 15, "path": "/documentation/source/apps/gridplatform/customers.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Customers\n=========\n\nThe ``customers`` app defines the\n:py:class:`~gridplatform.customers.models.Customer` model, which in turn\nrepresent the entity that owns any particular instance of the domain.\n\n.. autoclass:: gridplatform.customers.models.Customer\n :members: clean_fields, save, now, get_encryption_id, satisfies_search,\n get_production_unit_choices\n\n.. autoclass:: gridplatform.customers.managers.CustomerManager\n\n.. autoclass:: gridplatform.customers.managers.CustomerQuerySetMixin\n :members: _apply_filtering\n" }, { "alpha_fraction": 0.6496964693069458, "alphanum_fraction": 0.6518504023551941, "avg_line_length": 33.50675582885742, "blob_id": "134f422caae97325ee7ca9b10fe0dfef7d55d7ba", "content_id": "f287b7376b769175256bc2348db630789a4f333d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5107, "license_type": "no_license", "max_line_length": 83, "num_lines": 148, "path": "/gridplatform/cost_compensations/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.utils.functional import cached_property\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.datasequences.models import piecewiseconstant\nfrom gridplatform.datasequences.models import PiecewiseConstantPeriodManager\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import ENERGY_TARIFF_CHOICES\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\n\n\nclass CostCompensation(piecewiseconstant.PiecewiseConstantBase):\n \"\"\"\n Cost compensation data sequence. Defines sequences of conversion ranged\n samples for calculating a cost compensation amount from an energy\n consumption.\n\n :ivar name: The name of the tariff\n :ivar customer: The customer owning the tariff.\n \"\"\"\n\n class Meta:\n verbose_name = _('cost compensation')\n verbose_name_plural = _('cost compensations')\n\n @cached_property\n def unit(self):\n result = self.customer.currency_unit + '*kilowatt^-1*hour^-1'\n assert any((\n PhysicalQuantity.compatible_units(\n result, 'currency_dkk*kilowatt^-1*hour^-1'),\n PhysicalQuantity.compatible_units(\n result, 'currency_eur*kilowatt^-1*hour^-1')))\n return result\n\n\nclass CostCompensationPeriodManager(PiecewiseConstantPeriodManager):\n \"\"\"\n Manager defining methods useful for reverse relations to cost compensation\n periods. E.g.::\n\n mainconsumption.cost_compensation.period_set.value_sequence()\n\n The concept is similar to\n :py:class:`gridplatform.tariffs.models.TariffPeriodManager`.\n \"\"\"\n\n def value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n A sequence of cost compensation samples of all periods in the given range.\n\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n :return: A sequence of ranged cost compensation samples in one hour\n resolutions.\n \"\"\"\n for sample in super(\n CostCompensationPeriodManager, self).value_sequence(\n from_timestamp, to_timestamp):\n assert RelativeTimeDelta(\n sample.to_timestamp, sample.from_timestamp) == \\\n RelativeTimeDelta(hours=1)\n yield sample\n\n\nclass Period(piecewiseconstant.PiecewiseConstantPeriodBase):\n \"\"\"\n Base class for cost compensation periods.\n\n :ivar datasequence: The aggregating :class:`.CostCompensation`.\n \"\"\"\n datasequence = models.ForeignKey(\n CostCompensation,\n verbose_name=_('data sequence'),\n editable=False)\n\n objects = CostCompensationPeriodManager()\n\n class Meta:\n verbose_name = _('cost compensation period')\n verbose_name_plural = _('cost compensation periods')\n\n @virtual\n def __unicode__(self):\n raise NotImplementedError(self.__class__)\n\n\nclass FixedCompensationPeriod(\n piecewiseconstant.FixedPiecewiseConstantPeriodValueSequenceMixin,\n Period):\n \"\"\"\n Specialization of cost compensation\n :class:`~gridplatform.cost_compensations.models.Period` for fixed cost\n compensation.\n\n :ivar value: The value of the fixed compensation.\n :ivar unit: The unit of the value fo the fixed compensation.\n \"\"\"\n\n value = models.DecimalField(_('value'), max_digits=12, decimal_places=3)\n unit = BuckinghamField(_('unit'), choices=ENERGY_TARIFF_CHOICES)\n resolution = condense.HOURS\n\n class Meta:\n verbose_name = _('fixed compensation period')\n verbose_name_plural = _('fixed compensation periods')\n\n def __unicode__(self):\n if self.to_timestamp is None:\n return '%s - ...: %s %s' % (\n self.from_timestamp,\n self.value,\n self.get_unit_display())\n else:\n return '%s - %s: %s %s' % (\n self.from_timestamp, self.to_timestamp,\n self.value,\n self.get_unit_display())\n\n def clean(self):\n \"\"\"\n :raise ValidationError: if ``self.unit`` is not compatible with the unit of\n aggregating :class:`.CostCompensation`.\n \"\"\"\n super(FixedCompensationPeriod, self).clean()\n if not PhysicalQuantity.compatible_units(\n self.unit, self.datasequence.unit):\n raise ValidationError(\n {\n 'unit': [\n ugettext(\n 'Selected unit is not compatible with '\n 'unit of cost compensation.')]\n }\n )\n\n @cached_property\n def _quantity(self):\n return PhysicalQuantity(self.value, self.unit)\n" }, { "alpha_fraction": 0.6206824779510498, "alphanum_fraction": 0.6208905577659607, "avg_line_length": 29.037500381469727, "blob_id": "89d6aa8aa1b7c1419105e328db7a95cc73034458", "content_id": "626000235c2b5db2486fb4639c9de57edbbbec60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4806, "license_type": "no_license", "max_line_length": 90, "num_lines": 160, "path": "/legacy/manage_devices/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.db.models.fields import BLANK_CHOICE_DASH\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext as _\n\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.utils import units\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.consumptions.models import PulsePeriod as ConsumptionPulsePeriod # noqa\nfrom gridplatform.productions.models import Production\nfrom gridplatform.productions.models import PulsePeriod as ProductionPulsePeriod # noqa\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\n\n\nclass AgentForm(forms.ModelForm):\n class Meta:\n model = Agent\n fields = ('location', 'no_longer_in_use')\n localized_fields = '__all__'\n\n\nclass MeterForm(forms.ModelForm):\n class Meta:\n model = Meter\n fields = ('name', 'location', 'relay_enabled')\n localized_fields = '__all__'\n\n def clean(self):\n # If relay is disabled, make sure that no one uses it.\n if not self.cleaned_data.get('relay_enabled'):\n mps = Collection.objects.filter(relay=self.instance)\n reason = \"\"\n for mp in mps:\n if reason == \"\":\n reason = mp.name_plain\n else:\n reason += \", \" + mp.name_plain\n if reason:\n raise ValidationError(\n _('Relay cannot be disabled because it is used by '\n + unicode(reason)))\n return self.cleaned_data\n\n\nRELAY_CHOICES = (\n ('on', _('On')),\n ('off', _('Off')),\n)\n\n\nclass RelayForm(forms.Form):\n relay_state = forms.ChoiceField(required=True, choices=RELAY_CHOICES)\n\n\nclass ElectricityConsumptionForm(forms.ModelForm):\n class Meta:\n model = Consumption\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(ElectricityConsumptionForm, self).__init__(\n *args, **kwargs)\n self.instance.unit = 'milliwatt*hour'\n\n\nclass WaterConsumptionForm(forms.ModelForm):\n class Meta:\n model = Consumption\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(WaterConsumptionForm, self).__init__(\n *args, **kwargs)\n self.instance.unit = 'milliliter'\n\n\nclass DistrictHeatingConsumptionForm(forms.ModelForm):\n class Meta:\n model = Consumption\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(DistrictHeatingConsumptionForm, self).__init__(\n *args, **kwargs)\n self.instance.unit = 'milliwatt*hour'\n\n\nclass GasConsumptionForm(forms.ModelForm):\n class Meta:\n model = Consumption\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(GasConsumptionForm, self).__init__(\n *args, **kwargs)\n self.instance.unit = 'milliliter'\n\n\nclass OilConsumptionForm(forms.ModelForm):\n class Meta:\n model = Consumption\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(OilConsumptionForm, self).__init__(\n *args, **kwargs)\n self.instance.unit = 'milliliter'\n\n\nclass ProductionForm(forms.ModelForm):\n class Meta:\n model = Production\n fields = ('name', )\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n unit = kwargs.pop('unit', None)\n super(ProductionForm, self).__init__(\n *args, **kwargs)\n if unit:\n self.instance.unit = unit\n\n\nclass InputPeriodFormBase(forms.ModelForm):\n class Meta:\n model = ConsumptionPulsePeriod\n fields = ('from_timestamp', 'to_timestamp', 'pulse_quantity',\n 'output_quantity', 'output_unit')\n localized_fields = '__all__'\n\n def clean(self):\n self.instance._clean_overlapping_periods = False\n return super(InputPeriodFormBase, self).clean()\n\n\nclass EnergyInputPeriodForm(InputPeriodFormBase):\n output_unit = forms.ChoiceField(\n choices=BLANK_CHOICE_DASH + list(units.ENERGY_CHOICES))\n\n\nclass VolumeInputPeriodForm(InputPeriodFormBase):\n output_unit = forms.ChoiceField(\n choices=BLANK_CHOICE_DASH + list(units.VOLUME_CHOICES))\n\n\nclass ProductionInputPeriodForm(InputPeriodFormBase):\n class Meta(InputPeriodFormBase.Meta):\n model = ProductionPulsePeriod\n fields = ('from_timestamp', 'to_timestamp', 'pulse_quantity',\n 'output_quantity')\n" }, { "alpha_fraction": 0.6214856505393982, "alphanum_fraction": 0.6260234713554382, "avg_line_length": 39.54800033569336, "blob_id": "e8efd8bca3a81227974d3b62d1814c03406caa94", "content_id": "69de181d5cb79c24d8a557a10acb59f7909b3b8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20274, "license_type": "no_license", "max_line_length": 102, "num_lines": 500, "path": "/legacy/measurementpoints/models/collections.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nimport pytz\nfrom django.db import models\nfrom mptt.models import MPTTModel\nfrom mptt.models import TreeForeignKey\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFit\nfrom imagekit.models import ImageSpecField\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.trackuser.managers import TreeCustomerBoundManager\nfrom gridplatform.trackuser.managers import StoredSubclassTreeCustomerBoundManager # noqa\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.units import INPUT_CHOICES\nfrom gridplatform.encryption.fields import EncryptedTextField\n\n\nclass CollectionManager(StoredSubclassTreeCustomerBoundManager):\n \"\"\"\n Manager for L{Collection}s\n \"\"\"\n\n def get_query_set(self):\n customer = get_customer()\n user = get_user()\n\n qs = super(CollectionManager, self).get_query_set()\n\n if customer is None or user is None:\n return qs\n\n constrained_collection_ids = list(\n CollectionConstraint.objects.filter(\n userprofile__user=user).\n values_list('collection_id', flat=True))\n\n if constrained_collection_ids:\n collection_ids = set()\n root_collections = qs.filter(id__in=constrained_collection_ids)\n for root_collection in root_collections:\n if root_collection.is_leaf_node():\n collection_ids.add(root_collection.id)\n continue\n opts = root_collection._mptt_meta\n left = getattr(root_collection, opts.left_attr)\n right = getattr(root_collection, opts.right_attr)\n if not hasattr(self, '_base_manager'):\n self.init_from_model(self.model)\n collection_ids.update(\n self._mptt_filter(\n qs,\n tree_id=root_collection._mpttfield('tree_id'),\n left__gte=left,\n left__lte=right).\n values_list('id', flat=True))\n return qs.filter(id__in=collection_ids)\n else:\n return qs\n\n\nclass Collection(MPTTModel, EncryptedModel, StoreSubclass):\n \"\"\"\n The way for customers to organise measurement points. Prices may be\n attached to collections, and then apply to all monitored equipment in that\n collection. Users may be bound to a set of collections, and will then only\n be able to see monitored equipment in those collections.\n\n @ivar role: The role that this C{Collection} is used in.\n\n C{GROUP}: This C{Collection} is strictly used to group other collections.\n This is the default.\n\n C{CONSUMPTION_GROUP}: This C{Collection} defines a consumption group for a\n module. The role of all descendants will either be in C{DATA_POINTS} or\n equal C{GROUP}.\n\n C{MEASUREMENT_POINT} (in C{DATA_POINTS}: A leaf C{Collection} (whith no\n children) holding one or more L{Graph}s.\n \"\"\"\n customer = models.ForeignKey(Customer, on_delete=models.PROTECT,\n blank=True, default=get_customer)\n parent = TreeForeignKey('self', related_name='children',\n blank=True, null=True)\n name = EncryptedCharField(_('Name'), max_length=50)\n # The next two fields are used for billing meters in Denmark. They are\n # shown as part of the consumption/cost report.\n billing_meter_number = models.CharField(_('meter number'),\n max_length=20, blank=True)\n billing_installation_number = models.CharField(\n _('installation number'), max_length=20, blank=True)\n\n # Design-note: Keep unrelated roles in their own 100s, so that there is\n # room to add new roles in-between. The hope is that the number of roles\n # will be stabilized before this schema is preempted.\n GROUP = 0\n\n CONSUMPTION_GROUP = 150\n\n MEASUREMENT_POINT_TEMPERATURE = 204\n MEASUREMENT_POINT_PRODUCTION = 205\n MEASUREMENT_POINT_CURRENT = 206\n MEASUREMENT_POINT_VOLTAGE = 207\n MEASUREMENT_POINT_POWER = 208\n MEASUREMENT_POINT_EFFICIENCY = 209\n MEASUREMENT_POINT_REACTIVE_POWER = 210\n MEASUREMENT_POINT_REACTIVE_ENERGY = 211\n MEASUREMENT_POINT_POWER_FACTOR = 212\n CONSUMPTION_MEASUREMENT_POINT = 250\n\n CONSUMPTION_GROUPS = (CONSUMPTION_GROUP,)\n MEASUREMENT_POINTS = (\n MEASUREMENT_POINT_TEMPERATURE,\n MEASUREMENT_POINT_PRODUCTION,\n CONSUMPTION_MEASUREMENT_POINT,\n MEASUREMENT_POINT_CURRENT,\n MEASUREMENT_POINT_VOLTAGE,\n MEASUREMENT_POINT_POWER,\n MEASUREMENT_POINT_REACTIVE_POWER,\n MEASUREMENT_POINT_REACTIVE_ENERGY,\n MEASUREMENT_POINT_POWER_FACTOR,\n MEASUREMENT_POINT_EFFICIENCY,\n )\n DATA_POINTS = MEASUREMENT_POINTS\n PARENTS = (GROUP,)\n\n ROLE_CHOICES = (\n (GROUP, _('Group')),\n (CONSUMPTION_GROUP, _('Consumption group')),\n (MEASUREMENT_POINT_TEMPERATURE, _('Temperature measurement point')),\n (MEASUREMENT_POINT_PRODUCTION, _('Production measurement point')),\n (MEASUREMENT_POINT_VOLTAGE, _('Voltage measurement point')),\n (MEASUREMENT_POINT_CURRENT, _('Current measurement point')),\n (MEASUREMENT_POINT_POWER, _('Power measurement point')),\n (MEASUREMENT_POINT_REACTIVE_POWER,\n _('Reactive power measurement point')),\n (MEASUREMENT_POINT_REACTIVE_ENERGY,\n _('Reactive energy measurement point')),\n (MEASUREMENT_POINT_POWER_FACTOR, _('Power factor measurement point')),\n (MEASUREMENT_POINT_EFFICIENCY, _('Efficiency measurement point')),\n (CONSUMPTION_MEASUREMENT_POINT, _('Consumption measurement point')),\n )\n\n # NOTE: Superseded by ContentType. Only used in\n # display_measurementpoints/views.py\n # manage_reports/templates/manage_reports/generate_report.html\n # manage_measurementpoints/forms/consumptionsummation.py\n # customers/models.py and then ofcourse in each and every one of\n # customers/proxies/*.py\n #\n # The question is: is there a ContentType for each role? Are there any\n # stale ContentTypes?\n #\n # A1: There are ContentTypes without a role, in particular for\n # SummationMeasurementPoint and DistrictHeatingMeasurementPoint.\n #\n # A2: There are also roles without a ContentType, in particular GROUP does\n # not have a ContentType. It probably should have though. But that\n # requires data migrations (setting the content type on all collection with\n # role GROUP), so it will wait for now.\n role = models.IntegerField(_(\"Role\"), choices=ROLE_CHOICES)\n utility_type = models.IntegerField(\n _('utility type'), choices=utilitytypes.OPTIONAL_METER_CHOICES)\n\n gauge_lower_threshold = models.DecimalField(\n max_digits=10, decimal_places=2, null=True, blank=True)\n gauge_upper_threshold = models.DecimalField(\n max_digits=10, decimal_places=2, null=True, blank=True)\n gauge_min = models.DecimalField(\n max_digits=10, decimal_places=2, null=True, blank=True, default=0)\n gauge_max = models.DecimalField(\n max_digits=10, decimal_places=2, null=True, blank=True)\n gauge_preferred_unit = models.CharField(\n max_length=50, null=True, blank=True, choices=INPUT_CHOICES)\n\n GREEN_YELLOW_RED = 1\n RED_GREEN_RED = 2\n YELLOW_GREEN_YELLOW = 3\n RED_YELLOW_GREEN = 4\n\n GAUGE_COLOR_CHOICES = (\n (GREEN_YELLOW_RED, _('green-yellow-red')),\n (RED_GREEN_RED, _('red-green-red')),\n (YELLOW_GREEN_YELLOW, _('yellow-green-yellow')),\n (RED_YELLOW_GREEN, _('red-yellow-green')),\n )\n gauge_colours = models.PositiveIntegerField(\n _('Gauge colours'), choices=GAUGE_COLOR_CHOICES, blank=True, null=True)\n\n relay = models.ForeignKey(\"devices.Meter\", on_delete=models.PROTECT,\n null=True, blank=True)\n\n hidden_on_details_page = models.BooleanField(default=False)\n\n hidden_on_reports_page = models.BooleanField(default=False)\n\n comment = EncryptedTextField(blank=True)\n\n image = ProcessedImageField(\n upload_to='measuremenpoints',\n processors=[ResizeToFit(900, 900, upscale=False)],\n format='JPEG',\n blank=True,\n null=True)\n\n thumbnail = ImageSpecField(\n source='image',\n processors=[ResizeToFit(100, 50)],\n format='JPEG',\n options={'quality': 90}\n )\n\n # Removes warning issued by django_mptt-0.5.4\n #\n # DeprecationWarning: Implicit manager Collection.tree will be removed in\n # django-mptt 0.6. Explicitly define a TreeManager() on your model to\n # remove this warning.\n #\n # See also:\n # http://django-mptt.github.com/django-mptt/upgrade.html\\\n # #treemanager-is-now-the-default-manager-yourmodel-tree-removed\n objects = tree = CollectionManager()\n\n class Meta:\n # default ordering for MPTTModel instances is tree order\n verbose_name = _('collection')\n verbose_name_plural = _('collections')\n db_table = 'customers_collection'\n app_label = 'customers'\n\n def __unicode__(self):\n return unicode(self.name_plain)\n\n def clean(self):\n super(Collection, self).clean()\n if not self.gauge_preferred_unit and getattr(self, 'rate', None):\n preferred_unit_converter = self.rate.get_preferred_unit_converter()\n if hasattr(preferred_unit_converter, 'physical_unit'):\n self.gauge_preferred_unit = \\\n self.rate.get_preferred_unit_converter().physical_unit\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n\n def satisfies_search(self, search):\n elems = [\n self.name_plain,\n ]\n if self.parent:\n elems.append([self.parent.name_plain])\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n def get_floorplan(self):\n \"\"\"\n Returns the collection floorplan if it exists, else returns None\n \"\"\"\n if hasattr(self, 'floorplan'):\n return self.floorplan\n else:\n return None\n\n def is_online(self):\n \"\"\"\n Check if this MeasurementPoint is online.\n\n This is done by checking if any measurements are available from the\n last half hour. Collections that are not MeasurementPoints are\n considered online always (for some reason).\n\n ... actually; a Collection will only be considered \"offline\" if it is a\n measurement point, has at least one logical input attached, and none of\n its logical inputs have stored data inside the last 30 minutes; any\n other combination is \"online\"...\n\n @deprecated: Similar concept is implemented better and more clean in\n L{Meter.connection_state}\n \"\"\"\n if not hasattr(self, '_is_online'):\n self._is_online = False\n if self.role not in self.MEASUREMENT_POINTS or \\\n self.get_last_rate() is not None:\n # being online is True by a a post-condition of get_last_rate()\n # given it didn't return None.\n self._is_online = True\n else:\n from legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter # noqa\n from legacy.datasequence_adapters.models import NonaccumulationAdapter # noqa\n\n input_configurations = list(\n ConsumptionAccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self)) + list(\n NonaccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self))\n if not input_configurations:\n self._is_online = True\n else:\n now = datetime.datetime.now(pytz.utc)\n half_hour_ago = now - datetime.timedelta(minutes=30)\n for ic in input_configurations:\n data = ic.get_samples(half_hour_ago, now)\n if any([not sample.extrapolated for sample in data]):\n self._is_online = True\n break\n\n return self._is_online\n\n def get_last_rate(self):\n \"\"\"\n Get the last rate for this C{MeasurementPoint}.\n\n @return: Return a C{(v, u)} tuple where v is a numeric value and u is a\n localized unit. If there is no last rate, None is returned (for\n instance because there is no gauge data series defined for this\n C{MeasurementPoint}, or this C{Collection} is not a C{MeasurementPoint}\n at all).\n\n @note: The return format C{(v, u)} is intended to be compatible with\n the physicalquantity template filter.\n \"\"\"\n if not hasattr(self, '_last_rate'):\n self._last_rate = None\n if self.role in self.MEASUREMENT_POINTS:\n mp = self.subclass_instance\n to_timestamp = datetime.datetime.now(pytz.utc).replace(\n microsecond=0)\n from_timestamp = to_timestamp - datetime.timedelta(minutes=30)\n gauge_data_series = mp.get_gauge_data_series()\n if gauge_data_series:\n sample = gauge_data_series.latest_sample(\n from_timestamp, to_timestamp)\n if sample:\n preferred_unit_converter = \\\n gauge_data_series.get_preferred_unit_converter()\n self._last_rate = (\n preferred_unit_converter.extract_value(\n sample.physical_quantity),\n preferred_unit_converter.get_display_unit())\n return self._last_rate\n\n def get_icon(self):\n if self.role in (self.CONSUMPTION_GROUP,\n self.CONSUMPTION_MEASUREMENT_POINT):\n if self.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return 'electricity'\n elif self.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.water:\n return 'water'\n elif self.utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return 'gas'\n elif self.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n return 'heat'\n elif self.utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return 'oil'\n else:\n return 'consumption'\n elif self.role == self.MEASUREMENT_POINT_TEMPERATURE:\n return 'temperature'\n elif self.role == self.GROUP:\n return 'group'\n elif self.role == self.MEASUREMENT_POINT_CURRENT:\n return 'electricity'\n elif self.role == self.MEASUREMENT_POINT_VOLTAGE:\n return 'electricity'\n elif self.role == self.MEASUREMENT_POINT_POWER:\n return 'electricity'\n elif self.role == self.MEASUREMENT_POINT_REACTIVE_POWER:\n return 'electricity'\n elif self.role == self.MEASUREMENT_POINT_REACTIVE_ENERGY:\n return 'electricity'\n elif self.role == self.MEASUREMENT_POINT_POWER_FACTOR:\n return 'electricity'\n elif self.role == self. MEASUREMENT_POINT_PRODUCTION:\n return 'production'\n elif self.role == self. MEASUREMENT_POINT_EFFICIENCY:\n return 'efficiency'\n else:\n assert False\n\n def is_measurementpoint(self):\n return self.role in self.MEASUREMENT_POINTS\n\n def get_role_display_short(self):\n return {\n Collection.GROUP: _(\"Group\"),\n\n Collection.CONSUMPTION_GROUP: _('Consumption group'),\n Collection.CONSUMPTION_MEASUREMENT_POINT:\n _('Consumption measurement point'),\n Collection.MEASUREMENT_POINT_TEMPERATURE:\n _('Temperature measurement point'),\n Collection.MEASUREMENT_POINT_CURRENT: _(\"Current\"),\n Collection.MEASUREMENT_POINT_VOLTAGE: _(\"Voltage\"),\n Collection.MEASUREMENT_POINT_POWER: _(\"Power\"),\n Collection.MEASUREMENT_POINT_REACTIVE_POWER: _(\"Reactive power\"),\n Collection.MEASUREMENT_POINT_REACTIVE_POWER: _(\"Reactive energy\"),\n Collection.MEASUREMENT_POINT_POWER_FACTOR: _(\"Power factor\"),\n }[self.role]\n\n def get_delete_prevention_reason(self):\n \"\"\"\n Returns a HTML formated string with a description of why\n this collection cannot be deleted.\n Returning None, if no reason exist, meaning the collection can\n be deleted without breaking anything.\n \"\"\"\n if self.is_deletable():\n return None\n\n measurementpoints = self.children.filter(\n graph__isnull=False).distinct()\n groups = self.children.filter(graph__isnull=True).distinct()\n dependents = []\n if measurementpoints:\n dependents.append(unicode(_(\"Measurement Points:\")))\n dependents.append('<ul>')\n for mp in measurementpoints:\n dependents.append('<li>%s</li>' % (escape(unicode(mp)),))\n dependents.append('</ul>')\n if groups:\n dependents.append(unicode(_(\"Collections:\")))\n dependents.append('<ul>')\n for group in groups:\n dependents.append('<li>%s</li>' % (escape(unicode(group)),))\n dependents.append('</ul>')\n if dependents:\n return _(\"This group cannot be deleted because the following \\\n depends on it:\") + \"<br />\" + \"\".join(dependents)\n\n def is_deletable(self):\n \"\"\"\n Returns true or false whether\n this collection can be deleted or not.\n \"\"\"\n if self.children.all():\n return False\n return True\n\n\n# NOTE: Bound to auto-create on user-create in portal.website.models.\n# This app may be used without the auto-create from outside the portal.\n\nclass CollectionConstraint(models.Model):\n \"\"\"\n A {CollectionConstraint} is the relation between L{UserProfile}s and\n L{Collection}s. This relation \"table\" has been created to prevent a\n Collection to be deleted if a User and the Collection has a relation.\n \"\"\"\n userprofile = models.ForeignKey(\n 'customers.UserProfile', on_delete=models.CASCADE)\n collection = models.ForeignKey(Collection, on_delete=models.PROTECT)\n\n class Meta:\n db_table = 'customers_userprofile_collections'\n app_label = 'customers'\n\n\nclass Location(MPTTModel, EncryptedModel):\n \"\"\"\n The way for customers to organise agents and meters, i.e. physical\n equipment. Locations are organised as one or more tree structures per\n customer.\n \"\"\"\n customer = models.ForeignKey(\n Customer, on_delete=models.CASCADE,\n blank=True, default=get_customer)\n parent = TreeForeignKey('self', on_delete=models.PROTECT,\n related_name='children', blank=True, null=True)\n name = EncryptedCharField(_('name'), max_length=50)\n\n objects = TreeCustomerBoundManager()\n\n class Meta:\n # default ordering for MPTTModel instances is tree order\n verbose_name = _('location')\n verbose_name_plural = _('locations')\n db_table = 'customers_location'\n app_label = 'customers'\n\n def __unicode__(self):\n return unicode(self.name_plain)\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n\n def satisfies_search(self, search):\n return search.lower() in unicode(self).lower()\n" }, { "alpha_fraction": 0.608208954334259, "alphanum_fraction": 0.608208954334259, "avg_line_length": 24.5238094329834, "blob_id": "e3706d45793a7f6490cb17150f9e4ea1b3a0b73b", "content_id": "b201812fdcbd788c5ec069033e4c38435805b414", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 61, "num_lines": 21, "path": "/gridplatform/settings/production_nordic.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nfrom .production import * # noqa\n\n\n# ######### CELERY CONFIGURATION\nCELERY_ROUTES = {\n 'legacy.energy_use_reports.tasks.EnergyUseReportTask': {\n 'queue': 'reports',\n },\n 'legacy.manage_reports.tasks.collect_consumption_data': {\n 'queue': 'reports',\n },\n 'legacy.display_projects.tasks.ProjectReportTask': {\n 'queue': 'reports',\n },\n 'legacy.enpi_reports.tasks.ENPIReportTask': {\n 'queue': 'reports',\n },\n}\n# ######### END CELERY CONFIGURATION\n" }, { "alpha_fraction": 0.6562998294830322, "alphanum_fraction": 0.6566985845565796, "avg_line_length": 32.89189147949219, "blob_id": "c60cb353991bbbe1029c3492aadd70c8afe33dfb", "content_id": "0bb44626033df6adbf8c1798f31ad9a95e7f6689", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2508, "license_type": "no_license", "max_line_length": 77, "num_lines": 74, "path": "/gridplatform/tariffs/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils import units\n\nfrom . import models\n\n\nclass TariffSerializerBase(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set', many=True, read_only=True)\n hourly = serializers.SerializerMethodField('get_hourly')\n fixed_price_periods = serializers.HyperlinkedIdentityField(\n view_name='api:tariffs:fixedpriceperiod-list')\n spot_price_periods = serializers.HyperlinkedIdentityField(\n view_name='api:tariffs:spotpriceperiod-list')\n unit = serializers.SerializerMethodField('get_unit')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n fields = (\n 'url', 'id', 'name', 'customer', 'unit', 'display_unit',\n 'periods', 'fixed_price_periods', 'spot_price_periods', 'hourly')\n\n def get_unit(self, obj):\n return obj.unit\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n\nclass EnergyTariff(TariffSerializerBase):\n class Meta(TariffSerializerBase.Meta):\n model = models.EnergyTariff\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:tariffs:energytariff-hourly', kwargs={'pk': obj.id})\n\n\nclass VolumeTariff(TariffSerializerBase):\n class Meta(TariffSerializerBase.Meta):\n model = models.VolumeTariff\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:tariffs:volumetariff-hourly', kwargs={'pk': obj.id})\n\n\nclass FixedPricePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.FixedPricePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'subscription_fee', 'subscription_period', 'value', 'unit')\n read_only_fields = ('datasequence',)\n\n\nclass SpotPricePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.SpotPricePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'subscription_fee', 'subscription_period',\n 'spotprice', 'coefficient',\n 'unit_for_constant_and_ceiling', 'constant', 'ceiling')\n read_only_fields = ('datasequence',)\n" }, { "alpha_fraction": 0.7846448421478271, "alphanum_fraction": 0.7860376238822937, "avg_line_length": 48.094017028808594, "blob_id": "cf5e483480df446995ac71a51a5734c268b3f6bd", "content_id": "532454c5ec948b7a9dbaede81c6eda1b1ceb00f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5758, "license_type": "no_license", "max_line_length": 79, "num_lines": 117, "path": "/documentation/source/consumptions.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Consumptions\n============\n\nThis chapter covers utility consumptions that represent energy consumption in\nsome form. The utility consumptions that companies are billed for directly are\nthe main consumptions. Each main consumption can be partitioned into energy\nuses.\n\n.. _main-consumptions:\n\nMain Consumptions\n-----------------\n\nMain consumptions are individually billed sources of utilities going into a\ncompany. Examples of main consumptions are:\n\n * The power consumption measured by a main electrical meter with billing\n number.\n * The heat consumption measured by a main district heating meter with\n billing number.\n * The amount of gas measured by a main gas meter with billing number.\n * The amount of oil delivered to a oil storage tank with a billing number..\n\nThe important properties of main consumptions are that they are individually\nbilled, and they deal with utilties that deliver energy in some form.\n\nThe utility type of each main consumption is unambiguous. As such knowing the\nenergy consumption represented by each main consumption gives the distribution\nof energy on different utility types.\n\nFor a given quantity of a given utility type at a given time, the CO₂ emissions\nmay be determined.\n\nEnergy Uses\n-----------\n\nEnergy uses are main consumptions partitioned into smaller energy consumptions\neach with a particular use. Examples of energy uses are:\n\n * The lighting in an office building.\n * The power used by a conveyor belt.\n * The energy used for the casting of metals.\n * The power used by a compressor.\n * The energy consumption of a freezer.\n\nInterresting properties that can be derived from energy uses include variable\ncosts and CO₂ emissions.\n\n.. _adjustments-etc:\n\nAdjustment Factors, Energy Performances and Normalized Consumptions\n-------------------------------------------------------------------\n\nThe consumptions of different periods of the same energy use are comparable if\nthese consumptions are adjusted by the right adjustment factors. Adjustment\nfactors are determined by what we find acceptable to increase the energy\nconsumption, say for instance:\n\n * The duration of the period may be normalized to a standard period duration.\n Say one period is one week and another is 9 days we can multiply them both\n with an adjustment factor to make them both correspond to a full month.\n * The heating degree days in the period may be normalizided to standard\n heating degree days. Say the energy used to maintain a comfortable indoor\n temperature in a cold period is larger than the energy used to maintain the\n same temperature in a warmer period.\n * The production of one period may be larger than that of another, so to\n compare the energy consumption accross such two periods for the same energy\n use, they must be adjusted wich each their production counts.\n\nMany more adjustment factors exist. The above examples are adjusted energy\nconsumptions with following normalization, and their unit ends up being energy\n(kWh) also when combined. We call these normalized energy consumptions.\nBecause the unit before and after normalization are the same, multiple\nadjustment factors can be used in calculating a normalized energy consumption.\n\nWhen adjustment factors are applied without being followed by normalization, we\nhave an energy performance. Comparing energy performances is equally fair, but\ndifferenses in energy performances can be less trivial to value. To reiterate\nthe above adjustment factors:\n\n * Adjusting for time gives a mean power W.\n * Adjusting for heating degree days gives a mean heat loss coefficient W/°K.\n * Adjusting for production gives mean production consumption kWh/pcs.\n\nIn isolation these units make sense. When combined we risk getting meaningless\nunits. For instances both heating degree days and production are not\ncompatible with duration adjustment; i.e. W/s°K and W/pcs are meaningless\nunits. In these cases a normalized energy consumption is preferred. For an\nalready normalized consumption an energy performance may be defined by applying\nan additional adjustmentfactor (or leaving out the normalization of an existing\nadjustment factor).\n\nSimilar to adjustment factors, other (additional) factors may be used to define\nenergy performances, including utility costs and CO₂ emissions. For example\nthe marginal utility cost for production (EUR/pcs) is an energy performance,\nand so is the marginal CO₂ emissions for production (tonne/pcs), even burn-rate\n(EUR/year) and CO₂ emission rate (tonne/year). These factors may also be used\non normalized energy consumptions to get normalized yearly costs (EUR), or\nnormalized yearly CO₂ emissions (tonne).\n\nSome adjustment factors (or other factors) represent great value to companies,\nfor example the production. Energy performances based on these may be promoted\nto energy performance indicators.\n\nThe adjustment factors applied need not necessarily be part of the physics\nobserved. As mentioned before it is enough if one finds the adjustment factor\nrelevant. For instance, it may be relevant how much energy is used for\nlighting a factory per unit produced, though the production does not influence\nthe energy consumption of lighting proportionally (or at all), it may be\ndesireable to improve this performance indicator after all. The same goes for\nman hours of work and energy used for comfort heating.\n\nIn particular, if only adjustment factors being part of the physics observed,\nand all the adjustment factors being part of the physics observed are applied,\nthe resulting energy performance becomes an informationless physical constant\ndefined by nature. For instance energy (kWh) adjusted for power (W) and\ntime (s) will always give 1 with no unit.\n" }, { "alpha_fraction": 0.6489167213439941, "alphanum_fraction": 0.6491777896881104, "avg_line_length": 34.14678955078125, "blob_id": "4a6a031e700325077bfe271c08b44a076a7b178b", "content_id": "4afa8a34c85b9f71952864492b3d17a362490c6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3831, "license_type": "no_license", "max_line_length": 78, "num_lines": 109, "path": "/gridplatform/datasources/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport pytz\n\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import BASE_UNITS\nfrom gridplatform.utils.units import unit_conversion_map\nfrom gridplatform.utils import units\n\nfrom .models import RawData\nfrom .models import DataSource\n\n\nclass DataSourceSerializerBase(serializers.DefaultSerializer):\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n def get_display_unit(self, obj):\n if obj.unit == 'millibar':\n return 'efficiency'\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n def validate_unit(self, attrs, source):\n unit = attrs[source]\n if unit not in unit_conversion_map:\n raise ValidationError(b'invalid unit %s' % unit)\n attrs[source] = unit_conversion_map[unit]\n return attrs\n\n def _url_parameters(self):\n model_meta = self.opts.model._meta\n return {\n 'app_label': model_meta.app_label,\n 'model_name': model_meta.object_name.lower()\n }\n\n\nclass RawDataWithUnitSerializer(serializers.ModelSerializer):\n unit = serializers.ChoiceField(choices=())\n\n class Meta:\n model = RawData\n fields = ('timestamp', 'value', 'unit')\n\n def __init__(self, *args, **kwargs):\n super(RawDataWithUnitSerializer, self).__init__(*args, **kwargs)\n parser_context = self.context['request'].parser_context\n datasource_id = parser_context['kwargs'].get('datasource_id')\n datasource_model = self.opts.model.datasource.field.rel.to\n self.datasource = datasource_model.objects.get(id=datasource_id)\n unit_choices = (\n (unit, display_name) for unit, display_name in\n units.UNIT_DISPLAY_NAMES.items()\n if PhysicalQuantity.compatible_units(self.datasource.unit, unit)\n )\n self.fields['unit'].choices = unit_choices\n\n def restore_object(self, attrs, instance=None):\n assert instance is None\n value = attrs['value']\n unit = attrs['unit']\n assert unit in BASE_UNITS\n instance = self.opts.model(\n value=value, timestamp=attrs['timestamp'],\n datasource=self.datasource)\n return instance\n\n def validate_unit(self, attrs, source):\n # only checks that unit is valid\n unit = attrs[source]\n if unit not in unit_conversion_map:\n raise ValidationError(b'invalid unit %s' % unit)\n return attrs\n\n def validate(self, attrs):\n # actually convert unit/value\n value = attrs['value']\n unit = attrs['unit']\n timestamp = attrs['timestamp']\n # unit is known to be present in conversion map from validate_unit()\n base_unit = unit_conversion_map[unit]\n attrs['value'] = int(PhysicalQuantity(value, unit).convert(base_unit))\n attrs['unit'] = base_unit\n attrs['timestamp'] = timestamp.replace(tzinfo=pytz.utc)\n return attrs\n\n def get_validation_exclusions(self, instance=None):\n # NOTE: datasource is set in restore_object and we would like\n # uniqueness constraints to be validated.\n return [\n exclusion for exclusion in\n super(RawDataWithUnitSerializer, self).get_validation_exclusions()\n if exclusion != 'datasource']\n\n\nclass DataSourceSerializer(DataSourceSerializerBase):\n raw_data = serializers.HyperlinkedIdentityField(\n view_name='api:datasources:rawdata-list')\n\n class Meta:\n model = DataSource\n fields = (\n 'url', 'id', 'customer', 'unit', 'display_unit',\n 'hardware_id', 'raw_data'\n )\n" }, { "alpha_fraction": 0.6136606335639954, "alphanum_fraction": 0.6147278547286987, "avg_line_length": 31.310344696044922, "blob_id": "8eb8212d870f77b6ca225e55c0e7e4621d05bda5", "content_id": "64025bbdd8b0cd9c36b6905f0e75e2f55a9a7725", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 937, "license_type": "no_license", "max_line_length": 70, "num_lines": 29, "path": "/legacy/manage_measurementpoints/forms/collection.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\n\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform import trackuser\n\n\nclass CollectionForm(forms.ModelForm):\n def __init__(self, *args, **kwargs):\n super(CollectionForm, self).__init__(*args, **kwargs)\n\n self.fields['parent'].queryset = \\\n self.fields['parent'].queryset.filter(\n customer=trackuser.get_customer(),\n role__in=Collection.PARENTS)\n\n if self.instance.id:\n subtree = self.instance.get_descendants(\n include_self=True).values_list('id', flat=True)\n self.fields['parent'].queryset = \\\n self.fields['parent'].queryset.exclude(id__in=subtree)\n\n class Meta:\n model = Collection\n fields = ('name', 'parent')\n localized_fields = '__all__'\n" }, { "alpha_fraction": 0.7086247205734253, "alphanum_fraction": 0.7109557390213013, "avg_line_length": 20.450000762939453, "blob_id": "8cf7cec7a0d79cfd92c67eef64cd1f73a5038b1a", "content_id": "e0f78aedc47104b7aa5d35bc1ede9859223bb818", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 62, "num_lines": 20, "path": "/legacy/website/templatetags/gminfo.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines Django template tags for showing versions.\n\"\"\"\n\nfrom django import template\nfrom django.conf import settings\n\n\nregister = template.Library()\n\n\[email protected]_tag\ndef gridmanager_info():\n \"\"\"\n Display GridManager information\n \"\"\"\n return settings.GRIDMANAGER_ADDRESS.replace('\\n', '<br>')\n" }, { "alpha_fraction": 0.5962913632392883, "alphanum_fraction": 0.6199631094932556, "avg_line_length": 41.631126403808594, "blob_id": "3759e9ef0a08b481ce73adf3935d1f6812289c46", "content_id": "42bdcdf724a84632cc7d9e008eb95e76e3238b48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 79166, "license_type": "no_license", "max_line_length": 108, "num_lines": 1857, "path": "/gridplatform/consumptions/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom fractions import Fraction\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\nimport pytz\nfrom mock import patch\nfrom django.test import RequestFactory\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom gridplatform.tariffs.models import VolumeTariff\nfrom gridplatform.tariffs.models import FixedPricePeriod\nfrom gridplatform.tariffs.models import TariffPeriodManager\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_CHOICES\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import sum_or_none\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.datasequences.models import EnergyPerVolumeDataSequence\nfrom gridplatform.datasequences.models import AccumulationBase\nfrom gridplatform.cost_compensations.models import CostCompensation\nfrom gridplatform.cost_compensations.models import FixedCompensationPeriod\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\nfrom gridplatform.rest.serializers import HyperlinkedIdentityField\nfrom gridplatform.rest.serializers import HyperlinkedRelatedField\nfrom energymanager.energyuses.models import MAIN_ENERGY_USE_AREAS\nfrom energymanager.energyuses.models import EnergyUse\nfrom gridplatform.datasequences.models.energyconversion import VolumeToEnergyConversionPeriodManager # noqa\nfrom gridplatform.co2conversions.models import Co2ConversionManager\n\nfrom .models import ConsumptionGroup\nfrom .models import MainConsumption\nfrom .models import Consumption\nfrom .models import SingleValuePeriod\nfrom .models import ConsumptionUnionBase\nfrom .tasks import net_cost_sum_and_costcompensation_amount_task\nfrom .tasks import total_cost_sum_task\nfrom .tasks import mainconsumptions_weekly_utility_task\nfrom .tasks import mainconsumptions_weekly_cost_sequence\nfrom .tasks import energyuse_weekly_sequence\nfrom .tasks import energyuse_weekly_cost_sequence\nfrom . import viewsets\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VolumeConsumptionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.consumption = Consumption.objects.create(\n customer=self.customer,\n unit='meter^3')\n\n self.utility_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i * 7, 'meter^3'))\n for i in range(12)]\n\n self.patched_hourly_accumulated = patch.object(\n AccumulationBase, '_hourly_accumulated',\n return_value=self.utility_samples, autospec=True)\n\n self.conversion_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(Fraction(1, 7), 'joule*meter^-3'))\n for i in range(12)]\n\n self.patched_conversion_sequence = patch.object(\n Consumption, '_hourly_conversion_sequence',\n return_value=self.conversion_samples, autospec=True)\n\n self.patched_conversion_value_sequence = patch.object(\n VolumeToEnergyConversionPeriodManager, 'value_sequence',\n return_value=self.conversion_samples, autospec=True)\n\n def test_clean_volumetoenergyconversion_happy(self):\n self.consumption.volumetoenergyconversion = \\\n EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n self.consumption.clean()\n\n def test_hourly_conversion_sequence_no_volumetoenergyconversion(self):\n self.assertEqual(\n list(\n self.consumption._hourly_conversion_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))),\n [])\n\n def test_hourly_conversion_sequence_volumetoenergyconversion(self):\n self.consumption.volumetoenergyconversion = \\\n EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n\n with self.patched_conversion_value_sequence:\n self.assertEqual(\n list(\n self.consumption._hourly_conversion_sequence(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)))),\n self.conversion_samples)\n\n def test_energy_sequence(self):\n energy_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i, 'joule'))\n for i in range(12)]\n\n with self.patched_hourly_accumulated, \\\n self.patched_conversion_sequence:\n self.assertEqual(\n list(\n self.consumption.energy_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)),\n condense.HOURS)),\n energy_samples)\n\n def test_utility_sequence(self):\n with self.patched_hourly_accumulated:\n self.assertEqual(\n list(\n self.consumption.utility_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)),\n condense.HOURS)),\n self.utility_samples)\n\n def test_energy_sum(self):\n with self.patched_hourly_accumulated, \\\n self.patched_conversion_sequence:\n self.assertEqual(\n self.consumption.energy_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(12 * 11 / 2, 'joule'))\n\n def test_utility_sum(self):\n patched_development_sum = patch.object(\n AccumulationBase, 'development_sum',\n return_value=PhysicalQuantity(42, 'meter^3'), autospec=True)\n\n with patched_development_sum:\n self.assertEqual(\n self.consumption.utility_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42, 'meter^3'))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass EnergyConsumptionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.consumption = Consumption.objects.create(\n customer=self.customer,\n unit='joule')\n\n def test_clean_volumetoenergyconversion_unhappy(self):\n self.consumption.volumetoenergyconversion = \\\n EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n with self.assertRaises(ValidationError):\n self.consumption.clean()\n\n def test_energy_sequence(self):\n energy_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i, 'joule'))\n for i in range(12)]\n\n patched_hourly_accumulated = patch.object(\n AccumulationBase, '_hourly_accumulated',\n return_value=energy_samples, autospec=True)\n\n with patched_hourly_accumulated:\n self.assertEqual(\n list(\n self.consumption.energy_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)),\n condense.HOURS)),\n energy_samples)\n\n def test_utility_sequence(self):\n energy_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i, 'joule'))\n for i in range(12)]\n\n patched_hourly_accumulated = patch.object(\n AccumulationBase, '_hourly_accumulated',\n return_value=energy_samples, autospec=True)\n\n with patched_hourly_accumulated:\n self.assertEqual(\n list(\n self.consumption.energy_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)),\n condense.HOURS)),\n energy_samples)\n\n def test_energy_sum(self):\n patched_development_sum = patch.object(\n AccumulationBase, 'development_sum',\n return_value=PhysicalQuantity(42, 'joule'), autospec=True)\n\n with patched_development_sum:\n self.assertEqual(\n self.consumption.energy_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42, 'joule'))\n\n def test_utility_sum(self):\n patched_development_sum = patch.object(\n AccumulationBase, 'development_sum',\n return_value=PhysicalQuantity(42, 'joule'), autospec=True)\n\n with patched_development_sum:\n self.assertEqual(\n self.consumption.utility_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42, 'joule'))\n\n\nclass TestConsumptionUnion(ConsumptionUnionBase):\n pass\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ConsumptionUnionBaseTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.consumption = Consumption.objects.create(\n customer=self.customer,\n unit='meter^3')\n\n def test_utility_sum_delegation(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n subject.consumptions = [self.consumption]\n with patch.object(\n Consumption, 'utility_sum', autospec=True,\n return_value=PhysicalQuantity(1, 'meter^3')) as mock:\n subject.utility_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n mock.assert_called_with(\n self.consumption,\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_utility_sum_delegation_none_quantity(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n subject.consumptions = [self.consumption]\n with patch.object(\n Consumption, 'utility_sum', autospec=True,\n side_effect=Consumption.utility_sum) as mock:\n subject.utility_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n mock.assert_called_with(\n self.consumption,\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_utility_sum_no_consumptions(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n self.assertIsNone(\n subject.utility_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_co2_emission_sequence_no_consumptions(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n\n patched_co2conversion = patch.object(\n TestConsumptionUnion, 'fiveminute_co2conversion_sequence',\n autospec=True,\n return_value=[])\n\n with patched_co2conversion:\n self.assertEqual(\n [],\n list(\n subject.co2_emissions_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n condense.HOURS)))\n\n def test_fiveminute_co2conversion_sequence_abstract(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n with self.assertRaises(NotImplementedError):\n subject.fiveminute_co2conversion_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_co2_emission_sequence(self):\n subject = TestConsumptionUnion.objects.create(\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n\n patched_co2conversion = patch.object(\n TestConsumptionUnion, 'fiveminute_co2conversion_sequence',\n autospec=True,\n return_value=[\n RangedSample(\n from_timestamp + datetime.timedelta(minutes=5 * i),\n from_timestamp + datetime.timedelta(minutes=5 * (i + 1)),\n PhysicalQuantity(i % 7, 'kilogram*kilowatt^-1*hour^-1'))\n for i in range(24 * 60 / 5)\n ])\n\n patched_utility_consumption = patch.object(\n TestConsumptionUnion, 'utility_sequence', autospec=True,\n return_value=[\n RangedSample(\n from_timestamp + datetime.timedelta(minutes=5 * i),\n from_timestamp + datetime.timedelta(minutes=5 * (i + 1)),\n PhysicalQuantity(i % 11, 'kilowatt*hour'))\n for i in range(24 * 60 / 5)\n ])\n\n with patched_co2conversion, patched_utility_consumption:\n self.assertEqual(\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n sum_or_none(\n PhysicalQuantity((i % 7) * (i % 11), 'kilogram')\n for i in range(h * 60 / 5, (h + 1) * 60 / 5)))\n for h in range(24)\n ],\n list(\n subject.co2_emissions_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n condense.HOURS)))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ConsumptionGroupTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.consumptiongroup = ConsumptionGroup.objects.create(\n mainconsumption=self.mainconsumption,\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n self.timezone = self.customer.timezone\n\n def test_energy_sequence_integration(self):\n self.consumptiongroup.consumptions.add(\n Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer))\n self.consumptiongroup.consumptions.add(\n Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer))\n\n consumptions = list(self.consumptiongroup.consumptions.all())\n self.assertEqual(len(consumptions), 2)\n\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_development_sequence = patch.object(\n Consumption,\n 'development_sequence',\n return_value=[\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(42, 'joule'))],\n autospec=True)\n\n with patched_development_sequence as mock:\n result = list(\n self.consumptiongroup.energy_sequence(\n from_timestamp, to_timestamp, condense.DAYS))\n\n mock.assert_any_call(\n consumptions[0], from_timestamp, to_timestamp, condense.DAYS)\n mock.assert_any_call(\n consumptions[1], from_timestamp, to_timestamp, condense.DAYS)\n\n self.assertEqual(mock.call_count, 2)\n\n self.assertEqual(\n [\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(84, 'joule'))],\n result)\n\n def test_save_no_mainconsumption_change(self):\n mainconsumption2 = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.consumptiongroup.mainconsumption = mainconsumption2\n\n with self.assertRaises(AssertionError):\n self.consumptiongroup.save()\n\n def test_energy_sum_integration(self):\n self.assertIsNone(\n self.consumptiongroup.energy_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_net_cost_sum_no_tariff_and_no_consumptions(self):\n self.assertIsNone(self.consumptiongroup.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_net_cost_sum_energy_tariff(self):\n self.consumptiongroup.mainconsumption = \\\n MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.consumptiongroup.mainconsumption.tariff = \\\n EnergyTariff.objects.create(customer=self.customer)\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.consumptiongroup.mainconsumption.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n self.consumptiongroup.consumptions.add(consumption)\n\n self.assertEqual(\n self.consumptiongroup.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_net_cost_sum_volume_tariff(self):\n self.consumptiongroup.mainconsumption = \\\n MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n from_date=datetime.date(2014, 1, 1))\n self.consumptiongroup.mainconsumption.tariff = \\\n VolumeTariff.objects.create(customer=self.customer)\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*meter^-3',\n datasequence=self.consumptiongroup.mainconsumption.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n utility_consumption = Consumption.objects.create(\n unit='meter^3',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=utility_consumption,\n value=42,\n unit='meter^3')\n\n self.consumptiongroup.consumptions.add(utility_consumption)\n\n energy_pr_volume = EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n\n utility_consumption.volumetoenergyconversion = energy_pr_volume\n utility_consumption.save()\n\n self.assertEqual(\n self.consumptiongroup.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_costcompensation_amount_sum_no_costcompensation_nor_consumptions(self): # noqa\n self.assertIsNone(self.consumptiongroup.costcompensation_amount_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_costcompensation_amount_sum(self):\n self.consumptiongroup.cost_compensation = \\\n CostCompensation.objects.create(customer=self.customer)\n FixedCompensationPeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.consumptiongroup.cost_compensation)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n self.consumptiongroup.consumptions.add(consumption)\n\n self.assertEqual(\n self.consumptiongroup.costcompensation_amount_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_mainconsumption_costcompensation_amount_sum(self):\n self.mainconsumption.cost_compensation = \\\n CostCompensation.objects.create(customer=self.customer)\n FixedCompensationPeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.mainconsumption.cost_compensation)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n self.consumptiongroup.consumptions.add(consumption)\n\n self.assertEqual(\n self.consumptiongroup.costcompensation_amount_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_variable_cost_sum_integration(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n self.assertIsNone(\n self.consumptiongroup.variable_cost_sum(\n from_timestamp, to_timestamp))\n\n def test_fiveminute_co2conversion_sequence_integration(self):\n patched_co2conversion = patch.object(\n MainConsumption, 'fiveminute_co2conversion_sequence',\n autospec=True,\n return_value=[])\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n with patched_co2conversion as mock:\n self.consumptiongroup.fiveminute_co2conversion_sequence(\n from_timestamp, to_timestamp)\n\n mock.assert_called_with(\n self.mainconsumption, from_timestamp, to_timestamp)\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass NetCostSumAndCostCompensationAmountTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.consumptiongroup = ConsumptionGroup.objects.create(\n mainconsumption=self.mainconsumption,\n customer=self.customer,\n from_date=datetime.date(2014, 1, 1))\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n\n def test_no_consumptiongroups(self):\n with replace_user(self.user):\n eager = net_cost_sum_and_costcompensation_amount_task.delay(\n [],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n self.assertEqual({}, eager.result)\n\n def test_unknown_net_cost_and_unknown_costcompensation_amount(self):\n with replace_user(self.user):\n eager = net_cost_sum_and_costcompensation_amount_task.delay(\n [self.consumptiongroup.id],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n self.assertEqual(\n {\n self.consumptiongroup.id: {\n 'net_cost_sum': None,\n 'costcompensation_amount_sum': None,\n },\n },\n eager.result)\n\n def test_unknown_net_cost(self):\n costcompensation_amount_sum = PhysicalQuantity(17, 'currency_dkk')\n\n with replace_user(self.user), patch.object(\n ConsumptionGroup, 'costcompensation_amount_sum',\n return_value=costcompensation_amount_sum):\n\n eager = net_cost_sum_and_costcompensation_amount_task.delay(\n [self.consumptiongroup.id],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n self.assertEqual(\n {\n self.consumptiongroup.id: {\n 'net_cost_sum': None,\n 'costcompensation_amount_sum': costcompensation_amount_sum,\n },\n },\n eager.result)\n\n def test_unknown_costcompensation_amount(self):\n net_cost_sum = PhysicalQuantity(42, 'currency_dkk')\n\n with replace_user(self.user), patch.object(\n ConsumptionGroup, 'net_cost_sum', return_value=net_cost_sum):\n\n eager = net_cost_sum_and_costcompensation_amount_task.delay(\n [self.consumptiongroup.id],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n self.assertEqual(\n {\n self.consumptiongroup.id: {\n 'net_cost_sum': net_cost_sum,\n 'costcompensation_amount_sum': None,\n },\n },\n eager.result)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass MainConsumptionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=self.timezone,\n currency_unit='currency_dkk')\n\n def test_save_no_utility_type_change(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.utility_type = ENERGY_UTILITY_TYPE_CHOICES.electricity\n with self.assertRaises(AssertionError):\n mainconsumption.save()\n\n def test_clean_happy(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.clean()\n\n def test_clean_no_tariff_change_once_set(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.tariff = VolumeTariff.objects.create(\n customer=self.customer)\n with self.assertRaises(ValidationError):\n mainconsumption.clean()\n\n def test_clean_no_clearing_tariff_once_set(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.tariff = None\n with self.assertRaises(ValidationError):\n mainconsumption.clean()\n\n def test_clean_no_costcompensation_change_once_set(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.cost_compensation = CostCompensation.objects.create(\n customer=self.customer)\n with self.assertRaises(ValidationError):\n mainconsumption.clean()\n\n def test_clean_no_clearing_costcompensation_once_set(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n mainconsumption.cost_compensation = None\n\n with self.assertRaises(ValidationError):\n mainconsumption.clean()\n\n def test_energy_sum_integration(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n from_date=datetime.date(2014, 1, 1))\n\n self.assertIsNone(\n mainconsumption.energy_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_net_cost_sum_no_tariff_and_no_consumptions(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n self.assertIsNone(mainconsumption.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_energy_sequence_integration(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n mainconsumption.consumptions.add(\n Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer))\n mainconsumption.consumptions.add(\n Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer))\n\n consumptions = list(mainconsumption.consumptions.all())\n self.assertEqual(len(consumptions), 3) # the above + historical\n\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_development_sequence = patch.object(\n Consumption,\n 'development_sequence',\n return_value=[\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(42, 'joule'))],\n autospec=True)\n\n with patched_development_sequence as mock:\n result = list(\n mainconsumption.energy_sequence(\n from_timestamp, to_timestamp, condense.DAYS))\n\n mock.assert_any_call(\n consumptions[0], from_timestamp, to_timestamp, condense.DAYS)\n mock.assert_any_call(\n consumptions[1], from_timestamp, to_timestamp, condense.DAYS)\n mock.assert_any_call(\n consumptions[2], from_timestamp, to_timestamp, condense.DAYS)\n\n self.assertEqual(mock.call_count, 3)\n\n self.assertEqual(\n [\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(126, 'joule'))],\n result)\n\n def test_net_cost_sum_energy_tariff(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n tariff=EnergyTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=mainconsumption.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n mainconsumption.consumptions.add(consumption)\n\n self.assertEqual(\n mainconsumption.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_net_cost_sum_volume_tariff(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n value=10,\n unit='currency_dkk*meter^-3',\n datasequence=mainconsumption.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n utility = Consumption.objects.create(\n unit='meter^3',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)),\n datasequence=utility,\n value=42,\n unit='meter^3')\n\n mainconsumption.consumptions.add(utility)\n\n energy_pr_volume = EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n\n utility.volumetoenergyconversion = energy_pr_volume\n utility.save()\n\n self.assertEqual(\n mainconsumption.net_cost_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_costcompensation_amount_sum_no_costcompensation_nor_consumptions(self): # noqa\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n from_date=datetime.date(2014, 1, 1))\n\n self.assertIsNone(mainconsumption.costcompensation_amount_sum(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_costcompensation_amount_sum_both(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n FixedCompensationPeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=mainconsumption.cost_compensation)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n mainconsumption.consumptions.add(consumption)\n\n consumptiongroup = ConsumptionGroup.objects.create(\n mainconsumption=mainconsumption,\n customer=self.customer,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n\n FixedCompensationPeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=7,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=consumptiongroup.cost_compensation)\n\n consumption_part = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n datasequence=consumption_part,\n value=17,\n unit='kilowatt*hour')\n consumptiongroup.consumptions.add(consumption_part)\n\n self.assertEqual(\n mainconsumption.costcompensation_amount_sum(\n from_timestamp, to_timestamp),\n PhysicalQuantity((42 - 17) * 10 + 17 * 7, 'currency_dkk'))\n\n def test_costcompensation_amount_sum_tainted(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n consumptiongroup = ConsumptionGroup.objects.create(\n mainconsumption=mainconsumption,\n customer=self.customer,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n\n FixedCompensationPeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=7,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=consumptiongroup.cost_compensation)\n\n consumption_part = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n datasequence=consumption_part,\n value=17,\n unit='kilowatt*hour')\n consumptiongroup.consumptions.add(consumption_part)\n\n self.assertEqual(\n mainconsumption.costcompensation_amount_sum(\n from_timestamp, to_timestamp),\n PhysicalQuantity(17 * 7, 'currency_dkk'))\n\n def test_costcompensation_amount_sum_untainted(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n FixedCompensationPeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=mainconsumption.cost_compensation)\n\n consumption = Consumption.objects.create(\n unit='milliwatt*hour',\n customer=self.customer)\n SingleValuePeriod.objects.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n datasequence=consumption,\n value=42,\n unit='kilowatt*hour')\n mainconsumption.consumptions.add(consumption)\n\n self.assertEqual(\n mainconsumption.costcompensation_amount_sum(\n from_timestamp, to_timestamp),\n PhysicalQuantity(42 * 10, 'currency_dkk'))\n\n def test_variable_cost_sum_integration(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n cost_compensation=CostCompensation.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n self.assertIsNone(\n mainconsumption.variable_cost_sum(from_timestamp, to_timestamp))\n\n def test_fixed_cost_sum_delegation(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_subscription_cost = patch.object(\n TariffPeriodManager, 'subscription_cost_sum', autospec=True,\n return_value=PhysicalQuantity(11, 'currency_dkk'))\n\n mainconsumption.fixed_cost_sum(from_timestamp, to_timestamp)\n\n with patched_subscription_cost:\n self.assertEqual(\n PhysicalQuantity(11, 'currency_dkk'),\n mainconsumption.fixed_cost_sum(from_timestamp, to_timestamp))\n\n def test_total_cost_sum(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_variable_cost = patch.object(\n MainConsumption, 'variable_cost_sum', autospec=True,\n return_value=PhysicalQuantity(7, 'currency_dkk'))\n patched_fixed_cost = patch.object(\n MainConsumption, 'fixed_cost_sum', autospec=True,\n return_value=PhysicalQuantity(11, 'currency_dkk'))\n\n with patched_variable_cost, patched_fixed_cost:\n self.assertEqual(\n PhysicalQuantity(7 + 11, 'currency_dkk'),\n mainconsumption.total_cost_sum(from_timestamp, to_timestamp))\n\n def test_total_cost_sum_no_variable_cost(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_fixed_cost = patch.object(\n MainConsumption, 'fixed_cost_sum', autospec=True,\n return_value=PhysicalQuantity(11, 'currency_dkk'))\n\n with patched_fixed_cost:\n self.assertEqual(\n PhysicalQuantity(11, 'currency_dkk'),\n mainconsumption.total_cost_sum(from_timestamp, to_timestamp))\n\n def test_total_cost_sum_no_fixed_cost(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n tariff=VolumeTariff.objects.create(\n customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_variable_cost = patch.object(\n MainConsumption, 'variable_cost_sum', autospec=True,\n return_value=PhysicalQuantity(7, 'currency_dkk'))\n\n with patched_variable_cost:\n self.assertEqual(\n PhysicalQuantity(7, 'currency_dkk'),\n mainconsumption.total_cost_sum(from_timestamp, to_timestamp))\n\n def test_clean_good_tariff(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n tariff=EnergyTariff.objects.create(customer=self.customer),\n from_date=datetime.date(2014, 1, 1))\n\n mainconsumption.clean()\n\n def test_clean_bad_unit_tariff(self):\n mainconsumption = MainConsumption(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n tariff=VolumeTariff.objects.create(customer=self.customer))\n\n with self.assertRaises(ValidationError):\n mainconsumption.clean()\n\n def test_fiveminute_co2conversion_sequence_integration(self):\n mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n patched_co2conversion = patch.object(\n Co2ConversionManager, 'value_sequence',\n autospec=True,\n return_value=[])\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n with patched_co2conversion as mock:\n mainconsumption.fiveminute_co2conversion_sequence(\n from_timestamp, to_timestamp)\n\n # First argument of value_sequence() is a new instance of some subclass\n # of Co2ConversionManager upon every access. We are happy if the call\n # just got there. Otherwise mock.assert_called_with() should have been\n # used.\n args = mock.call_args[0][1:]\n self.assertEqual(args, (from_timestamp, to_timestamp))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VariableCostSumTest(TestCase):\n def setUp(self):\n self.consumptionunion = TestConsumptionUnion()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n self.to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n def test_no_costcompensation(self):\n patched_net_cost_sum = patch.object(\n TestConsumptionUnion, 'net_cost_sum', autospec=True,\n return_value=PhysicalQuantity(42, 'currency_dkk'))\n patched_costcompensation_amount_sum = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sum',\n autospec=True, return_value=None)\n\n with patched_net_cost_sum, patched_costcompensation_amount_sum:\n self.assertEqual(\n PhysicalQuantity(42, 'currency_dkk'),\n self.consumptionunion.variable_cost_sum(\n self.from_timestamp, self.to_timestamp))\n\n def test_no_net_cost(self):\n patched_net_cost_sum = patch.object(\n TestConsumptionUnion, 'net_cost_sum', autospec=True,\n return_value=None)\n patched_costcompensation_amount_sum = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sum',\n autospec=True, return_value=PhysicalQuantity(42, 'currency_dkk'))\n\n with patched_net_cost_sum, patched_costcompensation_amount_sum:\n self.assertIsNone(\n self.consumptionunion.variable_cost_sum(\n self.from_timestamp, self.to_timestamp))\n\n def test_net_cost_and_costcompensation(self):\n patched_net_cost_sum = patch.object(\n TestConsumptionUnion, 'net_cost_sum', autospec=True,\n return_value=PhysicalQuantity(42, 'currency_dkk'))\n patched_costcompensation_amount_sum = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sum',\n autospec=True,\n return_value=PhysicalQuantity(17, 'currency_dkk'))\n\n with patched_net_cost_sum, patched_costcompensation_amount_sum:\n self.assertEqual(\n PhysicalQuantity(42 - 17, 'currency_dkk'),\n self.consumptionunion.variable_cost_sum(\n self.from_timestamp, self.to_timestamp))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VariableCostSequenceTest(TestCase):\n def setUp(self):\n self.consumptionunion = TestConsumptionUnion()\n self.consumptionunion.customer = Customer(\n currency_unit='currency_dkk',\n timezone=pytz.timezone('Europe/Copenhagen'))\n self.timezone = self.consumptionunion.customer.timezone\n self.from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n self.to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12))\n\n self.net_cost_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i * 7, 'currency_dkk'))\n for i in range(12)]\n\n self.costcompensation_amount_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i * 3, 'currency_dkk'))\n for i in range(12)]\n\n self.variable_cost_samples = [\n RangedSample(\n self.timezone.localize(datetime.datetime(2014, 1, 1, i)),\n self.timezone.localize(datetime.datetime(2014, 1, 1, i + 1)),\n PhysicalQuantity(i * (7 - 3), 'currency_dkk'))\n for i in range(12)]\n\n def test_no_costcompensation_and_no_net_cost(self):\n patched_net_cost_sequence = patch.object(\n TestConsumptionUnion, 'net_cost_sequence', autospec=True,\n return_value=[])\n patched_costcompensation_amount_sequence = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sequence',\n autospec=True, return_value=[])\n\n with patched_net_cost_sequence, \\\n patched_costcompensation_amount_sequence:\n self.assertListEqual(\n [],\n list(\n self.consumptionunion.variable_cost_sequence(\n self.from_timestamp, self.to_timestamp,\n condense.HOURS)))\n\n def test_no_costcompensation(self):\n patched_net_cost_sequence = patch.object(\n TestConsumptionUnion, 'net_cost_sequence', autospec=True,\n return_value=self.net_cost_samples)\n patched_costcompensation_amount_sequence = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sequence',\n autospec=True, return_value=[])\n\n with patched_net_cost_sequence, \\\n patched_costcompensation_amount_sequence:\n self.assertListEqual(\n self.net_cost_samples,\n list(\n self.consumptionunion.variable_cost_sequence(\n self.from_timestamp, self.to_timestamp,\n condense.HOURS)))\n\n def test_no_net_cost(self):\n patched_net_cost_sequence = patch.object(\n TestConsumptionUnion, 'net_cost_sequence', autospec=True,\n return_value=[])\n patched_costcompensation_amount_sequence = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sequence',\n autospec=True, return_value=self.costcompensation_amount_samples)\n\n with patched_net_cost_sequence, \\\n patched_costcompensation_amount_sequence:\n self.assertListEqual(\n [\n RangedSample(\n sample.from_timestamp, sample.to_timestamp,\n -sample.physical_quantity)\n for sample in self.costcompensation_amount_samples],\n list(\n self.consumptionunion.variable_cost_sequence(\n self.from_timestamp, self.to_timestamp,\n condense.HOURS)))\n\n def test_net_cost_and_costcompensation(self):\n patched_net_cost_sequence = patch.object(\n TestConsumptionUnion, 'net_cost_sequence', autospec=True,\n return_value=self.net_cost_samples)\n patched_costcompensation_amount_sequence = patch.object(\n TestConsumptionUnion, 'costcompensation_amount_sequence',\n autospec=True, return_value=self.costcompensation_amount_samples)\n\n with patched_net_cost_sequence, \\\n patched_costcompensation_amount_sequence:\n self.assertListEqual(\n self.variable_cost_samples,\n list(\n self.consumptionunion.variable_cost_sequence(\n self.from_timestamp, self.to_timestamp,\n condense.HOURS)))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass TotalCostSumTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n\n def test_empty(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n with replace_user(self.user):\n eager = total_cost_sum_task.delay([], from_timestamp, to_timestamp)\n\n self.assertEqual({}, eager.result)\n\n def test_some(self):\n electricity = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n gas = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.gas,\n from_date=datetime.date(2014, 1, 1))\n\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n total_cost_quantity = PhysicalQuantity(42, 'currency_dkk')\n patched_total_cost_sum = patch.object(\n MainConsumption, 'total_cost_sum',\n return_value=total_cost_quantity)\n\n with replace_user(self.user), patched_total_cost_sum:\n eager = total_cost_sum_task.delay(\n [electricity.id, gas.id], from_timestamp, to_timestamp)\n\n self.assertEqual(\n {\n electricity.id: total_cost_quantity,\n gas.id: total_cost_quantity},\n eager.result)\n\n\ndef get_url_mock(self, obj, view_name, request, format):\n \"\"\"Mock used to render HyperlinkedModelSerializer\"\"\"\n return \"/%s\" % view_name\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass MainConsumptionViewSetTest(TestCase):\n\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.factory = RequestFactory()\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n name_plain='Dat main meter',\n from_date=datetime.date(2014, 1, 1))\n\n consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.mainconsumption.consumptions.add(consumption)\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=consumption,\n value=1024,\n unit='kilowatt*hour')\n\n def test_get(self):\n request = self.factory.get('/', content_type='application/json')\n request.user = User(name_plain='test user')\n view = viewsets.MainConsumption.as_view(actions={'get': 'list'})\n with patch.object(HyperlinkedIdentityField, 'get_url', get_url_mock), \\\n patch.object(HyperlinkedRelatedField, 'get_url', get_url_mock):\n response = view(request, pk=self.mainconsumption.id)\n self.assertContains(response, 'Dat main meter')\n\n def test_get_hourly(self):\n request = self.factory.get(\n '/?date=2014-08-19', content_type='application/json')\n request.user = User(name_plain='test user')\n\n view = viewsets.MainConsumption.as_view(actions={'get': 'hourly'})\n with patch.object(HyperlinkedIdentityField, 'get_url', get_url_mock), \\\n patch.object(HyperlinkedRelatedField, 'get_url', get_url_mock):\n response = view(request, pk=self.mainconsumption.id)\n self.assertContains(response, '2014-08-19T00:00:00+02:00')\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass ConsumptionGroupViewSetTest(TestCase):\n\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.factory = RequestFactory()\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n name_plain='Dat main meter',\n from_date=datetime.date(2014, 1, 1))\n\n self.consumptiongroup = ConsumptionGroup.objects.create(\n mainconsumption=self.mainconsumption,\n customer=self.customer,\n name_plain='Der Verbrauch Gruppe',\n from_date=datetime.date(2014, 1, 1))\n\n consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.consumptiongroup.consumptions.add(consumption)\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=consumption,\n value=1024,\n unit='kilowatt*hour')\n\n def test_get(self):\n request = self.factory.get('/', content_type='application/json')\n request.user = User(name_plain='test user')\n view = viewsets.ConsumptionGroup.as_view(actions={'get': 'list'})\n with patch.object(HyperlinkedIdentityField, 'get_url', get_url_mock), \\\n patch.object(HyperlinkedRelatedField, 'get_url', get_url_mock):\n response = view(request, pk=self.consumptiongroup.id)\n self.assertContains(response, 'Der Verbrauch Gruppe')\n\n def test_get_hourly(self):\n request = self.factory.get(\n '/?date=2014-08-19', content_type='application/json')\n request.user = User(name_plain='test user')\n\n view = viewsets.ConsumptionGroup.as_view(actions={'get': 'hourly'})\n with patch.object(HyperlinkedIdentityField, 'get_url', get_url_mock), \\\n patch.object(HyperlinkedRelatedField, 'get_url', get_url_mock):\n response = view(request, pk=self.consumptiongroup.id)\n self.assertContains(response, '2014-08-19T00:00:00+02:00')\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass MainConsumptionsWeeklyCostSequenceTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.tariff = EnergyTariff.objects.create(\n customer=self.customer, name_plain='Tariff test')\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n tariff=self.tariff,\n from_date=datetime.date(2014, 1, 1))\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n self.consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.mainconsumption.consumptions.add(self.consumption)\n\n def test_no_data(self):\n with replace_user(self.user):\n sequence = mainconsumptions_weekly_cost_sequence.delay(\n [self.mainconsumption.id],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 7)))\n\n self.assertEqual(list(sequence.result['week_selected']), [])\n self.assertEqual(list(sequence.result['week_before']), [])\n\n def test_with_data(self):\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(\n 2014, 10, 1)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=self.consumption,\n value=1024,\n unit='kilowatt*hour')\n\n with replace_user(self.user):\n sequence = mainconsumptions_weekly_cost_sequence.delay(\n [self.mainconsumption.id],\n self.timezone.localize(datetime.datetime(2014, 1, 26)),\n self.timezone.localize(datetime.datetime(2014, 2, 2)))\n\n week_selected = list(sequence.result['week_selected'])\n week_before = list(sequence.result['week_before'])\n\n self.assertEqual(\n min(week_selected).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n self.assertEqual(\n max(week_selected).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 2, 2)))\n\n self.assertEqual(\n min(week_before).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 19)))\n self.assertEqual(\n max(week_before).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass EnergyUseWeeklySequenceTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1)\n )\n self.energyuse = EnergyUse.objects.create(\n mainconsumption=self.mainconsumption,\n customer=self.customer,\n main_energy_use_area=MAIN_ENERGY_USE_AREAS.lighting,\n from_date=datetime.date(2000, 1, 1))\n\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n self.consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.energyuse.consumptions.add(self.consumption)\n\n def test_no_data(self):\n with replace_user(self.user):\n sequence = energyuse_weekly_sequence.delay(\n self.energyuse.id,\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 7)))\n\n self.assertEqual(list(sequence.result['week_selected']), [])\n self.assertEqual(list(sequence.result['week_before']), [])\n self.assertEqual(\n sequence.result['utility_type'],\n self.energyuse.mainconsumption.utility_type)\n\n def test_with_data(self):\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=self.consumption,\n value=1024,\n unit='kilowatt*hour')\n\n with replace_user(self.user):\n sequence = energyuse_weekly_sequence.delay(\n self.energyuse.id,\n self.timezone.localize(datetime.datetime(2014, 1, 26)),\n self.timezone.localize(datetime.datetime(2014, 2, 2)))\n\n week_selected = list(sequence.result['week_selected'])\n week_before = list(sequence.result['week_before'])\n\n self.assertEqual(\n min(week_selected).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n self.assertEqual(\n max(week_selected).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 2, 2)))\n\n self.assertEqual(\n min(week_before).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 19)))\n self.assertEqual(\n max(week_before).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass EnergyUseWeeklyCostSequenceTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.tariff = EnergyTariff.objects.create(\n customer=self.customer, name_plain='Tariff test')\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n tariff=self.tariff,\n from_date=datetime.date(2014, 1, 1))\n self.energyuse = EnergyUse.objects.create(\n mainconsumption=self.mainconsumption,\n customer=self.customer,\n main_energy_use_area=MAIN_ENERGY_USE_AREAS.lighting,\n from_date=datetime.date(2000, 1, 1))\n\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n self.consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.energyuse.consumptions.add(self.consumption)\n\n def test_no_data(self):\n with replace_user(self.user):\n sequence = energyuse_weekly_cost_sequence.delay(\n self.energyuse.id,\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 7)))\n\n self.assertEqual(list(sequence.result['week_selected']), [])\n self.assertEqual(list(sequence.result['week_before']), [])\n self.assertEqual(sequence.result['energyuse_id'], self.energyuse.id)\n\n def test_withdata_data(self):\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=self.consumption,\n value=1024,\n unit='kilowatt*hour')\n\n FixedPricePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(\n 2014, 10, 1)),\n value=10,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n datasequence=self.tariff,\n subscription_fee=100,\n subscription_period=FixedPricePeriod.SUBSCRIPTION_PERIODS.monthly)\n\n with replace_user(self.user):\n sequence = energyuse_weekly_cost_sequence.delay(\n self.energyuse.id,\n self.timezone.localize(datetime.datetime(2014, 1, 26)),\n self.timezone.localize(datetime.datetime(2014, 2, 2)))\n\n week_selected = list(sequence.result['week_selected'])\n week_before = list(sequence.result['week_before'])\n\n self.assertEqual(\n min(week_selected).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n self.assertEqual(\n max(week_selected).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 2, 2)))\n\n self.assertEqual(\n min(week_before).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 19)))\n self.assertEqual(\n max(week_before).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_ALWAYS_EAGER=True)\nclass MainconsumptionsWeeklyUtilityTaskTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.mainconsumption2 = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n self.user = User.objects.create_user(\n 'test user', 'secret', User.ADMIN, provider=self.provider)\n self.consumption = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.mainconsumption.consumptions.add(self.consumption)\n\n self.consumption2 = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.mainconsumption2.consumptions.add(self.consumption2)\n\n def test_no_data(self):\n with replace_user(self.user):\n sequence = mainconsumptions_weekly_utility_task.delay(\n [self.mainconsumption.id, self.mainconsumption2.id],\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 7)),\n ENERGY_UTILITY_TYPE_CHOICES.electricity)\n\n self.assertEqual(list(\n sequence.result['week_selected']), [])\n self.assertEqual(list(\n sequence.result['week_before']), [])\n\n def test_with_data(self):\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=self.consumption,\n value=1024,\n unit='kilowatt*hour')\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=self.consumption2,\n value=1024,\n unit='kilowatt*hour')\n\n with replace_user(self.user):\n sequence = mainconsumptions_weekly_utility_task.delay(\n [self.mainconsumption.id, self.mainconsumption2.id],\n self.timezone.localize(datetime.datetime(2014, 1, 26)),\n self.timezone.localize(datetime.datetime(2014, 2, 2)),\n ENERGY_UTILITY_TYPE_CHOICES.electricity)\n\n week_selected = sequence.result['week_selected']\n week_before = sequence.result['week_before']\n\n self.assertEqual(\n min(week_selected).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n self.assertEqual(\n max(week_selected).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 2, 2)))\n\n self.assertEqual(\n min(week_before).from_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 19)))\n self.assertEqual(\n max(week_before).to_timestamp, self.timezone.localize(\n datetime.datetime(2014, 1, 26)))\n" }, { "alpha_fraction": 0.5118356943130493, "alphanum_fraction": 0.5599231719970703, "avg_line_length": 46.33395004272461, "blob_id": "2fb88b09c5e50e1725b2af8de946841980f0d53a", "content_id": "2548e24c9e080924cd3afe27d0dda28678d1491d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25516, "license_type": "no_license", "max_line_length": 278, "num_lines": 539, "path": "/EmonTX/SC-EmonTX_V140_Net210/SC-EmonTX_V140_Net210.ino", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#define emonTxV3 // Tell emonLib this is the emonTx V3 - don't read Vcc assume Vcc = 3.3V as is always the case on emonTx V3 eliminates bandgap error and need for calibration http://harizanov.com/2013/09/thoughts-on-avr-adc-accuracy/\n#define RF69_COMPAT 1 // Set to 1 if using RFM69CW or 0 is using RFM12B\n#include <JeeLib.h> //https://github.com/jcw/jeelib - Tested with JeeLib 3/11/14\n#include <avr/wdt.h>\n\nISR(WDT_vect) { Sleepy::watchdogEvent(); } // Attached JeeLib sleep function to Atmega328 watchdog -enables MCU to be put into sleep mode inbetween readings to reduce power consumption \n\n#include \"EmonLib.h\" // Include EmonLib energy monitoring library https://github.com/openenergymonitor/EmonLib\nEnergyMonitor ct1, ct2, ct3, ct4; \n\n// - OneWire and Dallas has been taken out of this software\n#include <OneWire.h> //http://www.pjrc.com/teensy/td_libs_OneWire.html\n#include <DallasTemperature.h> //http://download.milesburton.com/Arduino/MaximTemperature/DallasTemperature_LATEST.zip\n\nconst byte version = 140; // firmware version divided by 10 e,g 160 = V1.60\n\n//----------------------------emonTx V3 Settings---------------------------------------------------------------------------------------------------------------\nconst byte Vrms= 230; // Vrms for apparent power readings (when no AC-AC voltage sample is present)\nconst byte TIME_BETWEEN_READINGS = 9; //Time between readings \n\n//http://openenergymonitor.org/emon/buildingblocks/calibration\n\nconst float Ical1= 90.9; // (2000 turns / 22 Ohm burden) = 90.9\nconst float Ical2= 90.9; // (2000 turns / 22 Ohm burden) = 90.9\nconst float Ical3= 90.9; // (2000 turns / 22 Ohm burden) = 90.9\nconst float Ical4= 16.67; // (2000 turns / 120 Ohm burden) = 16.67\n\nconst float Vcal= 242; //238.86 reported, 216 measured\n//Old value for standard software 268.97; // (230V x 13) / (9V x 1.2) = 276.9 Calibration for UK AC-AC adapter 77DB-06-09 \n//const float Vcal= 276.9; //Calibrated by OpenEnergy Forum\n//const float Vcal= 260; // Calibration for EU AC-AC adapter 77DE-06-09 \n\nconst float phase_shift= 1.7;\nconst int no_of_samples= 1662; \nconst int no_of_half_wavelengths= 30;\nconst int timeout= 2000; //emonLib timeout \nconst int ACAC_DETECTION_LEVEL= 3000;\nconst byte min_pulsewidth= 110; // minimum width of interrupt pulse (default pulse output meters = 100ms)\nconst int TEMPERATURE_PRECISION= 11; //9 (93.8ms),10 (187.5ms) ,11 (375ms) or 12 (750ms) bits equal to resplution of 0.5C, 0.25C, 0.125C and 0.0625C\nconst byte MaxOnewire= 6; \n\n\n#define ASYNC_DELAY 375 // DS18B20 conversion delay - 9bit requres 95ms, 10bit 187ms, 11bit 375ms and 12bit resolution takes 750ms\n\n//-------------------------------------------------------------------------------------------------------------------------------------------\n//-------------------------------------------------------------------------------------------------------------------------------------------\n\n\n//----------------------------emonTx V3 hard-wired connections--------------------------------------------------------------------------------------------------------------- \nconst byte LEDpin= 6; // emonTx V3 LED\nconst byte DS18B20_PWR= 19; // DS18B20 Power\nconst byte DIP_switch1= 8; // Voltage selection 230 / 110 V AC (default switch off 230V) - switch off D8 is HIGH from internal pullup\nconst byte DIP_switch2= 9; // RF node ID (default no chance in node ID, switch on for nodeID -1) switch off D9 is HIGH from internal pullup\nconst byte battery_voltage_pin= 7; // Battery Voltage sample from 3 x AA\nconst byte pulse_countINT= 1; // INT 1 / Dig 3 Terminal Block / RJ45 Pulse counting pin(emonTx V3.4) - (INT0 / Dig2 emonTx V3.2)\nconst byte pulse_count_pin= 3; // INT 1 / Dig 3 Terminal Block / RJ45 Pulse counting pin(emonTx V3.4) - (INT0 / Dig2 emonTx V3.2)\n#define ONE_WIRE_BUS 5 // DS18B20 Data \n//-------------------------------------------------------------------------------------------------------------------------------------------\n\n//Setup DS128B20\nOneWire oneWire(ONE_WIRE_BUS);\nDallasTemperature sensors(&oneWire);\nbyte allAddress [MaxOnewire][8]; // 8 bytes per address\nbyte numSensors;\n//-------------------------------------------------------------------------------------------------------------------------------------------\n\n//-----------------------RFM12B / RFM69CW SETTINGS----------------------------------------------------------------------------------------------------\n#define RF_freq RF12_433MHZ // Frequency of RF69CW module can be RF12_433MHZ, RF12_868MHZ or RF12_915MHZ. You should use the one matching the module you have.\nbyte nodeID = 10; // emonTx RFM12B node ID\nconst int networkGroup = 210;\n \n// Note: Please update emonhub configuration guide on OEM wide packet structure change:\n// https://github.com/openenergymonitor/emonhub/blob/emon-pi/configuration.md\n/*\n[[9]]\n nodename = EMONTX9\n firmware =V130\n hardware = SC-EmonTx\n [[[rx]]]\n names = power1, power2, power3, power4, Vrms, pulse, Wh1, Wh2, Wh3, Wh4, RunHours1, RunHours2, RunHours3, RunHours4\n datacodes = h,h,h,h,h, L, l, l, l, l, L, L, L, L\n scales = 1,1,1,1,0.01, 1, 1, 1, 1, 1, 1, 1, 1, 1 \n units = W,W,W,W,V, p, Wh, Wh, Wh, Wh, sec, sec, sec, sec\n senddata = 0,0,0,0,0,0,1,0,0,0,1,0,0,0 */\n \ntypedef struct { \n int power1, power2, power3, power4, Vrms, temp[MaxOnewire]; \n unsigned long pulseCount; //pulse counter maintained\n long lAccPower1, lAccPower2, lAccPower3, lAccPower4; //accumulating power added\n unsigned long lRunHour1,lRunHour2, lRunHour3, lRunHour4; //accumulating running hours\n} PayloadTX; // create structure - a neat way of packaging data for RF comms\nPayloadTX emontx_package;\n\n//-------------------------------------------------------------------------------------------------------------------------------------------\n//-------------------------------------------------------------------------------------------------------------------------------------------\n\n//Random Variables \n//boolean settled = false;\nboolean CT1, CT2, CT3, CT4, ACAC, debug, DS18B20_STATUS; \nbyte CT_count=0;\nvolatile byte pulseCount = 0;\nunsigned long pulsetime=0; // Record time of interrupt pulse\nlong lWhCounter1,lWhCounter2,lWhCounter3,lWhCounter4;\n \nvoid setup()\n{ \n pinMode(LEDpin, OUTPUT); \n pinMode(DS18B20_PWR, OUTPUT); \n\n pinMode(pulse_count_pin, INPUT_PULLUP); // Set emonTx V3.4 interrupt pulse counting pin as input (Dig 3 / INT1)\n emontx_package.pulseCount=0; // Make sure pulse count starts at zero\n\n digitalWrite(LEDpin,HIGH); \n\n Serial.begin(9600);\n \n Serial.print(\"SC-EmonTx - Version \"); Serial.println(version*0.01);\n #if (RF69_COMPAT)\n Serial.println(\" RFM69CW\");\n #else\n Serial.println(\" RFM12B\");\n #endif\n Serial.println(\"www.scnordic.com\");\n \n //READ DIP SWITCH POSITIONS \n pinMode(DIP_switch1, INPUT_PULLUP);\n pinMode(DIP_switch2, INPUT_PULLUP);\n \n if ((digitalRead(DIP_switch1)==HIGH) && (digitalRead(DIP_switch2)==HIGH)) nodeID=9; // IF DIP switch 1 is switched on then subtract 1 from nodeID\n if ((digitalRead(DIP_switch1)==LOW) && (digitalRead(DIP_switch2)==HIGH)) nodeID=8; // IF DIP switch 1 is switched on then subtract 1 from nodeID\n if ((digitalRead(DIP_switch1)==HIGH) && (digitalRead(DIP_switch2)==LOW)) nodeID=7; // IF DIP switch 1 is switched on then subtract 1 from nodeID\n if ((digitalRead(DIP_switch1)==LOW) && (digitalRead(DIP_switch2)==LOW)) nodeID=6; // IF DIP switch 1 is switched on then subtract 1 from nodeID\n\n Serial.print(\"NodeID: \"); Serial.println(nodeID);\n Serial.print(\"Net: \"); Serial.println(networkGroup);\n Serial.print(\"TXPackage size: \"); Serial.println(sizeof(emontx_package));\n Serial.print(\"Reporting interval: \"); Serial.println(TIME_BETWEEN_READINGS);\n\n Serial.print(\"POST.....wait 10s\");\n delay(10);\n\n rf12_initialize(nodeID, RF_freq, networkGroup); // initialize RFM12B/rfm69CW\n \n rf12_sendWait(2);\n emontx_package.power1=0;\n \n if (analogRead(1) > 0) {CT1 = 1; CT_count++;} else CT1=0; // check to see if CT is connected to CT1 input, if so enable that channel\n if (analogRead(2) > 0) {CT2 = 1; CT_count++;} else CT2=0; // check to see if CT is connected to CT2 input, if so enable that channel\n if (analogRead(3) > 0) {CT3 = 1; CT_count++;} else CT3=0; // check to see if CT is connected to CT3 input, if so enable that channel\n if (analogRead(4) > 0) {CT4 = 1; CT_count++;} else CT4=0; // check to see if CT is connected to CT4 input, if so enable that channel\n \n if ( CT_count == 0) CT1=1; // If no CT's are connect ed CT1-4 then by default read from CT1\n\n // Quick check to see if there is a voltage waveform present on the ACAC Voltage input\n // Check consists of calculating the RMS from 100 samples of the voltage input.\n Sleepy::loseSomeTime(10000); //wait for settle\n digitalWrite(LEDpin,LOW); \n \n // Calculate if there is an ACAC adapter on analog input 0\n //double vrms = calc_rms(0,1780) * (Vcal * (3.3/1024) );\n double vrms = calc_rms(0,1780) * 0.87;\n if (vrms>90) ACAC = 1; else ACAC=0;\n \n if (ACAC) \n {\n for (int i=0; i<10; i++) // indicate AC has been detected by flashing LED 10 times\n { \n digitalWrite(LEDpin, HIGH); delay(200);\n digitalWrite(LEDpin, LOW); delay(300);\n }\n }\n else \n digitalWrite(LEDpin, HIGH); delay(2000); digitalWrite(LEDpin, LOW); // indicate DC power has been detected by turing LED on then off\n \n //################################################################################################################################\n //Setup and for presence of DS18B20\n //################################################################################################################################\n digitalWrite(DS18B20_PWR, HIGH); delay(100); \n sensors.begin();\n sensors.setWaitForConversion(false); // disable automatic temperature conversion to reduce time spent awake, conversion will be implemented manually in sleeping \n // http://harizanov.com/2013/07/optimizing-ds18b20-code-for-low-power-applications/ \n numSensors=(sensors.getDeviceCount());\n if (numSensors > MaxOnewire) numSensors=MaxOnewire; //Limit number of sensors to max number of sensors \n \n byte j=0; // search for one wire devices and\n // copy to device address arrays.\n while ((j < numSensors) && (oneWire.search(allAddress[j]))) j++;\n \n delay(500);\n digitalWrite(DS18B20_PWR, LOW);\n \n if (numSensors==0) DS18B20_STATUS=0; \n else DS18B20_STATUS=1;\n\n lWhCounter1 = lWhCounter2 = lWhCounter3 = lWhCounter4 = 0;\n\n \n //################################################################################################################################\n\n if (Serial) debug = 1; else debug=0; // if serial UART to USB is connected show debug O/P. If not then disable serial\n if (debug==1)\n {\n Serial.print(\"CT 1 Cal \"); Serial.println(Ical1);\n Serial.print(\"CT 2 Cal \"); Serial.println(Ical2);\n Serial.print(\"CT 3 Cal \"); Serial.println(Ical3);\n Serial.print(\"CT 4 Cal \"); Serial.println(Ical4);\n delay(1000);\n\n Serial.print(\"RMS Voltage on AC-AC is: ~\");\n Serial.print(vrms,0); Serial.println(\"V\");\n \n if (ACAC) {\n Serial.println(\"AC-AC detected - Real Power measure enabled\");\n Serial.println(\"assuming pwr from AC-AC (jumper closed)\");\n// if (USA==TRUE) Serial.println(\"USA mode active\"); \n Serial.print(\"Vcal: \"); Serial.println(Vcal);\n Serial.print(\"Phase Shift: \"); Serial.println(phase_shift);\n } else {\n Serial.println(\"AC-AC NOT detected - Apparent Pwr measure enabled\");\n Serial.print(\"Assuming VRMS: \"); Serial.print(Vrms); Serial.println(\"V\");\n Serial.println(\"Assuming power from batt / 5V USB - power save enabled\");\n } \n\n if (CT_count==0) {\n Serial.println(\"NO CT's detected\");\n } else {\n if (CT1) Serial.println(\"CT 1 detected\");\n if (CT2) Serial.println(\"CT 2 detected\");\n if (CT3) Serial.println(\"CT 3 detected\");\n if (CT4) Serial.println(\"CT 4 detected\");\n }\n \n if (DS18B20_STATUS==1) {\n Serial.print(\"Detected Temp Sensors: \"); \n Serial.println(numSensors);\n } else { \n Serial.println(\"No temperature sensor\");\n }\n \n #if (RF69_COMPAT)\n Serial.println(\"RFM69CW\");\n #else\n Serial.println(\"RFM12B\");\n #endif\n \n Serial.print(\"Node: \"); Serial.print(nodeID); \n Serial.print(\" Freq: \"); \n if (RF_freq == RF12_433MHZ) Serial.print(\"433Mhz\");\n if (RF_freq == RF12_868MHZ) Serial.print(\"868Mhz\");\n if (RF_freq == RF12_915MHZ) Serial.print(\"915Mhz\"); \n Serial.print(\" Network: \"); Serial.println(networkGroup);\n\n Serial.println(\"CT1-4 Vrms/BATT Pulse kwh1-4 Live1-4\");\n \n if (DS18B20_STATUS==1){Serial.print(\" Temperature 1-\"); Serial.print(numSensors);}\n //Serial.println(\"Temperature sensors are disabled in this SW \");\n \n delay(500); \n }\n else \n Serial.end();\n \n if (CT1) ct1.current(1, Ical1); // CT ADC channel 1, calibration. calibration (2000 turns / 22 Ohm burden resistor = 90.909)\n if (CT2) ct2.current(2, Ical2); // CT ADC channel 2, calibration.\n if (CT3) ct3.current(3, Ical3); // CT ADC channel 3, calibration. \n if (CT4) ct4.current(4, Ical4); // CT ADC channel 4, calibration. calibration (2000 turns / 120 Ohm burden resistor = 16.66) high accuracy @ low power - 4.5kW Max @ 240V \n \n if (ACAC)\n {\n if (CT1) ct1.voltage(0, Vcal, phase_shift); // ADC pin, Calibration, phase_shift\n if (CT2) ct2.voltage(0, Vcal, phase_shift); // ADC pin, Calibration, phase_shift\n if (CT3) ct3.voltage(0, Vcal, phase_shift); // ADC pin, Calibration, phase_shift\n if (CT4) ct4.voltage(0, Vcal, phase_shift); // ADC pin, Calibration, phase_shift\n }\n\n attachInterrupt(pulse_countINT, onPulse, FALLING); // Attach pulse counting interrupt pulse counting \n\n //Serial.println(\"+WDT\");\n //wdt_reset();\n //wdt_enable(WDTO_8S);\n \n for(byte j=0;j<MaxOnewire;j++) \n emontx_package.temp[j] = 3000; // If no temp sensors connected default to status code 3000 \n // will appear as 300 once multipled by 0.1 in emonhub\n \n} //end SETUP\n\nvoid loop()\n{\n unsigned long start = millis();\n\n // Set crc helpers\n if (emontx_package.lAccPower1 == 2147483647)\n emontx_package.lAccPower1 = 0;\n if (emontx_package.lAccPower2 == 2147483647)\n emontx_package.lAccPower2 = 0;\n if (emontx_package.lAccPower3 == 2147483647)\n emontx_package.lAccPower3 = 0;\n if (emontx_package.lAccPower4 == 2147483647)\n emontx_package.lAccPower4 = 0;\n if (emontx_package.lRunHour1 == 2147483647)\n emontx_package.lRunHour1 = 0;\n if (emontx_package.lRunHour2 == 2147483647)\n emontx_package.lRunHour2 = 0;\n if (emontx_package.lRunHour3 == 2147483647)\n emontx_package.lRunHour3 = 0;\n if (emontx_package.lRunHour4 == 2147483647)\n emontx_package.lRunHour4 = 0;\n\n //wdt_reset();\n \n if (ACAC) {\n delay(200); //if powering from AC-AC allow time for power supply to settle \n emontx_package.Vrms=0; //Set Vrms to zero, this will be overwirtten by CT 1-4\n }\n \n emontx_package.power1 = 1;\n emontx_package.power2 = 1;\n emontx_package.power3 = 1;\n emontx_package.power4 = 1;\n \n if (CT1) {\n if (ACAC) {\n ct1.calcVI(no_of_half_wavelengths,timeout); emontx_package.power1=ct1.realPower;\n emontx_package.Vrms=ct1.Vrms*100;\n } else {\n emontx_package.power1 = ct1.calcIrms(no_of_samples)*Vrms; // Calculate Apparent Power 1 1480 is number of sample\n }\n }\n \n if (CT2) {\n if (ACAC) {\n ct2.calcVI(no_of_half_wavelengths,timeout); \n emontx_package.power2=ct2.realPower;\n emontx_package.Vrms=ct2.Vrms*100;\n } else {\n emontx_package.power2 = ct2.calcIrms(no_of_samples)*Vrms; // Calculate Apparent Power 1 1480 is number of samples\n }\n }\n\n if (CT3) {\n if (ACAC) {\n ct3.calcVI(no_of_half_wavelengths,timeout); \n emontx_package.power3=ct3.realPower;\n emontx_package.Vrms=ct3.Vrms*100;\n } else {\n emontx_package.power3 = ct3.calcIrms(no_of_samples)*Vrms; // Calculate Apparent Power 1 1480 is number of samples\n }\n }\n \n if (CT4) {\n if (ACAC) {\n ct4.calcVI(no_of_half_wavelengths,timeout); \n emontx_package.power4=ct4.realPower;\n emontx_package.Vrms=ct4.Vrms*100;\n } else {\n emontx_package.power4 = ct4.calcIrms(no_of_samples)*Vrms; // Calculate Apparent Power 1 1480 is number of samples\n }\n }\n \n if (!ACAC){ // read battery voltage if powered by DC\n int battery_voltage=analogRead(battery_voltage_pin) * 0.681322727; // 6.6V battery = 3.3V input = 1024 ADC\n emontx_package.Vrms= battery_voltage;\n }\n \n if (DS18B20_STATUS==1) \n {\n digitalWrite(DS18B20_PWR, HIGH); \n Sleepy::loseSomeTime(50); \n for(int j=0;j<numSensors;j++) \n sensors.setResolution(allAddress[j], TEMPERATURE_PRECISION); // and set the a to d conversion resolution of each.\n sensors.requestTemperatures();\n Sleepy::loseSomeTime(ASYNC_DELAY); // Must wait for conversion, since we use ASYNC mode \n for(byte j=0;j<numSensors;j++) \n emontx_package.temp[j]=get_temperature(j); \n digitalWrite(DS18B20_PWR, LOW);\n }\n \n if (pulseCount) // if the ISR has counted some pulses, update the total count\n {\n cli(); // Disable interrupt just in case pulse comes in while we are updating the count\n emontx_package.pulseCount += pulseCount;\n pulseCount = 0;\n sei(); // Re-enable interrupts\n }\n\n // If power is less than zero, turn algebraic sign\n if (emontx_package.power1 < 0)\n emontx_package.power1 = emontx_package.power1 * -1;\n if (emontx_package.power2 < 0)\n emontx_package.power2 = emontx_package.power2 * -1;\n if (emontx_package.power3 < 0)\n emontx_package.power3 = emontx_package.power3 * -1;\n if (emontx_package.power4 < 0)\n emontx_package.power4 = emontx_package.power4 * -1;\n \n lWhCounter1 += emontx_package.power1;\n lWhCounter2 += emontx_package.power2;\n lWhCounter3 += emontx_package.power3;\n lWhCounter4 += emontx_package.power4;\n\n if(emontx_package.power1 > 20)\n emontx_package.lRunHour1 += TIME_BETWEEN_READINGS;\n if(emontx_package.power2 > 20)\n emontx_package.lRunHour2 += TIME_BETWEEN_READINGS;\n if(emontx_package.power3 > 20)\n emontx_package.lRunHour3 += TIME_BETWEEN_READINGS;\n if(emontx_package.power4 > 20)\n emontx_package.lRunHour4 += TIME_BETWEEN_READINGS;\n\n int iDelta;\n\n iDelta = lWhCounter4 / (3600 / TIME_BETWEEN_READINGS);\n emontx_package.lAccPower4 += iDelta;\n lWhCounter4 -= (iDelta * (3600 / TIME_BETWEEN_READINGS));\n\n iDelta = lWhCounter3 / (3600 / TIME_BETWEEN_READINGS);\n emontx_package.lAccPower3 += iDelta;\n lWhCounter3 -= (iDelta * (3600 / TIME_BETWEEN_READINGS));\n\n iDelta = lWhCounter2 / (3600 / TIME_BETWEEN_READINGS);\n emontx_package.lAccPower2 += iDelta;\n lWhCounter2 -= (iDelta * (3600 / TIME_BETWEEN_READINGS));\n\n iDelta = lWhCounter1 / (3600 / TIME_BETWEEN_READINGS);\n emontx_package.lAccPower1 += iDelta;\n lWhCounter1 -= (iDelta * (3600 / TIME_BETWEEN_READINGS));\n\n if (debug==1) {\n Serial.print(emontx_package.power1); Serial.print(\" \");\n Serial.print(emontx_package.power2); Serial.print(\" \");\n Serial.print(emontx_package.power3); Serial.print(\" \");\n Serial.print(emontx_package.power4); Serial.print(\" \");\n Serial.print(emontx_package.Vrms); \n \n Serial.print(\"v C:\");\n Serial.print(emontx_package.pulseCount); Serial.print(\" \");\n Serial.print(emontx_package.lAccPower1); Serial.print(\".\"); Serial.print(lWhCounter1); Serial.print(\" \");\n Serial.print(emontx_package.lAccPower2); Serial.print(\" \");\n Serial.print(emontx_package.lAccPower3); Serial.print(\" \");\n\n Serial.print(\" L: \"); Serial.print(emontx_package.lRunHour1); \n Serial.print(\"-\"); Serial.print(emontx_package.lRunHour2); \n Serial.print(\"-\"); Serial.print(emontx_package.lRunHour3); \n Serial.print(\"-\"); Serial.println(emontx_package.lRunHour4); \n\n if (DS18B20_STATUS==1){\n for(byte j=0;j<numSensors;j++){\n Serial.print(emontx_package.temp[j]);\n Serial.print(\" \");\n } \n }\n delay(50);\n } \n\n // Set crc helpers\n if (emontx_package.lAccPower1 == 0)\n emontx_package.lAccPower1 = 2147483647;\n if (emontx_package.lAccPower2 == 0)\n emontx_package.lAccPower2 = 2147483647;\n if (emontx_package.lAccPower3 == 0)\n emontx_package.lAccPower3 = 2147483647;\n if (emontx_package.lAccPower4 == 0)\n emontx_package.lAccPower4 = 2147483647;\n if (emontx_package.lRunHour1 == 0)\n emontx_package.lRunHour1 = 2147483647;\n if (emontx_package.lRunHour2 == 0)\n emontx_package.lRunHour2 = 2147483647;\n if (emontx_package.lRunHour3 == 0)\n emontx_package.lRunHour3 = 2147483647;\n if (emontx_package.lRunHour4 == 0)\n emontx_package.lRunHour4 = 2147483647;\n\n \n if (ACAC) {digitalWrite(LEDpin, HIGH); delay(200); digitalWrite(LEDpin, LOW);} // flash LED if powered by AC\n else delay(200); \n \n send_rf_data(); // *SEND RF DATA* - see emontx_lib\n \n unsigned long runtime = millis() - start;\n unsigned long sleeptime = (TIME_BETWEEN_READINGS*1000) - runtime - 100;\n \n if (ACAC) { // If powered by AC-AC adaper (mains power) then delay instead of sleep\n delay(sleeptime);\n } else { // if powered by battery then sleep rather than dealy and disable LED to lower energy consumption \n // lose an additional 500ms here (measured timing)\n Sleepy::loseSomeTime(sleeptime-500); // sleep or delay in seconds \n }\n \n // send data only when you receive data:\n if (Serial.available() > 0) {\n int incomingByte = 0;\n // read the incoming byte:\n incomingByte = Serial.read();\n\n // say what you got:\n Serial.print(\"RX: \");\n Serial.println(incomingByte, DEC);\n } \n}\n\nvoid send_rf_data()\n{\n rf12_sleep(RF12_WAKEUP);\n rf12_sendNow(0, &emontx_package, sizeof emontx_package); //send data via RFM12B using new rf12_sendNow wrapper\n rf12_sendWait(2);\n \n if (!ACAC) \n rf12_sleep(RF12_SLEEP); //if powred by battery then put the RF module into sleep inbetween readings \n}\n\n\ndouble calc_rms(int pin, int samples)\n{\n unsigned long sum = 0;\n for (int i=0; i<samples; i++) // 178 samples takes about 20ms\n {\n int raw = (analogRead(0)-512);\n sum += (unsigned long)raw * raw;\n }\n double rms = sqrt((double)sum / samples);\n return rms;\n}\n\n// The interrupt routine - runs each time a falling edge of a pulse is detected\nvoid onPulse() \n{ \n if ( (millis() - pulsetime) > min_pulsewidth) {\n pulseCount++;\t\t\t\t\t//calculate wh elapsed from time between pulses\n }\n pulsetime=millis(); \t\n}\n\n\nint get_temperature(byte sensor) \n{\n float temp=(sensors.getTempC(allAddress[sensor]));\n if ((temp<125.0) && (temp>-55.0)) return(temp*10); //if reading is within range for the sensor convert float to int ready to send via RF\n}\n\n\n\n" }, { "alpha_fraction": 0.7013888955116272, "alphanum_fraction": 0.7100694179534912, "avg_line_length": 31.91428565979004, "blob_id": "4a3363b30c22fbc12209a055233311dd63d6bb17", "content_id": "fb8d52ddfcb311b1e955580f85d7e57e6a579d0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 79, "num_lines": 35, "path": "/gridplatform/global_datasources/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom django_countries.fields import CountryField\n\nfrom gridplatform.datasources.models import DataSource\n\n\nclass GlobalDataSource(DataSource):\n \"\"\"\n Specialization of :class:`~gridplatform.datasources.models.DataSource` that\n is globally accessible.\n\n :ivar name: The name.\n :ivar app_label: String used identify the app that feeds data into this\n global data source.\n :ivar codename: Application specific string used to help identify this\n global data source.\n :ivar country: A country code for the country in which this global data\n source applies.\n \"\"\"\n name = models.CharField(_('name'), max_length=120)\n app_label = models.CharField(max_length=100, editable=False)\n codename = models.CharField(max_length=100, editable=False)\n country = CountryField(editable=False)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n unique_together = ('app_label', 'codename', 'country')\n" }, { "alpha_fraction": 0.7251381278038025, "alphanum_fraction": 0.7265193462371826, "avg_line_length": 33.47618865966797, "blob_id": "4c6457fc1b9658fe9747db633a4517ba5547b79a", "content_id": "5ae820e6a70a6a86fb88a81224229fc065ce0881", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 724, "license_type": "no_license", "max_line_length": 115, "num_lines": 21, "path": "/gridplatform/global_datasources/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.datasources.serializers import DataSourceSerializerBase\nfrom gridplatform.datasources.serializers import RawDataWithUnitSerializer as RawDataWithUnitSerializerBase # noqa\n\nfrom gridplatform.rest import serializers\nfrom .models import GlobalDataSource\n\n\nclass GlobalDataSourceSerializer(DataSourceSerializerBase):\n raw_data = serializers.HyperlinkedIdentityField(\n view_name='api:datasources:rawdata-list')\n\n class Meta:\n model = GlobalDataSource\n fields = (\n 'url', 'id', 'name', 'unit', 'display_unit', 'country',\n 'hardware_id', 'raw_data'\n )\n" }, { "alpha_fraction": 0.5389569401741028, "alphanum_fraction": 0.548382043838501, "avg_line_length": 32.15625, "blob_id": "44cdedd7c20988260e81d74aa68e7cb09ae410be", "content_id": "755b5c50c08bf75dc068f6a7a8a8e02ca2a58b31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6366, "license_type": "no_license", "max_line_length": 129, "num_lines": 192, "path": "/scnordic-bridge/send_measurements.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import mysql.connector\nimport redis\nimport datetime\nimport time\nimport requests\nimport sqlite3\nimport unicodedata\n\nfrom configobj import ConfigObj\nfrom requests.auth import AuthBase\n\n\nclass TokenAuth(AuthBase):\n \"\"\"Attaches HTTP Token Authentication to the given Request object.\"\"\"\n\n def __init__(self, token):\n # setup any auth-related data here\n self.token = token\n\n def __call__(self, r):\n # modify and return the request\n r.headers['Authorization'] = \"token %s\" % self.token\n return r\n\n\nclass RequestHandler():\n def __init__(self):\n api_key = ''\n api_base_url = 'https://test.codewizards.dk/api/v3'\n with open('/home/pi/data/emonhub.conf') as f:\n for line in f:\n if api_key == '':\n api_key = line.strip().replace('# ', '')\n else:\n api_base_url = line.strip().replace(\"# \", \"\")\n break\n\n self.auth = TokenAuth(api_key)\n self.base_url = api_base_url\n self.config = ConfigObj('/tmp/endpoint.cache')\n\n def fetch_endpoint(self, name):\n payload = {'hardware_id': name}\n try:\n r = requests.get('%s/datasources/customer_datasources/' % self.base_url, auth=self.auth, params=payload,\n timeout=1)\n except:\n return None\n response = {}\n\n if r.status_code == requests.codes.ok:\n response = r.json()\n\n if response['count'] == 1:\n self.config[name] = {\n 'timestamp': time.time(),\n 'endpoint': response['results'][0]['rawData']\n }\n self.config.write()\n return response['results'][0]['rawData']\n else:\n return None\n else:\n return None\n\n def get_endpoint(self, name):\n try:\n cached = self.config[name]\n\n if (datetime.datetime.fromtimestamp(\n float(cached['timestamp'])) > datetime.datetime.now() - datetime.timedelta(minutes=10)):\n return cached['endpoint']\n else:\n return self.fetch_endpoint(name)\n except KeyError:\n return self.fetch_endpoint(name)\n\n # TODO: Handle error logging\n def send_measurement(self, measurement):\n endpoint = self.get_endpoint(measurement['name'])\n\n if endpoint:\n payload = {\n \"timestamp\": measurement['timestamp'].strftime(\"%Y-%m-%dT%H:%M:%S\"),\n }\n if measurement['unit'] == 'watthour':\n payload['value'] = int(float(measurement['value']) * 1000)\n payload['unit'] = \"milliwatt*hour\"\n elif measurement['unit'] == 'celcius':\n payload['value'] = int((float(measurement['value']) - 273.15) * 1000)\n payload['unit'] = \"millikelvin\"\n else:\n # If no tag is set, just return and throw it away\n return 200\n try:\n r = requests.post(endpoint, auth=self.auth, data=payload)\n return r.status_code\n except:\n return 500\n return 500\n\n\nclass MySQLHandler():\n def get_feeds(self):\n feeds = []\n cnx = mysql.connector.connect(user=\"root\", password=\"raspberry\", database=\"emoncms\")\n cursor = cnx.cursor()\n cursor.execute(\"SELECT id, name, tag FROM feeds\")\n\n for feed in cursor:\n feeds.append({'id': feed[0], 'name': feed[1], 'tag': feed[2]})\n\n return feeds\n\n\n# TODO: Send all when enmonpi has been offline\n# class FINAReader():\n#\tdef read(feeds, ):\n#\t\tp = pyfina('/home/pi')\n\nclass RedisHandler():\n def __init__(self):\n self.redis = redis.StrictRedis(host='localhost', port=6379, db=0)\n\n def get_data(self, feed_id):\n return self.redis.hmget('feed:timevalue:%i' % feed_id, ['time', 'value'])\n\n\nclass SqLiteHandler():\n def __init__(self):\n conn = sqlite3.connect('/tmp/measurements.db')\n c = conn.cursor()\n c.execute(\n 'CREATE TABLE IF NOT EXISTS measurements (id INTEGER PRIMARY KEY, name TEXT, timestamp INT, value REAL, unit TEXT);')\n conn.close()\n\n def save_measurement(self, name, timestamp, value, unit):\n conn = sqlite3.connect('/tmp/measurements.db')\n c = conn.cursor()\n c.execute('SELECT id FROM measurements WHERE name=? AND timestamp=? AND value=? AND unit=?',\n (name, timestamp, value, unit,))\n if not c.fetchone():\n c.execute('INSERT INTO measurements (name, timestamp, value, unit) VALUES (?, ?, ?, ?)',\n (name, timestamp, value, unit,))\n conn.commit()\n conn.close()\n\n def fetch_measurements(self):\n conn = sqlite3.connect('/tmp/measurements.db')\n c = conn.cursor()\n c.execute('SELECT * FROM measurements')\n measurements = c.fetchall()\n conn.close()\n\n return measurements\n\n def delete_measurement(self, id):\n conn = sqlite3.connect('/tmp/measurements.db')\n c = conn.cursor()\n c.execute('DELETE FROM measurements WHERE id=?', (id,))\n conn.commit()\n conn.close()\n\n\nif __name__ == \"__main__\":\n myhandler = MySQLHandler()\n redishandler = RedisHandler()\n request = RequestHandler()\n feeds = myhandler.get_feeds()\n sqlite = SqLiteHandler()\n\n for feed in feeds:\n data = redishandler.get_data(feed['id'])\n if data[0] == '':\n continue\n\n timestamp = datetime.datetime.fromtimestamp(float(data[0]))\n value = data[1]\n sent = request.send_measurement(\n {'name': feed['name'], 'timestamp': timestamp, 'value': value, 'unit': feed['tag']})\n\n if sent in (500, 502):\n sqlite.save_measurement(feed['name'], data[0], value, feed['tag'])\n\n else:\n measurements = sqlite.fetch_measurements()\n for measurement in measurements:\n worked = request.send_measurement(\n {'name': measurement[1], 'timestamp': datetime.datetime.fromtimestamp(float(measurement[2])),\n 'value': measurement[3], 'unit': measurement[4]})\n if not worked == 500:\n sqlite.delete_measurement(measurement[0])\n" }, { "alpha_fraction": 0.6134106516838074, "alphanum_fraction": 0.6149706244468689, "avg_line_length": 36.96841049194336, "blob_id": "3c526bbac275733c617377fb2b8b695da1339a36", "content_id": "b9c10b5f5678f637fec17046b5997604ff510df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 38462, "license_type": "no_license", "max_line_length": 79, "num_lines": 1013, "path": "/legacy/rules/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nDjango model for rules.\n\nThere are two sides of rules:\n\n - The user rules, which are given by the user, and are\n declarative and generic. User rules are stored in the\n database, and considered an internal part of the L{Rule} Django\n model.\n\n - The agent rules, which are generated from user rules, price\n tables and other forms of indexes, and interpreted by agents.\n These are not stored in the database, but generated on the fly\n as they are needed, see also L{Rule.generate_rules()}.\n These are defined by the L{AgentRule} class.\n\"\"\"\n\nimport contextlib\nimport operator as python_operator\nimport datetime\nimport urllib\nimport math\nimport urllib2\nimport warnings\nfrom smtplib import SMTPException\n\nfrom django.conf import settings\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core import mail\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom timezones2.models import TimeZoneField\n\nfrom gridplatform.customers.models import Customer\nfrom legacy.devices.models import Meter\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom legacy.ipc import agentserver\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.trackuser import get_timezone\nfrom gridplatform.utils import units\nfrom gridplatform.utils.fields import DurationField\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom . import UserRuleIntegrityError\n\n\nTURN_OFF = 0\nTURN_ON = 1\n\n\nclass UserRule(EncryptedModel):\n \"\"\"\n Model representing rules.\n\n Rules controls relays and sends out warnings to users, usually\n with the goal to minimize energy expenses. This is done by\n monitoring various meters, and processing energy price forecasts,\n and similar indexes.\n\n The user defines user rules, which are the declarative, generic\n and unprocessed form of rules.\n\n User rules are processed against energy price forecasts and\n similar indexes to generate agent rules. This is done by the\n L{generate_rules()} method.\n\n Each rule is specified in terms of weekdays and local time, to allow\n specification of control rules corresponding to relevant employee work\n schedules.\n\n A rule is I{active} in time intervals specified through weekdays,\n L{DateException} objects, L{from_time} and L{to_time}, as well as the\n L{enabled} switch. During periods while a rule is active, it will,\n depending on the rule type and specific conditions, have zero or more\n periods of I{activity}. When a period of I{activity} begins, a number of\n C{INITIAL} L{Action}s are taken, and when the period of I{activity} ends, a\n number of C{FINAL} L{Action}s are taken.\n\n @ivar customer: A customer which the rule is bound to.\n @ivar name: A human-readable name.\n @ivar enabled: Declares whether this rule should be processed/acted on.\n @ivar timezone: Timezone used ot interpret L{from_time} and L{to_time}.\n\n @groups Weekdays: *day\n @ivar monday: Whether this rule should be enabled on mondays.\n @ivar tuesday: Whether this rule should be enabled on tuesdays.\n @ivar wednesday: Whether this rule should be enabled on wednesdays.\n @ivar thursday: Whether this rule should be enabled on thursdays.\n @ivar friday: Whether this rule should be enabled on fridays.\n @ivar saturday: Whether this rule should be enabled on saturdays.\n @ivar sunday: Whether this rule should be enabled on sundays.\n\n @ivar from_time: Local time when the rule becomes enabled. The specified\n weekdays are the days where the rule becomes enabled at C{from_time}.\n @ivar to_time: Local time when the rule becomes disabled. If C{to_time <=\n from_time}, this specifies a timestamp on the following day.\n\n @ivar content_type: Actual type of the rule; otherwise not available when\n initialising objects from the base UserRule database table.\n @ivar content_object: Descriptor for obtaining a corresponding object of\n the appropriate subclass.\n\n @attention: We assume that only one level of subclasses of this will be\n used. If/when this is not the case, the code in C{__init__} and C{save}\n may need to be updated.\n \"\"\"\n\n customer = models.ForeignKey(\n Customer, on_delete=models.PROTECT,\n editable=False, blank=True, default=get_customer)\n name = EncryptedCharField(_('name'), max_length=50, blank=False)\n enabled = models.BooleanField(_('enabled'), default=True)\n timezone = TimeZoneField(_('timezone'), default=get_timezone)\n\n # active on days:\n monday = models.BooleanField(_('Monday'), default=True)\n tuesday = models.BooleanField(_('Tuesday'), default=True)\n wednesday = models.BooleanField(_('Wednesday'), default=True)\n thursday = models.BooleanField(_('Thursday'), default=True)\n friday = models.BooleanField(_('Friday'), default=True)\n saturday = models.BooleanField(_('Saturday'), default=False)\n sunday = models.BooleanField(_('Sunday'), default=False)\n # in interval:\n # (to_time <= from_time implies \"on the following day\")\n # @bug: Now these are insane default values.\n from_time = models.TimeField(_('from time'), default=datetime.time())\n to_time = models.TimeField(_('to time'), default=datetime.time())\n\n # Use generic relation to indicate \"concrete\" UserRule subclass.\n # content_type indicates type; content_object is purely a convenience\n # wrapper for the object lookup; a custom enumeration would hardly reduce\n # the storage-overhead. (A custom enumeration might be stored as a shorter\n # integer type, depending on DB-backend; not worth the effort.)\n\n content_type = models.ForeignKey(\n ContentType, on_delete=models.CASCADE, editable=False)\n content_object = generic.GenericForeignKey('content_type', 'id')\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('user rule')\n verbose_name_plural = _('user rules')\n ordering = ['-to_time', '-from_time', '-enabled', 'id']\n\n def __unicode__(self):\n return unicode(self.name_plain or self.name)\n\n def __init__(self, *args, **kwargs):\n super(UserRule, self).__init__(*args, **kwargs)\n if self.__class__ != UserRule and \\\n not hasattr(self, '_content_object_cache'):\n # The object is already of the subclass; avoid loading it again\n # when accessing content_object.\n # We check for _content_object_cache, as it may have been set\n # during a callback from the pre_init or post_init signals --- in\n # that case, we won't overwrite it.\n self._content_object_cache = self\n\n def save(self, *args, **kwargs):\n if not self.id:\n # Initial save/creation *must* be of subclass. (Later, properties\n # like name may be modified with knowledge of/access to the\n # concrete subclass...)\n assert self.__class__ != UserRule\n self.content_type = ContentType.objects.get_for_model(self)\n super(UserRule, self).save(*args, **kwargs)\n\n def clean(self):\n \"\"\"\n Basic validation: Check that the time available between L{from_time}\n and L{to_time} is enough for the activity_duration.\n\n @raise ValidationError: if the time available is shortare than the time\n required.\n\n @note: Does not check wrt. timezone. Rules that are problematic only\n on the switch to DST are not caught; rules that are OK only on the\n switch from DST are still considered in error.\n \"\"\"\n return None\n available_time = self.to_time - self.from_time\n if available_time <= datetime.timedelta():\n # from_time <= to_time; i.e. to_time should be taken to be next day\n available_time += datetime.timedelta(days=1)\n if available_time < self.activity_duration:\n raise ValidationError(\n _(\"User rule is self-contradictory. \"\n \"The earliest usage end is after interval end\"))\n\n def get_encryption_id(self):\n \"\"\"\n L{Rule} implementation of L{EncryptedModel.get_encryption_id()}. The\n C{OwnerModelClass} of the L{Rule} class is L{Customer}.\n \"\"\"\n return (Customer, self.customer_id)\n\n def satisfies_search(self, substring):\n \"\"\"\n Check if this L{Rule} matches a given substring.\n\n @param substring: The given substring.\n\n @return: Returns C{True} if the C{substring} is matched by\n this L{Rule}, C{False} otherwise.\n \"\"\"\n return substring.lower() in unicode(self.name_plain).lower()\n\n def __enabled_at_date(self, date):\n \"\"\"\n Checks if this Rule applies to a given date.\n\n @param date: the given date.\n\n @return: Returns C{True} if the rule applies to the given\n date, C{False} otherwise.\n \"\"\"\n enabled_weekdays = [\n self.monday, self.tuesday, self.wednesday, self.thursday,\n self.friday, self.saturday, self.sunday]\n return (enabled_weekdays[date.weekday()] and\n not self.dateexception_set.filter(\n from_date__lte=date, to_date__gte=date).exists())\n\n def generate_rules(self, begin_timestamp, days=1):\n \"\"\"\n Generate list of rules that implement the user rule of this Rule\n object.\n\n @param begin_timestamp: The first date to generate agent and engine\n rules for. This is required to be a datetime object, because dates\n should be in the timezone of this rule.\n\n @param days: The number of days to generate rules for.\n\n @raise UserRuleIntegrityError: if for one of the dates, the\n rule can't be run even though it was supposed to.\n \"\"\"\n result = []\n\n assert isinstance(begin_timestamp, datetime.datetime)\n tz = self.timezone\n begin_date = tz.normalize(begin_timestamp.astimezone(tz)).date()\n\n # the rule spans more than one date\n if self.from_time >= self.to_time:\n # Intention is to return rules that start to run, or are already\n # running at the given date, rather than the original\n # implementation, which returned rules that should start run on the\n # given date.\n days += 1\n begin_date -= datetime.timedelta(days=1)\n\n dates = [begin_date + datetime.timedelta(days=i) for i in range(days)]\n dates = filter(self.__enabled_at_date, dates)\n for date in dates:\n interval_begin = self.timezone.localize(\n datetime.datetime.combine(\n date,\n self.from_time))\n interval_end = self.timezone.localize(\n datetime.datetime.combine(\n date,\n self.to_time))\n if interval_end <= interval_begin:\n interval_end += RelativeTimeDelta(days=1)\n result.extend(self.content_object._day_rules(interval_begin,\n interval_end))\n return result\n\n\nclass RuleCustomerBoundManager(CustomerBoundManager):\n _field = 'rule__customer'\n\n\nclass DateException(models.Model):\n \"\"\"\n Specific date range that a rule should I{not} apply to.\n\n @ivar rule: The L{Rule} this exception is specified for.\n @ivar from_date: The first date the exception is in effect for.\n @ivar to_date: The last date the exception is in effect for.\n \"\"\"\n rule = models.ForeignKey(\n UserRule, on_delete=models.CASCADE, editable=False)\n from_date = models.DateField(_('from date'))\n to_date = models.DateField(_('to date'))\n\n objects = RuleCustomerBoundManager()\n\n class Meta:\n verbose_name = _('date exception')\n verbose_name_plural = _('date exceptions')\n ordering = ['-to_date', '-from_date', 'id']\n\n def __unicode__(self):\n return u'%(rule_id)s; %(from)s - %(to)s' % {\n 'rule_id': self.rule_id,\n 'from': self.from_date,\n 'to': self.to_date}\n\n\nclass Action(models.Model):\n \"\"\"\n Base class for rule actions.\n\n @cvar INITIAL: Initial action.\n @cvar FINAL: Final action.\n @cvar EXECUTION_TIME_CHOICES: Initial/final choice specification for\n Django.\n\n @ivar rule: The L{Rule} this exception is specified for.\n @ivar execution_time: Choice between C{INITIAL} and C{FINAL} execution.\n \"\"\"\n INITIAL = 0\n FINAL = 1\n EXECUTION_TIME_CHOICES = (\n (INITIAL, _('initial')),\n (FINAL, _('final')))\n rule = models.ForeignKey(UserRule, on_delete=models.CASCADE)\n execution_time = models.PositiveSmallIntegerField(\n _('execution time'), choices=EXECUTION_TIME_CHOICES)\n\n objects = RuleCustomerBoundManager()\n\n class Meta:\n abstract = True\n verbose_name = _('action')\n verbose_name_plural = _('actions')\n\n def execute(self):\n \"\"\"\n Executes this action.\n\n @raise NotImplementedError: This exception is raised, if the\n C{execute()} method is not implemented in the concrete\n C{Action} subclass.\n \"\"\"\n raise NotImplementedError(\"Subclass must reimplement this method\")\n\n\nclass RelayAction(Action):\n \"\"\"\n Rule action for setting the state of a relay.\n\n @cvar RELAY_ACTION_CHOICES: On/off choice specification for Django.\n\n @ivar meter: The meter to switch relay on.\n @ivar relay_action: Choice between C{TURN_ON} and C{TURN_OFF}.\n \"\"\"\n RELAY_ACTION_CHOICES = (\n (TURN_ON, _('turn on')),\n (TURN_OFF, _('turn off')))\n meter = models.ForeignKey(Meter, on_delete=models.PROTECT)\n relay_action = models.PositiveSmallIntegerField(\n _('relay action'), choices=RELAY_ACTION_CHOICES)\n\n class Meta:\n verbose_name = _('relay action')\n verbose_name_plural = _('relay actions')\n ordering = ['id']\n\n def __unicode__(self):\n \"\"\"\n @return: Return localized human readable representation of\n this object.\n \"\"\"\n if self.relay_action == TURN_ON:\n return _(u\"set relay on {meter} to on\").format(\n meter=unicode(self.meter))\n else:\n assert(self.relay_action == TURN_OFF)\n return _(u\"set relay on {meter} to off\").format(\n meter=unicode(self.meter))\n\n def execute(self):\n \"\"\"\n Executes this action.\n \"\"\"\n agentserver.relay_state(\n self.meter.agent.mac,\n [(self.meter.connection_type, self.meter.manufactoring_id)],\n self.relay_action)\n\n\nclass EmailAction(Action):\n \"\"\"\n Rule action for sending an email.\n\n @ivar recipient: Receiver e-mail address.\n @ivar message: Mail text to send.\n \"\"\"\n recipient = models.EmailField(_('recipient'))\n message = models.TextField(_('message'))\n\n class Meta:\n verbose_name = _('email action')\n verbose_name_plural = _('email actions')\n ordering = ['message', 'id']\n\n def __unicode__(self):\n \"\"\"\n @return: Return localized human readable representation of\n this object.\n \"\"\"\n return _(u\"send email '{message}' to '{recipient}'\").format(\n message=self.message, recipient=self.recipient)\n\n def execute(self):\n \"\"\"\n Executes this action.\n \"\"\"\n try:\n mail.send_mail(\"Email notification from GridEngine\",\n self.message,\n settings.SITE_MAIL_ADDRESS,\n [self.recipient],\n fail_silently=False)\n except SMTPException, e:\n warnings.warn(\n \"EmailAction.execute() (%s) failed with message %s\" %\n (self, e),\n SMTPException)\n\n\nclass PhoneAction(Action):\n \"\"\"\n Rule action for sending an SMS.\n\n @ivar phone_number: Receiver phone number.\n @ivar message: SMS text to send.\n \"\"\"\n\n # Concatenated message lenght is acually 153 chars,\n # but we taking special characters into consideration, which takes\n # two bytes instead of just one.\n CONCATENATED_MESSAGE_LENGHT = 140\n\n phone_number = models.CharField(_('phone number'), max_length=20)\n message = models.TextField(_('message'))\n\n class Meta:\n verbose_name = _('phone action')\n verbose_name_plural = _('phone actions')\n ordering = ['phone_number', 'message', 'id']\n\n def __unicode__(self):\n \"\"\"\n @return: Return localized human readable representation of\n this object.\n \"\"\"\n return _(u\"send text '{message}' to '{phone_number}'\").format(\n message=self.message, phone_number=self.phone_number)\n\n def execute(self):\n \"\"\"\n Executes this action.\n \"\"\"\n message = self.message.encode('iso8859-1')\n\n # Figure out have many parts we have to split up\n # the message. Rounding up to int.\n concat = int(\n math.ceil(len(message) / float(self.CONCATENATED_MESSAGE_LENGHT)))\n\n url = \"http://api.clickatell.com/http/sendmsg?%s\" % (\n urllib.urlencode([\n (\"user\", \"gridmanager\"),\n (\"password\", \"1GridManager2Go\"),\n (\"api_id\", \"3191312\"),\n (\"to\", self.phone_number),\n (\"text\", message),\n (\"concat\", concat)],))\n\n with contextlib.closing(urllib2.urlopen(url)) as ud:\n result = ud.read()\n if 'ID: ' not in result:\n warnings.warn(\n 'PhoneAction.execute() (%s) failed: url=\"%s\", '\n 'response=\"%s\"' % (self, url, result))\n\n\nclass MinimizeRule(UserRule):\n \"\"\"\n Rule taking action when a specified index has its minimal value(s) within\n its I{active} interval. This can lead to one or more periods of\n I{activity}.\n\n @ivar consecutive: Whether a single consecutive activity interval is\n required, or a sequence of non-consecutive intervals may be used.\n @ivar activity_duration: The total duration of activity required.\n @ivar index: The L{Index} to minimise with regards to.\n \"\"\"\n consecutive = models.BooleanField(_('Consecutive'))\n activity_duration = DurationField(_('duration of activity'))\n index = models.ForeignKey(\n 'indexes.Index', on_delete=models.PROTECT,\n limit_choices_to=~models.Q(\n role__in=[DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n DataRoleField.CO2_QUOTIENT]))\n\n class Meta:\n verbose_name = _('minimize rule')\n verbose_name_plural = _('minimize rules')\n # inherit ordering from UserRule\n\n def _day_intervals(self, from_time, to_time):\n if (to_time - from_time) < self.activity_duration:\n raise UserRuleIntegrityError(\n \"User rule is self-contradictory. \"\n \"The earliest usage end is after interval end\")\n\n if self.consecutive:\n start_time = self.index.minimize_contiguous(\n from_timestamp=from_time,\n to_timestamp=to_time,\n duration=self.activity_duration)\n assert(start_time.tzinfo is not None)\n return [(start_time,\n start_time + self.activity_duration)]\n else:\n return self.index.minimize_noncontiguous(\n from_timestamp=from_time,\n to_timestamp=to_time,\n duration=self.activity_duration)\n\n def _day_rules(self, interval_begin, interval_end):\n result = []\n # intervals is iterated multiple times, and therefore needs to be a\n # list.\n intervals = list(self._day_intervals(interval_begin, interval_end))\n assert intervals is not None\n for from_time, to_time in intervals:\n result.extend([\n AgentRule(from_time, initial_action)\n for initial_action\n in self.relayaction_set.filter(\n execution_time=Action.INITIAL)])\n result.extend([\n AgentRule(to_time, final_action)\n for final_action\n in self.relayaction_set.filter(\n execution_time=Action.FINAL)])\n result.append(EngineRule(intervals, [], self, False))\n return result\n\n\nclass TriggeredRule(UserRule):\n \"\"\"\n Rule taking action when specific conditions are true within its activity\n interval.\n\n The rule I{activity} starts as soon as all associated L{Invariant}s are\n fulfilled within the rules I{active} interval, and lasts until one or more\n stops being fulfilled or the rule is no longer I{active}.\n \"\"\"\n\n class Meta:\n verbose_name = _('triggered rule')\n verbose_name_plural = _('triggered rules')\n # inherit ordering from UserRule\n\n def _generate_periods(self, from_time, to_time, index_invariants):\n \"\"\"\n Recursively generate list of periods in which a conjunction of\n propositions holds. The periods are all generated within a\n given interval.\n\n @param from_time: The start of the given interval.\n\n @param to_time: The end of the given interval.\n\n @param propositions: The list of propositions that must hold\n inside the generated periods. This list is on the same form\n as the C{\"invariants\"} member of the L{user_rule} JSON\n object.\n\n @return: Returns a list of nonoverlapping distinct periods in\n the form of tuples where the first element is a\n C{datetime.datetime} marking the start of the period, and the\n second element is a C{datetime.datetime} marking the end of\n the period.\n \"\"\"\n assert(isinstance(from_time, datetime.datetime))\n assert(isinstance(to_time, datetime.datetime))\n assert(from_time <= to_time)\n\n result = []\n if index_invariants == []:\n result = [(from_time, to_time)]\n else:\n for period_from_time, period_to_time in \\\n index_invariants[0].index.generate_true_periods(\n from_time, to_time, index_invariants[0].compare_value):\n assert(isinstance(period_from_time, datetime.datetime))\n assert(isinstance(period_to_time, datetime.datetime))\n result.extend(self._generate_periods(period_from_time,\n period_to_time,\n index_invariants[1:]))\n\n return result\n\n def _day_rules(self, from_time, to_time):\n \"\"\"\n Generate agent rules for triggered usage, within a given\n interval.\n\n @param from_time: The start of the given interval.\n\n @param to_time: The end of the given interval.\n\n @return: Returns a list of AgentRules that realize the\n triggered usage in the given interval.\n \"\"\"\n assert(isinstance(from_time, datetime.datetime))\n assert(isinstance(to_time, datetime.datetime))\n result = []\n inputinvariants = list(self.inputinvariant_set.all())\n if inputinvariants:\n result.append(\n EngineRule(\n self._generate_periods(\n from_time, to_time,\n list(self.indexinvariant_set.all())),\n inputinvariants,\n self,\n True))\n else:\n periods = self._generate_periods(\n from_time, to_time,\n list(self.indexinvariant_set.all()))\n for activity_start, activity_end in periods:\n assert(isinstance(from_time, datetime.datetime))\n assert(isinstance(to_time, datetime.datetime))\n result.extend([\n AgentRule(activity_start, initial_action)\n for initial_action\n in self.relayaction_set.filter(\n execution_time=Action.INITIAL)])\n result.extend([\n AgentRule(activity_end, final_action)\n for final_action\n in self.relayaction_set.filter(\n execution_time=Action.FINAL)])\n result.append(EngineRule(periods, [], self, False))\n return result\n\n\nclass Invariant(models.Model):\n \"\"\"\n Base class for L{TriggeredRule} invariants. Invariants compare\n index value or the input from monitored equipment to a constant.\n\n @note: LTE, EQ, GTE, NEQ are no longer supported. They are defined here,\n to preserve their meening, but they are not meant to be used in future\n applications of the Invariant class.\n \"\"\"\n LT = 0\n LTE = 1\n EQ = 2\n GTE = 3\n GT = 4\n NEQ = 5\n OPERATOR_CHOICES = (\n (LT, '<'),\n (GT, '>'))\n\n # NOTE: As this class is abstract, this will work as if the fields were\n # declared on the child classes --- including the behaviour of the\n # ForeignKey/reverse relations.\n rule = models.ForeignKey(TriggeredRule, on_delete=models.CASCADE,\n editable=False)\n operator = models.IntegerField(\n _('operator'), choices=OPERATOR_CHOICES)\n\n unit = models.CharField(choices=units.UNIT_CHOICES, max_length=100)\n\n objects = RuleCustomerBoundManager()\n\n class Meta:\n abstract = True\n verbose_name = _('invariant')\n verbose_name_plural = _('invariants')\n ordering = ['id']\n\n def save(self, *args, **kwargs):\n assert self.operator in dict(self.OPERATOR_CHOICES).keys()\n assert self.unit in dict(units.UNIT_CHOICES).keys()\n super(Invariant, self).save(*args, **kwargs)\n\n OPERATOR_MAP = {\n LT: python_operator.lt,\n LTE: python_operator.le,\n EQ: python_operator.eq,\n GTE: python_operator.ge,\n GT: python_operator.gt,\n NEQ: python_operator.ne,\n }\n\n def compare_value(self, value):\n \"\"\"\n Check this C{Invariant} against a value.\n\n Use this method wherever comparing C{Invariant}s against other\n values, so that the left and right hand sides of the operator\n stay consistent.\n\n @param value: The value to check against.\n\n @return: True if C{value OPERATOR self.value}, where OPERATOR\n is replaced with the actual operator represented with\n C{self.operator}. False otherwise.\n\n @note: Most of these operators are no longer possible to choose when\n creating invariants, but they are kept here to avoid invalidating rules\n created prior to this limitation. Those rules don't make much sense\n though, but still. Some day a decission is probably made to delete the\n redundant operators.\n \"\"\"\n op = Invariant.OPERATOR_MAP[self.operator]\n return op(value, self.value_as_physical_quantity())\n\n def value_as_physical_quantity(self):\n \"\"\"\n Converts value to a L{PhysicalQuantity}.\n\n @precondition: C{self.unit not in ['celsius', 'fahrenheit']}\n \"\"\"\n assert self.unit != 'celsius'\n assert self.unit != 'fahrenheit'\n return PhysicalQuantity(self.value, self.unit)\n\n\nclass IndexInvariant(Invariant):\n \"\"\"\n L{TriggeredRule} invariant comparing an index value to a constant.\n \"\"\"\n index = models.ForeignKey('indexes.Index', on_delete=models.PROTECT)\n value = models.DecimalField(_('value'), decimal_places=3, max_digits=8)\n\n class Meta:\n verbose_name = _('index invariant')\n verbose_name_plural = _('index invariants')\n\n\nclass InputInvariant(Invariant):\n \"\"\"\n L{TriggeredRule} invariant comparing a measurement to a constant.\n \"\"\"\n data_series = models.ForeignKey(\n 'measurementpoints.DataSeries', on_delete=models.PROTECT)\n value = models.BigIntegerField(_('value'))\n\n class Meta:\n verbose_name = _('input invariant')\n verbose_name_plural = _('input invariants')\n\n def __repr__(self):\n return 'InputInvariant(data_series=%r, value=%r, rule=%r, unit=%r, ' \\\n 'operator=%r)' % (self.data_series, self.value, self.rule,\n self.unit, self.operator)\n\n def clean(self):\n if self.data_series.unit and self.unit:\n if self.unit == 'celsius':\n real_unit = 'kelvin'\n elif self.unit == 'fahrenheit':\n real_unit = 'rankine'\n else:\n real_unit = self.unit\n if not PhysicalQuantity.compatible_units(\n self.data_series.unit, real_unit):\n raise ValidationError(\n _(u'Unit incompatible with selected input.'))\n\n def value_as_physical_quantity(self):\n \"\"\"\n C{InputInvariant} override of\n L{Invariant.value_as_physical_quantity()}. This implementation will\n also handle C{self.unit in ['celsius', 'fahrenheit']}.\n \"\"\"\n if self.unit == 'celsius':\n result = PhysicalQuantity(self.value, 'kelvin')\n if self.data_series.role == DataRoleField.ABSOLUTE_TEMPERATURE:\n result += PhysicalQuantity('273.15', 'kelvin')\n elif self.unit == 'fahrenheit':\n result = PhysicalQuantity(self.value, 'rankine')\n if self.data_series.role == DataRoleField.ABSOLUTE_TEMPERATURE:\n result += PhysicalQuantity('459.67', 'rankine')\n else:\n result = super(InputInvariant, self).value_as_physical_quantity()\n return result\n\n\nclass EngineRule(object):\n \"\"\"\n A C{EngineRule} is the execution of a rule by acting on\n relevant events when they are detected. C{EngineRule}s work by\n processing their rule once every time the member method\n L{process_rule()} is called. The idea is that an owning process\n has a number of C{EngineRule} objects, one for every rule that\n process is responsible for, and the L{process_rule()} method of\n these are then called in turn at a frequent interval.\n\n Events are transitions in and out of certain states, defined by\n the underlying rule. Most of these states will be stored as\n measurment values in the database, and state transitions are\n detected some time (hopefully shortly) after they actually occur.\n This means that it is necessary to keep track of state transition\n that has already been detected and handled, and this is what this\n object serves to do.\n\n @ivar process_again: If C{True} it makes sense to call process()\n again. If C{False}, this C{EngineRule} is done, and it can be\n deleted.\n \"\"\"\n def __init__(self, execution_periods, input_invariants, user_rule,\n engine_controls_relays):\n self.execution_periods = execution_periods\n self.input_invariants = list(input_invariants)\n self.user_rule = user_rule\n self.current_period = None\n self.process_again = True\n self.engine_controls_relays = engine_controls_relays\n\n def __cmp__(self, other):\n \"\"\"\n Two EngineRules are considered equal if they are instantiated from the\n same user_rule with the same input invariants and run on the same date.\n EngineRules support updates on the run. So new rules and updates to\n rules do take effect emmidiately when rules are reloaded. When a rule\n is updated, the final actions are not executed, but the initial actions\n of the updated rule are executed.\n \"\"\"\n return cmp(self.__class__, other.__class__) or \\\n cmp((self.execution_periods,\n [(ii.data_series, ii.value, ii.operator, ii.unit) for\n ii in self.input_invariants],\n self.user_rule),\n (other.execution_periods,\n [(ii.data_series, ii.value, ii.operator, ii.unit) for\n ii in other.input_invariants],\n other.user_rule))\n\n def __hash__(self):\n return hash((tuple(self.execution_periods),\n tuple(self.input_invariants),\n self.user_rule))\n\n def __repr__(self):\n return 'EngineRule(execution_periods=%r, input_invariants=%r, '\\\n 'user_rule=%r)' % (self.execution_periods, self.input_invariants,\n self.user_rule)\n\n def __get_actions(self, execution_time):\n \"\"\"\n Construct a list of actions with the given C{execution_time}.\n \"\"\"\n actions = list(self.user_rule.emailaction_set.filter(\n execution_time=execution_time).distinct())\n actions.extend(list(self.user_rule.phoneaction_set.filter(\n execution_time=execution_time).distinct()))\n if self.engine_controls_relays:\n actions.extend(list(self.user_rule.relayaction_set.filter(\n execution_time=execution_time).distinct()))\n return actions\n\n def __check_input_invariants(self, from_time, now):\n \"\"\"\n Check that our input_invariants are met by all inputs.\n\n @return: C{False} if any input invariant is violated.\n C{True} otherwise.\n \"\"\"\n for input_invariant in self.input_invariants:\n data_series = input_invariant.data_series.subclass_instance\n from_time\n assert from_time <= now\n if data_series.is_rate():\n measurement = data_series.latest_sample(\n from_timestamp=from_time,\n to_timestamp=now)\n else:\n assert data_series.is_accumulation()\n measurement = data_series.calculate_development(\n from_timestamp=from_time,\n to_timestamp=now)\n if not measurement or not input_invariant.compare_value(\n measurement.physical_quantity):\n return False\n return True\n\n def process(self, now):\n \"\"\"\n Process input invariants against recent measurement data.\n\n Relay switch actions are only to be taken if the state of\n input invariants has changed since last time C{process()} was\n called.\n\n @return Returns a list of L{Action}s to be taken right now.\n \"\"\"\n\n result = []\n if self.current_period:\n from_time, to_time = self.current_period\n if now >= to_time or not self.__check_input_invariants(\n from_time, now):\n self.current_period = None\n result.extend(self.__get_actions(Action.FINAL))\n\n self.process_again = any([now < to_time_ for from_time_, to_time_\n in self.execution_periods])\n\n if not self.current_period and self.process_again:\n for from_time, to_time in self.execution_periods:\n if from_time <= now < to_time and \\\n self.__check_input_invariants(from_time, now):\n self.current_period = (from_time, to_time)\n result.extend(self.__get_actions(Action.INITIAL))\n break\n\n return result\n\n\nclass AgentRule(object):\n \"\"\"\n Agent rules are interpreted by individual agents.\n\n Unlike user rules (L{Rule}), agent rules are limited to some quite\n minimalistic semantics, namely those on the form \"at time t,\n relay NAME is turned on/off\"\n\n @ivar activation_time: A datetime.datetime at which to activate\n this rule.\n\n @ivar relay_action: A L{RelayAction} to be executed when time\n passes C{activation_time}.\n\n @ivar process_again: If C{True} it makes sense to call process()\n again. If C{False}, this C{EngineRule} is done, and it can be\n deleted.\n \"\"\"\n\n def __init__(self, activation_time, relay_action):\n \"\"\"\n Construct an AgentRule.\n\n @param activation_time: A datetime.datetime at which to\n activate this rule.\n\n @param relay_action: A L{RelayAction} to be executed when time\n passes C{activation_time}.\n \"\"\"\n self.activation_time = activation_time\n self.relay_action = relay_action\n self.process_again = True\n\n def __cmp__(self, other):\n return cmp(self.__class__, other.__class__) or \\\n cmp((self.activation_time,\n self.relay_action.relay_action,\n self.relay_action.meter_id),\n (other.activation_time,\n other.relay_action.relay_action,\n other.relay_action.meter_id))\n\n def __hash__(self):\n return hash((self.activation_time,\n self.relay_action.relay_action,\n self.relay_action.meter_id))\n\n def __unicode__(self):\n details = {\"activation_time\":\n self.activation_time.tzinfo.normalize(self.activation_time),\n \"relay\": self.relay_action.meter}\n if self.relay_action.relay_action == TURN_ON:\n return _(\"at %(activation_time)s relay \"\n \"%(relay)s is turned on\") % details\n else:\n assert(self.relay_action.relay_action == TURN_OFF)\n return _(\"at %(activation_time)s relay \"\n \"%(relay)s is turned off\") % details\n\n def __repr__(self):\n return b\"AgentRule(%r, %r)\" % (self.activation_time,\n self.relay_action)\n\n def process(self, now):\n \"\"\"\n Process the scheduled C{RelayAction} against current time. If\n C{self.relay_action} has not been executed yet, but C{now >=\n self.activation_time} it is returned, and assumed to be\n executed.\n\n @param now: The current time.\n\n @return Returns a list of L{Action}s to be taken right now.\n \"\"\"\n if self.process_again and now >= self.activation_time:\n self.process_again = False\n return [self.relay_action]\n return []\n" }, { "alpha_fraction": 0.5645161271095276, "alphanum_fraction": 0.6290322542190552, "avg_line_length": 12.88888931274414, "blob_id": "358292125be06753505644f4c265611a420ac2dc", "content_id": "9bb547783c6951a23e1899836459bea727b9231f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 124, "license_type": "no_license", "max_line_length": 34, "num_lines": 9, "path": "/run.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ -z \"$VIRTUAL_ENV\" ]\nthen\n . ../ve/bin/activate\nfi\n\ncd ~/gridplatform\n./manage.py runserver 0.0.0.0:8000" }, { "alpha_fraction": 0.5923362374305725, "alphanum_fraction": 0.5980222225189209, "avg_line_length": 34.276161193847656, "blob_id": "c374b027021f0bdecec10d446c423f49bb347d01", "content_id": "d0e6ef8ed12c646f0155280f4033e8d37b510a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12135, "license_type": "no_license", "max_line_length": 79, "num_lines": 344, "path": "/gridplatform/utils/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom isoweek import Week\n\nfrom django.utils.translation import ugettext_lazy\nfrom django.utils.translation import ugettext as _\nfrom django import forms\nfrom django.core.exceptions import ValidationError\n\nfrom model_utils import Choices\n\nfrom gridplatform.trackuser import get_timezone\nfrom gridplatform.trackuser import get_customer\n\nfrom . import condense\nfrom .relativetimedelta import RelativeTimeDelta\n\n\ndef _date_hour_to_datetime(date, hours, timezone):\n return timezone.localize(\n datetime.datetime.combine(date, datetime.time()) +\n datetime.timedelta(hours=hours))\n\n\nclass TimePeriodFormMixin(object):\n \"\"\"\n Mixes :meth:`.TimePeriodFormMixin.clean` into a form. The mixed\n form is required to have the following fields::\n\n from_date = forms.DateField()\n from_hour = forms.TypedChoiceField(\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n to_date = forms.DateField()\n to_hour = forms.TypedChoiceField(\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n\n\n :note: The fields are set on the subclasses\n :class:`.TimePeriodForm` and :class:`.TimePeriodModelForm` ---\n this is intentional.\n\n Due to how form fields are set up with logic in the metaclasses for\n ``forms.Form`` and ``forms.ModelForm``, \"normal\" field declarations only\n work on classes that inherit from either of them. Declaring this class a\n subclass of either would, however, lead to metaclass conflict and make it\n unusable as mixin for the other...\n\n :cvar HOUR_CHOICES: A :class:`~model_utils.Choices` of clock hours\n 00:00 ... 24:00. These can be accessed with\n ``HOUR_CHOICES.hour_0`` ... ``HOUR_CHOICES.hour_24``.\n \"\"\"\n HOUR_CHOICES = Choices(*[\n (h, 'hour_{}'.format(h), '{:02d}:00'.format(h))\n for h in range(25)\n ])\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n The initial value of ``to_hour`` is 24:00 to include the entire\n duration of ``to_date``.\n \"\"\"\n super(TimePeriodFormMixin, self).__init__(*args, **kwargs)\n self.initial['to_hour'] = self.HOUR_CHOICES.hour_24\n\n def clean(self):\n \"\"\"\n Populates ``self.cleaned_data['from_timestamp']`` and\n ``self.cleaned_data['to_timestamp']`` with cleaned values of\n date and hour fields.\n \"\"\"\n super(TimePeriodFormMixin, self).clean()\n assert 'from_timestamp' not in self.cleaned_data\n assert 'to_timestamp' not in self.cleaned_data\n if 'from_date' in self.cleaned_data and \\\n 'from_hour' in self.cleaned_data:\n self.cleaned_data['from_timestamp'] = _date_hour_to_datetime(\n self.cleaned_data['from_date'],\n self.cleaned_data['from_hour'],\n self._get_timezone())\n if 'to_date' in self.cleaned_data and \\\n 'to_hour' in self.cleaned_data and \\\n self.cleaned_data['to_date']:\n self.cleaned_data['to_timestamp'] = _date_hour_to_datetime(\n self.cleaned_data['to_date'],\n self.cleaned_data['to_hour'],\n self._get_timezone())\n return self.cleaned_data\n\n def _get_timezone(self):\n return get_timezone()\n\n\nclass TimePeriodForm(TimePeriodFormMixin, forms.Form):\n \"\"\"\n A Non-model form mixed with :class:`.TimePeriodFormMixin`.\n \"\"\"\n from_date = forms.DateField(\n label=ugettext_lazy('From date'), localize=True)\n from_hour = forms.TypedChoiceField(\n label=ugettext_lazy('From hour'),\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n to_date = forms.DateField(\n label=ugettext_lazy('To date'), localize=True)\n to_hour = forms.TypedChoiceField(\n label=ugettext_lazy('To hour'),\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n\n\nclass TimePeriodModelForm(TimePeriodFormMixin, forms.ModelForm):\n \"\"\"\n A model form mixed with :class:`.TimePeriodFormMixin`.\n\n A :class:`.TimePeriodModelForm` facilitates modifying a pair of\n :class:`~django.db.models.DateTimeField` on a model. These should\n be named ``from_timestamp`` and ``to_timestamp`` by convention,\n but can be customized by the following class variables (not\n recommended):\n\n :cvar instance_from_attr: Defaults to ``'from_timestamp'``\n :cvar instance_to_attr: Defaults to ``'to_timestamp'``\n \"\"\"\n from_date = forms.DateField(\n label=ugettext_lazy('From date'), localize=True)\n from_hour = forms.TypedChoiceField(\n label=ugettext_lazy('From hour'),\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n to_date = forms.DateField(\n label=ugettext_lazy('To date'), localize=True)\n to_hour = forms.TypedChoiceField(\n label=ugettext_lazy('To hour'),\n choices=TimePeriodFormMixin.HOUR_CHOICES,\n coerce=int, empty_value=None)\n\n instance_from_attr = 'from_timestamp'\n instance_to_attr = 'to_timestamp'\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initializes the :class:`.TimePeriodFormMixin` fields from\n ``self.instance``.\n\n :note: ``to_timestamp`` midnight is displayed as 24:00, to not\n mention dates that has an empty overlap with the period.\n \"\"\"\n super(TimePeriodModelForm, self).__init__(*args, **kwargs)\n timezone = self._get_timezone()\n from_timestamp = getattr(self.instance, self.instance_from_attr, None)\n if from_timestamp:\n from_timestamp = timezone.normalize(\n from_timestamp.astimezone(timezone))\n self.initial['from_date'] = from_timestamp.date()\n self.initial['from_hour'] = from_timestamp.hour\n to_timestamp = getattr(self.instance, self.instance_to_attr, None)\n if to_timestamp:\n to_timestamp = timezone.normalize(\n to_timestamp.astimezone(timezone))\n if to_timestamp.hour == 0:\n # to_timestamp midnight is displayed as 24:00, to not\n # mention dates that has an empty overlap with the period.\n self.initial['to_date'] = to_timestamp.date() - \\\n datetime.timedelta(days=1)\n self.initial['to_hour'] = 24\n else:\n self.initial['to_date'] = to_timestamp.date()\n self.initial['to_hour'] = to_timestamp.hour\n\n def clean(self):\n \"\"\"\n Sets ``instance`` fields from :class:`.TimePeriodFormMixin` fields\n \"\"\"\n super(TimePeriodModelForm, self).clean()\n if 'from_timestamp' in self.cleaned_data:\n setattr(\n self.instance,\n self.instance_from_attr,\n self.cleaned_data['from_timestamp'])\n if 'to_timestamp' in self.cleaned_data:\n setattr(\n self.instance,\n self.instance_to_attr,\n self.cleaned_data['to_timestamp'])\n\n return self.cleaned_data\n\n\nclass HalfOpenTimePeriodModelForm(TimePeriodModelForm):\n \"\"\"\n Specialization of :class:`.TimePeriodModelForm` that allows for\n empty ``to_date``.\n \"\"\"\n to_date = forms.DateField(\n label=ugettext_lazy('To date'), localize=True, required=False)\n\n def clean(self):\n \"\"\"\n Clears ``instance.to_timestamp`` if ``to_date`` is blank.\n \"\"\"\n super(HalfOpenTimePeriodModelForm, self).clean()\n if 'to_timestamp' not in self.cleaned_data and \\\n 'to_date' not in self.errors and 'to_time' not in self.errors:\n setattr(self.instance, self.instance_to_attr, None)\n\n return self.cleaned_data\n\n\ndef previous_month_initial_values(timestamp=None):\n \"\"\"\n Initial values for a form mixed with :class:`.TimePeriodFormMixin`\n covering the duration of a previous month.\n\n :rtype: :class:`dict`\n\n :keyword datetime timestamp: Result will be the latest completed\n month before this value. If ``None`` (the default) now will\n be used instead.\n \"\"\"\n if timestamp is None:\n timestamp = get_customer().now()\n initial = {\n 'from_date': condense.floor(\n timestamp - RelativeTimeDelta(months=1),\n condense.MONTHS, get_timezone()).date(),\n 'to_date': (\n condense.floor(\n timestamp,\n condense.MONTHS, get_timezone()) -\n RelativeTimeDelta(days=1)).date(),\n 'from_hour': 0,\n 'to_hour': 24\n }\n return initial\n\n\ndef this_week_initial_values(timestamp=None):\n \"\"\"\n Initial values for a form mixed with :class:`.TimePeriodFormMixin`\n covering the duration of a week.\n\n :rtype: :class:`dict`\n\n :keyword datetime timestamp: Result will be the week containing\n this value. If ``None`` (the default) now will be used\n instead.\n \"\"\"\n if timestamp is None:\n timestamp = get_customer().now()\n week = Week.withdate(timestamp.date())\n initial = {\n 'year': week.year,\n 'week': week.week,\n }\n return initial\n\n\ndef _year_week_to_timestamps(year, week):\n week = Week.fromstring(\"%sW%02d\" % (year, week))\n\n from_timestamp = datetime.datetime.combine(\n week.monday(), datetime.time())\n to_timestamp = from_timestamp + datetime.timedelta(days=7)\n return (from_timestamp, to_timestamp, )\n\n\nclass YearWeekPeriodForm(forms.Form):\n \"\"\"\n Form for selecting a timestamp range with a duration of one week.\n\n :cvar year: A form field for selecting year of the week.\n :cvar week: A form field for selecting the week number of the week.\n \"\"\"\n from_timestamp = None\n to_timestamp = None\n\n year = forms.TypedChoiceField(\n label=ugettext_lazy('Year'),\n choices=[],\n coerce=int, empty_value=2016)\n\n week = forms.TypedChoiceField(\n label=ugettext_lazy('Week'),\n choices=Choices(*[\n (w, w, w)\n for w in range(1, 54)\n ]),\n coerce=int, empty_value=1)\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialize choices for ``self.year`` with 2005 ... next year.\n \"\"\"\n super(YearWeekPeriodForm, self).__init__(*args, **kwargs)\n self.fields['year'].choices = Choices(*[\n (y, y, y)\n for y in range(\n 2005, self._get_timezone().localize(\n datetime.datetime.now()).year + 1)\n ])\n\n def clean(self):\n \"\"\"\n :raise: ValidationError: If no such week number exist in given\n year.\n \"\"\"\n super(YearWeekPeriodForm, self).clean()\n if 'year' in self.cleaned_data and \\\n 'week' in self.cleaned_data:\n year = self.cleaned_data['year']\n week = self.cleaned_data['week']\n timestamps = _year_week_to_timestamps(\n year, week)\n\n if week == 53:\n fourth_jan = datetime.date(year + 1, 1, 4)\n if timestamps[1] >= datetime.datetime.combine(\n fourth_jan, datetime.time()):\n raise ValidationError(\n _(\"There's no week %s in %s\" % (week, year, )))\n\n self.from_timestamp = self._get_timezone().localize(\n timestamps[0])\n self.to_timestamp = self._get_timezone().localize(\n timestamps[1])\n\n return self.cleaned_data\n\n def get_timestamps(self):\n \"\"\"\n After successful validation this method may be called.\n\n :return: The timestamp range of the selected week.\n :rtype: Pair of :class:`~datetime.datetime`.\n \"\"\"\n return (self.from_timestamp, self.to_timestamp, )\n\n def _get_timezone(self):\n return get_timezone()\n" }, { "alpha_fraction": 0.7238562107086182, "alphanum_fraction": 0.7238562107086182, "avg_line_length": 33, "blob_id": "ec8d652c7809db3114bfeb15431245045e0a5462", "content_id": "3d6f54c3060a7137b2f2164f132646f410645478", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 612, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/documentation/source/changes.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": ".. _changes-in-domain:\n\nChanges in the Domain\n=====================\n\nOccationally, one of the following will happen:\n\n * A new main consumption is installed.\n * An existing main consumption is discontinued.\n * A new energy use is introduced.\n * An existing energy use is disconnected.\n * A new data source is introduced.\n * A data source is replaced in some application (say a new meter is\n installed, or a different tariff is applied).\n\nIt is not enough to model the state of the domain at just a single\npoint in time. The state of the domain needs to be modelled with\nsupport for historical changes.\n" }, { "alpha_fraction": 0.6563758254051208, "alphanum_fraction": 0.6602994203567505, "avg_line_length": 46.70935821533203, "blob_id": "b1afe248bce0dfbdfd6e299b243c8f175f353120", "content_id": "42bacb314e64df588856534e3f756d34c4d74f7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9685, "license_type": "no_license", "max_line_length": 146, "num_lines": 203, "path": "/gridplatform/encryption/middleware.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport base64\nimport pickle\n\nfrom django.core import signing\n\nfrom .conf import settings\n\nfrom .base import EncryptionContext\nfrom .base import _store\nfrom .base import get_cipher_module\n\n\ndef _will_refresh_session_cookie(request, response):\n \"\"\"\n Determine whether the session cookie should be set/refreshed --- logic\n taken from django.contrib.sessions.middleware.SessionMiddleware.\n \"\"\"\n try:\n modified = request.session.modified\n except AttributeError:\n return False\n return (modified or settings.SESSION_SAVE_EVERY_REQUEST) and \\\n response.status_code != 500\n\n\ndef _session_cookie_max_age(request):\n \"\"\"\n Determine appropriate max_age for cookie --- logic taken from\n django.contrib.sessions.middleware.SessionMiddleware.\n \"\"\"\n # HttpResponse.set_cookie() will construct expires from max_age; including\n # the logic here is not necessary.\n if request.session.get_expire_at_browser_close():\n max_age = None\n else:\n max_age = request.session.get_expiry_age()\n return max_age\n\n\n\n\nclass EncryptionMiddleware(object):\n \"\"\"\n Middleware to manage 'secret' data; storing an attribute of the request\n encrypted such that the server has the ciphertext (as a session variable)\n while the client has the key (in a cookie). The data is decrypted with the\n received key on each request and encrypted and stored if changed on each\n response.\n\n Implementation notes:\n\n Encryption key is sent to browser in cookie.\n Ciphertext and initialisation vector is stored in session.\n\n The locations to store the key and ciphertext are obvious --- sending much\n data in cookies is problematic, so the ciphertext needs to stay on the\n server, and the key should then *not* be stored on the server.\n\n The choice of where to store the initialisation vector is less\n straightforward, though keeping it on the server greatly simplifies\n synchronisation between browser and server: On storing new data, we must\n generate a new initialisation vector, and keeping it on the server means\n that the current credentials known by the client are still valid, which\n saves us from various ugly edge cases... (Our use might be a special case\n where reusing the initialisation vector is not as big a problem as it\n usually is --- but then again, it might not, and it's better to be safe\n than sorry...)\n\n If data has not changed, then we will *not* update the data stored for the\n session. Checking for this adds some complexity, but reduces the database\n load --- depending on session configuration this may entirely avoid hitting\n the database --- and in particular, this avoids what could otherwise be\n some *really* stupid transaction errors in case of parallel requests that\n semantically should be read-only.\n \"\"\"\n\n def process_request(self, request):\n if settings.ENCRYPTION_TESTMODE or request.META['PATH_INFO'] == '/Wibeee/receiver' or request.META['PATH_INFO'] == '/Wibeee/receiverJSON':\n return\n setattr(_store, settings.ENCRYPTION_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_EPHEMERAL_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_ORIGINAL_STORE_KEY, None)\n if 'encryption_context' in request.session:\n from django.contrib.auth import logout\n logout(request)\n return\n try:\n key_cookie = request.COOKIES[settings.ENCRYPTION_COOKIE_NAME]\n data = request.session[settings.ENCRYPTION_SESSION_KEY]\n except KeyError:\n # Cookie, data or both are missing; nothing to do.\n return\n b64_key = signing.loads(key_cookie, salt=settings.ENCRYPTION_SIGN_SALT)\n key = base64.b64decode(b64_key)\n iv, ciphertext = data\n cipher = get_cipher_module().symmetric_cipher(key, iv)\n plaintext = cipher.decrypt(ciphertext)\n data = pickle.loads(plaintext)\n setattr(_store, settings.ENCRYPTION_STORE_KEY, data)\n setattr(_store, settings.ENCRYPTION_ORIGINAL_STORE_KEY, data)\n\n def process_response(self, request, response):\n if settings.ENCRYPTION_TESTMODE:\n return\n if request.META['PATH_INFO'] == '/Wibeee/receiver' or request.META['PATH_INFO'] == '/Wibeee/receiverJSON':\n return response\n\n data = getattr(_store, settings.ENCRYPTION_STORE_KEY, None)\n original_data = getattr(\n _store, settings.ENCRYPTION_ORIGINAL_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_EPHEMERAL_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_ORIGINAL_STORE_KEY, None)\n if not hasattr(request, 'session'):\n return response\n if data is None:\n # No data to store. Cleanup just in case; data may have been\n # removed from request but still be present on our side...\n if settings.ENCRYPTION_COOKIE_NAME in request.COOKIES:\n # Don't \"delete\" the cookie if it doesn't exist; as \"deleting\"\n # it implies setting it to \"something else\"; here the empty\n # string and with a timeout in the past.\n response.delete_cookie(settings.ENCRYPTION_COOKIE_NAME)\n if settings.ENCRYPTION_SESSION_KEY in request.session:\n del request.session[settings.ENCRYPTION_SESSION_KEY]\n return response\n try:\n key_cookie = request.COOKIES[settings.ENCRYPTION_COOKIE_NAME]\n # Pretend cookie does not exist if empty --- a client might not\n # check the timeout and hand us the value we \"deleted\" it with; and\n # this should *not* lead to an error indicating that the cookie has\n # been modified on the client side... (The Django test client acts\n # like that; i.e. this logic is necessary for convenient\n # testing...)\n if key_cookie == '':\n raise KeyError\n b64_key = signing.loads(\n key_cookie, salt=settings.ENCRYPTION_SIGN_SALT)\n key = base64.b64decode(b64_key)\n except KeyError:\n # Cookie does not exist. If it exists but with an invalid value,\n # signing.loads would throw BadSignature, which we don't catch\n # here.\n key = get_cipher_module().generate_symmetric_key()\n # Check whether anything has changed --- if not, we don't want to\n # modify the session state. (Also, if the backing RNG is based on\n # Linux /dev/urandom or something similar, then the supply of random\n # bytes is actually limited, and we need a new block of random bytes\n # for the initialisation vector each time we encrypt data.)\n data_changed = (data != original_data)\n if data_changed:\n # We use the newest/most efficient version of the pickle protocol;\n # we will not need to load data with an older version of\n # Python/pickle than the one running while \"now\", we store it...\n # (The latest version is currently compatible with Python 2.3 and\n # forward; Python 2.3 was released in 2003.)\n plaintext = pickle.dumps(data, pickle.HIGHEST_PROTOCOL)\n # Make a new initialisation vector, encrypt data, store. \"Reuse\"\n # key; if session has an active key, that will be used; otherwise a\n # new key will have been generated...\n cipher_module = get_cipher_module()\n iv = cipher_module.generate_iv()\n cipher = cipher_module.symmetric_cipher(key, iv)\n ciphertext = cipher.encrypt(plaintext)\n request.session[settings.ENCRYPTION_SESSION_KEY] = (iv, ciphertext)\n if data_changed or _will_refresh_session_cookie(request, response):\n # Wrap key in cookie, hand to client. This will \"refresh\" cookie\n # expiry if already present. To avoid strange edge cases, we will\n # set the cookie on data change and on session cookie refresh...\n # (... data change implies a session cookie refresh anyway.)\n # If the encryption cookie expires before the session cookie, the\n # resulting behaviour may be somewhat confusing to users...\n b64_key = base64.b64encode(key)\n key_cookie = signing.dumps(\n b64_key, salt=settings.ENCRYPTION_SIGN_SALT, compress=True)\n max_age = _session_cookie_max_age(request)\n response.set_cookie(\n settings.ENCRYPTION_COOKIE_NAME, key_cookie,\n max_age=max_age, httponly=True)\n return response\n\n\nclass KeyLoaderMiddleware(object):\n \"\"\"\n Ensures that the thread-local store has an request specific\n :class:`.EncryptionContext` for loading private keys entrusted to the\n entity performing the request.\n \"\"\"\n def process_request(self, request):\n if settings.ENCRYPTION_TESTMODE or request.META['PATH_INFO'] == '/Wibeee/receiver' or request.META['PATH_INFO'] == '/Wibeee/receiverJSON':\n return\n setattr(\n _store, settings.ENCRYPTION_CONTEXT_STORE_KEY, EncryptionContext())\n\n def process_response(self, request, response):\n if settings.ENCRYPTION_TESTMODE or request.META['PATH_INFO'] == '/Wibeee/receiver' or request.META['PATH_INFO'] == '/Wibeee/receiverJSON':\n return response\n setattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, None)\n return response\n" }, { "alpha_fraction": 0.5893284678459167, "alphanum_fraction": 0.6007320880889893, "avg_line_length": 32.50471878051758, "blob_id": "c4454de348f7b29ee2cd9be55bee493b61d43f2e", "content_id": "f1ea19176b9247886255111f405f2138cb94719e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7103, "license_type": "no_license", "max_line_length": 77, "num_lines": 212, "path": "/legacy/manage_collections/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom StringIO import StringIO\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom PIL import Image\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.users.models import User\nfrom gridplatform.encryption.shell import Request\nfrom gridplatform.utils import utilitytypes\n\nfrom .models import Floorplan\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass CollectionTestSetup(TestCase):\n fixtures = [\"manage_indexes_test.json\"]\n\n def setUp(self):\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n\n self.customer = User.objects.get(\n id=self.client.session[\"_auth_user_id\"]).customer\n trackuser._set_customer(self.customer)\n assert self.customer.id and self.customer == \\\n trackuser.get_customer()\n\n self.request = Request('super', '123')\n\n self.group = Collection.objects.create(\n name_plain='Test group',\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n self.assertFalse(Floorplan.objects.filter(\n collection=self.group).exists())\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n\nclass TestCollectionView(CollectionTestSetup):\n def test_group_form_success(self):\n \"\"\"\n Test C{group_form} wizard view for adding a collection.\n \"\"\"\n NAME = \"Test collection\"\n\n response = self.client.get(\"/groups/\")\n self.assertEqual(response.status_code, 200)\n\n response = self.client.get(\n \"/groups/form/\")\n self.assertEqual(response.status_code, 200)\n\n response = self.client.post(\n \"/groups/update/\",\n data={\n 'name': NAME,\n 'parent': ''\n })\n self.assertNotContains(response, 'error')\n\n # Verify JSON slide\n response = self.client.get(\n \"/groups/json/groups/\")\n self.assertContains(response, NAME)\n\n collection = Collection.objects.\\\n subclass_only().order_by('-id')[0].subclass_instance\n\n # Verify model\n self.assertEqual(collection.name_plain, NAME)\n\n # # Verify edit form\n response = self.client.get(\n '/groups/form/%s' % collection.id)\n self.assertContains(response, NAME)\n\n def test_group_form_failed(self):\n \"\"\"\n Test C{group_form} wizard view for adding a collection\n with faulty input.\n \"\"\"\n response = self.client.post(\n \"/groups/update/\",\n data={\n 'name': '',\n 'parent': ''\n })\n self.assertContains(response, 'error')\n\n def test_group_edit_form_success(self):\n \"\"\"\n Test C{group_form} wizard view for edition a collection group.\n \"\"\"\n response = self.client.post(\n \"/groups/update/%d\" % self.group.id,\n data={\n 'name': 'New name',\n 'parent': ''\n })\n self.assertNotContains(response, 'error')\n\n # Verify model\n collection = Collection.objects.get(id=self.group.id)\n self.assertEqual(collection.name_plain, 'New name')\n\n def test_group_edit_form_failed(self):\n \"\"\"\n Test C{group_form} wizard view for edition a collectin group\n with faulty input.\n \"\"\"\n response = self.client.post(\n \"/groups/update/%d\" % self.group.id,\n data={\n 'name': '',\n 'parent': ''})\n self.assertContains(response, 'error')\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestFloorPlanView(CollectionTestSetup):\n \"\"\"\n Test the L{floorplan} view.\n \"\"\"\n fixtures = [\"manage_indexes_test.json\"]\n\n def setUp(self):\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n\n self.customer = User.objects.get(\n id=self.client.session[\"_auth_user_id\"]).customer\n trackuser._set_customer(self.customer)\n assert self.customer.id and self.customer == trackuser.get_customer()\n\n self.request = Request('super', '123')\n\n self.group = Collection.objects.create(\n name_plain='Test group',\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n self.assertFalse(Floorplan.objects.filter(\n collection=self.group).exists())\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def create_image(self, width, height, name):\n # http://janneke-janssen.blogspot.dk/2012/01/\n # django-testing-imagefield-with-test.html\n file_obj = StringIO()\n image = Image.new(\"RGBA\", size=(width, height), color=(256, 0, 0))\n image.save(file_obj, 'png')\n file_obj.name = '%s.png' % name\n file_obj.seek(0)\n return file_obj\n\n def test_show_new(self):\n response = self.client.get('/groups/floorplan/%d' % self.group.id)\n self.assertEqual(response.status_code, 200)\n self.assertFalse(Floorplan.objects.filter(\n collection=self.group).exists())\n\n def test_create_new_then_show_then_update_then_show(self):\n response = self.client.post(\n '/groups/floorplan/%d' % self.group.id,\n {'image': self.create_image(1200, 400, 'test1')})\n self.assertEqual(response.status_code, 200)\n\n floor_plan = Floorplan.objects.get(collection=self.group)\n self.assertEqual(floor_plan.image.width, 900)\n self.assertEqual(floor_plan.image.height, 300)\n\n response = self.client.get('/groups/floorplan/%d' % self.group.id)\n self.assertEqual(response.status_code, 200)\n\n response = self.client.get(\n '/groups/floorplan/%d/image' % self.group.floorplan.id)\n self.assertEqual(response.status_code, 200)\n\n response = self.client.post(\n '/groups/floorplan/%d' % self.group.id,\n {'image': self.create_image(400, 1200, 'test2')})\n self.assertEqual(response.status_code, 200)\n\n floor_plan = Floorplan.objects.get(collection=self.group)\n self.assertEqual(floor_plan.image.width, 300)\n self.assertEqual(floor_plan.image.height, 900)\n\n response = self.client.get(\n '/groups/floorplan/%d/image' % self.group.floorplan.id)\n self.assertEqual(response.status_code, 200)\n\n def test_create_new_with_errors(self):\n self.assertFalse(Floorplan.objects.filter(\n collection=self.group).exists())\n response = self.client.post(\n '/groups/floorplan/%d' % self.group.id,\n {'image': ''})\n self.assertEqual(response.status_code, 200)\n self.assertIn(b'errorlist', response.content)\n\n self.assertFalse(Floorplan.objects.filter(\n collection=self.group).exists())\n" }, { "alpha_fraction": 0.6738350987434387, "alphanum_fraction": 0.6811922192573547, "avg_line_length": 38.266666412353516, "blob_id": "e92fb689102c7ea9cce6f9d2be1b8b24fb157d14", "content_id": "9cb33b898d1616e2c6ba0cd926630d3dfeba2a31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5301, "license_type": "no_license", "max_line_length": 79, "num_lines": 135, "path": "/legacy/nordpool/parser.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nParsing of the weekly spot price format from NordPool.\n\nThe file format specification is available at:\nftp://ftp.nordpoolspot.com/Information/File_specifications/SPOT-eng.DOC\nWhile not explicitly described, lines starting with # are comment lines.\nComment lines are still counted in the \"total number of lines\".\n\nPrices may be \"preliminary\" or \"official\". In both cases, final prices in EUR\nare known --- prices in other currencies are \"preliminary\" until exact exchange\nrates are known. This is explained at:\nftp://ftp.nordpoolspot.com/Information/File_specifications/\nPreliminary%20vs.%20official%20Elspot%20prices%20on%20NPS%20FTP-server.doc\n\nTime is in local time, including DST.\nOn switch to DST: Entry for \"missing\" hour empty.\nOn switch from DST: Use same entry for both instances of \"repeated\" hour.\n\nPrices are per MWh.\n\"\"\"\n\nimport csv\nimport datetime\nfrom decimal import Decimal\nfrom collections import defaultdict\n\n\ndef parse_lines(lines):\n \"\"\"\n Parse the semicolon-separated Nordpool file format and separate lines by\n their \"data type\" field. Apart from all starting with a \"data type\" field,\n fields are specific to each data type; the specifics of those is not\n handled here.\n\n @type lines: string list\n @param lines: Lines from a spot price file.\n @rtype: dictionary from strings to lists of lists of strings\n @return: A dictionary from \"data type\" values to lists of per-line field\n lists, containing the fields apart from \"data type\".\n \"\"\"\n linecount = len(lines)\n datalines = [l for l in lines if l[0] != b'#']\n reader = csv.reader(datalines, delimiter=b';', quoting=csv.QUOTE_NONE)\n data = defaultdict(list)\n for line in reader:\n datatype = line[0]\n content = line[1:]\n data[datatype].append(content)\n # simple consistency check; AL specifies total number of lines in file\n assert int(data['AL'][0][0]) == linecount\n return data\n\n\ndef extract_prices(data, area, currency):\n \"\"\"\n Pulls prices for specified area and in specified currency out of a data\n dictionary as extracted from a Nordpool spot file.\n\n @type data: dictionary from strings to lists of lists of strings\n @param data: A data dictionary created from a Nordpool spot price file.\n @type area: string\n @param area: Nordpool pricing area to include.\n @type currency: string\n @param currency: Currency to include.\n @rtype: (datetime.date, decimal.Decimal list) list\n @return: A list of (date, hourly_price) tuples.\n \"\"\"\n preliminary = []\n final = []\n\n def decimal_or_none(pricestr):\n if pricestr == '':\n return None\n else:\n return Decimal(pricestr.replace(',', '.'))\n for price in data['PR']:\n code, _year, _week, _weekday, date, alias, unit = price[:7]\n if alias != area or unit != currency:\n continue\n hourly = price[7:-1]\n hourly = map(decimal_or_none, hourly)\n # _average = price[-1]\n date = datetime.datetime.strptime(date, \"%d.%m.%Y\").date()\n if code == 'SF':\n preliminary.append((date, hourly))\n elif code == 'SO':\n final.append((date, hourly))\n return (preliminary, final)\n\n\ndef localized_hours(date, timezone):\n \"\"\"\n Constructs localised C{datetime.datetime} objects for each hour in the\n given day; starting at midnight local time, ending at the hour before\n midnight on the next calendar day. This takes DST into account, meaning\n that a \"day\" may consist of 23, 24 or 25 hours.\n\n @param date: Date to get hours for.\n @param timezone: A L{pytz.timezone} to compute hours in/for.\n @return: The list of C{datetime.datetime} objects.\n \"\"\"\n start_hour = timezone.localize(\n datetime.datetime.combine(date, datetime.time()))\n # usually 24 hours, but 23 or 25 on DST-switch\n hours = [timezone.normalize(start_hour + datetime.timedelta(hours=n))\n for n in range(25)]\n return [hour for hour in hours if hour.date() == date]\n\n\ndef day_entries(date, hourly, timezone):\n \"\"\"\n Combines date and hourly prices, nominally obtained by parsing a Nordpool\n spot price file, to get (from_timestamp, to_timestamp, value)-tuples that\n may be directly used in constructing L{legacy.indexes.models.Entry}\n objects.\n\n Takes DST and the data format wrt. those into account.\n\n @param date: Date to construct entries for.\n @param hourly: Hourly price entries. Assumed to match the L{date}.\n @return: A list of (from_timestamp, to_timestamp, value)-tuples; with\n localised C{datetime.datetime} objects, sorted by time, each with\n a period of one hour and within the calendar day specified; in\n total covering the specified day.\n \"\"\"\n hours = localized_hours(date, timezone)\n one_hour = datetime.timedelta(hours=1)\n # This implicitly handles DST-switch correctly wrt. the input data format:\n # Will not access the non-existent hour on switch to DST, will access the\n # repeating hour twice on switch to standard time.\n return [(hour, timezone.normalize(hour + one_hour), hourly[hour.hour])\n for hour in hours]\n" }, { "alpha_fraction": 0.606261134147644, "alphanum_fraction": 0.6133997440338135, "avg_line_length": 38.90504455566406, "blob_id": "35d0ce364d17f92d82d63df4a92f36c0f67a001e", "content_id": "f735cd5e5f3a249631b26f0e6dd676939a175527", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13448, "license_type": "no_license", "max_line_length": 79, "num_lines": 337, "path": "/legacy/manage_reports/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom decimal import Decimal\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.conf import settings\n\nimport pytz\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.energy_use_reports.models import EnergyUseArea\nfrom legacy.energy_use_reports.models import EnergyUseReport\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import ChainLink\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import StoredData\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import DATETIME_MAX\nfrom gridplatform.utils import DATETIME_MIN\n\nfrom .views import GenerateReportForm\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n MIDDLEWARE_CLASSES=[\n x for x in settings.MIDDLEWARE_CLASSES\n if x != 'gridplatform.trackuser.middleware.TrackUserMiddleware'])\nclass TestGenerateReportForm(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(name_plain='Test customer', timezone=pytz.utc)\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.client.login(username='testuser', password='testpassword')\n\n self.tariff1 = Index.objects.create(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Test eltariff\",\n timezone=\"Europe/Copenhagen\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.tariff1.seasonindexperiod_set.create(\n from_date=DATETIME_MIN,\n value_at_hour=[Decimal(\"1\") for _ in range(24)])\n\n self.collection = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"Test Collection\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.collection.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.collection.tariff_list = [ChainLink(\n valid_from=DATETIME_MIN,\n data_series=self.tariff1)]\n self.collection.save()\n\n StoredData.objects.create(\n data_series=self.collection.consumption,\n value=1,\n timestamp=DATETIME_MIN)\n StoredData.objects.create(\n data_series=self.collection.consumption,\n value=2,\n timestamp=DATETIME_MAX)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_dependency(self):\n collection = Collection.objects.create(\n name='test collection',\n customer=self.customer,\n role=Collection.GROUP,\n utility_type=0)\n\n collection2 = Collection.objects.create(\n name='test collection 2',\n customer=self.customer,\n role=Collection.GROUP,\n utility_type=0)\n\n self.user = User.objects.create_user(\n 'username', 'password', user_type=0)\n self.user.save()\n with replace_user(self.user):\n form = GenerateReportForm()\n self.assertIn(\n (collection.id, collection.name),\n form.fields['collections'].choices)\n self.assertIn(\n (collection2.id, collection2.name),\n form.fields['collections'].choices)\n\n CollectionConstraint.objects.create(\n collection_id=collection2.id,\n userprofile=self.user.userprofile)\n\n assert list(\n self.user.userprofile.collections.all()) == [collection2]\n\n form = GenerateReportForm()\n\n self.assertNotIn(\n (collection.id, collection.name),\n form.fields['collections'].choices)\n self.assertIn(\n (collection2.id, collection2.name),\n form.fields['collections'].choices)\n\n self.assertEqual(len(form.get_collections()), 1)\n\n def test_valid_tariff(self):\n user = User.objects.create_user(\n 'username', 'password', user_type=0)\n with replace_user(user):\n response = self.client.post(\n '/reports/request/',\n data={\n 'collections': str(self.collection.id),\n 'from_date': str(DATETIME_MIN.date()),\n 'to_date': str(DATETIME_MAX.date()),\n 'include_cost': 'on'\n }\n )\n self.assertNotContains(response, 'form_errors')\n self.client.logout()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestEnergyUseReports(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(name_plain='Test customer', timezone=pytz.utc)\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.super_user = User.objects.create_user(\n username='testsuperuser', password='testpassword',\n user_type=User.CUSTOMER_SUPERUSER, customer=self.customer)\n\n self.client.login(username='testsuperuser', password='testpassword')\n\n self.main_mp_1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"First main measurement point\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.main_mp_1.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.main_mp_1.save()\n\n self.main_mp_2 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"Second main measurement point\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.main_mp_2.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.main_mp_2.save()\n\n self.mp_1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"Test MP 1\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_1.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_1.save()\n\n self.mp_2 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"Test MP 2\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_2.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_2.save()\n\n self.mp_heat = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain=\"Test MP DISTRICT_HEATING\",\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.mp_heat.consumption = DataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.mp_2.save()\n\n self.report = EnergyUseReport.objects.create(\n customer=self.customer,\n title_plain=\"Test report\",\n currency_unit='currency_dkk',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.report.main_measurement_points.add(\n *[self.main_mp_1, self.main_mp_2])\n\n self.area = EnergyUseArea.objects.create(\n report=self.report,\n name_plain=\"Test Area\")\n self.area.measurement_points.add(*[self.mp_1, self.mp_2])\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_report_index_page(self):\n response = self.client.get(\n '/reports/')\n\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, self.report.title_plain)\n\n def test_create_form_get(self):\n response = self.client.get(\n '/reports/create/energy_use/electricity/')\n\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_create_empty_fail(self):\n response = self.client.post(\n '/reports/create/energy_use/electricity/',\n data={\n 'title': '',\n 'currency_unit': '',\n 'main_measurement_points': '',\n 'energyusearea_set-TOTAL_FORMS': '1',\n 'energyusearea_set-INITIAL_FORMS': '0',\n 'energyusearea_set-MAX_NUM_FORMS': '1000',\n 'energyusearea_set-0-name': '',\n 'energyusearea_set-0-measurement_points': '',\n })\n\n self.assertContains(response, 'errorlist')\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_create_success(self):\n response = self.client.post(\n '/reports/create/energy_use/electricity/',\n data={\n 'title': 'Test report',\n 'currency_unit': 'currency_dkk',\n 'main_measurement_points': [\n self.main_mp_1.id,\n self.main_mp_2.id,\n ],\n 'energyusearea_set-TOTAL_FORMS': '1',\n 'energyusearea_set-INITIAL_FORMS': '0',\n 'energyusearea_set-MAX_NUM_FORMS': '1000',\n 'energyusearea_set-0-name': 'Lighting',\n 'energyusearea_set-0-measurement_points': [\n self.mp_2.id,\n self.mp_1.id,\n ],\n })\n self.assertNotContains(response, 'XYZXYZXYZ', 302)\n created_report = EnergyUseReport.objects.latest('id')\n self.assertEqual(created_report.energyusearea_set.count(), 1)\n self.assertEqual(created_report.energyusearea_set.get().\n measurement_points.count(), 2)\n self.assertEqual(created_report.main_measurement_points.count(), 2)\n\n def test_update_form_get(self):\n response = self.client.get(\n '/reports/update/energy_use/%s/' % self.report.id)\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_update_empty_fail(self):\n response = self.client.post(\n '/reports/update/energy_use/%s/' % self.report.id,\n data={\n 'title': '',\n 'currency_unit': '',\n 'main_measurement_points': '',\n 'energyusearea_set-TOTAL_FORMS': '1',\n 'energyusearea_set-INITIAL_FORMS': '0',\n 'energyusearea_set-MAX_NUM_FORMS': '1000',\n 'energyusearea_set-0-name': '',\n 'energyusearea_set-0-measurement_points': '',\n })\n self.assertContains(response, 'errorlist')\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_update_success(self):\n response = self.client.post(\n '/reports/update/energy_use/%s/' % self.report.id,\n data={\n 'title': 'Altered report',\n 'currency_unit': 'currency_dkk',\n 'main_measurement_points': self.main_mp_1.id,\n 'energyusearea_set-TOTAL_FORMS': '1',\n 'energyusearea_set-INITIAL_FORMS': '0',\n 'energyusearea_set-MAX_NUM_FORMS': '1000',\n 'energyusearea_set-0-name': 'Lights',\n 'energyusearea_set-0-measurement_points': self.mp_1.id,\n 'energyusearea_set-1-id': '',\n 'energyusearea_set-1-name': 'Production line',\n 'energyusearea_set-1-measurement_points': self.mp_2.id\n })\n self.assertNotContains(response, 'XYZXYZXYZ', status_code=302)\n altered_report = EnergyUseReport.objects.get(id=self.report.id)\n self.assertEqual(altered_report.energyusearea_set.count(), 2)\n self.assertEqual(altered_report.main_measurement_points.count(), 1)\n" }, { "alpha_fraction": 0.6792972683906555, "alphanum_fraction": 0.6820530295372009, "avg_line_length": 28.92783546447754, "blob_id": "421e1e41a93b803b2b6cd194c2d3f4d2c5a46f73", "content_id": "9d648f2c636f754e24701b22e15ba18dfa375f2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2903, "license_type": "no_license", "max_line_length": 124, "num_lines": 97, "path": "/gridplatform/settings/production.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\nProduction settings and globals.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport os\nimport os.path\n\nimport dj_database_url\n\nfrom .base import * # noqa\n\n\n# ######### HOST CONFIGURATION\n# See: https://docs.djangoproject.com/en/1.5/releases/1.5/#allowed-hosts-required-in-production # noqa\nALLOWED_HOSTS = get_secret_setting('ALLOWED_HOSTS')\n# ######### END HOST CONFIGURATION\n\n\n# ######### DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\n# See: https://github.com/kennethreitz/dj-database-url\nDATABASES = {\n 'default': dj_database_url.parse(get_secret_setting('DATABASE_URL')),\n}\n# ######### END DATABASE CONFIGURATION\n\n\n# ######### CACHE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n 'LOCATION': get_secret_setting('CACHE_LOCATION'),\n }\n}\n# ######### END CACHE CONFIGURATION\n\n\n# ######### SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\nSECRET_KEY = get_secret_setting('SECRET_KEY')\n# ######### END SECRET CONFIGURATION\n\n\n# ######### MEDIA CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = os.path.normpath(\n os.path.join(os.path.dirname(SITE_ROOT), 'media/'))\n# ######### END MEDIA CONFIGURATION\n\n\n# ######### DJANGO COMPRESSOR CONFIGURATION\n# Use pre-compression. The \"compress\" management command must be run as part\n# of deployment.\n# See: http://django-compressor.readthedocs.org/en/latest/usage/#pre-compression # noqa\nCOMPRESS_OFFLINE = True\n# See: http://django-compressor.readthedocs.org/en/latest/settings/#django.conf.settings.COMPRESS_CSS_HASHING_METHOD # noqa\nCOMPRESS_CSS_HASHING_METHOD = 'content'\n# ######### END DJANGO COMPRESSOR CONFIGURATION\n\n\n# ######### DATA IMPORT LOGIN CONFIGURATION\nENERGINET_CO2_USER = get_secret_setting('ENERGINET_CO2_USER')\nENERGINET_CO2_PASS = get_secret_setting('ENERGINET_CO2_PASS')\nNORDPOOL_USER = get_secret_setting('NORDPOOL_USER')\nNORDPOOL_PASS = get_secret_setting('NORDPOOL_PASS')\n# ######### END DATA IMPORT LOGIN CONFIGURATION\n\n\n# ######### CELERY CONFIGURATION\nBROKER_URL = get_secret_setting(\"BROKER_URL\")\nCELERY_ROUTES = {\n 'legacy.energy_use_reports.tasks.EnergyUseReportTask': {\n 'queue': 'reports',\n },\n 'legacy.manage_reports.tasks.collect_consumption_data': {\n 'queue': 'reports',\n },\n 'legacy.display_projects.tasks.ProjectReportTask': {\n 'queue': 'reports',\n },\n 'legacy.enpi_reports.tasks.ENPIReportTask': {\n 'queue': 'reports',\n },\n}\n# ######### END CELERY CONFIGURATION\n\n\nSITE_MAIL_ADDRESS = get_secret_setting('SITE_MAIL_ADDRESS')\n\nINSTALLED_APPS = INSTALLED_APPS + (\n # Integration with the WSGI server used for deployment.\n # 'gunicorn',\n)\n\nNETS_KEY_DIR = \"/home/portal/keys\"\n" }, { "alpha_fraction": 0.6233130693435669, "alphanum_fraction": 0.6243512034416199, "avg_line_length": 35.84699630737305, "blob_id": "9287bd66a1ec9ac1dc8ccfb3a91aa0439cd1ff7e", "content_id": "86ebfea86c9bfb38bf6c01c490d2a3736a861a98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6743, "license_type": "no_license", "max_line_length": 77, "num_lines": 183, "path": "/legacy/enpi_reports/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\nimport pytz\n\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import DataSeries\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.providers.models import Provider\n\nfrom .models import ENPIReport\nfrom .models import ENPIUseArea\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ENPIReportRoleTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n with replace_customer(self.customer):\n self.mp = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Test measurement point',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp.consumption = DataSeries(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp.save()\n\n self.enpi_report = ENPIReport(\n customer=self.customer,\n title_plain='Test energy use report')\n\n def test_employees(self):\n self.enpi_report.energy_driver_unit = 'personyear'\n self.enpi_report.save()\n with replace_customer(self.customer):\n employees = DataSeries.objects.create(\n role=DataRoleField.EMPLOYEES,\n unit='person',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.enpi_use_area = ENPIUseArea.objects.create(\n report=self.enpi_report,\n name_plain='coffee production',\n energy_driver=employees)\n self.enpi_use_area.measurement_points.add(self.mp)\n\n self.assertEqual(\n self.enpi_report.energy_driver_role,\n DataRoleField.EMPLOYEES)\n\n self.assertEqual(\n self.enpi_report.enpi_role,\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES)\n\n self.assertTrue(\n PhysicalQuantity.compatible_units(\n self.enpi_report.enpi_unit,\n 'kilowatt*hour*person^-1*second^-1'))\n\n def test_area(self):\n self.enpi_report.energy_driver_unit = 'squaremeteryear'\n self.enpi_report.save()\n\n with replace_customer(self.customer):\n area = DataSeries.objects.create(\n role=DataRoleField.AREA,\n unit='meter^2',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.enpi_use_area = ENPIUseArea.objects.create(\n report=self.enpi_report,\n name_plain='coffee production',\n energy_driver=area)\n self.enpi_use_area.measurement_points.add(self.mp)\n\n self.assertEqual(\n self.enpi_report.energy_driver_role,\n DataRoleField.AREA)\n\n self.assertEqual(\n self.enpi_report.enpi_role,\n DataRoleField.CONSUMPTION_UTILIZATION_AREA)\n\n self.assertTrue(\n PhysicalQuantity.compatible_units(\n self.enpi_report.enpi_unit,\n 'kilowatt*hour*meter^-2*second^-1'))\n\n def test_production(self):\n self.enpi_report.energy_driver_unit = 'production_a'\n self.enpi_report.save()\n\n with replace_customer(self.customer):\n production = DataSeries.objects.create(\n role=DataRoleField.PRODUCTION,\n unit='production_a',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.enpi_use_area = ENPIUseArea.objects.create(\n report=self.enpi_report,\n name_plain='coffee production',\n energy_driver=production)\n self.enpi_use_area.measurement_points.add(self.mp)\n\n self.assertEqual(\n self.enpi_report.energy_driver_role,\n DataRoleField.PRODUCTION)\n\n self.assertEqual(\n self.enpi_report.enpi_role,\n DataRoleField.PRODUCTION_ENPI)\n\n self.assertTrue(\n PhysicalQuantity.compatible_units(\n self.enpi_report.enpi_unit,\n 'kilowatt*hour*production_a^-1'))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ENPIUseAreaCleanTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n with replace_customer(self.customer):\n self.mp = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Test measurement point',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp.consumption = DataSeries(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp.save()\n\n self.enpi_report = ENPIReport.objects.create(\n customer=self.customer,\n title_plain='Test energy use report',\n energy_driver_unit='person')\n\n def test_validates(self):\n with replace_customer(self.customer):\n employees = DataSeries.objects.create(\n role=DataRoleField.EMPLOYEES,\n unit='person',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.enpi_use_area = ENPIUseArea(\n report=self.enpi_report,\n name_plain='coffee production',\n energy_driver=employees)\n\n self.enpi_use_area.full_clean()\n\n def test_bad_energy_driver_unit_validation_error(self):\n with replace_customer(self.customer):\n area = DataSeries.objects.create(\n role=DataRoleField.AREA,\n unit='meter*meter',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.enpi_use_area = ENPIUseArea(\n report=self.enpi_report,\n name_plain='coffee production',\n energy_driver=area)\n\n with self.assertRaises(ValidationError):\n self.enpi_use_area.full_clean()\n" }, { "alpha_fraction": 0.708053708076477, "alphanum_fraction": 0.709172248840332, "avg_line_length": 40.58139419555664, "blob_id": "804ad5194694320b0bb4fabb968f4a0995302550", "content_id": "10e19c3de25374fcb24c4b288c19bd25246484d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1788, "license_type": "no_license", "max_line_length": 79, "num_lines": 43, "path": "/gridplatform/utils/iterpairs.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .decorators import deprecated\nfrom .iter_ext import pairwise, pairwise_extended\n\n\n# With include_final=False, this gives the same behaviour as \"pairwise\" on\n# http://docs.python.org/2/library/itertools.html#recipes\n# Having two functions is clearer than include_final here; and the behaviour of\n# pairwise --- i.e. like include_final=False is a better \"default\", but\n# changing it without renaming the function would be problematic...\n@deprecated('use pairwise/pairwise_extended from gridplatform.utils.iter_ext')\ndef iterpairs(iterable, include_final=True):\n \"\"\"\n Translate an iterable to an iterable over a sequence of pairs of (current,\n next).\n\n This is intended as a helper when implementing tranformations from\n (timestamp, value)-sequences to (timestamp_from, timestamp_to,\n value)-sequences, for the cases where the from/to timestamps can be taken\n from the timestamps of the \"current\" and \"next\" elements in the sequence.\n\n Example use::\n for current_sample, next_sample in iterpairs(samples):\n yield range_sample(\n current_sample.timestamp,\n getattr(next_sample, 'timestamp', max_time),\n current_sample.value)\n\n @see: L{Sample} which defines samples and\n L{range_sample<legacy.measurementpoints.samples.range_sample>} which\n construct ranged samples, such as in the example above.\n\n @param include_final: If C{True}, the final output pair will consist of the\n final input pair and C{None} for \"next\"; if C{False}, this pair will not be\n included.\n \"\"\"\n if include_final:\n return pairwise_extended(iterable)\n else:\n return pairwise(iterable)\n" }, { "alpha_fraction": 0.6477404236793518, "alphanum_fraction": 0.6496716737747192, "avg_line_length": 33.29138946533203, "blob_id": "370bbb426192b45a31f881f8fca3f3fc8fd823e5", "content_id": "a76c7c6dfc14fbd5c7c1bf7df38e1bc072799373", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5178, "license_type": "no_license", "max_line_length": 74, "num_lines": 151, "path": "/gridplatform/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\nimport django.contrib.auth.models\nfrom django.conf import settings\nfrom django.conf.urls import include\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import RedirectView\nimport djcelery.models\n\nfrom gridplatform.utils.urls import restricted_url\n\n\njs_info_dict = {\n 'packages': (\n 'legacy.website',\n 'legacy.manage_devices',\n 'legacy.manage_customers',\n ),\n}\n\n\nurlpatterns = patterns(\n '',\n (r'^i18n/', include('django.conf.urls.i18n')),\n (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),\n (r'^jserror/', include('gridplatform.jserror.urls')),\n url(r'^task_status/$',\n 'gridplatform.utils.views.task_status',\n name='task_status'),\n url(r'^manage/customers/', include('legacy.manage_customers.urls')),\n url(r'^manage/agents/', include('legacy.setup_agents.urls')),\n url(r'^locations/', include('legacy.manage_locations.urls')),\n url(r'^groups/', include('legacy.manage_collections.urls')),\n url(r'^devices/', include('legacy.manage_devices.urls')),\n url(r'^measurementpoints/',\n include(\n 'legacy.manage_measurementpoints.urls',\n namespace='manage_measurementpoints')),\n url(r'^overview/details/',\n include('legacy.display_measurementpoints.urls')),\n url(r'^overview/indexes/',\n include('legacy.display_indexes.urls')),\n url(r'^projects/', include('legacy.display_projects.urls')),\n url(r'^users/', include('legacy.manage_users.urls')),\n url(r'^widgets/', include('legacy.display_widgets.urls')),\n url(r'^userprofile/', include('legacy.edit_userprofile.urls')),\n url(r'^rules/', include('legacy.manage_rules.urls')),\n url(r'^indexes/', include('legacy.manage_indexes.urls')),\n url(r'^reports/', include('legacy.manage_reports.urls')),\n url(r'', include('legacy.website.urls')),\n url('^energy_use_reports/',\n include('legacy.energy_use_reports.urls')),\n url('^enpi_reports/',\n include('legacy.enpi_reports.urls')),\n url(r'^report_generators/', include('gridplatform.reports.urls')),\n url(r'^project_generators/', include('legacy.projects.urls')),\n url(r'^start/',\n include('energymanager.start_site.urls', namespace='start_site')),\n url(r'^user/', include('gridplatform.users.urls', namespace='users')),\n url(r'^Wibeee/', include('gridplatform.smilics.urls')),\n # Provider site\n restricted_url(\n r'^admin/',\n include('energymanager.provider_site.urls',\n namespace='provider_site'),\n permission='users.access_provider_site',\n requires_provider=True),\n restricted_url(\n r'^configuration/',\n include('energymanager.configuration_site.urls',\n namespace='configuration_site'),\n permission='users.access_provider_site',\n requires_provider=True),\n # LED Light site\n restricted_url(\n r'^led_light/',\n include('energymanager.led_light_site.urls',\n namespace='led_light_site'),\n permission='users.access_led_light_site'),\n\n # HACK to restrict project urls\n # TODO: Figure out why restricted_url doesn't work in app url files\n restricted_url(\n r'^led_light/',\n include('energymanager.led_light_site.restricted_urls',\n namespace='led_light_site_projects'),\n permission='users.access_led_light_site_projects'),\n\n # Access price_relay site\n restricted_url(\n r'^price_relay/',\n include('energymanager.price_relay_site.urls',\n namespace='price_relay_site'),\n permission='users.access_price_relay_site'),\n\n # Project site\n restricted_url(\n r'^escolite/',\n include('energymanager.project_site.urls',\n namespace='project_site'),\n permission='users.access_project_site'),\n\n # Datahub site\n restricted_url(\n r'^datahub/',\n include('energymanager.datahub_site.urls',\n namespace='datahub_site'),\n permission='users.access_datahub_site'),\n\n\n # REST API\n url(r'^api/current/',\n RedirectView.as_view(url=reverse_lazy('api:api-root')),\n name='api-current-version'),\n url(r'^api/v3/', include('gridplatform.api', namespace='api')),\n\n)\n\n\nadmin.autodiscover()\n\nadmin.site.unregister(django.contrib.auth.models.User)\n\nadmin.site.unregister(djcelery.models.TaskState)\nadmin.site.unregister(djcelery.models.WorkerState)\nadmin.site.unregister(djcelery.models.IntervalSchedule)\nadmin.site.unregister(djcelery.models.CrontabSchedule)\nadmin.site.unregister(djcelery.models.PeriodicTask)\n\n\nurlpatterns += patterns(\n '',\n restricted_url(\n r'^sysadmin/',\n include(admin.site.urls),\n requires_is_staff=True),\n)\n\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns(\n '',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n url(r'^qunit/', include('django_qunit.urls')),\n )\n" }, { "alpha_fraction": 0.8015872836112976, "alphanum_fraction": 0.8029100298881531, "avg_line_length": 28.076923370361328, "blob_id": "adbe22fed04356d2e9b2b7e68169eb059282315c", "content_id": "de3d9724caeb0bfbc3270c0ac2871ed9f5a87296", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 756, "license_type": "no_license", "max_line_length": 41, "num_lines": 26, "path": "/documentation/source/apps.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Apps\n****\n\n.. toctree::\n apps/gridplatform/bootstrap\n apps/gridplatform/co2conversions\n apps/gridplatform/condensing\n apps/gridplatform/consumptions\n apps/gridplatform/costcompensations\n apps/gridplatform/customer_datasources\n apps/gridplatform/customers\n apps/gridplatform/datasequences\n apps/gridplatform/datasources\n apps/gridplatform/encryption\n apps/gridplatform/energyperformances\n apps/gridplatform/global_datasources\n apps/gridplatform/productions\n apps/gridplatform/provider_datasources\n apps/gridplatform/providers\n apps/gridplatform/reports\n apps/gridplatform/rest\n apps/gridplatform/tariffs\n apps/gridplatform/token_auth\n apps/gridplatform/trackuser\n apps/gridplatform/users\n apps/gridplatform/utils\n" }, { "alpha_fraction": 0.6437994837760925, "alphanum_fraction": 0.6701846718788147, "avg_line_length": 20.05555534362793, "blob_id": "5ccb6582f30fdda03aff5b23d14dc362b9517fa1", "content_id": "acf29e1805275e6b8054521471fb0ce7d144fc12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 379, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/test_javascript.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nurl='http://127.0.0.1:8000'\nif [ ! -z \"$QUNIT_SERVER_URL\" ]\nthen\n\turl=$QUNIT_SERVER_URL\nfi\n\nif ! curl --output /dev/null --silent --head --fail \"$url\"; then\n echo \"No server running on ${url}\"\n exit\nfi\n\n\necho 'Running bootstrap tests'\nphantomjs qunit/runner.js \"${url}/qunit/bootstrap\"\necho 'Running utils tests'\nphantomjs qunit/runner.js \"${url}/qunit/utils\"\n" }, { "alpha_fraction": 0.7110576629638672, "alphanum_fraction": 0.715624988079071, "avg_line_length": 32.279998779296875, "blob_id": "dbd4806193620359d69e3366259e186c2542f308", "content_id": "ba604a74f6f9ebd46524b267ab03e061dbed8186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4160, "license_type": "no_license", "max_line_length": 80, "num_lines": 125, "path": "/gridplatform/consumptions/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nfrom rest_framework.decorators import link\nimport rest_framework.reverse\nfrom rest_framework.response import Response\nfrom rest_framework import status\n\nfrom gridplatform.datasequences.views import HourlyDataView\nfrom gridplatform.rest.viewsets import NestedMixin\n\nfrom . import models\nfrom . import serializers\n\n\nclass HourlyConsumptionView(NestedMixin, HourlyDataView):\n method_name = 'development_sequence'\n\n def get(self, request, consumption_id=None, format=None):\n consumption = get_object_or_404(\n models.Consumption, pk=consumption_id)\n timezone = consumption.customer.timezone\n return self._get(request, consumption, timezone)\n\n\nclass Consumption(viewsets.ModelViewSet):\n model = models.Consumption\n serializer_class = serializers.Consumption\n filter_fields = ('name', 'unit', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyConsumptionView.as_view()\n return view_fn(request, consumption_id=pk)\n\n\nclass HourlyMainConsumptionView(NestedMixin, HourlyDataView):\n method_name = 'utility_sequence'\n unit_field = 'utility_unit'\n\n def get(self, request, consumption_id=None, format=None):\n consumption = get_object_or_404(\n models.MainConsumption, pk=consumption_id)\n timezone = consumption.customer.timezone\n return self._get(\n request, consumption, timezone)\n\n\nclass MainConsumption(viewsets.ModelViewSet):\n model = models.MainConsumption\n serializer_class = serializers.MainConsumption\n filter_fields = ('name', 'customer')\n\n @link()\n def hourly(self, request, pk=None):\n view_fn = HourlyMainConsumptionView.as_view()\n return view_fn(request, consumption_id=pk)\n\n\nclass HourlyConsumptionGroup(NestedMixin, HourlyDataView):\n method_name = 'utility_sequence'\n unit_field = 'utility_unit'\n\n def get(self, request, consumption_id=None, format=None):\n consumption = get_object_or_404(\n models.ConsumptionGroup, pk=consumption_id)\n timezone = consumption.customer.timezone\n return self._get(\n request, consumption, timezone)\n\n\nclass ConsumptionGroup(viewsets.ModelViewSet):\n model = models.ConsumptionGroup\n serializer_class = serializers.ConsumptionGroup\n filter_fields = ('name', 'customer')\n\n @link()\n def hourly(self, request, pk=None):\n view_fn = HourlyConsumptionGroup.as_view()\n return view_fn(request, consumption_id=pk)\n\n\nclass ConsumptionParentMixin(object):\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.DATA, files=request.FILES)\n\n if serializer.is_valid():\n\n self.pre_save(serializer.object)\n serializer.object.datasequence_id = kwargs.pop('datasequence_id')\n self.object = serializer.save(force_insert=True)\n\n self.post_save(self.object, created=True)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED,\n headers=headers)\n\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass NonpulsePeriod(\n NestedMixin, ConsumptionParentMixin, viewsets.ModelViewSet):\n model = models.NonpulsePeriod\n serializer_class = serializers.NonpulsePeriod\n\n\nclass PulsePeriod(NestedMixin, ConsumptionParentMixin, viewsets.ModelViewSet):\n model = models.PulsePeriod\n serializer_class = serializers.PulsePeriod\n\n\nclass SingleValuePeriod(\n NestedMixin, ConsumptionParentMixin, viewsets.ModelViewSet):\n model = models.SingleValuePeriod\n serializer_class = serializers.SingleValuePeriod\n\n\nclass OfflineTolerance(\n NestedMixin, ConsumptionParentMixin, viewsets.ModelViewSet):\n model = models.OfflineTolerance\n serializer_class = serializers.OfflineTolerance\n" }, { "alpha_fraction": 0.5284122824668884, "alphanum_fraction": 0.531267523765564, "avg_line_length": 34.78559494018555, "blob_id": "6f9a91be80c0174ce62031ac375262c7a1d00d81", "content_id": "098e201da481a1957dfb18341570fc65c96fa6a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 21365, "license_type": "no_license", "max_line_length": 155, "num_lines": 597, "path": "/gridplatform/bootstrap/static/bootstrap/base.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true */\n/*global $, jQuery, gettext, pgettext, get_format*/\n\nvar ui = window.ui || {};\n\n// The javascript version of the icon templatetag\nui.icon = function (iconName, size, spin) {\n 'use strict';\n var icon = $('<i class=\"fa\"></i>');\n icon.addClass('fa-' + iconName);\n if (size) {\n icon.addClass('fa-' + size);\n }\n if (spin) {\n icon.addClass('fa-spin');\n }\n\n //hack html() returns the html contents of the first node\n return $('<div>').append(icon).html();\n};\n\nui.parseNumber = function (numberString) {\n 'use strict';\n var thousandSeparator = get_format('THOUSAND_SEPARATOR'),\n decimalSeparator = get_format('DECIMAL_SEPARATOR');\n while (numberString.length !== numberString.replace(thousandSeparator, '').length) {\n numberString = numberString.replace(thousandSeparator, '');\n }\n return parseFloat(numberString.replace(decimalSeparator, '.'));\n};\n\nui.formatNumber = function (number, decimalPlaces) {\n 'use strict';\n var formattedWithoutThousandSeparator = number.toFixed(decimalPlaces).replace('.', get_format('DECIMAL_SEPARATOR')),\n addThousandSeparator = function (numberString, thousandSeparator) {\n var rx = /(\\d+)(\\d{3})/;\n return numberString.replace(/\\d+/, function (w) {\n while (rx.test(w)) {\n w = w.replace(rx, '$1' + thousandSeparator + '$2');\n }\n return w;\n });\n };\n return addThousandSeparator(formattedWithoutThousandSeparator, get_format('THOUSAND_SEPARATOR'));\n};\n\nui.addFormsetForm = function (event) {\n 'use strict';\n event.preventDefault();\n var parent = $(event.target).closest('div.box'),\n emptyForm = parent.find('.empty-form'),\n newForm = emptyForm.clone(),\n totalForms = parent.find('input[name$=\"TOTAL_FORMS\"]'),\n newId = totalForms.val();\n newForm.find('div, input, select, li, label').each(function () {\n var input = $(this);\n if (input.attr(\"name\")) {\n input.attr('name', input.attr('name').replace('__prefix__', newId));\n }\n if (input.attr(\"id\")) {\n input.attr('id', input.attr('id').replace('__prefix__', newId));\n }\n if (input.attr(\"for\")) {\n input.attr('for', input.attr('for').replace('__prefix__', newId));\n }\n });\n newForm.removeClass('empty-form').show();\n totalForms.val(parseInt(totalForms.val(), 10) + 1);\n newForm.appendTo(emptyForm.parent());\n};\n\n\nui.datepickerOptions = (function () {\n 'use strict';\n var format = get_format('DATE_INPUT_FORMATS')[0],\n // Python/Django format to Bootstrap Datepicker format...\n mapping = {\n '%d': 'dd',\n '%m': 'mm',\n '%Y': 'yyyy',\n '%y': 'yy'\n },\n capitalize = function (str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n };\n _.forEach(mapping, function (js, python) {\n format = format.replace(python, js);\n });\n jQuery.fn.datepicker.dates.current = {\n days: [\n gettext('Sunday'),\n gettext('Monday'),\n gettext('Tuesday'),\n gettext('Wednesday'),\n gettext('Thursday'),\n gettext('Friday'),\n gettext('Saturday'),\n gettext('Sunday')\n ],\n daysShort: [\n gettext('Sun'),\n gettext('Mon'),\n gettext('Tue'),\n gettext('Wed'),\n gettext('Thu'),\n gettext('Fri'),\n gettext('Sat'),\n gettext('Sun')\n ],\n daysMin: [\n pgettext('weekday', 'Su'),\n pgettext('weekday', 'Mo'),\n pgettext('weekday', 'Tu'),\n pgettext('weekday', 'We'),\n pgettext('weekday', 'Th'),\n pgettext('weekday', 'Fr'),\n pgettext('weekday', 'Sa'),\n pgettext('weekday', 'Su')\n ],\n months: [\n capitalize(gettext('January')),\n capitalize(gettext('February')),\n capitalize(gettext('March')),\n capitalize(gettext('April')),\n capitalize(gettext('May')),\n capitalize(gettext('June')),\n capitalize(gettext('July')),\n capitalize(gettext('August')),\n capitalize(gettext('September')),\n capitalize(gettext('October')),\n capitalize(gettext('November')),\n capitalize(gettext('December'))\n ],\n monthsShort: [\n capitalize(gettext('jan')),\n capitalize(gettext('feb')),\n capitalize(gettext('mar')),\n capitalize(gettext('apr')),\n capitalize(gettext('may')),\n capitalize(gettext('jun')),\n capitalize(gettext('jul')),\n capitalize(gettext('aug')),\n capitalize(gettext('sep')),\n capitalize(gettext('oct')),\n capitalize(gettext('nov')),\n capitalize(gettext('dec'))\n ],\n today: gettext('Today')\n };\n return {\n // from Django i18n\n weekStart: parseInt(get_format('FIRST_DAY_OF_WEEK'), 10),\n format: format,\n autoclose: true,\n language: 'current'\n };\n}());\n\n/*\n target: A jquery object that should have the popup attached\n options: A list of filters\n contentLoader: A jquery object containing the contentLoader div\n*/\nui.popoverFilter = function (target, options, contentLoader) {\n 'use strict';\n var popop = $('<div><div class=\"arrow\"></div></div>'),\n content,\n listContent,\n filterContent,\n label,\n count,\n countChecked,\n checkbox,\n selected = [],\n popover,\n extra = contentLoader.data('extra');\n\n if (extra !== undefined) {\n try {\n extra = JSON.parse(extra);\n } catch (err) {\n extra = {};\n }\n } else {\n extra = {};\n }\n jQuery.each(options, function (index, filter) {\n if (extra[filter.name] === undefined) {\n extra[filter.name] = [];\n }\n });\n filterContent = function () {\n jQuery.each(options, function (index, filter) {\n if (extra[filter.name]) {\n selected = extra[filter.name];\n }\n count = filter.choices.length;\n countChecked = 0;\n content = $('<div></div>').attr('id', filter.name).addClass('filter');\n\n $('<h3></h3>').addClass('popover-title').text(filter.verbose).appendTo(content);\n listContent = $('<div></div>').addClass('popover-content').appendTo(content);\n jQuery.each(filter.choices, function (index, choice) {\n label = $('<div><label></label></div>').appendTo(listContent);\n checkbox = $('<input type=\"checkbox\">').val(choice[0]).appendTo(label);\n if (_.contains(selected, String(choice[0]))) {\n checkbox.prop('checked', true);\n countChecked += 1;\n }\n $('<span></span>').text(' ' + choice[1]).appendTo(label);\n });\n if (filter.allNone) {\n label = $('<div><label></label></div>').prependTo(listContent);\n checkbox = $('<input type=\"checkbox\">').addClass('check-all').appendTo(label);\n $('<span></span>').text(' ' + filter.allNoneVerbose).appendTo(label);\n if (countChecked === count) {\n checkbox.prop('checked', true);\n } else if (countChecked) {\n checkbox.prop('indeterminate', true);\n }\n }\n popop.append(content);\n });\n\n return popop;\n };\n $(document).on('change', '.popover .filter input.check-all', function (event) {\n checkbox = $(event.target);\n var isChecked = checkbox.prop('checked'),\n filter = checkbox.closest('.filter');\n filter.find('input:not(.check-all)').prop('checked', isChecked);\n filter.find('input:not(.check-all)').change();\n });\n $(document).on('change', '.popover .filter input:not(.check-all)', function (event) {\n var filter = $(event.target).closest('.filter'),\n ids = [],\n anyChecked = false,\n anyUnchecked = false;\n filter.find('input:not(.check-all)').each(function () {\n checkbox = $(this);\n if (checkbox.prop('checked')) {\n ids.push(checkbox.attr('value'));\n anyChecked = true;\n } else {\n anyUnchecked = true;\n }\n });\n if (anyChecked && anyUnchecked) {\n filter.find('.check-all').prop('checked', false);\n filter.find('.check-all').prop('indeterminate', true);\n } else {\n // all checked or all unchecked\n filter.find('.check-all').prop('indeterminate', false);\n filter.find('.check-all').prop('checked', anyChecked);\n }\n extra[filter.attr('id')] = ids;\n ui.loadContent(contentLoader, extra, contentLoader.closest('.box').find('.list-search input').val());\n });\n\n // Content needs to be an empty space, else it doesn't get shown\n // We set the real content futher down\n target.popover({\n html: true,\n placement: 'bottom',\n content: ' ',\n title: ''\n });\n\n popover = target.data('bs.popover');\n popover.setContent = function () {\n var $tip = this.tip();\n if (!$tip.hasClass('filter')) {\n $tip.html(filterContent());\n }\n $tip.removeClass('fade top bottom left right in').addClass('filter');\n };\n};\n\n\nui.getQuerystrings = function (url) {\n 'use strict';\n var querystrings = {},\n match,\n pl = /\\+/g,\n search = /([^&=]+)=?([^&]*)/g,\n decode = function (s) { return decodeURIComponent(s.replace(pl, \" \")); },\n query = \"\";\n\n if (url === undefined) {\n query = window.location.search.substring(1);\n } else {\n if (url.indexOf('?') !== -1) {\n query = url.split('?')[1];\n }\n }\n\n while (match = search.exec(query)) {\n querystrings[decode(match[1])] = decode(match[2]);\n }\n return querystrings;\n};\n\nui.updateLocationHash = function (hashObject, override) {\n 'use strict';\n var currentHash = window.location.hash.replace(/^#/, ''),\n override = override || false,\n currentObject = {};\n\n if (currentHash !== \"\") {\n currentObject = JSON.parse(decodeURIComponent(currentHash));\n if (!override) {\n hashObject = jQuery.extend(currentObject, hashObject);\n }\n }\n\n window.location.hash = encodeURIComponent(\n JSON.stringify(hashObject));\n};\n\nui.getHashValueFromKey = function (key) {\n var currentHash = window.location.hash.replace(/^#/, ''),\n hashObject = {}\n result = \"\";\n\n if (currentHash !== \"\") {\n hashObject = JSON.parse(decodeURIComponent(currentHash));\n if (hashObject[key]) {\n result = hashObject[key];\n }\n }\n return result;\n};\n\nui.generateStringHash = function (string) {\n // Found at http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery\n var hash = 0,\n i,\n chr,\n len;\n if (string.length === 0) {\n return hash;\n }\n for (i = 0, len = string.length; i < len; i++) {\n chr = string.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0; // Convert to 32bit integer\n }\n return hash;\n},\n\n\nui.loadContent = function (selector, extra, query) {\n 'use strict';\n var load,\n storageId = function (url, setting) {\n // remove pagination and similar parameters from storage key\n var baseUrl = url.replace(/\\?.*$/, '');\n return 'contentLoader-' + baseUrl + '-' + setting;\n },\n saveOptions = function (contentLoader) {\n var options = contentLoader.data(),\n url = options.url;\n localStorage.setItem(storageId(url, 'orderby'), options.orderby);\n localStorage.setItem(storageId(url, 'direction'), options.direction);\n },\n loadOptions = function (contentLoader) {\n var url = contentLoader.data('url'),\n orderBy = localStorage.getItem(storageId(url, 'orderby')),\n direction = localStorage.getItem(storageId(url, 'direction')),\n extra = localStorage.getItem(storageId(url, 'extra'));\n if (orderBy) {\n contentLoader.data('orderby', orderBy);\n }\n if (direction) {\n contentLoader.data('direction', direction);\n }\n if (extra !== null) {\n contentLoader.data('extra', extra);\n }\n },\n setUpSorting = function (contentLoader) {\n var options = contentLoader.data();\n // First remove the old sorting direction indicator\n contentLoader.find('th').removeClass('sorting_asc sorting_desc');\n // Then add the current one\n contentLoader.find('th[data-orderby=\"' + options.orderby + '\"]').\n addClass('sorting_' + (options.direction || 'asc'));\n // Make every sortable th clickable.\n contentLoader.find('th.sorting').click(function () {\n var sorting = $(this),\n orderBy = sorting.data('orderby');\n if (orderBy === options.orderby) {\n if (options.direction === 'asc' || !options.direction) {\n contentLoader.data('direction', 'desc');\n } else {\n contentLoader.data('direction', 'asc');\n }\n }\n contentLoader.data('orderby', orderBy);\n saveOptions(contentLoader);\n load(contentLoader);\n });\n },\n setUpPagination = function (contentLoader) {\n contentLoader.find('.pagination a').click(function (event) {\n event.preventDefault();\n event.stopPropagation();\n contentLoader.data('url', $(this).attr('href'));\n load(contentLoader);\n });\n },\n updateLocationHash = function (contentLoader) {\n var options = contentLoader.data(),\n hashObject = {},\n page = ui.getQuerystrings(options.url).page;\n if (page) {\n hashObject[options.urlHash] = page;\n ui.updateLocationHash(hashObject);\n }\n },\n urlHashString = function (url) {\n var location = url;\n if (url.indexOf('?') !== -1) {\n location = url.split('?')[0];\n }\n return ui.generateStringHash(location);\n },\n extractPageFromHash = function (contentLoader, page) {\n var pageFromHash = ui.getHashValueFromKey(contentLoader.data('urlHash'));\n if (pageFromHash) {\n return pageFromHash;\n }\n return page;\n };\n load = function (contentLoader) {\n var options = contentLoader.data(),\n urlHash = options.urlHash || undefined,\n page;\n if (!options.url) {\n throw \"You must specify an URL for the content loader!\";\n }\n contentLoader.html('<i class=\"fa fa-spinner fa-spin\"></i>');\n if (!options.urlHash) {\n urlHash = urlHashString(options.url);\n contentLoader.data('urlHash', urlHash);\n }\n updateLocationHash(contentLoader);\n page = extractPageFromHash(contentLoader, ui.getQuerystrings(options.url).page);\n jQuery.ajax(options.url, {\n type: 'GET',\n data: {\n o: options.orderby,\n ot: options.direction || 'asc',\n extra: options.extra || undefined,\n page: page,\n q: query\n }\n }).done(function (data) {\n contentLoader.empty(); // Kill spinner\n // Hack: jquery only searches inside the outmost block,\n // so we have to append a div around the atual data\n if (contentLoader.hasClass('search-block') && $('.no-data', $('<div></div>').append(data)).length > 0) {\n contentLoader.closest('.box').fadeOut(500, function () {\n $(this).remove();\n });\n } else {\n contentLoader.append(data);\n }\n // Enable rowlink\n contentLoader.find('table[data-provides=\"rowlink\"]').rowlink();\n setUpSorting(contentLoader);\n setUpPagination(contentLoader);\n contentLoader.trigger('contentloader.loaded');\n }).fail(function () {\n contentLoader.empty(); // Kill spinner\n // TODO: Report (connection?) error?\n });\n };\n $(selector).each(function () {\n var contentLoader = $(this),\n url;\n if (extra !== undefined) {\n url = contentLoader.data('url');\n localStorage.setItem(storageId(url, 'extra'), JSON.stringify(extra));\n }\n loadOptions(contentLoader);\n load(contentLoader);\n });\n};\n\n\nui.initializeSearchField = function (selector) {\n 'use strict';\n var field = $(selector),\n input = field.find('input');\n input.keydown(function (event) {\n if (event.keyCode === 13) {\n window.location = field.data('url') + '?q=' + encodeURIComponent(input.val());\n }\n });\n};\n\n$(document).ready(function () {\n 'use strict';\n var changed = false,\n submit = false;\n // NOTE: wrap stuff in something with class empty-form to *not* use chosen or multiselect --- should be done for empyt_form for JS-insert in particular\n $('select').not('.empty-form select, [multiple=multiple]').chosen({enable_split_word_search: true, search_contains: true});\n\n $('select[multiple=multiple]').not('.empty-form select').multiSelect({\n selectableHeader: \"<input type='text' class='charfield textinput form-control search-input' autocomplete='off'>\",\n selectionHeader: \"<input type='text' class='charfield textinput form-control search-input' autocomplete='off'>\",\n afterInit: function () {\n var multiselect = this,\n selectableSearch = multiselect.$selectableUl.prev(),\n selectionSearch = multiselect.$selectionUl.prev(),\n selectableSearchString = '#' + multiselect.$container.attr('id') + ' .ms-elem-selectable:not(.ms-selected)',\n selectionSearchString = '#' + multiselect.$container.attr('id') + ' .ms-elem-selection.ms-selected';\n\n multiselect.qs1 = selectableSearch.quicksearch(selectableSearchString);\n multiselect.qs2 = selectionSearch.quicksearch(selectionSearchString);\n },\n afterSelect: function () {\n this.qs1.cache();\n this.qs2.cache();\n },\n afterDeselect: function () {\n this.qs1.cache();\n this.qs2.cache();\n }\n });\n\n $('.dateinput, .date-picker').datepicker(ui.datepickerOptions);\n\n $('.list-datepicker i').click(function () {\n $(this).parent().find('input.date-picker').datepicker().focus();\n });\n\n // Makes it possible to click on the icon to show the datepicker\n $('#customerfilter').quicksearch('#customer-select-modal .list-group a');\n\n ui.loadContent('.content-loader');\n ui.initializeSearchField('#search');\n\n $('body').on('click', '.popover .close', function () {\n $(this).parent().hide();\n });\n\n // It should not be possible to generate two POSTs in a row by mistake. For\n // this reason buttons can be decorated with the \"disable-on-click\" class.\n $('.disable-reenable-on-click').click(function () {\n var button = $(this);\n button.addClass('disabled');\n window.setTimeout(function () {\n button.removeClass('disabled');\n }, 500);\n });\n\n //Disable form submit on Enter press\n $('form').bind(\"keyup keypress\", function (e) {\n var code = e.keyCode || e.which;\n if (code === 13 && e.target.nodeName !== \"TEXTAREA\") {\n e.preventDefault();\n return false;\n }\n });\n\n $('form :input').not('.ms-selectable .search-input').change(function () {\n changed = true;\n });\n\n $(\"form button[type=submit], form input[type=submit]\").click(function () {\n submit = true;\n });\n\n\n window.onbeforeunload = function () {\n if (changed && !submit) {\n submit = false;\n return gettext('Your changes are not saved');\n }\n };\n\n $('.list-search input').each(function () {\n var input = $(this),\n oldQuery = '';\n input.on('keydown keyup change cut paste input', _.debounce(function () {\n var query = input.val(),\n contentLoader;\n if (query !== oldQuery) {\n oldQuery = query;\n contentLoader = input.closest('.box').find('.content-loader');\n ui.loadContent(contentLoader, undefined, query);\n }\n }, 250));\n });\n});\n" }, { "alpha_fraction": 0.5789189338684082, "alphanum_fraction": 0.5832432508468628, "avg_line_length": 29.83333396911621, "blob_id": "fd78e11d579006ebbfbd977dcdcde716b55a65d8", "content_id": "b8db58563030d5ea6f42ef9703eee9d3f5cd9343", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1850, "license_type": "no_license", "max_line_length": 77, "num_lines": 60, "path": "/legacy/nordpool/management/commands/import_nordpool.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport ftplib\n\nfrom isoweek import Week\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.transaction import commit_on_success\n\nfrom legacy.nordpool.legacy import fetch_import_week\nfrom legacy.nordpool.legacy import prices_today\n\n\nclass Command(BaseCommand):\n args = '[week [year]]'\n help = 'Import Nordpool spot prices for specific week plus one. ' + \\\n 'Week/year defaults to current week/year.'\n\n def handle(self, *args, **options):\n week_number = None\n year = None\n\n try:\n week_number = int(args[0])\n year = int(args[1])\n except IndexError:\n pass\n\n today = datetime.datetime.now().date()\n if week_number is None:\n assert year is None\n this_week = Week.withdate(today)\n elif year is None:\n assert week_number is not None\n year = today.year\n this_week = Week(year, week_number)\n else:\n assert week_number is not None\n assert year is not None\n this_week = Week(year, week_number)\n next_week = this_week + 1\n\n try:\n with commit_on_success():\n fetch_import_week(this_week.year, this_week.week)\n with commit_on_success():\n fetch_import_week(next_week.year, next_week.week)\n except ftplib.error_perm as e:\n if e.args[0].startswith('550'):\n # File not found error --- usually caused by file not yet\n # uploaded to Nordpool FTP server...\n pass\n else:\n raise\n\n if not prices_today():\n print \"Warning: Some spot prices does not have prices for today!\"\n" }, { "alpha_fraction": 0.6628587245941162, "alphanum_fraction": 0.6673167943954468, "avg_line_length": 28.178861618041992, "blob_id": "3138c2906aea89711e5b2e2bb0cb3e572a782c6e", "content_id": "f5729b0aba218c44cade14aebf2775ea97f1ef73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3589, "license_type": "no_license", "max_line_length": 75, "num_lines": 123, "path": "/gridplatform/utils/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport calendar\nfrom fractions import Fraction\nfrom decimal import Decimal\n\nimport pytz\nfrom django.db.models.query import QuerySet\n\nfrom .decorators import deprecated\nfrom .unitconversion import PhysicalQuantity\n\n\n__all__ = ['DATETIME_MIN', 'DATETIME_MAX', 'unix_timestamp', 'deprecated']\n\n\n# Shift by 24 hours to leave room for converting to any local timezone.\n#\n# shift by additional one year, to allow for condense.floor\nDATETIME_MIN = datetime.datetime.min.replace(tzinfo=pytz.utc) + \\\n datetime.timedelta(days=366)\nDATETIME_MAX = datetime.datetime.max.replace(tzinfo=pytz.utc) - \\\n datetime.timedelta(days=366)\n\n\ndef unix_timestamp(timestamp):\n \"\"\"\n Convert a :class:`datetime.datetime` to a POSIX timestamp.\n\n :param timestamp: The :class:`datetime.datetime` to convert. If naive,\n assumed to already be in UTC.\n\n :return: 1970 epoch offset in seconds, i.e. a POSIX timestamp,\n representing the timestamp given.\n \"\"\"\n assert isinstance(timestamp, datetime.datetime)\n return calendar.timegm(timestamp.utctimetuple())\n\n\ndef first_last(iterable):\n \"\"\"\n Efficiently extract the first and last element of an iterable.\n\n :raise ValueError: If the iterable is empty.\n\n :return: ``(first, last)`` where ``first`` is the first element in\n ``iterable`` and ``last`` is the last element in ``iterable``.\n \"\"\"\n try:\n if isinstance(iterable, QuerySet):\n raise TypeError('QuerySet does not support negative indexing')\n first = iterable[0]\n last = iterable[-1]\n except TypeError:\n iterator = iter(iterable)\n try:\n last = first = next(iterator)\n except StopIteration:\n raise ValueError('iterable is empty')\n\n for last in iterator:\n pass\n except IndexError:\n raise ValueError('iterable is empty')\n\n return (first, last)\n\n\ndef fraction_to_decimal(fraction):\n \"\"\"\n :return: The given :class:`~fractions.Fraction` converted to a\n :class:`~decimal.Decimal`.\n :param fraction: The given :class:`~fractions.Fraction`\n \"\"\"\n if isinstance(fraction, Fraction):\n return Decimal(fraction.numerator) / fraction.denominator\n else:\n return Decimal(fraction)\n\n\ndef choices_extract_python_identifier(choices, db_value):\n \"\"\"\n Extract the name (python identifier) of the\n :class:`model_utils.Choices` attribute that correspond to a given\n db value.\n\n :param choices: A :class:`model_utils.Choices` instance.\n :param db_value: The given db value.\n :return: A python identifier that corresponds to the given db value.\n \"\"\"\n for key, value in choices._identifier_map.items():\n if value == db_value:\n return key\n raise ValueError('db value %r not found in %r' % (db_value, choices))\n\n\ndef development_sum(datasequences, unit, from_timestamp, to_timestamp):\n \"\"\"\n Function for calculating the sum of developments given a datasequence\n iterable.\n \"\"\"\n values = [\n datasequence.development_sum(from_timestamp, to_timestamp)\n for datasequence\n in datasequences\n ]\n return sum(values, PhysicalQuantity(0, unit))\n\n\ndef sum_or_none(iterable):\n \"\"\"\n Sumarize elements of ``iterable``, but return ``None`` if\n ``iterable`` is empty.\n \"\"\"\n iterable = iter(iterable)\n try:\n first = next(iterable)\n return sum(iterable, first)\n except StopIteration:\n return None\n" }, { "alpha_fraction": 0.6694214940071106, "alphanum_fraction": 0.6714876294136047, "avg_line_length": 25.88888931274414, "blob_id": "14781f6ad01d2b00b8a584a6b2b41631427859d7", "content_id": "92cfb5bef914db7a4a22384e804358ce05bf9cc8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 74, "num_lines": 18, "path": "/gridplatform/trackuser/context_processors.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom . import get_user, get_customer\n\n\ndef trackuser(request):\n \"\"\"\n Provide template context variables for the current user and customer,\n obtained from the global context/user-tracking.\n\n With user impersonation, this user may be different from request.user.\n \"\"\"\n return {\n 'current_user': get_user(),\n 'current_customer': get_customer(),\n }\n" }, { "alpha_fraction": 0.5694618225097656, "alphanum_fraction": 0.5744680762290955, "avg_line_length": 28.592592239379883, "blob_id": "e68cd38a2510c122e7f1ad774c5c0c4992792787", "content_id": "4cff5662e39f0845feff5aa0c1d9efe78ca8cafb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 799, "license_type": "no_license", "max_line_length": 123, "num_lines": 27, "path": "/energymanager/project_site/templates/project_site/_project_list_content.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% load i18n %}\n\n{% load bootstrap_tags %}\n\n{% if object_list %}\n<table class=\"table table-striped table-bordered sorted\" data-provides=\"rowlink\">\n <thead>\n <th class=\"sorting\" data-orderby=\"name_plain\" width=\"90%\">{% trans \"Name\" %}</th>\n <th>{% trans \"Overview\" %}</th>\n </thead>\n <tbody>\n {% for object in object_list %}\n <tr>\n <td>\n <a href=\"{% url \"project_site:project-update\" customer_id=customer.id pk=object.id %}\">{{ object.name_plain }}</a>\n </td>\n <td>\n <a href=\"{% url \"project_site:project-detail\" customer_id=customer.id pk=object.id %}\">{% icon \"arrow-right\" %}</a>\n </td>\n </tr>\n {% endfor %}\n </tbody>\n</table>\n{% include \"bootstrap/_pagination.html\" %}\n{% else %}\n<span>{% trans \"No projects present.\" %}</span>\n{% endif %}\n" }, { "alpha_fraction": 0.5226986408233643, "alphanum_fraction": 0.5264816880226135, "avg_line_length": 27.836362838745117, "blob_id": "781ffb9989d64201a383beb3f5b685863865455f", "content_id": "b4b00322635581edd1221f7790e5d90b8a02e4f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1586, "license_type": "no_license", "max_line_length": 72, "num_lines": 55, "path": "/legacy/manage_devices/templates/manage_devices/pulseconversioninputperiod_form.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% load i18n %}\n{% load l10n %}\n{% load static from staticfiles %}\n\n{% block title %}{% trans \"Settings: Devices\" %}{% endblock title %}\n{% block page_id %}devices-page{% endblock %}\n\n{% block content_heading %}{% trans \"Settings: Devices\" %}{% endblock %}\n\n{% block left_content %}\n<div class=\"clearfix\">\n <form method=\"post\" action=\"{{ request.path }}\">\n <div class=\"overlay-header clearfix\">\n <div class=\"left\"><h4></h4></div>\n <div class=\"right\">\n {% block buttons %}\n <input type=\"submit\" value=\"{% trans \"Save\" %}\" />\n {% endblock buttons %}\n </div>\n </div>\n {% csrf_token %}\n <div class=\"left\">\n <fieldset>\n <label>{% trans 'From:' %}</label>\n {{ form.from_timestamp }}\n {{ form.from_timestamp.errors }}\n </fieldset>\n <fieldset>\n <label>{% trans 'To:' %}</label>\n {{ form.to_timestamp }}\n {{ form.to_timestamp.errors }}\n </fieldset>\n {{ form.non_field_errors }}\n </div>\n <div class=\"left\">\n <fieldset>\n <label>{% trans 'Pulse quantity:' %}</label>\n {{ form.pulse_quantity }}\n {{ form.pulse_quantity.errors }}\n </fieldset>\n <fieldset>\n <label>{% trans 'Output quantity:' %}</label>\n {{ form.output_quantity }}\n {{ form.output_quantity.errors }}\n </fieldset>\n <fieldset>\n <label>{% trans 'Output unit:' %}</label>\n {{ form.output_unit }}\n {{ form.output_unit.errors }}\n </fieldset>\n </div>\n </form>\n</div>\n{% endblock left_content %}\n" }, { "alpha_fraction": 0.7243526577949524, "alphanum_fraction": 0.7423795461654663, "avg_line_length": 55.48147964477539, "blob_id": "f3aed7db4a41b8308eb9ac5c6217982993a17c7c", "content_id": "5ba63e27596d60f6240a9d1bdc77c165f4ff2968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3051, "license_type": "no_license", "max_line_length": 548, "num_lines": 54, "path": "/emonhub/conf/VEDirect.readme.md", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#VE Direct interface Victron products#\n\nThe VE Direct protocol is as binary/ASCII [protocol](https://www.victronenergy.com/upload/documents/VE.Direct-Protocol.pdf) used by [Victron Energy] to communicate between it's products. For those who don't know, Victron is the leading producer of solar inverters and charge controllers designed for the off grid market.\n\n With this interfacer now it's possible to interface data from any VE Direct compatible Victron product with Emon. In this example we use the [BMV 700](https://www.google.rw/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwi14t-MkqfLAhVBExoKHRGeCioQFggbMAA&url=https%3A%2F%2Fwww.victronenergy.com%2Fbattery-monitors%2Fbmv-700&usg=AFQjCNGENUubkSY_HkWGN61NdkP8onXHag&sig2=XjH6HIbtSzwY_kDDKOfsJw), which is a battery monitor. For emon users that have a battery bank, this will allow them to get stats on their batteries very easily.\n\n##Usage and configuration##\nThere is a sample vedirect.emonhub.conf file located in this directory.\nThis is already preconfigured to talk to a BMV700 that is connect to the emonpi via isolated [USB cable](https://www.victronenergy.com/accessories/ve-direct-to-usb-interface)\n\nEach VE Direct product has it's own source of variables that it delivers. The full list of variables can be found on Victron's github page as [datalist.py](https://github.com/victronenergy/velib_python/blob/master/dbusmonitor.py).\n\nThis file isn't necessary, but it's just useful as a reference to see which data codes correspond to which values.\n\n\n\n###Sample interfacer config within emonhub.conf ###\n # Sample configuration for Victron Product with VEDirect connection over USB\n # Configuration is for BMV 700\n [[VEDirect]]\n Type = EmonHubVEDirectInterfacer\n [[[init_settings]]]\n com_port = /dev/ttyUSB0 # Where to find our device\n com_baud = 19200 # Baud rate needed to decode\n toextract = SOC,CE,TTG,V,I,Relay,Alarm # These are the fields we wish to extract, explanation can be seen in datalist.py\n poll_interval = 10 # How often to get data in seconds\n [[[runtimesettings]]]\n nodeoffset = 9 #make sure this matches with nodename below\n pubchannels = ToEmonCMS,\n subchannels = ToBMV,\n basetopic = emonhub/\n\n\n### Followed by a corresponding Node declaration in emonhub.conf###\nIn this example our battery monitor will be designated node id 9 \n\n [[9]]\n nodename = emonDC\n firmware =V1_6_emonTxV3_4_DiscreteSampling #not used\n hardware = emonTx_(NodeID_DIP_Switch1:ON) #not used\n [[[rx]]]\n names = SOC,CE,TTG,V,I,Relay,Alarm # Make sure this matches 'toextract' in interfacer\n datacode = 0 #no need to decode values\n scales = 0.1,1,1,0.001,1,1,1 # Some scaling necassary\n units =%,Ah,s,V,A,S,S \n\n\nWith this config in place now you simply need to restart emonhub on our emonpi by ssh'ing into it and typing \n\n $>sudo service emonhub restart\n\nIf there are any problems you can debug by looking inside /var/emonhub/emonhub.log\n\nHope that helps\n\n" }, { "alpha_fraction": 0.7188478112220764, "alphanum_fraction": 0.7194740176200867, "avg_line_length": 31.59183692932129, "blob_id": "d4fb789de71bae63a313d281dac84443f208e3e7", "content_id": "4717aea4228a1869035648c5781f915af34f89a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1597, "license_type": "no_license", "max_line_length": 78, "num_lines": 49, "path": "/legacy/measurementpoints/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom celery import shared_task\n\nfrom gridplatform.trackuser.tasks import trackuser_task\n\n\n@trackuser_task\n@shared_task(\n name='legacy.measurementpoints.tasks.get_condensed_samples_task')\ndef get_condensed_samples_task(\n data_series_id, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Celery task that collect condensed samples for a DataSeries at within a\n given timespan at a given C{resolution}.\n\n @param data_series_id: The C{id} of the L{DataSeries} to collect condensed\n samples.\n\n @param from_timestamp: The start of the timespan.\n\n @param to_timestamp: The end of the timespan.\n \"\"\"\n from .models import DataSeries\n data_series = DataSeries.objects.get(id=data_series_id).subclass_instance\n return list(\n data_series.get_condensed_samples(\n from_timestamp, resolution, to_timestamp))\n\n\n@trackuser_task\n@shared_task(name='legacy.measurementpoints.tasks.get_samples_task')\ndef get_samples_task(data_series_id, from_timestamp, to_timestamp):\n \"\"\"\n Celery task that collect samples for a DataSeries at within a given\n timespan.\n\n @param data_series_id: The C{id} of the L{DataSeries} to collect condensed\n samples.\n\n @param from_timestamp: The start of the timespan.\n\n @param to_timestamp: The end of the timespan.\n \"\"\"\n from .models import DataSeries\n data_series = DataSeries.objects.get(id=data_series_id).subclass_instance\n return list(data_series.get_samples(from_timestamp, to_timestamp))\n" }, { "alpha_fraction": 0.6838192343711853, "alphanum_fraction": 0.6849931478500366, "avg_line_length": 31.554140090942383, "blob_id": "32c8582f92b54ba18fd93970d0f7a3b2ed5901fb", "content_id": "aaeb5367a2b515fc9f3ae8d3b6c4e6f2ad4bfa97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5111, "license_type": "no_license", "max_line_length": 77, "num_lines": 157, "path": "/energymanager/datahub_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport calendar\nimport pycurl\nimport StringIO\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext_lazy\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom django.db.models.fields import BLANK_CHOICE_DASH\nfrom django.http import HttpResponse\nfrom django.conf import settings\n\nfrom gridplatform.utils import generic_views\nfrom gridplatform.utils import units\nfrom gridplatform.utils.breadcrumbs import Breadcrumb\nfrom gridplatform.utils.breadcrumbs import Breadcrumbs\nfrom gridplatform.utils.views import ChooseCustomerBase\nfrom gridplatform.utils.views import CustomerInKwargsMixin\nfrom gridplatform.utils.views import CustomerListMixin\nfrom gridplatform.utils.views import CustomerViewBase\nfrom gridplatform.utils.views import HomeViewBase\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.utils.forms import YearWeekPeriodForm\nfrom gridplatform.utils.forms import this_week_initial_values\nfrom gridplatform.datahub.models import DatahubConnection\nfrom legacy.devices.models import PhysicalInput\n\n\nclass HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'datahub_site:connection-list',\n kwargs={'customer_id': customer_id})\n\n def get_choose_customer_url(self):\n return reverse(\n 'datahub_site:choose-customer')\n\n\nclass ChooseCustomer(ChooseCustomerBase):\n template_name = 'datahub_site/choose_customer.html'\n\n\nclass CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'datahub_site:connection-list',\n kwargs={'customer_id': customer_id})\n\n\nclass DatahubConnectionList(CustomerListMixin, generic_views.TemplateView):\n template_name = 'datahub_site/datahub_connection_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Forbindelser'),\n reverse(\n 'datahub_site:connection-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass DatahubConnectionListContentView(\n CustomerListMixin,\n generic_views.ListView):\n search_fields = ['customer_meter_number', ]\n sort_fields = ['customer_meter_number', ]\n model = DatahubConnection\n paginate_by = 100\n template_name = 'datahub_site/_datahub_connection_list_content.html'\n\n\nclass DatahubConnectionForm(forms.ModelForm):\n\n class Meta:\n model = DatahubConnection\n fields = (\n 'customer_meter_number', 'meter'\n )\n\n\nclass DatahubConnectionCreateView(CustomerListMixin,\n generic_views.CreateView):\n model = DatahubConnection\n template_name = 'datahub_site/datahub_connection_form.html'\n form_class = DatahubConnectionForm\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n meter = form.instance.meter\n input = PhysicalInput.objects.create(\n meter=meter,\n order=0,\n name_plain=\"Datahub\",\n unit=\"milliwatt*hour\",\n type=PhysicalInput.ELECTRICITY\n )\n\n form.instance.input = input\n\n response = super(DatahubConnectionCreateView, self).form_valid(form)\n return response\n\n def get_success_url(self):\n return reverse('datahub_site:connection-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return DatahubConnectionList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create connection'))\n\n\nclass DatahubConnectionUpdateView(CustomerListMixin,\n generic_views.UpdateView):\n model = DatahubConnection\n template_name = 'datahub_site/datahub_connection_form.html'\n fields = (\n 'customer_meter_number',\n )\n\n def get_success_url(self):\n return reverse('datahub_site:connection-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return DatahubConnectionList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n\ndef datahub_authorization_view(request):\n b = StringIO.StringIO()\n c = pycurl.Curl()\n url = 'https://eloverblik.dk/api/authorizationsv2'\n c.setopt(pycurl.URL, url)\n c.setopt(pycurl.WRITEFUNCTION, b.write)\n c.setopt(pycurl.SSLKEY, settings.NETS_KEY_DIR + \"/plainkey.pem\")\n c.setopt(pycurl.SSLCERT, settings.NETS_KEY_DIR + \"/crt.pem\")\n c.perform()\n c.close()\n response_body = b.getvalue()\n return HttpResponse(response_body, content_type='application/json')\n" }, { "alpha_fraction": 0.6284671425819397, "alphanum_fraction": 0.6291970610618591, "avg_line_length": 32.414634704589844, "blob_id": "81235c4048bf3950ade92ce4bb1075bd97a4c742", "content_id": "39a68a3bda70b77b84051d040ad1a4d89ca36745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1370, "license_type": "no_license", "max_line_length": 74, "num_lines": 41, "path": "/gridplatform/utils/api.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\ndef next_valid_date_for_datasequence(datasequences, date, timezone):\n \"\"\"\n :return: The next date with data among given data sequences. If no\n such date exist, ``None`` is returned.\n\n :param datasequences: The given data sequences.\n :param date: The date to find a date after.\n :param tzinfo timezone: The timezone used to translate dates into\n timestamp ranges.\n \"\"\"\n dates = [\n c.next_valid_date(date, timezone)\n for c in datasequences\n if c.next_valid_date(date, timezone)]\n if not dates:\n return None\n return min(dates)\n\n\ndef previous_valid_date_for_datasequence(datasequences, date, timezone):\n \"\"\"\n :return: The previous date with data among given data sequences.\n If no such date exist, ``None`` is returned.\n\n :param datasequences: The given data sequences.\n :param date: The date to find a date before.\n :param tzinfo timezone: The timezone used to translate dates into\n timestamp ranges.\n \"\"\"\n dates = [\n c.previous_valid_date(date, timezone)\n for c in datasequences\n if c.previous_valid_date(date, timezone)]\n if not dates:\n return None\n return max(dates)\n" }, { "alpha_fraction": 0.6323109269142151, "alphanum_fraction": 0.6375263929367065, "avg_line_length": 35.43891525268555, "blob_id": "e0bdd1ed9cfbb1d2d067199b39e442ef1a19650c", "content_id": "cf781af88765364f33b524553d9281ddbb350293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8077, "license_type": "no_license", "max_line_length": 118, "num_lines": 221, "path": "/gridplatform/co2conversions/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import cached_property\n\nfrom gridplatform.consumptions.models import MainConsumption\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.datasequences.models import PiecewiseConstantPeriodManager\nfrom gridplatform.datasequences.models.piecewiseconstant import FixedPiecewiseConstantPeriodValueSequenceMixin # noqa\nfrom gridplatform.datasequences.models.base import is_five_minute_multiplum\nfrom gridplatform.utils.models import TimestampRangeModelMixin\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.validators import clean_overlapping\nfrom gridplatform.utils import units\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils import condense\n\n\nclass Co2ConversionManager(PiecewiseConstantPeriodManager):\n use_for_related_fields = True\n\n def value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Yield ``RangedSample``s in five-minute resolution.\n \"\"\"\n for sample in super(Co2ConversionManager, self).value_sequence(\n from_timestamp, to_timestamp):\n assert RelativeTimeDelta(\n sample.to_timestamp, sample.from_timestamp) == \\\n RelativeTimeDelta(minutes=5)\n yield sample\n\n\nclass Co2Conversion(TimestampRangeModelMixin, StoreSubclass):\n \"\"\"\n Base class for defining CO₂ conversions of a\n :py:class:`gridplatform.consumptions.models.MainConsumption`\n within a timestamp range.\n\n CO₂ conversion samples are ``RangedSamples`` with a five minute\n duration.\n\n :ivar mainconsumption: The ``MainConsumption`` for which this\n instance defines CO₂ conversions.\n\n :ivar from_timestamp: The start of the timestamp range.\n\n :ivar to_timestamp: The end of the timestamp range.\n \"\"\"\n\n mainconsumption = models.ForeignKey(\n MainConsumption, verbose_name=_('main consumption'))\n\n objects = Co2ConversionManager()\n\n class Meta:\n verbose_name = _('CO₂ conversion')\n verbose_name = _('CO₂ conversions')\n\n def clean(self):\n \"\"\"\n :raises ValidationError: if timestamp range overlaps with that of\n another ``Co2Conversion`` for the same ``mainconsumption``.\n\n :raises ValidationError: if ``self.from_timestamp`` is not in\n five-minute resolution.\n\n :raises ValidationError: if ``self.to_timestamp`` is not in\n five-minute resolution.\n \"\"\"\n super(Co2Conversion, self).clean()\n if self.from_timestamp:\n # NOTE: does not support formset validation. See how that is done\n # in PeriodBase.\n co2conversions = [\n co2conversion\n for co2conversion\n in self.mainconsumption.co2conversion_set.all()\n if co2conversion.id != self.id]\n co2conversions.append(self)\n clean_overlapping(co2conversions)\n\n if self.from_timestamp and not is_five_minute_multiplum(\n self.from_timestamp):\n raise ValidationError(\n {\n 'from_timestamp': [\n ugettext(\n 'Timestamp must be in five-minute resolution.')]})\n\n if self.to_timestamp and not is_five_minute_multiplum(\n self.to_timestamp):\n raise ValidationError(\n {\n 'to_timestamp': [\n ugettext(\n 'Timestamp must be in five-minute resolution.')]})\n\n def unit_is_valid(self, unit):\n return (\n PhysicalQuantity(1, unit) *\n PhysicalQuantity(\n 1, self.mainconsumption.utility_unit)).compatible_unit('gram')\n\n def __unicode__(self):\n timezone = self.mainconsumption.customer.timezone\n return self.format_timestamp_range_unicode(\n self._get_description(), timezone)\n\n @virtual\n def _value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: A sequence of conversion ranged samples with five-minute\n durations, each specifying how utility consumptions within\n their time range is converted to CO₂ emissions.\n\n :param from_timestamp: Marks the beginning of the returned\n sequence.\n\n :param to_timestamp: Marks the end of the returned sequence.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n @virtual\n def _get_description(self):\n raise NotImplementedError(self.__class__)\n\n\nclass DynamicCo2Conversion(Co2Conversion):\n \"\"\"\n A CO₂ conversion defined in terms of a\n :py:class:`gridplatform.datasources.models.DataSource`.\n\n :ivar datasource: The ``DataSource`` in terms of which this\n ``DynamicCo2Conversion`` is defined.\n \"\"\"\n datasource = models.ForeignKey(\n DataSource,\n limit_choices_to=models.Q(unit__in=units.CO2_CONVERSION_BASE_UNITS),\n verbose_name=_('data source'))\n\n class Meta:\n verbose_name = _('dynamic CO₂ conversion')\n verbose_name_plural = _('dynamic CO₂ conversions')\n\n def clean(self):\n \"\"\"\n :raises ValidationError: if ``self.datasource.unit`` is incompatible with\n ``self.mainconsumption.unit``\n \"\"\"\n super(DynamicCo2Conversion, self).clean()\n if hasattr(self, 'datasource') and not self.unit_is_valid(\n self.datasource.unit):\n raise ValidationError(\n {\n 'datasource': [\n ugettext(\n 'Invalid data source for utility unit of '\n 'main consumption.')]})\n\n def _value_sequence(self, from_timestamp, to_timestamp):\n rawdata = self.datasource.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp).order_by(\n 'timestamp').values_list('timestamp', 'value')\n for timestamp, value in rawdata:\n yield RangedSample(\n timestamp,\n timestamp + RelativeTimeDelta(minutes=5),\n PhysicalQuantity(value, self.datasource.unit))\n\n def _get_description(self):\n return unicode(self.datasource)\n\n\nclass FixedCo2Conversion(\n FixedPiecewiseConstantPeriodValueSequenceMixin, Co2Conversion):\n \"\"\"\n A CO₂ conversion defined from a fixed factor.\n\n :ivar value: The value of the fixed factor.\n :ivar unit: The unit of the fixed factor.\n \"\"\"\n value = models.DecimalField(_('value'), max_digits=12, decimal_places=3)\n unit = BuckinghamField(_('unit'), choices=units.CO2_CONVERSION_CHOICES)\n\n resolution = condense.FIVE_MINUTES\n\n class Meta:\n verbose_name = _('fixed CO₂ conversion')\n verbose_name_plural = _('fixed CO₂ conversions')\n\n def clean(self):\n \"\"\"\n :raises ValidationError: if ``self.unit`` is incompatible with\n ``self.mainconsumption.unit``\n \"\"\"\n super(FixedCo2Conversion, self).clean()\n if self.unit and not self.unit_is_valid(self.unit):\n raise ValidationError(\n {\n 'unit': [\n ugettext(\n 'Invalid unit for utility unit of '\n 'main consumption.')]})\n\n def _get_description(self):\n return '%s %s' % (self.value, self.get_unit_display())\n\n @cached_property\n def _quantity(self):\n return PhysicalQuantity(self.value, self.unit)\n" }, { "alpha_fraction": 0.5803709626197815, "alphanum_fraction": 0.5912759900093079, "avg_line_length": 32.27428436279297, "blob_id": "3a72fc57f2c83055507d91f1e5f37feea6efe937", "content_id": "1e0e8d85041d3c064066b9d37c29aec66a311949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11646, "license_type": "no_license", "max_line_length": 79, "num_lines": 350, "path": "/gridagentserver-protocol/gridagentserver_protocol/client_messages.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"Messages to be sent from the (virtual) agent to the GridAgent server.\"\"\"\n\nfrom struct import Struct\nimport logging\n\nfrom messages import Message, timestamp_to_datetime, datetime_to_timestamp\nfrom datatypes import Meter, MeterData, MeasurementSet, Measurement, Version\n\n\nlogger = logging.getLogger(__name__)\n\nint32 = Struct('!i')\nuint32 = Struct('!I')\nint16 = Struct('!h')\nuint16 = Struct('!H')\nuint8 = Struct('!B')\n\n\n# ZigBee timestamp, i.e. seconds since 2000-01-01\ntimestamp_struct = Struct('!I')\n\n# major, minor, revision, extra string\nversion_struct = Struct('!BBB12s')\n\n\ndef normalise_version(version):\n \"\"\"\n Replace the received fixed-length \"extra\" string with its prefix before the\n first \\0 character.\n \"\"\"\n major, minor, revision, extra_bytes = version\n extra_bytes = extra_bytes.split('\\0', 1)[0]\n extra = extra_bytes.decode('iso8859-1')\n return (major, minor, revision, extra)\n\n\nclass BulkMeasurements(Message):\n # ID, timestamp, value\n measurement1_struct = Struct('!qIq')\n # type, unit, input_number, value\n measurement2_struct = Struct('!bbbq')\n # connection_type, ID\n meter2_struct = Struct('!bq')\n\n def __init__(self, meter_data):\n self.meter_data = meter_data\n\n def __cmp__(self, other):\n return cmp(self.meter_data, other.meter_data)\n\n def __hash__(self):\n return hash(self.meter_data)\n\n @classmethod\n def unpack(cls, header, read, version):\n if version == 1:\n return cls.unpack_1(read)\n else:\n return cls.unpack_2(read)\n\n # meter id, connection_type --- ver1 only id...\n @classmethod\n def unpack_1(cls, read):\n def group_ids(acc, elem):\n id, timestamp, value = elem\n if not acc:\n acc = [(id, [(timestamp, value)])]\n else:\n old_id = acc[-1][0]\n if id == old_id:\n acc[-1][1].append((timestamp, value))\n else:\n acc.append((id, [(timestamp, value)]))\n return acc\n count, = read(uint32)\n # [(id, timestamp, value), ...]\n raw_list = read(cls.measurement1_struct, count)\n raw_list.sort()\n # to [(id, [(timestamp, value), ...]), ...]\n data = reduce(group_ids, raw_list, [])\n meter_data = []\n for meter_id, measurements in data:\n meter = Meter(0, meter_id)\n measurement_sets = [\n MeasurementSet(timestamp_to_datetime(timestamp),\n [Measurement(0, 0, 0, value)])\n for timestamp, value in measurements]\n meter_data.append(MeterData(meter, measurement_sets))\n return cls(meter_data)\n\n @classmethod\n def unpack_2(cls, read):\n meter_data_count, = read(uint16)\n meter_data = []\n for n in range(meter_data_count):\n meter = Meter(*read(cls.meter2_struct))\n measurement_set_count, = read(uint16)\n measurement_sets = []\n for m in range(measurement_set_count):\n timestamp, = read(timestamp_struct)\n measurement_count, = read(uint16)\n measurements = []\n for l in range(measurement_count):\n measurements.append(\n Measurement(*read(cls.measurement2_struct)))\n measurement_sets.append(\n MeasurementSet(timestamp_to_datetime(timestamp),\n measurements))\n meter_data.append(MeterData(meter, measurement_sets))\n return cls(meter_data)\n\n def pack(self, version):\n if version < 2:\n raise Exception(\"Not implemented for version {}\".format(version))\n data = []\n data.append(uint16.pack(len(self.meter_data)))\n for meter, measurement_sets in self.meter_data:\n data.append(self.meter2_struct.pack(*meter))\n data.append(uint16.pack(len(measurement_sets)))\n for timestamp, measurements in measurement_sets:\n data.append(timestamp_struct.pack(\n datetime_to_timestamp(timestamp)))\n data.append(uint16.pack(len(measurements)))\n data.extend([self.measurement2_struct.pack(*measurement)\n for measurement in measurements])\n return self._pack(data, version)\n\n\nclass NotificationGaAddMode(Message):\n def __init__(self, timestamp, in_add_mode):\n self.timestamp = timestamp\n self.in_add_mode = in_add_mode\n\n def __cmp__(self, other):\n return cmp((self.timestamp, self.in_add_mode),\n (other.timestamp, other.in_add_mode))\n\n def __hash__(self):\n return hash((self.timestamp, self.in_add_mode))\n\n @classmethod\n def unpack(cls, header, read, version):\n timestamp = timestamp_to_datetime(*read(timestamp_struct))\n in_add_mode = bool(header.flags & 1)\n return cls(timestamp, in_add_mode)\n\n def pack(self, version):\n data = timestamp_struct.pack(datetime_to_timestamp(self.timestamp))\n return self._pack([data], version, int(self.in_add_mode))\n\n\nclass NotificationGaTime(Message):\n def __init__(self, timestamp):\n self.timestamp = timestamp\n\n def __cmp__(self, other):\n return cmp(self.timestamp, other.timestamp)\n\n def __hash__(self):\n return hash(self.timestamp)\n\n @classmethod\n def unpack(cls, header, read, version):\n timestamp = timestamp_to_datetime(*read(timestamp_struct))\n return cls(timestamp)\n\n def pack(self, version):\n data = timestamp_struct.pack(datetime_to_timestamp(self.timestamp))\n return self._pack([data], version)\n\n\nclass NotificationGaConnectedSet(Message):\n # ID\n meter1_struct = Struct('!q')\n # connection_type, ID\n meter2_struct = Struct('!bq')\n # connection_type, ID, device type, device option,\n # hw major, hw minor, hw revision, hw revisionstring\n # sw major, sw minor, sw revision, sw revisionstring\n meter4_struct = Struct('!BqBB' + 'BBB12s' + 'BBB12s')\n\n def __init__(self, meters, device_opts=None, versions=None):\n self.meters = meters\n self.device_opts = device_opts\n self.versions = versions\n\n def __cmp__(self, other):\n return cmp(self.meters, other.meters)\n\n def __hash__(self):\n return hash(self.meters)\n\n @classmethod\n def unpack(cls, header, read, version):\n count, = read(uint32)\n if version == 1:\n meters = [Meter(0, id) for id, in read(cls.meter1_struct, count)]\n return cls(meters)\n elif version < 4:\n meters = [Meter(*data) for data in read(cls.meter2_struct, count)]\n return cls(meters)\n else:\n data = read(cls.meter4_struct, count)\n meters = [Meter(elem[0], elem[1]) for elem in data]\n device_opts = [(elem[2], elem[3]) for elem in data]\n versions = [(Version(*elem[4:8]), Version(*elem[8:12]))\n for elem in data]\n return cls(meters, device_opts, versions)\n\n def pack(self, version):\n if version < 2:\n raise Exception(\"Not implemented for version {}\".format(version))\n data = [uint32.pack(len(self.meters))]\n data.extend([self.meter2_struct.pack(*meter) for meter in self.meters])\n return self._pack(data, version)\n\n\nclass NotificationGpState(Message):\n # ID\n meter1_struct = Struct('!q')\n # connection_type, ID\n meter2_struct = Struct('!bq')\n\n def __init__(self, meter, online, control_manual, relay_on, timestamp):\n self.meter = meter\n self.online = online\n self.control_manual = control_manual\n self.relay_on = relay_on\n self.timestamp = timestamp\n\n def __cmp__(self, other):\n return cmp((self.meter, self.timestamp,\n self.online, self.control_manual, self.relay_on),\n (other.meter, other.timestamp,\n other.online, other.control_manual, other.relay_on))\n\n def __hash__(self):\n return hash((self.meter, self.timestamp,\n self.online, self.control_manual, self.relay_on))\n\n @classmethod\n def unpack(cls, header, read, version):\n online = bool(header.flags & 1)\n control_manual = bool(header.flags & 2)\n relay_on = bool(header.flags & 4)\n timestamp = timestamp_to_datetime(*read(timestamp_struct))\n if version == 1:\n id, = read(cls.meter1_struct)\n meter = Meter(0, id)\n else:\n meter = Meter(*read(cls.meter2_struct))\n return cls(meter, online, control_manual, relay_on, timestamp)\n\n def pack(self, version):\n if version < 2:\n raise Exception(\"Not implemented for version {}\".format(version))\n flags = self.online * 1 + self.control_manual * 2 + self.relay_on * 4\n data = [timestamp_struct.pack(datetime_to_timestamp(self.timestamp)),\n self.meter2_struct.pack(*self.meter)]\n return self._pack(data, version, flags)\n\n\nclass AcknowledgementGpSoftware(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass AcknowledgementGaSoftware(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass ErrorGpSoftware(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass ErrorGaSoftware(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass InfoAgentVersions(Message):\n def __init__(self, sw_version, device_type, hw_revision, serial):\n self.sw_version = sw_version\n self.device_type = device_type\n self.hw_revision = hw_revision\n self.serial = serial\n\n @classmethod\n def unpack(cls, header, read, version):\n assert version >= 3\n sw_version = normalise_version(read(version_struct))\n device_type, = read(uint8)\n hw_revision = normalise_version(read(version_struct))\n serial, = read(int32)\n return cls(sw_version, device_type, hw_revision, serial)\n\n def pack(self, version):\n assert version >= 3\n data = [version_struct.pack(*self.sw_version),\n uint8.pack(self.device_type),\n version_struct.pack(*self.hw_revision),\n uint32.pack(self.serial)]\n return self._pack(data, version)\n\n\nclass InfoEventLog(Message):\n eventtext_struct = Struct('!128s')\n\n def __init__(self, timestamp, code, text):\n self.timestamp = timestamp\n self.code = code\n self.text = text\n\n @classmethod\n def unpack(cls, header, read, version):\n timestamp_raw, = read(timestamp_struct)\n timestamp = timestamp_to_datetime(timestamp_raw)\n code, = read(int16)\n text_raw, = read(cls.eventtext_struct)\n text = text_raw.split('\\0', 1)[0]\n return cls(timestamp, code, text)\n\n def pack(self, version):\n assert version >= 5\n data = [timestamp_struct.pack(datetime_to_timestamp(self.timestamp)),\n int16.pack(self.code),\n self.eventtext_struct.pack(self.text)]\n return self._pack(data, version)\n" }, { "alpha_fraction": 0.6366162300109863, "alphanum_fraction": 0.6423279047012329, "avg_line_length": 32.916229248046875, "blob_id": "2022f42d90b39bd1ee1ef5da29f63f4a9e413bd9", "content_id": "4d620bc31f8ae22e8ad15640e2c6f1156d0db69f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6478, "license_type": "no_license", "max_line_length": 96, "num_lines": 191, "path": "/energymanager/energy_projects/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport pytz\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.utils import DATETIME_MIN, PhysicalQuantity\n\nPHASE_ONE = 1\nPHASE_TWO = 2\nPHASE_TREE = 3\n\nENERGY_PROJECT_PHASES = {\n PHASE_ONE: _('Phase 1'),\n PHASE_TWO: _('Phase 2'),\n PHASE_TREE: _('Phase 3'),\n}\n\n\nclass EnergyProject(EncryptionCustomerFieldMixin, EncryptedModel):\n name = EncryptedCharField(_('name'), max_length=50)\n\n baseline_from_date = models.DateField(_('Baseline start date'))\n baseline_to_date = models.DateField(_('Baseline end date'))\n\n time_datasource = models.ForeignKey(\n Consumption,\n verbose_name=_('time datasource'),\n null=True, blank=True,\n related_name='energyproject_time_set'\n )\n\n datasource = models.ForeignKey(\n Consumption,\n verbose_name=_('datasource'),\n null=True, blank=True,\n related_name='energyproject_set'\n )\n\n result_from_date = models.DateField(_('Result start date'), blank=True, null=True)\n result_to_date = models.DateField(_('Result end date'), blank=True, null=True)\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('Energy project')\n verbose_name_plural = _('Energy projects')\n\n def __unicode__(self):\n return unicode(self.name_plain)\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If baseline timestamp range is empty.\n \"\"\"\n super(EnergyProject, self).clean()\n if self.baseline_from_date and self.baseline_to_date and \\\n self.baseline_from_date > self.baseline_to_date:\n raise ValidationError(_('Baseline period must be non-empty.'))\n\n if self.datasource_id and not PhysicalQuantity.compatible_units(\n self.datasource.unit, 'joule'):\n raise ValidationError(_('Datasource must be an energy datasource'))\n\n if self.time_datasource_id and not PhysicalQuantity.compatible_units(\n self.time_datasource.unit, 'second'):\n raise ValidationError(_('Datasource must be a time datasource'))\n\n def project_phase(self):\n now = datetime.date.today()\n if now <= self.baseline_to_date:\n return PHASE_ONE\n elif now > self.baseline_to_date and now < self.result_from_date:\n return PHASE_TWO\n else:\n return PHASE_TREE\n\n def baseline_timestamps(self):\n return (\n datetime.datetime.combine(\n self.baseline_from_date,\n datetime.time(0, 0).replace(tzinfo=self.customer.timezone)),\n datetime.datetime.combine(\n self.baseline_to_date,\n datetime.time(23, 0).replace(tzinfo=self.customer.timezone))\n )\n\n def total_baseline_consumption(self):\n if not self.datasource:\n return None\n\n timestamps = self.baseline_timestamps()\n return self.datasource.energy_sum(timestamps[0], timestamps[1]).convert('kilowatt*hour')\n\n def total_baseline_time_consumption(self):\n if not self.time_datasource:\n return None\n\n timestamps = self.baseline_timestamps()\n return self.time_datasource.energy_sum(timestamps[0], timestamps[1]).convert('hour')\n\n\nclass LedLightProject(\n EncryptionCustomerFieldMixin, EncryptedModel):\n name = EncryptedCharField(_('name'), max_length=50)\n previous_tube_count = models.IntegerField(_('previous tube count'))\n previous_consumption_per_tube = models.IntegerField(\n _('previous consumption per tube in W/h'))\n\n led_tube_count = models.IntegerField(_('LED tube count'))\n led_consumption_per_tube = models.IntegerField(\n _('consumption per LED tube in W/h'))\n\n price = models.FloatField(_('price per kw/h'))\n\n datasource = models.ForeignKey(\n Consumption,\n verbose_name=_('datasource'),\n null=True, blank=True)\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('LED light project')\n verbose_name_plural = _('LED light projects')\n\n def __unicode__(self):\n return unicode(self.name_plain)\n\n def calculate_previous_consumption(self):\n return self.previous_tube_count * self.previous_consumption_per_tube\n\n def measured_consumption(self, from_timestamp, to_timestamp):\n if not from_timestamp:\n from_timestamp = DATETIME_MIN\n if not to_timestamp:\n to_timestamp = datetime.datetime(\n 9998, 12, 30, 23, 0, 0).replace(tzinfo=pytz.utc)\n\n return self.datasource.energy_sum(from_timestamp, to_timestamp)\n\n def calculate_previous_price_per_hour(self):\n return self.calculate_previous_consumption() / 1000.0 * self.price\n\n def calculate_savings(self, from_time=None, to_time=None):\n '''\n Returns the savings\n '''\n if not self.datasource:\n return None\n\n return self.calculated_previous_price(\n from_time, to_time) - self.measured_price(\n from_time, to_time)\n\n def calculate_burn_hours(self, from_time=None, to_time=None):\n if self.datasource:\n consumption = self.measured_consumption(\n from_time, to_time).convert('watt*hour')\n\n calculated_consumption = self.led_tube_count \\\n * self.led_consumption_per_tube\n return consumption / calculated_consumption\n else:\n return None\n\n def calculated_previous_price(\n self, from_time=None, to_time=None):\n if self.datasource:\n return self.calculate_burn_hours(\n from_time, to_time) * self.calculate_previous_price_per_hour()\n else:\n return None\n\n def measured_price(self, from_time=None, to_time=None):\n if self.datasource:\n\n return self.measured_consumption(\n from_time, to_time).convert('kilowatt*hour') * self.price\n else:\n return None\n" }, { "alpha_fraction": 0.5402112007141113, "alphanum_fraction": 0.5597075819969177, "avg_line_length": 34.17142868041992, "blob_id": "9eeb75a9905070174aae8b0ddde09ff8636fa290", "content_id": "2afe4a13520f2dfbd2ca388c7fff0513ab717332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1231, "license_type": "no_license", "max_line_length": 114, "num_lines": 35, "path": "/wifiagent/wifiagent/relay/migrations/0001_initial.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9 on 2015-12-18 20:28\nfrom __future__ import unicode_literals\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='EndpointCache',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('mac', models.CharField(max_length=50, verbose_name='mac')),\n ('endpoint', models.CharField(max_length=256, verbose_name='endpoint')),\n ('timestamp', models.DateTimeField()),\n ],\n ),\n migrations.CreateModel(\n name='Measurement',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('mac', models.CharField(max_length=50, verbose_name='mac')),\n ('ip', models.CharField(max_length=50, verbose_name='source ip')),\n ('timestamp', models.DateTimeField()),\n ('vrms_total', models.FloatField(verbose_name='Volt')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5162634253501892, "alphanum_fraction": 0.5215510129928589, "avg_line_length": 36.824241638183594, "blob_id": "76bf9fe927b92c268c837f806227ba0b6302999c", "content_id": "202b193b671bcbaeb688754dcd9c575093f6e6c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6241, "license_type": "no_license", "max_line_length": 79, "num_lines": 165, "path": "/legacy/devices/management/commands/hickup_detection.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom operator import attrgetter\n\nimport datetime\nfrom optparse import make_option\n\nfrom django.core.management.base import BaseCommand\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.iter_ext import nwise\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.devices.models import RawData\nimport pytz\n\n\ndef is_monotonic(data):\n return all(a.value <= b.value for a, b in zip(data, data[1:])) or \\\n all(a.value >= b.value for a, b in zip(data, data[1:]))\n\n\ndef find_hickups(data):\n hickups = []\n for raw_data in nwise(data, 15):\n # Strategy: The data is split into two control periods and\n # on period which is analysed for hickups given that both\n # control periods are monotonic.\n # All values in the hickup candidates period are checked if\n # the break the monotonisicity, and if so, if they are\n # diverging more than a certain decided tolerance.\n control_period_before = raw_data[:5]\n hickup_candidates = raw_data[5:10]\n control_period_after = raw_data[10:15]\n control_sequence = control_period_before + \\\n control_period_after\n if not is_monotonic(raw_data) and \\\n is_monotonic(control_sequence):\n value_getter = attrgetter('value')\n control_max = max(control_sequence, key=value_getter)\n control_min = min(control_sequence, key=value_getter)\n control_diff = control_max.value - control_min.value\n tolerance = max(control_diff * 2, 100000)\n hickups.extend([\n candidate for candidate in hickup_candidates\n if not (\n (control_min.value - tolerance) <\n candidate.value <\n (control_max.value + tolerance)\n )\n ])\n return sorted(set(hickups))\n\n\nclass Command(BaseCommand):\n help = 'Detect hickups by scanning through raw measurement data'\n\n option_list = BaseCommand.option_list + (\n make_option(\n '-d',\n '--delete',\n action='store_true',\n dest='delete',\n default=False,\n help='Delete hickups when detected'),\n make_option(\n '-f',\n '--from',\n action='store',\n dest='from_datetime',\n default=\"2000-01-01T00:00\",\n help='From timestamp in yyyy-mm-ddThh:mm notation'),\n make_option(\n '-c',\n '--customer',\n action='append',\n dest='customer',\n help='Only detect hickups for a certain customer id',\n type=int),\n make_option(\n '-m',\n '--meter',\n action='append',\n dest='meter',\n help='Only detect hickups for a specific meter id',\n type=int),\n make_option(\n '-p',\n '--previous-hour',\n action='store_true',\n dest='use_previous_hour',\n default=False),\n make_option(\n '-q',\n '--quiet',\n action='store_true',\n dest='be_quiet',\n default=False))\n\n def handle(self, *args, **options):\n with replace_customer(None), replace_user(None):\n be_quiet = options['be_quiet']\n delete_hickups = options['delete']\n\n hour = RelativeTimeDelta(hours=1)\n if options['use_previous_hour']:\n from_datetime = condense.floor(\n datetime.datetime.now(pytz.utc), hour, pytz.utc) - hour\n else:\n from_datetime = pytz.utc.localize(\n datetime.datetime.strptime(\n options['from_datetime'], '%Y-%m-%dT%H:%M'))\n # Now go back one extra hour to make sure we catch possible hickups\n # in the beginning of the period.\n from_datetime = from_datetime - hour\n\n if not be_quiet:\n self.stdout.write(\"Finding peaks from %s\" % (from_datetime,))\n\n customer = options['customer']\n meter = options['meter']\n\n # Note that we only check GM devices (the only devices for which\n # physical inputs exist) and we only check energy inputs.\n physical_input_qs = PhysicalInput.objects.filter(\n unit='milliwatt*hour')\n\n if meter:\n physical_input_qs = physical_input_qs.filter(\n meter_id__in=meter)\n\n if customer:\n physical_input_qs = physical_input_qs.filter(\n meter__customer_id__in=customer)\n\n hickup_ids = []\n for physical_input in physical_input_qs:\n raw_data = list(RawData.objects.filter(\n datasource=physical_input,\n timestamp__gt=from_datetime).order_by('timestamp'))\n while True:\n hickups = find_hickups(raw_data)\n if not hickups:\n break\n for hickup in hickups:\n raw_data.remove(hickup)\n hickup_ids.append(hickup.id)\n if not be_quiet:\n self.stdout.write(\n ('hickup: meter_id: %s, '\n 'physicalinput_id: %s, '\n 'agent_mac: %s, value=%s, timestamp=%s')\n % (\n physical_input.meter.id,\n physical_input.id,\n physical_input.meter.agent.mac,\n hickup.value,\n hickup.timestamp\n )\n )\n if delete_hickups and hickup_ids:\n RawData.objects.filter(id__in=hickup_ids).delete()\n" }, { "alpha_fraction": 0.49203187227249146, "alphanum_fraction": 0.493525892496109, "avg_line_length": 37.61538314819336, "blob_id": "3d725fe09833f46fd3a6a53a973b6d245e1e4fb9", "content_id": "91938cfa981dc2b4df97c4b46100da11fb68d322", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2008, "license_type": "no_license", "max_line_length": 78, "num_lines": 52, "path": "/gridplatform/jserror/templates/jserror/jserror.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true */\n\n(function () {\n 'use strict';\n // \"Best effort\" attempt to send JS error message to error reporting\n // service at server; attached as onerror event handler. (Will call\n // previous onerror handler if it exists.)\n var oldOnError = window.onerror;\n window.onerror = function(message, url, line) {\n var req,\n csrftoken,\n cookies,\n cookie,\n i;\n if (window.XMLHttpRequest && window.JSON && window.JSON.stringify) {\n // Only attempt to send data if the browser supports standard APIs\n // for AJAX and JSON...\n if (document.cookie) {\n // Get CSRF token from cookie, if possible. The cookie string\n // entries should be separated by \";\", but split on \" \" too,\n // just in case. (\"Extra\" empty entries won't harm.)\n cookies = document.cookie.split('; ');\n for (i = 0; i < cookies.length; i += 1) {\n cookie = cookies[i];\n if (cookie.indexOf('csrftoken=') === 0) {\n csrftoken = cookie.substring('csrftoken='.length);\n break;\n }\n }\n }\n req = new XMLHttpRequest();\n req.open('post', '{% url \"jserror-jserror\" %}', true);\n req.setRequestHeader('Content-type', 'application/json');\n if (csrftoken) {\n // Include CSRF token if known.\n req.setRequestHeader('X-CSRFToken', csrftoken);\n }\n req.send(JSON.stringify({\n message: message,\n url: url,\n line: line,\n location: window.location.href\n }));\n }\n if (oldOnError) {\n // Call old error handler.\n return oldOnError(message, url, line);\n }\n // Don't preempt default error handler.\n return false;\n };\n}());\n" }, { "alpha_fraction": 0.6665676236152649, "alphanum_fraction": 0.666864812374115, "avg_line_length": 33.336734771728516, "blob_id": "639d8ddd325b01e00deca0000eb864edaadcac85", "content_id": "8e29aebaad477dcec4b5c83148899fb72028ea76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3365, "license_type": "no_license", "max_line_length": 83, "num_lines": 98, "path": "/gridplatform/customers/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\n# from django.db.models.query import QuerySet\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\nfrom django.db.models.query_utils import Q\n\nfrom gridplatform.encryption.managers import DecryptingManager\nfrom gridplatform.encryption.managers import DecryptingQuerySet\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_provider_id\nfrom gridplatform.trackuser.managers import FilteringQuerySetMixinBase\n\n\nclass CustomerQuerySetMixin(FilteringQuerySetMixinBase):\n \"\"\"\n Slightly modified variant of code from\n :class:`gridplatform.trackuser.managers.CustomerBoundQuerySetMixin`\n \"\"\"\n def _apply_filtering(self):\n \"\"\"\n Filters out customers different from the customer of a customer user or the\n selected customer for a provider user (if any is selected). For these\n users inactive customers are also excluded.\n\n For provider users without any particular customer selected, only\n customers that belong to that provider will pass the filter. For these\n provider users inactive customers are not excluded.\n \"\"\"\n user = get_user()\n if user is None:\n return\n if not user.is_authenticated():\n self.query.set_empty()\n return\n customer = get_customer()\n if customer is not None:\n if not customer.is_active:\n self.query.set_empty()\n return\n id_field = 'id'\n kwargs = {id_field: customer.id}\n self.query.add_q(Q(**kwargs))\n return\n provider_id = get_provider_id()\n if provider_id:\n kwargs = {'provider_id': provider_id}\n self.query.add_q(Q(**kwargs))\n return\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n return\n\n\nclass CustomerManager(DecryptingManager):\n \"\"\"\n Manager for :class:`Customer` model ensuring that only customers that the\n user is supposed to see will be accessible.\n\n Querysets of this manager are mixed with the\n :class:`.CustomerQuerySetMixin`.\n \"\"\"\n\n _field = None\n\n class _QuerySet(CustomerQuerySetMixin, DecryptingQuerySet):\n pass\n\n class _ValuesQuerySet(CustomerQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(CustomerQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(CustomerQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(CustomerQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(CustomerManager, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_filter_field': self._field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n" }, { "alpha_fraction": 0.6278141140937805, "alphanum_fraction": 0.6289033889770508, "avg_line_length": 35.91688919067383, "blob_id": "e81544a50075ccb8a4e05ec5218b3b4c311024f6", "content_id": "29c307b8d71bfba066eb9064bb896839d496bb87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13770, "license_type": "no_license", "max_line_length": 79, "num_lines": 373, "path": "/gridplatform/users/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport warnings\n\nfrom django.contrib.auth import hashers\nfrom django.contrib.auth.models import User as DjangoUser\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db.models.signals import post_save\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedEmailField\nfrom gridplatform.encryption.fields import EncryptedField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.models import EncryptionKey\nfrom gridplatform.encryption.models import EncryptionUser\nfrom gridplatform.encryption.signals import encryption_key_created\nfrom gridplatform.encryption.signals import encryption_user_created\nfrom gridplatform.trackuser import get_user\n\nfrom .managers import BoundUserManager\nfrom .managers import UserManager\nfrom .managers import hash_username\n\n\nclass User(DjangoUser, EncryptionUser, EncryptedModel):\n \"\"\"\n GridPlatform user. Includes encrypted replacement fields for several of\n Djangos built-in User fields.\n\n :ivar user_type: One of :py:attr:`USER_TYPE_CHOICES`.\n :ivar e_mail: Email.\n :ivar phone:\n :ivar mobile: cell phone\n :ivar name:\n :ivar customer: A foreign key to\n :py:class:`gridplatform.customers.models.Customer`. If set this user\n belongs to this customer. This field may not be updated. If\n ``self.provider`` is set, this field must be ``None``.\n :ivar provider: A foreign key to\n :py:class:`gridplatform.providers.models.Provider`. If set this user\n belongs to this provider. This field may not be updated. If\n ``self.customer`` is set, this field must be ``None``.\n \"\"\"\n ADMIN = 1\n CUSTOMER_SUPERUSER = 2\n CUSTOMER_USER = 3\n API_USER = 4\n USER_TYPE_CHOICES = (\n (ADMIN, _('Admin')),\n (CUSTOMER_SUPERUSER, _('Super User')),\n (CUSTOMER_USER, _('User')),\n (API_USER, _('Api User')),\n )\n user_type = models.IntegerField(\n choices=USER_TYPE_CHOICES, blank=True, null=True)\n\n # normal email property of Django User not encrypted\n e_mail = EncryptedEmailField(_('e-mail address'))\n phone = EncryptedCharField(_('phone'), max_length=20)\n mobile = EncryptedCharField(_('mobile'), max_length=20, blank=True)\n # normal first_name/last_name of Django User not encrypted\n name = EncryptedCharField(_('name'), max_length=60)\n\n customer = models.ForeignKey(\n 'customers.Customer', verbose_name=_('customer'),\n blank=True, null=True, editable=False)\n provider = models.ForeignKey(\n 'providers.Provider', verbose_name=_('provider'),\n blank=True, null=True, editable=False)\n\n objects = BoundUserManager()\n _all_users = UserManager()\n\n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n ordering = ['user_type', 'name', 'id']\n permissions = (\n ('access_provider_site',\n _('Can access the provider site')),\n ('access_led_light_site',\n _('Can access the led light site')),\n ('access_led_light_site_dashboard',\n _('Can access the led light site dashboard')),\n ('access_led_light_site_projects',\n _('Can access the led light site projects')),\n ('access_project_site',\n _('Can access the ESCo Lite site')),\n ('access_price_relay_site',\n _('Can access the Price Relay site')),\n ('access_datahub_site',\n _('Can access the Datahub site')),\n )\n\n def __unicode__(self):\n return unicode(self.name_plain or self.name)\n\n def clean_fields(self, exclude=None):\n \"\"\"\n :raise ValidationError: if ``self.is_staff`` and ``self.customer`` or\n ``self.provider`` is set.\n :raise ValidationError: If both ``self.customer`` and ``self.provider``\n are set, or both are not set.\n \"\"\"\n if self.is_staff and (self.customer or self.provider):\n raise ValidationError('Staff users can neither be bound to '\n 'customer nor provider')\n elif (not exclude or ('customer' not in exclude and\n 'provider' not in exclude)):\n # unreachable code, as bot customer and provider are not editable.\n if bool(self.customer) == bool(self.provider):\n raise ValidationError('Provider or customer must be set and '\n 'both cannot be set at the same time')\n super(User, self).clean_fields(exclude=exclude)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Derives hashed ``self.username`` from unencrypted email field.\n\n Implements necessary work-arounds for encryption key needed for\n initially encrypting this instance does not exist before the instance\n has been saved.\n \"\"\"\n assert not self.customer_id or not self.provider_id, \\\n 'User cannot be bound to both customer and provider'\n if not self.username:\n self.username = hash_username(self.e_mail_plain)\n\n if not self.id:\n encrypted_field_names = [\n field.name\n for field in self._meta.fields\n if isinstance(field, EncryptedField)\n ]\n if any(getattr(self, '{}_plain'.format(name))\n for name in encrypted_field_names):\n tmp_user = User(\n username=self.username,\n encryption_public_key=self.encryption_public_key,\n customer_id=self.customer_id,\n provider_id=self.provider_id,\n )\n tmp_user.save(force_insert=True, force_update=False)\n self.id = tmp_user.id\n opts = kwargs.copy()\n opts.update({'force_insert': False, 'force_update': True})\n super(User, self).save(*args, **kwargs)\n encryption_user_created.send(sender=User, user=self)\n return\n super(User, self).save(*args, **kwargs)\n\n def _decrypt(self, encryption_context):\n key_id = self.get_encryption_id()\n if key_id not in encryption_context.keys:\n return\n super(User, self)._decrypt(encryption_context)\n\n def get_username(self):\n \"\"\"\n The username is the decrypted email.\n \"\"\"\n return self.e_mail_plain\n\n def set_password(self, raw_password, old_password=None):\n \"\"\"\n Updates private keys upon password change.\n \"\"\"\n if not raw_password:\n raise ValueError('The given password must be set')\n if self.encryption_private_key:\n if not old_password:\n # On Django 1.5 -> 1.6 upgrade, the default password hashing\n # algorithm was changed.\n # ... when that happens, users passwords are \"set\" to the\n # current entered password on a successful login, in order to\n # have it stored with the updated hash...\n warnings.warn(\n 'old password not provided; will not update encryption')\n else:\n if not self.check_password(old_password):\n raise ValueError('Incorrect old password')\n self.update_private_key(old_password, raw_password)\n self.password = hashers.make_password(raw_password)\n else:\n self.password = hashers.make_password(raw_password)\n self.generate_private_key(raw_password)\n\n def reset_password(self, request, raw_password):\n \"\"\"\n To be run by admin/other with permission to access/share relevant keys.\n\n User will need a new private key. (The private key can't be preserved\n unless old_password is provided; set_password will report an error if\n we try.)\n \"\"\"\n self.encryption_private_key = bytearray()\n self.set_password(raw_password)\n # Remove and re-grant all currently known keys.\n\n old_keys = set([key.key_id() for key in self.encryptionkey_set.all()])\n EncryptionKey.objects.filter(user=self).delete()\n for key in old_keys:\n EncryptionKey.share(key, self)\n\n @property\n def is_admin(self):\n \"\"\"\n for easier checks in template code\n \"\"\"\n return self.user_type == self.ADMIN\n\n @property\n def is_customer_superuser(self):\n \"\"\"\n for easier checks in template code\n \"\"\"\n return self.user_type == self.CUSTOMER_SUPERUSER\n\n def get_encryption_id(self):\n \"\"\"\n Implementation of abstract method declared by\n :class:`gridplatform.encryption.models.EncryptedModel`.\n \"\"\"\n return (User, self.id)\n\n def satisfies_search(self, search):\n \"\"\"\n Implementation of interface required by\n :py:func:`gridplatform.utils.views.json_list_response` view function\n decorator.\n\n :param search: A string to search for.\n\n :return: True if the ``search`` argument is found in any relevant\n property of this customer.\n \"\"\"\n elems = [\n self.name_plain,\n self.e_mail_plain\n ]\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n\n@receiver(post_save, sender=User)\ndef create_user_key(sender, instance, created, raw, **kwargs):\n \"\"\"\n Signal handler generating encryption keys for freshly created users.\n \"\"\"\n if raw:\n return\n if created:\n EncryptionKey.generate((sender, instance.id))\n\n\n@receiver(encryption_key_created)\ndef auto_grant_to_admins(sender, key, key_id, **kwargs):\n \"\"\"\n Signal handler granting any created encryption keys to admin users.\n \"\"\"\n admins = User._all_users.filter(user_type=User.ADMIN)\n user = get_user()\n for admin in admins:\n # already shared to current user, so avoid repeating it...\n if admin != user:\n admin.grant_key(key_id, key)\n\n\n@receiver(encryption_key_created, sender=User)\ndef auto_grant_user_self_key(sender, key, key_id, **kwargs):\n \"\"\"\n Signal handler granting key with user identifier to that user.\n \"\"\"\n model_class, object_id = key_id\n assert sender is model_class\n user = model_class._all_users.get(id=object_id)\n user.grant_key(key_id, key)\n\n\n@receiver(encryption_key_created, sender=User)\ndef auto_grant_user_key_to_superusers(sender, key, key_id, **kwargs):\n \"\"\"\n If key created for user on customer, find all the superuser for that\n customer and shares the key to them.\n \"\"\"\n model_class, object_id = key_id\n assert sender is model_class\n user = model_class._all_users.get(id=object_id)\n if user.customer:\n customer = user.customer\n superusers = customer.user_set.filter(\n user_type=User.CUSTOMER_SUPERUSER)\n for superuser in superusers:\n superuser.grant_key(key_id, key)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_customer_key(sender, user, **kwargs):\n \"\"\"\n Provide key from customer that user is associated with.\n \"\"\"\n if user.customer_id:\n key_id = (Customer, user.customer_id)\n EncryptionKey.share(key_id, user)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_customer_superuser_user_keys(sender, user, **kwargs):\n \"\"\"\n If the new user is a superuser, then give access to keys for user\n information for users on same customer.\n \"\"\"\n if user.customer and user.user_type == User.CUSTOMER_SUPERUSER:\n customer = user.customer\n users = customer.user_set.all()\n for otheruser in users:\n EncryptionKey.share((User, otheruser.id), user)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_provideruser_provider_key(sender, user, **kwargs):\n \"\"\"\n Signal handler granting new provider users the encryption key for the same\n provider.\n \"\"\"\n from gridplatform.providers.models import Provider\n if user.provider:\n assert not user.customer\n EncryptionKey.share((Provider, user.provider_id), user)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_provideruser_customer_keys(sender, user, **kwargs):\n \"\"\"\n Signal handler granting new provider users the encryption keys for all\n customers of the same provider.\n \"\"\"\n if user.provider:\n assert not user.customer\n for customer in user.provider.customer_set.all():\n EncryptionKey.share((Customer, customer.id), user)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_provideruser_customeruser_keys(sender, user, **kwargs):\n \"\"\"\n Signal handler granting new provider users the encryption key for each user\n of all customers of the same provider.\n \"\"\"\n if user.provider:\n assert not user.customer\n for customeruser in User._all_users.filter(\n customer__provider_id=user.provider_id):\n EncryptionKey.share((User, customeruser.id), user)\n\n\n@receiver(encryption_user_created)\ndef auto_grant_provideruser_provideruser_keys(sender, user, **kwargs):\n \"\"\"\n Signal handler granting new provider users the encryption key for each user\n of the same provider.\n \"\"\"\n if user.provider:\n assert not user.customer\n for provideruser in User._all_users.filter(\n provider_id=user.provider_id):\n EncryptionKey.share((User, provideruser.id), user)\n" }, { "alpha_fraction": 0.5990437269210815, "alphanum_fraction": 0.5997267961502075, "avg_line_length": 35.599998474121094, "blob_id": "98407bf3f0e345c5e97b8f7e2cccd986a0451488", "content_id": "e685b1c34051374c78f0a7004d1c31eade689c2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1464, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/legacy/nordpool/management/commands/setup_nordpool.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\n\nfrom gridplatform.utils import utilitytypes\nfrom legacy.indexes.models import SpotMapping\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.nordpool.conf import settings\n\n\nclass Command(BaseCommand):\n args = ''\n help = 'Setup Nordpool spot tariffs for later import by '\\\n '`import_nordpool` command'\n\n def handle(self, *args, **options):\n if SpotMapping.objects.exists():\n print 'Nothing to do. Nordpool spot tariffs already setup.'\n return\n\n with transaction.atomic():\n for opts in settings.NORDPOOL_AUTO_INDEXES:\n print 'setting up %s' % opts\n index = Index.objects.create(\n unit=opts['UNIT'],\n name_plain=opts['NAME'],\n timezone=opts['TIMEZONE'],\n role=DataRoleField.ELECTRICITY_TARIFF,\n utility_type=utilitytypes.METER_CHOICES.electricity,\n data_format=Index.SPOT,\n customer=None)\n SpotMapping.objects.create(\n index=index,\n area=opts['AREA'],\n timezone=opts['TIMEZONE'],\n unit=opts['UNIT'])\n" }, { "alpha_fraction": 0.625356137752533, "alphanum_fraction": 0.6310541033744812, "avg_line_length": 19.647058486938477, "blob_id": "ba4496ad7f85a64bb3c453018681b14be00e2de3", "content_id": "659d93c34c1b1081c87d7057b16254c8b25a9146", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 702, "license_type": "no_license", "max_line_length": 115, "num_lines": 34, "path": "/translate.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ -z \"$VIRTUAL_ENV\" ]\nthen\n echo 'Missing (virtual) Python env'\n exit 1\nfi\n\ncd `dirname $0`\n\nmake makemessages -j6 LOCALES=\"da\"\n\nHAS_FUZZY=\"\"\nHAS_UNTRANSLATED=\"\"\nfor FILE in $(find gridplatform energymanager legacy \\( -name django.po -o -name djangojs.po \\) | grep \"locale/da\")\ndo\n if [ -n \"`msgattrib $FILE --only-fuzzy`\" ]\n then\n HAS_FUZZY=\"$HAS_FUZZY $FILE\"\n fi\n if [ -n \"`msgattrib $FILE --untranslated`\" ]\n then\n HAS_UNTRANSLATED=\"$HAS_UNTRANSLATED $FILE\"\n fi\ndone\n\nTO_EDIT=`(for NAME in $HAS_FUZZY $HAS_UNTRANSLATED; do echo $NAME; done) | sort | uniq`\n\nif [ -n \"$TO_EDIT\" ]\nthen\n editor $TO_EDIT\nfi\n\nmake compilemessages -j6 LOCALES=\"da\"\n" }, { "alpha_fraction": 0.638837456703186, "alphanum_fraction": 0.6473528146743774, "avg_line_length": 39.92424392700195, "blob_id": "8be8778008b37f1ce5912ac748b70a1fcd9e30d4", "content_id": "41bd4b463d14ebf93b4abc63062e57ae29d61390", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5402, "license_type": "no_license", "max_line_length": 78, "num_lines": 132, "path": "/legacy/indexes/models/standardmonth.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils import first_last\nfrom gridplatform.utils import condense\nfrom legacy.measurementpoints.models import DataSeries\n\nfrom .index import Index\n\n\nclass StandardMonthIndex(Index):\n \"\"\"\n C{StandardMonthIndex} is a L{DataSeries} whose underlying function is an\n unbound accumulation of standard values explicitly defined for each month.\n \"\"\"\n\n class Meta(Index.Meta):\n verbose_name = _('standard month index')\n verbose_name_plural = _('standard month index')\n app_label = 'indexes'\n\n january = models.DecimalField(decimal_places=3, max_digits=10)\n february = models.DecimalField(decimal_places=3, max_digits=10)\n march = models.DecimalField(decimal_places=3, max_digits=10)\n april = models.DecimalField(decimal_places=3, max_digits=10)\n may = models.DecimalField(decimal_places=3, max_digits=10)\n june = models.DecimalField(decimal_places=3, max_digits=10)\n july = models.DecimalField(decimal_places=3, max_digits=10)\n august = models.DecimalField(decimal_places=3, max_digits=10)\n september = models.DecimalField(decimal_places=3, max_digits=10)\n october = models.DecimalField(decimal_places=3, max_digits=10)\n november = models.DecimalField(decimal_places=3, max_digits=10)\n december = models.DecimalField(decimal_places=3, max_digits=10)\n\n def get_month_quantity(self, timestamp):\n \"\"\"\n Get L{PhysicalQuantity} associated to the month of the given\n C{timestamp}.\n \"\"\"\n assert timestamp == self.timezone.normalize(\n timestamp.astimezone(self.timezone))\n MONTH_ATTRS = ['january', 'february', 'march', 'april',\n 'may', 'june', 'july', 'august',\n 'september', 'october', 'november', 'december']\n # timestamp.month is in [1, 12], not [0, 11]\n return PhysicalQuantity(\n getattr(self, MONTH_ATTRS[timestamp.month - 1]), self.unit)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{StandardMonthIndex} implementation of\n L{DataSeries.get_raw_data_samples()}.\n \"\"\"\n assert from_timestamp <= to_timestamp\n\n # convert end-points to our timezone to ensure L{get_month_value()}\n # works correctly.\n from_timestamp = self.timezone.normalize(\n from_timestamp.astimezone(self.timezone))\n to_timestamp = self.timezone.normalize(\n to_timestamp.astimezone(self.timezone))\n\n month_delta = RelativeTimeDelta(months=1)\n\n accumulated_value = PhysicalQuantity(0, self.unit)\n\n current_month_start = condense.floor(\n from_timestamp, month_delta, self.timezone)\n current_month_end = current_month_start + month_delta\n\n yield self.create_point_sample(\n from_timestamp, accumulated_value)\n\n while current_month_start < to_timestamp:\n current_range_start = max(current_month_start, from_timestamp)\n current_range_end = min(current_month_end, to_timestamp)\n\n accumulated_value += (\n self.get_month_quantity(current_range_start) *\n PhysicalQuantity(\n (current_range_end -\n current_range_start).total_seconds(),\n 'second') /\n PhysicalQuantity(\n (current_month_end -\n current_month_start).total_seconds(),\n 'second'))\n yield self.create_point_sample(\n current_range_end, accumulated_value)\n\n current_month_start = current_month_end\n current_month_end += month_delta\n\n def calculate_development(self, from_timestamp, to_timestamp):\n \"\"\"\n C{StandardMonth} implementation of\n L{DataSeries.calculate_development()}\n\n @note: Could share implementation with CostCalculation, but since\n current implementation requires no queries at all, that will not be\n beneficial, once L{CostCalculation.calculate_development()} is\n optimized using cache.\n \"\"\"\n first, last = first_last(\n self.get_samples(from_timestamp, to_timestamp))\n return self.create_range_sample(\n from_timestamp, to_timestamp,\n last.physical_quantity - first.physical_quantity,\n uncachable=(first.uncachable or last.uncachable))\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n The Index class hierachy is a bit messy. A StandardMonthIndex needs to\n work much like an Index, but its data should be handled more like\n normal DataSeries.\n \"\"\"\n return DataSeries._condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp)\n\n def get_recursive_condense_resolution(self, resolution):\n \"\"\"\n Only one sample pr month in raw data, and these data are part of the\n model itself. No need at all to build cache recursively.\n \"\"\"\n return None\n" }, { "alpha_fraction": 0.6515317559242249, "alphanum_fraction": 0.6518052220344543, "avg_line_length": 33.49056625366211, "blob_id": "5b998340e9ec628c18ed8757233fb5b0ceabec7f", "content_id": "647801bc6e96aa1e4e02608ccdd7eb0bc705cebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3656, "license_type": "no_license", "max_line_length": 79, "num_lines": 106, "path": "/gridplatform/users/decorators.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom functools import wraps\n\nfrom django.utils.decorators import available_attrs\nfrom django.http import HttpResponseForbidden\nfrom django.contrib.auth.views import redirect_to_login\n\nfrom gridplatform.trackuser import get_user\n\n\ndef admin_or_error(view_func):\n \"\"\"\n Decorator for views that checks that the current user has admin privileges,\n and returns a HTTP Forbidden if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated() and user.is_admin:\n return view_func(request, *args, **kwargs)\n else:\n return HttpResponseForbidden()\n return wrapper\n\n\ndef admin_or_redirect(view_func):\n \"\"\"\n Decorator for views that checks that the current user has admin privileges,\n and redirects to the login page if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated() and user.is_admin:\n return view_func(request, *args, **kwargs)\n else:\n return redirect_to_login(request.get_full_path())\n return wrapper\n\n\ndef auth_or_error(view_func):\n \"\"\"\n Decorator for views that checks that the current user is logged in, and\n returns a HTTP Forbidden if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated():\n return view_func(request, *args, **kwargs)\n else:\n return HttpResponseForbidden()\n return wrapper\n\n\ndef auth_or_redirect(view_func):\n \"\"\"\n Decorator for views that checks that the current user is logged in, and\n redirects to the login page if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated():\n return view_func(request, *args, **kwargs)\n else:\n return redirect_to_login(request.get_full_path())\n return wrapper\n\n\ndef customer_admin_or_error(view_func):\n \"\"\"\n Decorator for views that checks that the current user has administrative\n privileges for the current customer, and returns a HTTP Forbidden if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated() and \\\n (user.is_customer_superuser or\n (user.is_admin and\n getattr(request, 'customer', None) is not None)):\n return view_func(request, *args, **kwargs)\n else:\n return HttpResponseForbidden()\n return wrapper\n\n\ndef customer_admin_or_admin_or_error(view_func):\n \"\"\"\n Decorator for views that checks that the current user has administrative\n privileges or administrative privileges for the current customer,\n and returns a HTTP Forbidden if not.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n user = get_user()\n if user is not None and user.is_authenticated() and \\\n (user.is_customer_superuser or user.is_admin):\n return view_func(request, *args, **kwargs)\n else:\n return HttpResponseForbidden()\n return wrapper\n" }, { "alpha_fraction": 0.7183098793029785, "alphanum_fraction": 0.7218309640884399, "avg_line_length": 24.81818199157715, "blob_id": "5da3b0530222d1202798d2eb2d0a7d5c765e5c63", "content_id": "661dbf5b1c3fbdef9433c89180fd59389bc43626", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 51, "num_lines": 11, "path": "/gridplatform/customers/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.functional import cached_property\n\n\nclass GetObjectCustomerMixin(object):\n @cached_property\n def _customer(self):\n return self.get_object().customer\n" }, { "alpha_fraction": 0.7256097793579102, "alphanum_fraction": 0.7317073345184326, "avg_line_length": 19.5, "blob_id": "16bef662a58ed00d5c3f6c64690358a59621da68", "content_id": "39a5703a1cafc65bd5cf11ffadc1ae0145e63c58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 164, "license_type": "no_license", "max_line_length": 52, "num_lines": 8, "path": "/gridagentserver-protocol/run_tests.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd `dirname $0`\n\npython -m unittest discover -p '**_test.py'\n\n# unit test library from twisted...\ntrial gridagentserver_protocol.twisted_protocol_test\n" }, { "alpha_fraction": 0.6296394467353821, "alphanum_fraction": 0.629904568195343, "avg_line_length": 42.86046600341797, "blob_id": "ef80615a095fd9a82ad16514a2894de632513a70", "content_id": "faef2b9be634d37f5306647e0d053fcf3c1f3532", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3772, "license_type": "no_license", "max_line_length": 109, "num_lines": 86, "path": "/legacy/manage_devices/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'legacy.manage_devices.views',\n url(r'^$',\n 'agent_list',\n name='manage_devices-list'),\n url(r'^meters/$',\n 'meter_list',\n name='manage_devices-meter-list'),\n url(r'^json/agent/$',\n 'agent_list_json',\n name='manage_devices-agent-list-json'),\n url(r'^agent/form/(?P<pk>\\d+)/$',\n 'agent_form',\n name='manage_devices-agent-form'),\n url(r'^agent/update/(?P<pk>\\d+)/$',\n 'agent_update',\n name='manage_devices-agent-update'),\n url(r'^json/meter/$',\n 'meter_list_json',\n name='manage_devices-meter-list-json'),\n url(r'^meter/update/(?P<pk>\\d+)/$',\n views.MeterUpdateView.as_view(),\n name='manage_devices-meter-update'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/update$',\n views.pulseconversion_update,\n name='manage_devices-pulseconversion-update'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/electricity$',\n views.ElectricityConsumptionCreateView.as_view(),\n name='manage_devices-pulseconversion-electricity-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/electricity/update$',\n views.ElectricityConsumptionUpdateView.as_view(),\n name='manage_devices-pulseconversion-electricity-update'),\n\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/water$',\n views.WaterConsumptionCreateView.as_view(),\n name='manage_devices-pulseconversion-water-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/water/update$',\n views.WaterConsumptionUpdateView.as_view(),\n name='manage_devices-pulseconversion-water-update'),\n\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/district_heating$', # noqa\n views.DistrictHeatingConsumptionCreateView.as_view(),\n name='manage_devices-pulseconversion-district_heating-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/district_heating/update$',\n views.DistrictHeatingConsumptionUpdateView.as_view(),\n name='manage_devices-pulseconversion-district_heating-update'),\n\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/gas$',\n views.GasConsumptionCreateView.as_view(),\n name='manage_devices-pulseconversion-gas-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/gas/update$',\n views.GasConsumptionUpdateView.as_view(),\n name='manage_devices-pulseconversion-gas-update'),\n\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/oil$',\n views.OilConsumptionCreateView.as_view(),\n name='manage_devices-pulseconversion-oil-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/oil/update$',\n views.OilConsumptionUpdateView.as_view(),\n name='manage_devices-pulseconversion-oil-update'),\n\n url(r'^meter/(?P<meter>\\d+)/input/(?P<physicalinput>\\d+)/(?P<production_unit>production_[a-z])$', # noqa\n views.ProductionCreateView.as_view(),\n name='manage_devices-pulseconversion-production-create'),\n url(r'^meter/(?P<meter>\\d+)/input/(?P<pk>\\d+)/production/update$',\n views.ProductionUpdateView.as_view(),\n name='manage_devices-pulseconversion-production-update'),\n\n url(r'^meter/switch_relay/(?P<pk>\\d+)/$',\n 'meter_relay',\n name='manage_devices-meter-relay'),\n url(r'^meter/switch_relay/(?P<pk>\\d+)/(?P<action>on|off)/$',\n 'meter_relay_toggle',\n name='manage_devices-meter-relay-toggle'),\n url(r'^meter/relay_state/(?P<pk>\\d+)/$',\n 'meter_relay_state',\n name='manage_devices-meter-relay-state'),\n)\n" }, { "alpha_fraction": 0.7350427508354187, "alphanum_fraction": 0.7357001900672913, "avg_line_length": 32.065216064453125, "blob_id": "5dee78af46506b7e1133a1f6751bec3d757eee4d", "content_id": "7b57118b5e92c00f5f1465091645ae3b7a909d53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1521, "license_type": "no_license", "max_line_length": 79, "num_lines": 46, "path": "/gridplatform/provider_datasources/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import get_provider\n\nfrom .managers import ProviderDataSourceManager\n\n\n# NOTE: The ProviderDataSourceManager applies to all ProviderDataSource\n# specializations. For the manager to be inherited it must be set on an\n# abstract Model.\nclass ProviderDataSourceBase(DataSource):\n class Meta:\n abstract = True\n\n objects = ProviderDataSourceManager()\n\n\nclass ProviderDataSource(ProviderDataSourceBase):\n \"\"\"\n Specialization of :class:`~gridplatform.datasources.models.DataSource` that\n is owned by :class:`~gridplatform.providers.models.Provider` and shared\n among the :class:`~gridplatform.customers.models.Customer` of that\n :class:`~gridplatform.providers.models.Provider`.\n\n :ivar provider: The owning\n :class:`~gridplatform.providers.models.Provider`.\n\n :cvar objects: The manager of :class:`.ProviderDataSource` is a\n :class:`.ProviderDataSourceManager`.\n \"\"\"\n provider = models.ForeignKey(\n Provider, verbose_name=_('provider'), default=get_provider)\n\n class Meta:\n verbose_name = _('provider data source')\n verbose_name_plural = _('provider data sources')\n\n def __unicode__(self):\n return self.hardware_id\n" }, { "alpha_fraction": 0.6154791116714478, "alphanum_fraction": 0.6160933375358582, "avg_line_length": 30.30769157409668, "blob_id": "98e44d83c5e2c08fb88512e9130a81660fdffc1a", "content_id": "aa8ad5670c6d513a599054806aae8bb6ee431c5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1628, "license_type": "no_license", "max_line_length": 78, "num_lines": 52, "path": "/gridplatform/utils/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n\nclass DateRangeManagerMixin(object):\n \"\"\"\n Mixes :meth:`~.DateRangeManagerMixin.in_range` into mixed manager.\n Intended for managers used for\n :class:`~gridplatform.utils.models.DateRangeModelMixin` mixed\n models.\n \"\"\"\n\n def in_range(self, from_date, to_date):\n \"\"\"\n A queryset of rows that have a non-empty overlap with the given range.\n\n :param from_date: Rows must be overlapping with this date or\n later.\n :param to_date: Rows must be overlapping with this date or\n earlier.\n \"\"\"\n return self.filter(\n (\n models.Q(to_date__gte=from_date) |\n models.Q(to_date__isnull=True)),\n from_date__lt=to_date)\n\n\nclass TimestampRangeManagerMixin(object):\n \"\"\"\n Mixes :meth:`~.TimestampRangeManagerMixin.in_range` into mixed\n manager. Intended for managers used for\n :class:`~gridplatform.utils.models.TimestampRangeModelMixin` mixed\n models.\n \"\"\"\n\n def in_range(self, from_timestamp, to_timestamp):\n \"\"\"\n A queryset of rows that have a non-empty overlap with the given\n range.\n\n :param from_timestamp: The start point of the given range.\n :param to_timestamp: The end point of the given range.\n \"\"\"\n return self.filter(\n (\n models.Q(to_timestamp__gte=from_timestamp) |\n models.Q(to_timestamp__isnull=True)),\n from_timestamp__lt=to_timestamp)\n" }, { "alpha_fraction": 0.718120813369751, "alphanum_fraction": 0.7248322367668152, "avg_line_length": 28.799999237060547, "blob_id": "0da620b79354ac42be5ae088a5283e4f5f9921ae", "content_id": "2873fde87a7b0505d352925e01ba14e7a10f7fbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 149, "license_type": "no_license", "max_line_length": 44, "num_lines": 5, "path": "/gridplatform/datasequences/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# from django.utils.unittest import TestCase\n" }, { "alpha_fraction": 0.6639999747276306, "alphanum_fraction": 0.6759999990463257, "avg_line_length": 18.230770111083984, "blob_id": "e129d538c4fadb70d0fbdb70de21dd9691dbdb7e", "content_id": "3936eff9eb5dbb692b00ed7c7163d965b55b46bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 50, "num_lines": 52, "path": "/fixture_hack.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\nif [ -z \"$VIRTUAL_ENV\" ]\nthen\n echo \"ERROR: virtualenv not active\"\n exit -1\nfi\n\n# sudo -u postgres dropdb portal\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n dropdb -h localhost portal\nelse\n dropdb portal\nfi\n\nif [ $? -ne 0 ]\nthen\n echo \"ERROR: failed to drop database\"\n exit -1\nfi\n\n# sudo -u postgres createdb -O $USER portal\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n createdb -h localhost -E utf8 portal\nelse\n createdb -E utf8 portal\nfi\nif [ $? -ne 0 ]\nthen\n echo \"ERROR: failed to recreate database\"\n exit -1\nfi\n\necho 'Clearing memcached (old sessions...)'\necho 'flush_all' | telnet localhost 11211\n\nset -e\n\necho 'Clearing pyc-files'\nfind . -name '*.pyc' -delete\n\necho 'Setting up tables'\ngunzip -c initial.sql.gz | psql portal > /dev/null\n./manage.py migrate --all --noinput --traceback\n./manage.py fix_contenttypes_and_permissions\n\necho 'Adding \"fixture\" data'\npython fixture_hack.py\n#python measurement_fixture.hack.py\n#./manage.py loaddata salestool_data\necho 'done'\n" }, { "alpha_fraction": 0.7585914134979248, "alphanum_fraction": 0.7594399452209473, "avg_line_length": 39.63793182373047, "blob_id": "1baa891d69ad8674e335fac745bc386aca975f6f", "content_id": "a09b9fae6deaaa497829425ccdc7a38ddd934841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2357, "license_type": "no_license", "max_line_length": 77, "num_lines": 58, "path": "/documentation/source/apps/gridplatform/consumptions.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Consumptions\n============\n\nThis app defines models directly related to consumption, including\nmain consumptions, energy uses and consumption data sequences.\n\nMain Consumption and Energy Use\n-------------------------------\n\nThe consumptions app defines the models\n:py:class:`~gridplatform.consumptions.models.MainConsumption` and\n:py:class:`~gridplatform.consumptions.models.ConsumptionGroup`, where\nthe later should have been named ``EnergyUse``. The commonality\nbetween these two models are sufficiently big that they share a base\nclass\n:py:class:`~gridplatform.consumptions.models.ConsumptionUnionBase`.\n\n\n.. autoclass:: gridplatform.consumptions.models.ConsumptionUnionBase\n :members: energy_sum, energy_sequence, utility_sum, utility_sequence,\n net_cost_sum, net_cost_sequence,\n variable_cost_sum, variable_cost_sequence,\n costcompensation_amount_sum,\n co2_emissions_sum, co2_emissions_sequence\n\n.. autoclass:: gridplatform.consumptions.models.MainConsumption\n :members: costcompensation_amount_sequence, total_cost_sum, fixed_cost_sum\n\n.. autoclass:: gridplatform.consumptions.models.ConsumptionGroup\n :members: costcompensation_amount_sequence\n\nConsumption Data Sequence\n-------------------------\n\nSecondarily the\n:py:class:`~gridplatform.consumptions.models.Consumption` (a\n``DataSequence`` specialization) is defined, along with small pallete\nof input configuration periods.\n\nIn particular one period\n:py:class:`~gridplatform.consumptions.models.NonepulsePeriod` is used\nto define the ``utility_sequence()`` of ``Consumption`` directly from\n``DataSource`` with the relevant utility unit, and another period\n:py:class:`~gridplatform.consumptions.models.PulsePeriod` is used to\ndefine the ``utility_sequence()`` of ``Consumption`` via pulse\nconversion from ``DataSource`` with the ``\"impulse\"`` unit. Finally a\nperiod that skips the ``DataSource`` framework entirely is available,\nthe :py:class:`~gridplatform.consumptions.models.SingleValuePeriod`.\n\n.. autoclass:: gridplatform.consumptions.models.Consumption\n :members: clean, energy_sequence, energy_sum,\n utility_sequence, utility_sum\n\n.. autoclass:: gridplatform.consumptions.models.NonpulsePeriod\n\n.. autoclass:: gridplatform.consumptions.models.PulsePeriod\n\n.. autoclass:: gridplatform.consumptions.models.SingleValuePeriod\n" }, { "alpha_fraction": 0.6261400580406189, "alphanum_fraction": 0.6286353468894958, "avg_line_length": 34.650306701660156, "blob_id": "325d24b751c225fa5eac420e9633fc4b0ae197eb", "content_id": "5cdab524b832c19c16484101f6bd73a8f60aec90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11622, "license_type": "no_license", "max_line_length": 79, "num_lines": 326, "path": "/legacy/manage_rules/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseForbidden, Http404\nfrom django.shortcuts import redirect\nfrom django.forms.models import inlineformset_factory, modelform_factory\nfrom django.db.models import BLANK_CHOICE_DASH\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom django.utils.translation import ugettext as _\nfrom django.views.decorators.http import require_http_methods\n\nfrom gridplatform.utils.views import (\n render_to,\n json_list_response,\n)\nfrom gridplatform.utils import units\nfrom legacy.rules.models import (\n UserRule, MinimizeRule, TriggeredRule,\n DateException,\n RelayAction, EmailAction, PhoneAction, Action,\n IndexInvariant, InputInvariant,\n)\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.users.decorators import (\n auth_or_error,\n customer_admin_or_error,\n)\nfrom gridplatform.trackuser import get_customer\n\n\n@auth_or_error\n@json_list_response\ndef rule_list_json(request):\n customer = request.customer\n rules = list(UserRule.objects.filter(customer=customer))\n\n order_map = {\n 'name': lambda rule: rule.name_plain.lower(),\n }\n return (order_map, rules, 'manage_rules/rule_block.html')\n\n\nclass MinimizeRuleForm(forms.ModelForm):\n class Meta:\n model = MinimizeRule\n localized_fields = '__all__'\n fields = (\n 'name', 'enabled', 'timezone', 'monday', 'tuesday', 'wednesday',\n 'thursday', 'friday', 'saturday', 'sunday', 'from_time', 'to_time',\n 'consecutive', 'activity_duration', 'index',\n )\n\n def clean_activity_duration(self):\n activity_duration = self.cleaned_data['activity_duration']\n # checks both length of duration and blank duration\n if not activity_duration:\n raise forms.ValidationError(_(\"Duration is required\"))\n return activity_duration\n\nTriggeredRuleForm = modelform_factory(\n TriggeredRule, localized_fields='__all__')\n\n\ndef base_rule_formsets(rule, meters_qs, data=None):\n\n class Meta:\n model = RelayAction\n exclude = ['execution_time']\n\n RelayActionForm = type(b'RelayActionForm', (ModelForm,), {\n 'meter': forms.ModelChoiceField(\n queryset=meters_qs),\n 'Meta': Meta,\n })\n\n class PhoneActionForm(forms.ModelForm):\n phone_number = forms.CharField(\n label=_('phone number'), min_length=10)\n\n class Meta:\n model = PhoneAction\n exclude = ('execution_time', )\n localized_fields = '__all__'\n\n DateExceptionFormset = inlineformset_factory(\n UserRule, DateException, extra=0)\n RelayActionFormSet = inlineformset_factory(\n UserRule, RelayAction, form=RelayActionForm, extra=0)\n EmailActionFormSet = inlineformset_factory(\n UserRule, EmailAction, exclude=['execution_time'], extra=0)\n PhoneActionFormSet = inlineformset_factory(\n UserRule, PhoneAction, form=PhoneActionForm, extra=0)\n result = {\n 'dateexception': DateExceptionFormset(\n data, instance=rule, auto_id=False, prefix='dateexception'),\n }\n for name, cls in [('relay', RelayActionFormSet),\n ('email', EmailActionFormSet),\n ('phone', PhoneActionFormSet)]:\n result[name + '_initial'] = cls(\n data, instance=rule, auto_id=False, prefix=name + '-initial',\n queryset=cls.model.objects.filter(\n rule=rule, execution_time=Action.INITIAL))\n result[name + '_final'] = cls(\n data, instance=rule, auto_id=False, prefix=name + '-final',\n queryset=cls.model.objects.filter(\n rule=rule, execution_time=Action.FINAL))\n return result\n\n\n@customer_admin_or_error\n@render_to('manage_rules/minimizerule_form.html')\ndef minimizerule_form(request, pk=None):\n customer = request.customer\n if pk:\n rule = get_object_or_404(MinimizeRule, pk=pk)\n if rule.customer != customer:\n return HttpResponseForbidden()\n else:\n rule = None\n if request.method == 'POST':\n data = request.POST\n else:\n data = None\n\n form = MinimizeRuleForm(data, auto_id=False, instance=rule)\n qs = Index.objects.all().exclude(\n role__in=[DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n DataRoleField.CO2_QUOTIENT])\n form.fields['index'].queryset = qs\n\n if data and form.is_valid():\n rule = form.save(commit=False)\n meters_qs = customer.meter_set.filter(relay_enabled=True)\n formsets = base_rule_formsets(rule, meters_qs, data)\n if data and form.is_valid() and all([f.is_valid()\n for f in formsets.itervalues()]):\n rule = form.save(commit=False)\n rule.customer = request.customer\n rule.save()\n for name, formset in formsets.iteritems():\n instances = formset.save(commit=False)\n for instance in instances:\n if name.endswith('_initial'):\n instance.execution_time = Action.INITIAL\n elif name.endswith('_final'):\n instance.execution_time = Action.FINAL\n instance.save()\n if pk:\n messages.success(request, _('The rule has been saved'))\n else:\n messages.success(request, _('The rule has been created'))\n if 'save_return' in data:\n return redirect('manage_rules-list')\n if not pk:\n return redirect('manage_rules-minimizerule_form',\n pk=rule.id)\n else:\n # reload formsets from DB, to get IDs, remove deleted...\n formsets = base_rule_formsets(rule, meters_qs)\n\n return {\n 'form': form,\n 'formsets': formsets,\n }\n\n\nclass IndexInvariantForm(ModelForm):\n \"\"\"\n C{ModelForm} for L{IndexInvariant}s.\n\n This form is intended for use in inline formsets, so it is required to\n work-out-of-the-box without special initialization requirements.\n \"\"\"\n class Meta:\n model = IndexInvariant\n fields = ('operator', 'index', 'value')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(IndexInvariantForm, self).__init__(*args, **kwargs)\n self.fields['index'].queryset = Index.objects.filter(\n Q(customer=get_customer()) | Q(customer=None)).exclude(\n role__in=[DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n DataRoleField.CO2_QUOTIENT])\n\n def save(self, commit=True):\n \"\"\"\n C{IndexInvariantForm} specialization of C{ModelForm.save()}. Unit is\n derived from the chosen index.\n \"\"\"\n super(IndexInvariantForm, self).save(commit=False)\n self.instance.unit = self.instance.index.unit\n if commit:\n super(IndexInvariantForm, self).save(commit=True)\n return self.instance\n\n\nclass InputInvariantForm(ModelForm):\n \"\"\"\n C{ModelForm} for L{InputInvariant}s.\n\n This form is intended for use in inline formsets, so it is required to\n work-out-of-the-box without special initialization requirements.\n \"\"\"\n unit = forms.ChoiceField(\n choices=tuple(BLANK_CHOICE_DASH) +\n units.INPUT_CHOICES + units.CURRENCY_CHOICES)\n\n class Meta:\n model = InputInvariant\n fields = ('operator', 'data_series', 'value', 'unit')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(InputInvariantForm, self).__init__(*args, **kwargs)\n self.fields['data_series'].queryset = \\\n DataSeries.objects.filter(\n graph__collection__customer=get_customer()).exclude(\n role__in=DataSeries.HIDDEN_ROLES).exclude(\n graph__role__in=DataSeries.HIDDEN_ROLES)\n\n customer = get_customer()\n self.fields['unit'].choices.extend(\n customer.get_production_unit_choices())\n\n\ndef triggeredrule_formsets(rule, meters_qs, data=None):\n IndexInvariantFormSet = inlineformset_factory(\n TriggeredRule, IndexInvariant, form=IndexInvariantForm, extra=0)\n InputInvariantFormSet = inlineformset_factory(\n TriggeredRule, InputInvariant, form=InputInvariantForm, extra=0)\n\n result = {\n 'index_invariant': IndexInvariantFormSet(\n data, instance=rule, auto_id=False, prefix='index-invariant'),\n 'input_invariant': InputInvariantFormSet(\n data, instance=rule, auto_id=False, prefix='input-invariant'),\n }\n result.update(base_rule_formsets(rule, meters_qs, data))\n return result\n\n\n@customer_admin_or_error\n@render_to('manage_rules/triggeredrule_form.html')\ndef triggeredrule_form(request, pk=None):\n customer = request.customer\n if pk:\n rule = get_object_or_404(TriggeredRule, pk=pk)\n if rule.customer != customer:\n return HttpResponseForbidden()\n initial = {}\n else:\n rule = None\n initial = {\"timezone\": get_customer().timezone}\n if request.method == 'POST':\n data = request.POST\n else:\n data = None\n form = TriggeredRuleForm(data, auto_id=False, instance=rule,\n initial=initial)\n if data and form.is_valid():\n rule = form.save(commit=False)\n meters_qs = customer.meter_set.filter(relay_enabled=True)\n\n formsets = triggeredrule_formsets(rule, meters_qs, data)\n if data and form.is_valid() and all([f.is_valid()\n for f in formsets.itervalues()]):\n rule = form.save(commit=False)\n rule.customer = request.customer\n rule.save()\n for name, formset in formsets.iteritems():\n instances = formset.save(commit=False)\n for instance in instances:\n if name.endswith('_initial'):\n instance.execution_time = Action.INITIAL\n elif name.endswith('_final'):\n instance.execution_time = Action.FINAL\n instance.save()\n\n if pk:\n messages.success(request, _('The rule has been saved'))\n else:\n messages.success(request, _('The rule has been created'))\n\n if 'save_return' in data:\n return redirect('manage_rules-list')\n if not pk:\n return redirect('manage_rules-triggeredrule_form',\n pk=rule.id)\n else:\n # reload formsets from DB, to get IDs, remove deleted...\n formsets = triggeredrule_formsets(rule, meters_qs)\n return {\n 'form': form,\n 'formsets': formsets,\n }\n\n\n@customer_admin_or_error\ndef form(request, pk):\n if TriggeredRule.objects.filter(pk=pk).exists():\n return redirect('manage_rules-triggeredrule_form', pk=pk)\n elif MinimizeRule.objects.filter(pk=pk).exists():\n return redirect('manage_rules-minimizerule_form', pk=pk)\n raise Http404('No rule with pk=%s' % (pk,))\n\n\n@require_http_methods([\"POST\"])\n@customer_admin_or_error\ndef delete(request):\n pk = request.POST.get('pk', None)\n customer = request.customer\n rule = get_object_or_404(UserRule, pk=pk)\n if rule.customer != customer:\n return HttpResponseForbidden()\n rule.delete()\n messages.success(request, _('The rule has been deleted'))\n return redirect('manage_rules-list')\n" }, { "alpha_fraction": 0.7683615684509277, "alphanum_fraction": 0.7796609997749329, "avg_line_length": 34.400001525878906, "blob_id": "aea81adb9e1d011d8dff5751c629fceb67f66b33", "content_id": "518f00c053d2ea4c01d8c5951e8593325b3a4bcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 177, "license_type": "no_license", "max_line_length": 73, "num_lines": 5, "path": "/gridagentserver-protocol/gridagentserver_protocol/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# Protocol and library version will differ; protocol version is always an\n# integer without any concept of major/minor versions...\n\nPROTOCOL_VERSION = 5\nSECRET = \"jicWehirnEn2\"\n" }, { "alpha_fraction": 0.743388831615448, "alphanum_fraction": 0.7443682551383972, "avg_line_length": 31.935483932495117, "blob_id": "e30694302cda9ceac567251256567b295c90e054", "content_id": "9ca5c9d8bdf0a96b6ac4453490913fd0800c0c6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 66, "num_lines": 31, "path": "/gridplatform/customer_datasources/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport django_filters\nfrom rest_framework.viewsets import ModelViewSet\n\nfrom gridplatform.encryption.filters import DecryptingSearchFilter\nfrom gridplatform.rest.viewsets import NestedMixin\nfrom . import models\nfrom . import serializers\n\n\nclass CustomerDataSourceFilter(django_filters.FilterSet):\n hardware_id_contains = django_filters.CharFilter(\n name='hardware_id', lookup_type='contains')\n name_contains = DecryptingSearchFilter(name='name_plain')\n\n class Meta:\n model = models.CustomerDataSource\n fields = (\n 'customer', 'unit', 'hardware_id',\n 'hardware_id_contains', 'name_contains'\n )\n\n\nclass CustomerDataSourceViewSet(NestedMixin, ModelViewSet):\n model = models.CustomerDataSource\n serializer_class = serializers.CustomerDataSourceSerializer\n filter_class = CustomerDataSourceFilter\n filter_fields = CustomerDataSourceFilter.Meta.fields\n" }, { "alpha_fraction": 0.6658735275268555, "alphanum_fraction": 0.6665533781051636, "avg_line_length": 26.49532699584961, "blob_id": "6f3a61cc345335291c097f824b9628e14afdb072", "content_id": "8bfdd9c9fe9e3316587a221ab8fc73784a4677b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2942, "license_type": "no_license", "max_line_length": 74, "num_lines": 107, "path": "/gridplatform/encryption/test_urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.http import HttpResponse, HttpResponseBadRequest\nfrom django import template\n\nfrom .conf import settings\nfrom .tests import ModelWithSecrets\nfrom .tests import TestModel\nfrom .models import EncryptionKey\nfrom .middleware import _store\nfrom . import get_encryption_context\n\n\ndef simple_view(request):\n return HttpResponse()\n\n\ndef set_secret(request):\n secret = request.POST['secret']\n setattr(_store, settings.ENCRYPTION_STORE_KEY, secret)\n return HttpResponse()\n\n\ndef get_secret(request):\n secret = getattr(_store, settings.ENCRYPTION_STORE_KEY, None)\n if secret is not None:\n return HttpResponse(secret)\n else:\n return HttpResponseBadRequest()\n\n\ndef encryption_password_change(request):\n user = request.user\n old_password = request.POST['old_password']\n new_password = request.POST['new_password']\n user.update_private_key(old_password, new_password, save=True)\n return HttpResponse()\n\n\ndef read_context(request):\n t = template.Template('')\n c = template.Context({\n 'encryption_context': getattr(_store, 'encryption_context', None)\n })\n return HttpResponse(t.render(c))\n\n\ndef after_login(request):\n password = request.POST['password']\n _store.private_key = request.user.decrypt_private_key(password)\n return read_context(request)\n\n\ndef generate_data_key(request):\n link_id = int(request.POST['link_id'])\n key_id = (TestModel, link_id)\n EncryptionKey.generate(key_id)\n return read_context(request)\n\n\ndef read_secret(request):\n obj_id = int(request.GET['id'])\n link_id = int(request.GET['link_id'])\n obj = ModelWithSecrets.objects.get(pk=obj_id)\n obj.mock_encryption_id = (TestModel, link_id)\n try:\n obj._decrypt(get_encryption_context())\n except UnicodeDecodeError:\n # Output from AES decryption was not valid UTF-8; wrong decryption\n # key...\n pass\n t = template.Template('')\n c = template.Context({\n 'obj': obj,\n })\n return HttpResponse(t.render(c))\n\n\ndef store_secret(request):\n link_id = int(request.POST['link_id'])\n obj = ModelWithSecrets()\n obj.name_plain = request.POST['name']\n obj.other_plain = request.POST['other']\n obj.mock_encryption_id = (TestModel, link_id)\n obj.save()\n t = template.Template('')\n c = template.Context({\n 'obj': obj,\n })\n return HttpResponse(t.render(c))\n\n\nurlpatterns = patterns(\n '',\n (r'^$', simple_view),\n (r'^set_secret/$', set_secret),\n (r'^get_secret/$', get_secret),\n (r'^encryption_password_change/$', encryption_password_change),\n (r'^after_login/$', after_login),\n (r'^read_context/$', read_context),\n (r'^generate_data_key/$', generate_data_key),\n (r'^store_secret/$', store_secret),\n (r'^read_secret/$', read_secret),\n)\n" }, { "alpha_fraction": 0.5970602035522461, "alphanum_fraction": 0.5989267230033875, "avg_line_length": 35.016807556152344, "blob_id": "b1dfb61010a101ab3644c6bcfe100342fdbd592d", "content_id": "b6da5e35e5b06d7b681cf3e3d1a6cac4d1c92fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4286, "license_type": "no_license", "max_line_length": 79, "num_lines": 119, "path": "/gridplatform/datasequences/models/qualitycontrol.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nimport datetime\n\nfrom django.db import connection\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.validators import MinValueValidator\n\nfrom gridplatform.utils.iter_ext import pairwise\n\nfrom .nonaccumulation import NonaccumulationDataSequence\n\n\nclass OfflineToleranceMixin(models.Model):\n \"\"\"\n Base class for offline tolerance models. Despite its name, this model is\n barely ever used as a mixin.\n\n :ivar hours: Report error if offline for this many clock hours.\n\n .. class:: _Invalidation\n\n A named tuple with the first element named ``from_datetime`` and the\n second element named ``to_datetime``. Used in return for\n :meth:`.OfflineToleranceMixin.validate_requirement`.\n \"\"\"\n hours = models.PositiveIntegerField(\n _('clock hours'),\n help_text=_('report error if offline for this many clock hours'),\n validators=[MinValueValidator(1)])\n\n class Meta:\n abstract = True\n\n _Invalidation = namedtuple(\n 'Invalidation', ('from_datetime', 'to_datetime'))\n\n def __unicode__(self):\n return 'report error if offline for more than {} clock hours'.format(\n self.hours)\n\n def validate_requirement(self, from_date, to_date):\n \"\"\"\n Validate offline tolerance requirements in given date range.\n\n :param from_date: The first date in the given date range.\n :param to_date: The final date in the given date range.\n\n :return: A list of :class:`_Invalidations<._Invalidation>` named tuples\n where ``self.datasequence`` did not have any date for\n ``self.hours`` or more.\n \"\"\"\n assert from_date <= to_date\n timezone = self.datasequence.customer.timezone\n from_timestamp = timezone.localize(datetime.datetime.combine(\n from_date,\n datetime.time()))\n to_timestamp = timezone.localize(datetime.datetime.combine(\n to_date + datetime.timedelta(days=1),\n datetime.time()))\n online_hours = []\n invalidations = []\n for period in self.datasequence.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'):\n if not hasattr(period.subclass_instance, 'datasource'):\n continue\n\n overlap_from_timestamp, overlap_to_timestamp = period.overlapping(\n from_timestamp, to_timestamp)\n\n cursor = connection.cursor()\n cursor.execute(\n '''\n SELECT DATE_TRUNC('hour', timestamp) AS hour,\n COUNT(*)\n FROM datasources_rawdata\n WHERE datasource_id = %s\n AND timestamp BETWEEN %s AND %s\n GROUP BY hour\n ''', [\n period.subclass_instance.datasource_id,\n overlap_from_timestamp,\n overlap_to_timestamp,\n ]\n )\n online_hours.extend([\n hour for hour, count in cursor.fetchall() if count > 0])\n for a, b in pairwise(\n sorted([from_timestamp] + online_hours + [to_timestamp])):\n if int((b - a).total_seconds() / 3600) > self.hours:\n invalidations.append(\n self._Invalidation(\n from_datetime=timezone.normalize(\n a.astimezone(timezone)),\n to_datetime=timezone.normalize(\n b.astimezone(timezone))))\n return invalidations\n\n\nclass NonaccumulationOfflineTolerance(\n OfflineToleranceMixin, models.Model):\n \"\"\"\n :class:`.OfflineToleranceMixin` specialization for\n :class:`.NonaccumulationDataSequence`.\n\n :ivar datasequence: The :class:`.NonaccumulationDataSequence` this is the\n offline tolerance for.\n \"\"\"\n datasequence = models.OneToOneField(\n NonaccumulationDataSequence,\n related_name='offlinetolerance',\n editable=False)\n\n class Meta:\n app_label = 'datasequences'\n" }, { "alpha_fraction": 0.7885763049125671, "alphanum_fraction": 0.7885763049125671, "avg_line_length": 35.65625, "blob_id": "4fda412b6bf08527cfeabadc571d30bd9bed1c7f", "content_id": "ea988bbdd8d9949d6b905447117deb12a96718f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 72, "num_lines": 32, "path": "/gridagentserver-protocol/gridagentserver_protocol/message_types.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# break module dependency chain...\n# messages module needs the lookup table to construct send/parse message\n# headers; but client/server message modules depend on that code...\n\nimport client_messages\nimport server_messages\n\n# NOTE: order matters; same as in client...\n# (To make ID-number/type mapping simple.)\nmessage_types = [\n client_messages.BulkMeasurements,\n server_messages.ConfigGp,\n server_messages.ConfigGaRulesets,\n server_messages.ConfigGaTime,\n server_messages.ConfigGaPrices,\n server_messages.ConfigGpSoftware,\n server_messages.ConfigGaSoftware,\n server_messages.CommandGaPollMeasurements,\n server_messages.CommandGaPropagateTime,\n server_messages.CommandGpSwitchControl,\n server_messages.CommandGpSwitchRelay,\n client_messages.NotificationGaAddMode,\n client_messages.NotificationGaTime,\n client_messages.NotificationGaConnectedSet,\n client_messages.NotificationGpState,\n client_messages.AcknowledgementGpSoftware,\n client_messages.AcknowledgementGaSoftware,\n client_messages.ErrorGpSoftware,\n client_messages.ErrorGaSoftware,\n client_messages.InfoAgentVersions,\n client_messages.InfoEventLog,\n]\n" }, { "alpha_fraction": 0.7444717288017273, "alphanum_fraction": 0.748157262802124, "avg_line_length": 39.70000076293945, "blob_id": "517148efb690af8b7813a7c3d51b3332712d1b3c", "content_id": "ee3a9e93ffbe5b03a6c1b38822b918dcf92d2bf7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 819, "license_type": "no_license", "max_line_length": 81, "num_lines": 20, "path": "/documentation/source/datasources.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": ".. _data-sources:\n\nData Sources\n============\n\nData sources are streams of samples in the domain. A sample consist of a\nphysical quantity and a timestamp (or timestamp range). Examples of data\nsources are:\n\n * Accumulated energy consumption measured by a particular meter (kWh),\n * Tariff for a particular utility (EUR/kWh or EUR/m³),\n * CO₂ emission quotient (kg/kWh),\n * Temperature measured by a thermometer (°K),\n * Accumulated production counted automatically on a conveyorbelt (say bottles),\n * Power measured by a particular meter (W),\n * Volume flow measured by a particular meter (m²/h), and so on.\n\nSome data sources sample continuous functions (each physical quantity belongs\nto a point in time), and some sample piecewise constant functions (each\nphysical quantity belongs to a range of time).\n" }, { "alpha_fraction": 0.7173366546630859, "alphanum_fraction": 0.7185929417610168, "avg_line_length": 27.428571701049805, "blob_id": "5dc9489d2a0beef6347fa98b486afd60f030930c", "content_id": "27abcd26aed61b9ae9dbc1e4a24e34e46d07099e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/gridplatform/provider_datasources/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport django_filters\nfrom rest_framework import viewsets\n\nfrom . import models\nfrom . import serializers\n\n\nclass ProviderDataSourceFilter(django_filters.FilterSet):\n hardware_id_contains = django_filters.CharFilter(\n name='hardware_id', lookup_type='contains')\n\n class Meta:\n model = models.ProviderDataSource\n fields = (\n 'unit', 'hardware_id',\n 'hardware_id_contains',\n )\n\n\nclass ProviderDataSourceViewSet(viewsets.ModelViewSet):\n model = models.ProviderDataSource\n serializer_class = serializers.ProviderDataSourceSerializer\n filter_class = ProviderDataSourceFilter\n filter_fields = ProviderDataSourceFilter.Meta.fields\n" }, { "alpha_fraction": 0.7762911319732666, "alphanum_fraction": 0.7762911319732666, "avg_line_length": 40.988765716552734, "blob_id": "10e5559c1cdcc301e93e84f589e8749147d8726d", "content_id": "2dcc658d073702df021766d5b800c527e17fd82a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3737, "license_type": "no_license", "max_line_length": 113, "num_lines": 89, "path": "/documentation/source/apps/gridplatform/datasequences.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Data Sequences\n==============\n\nData sequences are the glue between sources of data and applications of data.\nTo support :ref:`changes-in-domain` data sequences are defined in terms of\nperiods. This app defines base classes and utility functions and utility\nclasses related to this task.\n\nModels\n------\n\n.. autoclass:: gridplatform.datasequences.models.CurrencyUnitMixin\n\nBase\n~~~~\n\n.. autofunction:: gridplatform.datasequences.models.base.is_clock_hour\n.. autofunction:: gridplatform.datasequences.models.base.is_five_minute_multiplum\n.. autoclass:: gridplatform.datasequences.models.DataSequenceBase\n :members: next_valid_date, previous_valid_date, validate_requirements\n.. autoclass:: gridplatform.datasequences.models.base.PeriodBaseManager\n :members: in_range\n.. autoclass:: gridplatform.datasequences.models.PeriodBase\n :members: clean, clean_overlapping_periods\n\nAccumulation\n~~~~~~~~~~~~\n\n.. autoclass:: gridplatform.datasequences.models.AccumulationBase\n :members: _hourly_accumulated, _five_minute_accumulated,\n development_sequence, development_sum\n.. autoclass:: gridplatform.datasequences.models.accumulation.AccumulationPeriodManager\n.. autoclass:: gridplatform.datasequences.models.AccumulationPeriodBase\n :members: _hourly_accumulated, _five_minute_accumulated, _get_unit\n.. autoclass:: gridplatform.datasequences.models.NonpulseAccumulationPeriodMixin\n :members: clean, _hourly_accumulated, _five_minute_accumulated\n.. autoclass:: gridplatform.datasequences.models.PulseAccumulationPeriodMixin\n :members: clean, _convert_sample, _hourly_accumulated,\n _five_minute_accumulated\n.. autoclass:: gridplatform.datasequences.models.SingleValueAccumulationPeriodMixin\n :members: clean, _period_accumulated, _hourly_accumulated,\n _five_minute_accumulated\n\nEnergy Conversion\n~~~~~~~~~~~~~~~~~\n\n.. autofunction:: gridplatform.datasequences.models.energyconversion._break_into_hourly_samples\n.. autoclass:: gridplatform.datasequences.models.EnergyPerVolumeDataSequence\n.. autoclass:: gridplatform.datasequences.models.energyconversion.VolumeToEnergyConversionPeriodManager\n :members: value_sequence\n.. autoclass:: gridplatform.datasequences.models.EnergyPerVolumePeriod\n :members: _raw_samples, _value_sequence\n\nNonaccumulation\n~~~~~~~~~~~~~~~\n\n.. autoclass:: gridplatform.datasequences.models.NonaccumulationDataSequence\n :members: clean, raw_sequence\n.. autoclass:: gridplatform.datasequences.models.NonaccumulationPeriod\n :members: _raw_sequence\n\nPiece-wise Constant\n~~~~~~~~~~~~~~~~~~~\n\n.. autoclass:: gridplatform.datasequences.models.PiecewiseConstantBase\n.. autoclass:: gridplatform.datasequences.models.piecewiseconstant.PiecewiseConstantPeriodManagerBase\n :members: value_sequence\n.. autoclass:: gridplatform.datasequences.models.PiecewiseConstantPeriodManager\n.. autoclass:: gridplatform.datasequences.models.PiecewiseConstantPeriodBase\n :members: _value_sequence\n.. autoclass:: gridplatform.datasequences.models.piecewiseconstant.FixedPiecewiseConstantPeriodValueSequenceMixin\n :members: _value_sequence\n\nQuality Control\n~~~~~~~~~~~~~~~\n\n.. autoclass:: gridplatform.datasequences.models.OfflineToleranceMixin\n :members: validate_requirement\n.. autoclass:: gridplatform.datasequences.models.NonaccumulationOfflineTolerance\n\nUtilities\n---------\n\n.. automodule:: gridplatform.datasequences.utils\n :members: _pad_ranged_sample_sequence, multiply_ranged_sample_sequences,\n subtract_ranged_sample_sequences, add_ranged_sample_sequences,\n _fiveminutes_period_key, _hour_period_key, _day_period_key,\n _month_period_key, _quarter_period_key, _year_period_key,\n _PERIOD_KEYS, aggregate_sum_ranged_sample_sequence\n" }, { "alpha_fraction": 0.8089743852615356, "alphanum_fraction": 0.8089743852615356, "avg_line_length": 44.882354736328125, "blob_id": "0f31b947012a88be4bd920e0dc869c4bdeaf7d9c", "content_id": "904c33c0c510bbe6a2769ff641d62b2fe5b755c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 780, "license_type": "no_license", "max_line_length": 89, "num_lines": 17, "path": "/documentation/source/apps/gridplatform/provider_datasources.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Provider Data Sources\n=====================\n\nThis app defines :class:`~gridplatform.datasources.models.DataSource` owned by\n:class:`~gridplatform.providers.models.Provider`\n(:class:`~gridplatform.provider_datasources.models.ProviderDataSource`) and\nshared among the :class:`~gridplatform.customers.models.Customer` of that\n:class:`~gridplatform.providers.models.Provider`.\n\n.. autoclass:: gridplatform.provider_datasources.models.ProviderDataSource\n\n.. autoclass:: gridplatform.provider_datasources.managers.ProviderDataSourceManager\n\n.. autoclass:: gridplatform.provider_datasources.managers.ProviderDataSourceManagerBase\n\n.. autoclass:: gridplatform.provider_datasources.managers.ProviderDataSourceQuerySetMixin\n :members: _apply_customer_filtering, _apply_provider_filtering\n" }, { "alpha_fraction": 0.6465082764625549, "alphanum_fraction": 0.6465082764625549, "avg_line_length": 32.878047943115234, "blob_id": "824abd0247ebcf620411bfdae0cf668f808835b1", "content_id": "154348033c82a5d8ffcae7f26d85dc46fd009f71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4167, "license_type": "no_license", "max_line_length": 81, "num_lines": 123, "path": "/gridplatform/encryption/base.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nimport threading\n\nfrom django.utils.importlib import import_module\n\nfrom gridplatform.trackuser import get_user\n\nfrom .conf import settings\n\n\n_store = threading.local()\n\n\n_cipher_modules = {}\n\n\ndef _get_cipher_module(import_path):\n \"\"\"\n Get cipher module from given path.\n\n :param import_path: The given path.\n \"\"\"\n if import_path not in _cipher_modules:\n _cipher_modules[import_path] = import_module(import_path)\n return _cipher_modules[import_path]\n\n\ndef get_cipher_module():\n \"\"\"\n Get cipher module from :data:`settings.ENCRYPTION_CIPHER_MODULE`.\n \"\"\"\n return _get_cipher_module(settings.ENCRYPTION_CIPHER_MODULE)\n\n\nclass MissingEncryptionKeyError(Exception):\n \"\"\"\n Exception raised when a requested encryption key is not found in the\n current encryption context.\n\n :see: :meth:`.EncryptionContext.get_cipher`.\n \"\"\"\n def __init__(self, cls, pk):\n super(MissingEncryptionKeyError, self).__init__(\n 'Missing encryption key: ({}, {})'.format(\n cls.__name__, pk))\n\n\nclass _CachedKeys(object):\n \"\"\"\n A single instance of _CachedKeys is attached to the\n :class:`.EncryptionContext` class --- rather than modify itself, it should\n override itself in specific instance dictionaries. \"attrname\" is the name\n it is attached with/the name to override.\n\n :note: Similar to something which could be implemented with\n ``@cached_property`` --- but that would not enable the current workaround\n for mutual recursion with get_user()...\n \"\"\"\n def __init__(self, attrname):\n self.attrname = attrname\n\n def __get__(self, instance, owner):\n # \"cache\" immediately --- avoid recursion on potentially attempting to\n # decrypt on loading user on get_user() ...\n setattr(instance, self.attrname, {})\n user = get_user()\n if user is not None and not user.is_authenticated():\n # in the process of logging in/loading session data; the empty\n # result should not be \"cached\"...\n delattr(instance, self.attrname)\n return {}\n private_key = getattr(\n _store, settings.ENCRYPTION_EPHEMERAL_STORE_KEY, None) or \\\n getattr(_store, settings.ENCRYPTION_STORE_KEY, None)\n if private_key is not None and user is not None and \\\n user.is_authenticated():\n keys = user.decrypt_keys(private_key)\n setattr(instance, self.attrname, keys)\n return keys\n else:\n return {}\n\n\nclass EncryptionContext(object):\n \"\"\"\n An encryption context holding keys for the user currently logged in.\n\n :ivar keys: A :class:`._CachedKeys` that per instance replaces itself with\n a dictionary mapping key ids to private keys entities that have\n entrusted these to the currently authenticated entity (the trusted\n entity, the user currently logged in).\n\n The trusted entity keeps private keys entrusted to it encrypted. So\n upon initial read from the keys property these entrusted private keys\n are decrypted using private key of trusted entity. Private key of\n entrusted entity is loaded from thread-local store using either\n :data:`settings.ENCRYPTION_EPHEMERAL_STORE_KEY` or\n :data:`settings.ENCRYPTION_STORE_KEY` as attribute name.\n \"\"\"\n keys = _CachedKeys('keys')\n\n @classmethod\n def generate_iv(cls):\n \"\"\"\n Generate a new encryption data initialization vector.\n \"\"\"\n cipher_module = get_cipher_module()\n return cipher_module.generate_iv()\n\n def get_cipher(self, key_id, iv):\n \"\"\"\n Get the cipher object (something that can encrypt and decrypt data) for\n given encryption key and encryption data initialization vector.\n\n :param key_id: The id of the given encryption key.\n \"\"\"\n try:\n key = self.keys[key_id]\n cipher_module = get_cipher_module()\n return cipher_module.symmetric_cipher(key, iv)\n except KeyError:\n raise MissingEncryptionKeyError(*key_id)\n" }, { "alpha_fraction": 0.648790717124939, "alphanum_fraction": 0.6498422622680664, "avg_line_length": 33.581817626953125, "blob_id": "e10ea85f18b71a3a2d3a912ed39da10669bfb485", "content_id": "6f0e25bd35cd94a25bed08c36efa6e4f39d67eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1902, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/gridplatform/trackuser/middleware.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils import timezone\n\nfrom gridplatform.customers.models import Customer\n\nfrom . import _store\nfrom . import get_customer\nfrom . import get_timezone\n\n\nclass TrackUserMiddleware(object):\n \"\"\"\n Middleware to keep track of the current user during processing of a\n request. Useful for making it available to model member methods; e.g::\n\n customer = models.ForeignKey(\n Customer, editable=False, default=trackuser.get_customer)\n\n However, for such uses see also :class:`EncryptionCustomerFieldMixin`.\n\n Also makes \"current customer\" available as property on request/session, and\n sets \"current timezone\" to the customer timezone.\n \"\"\"\n def process_request(self, request):\n user = request.user\n _store.user = user\n # NOTE: \"Log in as customer\" fearture; to be removed.\n override_customer_id = request.session.get('customer_id', None)\n if override_customer_id is not None:\n try:\n override_customer = Customer.objects.get(\n id=override_customer_id)\n except Customer.DoesNotExist:\n override_customer = None\n else:\n override_customer = None\n _store.override_customer = override_customer\n # NOTE: customer on request --- used in Portal 2 code; to be removed\n request.customer = get_customer()\n customer_timezone = get_timezone()\n if customer_timezone is not None:\n timezone.activate(customer_timezone)\n else:\n timezone.deactivate()\n return None\n\n def process_response(self, request, response):\n _store.user = None\n _store.override_customer = None\n _store.selected_customer = None\n timezone.deactivate()\n return response\n" }, { "alpha_fraction": 0.6940330266952515, "alphanum_fraction": 0.7003808617591858, "avg_line_length": 39.050846099853516, "blob_id": "13890d3b2ae9af3d3a50a658ab009d13beef946d", "content_id": "1d567abe96d6cc01a6a67a2691cbd15fcee0ae53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 78, "num_lines": 59, "path": "/gridplatform/datasources/test_datasourcemanager.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\n\nfrom .models import DataSource\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DataSourceManagerTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer1 = Customer.objects.create()\n self.customer2 = Customer.objects.create()\n self.user = User(customer=self.customer1)\n self.user.is_authenticated = lambda: True\n\n def test_customerdatasources_visible_to_console(self):\n datasource1 = CustomerDataSource.objects.create(\n customer=self.customer1,\n unit='milliwatt*hour')\n datasource2 = CustomerDataSource.objects.create(\n customer=self.customer2,\n unit='milliwatt*hour')\n\n self.assertTrue(DataSource.objects.filter(id=datasource1.id).exists())\n self.assertTrue(DataSource.objects.filter(id=datasource2.id).exists())\n\n def test_filtered_customerdatasource(self):\n datasource = CustomerDataSource.objects.create(\n customer=self.customer1,\n unit='milliwatt*hour')\n with replace_customer(self.customer1), replace_user(self.user):\n self.assertTrue(\n DataSource.objects.filter(id=datasource.id).exists())\n\n def test_excluded_customerdatasource(self):\n datasource = CustomerDataSource.objects.create(\n customer=self.customer2,\n unit='milliwatt*hour')\n with replace_customer(self.customer1), replace_user(self.user):\n self.assertFalse(\n DataSource.objects.filter(id=datasource.id).exists())\n\n def test_filtered_datasource(self):\n datasource = DataSource.objects.create(\n unit='milliwatt*hour')\n with replace_customer(self.customer1), replace_user(self.user):\n self.assertTrue(\n DataSource.objects.filter(id=datasource.id).exists())\n" }, { "alpha_fraction": 0.8560940027236938, "alphanum_fraction": 0.8564611077308655, "avg_line_length": 45.169490814208984, "blob_id": "e1533ecea603b3c701407a5ca236ebd5b430c336", "content_id": "82257c504bfd112fd11dd5a68ef06c9b59d703e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2724, "license_type": "no_license", "max_line_length": 92, "num_lines": 59, "path": "/legacy/manage_measurementpoints/forms/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .collection import CollectionForm\nfrom .consumption import ConsumptionMeasurementPointUpdateForm\nfrom .consumption import InputConsumptionMeasurementPointForm\nfrom .consumptionsummation import ConsumptionMeasurementPointSummationForm\nfrom .current import CurrentMeasurementPointForm\nfrom .current import InputCurrentMeasurementPointForm\nfrom .districtheatingform import DistrictHeatingMeasurementPointCreateForm\nfrom .districtheatingform import DistrictHeatingMeasurementPointEditForm\nfrom .multipliedconsumptionform import MultiplicationConsumptionMeasurementPointForm # noqa\nfrom .production import InputProductionMeasurementPointForm\nfrom .production import ProductionMeasurementPointForm\nfrom .tariff import TariffPeriodForm\nfrom .temperature import InputTemperatureMeasurementPointForm\nfrom .temperature import TemperatureMeasurementPointForm\nfrom .voltage import InputVoltageMeasurementPointForm\nfrom .voltage import VoltageMeasurementPointForm\nfrom .power import InputPowerMeasurementPointForm\nfrom .power import PowerMeasurementPointForm\nfrom .efficiency import EfficiencyMeasurementPointForm\nfrom .efficiency import InputEfficiencyMeasurementPointForm\nfrom .reactive_power import InputReactivePowerMeasurementPointForm\nfrom .reactive_power import ReactivePowerMeasurementPointForm\nfrom .reactive_energy import InputReactiveEnergyMeasurementPointForm\nfrom .reactive_energy import ReactiveEnergyMeasurementPointForm\nfrom .powerfactor import InputPowerFactorMeasurementPointForm\nfrom .powerfactor import PowerFactorMeasurementPointForm\n\n__all__ = [\n 'CollectionForm',\n 'ConsumptionMeasurementPointUpdateForm',\n 'InputConsumptionMeasurementPointForm',\n 'ConsumptionMeasurementPointSummationForm',\n 'MultiplicationConsumptionMeasurementPointForm',\n 'TariffPeriodForm',\n 'InputTemperatureMeasurementPointForm',\n 'TemperatureMeasurementPointForm',\n 'DistrictHeatingMeasurementPointCreateForm',\n 'DistrictHeatingMeasurementPointEditForm',\n 'ProductionMeasurementPointForm',\n 'InputProductionMeasurementPointForm',\n 'CurrentMeasurementPointForm',\n 'InputCurrentMeasurementPointForm',\n 'VoltageMeasurementPointForm',\n 'InputVoltageMeasurementPointForm',\n 'PowerMeasurementPointForm',\n 'InputPowerMeasurementPointForm',\n 'EfficiencyMeasurementPointForm',\n 'InputEfficiencyMeasurementPointForm',\n 'ReactivePowerMeasurementPointForm',\n 'InputReactivePowerMeasurementPointForm',\n 'ReactiveEnergyMeasurementPointForm',\n 'InputReactiveEnergyMeasurementPointForm',\n 'PowerFactorMeasurementPointForm',\n 'InputPowerFactorMeasurementPointForm',\n]\n" }, { "alpha_fraction": 0.6202531456947327, "alphanum_fraction": 0.621835470199585, "avg_line_length": 27.727272033691406, "blob_id": "d9ee689fc993be33d25ab61635a5b35ebf148164", "content_id": "a885619e24c24401ddca6edbfe5734dde2cfad23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 632, "license_type": "no_license", "max_line_length": 77, "num_lines": 22, "path": "/gridplatform/rest/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nclass NestedMixin(object):\n \"\"\"\n Mixin to be used by nested viewsets allowing them to simply overwrite\n :attr:`filter_by` to enable queryset filtering.\n\n :ivar filter_by: List of nesting parameter names used to filter queryset.\n \"\"\"\n filter_by = None\n\n def get_queryset(self):\n qs = super(NestedMixin, self).get_queryset()\n filters = {\n key: value\n for key, value in self.kwargs.items()\n if key in self.filter_by\n }\n return qs.filter(**filters)\n" }, { "alpha_fraction": 0.6775510311126709, "alphanum_fraction": 0.6778061389923096, "avg_line_length": 28.037036895751953, "blob_id": "7e9e4f7cfe1886d679a84f40cbe2d0c783cd7158", "content_id": "15037a4d15f573ed8e19a8775da30063fdff10c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3920, "license_type": "no_license", "max_line_length": 79, "num_lines": 135, "path": "/gridplatform/trackuser/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport functools\nfrom threading import local\n\n\n# Store members cannot be initialised statically as that would happen in one\n# thread, thus getattr is used below.\n_store = local()\n\n\ndef get_user():\n \"\"\"\n The currently logged-in user, tracked through middleware.\n \"\"\"\n return getattr(_store, 'user', None)\n\n\ndef _get_user_customer():\n \"\"\"\n The customer of the currently logged in user, if any. Used to filter data\n to only display what is related to this specific customer, and, where\n appliccable, as the default/selected customer on model object creation.\n Some models are entirely inaccessible when the user is associated with a\n customer.\n \"\"\"\n return getattr(get_user(), 'customer', None)\n\n\n# DEPRECATED\ndef _get_override_customer():\n \"\"\"\n Access is limited as if this was the customer of the current user (unless\n the user has an explicit customer; then that takes precedence). Used for\n the --- to be removed --- \"log in as customer\" feature.\n \"\"\"\n return getattr(_store, 'override_customer', None)\n\n\ndef _get_selected_customer():\n \"\"\"\n The \"active\" customer, selected on partner/provider parts of the\n GridPortal. Used to filter customer-related data and as the\n default/selected customer on model object creation. Unlike \"user\n customer\"/\"override customer\", the presence of a \"selected customer\" does\n not imply any filtering of the models *not* related to any customers.\n \"\"\"\n return getattr(_store, 'selected_customer', None)\n\n\ndef get_customer():\n \"\"\"\n The appropriate \"default\" customer for model object creation. A user with\n an associated customer is limited to only accessing that customer; override\n has a similar effect; and otherwise a selected customer is used.\n \"\"\"\n return _get_user_customer() or \\\n _get_override_customer() or \\\n _get_selected_customer()\n\n\ndef get_provider():\n \"\"\"\n The provider of the currently logged-in user. Requires that the user has\n permission to decrypt provider.\n \"\"\"\n return getattr(get_user(), 'provider', None) or \\\n getattr(get_customer(), 'provider', None)\n\n\ndef get_provider_id():\n \"\"\"\n The provider id of the currently logged-in user. Used to filter data\n associated with providers.\n \"\"\"\n return getattr(get_user(), 'provider_id', None) or \\\n getattr(get_customer(), 'provider_id', None)\n\n\ndef get_timezone():\n \"\"\"\n Get the timezone of the customer we are currently logged in as/working\n with.\n \"\"\"\n return getattr(get_customer(), 'timezone', None)\n\n\ndef get_current_date():\n \"\"\"\n Get the current date for the customer that we are currently logged in\n as/working with.\n \"\"\"\n customer = get_customer()\n if customer is not None:\n return customer.now().date()\n else:\n return None\n\n\n# DEPRECATED\ndef _set_user(user):\n # assert getattr(settings, 'TRACKUSER_TESTMODE', False)\n _store.user = user\n\n\n# DEPRECATED\ndef _set_customer(customer):\n # assert getattr(settings, 'TRACKUSER_TESTMODE', False)\n _store.override_customer = customer\n\n\nclass _StoreOverride(object):\n def __init__(self, replacement, attr=None):\n self.attr = attr\n self.replacement = replacement\n self.old = None\n\n def __enter__(self):\n self.old = getattr(_store, self.attr, None)\n setattr(_store, self.attr, self.replacement)\n\n def __exit__(self, exc_type, exc_value, traceback):\n setattr(_store, self.attr, self.old)\n\n\nreplace_user = functools.partial(_StoreOverride, attr='user')\nreplace_override_customer = functools.partial(\n _StoreOverride, attr='override_customer')\nreplace_selected_customer = functools.partial(\n _StoreOverride, attr='selected_customer')\n\n# DEPRECATED?\nreplace_customer = replace_override_customer\n" }, { "alpha_fraction": 0.6379807591438293, "alphanum_fraction": 0.6394230723381042, "avg_line_length": 36.818180084228516, "blob_id": "78981df8d802b69564df0893efa29b43bfaca32d", "content_id": "511785ab3e5990121a9cdf211f6841533552599b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2080, "license_type": "no_license", "max_line_length": 72, "num_lines": 55, "path": "/legacy/manage_reports/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import StartGraphdataDownloadView\nfrom .views import FinalizeGraphdataDownloadView\nfrom legacy.enpi_reports.views import CreateENPIReportView\nfrom legacy.enpi_reports.views import UpdateENPIReportView\n\n\nurlpatterns = patterns(\n 'legacy.manage_reports.views',\n url(r'^$', 'index',\n name='manage_reports-index'),\n url(r'^create/consumption/$', 'create_consumption_report',\n name='manage_reports-create_consumption_report'),\n url(r'^create/energy_use/(?P<utility_type>\\w+)/$',\n 'create_energy_use_report',\n name='manage_reports-create_energy_use_report'),\n url(r'^update/energy_use/(?P<pk>\\d+)/$', 'update_energy_use_report',\n name='manage_reports-update_energy_use_report'),\n url(r'^delete/$',\n 'delete',\n name='manage_reports-delete'),\n url(r'^request/$',\n 'request_consumption_report',\n name='manage_reports-request_consumption_report'),\n url(r'^finalize/$',\n 'finalize_consumption_report',\n name='manage_reports-finalize_consumption_report'),\n url(r'^(?P<pdf_id>\\d+)/(?P<title>.+)\\.pdf$',\n 'serve_pdf',\n name='manage_reports-serve_pdf'),\n url(r'^(?P<csv_id>\\d+)/(?P<title>.+)\\.csv$',\n 'serve_csv',\n name='manage_reports-serve_csv'),\n url(r'^request_export/$',\n StartGraphdataDownloadView.as_view(),\n name='manage_reports-startgraphdatadownload'),\n url(r'^finalize_export/$',\n FinalizeGraphdataDownloadView.as_view(),\n name='manage_reports-finalizegraphdatadownload'),\n\n url(r'^enpi/new/(?P<energy_driver_unit>[-a-z0-9_^*]+)$',\n CreateENPIReportView.as_view(),\n name='manage_reports-create_enpi_report_form'),\n url(r'^enpi/(?P<pk>\\d+)/$',\n UpdateENPIReportView.as_view(),\n name='manage_reports-update_enpi_report_form'),\n url(r'^enpi/delete/$',\n 'enpi_delete',\n name='manage_reports-enpi-delete'),\n)\n" }, { "alpha_fraction": 0.5885336399078369, "alphanum_fraction": 0.615161657333374, "avg_line_length": 36.94158172607422, "blob_id": "a1704a74931e4fbd7de5372c5dcbd4cddfa9fc14", "content_id": "24e2bee16d1740e9c55f516725a609ce16be8603", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11041, "license_type": "no_license", "max_line_length": 77, "num_lines": 291, "path": "/gridplatform/co2conversions/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nimport pytz\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.consumptions.models import MainConsumption\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_CHOICES\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .models import Co2Conversion\nfrom .models import DynamicCo2Conversion\nfrom .models import FixedCo2Conversion\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass Co2ConversionManagerTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n def test_value_sequence_no_conversions(self):\n result = list(\n self.mainconsumption.co2conversion_set.value_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n self.assertEqual(result, [])\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass Co2ConversionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n def test_unicode_pure_virtual(self):\n with self.assertRaises(NotImplementedError):\n unicode(\n Co2Conversion(\n mainconsumption=self.mainconsumption,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2))))\n\n def test_value_sequence_pure_virtual(self):\n conversion = Co2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n with self.assertRaises(NotImplementedError):\n list(\n conversion._value_sequence(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2))))\n\n def test_clean_blank(self):\n conversion = Co2Conversion(\n mainconsumption=self.mainconsumption)\n conversion.clean()\n\n def test_clean_detects_overlaps(self):\n Co2Conversion.objects.create(\n mainconsumption=self.mainconsumption,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2000, 1, 1)))\n\n conversion = Co2Conversion(\n mainconsumption=self.mainconsumption,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n\n with self.assertRaises(ValidationError):\n conversion.clean()\n\n def test_clean_detects_from_timestamp_invalid_resolution(self):\n conversion = Co2Conversion(\n mainconsumption=self.mainconsumption,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1, 1, 1)))\n\n with self.assertRaises(ValidationError) as e:\n conversion.clean()\n\n self.assertIn('from_timestamp', e.exception.message_dict)\n\n def test_clean_detects_to_timestamp_invalid_resolution(self):\n conversion = Co2Conversion(\n mainconsumption=self.mainconsumption,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2, 1, 1)))\n\n with self.assertRaises(ValidationError) as e:\n conversion.clean()\n\n self.assertIn('to_timestamp', e.exception.message_dict)\n\n\nclass DataSourceMock(DataSource):\n class Meta:\n proxy = True\n\n def __unicode__(self):\n return 'DATASOURCEMOCK'\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DynamicCo2ConversionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n self.datasource = DataSourceMock.objects.create(\n unit='gram*kilowatt^-1*hour^-1')\n\n def test_unicode(self):\n conversion = DynamicCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n datasource=self.datasource)\n self.assertIn('DATASOURCEMOCK', unicode(conversion))\n\n def test_clean_happy(self):\n conversion = DynamicCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n datasource=self.datasource)\n conversion.clean()\n\n def test_clean_detects_bad_unit(self):\n self.datasource.unit = 'gram*liter^-1'\n conversion = DynamicCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n datasource=self.datasource)\n with self.assertRaises(ValidationError) as e:\n conversion.clean()\n\n self.assertIn('datasource', e.exception.message_dict)\n\n def test_value_sequence_empty(self):\n DynamicCo2Conversion.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n datasource=self.datasource)\n self.assertEqual(\n [],\n list(\n self.mainconsumption.co2conversion_set.value_sequence(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)))))\n\n def test_value_sequence(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n self.datasource.rawdata_set.bulk_create(\n [\n RawData(\n datasource=self.datasource,\n timestamp=from_timestamp + datetime.timedelta(\n minutes=5 * i),\n value=i % 20)\n for i in range(12 * 60 / 5)])\n\n DynamicCo2Conversion.objects.create(\n from_timestamp=from_timestamp,\n mainconsumption=self.mainconsumption,\n datasource=self.datasource)\n\n self.assertEqual(\n [\n RangedSample(\n from_timestamp + datetime.timedelta(minutes=5 * i),\n from_timestamp + datetime.timedelta(minutes=5 * (i + 1)),\n PhysicalQuantity(i % 20, self.datasource.unit))\n for i in range(12 * 60 / 5)],\n list(\n self.mainconsumption.co2conversion_set.value_sequence(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)))))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass FixedCo2ConversionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.mainconsumption = MainConsumption.objects.create(\n customer=self.customer,\n utility_type=ENERGY_UTILITY_TYPE_CHOICES.electricity,\n from_date=datetime.date(2014, 1, 1))\n\n self.datasource = DataSource.objects.create(\n unit='gram*kilowatt^-1*hour^-1')\n\n def test_unicode(self):\n conversion = FixedCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n value='123.456',\n unit='gram*kilowatt^-1*hour^-1')\n unicode(conversion)\n\n def test_clean_happy(self):\n conversion = FixedCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n value='123.456',\n unit='gram*kilowatt^-1*hour^-1')\n conversion.clean()\n\n def test_clean_detects_bad_unit(self):\n conversion = FixedCo2Conversion(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n mainconsumption=self.mainconsumption,\n value='123.456',\n unit='gram*liter^-1')\n\n with self.assertRaises(ValidationError) as e:\n conversion.clean()\n\n self.assertIn('unit', e.exception.message_dict)\n\n def test_value_sequence(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n\n FixedCo2Conversion.objects.create(\n from_timestamp=from_timestamp,\n mainconsumption=self.mainconsumption,\n value='123.456',\n unit='gram*kilowatt^-1*hour^-1')\n\n self.assertEqual(\n [\n RangedSample(\n from_timestamp + datetime.timedelta(minutes=5 * i),\n from_timestamp + datetime.timedelta(minutes=5 * (i + 1)),\n PhysicalQuantity('123.456', 'gram*kilowatt^-1*hour^-1'))\n for i in range(24 * 60 / 5)],\n list(\n self.mainconsumption.co2conversion_set.value_sequence(\n self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n self.timezone.localize(\n datetime.datetime(2014, 1, 2)))))\n" }, { "alpha_fraction": 0.8506410121917725, "alphanum_fraction": 0.8512820601463318, "avg_line_length": 42.33333206176758, "blob_id": "03f0cd93ad1e069a068c84b5ffeb981073b86379", "content_id": "bdad811a96de25dee2867bac2e4b4a5e575b82d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1560, "license_type": "no_license", "max_line_length": 94, "num_lines": 36, "path": "/legacy/measurementpoints/proxies/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .consumptionmeasurementpoint import ConsumptionMeasurementPoint\nfrom .importedmeasurementpoint import ImportedMeasurementPoint\nfrom .consumptionmeasurementpointsummation import ConsumptionMeasurementPointSummation # noqa\nfrom .consumptionmultiplicationpoint import ConsumptionMultiplicationPoint\nfrom .districtheatingmeasurementpoint import DistrictHeatingMeasurementPoint\nfrom .measurementpoint import MeasurementPoint\nfrom .temperaturemeasurementpoint import TemperatureMeasurementPoint\nfrom .productionmeasurementpoint import ProductionMeasurementPoint\nfrom .currentmeasurementpoint import CurrentMeasurementPoint\nfrom .voltagemeasurementpoint import VoltageMeasurementPoint\nfrom .powermeasurementpoint import PowerMeasurementPoint\nfrom .reactivepowermeasurementpoint import ReactivePowerMeasurementPoint\nfrom .reactiveenergymeasurementpoint import ReactiveEnergyMeasurementPoint\nfrom .powerfactormeasurementpoint import PowerFactorMeasurementPoint\n\n\n__all__ = [\n 'ConsumptionMeasurementPoint',\n 'ConsumptionMeasurementPointSummation',\n 'ConsumptionMultiplicationPoint',\n 'DistrictHeatingMeasurementPoint',\n 'ImportedMeasurementPoint',\n 'MeasurementPoint',\n 'TemperatureMeasurementPoint',\n 'ProductionMeasurementPoint',\n 'CurrentMeasurementPoint',\n 'VoltageMeasurementPoint',\n 'PowerMeasurementPoint',\n 'ReactivePowerMeasurementPoint',\n 'ReactiveEnergyMeasurementPoint',\n 'PowerFactorMeasurementPoint',\n]\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6856368780136108, "avg_line_length": 27.384614944458008, "blob_id": "87874ebab837cf65402f530c892d5731eda13d38", "content_id": "037194e8c78a651db924d79a654aaffa27f484e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 62, "num_lines": 13, "path": "/energymanager/start_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom energymanager.start_site import views\n\nurlpatterns = patterns(\n 'legacy.website.views',\n url(r'^login/$', views.LoginView.as_view(), name='login'),\n url(r'^apps/$', views.AppsView.as_view(), name='apps'),\n)\n" }, { "alpha_fraction": 0.6907073259353638, "alphanum_fraction": 0.6911696791648865, "avg_line_length": 33.8870964050293, "blob_id": "552cefa5d0e607a4ad11f341a7f16e8f2ce0c408", "content_id": "1ef4aa0acb9dbff88b4d5c65bc475aaf85766aae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2163, "license_type": "no_license", "max_line_length": 81, "num_lines": 62, "path": "/legacy/manage_measurementpoints/forms/current.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import CurrentMeasurementPoint\nfrom legacy.measurementpoints.models import Collection\n\nfrom .measurementpointform import MeasurementPointForm\n\nfrom gridplatform.datasequences.models import NonaccumulationDataSequence # noqa\n\n\nclass CurrentMeasurementPointForm(MeasurementPointForm):\n \"\"\"\n A C{CurrentMeasurementPointForm} sets properties on a\n L{CurrentMeasurementPoint} that can be both set when creating and when\n updating.\n \"\"\"\n class Meta:\n model = CurrentMeasurementPoint\n fields = ('name', 'parent',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(CurrentMeasurementPointForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n def _get_edit_headline_display(self):\n return _(u'Edit Current Measurement Point')\n\n\nclass InputCurrentMeasurementPointForm(CurrentMeasurementPointForm):\n \"\"\"\n An C{InputCurrentMeasurementPointForm} is a\n L{CurrentMeasurementPointForm}, that in addition also sets properties\n that can only be set when creating a L{CurrentMeasurementPointForm}.\n \"\"\"\n input_configuration = forms.ModelChoiceField(\n required=True,\n queryset=NonaccumulationDataSequence.objects.none())\n\n class ProxyMeta:\n fields = ('input_configuration', )\n\n def __init__(self, *args, **kwargs):\n super(InputCurrentMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['input_configuration'].queryset = \\\n CurrentMeasurementPoint.get_input_configuration_choices()\n\n def _get_new_headline_display(self):\n return _(u'New Current Measurement Point')\n" }, { "alpha_fraction": 0.6495327353477478, "alphanum_fraction": 0.6498075723648071, "avg_line_length": 31.7747745513916, "blob_id": "266e110c312898480694eaafae06526c6ce19355", "content_id": "917413977c067aec5bfe2c00670f760067b342a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3638, "license_type": "no_license", "max_line_length": 79, "num_lines": 111, "path": "/legacy/measurementpoints/proxies/currentmeasurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.measurementpoints.models import Link\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\n\nfrom .measurementpoint import MeasurementPoint\n\n\nclass CurrentMeasurementPoint(MeasurementPoint):\n \"\"\"\n A C{CurrentMeasurementPoint} is a L{MeasurementPoint} that measures\n current.\n \"\"\"\n class Meta:\n proxy = True\n verbose_name = _('Current measurement point')\n verbose_name_plural = _('Current measurement points')\n app_label = 'customers'\n\n def __init__(self, *args, **kwargs):\n super(CurrentMeasurementPoint, self).__init__(*args, **kwargs)\n if self.utility_type is None:\n self.utility_type = utilitytypes.OPTIONAL_METER_CHOICES.electricity\n\n if self.role is None:\n self.role = self.MEASUREMENT_POINT_CURRENT\n\n def save(self, *args, **kwargs):\n super(CurrentMeasurementPoint, self).save(*args, **kwargs)\n assert self.input_configuration\n\n graph, created = Graph.objects.get_or_create(\n collection=self,\n role=DataRoleField.CURRENT)\n if created:\n Link.objects.create(\n customer=self.customer,\n graph=graph,\n role=DataRoleField.CURRENT,\n unit='milliampere',\n utility_type=self.utility_type,\n target=self._input_configuration)\n\n def _get_input_configuration(self):\n self._input_configuration = getattr(self, '_input_configuration', None)\n if self.id and not self._input_configuration:\n self._input_configuration = \\\n NonaccumulationAdapter.objects.get(\n link_derivative_set__graph__collection=self.id)\n return self._input_configuration\n\n def _set_input_configuration(self, input_configuration):\n self._input_configuration = input_configuration\n\n input_configuration = property(\n _get_input_configuration, _set_input_configuration)\n\n def get_delete_prevention_reason(self, return_dependents_only=False):\n \"\"\"\n Returns a HTML formated string with a description of why\n this current measurement point cannot be deleted.\n Returning None, if no reason exist, meaning the MP can\n be deleted without breaking anything.\n\n @param return_dependents_only: If true, only return a string of\n the units that depends on this resource.\n \"\"\"\n return None\n\n def is_deletable(self):\n \"\"\"\n Returns true or false whether\n this current measurement point can be deleted or not.\n \"\"\"\n return True\n\n def get_gauge_data_series(self):\n \"\"\"\n C{CurrentMeasurementPoint} implementation of\n L{MeasurementPoint.get_gauge_data_series()}\n \"\"\"\n return self.input_configuration\n\n @property\n def has_consumption(self):\n return False\n\n @property\n def has_gauge(self):\n return False\n\n @property\n def has_rate(self):\n return True\n\n @staticmethod\n def get_input_configuration_choices():\n \"\"\"\n Get L{NonaccumulationAdapter} choices.\n \"\"\"\n return NonaccumulationAdapter.objects.filter(\n unit='milliampere',\n customer=trackuser.get_customer())\n" }, { "alpha_fraction": 0.6406944990158081, "alphanum_fraction": 0.645056426525116, "avg_line_length": 32.694522857666016, "blob_id": "2e6781ae7178515006a6a0916224bc8a30748bbd", "content_id": "a87c1e64a1a32cc68b4cd487e12ed7e00f067cdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11692, "license_type": "no_license", "max_line_length": 79, "num_lines": 347, "path": "/legacy/display_measurementpoints/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django import forms\nfrom django.http import HttpResponseNotFound\nfrom django.http import Http404\nfrom django.shortcuts import get_object_or_404\nfrom django.template.defaultfilters import floatformat\nfrom django.utils import translation\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.decorators.http import require_POST\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import DataSeries\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.users.decorators import auth_or_error, auth_or_redirect\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.views import render_to, json_response\nfrom gridplatform.utils import condense\nfrom legacy.display_widgets.models import DashboardWidget\nfrom legacy.manage_collections.models import CollectionItem\nfrom gridplatform.reports.consumption import consumption_csv\n\n\nfrom .tasks import graph_task\n\n\naccumulation_types = {\n DataSeries.PIECEWISE_CONSTANT_ACCUMULATION,\n DataSeries.CONTINUOUS_ACCUMULATION\n}\n\nrate_types = {\n DataSeries.PIECEWISE_CONSTANT_RATE,\n DataSeries.CONTINUOUS_RATE\n}\n\n\nclass PeriodForm(forms.Form):\n from_date = forms.DateTimeField()\n to_date = forms.DateTimeField()\n months_limit = None\n\n BAR_MINUTE_CURVE_RAW = datetime.timedelta(hours=1)\n BAR_HOURS_CURVE_RAW = datetime.timedelta(days=7)\n BAR_DAYS_CURVE_HOURS = datetime.timedelta(days=180)\n\n def __init__(self, *args, **kwargs):\n self.months_limit = kwargs.pop('months_limit', self.months_limit)\n super(PeriodForm, self).__init__(*args, **kwargs)\n\n def clean(self):\n cleaned_data = super(PeriodForm, self).clean()\n from_date = cleaned_data.get('from_date')\n to_date = cleaned_data.get('to_date')\n\n if from_date and to_date:\n if from_date >= to_date:\n raise forms.ValidationError(\n _('From date must be before to date'))\n\n if self.months_limit:\n date_span = RelativeTimeDelta(to_date, from_date)\n if date_span.months >= self.months_limit:\n raise forms.ValidationError(\n _('The selection has exceeded the limit '\n 'of {limit} months').format(limit=self.months_limit))\n if to_date - from_date < datetime.timedelta(minutes=59):\n raise forms.ValidationError(\n _('Selection is too small. It must be at least one hour.'))\n return cleaned_data\n\n def get_period(self):\n assert self.is_valid()\n from_timestamp = self.cleaned_data['from_date']\n to_timestamp = self.cleaned_data['to_date'] + \\\n datetime.timedelta(minutes=1)\n\n duration = to_timestamp - from_timestamp\n if duration <= self.BAR_MINUTE_CURVE_RAW:\n from_timestamp, to_timestamp = self.normalize_range(\n from_timestamp, to_timestamp, RelativeTimeDelta(minutes=1))\n elif duration < self.BAR_HOURS_CURVE_RAW:\n from_timestamp, to_timestamp = self.normalize_range(\n from_timestamp, to_timestamp, RelativeTimeDelta(hours=1))\n elif duration < self.BAR_DAYS_CURVE_HOURS:\n from_timestamp, to_timestamp = self.normalize_range(\n from_timestamp, to_timestamp, RelativeTimeDelta(days=1))\n else:\n from_timestamp, to_timestamp = self.normalize_range(\n from_timestamp, to_timestamp, RelativeTimeDelta(months=1))\n\n return from_timestamp, to_timestamp\n\n def normalize_range(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Normalize a datetime range against a relative time delta.\n \"\"\"\n timezone = get_customer().timezone\n rounded_from_time = condense.floor(\n from_timestamp, resolution, timezone)\n rounded_to_time = condense.floor(to_timestamp, resolution, timezone)\n if rounded_to_time < to_timestamp:\n rounded_to_time = rounded_to_time + resolution\n return (rounded_from_time, rounded_to_time)\n\n\n@auth_or_redirect\n@render_to('display_measurementpoints/index.html')\ndef index(request):\n customer = request.customer\n\n root_groups = get_user().userprofile.collections.all()\n if not root_groups:\n root_groups = Collection.objects.root_nodes().filter(customer=customer)\n\n groups = [group.get_descendants(include_self=True)\n .exclude(hidden_on_details_page=True)\n for group in root_groups]\n return {\n 'groups': groups,\n }\n\n\n@auth_or_redirect\n@render_to('display_measurementpoints/group_detail.html')\ndef group(request, pk):\n period_form = PeriodForm(request.GET)\n customer = get_customer()\n if not period_form.is_valid():\n from_timestamp = condense.floor(\n customer.now(), RelativeTimeDelta(days=1),\n customer.timezone)\n to_timestamp = from_timestamp + RelativeTimeDelta(days=1)\n else:\n from_timestamp, to_timestamp = period_form.get_period()\n\n if 'from_date' in request.GET:\n from_datetime = request.GET['from_date']\n to_datetime = request.GET['to_date']\n else:\n from_datetime = None\n to_datetime = None\n\n customer = request.customer\n\n root_groups = get_user().userprofile.collections.all()\n if root_groups:\n # if user is bound to groups, use those\n groups = [group.get_descendants(include_self=True)\n .exclude(hidden_on_details_page=True)\n for group in root_groups]\n else:\n # otherwise, show all groups for customer\n groups = [Collection.objects.filter(customer=customer)\n .exclude(hidden_on_details_page=True)]\n\n group_list = [c for grouptree in groups\n for c in grouptree if c.id == int(pk)]\n if group_list != []:\n group = group_list[0]\n else:\n return HttpResponseNotFound()\n\n if group.role in Collection.MEASUREMENT_POINTS:\n group = group.subclass_instance\n\n graphs = list(group.graph_set.filter(hidden=False))\n if to_timestamp - from_timestamp > datetime.timedelta(days=31, hours=1):\n for graph in graphs:\n if graph.role in DataSeries.CONTINUOUS_RATE_ROLES:\n graph.HIDE_HACK = True\n\n floorplan_items = []\n\n # You can only have one floorplan per collection\n floorplan = group.get_floorplan()\n if floorplan:\n floorplan_items = [\n item.subclass_instance for item in floorplan.item_set.all()]\n\n main_graph = None\n if len(graphs) > 0:\n main_graph = graphs.pop(0)\n\n widgets = DashboardWidget.objects.filter(\n collection=group, user=get_user())\n\n is_group = False\n if group.role == group.GROUP:\n is_group = True\n\n return {\n 'from_timestamp': from_timestamp,\n 'to_timestamp': to_timestamp,\n 'group': group,\n 'widgets': widgets,\n 'relay': group.relay,\n 'groups': groups,\n 'graphs': graphs,\n 'main_graph': main_graph,\n 'period_form': period_form,\n 'floorplan': floorplan,\n 'placed_items': floorplan_items,\n 'is_group': is_group,\n 'from_date': from_timestamp.strftime('%Y-%m-%d'),\n 'to_date': to_timestamp.strftime('%Y-%m-%d'),\n 'from_datetime': from_datetime,\n 'to_datetime': to_datetime,\n }\n\n\n@auth_or_redirect\n@render_to('display_measurementpoints/fullscreen_floorplan.html')\ndef fullscreen_floorplan(request, pk):\n customer = request.customer\n\n root_groups = get_user().userprofile.collections.all()\n if root_groups:\n # if user is bound to groups, use those\n groups = [group.get_descendants(include_self=True)\n .exclude(hidden_on_details_page=True)\n for group in root_groups]\n else:\n # otherwise, show all groups for customer\n groups = [Collection.objects.filter(customer=customer)\n .exclude(hidden_on_details_page=True)]\n\n group_list = [c for grouptree in groups\n for c in grouptree if c.id == int(pk)]\n if group_list != []:\n group = group_list[0]\n else:\n return HttpResponseNotFound()\n\n if group.role in Collection.MEASUREMENT_POINTS:\n group = group.subclass_instance\n\n floorplan_items = []\n\n # You can only have one floorplan per collection\n floorplan = group.get_floorplan()\n if floorplan:\n floorplan_items = [\n item.subclass_instance for item in floorplan.item_set.all()]\n\n return {\n 'group': group,\n 'floorplan': floorplan,\n 'placed_collections': floorplan_items,\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef async_graph(request, pk):\n period_form = PeriodForm(request.POST)\n customer = get_customer()\n if not period_form.is_valid():\n from_timestamp = condense.floor(\n customer.now().replace(minute=0, second=0, microsecond=0),\n RelativeTimeDelta(days=1),\n customer.timezone)\n to_timestamp = from_timestamp + RelativeTimeDelta(days=1)\n else:\n from_timestamp, to_timestamp = period_form.get_period()\n from_timestamp = condense.floor(\n from_timestamp, RelativeTimeDelta(hours=1), customer.timezone)\n to_timestamp = condense.ceil(\n to_timestamp, RelativeTimeDelta(hours=1), customer.timezone)\n customer = request.customer\n\n current_language = translation.get_language()\n async = graph_task.delay(\n pk, from_timestamp, to_timestamp, current_language)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef async_graph_last_24h(request, pk):\n if not get_customer():\n raise Http404\n\n to_timestamp = condense.floor(\n request.customer.now() + RelativeTimeDelta(hours=1),\n RelativeTimeDelta(hours=1),\n request.customer.timezone)\n from_timestamp = to_timestamp - RelativeTimeDelta(hours=24)\n\n current_language = translation.get_language()\n async = graph_task.delay(\n pk, from_timestamp, to_timestamp, current_language, 5)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\n@auth_or_error\n@json_response\ndef floorplan_values(request, pk):\n customer = request.customer\n items = CollectionItem.objects.filter(\n floorplan__collection_id=pk,\n floorplan__collection__customer=customer)\n values = {}\n for item in items:\n last_rate = item.collection.subclass_instance.get_last_rate()\n if last_rate:\n values.update({item.id: [floatformat(float(last_rate[0]), 1),\n unicode(last_rate[1])]})\n else:\n values.update({item.id: None})\n\n return values\n\n\ndef _parse_date(datestring, tzinfo):\n return tzinfo.normalize(datetime.datetime.strptime(\n datestring, '%Y-%m-%d').replace(tzinfo=tzinfo))\n\n\n@auth_or_error\ndef export_csv(request, from_date, to_date, name, pk=None):\n customer = get_customer()\n tz = customer.timezone\n\n from_date = _parse_date(from_date, tz)\n to_date = _parse_date(to_date, tz)\n\n if pk is not None:\n collection = get_object_or_404(Collection, customer=customer, pk=pk)\n collections = collection.get_descendants(include_self=True)\n else:\n collections = Collection.objects.filter(customer=customer)\n\n return consumption_csv(collections, from_date, to_date)\n" }, { "alpha_fraction": 0.5658826231956482, "alphanum_fraction": 0.5892451405525208, "avg_line_length": 37.44160461425781, "blob_id": "a4d4ae657fb0453987d9ed5b5e8dbd3a37ab82c5", "content_id": "7a1c0c022b3550093480895b214531f715275ae8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 100720, "license_type": "no_license", "max_line_length": 79, "num_lines": 2620, "path": "/legacy/measurementpoints/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime, timedelta\nfrom fractions import Fraction\nimport functools\nimport itertools\nimport operator\nimport unittest\n\nfrom mock import Mock\nfrom mock import patch\nimport pytz\n\nfrom django.core.exceptions import ValidationError\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django import forms\nfrom django.db.models import ProtectedError\n\nfrom gridplatform import trackuser\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.testutils import encryption_context\nfrom gridplatform.encryption.testutils import no_encryption\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.iter_ext import count_extended\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom .fields import DataRoleField\nfrom .interpolationcloud import InterpolationCloud\nfrom .models import AbstractGraph\nfrom .models import Chain\nfrom .models import Co2Calculation\nfrom .models import CostCalculation\nfrom .models import DataSeries\nfrom .models import DegreeDayCorrection\nfrom .models import HeatingDegreeDays\nfrom .models import IndexCalculation\nfrom .models import Location\nfrom .models import Multiplication\nfrom .models import PiecewiseConstantIntegral\nfrom .models import RateConversion\nfrom .models import SimpleLinearRegression\nfrom .models import Summation\nfrom .models import Utilization\nfrom .models.dataseries import UndefinedSamples\nfrom .models.mixins import CacheOptimizedCalculateDevelopmentMixin\nfrom .models.mixins import VariablyBoundAccumulationMixin\nfrom .proxies import ConsumptionMeasurementPoint\nfrom .proxies import ConsumptionMeasurementPointSummation\nfrom .proxies import ImportedMeasurementPoint\nfrom .tasks import get_condensed_samples_task\nfrom .tasks import get_samples_task\n\n\nclass TestDataSeries(DataSeries):\n \"\"\"\n Simplest concrete implementation of the abstract L{DataSeries} class.\n \"\"\"\n\n def get_recursive_condense_resolution(self, resolution):\n \"\"\"\n Unless recursive condension is the particular subject to test, it is\n disabled during unit-testsing.\n \"\"\"\n return None\n\n def calculate_development(self, from_timestamp, to_timestamp):\n assert self.is_accumulation()\n\n try:\n from_sample = next(iter(\n self.get_samples(from_timestamp, from_timestamp)))\n to_sample = next(iter(\n self.get_samples(to_timestamp, to_timestamp)))\n\n return self.create_range_sample(\n from_timestamp, to_timestamp,\n to_sample.physical_quantity - from_sample.physical_quantity,\n uncachable=(\n from_sample.uncachable or\n to_sample.uncachable),\n extrapolated=(\n from_sample.extrapolated or\n to_sample.extrapolated))\n except StopIteration:\n return None\n\n\nclass DataSeriesMock(TestDataSeries):\n def depends_on(self):\n if hasattr(self, 'depends_on_list'):\n return self.depends_on_list\n else:\n return []\n\n def _get_samples(self, from_timestamp, to_timestamp):\n if not hasattr(self, 'raw_data_samples'):\n self.raw_data_samples = []\n for s in self.raw_data_samples:\n if from_timestamp <= s.from_timestamp <= s.to_timestamp <= \\\n to_timestamp:\n yield s\n\n\nclass DataSeriesTestSpecification(object):\n \"\"\"\n A C{DataSeriesTestSpecification} is a mixin for C{TestCase}s that test\n C{DataSeries}. It defines abstract test methods which should be\n implemented for all L{DataSeries} specializations.\n \"\"\"\n\n def test_depends_on(self):\n raise NotImplementedError()\n\n def test_get_samples(self):\n raise NotImplementedError()\n\n def test_get_underlying_function(self):\n raise NotImplementedError()\n\n def test_calculate_development(self):\n raise NotImplementedError()\n\n\nclass ENPIMixinTestSpecification(DataSeriesTestSpecification):\n \"\"\"\n A C{ENPIMixinTestSpecification} is a L{DataSeriesTestSpecification} for\n L{DataSeries} that are mixed with the L{ENPIMixin}.\n \"\"\"\n\n def test_calculate_enpi(self):\n raise NotImplementedError()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ChainTest(TestCase):\n \"\"\"\n Test the L{Chain} data series.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n self.customer.electricity_consumption = \"kilowatt*hour\"\n self.customer.timezone = pytz.utc\n\n self.tariff = Chain.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.subtariff1 = TestDataSeries.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.subtariff2 = TestDataSeries.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*gigajoule^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.start_time = datetime(2013, 1, 1, tzinfo=pytz.utc)\n\n self.period1 = self.tariff.links.create(\n valid_from=self.start_time + timedelta(hours=12),\n data_series=self.subtariff1)\n\n self.period2 = self.tariff.links.create(\n valid_from=self.start_time + timedelta(hours=24),\n data_series=self.subtariff2)\n\n self.subtariff1.stored_data.create(\n timestamp=self.start_time,\n value=1)\n self.subtariff1.stored_data.create(\n timestamp=self.start_time + timedelta(hours=8),\n value=2)\n self.subtariff1.stored_data.create(\n timestamp=self.start_time + timedelta(hours=16),\n value=3)\n self.subtariff2.stored_data.create(\n timestamp=self.start_time + timedelta(hours=8),\n value=4)\n self.subtariff2.stored_data.create(\n timestamp=self.start_time + timedelta(hours=20),\n value=5)\n\n self.consumption = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.consumption.stored_data.create(\n value=0, timestamp=self.start_time)\n self.consumption.stored_data.create(\n value=100, timestamp=self.start_time + timedelta(hours=48))\n\n self.cost = CostCalculation.objects.create(\n customer=self.customer,\n role=DataRoleField.COST,\n unit='currency_dkk',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n consumption=self.consumption,\n tariff=self.tariff)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_get_samples(self):\n \"\"\"\n Test L{DerivedDataSeries.get_samples()} with formula\n DerivedDataSeries.SIMPLE_JOIN.\n\n @see: L{setUp()}\n \"\"\"\n samples_iterator = iter(\n self.tariff.get_samples(\n self.start_time,\n to_timestamp=self.start_time + timedelta(hours=48)))\n\n self.assertEqual(\n next(samples_iterator),\n self.tariff.create_range_sample(\n self.start_time + timedelta(hours=12),\n self.start_time + timedelta(hours=16),\n PhysicalQuantity(2, self.subtariff1.unit)))\n\n self.assertEqual(\n next(samples_iterator),\n self.tariff.create_range_sample(\n self.start_time + timedelta(hours=16),\n self.start_time + timedelta(hours=24),\n PhysicalQuantity(3, self.subtariff1.unit)))\n\n self.assertEqual(\n next(samples_iterator),\n self.tariff.create_range_sample(\n self.start_time + timedelta(hours=24),\n self.start_time + timedelta(hours=48),\n PhysicalQuantity(5, self.subtariff2.unit)))\n\n\nclass DataRoleFieldTest(TestCase):\n \"\"\"\n Tests for L{DataRoleField}.\n \"\"\"\n\n def test_choices(self):\n \"\"\"\n Test that noone mistakenly assigned the same number to two different\n roles.\n \"\"\"\n self.assertEqual(\n len(DataRoleField.CHOICES),\n len(dict(DataRoleField.CHOICES)))\n\n\nclass CostCalculationTest(TestCase):\n \"\"\"\n Test of L{CostCalculation} delegate class.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.unit = CostCalculation(\n customer=self.customer,\n role=DataRoleField.COST,\n unit='millicurrency_dkk',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n consumption=TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity),\n tariff=TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='millicurrency_dkk*watt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity))\n self.unit.save()\n\n self.start_time = datetime(2013, 1, 1, tzinfo=pytz.utc)\n\n def test_index_extrapolation(self):\n self.unit._get_accumulation_samples = Mock(\n return_value=[\n self.unit.consumption.create_point_sample(\n self.start_time,\n PhysicalQuantity(0, self.unit.consumption.unit)),\n self.unit.consumption.create_point_sample(\n self.start_time + timedelta(hours=1),\n PhysicalQuantity(10, self.unit.consumption.unit)),\n self.unit.consumption.create_point_sample(\n self.start_time + timedelta(hours=2),\n PhysicalQuantity(0, self.unit.consumption.unit)),\n ])\n\n self.unit._get_rate_samples = Mock(\n return_value=[\n self.unit.tariff.create_range_sample(\n self.start_time, self.start_time + timedelta(hours=1),\n PhysicalQuantity(1, self.unit.tariff.unit))])\n\n result = list(\n self.unit.get_samples(\n self.start_time, self.start_time + timedelta(hours=2)))\n self.assertEqual(\n result,\n [\n self.unit.create_point_sample(\n self.start_time,\n PhysicalQuantity(0, self.unit.unit)),\n self.unit.create_point_sample(\n self.start_time + timedelta(hours=1),\n (\n PhysicalQuantity(10, self.unit.consumption.unit) *\n PhysicalQuantity(1, self.unit.tariff.unit))),\n self.unit.create_point_sample(\n self.start_time + timedelta(hours=2),\n (\n PhysicalQuantity(10, self.unit.consumption.unit) *\n PhysicalQuantity(1, self.unit.tariff.unit)),\n uncachable=True, extrapolated=True)])\n\n def test_calculate_development(self):\n for i in range(11):\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(hours=i),\n value=i)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time,\n value=7919)\n\n result = self.unit.calculate_development(\n self.start_time, self.start_time + timedelta(hours=10))\n\n expected_result = self.unit.create_range_sample(\n self.start_time,\n self.start_time + timedelta(hours=10),\n PhysicalQuantity(1, 'milliwatt*hour') * 10 *\n PhysicalQuantity(7919, 'millicurrency_dkk*watt^-1*hour^-1'),\n uncachable=True, extrapolated=False)\n\n self.assertEqual(result, expected_result)\n\n @unittest.skip('Condensed values are currently not extrapolated')\n def test_extrapolated_condensed(self):\n \"\"\"\n Test cost calculation across an interval without consumption values at\n the end-point, and single tariff value covering same interval.\n \"\"\"\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time,\n value=2)\n\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(hours=1),\n value=3)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time,\n value=7919)\n\n condensed_cost_samples = iter(\n self.unit.get_condensed_samples(\n self.start_time,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.start_time + timedelta(hours=2)))\n\n sample = next(condensed_cost_samples)\n self.assertTrue(sample.is_range)\n self.assertEqual(sample.from_timestamp, self.start_time)\n self.assertEqual(\n sample.to_timestamp, self.start_time + timedelta(hours=1))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity('7.919', 'millicurrency_dkk'))\n\n sample = next(condensed_cost_samples)\n self.assertTrue(sample.is_range)\n self.assertEqual(sample.from_timestamp,\n self.start_time + timedelta(hours=1))\n self.assertEqual(sample.to_timestamp,\n self.start_time + timedelta(hours=2))\n self.assertEqual(\n sample.physical_quantity, PhysicalQuantity(0, 'millicurrency_dkk'))\n\n with self.assertRaises(StopIteration):\n next(condensed_cost_samples)\n\n def test_alternation_condensed(self):\n \"\"\"\n Test condensation where raw samples alternate between the timestamps of\n both tariff and consumption.\n \"\"\"\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time,\n value=2)\n\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=30),\n value=3)\n\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(hours=1, minutes=2),\n value=5)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time - timedelta(hours=1),\n value=7919)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time + timedelta(hours=1),\n value=3019)\n\n condensed_cost_samples = iter(\n self.unit.get_condensed_samples(\n self.start_time,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.start_time + timedelta(hours=2)))\n\n sample = next(condensed_cost_samples)\n self.assertTrue(sample.is_range)\n self.assertEqual(sample.from_timestamp, self.start_time)\n self.assertEqual(\n sample.to_timestamp, self.start_time + timedelta(hours=1))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity('7.919', 'millicurrency_dkk') *\n (1 + Fraction(2 * 30, 32)))\n\n sample = next(condensed_cost_samples)\n self.assertTrue(sample.is_range)\n self.assertEqual(\n sample.from_timestamp, self.start_time + timedelta(hours=1))\n self.assertEqual(\n sample.to_timestamp, self.start_time + timedelta(hours=2))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity('3.019', 'millicurrency_dkk') *\n 2 * Fraction(2, 32))\n\n with self.assertRaises(StopIteration):\n next(condensed_cost_samples)\n\n def test_alternation_raw(self):\n \"\"\"\n Test raw samples alternating between the timestamps of both tariff and\n consumption.\n \"\"\"\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time,\n value=2)\n\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=30),\n value=3)\n\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(hours=1),\n value=5)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time - timedelta(minutes=42),\n value=7919)\n\n self.unit.tariff.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=45),\n value=3019)\n\n raw_cost_samples = iter(\n self.unit.get_samples(\n self.start_time,\n self.start_time + timedelta(hours=1)))\n\n sample = next(raw_cost_samples)\n self.assertTrue(sample.is_point)\n self.assertEqual(sample.timestamp, self.start_time)\n self.assertEqual(\n sample.physical_quantity, PhysicalQuantity(0, 'currency_dkk'))\n\n sample = next(raw_cost_samples)\n self.assertTrue(sample.is_point)\n self.assertEqual(sample.timestamp,\n self.start_time + timedelta(minutes=45))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity('7.919', 'millicurrency_dkk') * 2)\n\n sample = next(raw_cost_samples)\n self.assertTrue(sample.is_point)\n self.assertEqual(sample.timestamp,\n self.start_time + timedelta(hours=1))\n self.assertAlmostEqual(\n sample.physical_quantity,\n PhysicalQuantity('7.919', 'millicurrency_dkk') * 2 +\n PhysicalQuantity('3.019', 'millicurrency_dkk'))\n\n with self.assertRaises(StopIteration):\n next(raw_cost_samples)\n\n\nclass InterpolationCloudTest(TestCase):\n \"\"\"\n Test the L{InterpolationCloud} class.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n self.from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.to_timestamp = datetime(2013, 1, 2, tzinfo=pytz.utc)\n\n self.data_series1 = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.data_series2 = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='joule',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n def test_no_samples(self):\n \"\"\"\n Test that an interpolation cloud spanning no samples, yields two empty\n sample vectors.\n \"\"\"\n interpolation_cloud = InterpolationCloud(\n [self.data_series1, self.data_series2],\n self.from_timestamp,\n self.to_timestamp)\n\n self.assertEqual(list(interpolation_cloud), [[None, None],\n [None, None]])\n\n def test_plenty_of_samples(self):\n \"\"\"\n Test that an interpolation cloud spanning plenty of sample, yields the\n correct interpolated samples.\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n\n self.data_series2.stored_data.create(\n value=17,\n timestamp=self.from_timestamp - timedelta(hours=2))\n self.data_series2.stored_data.create(\n value=19,\n timestamp=self.from_timestamp + timedelta(hours=9))\n self.data_series2.stored_data.create(\n value=23,\n timestamp=self.from_timestamp + timedelta(hours=20))\n self.data_series2.stored_data.create(\n value=29,\n timestamp=self.from_timestamp + timedelta(hours=24))\n\n interpolation_cloud = InterpolationCloud(\n [self.data_series1, self.data_series2],\n self.from_timestamp,\n self.to_timestamp)\n\n self.assertEqual(\n list(interpolation_cloud),\n\n [\n [\n self.data_series1.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(\n Fraction(7 * 5 + 4, 5), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(Fraction(17 * 11 + 4, 11), 'joule'))],\n\n [\n self.data_series1.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(11, 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(\n Fraction(17 * 11 + 12, 11), 'joule'))],\n\n [\n self.data_series1.create_point_sample(\n self.from_timestamp + timedelta(hours=9),\n PhysicalQuantity(\n Fraction(11 * 13 + 5, 13), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp + timedelta(hours=9),\n PhysicalQuantity(19, 'joule'))],\n\n [\n self.data_series1.create_point_sample(\n self.from_timestamp + timedelta(hours=20),\n PhysicalQuantity(\n Fraction(11 * 13 + 16, 13), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp + timedelta(hours=20),\n PhysicalQuantity(23, 'joule'))],\n\n [\n self.data_series1.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(\n Fraction(11 * 13 + 20, 13), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(29, 'joule'))]])\n\n def test_plenty_of_samples_and_no_samples(self):\n \"\"\"\n Test that an interpolation cloud spanning plenty of samples of one data\n series and no samples of another, yields the correct interpolated\n samples.\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n\n interpolation_cloud = InterpolationCloud(\n [self.data_series1, self.data_series2],\n self.from_timestamp,\n self.to_timestamp)\n\n self.assertEqual(\n list(interpolation_cloud),\n\n [\n [\n self.data_series1.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(\n Fraction(7 * 5 + 4, 5), 'milliwatt*hour')),\n None],\n\n [\n self.data_series1.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(11, 'milliwatt*hour')),\n None],\n\n [\n self.data_series1.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(\n Fraction(11 * 13 + 20, 13),\n 'milliwatt*hour')),\n None]])\n\n def test_plenty_of_samples_and_extrapolated_samples(self):\n \"\"\"\n Test that an interpolation cloud spanning plenty of samples for one\n data series and only extrapolated samples of another, yields the\n correct interpolated samples.\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n self.data_series2.stored_data.create(\n value=17,\n timestamp=self.from_timestamp - timedelta(hours=2))\n\n interpolation_cloud = InterpolationCloud(\n [self.data_series1, self.data_series2],\n self.from_timestamp,\n self.to_timestamp)\n\n result = list(interpolation_cloud)\n\n expected_result = [\n [\n self.data_series1.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(\n Fraction(7 * 5 + 4, 5), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(17, 'joule'),\n uncachable=True,\n extrapolated=True)],\n\n [\n self.data_series1.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(11, 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(17, 'joule'),\n uncachable=True,\n extrapolated=True)],\n\n [\n self.data_series1.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(\n Fraction(11 * 13 + 20, 13), 'milliwatt*hour')),\n self.data_series2.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(17, 'joule'),\n uncachable=True,\n extrapolated=True)]]\n\n self.assertEqual(result, expected_result)\n\n\nclass SummationTest(TestCase):\n \"\"\"\n Test the L{Summation} model.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n self.from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.to_timestamp = datetime(2013, 1, 2, tzinfo=pytz.utc)\n\n self.data_series1 = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.data_series2 = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='joule',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.summation = Summation.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='newton*foot',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n plus_data_series=[self.data_series1],\n minus_data_series=[self.data_series2])\n\n def test_empty_summation_get_samples(self):\n summation = Summation.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='newton*foot',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n result = list(\n summation.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n expected_result = []\n\n self.assertEqual(result, expected_result)\n\n def test_reload(self):\n \"\"\"\n Test reloading, i.e. that a Summation define the same sum before and\n after it was stored.\n \"\"\"\n reloaded_summation = Summation.objects.get(id=self.summation.id)\n self.assertEqual(\n self.summation.plus_data_series,\n reloaded_summation.plus_data_series)\n\n self.assertEqual(\n self.summation.minus_data_series,\n reloaded_summation.minus_data_series)\n\n def test_no_samples(self):\n \"\"\"\n Test summation across two data series without any samples at all.\n \"\"\"\n result = list(\n self.summation.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n expected_result = []\n\n self.assertEqual(result, expected_result)\n\n self.assertFalse(\n self.summation.calculate_development(\n self.from_timestamp, self.to_timestamp))\n\n self.assertEqual(\n list(\n self.summation.get_condensed_samples(\n self.from_timestamp,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.to_timestamp)),\n [])\n\n def test_plenty_of_samples(self):\n \"\"\"\n Test summation across two data series with plenty of samples\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n\n self.data_series2.stored_data.create(\n value=17,\n timestamp=self.from_timestamp - timedelta(hours=2))\n self.data_series2.stored_data.create(\n value=19,\n timestamp=self.from_timestamp + timedelta(hours=9))\n self.data_series2.stored_data.create(\n value=23,\n timestamp=self.from_timestamp + timedelta(hours=20))\n self.data_series2.stored_data.create(\n value=29,\n timestamp=self.from_timestamp + timedelta(hours=24))\n\n result = list(\n self.summation.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n expected_result = [\n self.summation.create_point_sample(\n self.from_timestamp,\n (PhysicalQuantity(7 + Fraction(11 - 7, 5), 'milliwatt*hour') -\n PhysicalQuantity(17 + Fraction((19 - 17) * 2, 11), 'joule'))),\n self.summation.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n (PhysicalQuantity(Fraction(11), 'milliwatt*hour') -\n PhysicalQuantity(17 + Fraction((19 - 17) * 6, 11), 'joule'))),\n self.summation.create_point_sample(\n self.from_timestamp + timedelta(hours=9),\n (PhysicalQuantity(11 + Fraction((13 - 11) * 5, 26),\n 'milliwatt*hour') -\n PhysicalQuantity(Fraction(19), 'joule'))),\n self.summation.create_point_sample(\n self.from_timestamp + timedelta(hours=20),\n (PhysicalQuantity(11 + Fraction((13 - 11) * 16, 26),\n 'milliwatt*hour') -\n PhysicalQuantity(Fraction(23), 'joule'))),\n self.summation.create_point_sample(\n self.to_timestamp,\n (PhysicalQuantity(11 + Fraction((13 - 11) * 20, 26),\n 'milliwatt*hour') -\n PhysicalQuantity(Fraction(29), 'joule')))]\n\n self.assertEqual(result, expected_result)\n\n self.assertEqual(\n self.summation.calculate_development(\n self.from_timestamp, self.to_timestamp),\n self.summation.create_range_sample(\n self.from_timestamp, self.to_timestamp,\n (expected_result[-1].physical_quantity -\n expected_result[0].physical_quantity)))\n\n self.assertEqual(\n list(\n self.summation.get_condensed_samples(\n self.from_timestamp,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.to_timestamp)),\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(37100, 4191), self.summation.unit))\n for i in range(0, 4)\n ] +\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(17000, 54483), self.summation.unit))\n for i in range(4, 9)\n ] +\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(-15500, 54483), self.summation.unit))\n for i in range(9, 20)\n ] +\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(-6625, 1651), self.summation.unit))\n for i in range(20, 24)\n ])\n\n @unittest.skip(\n '... mismatch on cachable/extrapolated; '\n 'we do not really track those anymore')\n def test_plenty_of_samples_and_no_samples(self):\n \"\"\"\n Test summation across two data series; one with plenty of samples, one\n without any samples\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n\n result = list(\n self.summation.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n expected_result = [\n self.summation.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(\n 7 + Fraction(11 - 7, 5), 'milliwatt*hour'),\n uncachable=True, extrapolated=True),\n self.summation.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n PhysicalQuantity(\n Fraction(11), 'milliwatt*hour'),\n uncachable=True, extrapolated=True),\n self.summation.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(\n 11 + Fraction((13 - 11) * 20, 26), 'milliwatt*hour'),\n uncachable=True, extrapolated=True)]\n\n self.assertEqual(result, expected_result)\n\n self.assertEqual(\n self.summation.calculate_development(\n self.from_timestamp, self.to_timestamp),\n self.summation.create_range_sample(\n self.from_timestamp, self.to_timestamp,\n (expected_result[-1].physical_quantity -\n expected_result[0].physical_quantity),\n uncachable=True, extrapolated=True))\n\n self.assertEqual(\n list(\n self.summation.get_condensed_samples(\n self.from_timestamp,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.to_timestamp)),\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(Fraction(1200, 127), self.summation.unit),\n uncachable=True, extrapolated=True) for i in range(0, 4)] +\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(1500, 1651), self.summation.unit),\n uncachable=True, extrapolated=True) for i in range(4, 24)])\n\n def test_plenty_of_samples_and_extrapolation(self):\n \"\"\"\n Test summation across two data series; one with plenty of samples, and\n one only with samples outside the given range.\n \"\"\"\n self.data_series1.stored_data.create(\n value=7,\n timestamp=self.from_timestamp - timedelta(hours=1))\n self.data_series1.stored_data.create(\n value=11,\n timestamp=self.from_timestamp + timedelta(hours=4))\n self.data_series1.stored_data.create(\n value=13,\n timestamp=self.from_timestamp + timedelta(hours=30))\n\n self.data_series2.stored_data.create(\n value=17,\n timestamp=self.from_timestamp - timedelta(hours=2))\n\n result = list(self.summation.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n expected_result = [\n self.summation.create_point_sample(\n self.from_timestamp,\n (PhysicalQuantity(\n 7 + Fraction(11 - 7, 5), 'milliwatt*hour') -\n PhysicalQuantity(17, 'joule')),\n uncachable=True, extrapolated=True),\n self.summation.create_point_sample(\n self.from_timestamp + timedelta(hours=4),\n (PhysicalQuantity(\n Fraction(11), 'milliwatt*hour') -\n PhysicalQuantity(17, 'joule')),\n uncachable=True, extrapolated=True),\n self.summation.create_point_sample(\n self.to_timestamp,\n (PhysicalQuantity(\n 11 + Fraction((13 - 11) * 20, 26), 'milliwatt*hour') -\n PhysicalQuantity(\n Fraction(17), 'joule')),\n uncachable=True, extrapolated=True)]\n\n self.assertEqual(result, expected_result)\n\n self.assertEqual(\n self.summation.calculate_development(\n self.from_timestamp, self.to_timestamp),\n self.summation.create_range_sample(\n self.from_timestamp, self.to_timestamp,\n (expected_result[-1].physical_quantity -\n expected_result[0].physical_quantity),\n uncachable=True, extrapolated=True))\n\n self.assertEqual(\n list(\n self.summation.get_condensed_samples(\n self.from_timestamp,\n RelativeTimeDelta(hours=1),\n to_timestamp=self.to_timestamp)),\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(Fraction(1200, 127), self.summation.unit),\n uncachable=True, extrapolated=True) for i in range(0, 4)] +\n [\n self.summation.create_range_sample(\n self.from_timestamp + timedelta(hours=i),\n self.from_timestamp + timedelta(hours=i + 1),\n PhysicalQuantity(\n Fraction(1500, 1651), self.summation.unit),\n uncachable=True, extrapolated=True) for i in range(4, 24)])\n\n def test_data_series_dependencies(self):\n \"\"\"\n Test that summation depends on data_series1 and data_series2\n \"\"\"\n self.assertEqual(self.summation.depends_on(),\n [self.data_series1, self.data_series2])\n\n\nclass MultiplicationTest(TestCase):\n \"\"\"\n Test the L{Multiplication} model.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n self.unit = Multiplication.objects.create(\n customer=customer,\n role=DataRoleField.CONSUMPTION,\n unit='meter^3',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water,\n multiplier='123.456',\n source_data_series=TestDataSeries.objects.create(\n customer=customer,\n role=DataRoleField.CONSUMPTION,\n unit='liter',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water))\n self.from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.to_timestamp = self.from_timestamp + timedelta(days=1)\n\n self.unit.source_data_series.stored_data.create(\n value=5,\n timestamp=self.from_timestamp - timedelta(minutes=10))\n self.unit.source_data_series.stored_data.create(\n value=7,\n timestamp=self.from_timestamp + timedelta(minutes=20))\n\n def test_get_raw_data_series(self):\n \"\"\"\n Test L{Multiplication.get_raw_data_series()}\n \"\"\"\n self.assertEqual(\n list(\n self.unit.get_samples(self.from_timestamp, self.to_timestamp)),\n [\n self.unit.create_point_sample(\n self.from_timestamp,\n PhysicalQuantity(\n (5 + Fraction(2, 3)) * Fraction('123.456') *\n Fraction(1, 1000),\n 'meter^3')),\n self.unit.create_point_sample(\n self.from_timestamp + timedelta(minutes=20),\n PhysicalQuantity(\n 7 * Fraction('123.456') *\n Fraction(1, 1000),\n 'meter^3')),\n self.unit.create_point_sample(\n self.to_timestamp,\n PhysicalQuantity(\n 7 * Fraction('123.456') *\n Fraction(1, 1000),\n 'meter^3'),\n uncachable=True,\n extrapolated=True)])\n\n def test_depends_on(self):\n \"\"\"\n Test L{Multiplication.depends_on()}\n \"\"\"\n self.assertEqual(\n self.unit.depends_on(),\n [self.unit.source_data_series])\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass HeatingDegreeDaysTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.temperature = TestDataSeries.objects.create(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n\n self.from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.to_timestamp = self.from_timestamp + timedelta(days=7)\n\n self.celsius_base = PhysicalQuantity('273.15', 'kelvin')\n\n for n in range(5):\n self.temperature.stored_data.create(\n value=(\n (\n self.celsius_base +\n PhysicalQuantity(15, 'kelvin'))\n .convert(self.temperature.unit)),\n timestamp=self.from_timestamp + timedelta(days=n) -\n timedelta(hours=1))\n self.temperature.stored_data.create(\n value=(\n (\n self.celsius_base +\n PhysicalQuantity(15, 'kelvin')).\n convert(self.temperature.unit)),\n timestamp=self.from_timestamp + timedelta(days=n) +\n timedelta(hours=1))\n self.temperature.stored_data.create(\n value=(self.celsius_base + PhysicalQuantity(15, 'kelvin')).convert(\n self.temperature.unit),\n timestamp=self.from_timestamp + timedelta(days=5))\n for n in range(6, 8):\n self.temperature.stored_data.create(\n value=(\n (\n self.celsius_base +\n PhysicalQuantity(17, 'kelvin')).\n convert(self.temperature.unit)),\n timestamp=self.from_timestamp + timedelta(days=n))\n\n self.heatingdegreedays = HeatingDegreeDays.objects.create(\n derived_from=self.temperature,\n role=DataRoleField.HEATING_DEGREE_DAYS,\n unit='kelvin*day',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_get_samples(self):\n val = list(\n self.heatingdegreedays.get_samples(\n self.from_timestamp - timedelta(days=1),\n self.to_timestamp + timedelta(days=1)))\n physical_quantities = map(\n operator.attrgetter('physical_quantity'), val)\n\n degree_day_unit = functools.partial(\n PhysicalQuantity, unit='kelvin*day')\n expected = map(degree_day_unit, [0, 0, 2, 4, 6, 8, 10, 11, 11, 11])\n\n self.assertListEqual(\n expected,\n physical_quantities)\n\n def test_calculate_development(self):\n actual = self.heatingdegreedays.calculate_development(\n self.from_timestamp, self.to_timestamp)\n expected = self.heatingdegreedays.create_range_sample(\n self.from_timestamp, self.to_timestamp,\n PhysicalQuantity(11, 'kelvin*day'))\n\n self.assertEqual(expected, actual)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DegreeDayCorrectionTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.consumption = TestDataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='watt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.degreedays = TestDataSeries.objects.create(\n role=DataRoleField.HEATING_DEGREE_DAYS,\n unit='kelvin*day',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n\n self.standarddegreedays = TestDataSeries.objects.create(\n role=DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n unit='kelvin*day',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n\n self.degreedaycorrection = DegreeDayCorrection.objects.create(\n consumption=self.consumption,\n degreedays=self.degreedays,\n standarddegreedays=self.standarddegreedays,\n role=DataRoleField.CONSUMPTION,\n unit='watt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.to_timestamp = datetime(2013, 2, 1, tzinfo=pytz.utc)\n\n self.days = list(itertools.takewhile(\n lambda t: t <= self.to_timestamp,\n count_extended(self.from_timestamp, timedelta(days=1))))\n\n for n, day in itertools.izip(itertools.count(), self.days):\n self.consumption.stored_data.create(\n value=1000 * n,\n timestamp=day)\n self.standarddegreedays.stored_data.create(\n value=1 * n,\n timestamp=day)\n self.degreedays.stored_data.create(\n value=2 * n,\n timestamp=day)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_get_samples(self):\n with self.assertRaises(NotImplementedError):\n list(\n self.degreedaycorrection.get_samples(\n self.from_timestamp, self.to_timestamp))\n\n def test_calculate_development(self):\n actual = self.degreedaycorrection.calculate_development(\n self.from_timestamp, self.to_timestamp)\n expected = self.degreedaycorrection.create_range_sample(\n self.from_timestamp, self.to_timestamp,\n PhysicalQuantity(31000 / 2, 'watt*hour'))\n self.assertEqual(actual, expected)\n\n def test_get_condensed(self):\n actual = list(self.degreedaycorrection.get_condensed_samples(\n from_timestamp=self.from_timestamp, to_timestamp=self.to_timestamp,\n sample_resolution=RelativeTimeDelta(days=1)))\n expected = [\n self.degreedaycorrection.create_range_sample(\n start, end, PhysicalQuantity(1000 / 2, 'watt*hour'))\n for start, end in pairwise(self.days)]\n self.assertListEqual(actual, expected)\n\n\nclass UtilizationTest(TestCase, ENPIMixinTestSpecification):\n \"\"\"\n Test the L{Utilization} data series model.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.consumption = DataSeriesMock.objects.create(\n role=DataRoleField.CONSUMPTION,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating,\n unit='milliwatt*hour')\n self.needs = DataSeriesMock.objects.create(\n role=DataRoleField.EMPLOYEES,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='person')\n self.utilization = Utilization.objects.create(\n role=DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n consumption=self.consumption,\n needs=self.needs,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating,\n unit='milliwatt*hour*person^-1*hour^-1')\n\n self.consumption.domain = (\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 3, tzinfo=pytz.utc))\n\n self.consumption.raw_data_samples = [\n self.consumption.create_point_sample(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n PhysicalQuantity(5, self.consumption.unit)),\n self.consumption.create_point_sample(\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n PhysicalQuantity(7, self.consumption.unit)),\n self.consumption.create_point_sample(\n datetime(2013, 1, 3, tzinfo=pytz.utc),\n PhysicalQuantity(11, self.consumption.unit)),\n self.consumption.create_point_sample(\n datetime(2013, 1, 4, tzinfo=pytz.utc),\n PhysicalQuantity(11, self.consumption.unit),\n uncachable=True,\n extrapolated=True)]\n\n self.needs.domain = (\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc))\n\n self.needs.raw_data_samples = [\n self.needs.create_range_sample(\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n datetime(2013, 1, 3, tzinfo=pytz.utc),\n PhysicalQuantity(5, self.needs.unit)),\n self.needs.create_range_sample(\n datetime(2013, 1, 3, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc),\n PhysicalQuantity(5, self.needs.unit)),\n ]\n\n def test_depends_on(self):\n consumption = TestDataSeries.objects.create(\n unit='kilowatt*hour',\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n role=DataRoleField.CONSUMPTION)\n needs = TestDataSeries.objects.create(\n unit='person',\n customer=self.customer,\n role=DataRoleField.EMPLOYEES,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n utilization = Utilization.objects.create(\n consumption=consumption,\n needs=needs,\n unit='kilowatt*person^-1',\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n role=DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES)\n self.assertIn(consumption, utilization.depends_on())\n self.assertIn(needs, utilization.depends_on())\n self.assertIn(self.consumption, self.utilization.depends_on())\n self.assertIn(self.needs, self.utilization.depends_on())\n\n def test_get_samples(self):\n with self.assertRaises(UndefinedSamples):\n list(\n self.utilization.get_samples(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc)))\n\n def test_get_condensed_samples(self):\n self.assertEqual(\n list(\n self.utilization.get_condensed_samples(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n condense.DAYS,\n datetime(2013, 1, 4, tzinfo=pytz.utc))),\n [\n self.utilization.create_range_sample(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n PhysicalQuantity(6, self.consumption.unit) / (\n PhysicalQuantity(5, self.needs.unit) *\n PhysicalQuantity(1, 'day')),\n uncachable=False,\n extrapolated=False),\n self.utilization.create_range_sample(\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n datetime(2013, 1, 3, tzinfo=pytz.utc),\n PhysicalQuantity(6, self.consumption.unit) / (\n PhysicalQuantity(5, self.needs.unit) *\n PhysicalQuantity(1, 'day')),\n uncachable=False,\n extrapolated=False),\n self.utilization.create_range_sample(\n datetime(2013, 1, 3, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc),\n PhysicalQuantity(0, self.consumption.unit) / (\n PhysicalQuantity(5, self.needs.unit) *\n PhysicalQuantity(1, 'day')),\n uncachable=True,\n extrapolated=True),\n ]\n )\n\n def test_get_underlying_function(self):\n self.assertEqual(\n self.utilization.get_underlying_function(),\n DataSeries.INTERVAL_FUNCTION)\n\n def test_calculate_development(self):\n with self.assertRaises(AssertionError):\n self.utilization.calculate_development(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 2, tzinfo=pytz.utc))\n\n def test_delete(self):\n self.consumption.delete()\n\n def test_calculate_enpi(self):\n self.assertEqual(\n self.utilization.calculate_enpi(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc)),\n self.utilization.create_range_sample(\n datetime(2013, 1, 1, tzinfo=pytz.utc),\n datetime(2013, 1, 4, tzinfo=pytz.utc),\n physical_quantity=(\n PhysicalQuantity(6, self.consumption.unit) / (\n PhysicalQuantity(5, self.needs.unit) *\n PhysicalQuantity(2, 'day'))),\n uncachable=True,\n extrapolated=True))\n\n\nclass VariablyBoundAccumulation(VariablyBoundAccumulationMixin,\n TestDataSeries):\n pass\n\n\nclass VariablyBoundAccumulationMixinTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n self.unit = VariablyBoundAccumulation(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='watt',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n )\n self.unit.save()\n self.start_time = datetime(2013, 1, 1, 2, 3, 4, tzinfo=pytz.utc)\n\n def test_calculate_development(self):\n for i in range(121):\n self.unit.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=i),\n value=i)\n result = self.unit.calculate_development(\n self.start_time,\n self.start_time + timedelta(minutes=120))\n result_x = self.unit.calculate_development(\n self.start_time,\n self.start_time + timedelta(minutes=120))\n\n expected = self.unit.create_range_sample(\n self.start_time,\n self.start_time + timedelta(minutes=120),\n PhysicalQuantity(120, 'watt'))\n self.assertEqual(expected, result)\n self.assertEqual(result, result_x)\n\n\nclass CacheOptimizedCalculateDevelopment(\n CacheOptimizedCalculateDevelopmentMixin, TestDataSeries):\n pass\n\n\nclass CacheOptimizedCalculateDevelopmentMixinTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n self.unit = CacheOptimizedCalculateDevelopment(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='watt',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n )\n self.unit.save()\n self.start_time = datetime(2013, 1, 1, 2, 3, 4, tzinfo=pytz.utc)\n\n def test_calculate_development(self):\n for i in range(121):\n self.unit.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=i),\n value=i)\n result = self.unit.calculate_development(\n self.start_time,\n self.start_time + timedelta(minutes=120))\n result_x = self.unit.calculate_development(\n self.start_time,\n self.start_time + timedelta(minutes=120))\n\n expected = self.unit.create_range_sample(\n self.start_time,\n self.start_time + timedelta(minutes=120),\n PhysicalQuantity(120, 'watt'))\n self.assertEqual(expected, result)\n self.assertEqual(result, result_x)\n\n\nclass RateConversionTest(TestCase):\n \"\"\"\n Test the L{RateConversion} model.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_aggregated_samples_one_measurement_no_crash(self):\n \"\"\"\n When creating a new measurement point with a gauge widget, chances were\n that we would have an assertion error in\n L{DataSeries.aggregated_samples}, once only a single measurement would\n be available.\n\n The details involve the domain of a rate conversion being inherited\n directly from its consumption data series. This is not entirely\n true. No rate can be defined at points that are not accumulation points\n in the consumption domain.\n \"\"\"\n derived_rate = RateConversion.objects.create(\n role=DataRoleField.POWER,\n unit=\"milliwatt\",\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n consumption=TestDataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit=\"milliwatt*hour\",\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity))\n\n derived_rate.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, 0, 3, tzinfo=pytz.utc))\n\n list(derived_rate.aggregated_samples(\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc),\n datetime(2013, 1, 1, 0, 15, tzinfo=pytz.utc)))\n\n\nclass AbstractGraphTest(TestCase):\n \"\"\"\n Unit tests for the L{AbstractGraph} class.\n \"\"\"\n def test_get_graph_data(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n data_series = TestDataSeries.objects.create(\n customer=customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n graph = AbstractGraph()\n\n with patch.object(AbstractGraph,\n '_get_data_series',\n return_value=[data_series]):\n graph.get_graph_data(\n 12, datetime(2013, 1, 1, tzinfo=pytz.utc),\n num_samples=12,\n sample_resolution=RelativeTimeDelta(months=1),\n to_timestamp=datetime(2014, 1, 1, tzinfo=pytz.utc))\n\n\nclass SimpleLinearRegressionTest(DataSeriesTestSpecification, TestCase):\n def setUp(self):\n super(SimpleLinearRegressionTest, self).setUp()\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n self.start_time = self.customer.timezone.localize(datetime(2013, 1, 1))\n self.end_time = self.customer.timezone.localize(datetime(2013, 1, 2))\n self.consumption = TestDataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n unit='milliwatt*hour',\n customer=self.customer)\n\n # create stored data s.t. all hours have a consumption of 1 kWh\n self.consumption.stored_data.create(\n timestamp=self.start_time, value=0)\n self.consumption.stored_data.create(\n timestamp=self.end_time, value=24000000)\n\n self.simple_linear_regression = SimpleLinearRegression(\n data=self.consumption)\n self.simple_linear_regression.full_clean()\n self.simple_linear_regression.save()\n\n def test_calculate_development(self):\n with self.assertRaises(AssertionError):\n self.simple_linear_regression.calculate_development(\n self.start_time,\n self.end_time)\n\n def test_depends_on(self):\n with patch.object(self.consumption, 'depends_on',\n return_value=[]) as mock:\n self.assertIn(\n self.consumption, self.simple_linear_regression.depends_on())\n\n mock.assertCalledWith()\n\n def test_get_samples(self):\n with self.assertRaises(UndefinedSamples):\n list(\n self.simple_linear_regression.get_samples(\n self.start_time,\n self.end_time))\n\n def test_get_underlying_function(self):\n self.assertEqual(\n self.simple_linear_regression.get_underlying_function(),\n DataSeries.CONTINUOUS_RATE)\n\n def test_get_condensed_samples(self):\n samples = list(\n self.simple_linear_regression.get_condensed_samples(\n self.start_time,\n condense.HOURS,\n self.end_time))\n\n self.assertEqual(\n samples[0],\n self.simple_linear_regression.create_point_sample(\n self.start_time,\n PhysicalQuantity(1, 'kilowatt*hour'),\n uncachable=True))\n\n self.assertEqual(\n samples[-1],\n self.simple_linear_regression.create_point_sample(\n self.end_time,\n PhysicalQuantity(1, 'kilowatt*hour'),\n uncachable=True))\n\n\nclass PiecewiseConstantIntegralTest(DataSeriesTestSpecification, TestCase):\n def setUp(self):\n super(PiecewiseConstantIntegralTest, self).setUp()\n Provider.objects.create()\n self.customer = Customer(timezone=pytz.utc)\n self.customer.save()\n self.start_time = self.customer.timezone.localize(datetime(2013, 1, 1))\n self.end_time = self.customer.timezone.localize(datetime(2013, 1, 2))\n\n self.piecewise_constant_rate = TestDataSeries.objects.create(\n role=DataRoleField.EMPLOYEES,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='person',\n customer=self.customer)\n\n # 1 at work in the timespan 0:00 - 12:00\n self.piecewise_constant_rate.stored_data.create(\n timestamp=self.start_time, value=1)\n\n # 2 at work in the timespan 12:00 -\n self.piecewise_constant_rate.stored_data.create(\n timestamp=self.start_time + timedelta(hours=12), value=2)\n\n self.integral = PiecewiseConstantIntegral.objects.create(\n role=DataRoleField.ENERGY_DRIVER,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='person*hour',\n customer=self.customer,\n data=self.piecewise_constant_rate)\n\n def test_calculate_development(self):\n self.assertEqual(\n self.integral.create_range_sample(\n self.start_time, self.end_time,\n physical_quantity=PhysicalQuantity(\n 12 * 1 + 12 * 2, 'person*hour')),\n self.integral.calculate_development(\n self.start_time, self.end_time))\n\n def test_calculate_development_fallback(self):\n self.assertEqual(\n self.integral.create_range_sample(\n self.start_time, self.end_time,\n physical_quantity=PhysicalQuantity(\n 12 * 1 + 12 * 2, 'person*hour')),\n self.integral._calculate_development_fallback(\n self.start_time, self.end_time))\n\n def test_depends_on(self):\n with patch.object(self.piecewise_constant_rate, 'depends_on',\n return_value=[]) as mock:\n self.assertIn(\n self.piecewise_constant_rate,\n self.integral.depends_on())\n\n mock.assertCalledWith()\n\n def test_get_samples(self):\n with self.assertRaises(UndefinedSamples):\n list(self.integral.get_samples(self.start_time, self.end_time))\n\n def test_get_condensed_samples(self):\n condensed_samples = iter(\n self.integral.get_condensed_samples(\n self.start_time - timedelta(hours=1),\n condense.HOURS, self.end_time))\n\n self.assertEqual(\n self.integral.create_range_sample(\n self.start_time - timedelta(hours=1),\n self.start_time,\n physical_quantity=PhysicalQuantity(0, 'person*hour'),\n uncachable=True,\n extrapolated=True),\n next(condensed_samples))\n\n for i in range(0, 12):\n self.assertEqual(\n self.integral.create_range_sample(\n self.start_time + timedelta(hours=i),\n self.start_time + timedelta(hours=i + 1),\n physical_quantity=PhysicalQuantity(1, 'person*hour')),\n next(condensed_samples))\n\n for i in range(12, 24):\n self.assertEqual(\n self.integral.create_range_sample(\n self.start_time + timedelta(hours=i),\n self.start_time + timedelta(hours=i + 1),\n physical_quantity=PhysicalQuantity(2, 'person*hour')),\n next(condensed_samples))\n\n with self.assertRaises(StopIteration):\n next(condensed_samples)\n\n def test_get_underlying_function(self):\n self.assertEqual(\n self.integral.get_underlying_function(),\n DataSeries.CONTINUOUS_ACCUMULATION)\n\n\n@override_settings(\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory',\n ENCRYPTION_TESTMODE=True)\nclass GetCondensedSamplesTaskTest(TestCase):\n def test_get_condensed_samples_task(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n user = User.objects.create_user(\n 'username', 'password', user_type=User.CUSTOMER_USER,\n customer=customer)\n data_series = TestDataSeries.objects.create(\n customer=customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n START_TIME = datetime(2014, 1, 1, tzinfo=pytz.utc)\n END_TIME = datetime(2014, 1, 1, 2, tzinfo=pytz.utc)\n\n data_series.stored_data.create(value=0, timestamp=START_TIME)\n\n data_series.stored_data.create(value=2, timestamp=END_TIME)\n\n with replace_customer(customer), replace_user(user):\n task_status = get_condensed_samples_task.delay(\n data_series.id, START_TIME, END_TIME, condense.HOURS)\n self.assertTrue(task_status.successful())\n\n self.assertEqual(\n task_status.result[0],\n data_series.create_range_sample(\n START_TIME, START_TIME + condense.HOURS,\n PhysicalQuantity(1, 'milliwatt*hour')))\n\n self.assertEqual(\n task_status.result[1],\n data_series.create_range_sample(\n START_TIME + condense.HOURS, END_TIME,\n PhysicalQuantity(1, 'milliwatt*hour')))\n\n self.assertEqual(len(task_status.result), 2)\n\n\n@override_settings(\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory',\n ENCRYPTION_TESTMODE=True)\nclass GetSamplesTaskTest(TestCase):\n def test_get_samples_task(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n user = User.objects.create_user(\n 'username', 'password', user_type=User.CUSTOMER_USER,\n customer=customer)\n data_series = TestDataSeries.objects.create(\n customer=customer,\n role=DataRoleField.POWER,\n unit='milliwatt',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n START_TIME = datetime(2014, 1, 1, tzinfo=pytz.utc)\n END_TIME = datetime(2014, 1, 1, 2, tzinfo=pytz.utc)\n\n data_series.stored_data.create(value=0, timestamp=START_TIME)\n\n data_series.stored_data.create(value=2, timestamp=END_TIME)\n\n with replace_customer(customer), replace_user(user):\n task_status = get_samples_task.delay(\n data_series.id, START_TIME, END_TIME)\n self.assertTrue(task_status.successful())\n\n self.assertEqual(\n task_status.result[0],\n data_series.create_point_sample(\n START_TIME, PhysicalQuantity(0, 'milliwatt')))\n\n self.assertEqual(\n task_status.result[1],\n data_series.create_point_sample(\n END_TIME,\n PhysicalQuantity(2, 'milliwatt')))\n\n self.assertEqual(len(task_status.result), 2)\n\n\nclass IndexCalculationAutoUnitForm(forms.ModelForm):\n class Meta:\n model = IndexCalculation\n fields = ['role', 'utility_type', 'consumption', 'customer', 'index']\n\n\nclass IndexCalculationForm(forms.ModelForm):\n class Meta:\n model = IndexCalculation\n fields = ['role', 'utility_type', 'consumption', 'customer', 'index',\n 'unit']\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass IndexCalculationTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n self.tariff = DataSeries.objects.create(\n role=DataRoleField.ELECTRICITY_TARIFF,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n customer=self.customer)\n self.consumption = DataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n customer=self.customer)\n\n def test_no_auto_unit(self):\n form = IndexCalculationForm(\n data={\n 'role': DataRoleField.COST,\n 'utility_type': utilitytypes.METER_CHOICES.electricity,\n 'index': self.tariff.id,\n 'consumption': self.consumption.id,\n 'customer': self.customer.id,\n })\n\n self.assertTrue(form.is_valid())\n\n index_calculation = form.save(commit=False)\n\n self.assertFalse(index_calculation.unit)\n\n def test_auto_unit(self):\n form = IndexCalculationAutoUnitForm(\n data={\n 'role': DataRoleField.COST,\n 'utility_type': utilitytypes.METER_CHOICES.electricity,\n 'index': self.tariff.id,\n 'consumption': self.consumption.id,\n 'customer': self.customer.id,\n })\n\n self.assertTrue(form.is_valid())\n\n index_calculation = form.save(commit=False)\n\n self.assertTrue(\n PhysicalQuantity.compatible_units(\n index_calculation.unit,\n 'currency_dkk'),\n '\"%s\" incompatible with \"%s\"' % (\n index_calculation.unit, 'currency_dkk'))\n\n\nclass Co2CalculationTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.unit = Co2Calculation(\n customer=self.customer,\n role=DataRoleField.CO2,\n unit='tonne',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n consumption=TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity),\n index=TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CO2_QUOTIENT,\n unit='gram*kilowatt^-1*hour^-1',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity))\n self.unit.save()\n\n self.start_time = datetime(2013, 1, 1, tzinfo=pytz.utc)\n\n def test_calculate_development(self):\n for i in range(13):\n self.unit.consumption.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=i*5),\n value=i)\n\n self.unit.index.stored_data.create(\n timestamp=self.start_time,\n value=7919)\n self.unit.index.stored_data.create(\n timestamp=self.start_time + timedelta(minutes=30),\n value=1292)\n\n result = self.unit.calculate_development(\n self.start_time, self.start_time + timedelta(hours=1))\n\n expected_result = self.unit.create_range_sample(\n self.start_time,\n self.start_time + timedelta(hours=1),\n PhysicalQuantity(1, 'milliwatt*hour') * 6 *\n PhysicalQuantity(7919, 'gram*kilowatt^-1*hour^-1') +\n PhysicalQuantity(1, 'milliwatt*hour') * 6 *\n PhysicalQuantity(1292, 'gram*kilowatt^-1*hour^-1'),\n uncachable=True, extrapolated=False)\n\n self.assertEqual(result, expected_result)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestConsumptionMeasurementPointDegreeDays(TestCase):\n \"\"\"\n Test the heating degree day corrected consumption aspect of the\n L{ConsumptionMeasurementPoint} proxy model. In particular the\n C{standard_heating_degree_days} and C{heating_degree_days} properties\n behaviour upon validation, saving and loading are tested.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.agent = Agent.objects.create(\n mac=\"AB:CD:DE:F0:12:34\",\n customer=self.customer)\n self.meter = Meter.objects.create(\n agent=self.agent,\n manufactoring_id=\"1234567891234\",\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n name_plain=\"test meter\",\n customer=self.customer)\n\n self.physicalinput = PhysicalInput.objects.create(\n unit='millikelvin',\n type=PhysicalInput.DISTRICT_HEATING,\n meter=self.meter,\n order=0,\n name_plain=\"Energy consumption (#0)\")\n\n self.mp = ConsumptionMeasurementPoint(\n name_plain='test heating degree days',\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp.consumption = DataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='milliwatt*hour',\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.assertIsNone(self.mp.standard_heating_degree_days)\n self.assertIsNone(self.mp.heating_degree_days)\n self.assertFalse(\n self.mp.graph_set.filter(\n role=DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION).\n exists())\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_neither_set(self):\n self.mp.clean()\n self.mp.save()\n loaded_mp = ConsumptionMeasurementPoint.objects.get(id=self.mp.id)\n self.assertIsNone(loaded_mp.standard_heating_degree_days)\n self.assertIsNone(loaded_mp.heating_degree_days)\n self.assertFalse(\n loaded_mp.graph_set.filter(\n role=DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION).\n exists())\n\n def test_both_set(self):\n self.mp.standard_heating_degree_days = DataSeries.objects.create(\n role=DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='kelvin*day',\n customer=self.customer)\n self.mp.heating_degree_days = DataSeries.objects.create(\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='kelvin*day',\n customer=self.customer)\n self.mp.clean()\n self.mp.save()\n loaded_mp = ConsumptionMeasurementPoint.objects.get(id=self.mp.id)\n self.assertEqual(loaded_mp.standard_heating_degree_days,\n self.mp.standard_heating_degree_days)\n self.assertEqual(loaded_mp.heating_degree_days,\n self.mp.heating_degree_days)\n self.assertTrue(\n loaded_mp.graph_set.filter(\n role=DataRoleField.\n HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION).exists())\n\n # Check deletion\n loaded_mp.standard_heating_degree_days = None\n loaded_mp.heating_degree_days = None\n loaded_mp.clean()\n loaded_mp.save()\n loaded_mp.save()\n # double save when deleting corrected consumption has\n # previously not worked, and sw we test it here.\n loaded_mp = ConsumptionMeasurementPoint.objects.get(id=self.mp.id)\n self.assertIsNone(loaded_mp.standard_heating_degree_days)\n self.assertIsNone(loaded_mp.heating_degree_days)\n self.assertFalse(\n loaded_mp.graph_set.filter(\n role=DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION).\n exists())\n\n def test_standard_heating_degree_days_set(self):\n self.mp.standard_heating_degree_days = DataSeries.objects.create(\n role=DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='kelvin*day',\n customer=self.customer)\n self.assertIsNotNone(self.mp.standard_heating_degree_days)\n self.assertIsNone(self.mp.heating_degree_days)\n with self.assertRaises(ValidationError):\n self.mp.clean()\n\n def test_heating_degree_days_set(self):\n self.mp.heating_degree_days = DataSeries.objects.create(\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n unit='kelvin*day',\n customer=self.customer)\n self.assertIsNone(self.mp.standard_heating_degree_days)\n self.assertIsNotNone(self.mp.heating_degree_days)\n with self.assertRaises(ValidationError):\n self.mp.clean()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestConsumptionMeasurementPointSummation(TestCase):\n \"\"\"\n Test the L{ConsumptionMeasurementPointSummation} proxy class.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.mp_electricity1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Electricity 1',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_electricity1.consumption = DataSeries.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n role=DataRoleField.CONSUMPTION)\n self.mp_electricity1.save()\n\n self.mp_electricity2 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Electricity 2',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.mp_electricity2.consumption = DataSeries.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n role=DataRoleField.CONSUMPTION)\n self.mp_electricity2.save()\n\n self.mp_water1 = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Water 1',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water)\n self.mp_water1.consumption = DataSeries.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water,\n role=DataRoleField.CONSUMPTION)\n self.mp_water1.save()\n\n self.unit = ConsumptionMeasurementPointSummation(\n name_plain='Electricity sum',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantiation(self):\n self.unit.plus_consumption_measurement_points = [self.mp_electricity1]\n self.assertIn(\n self.mp_electricity1,\n self.unit.plus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_electricity1,\n self.unit.minus_consumption_measurement_points)\n\n self.unit.minus_consumption_measurement_points = [self.mp_electricity2]\n self.assertIn(\n self.mp_electricity2,\n self.unit.minus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_electricity2,\n self.unit.plus_consumption_measurement_points)\n\n self.assertNotIn(\n self.mp_water1,\n self.unit.plus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_water1,\n self.unit.minus_consumption_measurement_points)\n\n def test_reinstantiation(self):\n self.test_instantiation()\n self.unit.save()\n self.reinstantiation = ConsumptionMeasurementPointSummation.\\\n objects.get(id=self.unit.id)\n\n self.assertIn(\n self.mp_electricity1,\n self.reinstantiation.plus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_electricity1,\n self.reinstantiation.minus_consumption_measurement_points)\n\n self.assertIn(\n self.mp_electricity2,\n self.reinstantiation.minus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_electricity2,\n self.reinstantiation.plus_consumption_measurement_points)\n\n self.assertNotIn(\n self.mp_water1,\n self.reinstantiation.plus_consumption_measurement_points)\n self.assertNotIn(\n self.mp_water1,\n self.reinstantiation.minus_consumption_measurement_points)\n\n def test_dependencies(self):\n self.unit.plus_consumption_measurement_points = [self.mp_electricity1]\n self.unit.minus_consumption_measurement_points = [self.mp_electricity2]\n self.unit.save()\n\n self.assertEqual(\n any([self.mp_electricity1.is_deletable(),\n self.mp_electricity2.is_deletable()]),\n False)\n\n def test_dependencies_by_db_level(self):\n self.unit.plus_consumption_measurement_points = [self.mp_electricity1]\n self.unit.minus_consumption_measurement_points = [self.mp_electricity2]\n self.unit.save()\n\n self.assertRaises(\n ProtectedError, lambda: self.mp_electricity1.delete())\n self.assertRaises(\n ProtectedError, lambda: self.mp_electricity2.delete())\n\n\nclass ImportedMeasurementPointTest(TestCase):\n def test_clean_success(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;0,125;1,8\\n'\n\n mp.timezone = pytz.utc\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.unit = 'kilowatt*hour'\n\n mp.clean()\n\n self.assertEqual(\n mp.parsed_csv,\n [(datetime(2010, 8, 1, 0, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n Fraction('0.475')),\n (datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 2, 0, tzinfo=pytz.utc),\n Fraction('0.125'))])\n\n def test_clean_skip_an_empty_line_success(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;0,125;1,8\\n'\n\n mp.timezone = pytz.utc\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.unit = 'kilowatt*hour'\n\n mp.clean()\n\n self.assertEqual(\n mp.parsed_csv,\n [(datetime(2010, 8, 1, 0, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n Fraction('0.475')),\n (datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 2, 0, tzinfo=pytz.utc),\n Fraction('0.125'))])\n\n def test_clean_decoding_success(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454; '\\\n u'Åbenbar unicode-ødelæggende kommentar\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;0,125;1,8\\n'\n\n mp.timezone = pytz.utc\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', csv.encode('iso8859'))\n mp.unit = 'kilowatt*hour'\n\n mp.clean()\n\n self.assertEqual(\n mp.parsed_csv,\n [(datetime(2010, 8, 1, 0, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n Fraction('0.475')),\n (datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 2, 0, tzinfo=pytz.utc),\n Fraction('0.125'))])\n\n def test_clean_consumption_column_does_not_exist(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;0,125;1,8\\n'\n mp.timezone = pytz.utc\n mp.consumption_column = 42\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.unit = 'kilowatt*hour'\n\n with self.assertRaises(ImportedMeasurementPoint.\n ConsumptionColumnDoesNotExist) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n self.assertEqual(cm.exception.lineno, 2)\n\n def test_clean_consumption_parse_error(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;pi;1,8\\n'\n\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.timezone = pytz.utc\n mp.unit = 'kilowatt*hour'\n with self.assertRaises(ImportedMeasurementPoint.\n ConsumptionParseError) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n self.assertEqual(cm.exception.lineno, 3)\n\n def test_clean_time_sequence_first_row_error(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 01:00 - 01-08-2010 00:00;0,475;1,825\\n'\\\n '01-08-2010 01:00 - 01-08-2010 02:00;0,125;1,8\\n'\n\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.timezone = pytz.utc\n mp.unit = 'kilowatt*hour'\n\n with self.assertRaises(ImportedMeasurementPoint.\n TimeSequenceError) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n self.assertEqual(cm.exception.lineno, 2)\n\n def test_clean_time_sequence_between_rows_error(self):\n\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '01-08-2010 00:00 - 01-08-2010 01:00;0,475;1,825\\n'\\\n '01-08-2010 02:00 - 01-08-2010 03:00;0,125;1,8\\n'\n\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.timezone = pytz.utc\n mp.unit = 'kilowatt*hour'\n\n with self.assertRaises(ImportedMeasurementPoint.\n TimeSequenceError) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n self.assertEqual(cm.exception.lineno, 3)\n\n def test_clean_time_value_error(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\\\n '2010-08-01 8.30pm - 01-08-2010 01:00;0,475;1,825\\n'\n\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.timezone = pytz.utc\n mp.unit = 'kilowatt*hour'\n with self.assertRaises(ImportedMeasurementPoint.\n TimeValueError) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n self.assertEqual(cm.exception.lineno, 2)\n\n def test_clean_empty_file_error(self):\n mp = ImportedMeasurementPoint()\n\n csv = 'kWh - Time;571313115400167430;571313115400167454\\n'\\\n ';;\\n'\n\n mp.consumption_column = 1\n mp.upload_file = SimpleUploadedFile('test.csv', str(csv))\n mp.timezone = pytz.utc\n mp.unit = 'kilowatt*hour'\n with self.assertRaises(ImportedMeasurementPoint.\n EmptyFileError) as cm:\n mp.clean()\n\n self.assertEqual(cm.exception.filename, 'test.csv')\n\n def test_clean_no_file_no_exception(self):\n mp = ImportedMeasurementPoint()\n mp.consumption_column = 1\n mp.clean()\n\n def test_save(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n with replace_customer(self.customer):\n assert self.customer is trackuser.get_customer()\n with no_encryption():\n mp = ImportedMeasurementPoint(\n utility_type=utilitytypes.METER_CHOICES.electricity)\n mp.parsed_csv = [\n (datetime(2010, 8, 1, 0, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n Fraction('0.475')),\n (datetime(2010, 8, 1, 1, 0, tzinfo=pytz.utc),\n datetime(2010, 8, 1, 2, 0, tzinfo=pytz.utc),\n Fraction('0.125'))]\n mp.unit = 'kilowatt*hour'\n mp.timezone = pytz.utc\n mp.save()\n\n self.assertTrue(mp.consumption.stored_data.filter(\n timestamp=datetime(2010, 8, 1, tzinfo=pytz.utc),\n value=0).exists())\n self.assertTrue(mp.consumption.stored_data.filter(\n timestamp=datetime(2010, 8, 1, 1, tzinfo=pytz.utc),\n value=int(0.475 * 1000000)).exists())\n self.assertTrue(mp.consumption.stored_data.filter(\n timestamp=datetime(2010, 8, 1, 2, tzinfo=pytz.utc),\n value=int((0.125 + 0.475) * 1000000)).exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestLocation(TestCase):\n \"\"\"\n Test the L{Location} class.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n def test_dependencies_by_db_level(self):\n loc1 = Location.objects.create(\n name_plain='test 1', customer=self.customer)\n Location.objects.create(\n name_plain='test 2', customer=self.customer, parent=loc1)\n\n self.assertRaises(ProtectedError, lambda: loc1.delete())\n\n @unittest.skip(\"Implementation is missing on model, currently in view.py\")\n def test_dependencies(self):\n loc1 = Location.objects.create(\n name_plain='test 1', customer=self.customer)\n Location.objects.create(\n name_plain='test 2', customer=self.customer, parent=loc1)\n self.assertEqual(loc1.is_deletable(), False)\n\n\nclass TestCollection(TestCase):\n \"\"\"\n Test C{Collection}.\n \"\"\"\n\n def test_get_icon_completeness(self):\n \"\"\"\n Test Collection.get_icon() for completeness.\n \"\"\"\n unit = Collection()\n for role, _ in Collection.ROLE_CHOICES:\n unit.role = role\n unit.get_icon()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass CollectionManagerTest(TestCase):\n def setUp(self):\n with encryption_context():\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.user = User.objects.create_user(\n 'username', 'password', user_type=User.CUSTOMER_USER,\n customer=self.customer)\n\n def test_no_customer_and_no_user(self):\n collection = Collection.objects.create(\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.assertEqual(\n collection, Collection.objects.get())\n\n def test_constraint_customer(self):\n collection = Collection.objects.create(\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n customer2 = Customer()\n customer2.save()\n Collection.objects.create(\n customer=customer2,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n with replace_customer(self.customer), replace_user(self.user):\n self.assertEqual(\n collection, Collection.objects.get())\n\n def test_user_collection_constraint_root(self):\n collection = Collection.objects.create(\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n Collection.objects.create(\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n CollectionConstraint.objects.create(\n collection=collection, userprofile=self.user.userprofile)\n\n with replace_customer(self.customer), replace_user(self.user):\n self.assertEqual(\n collection, Collection.objects.get())\n\n def test_user_collection_constraint_child(self):\n group = Collection.objects.create(\n customer=self.customer,\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n collection = Collection.objects.create(\n parent=group,\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n rogue_collection = Collection.objects.create(\n customer=self.customer,\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n CollectionConstraint.objects.create(\n collection=group, userprofile=self.user.userprofile)\n\n with replace_customer(self.customer), replace_user(self.user):\n self.assertTrue(Collection.objects.filter(id=group.id).exists())\n self.assertTrue(Collection.objects.filter(\n id=collection.id).exists())\n self.assertFalse(Collection.objects.filter(\n id=rogue_collection.id).exists())\n\n self.assertTrue(Collection.objects.filter(id=group.id).exists())\n self.assertTrue(Collection.objects.filter(id=collection.id).exists())\n self.assertTrue(Collection.objects.filter(\n id=rogue_collection.id).exists())\n" }, { "alpha_fraction": 0.6378762125968933, "alphanum_fraction": 0.6381208896636963, "avg_line_length": 33.93162536621094, "blob_id": "94b593c431e422746ae9a66e5f968dec743b75ef", "content_id": "2f655bf8343a67af75a06f04b6c7d2815ce33fed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4087, "license_type": "no_license", "max_line_length": 78, "num_lines": 117, "path": "/gridplatform/consumptions/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils import units\n\nfrom . import models\n\n\nclass Consumption(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set', many=True, read_only=True)\n hourly = serializers.SerializerMethodField('get_hourly')\n nonpulse_periods = serializers.HyperlinkedIdentityField(\n view_name='api:consumptions:nonpulseperiod-list')\n pulse_periods = serializers.HyperlinkedIdentityField(\n view_name='api:consumptions:pulseperiod-list')\n single_value_periods = serializers.HyperlinkedIdentityField(\n view_name='api:consumptions:singlevalueperiod-list')\n offlinetolerance = serializers.HyperlinkedIdentityField(\n view_name='api:consumptions:offlinetolerance-list')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.Consumption\n fields = ('url', 'id', 'name', 'unit', 'display_unit', 'customer',\n 'periods', 'offlinetolerance', 'hourly', 'nonpulse_periods',\n 'pulse_periods', 'single_value_periods')\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:consumptions:consumption-hourly', kwargs={'pk': obj.id})\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n\nclass MainConsumption(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n description = serializers.CharField(source='description_plain')\n hourly = serializers.SerializerMethodField('get_hourly')\n\n class Meta:\n model = models.MainConsumption\n fields = (\n 'url', 'id', 'customer',\n 'name', 'description', 'utility_type',\n 'tariff', 'cost_compensation', 'hourly',\n 'from_date', 'to_date',\n )\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:consumptions:mainconsumption-hourly',\n args=[obj.id], request=self.context['request'])\n\n\nclass ConsumptionGroup(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n description = serializers.CharField(source='description_plain')\n hourly = serializers.SerializerMethodField('get_hourly')\n\n class Meta:\n model = models.ConsumptionGroup\n fields = (\n 'url', 'id', 'customer', 'name', 'description',\n 'mainconsumption', 'cost_compensation', 'hourly',\n 'from_date', 'to_date',\n )\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:consumptions:consumptiongroup-hourly',\n args=[obj.id], request=self.context['request'])\n\n\nclass NonpulsePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.NonpulsePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource')\n read_only_fields = ('datasequence',)\n\n\nclass PulsePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.PulsePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource', 'pulse_quantity', 'output_quantity', 'output_unit')\n read_only_fields = ('datasequence',)\n\n\nclass SingleValuePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.SingleValuePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'value', 'unit')\n read_only_fields = ('datasequence',)\n\n\nclass OfflineTolerance(serializers.DefaultSerializer):\n class Meta:\n model = models.OfflineTolerance\n fields = (\n 'url', 'id', 'hours', 'datasequence')\n read_only_fields = ('datasequence',)\n" }, { "alpha_fraction": 0.6078187823295593, "alphanum_fraction": 0.6087496280670166, "avg_line_length": 32.398963928222656, "blob_id": "bb0ec851918f64285c52e623c2118217d7d8692c", "content_id": "8efa153b02acedf9f93b4622c987f60edbf1d880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6446, "license_type": "no_license", "max_line_length": 79, "num_lines": 193, "path": "/gridplatform/trackuser/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport functools\nimport types\n\nfrom django.utils import translation\n\nfrom celery import Task\nfrom celery import shared_task\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.users.models import User\n\nfrom . import _get_override_customer\nfrom . import _get_selected_customer\nfrom . import get_customer\nfrom . import get_user\nfrom . import replace_override_customer\nfrom . import replace_selected_customer\nfrom . import replace_user\n\n\ndef trackuser_task(task_instance):\n \"\"\"\n Decorate the given Celery task instance to be in the same trackuser context\n on the worker side as it was on the invokation side.\n\n Usage::\n\n @trackuser_task\n @task\n class MyTask(Task):\n def run(self, *args, **kwargs):\n ...\n\n or::\n\n @trackuser_task\n @task\n def my_task(*args, **kwargs):\n ...\n\n :precondition: This decorator can only be used on concrete\n :class:`celery.Task` instances. So always write the\n ``@trackuser_task`` decorator above the ``@task`` decorator.\n\n :see: :func:`.task`, for a simpler decorator intended for function tasks.\n \"\"\"\n assert isinstance(task_instance, Task), \\\n 'precondition violated: @trackuser_task decorator should be on top '\\\n 'of @task decorator'\n\n task_instance.__class__.orig_apply_async = \\\n task_instance.__class__.apply_async\n orig_run = task_instance.run\n\n def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,\n link=None, link_error=None, **options):\n # Extract customer and user from current trackuser context, and forward\n # these as keyword arguments to L{run()}.\n extra_kwargs = {\n '_customer_id': get_customer().id,\n '_user_id': get_user().id,\n }\n\n if kwargs is None:\n kwargs = extra_kwargs\n else:\n assert '_customer_id' not in kwargs\n assert '_user_id' not in kwargs\n kwargs.update(extra_kwargs)\n\n return self.orig_apply_async(\n args=args, kwargs=kwargs, task_id=task_id, producer=producer,\n link=link, link_error=link_error, **options)\n\n def run(*args, **kwargs):\n # Runs C{run()} in a trackuser context similar to the one of the\n # request in which the task invocation was enqueued.\n customer = Customer.objects.get(id=kwargs.pop('_customer_id'))\n user = User.objects.get(id=kwargs.pop('_user_id'))\n with replace_override_customer(customer), replace_user(user):\n return orig_run(*args, **kwargs)\n\n # In production environments Celery behaves different than in unit-test. In\n # particular:\n #\n # - If apply_async is not a bound method on class level it won't be bound\n # at all for function based tasks.\n #\n # - If apply_async is not assigned on class level it won't be called at\n # all for function based tasks.\n task_instance.__class__.apply_async = types.MethodType(\n apply_async, task_instance, task_instance.__class__)\n\n # ahh, our run must be bound/unbound the same way their run is...\n task_instance.run = run\n\n return task_instance\n\n\ndef _context_from_kwargs(f):\n @functools.wraps(f)\n def wrapped(*args, **kwargs):\n user_id = kwargs.pop('_user_id')\n if user_id is not None:\n user = User.objects.get(id=user_id)\n else:\n user = None\n override_customer_id = kwargs.pop('_override_customer_id')\n if override_customer_id is not None:\n override_customer = Customer.objects.get(id=override_customer_id)\n else:\n override_customer = None\n selected_customer_id = kwargs.pop('_selected_customer_id')\n if selected_customer_id is not None:\n selected_customer = Customer.objects.get(id=selected_customer_id)\n else:\n selected_customer = None\n language = kwargs.pop('_language')\n with replace_user(user), \\\n replace_override_customer(override_customer), \\\n replace_selected_customer(selected_customer), \\\n translation.override(language):\n return f(*args, **kwargs)\n return wrapped\n\n\ndef _context_to_kwargs():\n return {\n '_user_id': getattr(get_user(), 'id', None),\n '_override_customer_id': getattr(_get_override_customer(), 'id', None),\n '_selected_customer_id': getattr(_get_selected_customer(), 'id', None),\n '_language': translation.get_language(),\n }\n\n\nclass TaskBase(Task):\n abstract = True\n\n def apply_async(self, args=None, kwargs=None, task_id=None, producer=None,\n link=None, link_error=None, **options):\n extra_kwargs = _context_to_kwargs()\n if kwargs is None:\n kwargs = extra_kwargs\n else:\n assert all([key not in kwargs for key in extra_kwargs.keys()])\n kwargs.update(extra_kwargs)\n return super(TaskBase, self).apply_async(\n args=args, kwargs=kwargs, task_id=task_id, producer=producer,\n link=link, link_error=link_error, **options)\n\n def set_progress(self, current, total):\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': current,\n 'total': total,\n })\n\n\ndef task(*args, **kwargs):\n \"\"\"\n Wrapper/replacement for the Celery ``@shared_task`` decorator that will run\n the task in the same ``user``/``customer``/``selected_customer`` context\n that was active on the invocation side.\n\n Takes the same parameters as ``@shared_task``. Reserves the keyword\n arguments ``_user_id``, ``_customer_id`` and ``_selected_customer_id``.\n\n Usage::\n\n @task\n my_task(*args, **kwargs):\n ...\n \"\"\"\n def create_task(**options):\n base = options.pop('base', TaskBase)\n assert issubclass(base, TaskBase)\n\n def wrap_callable(f):\n return shared_task(base=base, **options)(_context_from_kwargs(f))\n return wrap_callable\n\n if len(args) == 1 and callable(args[0]):\n assert len(kwargs) == 0\n return create_task()(args[0])\n else:\n assert len(args) == 0\n return create_task(**kwargs)\n" }, { "alpha_fraction": 0.7765892148017883, "alphanum_fraction": 0.7805623412132263, "avg_line_length": 34.94505310058594, "blob_id": "2595ecadd83c71c7409292a83afcbf540828b49b", "content_id": "75223911092514c5818ef2630b1c81b516186c2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 3272, "license_type": "no_license", "max_line_length": 79, "num_lines": 91, "path": "/documentation/source/gridagent_server.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "****************\nGridAgent Server\n****************\n\nThe GridAgent server listens for network connections from GridAgents. Its\nprimary purpose is to receive measurement data from the GridAgents and add it\nto the database where the GridPortal may read it.\n\nIt keeps track of the currently connected GridAgents, and is responsible for\nforwarding time-based rules to connected GridAgents, for setting the time on\nGridAgents, for storing information about the current GridAgent and GridPoint\nstate as provided by the GridAgent, and it is also capable of sending GridAgent\nsoftware updates and relay control signals for GridPoints.\n\nThe GridAgent server access the same database as the GridPortal, using parts of\nthe same data model specified with the Django ORM that the GridPortal uses.\n\n\n\nGridAgent Server Protocol\n=========================\n\nCommunication is message-based. Messages have a common header with type,\nlength and a field for Boolean where this may simplify the payload.\n\nApart from the initial handshake, communication is encrypted. We use a\npre-shared key, merged with a nonce from the agent to protect against playback\nattacks (and with the MAC address from the agent for slightly improved\nobscurity).\n\nCurrently, the set of messages sent by a server is disjoint from the set of\nmessages sent by a client --- though the header is the same, and the type\nidentifiers are global, so this may be changed later.\n\nThe protocol has a version number, sent by both sides as part of the handshake.\nAt present, the server must handle version discrepencies, i.e. communication\ntakes place with the protocol version specified by the client.\n\nData is sent in big endian/network byte order format.\n\n\nHandshake\n---------\n\nThe server sends a 4-byte protocol version followed by a 8-byte random nonce.\n\nThe client/agent sends a 4-byte protocol version followed by an 8-byte\nidentifiers. (Currently, agents use their Ethernet MAC address as identifiers,\nwith the 48-bit MAC address encoded as a 64-bit number; meaning that the first\ntwo bytes of the identifier will always be zero.)\n\nIn the current setup, the server is responsible for handling protocol version\ndiscrepancies; either communication happens with the protocol version specified\nby the client, or the server closes the connection.\n\n\nEncryption\n----------\n\nCommunication is encrypted using RC4.\n\nThe encryption uses a key constructed by combining a shared secret with the\nnonce and the ID provided by the client.\n\nThe same key is used for communication from client to server and from server to\nclient, though these are otherwise considered separate streams with separate\nstate.\n\nAfter the handshake, communication is encrypted.\n\n\nMessage header\n--------------\n\nAll messages after the handshake share a common header format:\n\n* 4-bytes unsigned message size\n* 2 bytes padding\n* 1 byte message type\n* 1 byte boolean flags\n\nThe length is the total length *including* the header.\n\n\nMessage structure\n-----------------\n\nAll the different messages and their structure are very simple to follow by\nsimply inspecting the Python code. Client and server messages are found\n:file:`gridplatform/gridagentserver_protocol/client_messages.py` and\n:file:`gridplatform/gridagentserver_protocol/server_messages.py`, respectively.\n\n" }, { "alpha_fraction": 0.596868634223938, "alphanum_fraction": 0.6195547580718994, "avg_line_length": 35.20276641845703, "blob_id": "bcb5f132541f2e4a992b7bef398a9ab36f0ed1db", "content_id": "b842f04b0c3c35510a242626acb59014bde1a1a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70708, "license_type": "no_license", "max_line_length": 79, "num_lines": 1953, "path": "/gridplatform/utils/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\nimport datetime\nimport itertools\n\nfrom django.db import models\nfrom django.forms import ModelForm\nfrom django.test import TestCase\nfrom django.test import SimpleTestCase\nfrom django.utils import translation\nfrom django.contrib.sessions.middleware import SessionMiddleware\nfrom django.test import RequestFactory\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ValidationError\nfrom django.test.utils import override_settings\n\nfrom mock import patch\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport pytz\nfrom extra_views import InlineFormSet\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.users.models import User\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.consumptions.models import SingleValuePeriod\n\nfrom . import condense\nfrom . import fields\nfrom . import first_last\nfrom . import generic_views\nfrom . import utilitytypes\nfrom . import sum_or_none\nfrom .breadcrumbs import Breadcrumb\nfrom .breadcrumbs import Breadcrumbs\nfrom .decorators import virtual\nfrom .format_id import format_mbus_enhanced\nfrom .iter_ext import count_extended\nfrom .iter_ext import pairwise\nfrom .iter_ext import pairwise_extended\nfrom .iter_ext import nwise\nfrom .iter_ext import tee_lookahead\nfrom .models import StoreSubclass\nfrom .models import DateRangeModelMixin\nfrom .models import TimestampRangeModelMixin\nfrom .managers import DateRangeManagerMixin\nfrom .managers import TimestampRangeManagerMixin\nfrom .preferredunits import AbsoluteCelsiusUnitConverter\nfrom .preferredunits import AbsoluteFahrenheitUnitConverter\nfrom .preferredunits import AreaENPIUnitConverter\nfrom .preferredunits import PersonsENPIUnitConverter\nfrom .preferredunits import PhysicalUnitConverter\nfrom .preferredunits import ProductionAENPIUnitConverter\nfrom .preferredunits import ProductionBENPIUnitConverter\nfrom .preferredunits import ProductionCENPIUnitConverter\nfrom .preferredunits import ProductionDENPIUnitConverter\nfrom .preferredunits import ProductionEENPIUnitConverter\nfrom .preferredunits import RelativeCelsiusUnitConverter\nfrom .preferredunits import RelativeFahrenheitUnitConverter\nfrom .relativetimedelta import RelativeTimeDelta\nfrom .unitconversion import IncompatibleUnitsError\nfrom .unitconversion import NotPhysicalQuantityError\nfrom .unitconversion import PhysicalQuantity\nfrom .unitconversion import UnitParseError\nfrom .units import preferred_unit_bases\nfrom .views import HomeViewBase\nfrom .views import CustomerViewBase\nfrom .forms import TimePeriodModelForm\nfrom .forms import HalfOpenTimePeriodModelForm\nfrom .forms import previous_month_initial_values\nfrom .api import next_valid_date_for_datasequence\nfrom .api import previous_valid_date_for_datasequence\nfrom .forms import YearWeekPeriodForm\nfrom .forms import this_week_initial_values\n\n\nclass GenericViewTestCaseMixin(object):\n view_class = None\n\n def setUp(self):\n super(GenericViewTestCaseMixin, self).setUp()\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(name_plain='test customer')\n self.factory = RequestFactory()\n\n def get_view_kwargs(self):\n return {}\n\n def test_get(self):\n request = self.factory.get('/')\n request.user = User(name_plain='test user', is_superuser=True)\n view = self.view_class.as_view()\n response = view(request, **self.get_view_kwargs())\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n\ndef _fields_test_object_hook(json_object):\n \"\"\"\n JSON object_hook for converting named members to concrete Python\n objects. This particular hook is only used for testing purposes.\n \"\"\"\n if \"time\" in json_object:\n h, m, s = json_object[\"time\"].split(\":\")\n json_object[\"time\"] = datetime.time(hour=int(h),\n minute=int(m),\n second=int(s))\n return json_object\n\n\nclass CustomWebDriver(webdriver.Chrome):\n \"\"\"Our own WebDriver with some helpers added\"\"\"\n\n def __init__(self, *args, **kwargs):\n return super(CustomWebDriver, self).__init__(*args, **kwargs)\n\n def find_css(self, css_selector, raise_exception=True):\n \"\"\"\n Shortcut to find elements by CSS. Returns either a list or singleton\n \"\"\"\n elems = self.find_elements_by_css_selector(css_selector)\n found = len(elems)\n if found == 1:\n return elems[0]\n elif not elems and raise_exception:\n raise NoSuchElementException(css_selector)\n return elems\n\n def wait_for_css(self, css_selector, timeout=7):\n \"\"\" Shortcut for WebDriverWait\"\"\"\n return WebDriverWait(self, timeout).until(\n lambda driver: driver.find_css(css_selector))\n\n def login(self, url, user, password):\n \"\"\"\n Requires that a user exists, and the driver has been started\n \"\"\"\n self.get(url)\n self.find_css(\"#id_username\").clear()\n self.find_css(\"#id_username\").send_keys(user)\n self.find_css(\"#id_password\").clear()\n self.find_css(\"#id_password\").send_keys(password)\n self.find_css(\"input[type=\\\"submit\\\"]\").click()\n\n def logout(self):\n self.find_css(\".logout a\", raise_exception=False).click()\n\n\nclass FieldsTestModel(models.Model):\n \"\"\"\n Models must be defined in the models.py, otherwise they just\n aren't processed right when running unittests.\n \"\"\"\n field = fields.JSONField(object_hook=_fields_test_object_hook)\n\n\nclass JSONFieldTest(TestCase):\n def test_basic_serialization(self):\n \"\"\"\n Tests JSON serialization of various Python objects\n \"\"\"\n unit = FieldsTestModel()\n unit.field = {\"foo\": \"bar\", \"baz\": [\"inktvis\", 42, None, True, False]}\n unit.save()\n restored_unit = FieldsTestModel.objects.get(id=unit.id)\n self.assertEqual(unit.field, restored_unit.field)\n\n unit.field = \"\"\n unit.save()\n restored_unit = FieldsTestModel.objects.get(id=unit.id)\n self.assertEqual(unit.field, restored_unit.field)\n\n unit.field = None\n unit.save()\n restored_unit = FieldsTestModel.objects.get(id=unit.id)\n self.assertEqual(unit.field, restored_unit.field)\n\n def test_object_hook(self):\n \"\"\"\n Test JSON serialization using object_hook\n \"\"\"\n\n unit = FieldsTestModel()\n unit.field = {\"foo\": \"bar\", \"time\": datetime.time(hour=4, minute=42)}\n unit.save()\n restored_unit = FieldsTestModel.objects.get(id=unit.id)\n self.assertEqual(unit.field, restored_unit.field)\n\n\nclass RelativeTimeDeltaTest(TestCase):\n \"\"\"\n Test RelativeTimeDelta\n \"\"\"\n def setUp(self):\n self.timezone = pytz.timezone(\"Europe/Copenhagen\")\n self.to_summer_start = self.timezone.localize(\n datetime.datetime(2013, 3, 31, 0, 0))\n self.to_winter_start = self.timezone.localize(\n datetime.datetime(2013, 10, 27, 0, 0))\n\n def test_naive_date(self):\n \"\"\"\n Test L{RelativeTimeDelta} on naive dates.\n \"\"\"\n delta = RelativeTimeDelta(months=1)\n start_time = datetime.datetime(2013, 1, 1)\n self.assertEqual(start_time + delta, datetime.datetime(2013, 2, 1))\n self.assertEqual(start_time + 4 * delta, datetime.datetime(2013, 5, 1))\n\n def test_aware_date(self):\n \"\"\"\n Test L{RelativeTimeDelta} on timezone and daylight savings\n aware dates.\n \"\"\"\n delta = RelativeTimeDelta(months=1)\n start_time = self.timezone.localize(datetime.datetime(2013, 1, 1))\n self.assertIsInstance(start_time.tzinfo, pytz.tzinfo.BaseTzInfo)\n self.assertEqual(start_time + delta,\n self.timezone.localize(datetime.datetime(2013, 2, 1)))\n self.assertEqual(start_time + 4 * delta,\n self.timezone.localize(datetime.datetime(2013, 5, 1)))\n\n def test_dst_switch(self):\n \"\"\"\n Test L{RelativeTimeDelta} wrt. DST switch.\n\n @note: Regression test for bug where 2013-03-31 02:00 STD was followed\n by 2013-03-31 03:00 DST, i.e. a different representation of the same\n timestamp.\n \"\"\"\n hour = RelativeTimeDelta(hours=1)\n for n in range(6):\n timestamp = self.to_summer_start + n * hour\n self.assertNotEqual(timestamp, timestamp + hour)\n timestamp = self.to_winter_start + n * hour\n self.assertNotEqual(timestamp, timestamp + hour)\n\n def test_hour_duration_exiting_dst(self):\n hour = RelativeTimeDelta(hours=1)\n absolute_delta = datetime.timedelta(hours=1)\n for n in range(6):\n timestamp = self.to_winter_start + n * hour\n self.assertEqual(\n self.timezone.normalize(timestamp + absolute_delta),\n timestamp + hour)\n\n def test_hour_duration_entering_dst(self):\n hour = RelativeTimeDelta(hours=1)\n absolute_delta = datetime.timedelta(hours=1)\n for n in range(6):\n timestamp = self.to_summer_start + n * hour\n self.assertEqual(\n self.timezone.normalize(timestamp + absolute_delta),\n timestamp + hour)\n\n def test_minute_duration_exiting_dst(self):\n minutes = RelativeTimeDelta(minutes=5)\n absolute_delta = datetime.timedelta(minutes=5)\n for n in range(24 * 60 / 5):\n timestamp = self.to_winter_start + n * minutes\n self.assertEqual(\n self.timezone.normalize(timestamp + absolute_delta),\n timestamp + minutes)\n\n def test_minute_duration_entering_dst(self):\n minutes = RelativeTimeDelta(minutes=5)\n absolute_delta = datetime.timedelta(minutes=5)\n for n in range(24 * 60 / 5):\n timestamp = self.to_summer_start + n * minutes\n self.assertEqual(\n self.timezone.normalize(timestamp + absolute_delta),\n timestamp + minutes)\n\n\nclass CondenseTest(TestCase):\n def test_floor(self):\n for resolution in [\n \"minutes\",\n \"hours\",\n \"days\",\n \"months\",\n \"years\"\n ]:\n timestamp = datetime.datetime(\n year=2012,\n month=12,\n day=12,\n hour=12,\n minute=12,\n second=12,\n tzinfo=pytz.utc)\n\n relative_time_delta = RelativeTimeDelta(**{resolution: 1})\n timestamp = condense.floor(\n timestamp, relative_time_delta, pytz.utc)\n\n if resolution == \"second\":\n self.assertEqual(timestamp.microsecond, 00)\n elif resolution == \"minutes\":\n self.assertEqual(timestamp.microsecond, 00)\n self.assertEqual(timestamp.second, 00)\n elif resolution == \"hours\":\n self.assertEqual(timestamp.microsecond, 00)\n self.assertEqual(timestamp.second, 00)\n self.assertEqual(timestamp.minute, 00)\n elif resolution == \"days\":\n self.assertEqual(timestamp.microsecond, 00)\n self.assertEqual(timestamp.second, 00)\n self.assertEqual(timestamp.minute, 00)\n self.assertEqual(timestamp.hour, 00)\n elif resolution == \"months\":\n self.assertEqual(timestamp.microsecond, 00)\n self.assertEqual(timestamp.second, 00)\n self.assertEqual(timestamp.minute, 00)\n self.assertEqual(timestamp.hour, 00)\n self.assertEqual(timestamp.day, 1)\n elif resolution == \"years\":\n self.assertEqual(timestamp.microsecond, 00)\n self.assertEqual(timestamp.second, 00)\n self.assertEqual(timestamp.minute, 00)\n self.assertEqual(timestamp.hour, 00)\n self.assertEqual(timestamp.day, 1)\n self.assertEqual(timestamp.month, 1)\n\n def test_floor_ambiguous_is_dst(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(\n datetime.datetime(2013, 10, 27, 2), is_dst=True)\n\n self.assertEqual(\n timestamp, condense.floor(timestamp, condense.HOURS, timezone))\n\n def test_floor_ambiguous_is_not_dst(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(\n datetime.datetime(2013, 10, 27, 2), is_dst=False)\n\n self.assertEqual(\n timestamp, condense.floor(timestamp, condense.HOURS, timezone))\n\n def test_floor_exiting_dst(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(datetime.datetime(2013, 6, 1))\n\n self.assertEqual(\n timezone.localize(datetime.datetime(2013, 1, 1)),\n condense.floor(timestamp, condense.YEARS, timezone))\n\n def test_floor_entering_dst(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(datetime.datetime(2013, 10, 30))\n\n self.assertEqual(\n timezone.localize(datetime.datetime(2013, 10, 1)),\n condense.floor(timestamp, condense.MONTHS, timezone))\n\n def test_ceil_nontrivial(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(datetime.datetime(2013, 10, 20))\n\n self.assertEqual(\n timezone.localize(datetime.datetime(2013, 11, 1)),\n condense.ceil(timestamp, condense.MONTHS, timezone))\n\n def test_ceil_identity(self):\n timezone = pytz.timezone('Europe/Copenhagen')\n\n timestamp = timezone.localize(datetime.datetime(2013, 10, 1))\n\n self.assertEqual(\n timezone.localize(datetime.datetime(2013, 10, 1)),\n condense.ceil(timestamp, condense.MONTHS, timezone))\n\n\nclass CondenseGetPreferredDateFormatTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_no_resolution_within_day(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2013, 1, 2)))\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 2)))\n mock.assertCalledWith('TIME_FORMAT')\n\n def test_minutes_resolution_within_day(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2013, 1, 2)),\n condense.MINUTES)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 2)))\n mock.assertCalledWith('TIME_FORMAT')\n\n def test_five_minutes_resolution_within_day(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2013, 1, 2)),\n condense.FIVE_MINUTES)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 2)))\n mock.assertCalledWith('TIME_FORMAT')\n\n def test_hour_resolution_within_day(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2013, 1, 2)),\n condense.HOURS)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 2)))\n mock.assertCalledWith('TIME_FORMAT')\n\n def test_no_resolution_within_24h(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1, 12)),\n self.timezone.localize(datetime.datetime(2013, 1, 2, 12)))\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(\n datetime.datetime(2013, 1, 1, 12)))\n mock.assertCalledWith('SHORT_DATETIME_FORMAT')\n\n def test_minutes_resolution_within_24h(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1, 12)),\n self.timezone.localize(datetime.datetime(2013, 1, 2, 12)),\n condense.MINUTES)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(\n datetime.datetime(2013, 1, 1, 12)))\n mock.assertCalledWith('SHORT_DATETIME_FORMAT')\n\n def test_five_minutes_resolution_within_24h(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1, 12)),\n self.timezone.localize(datetime.datetime(2013, 1, 2, 12)),\n condense.FIVE_MINUTES)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(\n datetime.datetime(2013, 1, 1, 12)))\n mock.assertCalledWith('SHORT_DATETIME_FORMAT')\n\n def test_hour_resolution_within_24h(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1, 12)),\n self.timezone.localize(datetime.datetime(2013, 1, 2, 12)),\n condense.HOURS)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(\n datetime.datetime(2013, 1, 1, 12)))\n mock.assertCalledWith('SHORT_DATETIME_FORMAT')\n\n def test_day_resolution(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n condense.DAYS)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 1)))\n mock.assertCalledWith('SHORT_DATETIME_FORMAT')\n\n def test_month_resolution(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n condense.MONTHS)\n with patch('gridplatform.utils.condense._') as mock:\n formatter(self.timezone.localize(datetime.datetime(2014, 1, 1)))\n mock.assertCalledWith('%m %Y')\n\n def test_quarter_resolution(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n condense.QUARTERS)\n with patch('gridplatform.utils.condense._') as mock:\n formatter(self.timezone.localize(datetime.datetime(2014, 1, 1)))\n mock.assertCalledWith('Q{quarter} %Y')\n\n def test_year_resolution(self):\n formatter = condense.get_date_formatter(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n condense.YEARS)\n with patch('django.utils.formats.date_format') as mock:\n formatter(self.timezone.localize(datetime.datetime(2013, 1, 1)))\n mock.assertCalledWith('YEAR_FORMAT')\n\n\ndef test_view_a(request):\n pass\n\n\ndef test_view_b(request):\n pass\n\n\nclass OuterModel(models.Model):\n name = models.CharField(max_length=16)\n\n\nclass InnerModel(models.Model):\n inner = models.CharField(max_length=8)\n\n\nclass InnerModelForm(ModelForm):\n class Meta:\n model = InnerModel\n\n\nclass UnitConverterBasesTest(TestCase):\n \"\"\"\n The L{preferred_unit_bases} defines buckingham units suitable for storing a\n selection of other buckingham units that data needs to be converted to and\n from.\n \"\"\"\n\n def test_integer_conversion(self):\n \"\"\"\n Test that a large prime can be stored and recovered without noticable\n loss of precission for all unit and store unit combinations.\n \"\"\"\n large_prime = 797\n REQUIRED_PRECISSION = 7\n for unit, store_unit in preferred_unit_bases.iteritems():\n stored_number = int(\n PhysicalQuantity(large_prime, unit).convert(store_unit))\n loaded_number = float(PhysicalQuantity(\n stored_number, store_unit).convert(unit))\n self.assertAlmostEqual(\n large_prime, loaded_number, places=REQUIRED_PRECISSION,\n msg='%.8f did not equal large_prime=%d for unit=%s and '\n 'store_unit=%s within %d places' % (\n loaded_number, large_prime, unit, store_unit,\n REQUIRED_PRECISSION))\n\n\nclass FormatIdTest(TestCase):\n \"\"\"\n Tests for the format_id.py module.\n \"\"\"\n\n def test_format_mbus_enhanced(self):\n \"\"\"\n Test that format_mbus_enhanced does not crash when mbus medium is\n translated to a string outside the domain of ascii.\n \"\"\"\n with translation.override(\"da-dk\"):\n format_mbus_enhanced(0xFFFFFF0A)\n\n\nclass TestFirstLast(TestCase):\n\n def test_empty_list(self):\n \"\"\"\n Check that L{first_last} raises value error on empty list.\n \"\"\"\n with self.assertRaises(ValueError):\n first_last([])\n\n def test_one_element_list(self):\n \"\"\"\n Check that L{first_last} return the same first and last value for a\n list with one element.\n \"\"\"\n self.assertEqual(\n (1, 1),\n first_last([1]))\n\n def test_empty_generator(self):\n \"\"\"\n Check that L{first_last} raises value error on empty generator.\n \"\"\"\n def empty_generator():\n if False:\n yield 1\n\n with self.assertRaises(ValueError):\n first_last(empty_generator())\n\n\nclass StoreBaseModel(StoreSubclass):\n basefield = models.CharField(max_length=16)\n\n def __repr__(self):\n return 'StoreBaseModel(basefield=%s)' % self.basefield\n\n\nclass StoreSubmodel(StoreBaseModel):\n subfield = models.CharField(max_length=16)\n\n def __unicode__(self):\n return 'STORE SUB MODEL INSTANCE'\n\n def __repr__(self):\n return 'StoreSubmodel(basefield=%s, subfield=%s)' % (self.basefield,\n self.subfield)\n\n def combined_fields(self):\n return '{}+{}'.format(self.basefield, self.subfield)\n\n\nclass StoreProxyModel(StoreSubmodel):\n class Meta:\n proxy = True\n\n def __repr__(self):\n return 'StoreProxyModel(basefield=%s, subfield=%s)' % (self.basefield,\n self.subfield)\n\n def combined_fields(self):\n return '{}-{}'.format(self.basefield, self.subfield)\n\n\nclass StoreSubclassTest(TestCase):\n def test_base(self):\n obj = StoreBaseModel.objects.create(basefield='hello')\n loaded = StoreBaseModel.objects.get(pk=obj.id).subclass_instance\n self.assertIsNot(obj, loaded)\n self.assertEqual(obj, loaded)\n self.assertEqual(obj.__class__, loaded.__class__)\n\n def test_submodel(self):\n obj = StoreSubmodel.objects.create(basefield='hello', subfield='world')\n loaded = StoreBaseModel.objects.get(pk=obj.id).subclass_instance\n self.assertIsNot(obj, loaded)\n self.assertEqual(obj, loaded)\n self.assertEqual(obj.__class__, loaded.__class__)\n\n def test_proxy(self):\n obj = StoreProxyModel.objects.create(\n basefield='hello', subfield='world')\n loaded = StoreBaseModel.objects.get(pk=obj.id).subclass_instance\n self.assertIsNot(obj, loaded)\n self.assertEqual(obj, loaded)\n self.assertEqual(obj.__class__, loaded.__class__)\n\n def test_submodel_load(self):\n obj = StoreProxyModel.objects.create(\n basefield='hello', subfield='world')\n loaded_submodel = StoreSubmodel.objects.get(pk=obj.id)\n loaded_proxy = loaded_submodel.subclass_instance\n self.assertIsNot(obj, loaded_submodel)\n self.assertIsNot(obj, loaded_proxy)\n self.assertIsNot(loaded_submodel, loaded_proxy)\n self.assertIsInstance(loaded_submodel, StoreSubmodel)\n self.assertNotIsInstance(loaded_submodel, StoreProxyModel)\n self.assertIsInstance(loaded_proxy, StoreProxyModel)\n self.assertNotEqual(loaded_submodel.combined_fields(),\n loaded_proxy.combined_fields())\n\n def test_subclass_model_filter(self):\n StoreProxyModel.objects.create(\n basefield='how are you',\n subfield='gentlemen')\n\n StoreSubmodel.objects.create(\n basefield='I am not',\n subfield='an octopus')\n\n StoreBaseModel.objects.create(\n basefield='I am a free man')\n\n self.assertEqual(\n 'how are you-gentlemen',\n StoreBaseModel.objects.get(\n subclass__model='storeproxymodel').\n subclass_instance.combined_fields())\n\n self.assertEqual(\n 'I am not+an octopus',\n StoreBaseModel.objects.get(\n subclass__model='storesubmodel').\n subclass_instance.combined_fields())\n\n self.assertEqual(\n 'I am a free man',\n StoreBaseModel.objects.get(\n subclass__model='storebasemodel').\n subclass_instance.basefield)\n\n def test_subclass_filter(self):\n base_model = StoreBaseModel.objects.create(\n basefield='I am a free man')\n\n submodel = StoreSubmodel.objects.create(\n basefield='I am not',\n subfield='an octopus')\n\n proxy_model = StoreProxyModel.objects.create(\n basefield='how are you',\n subfield='gentlemen')\n\n self.assertIn(base_model,\n [m.subclass_instance for m in\n StoreBaseModel.objects.all()])\n self.assertIn(submodel,\n [m.subclass_instance for m in\n StoreBaseModel.objects.all()])\n self.assertIn(proxy_model,\n [m.subclass_instance for m in\n StoreBaseModel.objects.all()])\n\n self.assertIn(base_model,\n [m.subclass_instance for m in\n StoreBaseModel.objects.subclass_only().all()])\n self.assertIn(submodel,\n [m.subclass_instance for m in\n StoreBaseModel.objects.subclass_only().all()])\n self.assertIn(proxy_model,\n [m.subclass_instance for m in\n StoreBaseModel.objects.subclass_only().all()])\n\n self.assertNotIn(base_model,\n [m.subclass_instance for m in\n StoreSubmodel.objects.subclass_only().all()])\n self.assertIn(submodel,\n [m.subclass_instance for m in\n StoreSubmodel.objects.subclass_only().all()])\n self.assertIn(proxy_model,\n [m.subclass_instance for m in\n StoreSubmodel.objects.subclass_only().all()])\n\n self.assertNotIn(base_model,\n [m.subclass_instance for m in\n StoreProxyModel.objects.subclass_only().all()])\n self.assertNotIn(submodel,\n [m.subclass_instance for m in\n StoreProxyModel.objects.subclass_only().all()])\n self.assertIn(proxy_model,\n [m.subclass_instance for m in\n StoreProxyModel.objects.subclass_only().all()])\n\n def test_unicode_no_delegation(self):\n base_model = StoreBaseModel.objects.create(\n basefield='I am a free man')\n unicode(base_model)\n\n def test_unicode_delegation(self):\n submodel = StoreSubmodel.objects.create(\n basefield='I am not',\n subfield='an octopus')\n base_model = StoreBaseModel.objects.get(id=submodel.id)\n\n self.assertEqual(\n unicode(base_model),\n 'STORE SUB MODEL INSTANCE')\n\n def test_repr(self):\n repr(StoreBaseModel)\n\n\nclass IterTest(TestCase):\n def test_pairwise(self):\n self.assertListEqual(\n list(pairwise([1, 2, 3])),\n [(1, 2), (2, 3)])\n\n def test_nwise_2(self):\n self.assertListEqual(\n list(nwise([1, 2, 3], 2)),\n [(1, 2), (2, 3)])\n\n def test_nwise_5(self):\n self.assertListEqual(\n list(nwise([1, 2, 3, 4, 5, 6, 7], 5)),\n [(1, 2, 3, 4, 5), (2, 3, 4, 5, 6), (3, 4, 5, 6, 7)])\n\n def test_pairwise_extended(self):\n self.assertListEqual(\n list(pairwise_extended([1, 2, 3])),\n [(1, 2), (2, 3), (3, None)])\n\n def test_tee_lookahead(self):\n def gen():\n acc = 0\n while True:\n yield acc\n acc += 1\n it, = itertools.tee(gen(), 1)\n self.assertEqual(next(it), 0)\n self.assertEqual(tee_lookahead(it, 2), 3)\n self.assertEqual(next(it), 1)\n\n def test_count_extended(self):\n it = count_extended(datetime.date(2000, 1, 1),\n datetime.timedelta(days=1))\n self.assertListEqual(\n list(itertools.islice(it, 5)),\n [datetime.date(2000, 1, 1),\n datetime.date(2000, 1, 2),\n datetime.date(2000, 1, 3),\n datetime.date(2000, 1, 4),\n datetime.date(2000, 1, 5)])\n\n\nclass UnitConverterBaseTest(object):\n def test_extract_value(self):\n raise NotImplementedError(\n 'This method is not implemented by %r' % self.__class__)\n\n def test_display(self):\n self.assertTrue(unicode(self.preferred_unit.get_display_unit()))\n\n\nclass PhysicalUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = PhysicalUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(1000000, 'milliwatt*hour')),\n 1)\n\n\nclass RelativeCelsiusUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = RelativeCelsiusUnitConverter()\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(100, 'kelvin')),\n 100)\n\n\nclass AbsoluteCelsiusUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = AbsoluteCelsiusUnitConverter()\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity('273.15', 'kelvin')),\n 0)\n\n\nclass RelativeFahrenheitUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = RelativeFahrenheitUnitConverter()\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(72, 'rankine')),\n 72)\n\n\nclass AbsoluteFahrenheitUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = AbsoluteFahrenheitUnitConverter()\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity('459.67', 'rankine')),\n 0)\n\n\nclass PersonsENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = PersonsENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(100, 365), 'kilowatt*hour*person^-1*day^-1')),\n 100)\n\n\nclass AreaENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n self.preferred_unit = AreaENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(100, 365), 'kilowatt*hour*meter^-2*day^-1')),\n 100)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionAENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n with replace_customer(customer):\n self.preferred_unit = ProductionAENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n 42000, 'watt*hour*production_a^-1')),\n 42)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionBENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n with replace_customer(customer):\n self.preferred_unit = ProductionBENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n 42000, 'watt*hour*production_b^-1')),\n 42)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionCENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n with replace_customer(customer):\n self.preferred_unit = ProductionCENPIUnitConverter(\n 'meter*meter*meter')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n 42000, 'liter*production_c^-1')),\n 42)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionDENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n with replace_customer(customer):\n self.preferred_unit = ProductionDENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n 42000, 'watt*hour*production_d^-1')),\n 42)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionEENPIUnitConverterTest(UnitConverterBaseTest, TestCase):\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n with replace_customer(customer):\n self.preferred_unit = ProductionEENPIUnitConverter('kilowatt*hour')\n\n def test_extract_value(self):\n self.assertEqual(\n self.preferred_unit.extract_value(\n PhysicalQuantity(\n 42000, 'watt*hour*production_e^-1')),\n 42)\n\n\nclass PermissionModel(models.Model):\n somefield = models.CharField(max_length=50)\n\n\nclass PermissionRelatedModel(models.Model):\n base = models.ForeignKey(PermissionModel)\n otherfield = models.CharField(max_length=20)\n\n\nclass PermissionRelatedModelInline(InlineFormSet):\n model = PermissionRelatedModel\n\n\nclass GenericViewPermissionTest(TestCase):\n def test_createview(self):\n class MyView(generic_views.CreateView):\n model = PermissionModel\n unit = MyView()\n self.assertEqual(\n unit.permission_required, 'utils.add_permissionmodel')\n\n def test_deleteview(self):\n class MyView(generic_views.DeleteView):\n model = PermissionModel\n unit = MyView()\n self.assertEqual(\n unit.permission_required, 'utils.delete_permissionmodel')\n\n def test_updateview(self):\n class MyView(generic_views.UpdateView):\n model = PermissionModel\n unit = MyView()\n self.assertEqual(\n unit.permission_required, 'utils.change_permissionmodel')\n\n def test_modelformsetview(self):\n class MyView(generic_views.ModelFormSetView):\n model = PermissionModel\n unit = MyView()\n self.assertEqual(\n unit.permissions, {\n 'all': list({\n 'utils.add_permissionmodel',\n 'utils.change_permissionmodel',\n 'utils.delete_permissionmodel',\n }),\n })\n\n def test_inlineformsetview(self):\n class MyView(generic_views.InlineFormSetView):\n model = PermissionModel\n inline_model = PermissionRelatedModel\n unit = MyView()\n self.assertEqual(\n unit.permissions, {\n 'all': list({\n 'utils.add_permissionrelatedmodel',\n 'utils.change_permissionrelatedmodel',\n 'utils.delete_permissionrelatedmodel',\n }),\n })\n\n def test_createwithinlines(self):\n class MyView(generic_views.CreateWithInlinesView):\n model = PermissionModel\n inlines = [PermissionRelatedModelInline]\n unit = MyView()\n self.assertEqual(\n unit.permissions, {\n 'all': list({\n 'utils.add_permissionmodel',\n 'utils.add_permissionrelatedmodel',\n }),\n })\n\n def test_updatewithinlines(self):\n class MyView(generic_views.UpdateWithInlinesView):\n model = PermissionModel\n inlines = [PermissionRelatedModelInline]\n unit = MyView()\n self.assertEqual(\n set(unit.permissions['all']),\n {\n 'utils.add_permissionmodel',\n 'utils.change_permissionmodel',\n 'utils.delete_permissionmodel',\n 'utils.add_permissionrelatedmodel',\n 'utils.change_permissionrelatedmodel',\n 'utils.delete_permissionrelatedmodel',\n })\n\n\nclass UnitConversionTest(SimpleTestCase):\n def test_construction(self):\n self.assertNotEqual(\n PhysicalQuantity(10, 'meter*second^-1'),\n PhysicalQuantity(10, 'meter/second^2'))\n self.assertEqual(\n PhysicalQuantity(2, 'decimeter^3'),\n PhysicalQuantity(2, 'liter'))\n self.assertEqual(\n PhysicalQuantity('10', 'meter'),\n PhysicalQuantity('10.0', 'meter'))\n self.assertEqual(\n PhysicalQuantity('0.5', 'meter'),\n PhysicalQuantity('1/2', 'meter'))\n\n def test_construction_error(self):\n with self.assertRaises(UnitParseError):\n PhysicalQuantity(10, 'meter/second/liter')\n with self.assertRaises(UnitParseError):\n PhysicalQuantity(10, 'meter/second*liter')\n\n def test_add(self):\n a = PhysicalQuantity(2, 'volt')\n b = PhysicalQuantity(3, 'volt')\n self.assertEqual(\n a + b,\n PhysicalQuantity(5, 'volt'))\n self.assertEqual(\n (a + b),\n (b + a))\n with self.assertRaises(NotPhysicalQuantityError):\n a + 5\n with self.assertRaises(NotPhysicalQuantityError):\n PhysicalQuantity(2) + 5\n\n def test_sub(self):\n a = PhysicalQuantity(2, 'volt')\n b = PhysicalQuantity(3, 'volt')\n self.assertEqual(\n a - b,\n PhysicalQuantity(-1, 'volt'))\n self.assertEqual(\n b - a,\n PhysicalQuantity(1, 'volt'))\n\n def test_mul(self):\n self.assertEqual(\n PhysicalQuantity(2, 'meter') * 2,\n PhysicalQuantity(4, 'meter'))\n self.assertEqual(\n PhysicalQuantity(4, 'gram') * PhysicalQuantity(7, 'gram'),\n PhysicalQuantity(28, 'gram^2'))\n self.assertEqual(\n 3 * PhysicalQuantity(2, 'ampere'),\n PhysicalQuantity(6, 'ampere'))\n\n def test_div(self):\n self.assertEqual(\n PhysicalQuantity(2) / 1,\n PhysicalQuantity(2))\n self.assertEqual(\n PhysicalQuantity(4) / PhysicalQuantity(7, 'second'),\n PhysicalQuantity('4/7', 'second^-1'))\n self.assertEqual(\n PhysicalQuantity(4, 'meter') / PhysicalQuantity(2, 'meter'),\n PhysicalQuantity(2))\n self.assertEqual(\n 1 / PhysicalQuantity(2, 'ampere'),\n PhysicalQuantity('1/2', 'ampere^-1'))\n\n def test_pow(self):\n self.assertEqual(\n PhysicalQuantity(2, 'meter^2') ** 2,\n PhysicalQuantity(4, 'meter^4'))\n\n def test_lt(self):\n a = PhysicalQuantity(2, 'meter')\n b = PhysicalQuantity(1, 'kilometer')\n c = PhysicalQuantity(3, 'meter^2')\n self.assertLess(a, b)\n with self.assertRaises(IncompatibleUnitsError):\n a < c\n\n def test_le(self):\n a = PhysicalQuantity(1000, 'meter')\n b = PhysicalQuantity(1, 'kilometer')\n self.assertLessEqual(a, b)\n\n def test_gt(self):\n a = PhysicalQuantity(1002, 'meter')\n b = PhysicalQuantity(1, 'kilometer')\n self.assertGreater(a, b)\n\n def test_ge(self):\n a = PhysicalQuantity(1000, 'meter')\n b = PhysicalQuantity(1, 'kilometer')\n self.assertGreaterEqual(a, b)\n\n def test_nonzero(self):\n self.assertTrue(PhysicalQuantity(10, 'meter'))\n self.assertFalse(PhysicalQuantity(0, 'liter'))\n\n def test_units(self):\n self.assertEqual(\n PhysicalQuantity(10, 'meter*kilometer*centimeter').units,\n 'meter^3')\n self.assertEqual(\n PhysicalQuantity(1, 'meter*liter').units,\n 'meter^4')\n self.assertEqual(\n PhysicalQuantity(1, 'gram*meter*gram').units,\n 'meter*gram^2')\n\n def test_convert(self):\n self.assertEqual(\n PhysicalQuantity(0, 'meter*second^-1').convert(\n 'kilometer*hour^-1'),\n 0)\n self.assertEqual(\n PhysicalQuantity(1, 'meter^3').convert('liter'),\n 1000)\n self.assertIsInstance(\n PhysicalQuantity(1, 'kilometer*hour^-1').convert(\n 'kilometer*hour^-1'),\n Fraction)\n with self.assertRaises(IncompatibleUnitsError):\n PhysicalQuantity(1, 'kilometer').convert('kelvin')\n\n def test_compatible_unit(self):\n self.assertTrue(PhysicalQuantity(1, 'meter').compatible_unit('foot'))\n self.assertFalse(PhysicalQuantity(1, 'kilometer').compatible_unit(\n 'watt'))\n\n def test_compatible_units(self):\n self.assertTrue(PhysicalQuantity.compatible_units('meter', 'foot'))\n self.assertFalse(PhysicalQuantity.compatible_units('meter', 'watt'))\n\n def test_same_unit(self):\n self.assertTrue(PhysicalQuantity.same_unit('meter*meter', 'meter^2'))\n self.assertFalse(PhysicalQuantity.same_unit('meter', 'foot'))\n self.assertFalse(PhysicalQuantity.same_unit('meter', 'kelvin'))\n\n def test_repr(self):\n self.assertEqual(\n repr(PhysicalQuantity(100, 'meter')),\n \"PhysicalQuantity(100, u'meter')\")\n a = PhysicalQuantity(1, 'kilometer')\n b = PhysicalQuantity(5, 'second')\n self.assertEqual(\n eval(repr(a)),\n a)\n self.assertEqual(\n eval(repr(a * b)),\n a * b)\n\n def test_str(self):\n self.assertEqual(\n str(PhysicalQuantity(100, 'meter')),\n '100 meter')\n self.assertEqual(\n str(PhysicalQuantity(10, 'kilogram')),\n '10000 gram')\n self.assertEqual(\n str(PhysicalQuantity('0.5', 'second')),\n '1/2 second')\n\n def test_unit_unit(self):\n unit = PhysicalQuantity(1, 'hectoproduction_a')\n self.assertEqual(unit.units, 'production_a')\n self.assertEqual(unit.value, 100)\n self.assertEqual(unit, PhysicalQuantity(100, 'production_a'))\n\n\nclass UtilityTypesTest(TestCase):\n def test_electricity_in_meter_utility_type_choices(self):\n self.assertIn(\n utilitytypes.METER_CHOICES.electricity,\n [\n db_value for db_value, _ in\n utilitytypes.METER_CHOICES])\n\n\nclass ExampleBreadcrumbsBuilder(object):\n def build_root_page_breadcrumbs(self):\n return Breadcrumbs((Breadcrumb('Root Page', 'http://test-url/'),))\n\n def build_node_page_breadcrumbs(self):\n return self.build_root_page_breadcrumbs() + \\\n Breadcrumb(self.node_page_name, 'http://test-url/node/')\n\n def build_leaf_page_breadcrumbs(self):\n return self.build_node_page_breadcrumbs() + \\\n Breadcrumb('Leaf Page')\n\n\nclass BreadcrumbsBaseTest(TestCase):\n def test_example_usage(self):\n breadcrumbs_builder = ExampleBreadcrumbsBuilder()\n breadcrumbs_builder.node_page_name = 'Node Page'\n\n iterator = iter(breadcrumbs_builder.build_leaf_page_breadcrumbs())\n self.assertEqual(\n next(iterator), Breadcrumb('Root Page', 'http://test-url/'))\n self.assertEqual(\n next(iterator), Breadcrumb('Node Page', 'http://test-url/node/'))\n self.assertEqual(next(iterator), Breadcrumb('Leaf Page', None))\n with self.assertRaises(StopIteration):\n next(iterator)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass HomeViewBaseTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.factory = RequestFactory()\n\n class HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return \"redirect_to_url/%s\" % customer_id\n\n def get_choose_customer_url(self):\n return \"choose_customer_url\"\n\n self.view = HomeView.as_view()\n self.session = SessionMiddleware()\n\n def test_no_customers(self):\n request = self.factory.get('/')\n request.user = User(name_plain='test user')\n request.user.has_perm = lambda perm: True\n self.session.process_request(request)\n response = self.view(request)\n\n self.assertEqual(response.status_code, 301)\n self.assertEqual(\n response.url, reverse('provider_site:customer-list'))\n\n def test_one_customer(self):\n self.customer = Customer(name_plain='test customer')\n self.customer.save()\n\n request = self.factory.get('/')\n request.user = User(name_plain='test user')\n request.user.has_perm = lambda perm: True\n self.session.process_request(request)\n response = self.view(request)\n self.assertEqual(response.status_code, 301)\n self.assertEqual(\n response.url, \"redirect_to_url/%s\" % self.customer.id)\n\n def test_multiple_customers_no_session(self):\n self.customer = Customer(name_plain='test customer')\n self.customer.save()\n\n self.customer = Customer(name_plain='test customer2')\n self.customer.save()\n\n request = self.factory.get('/')\n request.user = User(name_plain='test user')\n request.user.has_perm = lambda perm: True\n self.session.process_request(request)\n response = self.view(request)\n self.assertEqual(response.status_code, 301)\n self.assertEqual(\n response.url, \"choose_customer_url\")\n\n def test_multiple_customers_with_session(self):\n self.customer = Customer(name_plain='test customer')\n self.customer.save()\n\n self.customer2 = Customer(name_plain='test customer2')\n self.customer2.save()\n\n request = self.factory.get('/')\n request.user = User(name_plain='test user')\n request.user.has_perm = lambda perm: True\n self.session.process_request(request)\n request.session['chosen_customer_id'] = self.customer2.id\n response = self.view(request)\n self.assertEqual(response.status_code, 301)\n self.assertEqual(\n response.url, \"redirect_to_url/%s\" % self.customer2.id)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass CustomerViewBaseTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer(name_plain='test customer')\n self.customer.save()\n self.factory = RequestFactory()\n\n class CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return \"redirect_to_url/%s\" % customer_id\n\n self.view = CustomerView.as_view()\n self.session = SessionMiddleware()\n\n def test_customer_in_session(self):\n request = self.factory.get('/')\n request.user = User(name_plain='test user')\n request.user.has_perm = lambda perm: True\n self.session.process_request(request)\n response = self.view(request, customer_id=self.customer.id)\n self.assertEqual(response.status_code, 301)\n self.assertEqual(\n response.url, \"redirect_to_url/%s\" % self.customer.id)\n self.assertEqual(\n request.session['chosen_customer_id'], self.customer.id)\n\n\nclass TestTimePeriodModel(models.Model):\n from_timestamp = models.DateTimeField()\n to_timestamp = models.DateTimeField()\n\n\nclass TestTimePeriodModelForm(TimePeriodModelForm):\n class Meta:\n model = TestTimePeriodModel\n fields = ()\n\n def _get_timezone(self):\n return pytz.timezone('Europe/Copenhagen')\n\n\nclass TimePeriodModelFormTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_from_time_initialization_from_instance(self):\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n form = TestTimePeriodModelForm(instance=instance)\n self.assertEqual(form.initial['from_date'], datetime.date(2014, 1, 1))\n self.assertEqual(form.initial['from_hour'], 0)\n\n def test_to_time_initialization_from_instance_midnight(self):\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n form = TestTimePeriodModelForm(instance=instance)\n self.assertEqual(form.initial['to_date'], datetime.date(2014, 1, 1))\n self.assertEqual(form.initial['to_hour'], 24)\n\n def test_to_time_initialization_from_instance_noon(self):\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)))\n\n form = TestTimePeriodModelForm(instance=instance)\n self.assertEqual(form.initial['to_date'], datetime.date(2014, 1, 1))\n self.assertEqual(form.initial['to_hour'], 12)\n\n def test_from_time_clean(self):\n form = TestTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': 0,\n 'to_date': '2014-01-01',\n 'to_hour': 12})\n self.assertTrue(form.is_valid())\n self.assertEqual(\n form.instance.from_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 1)))\n\n def test_from_time_clean_midnight(self):\n form = TestTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': 24,\n 'to_date': '2014-01-02',\n 'to_hour': 12})\n self.assertTrue(form.is_valid())\n self.assertEqual(\n form.instance.from_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_to_time_clean(self):\n form = TestTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': 0,\n 'to_date': '2014-01-01',\n 'to_hour': 12})\n self.assertTrue(form.is_valid())\n self.assertEqual(\n form.instance.to_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 1, 12)))\n\n def test_to_time_clean_midnight(self):\n form = TestTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': 0,\n 'to_date': '2014-01-01',\n 'to_hour': 24})\n self.assertTrue(form.is_valid())\n self.assertEqual(\n form.instance.to_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_invalid_from_time_does_not_alter_instance(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12))\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=from_timestamp, to_timestamp=to_timestamp)\n\n form = TestTimePeriodModelForm(data={\n 'from_date': '',\n 'from_hour': '',\n 'to_date': '2014-01-01',\n 'to_hour': 24}, instance=instance)\n self.assertFalse(form.is_valid())\n self.assertEquals(form.instance.from_timestamp, from_timestamp)\n\n def test_invalid_to_time_does_not_alter_instance(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12))\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=from_timestamp, to_timestamp=to_timestamp)\n\n form = TestTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': '0',\n 'to_date': '',\n 'to_hour': ''}, instance=instance)\n self.assertFalse(form.is_valid())\n self.assertEquals(form.instance.to_timestamp, to_timestamp)\n\n\nclass TestTimePeriodModel(models.Model):\n from_timestamp = models.DateTimeField()\n to_timestamp = models.DateTimeField()\n\n\nclass TestHalfOpenTimePeriodModelForm(HalfOpenTimePeriodModelForm):\n class Meta:\n model = TestTimePeriodModel\n fields = ()\n\n def _get_timezone(self):\n return pytz.timezone('Europe/Copenhagen')\n\n\nclass HalfOpenTimePeriodModelFormTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_cleared_to_date_alter_instance_to_timestamp(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12))\n instance = TestTimePeriodModel.objects.create(\n from_timestamp=from_timestamp, to_timestamp=to_timestamp)\n\n form = TestHalfOpenTimePeriodModelForm(data={\n 'from_date': '2014-01-01',\n 'from_hour': '0',\n 'to_date': '',\n 'to_hour': '24'}, instance=instance)\n self.assertTrue(form.is_valid())\n self.assertIsNone(form.instance.to_timestamp)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass PreviousMonthInitialValuesTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n\n def test_transition(self):\n timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 2, 1))\n with replace_customer(self.customer):\n initial = previous_month_initial_values(timestamp)\n\n self.assertEqual(initial['from_date'], datetime.date(2014, 1, 1))\n self.assertEqual(initial['to_date'], datetime.date(2014, 1, 31))\n self.assertEqual(initial['from_hour'], 0)\n self.assertEqual(initial['to_hour'], 24)\n\n def test_regular(self):\n timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 2, 15))\n with replace_customer(self.customer):\n initial = previous_month_initial_values(timestamp)\n\n self.assertEqual(initial['from_date'], datetime.date(2014, 1, 1))\n self.assertEqual(initial['to_date'], datetime.date(2014, 1, 31))\n self.assertEqual(initial['from_hour'], 0)\n self.assertEqual(initial['to_hour'], 24)\n\n def test_now(self):\n with replace_customer(self.customer):\n initial = previous_month_initial_values()\n self.assertIsInstance(initial['from_date'], datetime.date)\n self.assertIsInstance(initial['to_date'], datetime.date)\n self.assertEqual(initial['from_hour'], 0)\n self.assertEqual(initial['to_hour'], 24)\n\n\nclass VirtualBaseModel(StoreSubclass):\n @virtual\n def __unicode__(self):\n return 'Base class'\n\n @virtual\n def compute(self, a, b):\n return a + b\n\n\nclass VirtualSubModel(VirtualBaseModel):\n def __unicode__(self):\n return 'Subclass'\n\n @virtual\n def compute(self, a, b):\n return a * b\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestVirtual(TestCase):\n def test_base(self):\n obj = VirtualBaseModel.objects.create()\n loaded = VirtualBaseModel.objects.get(pk=obj.id)\n self.assertEqual(unicode(loaded), 'Base class')\n\n def test_submodel(self):\n obj = VirtualSubModel.objects.create()\n loaded = VirtualBaseModel.objects.get(pk=obj.id)\n self.assertEqual(unicode(loaded), 'Subclass')\n\n def test_parameterised(self):\n obj_base = VirtualBaseModel.objects.create()\n obj_sub = VirtualSubModel.objects.create()\n loaded_base = VirtualBaseModel.objects.get(pk=obj_base.id)\n loaded_sub = VirtualBaseModel.objects.get(pk=obj_sub.id)\n self.assertEqual(loaded_base.compute(2, 3), 5)\n self.assertEqual(loaded_sub.compute(2, 3), 6)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DateRangeModelMixinTest(TestCase):\n def test_empty_period(self):\n unit = DateRangeModelMixin(\n from_date=datetime.date(2000, 1, 2),\n to_date=datetime.date(2000, 1, 1))\n\n with self.assertRaises(ValidationError):\n unit.clean()\n\n def test_one_day_period(self):\n unit = DateRangeModelMixin(\n from_date=datetime.date(2000, 1, 1),\n to_date=datetime.date(2000, 1, 1))\n unit.clean()\n\n def test_default_period(self):\n with replace_customer(Customer(timezone=pytz.utc)):\n unit = DateRangeModelMixin()\n self.assertIsInstance(unit.from_date, datetime.date)\n self.assertIsNone(unit.to_date)\n unit.clean()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DateRangeModelMixinTimestampRangeIntersectionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_timestamp_within_range(self):\n daterangemodel = DateRangeModelMixin(\n from_date=datetime.date(2014, 1, 1))\n\n intersection = daterangemodel.timestamp_range_intersection(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone)\n\n self.assertEqual(\n intersection.from_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 1)))\n\n self.assertEqual(\n intersection.to_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_timestamp_before_range(self):\n daterangemodel = DateRangeModelMixin(\n from_date=datetime.date(2014, 1, 1))\n\n intersection = daterangemodel.timestamp_range_intersection(\n self.timezone.localize(datetime.datetime(2013, 1, 1)),\n self.timezone.localize(datetime.datetime(2013, 1, 2)),\n self.timezone)\n\n self.assertIsNone(intersection)\n\n def test_timestamp_after_range(self):\n daterangemodel = DateRangeModelMixin(\n from_date=datetime.date(2014, 1, 1),\n to_date=datetime.date(2014, 1, 2))\n\n intersection = daterangemodel.timestamp_range_intersection(\n self.timezone.localize(datetime.datetime(2014, 1, 3, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 4)),\n self.timezone)\n\n self.assertIsNone(intersection)\n\n def test_timestamp_overlap_range(self):\n daterangemodel = DateRangeModelMixin(\n from_date=datetime.date(2014, 1, 1))\n\n intersection = daterangemodel.timestamp_range_intersection(\n self.timezone.localize(datetime.datetime(2013, 12, 24)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone)\n\n self.assertEqual(\n intersection.from_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 1)))\n\n self.assertEqual(\n intersection.to_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n def test_timestamp_match_range(self):\n daterangemodel = DateRangeModelMixin(\n from_date=datetime.date(2014, 1, 1),\n to_date=datetime.date(2014, 1, 1))\n\n intersection = daterangemodel.timestamp_range_intersection(\n self.timezone.localize(datetime.datetime(2014, 1, 1)),\n self.timezone.localize(datetime.datetime(2014, 1, 2)),\n self.timezone)\n\n self.assertEqual(\n intersection.from_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 1)))\n\n self.assertEqual(\n intersection.to_timestamp,\n self.timezone.localize(datetime.datetime(2014, 1, 2)))\n\n\nclass DateRangeTestModelManager(\n DateRangeManagerMixin, models.Manager):\n pass\n\n\nclass DateRangeTestModel(DateRangeModelMixin):\n objects = DateRangeTestModelManager()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DateRangeManagerMixinTest(TestCase):\n def setUp(self):\n self.in_range = DateRangeTestModel.objects.create(\n from_date=datetime.date(2000, 1, 1))\n self.out_of_range = DateRangeTestModel.objects.create(\n from_date=datetime.date(2000, 1, 1),\n to_date=datetime.date(2001, 9, 11))\n\n def test_all(self):\n self.assertEqual(2, DateRangeTestModel.objects.all().count())\n\n def test_none_in_range(self):\n self.assertFalse(\n DateRangeTestModel.objects.in_range(\n from_date=datetime.date(1990, 1, 1),\n to_date=datetime.date(1999, 12, 31)).exists())\n\n def test_in_range(self):\n self.assertEqual(\n [self.in_range.id],\n list(\n DateRangeTestModel.objects.in_range(\n from_date=datetime.date(2002, 1, 1),\n to_date=datetime.date(2002, 1, 1)).\n values_list('id', flat=True)))\n\n\nclass TimestampRangeTestModelManager(\n TimestampRangeManagerMixin, models.Manager):\n pass\n\n\nclass TimestampRangeTestModel(TimestampRangeModelMixin):\n objects = TimestampRangeTestModelManager()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TimestampRangeManagerMixinTest(TestCase):\n def setUp(self):\n self.timezone = pytz.utc\n self.in_range = TimestampRangeTestModel.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2000, 1, 1)))\n self.out_of_range = TimestampRangeTestModel.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2000, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2001, 9, 11)))\n\n def test_all(self):\n self.assertEqual(2, TimestampRangeTestModel.objects.all().count())\n\n def test_none_in_range(self):\n self.assertFalse(\n TimestampRangeTestModel.objects.in_range(\n from_timestamp=self.timezone.localize(\n datetime.datetime(1990, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(1999, 12, 31))).exists())\n\n def test_in_range(self):\n self.assertEqual(\n [self.in_range.id],\n list(\n TimestampRangeTestModel.objects.in_range(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2002, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2002, 1, 1))).\n values_list('id', flat=True)))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TimestampRangeModelMixinTest(TestCase):\n def setUp(self):\n self.timezone = pytz.utc\n\n def test_clean_no_to_timestamp_success(self):\n instance = TimestampRangeTestModel(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n instance.clean()\n\n def test_clean_success(self):\n instance = TimestampRangeTestModel(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n instance.clean()\n\n def test_clean_empty_lifespan(self):\n instance = TimestampRangeTestModel(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n with self.assertRaises(ValidationError):\n instance.clean()\n\n def test_unicode_without_to_timestamp(self):\n instance = TimestampRangeTestModel(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n\n unicode(\n instance.format_timestamp_range_unicode('pøp cörn', self.timezone))\n\n def test_unicode_with_to_timestamp(self):\n instance = TimestampRangeTestModel(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n\n unicode(\n instance.format_timestamp_range_unicode('pøp cörn', self.timezone))\n\n\nclass SumOrNoneTest(TestCase):\n def test_empty_sum(self):\n self.assertIsNone(sum_or_none([]))\n\n def test_sum_of_physical_quantities(self):\n self.assertEqual(\n PhysicalQuantity(sum(range(4)), 'meter'),\n sum_or_none(PhysicalQuantity(i, 'meter') for i in range(4)))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass ValidDateForDataSequenceTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(timezone=self.timezone)\n\n self.consumption1 = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n self.consumption2 = Consumption.objects.create(\n unit='kilowatt*hour', customer=self.customer)\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n datasequence=self.consumption1,\n value=423,\n unit='kilowatt*hour')\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 2, 5)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 2, 5)),\n datasequence=self.consumption2,\n value=423,\n unit='kilowatt*hour')\n\n def test_next_valid_date_for_datasequence(self):\n self.assertEqual(\n datetime.date(2014, 2, 5),\n next_valid_date_for_datasequence(\n [self.consumption1, self.consumption2],\n datetime.date(2014, 1, 15),\n self.timezone))\n\n def test_previous_valid_date_for_datasequence(self):\n self.assertEqual(\n datetime.date(2013, 12, 31),\n previous_valid_date_for_datasequence(\n [self.consumption1, self.consumption2],\n datetime.date(2014, 1, 15),\n self.timezone))\n\n\nclass TestYearWeekPeriodForm(YearWeekPeriodForm):\n def _get_timezone(self):\n return pytz.timezone('Europe/Copenhagen')\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass YearWeakPeriodFormTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_get_timestamps(self):\n form = TestYearWeekPeriodForm(data={'week': 1, 'year': 2014})\n form.is_valid()\n self.assertEqual(\n (self.timezone.localize(datetime.datetime(2013, 12, 30, 0, 0)),\n self.timezone.localize(datetime.datetime(2014, 1, 6, 0, 0))),\n form.get_timestamps())\n\n def test_get_timestamps_middle_year(self):\n form = TestYearWeekPeriodForm(data={'week': 25, 'year': 2014})\n form.is_valid()\n self.assertEqual(\n (self.timezone.localize(datetime.datetime(2014, 6, 16, 0, 0)),\n self.timezone.localize(datetime.datetime(2014, 6, 23, 0, 0))),\n form.get_timestamps())\n\n def test_no_week_53(self):\n form = TestYearWeekPeriodForm(data={'week': 53, 'year': 2005})\n form.is_valid()\n with self.assertRaises(ValidationError):\n form.clean()\n\n def test_initial_values(self):\n form = TestYearWeekPeriodForm(data=this_week_initial_values(\n self.timezone.localize(datetime.datetime(2014, 1, 3, 0, 0))))\n form.is_valid()\n self.assertEqual(\n (self.timezone.localize(datetime.datetime(2013, 12, 30, 0, 0)),\n self.timezone.localize(datetime.datetime(2014, 1, 6, 0, 0))),\n form.get_timestamps())\n" }, { "alpha_fraction": 0.6517142653465271, "alphanum_fraction": 0.6520000100135803, "avg_line_length": 37.46154022216797, "blob_id": "c9a8b1a5dd677b1ea7bda58a4a3b388ec8be0382", "content_id": "a1ee76c39ce37388fd16d2fd0afed7c4feea27e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3500, "license_type": "no_license", "max_line_length": 77, "num_lines": 91, "path": "/legacy/measurementpoints/models/link.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .dataseries import DataSeries\n\n\nclass Link(DataSeries):\n \"\"\"\n A L{Link} is used to make a C{target} L{DataSeries} appear as a\n L{DataSeries} in another graph.\n\n @invariant: The C{unit} must be the same as for the C{target}\n L{DataSeries}. This is a precondition of all sample related methods,\n because they are forwarded to their C{target} counterpart.\n \"\"\"\n target = models.ForeignKey(DataSeries, on_delete=models.PROTECT,\n related_name='link_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('link')\n verbose_name_plural = _('link')\n app_label = 'measurementpoints'\n\n def clean(self):\n \"\"\"\n L{Link} specialization of C{Model.clean()}.\n\n @postcondition: If C{target} is set, the class invariant holds.\n \"\"\"\n self.unit = self.target.subclass_instance.unit\n self._assert_invariants()\n return super(Link, self).clean()\n\n def save(self, *args, **kwargs):\n self._assert_invariants()\n return super(Link, self).save(*args, **kwargs)\n\n def _assert_invariants(self):\n assert self.unit == self.target.subclass_instance.unit, \\\n '%s != %s' % (self.unit, self.target.subclass_instance.unit)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n self._assert_invariants()\n return self.target.subclass_instance.get_samples(\n from_timestamp, to_timestamp)\n\n def _get_condensed_samples(self, from_timestamp,\n sample_resolution, to_timestamp):\n self._assert_invariants()\n return self.target.subclass_instance.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n\n def _interpolate_extrapolate_sample(self, timestamp,\n data_before=None, data_after=None):\n self._assert_invariants()\n return self.target.subclass_instance._interpolate_extrapolate_sample(\n timestamp, data_before=data_before, data_after=data_after)\n\n def calculate_development(self, from_timestamp, to_timestamp):\n self._assert_invariants()\n return self.target.subclass_instance.calculate_development(\n from_timestamp, to_timestamp)\n\n def calculate_cost(self, from_timestamp, to_timestamp, consumption=None):\n self._assert_invariants()\n return self.target.subclass_instance.calculate_cost(\n from_timestamp, to_timestamp, consumption=consumption)\n\n def depends_on(self):\n return self.target.subclass_instance.depends_on() + [\n self.target.subclass_instance]\n\n def latest_sample(self, from_timestamp, to_timestamp):\n self._assert_invariants()\n return self.target.subclass_instance.latest_sample(\n from_timestamp, to_timestamp)\n\n def aggregated_samples(self, from_timestamp, to_timestamp):\n self._assert_invariants()\n return self.target.subclass_instance.aggregated_samples(\n from_timestamp, to_timestamp)\n\n def get_recursive_condense_resolution(self, resolution):\n # Whatever is efficient for the target, ought to be efficient for\n # the link.\n return self.target.subclass_instance.\\\n get_recursive_condense_resolution(resolution)\n" }, { "alpha_fraction": 0.6663479804992676, "alphanum_fraction": 0.6673040390014648, "avg_line_length": 29.764705657958984, "blob_id": "fae204eac88b978b755382048ded43f268a0790b", "content_id": "8e8435f8988e18ba35a02b6720df683b4bd684fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1046, "license_type": "no_license", "max_line_length": 80, "num_lines": 34, "path": "/gridplatform/encryption/shell.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth import authenticate\n\nfrom gridplatform import trackuser\n\nfrom .base import _store\nfrom .base import EncryptionContext\n\n\nclass Request(object):\n \"\"\"\n Class for emulating request from shell. Sets up current user, private key\n and encryption context upon construction.\n \"\"\"\n def __init__(self, username, password):\n \"\"\"\n Authenticates with given user name and password.\n\n :param username: Given user name.\n :param password: Given password.\n \"\"\"\n self.user = authenticate(username=username, password=password)\n trackuser._store.user = self.user\n _store.private_key = self.user.decrypt_private_key(password)\n _store.encryption_context = EncryptionContext()\n\n def __unicode__(self):\n \"\"\"\n The text representation are the keys held by current encryption context.\n \"\"\"\n return unicode(self.encryption_context.keys())\n" }, { "alpha_fraction": 0.6797158122062683, "alphanum_fraction": 0.6830410957336426, "avg_line_length": 32.92820358276367, "blob_id": "23e5f3c351a7dc7d0a9dd263833008c0ea5f09c4", "content_id": "50b44610185059029bffa43c2648cc726ea45880", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6616, "license_type": "no_license", "max_line_length": 79, "num_lines": 195, "path": "/gridplatform/consumptions/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom collections import defaultdict\n\nfrom gridplatform.trackuser.tasks import task\nfrom gridplatform.utils import condense\nfrom gridplatform.datasequences.utils import add_ranged_sample_sequences\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .models import ConsumptionGroup\nfrom .models import MainConsumption\nfrom .models import Consumption\n\n\n@task(bind=True)\ndef net_cost_sum_and_costcompensation_amount_task(\n task, consumptiongroup_ids, from_timestamp, to_timestamp):\n consumptiongroups = ConsumptionGroup.objects.filter(\n id__in=consumptiongroup_ids)\n count = len(consumptiongroups)\n\n result = {}\n\n task.set_progress(0, count)\n for n, consumptiongroup in enumerate(consumptiongroups):\n result[consumptiongroup.id] = {\n 'net_cost_sum': consumptiongroup.net_cost_sum(\n from_timestamp, to_timestamp),\n 'costcompensation_amount_sum': (\n consumptiongroup.costcompensation_amount_sum(\n from_timestamp, to_timestamp)),\n }\n\n task.set_progress(n + 1, count)\n\n return result\n\n\n@task(bind=True)\ndef total_cost_sum_task(\n task, mainconsumption_ids, from_timestamp, to_timestamp):\n mainconsumptions = MainConsumption.objects.filter(\n id__in=mainconsumption_ids)\n count = len(mainconsumptions)\n\n result = {}\n\n task.set_progress(0, count)\n for n, mainconsumption in enumerate(mainconsumptions):\n result[mainconsumption.id] = mainconsumption.total_cost_sum(\n from_timestamp, to_timestamp)\n task.set_progress(n + 1, count)\n\n return result\n\n\n@task(bind=True)\ndef mainconsumptions_weekly_utility_task(\n task, mainconsumption_ids, from_timestamp, to_timestamp, utility_type):\n mainconsumptions = MainConsumption.objects.filter(\n id__in=mainconsumption_ids)\n total_mainconsumptions = len(mainconsumptions)\n\n before_from_timestamp = from_timestamp - datetime.timedelta(days=7)\n before_to_timestamp = to_timestamp - datetime.timedelta(days=7)\n\n measured = {'week_selected': [], 'week_before': []}\n for n, mainconsumption in enumerate(mainconsumptions):\n task.set_progress(n, total_mainconsumptions)\n\n measured['week_selected'].append(\n list(mainconsumption.utility_sequence(\n from_timestamp, to_timestamp, condense.DAYS)))\n\n measured['week_before'].append(\n list(mainconsumption.utility_sequence(\n before_from_timestamp, before_to_timestamp, condense.DAYS)))\n\n result = {'utility_type': utility_type}\n result['week_selected'] = list(add_ranged_sample_sequences(\n measured['week_selected'], from_timestamp,\n to_timestamp, condense.DAYS))\n result['week_before'] = list(add_ranged_sample_sequences(\n measured['week_before'], before_from_timestamp,\n before_to_timestamp, condense.DAYS))\n\n return result\n\n\n@task(bind=True)\ndef consumptions_weekly_utility_task(\n task, consumption_ids, from_timestamp, to_timestamp):\n consumptions = Consumption.objects.filter(\n id__in=consumption_ids)\n total_consumptions = len(consumptions)\n\n\n measured = {'week_selected': []}\n for n, consumption in enumerate(consumptions):\n task.set_progress(n, total_consumptions)\n\n measured['week_selected'].append(\n list(consumption.utility_sequence(\n from_timestamp, to_timestamp, condense.HOURS)))\n\n result = {}\n result['consumption_id'] = consumption_ids[0]\n result['week_selected'] = list(add_ranged_sample_sequences(\n measured['week_selected'], from_timestamp,\n to_timestamp, condense.HOURS))\n\n return result\n\n@task(bind=True)\ndef consumptions_weekly_time_task(\n task, consumption_ids, from_timestamp, to_timestamp):\n consumptions = Consumption.objects.filter(\n id__in=consumption_ids)\n total_consumptions = len(consumptions)\n\n\n measured = {'week_selected': []}\n for n, consumption in enumerate(consumptions):\n task.set_progress(n, total_consumptions)\n\n measured['week_selected'].append(\n list(consumption.utility_sequence(\n from_timestamp, to_timestamp, condense.DAYS)))\n\n result = {}\n result['consumption_id'] = consumption_ids[0]\n result['week_selected'] = list(add_ranged_sample_sequences(\n measured['week_selected'], from_timestamp,\n to_timestamp, condense.HOURS))\n\n return result\n\n@task(bind=True)\ndef mainconsumptions_weekly_co2_emissions_task(\n task, mainconsumption_ids, from_timestamp, to_timestamp):\n mainconsumptions = MainConsumption.objects.filter(\n id__in=mainconsumption_ids)\n total_mainconsumptions = len(mainconsumptions)\n\n before_from_timestamp = from_timestamp - datetime.timedelta(days=7)\n before_to_timestamp = to_timestamp - datetime.timedelta(days=7)\n\n measured = {'week_selected': [], 'week_before': []}\n for n, mainconsumption in enumerate(mainconsumptions):\n task.set_progress(n, total_mainconsumptions)\n\n measured['week_selected'].append(\n list(mainconsumption.co2_emissions_sequence(\n from_timestamp, to_timestamp, condense.DAYS)))\n\n measured['week_before'].append(\n list(mainconsumption.co2_emissions_sequence(\n before_from_timestamp, before_to_timestamp, condense.DAYS)))\n\n result = {}\n result['week_selected'] = list(add_ranged_sample_sequences(\n measured['week_selected'], from_timestamp,\n to_timestamp, condense.DAYS))\n result['week_before'] = list(add_ranged_sample_sequences(\n measured['week_before'], before_from_timestamp,\n before_to_timestamp, condense.DAYS))\n\n return result\n\n\n@task(bind=True)\ndef mainconsumptions_weekly_cost_sequence(\n task, mainconsumption_ids, from_timestamp, to_timestamp):\n mainconsumption = MainConsumption.objects.get(\n id__in=mainconsumption_ids)\n\n result = {}\n\n before_from_timestamp = from_timestamp - datetime.timedelta(days=7)\n before_to_timestamp = to_timestamp - datetime.timedelta(days=7)\n\n task.set_progress(0, 2)\n result['week_selected'] = list(mainconsumption.variable_cost_sequence(\n from_timestamp, to_timestamp, condense.DAYS))\n\n task.set_progress(1, 2)\n\n result['week_before'] = list(mainconsumption.variable_cost_sequence(\n before_from_timestamp, before_to_timestamp, condense.DAYS))\n task.set_progress(2, 2)\n\n return result\n" }, { "alpha_fraction": 0.7433628439903259, "alphanum_fraction": 0.7449018955230713, "avg_line_length": 34.121620178222656, "blob_id": "8a537491c53f26bd200c3e786fcb566e8462bbef", "content_id": "03ca1cd9c7b7d76665c14de00a3ba2cc135bc4b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2599, "license_type": "no_license", "max_line_length": 76, "num_lines": 74, "path": "/legacy/rules/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\n<p>This app define Django models and functionality related to\nRules.</p>\n\n<div><p><b>Figure: Data-flow Diagram for Rules:</b> This figure\ndescribes the data flow related to rules between input (GridPortal,\nSpot Index, Meter), output (Phone, Email, Meter (relays)), functions\n(GridEngine, Agent), and database (PostgreSQL). </p><img\nsrc=\"data-flow-diagram-for-rules.jpg\" style=\"max-width:100%;\" align=\"center\"\n/></div>\n\n<p>{@link UserRule}s are created in the GridPortal and stored in the\nPostgreSQL database.</p>\n\n<p>Spot {@link Index}es in the PostgreSQL database are updated daily\nfrom their relevant sources, such as Nordpool FTP, by {@link\n#legacy.nordpool.importer.fetch_import_week fetch_import_week()}.</p>\n\n<p>{@link measurementpoints.models.LogicalInput LogicalInput} values are\nmeasured by {@link legacy.devices.models.Meter Meter}s which\nforwards these measurements to their {@link legacy.devices.Agent\nAgent}, who forwards them on to the PostgreSQL server.</p>\n\n<p>The stored {@link UserRule}s are loaded along with relevant data,\nsuch as {@link Index}es by the GridEngine. The GridEngine processes\nthe loaded {@link UserRule}s with these results:</p>\n\n<ul>\n<li>relay switch schedules in form of {@link AgentRule}s</li>\n<li>rule execution objects in form of {@link EngineRule}s</li>\n</ul>\n\n<p>The {@link AgentRule} are send to the relevant {@link\nlegacy.devices.Agent Agent}, which then makes sure to process\nthese schedules as time goes.</p>\n\n<p>The {@link EngineRule}s regularily monitor {@link\nmeasurementpoints.models.LogicalInput LogicalInput} values to check if\ntheir triggering conditions are all met, to produce the following\nkinds of actions:</p>\n\n<ul>\n<li>relay switch actions in form of {@link RelayAction}s</li>\n<li>email message actions in form of {@link EmailAction}s</li>\n<li>phone text message actions in form of {@link PhoneAction}s</li>\n</ul>\n\n<p>The relay switch actions are too send to the relevant {@link\nlegacy.devices.Agent Agent}, which then immediatly executes the\nswitch action.</p>\n\n<p>The email message actions are executed directly by the GridEngine,\nby sending an email message to a given recipient.</p>\n\n<p>The phone text message actions are executed directly by the\nGridEngine, by sending a text message to the given recipient.</p>\n\"\"\"\n__docformat__ = \"javadoc en\"\n\n\nclass RuleError(Exception):\n \"\"\"\n Base class for exceptions raised by the rules package.\n \"\"\"\n pass\n\n\nclass UserRuleIntegrityError(RuleError):\n \"\"\"\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.640972375869751, "alphanum_fraction": 0.6494909524917603, "avg_line_length": 34.917911529541016, "blob_id": "777b62282669e9a5534abc7bd81aba8d76151c3e", "content_id": "03d1e0e7de35a01adc2aaefd60ba1f819a395ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4813, "license_type": "no_license", "max_line_length": 79, "num_lines": 134, "path": "/gridplatform/providers/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom imagekit.models import ImageSpecField\nfrom imagekit.processors import ResizeToFit\n\nfrom django.db import models\nfrom django.dispatch import receiver\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.models import EncryptionKey\nfrom gridplatform.encryption.signals import encryption_key_created\nfrom gridplatform.users.models import User\n\n\nclass Provider(EncryptedModel):\n \"\"\"\n Providers are entities facilitating the energy management system towards\n :class:`~gridplatform.customers.models.Customer`.\n\n :ivar name:\n :ivar address:\n :ivar zipcode: Zip code.\n :ivar city:\n :ivar cvr: VAT number (CVR is the Danish acronym that correspond to VAT).\n :ivar logo: An image containing the logo of the provider.\n\n :ivar thumbnail: File path to a 100x50 thumbnail of the logo.\n :ivar pdf_logo: File path to a 200x100 version of the logo suitable for\n inclusion in PDF-documents.\n \"\"\"\n name = EncryptedCharField(_('name'), max_length=50)\n address = EncryptedCharField(_('address'), max_length=100)\n zipcode = EncryptedCharField(_('zipcode'), max_length=100)\n city = EncryptedCharField(_('city'), max_length=100)\n cvr = EncryptedCharField(_('cvr'), max_length=100)\n logo = models.ImageField(\n _('logo'), upload_to='logos', blank=True, null=True)\n\n class Meta:\n permissions = (\n ('provider_admin_group',\n _('Group can be used by providers')),\n )\n\n thumbnail = ImageSpecField(\n source='logo',\n processors=[ResizeToFit(100, 50)],\n format='JPEG',\n options={'quality': 90}\n )\n\n pdf_logo = ImageSpecField(\n source='logo',\n processors=[ResizeToFit(200, 100)],\n format='JPEG',\n options={'quality': 90}\n )\n\n def __unicode__(self):\n return self.name_plain\n\n def get_encryption_id(self):\n \"\"\"\n Implementation of abstract method declared by\n :class:`gridplatform.encryption.models.EncryptedModel`.\n \"\"\"\n return (Provider, self.id)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Implements necessary work-arounds for the encryption keys not being\n available upon initial save.\n \"\"\"\n if not self.id:\n if self.name is None:\n # Save an instance without encrypted fields to generate the\n # encryption key\n tmp_provider = Provider()\n tmp_provider.name = ''\n tmp_provider.save()\n self.id = tmp_provider.id\n kwargs['force_update'] = True\n kwargs['force_insert'] = False\n super(Provider, self).save(*args, **kwargs)\n else:\n # Save without an existing encryption key only if there are\n # no encrypted fields.\n super(Provider, self).save(*args, **kwargs)\n # Then generate the key.\n EncryptionKey.generate((Provider, self.id))\n assert self.id\n else:\n super(Provider, self).save(*args, **kwargs)\n\n\n@receiver(encryption_key_created, sender=User)\ndef auto_grant_provider_user_key(sender, key, key_id, **kwargs):\n \"\"\"\n Whenever a customer user is created,an encryption key is created for him as\n well. This signal handler grants that key to all provider users of the\n provider of the customer of the given user.\n \"\"\"\n model_class, object_id = key_id\n assert sender is model_class\n key_user = model_class._all_users.get(id=object_id)\n if not key_user.customer:\n return\n provider_id = key_user.customer.provider_id\n provider_users = User._all_users.filter(\n provider_id=provider_id, customer__isnull=True)\n for provider_user in provider_users:\n provider_user.grant_key(key_id, key)\n\n\n@receiver(encryption_key_created, sender=Customer)\ndef auto_grant_provider_customer_key(sender, key, key_id, **kwargs):\n \"\"\"\n Whenever a customer is created, an encryption key is created for it as\n well. This signal handler grants that key to all provider users of the\n provider of the given customer.\n \"\"\"\n model_class, object_id = key_id\n assert sender is model_class\n key_customer = model_class.objects.get(id=object_id)\n provider_id = key_customer.provider_id\n provider_users = User._all_users.filter(\n provider_id=provider_id, customer__isnull=True)\n for provider_user in provider_users:\n provider_user.grant_key(key_id, key)\n" }, { "alpha_fraction": 0.48899826407432556, "alphanum_fraction": 0.508975088596344, "avg_line_length": 41.121952056884766, "blob_id": "993c73f4685475f163456e6d9c7ede099a3500fc", "content_id": "9655d234f6d0cb0e44798d4cb67ef83202ebd0f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3454, "license_type": "no_license", "max_line_length": 135, "num_lines": 82, "path": "/gridplatform/global_datasources/management/commands/fetch_nordpool.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport requests\nimport re\n\nfrom django.core.management.base import BaseCommand\nfrom django.db import transaction\n\nimport pytz\n\nfrom gridplatform.global_datasources.models import GlobalDataSource\nfrom gridplatform.datasources.models import RawData\n\n\nclass Command(BaseCommand):\n help = \"Import data from nordpool api\"\n\n def handle(self, *args, **options):\n dk1, created = GlobalDataSource.objects.get_or_create(\n name=\"dk1\", app_label=\"nordpool\", codename=\"nordpool_dk1\",\n country=\"DK\", unit=\"currency_dkk*gigawatt^-1*hour^-1\")\n dk2, created = GlobalDataSource.objects.get_or_create(\n name=\"dk2\", app_label=\"nordpool\", codename=\"nordpool_dk2\",\n country=\"DK\", unit=\"currency_dkk*gigawatt^-1*hour^-1\")\n\n url = 'http://www.nordpoolspot.com/api/marketdata/page/41?currency=,DKK,,EUR'\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML,'\n ' like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136',\n 'Referer': 'http://www.nordpoolspot.com/Market-data1/'\n 'Elspot/Area-Prices/ALL1/Hourly/?view=table',\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Encoding': 'gzip, deflate, sdch',\n 'Accept-Language': 'da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4,nb;q=0.2',\n }\n\n response = requests.get(url, headers=headers)\n data = {}\n\n if response.ok:\n data = response.json()['data']['Rows']\n\n prog = re.compile(r\"\\d\\d&nbsp;-&nbsp;\\d\\d\")\n\n with transaction.atomic():\n for row in data:\n if prog.match(row[\"Name\"]):\n timestamp = datetime.datetime.strptime(\n row[\"StartTime\"], \"%Y-%m-%dT%H:%M:%S\")\n timestamp = pytz.timezone('Europe/Copenhagen').localize(timestamp)\n print timestamp\n for column in row[\"Columns\"]:\n if column[\"Name\"] == \"DK1\":\n self._update_or_create(\n timestamp,\n dk1.id,\n {\n 'value': int(float(column[\"Value\"].replace(',', '.').replace(' ', '')) * 1000),\n }\n )\n elif column[\"Name\"] == \"DK2\":\n self._update_or_create(\n timestamp,\n dk2.id,\n {\n 'value': int(float(column[\"Value\"].replace(',', '.').replace(' ', '')) * 1000),\n }\n )\n\n def _update_or_create(self, timestamp, datasource_id, updated_values):\n try:\n obj = RawData.objects.get(timestamp=timestamp, datasource_id=datasource_id)\n for key, value in updated_values.iteritems():\n setattr(obj, key, value)\n obj.save()\n except RawData.DoesNotExist:\n updated_values.update({'timestamp': timestamp, 'datasource_id': datasource_id, 'unit': \"currency_dkk*gigawatt^-1*hour^-1\"})\n obj = RawData(**updated_values)\n obj.save()\n" }, { "alpha_fraction": 0.773508608341217, "alphanum_fraction": 0.773508608341217, "avg_line_length": 34.32143020629883, "blob_id": "d56d1f06e42322bd74cda3f6554ad93eb332af7a", "content_id": "326c5820df32cf8ccb4454e0fd20370a7cb50e1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2967, "license_type": "no_license", "max_line_length": 85, "num_lines": 84, "path": "/documentation/source/apps/gridplatform/trackuser.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Track User\n=================\n\nThe ``trackuser`` app defines a number of global functions to access various\ndata that depend on the user currently logged in.\n\n.. autofunction:: gridplatform.trackuser.get_user\n.. autofunction:: gridplatform.trackuser._get_user_customer\n.. autofunction:: gridplatform.trackuser._get_override_customer\n.. autofunction:: gridplatform.trackuser._get_selected_customer\n.. autofunction:: gridplatform.trackuser.get_customer\n.. autofunction:: gridplatform.trackuser.get_provider\n.. autofunction:: gridplatform.trackuser.get_provider_id\n.. autofunction:: gridplatform.trackuser.get_timezone\n.. autofunction:: gridplatform.trackuser.get_current_date\n\nContext Managers\n----------------\n\n.. py:function:: gridplatform.trackuser.replace_user(user)\n\n A context manager within which the :class:`~gridplatform.users.models.User`\n returned by :py:func:`get_user` will appear to be the given user.\n\n.. py:function:: gridplatform.trackuser.replace_override_customer(customer)\n\n A context manager within which the\n :class:`~gridplatform.customers.models.Customer` returned by\n :py:func:`_get_override_customer` will appear to be the given customer.\n\n.. py:function:: gridplatform.trackuser.replace_selected_customer(customer)\n\n A context manager within which the\n :class:`~gridplatform.customers.models.Customer` returned by\n :py:func:`_get_selected_customer` will appear to be the given customer.\n\n\n.. py:function:: gridplatform.trackuser.replace_customer(customer)\n\n A context manager within which the\n :class:`~gridplatform.customers.models.Customer` returned by\n :py:func:`get_customer` will appear to be the given customer.\n\n This is primariliy used for unit-testing.\n\nManagers\n--------\n\n.. autoclass:: gridplatform.trackuser.managers.FilteringQuerySetMixinBase\n :members: iterator, aggregate, count, delete, update, _update, exists,\n _clone, values, values_list, dates,\n datetimes, _apply_filtering\n\n.. autoclass:: gridplatform.trackuser.managers.CustomerBoundQuerySetMixin\n :members: _apply_filtering\n\n.. autoclass:: gridplatform.trackuser.managers.ProviderBoundQuerySetMixin\n :members: _apply_filtering\n\n.. autoclass:: gridplatform.trackuser.managers.CustomerBoundManagerBase\n\n.. autoclass:: gridplatform.trackuser.managers.CustomerBoundManager\n\n.. autoclass:: gridplatform.trackuser.managers.TreeCustomerBoundManager\n\n.. autoclass:: gridplatform.trackuser.managers.StoredSubclassCustomerBoundManager\n\n.. autoclass:: gridplatform.trackuser.managers.StoredSubclassTreeCustomerBoundManager\n\n.. autoclass:: gridplatform.trackuser.managers.ProviderBoundManager\n\nMiddleware\n----------\n\n.. autoclass:: gridplatform.trackuser.middleware.TrackUserMiddleware\n\nTasks\n-----\n\nThe ``trackuser`` provides some Celery task decorators for tracking users and\nsimilar context into Celery tasks.\n\n.. autofunction:: gridplatform.trackuser.tasks.trackuser_task\n.. autofunction:: gridplatform.trackuser.tasks.task\n" }, { "alpha_fraction": 0.6983240246772766, "alphanum_fraction": 0.7039105892181396, "avg_line_length": 16.899999618530273, "blob_id": "fb4507068bcf397b773a35e1a994e4dacb3f0dee", "content_id": "fef85a9d918c0cd7ba985e1edc82d3d5c8b126a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 179, "license_type": "no_license", "max_line_length": 64, "num_lines": 10, "path": "/scripts/production/base.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd $(dirname $0)\ncd ../../\n\nsource ../ve/bin/activate\n\nexport DJANGO_SETTINGS_MODULE=\"gridplatform.settings.production\"\n\nexport PID_DIR=$(readlink --canonicalize ..)\n" }, { "alpha_fraction": 0.5625112652778625, "alphanum_fraction": 0.5637741088867188, "avg_line_length": 38.03520965576172, "blob_id": "9796e24c3803c56eda618cf78956fb6bd608de86", "content_id": "4e4a7df10276cf5195bc5a2d0d2fbef3ab0b3513", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5543, "license_type": "no_license", "max_line_length": 78, "num_lines": 142, "path": "/legacy/manage_customers/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.urlresolvers import reverse\n\nfrom gridplatform import trackuser\nfrom gridplatform.customers.models import Customer\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ManageCustomerTest(TestCase):\n \"\"\"\n Test that admin user can view and edit customers.\n \"\"\"\n fixtures = [\"super_user_and_customer.json\"]\n\n def setUp(self):\n self.customer = Customer(name_plain='Test customer')\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n self.client.post('/login/', {'username': 'root',\n 'password': 'feet'})\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_customer_list(self):\n \"\"\"\n Test that admin can view a list of customers.\n \"\"\"\n response = self.client.get(reverse('manage_customers-list-json'))\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, self.customer.name_plain)\n\n def test_customer_create_form_get(self):\n \"\"\"\n Test that admin can get create customer view.\n \"\"\"\n response = self.client.get(reverse('manage_customers-create'))\n self.assertContains(response, 'submit')\n\n def test_customer_create_form_empty_fails(self):\n \"\"\"\n Test that admin can't create an empty customer.\n \"\"\"\n response = self.client.post(reverse('manage_customers-update'))\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, 'errorlist')\n\n def test_customer_create_form_success(self):\n \"\"\"\n Test that admin can create new customer.\n \"\"\"\n response = self.client.post(\n reverse('manage_customers-update'),\n {\n 'name': 'New test customer',\n 'address': '',\n 'timezone': 'Europe/Copenhagen',\n 'currency_unit': 'currency_dkk',\n 'postal_code': '',\n 'country_code': '',\n 'electricity_instantaneou': 'watt',\n 'electricity_consumption': 'kilowatt*hour',\n 'gas_instantaneous': 'liter*second^-1',\n 'gas_consumption': 'meter*meter*meter',\n 'water_instantaneous': 'meter*meter*meter*hour^-1',\n 'water_consumption': 'meter*meter*meter',\n 'heat_instantaneous': 'watt',\n 'heat_consumption': 'kilowatt*hour',\n 'oil_instantaneous': 'meter*meter*meter*hour^-1',\n 'oil_consumption': 'meter*meter*meter',\n 'temperature': 'celsius',\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertNotContains(response, 'errorlist')\n self.assertContains(response, 'New test customer')\n\n def test_customer_update_form_get(self):\n \"\"\"\n Test that admin can view customer.\n \"\"\"\n response = self.client.get(\n reverse('manage_customers-form', kwargs={'pk': self.customer.id}))\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, self.customer.name_plain)\n\n for field in ('address', 'postal_code', 'country_code',\n 'timezone', 'currency_unit',\n 'electricity_instantaneous', 'electricity_consumption',\n 'gas_instantaneous', 'gas_consumption',\n 'water_instantaneous', 'water_consumption',\n 'heat_instantaneous', 'heat_consumption',\n 'oil_instantaneous', 'oil_consumption',\n 'temperature'):\n self.assertContains(response, field)\n\n def test_customer_update_form_success(self):\n \"\"\"\n Test that admin can edit customer.\n \"\"\"\n response = self.client.post(\n reverse('manage_customers-update',\n kwargs={'pk': self.customer.id}),\n {\n 'name': 'New name',\n 'timezone': 'Europe/Copenhagen',\n 'currency_unit': 'currency_dkk',\n 'electricity_instantaneous': 'watt',\n 'electricity_consumption': 'kilowatt*hour',\n 'gas_instantaneous': 'liter*second^-1',\n 'gas_consumption': 'meter*meter*meter',\n 'water_instantaneous': 'meter*meter*meter*hour^-1',\n 'water_consumption': 'meter*meter*meter',\n 'heat_instantaneous': 'watt',\n 'heat_consumption': 'kilowatt*hour',\n 'oil_instantaneous': 'meter*meter*meter*hour^-1',\n 'oil_consumption': 'meter*meter*meter',\n 'temperature': 'celsius',\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertNotContains(response, 'errorlist')\n self.assertContains(response, 'New name')\n\n def test_customer_update_form_empty_fail(self):\n \"\"\"\n Test that admin can edit customer.\n \"\"\"\n response = self.client.post(\n reverse('manage_customers-update',\n kwargs={'pk': self.customer.id}),\n {\n 'name': '',\n 'timezone': '',\n })\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, 'errorlist')\n" }, { "alpha_fraction": 0.5889815092086792, "alphanum_fraction": 0.5929684638977051, "avg_line_length": 30.352272033691406, "blob_id": "7da1513884447a5bf7ac033ae3c19f3186e14b40", "content_id": "9eff3e2606ad9690d08f3773c4dd4c33b0fd5053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2759, "license_type": "no_license", "max_line_length": 76, "num_lines": 88, "path": "/gridplatform/condensing/management/commands/generate_cache.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nRun ``./manage.py help generate_cache`` for further details on invoking the\ncommand for generating cache.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nfrom optparse import make_option\nimport datetime\n\nfrom django.core.management.base import BaseCommand\nfrom django.core.management.base import CommandError\nfrom django.db import transaction\n\nimport pytz\n\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\n\nfrom ...models import generate_cache\nfrom ...models import DataSource\nfrom ...models import CACHABLE_UNITS\n\n\ndef _make_periods(from_timestamp, to_timestamp):\n assert from_timestamp <= to_timestamp\n period_to = to_timestamp\n while period_to > from_timestamp:\n period_from = max(\n from_timestamp, period_to - datetime.timedelta(days=7))\n yield period_from, period_to\n period_to = period_from\n\n\nclass Command(BaseCommand):\n help = \"Generate condensed measurement cache data for accumulation \" + \\\n \"data sources\"\n\n option_list = BaseCommand.option_list + (\n make_option(\n '--years_back', '-Y',\n dest='years',\n type=int,\n default=0),\n make_option(\n '--months_back', '-m',\n dest='months',\n type=int,\n default=0),\n make_option(\n '--days_back', '-d',\n dest='days',\n type=int,\n default=0),\n make_option(\n '--hours_back', '-H',\n dest='hours',\n type=int,\n default=0),\n )\n\n def handle(self, *args, **options):\n verbosity = int(options.get('verbosity'))\n now = datetime.datetime.now(pytz.utc)\n to_timestamp = now.replace(minute=0, second=0, microsecond=0)\n delta = RelativeTimeDelta(\n years=options['years'],\n months=options['months'],\n days=options['days'],\n hours=options['hours'])\n from_timestamp = to_timestamp - delta\n if from_timestamp == to_timestamp:\n raise CommandError('Needs non-empty time range specified.')\n if verbosity >= 1:\n self.stdout.write('Generating cache for period:\\n %s -- %s' % (\n from_timestamp, to_timestamp))\n\n datasources = list(\n DataSource.objects.filter(unit__in=CACHABLE_UNITS))\n if verbosity >= 1:\n self.stdout.write('%s data sources' % (len(datasources),))\n\n for period_from, period_to in _make_periods(\n from_timestamp, to_timestamp):\n for datasource in datasources:\n with transaction.atomic():\n generate_cache(datasource, period_from, period_to)\n" }, { "alpha_fraction": 0.5529412031173706, "alphanum_fraction": 0.565944254398346, "avg_line_length": 28.290908813476562, "blob_id": "d2fda18c533b5cf5c87d049f3a35f52dcef0f72a", "content_id": "a678248158db38cc193bbf629c77366a04113aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1615, "license_type": "no_license", "max_line_length": 99, "num_lines": 55, "path": "/forecast-daemon/relay_handler.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from random import randint\n\nimport datetime\nimport pytz\nfrom RPi import GPIO\n\n\nclass RelayHandler:\n\n def __init__(self, configuration):\n self.configuration = configuration\n self.prev_port_setting = -1\n self.pins = [2, 3, 4, 17, 27, 22, 10, 9]\n\n GPIO.setmode(GPIO.BCM)\n\n for i in self.pins:\n GPIO.setup(i, GPIO.OUT)\n GPIO.output(i, GPIO.HIGH)\n\n def update_ports(self, forecast_data):\n now = datetime.datetime.now().replace(tzinfo=pytz.utc) # + datetime.timedelta(hours=2)\n port_setting = 0\n\n if not forecast_data:\n port_setting = 9\n else:\n for setting in forecast_data:\n print setting['timestamp'], now\n if setting['timestamp'] < now < setting['timestamp'] + datetime.timedelta(hours=1):\n print setting['timestamp'], setting['relay']\n port_setting = setting['relay']\n\n if self.prev_port_setting != port_setting:\n for i in self.pins:\n GPIO.output(i, GPIO.HIGH)\n\n self.open_port(port_setting)\n self.prev_port_setting = port_setting\n\n def open_port(self, port_number):\n\n if port_number == 0:\n for i in self.pins:\n GPIO.output(i, GPIO.LOW)\n else:\n self.set_port_state(port_number, GPIO.LOW)\n\n def close_port(self, port_number):\n\n self.set_port_state(port_number, GPIO.HIGH)\n\n def set_port_state(self, port_number, state):\n if 0 < port_number < 9:\n GPIO.output(self.pins[port_number - 1], state)\n\n\n\n\n" }, { "alpha_fraction": 0.6641327142715454, "alphanum_fraction": 0.6655148863792419, "avg_line_length": 32.264366149902344, "blob_id": "17faa2647e906682a4998384a30cfb1660ec81f5", "content_id": "ea3f49db2c6efff966cb68ef5d123892f38bcd6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2894, "license_type": "no_license", "max_line_length": 79, "num_lines": 87, "path": "/gridplatform/utils/generic_views/access_control.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nimport braces.views\n\nfrom gridplatform.trackuser import replace_selected_customer\n\n\ndef _get_permission_name(action, opts):\n return '%s.%s_%s' % (opts.app_label, action, opts.object_name.lower())\n\n\nclass CheckAJAXMixin(object):\n \"\"\"\n Set ``self.raise_exception = True`` on AJAX requests, to have\n access control return \"403 Forbidden\" rather than redirect to\n login page on permission denied for those.\n \"\"\"\n def dispatch(self, request, *args, **kwargs):\n if request.is_ajax():\n self.raise_exception = True\n return super(CheckAJAXMixin, self).dispatch(request, *args, **kwargs)\n\n\nclass LoginRequiredMixin(CheckAJAXMixin, braces.views.LoginRequiredMixin):\n \"\"\"\n Mixin to check that user is logged in.\n \"\"\"\n pass\n\n\nclass ModelPermissionRequiredMixin(\n CheckAJAXMixin, braces.views.PermissionRequiredMixin):\n \"\"\"\n Mixin to simplify specifying a required model permission for a specific\n model --- where the generic view specifies the permission as \"add\",\n \"change\" or \"delete\"; and this will then be combined with the name of the\n concrete model in use for the concrete permission name.\n \"\"\"\n model_permission = None\n\n @property\n def permission_required(self):\n model = self.model or self.get_queryset().model\n return _get_permission_name(self.model_permission, model._meta)\n\n\nclass MultipleModelPermissionsRequiredMixin(\n CheckAJAXMixin, braces.views.MultiplePermissionsRequiredMixin):\n \"\"\"\n Mixin to simplify specifying a required set of permissions for a set of\n models --- generic views specify model permissions and *how* to obtain the\n list of relevant models from whatever configuration of models, formsets and\n inline-models are relevant for the view type. (Permissions for the more\n advanced viwes from `extra_views` cannot be expressed with\n :class:`.ModelPermissionRequiredMixin`.)\n \"\"\"\n model_permissions = None\n\n def get_permissions_models(self):\n raise NotImplementedError('not implemented by %r' % self.__class__)\n\n @property\n def permissions(self):\n models = self.get_permissions_models()\n return {\n 'all': list({\n _get_permission_name(perm, model._meta)\n for model in models\n for perm in self.model_permissions\n })\n }\n\n\nclass CustomerBoundMixin(object):\n \"\"\"\n Expects ``_customer`` to exist on the view using this mixin.\n \"\"\"\n def dispatch(self, request, *args, **kwargs):\n with replace_selected_customer(self._customer):\n res = super(CustomerBoundMixin, self).dispatch(\n request, *args, **kwargs)\n if hasattr(res, 'render'):\n res.render()\n return res\n" }, { "alpha_fraction": 0.5743765830993652, "alphanum_fraction": 0.5846947431564331, "avg_line_length": 30.849315643310547, "blob_id": "5451419a2e49843d208fc61c774701af0ed407dc", "content_id": "902a37c49d1889df83b7e239df9a37212fc9d6b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2326, "license_type": "no_license", "max_line_length": 157, "num_lines": 73, "path": "/wifiagent/wifiagent/relay/request_handler.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import datetime\nimport requests\n\nfrom requests.auth import AuthBase\nfrom django.conf import settings\n\nfrom .models import EndpointCache\n\n\nclass TokenAuth(AuthBase):\n \"\"\"Attaches HTTP Token Authentication to the given Request object.\"\"\"\n def __init__(self, token):\n # setup any auth-related data here\n self.token = token\n\n def __call__(self, r):\n # modify and return the request\n r.headers['Authorization'] = \"token %s\" % self.token\n return r\n\n\nclass RequestHandler():\n\n def __init__(self):\n if settings.DEBUG:\n self.auth = TokenAuth('9dc8c71d767673d21552055c856977c1a33700925ad44d85db2f76a91d829efba50ac4f50dec8d39dd354eb3e9180780b55f8506')\n self.base_url = \"http://192.168.13.37:8000/api/v3\" \n else:\n self.auth = TokenAuth(settings.API_TOKEN)\n self.base_url = settings.API_BASE_URL\n\n def fetch_endpoint(self, mac):\n payload = {'hardware_id': mac}\n r = requests.get('%s/datasources/customer_datasources/' % self.base_url, auth=self.auth, params=payload, timeout=1)\n response = {}\n \n if r.status_code == requests.codes.ok:\n response = r.json()\n\n if response['count'] == 1:\n EndpointCache.objects.update_or_create(\n mac=response['results'][0]['hardwareId'], defaults={'timestamp': datetime.datetime.now(), 'endpoint': response['results'][0]['rawData']})\n return response['results'][0]['rawData']\n\n else: \n return None\n else:\n return None\n\n def get_endpoint(self, mac):\n cached = EndpointCache.objects.filter(mac=mac)\n if cached and cached[0].timestamp.replace(tzinfo=None) > datetime.datetime.now() - datetime.timedelta(minutes=10):\n return cached[0].endpoint\n\n else:\n return self.fetch_endpoint(mac)\n\n # TODO: Handle error logging\n def send_measurement(self, measurement):\n endpoint = self.get_endpoint(measurement.mac)\n\n if endpoint:\n payload = {\n \"timestamp\": measurement.timestamp.strftime(\"%Y-%m-%dT%H:%M:%S\"), \n \"value\": int(measurement.vrms_total), \n \"unit\": \"volt\"\n }\n\n r = requests.post(endpoint, auth=self.auth, data=payload)\n\n return r.status_code == requests.codes.created \n\n return False\n\n" }, { "alpha_fraction": 0.6897016763687134, "alphanum_fraction": 0.6907972097396851, "avg_line_length": 31.420764923095703, "blob_id": "4743e42aca3950f3eae1ec7d72e0096e499ef0a7", "content_id": "78c4b35b223264df73c90e163ad50f4edc467096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11866, "license_type": "no_license", "max_line_length": 78, "num_lines": 366, "path": "/legacy/manage_indexes/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines the views of the manage_indexes Django app.\n\"\"\"\n\nfrom django import forms\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.views.generic import TemplateView\nfrom django.contrib import messages\nfrom django.http import HttpResponseForbidden\nfrom django.views.decorators.http import require_http_methods\nfrom django.core.urlresolvers import reverse\nfrom django.core.exceptions import ValidationError\nfrom django.forms.models import BaseInlineFormSet\n\nfrom extra_views import CreateWithInlinesView\nfrom extra_views import UpdateWithInlinesView\nfrom extra_views import InlineFormSet\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.users.decorators import customer_admin_or_error\nfrom gridplatform.utils import units\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.formsets import SurvivingFormsModelFormSetMixin\nfrom gridplatform.utils.generic_views import LocalizedInlineFormSetMixin\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.utils.views import json_list_response\nfrom gridplatform.utils.views import render_to\nfrom legacy.indexes.models import DerivedIndexPeriod\nfrom legacy.indexes.models import Index\nfrom legacy.indexes.models import SeasonIndexPeriod\nfrom legacy.measurementpoints.fields import DataRoleField\n\n\n@auth_or_error\ndef listing(request):\n \"\"\"\n The view function for listing indexes visible to the current user.\n \"\"\"\n return TemplateView.as_view(\n template_name=\"manage_indexes/indexes_list.html\")(request)\n\n\nclass DerivedPeriodForm(forms.ModelForm):\n class Meta:\n model = DerivedIndexPeriod\n fields = [\n 'from_date', 'other_index', 'coefficient', 'constant', 'roof']\n\n def __init__(self, *args, **kwargs):\n inline_instance = kwargs.pop('inline_instance')\n super(DerivedPeriodForm, self).__init__(*args, **kwargs)\n assert inline_instance.view.utility_type is not None\n assert inline_instance.view.role is not None\n self.fields['other_index'].queryset = Index.objects.filter(\n utility_type=inline_instance.view.utility_type,\n role=inline_instance.view.role)\n if self.instance.id:\n self.fields['other_index'].queryset = self.fields['other_index'].\\\n queryset.exclude(\n id__in=[\n i.id for i in self.instance.index.get_derivatives()])\n\n\nclass PeriodFormSet(SurvivingFormsModelFormSetMixin, BaseInlineFormSet):\n def clean(self):\n super(PeriodFormSet, self).clean()\n\n surviving_forms = self.surviving_forms()\n if len(surviving_forms) < 1:\n raise ValidationError(_('At least one period must be defined'))\n\n from_dates = []\n for form in surviving_forms:\n if 'from_date' not in form.cleaned_data:\n continue\n if form.cleaned_data['from_date'] in from_dates:\n raise ValidationError(\n _('No two periods can have the same from date'))\n from_dates.append(form.cleaned_data['from_date'])\n\n\n@auth_or_error\n@json_list_response\ndef list_json(request):\n \"\"\"\n View function for listing rendered indexes in JSON container.\n\n Returns a dictionary with two keys, C{\"total\"} and C{\"data\"},\n where C{[\"totoal\"]} is the total number of indexes matching a\n filter, and C{[\"data\"]} is a list of HTML strings reprecenting\n indexes to be displayed.\n \"\"\"\n options = json_list_options(request)\n\n indexes = list(\n Index.objects.all())\n\n order_map = {\n 'name': lambda index: unicode(index.name_plain.lower()),\n 'unit': lambda index: unicode(index.unit)}\n\n if options['order_by'] in order_map:\n indexes.sort(key=order_map[options['order_by']])\n\n return (order_map, indexes, \"manage_indexes/index_block.html\")\n\n\nclass DerivedPeriodInline(LocalizedInlineFormSetMixin, InlineFormSet):\n model = DerivedIndexPeriod\n form_class = DerivedPeriodForm\n fk_name = 'index'\n extra = 1\n formset_class = PeriodFormSet\n\n def get_extra_form_kwargs(self):\n kwargs = super(DerivedPeriodInline, self).get_extra_form_kwargs()\n kwargs['inline_instance'] = self\n return kwargs\n\n\nclass SeasonsPeriodInline(LocalizedInlineFormSetMixin, InlineFormSet):\n model = SeasonIndexPeriod\n extra = 1\n fields = ['from_date'] + ['value_at_hour_%d' % i for i in range(24)]\n formset_class = PeriodFormSet\n\n\nclass TariffForm(forms.ModelForm):\n unit = forms.ChoiceField()\n\n class Meta:\n model = Index\n fields = ['name', 'collection', 'unit', 'timezone']\n\n\nclass IndexCreateView(CreateWithInlinesView):\n model = Index\n\n def get_success_url(self):\n return reverse('manage_indexes-listing')\n\n # Set in subclass:\n role = None\n data_format = None\n utility_type = None\n\n def get_form(self, form_class):\n form = super(IndexCreateView, self).get_form(form_class)\n assert self.role is not None\n form.instance.role = self.role\n assert self.data_format is not None\n form.instance.data_format = self.data_format\n assert self.utility_type is not None\n form.instance.utility_type = self.utility_type\n return form\n\n\nclass DerivedIndexCreateView(IndexCreateView):\n inlines = [DerivedPeriodInline]\n data_format = Index.DERIVED\n\n\nclass SeasonsIndexCreateView(IndexCreateView):\n inlines = [SeasonsPeriodInline]\n data_format = Index.SEASONS\n\n\nclass TariffCreateViewMixin(object):\n form_class = TariffForm\n\n # Set in subclass:\n unit_choices = None\n\n def get_form(self, form_class):\n form = super(TariffCreateViewMixin, self).get_form(form_class)\n assert self.unit_choices is not None\n form.fields['unit'].choices = self.unit_choices\n form.fields['unit'].initial = self.get_initial_unit()\n return form\n\n def get_initial_unit(self):\n customer_currency_unit = get_customer().currency_unit\n for unit, unit_display in self.unit_choices:\n if customer_currency_unit in unit:\n return unit\n return None\n\n\nclass NontariffCreateViewMixin(object):\n fields = ['name', 'collection', 'timezone']\n template_name = 'manage_indexes/seasons_index_form.html'\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.unknown\n\n # Set in sublcass:\n unit = None\n\n def get_form(self, form_class):\n form = super(NontariffCreateViewMixin, self).get_form(form_class)\n assert self.unit is not None\n form.instance.unit = self.unit\n return form\n\n\nclass DerivedTariffCreateView(TariffCreateViewMixin, DerivedIndexCreateView):\n template_name = 'manage_indexes/derived_tariff_form.html'\n\n\nclass ElectricityTariffMixin(object):\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.electricity\n role = DataRoleField.ELECTRICITY_TARIFF\n unit_choices = units.ENERGY_TARIFF_CHOICES\n\n\nclass GasTariffMixin(object):\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.gas\n role = DataRoleField.GAS_TARIFF\n unit_choices = units.VOLUME_TARIFF_CHOICES\n\n\nclass WaterTariffMixin(object):\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.water\n role = DataRoleField.WATER_TARIFF\n unit_choices = units.VOLUME_TARIFF_CHOICES\n\n\nclass DistrictHeatingTariffMixin(object):\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.district_heating\n role = DataRoleField.HEAT_TARIFF\n unit_choices = units.ENERGY_TARIFF_CHOICES\n\n\nclass OilTariffMixin(object):\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.oil\n role = DataRoleField.OIL_TARIFF\n unit_choices = units.VOLUME_TARIFF_CHOICES\n\n\nclass DerivedElectricityTariffCreateView(ElectricityTariffMixin,\n DerivedTariffCreateView):\n headline = _('Create New Derived Electricity Tariff')\n\n\nclass DerivedGasTariffCreateView(GasTariffMixin,\n DerivedTariffCreateView):\n headline = _('Create New Derived Gas Tariff')\n\n\nclass DerivedWaterTariffCreateView(WaterTariffMixin,\n DerivedTariffCreateView):\n headline = _('Create New Derived Water Tariff')\n\n\nclass DerivedDistrictHeatingTariffCreateView(DistrictHeatingTariffMixin,\n DerivedTariffCreateView):\n headline = _('Create New Derived District Heating Tariff')\n\n\nclass DerivedOilTariffCreateView(OilTariffMixin,\n DerivedTariffCreateView):\n headline = _('Create New Derived Oil Tariff')\n\n\nclass SeasonsTariffCreateView(TariffCreateViewMixin, SeasonsIndexCreateView):\n template_name = 'manage_indexes/seasons_tariff_form.html'\n\n\nclass SeasonsElectricityTariffCreateView(ElectricityTariffMixin,\n SeasonsTariffCreateView):\n headline = _('Create New Seasons Electricity Tariff')\n\n\nclass SeasonsGasTariffCreateView(GasTariffMixin,\n SeasonsTariffCreateView):\n headline = _('Create New Seasons Gas Tariff')\n\n\nclass SeasonsWaterTariffCreateView(WaterTariffMixin,\n SeasonsTariffCreateView):\n headline = _('Create New Seasons Water Tariff')\n\n\nclass SeasonsDistrictHeatingTariffCreateView(DistrictHeatingTariffMixin,\n SeasonsTariffCreateView):\n headline = _('Create New Seasons District Heating Tariff')\n\n\nclass SeasonsOilTariffCreateView(OilTariffMixin,\n SeasonsTariffCreateView):\n headline = _('Create New Seasons Oil Tariff')\n\n\nclass SeasonsEmployeesIndexCreateView(NontariffCreateViewMixin,\n SeasonsIndexCreateView):\n headline = _('Create New Seasons Employees Index')\n role = DataRoleField.EMPLOYEES\n unit = 'person'\n\n\nclass SeasonsAreaIndexCreateView(NontariffCreateViewMixin,\n SeasonsIndexCreateView):\n headline = _('Create New Seasons Area Index')\n role = DataRoleField.AREA\n unit = 'meter^2'\n\n\nclass IndexUpdateView(UpdateWithInlinesView):\n fields = ['name', 'collection']\n model = Index\n\n def get_success_url(self):\n return reverse('manage_indexes-listing')\n\n @property\n def utility_type(self):\n return self.object.utility_type\n\n @property\n def role(self):\n return self.object.role\n\n\nclass DerivedIndexUpdateView(IndexUpdateView):\n inlines = [DerivedPeriodInline]\n template_name = 'manage_indexes/derived_index_form.html'\n\n @property\n def headline(self):\n return _('Update Derived {index_role}').format(\n index_role=self.object.get_role_display())\n\n\nclass SeasonsIndexUpdateView(IndexUpdateView):\n inlines = [SeasonsPeriodInline]\n template_name = 'manage_indexes/seasons_index_form.html'\n\n @property\n def headline(self):\n return _('Update Seasons {index_role}').format(\n index_role=self.object.get_role_display())\n\n\n@auth_or_error\n@render_to(\"manage_indexes/indexes_display.html\")\ndef display(request, index_id):\n \"\"\"\n The view function for listing indexes visible to the current user.\n \"\"\"\n return {\"index_id\": index_id}\n\n\n@require_http_methods([\"POST\"])\n@customer_admin_or_error\ndef delete(request):\n pk = request.POST.get('pk', None)\n customer = request.customer\n instance = get_object_or_404(Index, pk=pk)\n if instance.customer != customer or not instance.is_deletable():\n return HttpResponseForbidden()\n instance.delete()\n messages.success(request, _('The index has been deleted'))\n return redirect(\"manage_indexes-listing\")\n" }, { "alpha_fraction": 0.7068965435028076, "alphanum_fraction": 0.7155172228813171, "avg_line_length": 15.571428298950195, "blob_id": "b65bd750d9887dcaffd1db044a4cc4ebde361ec6", "content_id": "489c5be346c73d8247cd5f975bf6c2869f8baf5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 116, "license_type": "no_license", "max_line_length": 47, "num_lines": 7, "path": "/scripts/production/stop_celery.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsource $(dirname $0)/base.sh\n\nPIDFILE=$PID_DIR/%n.pid\n\ncelery multi stopwait celery --pidfile=$PIDFILE\n" }, { "alpha_fraction": 0.718480110168457, "alphanum_fraction": 0.7202072739601135, "avg_line_length": 31.16666603088379, "blob_id": "58d5012f3c5cd9435f6d4b7f0db9882331bd0ff4", "content_id": "96d1bac214a2a9874b0e355a75e07fc832bf343e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/gridplatform/provider_datasources/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.datasources.serializers import DataSourceSerializerBase\n\nfrom gridplatform.rest import serializers\nfrom .models import ProviderDataSource\n\n\nclass ProviderDataSourceSerializer(DataSourceSerializerBase):\n raw_data = serializers.HyperlinkedIdentityField(\n view_name='api:datasources:rawdata-list')\n\n class Meta:\n model = ProviderDataSource\n fields = ('url', 'id', 'unit', 'display_unit',\n 'hardware_id', 'raw_data')\n" }, { "alpha_fraction": 0.5782092809677124, "alphanum_fraction": 0.5803667902946472, "avg_line_length": 29.899999618530273, "blob_id": "5a43fb17d964d61a0b9a6e41c70ecc894f179057", "content_id": "7933eed7634977cb9d005bd1b2889cdca2b5e3a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 927, "license_type": "no_license", "max_line_length": 72, "num_lines": 30, "path": "/gridplatform/utils/formsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nclass SurvivingFormsModelFormSetMixin(object):\n \"\"\"\n Mixes :meth:`~.SurvivingFormsModelFormSetMixin.surviving_forms`\n into a formset.\n \"\"\"\n\n def surviving_forms(self):\n \"\"\"\n Surviving forms are forms that Django will save to the database.\n\n Surviving forms may be subject to extra validation logic\n compared to nonsurviving forms (those that Django will either\n delete or ignore).\n \"\"\"\n result = []\n for i in range(0, self.total_form_count()):\n form = self.forms[i]\n if self._should_delete_form(form):\n continue\n if i >= self.initial_form_count():\n if form.has_changed():\n result.append(form)\n else:\n result.append(form)\n return result\n" }, { "alpha_fraction": 0.8094195127487183, "alphanum_fraction": 0.8094195127487183, "avg_line_length": 40.5, "blob_id": "6201dabb5272c7c7d22a22b01279b8a0b8842a04", "content_id": "5bbf01c26ce54be6416a8c1ddd99a5f06043929b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 913, "license_type": "no_license", "max_line_length": 83, "num_lines": 22, "path": "/documentation/source/apps/gridplatform/energyperformances.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Energy Performances\n===================\n\nEnergy performances are defined in the domain model in the section\n:ref:`adjustments-etc`. The ``energyperformances`` app defines a class hierachy of\nenergy performances. Notably, there is the base class\n:py:class:`~gridplatform.energyperformances.models.EnergyPerformance` which is\nspecialized by\n:py:class:`~gridplatform.energyperformances.models.ProductionEnergyPerformance`\n(based on production adjustments) and\n:py:class:`~gridplatform.energyperformances.models.TimeEnergyPerformance`\n(based on duration adjustments).\n\n\n.. autoclass:: gridplatform.energyperformances.models.EnergyPerformance\n :members: compute_performance\n\n.. autoclass:: gridplatform.energyperformances.models.ProductionEnergyPerformance\n :members: compute_performance, clean_fields\n\n.. autoclass:: gridplatform.energyperformances.models.TimeEnergyPerformance\n :members: compute_performance\n" }, { "alpha_fraction": 0.6243602633476257, "alphanum_fraction": 0.6248720288276672, "avg_line_length": 38.8775520324707, "blob_id": "13ef3fd0e7b1865e466c710c1c549c7f33f3853c", "content_id": "968c9fb81b56fdc9af185c4389c3018e19baa3ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1954, "license_type": "no_license", "max_line_length": 83, "num_lines": 49, "path": "/energymanager/project_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.project_site.views',\n url(r'^$',\n views.HomeView.as_view(),\n name='home'),\n url(r'^customer/(?P<customer_id>\\d+)/$',\n views.CustomerView.as_view(),\n name='customer'),\n url(r'^choose-customer/$',\n views.ChooseCustomer.as_view(),\n name='choose-customer'),\n url(r'^project/(?P<customer_id>\\d+)/$',\n views.EnergyProjectList.as_view(),\n name='project-list'),\n url(r'^project/content/(?P<customer_id>\\d+)/$',\n views.EnergyProjectListContentView.as_view(),\n name='project-list-content'),\n url(r'^project/create/(?P<customer_id>\\d+)/$',\n views.EnergyProjectCreateView.as_view(),\n name='project-create'),\n url(r'^project/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.EnergyProjectUpdateView.as_view(),\n name='project-update'),\n url(r'^project/delete/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.EnergyProjectDeleteView.as_view(),\n name='project-delete'),\n url(r'^project/overview/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.EnergyProjectDetailView.as_view(),\n name='project-detail'),\n\n url(r'^project/(?P<customer_id>\\d+)/start_power/(?P<project_id>\\d+)/$', # noqa\n views.StartBaselineHourConsumptionUtilityBarChartView.as_view(),\n name='consumption-utility-bar-chart-start'),\n url(r'^project/(?P<customer_id>\\d+)/start_time/(?P<project_id>\\d+)/$', # noqa\n views.StartBaselineDayliConsumptionUtilityBarChartView.as_view(),\n name='time-consumption-utility-bar-chart-start'),\n url(r'^project/(?P<customer_id>\\d+)/finalize/$',\n views.FinalizeWeekUtilityBarChartView.as_view(),\n name='utility-bar-chart-finalize'),\n)\n" }, { "alpha_fraction": 0.6001042723655701, "alphanum_fraction": 0.608967661857605, "avg_line_length": 31.508474349975586, "blob_id": "7b8d08b6501a974e78b80a5dbac01851305bdcf0", "content_id": "7e540a37c826e94c67cfd8028932ac0ee1fde3bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1918, "license_type": "no_license", "max_line_length": 76, "num_lines": 59, "path": "/legacy/nordpool/ftpclient.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nClient towards the Nordpool FTP server.\n\n@attention: Not included in unit tests --- we don't want to hit the Nordpool\nFTP server on normal test runs... (And we haven't added infrastructure for\nwriting tests that shouldn't run...)\n\"\"\"\n\nimport ftplib\n\nfrom gridplatform.utils.ftpclient import ftpconnection\n\nfrom .conf import settings\n\n\nclass NotFoundError(IOError):\n pass\n\n\ndef fetch_spot(year, week):\n \"\"\"\n Fetch the spot price file for a specified week from the Nordpool FTP\n server.\n\n @type year: integer\n @param year: The year to fetch data for.\n @type week: integer\n @param week: The week number to fetch data for. Use ISO weeks.\n @rtype: string list\n @return: A list of lines from the week data file.\n @raise NotFoundError: If the expected data file was not found on the\n server.\n \"\"\"\n base_dir = 'Elspot/Elspot_file'\n filename = 'spot%02d%02d.sdv' % (year % 100, week)\n yeardir = '%04d' % (year,)\n with ftpconnection(\n settings.NORDPOOL_HOST, settings.NORDPOOL_USER,\n settings.NORDPOOL_PASS) as ftp:\n ftp.cwd(base_dir)\n try:\n # base directory contains three years of data; for last year and\n # earlier, data is (also) present in subdirectories per year\n lines = []\n ftp.retrlines('RETR %s' % (filename,), lines.append)\n except ftplib.error_perm as e:\n if e.args[0].startswith('550'):\n # \"file unavailable\" (FTP error code 550)\n # try subdirectory for year if file not present in base\n # directory\n ftp.cwd(yeardir)\n lines = []\n ftp.retrlines('RETR %s' % (filename,), lines.append)\n else:\n raise\n return lines\n" }, { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6381579041481018, "avg_line_length": 10.692307472229004, "blob_id": "883a8f719f730515db535359903a033ed8191eee", "content_id": "959ff82affade412d1517bfb67624fccc3b7180d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 152, "license_type": "no_license", "max_line_length": 20, "num_lines": 13, "path": "/documentation/source/domainmodel.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Domain Model\n============\n\n.. toctree::\n :maxdepth: 2\n\n datasources\n consumptions\n costcompensations\n changes\n projects\n\n samplesequences\n" }, { "alpha_fraction": 0.6391752362251282, "alphanum_fraction": 0.6417526006698608, "avg_line_length": 26.714284896850586, "blob_id": "033457043a44a1a87c959951dc25abb9f98aeb43", "content_id": "0e72851974659b331cd81b77b22c64d3c8531e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 54, "num_lines": 14, "path": "/legacy/edit_userprofile/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'legacy.edit_userprofile.views',\n url(r'^(?P<pk>\\d+)$', 'userprofile_form',\n name='edit_userprofile'),\n url(r'^update/(?P<pk>\\d+)$', 'userprofile_update',\n name='edit_userprofile-update'),\n)\n" }, { "alpha_fraction": 0.7239548563957214, "alphanum_fraction": 0.7299270033836365, "avg_line_length": 36.67499923706055, "blob_id": "f3ed0cf0a503e2a14351799b91f673f952752578", "content_id": "07ba410063ecba91867e9981593c5458a7b9e564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 79, "num_lines": 40, "path": "/legacy/display_measurementpoints/templatetags/display_measurementpoints.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom django.template.defaultfilters import floatformat\nfrom django.utils.translation import ugettext as _\n\n\nregister = template.Library()\n\n\[email protected](is_safe=True)\ndef physicalquantity(physical_quantity, decimals):\n \"\"\"\n Formats a physical quantity nicely.\n\n @param physical_quantity: A two-tuple C{(n, u)} where C{n} is number to be\n displayed. and C{u} is a localized unit name.\n\n @param decimals: The number of decimals that should be displayed. Use\n negative values to indicate that right-most zeroes must be\n discarded. (similar to floatformat filter)\n\n @precondition: decimals <= 12, because the underlying library will truncate\n and replace additional decimals with 0.\n\n @note: This method is not intended to format a PhysicalQuantity instance\n directly. The application is responsible for converting the\n PhysicalQuantity to the right unit, decide how many decimals are needed,\n and provide a localized unit.\n\n @note: The name of this method follows a convention of Emacs Django\n template mode, where filters may not contain underscore.\n \"\"\"\n assert int(decimals) <= 12, \\\n 'successive decimals will be 0, regardless of their value'\n return _(u'{numeric_quantity} {unit_name}').format(\n numeric_quantity=floatformat(physical_quantity[0], decimals),\n unit_name=physical_quantity[1])\n" }, { "alpha_fraction": 0.6297376155853271, "alphanum_fraction": 0.6297376155853271, "avg_line_length": 27.58333396911621, "blob_id": "03cf331f62a83c2f14a6f8747bb18f5d15b596cd", "content_id": "6b0be91a719257db7f21a4b5aef0121a0651fb22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 686, "license_type": "no_license", "max_line_length": 50, "num_lines": 24, "path": "/legacy/devices/filters.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nimport django_filters\n\nfrom .models import RawData\n\n\nclass RawDataFilter(django_filters.FilterSet):\n value_gte = django_filters.NumberFilter(\n name='value', lookup_type='gte')\n value_lte = django_filters.NumberFilter(\n name='value', lookup_type='lte')\n timestamp_gte = django_filters.DateTimeFilter(\n name='timestamp', lookup_type='gte')\n timestamp_lte = django_filters.DateTimeFilter(\n name='timestamp', lookup_type='lte')\n\n class Meta:\n model = RawData\n fields = [\n 'physicalinput',\n 'value_gte', 'value_lte',\n 'timestamp_gte', 'timestamp_lte'\n ]\n" }, { "alpha_fraction": 0.7668740749359131, "alphanum_fraction": 0.767352819442749, "avg_line_length": 32.69355010986328, "blob_id": "456d27898e57f48369122e2a731c37cab659b173", "content_id": "8f04436b4b31f571d6c1665c497a634f23843c53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2089, "license_type": "no_license", "max_line_length": 71, "num_lines": 62, "path": "/gridplatform/datasequences/models/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.functional import cached_property\n\nfrom .accumulation import AccumulationBase\nfrom .accumulation import AccumulationPeriodBase\nfrom .accumulation import NonpulseAccumulationPeriodMixin\nfrom .accumulation import PulseAccumulationPeriodMixin\nfrom .accumulation import SingleValueAccumulationPeriodMixin\nfrom .base import DataSequenceBase\nfrom .base import PeriodBase\nfrom .base import is_clock_hour\nfrom .piecewiseconstant import PiecewiseConstantBase\nfrom .piecewiseconstant import PiecewiseConstantPeriodBase\nfrom .piecewiseconstant import PiecewiseConstantPeriodManager\n\nfrom .energyconversion import EnergyPerVolumeDataSequence\nfrom .energyconversion import EnergyPerVolumePeriod\nfrom .nonaccumulation import NonaccumulationDataSequence\nfrom .nonaccumulation import NonaccumulationPeriod\nfrom .qualitycontrol import OfflineToleranceMixin\nfrom .qualitycontrol import NonaccumulationOfflineTolerance\n\n__all__ = [\n 'PeriodBase',\n 'AccumulationBase',\n 'AccumulationPeriodBase',\n 'DataSequence',\n 'DataSequenceBase',\n 'EnergyPerVolumeDataSequence',\n 'EnergyPerVolumePeriod',\n 'NonaccumulationDataSequence',\n 'NonaccumulationOfflineTolerance',\n 'NonaccumulationPeriod',\n 'NonpulseAccumulationPeriodMixin',\n 'PiecewiseConstantBase',\n 'PiecewiseConstantPeriodBase',\n 'PiecewiseConstantPeriodManager',\n 'PeriodBase',\n 'PulseAccumulationPeriodMixin',\n 'SingleValueAccumulationPeriodMixin',\n 'OfflineToleranceMixin',\n 'CurrencyUnitMixin',\n 'is_clock_hour'\n]\n\n\nclass CurrencyUnitMixin(object):\n \"\"\"\n Gives ``self.currency_unit`` property, given `self.unit` contains a\n currency.\n \"\"\"\n @cached_property\n def currency_unit(self):\n currency_units = ['currency_dkk', 'currency_eur']\n for currency_unit in currency_units:\n if currency_unit in self.unit:\n return currency_unit\n assert False, 'currency unit in \"%s\" not recognized' % (\n self.unit)\n" }, { "alpha_fraction": 0.6179587244987488, "alphanum_fraction": 0.6296709179878235, "avg_line_length": 37.559139251708984, "blob_id": "fe2e9e475a49e921a592870f1f2302c44fdf37e6", "content_id": "c68b638e84e8bf66488e27af8fad8af6ef6de251", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7172, "license_type": "no_license", "max_line_length": 79, "num_lines": 186, "path": "/legacy/display_indexes/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module contains tests for the display_indexes Django app.\n\"\"\"\n\nfrom decimal import Decimal\nimport datetime\n\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\n\nfrom mock import patch\nimport pytz\nimport unittest\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.shell import Request\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\n\nfrom .views import graph_task\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ViewTest(TestCase):\n \"\"\"\n Tests for the view module.\n \"\"\"\n fixtures = [\"manage_indexes_test.json\"]\n\n def setUp(self):\n \"\"\"\n Setup test fixture as if we are logged in as some user called\n super.\n \"\"\"\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n self.customer = User.objects.get(\n id=self.client.session[\"_auth_user_id\"]).customer\n self.request = Request('super', '123')\n\n @unittest.skip(\"self.client session state cannot decrypt these objects...\")\n def test_index_view(self):\n self.index_el = Index.objects.create(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Test electricity index for customer\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n\n self.another_customer_index = Index.objects.create(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Test index for another customer\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n customer=Customer.objects.create(),\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n\n response = self.client.get('/overview/indexes/')\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, self.index_el.name)\n self.assertNotContains(response, self.another_customer_index.name)\n\n def test_detail_view_success(self):\n self.index_el = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"Test electricity index for customer\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone=self.customer.timezone)\n self.index_el._exclude_field_from_validation = ['name']\n self.index_el.save()\n\n customer = Customer()\n customer.save()\n\n response = self.client.get('/overview/indexes/%s/' % self.index_el.id)\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, self.index_el.name)\n\n def test_graph(self):\n \"\"\"\n Test that the Index graph displays the exact hourly tarriffs\n for the last 24 hours. This test is expected to fail for part\n of a unfortunate single microsecond every hour, i.e. with\n probability M{< 1/3600000}.\n \"\"\"\n # Create an index and populate it with some recognizable\n # values.\n timezone = pytz.timezone(\"Europe/Copenhagen\")\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Nordpool spot-tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=timezone,\n data_format=Index.SPOT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n index.save()\n start_time = timezone.localize(\n datetime.datetime.now()).replace(\n hour=0, minute=0, second=0, microsecond=0)\n current_time = start_time\n for i in range(24):\n index.entry_set.create(\n from_timestamp=current_time,\n to_timestamp=current_time + datetime.timedelta(hours=1),\n value=Decimal(i))\n current_time += datetime.timedelta(hours=1)\n\n # Aquire the JSON data defining the graph.\n response = self.client.get(\"/overview/indexes/graph/%d/\" % index.id)\n self.assertEqual(response.status_code, 200)\n\n # Verify that the recognizable values are held within the\n # graph.\n for i in range(24):\n self.assertIn(str(i), response.content)\n\n def test_async_graph_last_24h(self):\n class PhonyAsync:\n id = 42\n status = 'PHONY'\n\n timezone = pytz.timezone(\"Europe/Copenhagen\")\n to_timestamp = condense.floor(\n datetime.datetime.now(pytz.utc) + RelativeTimeDelta(hours=1),\n RelativeTimeDelta(hours=1),\n timezone)\n from_timestamp = to_timestamp - RelativeTimeDelta(hours=24)\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Nordpool spot-tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=timezone,\n data_format=Index.SPOT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n index.save()\n\n with patch.object(graph_task, 'delay',\n return_value=PhonyAsync()) as mock:\n result = self.client.post(\n '/overview/indexes/async_graph_last_24h/%d/' % index.id, {})\n self.assertContains(result, PhonyAsync.id)\n self.assertContains(result, PhonyAsync.status)\n\n mock.assert_called_with('%d' % index.id, from_timestamp, to_timestamp)\n\n def test_embedded_url_in_slide_in_menu(self):\n \"\"\"\n This test validates that the links for the indexes in the\n slide-in menu contains the from_date and to_date in the url.\n \"\"\"\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"Test index\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n index.save()\n\n response = self.client.get('/overview/indexes/')\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, index.name_plain)\n\n response = self.client.get(\n '/overview/indexes/%s/?from_date=2012-01-01&to_date=2012-12-31'\n % index.id)\n self.assertNotContains(response, 'XYZXYZXYZ')\n self.assertContains(response, index.name_plain)\n self.assertContains(\n response,\n '/overview/indexes/%s/?from_date=2012-01-01&to_date=2012-12-31'\n % index.id)\n" }, { "alpha_fraction": 0.6957424879074097, "alphanum_fraction": 0.6967809200286865, "avg_line_length": 31.100000381469727, "blob_id": "98ddbfbc052b436384385078a6615270a6b38d7c", "content_id": "d1a5c66ec9bcdf14677e87c848baf126ec8065ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 963, "license_type": "no_license", "max_line_length": 79, "num_lines": 30, "path": "/legacy/legacy_utils/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.models import Collection\n\n\n# Legacy user profile. Placed here instead of making another app just for\n# this one model.\n\nclass UserProfile(models.Model):\n \"\"\"\n \"Extra\" user information specific to customer users. For the GridPortal,\n this is the active User Profile; other applications on the GridPlatform may\n use something else.\n \"\"\"\n user = models.OneToOneField('users.User', on_delete=models.CASCADE)\n collections = models.ManyToManyField(\n Collection,\n through='customers.CollectionConstraint')\n\n class Meta:\n verbose_name = _('user profile')\n verbose_name_plural = _('user profiles')\n ordering = ['id']\n db_table = 'customers_userprofile'\n app_label = 'customers'\n" }, { "alpha_fraction": 0.6891345381736755, "alphanum_fraction": 0.6918306946754456, "avg_line_length": 27.53076934814453, "blob_id": "7a44399418e28b184b8f937de3e2b063cd48b124", "content_id": "8669ff7e0f9911be93b181d47d6d55eea3be5941", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3709, "license_type": "no_license", "max_line_length": 79, "num_lines": 130, "path": "/gridplatform/encryption/cipher.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThis module wraps the parts of the Python Cryptography Toolkit (pycrypto)\nthat is used in this encryption app. The pycrypto package requires some form\nof native compilation during installation, which makes it nontrivial to install\ncorrectly on windows machines. So to support the possible case of an\nalternative cryptography toolkit in some deployments this cipher module can be\nswitched out per deployment via :data:`settings.ENCRYPTION_CIPHER_MODULE`.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nfrom Crypto.Cipher import PKCS1_OAEP\nfrom Crypto.Hash import SHA256\nfrom Crypto.PublicKey import RSA\n\n\nfrom .conf import settings\n\n\ndef _random_bytes(count):\n return Random.new().read(count)\n\n\ndef generate_iv():\n \"\"\"\n Generate a random encryption data initialization vector of size\n :data:`AES.block_size`.\n \"\"\"\n return _random_bytes(AES.block_size)\n\n\ndef generate_symmetric_key():\n \"\"\"\n Generate a random symmetric key of size\n :data:`settings.ENCRYPTION_AES_KEYLENGTH`.\n \"\"\"\n assert settings.ENCRYPTION_AES_KEYLENGTH in AES.key_size\n return _random_bytes(settings.ENCRYPTION_AES_KEYLENGTH)\n\n\ndef hash_symmetric_key(text):\n \"\"\"\n One-way hash of symmetric key ``text`` (usually a password). The result is\n intended to be used as ``key`` argument to :func:`.symmetric_cipher`.\n\n :return: A hash of ``text``.\n \"\"\"\n key = SHA256.new(text).digest()\n assert len(key) in AES.key_size\n return key\n\n\ndef symmetric_cipher(key, iv):\n \"\"\"\n Construct symmetric cipher object from given key and encryption data\n initialization vector.\n\n :param key: The given key, (a password hashed by\n :func:`.hash_symmetric_key`).\n\n :param iv: The given encryption data initialization vector (random bytes\n generated per symmetric cipher using :func:`.generate_iv`).\n \"\"\"\n return AES.new(key, AES.MODE_CFB, iv)\n\n\ndef generate_private_public_keypair():\n \"\"\"\n Generate a private-public key pair.\n\n :return: A tuple with first element being the private key and the second\n being the public key. The keys are in a textual representation.\n \"\"\"\n rsa_key = RSA.generate(settings.ENCRYPTION_RSA_KEYLENGTH)\n private_key = rsa_key.exportKey(format='DER')\n public_key = rsa_key.publickey().exportKey(format='DER')\n return (private_key, public_key)\n\n\ndef load_private_key(text):\n \"\"\"\n Load a private key object from given private key text representation.\n\n :param text: The text representation of the private key (from first element\n in result of :func:`.generate_private_public_keypair`)\n \"\"\"\n key = RSA.importKey(text)\n assert key.has_private()\n return key\n\n\ndef load_public_key(text):\n \"\"\"\n Load a public key object from given public key text representation.\n\n :param text: The text representation of the public key (from second element\n in result of :func:`.generate_private_public_keypair`)\n \"\"\"\n key = RSA.importKey(text)\n assert not key.has_private()\n return key\n\n\ndef private_key_cipher(key):\n \"\"\"\n Construct a cipher object from a given private key.\n\n :param key: The given private key (as returned by\n :func:`.load_private_key`).\n\n :return: A cipher object.\n \"\"\"\n assert key.has_private()\n return PKCS1_OAEP.new(key)\n\n\ndef public_key_cipher(key):\n \"\"\"\n Construct a cipher object from a given public key.\n\n :param key: The given public key (as returned by\n :func:`.load_public_key`).\n\n :return: A cipher object.\n \"\"\"\n assert not key.has_private()\n return PKCS1_OAEP.new(key)\n" }, { "alpha_fraction": 0.7297714352607727, "alphanum_fraction": 0.7330142259597778, "avg_line_length": 35.382022857666016, "blob_id": "018b7e922ce9068e5b7a3c557f0d39c89e0e0b6a", "content_id": "289c11681d7dc54a4ea79d03b96b610717ad31a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 6476, "license_type": "no_license", "max_line_length": 81, "num_lines": 178, "path": "/documentation/source/architecture.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "*********************\nSoftware Architecture\n*********************\n\nThe GridPlatform is an energy management platform, meaning it supposed to be\nthe foundation on which to build Energy Management System (EMS) software\nproducts. Therefore there is a natural overall layered archicture with the\nGridPlatform at the bottom.\n\nThe now legacy GridPortal 2.0 has been integrated with GridPlatform using a few\nwrappers and can therefore be seen as one instance of an EMS. However, as it is\nlegacy it does have some of its own concepts that are not part of the\nGridPlatform as well as different interpretation of such concepts. One example\nis that the GridPortal 2.0 has a generic concept of ``indexes`` and the\nGridPlatform has a concept of ``tariffs``. Price indexes in GridPortal 2.0 are\nused similarly to how tariffs are used in the GridPlatform but are in no way\nconnected, nor should they be. The data models in the GridPlatform are superior\nto those in GridPortal 2.0, and no further development, apart from bug fixes, are\nplanned for GridPortal 2.0.\n\nA small EMS product, simply called Energy Manager, has been built on top of the\nGridPlatform. The original vision was for this to eventually replace GridPortal\n2.0, however, as development was cancelled in early stages this product turned\ninto a GridPlatfrom proof-of-concept implementation, and was used to drive the\nfurther development of the GridPlatform.\n\nThe GridPlatform is intended to be heavily used via REST web services, so\nfuture EMS software products may be implemented on top of the GridPlatform\nusing purely this interface, or they can built on top of it using Django like\nthe Energy Manager example does. Or indeed a mix of both if that makes the most\nsense.\n\nEnergy Manager and GridPortal only use the Django Interface. Asynchronous HTTP\nrequests made by them are made using their own Django views.\n\nThe overall architecture can be visualised as follows:\n\n.. code-block:: none\n\n +---------------------------------+\n | Energy Manager | GridPortal 2.0 |\n +--------------------------------------------------+\n | REST API | Django API |\n | GridPlatform |\n +--------------------------------------------------+\n\n\nLogging\n=======\n\n- Web traffic logging is done by ``nginx`` and the logs can normally be found\n in `/var/log/nginx`.\n\n- PostgreSQL logs can normally be found in `/var/log/postgreqsql`\n\n- Django and Celery error messages are not logged on the servers but are\n e-mailed directly to the list of administrators listed in the Django settings\n file.\n\n- GridAgent Server logs are located in the GridAgent Server directory.\n\n.. _architecture-cloud-architecture:\n\n******************\nCloud Architecture\n******************\nThe GridPlatform is designed to run in a cloud infrastructure for easy\nexpansion of resources as it becomes necessary. It is highly scalable and is\nmeant to be run in a distributed fashion across many servers. However, it is\nalso flexible in its deployment allowing for easy single server setups as well,\nand can run on any Linux system with enough resources running PostgreSQL. All\nthird part software used are free and open source.\n\nThe deployment architecture consists of the following component types\nresponsible for running the listed software services:\n\n\nWeb server load balancer\n========================\nOnly used in a multiple server deployment.\n\n\nWeb server\n==========\n\n- Nginx: Web server.\n\n- uWSGI: WSGI compliant application server for running the GridManager\n GridPlatform Django application.\n\n- Memcached: Distributed object caching system.\n\n\nMessage queue server\n====================\n\n- RabbitMQ: AMQP compliant message queue server.\n\n\nDatabase server\n===============\n\n- PostgreSQL\n\n\nHeavy computation server\n========================\n\n- Celery: Distributed task queue. The GridManager GridPlatform celery worker\n threads run on these types of servers.\n\n- Cache Generator: GridManager script for condensing energy measurements in\n to 1 hour and 5 minute periods.\n\n\nGridAgent Server\n================\n\n- Running the GridManager GridAgent Server Python application\n\n\nGridAgent Rules Server\n======================\n\nRule monitoring, execution and transmission.\n\n- GridAgent Rule Engine: GridManager Django application that continuously\n checks the specified rule constraints that customers have specified and runs\n specified actions when needed.\n *Note: This is not a distributed service. Only one rule engine should be\n running at any given time or actions might get triggered twice.*\n\n- GridAgent Rules Updater: GridManager script for transmitting specified\n rules to the GridAgents. Meant to run at the beginning of each clock hour.\n *Note: Only rules that can be handled solely by a single GridAgent are\n transmitted.*\n\n\nPeriodic Task Server\n====================\n\nThe services listed below are all meant to be run as only one instance each in\nthe cloud. They can of course be run on serveral different servers, though none\nof them are very computation nor memory hungry.\n\n- Nord Pool Spot prices import: GridManager script for importing spot prices\n from the Nord Pool FTP server.\n\n- Energinet.dk |CO2| index import: GridManager script for importing |CO2|/kWh\n data from Energinet.dk.\n\n .. |CO2| replace:: CO\\ :sub:`2`\n\n- Erroneous Peak Remover: A bug in old version of the GridManager GridPoint 3\n phase meter caused erroneous measurements being transmitted. A GridManager\n detects these abnormal measurements and deletes them.\n *Note: Must be run before cache generation to prevent the erroneous\n measurements affecting the cached values.*\n\n- Clear Django sessions: A Django script for cleaning the database of any\n dead sessions.\n\n\nSharding\n========\n\nTo support really large amounts of data, *sharding* should be\nconsidered. Partitioning of the data is trivial: It is naturally divided on\ncustomers. Customer data can then be distributed across many databases,\nconstrained by keeping data related to the same customer in the same database.\n\nThe web servers will then use a routing algorithm to use the correct database\nfor each logged in user. Many such schemas exists and libraries exists for\nimplementing such functionality trivial.\n\nAs we were nowhere near an amount of data that would necessitate sharding, it\nhas not been implemented; though the architecture is built with it in mind,\nallowing future developers to add sharding later.\n" }, { "alpha_fraction": 0.7635495662689209, "alphanum_fraction": 0.7657961249351501, "avg_line_length": 39.931034088134766, "blob_id": "8c64cf7ec10a0df7f4c94dab02f5d98d2ce517e0", "content_id": "3b02fbb01ace810ba6e25233d8f7d2ad6e4720a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 7149, "license_type": "no_license", "max_line_length": 82, "num_lines": 174, "path": "/documentation/source/samplesequences.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Sequences of Samples and their Operations\n=========================================\n\nData sources continuously bring sequences of samples into the system:\n\n * Utility consumption (m³, kWh),\n * Pulse (impulse),\n * CO₂ conversions (tonne/kWh, tonne/m³),\n * Tariffs (EUR/kWh, EUR/m³)\n\nMain consumptions and energy uses define other sequences of samples in\nterms of:\n\n * Variable costs (EUR),\n * Utility consumption (m³, kWh),\n * Energy consumption (kWh),\n * CO₂ emissions,\n * Energy performances,\n * Normalized consumptions,\n * Normalized variable costs, and so on.\n\nThe sequences of samples can be classified according to what\noperations can be applied to them and how they can be combined.\n\nSequences of Accumulating Ranged Samples\n----------------------------------------\n\nThese are the most forgiving kind of sample sequences. Each sample\ncovers a time range and holds a physical quantity. Sequences of\naccumulating ranged samples fit well into bar charts.\n\nThe samples of multiple such sequences having the same time range can\nbe added or subtracted to form a new sequence of accumulating ranged\nsamples.\n\nSamples of smaller time ranges may be accumulated over larger time\nranges, forming new samples with the larger time ranges. Doing so on\na sequence of accumulating ranged samples result in a new such\nsequence.\n\nFor sequences of accumulating ranged samples accumulation across all\nthe samples within a given time range is generally well-defined.\nGiven compatible units, this enables multiple sequences of\naccumulating ranged samples to be displayed in the same pie chart.\n\nTypical units for these sequences include m³, kWh, impulse, EUR, h,\nand tonne.\n\n.. _sequences-of-conversion-ranged-samples:\n\nSequences of Conversion Ranged Samples\n--------------------------------------\n\nIn their data structure these will resemble sequences of accumulating\nranged samples quite a lot. And while adding (or subtracting) samples\nwith the same time range of sequences of conversion ranged samples\nindeed result in new such sequences, and is well defined, accumulating\nsamples (or any other form of aggregation) across time ranges is not\nwell-defined.\n\nSequences of conversion ranged samples are typically illustrated as a\npiece-wise constant function in a graph.\n\nTypical units for these sequences include EUR/m³, EUR/kWh, kWh/m³,\nm³/impulse, kWh/impulse, tonne/kWh and tonne/m³.\n\nNote that while the units of conversion ranged samples in general seem\nto be fractions, the implication does not go both ways. There are\nranged samples whose units are fractions that can't be said to be\nconversion ranged samples. See sequences of fractional ranged\nsamples.\n\nSequences of conversion ranged samples may be sample-wise multiplied\nwith a sequence of accumulation ranged samples, resulting in a new\nsequence of accumulation ranged samples, having the units that would\nresult from the multiplication (e.g. a sequence of conversion ranged\nsample with unit EUR/m³ multiplied with a sequence of accumulation\nranged samples with unit m³ gives a sequence of accumulation ranged\nsamples with the unit EUR). The time range of multiplied samples must\nmatch exactly. If the sequence of accumulated ranged samples is in a\ntoo fine time range resolution, it should be accumulated to the matching\ntime resolution as described earlier before multiplication.\n\nSequences of Fractional Ranged Samples\n--------------------------------------\n\nGiven two sequences of accumulating ranged samples, we can sample-wise\ndivide one with the other (if the sample of other is not zero). A\ngreat deal of information is lost in this process, yet the result is\noften easy for humans to interpret.\n\nBecause of the information loss, no aggregation of samples across\nperiods is well-defined. Sample-wise addition of two sequences of\nfractional ranged samples is also not well-defined. Data sources on\nthis form in general should be avoided as they provide the system with\nvery little information to work with.\n\nTypical semantics of these sequences of fractional ranged samples include:\n\n * Marginal energy consumption (kWh/pcs),\n * Heat-loss coefficient (W/°K),\n * Cool-down temperature of distribution medium for district heating (°K),\n * Mean power (W),\n * Mean flow (m³/h),\n * Marginal CO₂ emissions (tonne/pcs),\n * Mean power factor (kWh/kVAh), and so on.\n\nWhile aggregation of samples is out of the question, it is possible to\ncalculate sequences of fractional ranged samples in any time range\nresolution in which the input sequences of accumulated ranged samples\nare available. For example mean power can both be calculated hour by\nhour, and day by day.\n\nSequences of fractional ranged samples may be used as sequences of\nconversion ranged samples in normalization of consumptions and costs.\nFor instance marginal energy consumption (kWh/pcs) can be used to\nconvert normal productions (pcs) to normalized energy consumption\n(kWh).\n\n.. _sequences-of-continuous-point-samples:\n\nSequences of Continuous Point Samples\n-------------------------------------\n\nThese sequences sample underlying continuous functions, and may stem\nfrom data sources, or be calculated from other sequences of continuous\npoint samples.\n\nSequences of continuous point samples are graphed by continuous\nfunction by linear interpolation.\n\nTypical semantics of sequences of continuous point samples include:\n\n * Power (W),\n * Electrical current (A),\n * Voltage (V),\n * Temperature (°K),\n * Power factor (kW/kVA),\n * Reactive power (VAr),\n * Volume flow (m³/h), and so on.\n\n.. _sequences-of-ranged-samples-aggregating-sequences-of-continuous-point-samples:\n\nSequences of Ranged Samples Aggregating Sequences of Continuous Point Samples\n-----------------------------------------------------------------------------\n\nSequences of continuous point samples can be converted to sequences of\naggregate ranged samples, by aggregation across time ranges\ncorresponding to the time ranges of the ranged samples in the\nresulting sequence of aggregate ranged samples. Well-defined\naggregate functions for this include average, minimum and maximum.\n\nIf the desired sequence of aggregate ranged samples alternatively can\nbe defined as a sequence of fractional ranged samples this is to be\npreferred for its higher precision. For instance mean power should\nbe defined by a sequence of fractional ranged samples, so the result\nis the actual mean, and not just a sampled mean, where as mean outdoor\ntemperature often cannot be defined by such a sequence of fractional\nranged samples (though it would be possible to create such a meter).\n\nTypical semantics of sequences of ranged samples aggregating sequences\nof continuous point samples include:\n\n * Minimum outdoor temperature (°K),\n * Maximum outdoor temperature (°K),\n * Average outdoor temperature (°K).\n\nAnother interesting class of aggregate functions to consider is\nconditional-time-weighed sums. The resulting sequence of ranged\nsamples aggregating sequences of continuous point samples is in fact a\nsequence of accumulating ranged samples. Examples include:\n\n * Heating degree days (°K*days)\n * Cooling degree days (°K*days)\n" }, { "alpha_fraction": 0.6550037860870361, "alphanum_fraction": 0.6552104353904724, "avg_line_length": 32.68677520751953, "blob_id": "d09b5fe56140c5603b9f9a7b3ad10212a5256e82", "content_id": "7ff549846eb48fc4e76f1bd44b648afc7d030bdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14519, "license_type": "no_license", "max_line_length": 79, "num_lines": 431, "path": "/gridplatform/utils/generic_views/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nDjango generic views and extra_views generic views wrapped with access control\nand localized form fields by default.\n\nChecks for logged in for read-only views; checks for add, change and delete\npermissions for the models involved as appropriate otherwise. (Access control\nis implemented using mixin classes from braces.)\n\nThis is intended to be imported as ``from gridplatform.utils import\ngeneric_views`` --- i.e. so that the generic views are referred to with the\nmodule as prefix on use, to make it explicit whether we use these or the base\nDjango generic views.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nfrom django.db.models import Q\nimport django.views.generic\n\nimport extra_views\nimport extra_views.formsets\nimport extra_views.advanced\n\nfrom .access_control import CustomerBoundMixin\nfrom .access_control import LoginRequiredMixin\nfrom .access_control import ModelPermissionRequiredMixin\nfrom .access_control import MultipleModelPermissionsRequiredMixin\nfrom .localized import LocalizedModelFormMixin\nfrom .localized import LocalizedModelFormSetMixin\nfrom .localized import LocalizedInlineFormSetMixin\n\n\n__all__ = [\n # read only; no explicit permission checks\n 'ListView',\n 'DetailView',\n # normal generic views with permission checks added\n 'CreateView',\n 'DeleteView',\n 'UpdateView',\n # extra_views\n 'InlineFormSet',\n 'ModelFormSetView',\n 'InlineFormSetView',\n 'CreateWithInlinesView',\n 'UpdateWithInlinesView',\n]\n\n\nclass InlineFormSet(\n LocalizedInlineFormSetMixin,\n CustomerBoundMixin,\n extra_views.InlineFormSet):\n \"\"\"\n Specialisation of :class:`extra_views.InlineFormSet` which adds\n ``localized_fields`` to parameters to ``modelformset_factory()``.\n \"\"\"\n pass\n\n\nclass View(\n LoginRequiredMixin,\n CustomerBoundMixin,\n django.views.generic.View):\n \"\"\"\n :class:`django.views.generic.View` specialization that requires\n login and is bound to the customer in context.\n \"\"\"\n pass\n\n\nclass TemplateView(\n LoginRequiredMixin,\n CustomerBoundMixin,\n django.views.generic.TemplateView):\n \"\"\"\n :class:`django.views.generic.TemplateView` specialization that\n requires login and is bound to the customer in context.\n \"\"\"\n pass\n\n\nclass SearchableListMixin(extra_views.SearchableListMixin):\n \"\"\"\n Mix :meth:`~.SearchableListMixin.get_queryset` into a view to\n allow for querying encrypted fields as well.\n\n :class:`extra_views.SearchableListMixin` specialization that\n replaces :meth:`~.SearchableListMixin.get_queryset` with a version\n that delegates search to\n ``self.model.objects.decrypting_search()`` if possible.\n \"\"\"\n def get_queryset(self):\n # Note that the super call skips a level. This is our replacement for\n # extra_views.SearchableListMixin.get_queryset.\n qs = super(extra_views.SearchableListMixin, self).get_queryset()\n query = self.get_search_query()\n if query and not hasattr(self.model.objects, 'decrypting_search'):\n w_qs = []\n search_pairs = self.get_search_fields_with_filters()\n for word in self.get_words(query):\n filters = [\n Q(**{'%s__%s' % (pair[0], pair[1]): word})\n for pair in search_pairs\n ]\n if self.search_date_fields:\n dt = self.try_convert_to_date(word)\n if dt:\n filters.extend([\n Q(**{field_name: dt})\n for field_name in self.search_date_fields\n ])\n w_qs.append(reduce(operator.or_, filters))\n qs = qs.filter(reduce(operator.and_, w_qs)).distinct()\n elif query:\n for word in self.get_words(query):\n qs = qs.decrypting_search(word, self.search_fields)\n return qs\n\n\nclass ListView(\n LoginRequiredMixin,\n CustomerBoundMixin,\n extra_views.SortableListMixin,\n SearchableListMixin,\n django.views.generic.ListView):\n \"\"\"\n Render list of objects from specified model.\n\n Set attribute ``model`` or override\n :meth:`~.ListView.get_queryset` to specify objects.\n\n By default, this will be rendered to template\n ``{app_label}/{model_name}_list.html`` -- to override, specify\n ``template_name`` attribute.\n\n The template will have access to the object list in variables\n ``object_list`` and ``{model_name}_list``, and to the generic view\n object in variable ``view``.\n\n If more data should be provided to template, override\n :meth:`~.ListView.get_context_data`. The conventional pattern\n for such extension is::\n\n def get_context_data(self, **kwargs):\n context = {\n ...\n }\n context.update(kwargs)\n return super(..., self).get_context_data(**context)\n\n There are numerous other hooks/extension points, though those should not\n normally be needed.\n\n This view supports is sortable on encrypted and non-encrypted fields.\n\n You can provide either sort_fields as a plain list like\n ['id', 'some', 'foo__bar', ...] or, if you want to hide original field\n names you can provide list of tuples with aliases that will be used by\n setting sort_field_aliases, e.g.:\n [('id', 'by_id'), ('some', 'show_this'), ('foo__bar', 'bar')]\n\n Supports GET parameters:\n 'o': For field to sort by\n 'ot': For sorting type: 'asc' or 'desc', default is 'asc'\n \"\"\"\n\n def _sort_queryset(self, queryset):\n self.sort_helper = self.get_sort_helper()\n sort = self.sort_helper.get_sort()\n if sort:\n if hasattr(queryset, 'decrypting_order_by'):\n queryset = queryset.decrypting_order_by(sort)\n else:\n queryset = queryset.order_by(sort)\n return queryset\n\n\nclass DetailView(\n LoginRequiredMixin,\n CustomerBoundMixin,\n django.views.generic.DetailView):\n \"\"\"\n Render single object of specified model.\n\n Should be exposed in an URL with a ``pk`` keyword argument; this\n will specify the primary key/ID of the object to render.\n\n Set attribute ``model`` to specify model class.\n\n By default, this will be rendered to template\n ``{app_label}/{model_name}_detail.html`` -- to override, specify\n ``template_name`` attribute.\n\n The template will have access to the object in variables ``object`` and\n ``{model_name}``, and to the generic view object in variable ``view``.\n\n If more data should be provided to template, override\n :meth:`~.DetailView.get_context_data` -- the conventional\n pattern for such extension is::\n\n def get_context_data(self, **kwargs):\n context = {\n ...\n }\n context.update(kwargs)\n return super(..., self).get_context_data(context)\n\n There are numerous other hooks/extension points, though those should not\n normally be needed...\n \"\"\"\n pass\n\n\nclass CreateView(\n ModelPermissionRequiredMixin,\n LocalizedModelFormMixin,\n CustomerBoundMixin,\n django.views.generic.CreateView):\n \"\"\"\n Render model form for specified model on GET; saves and redirects if model\n validates on POST, otherwise renders model form with the errors.\n\n If the model specifies a :meth:`~.CreateView.get_absolute_url`,\n then the default URL to redirect to will be the result of calling\n :meth:`~django.db.models.Model.get_absolute_url` on the saved\n object. Override :meth:`~.CreateView.get_success_url` to\n specify a different URL --- note that, at that point, the saved\n object will be available in ``self.object``.\n\n Set attribute ``model`` to specify model class.\n\n By default, a modelform for the model class is constructed, with its\n ``fields`` specification taken from the ``fields`` attribute on the view.\n An alternative modelform may be specified by setting ``form_class``.\n\n By default, this will be rendered to template\n ``{app_label}/{model_name}_form.html`` --- to override, specify\n ``template_name`` attribute.\n\n The template will have access to the modelform in variable ``form``, and to\n the generic view object in variable ``view``.\n\n If more data should be provided to template, override\n :meth:`~.CreateView.get_context_data` --- the conventional pattern\n for such extension is::\n\n def get_context_data(self, **kwargs):\n context = {\n ...\n }\n context.update(kwargs)\n return super(..., self).get_context_data(context)\n\n There are numerous other hooks/extension points, though those should not\n normally be needed...\n \"\"\"\n model_permission = 'add'\n\n\nclass DeleteView(\n ModelPermissionRequiredMixin,\n CustomerBoundMixin,\n django.views.generic.DeleteView):\n \"\"\"\n Delete a model object, then redirect.\n\n Should be exposed in an URL with a ``pk`` keyword argument; this\n will specify the primary key/ID of the object to delete.\n\n Set attribute ``model`` to specify model class.\n\n Override :meth:`~.DeleteView.get_success_url` to specify the URL\n to redirect to --- note that this is called *before* the object is\n deleted, with the object available in ``self.object``.\n \"\"\"\n model_permission = 'delete'\n\n\nclass UpdateView(\n ModelPermissionRequiredMixin,\n LocalizedModelFormMixin,\n CustomerBoundMixin,\n django.views.generic.UpdateView):\n \"\"\"\n Render model form for specified object on GET; saves and redirects if model\n validates on POST, otherwise renders model form with the errors.\n\n Should be exposed in an URL with a ``pk`` keyword argument; this\n will specify the primary key/ID of the object to update.\n\n If the model specifies a\n :meth:`~django.db.models.Model.get_absolute_url`, then the\n default URL to redirect to will be the result of calling\n :meth:`~django.db.models.Model.get_absolute_url` on the saved\n object. Override :meth:`~.UpdateView.get_success_url` to\n specify a different URL --- note that, at that point, the saved\n object will be available in ``self.object``.\n\n Set attribute ``model`` to specify model class.\n\n By default, a modelform for the model class is constructed, with its\n ``fields`` specification taken from the ``fields`` attribute on the view.\n An alternative modelform may be specified by setting ``form_class``.\n\n By default, this will be rendered to template\n ``{app_label}/{model_name}_form.html`` --- to override, specify\n ``template_name`` attribute.\n\n The template will have access to the object in variables ``object`` and\n ``{model_name}``, to the modelform in variable ``form``, and to the generic\n view object in variable ``view``.\n\n If more data should be provided to template, override\n :meth:`~.UpdateView.get_context_data` --- the conventional pattern\n for such extension is::\n\n def get_context_data(self, **kwargs):\n context = {\n ...\n }\n context.update(kwargs)\n return super(..., self).get_context_data(context)\n\n There are numerous other hooks/extension points, though those should not\n normally be needed...\n \"\"\"\n model_permission = 'change'\n\n\nclass ModelFormSetView(\n MultipleModelPermissionsRequiredMixin,\n LocalizedModelFormSetMixin,\n CustomerBoundMixin,\n extra_views.ModelFormSetView):\n \"\"\"\n :class:`extra_views.ModelFormSetView` specialization that require\n permissions, localizes model formset and binds to a customer.\n \"\"\"\n model_permissions = ('add', 'delete', 'change')\n\n def get_permissions_models(self):\n \"\"\"\n :return: The models for which to check permissions.\n \"\"\"\n model = self.model or self.get_queryset().model\n return [model]\n\n\nclass InlineFormSetView(\n MultipleModelPermissionsRequiredMixin,\n LocalizedModelFormSetMixin,\n CustomerBoundMixin,\n extra_views.InlineFormSetView):\n \"\"\"\n :class:`extra_views.InlineFormSetView` specialization that require\n permissions, localizes model formset and binds to a customer.\n \"\"\"\n model_permissions = ('add', 'delete', 'change')\n\n def get_permissions_models(self):\n \"\"\"\n :return: The models for which to check permissions.\n \"\"\"\n model = self.get_inline_model()\n return [model]\n\n\nclass CreateWithInlinesView(\n MultipleModelPermissionsRequiredMixin,\n LocalizedModelFormMixin,\n CustomerBoundMixin,\n extra_views.CreateWithInlinesView):\n \"\"\"\n :class:`extra_views.CreateWithInlinesView` specialization that\n require permissions, localizes model formset and binds to a\n customer.\n \"\"\"\n model_permissions = ('add',)\n # NOTE: Localized by using our specialisation of InlineFormSet;\n # not by mixin...\n\n def get_permissions_models(self):\n \"\"\"\n :return: The models for which to check permissions.\n \"\"\"\n base_model = self.model or self.get_queryset().model\n inline_models = [\n inline.model\n for inline in self.get_inlines()\n ]\n return [base_model] + inline_models\n\n\nclass UpdateWithInlinesView(\n MultipleModelPermissionsRequiredMixin,\n LocalizedModelFormMixin,\n CustomerBoundMixin,\n extra_views.UpdateWithInlinesView):\n \"\"\"\n :class:`extra_views.UpdateWithInlinesView` specialization that\n require permissions, localizes model formset and binds to a\n customer.\n \"\"\"\n model_permissions = ('add', 'delete', 'change')\n # NOTE: Localized by using our specialisation of InlineFormSet;\n # not by mixin...\n\n def get_permissions_models(self):\n \"\"\"\n :return: The models for which to check permissions.\n \"\"\"\n base_model = self.model or self.get_queryset().model\n inline_models = [\n inline.model\n for inline in self.get_inlines()\n ]\n return [base_model] + inline_models\n\n\nclass FormView(\n LoginRequiredMixin,\n CustomerBoundMixin,\n django.views.generic.FormView):\n \"\"\"\n :class:`django.views.generic.FormView` specialization that require\n login and binds to a customer.\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.5954738259315491, "alphanum_fraction": 0.5954738259315491, "avg_line_length": 38.27777862548828, "blob_id": "f557436f372207bc67deb59d6970813cafe87b78", "content_id": "7facc33085157f7e8f099e115e378303a96af866", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 707, "license_type": "no_license", "max_line_length": 155, "num_lines": 18, "path": "/gridplatform/bootstrap/templates/bootstrap/base/form_buttons.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% load bootstrap_tags %}\n{% if layout == 'horizontal' %}\n<div class=\"form-group\">\n <div class=\"col-sm-offset-{{ label_columns }} col-sm-{{ input_columns }}\">\n{% endif %}\n <button type=\"submit\" class=\"btn btn-primary disable-reenable-on-click\">{{ submit_label }}</button>\n {% if cancel_target %}\n <span>&nbsp;</span>\n <a class=\"btn btn-warning\" href=\"{{ cancel_target }}\">{{ cancel_label }}</a>\n {% endif %}\n {% if delete_target %}\n <span>&nbsp;</span>\n <button type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#delete-modal\" data-url=\"{{ delete_target }}\">{{ delete_label }}</button>\n {% endif %}\n{% if layout == 'horizontal' %}\n </div>\n</div>\n{% endif %}\n" }, { "alpha_fraction": 0.6214733719825745, "alphanum_fraction": 0.6233346462249756, "avg_line_length": 31.823150634765625, "blob_id": "268fb71d4eeda503f72e83dac1f8bef4ff5e2c09", "content_id": "4b2eb814fe2932d9bfb00a8c24b175a1aecdebbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10208, "license_type": "no_license", "max_line_length": 79, "num_lines": 311, "path": "/gridplatform/reports/pdf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport codecs\nimport datetime\nimport logging\nimport os\nimport os.path\nimport re\nimport shutil\nimport subprocess\nimport tempfile\nimport time\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.template.response import TemplateResponse\nfrom django.utils.formats import get_format\nfrom django.views.generic.base import TemplateResponseMixin\nfrom django.views.generic.detail import BaseDetailView\n\nimport braces.views\nimport pytz\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass LatexError(Exception):\n \"\"\"\n Exception representing errors during LaTeX run.\n \"\"\"\n def __init__(self, log_file_name):\n \"\"\"\n Construct :class:`.LatexError` containing errors from a LaTeX\n log-file.\n\n :param log_file_name: Name of log file to read actual\n LaTeX-error from.\n \"\"\"\n with codecs.open(log_file_name, 'r', 'iso8859-1') as log_file:\n log = log_file.read()\n short = None\n start = re.search('^! [^\\n]* Error:', log, re.MULTILINE)\n if start:\n short = log[start.start():]\n end = re.search(\n \"^Here is how much of TeX's memory you used:$\",\n short, re.MULTILINE)\n if end:\n short = short[:end.start()]\n self.value = log_file_name + '\\n\\n\\n' + short + '\\n\\n\\n' + log\n else:\n self.value = log_file_name + '\\n\\n\\n' + log\n\n def __str__(self):\n return self.value\n\n\ndef compile_pdf(file_basename, content):\n \"\"\"\n Compiles the given LaTeX ``content``.\n\n Wraps :func:`_compile_pdf` so that it uses a temponary output\n directory, that is deleted again after a successful compile, and\n left for debug inspection upon failure.\n\n :param file_basename: The base name of the generated PDF.\n :param content: The LaTeX to be compiled.\n\n :return: the contents of the resulting PDF.\n \"\"\"\n tmp_dir = tempfile.mkdtemp(prefix='latex')\n pdf_file_name = _compile_pdf(file_basename, content, tmp_dir)\n with open(pdf_file_name, 'rb') as pdf_file:\n data = pdf_file.read()\n shutil.rmtree(tmp_dir)\n return data\n\n\ndef _compile_pdf(file_basename, content, out_dir):\n \"\"\"\n Compiles the given LaTeX ``content``\n\n :param file_basename: The base name of the generated PDF.\n :param content: The LaTeX to be compiled.\n :param out_dir: The directory in which to perform the compilation.\n\n :return: The full path of the compiled PDF document.\n \"\"\"\n start_time = time.time()\n tex_file_name = os.path.join(out_dir, file_basename + '.tex')\n pdf_file_name = os.path.join(out_dir, file_basename + '.pdf')\n log_file_name = os.path.join(out_dir, file_basename + '.log')\n with codecs.open(tex_file_name, mode='wb', encoding='utf-8') as f:\n f.write(content)\n with codecs.open(tex_file_name, mode='wb', encoding='utf-8') as f:\n f.write(content)\n # -halt-on-error and -interaction=nonstopmode to have the process terminate\n # rather than wait for interactive commands...\n command = [\n 'xelatex',\n '-halt-on-error', '-interaction=nonstopmode',\n tex_file_name,\n ]\n with open('/dev/null', 'w') as FNULL:\n for n in range(4):\n # we run LaTeX up to 4 times...\n if subprocess.call(\n command, cwd=out_dir,\n stdin=FNULL, stdout=FNULL, stderr=FNULL) != 0:\n raise LatexError(log_file_name)\n with codecs.open(log_file_name, 'r', 'iso8859-1') as log:\n # stop sooner if LaTeX does not tell us to rerun\n if all(['Rerun to get' not in line and\n 'Rerun LaTeX' not in line\n for line in log]):\n break\n if not os.path.exists(pdf_file_name):\n raise LatexError(log_file_name)\n end_time = time.time()\n logger.debug('PDF generated in %f seconds', end_time - start_time)\n return pdf_file_name\n\n\ndef _generate_pdf(template, data, tmp_dir):\n \"\"\"\n Generates a PDF from the LaTeX that result from rendering a\n template in a given context in a given directory.\n\n :param template: The Django template that renders a LaTeX\n document.\n :param data: The template context in which to render the template.\n :param tmp_dir: The directory in which to compile the LaTeX\n document.\n\n :return: The full path to the generated PDF.\n \"\"\"\n file_root, ext = os.path.splitext(os.path.basename(template))\n return _compile_pdf(file_root, render_to_string(template, data), tmp_dir)\n\n\ndef _generate_gnuplot(plot, out_dir):\n \"\"\"\n Generate a gnuplot plot.\n\n :param plot: The string of commands to run in GNU plot.\n\n :param outdir: This is the directory in which gnuplot will be run (and thus\n generate it's output).\n\n :see: :class:`gridplatform.reports.tests.GnuPlotTest` for an\n example.\n \"\"\"\n with open('/dev/null', 'w') as FNULL:\n p = subprocess.Popen(\n ['gnuplot'], cwd=out_dir,\n stdin=subprocess.PIPE, stdout=FNULL, stderr=FNULL)\n p.communicate(plot.encode('utf-8'))\n p.wait()\n if p.returncode != 0:\n raise subprocess.CalledProcessError(\n returncode=p.returncode,\n cmd='gnuplot - \\n%s' % plot)\n\n\ndef generate_pdf(template, data, title, report_type, customer, gnuplots=[]):\n \"\"\"\n Generate a PDF from the named template instantiated with the\n provided data using LaTeX.\n\n :param template: Template for tex file.\n\n :param data: Data for template instantiation.\n\n :param title: Title for PDF file.\n\n :param report_type: \"Report type\" for document footer.\n\n :param gnuplots: List of gnuplot scripts to be run before\n generating the PDF.\n\n :return: Byte string with contents of generated PDF file.\n \"\"\"\n\n data['meta'] = {\n 'title': title,\n 'type': report_type,\n 'generation_time': datetime.datetime.now(pytz.utc),\n 'customer': customer,\n }\n tmp_dir = tempfile.mkdtemp(prefix='latex')\n for gnuplot in gnuplots:\n _generate_gnuplot(gnuplot, tmp_dir)\n pdf_file_name = _generate_pdf(template, data, tmp_dir)\n with open(pdf_file_name, 'rb') as pdf_file:\n data = pdf_file.read()\n shutil.rmtree(tmp_dir)\n return data\n\n\ndef serve_pdf(template, data, title, report_type, customer):\n \"\"\"\n Generate a PDF from the named template instantiated with the\n provided data using LaTeX and return it as a application/pdf\n HttpResponse.\n\n :see: :func:`.generate_pdf`\n \"\"\"\n pdf = generate_pdf(template, data, title, report_type, customer)\n return HttpResponse(pdf, content_type='application/pdf')\n\n\nclass PDFTemplateResponse(TemplateResponse):\n \"\"\"\n TemplateResponse wrapper which compiles its rendered data string\n to PDF with LaTeX.\n \"\"\"\n @property\n def rendered_content(self):\n template = self.resolve_template(self.template_name)\n context = self.resolve_context(self.context_data)\n content = template.render(context)\n template_path = template.name\n\n file_basename, ext = os.path.splitext(\n os.path.basename(template_path))\n if ext != '.tex':\n file_basename = 'report'\n return compile_pdf(file_basename, content)\n\n\nclass PDFDetailView(\n braces.views.LoginRequiredMixin,\n TemplateResponseMixin, BaseDetailView):\n \"\"\"\n Generic PDF-generation view for use where the normal setup with background\n data collection and saving the resulting PDF to the database does not\n provide any clear benefits.\n\n Designed as a replacement for the :func:`.serve_pdf` function...\n \"\"\"\n content_type = 'application/pdf'\n response_class = PDFTemplateResponse\n\n document_title = None\n document_customer = None\n document_type = None\n\n def get_document_title(self):\n \"\"\"\n :return: The document title.\n \"\"\"\n if self.document_title is not None:\n return self.document_title\n return unicode(self.object)\n\n def get_document_customer(self):\n \"\"\"\n :return: The customer for whom the document is served.\n \"\"\"\n if self.document_customer is not None:\n return self.document_customer\n elif hasattr(self.object, 'customer'):\n return self.object.customer\n else:\n raise ImproperlyConfigured(\n \"PDFDetailView requires either 'document_customer', \"\n \"a 'customer' attribute on its model object or \"\n \"an implementation of 'get_document_customer()'.\")\n\n def get_document_type(self):\n \"\"\"\n :return: The document type. If not set explicitly it is derived\n from the base name of a template.\n \"\"\"\n if self.document_type is not None:\n return self.document_type\n template_path = self.get_template_names()[0]\n file_basename, ext = os.path.splitext(\n os.path.basename(template_path))\n return file_basename\n\n def get_context_meta(self):\n \"\"\"\n :return: The meta dictionary available in the template context.\n \"\"\"\n return {\n 'title': self.get_document_title(),\n 'type': self.get_document_type(),\n 'generation_time': datetime.datetime.now(pytz.utc),\n 'customer': self.get_document_customer(),\n }\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Specialization of\n :meth:`django.views.generic.TemplateView.get_context_data`.\n\n :return: The context data made available by the view during\n template rendering.\n \"\"\"\n context = {\n 'meta': self.get_context_meta(),\n 'DECIMAL_SEPARATOR': get_format('DECIMAL_SEPARATOR'),\n 'THOUSAND_SEPARATOR': get_format('THOUSAND_SEPARATOR'),\n }\n context.update(kwargs)\n return super(PDFDetailView, self).get_context_data(**context)\n" }, { "alpha_fraction": 0.7276973128318787, "alphanum_fraction": 0.73465496301651, "avg_line_length": 25.426952362060547, "blob_id": "5f4d941cd3fdf330905dea41f3cb5dc6672f86b6", "content_id": "d1efd8a7d81b77a5a19d4f5d02bbe9fb3c8aaaaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 20984, "license_type": "no_license", "max_line_length": 161, "num_lines": 794, "path": "/dbname.sql", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "--\n-- PostgreSQL database dump\n--\n\n-- Dumped from database version 10.10 (Ubuntu 10.10-0ubuntu0.18.04.1)\n-- Dumped by pg_dump version 10.10 (Ubuntu 10.10-0ubuntu0.18.04.1)\n\nSET statement_timeout = 0;\nSET lock_timeout = 0;\nSET idle_in_transaction_session_timeout = 0;\nSET client_encoding = 'UTF8';\nSET standard_conforming_strings = on;\nSELECT pg_catalog.set_config('search_path', '', false);\nSET check_function_bodies = false;\nSET xmloption = content;\nSET client_min_messages = warning;\nSET row_security = off;\n\n--\n-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: \n--\n\nCREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;\n\n\n--\n-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: \n--\n\nCOMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';\n\n\nSET default_tablespace = '';\n\nSET default_with_oids = false;\n\n--\n-- Name: auth_group; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_group (\n id integer NOT NULL,\n name character varying(80) NOT NULL\n);\n\n\nALTER TABLE public.auth_group OWNER TO portal;\n\n--\n-- Name: auth_group_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_group_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_group_id_seq OWNER TO portal;\n\n--\n-- Name: auth_group_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_group_id_seq OWNED BY public.auth_group.id;\n\n\n--\n-- Name: auth_group_permissions; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_group_permissions (\n id integer NOT NULL,\n group_id integer NOT NULL,\n permission_id integer NOT NULL\n);\n\n\nALTER TABLE public.auth_group_permissions OWNER TO portal;\n\n--\n-- Name: auth_group_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_group_permissions_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_group_permissions_id_seq OWNER TO portal;\n\n--\n-- Name: auth_group_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_group_permissions_id_seq OWNED BY public.auth_group_permissions.id;\n\n\n--\n-- Name: auth_permission; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_permission (\n id integer NOT NULL,\n name character varying(50) NOT NULL,\n content_type_id integer NOT NULL,\n codename character varying(100) NOT NULL\n);\n\n\nALTER TABLE public.auth_permission OWNER TO portal;\n\n--\n-- Name: auth_permission_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_permission_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_permission_id_seq OWNER TO portal;\n\n--\n-- Name: auth_permission_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_permission_id_seq OWNED BY public.auth_permission.id;\n\n\n--\n-- Name: auth_user; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_user (\n id integer NOT NULL,\n password character varying(128) NOT NULL,\n last_login timestamp with time zone NOT NULL,\n is_superuser boolean NOT NULL,\n username character varying(30) NOT NULL,\n first_name character varying(30) NOT NULL,\n last_name character varying(30) NOT NULL,\n email character varying(75) NOT NULL,\n is_staff boolean NOT NULL,\n is_active boolean NOT NULL,\n date_joined timestamp with time zone NOT NULL\n);\n\n\nALTER TABLE public.auth_user OWNER TO portal;\n\n--\n-- Name: auth_user_groups; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_user_groups (\n id integer NOT NULL,\n user_id integer NOT NULL,\n group_id integer NOT NULL\n);\n\n\nALTER TABLE public.auth_user_groups OWNER TO portal;\n\n--\n-- Name: auth_user_groups_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_user_groups_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_user_groups_id_seq OWNER TO portal;\n\n--\n-- Name: auth_user_groups_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_user_groups_id_seq OWNED BY public.auth_user_groups.id;\n\n\n--\n-- Name: auth_user_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_user_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_user_id_seq OWNER TO portal;\n\n--\n-- Name: auth_user_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_user_id_seq OWNED BY public.auth_user.id;\n\n\n--\n-- Name: auth_user_user_permissions; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.auth_user_user_permissions (\n id integer NOT NULL,\n user_id integer NOT NULL,\n permission_id integer NOT NULL\n);\n\n\nALTER TABLE public.auth_user_user_permissions OWNER TO portal;\n\n--\n-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.auth_user_user_permissions_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.auth_user_user_permissions_id_seq OWNER TO portal;\n\n--\n-- Name: auth_user_user_permissions_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.auth_user_user_permissions_id_seq OWNED BY public.auth_user_user_permissions.id;\n\n\n--\n-- Name: corsheaders_corsmodel; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.corsheaders_corsmodel (\n id integer NOT NULL,\n cors character varying(255) NOT NULL\n);\n\n\nALTER TABLE public.corsheaders_corsmodel OWNER TO portal;\n\n--\n-- Name: corsheaders_corsmodel_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.corsheaders_corsmodel_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.corsheaders_corsmodel_id_seq OWNER TO portal;\n\n--\n-- Name: corsheaders_corsmodel_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.corsheaders_corsmodel_id_seq OWNED BY public.corsheaders_corsmodel.id;\n\n\n--\n-- Name: django_admin_log; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.django_admin_log (\n id integer NOT NULL,\n action_time timestamp with time zone NOT NULL,\n user_id integer NOT NULL,\n content_type_id integer,\n object_id text,\n object_repr character varying(200) NOT NULL,\n action_flag smallint NOT NULL,\n change_message text NOT NULL,\n CONSTRAINT django_admin_log_action_flag_check CHECK ((action_flag >= 0))\n);\n\n\nALTER TABLE public.django_admin_log OWNER TO portal;\n\n--\n-- Name: django_admin_log_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.django_admin_log_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.django_admin_log_id_seq OWNER TO portal;\n\n--\n-- Name: django_admin_log_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.django_admin_log_id_seq OWNED BY public.django_admin_log.id;\n\n\n--\n-- Name: django_content_type; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.django_content_type (\n id integer NOT NULL,\n name character varying(100) NOT NULL,\n app_label character varying(100) NOT NULL,\n model character varying(100) NOT NULL\n);\n\n\nALTER TABLE public.django_content_type OWNER TO portal;\n\n--\n-- Name: django_content_type_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.django_content_type_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.django_content_type_id_seq OWNER TO portal;\n\n--\n-- Name: django_content_type_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.django_content_type_id_seq OWNED BY public.django_content_type.id;\n\n\n--\n-- Name: django_session; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.django_session (\n session_key character varying(40) NOT NULL,\n session_data text NOT NULL,\n expire_date timestamp with time zone NOT NULL\n);\n\n\nALTER TABLE public.django_session OWNER TO portal;\n\n--\n-- Name: south_migrationhistory; Type: TABLE; Schema: public; Owner: portal\n--\n\nCREATE TABLE public.south_migrationhistory (\n id integer NOT NULL,\n app_name character varying(255) NOT NULL,\n migration character varying(255) NOT NULL,\n applied timestamp with time zone NOT NULL\n);\n\n\nALTER TABLE public.south_migrationhistory OWNER TO portal;\n\n--\n-- Name: south_migrationhistory_id_seq; Type: SEQUENCE; Schema: public; Owner: portal\n--\n\nCREATE SEQUENCE public.south_migrationhistory_id_seq\n AS integer\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\n\nALTER TABLE public.south_migrationhistory_id_seq OWNER TO portal;\n\n--\n-- Name: south_migrationhistory_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: portal\n--\n\nALTER SEQUENCE public.south_migrationhistory_id_seq OWNED BY public.south_migrationhistory.id;\n\n\n--\n-- Name: auth_group id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group ALTER COLUMN id SET DEFAULT nextval('public.auth_group_id_seq'::regclass);\n\n\n--\n-- Name: auth_group_permissions id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group_permissions ALTER COLUMN id SET DEFAULT nextval('public.auth_group_permissions_id_seq'::regclass);\n\n\n--\n-- Name: auth_permission id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_permission ALTER COLUMN id SET DEFAULT nextval('public.auth_permission_id_seq'::regclass);\n\n\n--\n-- Name: auth_user id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user ALTER COLUMN id SET DEFAULT nextval('public.auth_user_id_seq'::regclass);\n\n\n--\n-- Name: auth_user_groups id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_groups ALTER COLUMN id SET DEFAULT nextval('public.auth_user_groups_id_seq'::regclass);\n\n\n--\n-- Name: auth_user_user_permissions id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_user_permissions ALTER COLUMN id SET DEFAULT nextval('public.auth_user_user_permissions_id_seq'::regclass);\n\n\n--\n-- Name: corsheaders_corsmodel id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.corsheaders_corsmodel ALTER COLUMN id SET DEFAULT nextval('public.corsheaders_corsmodel_id_seq'::regclass);\n\n\n--\n-- Name: django_admin_log id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_admin_log ALTER COLUMN id SET DEFAULT nextval('public.django_admin_log_id_seq'::regclass);\n\n\n--\n-- Name: django_content_type id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_content_type ALTER COLUMN id SET DEFAULT nextval('public.django_content_type_id_seq'::regclass);\n\n\n--\n-- Name: south_migrationhistory id; Type: DEFAULT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.south_migrationhistory ALTER COLUMN id SET DEFAULT nextval('public.south_migrationhistory_id_seq'::regclass);\n\n\n--\n-- Name: auth_group auth_group_name_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group\n ADD CONSTRAINT auth_group_name_key UNIQUE (name);\n\n\n--\n-- Name: auth_group_permissions auth_group_permissions_group_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group_permissions\n ADD CONSTRAINT auth_group_permissions_group_id_permission_id_key UNIQUE (group_id, permission_id);\n\n\n--\n-- Name: auth_group_permissions auth_group_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group_permissions\n ADD CONSTRAINT auth_group_permissions_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_group auth_group_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group\n ADD CONSTRAINT auth_group_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_permission auth_permission_content_type_id_codename_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_permission\n ADD CONSTRAINT auth_permission_content_type_id_codename_key UNIQUE (content_type_id, codename);\n\n\n--\n-- Name: auth_permission auth_permission_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_permission\n ADD CONSTRAINT auth_permission_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_user_groups auth_user_groups_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_groups\n ADD CONSTRAINT auth_user_groups_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_user_groups auth_user_groups_user_id_group_id_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_groups\n ADD CONSTRAINT auth_user_groups_user_id_group_id_key UNIQUE (user_id, group_id);\n\n\n--\n-- Name: auth_user auth_user_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user\n ADD CONSTRAINT auth_user_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_user_user_permissions auth_user_user_permissions_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_user_permissions\n ADD CONSTRAINT auth_user_user_permissions_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_user_user_permissions auth_user_user_permissions_user_id_permission_id_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_user_permissions\n ADD CONSTRAINT auth_user_user_permissions_user_id_permission_id_key UNIQUE (user_id, permission_id);\n\n\n--\n-- Name: auth_user auth_user_username_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user\n ADD CONSTRAINT auth_user_username_key UNIQUE (username);\n\n\n--\n-- Name: corsheaders_corsmodel corsheaders_corsmodel_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.corsheaders_corsmodel\n ADD CONSTRAINT corsheaders_corsmodel_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: django_admin_log django_admin_log_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_admin_log\n ADD CONSTRAINT django_admin_log_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: django_content_type django_content_type_app_label_model_key; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_content_type\n ADD CONSTRAINT django_content_type_app_label_model_key UNIQUE (app_label, model);\n\n\n--\n-- Name: django_content_type django_content_type_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_content_type\n ADD CONSTRAINT django_content_type_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: django_session django_session_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_session\n ADD CONSTRAINT django_session_pkey PRIMARY KEY (session_key);\n\n\n--\n-- Name: south_migrationhistory south_migrationhistory_pkey; Type: CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.south_migrationhistory\n ADD CONSTRAINT south_migrationhistory_pkey PRIMARY KEY (id);\n\n\n--\n-- Name: auth_group_name_like; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_group_name_like ON public.auth_group USING btree (name varchar_pattern_ops);\n\n\n--\n-- Name: auth_group_permissions_group_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_group_permissions_group_id ON public.auth_group_permissions USING btree (group_id);\n\n\n--\n-- Name: auth_group_permissions_permission_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_group_permissions_permission_id ON public.auth_group_permissions USING btree (permission_id);\n\n\n--\n-- Name: auth_permission_content_type_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_permission_content_type_id ON public.auth_permission USING btree (content_type_id);\n\n\n--\n-- Name: auth_user_groups_group_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_user_groups_group_id ON public.auth_user_groups USING btree (group_id);\n\n\n--\n-- Name: auth_user_groups_user_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_user_groups_user_id ON public.auth_user_groups USING btree (user_id);\n\n\n--\n-- Name: auth_user_user_permissions_permission_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_user_user_permissions_permission_id ON public.auth_user_user_permissions USING btree (permission_id);\n\n\n--\n-- Name: auth_user_user_permissions_user_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_user_user_permissions_user_id ON public.auth_user_user_permissions USING btree (user_id);\n\n\n--\n-- Name: auth_user_username_like; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX auth_user_username_like ON public.auth_user USING btree (username varchar_pattern_ops);\n\n\n--\n-- Name: django_admin_log_content_type_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX django_admin_log_content_type_id ON public.django_admin_log USING btree (content_type_id);\n\n\n--\n-- Name: django_admin_log_user_id; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX django_admin_log_user_id ON public.django_admin_log USING btree (user_id);\n\n\n--\n-- Name: django_session_expire_date; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX django_session_expire_date ON public.django_session USING btree (expire_date);\n\n\n--\n-- Name: django_session_session_key_like; Type: INDEX; Schema: public; Owner: portal\n--\n\nCREATE INDEX django_session_session_key_like ON public.django_session USING btree (session_key varchar_pattern_ops);\n\n\n--\n-- Name: auth_group_permissions auth_group_permissions_permission_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group_permissions\n ADD CONSTRAINT auth_group_permissions_permission_id_fkey FOREIGN KEY (permission_id) REFERENCES public.auth_permission(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_user_groups auth_user_groups_group_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_groups\n ADD CONSTRAINT auth_user_groups_group_id_fkey FOREIGN KEY (group_id) REFERENCES public.auth_group(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_user_user_permissions auth_user_user_permissions_permission_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_user_permissions\n ADD CONSTRAINT auth_user_user_permissions_permission_id_fkey FOREIGN KEY (permission_id) REFERENCES public.auth_permission(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_permission content_type_id_refs_id_d043b34a; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_permission\n ADD CONSTRAINT content_type_id_refs_id_d043b34a FOREIGN KEY (content_type_id) REFERENCES public.django_content_type(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: django_admin_log django_admin_log_content_type_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_admin_log\n ADD CONSTRAINT django_admin_log_content_type_id_fkey FOREIGN KEY (content_type_id) REFERENCES public.django_content_type(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: django_admin_log django_admin_log_user_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.django_admin_log\n ADD CONSTRAINT django_admin_log_user_id_fkey FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_group_permissions group_id_refs_id_f4b32aac; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_group_permissions\n ADD CONSTRAINT group_id_refs_id_f4b32aac FOREIGN KEY (group_id) REFERENCES public.auth_group(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_user_groups user_id_refs_id_40c41112; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_groups\n ADD CONSTRAINT user_id_refs_id_40c41112 FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- Name: auth_user_user_permissions user_id_refs_id_4dc23c39; Type: FK CONSTRAINT; Schema: public; Owner: portal\n--\n\nALTER TABLE ONLY public.auth_user_user_permissions\n ADD CONSTRAINT user_id_refs_id_4dc23c39 FOREIGN KEY (user_id) REFERENCES public.auth_user(id) DEFERRABLE INITIALLY DEFERRED;\n\n\n--\n-- PostgreSQL database dump complete\n--\n\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6668075919151306, "avg_line_length": 23.63541603088379, "blob_id": "cda3e035238e9456c3843068a4c531ed7d925a75", "content_id": "0aa26f53804521b1c4226d1c925b9f95ad5dc53d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2365, "license_type": "no_license", "max_line_length": 79, "num_lines": 96, "path": "/gridplatform/utils/utilitytypes.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nReoccuring choices defined in one place to implement DRY. Choices that are\nunique to their application should just be defined inline, but choices that are\nlikely to overlap or be similar with choices of other apps are to be defined\nhere.\n\nIn particular the granularity of energy consumption classes vary a lot from\napplication to application (and so it should).\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils import Choices\n\n\n__all__ = [\n 'AREA_OF_ENERGY_USE_CHOICES',\n 'METER_CHOICES',\n 'OPTIONAL_METER_CHOICES',\n 'UTILITY_TYPE_TO_COLOR',\n]\n\nUNKNOWN = (1000, 'unknown', _('unknown'))\nTEMPERATURE = (1001, 'temperature', _('temperature'))\n\nELECTRICITY = (2000, 'electricity', _('electricity'))\n\nDISTRICT_HEATING = (3000, 'district_heating', _('district heating'))\n\nFUEL = (4000, 'fuel', _('fuel'))\n\nLIQUID_FUEL = (5000, 'liquid_fuel', _('liquid fuel'))\nOIL = (5500, 'oil', _('oil'))\n\nSOLID_FUEL = (6000, 'solid_fuel', _('solid fuel'))\n\nGAS = (7000, 'gas', _('gas'))\n\nWATER = (8000, 'water', _('water'))\n\nAREA_OF_ENERGY_USE_CHOICES = Choices(\n ELECTRICITY,\n WATER,\n DISTRICT_HEATING,\n FUEL,\n)\n\nMETER_CHOICES = Choices(\n ELECTRICITY,\n WATER,\n GAS,\n DISTRICT_HEATING,\n OIL,\n)\n\nENERGY_UTILITY_TYPE_CHOICES = Choices(\n ELECTRICITY,\n GAS,\n DISTRICT_HEATING,\n SOLID_FUEL,\n LIQUID_FUEL,\n)\n\nENERGY_UTILITY_TYPE_TO_BASE_UNIT_MAP = {\n ELECTRICITY[0]: 'milliwatt*hour',\n GAS[0]: 'milliliter',\n DISTRICT_HEATING[0]: 'milliwatt*hour',\n SOLID_FUEL[0]: 'gram',\n LIQUID_FUEL[0]: 'milliliter',\n}\n\nENERGY_UTILITY_TYPE_TO_DISPLAY_UNIT_MAP = {\n ELECTRICITY[0]: 'kilowatt*hour',\n GAS[0]: 'meter*meter*meter',\n DISTRICT_HEATING[0]: 'kilowatt*hour',\n SOLID_FUEL[0]: 'kilogram',\n LIQUID_FUEL[0]: 'meter*meter*meter',\n}\n\n# @deprecated: Use METER_UTILITY_TYPE_CHOICES and null=True instead.\nOPTIONAL_METER_CHOICES = Choices(UNKNOWN,) + Choices(TEMPERATURE,) + \\\n METER_CHOICES\n\nMETER_TYPE_CHOICES = Choices(TEMPERATURE,) + \\\n METER_CHOICES\n\nUTILITY_TYPE_TO_COLOR = {\n METER_CHOICES.electricity: '#294995',\n METER_CHOICES.water: '#009DE0',\n METER_CHOICES.gas: '#F2D4A3',\n METER_CHOICES.district_heating: '#B31117',\n METER_CHOICES.oil: '#E3A64A',\n}\n" }, { "alpha_fraction": 0.6817411184310913, "alphanum_fraction": 0.6823064088821411, "avg_line_length": 33.019229888916016, "blob_id": "f337e6731d8d14f53b477e4aee01cdd32c94f1fc", "content_id": "1fd76727cce28f534a7d6894c5522a545aea24f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1769, "license_type": "no_license", "max_line_length": 81, "num_lines": 52, "path": "/legacy/manage_measurementpoints/forms/power.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import PowerMeasurementPoint\nfrom legacy.measurementpoints.models import Collection\n\nfrom .measurementpointform import MeasurementPointForm\n\nfrom gridplatform.datasequences.models import NonaccumulationDataSequence # noqa\n\n\nclass PowerMeasurementPointForm(MeasurementPointForm):\n class Meta:\n model = PowerMeasurementPoint\n fields = ('name', 'parent',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(PowerMeasurementPointForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n def _get_edit_headline_display(self):\n return _(u'Edit Power Measurement Point')\n\n\nclass InputPowerMeasurementPointForm(PowerMeasurementPointForm):\n input_configuration = forms.ModelChoiceField(\n required=True,\n queryset=NonaccumulationDataSequence.objects.none())\n\n class ProxyMeta:\n fields = ('input_configuration', )\n\n def __init__(self, *args, **kwargs):\n super(InputPowerMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['input_configuration'].queryset = \\\n PowerMeasurementPoint.get_input_configuration_choices()\n\n def _get_new_headline_display(self):\n return _(u'New Power Measurement Point')\n" }, { "alpha_fraction": 0.6334838271141052, "alphanum_fraction": 0.6359668970108032, "avg_line_length": 37.080230712890625, "blob_id": "325e78828553e232203d99ae81542b50efa6eae5", "content_id": "cd97b0d63c74921d9e1084471551a92cb236a95c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13292, "license_type": "no_license", "max_line_length": 79, "num_lines": 349, "path": "/gridplatform/encryption/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport pickle\n\nfrom django.test import TestCase\nfrom django.test import SimpleTestCase\nfrom django.test import RequestFactory\nfrom django.http import HttpResponse\nfrom django.db import models\nfrom django.contrib.sessions.middleware import SessionMiddleware\nfrom django.forms.models import modelform_factory\nfrom django.test.utils import override_settings\n\nfrom gridplatform.users.models import User\n\nfrom .base import EncryptionContext\nfrom .base import _store\nfrom .conf import settings\nfrom .fields import EncryptedCharField\nfrom .middleware import EncryptionMiddleware\nfrom .models import EncryptedModel\nfrom .testutils import encryption_context\n\n\nclass TestModel(models.Model):\n pass\n\n\n# simple/\"raw\" tests\n@override_settings(\n MIDDLEWARE_CLASSES=[\n x for x in settings.MIDDLEWARE_CLASSES\n if x != 'gridplatform.encryption.middleware.KeyLoaderMiddleware'])\nclass MiddlewareTest(TestCase):\n def setUp(self):\n self.session = SessionMiddleware()\n self.encryption = EncryptionMiddleware()\n\n def test_no_data(self):\n request = RequestFactory().get('/')\n\n self.session.process_request(request)\n self.encryption.process_request(request)\n self.assertNotIn(settings.ENCRYPTION_SESSION_KEY, request.session)\n\n def test_store_load(self):\n secret_text = 'secret secret'\n\n # simulate an incoming request\n request = RequestFactory().get('/')\n self.session.process_request(request)\n self.encryption.process_request(request)\n # add the secret data to the request \"somewhere in the handling\"\n _store.private_key = secret_text\n\n # simulate the response in this context\n response = HttpResponse()\n response = self.encryption.process_response(request, response)\n self.assertTrue(request.session.modified)\n response = self.session.process_response(request, response)\n # we have store \"something\" in the session --- can't really check that\n # it is securely encrypted...\n self.assertIn('encryption_private_key', request.session)\n self.assertNotEqual(\n request.session['encryption_private_key'], secret_text)\n # we have put something in the expected cookie\n self.assertIn(settings.ENCRYPTION_COOKIE_NAME, response.cookies)\n\n # set up context; received cookies must be used in next request\n request_factory = RequestFactory()\n request_factory.cookies = response.cookies\n\n # simulate next request\n request = request_factory.get('/')\n # sanity check, the secret data is *not* present on the request\n self.assertIsNone(getattr(_store, 'private_key'))\n self.session.process_request(request)\n self.encryption.process_request(request)\n # the secret data should be available now\n self.assertEqual(_store.private_key, secret_text)\n\n def test_repeated_store(self):\n secret_text = 'secret secret'\n\n request = RequestFactory().get('/')\n self.session.process_request(request)\n self.encryption.process_request(request)\n setattr(_store, settings.ENCRYPTION_STORE_KEY, secret_text)\n\n response = HttpResponse()\n response = self.encryption.process_response(request, response)\n response = self.session.process_response(request, response)\n\n request_factory = RequestFactory()\n request_factory.cookies = response.cookies\n\n request = request_factory.get('/')\n self.session.process_request(request)\n self.encryption.process_request(request)\n\n # same value, i.e. should not lead to session modified\n setattr(_store, settings.ENCRYPTION_STORE_KEY, secret_text)\n response = HttpResponse()\n response = self.encryption.process_response(request, response)\n response = self.session.process_response(request, response)\n self.assertFalse(request.session.modified)\n\n # same factory; cookies kept...\n request = request_factory.get('/')\n self.session.process_request(request)\n self.encryption.process_request(request)\n self.assertEqual(\n getattr(_store, settings.ENCRYPTION_STORE_KEY), secret_text)\n\n # new data\n setattr(_store, settings.ENCRYPTION_STORE_KEY, secret_text + 'x')\n response = HttpResponse()\n response = self.encryption.process_response(request, response)\n response = self.session.process_response(request, response)\n self.assertTrue(request.session.modified)\n\n # new data replaced old...\n request = request_factory.get('/')\n self.session.process_request(request)\n self.encryption.process_request(request)\n self.assertEqual(\n getattr(_store, settings.ENCRYPTION_STORE_KEY), secret_text + 'x')\n\n\n# Using the simulated client --- it keeps track of client state wrt. cookies,\n# but this test requires more setup...\n@override_settings(\n MIDDLEWARE_CLASSES=[\n x for x in settings.MIDDLEWARE_CLASSES\n if x != 'gridplatform.encryption.middleware.KeyLoaderMiddleware'])\nclass MiddlewareClientTest(TestCase):\n urls = 'gridplatform.encryption.test_urls'\n\n def test_client(self):\n with encryption_context():\n User.objects.create_user(\n username='testuser', password='testpassword',\n user_type=0)\n\n # no secret present\n response = self.client.get('/get_secret/')\n self.assertEqual(response.status_code, 400)\n\n # save, read\n self.client.login(username='testuser', password='testpassword')\n self.client.post('/set_secret/', {'secret': 'my secret string'})\n response = self.client.get('/get_secret/')\n self.assertEqual(response.content, 'my secret string')\n\n # cleared on logout\n self.client.logout()\n response = self.client.get('/get_secret/')\n self.assertEqual(response.status_code, 400)\n\n # not reinstated on login\n self.client.login(username='testuser', password='testpassword')\n response = self.client.get('/get_secret/')\n self.assertEqual(response.status_code, 400)\n\n # set, overwrite...\n self.client.post('/set_secret/', {'secret': 'secret 1'})\n response = self.client.get('/get_secret/')\n self.assertEqual(response.content, 'secret 1')\n self.client.post('/set_secret/', {'secret': 'secret 2'})\n response = self.client.get('/get_secret/')\n self.assertEqual(response.content, 'secret 2')\n\n\nclass ModelWithSecrets(EncryptedModel):\n name = EncryptedCharField(max_length=8)\n other = models.CharField(max_length=5)\n\n mock_encryption_id = None\n\n def get_encryption_id(self):\n return self.mock_encryption_id\n\n\nclass MockEncryptionContext(EncryptionContext):\n def __init__(self, keys):\n self.keys = keys\n\n\nclass LoginTest(TestCase):\n urls = 'gridplatform.encryption.test_urls'\n\n def test_decrypt(self):\n with encryption_context():\n password = 'testpassword'\n User.objects.create_user(\n username='logintestuser', password=password,\n user_type=0)\n\n self.client.login(username='logintestuser', password=password)\n # loading private key, constructing context \"works\" --- though we have\n # no actual data in the context now...\n response = self.client.post('/after_login/', {'password': password})\n self.assertEqual(response.context['encryption_context'].keys, {})\n\n self.client.post('/encryption_password_change/', {\n 'old_password': password,\n 'new_password': password + 'x',\n })\n # changing password used for encryption should fail if the old password\n # is not the right encryption key (semi-white-box testing; for this\n # error, the exception raised is known to be ValueError...)\n self.assertRaises(ValueError, lambda: self.client.post(\n '/encryption_password_change/', {\n 'old_password': password,\n 'new_password': password + 'y',\n }))\n # the previous \"failure\" should not lead to further errors\n self.client.post('/encryption_password_change/', {\n 'old_password': password + 'x',\n 'new_password': password,\n })\n\n # put data in context --- in current context; stored...\n response = self.client.post('/generate_data_key/', {'link_id': 3})\n secret = response.context['encryption_context'].keys[(TestModel, 3)]\n\n # logging out removes context\n self.client.logout()\n response = self.client.get('/read_context/')\n self.assertEqual(response.context['encryption_context'].keys, {})\n\n # logging in does not add context before after_login\n self.client.login(username='logintestuser', password=password)\n response = self.client.get('/read_context/')\n self.assertEqual(response.context['encryption_context'].keys, {})\n\n # with after_login, the private key is loaded into the session\n response = self.client.post('/after_login/', {'password': password})\n self.assertEqual(response.context['encryption_context'].keys, {})\n # ... and used by middleware on the *next* request (doing it\n # immediately is not worth the bother; the login-page will redirect on\n # success anyway...)\n response = self.client.get('/read_context/')\n self.assertEqual(\n response.context['encryption_context'].keys[\n (TestModel, 3)], secret)\n\n # the context is still present...\n response = self.client.get('/read_context/')\n self.assertEqual(\n response.context['encryption_context'].keys[\n (TestModel, 3)], secret)\n\n # store some encrypted data...\n response = self.client.post('/store_secret/', {\n 'link_id': 3,\n 'name': 'hello',\n 'other': 'world',\n })\n secret_obj = response.context['obj']\n\n response = self.client.get('/read_secret/', {\n 'id': secret_obj.id,\n 'link_id': 3,\n })\n other_obj = response.context['obj']\n self.assertEqual(secret_obj.name, other_obj.name)\n self.assertEqual(secret_obj.other, other_obj.other)\n\n # add key to context...\n response = self.client.post('/generate_data_key/', {'link_id': 5})\n # other_secret = response.context['encryption_context'][5]\n\n # does not mess with existing key\n response = self.client.get('/read_secret/', {\n 'id': secret_obj.id,\n 'link_id': 3,\n })\n other_obj = response.context['obj']\n self.assertEqual(secret_obj.name, other_obj.name)\n self.assertEqual(secret_obj.other, other_obj.other)\n\n # new key won't work for object bound to other...\n response = self.client.get('/read_secret/', {\n 'id': secret_obj.id,\n 'link_id': 5,\n })\n other_obj = response.context['obj']\n # ... though the failure is that the \"decrypted\" data is garbage...\n self.assertNotEqual(secret_obj.name_plain, other_obj.name_plain)\n self.assertEqual(secret_obj.other, other_obj.other)\n\n # make/save secret object through modelform...\n form_class = modelform_factory(ModelWithSecrets)\n form = form_class({'name': u'testingå', 'other': 'more'})\n # note: is_valid() has side effects...\n self.assertTrue(form.is_valid())\n obj = form.save(commit=False)\n # self.assertRaises(Exception, obj.save)\n obj.mock_encryption_id = (TestModel, 3)\n mock_encryption_context = \\\n MockEncryptionContext({(TestModel, 3): secret})\n setattr(\n _store,\n settings.ENCRYPTION_CONTEXT_STORE_KEY,\n mock_encryption_context)\n obj.save()\n setattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, None)\n\n # read/check the data stored through modelform\n response = self.client.get('/read_secret/', {\n 'id': obj.id,\n 'link_id': 3,\n })\n self.assertEqual(response.context['obj'].name, obj.name)\n self.assertEqual(response.context['obj'].other, 'more')\n self.assertEqual(response.context['obj'].name_plain, u'testingå')\n\n\nclass EncryptedModelTest(TestCase):\n \"\"\"\n Test L{EncryptedModel}.\n \"\"\"\n\n def test_broken(self):\n \"\"\"\n Test that EncryptedField reports error on use with model without\n encryption support.\n \"\"\"\n def define_broken_class():\n class BrokenModel(models.Model):\n name = EncryptedCharField(max_length=20)\n self.assertRaises(AssertionError, define_broken_class)\n\n\nclass PickleFail(SimpleTestCase):\n def test_legal(self):\n obj = ModelWithSecrets()\n obj.name = 'testing'\n obj_copy = pickle.loads(pickle.dumps(obj))\n self.assertEqual(obj, obj_copy)\n\n def test_illegal(self):\n obj = ModelWithSecrets()\n obj.name_plain = 'testing'\n with self.assertRaises(ValueError):\n pickle.dumps(obj)\n" }, { "alpha_fraction": 0.5259395241737366, "alphanum_fraction": 0.5834354758262634, "avg_line_length": 42.32743453979492, "blob_id": "f09f34208ec95cb95435b77cd3e4264938e71563", "content_id": "f2e3154a494f4ece66fdd92fea8e39d6d0572ec6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9792, "license_type": "no_license", "max_line_length": 79, "num_lines": 226, "path": "/gridagentserver-protocol/gridagentserver_protocol/client_messages_test.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import unittest\nimport datetime\nimport ctypes\nfrom collections import namedtuple\nfrom StringIO import StringIO\nimport random\n\nfrom messages import parse\nfrom datatypes import MeterData, Meter, MeasurementSet, Measurement\nimport messages\n\nfrom client_messages import (\n BulkMeasurements,\n NotificationGaAddMode,\n NotificationGaTime,\n NotificationGaConnectedSet,\n NotificationGpState,\n)\n\n\ndef parse_message(data, version):\n stream = StringIO(data)\n return parse(stream, version)\n\nConnectionMock = namedtuple('ConnectionMock', ['agent_mac'])\n\n# NOTE: checking class names is perhaps silly, when what actually matters is\n# the behaviour on message.process() --- but we really want to test parsing by\n# itself, and checking the behaviour of process() requires a more complex test\n# setup in that it may lead to more messages being sent, interaction with the\n# database, interaction with the portal...\n\n\ndef cast_signed(val):\n return ctypes.c_longlong(val).value\n\n\nclass TestParsingVersion1(unittest.TestCase):\n def test_bulk_measurements(self):\n data = str(bytearray([\n 0x00, 0x00, 0x00, 0x48, # length\n 0x00, 0x00, # padding\n 0, # type\n 0x01, # flags (is last)\n 0x00, 0x00, # padding\n 0x00, 0x03, # count\n 0xAA, 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, # id\n 0xAB, 0xCD, 0xAB, 0xCD, # timestamp\n 0x00, 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, # value\n 0xAA, 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, # id\n 0xAB, 0xCD, 0xAB, 0xEF, # timestamp\n 0x00, 0x00, 0x00, 0x00, 0x22, 0x22, 0x22, 0x22, # value\n 0xCC, 0xCC, 0xCC, 0xCC, 0xDD, 0xDD, 0xDD, 0xDD, # id\n 0x12, 0x34, 0x12, 0x34, # timestamp\n 0x00, 0x00, 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, # value\n ]))\n message = parse_message(data, 1)\n self.assertEqual(len(message.meter_data), 2)\n self.assertEqual(message.meter_data[0].meter.id,\n cast_signed(0xAAAAAAAABBBBBBBB))\n self.assertEqual(message.meter_data[1].meter.id,\n cast_signed(0xCCCCCCCCDDDDDDDD))\n self.assertEqual(len(message.meter_data[0].measurement_sets), 2)\n self.assertEqual(len(message.meter_data[0].measurement_sets[0]\n .measurements), 1)\n self.assertEqual(message.meter_data[0].measurement_sets[0]\n .measurements[0].type, 0)\n self.assertEqual(message.meter_data[0].measurement_sets[0]\n .measurements[0].unit, 0)\n self.assertEqual(message.meter_data[0].measurement_sets[0]\n .measurements[0].input_number, 0)\n self.assertEqual(message.meter_data[0].measurement_sets[0]\n .measurements[0].value,\n cast_signed(0x0000000011111111))\n self.assertEqual(message.meter_data[0].measurement_sets[1]\n .measurements[0].value,\n cast_signed(0x0000000022222222))\n self.assertEqual(message.meter_data[1].measurement_sets[0]\n .measurements[0].value,\n cast_signed(0x0000000033333333))\n self.assertEqual(message.meter_data[0].measurement_sets[1].timestamp -\n message.meter_data[0].measurement_sets[0].timestamp,\n datetime.timedelta(seconds=34))\n self.assertEqual(message.__class__.__name__, 'BulkMeasurements')\n\n def test_notification_ga_add_mode(self):\n data = str(bytearray([\n 0x00, 0x00, 0x00, 0x0C, # length\n 0x00, 0x00, # padding\n 11, # type\n 0x00, # flags (not in add mode)\n 0x00, 0x00, 0xA4, 0xB2, # time; 11:42:42\n ]))\n message = parse_message(data, 1)\n self.assertEqual(message.in_add_mode, False)\n self.assertEqual(message.timestamp,\n datetime.datetime(2000, 1, 1, 11, 42, 42))\n self.assertEqual(message.__class__.__name__, 'NotificationGaAddMode')\n\n def test_notification_ga_time(self):\n data = str(bytearray([\n 0x00, 0x00, 0x00, 0x0C, # length\n 0x00, 0x00, # padding\n 12, # type\n 0x00, # flags\n 0x00, 0x00, 0xA4, 0xB2, # time; 11:42:42\n ]))\n message = parse_message(data, 1)\n self.assertEqual(message.timestamp,\n datetime.datetime(2000, 1, 1, 11, 42, 42))\n self.assertEqual(message.__class__.__name__, 'NotificationGaTime')\n\n def test_notification_ga_connected_set(self):\n data = str(bytearray([\n 0x00, 0x00, 0x00, 0x1C, # length\n 0x00, 0x00, # padding\n 13, # type\n 0x00, # flags\n 0x00, 0x00, 0x00, 0x02, # count\n 0xAA, 0xAA, 0xAA, 0xAA, 0xBB, 0xBB, 0xBB, 0xBB, # id\n 0xCC, 0xCC, 0xCC, 0xCC, 0xDD, 0xDD, 0xDD, 0xDD, # id\n ]))\n message = parse_message(data, 1)\n self.assertEqual(len(message.meters), 2)\n self.assertEqual(message.meters[0].id,\n cast_signed(0xAAAAAAAABBBBBBBB))\n self.assertEqual(message.meters[1].id,\n cast_signed(0xCCCCCCCCDDDDDDDD))\n self.assertEqual(message.__class__.__name__,\n 'NotificationGaConnectedSet')\n\n def test_notification_gp_state(self):\n data = str(bytearray([\n 0x00, 0x00, 0x00, 0x14, # length\n 0x00, 0x00, # padding\n 14, # type\n 0x03, # flags (connected, manual mode, relay off)\n 0x00, 0x00, 0xA4, 0xB2, # time; 11:42:42\n 0xFF, 0xEE, 0xFF, 0xFF, 0x00, 0x00, 0x11, 0x00, # id\n ]))\n message = parse_message(data, 1)\n self.assertEqual(message.online, True)\n self.assertEqual(message.control_manual, True)\n self.assertEqual(message.relay_on, False)\n self.assertEqual(message.timestamp,\n datetime.datetime(2000, 1, 1, 11, 42, 42))\n meter_id = cast_signed(0xFFEEFFFF00001100)\n self.assertEqual(message.meter, Meter(0, meter_id))\n self.assertEqual(message.__class__.__name__, 'NotificationGpState')\n\n\n# messages send timestamp as second; i.e. output will *not* match the\n# microsecond of input if we use timestamps with microseconds...\ndef utcsecond():\n return datetime.datetime.utcnow().replace(microsecond=0)\n\n\nclass TestRoundtripVersion2(unittest.TestCase):\n def test_bulk_measurements(self):\n data = [MeterData(Meter(0, 0xaabbcc),\n [MeasurementSet(utcsecond(),\n [Measurement(0, 0, 5, 123456),\n Measurement(0, 0, 9, 456789)]),\n MeasurementSet((utcsecond() +\n datetime.timedelta(hours=1)),\n [Measurement(0, 0, 9, 123457),\n Measurement(0, 0, 5, 456788)])]),\n MeterData(Meter(0, 0xccddee),\n [MeasurementSet(utcsecond(),\n [Measurement(0, 0, 1, 123),\n Measurement(0, 0, 3, 789)])])]\n bytes = StringIO()\n messages.write(bytes, BulkMeasurements(data), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.meter_data, data)\n self.assertEqual(message.__class__, BulkMeasurements)\n\n def test_notification_ga_add_mode(self):\n timestamp = utcsecond()\n in_add_mode = bool(random.randint(0, 1))\n bytes = StringIO()\n messages.write(bytes, NotificationGaAddMode(timestamp, in_add_mode), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.timestamp, timestamp)\n self.assertEqual(message.in_add_mode, in_add_mode)\n self.assertEqual(message.__class__, NotificationGaAddMode)\n\n def test_notification_ga_time(self):\n timestamp = utcsecond()\n bytes = StringIO()\n messages.write(bytes, NotificationGaTime(timestamp), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.timestamp, timestamp)\n self.assertEqual(message.__class__, NotificationGaTime)\n\n def test_notification_ga_connected_set(self):\n # NOTE: IDs are signed numbers --- because they are signed numbers\n # towards the DB...\n meters = [Meter(0, 0xAa), Meter(1, 0xBb), Meter(2, 0x7CDDEEFFCCDDEEFF)]\n bytes = StringIO()\n messages.write(bytes, NotificationGaConnectedSet(meters), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.meters, meters)\n self.assertEqual(message.__class__, NotificationGaConnectedSet)\n\n def test_notification_gp_state(self):\n meter = Meter(1, 0xAABBCC)\n online = bool(random.randint(0, 1))\n control_manual = bool(random.randint(0, 1))\n relay_on = bool(random.randint(0, 1))\n timestamp = utcsecond()\n bytes = StringIO()\n messages.write(bytes, NotificationGpState(\n meter, online, control_manual, relay_on, timestamp), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.meter, meter)\n self.assertEqual(message.online, online)\n self.assertEqual(message.control_manual, control_manual)\n self.assertEqual(message.relay_on, relay_on)\n self.assertEqual(message.timestamp, timestamp)\n self.assertEqual(message.__class__, NotificationGpState)\n" }, { "alpha_fraction": 0.5964623093605042, "alphanum_fraction": 0.6009593605995178, "avg_line_length": 35.653846740722656, "blob_id": "9263d42bfc1d07bcf29ca9a577dd14d5b88eabb4", "content_id": "90cb6769d3054603b125df7b31e112ca9e6fd622", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6671, "license_type": "no_license", "max_line_length": 79, "num_lines": 182, "path": "/gridplatform/users/admin.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.contrib.admin.options import IS_POPUP_VAR\nfrom django.contrib.auth.admin import csrf_protect_m\nfrom django.contrib.auth.admin import sensitive_post_parameters_m\nfrom django.core.exceptions import PermissionDenied\nfrom django.db import transaction\nfrom django.http import Http404\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.providers.models import Provider\n\nfrom .models import User\n\n\nclass UserCreationForm(forms.ModelForm):\n password1 = forms.CharField(\n label=_(\"Password\"),\n widget=forms.PasswordInput)\n password2 = forms.CharField(\n label=_(\"Password confirmation\"),\n widget=forms.PasswordInput,\n help_text=_(\"Enter the same password as above, for verification.\"))\n\n provider = forms.ModelChoiceField(\n label=_('Provider'),\n queryset=Provider.objects.all(), empty_label=None)\n\n class Meta:\n model = User\n fields = (\n 'name', 'e_mail', 'phone', 'mobile', 'user_type',\n )\n\n def clean_password2(self):\n password1 = self.cleaned_data.get(\"password1\")\n password2 = self.cleaned_data.get(\"password2\")\n if password1 and password2 and password1 != password2:\n raise forms.ValidationError(\n self.error_messages['password_mismatch'],\n code='password_mismatch',\n )\n return password2\n\n def save(self, commit=True):\n self.instance.provider = self.cleaned_data['provider']\n user = super(UserCreationForm, self).save(commit=False)\n user.set_password(self.cleaned_data[\"password1\"])\n if commit:\n user.save()\n return user\n\n\ndef e_mail_address(obj):\n return obj.e_mail_plain\n\n\ndef name(obj):\n return obj.name_plain\n\n\nclass UserAdmin(admin.ModelAdmin):\n add_form_template = 'admin/auth/user/add_form.html'\n fieldsets = (\n (_('Personal info'), {\n 'fields': ('name', 'e_mail', 'phone', 'mobile')\n }),\n (_('Permissions'), {\n 'fields': (\n 'is_active', 'is_staff', 'is_superuser',\n 'groups', 'user_permissions', 'user_type'\n )\n }),\n (_('Important dates'), {'fields': ('last_login', 'date_joined')}),\n )\n add_fieldsets = (\n (\n None, {\n 'classes': ('wide',),\n 'fields': (\n 'name', 'e_mail', 'phone', 'mobile', 'user_type',\n 'provider',\n 'password1', 'password2')\n },\n ),\n )\n add_form = UserCreationForm\n list_display = (e_mail_address, name,)\n list_filter = ('is_staff', 'is_superuser', 'is_active', 'groups')\n search_fields = ()\n ordering = ('username',)\n filter_horizontal = ('groups', 'user_permissions',)\n\n def get_fieldsets(self, request, obj=None):\n if not obj:\n return self.add_fieldsets\n return super(UserAdmin, self).get_fieldsets(request, obj)\n\n def get_form(self, request, obj=None, **kwargs):\n \"\"\"\n Use special form during user creation\n \"\"\"\n defaults = {}\n if obj is None:\n defaults.update({\n 'form': self.add_form,\n 'fields': admin.util.flatten_fieldsets(\n self.add_fieldsets),\n })\n defaults.update(kwargs)\n return super(UserAdmin, self).get_form(request, obj, **defaults)\n\n def lookup_allowed(self, lookup, value):\n # See #20078: we don't want to allow any lookups involving passwords.\n if lookup.startswith('password'):\n return False\n return super(UserAdmin, self).lookup_allowed(lookup, value)\n\n @sensitive_post_parameters_m\n @csrf_protect_m\n @transaction.atomic\n def add_view(self, request, form_url='', extra_context=None):\n # It's an error for a user to have add permission but NOT change\n # permission for users. If we allowed such users to add users, they\n # could create superusers, which would mean they would essentially have\n # the permission to change users. To avoid the problem entirely, we\n # disallow users from adding users if they don't have change\n # permission.\n if not self.has_change_permission(request):\n if self.has_add_permission(request) and settings.DEBUG:\n # Raise Http404 in debug mode so that the user gets a helpful\n # error message.\n raise Http404(\n 'Your user does not have the \"Change user\" permission. In '\n 'order to add users, Django requires that your user '\n 'account have both the \"Add user\" and \"Change user\" '\n 'permissions set.')\n raise PermissionDenied\n if extra_context is None:\n extra_context = {}\n username_field = self.model._meta.get_field(self.model.USERNAME_FIELD)\n defaults = {\n 'auto_populated_fields': (),\n 'username_help_text': username_field.help_text,\n }\n extra_context.update(defaults)\n return super(UserAdmin, self).add_view(\n request, form_url, extra_context)\n\n def response_add(self, request, obj, post_url_continue=None):\n \"\"\"\n Determines the HttpResponse for the add_view stage. It mostly defers to\n its superclass implementation but is customized because the User model\n has a slightly different workflow.\n \"\"\"\n # We should allow further modification of the user just added i.e. the\n # 'Save' button should behave like the 'Save and continue editing'\n # button except in two scenarios:\n # * The user has pressed the 'Save and add another' button\n # * We are adding a user in a popup\n if '_addanother' not in request.POST and \\\n IS_POPUP_VAR not in request.POST:\n request.POST['_continue'] = 1\n return super(UserAdmin, self).response_add(\n request, obj, post_url_continue)\n\n def formfield_for_manytomany(self, db_field, request=None, **kwargs):\n if db_field.name == 'user_permissions':\n qs = kwargs.get('queryset', db_field.rel.to.objects)\n kwargs['queryset'] = qs.select_related('content_type')\n return super(UserAdmin, self).formfield_for_manytomany(\n db_field, request=request, **kwargs)\n\n\nadmin.site.register(\n User,\n UserAdmin)\n" }, { "alpha_fraction": 0.6269261837005615, "alphanum_fraction": 0.6277372241020203, "avg_line_length": 33.25, "blob_id": "f8a0b443689349233d32ace6ad64dad797fbbef4", "content_id": "58b44a06b9c912cf60531afbf3503e6cc19a1728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 65, "num_lines": 36, "path": "/energymanager/datahub_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.price_relay_site.views',\n url(r'^$',\n views.HomeView.as_view(),\n name='home'),\n url(r'^customer/(?P<customer_id>\\d+)/$',\n views.CustomerView.as_view(),\n name='customer'),\n url(r'^choose-customer/$',\n views.ChooseCustomer.as_view(),\n name='choose-customer'),\n url(r'^connection/(?P<customer_id>\\d+)/$',\n views.DatahubConnectionList.as_view(),\n name='connection-list'),\n url(r'^project/content/(?P<customer_id>\\d+)/$',\n views.DatahubConnectionListContentView.as_view(),\n name='connection-list-content'),\n url(r'^connection/create/(?P<customer_id>\\d+)/$',\n views.DatahubConnectionCreateView.as_view(),\n name='connection-create'),\n url(r'^connection/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.DatahubConnectionUpdateView.as_view(),\n name='connection-update'),\n url(r'^authorizations/',\n views.datahub_authorization_view,\n name='authorizations-view'),\n)\n" }, { "alpha_fraction": 0.6528533697128296, "alphanum_fraction": 0.6537707448005676, "avg_line_length": 37.598289489746094, "blob_id": "6e337f646a818f2c65b0b4cdbff2fd990404535f", "content_id": "380e35f0a31c9f90461660bd6f62cc5d4a27c4d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31624, "license_type": "no_license", "max_line_length": 89, "num_lines": 819, "path": "/gridplatform/consumptions/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom model_utils import FieldTracker\nfrom model_utils import Choices\n\nimport gridplatform.datasequences.models\nfrom gridplatform.cost_compensations.models import CostCompensation\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.datasequences.utils import add_ranged_sample_sequences\nfrom gridplatform.datasequences.utils import multiply_ranged_sample_sequences\nfrom gridplatform.datasequences.utils import subtract_ranged_sample_sequences\nfrom gridplatform.datasequences.utils import aggregate_sum_ranged_sample_sequence # noqa\nfrom gridplatform.datasequences.models import EnergyPerVolumeDataSequence\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.tariffs.models import Tariff\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import sum_or_none\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_CHOICES\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_TO_BASE_UNIT_MAP # noqa\nfrom gridplatform.utils.api import next_valid_date_for_datasequence\nfrom gridplatform.utils.api import previous_valid_date_for_datasequence\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.models import DateRangeModelMixin\nfrom gridplatform.utils.managers import DateRangeManagerMixin\n\n\nclass Consumption(gridplatform.datasequences.models.AccumulationBase):\n \"\"\"\n A data sequence for energy consumption via various utilities.\n\n :ivar unit: The utility unit of this data sequence. This field is\n never supposed to be changed.\n\n :ivar volumetoenergyconversion: If the utility itself is not\n measured directly as energy, this\n :py:class:`EnergyPerVolumeDataSequence` foreign key may be set\n to enable the conversion.\n \"\"\"\n\n UNIT_CHOICES = Choices(\n ('joule', 'energy', _('energy')),\n ('meter^3', 'volume', _('volume')),\n ('second', 'time', _('time'))\n )\n\n # DO NOT UPDATE\n unit = BuckinghamField(_('unit'), choices=UNIT_CHOICES)\n\n tracker = FieldTracker(fields=['unit'])\n\n volumetoenergyconversion = models.ForeignKey(\n EnergyPerVolumeDataSequence,\n verbose_name=_('volume to energy conversion'),\n null=True, blank=True)\n\n class Meta:\n verbose_name = _('consumption data sequence')\n verbose_name_plural = _('consumption data sequences')\n\n def clean(self):\n \"\"\"\n :raises ValidationError: if ``self.volumetoenergyconversion`` is\n set, but the utility is energy.\n \"\"\"\n previous_unit = self.tracker.previous('unit')\n if previous_unit is not None:\n if not PhysicalQuantity.compatible_units(previous_unit, self.unit):\n raise ValidationError(\n {\n 'unit': [ugettext('Must not be changed')]})\n\n if not PhysicalQuantity.compatible_units(self.unit, 'meter^3') and \\\n self.volumetoenergyconversion is not None:\n raise ValidationError(\n {\n 'volumetoenergyconversion': [\n ugettext(\n 'Should only be set for volumeric consumptions.')\n ]})\n\n def _hourly_conversion_sequence(self, from_timestamp, to_timestamp):\n assert not PhysicalQuantity.compatible_units(self.unit, 'joule')\n if self.volumetoenergyconversion is not None:\n return self.volumetoenergyconversion.period_set.value_sequence(\n from_timestamp, to_timestamp)\n else:\n return []\n\n def energy_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n :return: a sequence of accumulating ranged samples of energy for\n given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n if PhysicalQuantity.compatible_units(self.unit, 'joule') or \\\n PhysicalQuantity.compatible_units(self.unit, 'second'):\n return self.utility_sequence(\n from_timestamp, to_timestamp, resolution)\n\n # NOTE: Conversion happens in hourly resolution.\n utility_samples = self.utility_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n conversion_samples = self._hourly_conversion_sequence(\n from_timestamp, to_timestamp)\n hourly_energy_samples = multiply_ranged_sample_sequences(\n utility_samples, conversion_samples)\n\n return aggregate_sum_ranged_sample_sequence(\n hourly_energy_samples, resolution, self.customer.timezone)\n\n def energy_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the total energy in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n if PhysicalQuantity.compatible_units(self.unit, 'joule') or \\\n PhysicalQuantity.compatible_units(self.unit, 'second'):\n return self.utility_sum(from_timestamp, to_timestamp)\n return sum_or_none(\n sample.physical_quantity for sample in\n self.energy_sequence(\n from_timestamp, to_timestamp, condense.HOURS))\n\n def utility_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n :return: a sequence of accumulating ranged samples of utility for\n given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n return self.development_sequence(\n from_timestamp, to_timestamp, resolution)\n\n def utility_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the total utility in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n return self.development_sum(from_timestamp, to_timestamp)\n\n @property\n def utility_unit(self):\n return self.unit\n\n\nclass ConsumptionUnionManager(DateRangeManagerMixin, CustomerBoundManager):\n pass\n\n\nclass ConsumptionUnionBase(\n DateRangeModelMixin, EncryptionCustomerFieldMixin, EncryptedModel):\n \"\"\"\n Base class for ``MainConsumption`` and ``ConsumptionGroup``. To\n support historical changes fields defining a date range are\n included.\n\n :ivar name: The name of this instance.\n\n :ivar description: A description of this instance.\n\n :ivar from_date: The first date in the date range.\n\n :ivar to_date: The final date in the date range.\n\n :ivar consumptions: The ``Consumption`` objects that belong to this\n instance.\n \"\"\"\n\n name = EncryptedCharField(_('name'), max_length=100)\n description = EncryptedTextField(_('description'), blank=True)\n\n # WARNING: removing anything from this relation is almost always an error.\n consumptions = models.ManyToManyField(\n Consumption, verbose_name=_('consumptions'), blank=True)\n\n cost_compensation = models.ForeignKey(\n CostCompensation, verbose_name=_('cost compensation'),\n blank=True, null=True)\n\n objects = ConsumptionUnionManager()\n tracker = FieldTracker(fields=['cost_compensation_id'])\n\n class Meta:\n abstract = True\n\n def __unicode__(self):\n return self.name_plain\n\n def clean(self):\n super(ConsumptionUnionBase, self).clean()\n\n previous_costcompensation_id = self.tracker.previous(\n 'cost_compensation_id')\n\n if previous_costcompensation_id is not None:\n if self.cost_compensation_id is None:\n raise ValidationError(\n _('Cost compensation cannot be cleared once selected'))\n if previous_costcompensation_id != self.cost_compensation_id:\n raise ValidationError(\n _('Cost compensation cannot be changed once selected'))\n\n def energy_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the total energy in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n intersection = self.timestamp_range_intersection(\n from_timestamp, to_timestamp, self.customer.timezone)\n\n if intersection is None:\n return None\n\n return sum_or_none(\n quantity for quantity in (\n consumption.energy_sum(\n intersection.from_timestamp, intersection.to_timestamp)\n for consumption in self.consumptions.all())\n if quantity is not None)\n\n def energy_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n :return: a sequence of accumulating ranged samples of energy for\n given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n intersection = self.timestamp_range_intersection(\n from_timestamp, to_timestamp, self.customer.timezone)\n\n if intersection is None:\n return []\n\n return add_ranged_sample_sequences(\n [\n consumption.energy_sequence(\n intersection.from_timestamp, intersection.to_timestamp,\n resolution)\n for consumption in self.consumptions.all()\n ],\n intersection.from_timestamp, intersection.to_timestamp, resolution)\n\n def utility_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the total utility in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n intersection = self.timestamp_range_intersection(\n from_timestamp, to_timestamp, self.customer.timezone)\n\n if intersection is None:\n return None\n\n return sum_or_none(\n quantity for quantity in (\n consumption.utility_sum(\n intersection.from_timestamp, intersection.to_timestamp)\n for consumption in self.consumptions.all())\n if quantity is not None)\n\n def utility_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n :return: a sequence of accumulating ranged samples of utility for\n given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n intersection = self.timestamp_range_intersection(\n from_timestamp, to_timestamp, self.customer.timezone)\n\n if intersection is None:\n return []\n\n return add_ranged_sample_sequences(\n [\n consumption.utility_sequence(\n intersection.from_timestamp, intersection.to_timestamp,\n resolution)\n for consumption in self.consumptions.all()\n ],\n intersection.from_timestamp, intersection.to_timestamp, resolution)\n\n def next_valid_date(self, date, timezone):\n return next_valid_date_for_datasequence(\n self.consumptions.all(), date, timezone)\n\n def previous_valid_date(self, date, timezone):\n return previous_valid_date_for_datasequence(\n self.consumptions.all(), date, timezone)\n\n def net_cost_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n The net costs are calculated by applying the tariff directly on\n the consumed utility.\n\n :return: a sequence of accumulating ranged samples of net\n costs for given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n if not self.tariff:\n return []\n\n tariff_sequence = self.tariff.period_set.value_sequence(\n from_timestamp, to_timestamp)\n\n utility_sequence = self.utility_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n\n hourly_net_cost_sequence = multiply_ranged_sample_sequences(\n utility_sequence, tariff_sequence)\n\n return aggregate_sum_ranged_sample_sequence(\n hourly_net_cost_sequence, resolution, self.customer.timezone)\n\n def net_cost_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n The net costs are calculated by applying the tariff directly on\n the consumed utility.\n\n :return: the total energy in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n net_cost_sequence = self.net_cost_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n\n return sum_or_none(\n sample.physical_quantity for sample in net_cost_sequence)\n\n def variable_cost_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n Variable costs are net costs minus cost compensation amounts.\n\n :return: the variable costs in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n net_cost = self.net_cost_sum(from_timestamp, to_timestamp)\n costcompensation_amount = self.costcompensation_amount_sum(\n from_timestamp, to_timestamp)\n\n if costcompensation_amount is None:\n return net_cost\n elif net_cost is not None:\n return net_cost - costcompensation_amount\n else:\n return None\n\n def variable_cost_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Variable costs are net costs minus cost compensation amounts.\n\n :return: a sequence of accumulating ranged samples of variable\n cost for given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n net_cost_samples = self.net_cost_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n costcompensation_amount_samples = \\\n self.costcompensation_amount_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n\n hourly_variable_cost_sequence = subtract_ranged_sample_sequences(\n net_cost_samples, costcompensation_amount_samples)\n\n return aggregate_sum_ranged_sample_sequence(\n hourly_variable_cost_sequence, resolution, self.customer.timezone)\n\n def costcompensation_amount_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n The cost compensation amount is calculated by applying the cost\n compensation directly to the consumed energy.\n\n :return: the total cost compensation amount in the given period.\n If undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n return sum_or_none(\n sample.physical_quantity for sample in\n self.costcompensation_amount_sequence(\n from_timestamp, to_timestamp, condense.HOURS))\n\n def costcompensation_amount_sequence(\n self, from_timestamp, to_timestamp, resolution):\n raise NotImplementedError(self.__class__)\n\n def fiveminute_co2conversion_sequence(self, from_timestamp, to_timestamp):\n raise NotImplementedError(self.__class__)\n\n def co2_emissions_sequence(\n self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n The CO₂ emissions are calculated by applying the CO₂ conversion\n directly on the consumed utility.\n\n :return: a sequence of accumulating ranged samples of CO₂\n emissions for the given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n\n fiveminute_conversion_samples = self.fiveminute_co2conversion_sequence(\n from_timestamp, to_timestamp)\n fiveminute_utility_samples = self.utility_sequence(\n from_timestamp, to_timestamp, condense.FIVE_MINUTES)\n\n fiveminute_emissions_samples = multiply_ranged_sample_sequences(\n fiveminute_conversion_samples, fiveminute_utility_samples)\n\n # 10 % performance improvement by noop optimization\n if resolution == condense.FIVE_MINUTES:\n return fiveminute_emissions_samples\n else:\n return aggregate_sum_ranged_sample_sequence(\n fiveminute_emissions_samples,\n resolution, self.customer.timezone)\n\n def co2_emissions_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n The CO₂ emissions are calculated by applying the CO₂ conversion\n directly on the consumed utility.\n\n :return: the total CO₂ emissions in the given period. If\n undefined, ``None`` is returned.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n \"\"\"\n return sum_or_none(\n sample.physical_quantity for sample in\n self.co2_emissions_sequence(\n from_timestamp, to_timestamp, condense.FIVE_MINUTES))\n\n\nclass MainConsumption(ConsumptionUnionBase):\n \"\"\"\n Main consumptions are individually billed sources of utilities\n going into a company.\n\n :ivar utility_type: The type of utility of this\n ``MainConsumption``. This is supposed never to change.\n\n :ivar tariff: The tariff according to which this\n ``MainConsumption`` is billed. Changing this will almost\n certainly invalidate existing cost calculations.\n \"\"\"\n\n # NOTE: do not update\n #\n # NOTE: could have been implemented via five simple subclasses.\n utility_type = models.IntegerField(\n _('utility type'),\n choices=ENERGY_UTILITY_TYPE_CHOICES)\n\n tariff = models.ForeignKey(\n Tariff, verbose_name=_('tariff'), blank=True, null=True)\n\n tracker = FieldTracker(\n fields=['utility_type', 'tariff_id', 'cost_compensation_id'])\n\n class Meta:\n verbose_name = _('main consumption')\n verbose_name_plural = _('main consumptions')\n\n def save(self, *args, **kwargs):\n previous_utility_type = self.tracker.previous('utility_type')\n if previous_utility_type is not None:\n assert previous_utility_type == self.utility_type\n\n if self.tariff:\n assert (PhysicalQuantity(1, self.utility_unit) *\n PhysicalQuantity(1, self.tariff.unit)).compatible_unit(\n self.tariff.currency_unit), \\\n '%s not valid tariff unit for utility unit %s' % (\n self.tariff.unit, self.utility_unit)\n\n super(MainConsumption, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.name_plain\n\n def clean(self):\n super(MainConsumption, self).clean()\n\n previous_tariff_id = self.tracker.previous('tariff_id')\n if previous_tariff_id is not None:\n if self.tariff_id is None:\n raise ValidationError(\n _('Tariff cannot be cleared once selected.'))\n if previous_tariff_id != self.tariff_id:\n raise ValidationError(\n _('Tariff cannot be changed once selected.'))\n\n if self.tariff:\n utility = PhysicalQuantity(1, self.utility_unit)\n tariff = PhysicalQuantity(1, self.tariff.unit)\n if not (utility * tariff).compatible_unit(\n self.tariff.currency_unit):\n raise ValidationError(\n _('Tariff unit incompatible with utility unit.'))\n\n @property\n def utility_unit(self):\n return ENERGY_UTILITY_TYPE_TO_BASE_UNIT_MAP[self.utility_type]\n\n def costcompensation_amount_sequence(\n self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n The cost compensation amount is calculated by applying the cost\n compensation directly to the consumed energy.\n\n :return: a sequence of accumulating ranged samples of net\n costs for given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n\n NOTE: `self.cost_compensation` only applies to consumptions without\n other cost compensations. You cannot be compensated twice.\n \"\"\"\n # Cost compensation amounts from consumption groups with their own cost\n # compensations plus cost compensation for utilities not covered by\n # consumption groups with their own cost compensations.\n\n energy_sequence = self.energy_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n\n tainted_energy_sequence = add_ranged_sample_sequences(\n [\n consumption.development_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n for consumption in Consumption.objects.filter(\n consumptiongroup__cost_compensation__isnull=False,\n consumptiongroup__mainconsumption=self)\n ],\n from_timestamp, to_timestamp, condense.HOURS)\n\n if self.cost_compensation:\n untainted_energy_sequence = subtract_ranged_sample_sequences(\n energy_sequence, tainted_energy_sequence)\n\n costcompensation_sequence = \\\n self.cost_compensation.period_set.value_sequence(\n from_timestamp, to_timestamp)\n\n untainted_costcompensation_amount_sequence = \\\n multiply_ranged_sample_sequences(\n untainted_energy_sequence,\n costcompensation_sequence)\n else:\n untainted_costcompensation_amount_sequence = []\n\n tainted_consumptiongroups = self.consumptiongroup_set.filter(\n cost_compensation__isnull=False)\n\n tainted_costcompensation_amount_sequence = add_ranged_sample_sequences(\n [consumptiongroup.costcompensation_amount_sequence(\n from_timestamp, to_timestamp, resolution)\n for consumptiongroup in tainted_consumptiongroups],\n from_timestamp, to_timestamp, condense.HOURS)\n\n hourly_costcompensation_amount_sequence = add_ranged_sample_sequences(\n [\n untainted_costcompensation_amount_sequence,\n tainted_costcompensation_amount_sequence],\n from_timestamp, to_timestamp, condense.HOURS)\n\n return aggregate_sum_ranged_sample_sequence(\n hourly_costcompensation_amount_sequence,\n resolution, self.customer.timezone)\n\n def fixed_cost_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the subscription costs in the given period.\n\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n if self.tariff:\n return self.tariff.period_set.subscription_cost_sum(\n from_timestamp, to_timestamp)\n return None\n\n def total_cost_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: the total of variable and fixed costs within the given\n period. If neither is defined ``None`` is returned.\n\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n variable_cost = self.variable_cost_sum(from_timestamp, to_timestamp)\n fixed_cost = self.fixed_cost_sum(from_timestamp, to_timestamp)\n return sum_or_none(\n x for x in [variable_cost, fixed_cost] if x is not None)\n\n def fiveminute_co2conversion_sequence(self, from_timestamp, to_timestamp):\n return self.co2conversion_set.value_sequence(\n from_timestamp, to_timestamp)\n\n\nclass ConsumptionGroup(ConsumptionUnionBase):\n \"\"\"\n Defines an energy use for a ``MainConsumption``. Most methods and\n fields are inherited from ``ConsumptionUnionBase``.\n\n :ivar mainconsumption: the ``MainConsumption`` for which this\n instance defines an energy use.\n \"\"\"\n\n # NOTE: do not update\n mainconsumption = models.ForeignKey(\n MainConsumption, verbose_name=_('main consumption'))\n\n tracker = FieldTracker(\n fields=['mainconsumption_id', 'cost_compensation_id'])\n\n class Meta:\n verbose_name = _('consumption group')\n verbose_name_plural = _('consumption groups')\n\n def save(self, *args, **kwargs):\n previous_mainconsumption_id = self.tracker.previous(\n 'mainconsumption_id')\n if previous_mainconsumption_id is not None:\n assert previous_mainconsumption_id == self.mainconsumption.id\n super(ConsumptionGroup, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.name_plain\n\n @property\n def utility_unit(self):\n return self.mainconsumption.utility_unit\n\n @property\n def tariff(self):\n return self.mainconsumption.tariff\n\n def costcompensation_amount_sequence(\n self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n The cost compensation amount is calculated by applying the cost\n compensation directly to the consumed energy.\n\n :return: a sequence of accumulating ranged samples of net\n costs for given period in given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n if self.cost_compensation:\n costcompensation = self.cost_compensation\n elif self.mainconsumption.cost_compensation:\n costcompensation = self.mainconsumption.cost_compensation\n else:\n return []\n\n costcompensation_sequence = costcompensation.period_set.value_sequence(\n from_timestamp, to_timestamp)\n\n energy_sequence = self.energy_sequence(\n from_timestamp, to_timestamp, condense.HOURS)\n\n hourly_costcompensation_amount_sequence = \\\n multiply_ranged_sample_sequences(\n energy_sequence, costcompensation_sequence)\n\n return aggregate_sum_ranged_sample_sequence(\n hourly_costcompensation_amount_sequence,\n resolution,\n self.customer.timezone)\n\n def fiveminute_co2conversion_sequence(self, from_timestamp, to_timestamp):\n return self.mainconsumption.fiveminute_co2conversion_sequence(\n from_timestamp, to_timestamp)\n\n\ndef check_utility_units(\n sender, instance, action, reverse, model, pk_set, **kwargs):\n if action == 'pre_add':\n for consumption in model.objects.filter(id__in=pk_set):\n assert PhysicalQuantity.compatible_units(\n instance.utility_unit,\n consumption.utility_unit), \\\n '%s incompatible with %s' % (\n instance.utility_unit, consumption.utility_unit)\n\n\nmodels.signals.m2m_changed.connect(\n check_utility_units, sender=ConsumptionGroup.consumptions.through,\n dispatch_uid='ConsumptionGroup.consumptions utility unit check')\nmodels.signals.m2m_changed.connect(\n check_utility_units, sender=MainConsumption.consumptions.through,\n dispatch_uid='MainConsumption.consumptions utility unit check')\n\n\nclass Period(gridplatform.datasequences.models.AccumulationPeriodBase):\n datasequence = models.ForeignKey(\n Consumption,\n verbose_name=_('data sequence'),\n editable=False)\n\n class Meta:\n verbose_name = _('consumption period')\n verbose_name_plural = _('consumption periods')\n\n\nclass NonpulsePeriod(\n gridplatform.datasequences.models.NonpulseAccumulationPeriodMixin,\n Period):\n \"\"\"\n Defines :py:meth:`.Consumption.utility_sequence` of\n ``self.datasequence`` within a period in terms of a\n :py:class:`~gridplatform.datasources.models.DataSource` with a\n compatible unit.\n\n :ivar datasequence: A foreign key back to the owning :py:class:`Consumption`.\n :ivar datasource: A foreign key to the nonpulse :py:class:`DataSource`.\n :ivar from_timestamp: The start of the period.\n :ivar from_timestamp: The end of the period.\n \"\"\"\n\n class Meta:\n verbose_name = _('non-pulse consumption period')\n verbose_name_plural = _('non-pulse consumption periods')\n\n\nclass PulsePeriod(\n gridplatform.datasequences.models.PulseAccumulationPeriodMixin,\n Period):\n \"\"\"\n Defines :py:meth:`.Consumption.utility_sequence` of\n ``self.datasequence`` within a period in terms of a\n :py:class:`~gridplatform.datasources.models.DataSource` with the\n ``\"impulse\"`` unit.\n\n :ivar datasequence: A foreign key back to the owning :py:class:`Consumption`.\n :ivar datasource: A foreign key to the pulse :py:class:`DataSource`.\n :ivar from_timestamp: The start of the period.\n :ivar from_timestamp: The end of the period.\n \"\"\"\n\n class Meta:\n verbose_name = _('pulse consumption period')\n verbose_name_plural = _('pulse consumption periods')\n\n\nclass SingleValuePeriod(\n gridplatform.datasequences.models.SingleValueAccumulationPeriodMixin,\n Period):\n \"\"\"\n Defines :py:meth:`.Consumption.utility_sequence` of\n ``self.datasequence`` within a period in terms of a single utility\n quantity spread evenly across the period.\n\n :ivar datasequence: A foreign key back to the owning :py:class:`Consumption`.\n :ivar value: The value of the utility quantity.\n :ivar unit: The unit of the utility quantity.\n :ivar from_timestamp: The start of the period.\n :ivar from_timestamp: The end of the period.\n \"\"\"\n class Meta:\n verbose_name = _('single value consumption period')\n verbose_name_plural = _('single value consumption periods')\n\n\nclass OfflineTolerance(\n gridplatform.datasequences.models.OfflineToleranceMixin):\n datasequence = models.OneToOneField(\n Consumption,\n editable=False)\n" }, { "alpha_fraction": 0.6037604212760925, "alphanum_fraction": 0.6309192180633545, "avg_line_length": 33.19047546386719, "blob_id": "bb88c214cd9e8110e7d7c3cd9ed166e1a85ea00d", "content_id": "b5de8ecb86d01815ef45e5fd2a46454728de87cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1436, "license_type": "no_license", "max_line_length": 89, "num_lines": 42, "path": "/gridagentserver/relay_state.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# dry-run example command:\n# ./relay_state.py -n -v 00:24:21:0e:8f:cd --on aa:bb:cc:dd:11:22:33:44 \\\n# 11:22:33:44:aa:bb:cc:dd\n\nimport argparse\n\nfrom client import normalise_mac, send_message, gridpoint_id\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('agent', help='target agent (MAC address)')\nparser.add_argument('meters', nargs='+',\n help='target meters (ZigBee MAC addresses)')\nparser.add_argument('-v', '--verbose', action='store_true',\n help='increase output verbosity')\nparser.add_argument('-n', '--dry-run', action='store_true',\n help='don\\'t actually send command')\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument('-o', '--on', action='store_true', help='switch relay on')\ngroup.add_argument('-f', '--off', action='store_true', help='switch relay off')\n\n\ndef relay_state(args):\n agent_mac = normalise_mac(args.agent)\n meters = [gridpoint_id(normalise_mac(meter, bytes=8))\n for meter in args.meters]\n routing_key = 'agent.%s' % (agent_mac,)\n assert args.on != args.off\n relay_on = args.on\n message = {\n 'command': 'relay_state',\n 'agent': agent_mac,\n 'relay_on': relay_on,\n 'meters': meters,\n }\n send_message(routing_key, message, args.verbose, args.dry_run)\n\n\nif __name__ == '__main__':\n relay_state(parser.parse_args())\n" }, { "alpha_fraction": 0.5291479825973511, "alphanum_fraction": 0.5417040586471558, "avg_line_length": 31.794116973876953, "blob_id": "e94a6dab1eff093eb7e38254c11bd0b00cef29e4", "content_id": "59769b4fb6b71f0805b8c0766634ea68d67510ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 71, "num_lines": 34, "path": "/legacy/display_measurementpoints/static/floorplan.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true, devel: true */\n/*global $, jQuery */\nvar gridportal = gridportal || {};\ngridportal.floorplan = gridportal.floorplan || {};\n\ngridportal.floorplan.show = function (updateUrl) {\n 'use strict';\n var floorplan = $('#floorplan');\n floorplan.height(floorplan.find('.map .floorplan-image').height());\n setTimeout(function () {\n gridportal.floorplan.update(updateUrl);\n }, 60 * 1000);\n};\n\ngridportal.floorplan.update = function (updateUrl) {\n 'use strict';\n jQuery.get(updateUrl, function (data) {\n var floorplan = $('#floorplan');\n $('#floorplan .item').not('.infoitem').each(function () {\n var item = $(this),\n value = data[item.data('id')],\n rendered_value;\n if (value === null) {\n rendered_value = \"\";\n } else {\n rendered_value = value[0] + ' ' + value[1];\n }\n item.find('.item_value').html(rendered_value);\n });\n setTimeout(function () {\n gridportal.floorplan.update(updateUrl);\n }, 60 * 1000);\n });\n};\n" }, { "alpha_fraction": 0.6726770997047424, "alphanum_fraction": 0.6728610992431641, "avg_line_length": 41.7952766418457, "blob_id": "0ab335983c755993665df4122d8362f4d8df88bb", "content_id": "e18cf85e3a628ffad4aebb06b7e7fb740816fa6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5435, "license_type": "no_license", "max_line_length": 79, "num_lines": 127, "path": "/legacy/measurementpoints/proxies/consumptionmeasurementpointsummation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints import default_unit_for_data_series\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Summation\nfrom legacy.measurementpoints.models import SummationTerm\n\nfrom .consumptionmeasurementpoint import ConsumptionMeasurementPoint\n\n\nclass ConsumptionMeasurementPointSummation(ConsumptionMeasurementPoint):\n \"\"\"\n A C{ConsumptionMeasurementPointSummation} is a\n L{ConsumptionMeasurementPoint} whose consumption L{DataSeries} is defined\n as the sum of other L{ConsumptionMeasurementPoint}s consumption data\n series. This is only well-defined if all the involved\n L{ConsumptionMeasurementPoint}s have the same resource type.\n\n @ivar consumption: A L{DataSeries} defined as the interpolated sum of the\n consumption data series of the related consumption measurement points.\n This property overrides that of L{ConsumptionMeasurementPoint}.\n\n @ivar plus_consumption_measurement_points: A list of consumption\n measurement points to be added in this summation.\n\n @ivar minus_consumption_measurement_points: A list of consumption\n measurement points to be subtracted in this summation.\n \"\"\"\n\n class Meta(ConsumptionMeasurementPoint.Meta):\n proxy = True\n verbose_name = _('Summation measurement point')\n verbose_name_plural = _('Summation measurement points')\n app_label = 'customers'\n\n def clean(self):\n super(ConsumptionMeasurementPointSummation, self).clean()\n if list(self.plus_consumption_measurement_points) == [] and \\\n list(self.minus_consumption_measurement_points) == []:\n raise ValidationError(\n _(u'At least one measurement point must be selected.'))\n\n for ds in [mp.consumption for mp in itertools.chain(\n self.plus_consumption_measurement_points,\n self.minus_consumption_measurement_points)]:\n if self.consumption == ds or self.consumption in ds.depends_on():\n raise ValidationError(\n _(u'{measurement_point} cannot be included in the '\n 'summation, as it would form circular dependencies.').\n format(measurement_point=ds.graph.\n collection.subclass_instance))\n\n def save(self, *args, **kwargs):\n \"\"\"\n Saves this C{ConsumptionMeasurementPointSummation}, by creating and/or\n updating the underlying relations.\n \"\"\"\n super(ConsumptionMeasurementPointSummation, self).save(*args, **kwargs)\n\n self.consumption.plus_data_series = [\n mp.consumption for mp in self.plus_consumption_measurement_points]\n self.consumption.minus_data_series = [\n mp.consumption for mp in self.minus_consumption_measurement_points]\n self.consumption.save()\n\n def _get_consumption(self):\n \"\"\"\n C{ConsumptionMeasurementPointSummation} specialziation of\n L{ConsumptionMeasurementPoint}.\n\n @return: Returns the current consumption DataSeries. If no such\n DataSeries is defined, a new consumption DataSeries is returned.\n \"\"\"\n if super(ConsumptionMeasurementPointSummation, self).\\\n _get_consumption() is None:\n self.consumption = Summation(\n role=DataRoleField.CONSUMPTION,\n customer=self.customer,\n utility_type=self.utility_type,\n unit=default_unit_for_data_series(\n DataRoleField.CONSUMPTION,\n self.utility_type))\n return super(ConsumptionMeasurementPointSummation, self).\\\n _get_consumption()\n\n consumption = property(\n _get_consumption,\n ConsumptionMeasurementPoint._set_consumption)\n\n def _set_plus_consumption_measurement_points(self, mp_list):\n self._positive_mp_terms = mp_list\n\n def _get_plus_consumption_measurement_points(self):\n if not hasattr(self, '_positive_mp_terms'):\n self._positive_mp_terms = list(\n ConsumptionMeasurementPoint.objects.filter(\n graph__dataseries__summationterm__sign=SummationTerm.PLUS,\n graph__dataseries__summationterm__summation=self.\n consumption))\n return self._positive_mp_terms\n\n plus_consumption_measurement_points = property(\n _get_plus_consumption_measurement_points,\n _set_plus_consumption_measurement_points)\n\n def _set_minus_consumption_measurement_points(self, mp_list):\n self._negative_mp_terms = mp_list\n\n def _get_minus_consumption_measurement_points(self):\n if not hasattr(self, '_negative_mp_terms'):\n self._negative_mp_terms = list(\n ConsumptionMeasurementPoint.objects.filter(\n graph__dataseries__summationterm__sign=SummationTerm.MINUS,\n graph__dataseries__summationterm__summation=self.\n consumption))\n return self._negative_mp_terms\n\n minus_consumption_measurement_points = property(\n _get_minus_consumption_measurement_points,\n _set_minus_consumption_measurement_points)\n" }, { "alpha_fraction": 0.6455211043357849, "alphanum_fraction": 0.6458696126937866, "avg_line_length": 37.253334045410156, "blob_id": "d00d4f20c0fde983ab8172487b3f5588d7f0218d", "content_id": "8f0e345dbc6cab2c2d9079562d2e6b3f7bc081b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2869, "license_type": "no_license", "max_line_length": 79, "num_lines": 75, "path": "/gridplatform/customers/fields.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django import forms\nfrom south.modelsinspector import add_introspection_rules\n\nfrom gridplatform.utils.units import preferred_unit_bases\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\n\nclass UnitNormalisingField(models.BigIntegerField):\n \"\"\"\n A model field which normalises data from a customer preferred input unit\n from input forms to the corresponding \"base\" unit for storage and access\n from code.\n\n I.e. when accessing a C{UnitNormalisingField} from code, the value held is\n in C{preferred_unit_bases[preferred_unit_getter(model)]}, where\n C{preferred_unit_getter()} is an argument for L{__init__()}, and C{model}\n is the model instance that this field is assigned to.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @param preferred_unit_getter: Callable which, given the model object\n instance that this field is used with, will return the relevant\n Buckingham preferred unit.\n \"\"\"\n self.preferred_unit_getter = kwargs.pop('preferred_unit_getter', None)\n super(UnitNormalisingField, self).__init__(*args, **kwargs)\n\n # NOTE: value_from_object is used to initialise form; serialising uses\n # value_to_string(), DB uses get_prep_value() (and others); we only convert\n # for forms...\n def value_from_object(self, obj):\n \"\"\"\n Get field value in customer preferred unit.\n \"\"\"\n normalised = super(UnitNormalisingField, self).value_from_object(obj)\n if normalised is not None:\n preferred_unit = self.preferred_unit_getter(obj)\n if preferred_unit is not None:\n base_unit = preferred_unit_bases[preferred_unit]\n data = float(\n PhysicalQuantity(normalised, base_unit).convert(\n preferred_unit))\n else:\n data = None\n else:\n data = None\n return data\n\n def save_form_data(self, instance, data):\n \"\"\"\n Normalise and store field value from customer preferred unit.\n \"\"\"\n if data is not None:\n preferred_unit = self.preferred_unit_getter(instance)\n base_unit = preferred_unit_bases[preferred_unit]\n normalised = int(PhysicalQuantity(\n data, preferred_unit).convert(base_unit))\n else:\n normalised = None\n super(UnitNormalisingField, self).save_form_data(instance, normalised)\n\n def formfield(self, **kwargs):\n defaults = {'form_class': forms.FloatField}\n defaults.update(kwargs)\n return models.Field.formfield(self, **defaults)\n\n\nadd_introspection_rules([], [\n \"^gridplatform\\.customers\\.fields\\.UnitNormalisingField\"])\n" }, { "alpha_fraction": 0.5821840167045593, "alphanum_fraction": 0.5828623175621033, "avg_line_length": 36.48305130004883, "blob_id": "652e5091023a9ec776a1f132ce8b1eec335cda5f", "content_id": "3d6f1d94a895f65e042716464652b42c6d0cd6cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13269, "license_type": "no_license", "max_line_length": 79, "num_lines": 354, "path": "/legacy/measurementpoints/models/summation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom ..interpolationcloud import InterpolationCloud\nfrom .dataseries import DataSeries\n\n\nclass Stream(object):\n \"\"\"\n Iterator wrapper which provides a `peek()` method by reading one ahead in\n the underlying iterator.\n\n NOTE: This will always have read one ahead in the underlying iterator ---\n which allows a simpler implementation than lazy/on-demand evaluation of the\n underlying iterator, and does not matter for the immediate use.\n\n NOTE: This will yield an infinite sequence of `None` after the elements of\n the underlying sequence. This, again, allows for a simpler implementation\n than one raising `StopIteration` when the underlying iterator does.\n \"\"\"\n def __init__(self, sequence):\n self._iterator = iter(sequence)\n self._head = next(self._iterator, None)\n\n def __iter__(self):\n return self\n\n def peek(self):\n return self._head\n\n def next(self):\n val = self._head\n self._head = next(self._iterator, None)\n return val\n\n\nclass Summation(DataSeries):\n \"\"\"\n A C{Summation} is a L{DataSeries} that is defined as the sum of other\n L{DataSeries} through the L{SummationTerm} relation, which also defines the\n sign to be used for the particular term in the sum.\n\n @ivar plus_data_series: A list of L{DataSeries} to add in this\n C{Summation}.\n\n @ivar minus_data_series: A list of L{DataSeries} to subtract in this\n C{Summation}.\n \"\"\"\n\n included_data_series = models.ManyToManyField(\n DataSeries, related_name='summation_derivative_set',\n through='measurementpoints.SummationTerm',\n symmetrical=False)\n\n class Meta(DataSeries.Meta):\n verbose_name = _('summation')\n verbose_name_plural = _('summations')\n app_label = 'measurementpoints'\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Construct a C{Summation}. Optionally, the data series to add and\n subtract may be given here.\n\n @keyword plus_data_series: An optional list of L{DataSeries} to add in\n this C{Summation}.\n\n @keyword minus_data_series: An optional list of L{DataSeries} to\n subtract in this C{Summation}.\n \"\"\"\n if 'plus_data_series' in kwargs:\n self.plus_data_series = kwargs.pop('plus_data_series')\n if 'minus_data_series' in kwargs:\n self.minus_data_series = kwargs.pop('minus_data_series')\n super(Summation, self).__init__(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save this C{Summation} and the involved relations.\n \"\"\"\n super(Summation, self).save(*args, **kwargs)\n\n # Ensure data series to be added in this summation are stored.\n add_data_series_ids = []\n for add_ds in self.plus_data_series:\n self.terms.get_or_create(\n sign=SummationTerm.PLUS,\n data_series=add_ds)\n add_data_series_ids.append(add_ds.id)\n # Remove those no longer required.\n self.terms.filter(\n sign=SummationTerm.PLUS).exclude(\n data_series__in=add_data_series_ids).delete()\n\n # Ensure data series to be subtracted in this summation are stored.\n subtract_data_series_ids = []\n for subtract_ds in self.minus_data_series:\n self.terms.get_or_create(\n sign=SummationTerm.MINUS,\n data_series=subtract_ds)\n subtract_data_series_ids.append(subtract_ds.id)\n # Remove those, no longer required.\n self.terms.filter(\n sign=SummationTerm.MINUS).exclude(\n data_series__in=subtract_data_series_ids).delete()\n\n def _set_plus_data_series(self, ds_list):\n self._plus_data_series = ds_list\n\n def _get_plus_data_series(self):\n if not hasattr(self, '_plus_data_series'):\n self._plus_data_series = [\n ds.subclass_instance for ds in\n DataSeries.objects.filter(\n summationterm__sign=SummationTerm.PLUS,\n summationterm__summation=self)]\n return self._plus_data_series\n\n plus_data_series = property(_get_plus_data_series, _set_plus_data_series)\n\n def _set_minus_data_series(self, ds_list):\n self._minus_data_series = ds_list\n\n def _get_minus_data_series(self):\n if not hasattr(self, '_minus_data_series'):\n self._minus_data_series = [\n ds.subclass_instance for ds in\n DataSeries.objects.filter(\n summationterm__sign=SummationTerm.MINUS,\n summationterm__summation=self)]\n return self._minus_data_series\n\n minus_data_series = property(_get_minus_data_series,\n _set_minus_data_series)\n\n def get_included_data_series(self):\n return itertools.chain(\n self.plus_data_series,\n self.minus_data_series)\n\n def calculate_development(self, from_timestamp, to_timestamp):\n result_quantity = PhysicalQuantity(0, self.unit)\n result_cachable = True\n result_extrapolated = False\n\n for pds in self.plus_data_series:\n s = pds.calculate_development(from_timestamp, to_timestamp)\n if s is None:\n result_cachable = False\n result_extrapolated = True\n else:\n result_cachable = s.cachable and result_cachable\n result_extrapolated = s.extrapolated or result_extrapolated\n result_quantity = result_quantity + s.physical_quantity\n\n for pds in self.minus_data_series:\n s = pds.calculate_development(from_timestamp, to_timestamp)\n if s is None:\n result_cachable = False\n result_extrapolated = True\n else:\n result_cachable = s.cachable and result_cachable\n result_extrapolated = s.extrapolated or result_extrapolated\n result_quantity = result_quantity - s.physical_quantity\n\n return self.create_range_sample(\n from_timestamp, to_timestamp, result_quantity,\n uncachable=not result_cachable, extrapolated=result_extrapolated)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{Summation} implementation of L{DataSeries.get_raw_data_samples()}.\n \"\"\"\n data_series_list = self.get_included_data_series()\n\n zero = PhysicalQuantity(0, self.unit)\n\n for sample_vector in InterpolationCloud(data_series_list,\n from_timestamp, to_timestamp):\n t = None\n for sample in sample_vector:\n if sample is not None:\n t = sample.timestamp\n break\n if t is None:\n break\n\n quantities = [getattr(s, 'physical_quantity', zero) for\n s in sample_vector]\n plus_quantities = quantities[:len(self.plus_data_series)]\n minus_quantities = quantities[len(self.plus_data_series):]\n physical_quantity = (sum(plus_quantities,\n -1 * sum(minus_quantities, zero)))\n\n uncachable = any(\n (sample is None or sample.uncachable for\n sample in sample_vector))\n\n extrapolated = any(\n (sample is None or sample.extrapolated for\n sample in sample_vector))\n yield Sample(t, t, physical_quantity, not uncachable, extrapolated)\n\n def depends_on(self):\n \"\"\"\n C{Summation} implementation of L{DataSeries.depends_on()}.\n \"\"\"\n if self.id:\n deps = []\n for ds in self.get_included_data_series():\n deps.append(ds)\n for dep in ds.depends_on():\n deps.append(dep)\n return deps\n else:\n return []\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n plus_data = [\n Stream(ds.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp))\n for ds in self.plus_data_series\n ]\n minus_data = [\n Stream(ds.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp))\n for ds in self.minus_data_series\n ]\n all_data = plus_data + minus_data\n zero = PhysicalQuantity(0, self.unit)\n while True:\n uncachable = False\n extrapolated = False\n next_samples = [\n elem.peek() for elem in all_data if elem.peek() is not None]\n if not next_samples:\n break\n from_timestamp = min(\n [sample.from_timestamp for sample in next_samples])\n to_timestamp = from_timestamp + sample_resolution\n val = zero\n for elem in plus_data:\n if getattr(elem.peek(), 'from_timestamp', None) == \\\n from_timestamp:\n sample = elem.next()\n assert sample.from_timestamp == from_timestamp\n assert sample.to_timestamp == to_timestamp\n val += sample.physical_quantity\n extrapolated = extrapolated or sample.extrapolated\n uncachable = uncachable or sample.uncachable\n for elem in minus_data:\n if getattr(elem.peek(), 'from_timestamp', None) == \\\n from_timestamp:\n sample = elem.next()\n assert sample.from_timestamp == from_timestamp\n assert sample.to_timestamp == to_timestamp\n val -= sample.physical_quantity\n extrapolated = extrapolated or sample.extrapolated\n uncachable = uncachable or sample.uncachable\n yield self.create_range_sample(\n from_timestamp, to_timestamp, val, uncachable, extrapolated)\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n C{Summation} override of the L{DataSeries} method.\n \"\"\"\n data_series_list = self.get_included_data_series()\n\n zero = PhysicalQuantity(0, self.unit)\n\n sample_vectors = itertools.izip_longest(\n *[\n iter(ds.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)) for\n ds in data_series_list])\n\n for sample_vector in sample_vectors:\n from_t = None\n to_t = None\n for sample in sample_vector:\n if sample is not None:\n from_t = sample.from_timestamp\n to_t = sample.to_timestamp\n break\n if from_t is None:\n assert to_t is None\n break\n\n quantities = [getattr(s, 'physical_quantity', zero) for\n s in sample_vector]\n plus_quantities = quantities[:len(self.plus_data_series)]\n minus_quantities = quantities[len(self.plus_data_series):]\n\n physical_quantity = (sum(plus_quantities,\n -1 * sum(minus_quantities, zero)))\n\n uncachable = any(\n (sample is None or sample.uncachable for\n sample in sample_vector))\n\n extrapolated = any(\n (sample is None or sample.extrapolated for\n sample in sample_vector))\n\n yield self.create_range_sample(\n from_t, to_t, physical_quantity, uncachable, extrapolated)\n\n def get_recursive_condense_resolution(self, resolution):\n if condense.is_finer_resolution(resolution, condense.HOURS):\n return None\n else:\n return condense.next_resolution(resolution)\n\n\nclass SummationTerm(models.Model):\n \"\"\"\n A C{SummationTerm} associates a L{DataSeries} with a C{SumInclusionPeriod}.\n\n @ivar sign: The sign used to include the given L{DataSeries} in the sum.\n\n @ivar summation: The C{Summation} the given L{DataSeries} should be\n included in.\n\n @ivar data_series. The given L{dataSeries} to include in the sum.\n \"\"\"\n PLUS = 1\n MINUS = 2\n SIGN_CHOICES = (\n (PLUS, '+'),\n (MINUS, '-'))\n\n sign = models.IntegerField(choices=SIGN_CHOICES)\n summation = models.ForeignKey(Summation, on_delete=models.CASCADE,\n related_name='terms')\n data_series = models.ForeignKey(DataSeries, on_delete=models.PROTECT)\n\n class Meta:\n app_label = 'measurementpoints'\n\n def __repr__(self):\n return '<SummationTerm(sign=%r, period=%r, data_series=%r)>' % (\n self.sign, self.period, self.data_series)\n" }, { "alpha_fraction": 0.647912859916687, "alphanum_fraction": 0.6529037952423096, "avg_line_length": 33.984127044677734, "blob_id": "19daf0cf8d20543798b0941f29dff6eed0190aaa", "content_id": "a7a82026e50e98f78de7dced1984a8feedcc1ebe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2204, "license_type": "no_license", "max_line_length": 77, "num_lines": 63, "path": "/gridagentserver-protocol/gridagentserver_protocol/handshake.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"Sending handshake messages.\"\"\"\n\nfrom struct import Struct\nimport random\nimport logging\n\nfrom encryption import StreamEncrypter\nfrom . import PROTOCOL_VERSION, SECRET\n\n\nlogger = logging.getLogger(__name__)\n\n# protocol version, ID/nonce\nhandshake_struct = Struct('!IQ')\nuint64 = Struct('!Q')\n\n\ndef handshake(wfile, rfile, wdata):\n outgoing = handshake_struct.pack(PROTOCOL_VERSION, wdata)\n wfile.write(outgoing)\n wfile.flush()\n incoming = rfile.read(handshake_struct.size)\n version, rdata = handshake_struct.unpack(incoming)\n return version, rdata\n\n\ndef handshake_serverside(wfile, rfile):\n nonce = random.randint(0, 2 ** 64)\n version, agent_mac = handshake(wfile, rfile, nonce)\n logger.debug('Connection from agent %X, protocol %d', agent_mac, version)\n if version > PROTOCOL_VERSION or version <= 0:\n raise Exception('Protocol %d not supported; disconnecting %X' % (\n version,\n agent_mac,\n ))\n encrypt_write, read_decrypt = init_encryption(wfile, rfile,\n agent_mac, nonce)\n return (version, agent_mac, encrypt_write, read_decrypt)\n\n\ndef handshake_clientside(wfile, rfile, agent_mac):\n serverside_version, nonce = handshake(wfile, rfile, agent_mac)\n if serverside_version != PROTOCOL_VERSION:\n logger.debug('Protocol versions differ: Client: %d, server: %d' % (\n PROTOCOL_VERSION,\n serverside_version\n ))\n # we use version from client anyway\n encrypt_write, read_decrypt = init_encryption(wfile, rfile,\n agent_mac, nonce)\n return encrypt_write, read_decrypt\n\n\ndef init_encryption(wfile, rfile, agent_mac, nonce):\n # initialise encryption state with nonce + secret + incoming data\n key_bytes = bytearray(SECRET)\n id_bytes = bytearray(uint64.pack(agent_mac))\n nonce_bytes = bytearray(uint64.pack(nonce))\n for i in range(len(nonce_bytes)):\n key_bytes[i] = key_bytes[i] ^ id_bytes[i] ^ nonce_bytes[i]\n encrypt_write = StreamEncrypter(key_bytes, wfile)\n read_decrypt = StreamEncrypter(key_bytes, rfile)\n return encrypt_write, read_decrypt\n" }, { "alpha_fraction": 0.7050520181655884, "alphanum_fraction": 0.7065379023551941, "avg_line_length": 25.920000076293945, "blob_id": "7c2cb0e071368d4b00734fe7e0dd09a3722f00db", "content_id": "65085a772a51b194ff31e9851b462028e5e4d8ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1346, "license_type": "no_license", "max_line_length": 79, "num_lines": 50, "path": "/gridplatform/encryption/testutils.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport contextlib\n\nfrom Crypto.Cipher import AES\n\nfrom .conf import settings\nfrom .base import EncryptionContext\nfrom .base import _store\n\n\nclass NoEncryptionCipher(object):\n def encrypt(self, plaintext):\n assert isinstance(plaintext, bytes)\n return b''.join(reversed(plaintext))\n\n def decrypt(self, ciphertext):\n assert isinstance(ciphertext, bytes)\n return b''.join(reversed(ciphertext))\n\n\nclass NoEncryptionContext(EncryptionContext):\n def __init__(self):\n self.keys = {}\n\n @classmethod\n def generate_iv(cls):\n return b'\\0' * AES.block_size\n\n def get_cipher(self, key_id, iv):\n return NoEncryptionCipher()\n\n\[email protected]\ndef no_encryption():\n old = getattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, None)\n setattr(\n _store, settings.ENCRYPTION_CONTEXT_STORE_KEY, NoEncryptionContext())\n yield\n setattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, old)\n\n\[email protected]\ndef encryption_context():\n old = getattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, None)\n setattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, EncryptionContext())\n yield\n setattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, old)\n" }, { "alpha_fraction": 0.6871493458747864, "alphanum_fraction": 0.6895538568496704, "avg_line_length": 39.247310638427734, "blob_id": "c83dd2c842c4e0641e3c86d88980b43118f7b4a6", "content_id": "69f13797bd581cc389805026992e31791f65b0ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3743, "license_type": "no_license", "max_line_length": 79, "num_lines": 93, "path": "/legacy/measurementpoints/models/meantemperaturechange.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\nfrom .mixins import ENPIMixin\n\n\nVOLUMETRIC_THERMAL_CAPACITY_WATER = PhysicalQuantity(\n 860, 'kelvin*meter^3*megawatt^-1*hour^-1')\n\n\nclass MeanTemperatureChange(ENPIMixin, DataSeries):\n \"\"\"\n Calculate the mean temperature change (cool-down or heat-up) using the\n volumetric thermal capacity, energy and volume.\n\n Relevant for district heating using water as heat distribution medium.\n\n @note: Using the volumetric thermal capacity of water, we can view the\n volume as energy pr degree kelvin, which in turn makes the volume an energy\n driver and the resulting ENPI a temperature. This is the idea behind using\n the C{ENPIMixin}.\n\n @ivar energy: The energy L{DataSeries}\n\n @ivar volume: The volume L{DataSeries}\n\n @invariant: The C{energy} L{DataSeries} has an energy unit (e.g joule).\n\n @invariant: The C{volume} L{DataSeries} has a volume unit (e.g. m^3).\n \"\"\"\n energy = models.ForeignKey(\n DataSeries, on_delete=models.CASCADE,\n related_name='mean_temperature_change_energy_derivative_set')\n volume = models.ForeignKey(\n DataSeries, on_delete=models.CASCADE,\n related_name='mean_temperature_change_volume_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('mean temperature change')\n verbose_name_plural = _('mean temperature change')\n app_label = 'measurementpoints'\n\n def save(self, *args, **kwargs):\n self._assert_invariants()\n super(MeanTemperatureChange, self).save(*args, **kwargs)\n\n def _assert_invariants(self):\n assert PhysicalQuantity.compatible_units(self.energy.unit, 'joule')\n assert PhysicalQuantity.compatible_units(self.volume.unit, 'meter^3')\n\n def depends_on(self):\n return [self.energy.subclass_instance,\n self.volume.subclass_instance] + \\\n self.energy.subclass_instance.depends_on() + \\\n self.volume.subclass_instance.depends_on()\n\n def _condense_energy_drivers(\n self, from_timestamp, sample_resolution, to_timestamp):\n for volume in self.volume.subclass_instance.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp):\n yield volume._replace(\n physical_quantity=volume.physical_quantity /\n VOLUMETRIC_THERMAL_CAPACITY_WATER)\n\n def _condense_energy_consumption(self, from_timestamp, sample_resolution,\n to_timestamp):\n return self.energy.subclass_instance.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n\n def calculate_cost(self, from_timestamp, to_timestamp, consumption=None):\n # load shifting according to measured data doesn't make sense anyway.\n raise NotImplementedError()\n\n def aggregated_samples(self, from_timestamp, to_timestamp):\n # aggregations of condensed mean are not defined without a resolution.\n raise NotImplementedError()\n\n def _calculate_energy_development(self, from_timestamp, to_timestamp):\n return self.energy.calculate_development(from_timestamp, to_timestamp)\n\n def _calculate_energy_driver_development(\n self, from_timestamp, to_timestamp):\n volume = self.volume.calculate_development(\n from_timestamp, to_timestamp)\n return volume._replace(\n physical_quantity=volume.physical_quantity /\n VOLUMETRIC_THERMAL_CAPACITY_WATER)\n" }, { "alpha_fraction": 0.5885002017021179, "alphanum_fraction": 0.6293730735778809, "avg_line_length": 31.077777862548828, "blob_id": "5301ccb987b481820886df6fb7ea3d38c924aea7", "content_id": "9971da941f1c7ce7904fa09fbe4b4a2ddf1233e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2887, "license_type": "no_license", "max_line_length": 79, "num_lines": 90, "path": "/measurement_fixture.hack.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport os\nimport datetime\nimport random\nimport pytz\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"gridplatform.settings.local\")\n\nfrom django.db import transaction\n\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.devices.models import RawData\n\ndays = 14\nstart = datetime.datetime.now(pytz.utc).replace(microsecond=0) - \\\n datetime.timedelta(days=days)\n\ndst_start = datetime.datetime(2013, 3, 31, tzinfo=pytz.utc)\ndst_end = datetime.datetime(2012, 10, 28, tzinfo=pytz.utc)\n\n\nval = 0\n\nfor physicalinput in PhysicalInput.objects.filter(\n unit='milliwatt*hour'):\n measurements = []\n if physicalinput.rawdata_set.exists():\n continue\n val = 0\n\n for time in [dst_end, dst_start]:\n for i in range(60 * 24 * 2):\n current = time + datetime.timedelta(minutes=i)\n if datetime.time(hour=6) < current.time() < datetime.time(hour=16):\n incr = random.randint(10000000, 11500000)\n else:\n incr = random.randint(100000, 300000)\n measurements.append(RawData(\n datasource_id=physicalinput.id,\n timestamp=current,\n value=val))\n val += incr / 60\n\n for i in range(60 * 24 * days):\n current = start + datetime.timedelta(minutes=i)\n if datetime.time(hour=6) < current.time() < datetime.time(hour=16):\n incr = random.randint(10000000, 11500000)\n else:\n incr = random.randint(100000, 300000)\n measurements.append(RawData(\n datasource_id=physicalinput.id,\n timestamp=current,\n value=val))\n val += incr / 60\n\n with transaction.commit_on_success():\n RawData.objects.bulk_create(measurements)\n\nfor physicalinput in PhysicalInput.objects.filter(\n unit='millikelvin') | PhysicalInput.objects.filter(\n unit='milliwatt') | PhysicalInput.objects.filter(\n unit='millinone'):\n measurements = []\n if physicalinput.rawdata_set.exists():\n continue\n for i in range(3 * 24 * days):\n current = start + datetime.timedelta(minutes=20 * i)\n val = random.randint(260000, 290000)\n measurements.append(RawData(\n datasource_id=physicalinput.id,\n timestamp=current,\n value=val))\n\n with transaction.commit_on_success():\n RawData.objects.bulk_create(measurements)\n\nfor pulse in PhysicalInput.objects.filter(\n unit='impulse'):\n measurements = []\n for i in range(3 * 24 * days):\n current = start + datetime.timedelta(minutes=20 * i)\n measurements.append(RawData(\n datasource_id=pulse.id,\n timestamp=current,\n value=i))\n RawData.objects.bulk_create(measurements)\n" }, { "alpha_fraction": 0.5666666626930237, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 11, "blob_id": "477b4416523802aa28fe846ed9ea9ed8eb5f8438", "content_id": "364c58d9914cd08cf237ba6d003f03d679628777", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 60, "license_type": "no_license", "max_line_length": 28, "num_lines": 5, "path": "/scripts/production_nordic/manage.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsource $(dirname $0)/base.sh\n\n./manage.py \"$@\"\n" }, { "alpha_fraction": 0.494775652885437, "alphanum_fraction": 0.49723416566848755, "avg_line_length": 24.421875, "blob_id": "ac85e5a928fd403284b5645400665bea9f6b2b88", "content_id": "ae7878915ee676704819ebed3b28dac8c082da47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1627, "license_type": "no_license", "max_line_length": 78, "num_lines": 64, "path": "/legacy/setup_agents/templates/setup_agents/agent_form.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends 'overlay_base.html' %}\n{% load i18n %}\n{% load url from future %}\n{% load static from staticfiles %}\n{% load action %}\n\n{% block title %}\n {% if agent.id %}\n {% trans \"Edit\" %} {{ agent }}\n {% else %}\n {% trans \"New Agent\" %}\n {% endif %}\n{% endblock title %}\n\n{% block action %}\n {% action 'setup_agents-update' form.instance pk=agent.id %}\n{% endblock %}\n\n{% block content %}\n<div class=\"clearfix\">\n {% csrf_token %}\n <div class=\"left\">\n <fieldset>\n <label>{% trans 'Customer:' %}</label>\n {{ form.customer }}\n {{ form.customer.errors }}\n </fieldset>\n </div>\n <div class=\"left\">\n <fieldset>\n {% if agent.id %}\n <span>{% trans \"MAC:\" %}</span>\n <span>{{ agent.mac }}</span>\n {{ form.mac.as_hidden }}\n {{ form.mac.errors }}\n {% else %}\n <label>{% trans 'MAC:' %}</label>\n {{ form.mac }}\n {{ form.mac.errors }}\n {% endif %}\n </fieldset>\n </div>\n</div>\n{% endblock %}\n{% block extra_content %}\n {% if upgrade_form %}\n <form method=\"POST\" action=\"{% url 'setup_agents-swupgrade' pk=agent.id %}\">\n {% csrf_token %}\n <h2>{% trans \"Software upgrade\" %}</h2>\n <div class=\"wrapper\">\n <div class=\"left\">\n <div class=\"form-item\">\n <label>{% trans 'Software version:' %}</label>\n {{ upgrade_form.software_image }}\n {{ upgrade_form.errors }}\n </div>\n </div>\n </div>\n <div class=\"right\">\n <input type=\"submit\" value=\"{% trans \"Send image\" %}\" />\n </div>\n </form>\n {% endif %}\n{% endblock extra_content %}\n" }, { "alpha_fraction": 0.6922257542610168, "alphanum_fraction": 0.6964856386184692, "avg_line_length": 30.830509185791016, "blob_id": "2a99672293ae9b963c599d6eb88c8e03b927accb", "content_id": "9313b6e4647abd568c2fbbbbe57027f8a9580d4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1880, "license_type": "no_license", "max_line_length": 79, "num_lines": 59, "path": "/legacy/energinet_co2/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport sys\nimport pytz\n\nfrom django.db import models\nfrom django.db.models import signals\n\n# ensure that appconf settings are loaded\nfrom .conf import settings\n\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.indexes.models import Index\n\n\nclass ModelBinding(models.Model):\n \"\"\"\n Reference to the index instances used for Energinet CO₂. Which index ID is\n used may differ between deployments; thus this is kept in the database ---\n as a model where only a single instance will be saved...\n \"\"\"\n index = models.ForeignKey(\n Index, on_delete=models.CASCADE, related_name='+')\n # forecast_index = models.ForeignKey(\n # Index, on_delete=models.CASCADE, related_name='+')\n\n\ndef setup_modelbinding(**kwargs):\n if ModelBinding.objects.exists():\n # already set up\n return\n unit = settings.ENERGINET_CO2_UNIT\n name = settings.ENERGINET_CO2_NAME\n timezone = pytz.timezone(settings.ENERGINET_CO2_TIMEZONE)\n binding = ModelBinding()\n binding.index = Index.objects.create(\n unit=unit,\n name_plain=name,\n data_format=Index.SPOT,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=timezone,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n customer=None)\n # binding.forecast_index = Index.objects.create(\n # unit=unit,\n # name=name,\n # data_format=Index.SPOT,\n # role=DataRoleField.CO2_QUOTIENT,\n # timezone=timezone,\n # utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n binding.save()\n\n\nif settings.ENERGINET_CO2_AUTO_SETUP:\n this_module = sys.modules[__name__]\n signals.post_syncdb.connect(setup_modelbinding, sender=this_module)\n" }, { "alpha_fraction": 0.6939643025398254, "alphanum_fraction": 0.6973646879196167, "avg_line_length": 36.147369384765625, "blob_id": "b68299b014c801138419139e6a4c6aa8a6fe6e1f", "content_id": "8415a86ec401fb77c923bf1a8b79ef44476c66be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3529, "license_type": "no_license", "max_line_length": 79, "num_lines": 95, "path": "/legacy/display_projects/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"\n\nimport datetime\nfrom datetime import timedelta\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.urlresolvers import reverse\n\nimport pytz\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.encryption.shell import Request\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import ChainLink\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.projects.models import BenchmarkProject\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import DATETIME_MIN\nfrom legacy.devices.models import PhysicalInput\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DisplayProjectsTest(TestCase):\n fixtures = [\"manage_indexes_test.json\"]\n\n def setUp(self):\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n\n self.customer = User.objects.get(\n id=self.client.session[\"_auth_user_id\"]).customer\n trackuser._set_customer(self.customer)\n\n self.request = Request('super', '123')\n\n self.electricity_index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"electricity index\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n self.electricity_index.save()\n\n self.measurement_point = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.tariff_list = [ChainLink(\n valid_from=DATETIME_MIN,\n data_series=self.electricity_index)]\n\n self.measurement_point.consumption = DataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_dependencies(self):\n NOW = datetime.datetime.now(pytz.utc)\n\n project = BenchmarkProject.objects.create(\n name_plain=\"Test project\",\n utility_type=PhysicalInput.ELECTRICITY,\n baseline_from_timestamp=NOW,\n baseline_to_timestamp=NOW + timedelta(days=1),\n result_from_timestamp=NOW + timedelta(days=2),\n result_to_timestamp=NOW + timedelta(days=3))\n\n project.baseline_measurement_points.add(self.measurement_point)\n project.result_measurement_points.add(self.measurement_point)\n\n # Verify that the MP which this project depends on cannot be deleted.\n response = self.client.get(\n reverse(\n 'manage_measurementpoints:measurement_point-update',\n args=(self.measurement_point.id, )))\n self.assertContains(response, 'data-reason')\n" }, { "alpha_fraction": 0.7443763017654419, "alphanum_fraction": 0.7464212775230408, "avg_line_length": 26.16666603088379, "blob_id": "d0aecd26af37090cd7332cdcf707a4a712ba783d", "content_id": "3af5cfa3c286efd187e201048e1ad49f847600e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 71, "num_lines": 18, "path": "/gridplatform/encryption/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .conf import settings\n\nfrom .middleware import _store\nfrom .testutils import NoEncryptionContext\n\n\ndef get_encryption_context():\n if settings.ENCRYPTION_TESTMODE:\n return NoEncryptionContext()\n return getattr(_store, settings.ENCRYPTION_CONTEXT_STORE_KEY, None)\n\n\ndef _set_ephemeral_private_key(key):\n setattr(_store, settings.ENCRYPTION_EPHEMERAL_STORE_KEY, key)\n" }, { "alpha_fraction": 0.5859788656234741, "alphanum_fraction": 0.5873016119003296, "avg_line_length": 25.526315689086914, "blob_id": "59d22a34185a010ecef1d6d98d812793830b52e4", "content_id": "1f61da7c224779eab5aa46fb250f3056e1c9f5a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1512, "license_type": "no_license", "max_line_length": 78, "num_lines": 57, "path": "/gridplatform/utils/breadcrumbs.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nfrom collections import namedtuple\n\n\n_Breadcrumb = namedtuple('Breadcrumb', ['title', 'url'])\n\n\nclass Breadcrumb(_Breadcrumb):\n \"\"\"\n A breadcrumb, consisting of a title and an URL, though the URL is optional\n in some instances.\n\n Instances of this class are immutable.\n\n :ivar title: The title.\n :ivar url: The URL.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, title, url=None):\n return _Breadcrumb.__new__(cls, title, url)\n\n def __add__(self, other):\n raise NotImplementedError(\n 'Adding to a breadcrumb object makes no sense.')\n\n\nclass Breadcrumbs(tuple):\n \"\"\"\n A tuple/sequence of :class:`.Breadcrumb`.\n\n Instances of this class are immutable.\n\n Only the last :class:`.Breadcrumb` may have a URL that is ``None``.\n \"\"\"\n __slots__ = ()\n\n def __new__(cls, elems=()):\n for elem in elems:\n assert isinstance(elem, Breadcrumb), \\\n 'Not a Breadcrumb: {}'.format(elem)\n for elem in elems[:-1]:\n assert elem.url is not None, \\\n 'Breadcrumb without URL: {}'.format(elem)\n return tuple.__new__(cls, elems)\n\n def __add__(self, other):\n \"\"\"\n Add a :class:`.Breadcrumb` to this; returning the result as a new\n :class:`.Breadcrumbs` object.\n \"\"\"\n assert isinstance(other, Breadcrumb)\n return Breadcrumbs(tuple(self) + (other,))\n" }, { "alpha_fraction": 0.6224328875541687, "alphanum_fraction": 0.622783899307251, "avg_line_length": 34.60625076293945, "blob_id": "f808f53ea46ce9ffc2d17f0b780fec40c33829e6", "content_id": "f7671e6f0e80e2ba1ff3c83366a4b7b255cbe97e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5697, "license_type": "no_license", "max_line_length": 79, "num_lines": 160, "path": "/gridplatform/encryption/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom functools import cmp_to_key\n\nfrom django.db.models.query import QuerySet\nfrom django.db import models\n\n\ndef cross_relation_getattr(obj, attr_path):\n \"\"\"\n Get attribute by Django ORM style dunder\n (``cross__relation__path__to_attribute``) path (but on python objects\n rather than on database relations). This is useful when the attributes are\n not part of the ORM.\n \"\"\"\n if attr_path == '':\n return obj\n paths = attr_path.split('__')\n try:\n for path in paths:\n obj = getattr(obj, path)\n return obj\n except AttributeError:\n return ''\n\n\nclass DecryptingOrderingMixin(object):\n \"\"\"\n Mixes :meth:`.DecryptingOrderingMixin.decrypting_order_by` and\n :meth:`.DecryptingOrderingMixin.iterator` into a :class:`.QuerySet` class,\n to enable ordering according to values on encrypted fields.\n \"\"\"\n _decrypt_ordering = []\n\n def decrypting_order_by(self, *field_names):\n \"\"\"\n Return a clone of this QuerySet ordering according to the given field\n names.\n\n :param field_names: The given field names. E.g. if ``name`` is an\n encrypted field, use ``'name_plain'``. Field names may be ORM\n style cross relation paths. See :func:`.cross_relation_getattr`.\n \"\"\"\n obj = self._clone()\n obj.query.clear_ordering(force_empty=False)\n obj._decrypt_ordering = field_names\n return obj\n\n def iterator(self):\n \"\"\"\n Iterate objects in decrypted order.\n \"\"\"\n objects = super(DecryptingOrderingMixin, self).iterator()\n if self._decrypt_ordering:\n return sorted(objects, key=cmp_to_key(self._decrypt_compare))\n return objects\n\n def _decrypt_compare(self, x, y):\n for field_name in self._decrypt_ordering:\n if field_name.startswith('-'):\n field_name = field_name[1:]\n return cmp(\n unicode(cross_relation_getattr(y, field_name)).lower(),\n unicode(cross_relation_getattr(x, field_name)).lower())\n else:\n return cmp(\n unicode(cross_relation_getattr(x, field_name)).lower(),\n unicode(cross_relation_getattr(y, field_name)).lower())\n\n def _clone(self, *args, **kwargs):\n c = super(DecryptingOrderingMixin, self)._clone(*args, **kwargs)\n c._decrypt_ordering = self._decrypt_ordering\n return c\n\n def __getitem__(self, k):\n if self._decrypt_ordering:\n return list(self)[k]\n else:\n return super(DecryptingOrderingMixin, self).__getitem__(k)\n\n\nclass DecryptingFilteringMixin(object):\n \"\"\"\n Mixes :meth:`.DecryptingFilteringMixin.decrypting_search` and\n :meth:`.DecryptingFilteringMixin.iterator` into a :class:`.QuerySet` class,\n to enable filtering according to plaintext values of encrypted fields.\n \"\"\"\n _decrypting_search_parameters = ()\n\n def decrypting_search(self, needle, field_names):\n \"\"\"\n Search for needle in given fields.\n\n :param needle: The needle to search for.\n :param field_names: The attribute names to search among. E.g. if\n ``name`` is an encrypted field, use ``'name_plain'``. Field names\n may be ORM style cross relation paths. See\n :func:`.cross_relation_getattr`.\n \"\"\"\n obj = self._clone()\n obj._decrypting_search_parameters = \\\n self._decrypting_search_parameters + \\\n ((unicode(needle).lower(), field_names),)\n return obj\n\n def iterator(self):\n objects = super(DecryptingFilteringMixin, self).iterator()\n if self._decrypting_search_parameters:\n for needle, field_names in self._decrypting_search_parameters:\n objects = [obj for obj in objects if self._satifies_search(\n obj, needle, field_names)]\n return objects\n\n @staticmethod\n def _satifies_search(obj, needle, field_names):\n for field_name in field_names:\n if needle in unicode(\n cross_relation_getattr(obj, field_name)).lower():\n return True\n return False\n\n def _clone(self, *args, **kwargs):\n c = super(DecryptingFilteringMixin, self)._clone(*args, **kwargs)\n c._decrypting_search_parameters = self._decrypting_search_parameters\n return c\n\n def __getitem__(self, k):\n if self._decrypting_search_parameters:\n return list(self)[k]\n else:\n return super(DecryptingFilteringMixin, self).__getitem__(k)\n\n\nclass DecryptingQuerySet(\n DecryptingOrderingMixin, DecryptingFilteringMixin, QuerySet):\n \"\"\"\n A :class:`.QuerySet` that has both :class:`.DecryptingOrderingMixin` and\n :class:`.DecryptingFilteringMixin` mixed into it.\n \"\"\"\n pass\n\n\nclass DecryptingManager(models.Manager):\n \"\"\"\n A :class:`django.db.models.Manager` specialization that uses\n :class:`.DecryptingQuerySet` for its querysets, and provides manager level\n versions of :meth:`.DecryptingOrderingMixin.decrypting_order_by` and\n :meth:`.DecryptingFilteringMixin.decrypting_search`.\n \"\"\"\n def get_queryset(self):\n qs = super(DecryptingManager, self).get_queryset()\n return qs._clone(klass=DecryptingQuerySet)\n\n def decrypting_search(self, *args, **kwargs):\n return self.get_queryset().decrypting_search(*args, **kwargs)\n\n def decrypting_order_by(self, *args, **kwargs):\n return self.get_queryset().decrypting_order_by(*args, **kwargs)\n" }, { "alpha_fraction": 0.7173699736595154, "alphanum_fraction": 0.7350343465805054, "avg_line_length": 32.96666717529297, "blob_id": "63eec188815123f536b18203b06a3c6291ecdded", "content_id": "8202cb9c1d7fa9eb954877d7d1ed7528e94e0b84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1019, "license_type": "no_license", "max_line_length": 98, "num_lines": 30, "path": "/doc/csgruppen/tarif_setup_script.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\n Don't run directly... C/P into ./manage.py shell. ONLY ONCE, AND ONLY AFTER NORD POOL FETCH!!!\n\"\"\"\nimport datetime\n\nfrom pytz import timezone\n\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom gridplatform.tariffs.models import SpotPricePeriod\nfrom gridplatform.global_datasources.models import GlobalDataSource\n\ndk1 = GlobalDataSource.objects.get(\n name=\"dk1\", app_label=\"nordpool\", codename=\"nordpool_dk1\",\n country=\"DK\", unit=\"currency_dkk*gigawatt^-1*hour^-1\")\ndk2 = GlobalDataSource.objects.get(\n name=\"dk2\", app_label=\"nordpool\", codename=\"nordpool_dk2\",\n country=\"DK\", unit=\"currency_dkk*gigawatt^-1*hour^-1\")\n\ntariff = EnergyTariff.objects.get(pk=1)\n\nperiod = SpotPricePeriod.objects.create(\n datasequence=tariff,\n spotprice=dk1,\n coefficient=1,\n unit_for_constant_and_ceiling=\"currency_dkk*kilowatt^-1*hour^-1\",\n constant=0,\n from_timestamp=datetime.datetime.now().replace(tzinfo=timezone('Europe/Copenhagen')),\n subscription_fee=0,\n subscription_period=3\n)\n" }, { "alpha_fraction": 0.5862208008766174, "alphanum_fraction": 0.5866236686706543, "avg_line_length": 31.657894134521484, "blob_id": "15cf403efab2611c96564f3a2d595c7ed221fe87", "content_id": "56c057c7abcdea618f57fb74f70a2c1e67b99153", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2482, "license_type": "no_license", "max_line_length": 78, "num_lines": 76, "path": "/gridplatform/utils/generic_views/localized.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport warnings\n\nfrom django.forms import models as model_forms\n\n\nclass LocalizedModelFormMixin(object):\n \"\"\"\n Mixin to inject ``localized_fields`` into parameters to\n ``modelform_factory()`` for Django create/update views.\n \"\"\"\n localized_fields = '__all__'\n\n def get_form_class(self):\n \"\"\"\n Copied from\n :meth:`django.views.generic.edit.ModelFormMixin.get_form_class()`;\n modified to provide ``localized_fields`` to\n ``modelform_factory()``\n \"\"\"\n if self.form_class:\n return self.form_class\n else:\n if self.model is not None:\n model = self.model\n elif hasattr(self, 'object') and self.object is not None:\n model = self.object.__class__\n else:\n model = self.get_queryset().model\n if self.fields is None:\n warnings.warn(\n \"Using ModelFormMixin (base class of %s) without \"\n \"the 'fields' attribute is deprecated.\" %\n self.__class__.__name__,\n PendingDeprecationWarning)\n return model_forms.modelform_factory(\n model,\n fields=self.fields,\n localized_fields=self.localized_fields)\n\n\nclass LocalizedModelFormSetMixin(object):\n \"\"\"\n Mixin to inject ``localized_fields`` into parameters to\n ``modelformset_factory()`` for :mod:``extra_views`` formset views.\n \"\"\"\n localized_fields = '__all__'\n\n def get_factory_kwargs(self):\n \"\"\"\n inject ``localized_fields`` into kwargs\n \"\"\"\n kwargs = super(LocalizedModelFormSetMixin, self).get_factory_kwargs()\n if 'localized_fields' not in kwargs:\n kwargs['localized_fields'] = self.localized_fields\n return kwargs\n\n\nclass LocalizedInlineFormSetMixin(object):\n \"\"\"\n Mixin to inject ``localized_fields`` into parameters to\n ``inlineformset_factory()`` for :mod:`extra_views` inline views.\n \"\"\"\n localized_fields = '__all__'\n\n def get_factory_kwargs(self):\n \"\"\"\n inject ``localized_fields`` into kwargs\n \"\"\"\n kwargs = super(LocalizedInlineFormSetMixin, self).get_factory_kwargs()\n if 'localized_fields' not in kwargs:\n kwargs['localized_fields'] = self.localized_fields\n return kwargs\n" }, { "alpha_fraction": 0.5928143858909607, "alphanum_fraction": 0.593532919883728, "avg_line_length": 39.53398132324219, "blob_id": "11b05526a7becf134d18c74410f4c915b8a7587e", "content_id": "1eb4c271a651ba21c85e1136d0d0e7824f9c0fab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8350, "license_type": "no_license", "max_line_length": 79, "num_lines": 206, "path": "/legacy/measurementpoints/models/integral.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nimport itertools\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.iter_ext import count_extended\n\nfrom .dataseries import DataSeries\nfrom .dataseries import UndefinedSamples\nfrom .mixins import CacheOptimizedCalculateDevelopmentMixin\n\n\nclass PiecewiseConstantIntegral(CacheOptimizedCalculateDevelopmentMixin,\n DataSeries):\n \"\"\"\n A C{PiecewiseConstantIntegral} is a L{DataSeries} that represent the\n definite integral of a piecewise constant L{DataSeries}, C{data}.\n \"\"\"\n data = models.ForeignKey(\n DataSeries,\n related_name='piecewise_constant_integrals_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('piecewise constant integral')\n verbose_name_plural = _('piecewise constant integrals')\n app_label = 'measurementpoints'\n\n def save(self, *args, **kwargs):\n assert PhysicalQuantity.compatible_units(\n self.unit, 'second*' + self.data.unit)\n assert self.data.role in self.PIECEWISE_CONSTANT_RATE_ROLES\n super(PiecewiseConstantIntegral, self).save(*args, **kwargs)\n\n def clean_fields(self, exclude=None):\n def should_clean_field(field_name):\n return not (exclude and field_name in exclude)\n\n if self.data:\n if should_clean_field('utility_type'):\n self.utility_type = self.data.utility_type\n if should_clean_field('customer'):\n self.customer_id = self.data.customer_id\n if should_clean_field('unit'):\n self.unit = self.data.unit + '*second'\n\n super(PiecewiseConstantIntegral, self).clean_fields(exclude=exclude)\n\n def _integrate_sample(\n self, sample, from_timestamp=None, to_timestamp=None):\n if from_timestamp is None or from_timestamp < sample.from_timestamp:\n from_timestamp = sample.from_timestamp\n if to_timestamp is None or to_timestamp > sample.to_timestamp:\n to_timestamp = sample.to_timestamp\n return (\n sample.physical_quantity *\n PhysicalQuantity(\n (to_timestamp - from_timestamp).total_seconds(),\n 'second'))\n\n def _calculate_development_fallback(self, from_timestamp, to_timestamp):\n \"\"\"\n Override of L{CacheOptimizedCalculateDevelopmentMixin.\n _calculate_development_fallback()}, because parent class'\n C{calculate_development()} does not do the right thing.\n \"\"\"\n data_samples = list(\n self.data.subclass_instance.get_samples(\n from_timestamp, to_timestamp))\n\n if not data_samples:\n return None\n\n integral_quantity = reduce(\n operator.add,\n (self._integrate_sample(sample) for sample in data_samples))\n\n integral_cachable = all(\n sample.cachable for sample in data_samples)\n\n integral_extrapolated = any(\n sample.extrapolated for sample in data_samples)\n\n return self.create_range_sample(\n from_timestamp,\n to_timestamp,\n physical_quantity=integral_quantity,\n uncachable=not integral_cachable,\n extrapolated=integral_extrapolated)\n\n def depends_on(self):\n return [self.data.subclass_instance] + \\\n self.data.subclass_instance.depends_on()\n\n def _get_samples(self, from_timestamp, to_timestamp):\n raise UndefinedSamples('This is a definite integral')\n\n def get_recursive_condense_resolution(self, resolution):\n # Computations not assumed to be harder than loading hours cache.\n # Therefore recursion is stopped at days resolution.\n if condense.is_coarser_resolution(resolution, condense.DAYS):\n return condense.next_resolution(resolution)\n else:\n return None\n\n def _condense_accumulation_data_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Override of C{DataSeries._condense_accumulation_data_samples()}\n \"\"\"\n timezone = from_timestamp.tzinfo\n\n def extract_frame_start(sample):\n return condense.floor(\n sample.from_timestamp, sample_resolution, timezone)\n\n def frame_timestamps(from_timestamp, to_timestamp):\n return pairwise(\n itertools.takewhile(\n lambda t: t <= to_timestamp,\n count_extended(from_timestamp, sample_resolution)))\n\n def chop_samples(samples):\n for s in samples:\n first_frame_start = condense.floor(\n s.from_timestamp, sample_resolution, from_timestamp.tzinfo)\n last_frame_end = condense.ceil(\n s.to_timestamp, sample_resolution, from_timestamp.tzinfo)\n\n frames = frame_timestamps(first_frame_start, last_frame_end)\n\n for frame_start, frame_end in frames:\n chopped_sample_start = max(s.from_timestamp, frame_start)\n chopped_sample_end = min(s.to_timestamp, frame_end)\n chopped_sample = s._replace(\n from_timestamp=chopped_sample_start,\n to_timestamp=chopped_sample_end)\n yield chopped_sample\n\n data_samples = list(chop_samples(\n self.data.subclass_instance.get_samples(\n from_timestamp, to_timestamp)))\n\n if data_samples:\n\n domain_start = condense.floor(\n data_samples[0].from_timestamp, sample_resolution,\n from_timestamp.tzinfo)\n domain_end = condense.ceil(\n data_samples[-1].to_timestamp, sample_resolution,\n from_timestamp.tzinfo)\n\n for frame_start, frame_end in frame_timestamps(from_timestamp,\n domain_start):\n yield self.create_range_sample(\n frame_start, frame_end, PhysicalQuantity(0, self.unit),\n uncachable=True, extrapolated=True)\n\n # assumes each data sample is contained in a signle frame.\n frames = itertools.groupby(data_samples, extract_frame_start)\n for frame_start, frame_samples in frames:\n frame_samples = list(frame_samples)\n assert frame_samples\n frame_quantity = reduce(\n operator.add,\n (\n self._integrate_sample(\n sample, frame_start,\n frame_start + sample_resolution) for\n sample in frame_samples))\n\n frame_cachable = all(\n sample.cachable for sample in frame_samples)\n frame_extrapolated = any(\n sample.extrapolated for sample in frame_samples)\n\n assert from_timestamp <= frame_start\n assert frame_start + sample_resolution <= to_timestamp\n frame_sample = self.create_range_sample(\n frame_start,\n frame_start + sample_resolution,\n physical_quantity=frame_quantity,\n uncachable=not frame_cachable,\n extrapolated=frame_extrapolated)\n yield frame_sample\n\n for frame_start, frame_end in frame_timestamps(domain_end,\n to_timestamp):\n yield self.create_range_sample(\n frame_start, frame_end, PhysicalQuantity(0, self.unit),\n uncachable=True, extrapolated=True)\n\n else:\n assert not data_samples\n for frame_start, frame_end in frame_timestamps(\n from_timestamp, to_timestamp):\n yield self.create_range_sample(\n frame_start, frame_end, PhysicalQuantity(0, self.unit),\n uncachable=True, extrapolated=True)\n" }, { "alpha_fraction": 0.5853658318519592, "alphanum_fraction": 0.5880758762359619, "avg_line_length": 22.0625, "blob_id": "f7f7dbbcd3acc2f74ebff9c1b9fac4555d781adf", "content_id": "887890d78f628565054b6ab4c9deb50a28255abd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/gridplatform/reports/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'gridplatform.reports.views',\n url(r'^status/$',\n 'status',\n name='reports-status'),\n url(r'^(?P<id>\\d+)/(?P<title>.*)$',\n 'serve',\n name='reports-serve'),\n)\n" }, { "alpha_fraction": 0.49565935134887695, "alphanum_fraction": 0.5667631030082703, "avg_line_length": 34.185455322265625, "blob_id": "fed450cc32a41397f418e7699c0ef5ee8f1b6c90", "content_id": "7b2c237499674de922f130ebc0feb3bd742f5cec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9676, "license_type": "no_license", "max_line_length": 79, "num_lines": 275, "path": "/gridagentserver-protocol/gridagentserver_protocol/server_messages_test.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import unittest\nimport ctypes\nimport datetime\nfrom StringIO import StringIO\nimport random\n\nfrom datatypes import Meter, RuleSet, Rule, Price\nimport server_messages\nimport messages\n\nfrom server_messages import (\n # ConfigGp,\n ConfigGaRulesets,\n ConfigGaTime,\n ConfigGaPrices,\n CommandGaPollMeasurements,\n CommandGaPropagateTime,\n CommandGpSwitchControl,\n CommandGpSwitchRelay,\n ConfigGaSoftware,\n ConfigGpSoftware,\n)\n\n\ndef signed_64(val):\n return ctypes.c_longlong(val).value\n\n\ndef signed_32(val):\n return ctypes.c_long(val).value\n\n\nclass TestSerializingVersion1(unittest.TestCase):\n def test_config_gp(self):\n pass\n\n def test_config_ga_rulesets(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x38, # length\n 0x00, 0x00, # padding\n 2, # type\n 0x00, # flags\n 0x00, 0x00, 0x00, 0x02, # count\n # entries\n 0x00, 0x00, 0x00, 0x01, # override timeout\n 0x00, 0x00, # rule count\n 0x00, 0x00, # endpoint count\n 0x00, 0x00, 0x00, 0x0F, # override timeout\n 0x00, 0x01, # rule count\n 0x00, 0x02, # endpoint count\n # rules\n 0x00, 0x00, 0x00, # padding\n 0x01, # action (turn on)\n 0x00, 0x00, 0x10, 0x00, # time begin\n 0x00, 0x00, 0x20, 0x00, # time end\n # endpoints\n 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, # id\n 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, 0x12, 0x34, # id\n ]))\n actual = server_messages.ConfigGaRulesets([\n RuleSet(1, [], []),\n RuleSet(\n 15,\n [Rule(True, 4096, 8192)],\n [\n Meter(0, signed_64(0xABCDABCDABCDABCD)),\n Meter(0, signed_64(0x1234123412341234)),\n ]\n ),\n ]).pack(1)\n self.assertEqual(actual, expected)\n\n def test_config_ga_time(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x0C, # length\n 0x00, 0x00, # padding\n 3, # type\n 0x00, # flags\n 0x00, 0x00, 0x69, 0x78, # timestamp\n ]))\n actual = server_messages.ConfigGaTime(\n datetime.datetime(2000, 1, 1, 7, 30)\n ).pack(1)\n self.assertEqual(actual, expected)\n\n def test_config_ga_prices(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x24, # length\n 0x00, 0x00, # padding\n 4, # type\n 0x00, # flags\n 0x00, 0x00, # padding\n 0x00, 0x02, # count\n 0x00, 0x00, 0x00, 0x00, # start time\n 0x00, 0x00, 0x01, 0x00, # end time\n 0x12, 0x12, 0x21, 0x21, # price\n 0x00, 0x00, 0x01, 0x00, # start time\n 0x00, 0x00, 0x02, 0x00, # end time\n 0x32, 0x32, 0x23, 0x23, # price\n ]))\n actual = server_messages.ConfigGaPrices([\n Price(\n datetime.datetime(2000, 1, 1, 0, 0, 0),\n datetime.datetime(2000, 1, 1, 0, 4, 16),\n signed_32(0x12122121)\n ),\n Price(\n datetime.datetime(2000, 1, 1, 0, 4, 16),\n datetime.datetime(2000, 1, 1, 0, 8, 32),\n signed_32(0x32322323)\n ),\n ]).pack(1)\n self.assertEqual(len(actual), len(expected))\n self.assertEqual(actual, expected)\n\n def test_command_ga_poll_measurements(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x08, # length\n 0x00, 0x00, # padding\n 7, # type\n 0x00, # flags\n ]))\n actual = server_messages.CommandGaPollMeasurements().pack(1)\n self.assertEqual(actual, expected)\n\n def test_command_ga_propagate_time(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x08, # length\n 0x00, 0x00, # padding\n 8, # type\n 0x00, # flags\n ]))\n actual = server_messages.CommandGaPropagateTime().pack(1)\n self.assertEqual(actual, expected)\n\n def test_command_gp_switch_control(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x10, # length\n 0x00, 0x00, # padding\n 9, # type\n 0x01, # flags (manual control)\n 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, # id\n ]))\n actual = server_messages.CommandGpSwitchControl(\n Meter(0, signed_64(0x1234567812345678)),\n True\n ).pack(1)\n self.assertEqual(actual, expected)\n\n def test_command_gp_switch_relay(self):\n expected = str(bytearray([\n 0x00, 0x00, 0x00, 0x10, # length\n 0x00, 0x00, # padding\n 10, # type\n 0x01, # flags (relay on)\n 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, # id\n ]))\n actual = server_messages.CommandGpSwitchRelay(\n Meter(0, signed_64(0x1234567812345678)),\n True\n ).pack(1)\n self.assertEqual(actual, expected)\n\n\n# messages send timestamp as second; i.e. output will *not* match the\n# microsecond of input if we use timestamps with microseconds...\ndef utcsecond():\n return datetime.datetime.utcnow().replace(microsecond=0)\n\n\nclass TestRoundtripVersion2(unittest.TestCase):\n def test_config_gp(self):\n pass\n\n def test_config_ga_rulesets(self):\n rulesets = [RuleSet(0, [Rule(True, 0, 604800)], [Meter(0, 0xAABBCC)]),\n RuleSet(15, [Rule(True, 5, 15), Rule(False, 0, 604800)],\n [Meter(1, 0xABC), Meter(2, 0xDEF)])]\n bytes = StringIO()\n messages.write(bytes, ConfigGaRulesets(rulesets), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.rulesets, rulesets)\n self.assertEqual(message.__class__, ConfigGaRulesets)\n\n def test_config_ga_time(self):\n timestamp = utcsecond()\n bytes = StringIO()\n messages.write(bytes, ConfigGaTime(timestamp), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.timestamp, timestamp)\n self.assertEqual(message.__class__, ConfigGaTime)\n\n def test_config_ga_prices(self):\n now = utcsecond()\n prices = [Price(now,\n now + datetime.timedelta(hours=1),\n 100),\n Price(now + datetime.timedelta(hours=1),\n now + datetime.timedelta(hours=2),\n 200)]\n bytes = StringIO()\n messages.write(bytes, ConfigGaPrices(prices), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.prices, prices)\n self.assertEqual(message.__class__, ConfigGaPrices)\n\n def test_command_ga_poll_meauserements(self):\n bytes = StringIO()\n messages.write(bytes, CommandGaPollMeasurements(), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.__class__, CommandGaPollMeasurements)\n\n def test_command_ga_propagate_time(self):\n bytes = StringIO()\n messages.write(bytes, CommandGaPropagateTime(), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.__class__, CommandGaPropagateTime)\n\n def test_command_gp_switch_control(self):\n meter = Meter(1, 0xABCD)\n control_manual = bool(random.randint(0, 1))\n bytes = StringIO()\n messages.write(bytes, CommandGpSwitchControl(meter, control_manual), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.meter, meter)\n self.assertEqual(message.control_manual, control_manual)\n self.assertEqual(message.__class__, CommandGpSwitchControl)\n\n def test_command_gp_switch_relay(self):\n meter = Meter(1, 0xABCD)\n relay_on = bool(random.randint(0, 1))\n bytes = StringIO()\n messages.write(bytes, CommandGpSwitchRelay(meter, relay_on), 2)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.meter, meter)\n self.assertEqual(message.relay_on, relay_on)\n self.assertEqual(message.__class__, CommandGpSwitchRelay)\n\n def test_config_ga_software(self):\n sw_version = (0xaa, 0xbb, 0xcc, 'debug')\n hw_model = 1\n target_hw_version = (0x11, 0x22, 0x33, '')\n image = 'abc' * 100\n bytes = StringIO()\n messages.write(bytes, ConfigGaSoftware(\n sw_version, hw_model, target_hw_version, image), 3)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.sw_version, sw_version)\n self.assertEqual(message.target_hw_version, target_hw_version)\n self.assertEqual(message.image, image)\n\n def test_config_ga_gp_software(self):\n sw_version = (0xaa, 0xbb, 0xcc, 'test')\n hw_model = 3\n target_hw_version = (0x11, 0x22, 0x33, '')\n image = 'abc' * 100\n meters = [Meter(1, 0xABCD)]\n bytes = StringIO()\n messages.write(bytes, ConfigGpSoftware(\n sw_version, hw_model, target_hw_version, image, meters), 3)\n bytes.seek(0)\n message = messages.parse(bytes, 2)\n self.assertEqual(message.sw_version, sw_version)\n self.assertEqual(message.target_hw_version, target_hw_version)\n self.assertEqual(message.hw_model, hw_model)\n self.assertEqual(message.image, image)\n self.assertEqual(message.meters, meters)\n" }, { "alpha_fraction": 0.4811801612377167, "alphanum_fraction": 0.48490557074546814, "avg_line_length": 40.77638626098633, "blob_id": "8c5233b1f1dfb983eeaa3170acdb133d1d377da0", "content_id": "06eb2620955ea996b57744591aa2b6b384e43105", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23353, "license_type": "no_license", "max_line_length": 79, "num_lines": 559, "path": "/legacy/measurementpoints/models/graph.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nimport datetime\n\nfrom django import template\nfrom django.template.defaultfilters import floatformat\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import models\n\nfrom gridplatform.utils import unix_timestamp\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.condense import get_date_formatter\nfrom gridplatform.utils.utilitytypes import UTILITY_TYPE_TO_COLOR\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser.managers import CustomerBoundManager\n\nfrom .collections import Collection\nfrom ..fields import DataRoleField\n\n\nclass AbstractGraph(object):\n \"\"\"\n A C{Graph} visualizes a set of C{DataSeries}.\n\n Non-abstract subclasses are required to implement L{_get_data_series()}, to\n define which DataSeries to visualize.\n \"\"\"\n\n BAR_GRAPH = 0\n PIECEWISE_CONSTANT_GRAPH = 1\n LINEAR_INTERPOLATION_GRAPH = 2\n\n PROGRESS_TOTAL = 20\n\n def _get_data_series(self):\n \"\"\"\n Get the L{DataSeries} visualized in this C{Graph}.\n\n @return: An iterable of L{DataSeries} subclass instances.\n \"\"\"\n raise NotImplementedError(\n 'Method not implemented for %r.' % self.__class__)\n\n def _get_float_format_decimals(self):\n \"\"\"\n Specifies string argument given to the Django template filter\n C{floatformat}, inside this instance. The intend is to allow for\n subclasses to decide how many decimals are relevant for them, because\n they have a change to know better.\n \"\"\"\n return '-3'\n\n def _get_caption_text(self, data_samples, converter, is_rate,\n is_condensed, avg_value=None):\n \"\"\"\n Renders caption text. Intended use is inclusion in JSON responses\n with L{get_graph_data()}.\n\n @param data_samples: List of data samples.\n\n @param converter: A L{UnitConverter} for converting\n C{sample.physical_quantity} for each sample in C{data_samples}.\n\n @param is_rate: True if data_samples are to be interpreted as a rate\n for this graph; False, if data_samples are to\n be interpreted as accumulation.\n\n @param is_condensed: True of false whether or not the samples\n are condensed. If samples are condensed, the average text will not be\n applied to the caption text.\n \"\"\"\n if is_rate or avg_value is not None:\n min_value = None\n max_value = None\n total_value = None\n\n for sample in data_samples:\n if total_value is None:\n total_value = sample.physical_quantity\n else:\n total_value += sample.physical_quantity\n\n if min_value is None or sample.physical_quantity < min_value:\n min_value = sample.physical_quantity\n\n if max_value is None or sample.physical_quantity > max_value:\n max_value = sample.physical_quantity\n\n if avg_value is None and data_samples and total_value is not None:\n avg_value = total_value / len(data_samples)\n\n if min_value is not None and max_value is not None \\\n and avg_value is not None:\n if is_condensed:\n caption = _('Min: {{ min_value }} {{ unit }} | '\n 'Max: {{ max_value }} {{ unit }}')\n subcontext = template.Context({\n 'min_value': converter.extract_value(min_value),\n 'max_value': converter.extract_value(max_value),\n 'unit': converter.get_display_unit()})\n else:\n caption = _('Avg: {{ avg_value }} {{ unit }} | '\n 'Min: {{ min_value }} {{ unit }} | '\n 'Max: {{ max_value }} {{ unit }}')\n subcontext = template.Context({\n 'avg_value': converter.extract_value(avg_value),\n 'min_value': converter.extract_value(min_value),\n 'max_value': converter.extract_value(max_value),\n 'unit': converter.get_display_unit()})\n else:\n subcontext = template.Context({})\n caption = _('No values in this range.')\n else:\n if data_samples:\n total = converter.extract_value(\n reduce(\n operator.add,\n (sample.physical_quantity for sample in data_samples)))\n caption = _('Total: {{ total }} {{ unit }}')\n else:\n caption = _('No values in this range.')\n total = None\n subcontext = template.Context({\n 'total': total,\n 'unit': converter.get_display_unit()})\n\n # Find out if samples are extrapolated and add a notice\n # to caption string about this.\n if data_samples:\n if all(not s.extrapolated for s in data_samples[0:-1]) and \\\n data_samples[-1].extrapolated:\n warning = _('Rightmost sample is incomplete')\n caption = _('{caption} ({warning})').format(caption=caption,\n warning=warning)\n elif (data_samples[0].extrapolated or\n data_samples[-1].extrapolated):\n warning = _('Graph is based on incomplete data')\n caption = _('{caption} ({warning})').format(caption=caption,\n warning=warning)\n\n # NOTE: including use of floatformat filter inside caption might be a\n # better approach...\n for elem in ['avg_value', 'min_value', 'max_value', 'total']:\n if elem in subcontext:\n subcontext[elem] = floatformat(\n subcontext[elem], self._get_float_format_decimals())\n return template.Template(unicode(caption)).render(subcontext)\n\n def get_graph_data(self, num_ticks, from_timestamp,\n num_samples=None, sample_resolution=None,\n data_series_set=None, to_timestamp=None,\n weekends_are_special=True):\n \"\"\"\n Returns a dictionary, suitable for rendering by Javascript\n flotr2. The dictionary will be on the form::\n\n {\"data\": data, \"options\": options}\n\n where C{data} corresponds to the C{data} argument to\n C{Flotr.draw(container, data, options)} in flotr2, and\n C{options} correspond to the C{options} argument.\n\n @param num_ticks: The number of ticks (labels) to be shown.\n This must be an integer\n\n @param from_timestamp: The earliest time used in the returned\n data.\n\n @param num_samples: The number of sample points in the\n returned data. There will be data for each L{DataSeries} at\n each sample point.\n\n @param sample_resolution: The symbolic timespan. If not given, raw\n data will be used. In that case to_timestamp must be set, and\n num_samples will be ignored. This is only supported for non-bar\n graphs.\n\n @param to_timestamp: Only used when C{sample_resolution is None}, in\n which case it must be set.\n\n @keyword weekends_are_special: If C{True}, samples contained within\n weekends are colored specially. Default is C{True}.\n \"\"\"\n assert from_timestamp.tzinfo is not None, \\\n 'timezone-aware from_timestamp required'\n assert isinstance(num_ticks, int)\n if sample_resolution:\n from_timestamp = condense.floor(\n from_timestamp, sample_resolution, from_timestamp.tzinfo)\n to_timestamp = from_timestamp + (num_samples * sample_resolution)\n\n assert num_samples >= num_ticks\n ticks_range = [\n # RelativeTimeDelta does not support division, so we need to do\n # the operations so that division is done on datetime.timedelta\n # objects instead.\n from_timestamp + sample_resolution * x +\n ((from_timestamp + sample_resolution * (x + 1))\n - (from_timestamp + sample_resolution * x)) / 2 for\n x in range(num_samples)\n if x % (num_samples / num_ticks) == 0 and\n x < num_samples - (num_samples % num_ticks)]\n assert len(ticks_range) == num_ticks\n else:\n assert to_timestamp, \\\n \"to_timestamp required when sample_resolution is None\"\n ticks_range = [\n from_timestamp + i * (to_timestamp - from_timestamp) /\n num_ticks for i in range(num_ticks)]\n\n if not data_series_set:\n data_series_set = list(self._get_data_series())\n\n total_seconds = (to_timestamp - from_timestamp).total_seconds()\n self.__progress = 0\n self.__tick_progress()\n\n self.__when_to_report_progress_next = (\n self.__progress / float(self.PROGRESS_TOTAL)) * \\\n len(data_series_set) * total_seconds\n\n all_data_samples = []\n\n data = []\n # @bug: get rid of this variable it is never set anyway.\n track_labels = {}\n\n formatter = get_date_formatter(\n from_timestamp, to_timestamp, resolution=sample_resolution)\n ticks = [(unix_timestamp(t), formatter(t)) for\n t in ticks_range]\n caption = ''\n\n # reasonable y-axis scale for data series that sample y(x)=0\n maximum = 0.01\n minimum = -0.001\n\n tz = from_timestamp.tzinfo\n\n def point_label(value, timestamp):\n if value is not None:\n ts = tz.normalize(timestamp.astimezone(tz))\n return (floatformat(value, 3),\n ts.strftime('%Y-%m-%d'),\n ts.strftime('%H:%M:%S'))\n\n def range_label(value, from_timestamp, to_timestamp):\n if value is not None:\n from_ts = tz.normalize(from_timestamp.astimezone(tz))\n to_ts = tz.normalize(to_timestamp.astimezone(tz))\n days = int((to_ts - from_ts).total_seconds() /\n datetime.timedelta(days=1).total_seconds())\n date = from_ts.strftime('%Y-%m-%d')\n time_range = '%s - %s' % (from_ts.strftime('%H:%M'),\n to_ts.strftime('%H:%M'))\n\n if days >= 1:\n time_range = ''\n if days > 27:\n date = ''\n time_range = '%s - %s' % (from_ts.strftime('%Y-%m-%d'),\n to_ts.strftime('%Y-%m-%d'))\n\n return (floatformat(value, 3),\n date,\n time_range)\n\n def report_progress(sample):\n progress_seconds = ds_no * total_seconds + (\n sample.from_timestamp - from_timestamp).total_seconds()\n if progress_seconds > self.__when_to_report_progress_next:\n self.__tick_progress()\n self.__when_to_report_progress_next = (\n self.__progress / float(self.PROGRESS_TOTAL)) * \\\n len(data_series_set) * total_seconds\n\n from .dataseries import UndefinedSamples\n from .dataseries import DataSeries\n for ds_no, data_series in enumerate(data_series_set):\n preferred_unit_converter = \\\n data_series.get_preferred_unit_converter()\n current_data = []\n current_weekend_data = []\n\n try:\n data_samples = []\n if sample_resolution:\n for s in data_series.get_condensed_samples(\n from_timestamp, sample_resolution,\n to_timestamp=to_timestamp):\n report_progress(s)\n data_samples.append(s)\n\n else:\n for s in data_series.get_samples(\n from_timestamp, to_timestamp):\n report_progress(s)\n data_samples.append(s)\n\n all_data_samples.extend(data_samples)\n\n if data_series.get_underlying_function() == \\\n DataSeries.CONTINUOUS_RATE:\n for sample in data_samples:\n converted_value = float(\n preferred_unit_converter.extract_value(\n sample.physical_quantity))\n current_data.append([unix_timestamp(sample.timestamp),\n converted_value,\n point_label(converted_value,\n sample.timestamp)])\n if converted_value is not None:\n maximum = max(maximum, converted_value)\n minimum = min(minimum, converted_value)\n\n graph_data = {\n \"data\": current_data,\n \"trackLabels\": track_labels,\n \"lines\": {\n \"show\": True,\n }\n }\n data.append(graph_data)\n\n else:\n for data_sample in data_samples:\n converted_value = float(\n preferred_unit_converter.extract_value(\n data_sample.physical_quantity))\n if data_series.get_underlying_function() == \\\n DataSeries.PIECEWISE_CONSTANT_RATE:\n current_data.extend(\n [[unix_timestamp(data_sample.from_timestamp),\n converted_value,\n range_label(converted_value,\n data_sample.from_timestamp,\n data_sample.to_timestamp)],\n [unix_timestamp(data_sample.to_timestamp),\n converted_value,\n range_label(converted_value,\n data_sample.from_timestamp,\n data_sample.to_timestamp)]])\n\n else:\n assert data_series.get_underlying_function() in (\n DataSeries.CONTINUOUS_ACCUMULATION,\n DataSeries.PIECEWISE_CONSTANT_ACCUMULATION,\n DataSeries.INTERVAL_FUNCTION)\n data_tuple = [\n # put the sample at center.\n unix_timestamp(\n data_sample.from_timestamp +\n (\n data_sample.to_timestamp -\n data_sample.from_timestamp) / 2),\n converted_value,\n # don't give label data for extrapolated values\n # that almost equal 0. These represent \"No\n # data\"\n range_label(converted_value,\n data_sample.from_timestamp,\n data_sample.to_timestamp) if\n float(\"%.7f\" % converted_value) or\n not data_sample.extrapolated else None]\n\n if weekends_are_special and \\\n data_sample.from_timestamp.astimezone(\n get_customer().timezone\n ).weekday() in [5, 6] \\\n and (sample_resolution.days == 1\n or sample_resolution.hours == 1):\n # bars contained in weekend.\n current_weekend_data.append(data_tuple)\n else:\n current_data.append(data_tuple)\n\n if converted_value is not None:\n maximum = max(maximum, converted_value)\n minimum = min(minimum, converted_value)\n\n if data_series.get_underlying_function() == \\\n DataSeries.PIECEWISE_CONSTANT_RATE:\n graph_data = {\n \"data\": current_data,\n \"trackLabels\": track_labels,\n \"lines\": {\n \"show\": True,\n }\n }\n else:\n graph_data = {\n \"data\": current_data,\n \"trackLabels\": track_labels,\n \"bars\": {\n \"show\": True,\n \"barWidth\": 0.8 *\n (\n to_timestamp -\n from_timestamp).total_seconds() /\n num_samples,\n 'centered': True,\n }\n }\n\n data.append(graph_data)\n\n if len(current_weekend_data) > 0:\n graph_weekend_data = {\n \"data\": current_weekend_data,\n \"trackLabels\": track_labels,\n \"bars\": {\n \"show\": True,\n \"barWidth\": 0.8 *\n (\n to_timestamp -\n from_timestamp).total_seconds() /\n num_samples,\n 'centered': True,\n }\n }\n data.append(graph_weekend_data)\n\n except UndefinedSamples, e:\n caption = unicode(e)\n\n if hasattr(data_series, 'calculate_enpi'):\n enpi_sample = data_series.calculate_enpi(\n from_timestamp, to_timestamp)\n extrapolated = any(s.extrapolated for s in all_data_samples)\n if enpi_sample is not None and not extrapolated:\n caption = _('Avg: {average} {unit}.').format(\n average=floatformat(\n preferred_unit_converter.extract_value(\n enpi_sample.physical_quantity),\n self._get_float_format_decimals()),\n unit=preferred_unit_converter.get_display_unit())\n elif enpi_sample is not None and extrapolated:\n caption = _(\n 'Avg: {average} {unit} (Graph is based on '\n 'incomplete data).').format(\n average=floatformat(\n preferred_unit_converter.extract_value(\n enpi_sample.physical_quantity),\n self._get_float_format_decimals()),\n unit=preferred_unit_converter.get_display_unit())\n else:\n caption = _('No values in this range.')\n else:\n caption = self._get_caption_text(\n all_data_samples,\n preferred_unit_converter,\n data_series.is_rate(),\n sample_resolution)\n\n MAXIMUM_FACTOR = 1.2\n\n result = {\n \"data\": data,\n \"options\": {\n \"colors\": self.get_colors(),\n \"xaxis\": {\n \"ticks\": ticks,\n \"min\": unix_timestamp(from_timestamp),\n \"max\": unix_timestamp(to_timestamp),\n 'title': unicode(caption),\n },\n \"yaxis\": {\n \"title\": unicode(\n preferred_unit_converter.get_display_unit()),\n \"min\": float(minimum) * MAXIMUM_FACTOR,\n \"max\": float(maximum) * MAXIMUM_FACTOR,\n }\n }\n }\n\n # tick remaining progress\n while self.__progress < self.PROGRESS_TOTAL:\n self.__tick_progress()\n\n return result\n\n def tick_progress(self):\n \"\"\"\n Hook for subclasses to implement progress reporting.\n\n Will be called exactly C{PROGRESS_TOTAL} times during each call to\n L{get_graph_data()}\n \"\"\"\n pass\n\n def __tick_progress(self):\n \"\"\"\n Wrapper for L{tick_progress()}, ensuring pre- and postconditions.\n \"\"\"\n assert 0 <= self.__progress\n self.__progress += 1\n assert self.__progress <= self.PROGRESS_TOTAL, \\\n '%s <= %s' % (self.__progress, self.PROGRESS_TOTAL)\n self.tick_progress()\n\n def get_colors(self):\n \"\"\"\n @return List of HTML RGB colors to cycle through when plotting graph.\n \"\"\"\n return ['#00A8F0', '#999999', '#CB4B4B', '#4DA74D', '#9440ED']\n\n\nclass CollectionCustomerBoundManager(CustomerBoundManager):\n _field = 'collection__customer'\n\n\nclass Graph(models.Model, AbstractGraph):\n \"\"\"\n A graph displays the data series of one or more L{DataSeries}s for a\n given time span.\n \"\"\"\n\n role = DataRoleField()\n\n collection = models.ForeignKey(Collection, on_delete=models.CASCADE)\n hidden = models.BooleanField(default=False)\n\n objects = CollectionCustomerBoundManager()\n\n class Meta:\n verbose_name = _('graph')\n verbose_name_plural = _('graphs')\n ordering = ['role', 'id']\n unique_together = ('collection', 'role')\n app_label = 'measurementpoints'\n\n def __unicode__(self):\n return self.get_role_display()\n\n def _get_data_series(self):\n \"\"\"\n Get the L{DataSeries} associated with this graph.\n \"\"\"\n return [ds.subclass_instance for ds in self.dataseries_set.all()]\n\n def _get_float_format_decimals(self):\n if self.role == DataRoleField.COST:\n return '-2'\n else:\n return super(Graph, self)._get_float_format_decimals()\n\n def get_colors(self):\n if self.role in [DataRoleField.CONSUMPTION, DataRoleField.POWER,\n DataRoleField.VOLUME_FLOW]:\n return [\n UTILITY_TYPE_TO_COLOR[self.collection.utility_type],\n '#999999']\n elif self.role == DataRoleField.CO2:\n return ['#444444', '#999999']\n else:\n return super(Graph, self).get_colors()\n" }, { "alpha_fraction": 0.7016706466674805, "alphanum_fraction": 0.7136037945747375, "avg_line_length": 19.950000762939453, "blob_id": "d0efde9ab017dbdeffd66a8d86a0bfdf0a31291d", "content_id": "bcca63ed3c19065b5d9f6162f1a53c43122ca9d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/gridplatform/token_auth/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. py:data:: settings.TOKEN_AUTH_USER_PASSWORD_LENGTH\n\n The password length used for token auth users. Defaults to 16.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.encryption.conf import settings\n\nfrom appconf import AppConf\n\n\n__all__ = ['settings', 'TokenAuthConf']\n\n\nclass TokenAuthConf(AppConf):\n USER_PASSWORD_LENGTH = 16\n" }, { "alpha_fraction": 0.5631313323974609, "alphanum_fraction": 0.5896464586257935, "avg_line_length": 25.69662857055664, "blob_id": "bd8cdf236114317ac1f77eff6412b3d1f9a5f640", "content_id": "3e9fd4e731c446d5b9253ea44280c2ba550f2956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2376, "license_type": "no_license", "max_line_length": 100, "num_lines": 89, "path": "/gridplatform/utils/iter_ext.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nMore iterator building blocks, based on\nhttp://docs.python.org/2/library/itertools.html#recipes\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\n\n\ndef nwise(iterable, n, tee=itertools.tee, izip=itertools.izip):\n \"\"\"\n >>> nwise([s0, s1, ...], n) # doctest: +SKIP\n (s_0,...,s_n-1), (s1,..,s_n), (s2,...,s_n+1), ...\n \"\"\"\n iterators = tee(iterable, n)\n for count, iterator in enumerate(iterators):\n for i in range(count):\n next(iterator, None)\n return izip(*iterators)\n\n\ndef triplewise(iterable, tee=itertools.tee, izip=itertools.izip):\n \"\"\"\n >>> triplewise([s0, s1, s2, s3, s4, ...]) # doctest: +SKIP\n (s0,s1,s2), (s1,s2,s3), (s2,s3,s4), ...\n \"\"\"\n a, b, c = tee(iterable, 3)\n next(b, None)\n next(c, None)\n next(c, None)\n return izip(a, b, c)\n\n\ndef pairwise(iterable, tee=itertools.tee, izip=itertools.izip):\n \"\"\"\n >>> pairwise([s0, s1, s2, s3, ...]) # doctest: +SKIP\n (s0,s1), (s1,s2), (s2,s3), ...\n \"\"\"\n a, b = tee(iterable)\n next(b, None)\n return izip(a, b)\n\n\ndef pairwise_extended(iterable,\n tee=itertools.tee, izip_longest=itertools.izip_longest):\n \"\"\"\n >>> pairwise_extended([s0, s1, s2, s3, ... sn]) # doctest: +SKIP\n (s0,s1), (s1,s2), (s2,s3), ..., (s_n,None)\n \"\"\"\n a, b = tee(iterable)\n next(b, None)\n return izip_longest(a, b)\n\n\ndef flatten(listOfLists, chain=itertools.chain):\n \"\"\"\n Flatten one level of nesting\n \"\"\"\n return chain.from_iterable(listOfLists)\n\n\ndef tee_lookahead(t, i, islice=itertools.islice):\n \"\"\"\n Inspect the i-th upcomping value from a tee object while leaving the tee\n object at its current position.\n\n :raise IndexError: If the underlying iterator doesn't have enough\n values.\n \"\"\"\n for value in islice(t.__copy__(), i, None):\n return value\n raise IndexError(i)\n\n\ndef count_extended(start, step):\n \"\"\"\n Similar to itertools.count, but itertools.count only works for numbers.\n (Based on the \"equivalent Python code\" for itertools.count.)\n\n >>> count_extended(datetime.date(2000, 1, 1), datetime.timedelta(days=1)) # noqa doctest: +SKIP\n datetime.date(2000, 1, 1), datetime.date(2000, 1, 2), ...\n \"\"\"\n n = start\n while True:\n yield n\n n += step\n" }, { "alpha_fraction": 0.6622516512870789, "alphanum_fraction": 0.6631977558135986, "avg_line_length": 28.36111068725586, "blob_id": "810221cd0b4305f0d6385ff11e5178f57294ef69", "content_id": "c7d170996b3e7a07f5ff947b558160a1ca8babab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2114, "license_type": "no_license", "max_line_length": 93, "num_lines": 72, "path": "/gridplatform/settings/test.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\nUnit test settings.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport os\n\nfrom .base import * # noqa\n\n# ######### DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid # noqa\nTEMPLATE_STRING_IF_INVALID = '\\XYZXYZXYZ'\n# ######### END DEBUG CONFIGURATION\n\n\nTEMPLATE_LOADERS = (\n ('django.template.loaders.cached.Loader', (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n )),\n)\n\n# avoid poluting local system queue.\nBROKER_BACKEND = 'memory'\n\n# ######### TEST SETTINGS\nTEST_RUNNER = 'junorunner.runner.JunoDiscoverRunner'\nTEST_RUNNER_RERUN_LOG_FILE_NAME = os.environ.get(\n 'TEST_RERUN_FILE', 'test_rerun.txt')\nTEST_RUNNER_FAILURE_LIST_FILENAME = os.environ.get(\n 'TEST_LOG_FILE', 'test_failures.txt')\n# ######### END_TEST SETTINGS\n\n\n# ######### STATIC FILE CONFIGURATION\n# Don't use the \"caching\" variant; as it will try to read the file from where\n# it *would* have been put by collectstatic to get the MD5 sum to append to the\n# URL.\nSTATICFILES_STORAGE = \\\n 'django.contrib.staticfiles.storage.StaticFilesStorage'\n# ######### END STATIC FILE CONFIGURATION\n\n\n# ######### EMAIL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n# ######### END EMAIL CONFIGURATION\n\n\n# ######### DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n \"default\": {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'portal',\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n 'TEST_NAME': os.environ.get('TEST_DATABASE_NAME', 'test_portal')\n },\n}\n# ######### END DATABASE CONFIGURATION\n\n\n# ######### SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Note: This key should only be used for development and testing.\nSECRET_KEY = r\"{{ secret_key }}\"\n# ######### END SECRET CONFIGURATION\n\nCELERY_EAGER_PROPAGATES_EXCEPTIONS = True\n" }, { "alpha_fraction": 0.8571428656578064, "alphanum_fraction": 0.8571428656578064, "avg_line_length": 24.77777862548828, "blob_id": "41bab2428b34cc5321c6b6db4cc8eff89849d75b", "content_id": "69b764b6b72f4ce815a3498fea6b3254f90beccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 71, "num_lines": 9, "path": "/energymanager/configuration_site/admin.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom gridplatform.customer_datasources.models import CustomerDataSource\n\n\nclass CustomerDataSourceAdmin(admin.ModelAdmin):\n pass\n\nadmin.site.register(CustomerDataSource, CustomerDataSourceAdmin)" }, { "alpha_fraction": 0.6131036877632141, "alphanum_fraction": 0.6141690611839294, "avg_line_length": 32.52381134033203, "blob_id": "86c0e31743c730d11fdca58a5f20d0452d723eb9", "content_id": "16dbdbaae6e924c3468e12cc5e2ce12e774ca790", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5632, "license_type": "no_license", "max_line_length": 79, "num_lines": 168, "path": "/gridplatform/reports/consumption.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nimport itertools\nimport re\n\nfrom django.utils.translation import ugettext as _\nfrom django.template.defaultfilters import floatformat\n\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.utils.units import UNIT_CHOICES\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\n\nfrom .csv import generate_csv\nfrom .pdf import generate_pdf\n\n\n_ConsumptionData = namedtuple('_ConsumptionData', [\n 'from_timestamp', 'to_timestamp', 'group', 'portal_name',\n 'measurement_type',\n 'consumption', 'degreedays_corrected_consumption', 'unit',\n 'cost', 'cost_unit',\n 'meter_number', 'installation_number', 'mp_id',\n])\n\n\ndef currency_display(currency_unit):\n if currency_unit is None:\n return ''\n else:\n normalized_unit = PhysicalQuantity(1, currency_unit).units\n assert re.match('currency_[a-z]{3}', normalized_unit)\n return PhysicalUnitConverter(normalized_unit)\n\n\ndef extend_consumption_data(collected):\n mp_ids = collected['mp_ids']\n mp_data = collected['mp_data']\n from_timestamp = collected['from_timestamp']\n to_timestamp = collected['to_timestamp']\n measurementpoints = Collection.objects.filter(\n id__in=mp_ids)\n result = {}\n for mp in measurementpoints:\n try:\n data = mp_data[mp.id]\n except KeyError:\n continue\n if mp.utility_type not in result:\n result[mp.utility_type] = {\n 'data': [],\n 'utility_name': mp.get_utility_type_display().capitalize(),\n 'unit': unicode(dict(UNIT_CHOICES)[data['unit']]),\n }\n\n result[mp.utility_type]['data'].append(_ConsumptionData(\n from_timestamp,\n to_timestamp,\n mp.get_ancestors(),\n unicode(mp),\n unicode(mp.get_utility_type_display()),\n data['consumption'],\n data['degreedays_corrected_consumption'],\n unicode(dict(UNIT_CHOICES)[data['unit']]),\n data['cost'],\n currency_display(data['currency_unit']),\n data['billing_meter_number'],\n data['billing_installation_number'],\n mp.id))\n\n return result\n\n\ndef consumption_csv(from_date, to_date, collected_data,\n include_degree_days_corrected, include_cost):\n \"\"\"\n Generate CSV consumption report for a given period.\n\n @param measurementpoints: Measurementpoints/collections to include in\n report.\n\n @param from_date: Start of period to include in report.\n\n @param to_date: End of period to include in report.\n\n\n @return: C{HttpResponse} containing CSV data.\n \"\"\"\n header = _ConsumptionData(\n _('from'), _('to'), _('group'), _('portal name'),\n _('resource type'), _('consumption'),\n _('degreedays-corrected consumption'),\n _('unit'), _('cost'),\n _('currency'), _('meter number'), _('installation number'),\n _('id'))\n\n def degree_days_filter(line):\n before_degree_days = [\n line.from_timestamp, line.to_timestamp, line.group,\n line.portal_name,\n line.measurement_type, line.consumption,\n ]\n if include_degree_days_corrected:\n degree_days = [line.degreedays_corrected_consumption]\n else:\n degree_days = []\n before_cost = [line.unit]\n if include_cost:\n cost = [line.cost, line.cost_unit]\n else:\n cost = []\n last = [line.meter_number, line.installation_number, line.mp_id]\n return before_degree_days + degree_days + before_cost + cost + last\n\n from_formatted = from_date.strftime('%Y-%m-%d')\n to_formatted = to_date.strftime('%Y-%m-%d')\n\n def csv_format(data):\n return data._replace(\n from_timestamp=from_formatted,\n to_timestamp=to_formatted,\n group=':'.join([unicode(g) for g in data.group]),\n consumption=floatformat(data.consumption, 2),\n degreedays_corrected_consumption=floatformat(\n data.degreedays_corrected_consumption, 2),\n cost=floatformat(data.cost, 2))\n data = collected_data\n for utility_type, values in collected_data.iteritems():\n data[utility_type]['data'] = itertools.imap(csv_format, values['data'])\n data[utility_type]['data'] = itertools.imap(degree_days_filter,\n data[utility_type]['data'])\n return generate_csv(data, header=degree_days_filter(header))\n\n\ndef consumption_pdf(from_date, to_date, collected_data,\n include_degree_days_corrected, include_cost, customer,\n errors=None):\n \"\"\"\n Generate PDF consumption report for a given period.\n\n @param measurementpoints: Measurementpoints/collections to include in\n report.\n\n @param from_date: Start of period to include in report.\n\n @param to_date: End of period to include in report.\n\n @return: C{HttpResponse} containing PDF data.\n \"\"\"\n\n data = {\n 'data': collected_data,\n 'from_date': from_date,\n 'to_date': to_date,\n 'include_degree_days_corrected': include_degree_days_corrected,\n 'include_cost': include_cost,\n 'errors': errors,\n }\n\n return generate_pdf(\n 'reports/consumption.tex',\n data,\n title=_('Consumption'),\n report_type='consumption',\n customer=customer)\n" }, { "alpha_fraction": 0.7137883305549622, "alphanum_fraction": 0.7186629772186279, "avg_line_length": 35.82051467895508, "blob_id": "c281f7c59b5d44445160344796fa1765abc3bf2f", "content_id": "0fcb397cb8fce533d58cbd9680f7cad64c9270a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1436, "license_type": "no_license", "max_line_length": 87, "num_lines": 39, "path": "/gridplatform/datahub/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import CustomerBoundManager\n\nfrom legacy.devices.models import Meter, PhysicalInput\n\n\nclass DatahubConnection(EncryptionCustomerFieldMixin, EncryptedModel):\n meter = models.ForeignKey(Meter, verbose_name=_('Meter'), on_delete=models.PROTECT)\n input = models.ForeignKey(PhysicalInput, editable=False,\n on_delete=models.PROTECT)\n\n customer_meter_number = models.CharField(\n _('Meter Number'), max_length=50)\n authorization_id = models.CharField(\n _('authorization_id'), max_length=10, blank=True, null=True)\n\n start_date = models.DateField(_('Start date'), blank=True, null=True)\n end_date = models.DateField(_('End date'), blank=True, null=True)\n\n unit = models.CharField(\n _('Unit'), max_length=50, blank=True)\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('Datahub connection')\n verbose_name_plural = _('Datahub connections')\n\n def __unicode__(self):\n return unicode(self.customer_meter_number)\n" }, { "alpha_fraction": 0.772849440574646, "alphanum_fraction": 0.7768816947937012, "avg_line_length": 36.20000076293945, "blob_id": "a16e4f36567c5b82c1579e2a1fce278402ca5c96", "content_id": "1f8e9a68fd762e5f637fdd14d934c3dd707d496e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 744, "license_type": "no_license", "max_line_length": 68, "num_lines": 20, "path": "/legacy/indexes/models/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .index import Index\nfrom .index import Entry\nfrom .index import Period\nfrom .index import DerivedIndexPeriod\nfrom .index import SeasonIndexPeriod\nfrom .index import SpotMapping\nfrom .standardmonth import StandardMonthIndex\nfrom .datasourceadapter import DataSourceIndexAdapter\nfrom .datasourceadapter import DataSourceTariffAdapter\nfrom .datasourceadapter import DataSourceCo2ConversionAdapter\n\n\n__all__ = ['Index', 'Entry', 'Period', 'DerivedIndexPeriod',\n 'SeasonIndexPeriod', 'SpotMapping', 'StandardMonthIndex',\n 'DataSourceIndexAdapter', 'DataSourceTariffAdapter',\n 'DataSourceCo2ConversionAdapter']\n" }, { "alpha_fraction": 0.6770251393318176, "alphanum_fraction": 0.6773743033409119, "avg_line_length": 33.92683029174805, "blob_id": "78c0b5a0b4fef716ffe645d57beb68fef2467e08", "content_id": "20b198926a4dc4a7abd2d8ca63029ed5a676c2cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2864, "license_type": "no_license", "max_line_length": 75, "num_lines": 82, "path": "/legacy/manage_indexes/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines URLs of the manage_indexes Django app.\n\"\"\"\n\nfrom django.conf.urls import patterns, url\n\nfrom . import views\n\n\ndef _url(regexp, view):\n \"\"\"\n All URLs are identified as C{manage_indexes-<VIEW_NAME>}.\n \"\"\"\n return url(regexp, view, name=(\"manage_indexes-\" + view))\n\n\nurlpatterns = patterns(\n \"legacy.manage_indexes.views\",\n _url(r\"^$\", \"listing\"),\n _url(r\"^list-json/$\", \"list_json\"),\n\n url(r'^form/derived/tariff/electricity$',\n views.DerivedElectricityTariffCreateView.as_view(),\n name='manage_indexes-derived-electricity-tariff-create-view'),\n\n url(r'^form/derived/tariff/gas$',\n views.DerivedGasTariffCreateView.as_view(),\n name='manage_indexes-derived-gas-tariff-create-view'),\n\n url(r'^form/derived/tariff/water$',\n views.DerivedWaterTariffCreateView.as_view(),\n name='manage_indexes-derived-water-tariff-create-view'),\n\n url(r'^form/derived/tariff/district_heating$',\n views.DerivedDistrictHeatingTariffCreateView.as_view(),\n name='manage_indexes-derived-district_heating-tariff-create-view'),\n\n url(r'^form/derived/tariff/oil$',\n views.DerivedOilTariffCreateView.as_view(),\n name='manage_indexes-derived-oil-tariff-create-view'),\n\n url(r'^form/seasons/tariff/electricity$',\n views.SeasonsElectricityTariffCreateView.as_view(),\n name='manage_indexes-seasons-electricity-tariff-create-view'),\n\n url(r'^form/seasons/tariff/gas$',\n views.SeasonsGasTariffCreateView.as_view(),\n name='manage_indexes-seasons-gas-tariff-create-view'),\n\n url(r'^form/seasons/tariff/water$',\n views.SeasonsWaterTariffCreateView.as_view(),\n name='manage_indexes-seasons-water-tariff-create-view'),\n\n url(r'^form/seasons/tariff/district_heating$',\n views.SeasonsDistrictHeatingTariffCreateView.as_view(),\n name='manage_indexes-seasons-district_heating-tariff-create-view'),\n\n url(r'^form/seasons/tariff/oil$',\n views.SeasonsOilTariffCreateView.as_view(),\n name='manage_indexes-seasons-oil-tariff-create-view'),\n\n url(r'^form/seasons/employees/unknown$',\n views.SeasonsEmployeesIndexCreateView.as_view(),\n name='manage_indexes-seasons-employees-index-create-view'),\n\n url(r'^form/seasons/area/unknown$',\n views.SeasonsAreaIndexCreateView.as_view(),\n name='manage_indexes-seasons-area-index-create-view'),\n\n url(r'^form/derived/(?P<pk>\\d+)/$',\n views.DerivedIndexUpdateView.as_view(),\n name='manage_indexes-derived-index-update-view'),\n\n url(r'^form/seasons/(?P<pk>\\d+)/$',\n views.SeasonsIndexUpdateView.as_view(),\n name='manage_indexes-seasons-index-update-view'),\n\n _url(r\"^delete/$\", \"delete\"),\n)\n" }, { "alpha_fraction": 0.7139175534248352, "alphanum_fraction": 0.7164948582649231, "avg_line_length": 24.866666793823242, "blob_id": "a75c74b1659eb0e1761cf3825cf169dd8902430f", "content_id": "b9bbb3077eb244213f79539c8e701ff77c7448dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 388, "license_type": "no_license", "max_line_length": 56, "num_lines": 15, "path": "/legacy/measurementpoints/management/commands/rebuild_group_tree.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.management.base import BaseCommand\n\nfrom legacy.measurementpoints.models import Collection\n\n\nclass Command(BaseCommand):\n args = ''\n help = 'Rebuilds the measurement points group tree.'\n\n def handle(self, *args, **options):\n Collection.tree.rebuild()\n" }, { "alpha_fraction": 0.6559792160987854, "alphanum_fraction": 0.65684574842453, "avg_line_length": 31.05555534362793, "blob_id": "651ca58563c86cd1ad1509f2ad303aef88d73702", "content_id": "7833a23582c888bbc7aeab8326516fe4e3fcf61f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 77, "num_lines": 36, "path": "/gridplatform/users/auth_backends.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.backends import ModelBackend\n\nfrom gridplatform import trackuser\nfrom gridplatform import encryption\n\nfrom .managers import hash_username\nfrom .models import User\n\n\nclass HashedUsernameBackend(ModelBackend):\n \"\"\"\n Custom authentication backend; uses hash of provided username rather than\n provided username directly. This works with our custom UserManager which\n uses the same hash function on creating users.\n \"\"\"\n def authenticate(self, username=None, password=None):\n try:\n user = User._all_users.get(username=hash_username(username))\n if user.check_password(password):\n trackuser._store.user = user\n encryption._store.private_key = user.decrypt_private_key(\n password)\n return user\n except User.DoesNotExist:\n pass\n return None\n\n def get_user(self, user_id):\n try:\n return User._all_users.get(pk=user_id)\n except User.DoesNotExist:\n return None\n" }, { "alpha_fraction": 0.7761449813842773, "alphanum_fraction": 0.7761449813842773, "avg_line_length": 35.45535659790039, "blob_id": "e562446f0e82eaaf12aa82981fd76a5a94a83a7d", "content_id": "faa5365df5468b78a274f63cf83cfcd372ecacc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4083, "license_type": "no_license", "max_line_length": 74, "num_lines": 112, "path": "/documentation/source/apps/gridplatform/reports.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Reports\n=======\n\nThe ``reports`` app defines some generic PDF report functionalities as\nwell as the first application of these functionalities, namely a\nlegacy consumption report. The legacy part of this app is outside the\nscope of this section.\n\nModels\n------\n\n.. autoclass:: gridplatform.reports.models.Report\n\nViews\n-----\n\nReports are generated by submitting a report specific form to a\nspecializaton of\n:py:class:`~gridplatform.reports.views.StartReportView`. If the\nsubmitted form is valid a Celery task specific to the\n:py:class:`~gridplatform.reports.views.StartReportView` specialization\nis started. Ajax is then used to query\n:py:func:`~gridplatform.reports.views.status` for the status of the\ntask (which may be rendered in a progress bar, or by a spinner icon or\nsimilar). When :py:func:`~gridplatform.reports.views.status` reports\nthe task as completed, a\n:py:class:`~gridplatform.reports.views.TaskForm` should be\nsubmitted via Ajax to\n:py:class:`~gridplatform.reports.views.FinalizeReportView` which then\ngenerates the report and returns a JSON object that includes a URL to\n:py:func:`~gridplatform.reports.views.serve` where the generated\nreport can be downloaded from.\n\n.. autofunction:: gridplatform.reports.views.is_queue_too_long\n\n.. autoclass:: gridplatform.reports.views.CeleryError\n :members: __init__\n\n.. autoclass:: gridplatform.reports.views.StartReportView\n :members: get_task, get_task_data, start_task, form_valid, form_invalid\n\n.. autoclass:: gridplatform.reports.views.TaskForm\n\n.. autoclass:: gridplatform.reports.views.FinalizeReportView\n :members: generate_report, form_valid, form_invalid\n\n.. autofunction:: gridplatform.reports.views.serve\n\n.. autofunction:: gridplatform.reports.views.status\n\nPDF Generation\n--------------\n\nPDF documents are generated by rendering a Django template into a\nLaTex document and then compiling this into a PDF.\n\nErrors in the LaTeX code is signalled via the\n:py:class:`~gridplatform.reports.pdf.LatexError` exception.\n\nSimple LaTex documents (without GNU Plots and free of Django\ntemplates) are compiled via\n:py:func:`~gridplatform.reports.pdf.compile_pdf`, which is implemented\nin terms of :py:func:`~gridplatform.reports.pdf._compile_pdf`.\n\n:py:func:`~gridplatform.reports.pdf._compile_pdf` is also used in\nimplementing :py:func:`~gridplatform.reports.pdf._generate_pdf` (which\nrenders a Django template into a LaTex file first).\n:py:func:`~gridplatform.reports.pdf._generate_pdf` and\n:py:func:`~gridplatform.reports.pdf._generate_gnuplot` is used for\nimplementing :py:func:`~gridplatform.reports.pdf.generate_pdf` which\nis the general interface for generating PDFs using Django templates\n(rendered into LaTex files) along with GNU plots.\n\n.. autoclass:: gridplatform.reports.pdf.LatexError\n :members: __init__\n\n.. autofunction:: gridplatform.reports.pdf.compile_pdf\n\n.. autofunction:: gridplatform.reports.pdf._compile_pdf\n\n.. autofunction:: gridplatform.reports.pdf.generate_pdf\n\n.. autofunction:: gridplatform.reports.pdf._generate_pdf\n\n.. autofunction:: gridplatform.reports.pdf._generate_gnuplot\n\n.. autofunction:: gridplatform.reports.pdf.serve_pdf\n\n.. autoclass:: gridplatform.reports.pdf.PDFTemplateResponse\n :members: rendered_content\n\n.. autoclass:: gridplatform.reports.pdf.PDFDetailView\n :members: get_document_title, get_document_customer,\n get_document_type, get_context_meta, get_context_data\n\nCSV Generation\n--------------\n\nCSV means comma separated values, which has stick to the text format\nexported from MS Excell, even in Denmark (and other european\ncountries), where comma is used as decimal delimiter forcing\nsemi-colon to be used to seperate columns instead.\n\n:py:func:`~gridplatform.reports.csv.generate_csv` converts data into a\nCSV format and :py:func:`~gridplatform.reports.csv.serve_csv` is\nimplemented in terms of\n:py:func:`~gridplatform.reports.csv.generate_csv` and returns a\n:py:class:`django.http.HttpResponse` holding the CSV as its content.\n\n.. autofunction:: gridplatform.reports.csv.generate_csv\n\n.. autofunction:: gridplatform.reports.csv.serve_csv\n" }, { "alpha_fraction": 0.6046647429466248, "alphanum_fraction": 0.6052477955818176, "avg_line_length": 30.18181800842285, "blob_id": "bfa2301d743e50cd013165ca1b61316d2b7ed721", "content_id": "443ad952cc532e53adc6feb766e682ff64cda69f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "no_license", "max_line_length": 61, "num_lines": 55, "path": "/energymanager/provider_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.views.generic import RedirectView\n\nfrom . import views\n\nurlpatterns = patterns(\n '',\n url(r'^$',\n RedirectView.as_view(\n url=reverse_lazy('provider_site:customer-list')),\n name='home'),\n url(r'^customers/$',\n views.CustomerListView.as_view(),\n name='customer-list'),\n url(r'^customers/content$',\n views.CustomerListContentView.as_view(),\n name='customer-list-content'),\n url(r'^customers/create$',\n views.CustomerCreateView.as_view(),\n name='customer-create'),\n url(r'^customers/update/(?P<pk>\\d+)/$',\n views.CustomerUpdateView.as_view(),\n name='customer-update'),\n\n url(r'^users/$',\n views.UserListView.as_view(),\n name='user-list'),\n url(r'^users/content$',\n views.UserListContentView.as_view(),\n name='user-list-content'),\n url(r'^users/create$',\n views.UserCreateView.as_view(),\n name='user-create'),\n url(r'^users/update/(?P<pk>\\d+)/$',\n views.UserUpdateView.as_view(),\n name='user-update'),\n\n url(r'^api_users/$',\n views.APIUserListView.as_view(),\n name='apiuser-list'),\n url(r'^api_users/content$',\n views.APIUserListContentView.as_view(),\n name='apiuser-list-content'),\n url(r'^api_users/create$',\n views.APIUserCreateView.as_view(),\n name='apiuser-create'),\n url(r'^api_users/update/(?P<pk>\\d+)/$',\n views.APIUserUpdateView.as_view(),\n name='apiuser-update'),\n)\n" }, { "alpha_fraction": 0.6371808052062988, "alphanum_fraction": 0.6381888389587402, "avg_line_length": 32.06666564941406, "blob_id": "ca17b2db14fd96d0bf21c85ebef72552a0b5a12c", "content_id": "d5a23a1457a323b2613ad140272882f3c4a9d60e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11904, "license_type": "no_license", "max_line_length": 77, "num_lines": 360, "path": "/energymanager/provider_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.conf import settings\nfrom django.contrib.auth import logout\nfrom django.contrib.auth.models import Group\nfrom django.contrib.auth.models import Permission\nfrom django.core.urlresolvers import reverse\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.utils.translation import ugettext as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.token_auth.models import create_token\nfrom gridplatform.trackuser import get_provider\nfrom gridplatform.trackuser import _get_user_customer\nfrom gridplatform.users.managers import hash_username\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import generic_views\nfrom gridplatform.utils.views import NoCustomerMixin\n\n\nclass CustomerListView(NoCustomerMixin, generic_views.ListView):\n model = Customer\n template_name = 'provider_site/customer_list.html'\n\n def get_breadcrumbs(self):\n return (\n (_('Customers'), ''),\n )\n\n\nclass CustomerListContentView(\n NoCustomerMixin, generic_views.ListView):\n sort_fields = ['name_plain', 'is_active']\n search_fields = ['name_plain']\n model = Customer\n paginate_by = 100\n template_name = 'provider_site/_customer_list_content.html'\n\n\nclass CustomerCreateView(\n NoCustomerMixin, generic_views.CreateView):\n model = Customer\n template_name = 'provider_site/customer_form.html'\n fields = (\n 'name', 'vat', 'address', 'postal_code', 'city', 'phone',\n 'country_code', 'timezone', 'contact_name', 'contact_email',\n 'contact_phone', 'electricity_instantaneous',\n 'electricity_consumption', 'gas_instantaneous', 'gas_consumption',\n 'water_instantaneous', 'water_consumption',\n 'heat_instantaneous', 'heat_consumption',\n 'oil_instantaneous', 'oil_consumption',\n 'temperature', 'currency_unit',\n )\n\n def get_success_url(self):\n return reverse('provider_site:customer-list')\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.provider = get_provider()\n self.object.save()\n\n return HttpResponseRedirect(self.get_success_url())\n\n def get_breadcrumbs(self):\n return (\n (_('Customers'),\n reverse('provider_site:customer-list')),\n (_('Customer Details'), ''),\n )\n\n\nclass CustomerUpdateView(\n NoCustomerMixin, generic_views.UpdateView):\n model = Customer\n template_name = 'provider_site/customer_form.html'\n fields = (\n 'name', 'vat', 'address', 'postal_code', 'city', 'phone',\n 'country_code', 'timezone', 'contact_name', 'contact_email',\n 'contact_phone', 'electricity_instantaneous',\n 'electricity_consumption', 'gas_instantaneous', 'gas_consumption',\n 'water_instantaneous', 'water_consumption',\n 'heat_instantaneous', 'heat_consumption',\n 'oil_instantaneous', 'oil_consumption',\n 'temperature', 'currency_unit', 'is_active'\n )\n\n def get_success_url(self):\n return reverse('provider_site:customer-list')\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return (\n (_('Customers'),\n reverse('provider_site:customer-list')),\n (_('Customer Details'), ''),\n )\n\n\nclass UserListView(\n NoCustomerMixin, generic_views.TemplateView):\n template_name = 'provider_site/user_list.html'\n\n\nclass UserListContentView(\n NoCustomerMixin, generic_views.ListView):\n sort_fields = ['e_mail_plain', 'name_plain']\n search_fields = ['e_mail_plain', 'name_plain']\n model = User\n paginate_by = 100\n template_name = 'provider_site/_user_list_content.html'\n\n def get_queryset(self):\n qs = super(UserListContentView, self).get_queryset()\n return qs.exclude(user_type=User.API_USER)\n\n\nclass UserFormBase(forms.ModelForm):\n class Meta:\n model = User\n\n def clean_e_mail(self):\n e_mail = self.cleaned_data['e_mail']\n if User.objects.filter(username=hash_username(e_mail)).exists():\n raise forms.ValidationError(\n _(\"A user with that e-mail already exists\"))\n return e_mail\n\n\nclass UserForm(UserFormBase):\n class Meta(UserFormBase.Meta):\n fields = ('groups', 'e_mail',\n 'phone', 'mobile', 'password',\n 'name')\n\n def __init__(self, *args, **kwargs):\n super(UserForm, self).__init__(*args, **kwargs)\n self.fields['password'].initial = User.objects.make_random_password()\n\n group_perm = Permission.objects.get(codename='provider_admin_group')\n groups = Group.objects.filter(permissions__id__exact=group_perm.id)\n self.fields['groups'].choices = [(g.id, g.name) for g in groups]\n\n\nclass UserCreateForm(UserForm):\n # customer field is editable=False on User model.\n customer = forms.ModelChoiceField(\n label=_('Customer'), queryset=Customer.objects.none())\n\n def __init__(self, *args, **kwargs):\n super(UserCreateForm, self).__init__(*args, **kwargs)\n self.fields['customer'].queryset = Customer.objects.all()\n\n def save(self, commit=True):\n self.instance.customer = self.cleaned_data['customer']\n return super(UserCreateForm, self).save(commit=commit)\n\n\nclass UserCreateView(\n NoCustomerMixin, generic_views.CreateView):\n model = User\n template_name = 'provider_site/user_form.html'\n form_class = UserCreateForm\n\n def get_success_url(self):\n return reverse('provider_site:user-list')\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n\n if self.object.customer:\n user = User.objects.create_user(\n self.object.e_mail_plain, self.object.password,\n user_type=User.ADMIN,\n customer=self.object.customer,\n groups=form.cleaned_data.get('groups', None))\n else:\n user = User.objects.create_user(\n self.object.e_mail_plain, self.object.password,\n user_type=User.ADMIN,\n provider=get_provider(),\n groups=form.cleaned_data.get('groups', None))\n\n user.e_mail_plain = self.object.e_mail_plain\n user.name_plain = self.object.name_plain\n user.phone_plain = self.object.phone_plain\n user.mobile_plain = self.object.mobile_plain\n user.save()\n\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass UserUpdateForm(forms.ModelForm):\n new_password = forms.CharField(required=False, min_length=8)\n\n class Meta:\n model = User\n fields = ('groups', 'e_mail',\n 'name', 'phone', 'mobile', 'is_active')\n\n def __init__(self, *args, **kwargs):\n super(UserUpdateForm, self).__init__(*args, **kwargs)\n group_perm = Permission.objects.get(codename='provider_admin_group')\n groups = Group.objects.filter(permissions__id__exact=group_perm.id)\n self.fields['groups'].choices = [(g.id, g.name) for g in groups]\n\n def save(self, commit=True):\n assert commit\n user = super(UserUpdateForm, self).save(commit=False)\n if self.cleaned_data.get('new_password'):\n user.reset_password(\n self.request, self.cleaned_data.get('new_password'))\n if user.id == self.request.user.id:\n logout(self.request)\n user.save()\n self.save_m2m()\n return user\n\n\nclass UserUpdateView(\n NoCustomerMixin, generic_views.UpdateView):\n model = User\n template_name = 'provider_site/user_form.html'\n form_class = UserUpdateForm\n\n def get_success_url(self):\n return reverse('provider_site:user-list')\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def form_valid(self, form):\n form.request = self.request\n form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n\nclass APIUserListView(NoCustomerMixin, generic_views.TemplateView):\n template_name = 'provider_site/api_user_list.html'\n\n def get_breadcrumbs(self):\n return ((_('API Users'), ''), )\n\n\nclass APIUserListContentView(NoCustomerMixin, generic_views.ListView):\n sort_fields = [\n 'provider__name_plain', 'customer__name_plain', 'e_mail_plain',\n ]\n search_fields = [\n 'provider__name_plain', 'customer__name_plain', 'e_mail_plain',\n ]\n model = User\n paginate_by = 100\n template_name = 'provider_site/_api_user_list_content.html'\n\n def get_queryset(self):\n qs = super(APIUserListContentView, self).get_queryset()\n return qs.filter(user_type=User.API_USER)\n\n\nclass APIUserForm(UserFormBase):\n class Meta(UserFormBase.Meta):\n fields = ('e_mail', 'groups')\n\n\nclass APIUserCreateForm(APIUserForm):\n def __init__(self, *args, **kwargs):\n super(APIUserCreateForm, self).__init__(*args, **kwargs)\n if _get_user_customer() is None:\n self.fields['customer'].required = False\n self.fields['customer'].widget.is_required = False\n self.fields['customer'].empty_label = \\\n 'All customers --- Provider API User'\n\n customer = forms.ModelChoiceField(\n label=_('Customer'),\n queryset=Customer.objects.all(), empty_label=None)\n\n def save(self, commit=True):\n self.instance.customer = self.cleaned_data['customer']\n if _get_user_customer() is None and not self.instance.customer:\n self.instance.provider = get_provider()\n return super(APIUserCreateForm, self).save(commit=commit)\n\n\nclass APIUserCreateView(NoCustomerMixin, generic_views.CreateView):\n model = User\n template_name = 'provider_site/api_user_form.html'\n form_class = APIUserCreateForm\n\n def get_success_url(self):\n return reverse('provider_site:apiuser-list')\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n\n password = User.objects.make_random_password(\n length=settings.TOKEN_AUTH_USER_PASSWORD_LENGTH)\n\n user = User.objects.create_user(\n self.object.e_mail_plain, password, user_type=User.API_USER,\n customer=self.object.customer, provider=self.object.provider,\n groups=form.cleaned_data.get('groups', None))\n\n user.name_plain = 'API User'\n user.save()\n token = create_token(user, password)\n\n context = {\n 'username': user.e_mail_plain,\n 'token': token,\n }\n return render(self.request, 'provider_site/show_token.html', context)\n\n def get_breadcrumbs(self):\n return (\n (_('API Users'), reverse('provider_site:apiuser-list')),\n (_('API User Create'), ''), )\n\n def get_cancel_url(self):\n return reverse('provider_site:apiuser-list')\n\n\nclass APIUserUpdateForm(UserFormBase):\n class Meta(UserFormBase.Meta):\n fields = ('groups', 'is_active')\n\n\nclass APIUserUpdateView(NoCustomerMixin, generic_views.UpdateView):\n model = User\n template_name = 'provider_site/api_user_update_form.html'\n form_class = APIUserUpdateForm\n\n def get_success_url(self):\n return reverse('provider_site:apiuser-list')\n\n def get_cancel_url(self):\n return reverse('provider_site:apiuser-list')\n\n def form_valid(self, form):\n form.request = self.request\n form.save()\n return HttpResponseRedirect(self.get_success_url())\n\n def get_breadcrumbs(self):\n return (\n (_('API Users'), reverse('provider_site:apiuser-list')),\n (self.object, ''), )\n" }, { "alpha_fraction": 0.650231122970581, "alphanum_fraction": 0.6550248265266418, "avg_line_length": 22.45783042907715, "blob_id": "1f00ca201df9ee05dfafbb62b1da9c204265b4b6", "content_id": "591fa9720baa10584124cc678c364c262f233e25", "detected_licenses": [], "is_generated": false, "is_vendor": true, "language": "Python", "length_bytes": 5841, "license_type": "no_license", "max_line_length": 71, "num_lines": 249, "path": "/fabfile.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nfrom cStringIO import StringIO\n\nfrom fabric.api import cd\nfrom fabric.api import env\nfrom fabric.api import execute\nfrom fabric.api import get\nfrom fabric.api import local\nfrom fabric.api import parallel\nfrom fabric.api import put\nfrom fabric.api import roles\nfrom fabric.api import run\nfrom fabric.api import runs_once\nfrom fabric.api import serial\nfrom fabric.api import task\n\n\nenv.user = 'portal'\n\nenv.roledefs['web'] = [\n '{}.grid-manager.com'.format(name)\n for name in ('web1', 'web2', 'web3', 'web4', 'web5')\n]\nenv.roledefs['gas'] = ['gas.grid-manager.com']\nenv.roledefs['engine'] = ['engine.grid-manager.com']\n\nenv.roledefs['staging'] = ['192.168.0.150']\nenv.roledefs['experimental'] = ['experimental.grid-manager.com']\n#env.roledefs['production'] = ['[email protected]']\nenv.roledefs['production'] = ['[email protected]']\n\nSCRIPT_DIR = 'gridplatform/scripts/production_nordic'\n\n\n@runs_once\ndef get_version():\n return local('git describe --always', capture=True)\n\n\n@runs_once\ndef get_distfilename():\n return 'gridplatform-{}.tar.gz'.format(get_version())\n\n\n@runs_once\ndef build_distfile(distfilename):\n local('make {}'.format(distfilename))\n\n\n@parallel\n@roles('web', 'gas', 'engine')\ndef upload(distfilename):\n put(distfilename, distfilename)\n\n\ndef unpack(distfilename):\n run('rm -rf gridplatform.old')\n run('mv gridplatform gridplatform.old')\n run('tar xzf {}'.format(distfilename))\n\n\ndef pip_setup():\n run('source $HOME/ve/bin/activate && ' +\n 'pip install -r gridplatform/requirements/production.txt')\n\n\n@parallel\n@roles('web')\ndef stop_web():\n with cd(SCRIPT_DIR):\n run('./stop_celery.sh')\n run('./stop_uwsgi.sh')\n\n\n@parallel\n@roles('web')\ndef unpack_web(distfilename):\n execute(unpack, distfilename)\n\n\n@parallel\n@roles('web')\ndef setup_web():\n execute(pip_setup)\n with cd(SCRIPT_DIR):\n run('./manage.sh collectstatic --noinput')\n run('./manage.sh compress')\n\n\n@parallel\n@roles('web')\ndef start_web():\n with cd(SCRIPT_DIR):\n run('./start_celery.sh')\n run('./start_uwsgi.sh')\n\n\n@roles('engine')\ndef stop_engine():\n with cd(SCRIPT_DIR):\n run('./stop_reports.sh')\n run('killall python')\n\n\n@roles('engine')\ndef unpack_engine(distfilename):\n execute(unpack, distfilename)\n\n\n@roles('engine')\ndef setup_engine():\n execute(pip_setup)\n\n\n@roles('engine')\ndef start_engine():\n with cd(SCRIPT_DIR):\n run('./start_reports.sh')\n run('./manage.sh ruleengine')\n\n\n@roles('gas')\ndef stop_gas():\n run('gridplatform/gridagentserver/stop.sh')\n\n\n@roles('gas')\ndef unpack_gas(distfilename):\n execute(unpack, distfilename)\n\n\n@roles('gas')\ndef setup_gas():\n execute(pip_setup)\n run('source $HOME/ve/bin/activate && ' +\n 'pip install -r gridplatform/gridagentserver/requirements.txt')\n with cd(SCRIPT_DIR):\n run('./manage.sh syncdb --migrate')\n run('./manage.sh fix_contenttypes_and_permissions')\n\n\n@roles('gas')\ndef start_gas():\n run('export DJANGO_CONFIGURATION=Prod && ' +\n 'source $HOME/ve/bin/activate && ' +\n '$HOME/gridplatform/gridagentserver/start.sh')\n\n\n@task\n@serial\ndef deploy_nordic():\n \"\"\"\n Deploy to the GridManager Nordic cloud.\n \"\"\"\n distfilename = get_distfilename()\n execute(build_distfile, distfilename)\n execute(upload, distfilename)\n\n execute(stop_engine)\n execute(unpack_engine, distfilename)\n\n execute(stop_gas)\n execute(unpack_gas, distfilename)\n execute(setup_gas)\n execute(start_gas)\n\n execute(setup_engine)\n execute(start_engine)\n\n execute(stop_web)\n execute(unpack_web, distfilename)\n execute(setup_web)\n execute(start_web)\n\n\ndef deploy_singleserver():\n distfilename = get_distfilename()\n execute(build_distfile, distfilename)\n put(distfilename, distfilename)\n # stop\n with cd('gridplatform/scripts/production'):\n run('./stop_celery.sh', warn_only=True)\n run('./stop_uwsgi.sh', warn_only=True)\n run('./stop_reports.sh', warn_only=True)\n run('gridplatform/gridagentserver/stop.sh', warn_only=True)\n run('killall python', warn_only=True)\n # unpack\n execute(unpack, distfilename)\n # setup\n execute(pip_setup)\n run('source $HOME/ve/bin/activate && ' +\n 'pip install -r gridplatform/gridagentserver/requirements.txt')\n with cd('gridplatform/scripts/production'):\n run('./manage.sh syncdb --migrate')\n run('./manage.sh fix_contenttypes_and_permissions')\n run('./manage.sh collectstatic --noinput')\n run('./manage.sh compress')\n # start\n with cd('gridplatform/scripts/production'):\n run('./start_celery.sh')\n run('./start_uwsgi.sh')\n run('./start_reports.sh')\n run('./manage.sh ruleengine')\n run('export DJANGO_CONFIGURATION=Local && ' +\n 'source $HOME/ve/bin/activate && ' +\n '$HOME/gridplatform/gridagentserver/start.sh')\n\n\n@task\n@roles('staging')\ndef deploy_staging():\n execute(deploy_singleserver)\n\n\n@task\n@roles('experimental')\ndef deploy_experimental():\n execute(deploy_singleserver)\n\n\n@task\n@roles('production')\ndef deploy_production():\n execute(deploy_singleserver)\n\n\n@parallel\n@roles('web', 'gas', 'engine', 'staging', 'experimental', 'iberia')\ndef deployed_versions():\n data = StringIO()\n get('gridplatform/gridplatform/__init__.py', data)\n for line in data.getvalue().split('\\n'):\n if line.startswith('__version__'):\n version = line.split()[-1]\n return version\n return None\n\n\n@task\ndef check_versions():\n \"\"\"\n Check software versions currently deployed.\n \"\"\"\n versions = execute(deployed_versions)\n for host, version in sorted(versions.items()):\n print '{}: {}'.format(host, version)\n" }, { "alpha_fraction": 0.6304750442504883, "alphanum_fraction": 0.6310918927192688, "avg_line_length": 36.69767379760742, "blob_id": "5fa06efce1431e410486a36c42cd4e9548d0fc54", "content_id": "5246268dbc3f29d8e2e31a877dd9679e64ef8e3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1621, "license_type": "no_license", "max_line_length": 77, "num_lines": 43, "path": "/energymanager/price_relay_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.price_relay_site.views',\n url(r'^$',\n views.HomeView.as_view(),\n name='home'),\n url(r'^customer/(?P<customer_id>\\d+)/$',\n views.CustomerView.as_view(),\n name='customer'),\n url(r'^choose-customer/$',\n views.ChooseCustomer.as_view(),\n name='choose-customer'),\n url(r'^project/(?P<customer_id>\\d+)/$',\n views.PriceRelayProjectList.as_view(),\n name='price-relay-project-list'),\n url(r'^project/content/(?P<customer_id>\\d+)/$',\n views.PriceRelayProjectListContentView.as_view(),\n name='price-relay-project-list-content'),\n url(r'^project/create/(?P<customer_id>\\d+)/$',\n views.PriceRelayProjectCreateView.as_view(),\n name='price-relay-project-create'),\n url(r'^project/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.PriceRelayProjectUpdateView.as_view(),\n name='price-relay-project-update'),\n url(r'^(?P<customer_id>\\d+)/dashboard/$',\n views.PriceRelayProjectDashboardCustomerDetailView.as_view(),\n name='dashboard'),\n\n url(r'^project/(?P<customer_id>\\d+)/start/(?P<project_id>\\d+)/$', # noqa\n views.StartTariffHourlyLineChartView.as_view(),\n name='forecast-chart-start'),\n url(r'^project/(?P<customer_id>\\d+)/finalize/$',\n views.FinalizeTariffHourlyLineChartView.as_view(),\n name='forecast-chart-finalize'),\n)\n" }, { "alpha_fraction": 0.6381522417068481, "alphanum_fraction": 0.6449957489967346, "avg_line_length": 26.186046600341797, "blob_id": "d17df958a1a7eb1b8bde134b75c52db75ed977f0", "content_id": "c7d62ed2601d0dc2507ad0d54a89da4714cc6741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/gridplatform/bootstrap/templatetags/pagination.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom django.utils.encoding import iri_to_uri\n\n\nregister = template.Library()\n\nMAX_PAGE_CHOICES = 9\n\n\[email protected]_tag\ndef pagination_max_page_choices():\n return MAX_PAGE_CHOICES\n\n\[email protected]\ndef pagination_page_choices(paginator, page_obj):\n if paginator.num_pages < MAX_PAGE_CHOICES:\n return paginator.page_range\n\n first = page_obj.number - MAX_PAGE_CHOICES / 2\n last = page_obj.number + MAX_PAGE_CHOICES / 2\n if first < 1:\n first = 1\n last = MAX_PAGE_CHOICES + 1\n elif last > paginator.num_pages:\n first = paginator.num_pages - MAX_PAGE_CHOICES\n last = paginator.num_pages\n else:\n first -= 1\n return paginator.page_range[first:last]\n\n\[email protected]_tag(takes_context=True)\ndef page_url(context, n):\n request = context['request']\n query = [(k, v) for k, v in request.GET.iteritems() if k != 'page'] + \\\n [('page', n)]\n querystring = '&'.join(['%s=%s' % (k, v) for k, v in query])\n return '%s?%s' % (request.path, iri_to_uri(querystring))\n" }, { "alpha_fraction": 0.655572772026062, "alphanum_fraction": 0.6772446036338806, "avg_line_length": 24.33333396911621, "blob_id": "33c20ede91b9d90137dc7f0fb48236477f1e4d94", "content_id": "baf61b6ad3b58d141cd06d7ca8a0ec27dac18c6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 78, "num_lines": 51, "path": "/gridplatform/utils/paginator.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nPagination framework for resources grouped by date rather than\npages.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom rest_framework.exceptions import APIException\nfrom rest_framework import status\nfrom django.http import Http404\n\n\ndef parse_date(date_string):\n \"\"\"\n Parse date from a string.\n\n :param date_string: The string to parse.\n\n :see: :func:`.parse_date_or_404` for a version suitable for\n parsing date strings in URLs.\n \"\"\"\n if isinstance(date_string, datetime.date):\n return date_string\n else:\n return datetime.datetime.strptime(date_string, '%Y-%m-%d').date()\n\n\nclass Http404ApiException(Http404, APIException):\n \"\"\"\n Causes an HTTP 404 response for normal django views, and the same but with\n error detail message for REST views.\n \"\"\"\n status_code = status.HTTP_404_NOT_FOUND\n\n\ndef parse_date_or_404(date_string):\n \"\"\"\n Parse date from a string.\n\n :param date_string: The string to parse.\n\n :raise Http404ApiException: if no date could be parsed.\n \"\"\"\n try:\n return parse_date(date_string)\n except ValueError:\n raise Http404ApiException(\n detail='invalid date string \"%s\"' % date_string)\n" }, { "alpha_fraction": 0.643845796585083, "alphanum_fraction": 0.6440929174423218, "avg_line_length": 36.119266510009766, "blob_id": "6cba8fdc8999552aa8ad4d8052dc0c153750bf1a", "content_id": "4630e18418dffeae74b1a1ce2288e8dd85c88ff1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4046, "license_type": "no_license", "max_line_length": 78, "num_lines": 109, "path": "/gridplatform/productions/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom . import models\n\n\nclass Production(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set', many=True, read_only=True)\n hourly = serializers.SerializerMethodField('get_hourly')\n nonpulse_periods = serializers.HyperlinkedIdentityField(\n view_name='api:productions:nonpulseperiod-list')\n pulse_periods = serializers.HyperlinkedIdentityField(\n view_name='api:productions:pulseperiod-list')\n single_value_periods = serializers.HyperlinkedIdentityField(\n view_name='api:productions:singlevalueperiod-list')\n offlinetolerance = serializers.HyperlinkedIdentityField(\n view_name='api:productions:offlinetolerance-list')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.Production\n fields = (\n 'url', 'id', 'name', 'unit', 'display_unit', 'hourly', 'customer',\n 'periods', 'nonpulse_periods', 'single_value_periods',\n 'offlinetolerance')\n\n def __init__(self, *args, **kwargs):\n super(Production, self).__init__(*args, **kwargs)\n customer = self.context['request'].user.customer\n if customer:\n self.fields['unit'] = serializers.ChoiceField(\n choices=customer.get_production_unit_choices())\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:productions:production-hourly', kwargs={'pk': obj.id})\n\n def get_display_unit(self, obj):\n return obj.customer.get_production_unit_choices()[obj.unit]\n\n\nclass ProductionGroup(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n description = serializers.CharField(source='description_plain')\n hourly = serializers.SerializerMethodField('get_hourly')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.ProductionGroup\n fields = (\n 'url', 'id', 'customer', 'name', 'description',\n 'productions', 'unit', 'display_unit', 'hourly')\n\n def __init__(self, *args, **kwargs):\n super(ProductionGroup, self).__init__(*args, **kwargs)\n customer = self.context['request'].user.customer\n if customer:\n self.fields['unit'] = serializers.ChoiceField(\n choices=customer.get_production_unit_choices())\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:productions:productiongroup-hourly',\n args=[obj.id], request=self.context['request'])\n\n def get_display_unit(self, obj):\n return obj.customer.get_production_unit_choices()[obj.unit]\n\n\nclass NonpulsePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.NonpulsePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource')\n read_only_fields = ('datasequence',)\n\n\nclass PulsePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.PulsePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource', 'pulse_quantity', 'output_quantity', 'output_unit')\n read_only_fields = ('datasequence',)\n\n\nclass SingleValuePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.SingleValuePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'value', 'unit')\n read_only_fields = ('datasequence',)\n\n\nclass OfflineTolerance(serializers.DefaultSerializer):\n class Meta:\n model = models.OfflineTolerance\n fields = ('url', 'id', 'hours', 'datasequence')\n read_only_fields = ('datasequence',)\n" }, { "alpha_fraction": 0.6549575328826904, "alphanum_fraction": 0.6555240750312805, "avg_line_length": 37.369564056396484, "blob_id": "6909218240484c7a975f845270fd2fb0a64d4683", "content_id": "21a70d6a2610813eeefa79a7276e686e20791287", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1765, "license_type": "no_license", "max_line_length": 76, "num_lines": 46, "path": "/legacy/display_projects/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom . import views\n\n\nurlpatterns = patterns(\n '',\n url('^$',\n views.BenchmarkProjectIndexView.as_view(),\n name='display_projects-index'),\n url('^(?P<pk>\\d+)/$',\n views.BenchmarkProjectDetailView.as_view(),\n name='display_projects-details'),\n url('^update/(?P<pk>\\d+)/$',\n views.benchmarkproject_update,\n name='display_projects-update'),\n url('^update/(?P<pk>\\d+)/normal/$',\n views.BenchmarkProjectUpdateView.as_view(),\n name='display_projects-update_normal'),\n url('^update/(?P<pk>\\d+)/water/$',\n views.WaterBenchmarkProjectUpdateView.as_view(),\n name='display_projects-update_water'),\n url('^create/(?P<utility_type>(electricity|gas|district_heating|oil))$',\n views.BenchmarkProjectCreateView.as_view(),\n name='display_projects-create'),\n url('^create/(?P<utility_type>(water))$',\n views.WaterBenchmarkProjectCreateView.as_view(),\n name='display_projects-create_water'),\n url('^delete/(?P<pk>\\d+)/$',\n views.BenchmarkProjectDeleteView.as_view(),\n name='display_projects-delete'),\n url('^request_project_report/$',\n views.StartProjectReportView.as_view(),\n name='display_projects-startprojectreport'),\n url('^finalize_project_report/$',\n views.FinalizeProjectReportView.as_view(),\n name='display_projects-finalizeprojectreport'),\n url('^annual_savings_potential_form/$',\n views.AnnualSavingsPotentialReportGenerationFormView.as_view(),\n name='display_projects-annualsavingspotentialreportform'),\n)\n" }, { "alpha_fraction": 0.6195122003555298, "alphanum_fraction": 0.6487804651260376, "avg_line_length": 33.16666793823242, "blob_id": "0a721a9a2b72368392d137c83c74d1993e353bca", "content_id": "7bcb6d601f9bf4dc3988ec4357282133e3e82242", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 205, "license_type": "no_license", "max_line_length": 113, "num_lines": 6, "path": "/rabbitmq-check.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nmax_messages_per_queue=100\n\nsudo rabbitmqctl -q list_queues name messages | \\\n awk \"{ if (\\$2 > $max_messages_per_queue) print \\\"RabbitMQ ERROR: To many messages (\\\"\\$2\\\") in queue \\\"\\$1}\"\n" }, { "alpha_fraction": 0.7163068056106567, "alphanum_fraction": 0.7170513868331909, "avg_line_length": 30.9761905670166, "blob_id": "6c224c68215bc677549ee5edfb930e393b278e00", "content_id": "5d11231cdd37129ae0778fb762cbc43b7c063186", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 70, "num_lines": 42, "path": "/gridplatform/utils/contextmanagers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom contextlib import contextmanager\n\nfrom gridplatform.encryption import _store as encryption_store\nfrom gridplatform.trackuser import _store as trackuser_store\n\n\n@contextmanager\ndef global_context(user=None, customer=None, encryption=None):\n \"\"\"\n Context manager for global context.\n\n :keyword user: The :class:`~gridplatform.users.models.User` to use\n inside the context.\n\n :keyword customer: The\n :class:`~gridplatform.customers.models.Customer` to use inside\n the context.\n\n :keyword encryption: The encryption context to use inside the\n context.\n\n :see: :func:`gridplatform.trackuser.get_user`,\n :func:`gridplatform.trackuser.get_customer` and\n :func:`gridplatform.encryption.get_encryption_context`.\n \"\"\"\n # save old values\n old_encryption = encryption_store.encryption_context\n old_user = trackuser_store.user\n old_customer = trackuser_store.customer\n # set new\n encryption_store.encryption_context = encryption\n trackuser_store.user = user\n trackuser_store.customer = customer\n yield\n # restore old\n encryption_store.encryption_context = old_encryption\n trackuser_store.user = old_user\n trackuser_store.customer = old_customer\n" }, { "alpha_fraction": 0.6886363625526428, "alphanum_fraction": 0.6909090876579285, "avg_line_length": 24.882352828979492, "blob_id": "80649433d1338060d180eae07df3c17debde1268", "content_id": "53d0f8a776e989b2d0469a3527ede14fab222bd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 76, "num_lines": 17, "path": "/energymanager/start_site/context_processors.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.trackuser import get_user\n\nfrom .views import applist\n\n\ndef app_selection(request):\n \"\"\"\n Provide template context variable app_selection to make the list of apps\n that the current user has access to avaiable in all templates.\n \"\"\"\n return {\n 'app_selection': applist(request, get_user()),\n }\n" }, { "alpha_fraction": 0.586746871471405, "alphanum_fraction": 0.5960103273391724, "avg_line_length": 36.45437240600586, "blob_id": "19f541a62a99b0daebb192b6897cc1bf70aca35a", "content_id": "d62b83b4d41ba9dd190d10e7bfa2594145cc8e10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39402, "license_type": "no_license", "max_line_length": 79, "num_lines": 1052, "path": "/legacy/indexes/models/index.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nDjango model for indexes.\n\nAn index maps points in time to numeric values, such as dkr/kWh.\nThese are implemented in a L{Index} Django model and L{Entry} Django\nmodel, where each L{Entry} belongs to an L{Index}.\n\nThroughout this module, the term tariff will be used to abstractly\ndescribe that which define the charges (pr unit cost) under certain\ncircumstances, say the price for a kWh within a given time period.\n\"\"\"\n\nfrom decimal import Decimal\nfrom fractions import Fraction\nimport datetime\nimport itertools\nimport operator\n\nfrom django.db import models\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ungettext_lazy\nfrom django.core.exceptions import ValidationError\n\nfrom timezones2.models import TimeZoneField\n\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.utils.fields import BuckinghamField\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import CostCalculation\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import DegreeDayCorrection\nfrom legacy.measurementpoints.models import Utilization\nfrom legacy.measurementpoints.models.dataseries import UndefinedSamples\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.trackuser import get_timezone\n\nfrom .period import normalize_periods\n\n\nclass IndexUpdateError(Exception):\n pass\n\n\nclass Index(DataSeries, EncryptedModel):\n \"\"\"\n An index maps points in time to values.\n\n @ivar unit: A short string describing the unit, say \"dkr/kWh\".\n\n @ivar name: A less short string naming the index, say \"NOE\n el-priser\" This field is encrypted.\n\n @ivar name_plain: The unencrypted version of the C{name} member.\n\n @ivar _cached_entries: A list holding a cache of entries\n retrieved from the database using L{generate_cached_entries()}\n \"\"\"\n SPOT = 0\n SEASONS = 1\n DERIVED = 2\n STANDARD_MONTH_INDEX = 3\n DATASOURCEADAPTER = 4\n\n DATA_FORMAT_CHOICES = (\n (SPOT, _('Spot data')),\n (SEASONS, _('Season data')),\n (DERIVED, _('Derived data')),\n (STANDARD_MONTH_INDEX, _('Monthly defined data')),\n (DATASOURCEADAPTER, _('Data source adapter')),\n )\n\n name = EncryptedCharField(max_length=100, verbose_name=_('name'))\n\n data_format = models.IntegerField(\n _('Entry data format'),\n choices=DATA_FORMAT_CHOICES,\n help_text=_(\"\"\"\n <p><b>Spot data:</b> Entry data is stored as\n concrete time intervals mapped to constant entry\n data values.</p>\n\n <p><b>Season data:</b> Entry data is stored in\n seasons, where each season is defined in terms\n repeating the entry data values of one day. The\n entry data values of that day is stored as time\n intervals mapped to constant entry data\n values.</p>\n\n <p><b>Derived data:</b> Entry data is not stored\n directly, but rather derived from the entry data\n of another index by multiplying with a coefficient\n and adding a constant, where the coefficient and\n constant may be defined differently for different\n concrete periods of time.</p>\n \"\"\"))\n\n collection = models.ForeignKey(\n Collection, on_delete=models.PROTECT,\n blank=True, null=True, verbose_name=_('group'),\n limit_choices_to={'role': Collection.GROUP})\n\n timezone = TimeZoneField(verbose_name=_('timezone'),\n default=get_timezone, blank=False)\n\n class Meta:\n verbose_name = _('index')\n verbose_name_plural = _('indexes')\n app_label = 'indexes'\n # inherit ordering from DataSeries\n\n @virtual\n def __unicode__(self):\n \"\"\"\n @return: Return the decrypted name of the index if the index\n is owned by a customer, or the translated public name of the\n index otherwise\n \"\"\"\n can_be_translated = self.name == self.name_plain\n\n if can_be_translated:\n name = _(self.name_plain)\n else:\n name = self.name_plain or self.name\n\n return _('{name} ({unit})').format(\n name=name,\n unit=self.get_preferred_unit_converter().get_display_unit())\n\n @models.permalink\n def get_absolute_url(self):\n if self.data_format == self.SEASONS:\n return (\n 'manage_indexes-seasons-index-update-view', (),\n {'pk': str(self.id)})\n elif self.data_format == self.DERIVED:\n return (\n 'manage_indexes-derived-index-update-view', (),\n {'pk': str(self.id)})\n raise IndexUpdateError('%r cannot be updated.' % self)\n\n def can_be_updated(self):\n try:\n self.get_absolute_url()\n except IndexUpdateError:\n return False\n else:\n return True\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Construct a new L{Index}.\n \"\"\"\n self._cached_entries = None\n super(Index, self).__init__(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n if self.customer_id is None:\n self._exclude_field_from_validation = ['name']\n super(Index, self).save(*args, **kwargs)\n\n def get_delete_prevention_reason(self):\n \"\"\"\n Returns a HTML formated string with a description of why\n this index cannot be deleted.\n Returning None, if no reason exist, meaning the index can\n be deleted without breaking anything.\n \"\"\"\n utilization = Utilization.objects.filter(\n needs=self)\n\n cost = CostCalculation.objects.filter(\n index__chain__links__data_series=self)\n\n degree_days = DegreeDayCorrection.objects.filter(\n standarddegreedays=self)\n\n num_dependencies = len(utilization) + len(cost) + len(degree_days)\n\n if num_dependencies == 0:\n return None\n\n mp_string = \"<ul>\"\n for util in itertools.chain(utilization, cost, degree_days):\n collection_name = util.consumption.graph.collection.name_plain\n mp_string += \"<li>%s</li>\" % escape(collection_name)\n mp_string += \"</ul>\"\n\n return ungettext_lazy(\n 'This index cannot be deleted because the following '\n 'depends on it: <br> {measurement_points_list}',\n 'This index cannot be deleted because the following '\n 'depend on it: <br> {measurement_points_list}',\n num_dependencies).format(measurement_points_list=mp_string)\n\n def is_deletable(self):\n \"\"\"\n Returns true or false whether\n this index can be deleted or not.\n \"\"\"\n # Get indexes used for utilization\n utilization = Utilization.objects.filter(needs=self)\n\n # Get indexes used for tariffs\n cost = CostCalculation.objects.filter(\n index__chain__links__data_series=self)\n\n # Get indexes used for standard heating degree\n degree_days = DegreeDayCorrection.objects.filter(\n standarddegreedays=self)\n\n if len(cost) == 0 and len(utilization) == 0 and len(degree_days) == 0:\n return True\n return False\n\n def generate_cached_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Use this method rather than _iterate_entries() to minimize the\n number of database queries.\n \"\"\"\n entry_generator = {\n Index.SPOT: self._iterate_entries,\n Index.SEASONS: self._generate_period_entries,\n Index.DERIVED: self._generate_period_entries}[self.data_format]\n\n if not self._cached_entries:\n self._cached_entries = list(\n entry_generator(from_timestamp, to_timestamp))\n elif self._cached_entries[0].from_timestamp > from_timestamp or \\\n to_timestamp > self._cached_entries[-1].to_timestamp:\n self._cached_entries = list(\n entry_generator(\n min(self._cached_entries[0].from_timestamp,\n from_timestamp),\n max(self._cached_entries[-1].to_timestamp, to_timestamp)))\n\n for entry in self._cached_entries:\n if entry and entry.from_timestamp < to_timestamp \\\n and entry.to_timestamp > from_timestamp:\n yield entry\n\n def _generate_period_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Generate entries for season or derived periods within a given\n time interval.\n\n @param from_timestamp: The beginning of the interval.\n\n @param to_timestamp: The end of the interval.\n\n @invariant: All entries C{e} yielded, the interval C{[t,t']}\n of C{e} will overlap C{[from_timestamp, to_timestamp)}.\n \"\"\"\n def assert_invariant(entry):\n assert(entry.from_timestamp < to_timestamp)\n assert(entry.to_timestamp > from_timestamp)\n\n if self.data_format == Index.SEASONS:\n period_set = self.seasonindexperiod_set\n else:\n assert(self.data_format == Index.DERIVED)\n period_set = self.derivedindexperiod_set\n\n head_period = period_set.filter(\n from_date__lte=from_timestamp.date()).order_by(\"-from_date\")[:1]\n tail_periods = period_set.filter(\n from_date__lte=to_timestamp.date(),\n from_date__gt=from_timestamp.date()).order_by(\"from_date\")\n\n # Initial condition: The first interval yielded will start at\n # from_timestamp.\n #\n # Terminal condition: The final interval yielded will end at\n # to_timestamp\n #\n # Loop variant: The _from_time of any subsequently yielded\n # period equals the _to_time of the previously yielded period.\n def iterate_periods():\n _from_time = from_timestamp\n _to_time = None\n _period = None\n for p in head_period:\n _period = p\n for p in tail_periods:\n _to_time = p.from_timestamp()\n if _from_time != _to_time:\n # don't yield empty period\n assert _from_time < _to_time, '%s %s' % (\n _from_time, _to_time)\n # yield the previous period, as the current period\n # defines the end of that.\n yield (_period, _from_time, _to_time)\n _period = p\n _from_time = _to_time\n _to_time = to_timestamp\n # yield the final period, as no subsequent period define\n # the end of that.\n if _period:\n yield (_period, _from_time, _to_time)\n\n for period, from_time_, to_time_ in iterate_periods():\n if period:\n for entry in period.generate_entries(from_time_, to_time_):\n assert_invariant(entry)\n yield entry\n\n def _iterate_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Iterate over entries covering a given interval.\n\n This method will make sure that the entire interval is\n covered, but the entries yielded may be phony (covering for\n missing entries).\n\n @param from_timestamp: The beginning of the interval covered by the\n yielded entries.\n\n @param to_timestamp: The end of the interval covered by the yielded\n entries.\n\n @invariant: For each yielded entry C{e}, the set union of\n C{[e.from_timestamp; e.to_timestamp)} and C{[from_timestamp;\n to_timestamp)} is not empty.\n\n @precondition: You can only iterate entries for spot indexes:\n C{self.data_format == Index.SPOT}\n \"\"\"\n def assert_invariant(e):\n assert e.from_timestamp <= e.to_timestamp, \\\n 'e.from_timestamp=%r, e.to_timestamp=%r' % (\n e.from_timestamp, e.to_timestamp)\n assert e.from_timestamp < to_timestamp, \\\n 'e.from_timestamp=%r, to_timestamp=%r' % (\n e.from_timestamp, to_timestamp)\n assert from_timestamp < e.to_timestamp, \\\n 'from_timestamp=%r, e.to_timestamp=%r' % (\n from_timestamp, e.to_timestamp)\n assert e.value is not None, \\\n 'e.from_timestamp=%r, e.to_timestamp=%r. Value was None.' % (\n e.from_timestamp, e.to_timestamp)\n\n assert(self.data_format == Index.SPOT)\n\n assert(to_timestamp.tzinfo is not None)\n assert(from_timestamp is not None)\n assert(from_timestamp.tzinfo is not None)\n\n entries = self.entry_set.filter(\n from_timestamp__lt=to_timestamp,\n to_timestamp__gt=from_timestamp).order_by(\"from_timestamp\")\n\n for e in entries:\n assert_invariant(e)\n yield e\n\n def minimize_noncontiguous(self, from_timestamp, to_timestamp, duration):\n \"\"\"\n Generate a list of periods, within an interval, with a given\n combined duration that minimize the underlying index values.\n\n @param from_timestamp: The start of the interval, containing the\n resulting periods.\n\n @param to_timestamp: The end of the interval, containing the\n resulting periods.\n\n @param duration: The combined duration of the resulting\n periods.\n\n @return: A list of normalized periods. See also\n L{normalize_periods()}. If insufficient entries are available, the\n result will be extended with the earliest untaken periods to cover the\n entire C{duration}.\n\n @precondition: C{duration} must fit between C{from_timestamp} and\n C{to_timestamp}.\n\n @postcondition: The entire duration is covered\n \"\"\"\n assert(from_timestamp + duration <= to_timestamp)\n\n # The algorithm of this method consists of two steps:\n #\n #\n # 1) Ensure RangedSamples cover the entire [from_timestamp,\n # to_timestamp] interval.\n #\n # 2) Allocate the cheapest subintervals that combined add up to\n # duration.\n\n ZERO = PhysicalQuantity(0, self.unit)\n\n # Patch holes in samples with extra_samples\n samples = list(self.get_samples(from_timestamp, to_timestamp))\n if not samples:\n # one big hole.\n extra_samples = [\n self.create_range_sample(from_timestamp, to_timestamp, ZERO)]\n else:\n extra_samples = []\n if samples[0].from_timestamp > from_timestamp:\n # patch hole in front of samples\n extra_samples.append(\n self.create_range_sample(\n from_timestamp, samples[0].from_timestamp, ZERO))\n\n for s1, s2 in pairwise(samples):\n if s1.to_timestamp != s2.from_timestamp:\n # patch holes between samples\n assert s1.to_timestamp < s2.from_timestamp\n extra_samples.append(\n self.create_range_sample(\n s1.to_timestamp, s2.from_timestamp, ZERO))\n\n if samples[-1].to_timestamp < to_timestamp:\n # patch hole after samples\n extra_samples.append(\n self.create_range_sample(\n samples[-1].to_timestamp, to_timestamp, ZERO))\n\n # Sort samples in ascending order according to their values to allocate\n # the cheapest subintervals that combined add up to duration.\n minimized_periods = []\n remaining_duration = duration\n\n sorted_samples = itertools.chain(\n sorted(samples, key=operator.attrgetter('physical_quantity')),\n extra_samples)\n\n for sample in sorted_samples:\n new_from_time = max(sample.from_timestamp, from_timestamp)\n new_to_time = min(sample.to_timestamp, to_timestamp)\n\n if remaining_duration <= new_to_time - new_from_time:\n minimized_periods.append(\n (new_from_time,\n new_from_time + remaining_duration))\n remaining_duration = datetime.timedelta()\n break\n else:\n minimized_periods.append((new_from_time, new_to_time))\n remaining_duration -= (new_to_time - new_from_time)\n\n # allocated intervals must add up to duration.\n assert not remaining_duration\n return normalize_periods(minimized_periods)\n\n def calculate_average_value(self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate average value between two points in time.\n \"\"\"\n result = PhysicalQuantity(0, self.unit)\n total_duration = PhysicalQuantity(\n Fraction((to_timestamp - from_timestamp).total_seconds()),\n 'second')\n for sample in self.get_samples(from_timestamp, to_timestamp):\n sample_duration = PhysicalQuantity(\n Fraction(\n (sample.to_timestamp - sample.from_timestamp).\n total_seconds()), 'second')\n\n result += sample.physical_quantity * sample_duration / \\\n total_duration\n\n return result\n\n def minimize_contiguous(self, from_timestamp, to_timestamp, duration):\n \"\"\"\n Minimize contiguous usage in a given interval.\n\n @param from_timestamp: The start of the interval.\n\n @param to_timestamp: The end of the interval.\n\n @param duration: The duration of the contiguous usage.\n\n @return: Returns the start of the contiguous usage with\n minimized cost.\n \"\"\"\n assert(to_timestamp - from_timestamp >= duration)\n\n # Overall approach: intervals starting at the start of an\n # entry or ending at the end of an entry are interesting\n # candidates. Apart from that, starting at from_timestamp or\n # ending at to_timestamp are also candidates.\n candidates = {from_timestamp, to_timestamp - duration}\n\n for sample in self.get_samples(from_timestamp, to_timestamp):\n # Potential candidate: Start at this samples from_timestamp.\n if from_timestamp <= sample.from_timestamp <= \\\n to_timestamp - duration:\n candidates.add(sample.from_timestamp)\n\n # Potential candidate: Stop at this samples to_timestamp.\n if from_timestamp + duration <= sample.to_timestamp <= \\\n to_timestamp:\n candidates.add(sample.to_timestamp - duration)\n\n # Return the candidate with the minimum cost\n return min([(\n candidate,\n self.calculate_average_value(\n candidate, candidate + duration).\n convert(self.unit))\n for candidate in candidates], key=lambda e: e[1])[0]\n\n def generate_true_periods(self, from_timestamp, to_timestamp, predicate):\n \"\"\"\n Generate a list of disjunctive periods within a given interval\n where the L{Entry.value} checked with a C{predicate} evaluates\n to C{True}.\n\n @param from_timestamp: The start of the given interval.\n\n @param to_timestamp: The end of the given interval.\n\n @param predicate: A predicate function that takes a C{Decimal} as\n argument and returns a C{bool}.\n\n @return: Returns a list of nonoverlapping distinct periods in\n the form of tuples where the first element is a\n C{datetime.datetime} marking the start of the period, and the\n second element is a C{datetime.datetime} marking the end of\n the period. For instance::\n\n index.generate_true_periods(\n datetime.datetime(2011, 2, 1, 4),\n datetime.datetime(2011, 2, 1, 9),\n lambda x: x <= Decimal(\"0.32\"))\n\n will return a list of periods C{(from_timestamp, to_timestamp)} all\n somewhere between 4am and 9am on February 1st, 2011, in which\n the underlying value is less than or equal to C{0.32}.\n \"\"\"\n assert(isinstance(from_timestamp, datetime.datetime))\n assert(isinstance(to_timestamp, datetime.datetime))\n assert(from_timestamp <= to_timestamp)\n\n return [(max(period_from_time, from_timestamp),\n min(period_to_time, to_timestamp))\n for period_from_time, period_to_time in\n normalize_periods([\n (sample.from_timestamp, sample.to_timestamp)\n for sample in self.get_samples(\n from_timestamp, to_timestamp)\n if predicate(sample.physical_quantity)])]\n\n def satisfies_search(self, substring):\n \"\"\"\n Check if this C{Index} matches a search in the form of a\n substring.\n\n @param substring: The substring to match against this\n C{Index}.\n\n @return: Return C{True} if this C{Index} matches C{substring},\n C{False} otherwise.\n \"\"\"\n return substring.lower() in self.name.lower()\n\n def _encrypt(self, request):\n \"\"\"\n Encrypt L{EncryptedField}s of this L{Index} unless\n C{self.customer} is None, in which case we just store the\n plain text values as encrypted fields.\n\n @param request: The request used for encryption.\n \"\"\"\n if self.customer_id:\n super(Index, self)._encrypt(request)\n else:\n self._name_ciphertext = self.name_plain\n\n def _decrypt(self, request):\n \"\"\"\n Decrypt L{EncryptedField}s of this L{Index} unless\n C{self.customer} is None, in which case we just recover the\n plain text values directly from the encrypted fields.\n\n @param request: The request used for decryption.\n \"\"\"\n if self.customer_id:\n super(Index, self)._decrypt(request)\n else:\n self._name_plaintext = self.name\n\n def get_derivatives(self):\n \"\"\"\n Method for recursively getting C{Index}es derived from this\n C{Index}.\n\n @return: Return a list of C{Index}es derived from this\n C{Index}.\n \"\"\"\n result = [self]\n for p in self.period_derivative_set.all():\n result += p.index.get_derivatives()\n return result\n\n @virtual\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Override of L{DataSeries}.\n\n This override return entries converted to piecewise constant rate\n samples.\n \"\"\"\n values = [\n self.create_range_sample(\n max(from_timestamp, entry.from_timestamp),\n min(to_timestamp, entry.to_timestamp),\n PhysicalQuantity(entry.value, self.unit))\n for entry in self.generate_cached_entries(\n from_timestamp, to_timestamp)\n if entry.value is not None]\n\n return sorted(values, key=lambda x: x.from_timestamp)\n\n def _condense_data_samples_recursive(self, from_timestamp,\n sample_resolution, to_timestamp=None):\n raise UndefinedSamples()\n\n def get_icon(self):\n \"\"\"\n Returns icon string for this C{Index}\n \"\"\"\n if self.role in (DataRoleField.CO2, DataRoleField.CO2_QUOTIENT):\n return 'co2'\n elif self.role == DataRoleField.EMPLOYEES:\n return 'human'\n elif self.role == DataRoleField.AREA:\n return 'area'\n elif self.utility_type == utilitytypes.METER_CHOICES.electricity:\n return 'electricity'\n elif self.utility_type == utilitytypes.METER_CHOICES.water:\n return 'water'\n elif self.utility_type == utilitytypes.METER_CHOICES.gas:\n return 'gas'\n elif self.utility_type == utilitytypes.METER_CHOICES.district_heating:\n return 'heat'\n elif self.utility_type == utilitytypes.METER_CHOICES.oil:\n return 'oil'\n else:\n return None\n\n @virtual\n def get_preferred_unit_converter(self):\n \"\"\"\n Get preferred unit converter.\n\n Override of L{DataSeries.get_preferred_unit_converter()} because\n C{Index}es usually do not require conversion, and in particular\n customer may not be set on C{Index}es.\n \"\"\"\n return PhysicalUnitConverter(self.unit)\n\n\nclass Entry(models.Model):\n \"\"\"\n An C{Entry} holds a constant index value within a given\n C{datetime} interval.\n\n @ivar index: The L{Index} that this entry belongs to.\n\n @ivar from_timestamp: The start of the interval.\n\n @ivar to_timestamp: The end of the interval.\n\n @ivar value: The value held by the index in this interval.\n \"\"\"\n index = models.ForeignKey(Index, on_delete=models.CASCADE)\n from_timestamp = models.DateTimeField()\n to_timestamp = models.DateTimeField()\n value = models.DecimalField(decimal_places=5,\n max_digits=10)\n\n class Meta:\n verbose_name = _('entry')\n verbose_name_plural = _('entries')\n ordering = ['from_timestamp']\n app_label = 'indexes'\n unique_together = (\n ('index', 'from_timestamp'),\n ('index', 'to_timestamp'))\n\n def __unicode__(self):\n if self.index_id:\n return u'%s: %s -- %s: %s' % (\n self.index, self.from_timestamp, self.to_timestamp, self.value)\n else:\n return u'%s -- %s: %s' % (\n self.from_timestamp, self.to_timestamp, self.value)\n\n def save(self, *args, **kwargs):\n assert self.from_timestamp < self.to_timestamp\n super(Entry, self).save(*args, **kwargs)\n\n\nclass Period(models.Model):\n \"\"\"\n A C{Period} defines index values within a given date interval.\n The C{Period} class is abstract, see L{SeasonIndexPeriod} and\n L{DerivedIndexPeriod} for concrete classes.\n\n @ivar index: The Index that this C{Period} defines a\n period for.\n\n @ivar from_date: The date at which the period defined by this\n C{Period} starts.\n \"\"\"\n index = models.ForeignKey(Index, on_delete=models.CASCADE)\n from_date = models.DateField()\n\n class Meta(object):\n abstract = True\n verbose_name = _('period')\n verbose_name_plural = _('periods')\n ordering = ['from_date']\n app_label = 'indexes'\n\n def from_timestamp(self):\n \"\"\"\n Return when this period starts.\n\n @return: Returns a C{datetime.datetime} indicating when this\n period starts.\n \"\"\"\n return self.index.timezone.localize(\n datetime.datetime.combine(\n self.from_date,\n datetime.time()))\n\n def generate_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Generate entries.\n\n @param from_timestamp: The start of the interval.\n\n @param to_timestamp: The end of the interval.\n\n @precondition: C{from_timestamp >= self.from_timestamp()}\n\n @invariant: All entries C{e} yielded, the interval C{[t,t']}\n of C{e} will overlap C{[from_timestamp, to_timestamp)}.\n \"\"\"\n raise NotImplementedError(\n \"Specializations of this class must implement this method.\")\n\n\nclass DerivedIndexPeriod(Period):\n \"\"\"\n A C{DerivedIndexPeriod} define the tariff of an index within a\n certain period. The defined tariff is on the form C{y = ax + b},\n where C{y} is the defined tariff, C{a} is a coefficient, C{x}\n represent the tariff of another index and C{b} is a constant.\n There is also an optional C{roof}, so that if C{y} becomes larger\n than this C{roof}, the C{roof} is used instead.\n\n @ivar other_index: The index defining C{x}.\n\n @ivar coefficient: The coefficient defining C{a}.\n\n @ivar constant: The constant defining C{b}.\n\n @ivar roof: The optional roof, defining C{roof}\n \"\"\"\n other_index = models.ForeignKey(Index, on_delete=models.PROTECT,\n related_name='period_derivative_set')\n\n coefficient = models.DecimalField(decimal_places=5,\n max_digits=10,\n default=Decimal(\"1.000\"))\n constant = models.DecimalField(decimal_places=5,\n max_digits=10,\n default=Decimal(\"0.000\"))\n\n roof = models.DecimalField(decimal_places=5,\n max_digits=10,\n null=True,\n blank=True,\n default=None)\n\n class Meta(Period.Meta):\n verbose_name = _('derived index period')\n verbose_name_plural = _('derived index periods')\n app_label = 'indexes'\n # inherit ordering from Period\n\n def clean(self):\n super(DerivedIndexPeriod, self).clean()\n try:\n other_index = self.other_index\n index = self.index\n except Index.DoesNotExist:\n pass\n else:\n if other_index.utility_type != index.utility_type:\n raise ValidationError(_('Utility types must match'))\n if not PhysicalQuantity.compatible_units(other_index.unit,\n index.unit):\n raise ValidationError(_('Units must be compatible'))\n if other_index in index.get_derivatives():\n raise ValidationError(\n _('Other index is defined in terms of this index'))\n\n def generate_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Generate entries.\n\n @param from_timestamp: The start of the interval.\n\n @param to_timestamp: The end of the interval.\n\n @precondition: C{from_timestamp >= self.from_timestamp()}\n\n @invariant: All entries C{e} yielded, the interval C{[t,t']}\n of C{e} will overlap C{[from_timestamp, to_timestamp)}.\n \"\"\"\n def assert_invariant(entry):\n assert(entry.from_timestamp < to_timestamp)\n assert(entry.to_timestamp > from_timestamp)\n\n assert(from_timestamp >= self.from_timestamp())\n\n for sample in self.other_index._get_samples(\n from_timestamp, to_timestamp):\n value = self.coefficient * sample.physical_quantity + \\\n PhysicalQuantity(self.constant, self.index.unit)\n if self.roof is not None:\n value = min(\n value, PhysicalQuantity(self.roof, self.index.unit))\n e = Entry(value=value.convert(self.index.unit),\n from_timestamp=max(\n sample.from_timestamp, from_timestamp),\n to_timestamp=min(sample.to_timestamp, to_timestamp))\n assert_invariant(e)\n yield e\n\n\nclass SeasonIndexPeriod(Period):\n \"\"\"\n A C{SeasonIndexPeriod} define the tariff of an index within a\n certain period by repeating the entries of a 24 hour day.\n\n The hourly entries are stored in C{[value_at_hour_0, ...,\n value_at_hour_23]}, where for example C{value_at_hour_0} contains\n the value at hour 0:00-1:00 in the timezone of the owning\n L{Index}. Use the L{get_value_at_hour()} method to retrieve the\n values given an integer hour, time object or datetime object.\n \"\"\"\n value_at_hour_0 = models.DecimalField(\n _('value between midnight and 1:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_1 = models.DecimalField(\n _('value between 1:00 am and 2:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_2 = models.DecimalField(\n _('value between 2:00 am and 3:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_3 = models.DecimalField(\n _('value between 3:00 am and 4:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_4 = models.DecimalField(\n _('value between 4:00 am and 5:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_5 = models.DecimalField(\n _('value between 5:00 am and 6:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_6 = models.DecimalField(\n _('value between 6:00 am and 7:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_7 = models.DecimalField(\n _('value between 7:00 am and 8:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_8 = models.DecimalField(\n _('value between 8:00 am and 9:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_9 = models.DecimalField(\n _('value between 9:00 am and 10:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_10 = models.DecimalField(\n _('value between 10:00 am and 11:00 am'),\n decimal_places=5, max_digits=10)\n value_at_hour_11 = models.DecimalField(\n _('value between 11:00 am and noon'),\n decimal_places=5, max_digits=10)\n value_at_hour_12 = models.DecimalField(\n _('value between noon am and 1:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_13 = models.DecimalField(\n _('value between 1:00 pm and 2:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_14 = models.DecimalField(\n _('value between 2:00 pm and 3:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_15 = models.DecimalField(\n _('value between 3:00 pm and 4:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_16 = models.DecimalField(\n _('value between 4:00 pm and 5:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_17 = models.DecimalField(\n _('value between 5:00 pm and 6:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_18 = models.DecimalField(\n _('value between 6:00 pm and 7:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_19 = models.DecimalField(\n _('value between 7:00 pm and 8:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_20 = models.DecimalField(\n _('value between 8:00 pm and 9:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_21 = models.DecimalField(\n _('value between 9:00 pm and 10:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_22 = models.DecimalField(\n _('value between 10:00 pm and 11:00 pm'),\n decimal_places=5, max_digits=10)\n value_at_hour_23 = models.DecimalField(\n _('value between 11:00 pm and midnight'),\n decimal_places=5, max_digits=10)\n\n class Meta:\n verbose_name = _('season index period')\n verbose_name_plural = _('season index periods')\n app_label = 'indexes'\n # inherit ordering from Period\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Construct a new L{SeasonIndexPeriod}.\n\n @param args: Arguments forwarded to C{super(SeasonIndexPeriod,\n self)}\n\n @param kwargs: Arguments forwarded to\n C{super(SeasonIndexPeriod, self)}, except that the keyword\n C{value_at_hour} will be transformed into the corresponding\n C{value_at_hour_1},...C{value_at_hour_23} keywords\n \"\"\"\n if \"value_at_hour\" in kwargs:\n assert(len(kwargs[\"value_at_hour\"]) == 24)\n for i in range(24):\n kwargs[\"value_at_hour_%d\" % i] = kwargs[\"value_at_hour\"][i]\n del kwargs[\"value_at_hour\"]\n\n super(SeasonIndexPeriod, self).__init__(*args, **kwargs)\n\n def get_value_at_hour(self, key):\n \"\"\"\n Get value at a given hour.\n\n @param key: The given hour: this may be an integer in the\n range C{[0, 23]}, or a datetime.datetime in which case the\n corresponding hour of the timezone of this index is used.\n\n @return: Returns the value at the given hour.\n \"\"\"\n if isinstance(key, datetime.datetime):\n key = self.index.timezone.normalize(\n key.astimezone(self.index.timezone))\n key = key.hour\n return getattr(self, \"value_at_hour_%d\" % key)\n\n def generate_entries(self, from_timestamp, to_timestamp):\n \"\"\"\n Generate entries using C{value_at_hour} for each hour in the\n given interval.\n\n @param from_timestamp: The start of the interval.\n\n @param to_timestamp: The end of the interval.\n\n @precondition: C{from_timestamp >= self.from_timestamp()}\n\n @invariant: All entries C{e} yielded, the interval C{[t,t']}\n of C{e} will overlap C{[from_timestamp, to_timestamp)}.\n \"\"\"\n def assert_invariant(entry):\n assert(entry.from_timestamp < to_timestamp)\n assert(entry.to_timestamp > from_timestamp)\n\n assert(from_timestamp >= self.from_timestamp())\n\n # whole-hour times\n entry_from_time = from_timestamp.replace(\n minute=0, second=0, microsecond=0)\n while entry_from_time < to_timestamp:\n e = Entry(value=self.get_value_at_hour(entry_from_time),\n from_timestamp=entry_from_time,\n to_timestamp=(\n entry_from_time + datetime.timedelta(hours=1)))\n assert_invariant(e)\n yield e\n entry_from_time += datetime.timedelta(hours=1)\n\n\nclass SpotMapping(models.Model):\n \"\"\"\n A C{SpotMapping} contains information used when importing data, for\n translating external identifiers to L{Index} IDs.\n\n Currently used only for importing from Nordpool.\n\n @ivar index: The L{Index} data should be inserted for.\n @ivar area: For Nordpool, the area \"alias\".\n @ivar timezone: For Nordpool, timezone of input data.\n\n @attention: Not represented in the UI.\n \"\"\"\n index = models.OneToOneField(Index)\n area = models.CharField(max_length=3)\n unit = BuckinghamField()\n timezone = TimeZoneField()\n\n class Meta:\n verbose_name = _('spot mapping')\n verbose_name_plural = _('spot mappings')\n ordering = ['area', 'unit']\n app_label = 'indexes'\n\n def __unicode__(self):\n return u'%s-%s: %s' % (\n self.area, self.currency, self.index)\n\n def save(self, *args, **kwargs):\n assert self.index.data_format == Index.SPOT\n super(SpotMapping, self).save(*args, **kwargs)\n\n @property\n def currency(self):\n \"\"\"\n For Nordpool, the price \"unit\", i.e. currency.\n \"\"\"\n if 'currency_dkk' in self.unit:\n return 'DKK'\n elif 'currency_eur' in self.unit:\n return 'EUR'\n else:\n raise ValueError('no currency in %s' % self.unit)\n" }, { "alpha_fraction": 0.6245219111442566, "alphanum_fraction": 0.6434195637702942, "avg_line_length": 36.35293960571289, "blob_id": "ef14eaea6ba50d9277c238fe49ce1b44095e518d", "content_id": "3e054a06e74d0731d303388364365efd0af0c37a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4445, "license_type": "no_license", "max_line_length": 77, "num_lines": 119, "path": "/gridplatform/cost_compensations/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport pytz\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\n\nfrom .models import CostCompensation\nfrom .models import Period\nfrom .models import FixedCompensationPeriod\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass CostCompensationTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n\n def test_unit_dkk(self):\n costcompensation = CostCompensation(\n customer=Customer.objects.create(currency_unit='currency_dkk'))\n self.assertTrue(PhysicalQuantity.compatible_units(\n 'currency_dkk*joule^-1', costcompensation.unit))\n\n def test_unit_eur(self):\n costcompensation = CostCompensation(\n customer=Customer.objects.create(currency_unit='currency_eur'))\n self.assertTrue(PhysicalQuantity.compatible_units(\n 'currency_eur*joule^-1', costcompensation.unit))\n\n\nclass PeriodTest(TestCase):\n def test_unicode_is_pure_virtual(self):\n period = Period()\n with self.assertRaises(NotImplementedError):\n unicode(period)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass FixedCompensationPeriodTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(currency_unit='currency_dkk')\n self.costcompensation = CostCompensation(customer=self.customer)\n\n def test_unicode_without_to_timestamp(self):\n period = FixedCompensationPeriod(\n unit='currency_eur*kilowatt^-1*hour^-1',\n value=42,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n\n self.assertNotIn('None', unicode(period))\n\n def test_unicode_with_to_timestamp(self):\n period = FixedCompensationPeriod(\n unit='currency_eur*kilowatt^-1*hour^-1',\n value=42,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n\n self.assertNotIn('None', unicode(period))\n\n def test_clean_happy(self):\n period = FixedCompensationPeriod(\n datasequence=self.costcompensation,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n value=42,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n period.clean()\n\n def test_clean_bad_unit(self):\n period = FixedCompensationPeriod(\n datasequence=self.costcompensation,\n unit='currency_eur*kilowatt^-1*hour^-1',\n value=42,\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n with self.assertRaises(ValidationError) as raise_context:\n period.clean()\n self.assertIn('unit', raise_context.exception.error_dict)\n\n def test_value_sequence_integration(self):\n from_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(\n datetime.datetime(2014, 1, 2))\n period = FixedCompensationPeriod(\n datasequence=self.costcompensation,\n unit='currency_dkk*kilowatt^-1*hour^-1',\n value=42,\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp)\n self.assertEqual(\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(42, 'currency_dkk*kilowatt^-1*hour^-1'))\n for h in range(24)\n ],\n list(\n period._value_sequence(from_timestamp, to_timestamp)))\n" }, { "alpha_fraction": 0.6608198881149292, "alphanum_fraction": 0.6641274690628052, "avg_line_length": 34.254417419433594, "blob_id": "be853e8c31b8a62852e877bdb709d43fcbb539f7", "content_id": "e10672a21b581df78346ec15dbe517feb59524e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9977, "license_type": "no_license", "max_line_length": 79, "num_lines": 283, "path": "/gridplatform/datasequences/utils.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. data:: _PERIOD_KEYS\n\n Dictionary mapping condense resolutions to key function factories.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\nimport operator\n\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.samples import RangedSample\n\n\ndef _pad_ranged_sample_sequence(\n ranged_sample_sequence, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Pad a possibly incomplete ``ranged_sample_sequence`` by yielding `None`\n where :class:`RangedSamples<.RangedSample>` appear to be missing.\n \"\"\"\n current_timestamp = from_timestamp\n for sample in ranged_sample_sequence:\n while current_timestamp < sample.from_timestamp:\n yield None\n current_timestamp = current_timestamp + resolution\n yield sample\n current_timestamp = sample.to_timestamp\n\n while current_timestamp < to_timestamp:\n yield None\n current_timestamp = current_timestamp + resolution\n\n\ndef multiply_ranged_sample_sequences(sequence_a, sequence_b):\n \"\"\"\n Multiply two ranged sample sequences (`sequence_a` and `sequence_b`) sample\n by sample and yield the samples of the resulting ranged sample sequence.\n \"\"\"\n sequence_a = iter(sequence_a)\n sequence_b = iter(sequence_b)\n\n while True:\n # Will stop on either input raising StopIteration...\n a, b = next(sequence_a), next(sequence_b)\n if a.from_timestamp != b.from_timestamp:\n # Missing entries in either; skip in the other.\n while a.from_timestamp < b.from_timestamp:\n a = next(sequence_a)\n while b.from_timestamp < a.from_timestamp:\n b = next(sequence_b)\n assert a.from_timestamp == b.from_timestamp\n assert a.to_timestamp == b.to_timestamp\n val = a.physical_quantity * b.physical_quantity\n yield a._replace(physical_quantity=val)\n\n\ndef subtract_ranged_sample_sequences(sequence_a, sequence_b):\n \"\"\"\n Subtract two ranged sample sequences (`sequence_a` and `sequence_b`) sample\n by sample and yield the samples of the resulting ranged sample sequence.\n \"\"\"\n sequence_a = iter(sequence_a)\n sequence_b = iter(sequence_b)\n\n a, b = next(sequence_a, None), next(sequence_b, None)\n\n while a is not None and b is not None:\n if a.from_timestamp < b.from_timestamp:\n yield a\n a = next(sequence_a, None)\n elif b.from_timestamp < a.from_timestamp:\n yield b._replace(physical_quantity=-b.physical_quantity)\n b = next(sequence_b, None)\n else:\n yield a._replace(\n physical_quantity=a.physical_quantity - b.physical_quantity)\n a, b = next(sequence_a, None), next(sequence_b, None)\n\n assert a is None or b is None\n\n while b is not None:\n assert a is None\n yield b._replace(physical_quantity=-b.physical_quantity)\n b = next(sequence_b, None)\n assert b is None\n\n while a is not None:\n assert b is None\n yield a\n a = next(sequence_a, None)\n assert a is None\n\n\ndef add_ranged_sample_sequences(\n ranged_sample_sequences, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Add multiple `ranged_sample_sequences` into one sample sequence.\n \"\"\"\n padded_sequences = [\n _pad_ranged_sample_sequence(\n ranged_sample_sequence, from_timestamp, to_timestamp, resolution)\n for ranged_sample_sequence in ranged_sample_sequences]\n\n for padded_vector in itertools.izip(*padded_sequences):\n samples = [sample for sample in padded_vector if sample is not None]\n if samples:\n yield RangedSample(\n samples[0].from_timestamp, samples[0].to_timestamp,\n sum([sample.physical_quantity for sample in samples[1:]],\n samples[0].physical_quantity))\n\n\ndef _fiveminutes_period_key(timezone):\n \"\"\"\n Key function factory for five minute condense resolutions.\n\n :return: A key function for five minute condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest five minute multiplum.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n return timestamp.replace(\n minute=timestamp.minute - (timestamp.minute % 5),\n second=0, microsecond=0)\n return key\n\n\ndef _hour_period_key(timezone):\n \"\"\"\n Key function factory for hour condense resolutions.\n\n :return: A key function for hour condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest hour.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n return timestamp.replace(minute=0, second=0, microsecond=0)\n return key\n\n\ndef _day_period_key(timezone):\n \"\"\"\n Key function factory for day condense resolutions.\n\n :return: A key function for day condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest day.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n return timezone.localize(timestamp.replace(\n hour=0, minute=0, second=0, microsecond=0, tzinfo=None))\n return key\n\n\ndef _month_period_key(timezone):\n \"\"\"\n Key function factory for month condense resolutions.\n\n :return: A key function for month condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest month.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n return timezone.localize(timestamp.replace(\n day=1, hour=0, minute=0, second=0, microsecond=0, tzinfo=None))\n return key\n\n\ndef _quarter_period_key(timezone):\n \"\"\"\n Key function factory for quarter condense resolutions.\n\n :return: A key function for quarter condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest quarter.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n month = timestamp.month - ((timestamp.month - 1) % 3)\n return timezone.localize(timestamp.replace(\n month=month, day=1, hour=0, minute=0, second=0, microsecond=0,\n tzinfo=None))\n return key\n\n\ndef _year_period_key(timezone):\n \"\"\"\n Key function factory for year condense resolutions.\n\n :return: A key function for year condense resolutions.\n :rtype: :class:`datetime.datetime` -> :class:`datetime.datetime`\n\n :param timezone: The timezone in which the :class:`datetime.datetime` given\n to the key function should be interpreted when being rounded down to\n nearest year.\n\n :see: :func:`gridplatform.utils.condense.floor`.\n \"\"\"\n def key(sample):\n timestamp = timezone.normalize(\n sample.from_timestamp.astimezone(timezone))\n return timezone.localize(timestamp.replace(\n month=1, day=1, hour=0, minute=0, second=0, microsecond=0,\n tzinfo=None))\n return key\n\n\n_PERIOD_KEYS = {\n condense.FIVE_MINUTES: _fiveminutes_period_key,\n condense.HOURS: _hour_period_key,\n condense.DAYS: _day_period_key,\n condense.MONTHS: _month_period_key,\n condense.QUARTERS: _quarter_period_key,\n condense.YEARS: _year_period_key,\n}\n\n\ndef aggregate_sum_ranged_sample_sequence(data, resolution, timezone):\n \"\"\"\n Aggregate given sequence of accumulating\n :class:`RangedSamples<.RangedSample>` to new sequence of accumlating\n :class:`RangedSamples<.RangedSample>` with given resolution by summing\n sample values.\n\n :see: :meth:`.ConsumptionUnionBase.variable_cost_sequence` for example\n usage. There variable costs are calculated in hourly accumulation\n samples first and then aggregated to the desired resolution afterwards.\n\n :param data: The sequence of accumulating\n :class:`RangedSamples<.RangedSample>`.\n :param resolution: The given condense resolution. See\n :mod:`gridplatform.utils.condense`.\n :param tzinfo timezone: Used to determine the timespan of generated\n :class:`RangedSamples<.RangedSample>`.\n\n :return: A sequence of accumulating :class:`RangedSamples<.RangedSample>`\n \"\"\"\n assert resolution in _PERIOD_KEYS\n assert hasattr(timezone, 'localize')\n key = _PERIOD_KEYS[resolution](timezone)\n grouped = itertools.groupby(data, key)\n for timestamp, samples in grouped:\n yield RangedSample(\n timestamp, timestamp + resolution,\n reduce(\n operator.add,\n (s.physical_quantity for s in samples)))\n" }, { "alpha_fraction": 0.6794936656951904, "alphanum_fraction": 0.6797468066215515, "avg_line_length": 38.108909606933594, "blob_id": "6c37d70782732d12cb8226730d54d51f26de0a6f", "content_id": "fae3017dbdac42ad0cb92130ddec8b637c095cbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3950, "license_type": "no_license", "max_line_length": 89, "num_lines": 101, "path": "/legacy/manage_measurementpoints/forms/consumptionsummation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPointSummation # noqa\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\n\nfrom .consumption import ConsumptionMeasurementPointForm\n\n\nclass ConsumptionMeasurementPointSummationForm(\n ConsumptionMeasurementPointForm):\n class Meta(ConsumptionMeasurementPointForm.Meta):\n model = ConsumptionMeasurementPointSummation\n\n plus_consumption_measurement_points = forms.ModelMultipleChoiceField(\n queryset=ConsumptionMeasurementPoint.objects.none(), required=False)\n minus_consumption_measurement_points = forms.ModelMultipleChoiceField(\n queryset=ConsumptionMeasurementPoint.objects.none(), required=False)\n\n def __init__(self, *args, **kwargs):\n super(ConsumptionMeasurementPointSummationForm,\n self).__init__(*args, **kwargs)\n\n self.fields['plus_consumption_measurement_points'].queryset = \\\n ConsumptionMeasurementPoint.objects.filter(\n customer=trackuser.get_customer(),\n utility_type=self.instance.utility_type).exclude(\n id=self.instance.id)\n self.fields['minus_consumption_measurement_points'].queryset = \\\n ConsumptionMeasurementPoint.objects.filter(\n customer=trackuser.get_customer(),\n utility_type=self.instance.utility_type).exclude(\n id=self.instance.id)\n\n if kwargs.get('instance'):\n # initialise from existing instance when provided\n self.fields['plus_consumption_measurement_points'].initial = \\\n [mp.id for mp in\n kwargs['instance'].plus_consumption_measurement_points]\n self.fields['minus_consumption_measurement_points'].initial = \\\n [mp.id for mp in\n kwargs['instance'].minus_consumption_measurement_points]\n\n def clean(self):\n self.instance.role = ConsumptionMeasurementPointSummation.\\\n CONSUMPTION_MEASUREMENT_POINT\n self.instance.plus_consumption_measurement_points = \\\n self.cleaned_data['plus_consumption_measurement_points']\n self.instance.minus_consumption_measurement_points = \\\n self.cleaned_data['minus_consumption_measurement_points']\n self.instance.utility_type\n super(ConsumptionMeasurementPointSummationForm, self).clean()\n return self.cleaned_data\n\n def save(self, commit=True):\n \"\"\"\n C{ConsumptionMeasurementPointSummationForm} implementation\n of C{ModelForm.save()}.\n \"\"\"\n super(ConsumptionMeasurementPointSummationForm,\n self).save(commit=False)\n\n if commit:\n self.instance.save()\n\n return self.instance\n\n def _get_new_electricity_headline_display(self):\n return _(u'New Electricity Summation Point')\n\n def _get_new_water_headline_display(self):\n return _(u'New Water Summation Point')\n\n def _get_new_gas_headline_display(self):\n return _(u'New Gas Summation Point')\n\n def _get_new_heat_headline_display(self):\n return _(u'New Heat Summation Point')\n\n def _get_new_oil_headline_display(self):\n return _(u'New Oil Summation Point')\n\n def _get_edit_electricity_headline_display(self):\n return _(u'Edit Electricity Summation Point')\n\n def _get_edit_water_headline_display(self):\n return _(u'Edit Water Summation Point')\n\n def _get_edit_gas_headline_display(self):\n return _(u'Edit Gas Summation Point')\n\n def _get_edit_heat_headline_display(self):\n return _(u'Edit Heat Summation Point')\n\n def _get_edit_oil_headline_display(self):\n return _(u'Edit Oil Summation Point')\n" }, { "alpha_fraction": 0.7068345546722412, "alphanum_fraction": 0.7086330652236938, "avg_line_length": 29.88888931274414, "blob_id": "0b539c1d1a46b78686156d95d0a3f5b2d34597a1", "content_id": "a716140ab0399a1ba5f3594a042d84e172ab4bb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 556, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/legacy/energy_use_reports/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import FinalizeEnergyUseReportView\nfrom .views import StartEnergyUseReportView\n\nurlpatterns = patterns(\n 'legacy.energy_use_reports.views',\n url(r'^start_report/$',\n StartEnergyUseReportView.as_view(),\n name='energy_use_reports-start_report'),\n url(r'^finalize_report/$',\n FinalizeEnergyUseReportView.as_view(),\n name='energy_use_reports-finalize_report'),\n)\n" }, { "alpha_fraction": 0.707024335861206, "alphanum_fraction": 0.7073773145675659, "avg_line_length": 33.54878234863281, "blob_id": "09303050eacd0f11c09f409728ede0b83bf64b7a", "content_id": "b958cc315224fa70a08754712a8b6f5400e2d796", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2833, "license_type": "no_license", "max_line_length": 83, "num_lines": 82, "path": "/gridplatform/provider_datasources/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db.models.query import QuerySet\nfrom django.db import models\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\n\nfrom gridplatform.utils.models import StoredSubclassManager\nfrom gridplatform.datasources.managers import DataSourceQuerySetMixinBase\n\n\nclass ProviderDataSourceQuerySetMixin(DataSourceQuerySetMixinBase):\n \"\"\"\n Ensures that only ProviderDataSources that should be visible are visible.\n\n ProviderDataSources are visible to users that belong directly to the\n provider and users that belong to a customer of that provider.\n \"\"\"\n\n def _apply_customer_filtering(self, customer_id):\n \"\"\"\n Rows must belong to the :class:`.Provider` of the given :class:`.Customer`.\n\n :param customer_id: The id of the given :class:`.Customer`.\n \"\"\"\n self.query.add_q(models.Q(provider__customer__id=customer_id))\n\n def _apply_provider_filtering(self, provider_id):\n \"\"\"\n Rows must belong to the given :class:`.Provider`.\n\n :param provider_id: The id of the given :class:`.Provider`.\n \"\"\"\n self.query.add_q(models.Q(provider_id=provider_id))\n\n\nclass ProviderDataSourceManagerBase(models.Manager):\n \"\"\"\n Base class for model managers for the :class:`.ProviderDataSource` model,\n all whose querysets have been mixed with the\n :class:`.ProviderDataSourceQyerySetMixin` to ensure visibility only to\n intended audience.\n \"\"\"\n class _QuerySet(ProviderDataSourceQuerySetMixin, QuerySet):\n pass\n\n class _ValuesQuerySet(ProviderDataSourceQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(\n ProviderDataSourceQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(ProviderDataSourceQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(ProviderDataSourceQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(ProviderDataSourceManagerBase, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n\n\nclass ProviderDataSourceManager(\n StoredSubclassManager, ProviderDataSourceManagerBase):\n \"\"\"\n A model manager that is both a :class:`.StoredSubclassManager` and a\n :class:`.ProviderDataSourceManagerBase`.\n \"\"\"\n use_for_related_fields = False\n" }, { "alpha_fraction": 0.5769299864768982, "alphanum_fraction": 0.5790793299674988, "avg_line_length": 34.560508728027344, "blob_id": "10deb2dabe1948102730e84d735c4126380bcab1", "content_id": "b952a61983f5fddb86e1465252f7dba7056aa245", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5583, "license_type": "no_license", "max_line_length": 79, "num_lines": 157, "path": "/legacy/measurementpoints/models/chain.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils.iter_ext import pairwise_extended\nfrom gridplatform.utils.relativetimedelta import DATETIME_MAX\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\n\n\nclass Chain(DataSeries):\n \"\"\"\n A C{Chain} is a L{DataSeries} defined in terms of chained segments of other\n L{DataSeries}.\n \"\"\"\n chained_data_series = models.ManyToManyField(\n DataSeries, related_name='chain_derivative_set',\n through='measurementpoints.ChainLink',\n symmetrical=False)\n\n class Meta(DataSeries.Meta):\n verbose_name = _('chain')\n verbose_name_plural = _('chains')\n app_label = 'measurementpoints'\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{Chain} implementation of L{DataSeries.get_raw_data_samples()}\n \"\"\"\n for link in self.iterate_links(from_timestamp, to_timestamp):\n for sample in link.data_series.subclass_instance.\\\n get_samples(\n max(from_timestamp, link.valid_from),\n min(to_timestamp, link.get_valid_to())):\n assert sample.physical_quantity.compatible_unit(self.unit)\n yield sample\n\n def iterate_links(self, from_timestamp, to_timestamp):\n \"\"\"\n Iterate links in this C{Chain} covering a given timespan.\n\n @param from_timestamp: The start of the timespan.\n\n @param to_timestamp: The end of the timespan.\n \"\"\"\n result = self.links.filter(\n valid_from__gte=from_timestamp,\n valid_from__lt=to_timestamp).order_by('valid_from')\n\n if not result or result[0].valid_from >= from_timestamp:\n try:\n result = itertools.chain(\n [self.links.filter(\n valid_from__lt=from_timestamp).order_by(\n '-valid_from')[0]], result)\n except IndexError:\n pass\n\n # annotate yielded links with precalculated C{valid_to}.\n for l1, l2 in pairwise_extended(result):\n if l2 is not None:\n l1._valid_to = l2.valid_from\n else:\n l1._valid_to = DATETIME_MAX\n yield l1\n\n def get_recursive_condense_resolution(self, resolution):\n return condense.next_resolution(resolution)\n\n\ndef _customer_now():\n customer = get_customer()\n if customer:\n return customer.now()\n else:\n return None\n\n\nclass ChainLink(models.Model):\n \"\"\"\n Support model for L{Chain} model\n \"\"\"\n chain = models.ForeignKey(Chain, on_delete=models.CASCADE,\n related_name='links')\n data_series = models.ForeignKey(DataSeries, on_delete=models.PROTECT,\n related_name='chainlink_data_series')\n valid_from = models.DateTimeField(default=_customer_now)\n\n # NOTE: We may wish to specify a date rather than timestamp in the UI ---\n # but for computations, we need an absolute timestamp, and to ensure\n # consistent use/to only have the rules for translating date to timestamp\n # (taking time zone into account) once, we store the resulting datetime.\n\n class Meta:\n verbose_name = _('chain link')\n verbose_name_plural = _('chain links')\n app_label = 'measurementpoints'\n unique_together = (('chain', 'valid_from'))\n ordering = ['valid_from']\n\n def clean(self):\n try:\n chain = self.chain\n data_series = self.data_series\n except DataSeries.DoesNotExist:\n pass\n else:\n if self.chain.unit and \\\n not PhysicalQuantity.compatible_units(chain.unit,\n data_series.unit):\n raise ValidationError(\n {\n 'data_series': [\n ValidationError(\n _('The unit of the selected data series is '\n 'incompatible with this chain'),\n code='incompatible_units')]})\n\n def __unicode__(self):\n return '%s (%s %s)' % (self.data_series, self.chain, self.valid_from)\n\n def __repr__(self):\n return '<%s: id=%s, chain=%s, data_series=%s, valid_from=%s>' % (\n self.__class__.__name__, self.id, self.chain_id,\n self.data_series_id, self.valid_from)\n\n def get_valid_to(self):\n \"\"\"\n The C{datetime} marking the end of this C{ChainLink}\n\n @note: Actually returning C{valid_from} data of next C{Period} object.\n In case of no other C{ChainLink} exists, L{DATETIME_MAX} is returned.\n\n @return: A C{datetime} marking the end of this C{ChainLink}\n \"\"\"\n if hasattr(self, '_valid_to'):\n return self._valid_to\n\n ls = ChainLink.objects.filter(\n chain=self.chain,\n valid_from__gt=self.valid_from).\\\n order_by(\n 'valid_from').values_list('valid_from', flat=True)[:1]\n if ls:\n self._valid_to = ls[0]\n return self._valid_to\n else:\n return DATETIME_MAX\n" }, { "alpha_fraction": 0.6441798806190491, "alphanum_fraction": 0.6455026268959045, "avg_line_length": 27, "blob_id": "f8813a0329fc3949c9d39a42ff6c463c0e05746c", "content_id": "530e4f54a6f97c22815c79729a2d46c1642e33ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 756, "license_type": "no_license", "max_line_length": 50, "num_lines": 27, "path": "/energymanager/led_light_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\nfrom django.conf.urls import include\n\nfrom gridplatform.utils.urls import restricted_url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.led_light_view.views',\n url(r'^$',\n views.HomeView.as_view(),\n name='home'),\n url(r'^customer/(?P<customer_id>\\d+)/$',\n views.CustomerView.as_view(),\n name='customer'),\n url(r'^choose-customer/$',\n views.ChooseCustomer.as_view(),\n name='choose-customer'),\n url(r'^(?P<customer_id>\\d+)/dashboard/$',\n views.DashboardDetailView.as_view(),\n name='dashboard'),\n)\n" }, { "alpha_fraction": 0.5483468770980835, "alphanum_fraction": 0.5670617818832397, "avg_line_length": 39.582279205322266, "blob_id": "342e9a6dc4e731d432750df0e77bff8d1b092b36", "content_id": "49c5059f9d8e62d1dc8a68876442c7f72f94cfb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6412, "license_type": "no_license", "max_line_length": 89, "num_lines": 158, "path": "/legacy/display_measurementpoints/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport math\n\nfrom django.shortcuts import get_object_or_404\nfrom django.utils import translation\n\nfrom celery import shared_task\n\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPointSummation # noqa\nfrom legacy.measurementpoints.proxies import ConsumptionMultiplicationPoint\nfrom legacy.measurementpoints.models import DataSeries\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.trackuser import get_customer\n\n\ndef get_ticks(count, maximum):\n return int(math.floor(count / math.ceil(float(count) / float(maximum))))\n\n\ndef is_clock_hour(timestamp):\n return timestamp.minute == timestamp.second == timestamp.microsecond == 0\n\n\n@trackuser_task\n@shared_task(name='legacy.display_measurementpoints.tasks.graph_task')\ndef graph_task(pk, from_timestamp, to_timestamp, language, num_tics=None):\n assert is_clock_hour(from_timestamp)\n assert is_clock_hour(to_timestamp)\n\n graph = get_object_or_404(\n Graph, collection__customer__id=get_customer().id, pk=pk)\n\n translation.activate(language)\n\n delta = RelativeTimeDelta(to_timestamp, from_timestamp)\n months = delta.years * 12 + delta.months\n\n days = int(round((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(days=1).total_seconds()))\n\n is_multiplication_or_summation = isinstance(\n graph.collection.subclass_instance,\n (\n ConsumptionMeasurementPointSummation,\n ConsumptionMultiplicationPoint))\n if days <= 7:\n # display hours\n hours = int((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(hours=1).total_seconds())\n\n if graph.role in DataSeries.CONTINUOUS_RATE_ROLES:\n if hours == 0:\n minutes = int(\n (to_timestamp - from_timestamp).total_seconds() / 60)\n result = graph.get_graph_data(\n get_ticks(minutes, num_tics or 30),\n from_timestamp, to_timestamp=to_timestamp)\n elif hours > 24:\n if is_multiplication_or_summation:\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 10),\n from_timestamp, hours * 60 / 5,\n RelativeTimeDelta(minutes=5))\n else:\n # up to 10080 samples across 1000 pixels. VERRY\n # BAD\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 10),\n from_timestamp, to_timestamp=to_timestamp)\n else:\n if is_multiplication_or_summation:\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 12),\n from_timestamp, hours * 60 / 5,\n RelativeTimeDelta(minutes=5))\n else:\n # up to 1440 samples across 1000 pixels. BAD\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 12),\n from_timestamp,\n to_timestamp=to_timestamp)\n else:\n if hours == 0:\n minutes = int(\n (to_timestamp - from_timestamp).total_seconds() / 60)\n result = graph.get_graph_data(\n get_ticks(minutes, num_tics or 30),\n from_timestamp, minutes,\n RelativeTimeDelta(minutes=1))\n elif hours > 24:\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 10),\n from_timestamp, hours,\n RelativeTimeDelta(hours=1))\n else:\n result = graph.get_graph_data(\n get_ticks(hours, num_tics or 10), from_timestamp,\n hours,\n RelativeTimeDelta(hours=1))\n\n elif days < 32:\n # display days\n hours = int((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(hours=1).total_seconds())\n if graph.role in DataSeries.CONTINUOUS_RATE_ROLES:\n # up to 768 samples across 1000 pixels. OK\n result = graph.get_graph_data(\n get_ticks(days, num_tics or 15),\n from_timestamp, hours,\n RelativeTimeDelta(hours=1))\n else:\n result = graph.get_graph_data(\n get_ticks(days, num_tics or 15),\n from_timestamp,\n days, RelativeTimeDelta(days=1))\n\n elif days < 180:\n # display days\n hours = int((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(hours=1).total_seconds())\n if graph.role in DataSeries.CONTINUOUS_RATE_ROLES:\n # up to 4320 samples across 1000 pixels. VERRY BAD\n result = graph.get_graph_data(\n get_ticks(days, num_tics or 10),\n from_timestamp,\n hours, RelativeTimeDelta(hours=1))\n else:\n result = graph.get_graph_data(\n get_ticks(days, num_tics or 12),\n from_timestamp, days,\n RelativeTimeDelta(days=1))\n else:\n # display months\n if graph.role in DataSeries.CONTINUOUS_RATE_ROLES:\n # up to 1825 samples across 1000 pixels (assuming\n # expected maximum is 5 years). For 2 years, this\n # sample accumulation rate seem quite adequate. OK.\n result = graph.get_graph_data(\n get_ticks(months, num_tics or 11),\n from_timestamp, days,\n RelativeTimeDelta(days=1))\n else:\n result = graph.get_graph_data(\n get_ticks(months, num_tics or 11),\n from_timestamp,\n months, RelativeTimeDelta(months=1))\n\n result[\"options\"].update({\"grid\": {\"outlineWidth\": 0,\n \"verticalLines\": True}})\n result[\"options\"][\"yaxis\"].update({\"titleAngle\": 90})\n result[\"options\"].update({\"HtmlText\": False})\n return result\n" }, { "alpha_fraction": 0.7814432978630066, "alphanum_fraction": 0.7814432978630066, "avg_line_length": 31.33333396911621, "blob_id": "f35b17ae532bf46c2d1af3731ec4e6cb2cdd89fe", "content_id": "c1f147a8f515f361e0a1a1eb8aeddade5cc4d387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 485, "license_type": "no_license", "max_line_length": 80, "num_lines": 15, "path": "/documentation/source/apps/gridplatform/providers.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Providers\n=========\n\nThe ``providers`` app defines the\n:py:class:`~gridplatform.providers.models.Provider` model, which represent the\nentity that facilitates the software towards\n:py:class:`~gridplatform.customers.models.Customer`.\n\n\n.. autoclass:: gridplatform.providers.models.Provider\n :members: get_encryption_id, save\n\n.. autofunction:: gridplatform.providers.models.auto_grant_provider_user_key\n\n.. autofunction:: gridplatform.providers.models.auto_grant_provider_customer_key\n" }, { "alpha_fraction": 0.49418121576309204, "alphanum_fraction": 0.5149626135826111, "avg_line_length": 31.513513565063477, "blob_id": "afe6824bd59066b951074a9cd390f09d3ff40745", "content_id": "daa14dbd5344b636f6080837133de7cc5fd5ef94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2406, "license_type": "no_license", "max_line_length": 108, "num_lines": 74, "path": "/emonhub/src/interfacers/EmonHubTesterInterfacer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"class EmonHubTesterGenInterfacer\n\n\"\"\"\nimport time\nimport Cargo\nfrom pydispatch import dispatcher\nfrom emonhub_interfacer import EmonHubInterfacer\n\nclass EmonHubTesterInterfacer(EmonHubInterfacer):\n\n def __init__(self, name, mqtt_host=\"127.0.0.1\", mqtt_port=1883):\n # Initialization\n super(EmonHubTesterInterfacer, self).__init__(name)\n \n self._name = name\n \n self._settings = {\n 'subchannels':['ch1'],\n 'pubchannels':['ch2']\n };\n \n\n def run(self):\n\n last = time.time()\n consumption = 0\n time_consumption = 0\n while not self.stop:\n # Read the input and process data if available\n \n now = time.time()\n if (now-last)>5.0:\n time_consumption += int(now-last)\n last = now\n\n #if time_consumption == 30:\n # consumption = 0\n \n self._log.debug(\"5s loop\")\n rxc = Cargo.new_cargo()\n rxc.nodeid = 10\n rxc.nodename = \"EMONTEST\"\n rxc.names = ['power1', 'power2', 'power3', 'power4', 'Vrms', 'pulse',\n 'Wh1', 'Wh2', 'Wh3', 'Wh4', 'RunHours1', 'RunHours2', 'RunHours3', 'RunHours4']\n\n rxc.realdata = [10,10,10,10,230,0,consumption,consumption,consumption,consumption,\n time_consumption,time_consumption,time_consumption,time_consumption]\n\n consumption += 10\n\n\n for channel in self._settings[\"pubchannels\"]:\n dispatcher.send(channel, cargo=rxc)\n self._log.debug(str(rxc.uri) + \" Sent to channel' : \" + str(channel))\n \n # Don't loop to fast\n time.sleep(0.1)\n # Action reporter tasks\n # self.action()\n\n def receiver(self, cargo):\n pass\n \n \n def set(self, **kwargs):\n for key,setting in self._settings.iteritems():\n if key in kwargs.keys():\n # replace default\n self._settings[key] = kwargs[key]\n \n # Subscribe to internal channels \n for channel in self._settings[\"subchannels\"]:\n dispatcher.connect(self.receiver, channel)\n self._log.debug(self._name+\" Subscribed to channel' : \" + str(channel))\n" }, { "alpha_fraction": 0.7066728472709656, "alphanum_fraction": 0.7099165916442871, "avg_line_length": 31.208955764770508, "blob_id": "0763ef5b2b48bae07808fe4a4e1865e90bcf7b53", "content_id": "a5b5150511a99717778b21be53144d4286e5b84d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2158, "license_type": "no_license", "max_line_length": 78, "num_lines": 67, "path": "/gridplatform/tariffs/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nimport rest_framework.reverse\n\nfrom gridplatform.datasequences.views import HourlyDataView\nfrom gridplatform.rest.viewsets import NestedMixin\n\nfrom . import models\nfrom . import serializers\n\n\nclass HourlyView(NestedMixin, HourlyDataView):\n method_name = 'value_sequence'\n\n def get(self, request, datasequence_id=None, format=None):\n datasequence = get_object_or_404(models.Tariff, pk=datasequence_id)\n timezone = datasequence.customer.timezone\n return self._get(request, datasequence, timezone)\n\n\nclass EnergyTariff(viewsets.ModelViewSet):\n model = models.EnergyTariff\n serializer_class = serializers.EnergyTariff\n filter_fields = ('name', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyView.as_view()\n return view_fn(request, datasequence_id=pk)\n\n\nclass VolumeTariff(viewsets.ModelViewSet):\n model = models.VolumeTariff\n serializer_class = serializers.VolumeTariff\n filter_fields = ('name', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyView.as_view()\n return view_fn(request, datasequence_id=pk)\n\n\nclass TariffParentMixin(object):\n def create(self, request, *args, **kwargs):\n request.DATA['datasequence'] = rest_framework.reverse.reverse(\n viewname='api:tariff:tariff-detail',\n kwargs={\n 'pk': kwargs.pop('datasequence_id'),\n }\n )\n return super(TariffParentMixin, self).create(\n request, *args, **kwargs)\n\n\nclass FixedPricePeriod(NestedMixin, TariffParentMixin, viewsets.ModelViewSet):\n model = models.FixedPricePeriod\n serializer_class = serializers.FixedPricePeriod\n\n\nclass SpotPricePeriod(NestedMixin, TariffParentMixin, viewsets.ModelViewSet):\n model = models.SpotPricePeriod\n serializer_class = serializers.SpotPricePeriod\n" }, { "alpha_fraction": 0.6557271480560303, "alphanum_fraction": 0.6576576828956604, "avg_line_length": 30.079999923706055, "blob_id": "7f43412e2e7c40bbccb032d7ad6bbbe658ca3709", "content_id": "8aa65071562825e2ef122f1dc31906837d8ac79f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1554, "license_type": "no_license", "max_line_length": 75, "num_lines": 50, "path": "/gridplatform/users/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.db.models import ProtectedError\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.testutils import no_encryption\nfrom gridplatform.providers.models import Provider\n\nfrom .models import User\n\n\nclass TestUser(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_dependency(self):\n customer = self.customer\n assert customer is trackuser.get_customer()\n\n with no_encryption():\n collection = Collection.objects.create(\n name='test collection',\n customer=customer,\n role=Collection.GROUP,\n utility_type=0)\n\n user = User.objects.create_user(\n '[email protected]',\n 'totallyrandompassword',\n user_type=0)\n\n CollectionConstraint.objects.create(\n collection_id=collection.id,\n userprofile=user.userprofile)\n\n assert list(user.userprofile.collections.all()) == [collection]\n\n self.assertRaises(ProtectedError, lambda: collection.delete())\n" }, { "alpha_fraction": 0.7094188332557678, "alphanum_fraction": 0.7098196148872375, "avg_line_length": 35.159420013427734, "blob_id": "23813fcfc767f65f40d17a2fe6da1690d0c47d2d", "content_id": "f9d774b728c53fecdc302790e8fc95c704f28832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2495, "license_type": "no_license", "max_line_length": 75, "num_lines": 69, "path": "/legacy/manage_measurementpoints/forms/multipliedconsumptionform.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import ConsumptionMultiplicationPoint\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\n\nfrom .consumption import ConsumptionMeasurementPointForm\n\n\nclass MultiplicationConsumptionMeasurementPointForm(\n ConsumptionMeasurementPointForm):\n \"\"\"\n MultipliedConsumptionForm\n \"\"\"\n source_consumption_point = forms.ModelChoiceField(\n queryset=ConsumptionMeasurementPoint.objects.none(), required=True)\n multiplier = forms.DecimalField(localize=True)\n\n class Meta(ConsumptionMeasurementPointForm.Meta):\n model = ConsumptionMultiplicationPoint\n\n class ProxyMeta(ConsumptionMeasurementPointForm.ProxyMeta):\n fields = ConsumptionMeasurementPointForm.ProxyMeta.fields + (\n 'source_consumption_point', 'multiplier')\n\n def __init__(self, *args, **kwargs):\n super(MultiplicationConsumptionMeasurementPointForm,\n self).__init__(*args, **kwargs)\n\n self.fields['source_consumption_point'].queryset = \\\n ConsumptionMeasurementPoint.objects.subclass_only().filter(\n customer=trackuser.get_customer(),\n utility_type=self.instance.utility_type).exclude(\n id=self.instance.id)\n\n def _get_new_electricity_headline_display(self):\n return _(u'New Electricity Multiplication Point')\n\n def _get_new_water_headline_display(self):\n return _(u'New Water Multiplication Point')\n\n def _get_new_gas_headline_display(self):\n return _(u'New Gas Multiplication Point')\n\n def _get_new_heat_headline_display(self):\n return _(u'New Heat Multiplication Point')\n\n def _get_new_oil_headline_display(self):\n return _(u'New Oil Multiplication Point')\n\n def _get_edit_electricity_headline_display(self):\n return _(u'Edit Electricity Multiplication Point')\n\n def _get_edit_water_headline_display(self):\n return _(u'Edit Water Multiplication Point')\n\n def _get_edit_gas_headline_display(self):\n return _(u'Edit Gas Multiplication Point')\n\n def _get_edit_heat_headline_display(self):\n return _(u'Edit Heat Multiplication Point')\n\n def _get_edit_oil_headline_display(self):\n return _(u'Edit Oil Multiplication Point')\n" }, { "alpha_fraction": 0.7987679839134216, "alphanum_fraction": 0.7997946739196777, "avg_line_length": 37.959999084472656, "blob_id": "861eba2e90a902c148078ae8bc7d58db40ad8d40", "content_id": "66b1543a69209bc589d1599871493f628853049a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 974, "license_type": "no_license", "max_line_length": 83, "num_lines": 25, "path": "/documentation/source/apps/gridplatform/costcompensations.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Cost Compensations\n==================\n\nCost compensations are described in the domain model in the section\n:ref:`cost-compensations`. To facilitate changes in the domain, as mentioned\nin :ref:`changes-in-domain`, the\n:py:class:`~gridplatform.cost_compensations.models.CostCompensation` is defined\nin terms of periods, namely\n:py:class:`~gridplatform.cost_compensations.models.FixedCompensationPeriod`.\nThe periods are associated to cost compensations via the\n:py:class:`~gridplatform.cost_compensations.models.CostCompensationPeriodManager`.\n\nA simpler design for solving a simular task is described in\n:ref:`co2-conversions`.\n\n.. autoclass:: gridplatform.cost_compensations.models.CostCompensation\n\n.. autoclass:: gridplatform.cost_compensations.models.CostCompensationPeriodManager\n :members: value_sequence\n\n.. autoclass:: gridplatform.cost_compensations.models.Period\n\n\n.. autoclass:: gridplatform.cost_compensations.models.FixedCompensationPeriod\n :members: clean\n" }, { "alpha_fraction": 0.7247627377510071, "alphanum_fraction": 0.7277825474739075, "avg_line_length": 27.268293380737305, "blob_id": "00f9c32b26c0404ce5187e6bfcd3ed8f52d7edd7", "content_id": "daf221dd3b537af9de6b52d878dd9703df51490c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2318, "license_type": "no_license", "max_line_length": 78, "num_lines": 82, "path": "/legacy/manage_collections/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom imagekit.models import ProcessedImageField\nfrom imagekit.processors import ResizeToFit\n\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.trackuser.managers import StoredSubclassCustomerBoundManager\n\n\nclass CollectionCustomerBoundManager(CustomerBoundManager):\n _field = 'collection__customer'\n\n\nclass Floorplan(models.Model):\n collection = models.OneToOneField(Collection)\n image = ProcessedImageField(\n upload_to='floorplans',\n blank=False,\n processors=[ResizeToFit(900, 900, upscale=False)],\n format='JPEG')\n\n objects = CollectionCustomerBoundManager()\n\n def save(self, *args, **kwargs):\n assert self.image\n super(Floorplan, self).save(*args, **kwargs)\n\n\nclass FloorplanCollectionStoredSubclassCustomerBoundManager(\n StoredSubclassCustomerBoundManager):\n _field = 'floorplan__collection__customer'\n\n\nclass AbstractItem(StoreSubclass):\n objects = FloorplanCollectionStoredSubclassCustomerBoundManager()\n\n class Meta:\n abstract = True\n\n\nclass Item(AbstractItem):\n floorplan = models.ForeignKey(Floorplan)\n x = models.IntegerField()\n y = models.IntegerField()\n z = models.IntegerField()\n\n def has_collection(self):\n return self.subclass_instance._has_collection()\n\n def _has_collection(self):\n raise NotImplementedError(self.__class__)\n\n\nclass CollectionItem(Item):\n collection = models.ForeignKey(Collection)\n\n def _has_collection(self):\n return True\n\n\nclass InfoItem(Item, EncryptedModel):\n info = EncryptedTextField()\n\n def _has_collection(self):\n return False\n\n def get_encryption_id(self):\n if self.id:\n return (\n Customer,\n self.floorplan.collection.customer_id)\n else:\n return (Customer, get_customer().id)\n" }, { "alpha_fraction": 0.6164124011993408, "alphanum_fraction": 0.6169726848602295, "avg_line_length": 41.41682052612305, "blob_id": "3008372e5920a1f1dce32d76d047e4b5232a3515", "content_id": "425af76edc0bd49fdb4e015be3149853f3b54f16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23202, "license_type": "no_license", "max_line_length": 98, "num_lines": 547, "path": "/legacy/datasequence_adapters/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\nimport itertools\n\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.exceptions import MultipleObjectsReturned\n\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.datasequences.models import NonaccumulationDataSequence\nfrom gridplatform.datasequences.models.accumulation import NonpulseAccumulationPeriodMixin # noqa\nfrom gridplatform.datasequences.models.accumulation import PulseAccumulationPeriodMixin # noqa\nfrom gridplatform.productions.models import Production\nfrom gridplatform.utils import DATETIME_MAX\nfrom gridplatform.utils import DATETIME_MIN\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.measurementpoints.models import DataSeries\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.samples import wrap_ranged_sample_sequence\n\nHOUR_MAX = DATETIME_MAX.replace(minute=0, second=0, microsecond=0)\n\n\ndef is_clock_hour(timestamp):\n return timestamp.minute == timestamp.second == timestamp.microsecond == 0\n\n\ndef interpolate(timestamp, point_a, point_b):\n timestamp_a, value_a = point_a.timestamp, point_a.value\n timestamp_b, value_b = point_b.timestamp, point_b.value\n assert timestamp_a <= timestamp < timestamp_b\n assert timestamp.microsecond == 0\n assert timestamp_a.microsecond == 0\n assert timestamp_b.microsecond == 0\n return value_a + (value_b - value_a) * \\\n Fraction(int((timestamp - timestamp_a).total_seconds()),\n int((timestamp_b - timestamp_a).total_seconds()))\n\n\nclass DataSequenceAdapterUnicodeMixin(object):\n def __unicode__(self):\n # NOTE: data sequences in general cannot be assumed to have correct\n # name. In particular, some data sequences has been given an erronuous\n # autogenerated name. Fortunately, it is not possible to name a data\n # sequence via legacy code. We therefore default to the name the data\n # sequence should have been given (namely the unicode representation of\n # the corresponding physical input), if nothing suspicious is going on.\n # If more than one data source is associated with the data sequence we\n # say something suspicious is going on and the data sequence is assumed\n # to have a correct unicode representation. At least we can't do\n # better than that for now.\n try:\n datasource_id = self.datasequence.period_set.get().\\\n subclass_instance.datasource_id\n return unicode(PhysicalInput.objects.get(id=datasource_id))\n except (MultipleObjectsReturned, ObjectDoesNotExist):\n return unicode(self.datasequence)\n\n\nclass AccumulationAdapterBase(DataSequenceAdapterUnicodeMixin, DataSeries):\n # NOTE: Need different classes to wrap consumption and production...\n\n class Meta:\n abstract = True\n\n def _assert_invariants(self):\n assert self.unit == self.datasequence.unit, \\\n '{} != {}'.format(self.unit, self.datasequence.unit)\n\n def get_recursive_condense_resolution(self, resolution):\n if condense.RESOLUTIONS.index(resolution) >= \\\n condense.RESOLUTIONS.index(condense.DAYS):\n return None\n else:\n return condense.next_resolution(resolution)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n ZERO = PhysicalQuantity(0, self.unit)\n period_offset = ZERO\n\n def add_period_offset(sample):\n \"\"\"\n Add period offset from given C{sample} to make samples of two\n successive periods appear continuous.\n \"\"\"\n return sample._replace(\n physical_quantity=sample.physical_quantity + period_offset)\n\n input_periods = iter(\n wrap_period(period.subclass_instance)\n for period in self.datasequence.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'))\n\n last_sample_yielded = None\n try:\n first_input_period = next(input_periods)\n except StopIteration:\n # no input periods\n pass\n else:\n # yield extrapolated sample before first period if necessary\n if first_input_period.from_timestamp > from_timestamp:\n first_sample = self.create_point_sample(\n from_timestamp,\n PhysicalQuantity(0, self.unit),\n uncachable=True,\n extrapolated=True)\n yield first_sample\n last_sample_yielded = first_sample\n\n # yield samples of first period\n next_period_offset = ZERO\n for sample in first_input_period.get_samples(\n max(from_timestamp, first_input_period.from_timestamp),\n min(to_timestamp, first_input_period.to_timestamp)):\n yield sample\n period_offset = sample.physical_quantity\n last_sample_yielded = sample\n\n # yield samples of remaining periods with added offset from\n # previous period, and skipping first sample of each period as it\n # would otherwise be a duplicate of the last sample of the previous\n # period.\n for input_period in input_periods:\n input_period = input_period\n next_period_offset = ZERO\n first_sample_in_period = True\n for sample in input_period.get_samples(\n max(from_timestamp, input_period.from_timestamp),\n min(to_timestamp, input_period.to_timestamp)):\n if not first_sample_in_period:\n yield add_period_offset(sample)\n last_sample_yielded = sample\n next_period_offset = sample.physical_quantity\n first_sample_in_period = False\n period_offset = next_period_offset\n\n # yield extrapolated sample after last period if necessary\n if last_sample_yielded is not None and \\\n last_sample_yielded.timestamp != to_timestamp:\n yield last_sample_yielded._replace(\n timestamp=to_timestamp,\n cachable=False,\n extrapolated=True)\n if last_sample_yielded is None:\n yield self.create_point_sample(\n from_timestamp,\n PhysicalQuantity(0, self.unit),\n uncachable=True,\n extrapolated=True)\n yield self.create_point_sample(\n to_timestamp,\n PhysicalQuantity(0, self.unit),\n uncachable=True,\n extrapolated=True)\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n return wrap_ranged_sample_sequence(\n self.datasequence.development_sequence(\n from_timestamp, to_timestamp, sample_resolution))\n\n def calculate_development(self, from_timestamp, to_timestamp):\n # The \"normal\"/inherited DataSeries calculate_development() is based on\n # iterating over get_samples() --- usually far from optimal, but\n # reduces the amount of code necessary to implement the DataSeries\n # interface. If the from/to timestamps match clock hours, we may\n # optimise by using the development_sum()-method on the datasequence\n # object --- other optimisations would take more effort for less gain.\n # (Total consumption over a period with calculate_development() is\n # usually used in a context where the period is days or months and thus\n # implicitly match clock hours; the overhead from the inherited\n # calculate_development() is not all that significant for periods\n # shorter than hours...)\n if is_clock_hour(from_timestamp) and is_clock_hour(to_timestamp):\n value = self.datasequence.development_sum(\n from_timestamp, to_timestamp)\n return Sample(from_timestamp, to_timestamp, value, False, False)\n else:\n return super(\n AccumulationAdapterBase, self).calculate_development(\n from_timestamp, to_timestamp)\n\n\nclass ConsumptionAccumulationAdapter(AccumulationAdapterBase):\n datasequence = models.ForeignKey(\n Consumption, on_delete=models.PROTECT, related_name='+')\n\n\nclass ProductionAccumulationAdapter(AccumulationAdapterBase):\n datasequence = models.ForeignKey(\n Production, on_delete=models.PROTECT, related_name='+')\n\n\nclass PeriodAdapterBase(object):\n def __init__(self, period):\n self.period = period\n\n @property\n def datasource(self):\n # ... might not exist...\n return self.period.datasource\n\n @property\n def unit(self):\n return self.period.unit\n\n @cached_property\n def from_timestamp(self):\n if self.period.from_timestamp is not None:\n return self.period.from_timestamp\n else:\n return DATETIME_MIN\n\n @cached_property\n def to_timestamp(self):\n if self.period.to_timestamp is not None:\n return self.period.to_timestamp\n else:\n return HOUR_MAX\n\n def _get_leading_raw_data(self, timestamp):\n return self.period.datasource.rawdata_set.filter(\n timestamp__lt=timestamp).order_by('timestamp').last()\n\n @cached_property\n def _leading_raw_data(self):\n return self._get_leading_raw_data(self.from_timestamp)\n\n def _get_following_raw_data(self, timestamp):\n return self.period.datasource.rawdata_set.filter(\n timestamp__gt=timestamp).order_by('timestamp').first()\n\n @cached_property\n def _first_raw_data(self):\n return self.period.datasource.rawdata_set.filter(\n timestamp__gte=self.from_timestamp,\n timestamp__lte=self.to_timestamp).order_by('timestamp').first()\n\n def create_point_sample(\n self, timestamp, physical_quantity,\n cachable=True, extrapolated=False):\n return Sample(\n timestamp,\n timestamp,\n physical_quantity,\n cachable,\n extrapolated)\n\n def _interpolate_sample(self, timestamp, raw_data_before, raw_data_after):\n return self.create_point_sample(\n timestamp,\n PhysicalQuantity(\n interpolate(\n timestamp,\n raw_data_before,\n raw_data_after),\n self.unit))\n\n def get_samples(self, from_timestamp, to_timestamp):\n assert from_timestamp <= to_timestamp\n assert from_timestamp >= self.from_timestamp\n assert to_timestamp <= self.to_timestamp\n return self._get_samples(from_timestamp, to_timestamp)\n\n\nclass AccumulationPeriodAdapterBase(PeriodAdapterBase):\n def get_samples(self, from_timestamp, to_timestamp):\n previous_sample_yielded = None\n samples = iter(\n super(AccumulationPeriodAdapterBase, self).get_samples(\n from_timestamp, to_timestamp))\n try:\n first_sample = next(samples)\n except StopIteration:\n # no samples\n return\n assert first_sample.timestamp == from_timestamp\n # check postconditions of first sample yielded\n if from_timestamp == self.from_timestamp:\n assert not first_sample.physical_quantity\n yield first_sample\n previous_sample_yielded = first_sample\n for sample in samples:\n yield sample\n previous_sample_yielded = sample\n final_sample_yielded = previous_sample_yielded\n # check postconditions of final sample yielded\n assert final_sample_yielded.timestamp == to_timestamp\n\n @cached_property\n def offset(self):\n if self._first_raw_data is None:\n if self._leading_raw_data is None:\n return PhysicalQuantity(0, self.unit)\n else:\n return PhysicalQuantity(\n self._leading_raw_data.value, self.unit)\n else:\n assert self._first_raw_data is not None\n if self._first_raw_data.timestamp == self.from_timestamp:\n return PhysicalQuantity(\n self._first_raw_data.value,\n self.unit)\n elif self._leading_raw_data is not None:\n return PhysicalQuantity(\n interpolate(\n self.from_timestamp,\n self._leading_raw_data,\n self._first_raw_data),\n self.unit)\n else:\n return PhysicalQuantity(self._first_raw_data.value, self.unit)\n\n def _extrapolate_sample(self, timestamp, raw_data):\n return self.create_point_sample(\n timestamp,\n PhysicalQuantity(raw_data.value, self.unit),\n cachable=False, extrapolated=True)\n\n def _subtract_offset(self, sample):\n return sample._replace(\n physical_quantity=sample.physical_quantity - self.offset)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n return self._get_converted_samples(\n from_timestamp, to_timestamp)\n\n def _get_raw_samples(self, from_timestamp, to_timestamp):\n assert from_timestamp <= to_timestamp\n assert self.from_timestamp <= from_timestamp\n assert self.to_timestamp >= to_timestamp\n raw_data_iterator = iter(\n self.datasource.rawdata_set.filter(\n timestamp__gte=from_timestamp, timestamp__lte=to_timestamp))\n try:\n first_raw_data = next(raw_data_iterator)\n except StopIteration:\n leading_raw_data = self._get_leading_raw_data(from_timestamp)\n following_raw_data = self._get_following_raw_data(to_timestamp)\n if leading_raw_data is not None and following_raw_data is not None:\n if from_timestamp == to_timestamp:\n # single sample interpolated\n yield self._subtract_offset(\n self._interpolate_sample(\n from_timestamp, leading_raw_data,\n following_raw_data))\n else:\n # two samples interpolated\n yield self._subtract_offset(\n self._interpolate_sample(\n from_timestamp, leading_raw_data,\n following_raw_data))\n yield self._subtract_offset(\n self._interpolate_sample(\n to_timestamp, leading_raw_data,\n following_raw_data))\n elif leading_raw_data is not None or \\\n following_raw_data is not None:\n raw_data = leading_raw_data or following_raw_data\n if from_timestamp == to_timestamp:\n # single sample extrapolated\n yield self._subtract_offset(\n self._extrapolate_sample(from_timestamp, raw_data))\n else:\n # two samples extrapolated\n yield self._subtract_offset(\n self._extrapolate_sample(from_timestamp, raw_data))\n yield self._subtract_offset(\n self._extrapolate_sample(to_timestamp, raw_data))\n return\n # yield sample before first raw data if missing\n if first_raw_data.timestamp != from_timestamp:\n leading_raw_data = self._get_leading_raw_data(\n max(self.from_timestamp, from_timestamp))\n if leading_raw_data:\n first_sample = self._interpolate_sample(\n from_timestamp, leading_raw_data, first_raw_data)\n else:\n first_sample = self._extrapolate_sample(\n from_timestamp, first_raw_data)\n yield self._subtract_offset(first_sample)\n # yield the sample of the first raw data\n yield self._subtract_offset(\n self.create_point_sample(\n first_raw_data.timestamp,\n PhysicalQuantity(first_raw_data.value, self.unit)))\n final_raw_data = first_raw_data\n # yield samples for remaining raw data\n for raw_data in raw_data_iterator:\n yield self._subtract_offset(\n self.create_point_sample(\n raw_data.timestamp,\n PhysicalQuantity(raw_data.value, self.unit)))\n final_raw_data = raw_data\n # yield final sample after final raw data if missing\n if final_raw_data.timestamp != to_timestamp:\n following_raw_data = self._get_following_raw_data(\n min(self.to_timestamp, to_timestamp))\n if following_raw_data:\n final_sample = self._interpolate_sample(\n to_timestamp, final_raw_data, following_raw_data)\n else:\n final_sample = self._extrapolate_sample(\n to_timestamp, final_raw_data)\n yield self._subtract_offset(final_sample)\n\n\nclass PulseAccumulationPeriodAdapter(AccumulationPeriodAdapterBase):\n @cached_property\n def _conversion_factor(self):\n pulse_quantity = PhysicalQuantity(\n self.period.pulse_quantity, 'impulse')\n output_quantity = PhysicalQuantity(\n self.period.output_quantity, self.period.output_unit)\n return output_quantity / pulse_quantity\n\n def _convert_sample(self, sample):\n return sample._replace(\n physical_quantity=self._conversion_factor *\n sample.physical_quantity)\n\n def _get_converted_samples(self, from_timestamp, to_timestamp):\n return itertools.imap(\n self._convert_sample,\n self._get_raw_samples(\n from_timestamp, to_timestamp))\n\n\nclass NonpulseAccumulationPeriodAdapter(AccumulationPeriodAdapterBase):\n def _get_converted_samples(self, from_timestamp, to_timestamp):\n return self._get_raw_samples(from_timestamp, to_timestamp)\n\n\nclass UnsupportedPeriodAdapter(AccumulationPeriodAdapterBase):\n # SingleValueAccumulationPeriod, ConversionAccumulationPeriod: Avoid\n # crashing --- but make no further promises...\n def get_samples(self, from_timestamp, to_timestamp):\n return []\n\n\ndef wrap_period(period):\n if isinstance(period, NonpulseAccumulationPeriodMixin):\n return NonpulseAccumulationPeriodAdapter(period)\n elif isinstance(period, PulseAccumulationPeriodMixin):\n return PulseAccumulationPeriodAdapter(period)\n else:\n return UnsupportedPeriodAdapter(period)\n\n\nclass NonaccumulationPeriodAdapter(PeriodAdapterBase):\n def _get_samples(self, from_timestamp, to_timestamp):\n return self._get_samples_pure_implementation(\n from_timestamp, to_timestamp)\n\n def _get_samples_pure_implementation(self, from_timestamp, to_timestamp):\n assert hasattr(self, 'datasource')\n assert from_timestamp <= to_timestamp\n\n raw_data_iterator = iter(\n self.datasource.rawdata_set.filter(\n timestamp__gte=max(from_timestamp, self.from_timestamp),\n timestamp__lte=min(to_timestamp, self.to_timestamp)))\n\n try:\n first_raw_data = next(raw_data_iterator)\n except StopIteration:\n leading_raw_data = self._get_leading_raw_data(from_timestamp)\n following_raw_data = self._get_following_raw_data(to_timestamp)\n if leading_raw_data is not None and following_raw_data is not None:\n if from_timestamp == to_timestamp:\n # single sample interpolated\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, following_raw_data)\n else:\n # two samples interpolated\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, following_raw_data)\n yield self._interpolate_sample(\n to_timestamp, leading_raw_data, following_raw_data)\n return\n\n # yield sample before first raw data if missing\n if first_raw_data.timestamp != from_timestamp:\n leading_raw_data = self._get_leading_raw_data(from_timestamp)\n if leading_raw_data:\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, first_raw_data)\n\n # yield the sample of the first raw data\n yield self.create_point_sample(\n first_raw_data.timestamp,\n PhysicalQuantity(first_raw_data.value, self.unit))\n final_raw_data = first_raw_data\n\n # yield samples for remaining raw data\n for raw_data in raw_data_iterator:\n yield self.create_point_sample(\n raw_data.timestamp,\n PhysicalQuantity(raw_data.value, self.unit))\n final_raw_data = raw_data\n\n # yield final sample after final raw data if missing\n if final_raw_data.timestamp != to_timestamp:\n following_raw_data = self._get_following_raw_data(to_timestamp)\n if following_raw_data:\n yield self._interpolate_sample(\n to_timestamp, final_raw_data, following_raw_data)\n\n\nclass NonaccumulationAdapter(DataSequenceAdapterUnicodeMixin, DataSeries):\n datasequence = models.ForeignKey(\n NonaccumulationDataSequence,\n on_delete=models.PROTECT, related_name='+')\n\n class Meta:\n verbose_name = _('nonaccumulation adapter')\n verbose_name_plural = _('nonaccumulation adapters')\n\n def get_recursive_condense_resolution(self, resolution):\n if condense.RESOLUTIONS.index(resolution) >= \\\n condense.RESOLUTIONS.index(condense.DAYS):\n return None\n else:\n return condense.next_resolution(resolution)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n input_periods = iter(\n NonaccumulationPeriodAdapter(period)\n for period in self.datasequence.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'))\n\n for input_period in input_periods:\n for sample in input_period.get_samples(\n max(from_timestamp, input_period.from_timestamp),\n min(to_timestamp, input_period.to_timestamp)):\n # Adhere to postcondition defined by DataSeries.get_samples().\n if sample.timestamp != input_period.to_timestamp or \\\n input_period.to_timestamp == to_timestamp:\n yield sample\n" }, { "alpha_fraction": 0.5837492346763611, "alphanum_fraction": 0.6053944826126099, "avg_line_length": 32.583805084228516, "blob_id": "459424ef3b99c05403e8136faf49381b99397d38", "content_id": "ca790d982130d621981d45c93e14f11d7b2108b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17833, "license_type": "no_license", "max_line_length": 79, "num_lines": 531, "path": "/legacy/rules/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nUnittests for the rules package.\n\"\"\"\n\nimport StringIO\nimport datetime\nimport inspect\nimport itertools\nimport urllib2\nfrom mock import Mock, patch\n\nfrom django.core import mail\nfrom django.test import TestCase as DjangoTestCase\nfrom django.test.utils import override_settings\n\nimport pytz\n\nfrom gridplatform import trackuser\nfrom gridplatform.customers.models import Customer\nfrom legacy.devices.models import Agent, Meter\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import DataSeries\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.providers.models import Provider\n\nfrom .models import (\n TriggeredRule,\n Action,\n RelayAction,\n Invariant,\n EmailAction,\n PhoneAction,\n InputInvariant,\n IndexInvariant,\n AgentRule,\n TURN_ON,\n TURN_OFF,\n agentserver)\nfrom . import engine\n\n\nclass TestCase(DjangoTestCase):\n \"\"\"\n Custom TestCase implementation, to provide module specific\n assertion methods.\n \"\"\"\n\n def assertAny(self, l, f):\n \"\"\"\n Custom assertion method, for checking if a function evaluates\n to true on at least one element in a list.\n\n @raise AssertionError: If C{f(e)} does not evaluate to C{True}\n for any element in C{c in l}, an C{AssertionError} is raised.\n \"\"\"\n try:\n next(itertools.ifilter(f, l))\n except StopIteration:\n try:\n function = inspect.getsource(f)\n except IOError:\n function = repr(f)\n raise AssertionError(\"No element in %r was matched by\\n%s\" %\n (l, function))\n\n\nclass AgentRuleTest(TestCase):\n \"\"\"\n Test the L{AgentRule} class.\n \"\"\"\n def setUp(self):\n \"\"\"\n Initializes self.meter and self.agent prior to each test.\n \"\"\"\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.agent = Agent(\n mac='08:00:27:03:fe:c7',\n customer=self.customer)\n self.agent.save()\n\n self.meter = Meter(\n agent=self.agent,\n manufactoring_id=155173425101,\n connection_type=Meter.GRIDPOINT,\n customer=self.customer)\n self.meter.save()\n\n def test_unicode(self):\n \"\"\"\n Test unicode operator.\n \"\"\"\n unit1 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(meter=self.meter, relay_action=TURN_OFF))\n unit2 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(meter=self.meter, relay_action=TURN_ON))\n\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n def test_representation(self):\n \"\"\"\n Test representation operator.\n \"\"\"\n unit1 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(meter=self.meter, relay_action=TURN_OFF))\n\n unit2 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(meter=self.meter, relay_action=TURN_ON))\n\n self.assertNotEqual(repr(unit1), repr(unit2))\n\n def test_comparison(self):\n \"\"\"\n Test comparison operators\n \"\"\"\n unit1 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(relay_action=TURN_OFF))\n\n unit2 = AgentRule(\n datetime.datetime(2012, 10, 4, 12, 00, tzinfo=pytz.utc),\n RelayAction(relay_action=TURN_ON))\n\n self.assertTrue(unit1 < unit2)\n self.assertTrue(unit1 <= unit2)\n self.assertFalse(unit1 > unit2)\n self.assertFalse(unit1 >= unit2)\n self.assertEqual(unit1, unit1)\n self.assertTrue(unit1 != unit2)\n\n\nclass InvariantTest(TestCase):\n \"\"\"\n Tests the L{Variant} specializations L{IndexInvariant} and\n L{InputInvariant}.\n \"\"\"\n def test_input_invariant(self):\n \"\"\"\n Test InputInvariant\n \"\"\"\n unit = InputInvariant(value=10, operator=Invariant.LT, unit='watt')\n self.assertTrue(unit.compare_value(PhysicalQuantity(9, 'watt')))\n self.assertFalse(unit.compare_value(PhysicalQuantity(11, 'watt')))\n self.assertFalse(unit.compare_value(PhysicalQuantity(10, 'watt')))\n\n def test_input_invariant_absolute_fahrenheit(self):\n ds = DataSeries(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n unit = InputInvariant(\n data_series=ds, value=10, operator=Invariant.LT, unit='fahrenheit')\n # 10 F (absolute) = 260.93 K\n\n # 260 K < 260.93 K\n self.assertTrue(unit.compare_value(PhysicalQuantity(260, 'kelvin')))\n # 261 K >= 260.93 K\n self.assertFalse(unit.compare_value(PhysicalQuantity(261, 'kelvin')))\n\n def test_input_invariant_relative_fahrenheit(self):\n ds = DataSeries(\n role=DataRoleField.RELATIVE_TEMPERATURE,\n unit='millikelvin',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n unit = InputInvariant(\n data_series=ds, value=10, operator=Invariant.LT, unit='fahrenheit')\n\n self.assertTrue(unit.compare_value(PhysicalQuantity(9, 'rankine')))\n self.assertFalse(unit.compare_value(PhysicalQuantity(11, 'rankine')))\n\n def test_input_invariant_absolute_celsius(self):\n ds = DataSeries(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n unit = InputInvariant(\n data_series=ds, value=10, operator=Invariant.LT, unit='celsius')\n # 10 C (absolute) = 283.15 K\n\n # 283 K < 283.15 K\n self.assertTrue(unit.compare_value(PhysicalQuantity(283, 'kelvin')))\n # 284 K >= 283.15 K\n self.assertFalse(unit.compare_value(PhysicalQuantity(284, 'kelvin')))\n\n def test_input_invariant_relative_celsius(self):\n ds = DataSeries(\n role=DataRoleField.RELATIVE_TEMPERATURE,\n unit='millikelvin',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n unit = InputInvariant(\n data_series=ds, value=10, operator=Invariant.LT, unit='celsius')\n\n self.assertTrue(unit.compare_value(PhysicalQuantity(9, 'kelvin')))\n self.assertFalse(unit.compare_value(PhysicalQuantity(11, 'kelvin')))\n\n def test_index_invariant(self):\n \"\"\"\n Test IndexInvariant\n \"\"\"\n unit = IndexInvariant(value=10, operator=Invariant.LT,\n unit='currency_dkk*watt^-1*hour^-1')\n self.assertTrue(\n unit.compare_value(\n PhysicalQuantity(9, 'currency_dkk*watt^-1*hour^-1')))\n self.assertFalse(\n unit.compare_value(\n PhysicalQuantity(11, 'currency_dkk*watt^-1*hour^-1')))\n self.assertFalse(\n unit.compare_value(\n PhysicalQuantity(10, 'currency_dkk*watt^-1*hour^-1')))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestAction(TestCase):\n \"\"\"\n Test various forms of Actions\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.agent = Agent(\n mac='08:00:27:03:fe:c7',\n customer=self.customer)\n self.agent.save()\n self.meter1 = Meter(\n name_plain=\"Meter1\",\n agent=self.agent,\n manufactoring_id=155173425101,\n connection_type=Meter.GRIDPOINT,\n customer=self.customer)\n self.meter1.save()\n self.meter2 = Meter(\n name_plain=\"Meter2\",\n agent=self.agent,\n manufactoring_id=155173425221,\n connection_type=Meter.GRIDPOINT,\n customer=self.customer)\n self.meter2.save()\n\n def test_relay_action_internationalization(self):\n \"\"\"\n Test that the unicode representation of L{RelayAction} reveals\n differences between TURN_OFF and TURN_ON, and the same action\n on two different meters.\n \"\"\"\n unit1 = RelayAction(\n meter=self.meter1, relay_action=TURN_OFF)\n unit2 = RelayAction(\n meter=self.meter1, relay_action=TURN_ON)\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n unit1 = RelayAction(\n meter=self.meter1, relay_action=TURN_OFF)\n unit2 = RelayAction(\n meter=self.meter2, relay_action=TURN_OFF)\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n def test_email_action_internationalization(self):\n \"\"\"\n Test that the unicode representation of L{EmailAction} reveals\n differences between different recipients and between different\n messages.\n \"\"\"\n unit1 = EmailAction(recipient=\"[email protected]\", message=\"boo!\")\n unit2 = EmailAction(recipient=\"[email protected]\", message=\"boo!\")\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n unit1 = EmailAction(recipient=\"[email protected]\", message=\"boo!\")\n unit2 = EmailAction(recipient=\"[email protected]\", message=\"yay!\")\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n def test_phone_action_internationalization(self):\n \"\"\"\n Test that the unicode representation of L{PhoneAction} reveals\n differences between different phone numbers and between different\n messages.\n \"\"\"\n unit1 = PhoneAction(phone_number=\"555-BATPHONE\", message=\"boo!\")\n unit2 = PhoneAction(phone_number=\"1-800-U-SQUEAL\", message=\"boo!\")\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n unit1 = PhoneAction(phone_number=\"555-BATPHONE\", message=\"boo!\")\n unit2 = PhoneAction(phone_number=\"555-BATPHONE\", message=\"yay!\")\n self.assertNotEqual(unicode(unit1), unicode(unit2))\n\n def test_abstract_method(self):\n \"\"\"\n Test that relevant exception is raised when calling\n unimplemented C{execute()} method.\n \"\"\"\n unit = Action()\n self.assertRaises(NotImplementedError, unit.execute)\n\n def test_email_action(self):\n \"\"\"\n Test that as a consequence of executing an L{EmailAction}\n Django is convinced an email has been sent.\n \"\"\"\n unit = EmailAction(recipient=\"[email protected]\",\n message=\"Message send from unit-test\")\n self.assertEqual(len(mail.outbox), 0)\n unit.execute()\n self.assertEqual(len(mail.outbox), 1)\n\n def test_phone_action(self):\n \"\"\"\n Test execution of PhoneAction.\n\n To avoid paying for a SMS text message everytime someone runs\n a unit-test (and to avoid requiring an internet connection), a\n C{UrlOpenShunt} is used.\n \"\"\"\n class UrlOpenShunt(object):\n def __enter__(self):\n urllib2.install_opener(self)\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n urllib2.install_opener(None)\n return False\n\n def open(self, url, data, timeout):\n self.url = url\n return StringIO.StringIO(\"ID: URL open shunt\")\n\n with UrlOpenShunt() as url_open_shunt:\n\n unit = PhoneAction(phone_number=\"555-BATPHONE\",\n message=\"Test message with + sign\")\n unit.execute()\n\n self.assertEqual(\n url_open_shunt.url,\n \"http://api.clickatell.com/http/sendmsg?\"\n \"user=gridmanager&password=1GridManager2Go\"\n \"&api_id=3191312&to=555-BATPHONE&\"\n \"text=Test+message+with+%2B+sign&concat=1\")\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestEngine(TestCase):\n \"\"\"\n Test the rule engine.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.agent = Agent.objects.create(\n mac=0xbeefbeefbeef,\n online=True,\n customer=self.customer)\n\n self.meter = Meter.objects.create(\n agent=self.agent,\n manufactoring_id=123456789,\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n relay_enabled=True,\n name_plain='Our test meter',\n customer=self.customer)\n\n def tearDown(self):\n pass\n\n @patch(\"legacy.rules.models.agentserver.relay_state\", Mock())\n def test_celsius_triggered_rule(self):\n \"\"\"\n Test a rule that triggers when a absolute celsius input crosses a\n threshold.\n \"\"\"\n\n ds = DataSeries.objects.create(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n rule = TriggeredRule.objects.create(\n name_plain='test rule',\n timezone='Europe/Copenhagen',\n customer=self.customer)\n\n rule.inputinvariant_set.create(\n data_series=ds,\n value=1,\n operator=Invariant.LT,\n unit='celsius')\n\n RelayAction.objects.create(\n rule=rule,\n execution_time=Action.INITIAL,\n meter=self.meter,\n relay_action=TURN_ON)\n\n engine_rules = rule.generate_rules(\n datetime.datetime(2013, 1, 1, 1, tzinfo=pytz.utc))\n\n ds.stored_data.create(\n value=275000,\n timestamp=datetime.datetime(2013, 1, 1, 1, tzinfo=pytz.utc))\n\n start_time = datetime.datetime(2013, 1, 1, 1, tzinfo=pytz.utc)\n for rule in engine_rules:\n map(lambda action: action.execute(), rule.process(start_time))\n self.assertFalse(agentserver.relay_state.called)\n\n ds.stored_data.create(\n value=272000,\n timestamp=datetime.datetime(2013, 1, 1, 1, 2, tzinfo=pytz.utc))\n\n start_time = datetime.datetime(2013, 1, 1, 1, 2, 30, tzinfo=pytz.utc)\n for rule in engine_rules:\n map(lambda action: action.execute(), rule.process(start_time))\n self.assertTrue(agentserver.relay_state.called)\n agentserver.relay_state.assert_called_with(\n self.meter.agent.mac,\n [(self.meter.connection_type, self.meter.manufactoring_id)],\n TURN_ON)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestEngineRefreshRules(TestCase):\n \"\"\"\n Test the {engine.refresh_rules()} procedure\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n customer = Customer()\n customer.save()\n self.customer = customer\n trackuser._set_customer(self.customer)\n\n agent = Agent.objects.create(\n mac=0xbeefbeefbeef,\n online=True,\n customer=self.customer)\n\n meter = Meter.objects.create(\n agent=agent,\n manufactoring_id=123456789,\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n online=True,\n relay_enabled=True,\n name_plain='Our test meter',\n customer=self.customer)\n\n ds = DataSeries.objects.create(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n customer=customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n self.ds2 = DataSeries.objects.create(\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n customer=customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n rule = TriggeredRule.objects.create(\n name_plain='test rule',\n timezone='Europe/Copenhagen',\n customer=customer)\n\n self.input_invariant = rule.inputinvariant_set.create(\n data_series=ds,\n value=1,\n operator=Invariant.LT,\n unit='celsius')\n\n RelayAction.objects.create(\n rule=rule,\n execution_time=Action.INITIAL,\n meter=meter,\n relay_action=TURN_ON)\n\n self.hour = datetime.datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.rules = set(engine.get_engine_rules(self.hour))\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_no_changes(self):\n self.assertEqual(\n self.rules,\n engine.refresh_rules(self.rules, self.hour))\n\n def test_changed_input_invariant_value(self):\n self.input_invariant.value = 2\n self.input_invariant.save()\n self.assertNotEqual(\n self.rules,\n engine.refresh_rules(self.rules, self.hour))\n\n def test_changed_input_invariant_operator(self):\n self.input_invariant.operator = Invariant.GT\n self.input_invariant.save()\n self.assertNotEqual(\n self.rules,\n engine.refresh_rules(self.rules, self.hour))\n\n def test_changed_input_invariant_unit(self):\n self.input_invariant.unit = 'fahrenheit'\n self.input_invariant.save()\n self.assertNotEqual(\n self.rules,\n engine.refresh_rules(self.rules, self.hour))\n\n def test_changed_input_invariant_data_series(self):\n self.input_invariant.data_series = self.ds2\n self.input_invariant.save()\n self.assertNotEqual(\n self.rules,\n engine.refresh_rules(self.rules, self.hour))\n" }, { "alpha_fraction": 0.6744186282157898, "alphanum_fraction": 0.6782945990562439, "avg_line_length": 18.846153259277344, "blob_id": "0a9d66ff8008853393cde2ba8dcd84a6d4828420", "content_id": "327b16d4174b185a39b4449667d2f47240f4f089", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 258, "license_type": "no_license", "max_line_length": 46, "num_lines": 13, "path": "/gridplatform/jserror/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import jserror\n\n\nurlpatterns = patterns(\n '',\n url('^$', jserror, name='jserror-jserror')\n)\n" }, { "alpha_fraction": 0.6507073044776917, "alphanum_fraction": 0.6531556248664856, "avg_line_length": 34.346153259277344, "blob_id": "e625c91f219a7d4848332ff08ce21e7c27dc050f", "content_id": "ccf5fa26c40d9e6c9a04ae1f397feed9fca6e434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3676, "license_type": "no_license", "max_line_length": 79, "num_lines": 104, "path": "/gridplatform/token_auth/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport binascii\nimport hashlib\nimport hmac\nimport uuid\n\nfrom django.db import models\nfrom django.utils.encoding import force_bytes\nfrom django.utils.translation import ugettext_lazy as _\n\n\nfrom Crypto.Cipher import AES\nfrom Crypto import Random\n\nfrom .conf import settings\n\nHMAC_HEX_LENGTH = 40\nIV_LENGTH = AES.block_size\n\nTOKEN_LENGTH = HMAC_HEX_LENGTH + IV_LENGTH * 2 + \\\n settings.TOKEN_AUTH_USER_PASSWORD_LENGTH * 2\n\n\ndef create_token(user, password):\n \"\"\"\n Construct a new authentication token for the specified user; assuming/using\n the specified login (and data decryption) password.\n \"\"\"\n token_data, created = TokenData.objects.get_or_create(user=user)\n return token_data.provide_token(password)\n\n\nclass TokenData(models.Model):\n \"\"\"\n Extra information necessary to provide API tokens for a specific `User`.\n\n Token users are assumed to not be normal login users, and to have passwords\n of length `settings.TOKEN_AUTH_USER_PASSWORD_LENGTH`. (Passwords still\n necessary to support encryption system.)\n \"\"\"\n key = models.CharField(\n _('token identifier'), max_length=HMAC_HEX_LENGTH, primary_key=True)\n user = models.OneToOneField('users.User', verbose_name=_('user'))\n cipher = models.BinaryField(_('cipher to decrypt tokens'))\n\n def save(self, *args, **kwargs):\n if not self.key:\n self.key = hmac.new(\n uuid.uuid4().bytes, digestmod=hashlib.sha1).hexdigest()\n if not self.cipher:\n self.cipher = Random.new().read(settings.ENCRYPTION_AES_KEYLENGTH)\n return super(TokenData, self).save(*args, **kwargs)\n\n def provide_token(self, password):\n \"\"\"\n Construct a token string for the specified `password`.\n\n :note: The password is not validated for the user; if invalid, the\n resulting token string will not be usable for API login.\n \"\"\"\n password_bytes = force_bytes(password)\n assert len(password_bytes) == settings.TOKEN_AUTH_USER_PASSWORD_LENGTH\n iv = Random.new().read(IV_LENGTH)\n cipher = AES.new(self.cipher, AES.MODE_CFB, iv)\n encrypted_password = cipher.encrypt(password_bytes)\n return b''.join([\n force_bytes(self.key),\n binascii.hexlify(iv),\n binascii.hexlify(encrypted_password)])\n\n def decrypt_password(self, token):\n \"\"\"\n Decrypt/extract the password part from the specified `token`.\n\n :note: Invalid tokens will still decrypt to something, if they have the\n appropriate form --- correct length and containing only valid\n hexadecimal characters.\n \"\"\"\n assert len(token) == TOKEN_LENGTH, \\\n b'Token {} wrong length'.format(token)\n non_key = token[HMAC_HEX_LENGTH:]\n iv = binascii.unhexlify(non_key[:IV_LENGTH * 2])\n encrypted_password = binascii.unhexlify(non_key[IV_LENGTH * 2:])\n cipher = AES.new(self.cipher, AES.MODE_CFB, iv)\n return cipher.decrypt(encrypted_password)\n\n @classmethod\n def lookup_token(cls, token):\n \"\"\"\n Only part of a token string is actually saved (the _key_). This method\n extracts the key from a given token and returns the corresponding\n :class:`.TokenData` instance.\n\n :rtype: :class:`.TokenData`\n\n :param token: The given token string containing _key_.\n \"\"\"\n assert len(token) == TOKEN_LENGTH, \\\n b'Token {} wrong length'.format(token)\n key = token[:HMAC_HEX_LENGTH]\n return cls.objects.get(key=key)\n" }, { "alpha_fraction": 0.6199678182601929, "alphanum_fraction": 0.6215780973434448, "avg_line_length": 31.6842098236084, "blob_id": "d2a768ee111411a4afbf58e7c838f9777d48d087", "content_id": "e8b518fd06145e8d2a809e8dab155954adc6b516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 621, "license_type": "no_license", "max_line_length": 77, "num_lines": 19, "path": "/legacy/website/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'legacy.website.views',\n url(r'^$',\n 'find_home',\n name='website-home'),\n url(r'^login/$', 'login', name='website-login'),\n url(r'^logout/$', 'logout', name='website-logout'),\n url(r'^legacy_task_status/$', 'task_status', name='website-task_status'),\n url(r'^cancel_task/$', 'cancel_task', name='website-cancel_task'),\n url(r'^json_task_result/$', 'json_task_result',\n name='website-json_task_result'),\n)\n" }, { "alpha_fraction": 0.4753694534301758, "alphanum_fraction": 0.484674334526062, "avg_line_length": 41.242774963378906, "blob_id": "b5707aa7001890ad637909b4c6fe352c3e0a0f8b", "content_id": "d25958c36398415a572f7c446d8f99e455fc092c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7308, "license_type": "no_license", "max_line_length": 126, "num_lines": 173, "path": "/emonhub/src/interfacers/EmonHubMqttInterfacer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"class EmonHubMqttGenInterfacer\n\n\"\"\"\nimport time\nimport paho.mqtt.client as mqtt\nfrom pydispatch import dispatcher\nfrom emonhub_interfacer import EmonHubInterfacer\nimport Cargo\n\nclass EmonHubMqttInterfacer(EmonHubInterfacer):\n\n def __init__(self, name, mqtt_user=\" \", mqtt_passwd=\" \", mqtt_host=\"127.0.0.1\", mqtt_port=1883):\n # Initialization\n super(EmonHubMqttInterfacer, self).__init__(name)\n \n self._log.info(str(name)+\" Init mqtt_host=\"+str(mqtt_host)+\" mqtt_port=\"+str(mqtt_port)+ \" mqtt_user=\"+str(mqtt_user))\n self._name = name\n self._host = mqtt_host\n self._port = mqtt_port\n self._user = mqtt_user\n self._passwd = mqtt_passwd\n self._connected = False\n \n self._settings = {\n 'subchannels':['ch1'],\n 'pubchannels':['ch2'],\n \n # emonhub/rx/10/values format - default emoncms nodes module\n 'node_format_enable': 1,\n 'node_format_basetopic': 'emonhub/',\n \n # nodes/emontx/power1 format\n 'nodevar_format_enable': 0,\n 'nodevar_format_basetopic': \"nodes/\"\n };\n\n self._mqttc = mqtt.Client()\n self._mqttc.on_connect = self.on_connect\n self._mqttc.on_disconnect = self.on_disconnect\n self._mqttc.on_message = self.on_message\n self._mqttc.on_subscribe = self.on_subscribe\n \n\n def action(self):\n if not self._connected:\n self._log.info(\"Connecting to MQTT Server\")\n try:\n self._mqttc.username_pw_set(self._user, self._passwd)\n self._mqttc.connect(self._host, self._port, 60)\n except:\n self._log.info(\"Could not connect...\")\n time.sleep(1.0)\n self._mqttc.loop(0)\n \n def on_connect(self, client, userdata, flags, rc):\n \n connack_string = {0:'Connection successful',\n 1:'Connection refused - incorrect protocol version',\n 2:'Connection refused - invalid client identifier',\n 3:'Connection refused - server unavailable',\n 4:'Connection refused - bad username or password',\n 5:'Connection refused - not authorised'}\n\n if rc:\n self._log.warning(connack_string[rc])\n else:\n self._log.info(\"connection status: \"+connack_string[rc])\n self._connected = True\n # Subscribe to MQTT topics\n self._mqttc.subscribe(str(self._settings[\"node_format_basetopic\"])+\"tx/#\")\n \n self._log.debug(\"CONACK => Return code: \"+str(rc))\n\n def on_disconnect(self, client, userdata, rc):\n if rc != 0:\n self._log.info(\"Unexpected disconnection\")\n self._connected = False\n \n def on_subscribe(self, mqttc, obj, mid, granted_qos):\n self._log.info(\"on_subscribe\")\n\n def on_message(self, client, userdata, msg):\n topic_parts = msg.topic.split(\"/\")\n \n if topic_parts[0] == self._settings[\"node_format_basetopic\"][:-1]:\n if topic_parts[1] == \"tx\":\n if topic_parts[3] == \"values\":\n nodeid = int(topic_parts[2])\n \n payload = msg.payload\n realdata = payload.split(\",\")\n self._log.debug(\"Nodeid: \"+str(nodeid)+\" values: \"+msg.payload)\n\n rxc = Cargo.new_cargo(realdata=realdata)\n rxc.nodeid = nodeid\n\n if rxc:\n # rxc = self._process_tx(rxc)\n if rxc:\n for channel in self._settings[\"pubchannels\"]:\n dispatcher.send(channel, cargo=rxc)\n self._log.debug(str(rxc.uri) + \" Sent to channel' : \" + str(channel))\n\n def receiver(self, cargo):\n if self._connected:\n # ----------------------------------------------------------\n # General MQTT format: emonhub/rx/emonpi/power1 ... 100\n # ----------------------------------------------------------\n if int(self._settings[\"nodevar_format_enable\"])==1:\n \n # Node id or nodename if given\n nodestr = str(cargo.nodeid)\n if cargo.nodename!=False: nodestr = str(cargo.nodename)\n \n varid = 1\n for value in cargo.realdata:\n # Variable id or variable name if given\n varstr = str(varid)\n if (varid-1)<len(cargo.names):\n varstr = str(cargo.names[varid-1])\n # Construct topic\n topic = self._settings[\"nodevar_format_basetopic\"]+nodestr+\"/\"+varstr\n payload = str(value)\n \n self._log.info(\"Publishing: \"+topic+\" \"+payload)\n result =self._mqttc.publish(topic, payload=payload, qos=2, retain=False)\n \n if result[0]==4:\n self._log.info(\"Publishing error? returned 4\")\n \n varid += 1\n \n # RSSI\n topic = self._settings[\"nodevar_format_basetopic\"]+nodestr+\"/rssi\"\n payload = str(cargo.rssi)\n self._log.info(\"Publishing: \"+topic+\" \"+payload)\n result =self._mqttc.publish(topic, payload=payload, qos=2, retain=False)\n \n # ---------------------------------------------------------- \n # Emoncms nodes module format: emonhub/rx/10/values ... 100,200,300\n # ----------------------------------------------------------\n if int(self._settings[\"node_format_enable\"])==1:\n \n topic = self._settings[\"node_format_basetopic\"]+\"rx/\"+str(cargo.nodeid)+\"/values\"\n payload = \",\".join(map(str,cargo.realdata))\n \n self._log.info(\"Publishing: \"+topic+\" \"+payload)\n result =self._mqttc.publish(topic, payload=payload, qos=2, retain=False)\n \n if result[0]==4:\n self._log.info(\"Publishing error? returned 4\")\n \n # RSSI\n topic = self._settings[\"node_format_basetopic\"]+\"rx/\"+str(cargo.nodeid)+\"/rssi\"\n payload = str(cargo.rssi)\n \n self._log.info(\"Publishing: \"+topic+\" \"+payload)\n result =self._mqttc.publish(topic, payload=payload, qos=2, retain=False)\n \n if result[0]==4:\n self._log.info(\"Publishing error? returned 4\")\n \n \n def set(self, **kwargs):\n for key,setting in self._settings.iteritems():\n if key in kwargs.keys():\n # replace default\n self._settings[key] = kwargs[key]\n \n # Subscribe to internal channels \n for channel in self._settings[\"subchannels\"]:\n dispatcher.connect(self.receiver, channel)\n self._log.debug(self._name+\" Subscribed to channel' : \" + str(channel))\n" }, { "alpha_fraction": 0.6897590160369873, "alphanum_fraction": 0.6927710771560669, "avg_line_length": 31.129032135009766, "blob_id": "a4540f5d2b2f3bd65fce142a110fbc1f7859e044", "content_id": "88d53dbdd020d028df37f37cf318bfaa83094735", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 996, "license_type": "no_license", "max_line_length": 79, "num_lines": 31, "path": "/legacy/measurementpoints/management/commands/export_measurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom cStringIO import StringIO\n\nfrom pytz import utc\nfrom django.core.management.base import BaseCommand\n\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.export import consumption_report\n\n\nclass Command(BaseCommand):\n args = ''\n help = ''\n\n def handle(self, *args, **options):\n to_timestamp = datetime.datetime.now(utc) - RelativeTimeDelta(hours=1)\n from_timestamp = to_timestamp - RelativeTimeDelta(days=1)\n mp_ids = map(int, args)\n mp_map = {mp.id: mp for mp in Collection.objects.filter(id__in=mp_ids)}\n # get them in the input/specified order...\n mps = [mp_map[mp_id] for mp_id in mp_ids]\n\n f = StringIO()\n consumption_report(mps, from_timestamp, to_timestamp, f)\n\n # print(f.getvalue(), end='')\n" }, { "alpha_fraction": 0.6119096279144287, "alphanum_fraction": 0.6129363179206848, "avg_line_length": 33.78571319580078, "blob_id": "46d5ccb81455421b3101d4dcfd190d2e2256779e", "content_id": "f8bf83fc128d9a8352e1f9b27778c0b0aa2978d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 974, "license_type": "no_license", "max_line_length": 62, "num_lines": 28, "path": "/legacy/display_widgets/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'legacy.display_widgets.views',\n url(r'^$', 'dashboard',\n name='display_widgets-dashboard'),\n url(r'^fullscreen/$', 'dashboard_fullscreen',\n name='display_widgets-dashboard-fullscreen'),\n url(r'^remove/$',\n 'remove_from_dashboard',\n name='display_widgets-remove-from-dashboard'),\n url(r'^add/(?P<pk>\\d+)/(?P<widget_type>\\d+)$',\n 'add_to_dashboard',\n name='display_widgets-add-to-dashboard'),\n url(r'^remove_specific/(?P<pk>\\d+)/(?P<widget_type>\\d+)$',\n 'remove_specific_widget',\n name='display_widgets-remove-specific-widget'),\n url(r'^update_order/$',\n 'update_order',\n name='display_widgets-update-order'),\n url('^async_gague/(?P<pk>\\d+)/$', 'async_gauge',\n name='display_widgets-async_gauge'),\n)\n" }, { "alpha_fraction": 0.7742998600006104, "alphanum_fraction": 0.7742998600006104, "avg_line_length": 30.947368621826172, "blob_id": "79b937dd35695a9ae2eec5a95d2175b91f0a5ce0", "content_id": "414e9564a7526894b34229dccd1b76e8617000a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 607, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/documentation/source/apps/gridplatform/productions.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Productions\n===========\n\n.. autoclass:: gridplatform.productions.models.Production\n :members: clean, get_unit_display\n\n.. autoclass:: gridplatform.productions.models.ProductionGroup\n :members: save, clean, development_sum, production_sequence,\n next_valid_date, previous_valid_date\n\n.. autoclass:: gridplatform.productions.models.Period\n\n.. autoclass:: gridplatform.productions.models.NonpulsePeriod\n\n.. autoclass:: gridplatform.productions.models.PulsePeriod\n\n.. autoclass:: gridplatform.productions.models.SingleValuePeriod\n\n.. autoclass:: gridplatform.productions.models.OfflineTolerance\n" }, { "alpha_fraction": 0.6411347389221191, "alphanum_fraction": 0.651063859462738, "avg_line_length": 16.19512176513672, "blob_id": "e445ebe4a6a20b5981c0d2de315196ef3c14bd3c", "content_id": "ad02b58fe68a8564c12d58ebf77c95f2398120a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 705, "license_type": "no_license", "max_line_length": 45, "num_lines": 41, "path": "/selenium_test_data.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nif [ -z \"$VIRTUAL_ENV\" ]\nthen\n echo \"ERROR: virtualenv not active\"\n exit -1\nfi\n\n# sudo -u postgres dropdb portal\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n dropdb -h localhost portal\nelse\n dropdb portal\nfi\n\nif [ $? -ne 0 ]\nthen\n echo \"ERROR: failed to drop database\"\n exit -1\nfi\n\n# sudo -u postgres createdb -O $USER portal\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n createdb -h localhost -E utf8 portal\nelse\n createdb -E utf8 portal\nfi\nif [ $? -ne 0 ]\nthen\n echo \"ERROR: failed to recreate database\"\n exit -1\nfi\n\necho 'Setting up tables'\n./manage.py syncdb --noinput --traceback\n./manage.py migrate --all --traceback\n\necho 'Setting up test data'\npython selenium_test_data.py\n" }, { "alpha_fraction": 0.6563771367073059, "alphanum_fraction": 0.6566163897514343, "avg_line_length": 40.37623596191406, "blob_id": "0962d240125c1ec598b37ee43232da898fd7e298", "content_id": "20def4ccea12903055a7fbeb3f0ea89fb839edb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4179, "license_type": "no_license", "max_line_length": 79, "num_lines": 101, "path": "/legacy/measurementpoints/proxies/consumptionmultiplicationpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Multiplication\n\nfrom .consumptionmeasurementpoint import ConsumptionMeasurementPoint\n\n\nclass ConsumptionMultiplicationPoint(ConsumptionMeasurementPoint):\n \"\"\"\n A C{ConsumptionMultiplicationPoint} is a L{ConsumptionMeasurementPoint}\n whose consumption is the consumption of another C{source_consumption_point}\n multiplied by a C{multiplier}.\n\n @ivar source_consumption_point: The source L{ConsumptionMeasurementPoint}.\n\n @ivar multiplier: The multiplier.\n \"\"\"\n class Meta:\n proxy = True\n verbose_name = _('Multiplication measurement point')\n verbose_name_plural = _('Multiplication measurement points')\n app_label = 'customers'\n\n def save(self, *args, **kwargs):\n \"\"\"\n C{ConsumptionMultiplicationPoint} specialization of\n L{ConsumptionMeasurementPoint.save()}.\n\n Construct C{consumption} from C{source_consumption_point} and\n C{multiplier}.\n \"\"\"\n if self.consumption is None:\n self.consumption = Multiplication(role=DataRoleField.CONSUMPTION)\n assert self.multiplier is not None\n assert self.source_consumption_point is not None\n assert self.consumption not in \\\n self.source_consumption_point.consumption.depends_on()\n self.consumption.multiplier = self.multiplier\n self.consumption.source_data_series = \\\n self.source_consumption_point.consumption\n for attr in ['customer', 'unit', 'utility_type']:\n setattr(\n self.consumption, attr,\n getattr(self.consumption.source_data_series, attr))\n if self.utility_type is None:\n self.utility_type = self.source_consumption_point.utility_type\n if self.role is None:\n self.role = self.source_consumption_point.role\n super(ConsumptionMultiplicationPoint, self).save(*args, **kwargs)\n\n def clean(self):\n \"\"\"\n C{ConsumptionMultiplicationPoint} specialization of\n L{ConsumptionMeasurementPoint.clean()}.\n\n Validate that a circular dependency is not about to be formed.\n \"\"\"\n super(ConsumptionMultiplicationPoint, self).clean()\n if self.consumption is not None and \\\n self.source_consumption_point and self.consumption in \\\n self.source_consumption_point.consumption.depends_on():\n raise ValidationError(\n _(u'{measurement_point} cannot be used in the '\n 'multiplication, as it would form a circular dependency.').\n format(measurement_point=self.source_consumption_point))\n\n def _get_source_consumption_point(self):\n if not hasattr(self, '_source_consumption_point'):\n self._source_consumption_point = None\n if self.consumption is not None and \\\n self.consumption.id is not None:\n self._source_consumption_point = \\\n ConsumptionMeasurementPoint.objects.get(\n graph__dataseries=self.consumption.\n source_data_series).subclass_instance\n return self._source_consumption_point\n\n def _set_source_consumption_point(self, source_consumption_point):\n self._source_consumption_point = source_consumption_point\n\n source_consumption_point = property(_get_source_consumption_point,\n _set_source_consumption_point)\n\n def _get_multiplier(self):\n if not hasattr(self, '_multiplier'):\n self._multiplier = None\n if self.consumption is not None:\n self._multiplier = \\\n self.consumption.subclass_instance.multiplier\n return self._multiplier\n\n def _set_multiplier(self, multiplier):\n self._multiplier = multiplier\n\n multiplier = property(_get_multiplier, _set_multiplier)\n" }, { "alpha_fraction": 0.6286752820014954, "alphanum_fraction": 0.6290056109428406, "avg_line_length": 32.63333511352539, "blob_id": "8eed782e894f83947f9676c6897aa3d99a0b79b0", "content_id": "466d526defa100061aaa000619de5ca3d48f843e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3027, "license_type": "no_license", "max_line_length": 78, "num_lines": 90, "path": "/legacy/manage_measurementpoints/forms/measurementpointform.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport traceback\nimport warnings\nfrom django import forms\n\nfrom legacy.manage_collections.views import NoUrlClearableFileInput\n\n\nclass MeasurementPointForm(forms.ModelForm):\n \"\"\"\n Maps proxy instance properties to form fields initial values, and\n the other way; maps fields from form to proxy instance properties.\n\n To take advantage of this functionaly, fill in the fields in the internal\n ProxyMeta class. Please notice that fields are mapped by their name.\n \"\"\"\n class ProxyMeta:\n fields = []\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @param utility_type: Optional argument to initialize resource type of\n C{self.instance}.\n \"\"\"\n utility_type = kwargs.pop('utility_type', None)\n super(MeasurementPointForm, self).__init__(*args, **kwargs)\n if utility_type:\n self.instance.utility_type = utility_type\n\n # Assign form fields intial values from corresponding model properties\n for field in self.ProxyMeta.fields:\n self.initial[field] = getattr(self.instance, field)\n\n if 'image' in self.fields:\n self.fields['image'].widget.__class__ = NoUrlClearableFileInput\n\n def clean(self):\n # Assign form fields to corresponding model properties. Must be done\n # before calling super clean() as super clean() will call clean on\n # self.instance.\n for field in self.ProxyMeta.fields:\n setattr(self.instance, field, self.cleaned_data.get(field, None))\n\n cleaned_data = super(MeasurementPointForm, self).clean()\n\n return cleaned_data\n\n def get_headline_display(self):\n \"\"\"\n To be called directly from template.\n\n @return: The localized headline to be used for this form.\n \"\"\"\n try:\n if self.instance.id:\n return self._get_edit_headline_display()\n else:\n return self._get_new_headline_display()\n except:\n # Django is kind enough to replace a useful stacktrace with\n # XYZXYZXYZ in template output. Until that error camouflage has\n # been removed, this remains a work-around.\n warnings.warn(\n '%s.get_headline_display() raised an exception\\n%s' %\n (self.__class__, traceback.format_exc()))\n raise\n\n def _get_new_headline_display(self):\n \"\"\"\n Abstract method.\n\n Not to be called directly. See L{get_headline_display}\n\n @return: The localized headline to be used for new measurement points.\n \"\"\"\n raise NotImplementedError()\n\n def _get_edit_headline_display(self):\n \"\"\"\n Abstract method.\n\n Not to be called directly. See L{get_headline_display}\n\n @return: The localized headline to be used for editing existing\n measurement points.\n \"\"\"\n raise NotImplementedError()\n" }, { "alpha_fraction": 0.5829400420188904, "alphanum_fraction": 0.5958748459815979, "avg_line_length": 36.149349212646484, "blob_id": "63658a2570934be5b8a771b67bd4e1293d1ac749", "content_id": "1da9cdaf3b91858b224039f2e233f03375757a89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5721, "license_type": "no_license", "max_line_length": 75, "num_lines": 154, "path": "/gridplatform/datasequences/models/test_energyconversion.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.core.exceptions import ValidationError\nfrom django.test.utils import override_settings\nimport pytz\n\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .energyconversion import EnergyPerVolumeDataSequence\nfrom .energyconversion import EnergyPerVolumePeriod\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VolumeToEnergyConversionTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n self.conversion = EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n\n def test_value_sequence_no_periods(self):\n from_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n self.assertEqual(\n list(\n self.conversion.period_set.value_sequence(\n from_timestamp, to_timestamp)),\n [])\n\n def test_value_sequence_data_before(self):\n from_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n datasource = CustomerDataSource.objects.create(\n customer=self.customer,\n unit='milliwatt*hour/meter^3')\n\n RawData.objects.bulk_create(\n [\n RawData(\n datasource=datasource,\n timestamp=from_timestamp - datetime.timedelta(hours=1),\n value=3),\n RawData(\n datasource=datasource,\n timestamp=from_timestamp + datetime.timedelta(hours=7),\n value=7)\n ])\n\n self.conversion.period_set.create(\n from_timestamp=from_timestamp,\n datasource=datasource)\n\n self.assertEqual(\n list(\n self.conversion.period_set.value_sequence(\n from_timestamp, to_timestamp)),\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(3, 'milliwatt*hour/meter^3'))\n for h in range(7)] +\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(7, 'milliwatt*hour/meter^3'))\n for h in range(7, 24)])\n\n def test_value_sequence_data_before_missing(self):\n from_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 1))\n to_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 2))\n\n datasource = CustomerDataSource.objects.create(\n customer=self.customer,\n unit='milliwatt*hour/meter^3')\n\n RawData.objects.bulk_create(\n [\n RawData(\n datasource=datasource,\n timestamp=from_timestamp + datetime.timedelta(hours=1),\n value=3),\n RawData(\n datasource=datasource,\n timestamp=from_timestamp + datetime.timedelta(hours=7),\n value=7)\n ])\n\n self.conversion.period_set.create(\n from_timestamp=from_timestamp,\n datasource=datasource)\n\n self.assertEqual(\n list(\n self.conversion.period_set.value_sequence(\n from_timestamp, to_timestamp)),\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(3, 'milliwatt*hour/meter^3'))\n for h in range(1, 7)] +\n [\n RangedSample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(7, 'milliwatt*hour/meter^3'))\n for h in range(7, 24)])\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass VolumeToEnergyConversionPeriodTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n self.conversion = EnergyPerVolumeDataSequence.objects.create(\n customer=self.customer)\n\n def test_full_clean_detects_bad_unit(self):\n from_timestamp = self.customer.timezone.localize(\n datetime.datetime(2014, 1, 1))\n\n datasource = CustomerDataSource.objects.create(\n customer=self.customer,\n unit='milliwatt*hour')\n\n period = EnergyPerVolumePeriod(\n datasequence=self.conversion,\n from_timestamp=from_timestamp,\n datasource=datasource)\n\n with self.assertRaises(ValidationError):\n period.full_clean()\n" }, { "alpha_fraction": 0.7003058195114136, "alphanum_fraction": 0.7079510688781738, "avg_line_length": 27.434782028198242, "blob_id": "59a25335a63c71fc41934c78c960c5f9b6e75f8c", "content_id": "1e09709ce64e16a8d31f813de247fc359782c770", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 89, "num_lines": 23, "path": "/gridplatform/tariffs/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom gridplatform.trackuser.tasks import task\n\n\n@task(bind=True)\ndef tariff_hourly_task(\n task, tariff_id, from_timestamp, to_timestamp):\n tariff = EnergyTariff.objects.get(pk=tariff_id)\n\n task.set_progress(0, 1)\n\n data = list(tariff.period_set.value_sequence(from_timestamp, to_timestamp))\n\n result = {}\n result['tariff_id'] = tariff_id\n result['data'] = list(tariff.period_set.value_sequence(from_timestamp, to_timestamp))\n task.set_progress(1, 1)\n\n return result\n" }, { "alpha_fraction": 0.7864460349082947, "alphanum_fraction": 0.7872340679168701, "avg_line_length": 38.65625, "blob_id": "e050db2ab01c9cd69e3fb556d2738545418d8a4e", "content_id": "6f44ec81c239528de9c9ddce259193f2a00d2d61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 77, "num_lines": 32, "path": "/documentation/source/apps/gridplatform/tariffs.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Tariffs\n=======\n\nTariffs were mentioned in the domain model under the section\n:ref:`data-sources`, and also in :ref:`main-consumptions`. To facilitate\nchanges in the domain, as mentioned in :ref:`changes-in-domain`, the\n:py:class:`~gridplatform.tariffs.models.Tariff` (and its subclasses\n:py:class:`~gridplatform.tariffs.models.EnergyTariff` and\n:py:class:`~gridplatform.tariffs.models.VolumeTariff`) is defined in terms of\nperiods; namely :py:class:`~gridplatform.tariffs.models.FixedPricePeriod` and\n:py:class:`~gridplatform.tariffs.models.SpotPricePeriod`. The periods are\nassociated to tariffs via the\n:py:class:`~gridplatform.tariffs.models.TariffPeriodManager`\n\n\nA simpler design for solving a simular task is described in\n:ref:`co2-conversions`.\n\n.. autoclass:: gridplatform.tariffs.models.Tariff\n\n.. autoclass:: gridplatform.tariffs.models.EnergyTariff\n\n.. autoclass:: gridplatform.tariffs.models.VolumeTariff\n\n.. autoclass:: gridplatform.tariffs.models.TariffPeriodManager\n :members: subscription_cost_sum, value_sequence\n\n.. autoclass:: gridplatform.tariffs.models.FixedPricePeriod\n :members: subscription_cost_sum, clean, get_unit_choices, _value_sequence\n\n.. autoclass:: gridplatform.tariffs.models.SpotPricePeriod\n :members: clean, _value_sequence\n" }, { "alpha_fraction": 0.6127309799194336, "alphanum_fraction": 0.6129363179206848, "avg_line_length": 38.918033599853516, "blob_id": "ccbf1f19722e9f213c36520ec59c92030d2dfbae", "content_id": "2af9a53954eb26f8f8017faded46bdd18a9073d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4870, "license_type": "no_license", "max_line_length": 85, "num_lines": 122, "path": "/energymanager/configuration_site/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\nfrom django.conf.urls import include\n\nfrom gridplatform.utils.urls import restricted_url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.configuration_site_view.views',\n url(r'^$',\n views.HomeView.as_view(),\n name='home'),\n url(r'^customer/(?P<customer_id>\\d+)/$',\n views.CustomerView.as_view(),\n name='customer'),\n url(r'^choose-customer/$',\n views.ChooseCustomer.as_view(),\n name='choose-customer'),\n\n url(r'^customerdatasource/(?P<customer_id>\\d+)/$',\n views.CustomerDataSourceList.as_view(),\n name='customer-datasource-list'),\n url(r'^customerdatasource/content/(?P<customer_id>\\d+)/$',\n views.CustomerDataSourceListContentView.as_view(),\n name='customer-datasource-list-content'),\n url(r'^customerdatasource/create/(?P<customer_id>\\d+)/$',\n views.CustomerDataSourceCreateView.as_view(),\n name='customer-datasource-create'),\n url(r'^customerdatasource/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.CustomerDataSourceUpdateView.as_view(),\n name='customer-datasource-update'),\n url(r'^customerdatasource/delete/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.CustomerDataSourceDeleteView.as_view(),\n name='customer-datasource-delete'),\n\n url(r'^consumption/(?P<customer_id>\\d+)/$',\n views.ConsumptionList.as_view(),\n name='consumption-list'),\n url(r'^consumption/content/(?P<customer_id>\\d+)/$',\n views.ConsumptionListContentView.as_view(),\n name='consumption-list-content'),\n url(r'^consumption/detail/(?P<customer_id>\\d+)/'\n r'(?P<pk>\\d+)/$',\n views.ConsumptionDetailView.as_view(),\n name='consumption-detail'),\n url(r'^consumption/create/(?P<customer_id>\\d+)/$',\n views.ConsumptionCreateView.as_view(),\n name='consumption-create'),\n url(r'^consumption/update/(?P<customer_id>\\d+)/'\n r'(?P<pk>\\d+)/$',\n views.ConsumptionUpdateView.as_view(),\n name='consumption-update'),\n url(r'^consumption/delete/(?P<customer_id>\\d+)/'\n r'(?P<pk>\\d+)/$',\n views.ConsumptionDeleteView.as_view(),\n name='consumption-delete'),\n\n url(r'^consumption/(?P<customer_id>\\d+)/'\n r'(?P<datasequence_id>\\d+)/nonpulseperiod/create/$',\n views.ConsumptionNonpulsePeriodCreateView.as_view(),\n name='consumptionnonpulseperiod-create'),\n url(r'^consumption/(?P<customer_id>\\d+)/'\n r'(?P<datasequence_id>\\d+)/nonpulseperiod/update/'\n r'(?P<pk>\\d+)/$',\n views.ConsumptionNonpulsePeriodUpdateView.as_view(),\n name='consumptionnonpulseperiod-update'),\n url(r'^nonpulseperiod/(?P<customer_id>\\d+)/delete/'\n r'(?P<pk>\\d+)/$',\n views.ConsumptionNonpulsePeriodDeleteView.as_view(),\n name='consumptionnonpulseperiod-delete'),\n\n url(r'^consumption/(?P<customer_id>\\d+)/start/(?P<consumption_id>\\d+)/$', # noqa\n views.StartWeekConsumptionUtilityBarChartView.as_view(),\n name='consumption-utility-bar-chart-start'),\n url(r'^consumption/(?P<customer_id>\\d+)/finalize/$',\n views.FinalizeWeekUtilityBarChartView.as_view(),\n name='utility-bar-chart-finalize'),\n\n url(r'^tariff/(?P<customer_id>\\d+)/$',\n views.TariffList.as_view(),\n name='tariff-list'),\n url(r'^tariff/content/(?P<customer_id>\\d+)/$',\n views.TariffListContentView.as_view(),\n name='tariff-list-content'),\n url(r'^tariff/create/(?P<customer_id>\\d+)/$',\n views.TariffCreateView.as_view(),\n name='tariff-create'),\n url(r'^tariff/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.TariffUpdateView.as_view(),\n name='tariff-update'),\n\n url(r'^agent/(?P<customer_id>\\d+)/$',\n views.AgentList.as_view(),\n name='agent-list'),\n url(r'^agent/content/(?P<customer_id>\\d+)/$',\n views.AgentListContentView.as_view(),\n name='agent-list-content'),\n url(r'^agent/create/(?P<customer_id>\\d+)/$',\n views.AgentCreateView.as_view(),\n name='agent-create'),\n url(r'^agent/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.AgentUpdateView.as_view(),\n name='agent-update'),\n\n url(r'^meter/(?P<customer_id>\\d+)/$',\n views.MeterList.as_view(),\n name='meter-list'),\n url(r'^meter/content/(?P<customer_id>\\d+)/$',\n views.MeterListContentView.as_view(),\n name='meter-list-content'),\n url(r'^meter/create/(?P<customer_id>\\d+)/$',\n views.MeterCreateView.as_view(),\n name='meter-create'),\n url(r'^meter/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.MeterUpdateView.as_view(),\n name='meter-update'),\n)\n" }, { "alpha_fraction": 0.6265361905097961, "alphanum_fraction": 0.630436360836029, "avg_line_length": 37.171348571777344, "blob_id": "cf2d50d234555d430ae4d2a1f051b031dc93f794", "content_id": "84f59176742e5d61b6c7a2c4277d0bd6fc2d531c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13589, "license_type": "no_license", "max_line_length": 95, "num_lines": 356, "path": "/legacy/display_projects/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom decimal import Decimal\n\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom django.views import generic\nfrom django.views.generic.base import TemplateView\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import redirect\n\nimport pytz\nfrom braces.views import LoginRequiredMixin\nfrom extra_views import UpdateWithInlinesView\nfrom extra_views import CreateWithInlinesView\nfrom extra_views import InlineFormSet\n\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.energy_use_reports.views import flotr2_to_gnuplot\n\nfrom legacy.projects.forms import AnnualSavingsPotentialReportGenerationForm # noqa\nfrom legacy.projects.models import AdditionalSaving\nfrom legacy.projects.models import BenchmarkProject\nfrom legacy.projects.models import Cost\nfrom gridplatform.reports.pdf import generate_pdf\nfrom gridplatform.reports.views import FinalizeReportView\nfrom gridplatform.reports.views import ReportInfo\nfrom gridplatform.reports.views import StartReportView\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils import utilitytypes\n\nfrom .tasks import ProjectReportTask\n\n\nclass ProjectForm(forms.ModelForm):\n class Meta:\n model = BenchmarkProject\n fields = (\n 'name', 'background', 'expectations', 'actions', 'result',\n 'comments', 'runtime', 'estimated_yearly_consumption_costs_before',\n 'estimated_yearly_consumption_before',\n 'estimated_co2_emissions_before',\n 'expected_savings_in_yearly_total_costs',\n 'expected_savings_in_yearly_consumption_after',\n 'expected_reduction_in_yearly_co2_emissions',\n 'include_measured_costs', 'subsidy',\n 'baseline_from_timestamp', 'baseline_to_timestamp',\n 'result_from_timestamp', 'result_to_timestamp',\n 'baseline_measurement_points',\n 'result_measurement_points')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n utility_type = kwargs.pop('utility_type', None)\n super(ProjectForm, self).__init__(*args, **kwargs)\n if self.instance.utility_type is None:\n assert utility_type is not None\n self.instance.utility_type = utility_type\n\n for field in [\n \"estimated_yearly_consumption_costs_before\",\n \"estimated_yearly_consumption_before\",\n \"estimated_co2_emissions_before\",\n \"expected_savings_in_yearly_total_costs\",\n \"expected_savings_in_yearly_consumption_after\",\n \"expected_reduction_in_yearly_co2_emissions\",\n 'baseline_from_timestamp', 'baseline_to_timestamp',\n 'result_from_timestamp', 'result_to_timestamp']:\n if field in self.fields:\n self.fields[field].localize = True\n self.fields[field].widget.is_localized = True\n\n measurement_points_qs = ConsumptionMeasurementPoint.objects.\\\n subclass_only().filter(\n utility_type=self.instance.utility_type)\n\n self.fields[\n 'baseline_measurement_points'].queryset = measurement_points_qs\n self.fields[\n 'result_measurement_points'].queryset = measurement_points_qs\n\n\nclass WaterProjectForm(ProjectForm):\n class Meta(ProjectForm.Meta):\n fields = (\n 'name', 'background', 'expectations', 'actions', 'result',\n 'comments', 'runtime', 'estimated_yearly_consumption_costs_before',\n 'estimated_yearly_consumption_before',\n 'expected_savings_in_yearly_total_costs',\n 'expected_savings_in_yearly_consumption_after',\n 'include_measured_costs', 'subsidy',\n 'baseline_from_timestamp', 'baseline_to_timestamp',\n 'result_from_timestamp', 'result_to_timestamp',\n 'baseline_measurement_points',\n 'result_measurement_points')\n\n\nclass BenchmarkProjectOpenClosedMixin(object):\n def get_context_data(self, **kwargs):\n now = datetime.datetime.now(pytz.utc)\n context = {\n 'open': BenchmarkProject.active(now),\n 'closed': BenchmarkProject.done(now),\n }\n context.update(kwargs)\n return super(BenchmarkProjectOpenClosedMixin, self).get_context_data(\n **context)\n\n\nclass BenchmarkProjectIndexView(\n LoginRequiredMixin, BenchmarkProjectOpenClosedMixin,\n generic.TemplateView):\n template_name = 'display_projects/index.html'\n\n\nclass BenchmarkProjectDetailView(\n LoginRequiredMixin, BenchmarkProjectOpenClosedMixin,\n generic.DetailView):\n template_name = 'display_projects/project_details.html'\n model = BenchmarkProject\n\n\nclass AdditionalSavingsInline(InlineFormSet):\n model = AdditionalSaving\n extra = 1\n\n\nclass WaterAdditionalSavingsInline(AdditionalSavingsInline):\n fields = ('description', 'before_energy',\n 'after_energy', 'before_cost', 'after_cost')\n\n\nclass CostInline(InlineFormSet):\n model = Cost\n extra = 1\n\n\nclass BenchmarkProjectUpdateView(\n LoginRequiredMixin, BenchmarkProjectOpenClosedMixin,\n UpdateWithInlinesView):\n template_name = 'display_projects/project_form.html'\n model = BenchmarkProject\n form_class = ProjectForm\n inlines = [AdditionalSavingsInline, CostInline]\n\n def get_context_data(self, **kwargs):\n inlines = kwargs['inlines']\n additional_saving, cost = inlines\n context = {\n 'additional_saving': additional_saving,\n 'cost': cost,\n 'currency': get_customer().get_currency_unit_display(),\n }\n context.update(kwargs)\n return super(BenchmarkProjectUpdateView, self).get_context_data(\n **context)\n\n def get_success_url(self):\n return reverse('display_projects-index')\n\n\nclass BenchmarkProjectCreateView(\n LoginRequiredMixin, BenchmarkProjectOpenClosedMixin,\n CreateWithInlinesView):\n template_name = 'display_projects/project_form.html'\n model = BenchmarkProject\n form_class = ProjectForm\n inlines = [AdditionalSavingsInline, CostInline]\n\n def get_form_kwargs(self):\n utility_type = self.kwargs['utility_type']\n kwargs = super(BenchmarkProjectCreateView, self).get_form_kwargs()\n kwargs['utility_type'] = getattr(\n utilitytypes.METER_CHOICES, utility_type)\n return kwargs\n\n def get_context_data(self, **kwargs):\n inlines = kwargs['inlines']\n additional_saving, cost = inlines\n context = {\n 'additional_saving': additional_saving,\n 'cost': cost,\n 'currency': get_customer().get_currency_unit_display(),\n }\n context.update(kwargs)\n return super(BenchmarkProjectCreateView, self).get_context_data(\n **context)\n\n def get_success_url(self):\n return reverse('display_projects-index')\n\n\nclass WaterBenchmarkProjectUpdateView(BenchmarkProjectUpdateView):\n model = BenchmarkProject\n form_class = WaterProjectForm\n inlines = [WaterAdditionalSavingsInline, CostInline]\n\n def get_context_data(self, **kwargs):\n context = {\n 'is_water_project': True,\n }\n context.update(kwargs)\n return super(WaterBenchmarkProjectUpdateView, self).get_context_data(\n **context)\n\n\nclass WaterBenchmarkProjectCreateView(BenchmarkProjectCreateView):\n template_name = 'display_projects/project_form.html'\n model = BenchmarkProject\n form_class = WaterProjectForm\n inlines = [WaterAdditionalSavingsInline, CostInline]\n\n def get_context_data(self, **kwargs):\n context = {\n 'is_water_project': True,\n }\n context.update(kwargs)\n return super(WaterBenchmarkProjectCreateView, self).get_context_data(\n **context)\n\n\nclass BenchmarkProjectDeleteView(LoginRequiredMixin, generic.DeleteView):\n model = BenchmarkProject\n\n def get_success_url(self):\n return reverse('display_projects-index')\n\n\nclass ProjectReportForm(forms.Form):\n project = forms.IntegerField()\n\n\ndef benchmarkproject_update(request, pk):\n project = get_object_or_404(\n BenchmarkProject, id=pk)\n if project.utility_type == utilitytypes.METER_CHOICES.water:\n return redirect('display_projects-update_water', pk=pk)\n else:\n return redirect('display_projects-update_normal', pk=pk)\n\n\nclass StartProjectReportView(StartReportView):\n form_class = ProjectReportForm\n task = ProjectReportTask\n\n def get_task_data(self, form):\n data = form.cleaned_data\n return {\n 'project': data['project'],\n }\n\n\nclass FinalizeProjectReportView(FinalizeReportView):\n def generate_report(self, data, timestamp):\n project = BenchmarkProject.objects.get(id=data['project_id'])\n file_title = '{}.pdf'.format(project.name_plain.encode(\n 'ascii', 'ignore'))\n template = 'display_projects/report.tex'\n additional_savings = list(project.additionalsaving_set.all())\n additional_savings_sum = {\n 'before_energy': sum(\n [a.before_energy or 0 for a in additional_savings],\n Decimal(0)),\n 'after_energy': sum(\n [a.after_energy or 0 for a in additional_savings], Decimal(0)),\n 'diff_energy': sum(\n [a.diff_energy() for a in additional_savings], Decimal(0)),\n 'before_cost': sum(\n [a.before_cost or 0 for a in additional_savings], Decimal(0)),\n 'after_cost': sum(\n [a.after_cost or 0 for a in additional_savings], Decimal(0)),\n 'diff_cost': sum(\n [a.diff_cost() for a in additional_savings], Decimal(0)),\n 'before_co2': sum(\n [a.before_co2 or 0 for a in additional_savings], Decimal(0)),\n 'after_co2': sum(\n [a.after_co2 or 0 for a in additional_savings], Decimal(0)),\n 'diff_co2': sum(\n [a.diff_co2() for a in additional_savings], Decimal(0)),\n }\n project_costs = list(project.cost_set.all())\n data.update(\n {\n 'name': project.name_plain,\n 'background': project.background_plain,\n 'expectations': project.expectations_plain,\n 'actions': project.actions_plain,\n 'result': project.result_plain,\n 'comments': project.comments_plain,\n 'months': project.runtime,\n 'additional_savings': additional_savings,\n 'additional_savings_sum': additional_savings_sum,\n 'project_costs': project_costs,\n 'customer_name': unicode(project.customer),\n 'project_runtime': project.runtime,\n 'include_measured_costs': project.include_measured_costs,\n 'activity_duration': {\n 'from_timestamp': project.from_timestamp,\n 'to_timestamp': project.to_timestamp,\n },\n 'stage_1_start': project.baseline_from_timestamp,\n 'stage_1_end': project.baseline_to_timestamp,\n 'stage_1_tariff_domain_warning': (\n project.baseline_stage.tariff_domain_warning(\n data['baseline_tariff_domain_warning_measurement_point_ids'])), # noqa\n 'stage_2_start': project.result_from_timestamp,\n 'stage_2_end': project.result_to_timestamp,\n 'stage_2_tariff_domain_warning': (\n project.result_stage.tariff_domain_warning(\n data['result_tariff_domain_warning_measurement_point_ids'])), # noqa\n 'project': project,\n })\n\n has_rate_graphs = False\n for mp_dict in data['measurement_points']:\n mp_dict['instance'] = ConsumptionMeasurementPoint.objects.\\\n subclass_only().get(id=mp_dict['id']).subclass_instance\n if mp_dict['graph_data']:\n has_rate_graphs = True\n\n data.update({\n 'has_rate_graphs': has_rate_graphs,\n })\n\n content = generate_pdf(\n template, data, project.name_plain, 'project',\n project.customer,\n gnuplots=[\n flotr2_to_gnuplot(\n mp['graph_data'],\n 'rate-graph-%d.tex' % mp['id'],\n terminal='epslatex color solid size 26cm,11.5cm') for\n mp in data['measurement_points'] if mp['graph_data']] +\n [\n flotr2_to_gnuplot(\n mp['consumption_graph_data'],\n 'consumption-graph-%d.tex' % mp['id'],\n terminal='epslatex color solid size 26cm,11.5cm',\n sample_resolution=project.get_sample_resolution()) for\n mp in data['measurement_points']])\n\n return ReportInfo(file_title, 'application/pdf', content)\n\n\nclass AnnualSavingsPotentialReportGenerationFormView(TemplateView):\n template_name = 'display_projects/annual_savings_potential_form.html'\n\n def get_context_data(self, **kwargs):\n context = super(\n AnnualSavingsPotentialReportGenerationFormView, self).\\\n get_context_data(**kwargs)\n context['form'] = AnnualSavingsPotentialReportGenerationForm()\n return context\n" }, { "alpha_fraction": 0.6449056267738342, "alphanum_fraction": 0.645482063293457, "avg_line_length": 31.886255264282227, "blob_id": "7a8431fd7fe2071fe9368aae4a0a0e9336ae62a6", "content_id": "e2077c01f40e4fde0905a3313cc78bd78592d4ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6939, "license_type": "no_license", "max_line_length": 79, "num_lines": 211, "path": "/legacy/website/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport urlparse\n\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.views.decorators.http import require_POST\nfrom django.shortcuts import redirect\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.views.decorators.debug import sensitive_post_parameters\nfrom django.views.decorators.cache import never_cache\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.contrib.auth import REDIRECT_FIELD_NAME, login as auth_login\nfrom django.contrib.auth.views import logout_then_login\nfrom django.contrib.sites.models import get_current_site\n\nfrom celery.result import AsyncResult\nimport celery.task.control\n\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.utils.views import render_to, json_response\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_customer\n\n\n@sensitive_post_parameters()\n@csrf_protect\n@never_cache\n@render_to('website/login.html')\ndef login(request):\n \"\"\"\n Displays the login form and handles the login action.\n \"\"\"\n # based on django.contrib.auth.views.login --- \"simplified\" by removing\n # parameters, call to load encryption keys added.\n redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')\n\n # HACK: ONLY FOR USE ON GREENTECH SERVERS\n # if request.method == \"POST\" or \"username\" in request.GET:\n # if 'username' in request.GET:\n # form = AuthenticationForm(data=request.GET)\n # else:\n # form = AuthenticationForm(data=request.POST)\n\n if request.method == \"POST\":\n form = AuthenticationForm(data=request.POST)\n if form.is_valid():\n netloc = urlparse.urlparse(redirect_to)[1]\n\n # Use default setting if redirect_to is empty\n if not redirect_to:\n redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Heavier security check -- don't allow redirection to a different\n # host.\n elif netloc and netloc != request.get_host():\n redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Okay, security checks complete. Log the user in.\n auth_login(request, form.get_user())\n\n if request.session.test_cookie_worked():\n request.session.delete_test_cookie()\n\n return HttpResponseRedirect(redirect_to)\n else:\n form = AuthenticationForm(request)\n\n request.session.set_test_cookie()\n\n current_site = get_current_site(request)\n\n return {\n 'form': form,\n 'REDIRECT_FIELD_NAME': redirect_to,\n 'site': current_site,\n 'site_name': current_site.name,\n }\n\n\n@never_cache\ndef logout(request):\n return logout_then_login(request)\n\n\ndef find_home(request):\n if get_user().is_staff:\n return redirect('manage_customers-list')\n else:\n return redirect('display_widgets-dashboard')\n\n\n@python_2_unicode_compatible\nclass CeleryError(Exception):\n \"\"\"\n Wrapper for exceptions from Celery --- Celery provides an Exception object\n and a string representation of a traceback.\n \"\"\"\n def __init__(self, wrapped, traceback):\n self.wrapped = wrapped\n self.traceback = traceback\n\n def __str__(self):\n return '{}\\n{}'.format(self.wrapped, self.traceback)\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef task_status(request):\n \"\"\"\n Given a celery task ID the status of that task is returned.\n\n If the task has failed, this raises an exception to trigger the normal\n Django error reporting.\n \"\"\"\n task_id = request.POST['task_id']\n async = AsyncResult(task_id)\n\n # We have experienced async.failed() being false while async.result\n # contained an AssertionError instance. Hence the isinstance check.\n if async.failed() or isinstance(async.result, Exception):\n # NOTE: The available \"traceback\" is a string, not a traceback-object,\n # hence \"re-raising\" with that as traceback context will not work\n\n if async.status == 'REVOKED':\n return {\n 'task_id': async.id,\n 'status': async.status\n }\n else:\n raise CeleryError(async.result, async.traceback)\n\n if async.status == \"PROGRESS\":\n return {\n 'task_id': async.id,\n 'status': async.status,\n 'result': async.result,\n }\n else:\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef cancel_task(request):\n \"\"\"\n Kills a task with the given ID, if the logged in user\n is the same user that started the task\n \"\"\"\n task_id = request.POST['task_id']\n async = AsyncResult(task_id)\n success = False\n if async and isinstance(async.result, dict) and \\\n get_user().id == async.result.get('task_user_id', None):\n # NOTE: The Celery documentation recommends against using termitate\n # programmatically --- the worker in question is terminated, though it\n # may have started processing a different task when the termination\n # signal is delivered. As we have enabled CELERY_ACKS_LATE, the harm\n # in that particular case is limited --- any next/different task being\n # processed by the terminated worker will be retried by another worker,\n # rather than being lost (as it would have been without\n # CELERY_ACKS_LATE)...\n celery.task.control.revoke(task_id, terminate=True)\n success = True\n return {\n 'success': success\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef json_task_result(request):\n \"\"\"\n Given a celery task ID of a completed task, the result is returned. The\n result from the task must be serializable to JSON.\n \"\"\"\n task_id = request.POST['task_id']\n async = AsyncResult(task_id)\n assert async.successful(), async.traceback\n\n # HACK: Production units cannot be displayed in tasks because they are\n # encrypted. So we replace them here with their decrypted counter parts.\n def replace_production_unit(s, l):\n return s.replace(\n 'production_%s' % l, getattr(\n get_customer(),\n 'production_%s_unit_plain' % l))\n\n for letter in ['a', 'b', 'c', 'd', 'e']:\n try:\n async.result['options']['yaxis']['title'] = \\\n replace_production_unit(async.result[\n 'options']['yaxis']['title'], letter)\n except KeyError:\n pass\n try:\n async.result['options']['xaxis']['title'] = \\\n replace_production_unit(async.result[\n 'options']['xaxis']['title'], letter)\n except KeyError:\n pass\n return async.result\n" }, { "alpha_fraction": 0.5360323786735535, "alphanum_fraction": 0.5384615659713745, "avg_line_length": 31.5, "blob_id": "04432973acffe150dc9a100cd1d64a35d992f5cf", "content_id": "090d86ec99c7b73c4cf4dcbcfa61cdbbd1c666f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1235, "license_type": "no_license", "max_line_length": 76, "num_lines": 38, "path": "/legacy/rules/management/commands/ruleengine.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport traceback\n\nfrom django.core.management.base import BaseCommand\nfrom django.utils.daemonize import become_daemon\nfrom django.core import mail\n\nfrom legacy.rules import engine\n\n\nclass Command(BaseCommand):\n args = \"\"\n help = \"Run the Grid Platform rule engine\"\n\n def handle(self, *args, **kwargs):\n \"\"\"\n \"\"\"\n become_daemon(out_log='ruleengine.log', err_log='ruleengine.err')\n for i in range(10):\n # limited \"retries\", to avoid mail-flood in case of recurring\n # exception\n try:\n try:\n engine.run()\n except Exception as e:\n mail.mail_admins(\n 'Rule engine error: %s' % (e.__class__,),\n '%s\\n%s' % (e, traceback.format_exc()),\n fail_silently=False)\n except:\n mail.mail_admins(\n 'Rule engine error (not Exception)',\n traceback.format_exc(),\n fail_silently=True)\n mail.mail_admins('Rule engine now stopping', '', fail_silently=True)\n" }, { "alpha_fraction": 0.6351775527000427, "alphanum_fraction": 0.6352858543395996, "avg_line_length": 37.644351959228516, "blob_id": "a9a9e64136fae545c954a6f0404db0d822e47d89", "content_id": "b71a9b1bd77b32ea732e50e8ecca6483c61a8748", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18472, "license_type": "no_license", "max_line_length": 79, "num_lines": 478, "path": "/gridplatform/trackuser/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\nfrom django.db.models.query_utils import Q\nfrom django.utils import timezone\nfrom mptt.managers import TreeManager\n\nfrom gridplatform.encryption.managers import DecryptingQuerySet\nfrom gridplatform.encryption.managers import DecryptingManager\nfrom gridplatform.utils.models import StoredSubclassManager\n\nfrom . import get_customer\nfrom . import get_user\nfrom . import get_provider_id\nfrom . import _get_user_customer\nfrom . import _get_override_customer\n\n\nclass FilteringQuerySetMixinBase(object):\n \"\"\"\n Abstract queryset mixin that adds filtering when obtaining output. To make\n a concrete queryset mixin, one must subclass and implement\n :meth:`~.FilteringQuerySetMixinBase._apply_filtering`. The resulting mixin\n can then be mixed with actual queryset classes to define new filtering\n queryset classes.\n\n For instance, this abstract queryset mixin is subclassed by the queryset\n mixin :class:`.CustomerBoundQuerySetMixin` and mixed with the queryset\n class :class:`gridplatform.encryption.managers.DecryptingQuerySet` to form\n the new queryset class :class:`CustomerBoundManagerBase._QuerySet`.\n\n :ivar _filter_field: Field name delegated by :meth:`._clone` for\n specializations :meth:`~FilteringQuerySetMixinBase._apply_filtering`.\n See also :class:`.CustomerBoundManagerBase._field` and\n :class:`ProviderBoundManager._field`.\n :cvar _ValuesQuerySet: ``klass`` argument used by :meth:`._clone` in\n :meth:`.values`.\n :cvar _ValuesListQuerySet: ``klass`` argument used by :meth:`._clone` in\n :meth:`.values_list`.\n :cvar _DateQuerySet: ``klass`` argument used by :meth:`._clone` in\n :meth:`.dates`.\n :cvar _DateTimeQuerySet: ``klass`` argument used by :meth:`._clone` in\n :meth:`.datetimes`.\n \"\"\"\n # __len__() -> _fetch_all() -> iterator()\n # __iter__() -> _fetch_all() -> iterator()\n # __nonzero__() -> _fetch_all() -> iterator()\n # __getitem__() -> _result_cache / __iter__() -> _fetch_all() -> iterator()\n # _fetch_all() -> iterator()\n # get() -> __len__() / __getitem__() -> ... -> iterator()\n # earliest() -> _earliest_or_latest() -> get() -> ... -> iterator()\n # latest() -> _earliest_or_latest() -> get() -> ... -> iterator()\n # first() -> __getitem__() -> ... -> iterator()\n # last() -> __getitem__() -> ... -> iterator()\n # in_bulk() -> __iter__() -> ... -> iterator()\n\n # create(), bulk_create() not specifically handled.\n # get_or_create() as get() for reading; as create() for create...\n # _raw_delete() is used by deletion.Collector; should have a clone with\n # query filtered by then...\n # _prefetch_related_objects() is called after _result_cache is filled,\n # i.e. after filtering was relevant and has been performed.\n\n # Methods that give new QuerySets use _clone() --- we ensure that the\n # filtering options are transferred; after which we're back to having to\n # ensure that filtering is performed on data access.\n\n def iterator(self):\n \"\"\"\n Ensure filtering is applied for the ``iterator()`` of actual queryset\n class.\n\n Methods that read/return \"normal\" objects all use `iterator()`\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).iterator()\n\n def aggregate(self, *args, **kwargs):\n \"\"\"\n Ensure filtering is applied for the ``aggregate()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).aggregate(\n *args, **kwargs)\n\n def count(self):\n \"\"\"\n Ensure filtering is applied for the ``count()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).count()\n\n def delete(self):\n \"\"\"\n Ensure filtering is applied for the ``delete()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).delete()\n delete.alters_data = True\n\n def update(self, **kwargs):\n \"\"\"\n Ensure filtering is applied for the ``update()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).update(**kwargs)\n update.alters_data = True\n\n def _update(self, values):\n \"\"\"\n Ensure filtering is applied for the ``_update()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self)._update(values)\n _update.alters_data = True\n\n def exists(self):\n \"\"\"\n Ensure filtering is applied for the ``exists()`` of actual queryset\n class.\n \"\"\"\n self.__ensure_filtering_applied()\n return super(FilteringQuerySetMixinBase, self).exists()\n\n def _clone(self, klass=None, setup=False, **kwargs):\n \"\"\"\n Specialization of ``_clone()`` of actual queryset class that ensures\n that ``self._filter_field``, ``self._ValuesQuerySet``,\n ``self._ValuesListQuerySet``, ``self._DateQuerySet`` and\n ``self._DateTimeQuerySet`` are also transfered to the cloned queryset.\n \"\"\"\n clone_args = {\n '_filter_field': self._filter_field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n clone_args.update(kwargs)\n return super(FilteringQuerySetMixinBase, self)._clone(\n klass=klass, setup=setup, **clone_args)\n\n def _merge_sanity_check(self, other):\n super(FilteringQuerySetMixinBase, self)._merge_sanity_check(other)\n\n _filter_field = None\n _ValuesQuerySet = None\n _ValuesListQuerySet = None\n _DateQuerySet = None\n _DateTimeQuerySet = None\n\n def values(self, *fields):\n \"\"\"\n Override of ``values()`` of actual queryset class returning a clone of\n ``self`` with class ``self._ValuesQuerySet``.\n \"\"\"\n # NOTE: Copy from django.db.models.query.QuerySet + custom class\n return self._clone(\n klass=self._ValuesQuerySet, setup=True, _fields=fields)\n\n def values_list(self, *fields, **kwargs):\n \"\"\"\n Override of ``values_list()`` of actual queryset class returning a\n clone of ``self`` with class ``self._ValuesListQuerySet``.\n \"\"\"\n # NOTE: Copy from django.db.models.query.QuerySet + custom class\n flat = kwargs.pop('flat', False)\n if kwargs:\n raise TypeError(\n 'Unexpected keyword arguments to values_list: %s' %\n (list(kwargs),))\n if flat and len(fields) > 1:\n raise TypeError(\n \"'flat' is not valid when values_list is called with more \"\n \"than one field.\")\n return self._clone(\n klass=self._ValuesListQuerySet, setup=True, flat=flat,\n _fields=fields)\n\n def dates(self, field_name, kind, order='ASC'):\n \"\"\"\n Override of ``dates()`` of actual queryset class returning a clone of\n ``self`` with class ``self._DatesQuerySet``.\n \"\"\"\n # NOTE: Copy from django.db.models.query.QuerySet + custom class\n assert kind in (\"year\", \"month\", \"day\"), \\\n \"'kind' must be one of 'year', 'month' or 'day'.\"\n assert order in ('ASC', 'DESC'), \\\n \"'order' must be either 'ASC' or 'DESC'.\"\n return self._clone(\n klass=self._DateQuerySet, setup=True,\n _field_name=field_name, _kind=kind, _order=order)\n\n def datetimes(self, field_name, kind, order='ASC', tzinfo=None):\n \"\"\"\n Override of ``values()`` of actual queryset class returning a clone of\n ``self`` with class ``self._DateTimeQuerySet``.\n \"\"\"\n # NOTE: Copy from django.db.models.query.QuerySet + custom class\n assert kind in (\"year\", \"month\", \"day\", \"hour\", \"minute\", \"second\"), \\\n \"'kind' must be one of 'year', 'month', 'day', \" + \\\n \"'hour', 'minute' or 'second'.\"\n assert order in ('ASC', 'DESC'), \\\n \"'order' must be either 'ASC' or 'DESC'.\"\n if settings.USE_TZ:\n if tzinfo is None:\n tzinfo = timezone.get_current_timezone()\n else:\n tzinfo = None\n return self._clone(\n klass=self._DateTimeQuerySet, setup=True, _field_name=field_name,\n _kind=kind, _order=order, _tzinfo=tzinfo)\n\n def __ensure_filtering_applied(self):\n \"\"\"\n Filtering is applied the first time a specific `QuerySet` is used to\n access the database --- further filtering on the same `QuerySet` after\n we've started reading from the database would make no sense. (At best\n it's an expensive no-op; at worst it would introduce numerous edge\n cases.)\n \"\"\"\n if not getattr(self, '_filtering_applied', False):\n self._apply_filtering()\n self._filtering_applied = True\n\n def _apply_filtering(self):\n \"\"\"\n Implementations should have side effect on `self.query` and return\n `None`.\n\n Various edge cases break if this is not idempotent. For normal use,\n this will be fulfilled with no specific effort, as adding the same\n `WHERE` clause twice will have no effect on what objects are matched\n --- but don't use `datetime.datetime.now()` or similar...\n\n NOTE: If/when we redefine this interface, check whether it will allow a\n better `_merge_sanity_check()`.\n \"\"\"\n raise NotImplementedError()\n\n\nclass CustomerBoundQuerySetMixin(FilteringQuerySetMixinBase):\n \"\"\"\n QuerySet mixin limiting result set to rows belonging to the\n :class:`~gridplatform.customers.models.Customer` set whose data the current\n user is authorized to access.\n \"\"\"\n def _apply_filtering(self):\n \"\"\"\n Implementation of :meth:`FilteringQuerySetMixinBase._apply_filtering`.\n\n If no user is logged in, no filtering is applied (for shell command).\n For unauthenticated users the queryset is emptied.\n\n If user is limited to only one\n :class:`~gridplatform.customers.models.Customer` (at this time) and\n that customer is inactive, the queryset is emptied, if the customer is\n active, the queryset is filtered according to ``self._filter_field``\n which must equal the customer.\n\n If user is a provider user and not limited to a particular customer at\n this time, ``self._filter_field`` must equal one of the customers\n having the same :class:`~gridplatform.providers.models.Provider`.\n\n Finally, if user is neither customer user nor provider user, he must be\n admin, and no filtering is applied.\n \"\"\"\n user = get_user()\n if user is None:\n return\n if not user.is_authenticated():\n self.query.set_empty()\n return\n # user customer or override customer or selected customer\n customer = get_customer()\n if customer is not None:\n if not customer.is_active:\n self.query.set_empty()\n return\n id_field = '{}_id'.format(self._filter_field)\n kwargs = {id_field: customer.id}\n self.query.add_q(Q(**kwargs))\n return\n provider_id = get_provider_id()\n if provider_id:\n provider_id_field = '{}__provider_id'.format(self._filter_field)\n kwargs = {provider_id_field: provider_id}\n self.query.add_q(Q(**kwargs))\n return\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n return\n\n\nclass ProviderBoundQuerySetMixin(FilteringQuerySetMixinBase):\n \"\"\"\n QuerySet mixin limiting result set to rows belonging to the\n :class:`~gridplatform.providers.models.Provider` whose data the current\n user is authorized to access.\n \"\"\"\n def _apply_filtering(self):\n \"\"\"\n Implementation of :meth:`FilteringQuerySetMixinBase._apply_filtering`.\n\n If no user is logged in, no filtering is applied (for shell command).\n For unauthenticated users the queryset is emptied.\n\n If user is limited to only one\n :class:`~gridplatform.customers.models.Customer` (at this time) the\n queryset is emptied.\n\n If user is a provider user and not limited to a particular customer at\n this time, ``self._filter_field`` must equal the same\n :class:`~gridplatform.providers.models.Provider`.\n\n Finally, if user is neither customer user nor provider user, he must be\n admin, and no filtering is applied.\n \"\"\"\n user = get_user()\n if user is None:\n return\n if not user.is_authenticated():\n self.query.set_empty()\n return\n if _get_user_customer() is not None or \\\n _get_override_customer() is not None:\n self.query.set_empty()\n return\n provider_id = get_provider_id()\n if provider_id:\n provider_id_field = '{}_id'.format(self._filter_field)\n kwargs = {provider_id_field: provider_id}\n self.query.add_q(Q(**kwargs))\n return\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n return\n\n\nclass CustomerBoundManagerBase(DecryptingManager):\n \"\"\"\n Base class for managers that limit their querysets to rows belonging to the\n :class:`~gridplatform.customers.models.Customer` set whose data the current\n user is authorized to access.\n\n :cvar _field: The name of the lookup field that points to the owning\n :class:`~gridplatform.customers.models.Customer`. The default value is\n ``'customer'``.\n \"\"\"\n _field = 'customer'\n\n class _QuerySet(CustomerBoundQuerySetMixin, DecryptingQuerySet):\n pass\n\n class _ValuesQuerySet(CustomerBoundQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(CustomerBoundQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(CustomerBoundQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(CustomerBoundQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(CustomerBoundManagerBase, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_filter_field': self._field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n\n\nclass CustomerBoundManager(CustomerBoundManagerBase):\n \"\"\"\n A :class:`.CustomerBoundManagerBase` specialization that is used for\n related fields too.\n\n The ``use_for_related_fields`` being ``True`` ensures that reverse\n relations also will apply the customer-bound filtering. This could be\n useful when inspecting global resources used by different customers. Since\n many models use the :class:`.StoredSubclassCustomerBoundManager`, this\n functionality will seem only sporadically available, and relying on it\n could be a bad idea.\n \"\"\"\n use_for_related_fields = True\n\n\nclass TreeCustomerBoundManager(TreeManager, CustomerBoundManager):\n \"\"\"\n A manager that is both a :class:`mptt.managers.TreeManager` and\n a :class:`.CustomerBoundManager`.\n \"\"\"\n pass\n\n\nclass StoredSubclassCustomerBoundManager(\n StoredSubclassManager, CustomerBoundManagerBase):\n \"\"\"\n A manager that is both a :class:`.StoredSubclassManager` and a\n :class:`CustomerBoundManagerBase`.\n\n Since :class:`.StoredSubclassManager` should not be used in reverse\n relations, neither can :class:`.StoredSubclassCustomerBoundManager`.\n \"\"\"\n use_for_related_fields = False\n\n\nclass StoredSubclassTreeCustomerBoundManager(\n StoredSubclassManager, TreeManager, CustomerBoundManagerBase):\n \"\"\"\n A manager that is both a :class:`.StoredSubclassManager`, a\n :class:`mptt.managers.TreeManager` and a :class:`.CustomerBoundManager`.\n\n Since :class:`.StoredSubclassManager` should not be used in reverse\n relations, neither can :class:`.StoredSubclassTreeCustomerBoundManager`.\n \"\"\"\n use_for_related_fields = False\n\n\nclass ProviderBoundManager(DecryptingManager):\n \"\"\"\n Base class for managers that limit their querysets to rows belonging to the\n :class:`~gridplatform.providers.models.Provider` whose data the current\n user is authorized to access.\n\n :cvar _field: The name of the lookup field that points to the owning\n :class:`~gridplatform.providers.models.Provider`. The default value is\n ``'provider'``.\n \"\"\"\n _field = 'provider'\n use_for_related_fields = True\n\n class _QuerySet(ProviderBoundQuerySetMixin, DecryptingQuerySet):\n pass\n\n class _ValuesQuerySet(ProviderBoundQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(ProviderBoundQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(ProviderBoundQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(ProviderBoundQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(ProviderBoundManager, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_filter_field': self._field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n" }, { "alpha_fraction": 0.5294595956802368, "alphanum_fraction": 0.5343356132507324, "avg_line_length": 28.914634704589844, "blob_id": "395482cf95071837eab9bdd7dd44907dec2711b0", "content_id": "7eae627af454bbd801f50e81616f6feee59de778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2461, "license_type": "no_license", "max_line_length": 116, "num_lines": 82, "path": "/emonhub/src/scnordic_bridge.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import datetime\nimport time\nimport requests\n\nfrom configobj import ConfigObj\nfrom requests.auth import AuthBase\n\n\nclass TokenAuth(AuthBase):\n \"\"\"Attaches HTTP Token Authentication to the given Request object.\"\"\"\n\n def __init__(self, token):\n # setup any auth-related data here\n self.token = token\n\n def __call__(self, r):\n # modify and return the request\n r.headers['Authorization'] = \"token %s\" % self.token\n return r\n\n\nclass RequestHandler():\n def __init__(self, api_key, api_base_url):\n\n self.auth = TokenAuth(api_key)\n self.base_url = api_base_url\n self.config = ConfigObj('/tmp/endpoint.cache')\n\n def fetch_endpoint(self, name):\n payload = {'hardware_id': name}\n try:\n r = requests.get('%s/datasources/customer_datasources/' % self.base_url, auth=self.auth, params=payload,\n timeout=1)\n except:\n return None\n response = {}\n\n if r.status_code == requests.codes.ok:\n response = r.json()\n\n if response['count'] == 1:\n self.config[name] = {\n 'timestamp': time.time(),\n 'endpoint': response['results'][0]['rawData']\n }\n self.config.write()\n return response['results'][0]['rawData']\n else:\n return None\n else:\n return None\n\n def get_endpoint(self, name):\n try:\n cached = self.config[name]\n\n if (datetime.datetime.fromtimestamp(\n float(cached['timestamp'])) > datetime.datetime.now() - datetime.timedelta(minutes=10)):\n return cached['endpoint']\n else:\n return self.fetch_endpoint(name)\n except KeyError:\n return self.fetch_endpoint(name)\n\n # TODO: Handle error logging\n def send_measurement(self, package):\n print package.datasource_name\n endpoint = self.get_endpoint(package.datasource_name)\n\n if endpoint:\n payload = {\n \"timestamp\": package.timestamp.strftime(\"%Y-%m-%dT%H:%M:%S\"),\n \"value\": package.value,\n \"unit\": package.unit,\n }\n\n try:\n r = requests.post(endpoint, auth=self.auth, data=payload)\n return r.status_code\n except:\n return 500\n return 500\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6628054976463318, "alphanum_fraction": 0.670574963092804, "avg_line_length": 31.472476959228516, "blob_id": "619b028335d44c1de0e9dcbbe83893deb69e4657", "content_id": "5a84deef5af406bc6750741c21b515a99f774073", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7079, "license_type": "no_license", "max_line_length": 89, "num_lines": 218, "path": "/gridplatform/utils/condense.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nHistorically we have called time period's aggregating of samples\nfor condensing, and the generic description of the time periods in the\nforms of :class:`.RelativeTimeDelta` for condense resolutions. The\ncode and the documentation has not been cleaned up with respect to\nthis terminology confusion.\n\nThis module is made to be used as a namespace. In particular most\nnames held within this module seem overly generic if not used with the\nnamespace. For instance ``condense.ceil`` will be less confusing than\njust ``ceil`` in application code.\n\n.. data:: YEARS\n\n A condense resolution of one year.\n\n.. data:: QUARTERS\n\n A condense resolution of a quarter year.\n\n.. data:: MONTHS\n\n A condense resolution of one month.\n\n.. data:: DAYS\n\n A condense resolution of one day.\n\n.. data:: HOURS\n\n A condense resolution of one hour.\n\n.. data:: FIVE_MINUTES\n\n A condense resolution of five minutes.\n\n.. data:: MINUTES\n\n A condense resolution of one minute.\n\n.. data:: RESOLUTIONS\n\n A tuple of ordered condense resolutions ``(YEARS,... , MINUTES)``.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport pytz\nfrom django.utils.formats import date_format\nfrom django.utils.dateformat import format\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .relativetimedelta import RelativeTimeDelta\n\nYEARS = RelativeTimeDelta(years=1)\nQUARTERS = RelativeTimeDelta(months=3)\nMONTHS = RelativeTimeDelta(months=1)\nDAYS = RelativeTimeDelta(days=1)\nHOURS = RelativeTimeDelta(hours=1)\nFIVE_MINUTES = RelativeTimeDelta(minutes=5)\nMINUTES = RelativeTimeDelta(minutes=1)\n\nRESOLUTIONS = (\n YEARS,\n QUARTERS,\n MONTHS,\n DAYS,\n HOURS,\n FIVE_MINUTES,\n MINUTES,\n)\n\n\ndef next_resolution(resolution):\n \"\"\"\n Helper method for implementing\n :meth:`legacy.measurementpoints.models.DataSeries.get_recursive_condense_resolution`.\n\n :param resolution: A condense resolution.\n\n :return: Returns a slightly more fine grained\n :class:`.RelativeTimeDelta` than ``resolution`` or ``None``.\n\n :raise ValueError: If ``resolution`` is not a valid condense resolution.\n \"\"\"\n if resolution not in RESOLUTIONS:\n raise ValueError('%r is not a valid condense resolution' % resolution)\n if resolution == RESOLUTIONS[-1]:\n return None\n return RESOLUTIONS[\n RESOLUTIONS.index(resolution) + 1]\n\n\ndef is_finer_resolution(r1, r2):\n \"\"\"\n :return: Returns true if ``r1`` is finer than ``r2``.\n \"\"\"\n return RESOLUTIONS.index(r1) > RESOLUTIONS.index(r2)\n\n\ndef is_coarser_resolution(r1, r2):\n \"\"\"\n :return: Returns true if ``r1`` is coarser than ``r2``.\n \"\"\"\n return is_finer_resolution(r2, r1)\n\n\ndef floor(time_object, resolution, timezone):\n \"\"\"\n Round ``time_object`` down to nearest multiple of ``resolution``\n in the given ``timezone``.\n\n :return: Returns a datetime object in ``timezone`` which is a multiple of\n ``resolution``.\n \"\"\"\n assert resolution in RESOLUTIONS, \\\n '%r is an invalid resolution' % resolution\n\n time_object = timezone.normalize(time_object.astimezone(timezone))\n\n if resolution == YEARS:\n time_object = time_object.replace(\n month=1, day=1, hour=0, minute=0, second=0, microsecond=0)\n adjust_timezone = True\n elif resolution == QUARTERS:\n time_object = time_object.replace(\n month=time_object.month - ((time_object.month - 1) % 3),\n day=1, hour=0, minute=0, second=0, microsecond=0)\n adjust_timezone = True\n elif resolution == MONTHS:\n time_object = time_object.replace(\n day=1, hour=0, minute=0, second=0, microsecond=0)\n adjust_timezone = True\n elif resolution == DAYS:\n time_object = time_object.replace(\n hour=0, minute=0, second=0, microsecond=0)\n adjust_timezone = True\n elif resolution == HOURS:\n time_object = time_object.replace(\n minute=0, second=0, microsecond=0)\n adjust_timezone = False\n elif resolution == MINUTES:\n time_object = time_object.replace(\n second=0, microsecond=0)\n adjust_timezone = False\n elif resolution == FIVE_MINUTES:\n time_object = time_object.replace(\n minute=time_object.minute - (time_object.minute % 5),\n second=0, microsecond=0)\n adjust_timezone = False\n else:\n assert False\n\n if adjust_timezone and isinstance(timezone, pytz.tzinfo.BaseTzInfo):\n # normalize + localize handles edge case wrt. the timestamps with\n # two different hour # representations on DST switch...\n #\n # see test_floor_exiting_dst and test_floor_entering_dst\n time_object = timezone.localize(\n time_object.replace(tzinfo=None))\n\n time_object = timezone.normalize(time_object)\n\n return time_object\n\n\ndef ceil(time_object, resolution, timezone):\n \"\"\"\n Round ``time_object`` up to nearest multiple of ``resolution`` in the given\n ``timezone``.\n\n :return: Returns a datetime object in ``timezone`` which is a multiple of\n ``resolution``.\n \"\"\"\n floored = floor(time_object, resolution, timezone)\n if time_object == floored:\n return time_object\n else:\n return floored + resolution\n\n\ndef get_date_formatter(from_timestamp, to_timestamp, resolution=None):\n \"\"\"\n Get a date formatter which given a datetime will output a string with\n sufficient information for making each tick on graphs across timespan given\n by ``from_timestamp`` and ``to_timestamp``, optionally condensed to\n ``resolution`` identifiable.\n\n E.g. if all samples would be on the same date, only the clock time needs to\n be displayed. Or if all samples each represent a month, only month and\n year needs to be displayed.\n\n Returns a function that takes a datetime object and returns a formatted\n date/time string\n \"\"\"\n if floor(from_timestamp, DAYS, from_timestamp.tzinfo) + DAYS >= \\\n to_timestamp:\n # all times in the open interval between from_timestamp and\n # to_timestamp have the same date.\n return lambda timestamp: date_format(timestamp, 'TIME_FORMAT')\n elif resolution is None or resolution in (MINUTES, FIVE_MINUTES, HOURS):\n # both date and clock time is required.\n return lambda timestamp: date_format(\n timestamp, 'SHORT_DATETIME_FORMAT')\n elif resolution == DAYS:\n return lambda timestamp: date_format(timestamp, 'SHORT_DATE_FORMAT')\n elif resolution == MONTHS:\n return lambda timestamp: format(timestamp, _('M. Y'))\n elif resolution == QUARTERS:\n return lambda timestamp: format(timestamp, _('Q{quarter} Y').format(\n quarter=(timestamp.month - 1) / 3 + 1))\n elif resolution == YEARS:\n return lambda timestamp: date_format(timestamp, 'YEAR_FORMAT')\n\n raise ValueError(\n 'no preferred date format for from_timestamp=%r, to_timestamp=%r and '\n 'resolution=%r' % (from_timestamp, to_timestamp, resolution))\n" }, { "alpha_fraction": 0.6370967626571655, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 38.45454406738281, "blob_id": "4178e9388f54578f8addc226659771d5c550a5d4", "content_id": "d2a33b0b89b27e353734b9e8dcf6f5d20d42e548", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 868, "license_type": "no_license", "max_line_length": 70, "num_lines": 22, "path": "/legacy/display_measurementpoints/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns(\n 'legacy.display_measurementpoints.views',\n url('^$', 'index',\n name='display_measurementpoints-index'),\n url('^(?P<pk>\\d+)/$', 'group',\n name='display_measurementpoints-group'),\n url('^fullscreen/(?P<pk>\\d+)/$', 'fullscreen_floorplan',\n name='display_measurementpoints-fullscreen_floorplan'),\n url('^async_graph/(?P<pk>\\d+)/$', 'async_graph',\n name='display_measurementpoints-async_graph'),\n url('^async_graph_last_24h/(?P<pk>\\d+)/$', 'async_graph_last_24h',\n name='display_measurementpoints-async_graph_last_24h'),\n url('^floorplan_values/(?P<pk>\\d+)/$', 'floorplan_values',\n name='display_measurementpoints-floorplan-values'),\n)\n" }, { "alpha_fraction": 0.5388086438179016, "alphanum_fraction": 0.5586642622947693, "avg_line_length": 24.204545974731445, "blob_id": "b775f3f057621f1916db2c8e18474c17779c3a34", "content_id": "887ebc9a25ef3f25e656bc438dc0ee139e1165d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 101, "num_lines": 44, "path": "/emonhub/src/interfacers/portal_package.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import datetime\n\nclass PortalPackage:\n datasource_name = ''\n timestamp = 0\n value = None\n unit = ''\n\n WATTHOUR = 'Wh'\n WATT = 'W'\n SECOND = 'sec'\n CELSIUS = 'C'\n PULSE = 'p'\n\n\n VALUE_TO_BASEVALUE_MULTIPLIERS = {\n WATTHOUR: 1000,\n WATT: 1000,\n SECOND: 1,\n CELSIUS: 273.15,\n PULSE: 1,\n }\n\n UNIT_TO_BASEUNIT = {\n WATTHOUR: 'milliwatt*hour',\n WATT: 'milliwatt',\n SECOND: 'impulse',\n CELSIUS: 'millikelvin',\n PULSE: 'impulse',\n }\n\n def __init__(self, datasource_name, timestamp, value, unit):\n self.datasource_name = datasource_name\n self.timestamp = datetime.datetime.fromtimestamp(timestamp)\n\n if value > 0 or value < 0:\n if unit == self.CELSIUS:\n self.value = int((value + PortalPackage.VALUE_TO_BASEVALUE_MULTIPLIERS[unit]) * 1000)\n else:\n self.value = int(value * PortalPackage.VALUE_TO_BASEVALUE_MULTIPLIERS[unit])\n else:\n self.value = int(value)\n\n self.unit = PortalPackage.UNIT_TO_BASEUNIT[unit]" }, { "alpha_fraction": 0.7024090886116028, "alphanum_fraction": 0.7061880230903625, "avg_line_length": 39.71154022216797, "blob_id": "7c475dceb916d6a68b2fd0a579d73bc8642a8c25", "content_id": "123580c704d6d4b5799f04a62a6b5a7033daf8b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2117, "license_type": "no_license", "max_line_length": 86, "num_lines": 52, "path": "/documentation/source/future_work.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "===========\nFuture Work\n===========\n\nIn this chapter we list a few things we had planned to do in the near future\nthat we feel might be of use to future developers.\n\n\nUpgrade Python and Django\n=========================\n\nWe had planned to upgrade to Python 3 and the newest version of Django as soon\nas possible. Both upgrades should be fairly straight forward. The Python 3 upgrade\nmight require a significant amount work if some of the libraries currently used\nstill are unavailable in versions working with Python 3 but for the most part\nthe code has been prepared for Python 3.\n\n\nRefactor user model according to present Django convensions\n===========================================================\n\nThe user model was naturally one of the first models implemented and back then\nDjango was at version 1.5. A lot has changed since then, especially regarding\nto how custom user models are integrated, and therefore it would be wise to\nrefactor the model to follow current Django user model guidelines.\n\n\nGet rid of :attr:`User.user_type`\n===========================================================\n\nThe :attr:`gridplatform.users.models.User.user_type` attribute is legacy, and\nis still used in GridPortal 2.0 by access control logic. However, the same\naccess control can easily be achieved using permissions.\n\n\nRefactor the :attr:`Sample` class.\n==================================\n\nThe :class:`gridplatform.utils.samples.Sample` class already should be refactored into\ntwo separate classes, namely :class:`PointSample` and :class:`RangedSample`. See\n:file:`gridplatform/utils/samples.py` code comments for further details.\n\n\nRe-specification and refactoring of the *Provider* concept\n==========================================================\n\nWhen the provider concept was originally created only provider users needed\naccess to provider information. However, later it made sense that customers\nusers for a specific provider can see the provider information as well.\n\nWhoever continues the work on this code should stress the necessity of getting\nprovider concept properly specified and then refactor accordingly.\n" }, { "alpha_fraction": 0.520943284034729, "alphanum_fraction": 0.5420514345169067, "avg_line_length": 30.419689178466797, "blob_id": "4d47f23eeebaacfb6794fea54ef494e923e92f40", "content_id": "9a4a2e0caea5baa26d1e616231246c20285b3dfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6064, "license_type": "no_license", "max_line_length": 79, "num_lines": 193, "path": "/emonhub/src/interfacers/EmonHubSmilicsInterfacer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "'''\n Interface conf:\n [[SMILICS_INTERFACE]]\n Type = EmonHubSmilicsInterfacer\n [[[init_settings]]]\n port = 8080\n [[[runtimesettings]]]\n pubchannels = ToCloud\n subchannels = ToNothing\n\n Node conf:\n Using the Wibeee mac-address as node id\n\n [[121111111111]]\n nodename = SMILICS01\n firmware =V120\n hardware = Smilics Wibeee\n [[[rx]]]\n names = power1, power2, power3, power_total, wh1, wh2, wh3, wh_total\n datacodes = h, h, h, h, h, h, h, h\n scales = 1, 1, 1, 1, 1, 1, 1, 1\n units = W, W, W, W, Wh, Wh, Wh, Wh\n'''\n\nimport threading\nimport datetime\nimport time\nimport traceback\n\nfrom BaseHTTPServer import BaseHTTPRequestHandler\nfrom Queue import Queue\nfrom SocketServer import TCPServer, ThreadingMixIn\nfrom urlparse import parse_qs\nfrom pydispatch import dispatcher\n\nimport Cargo\nimport emonhub_coder as ehc\nfrom emonhub_interfacer import EmonHubInterfacer\n\n\nclass ThreadedTCPServer(ThreadingMixIn, TCPServer):\n def serve_forever(self, queue):\n self.RequestHandlerClass.queue = queue\n TCPServer.serve_forever(self)\n\n\nclass ServerHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n data = parse_qs(self.path[17:])\n data['timestamp'] = datetime.datetime.now()\n print data\n #self.queue.put(data)\n\n\nclass EmonHubSmilicsInterfacer(EmonHubInterfacer):\n \"\"\" Interface for the Smilics Wibee\n\n Listen for get request on the specified port\n \"\"\"\n\n def __init__(self, name, port):\n \"\"\"\n Args:\n name (str): Configuration name.\n port (int): The port the webserver should listen on.\n \"\"\"\n super(EmonHubSmilicsInterfacer, self).__init__(name)\n\n self._settings = {\n 'subchannels': ['ch1'],\n 'pubchannels': ['ch2'],\n }\n self._queue = Queue()\n self._server = ThreadedTCPServer((\"0.0.0.0\", int(port)), ServerHandler)\n self.last_reading = None\n self.wh_counter1 = 0\n self.wh_counter2 = 0\n self.wh_counter3 = 0\n self.wh_counter4 = 0\n self.acc_power1 = 0\n self.acc_power2 = 0\n self.acc_power3 = 0\n self.acc_power4 = 0\n\n def close(self):\n \"\"\"Cleanup when the interface closes\"\"\"\n if self._server is not None:\n self._log.debug('Closing server')\n self._server.shutdown()\n self._server.server_close()\n\n def run(self):\n \"\"\"Starts the server on a new thread and processes the queue\"\"\"\n server_thread = threading.Thread(\n target=self._server.serve_forever, args=(self._queue,))\n server_thread.daemon = True\n server_thread.start()\n\n while not self.stop:\n while not self._queue.empty():\n rxc = self._process_rx(self._queue.get(False))\n self._queue.task_done()\n\n if rxc:\n for channel in self._settings[\"pubchannels\"]:\n dispatcher.send(channel, cargo=rxc)\n self._log.debug(\n str(rxc.uri) + \" Sent to channel' : \" +\n str(channel))\n time.sleep(0.1)\n\n self.close()\n\n def _process_rx(self, smilics_dict):\n \"\"\" Converts the data recieved on the webserver to an instance of\n the Cargo class\n\n Args:\n smilics_dict: Dict with smilics data.\n\n Returns:\n Cargo if successful, None otherwise.\n \"\"\"\n try:\n c = Cargo.new_cargo()\n if 'mac' not in smilics_dict.keys():\n return None\n\n c.nodeid = smilics_dict['mac'][0]\n if c.nodeid not in ehc.nodelist.keys():\n self._log.debug(str(c.nodeid) + \" Not in config\")\n return None\n\n timestamp = smilics_dict['timestamp']\n if not self.last_reading:\n self.last_reading = timestamp\n return None\n\n time_between = timestamp - self.last_reading\n time_between = time_between.total_seconds()\n\n self.last_reading = timestamp\n\n self.wh_counter1 += float(smilics_dict['a1'][0])\n self.wh_counter2 += float(smilics_dict['a2'][0])\n self.wh_counter3 += float(smilics_dict['a3'][0])\n self.wh_counter4 += float(smilics_dict['at'][0])\n\n i_delta = self.wh_counter1 / (3600 / time_between)\n self.acc_power1 += i_delta\n self.wh_counter1 -= (i_delta * (3600 / time_between))\n\n i_delta = self.wh_counter2 / (3600 / time_between)\n self.acc_power2 += i_delta\n self.wh_counter2 -= (i_delta * (3600 / time_between))\n\n i_delta = self.wh_counter3 / (3600 / time_between)\n self.acc_power3 += i_delta\n self.wh_counter3 -= (i_delta * (3600 / time_between))\n\n i_delta = self.wh_counter4 / (3600 / time_between)\n self.acc_power4 += i_delta\n self.wh_counter4 -= (i_delta * (3600 / time_between))\n\n node_config = ehc.nodelist[str(c.nodeid)]\n\n c.names = node_config['rx']['names']\n c.nodename = node_config['nodename']\n\n c.realdata = [\n smilics_dict['a1'][0],\n smilics_dict['a2'][0],\n smilics_dict['a3'][0],\n smilics_dict['at'][0],\n self.acc_power1,\n self.acc_power2,\n self.acc_power3,\n self.acc_power4,\n ]\n c.timestamp = time.mktime(timestamp.timetuple())\n\n return c\n except:\n traceback.print_exc()\n return None\n\n def set(self, **kwargs):\n \"\"\" Override default settings with settings entered in the config file\n \"\"\"\n for key, setting in self._settings.iteritems():\n if key in kwargs.keys():\n # replace default\n self._settings[key] = kwargs[key]\n" }, { "alpha_fraction": 0.7145479321479797, "alphanum_fraction": 0.7150068879127502, "avg_line_length": 42.58000183105469, "blob_id": "df81513f59c7282628694dd1ecdc7fa8cd471681", "content_id": "10d0151e26bd2e8a87517964422acffed0a55d18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4358, "license_type": "no_license", "max_line_length": 79, "num_lines": 100, "path": "/legacy/measurementpoints/proxies/districtheatingmeasurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.measurementpoints.models import Link\nfrom legacy.measurementpoints.models import MeanTemperatureChange\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import utilitytypes\n\nfrom .consumptionmeasurementpoint import ConsumptionMeasurementPoint\nfrom .consumptionmeasurementpoint import cached_lookup_property\n\n\nclass DistrictHeatingMeasurementPoint(ConsumptionMeasurementPoint):\n \"\"\"\n In district heating, heat energy is transported in a distribution medium,\n usually water (but oil and steam can also be used). A\n C{DistrictHeatingMeasurementPoint} is a heat consumption measurement point\n specialized for district heating, using water as heat distribution medium.\n\n Since the temperature differense between the distribution medium and what\n needs to be heated is significantly lower for water than the other kinds\n distribution media, costs of circulating water between the utility provider\n and the consumer are sufficiently high to make utility providers\n interrested in minimizing the amount of water circulated pr distributed\n quantity of heat energy. This can reliably be translated to maximizing the\n mean cool-down temperature.\n\n So when inspecting a district heating measurement point one will be\n presented with a heat consumption graph, water circulation graph and\n finally a mean cool-down temperature graph.\n\n In general, given two of the graphs, the third graph can be deducted. In\n this implementation, the mean cool-down temperature graph is deduced from\n the heat consumption graph and water circulation graph.\n\n @ivar consumption_input: Inherited from L{ConsumptionMeasurementPoint}.\n\n @ivar volume_input: The L{ConsumptionAccumulationAdapter} that measure the\n heat distribution medium (i.e. a water consumption measurement point,\n district heating featuring steam as heat distribution medium is not\n supported).\n \"\"\"\n\n class Meta:\n verbose_name = _('district heating measurement point')\n verbose_name_plural = _('district heating measurement points')\n proxy = True\n app_label = 'customers'\n\n def __init__(self, *args, **kwargs):\n super(DistrictHeatingMeasurementPoint, self).__init__(*args, **kwargs)\n if self.utility_type is None:\n self.utility_type = utilitytypes.METER_CHOICES.district_heating\n\n def save(self, *args, **kwargs):\n assert self.volume_input\n assert PhysicalQuantity.compatible_units(\n self.volume_input.unit, 'meter^3')\n super(DistrictHeatingMeasurementPoint, self).save(*args, **kwargs)\n\n volume_graph, created = Graph.objects.get_or_create(\n collection=self, role=DataRoleField.VOLUME)\n if created:\n volume = Link(\n graph=volume_graph,\n role=DataRoleField.VOLUME,\n utility_type=self.utility_type)\n else:\n volume = volume_graph.dataseries_set.get().subclass_instance\n volume.target = self.volume_input\n volume.clean()\n volume.save()\n\n cooldown_graph, cooldown_created = self.graph_set.get_or_create(\n role=DataRoleField.MEAN_COOLDOWN_TEMPERATURE)\n if cooldown_created:\n cooldown = MeanTemperatureChange(\n graph=cooldown_graph,\n role=DataRoleField.MEAN_COOLDOWN_TEMPERATURE,\n utility_type=self.utility_type,\n unit='millikelvin')\n else:\n cooldown = cooldown_graph.dataseries_set.get().subclass_instance\n cooldown.energy = self.consumption\n cooldown.volume = volume\n cooldown.clean()\n cooldown.save()\n\n @cached_lookup_property\n def volume_input(self):\n return ConsumptionAccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self.id,\n link_derivative_set__graph__role=DataRoleField.VOLUME).\\\n distinct().get().subclass_instance\n" }, { "alpha_fraction": 0.6530866026878357, "alphanum_fraction": 0.6552635431289673, "avg_line_length": 36.49854278564453, "blob_id": "5b8c8e5db51a02b5a896277c07dbedfce26fd2c6", "content_id": "f788c4f46ae08cbdb908afbf9ef4d2c081b63754", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12862, "license_type": "no_license", "max_line_length": 79, "num_lines": 343, "path": "/gridplatform/tariffs/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.functional import cached_property\nfrom django.core.exceptions import ValidationError\nfrom model_utils import Choices\n\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.datasequences.models import piecewiseconstant\nfrom gridplatform.datasequences.models import PiecewiseConstantPeriodManager\nfrom gridplatform.utils import units\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils import sum_or_none\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.datasequences.models import CurrencyUnitMixin\n\n\nclass Tariff(CurrencyUnitMixin, piecewiseconstant.PiecewiseConstantBase):\n \"\"\"\n Base model for tariffs.\n\n :ivar name: The name of the tariff\n :ivar customer: The customer owning the tariff.\n \"\"\"\n\n class Meta:\n verbose_name = _('tariff')\n verbose_name_plural = _('tariff')\n\n @virtual\n def _unit(self):\n raise NotImplementedError(self.__class__)\n\n @cached_property\n def unit(self):\n return self._unit()\n\n\nclass EnergyTariff(Tariff):\n \"\"\"\n Specialization of :py:class:`.Tariff` for energy.\n \"\"\"\n class Meta:\n verbose_name = _('energy tariff')\n verbose_name_plural = _('energy tariff')\n\n def _unit(self):\n return self.customer.currency_unit + '*megawatt^-1*hour^-1'\n\n\nclass VolumeTariff(Tariff):\n \"\"\"\n Specialization of :py:class:`.Tariff` for volume.\n \"\"\"\n\n class Meta:\n verbose_name = _('volume tariff')\n verbose_name_plural = _('volume tariff')\n\n def _unit(self):\n return self.customer.currency_unit + '*meter^-3'\n\n\nclass TariffPeriodManager(PiecewiseConstantPeriodManager):\n \"\"\"\n Manager defining methods useful for reverse relations to tariff periods.\n E.g.::\n\n mainconsumption.tariff.period_set.value_sequence()\n\n or::\n\n mainconsumption.tariff.period_set.subscription_cost_sum()\n\n These would of course look nicer if the periods were attached directly to\n the :py:class:`~gridplatform.consumptions.models.MainConsumption`. E.g.::\n\n mainconsumption.tariff_set.value_sequence()\n\n :note: The methods being intended for reverse relations will also polute\n the default manager. Reverse relation methods that don't work on the\n default manager like this should be avoided, in fact they are\n considered wrong. Given no obvious means for doing this right a free\n function would be preferred.\n \"\"\"\n use_for_related_fields = True\n\n def subscription_cost_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: The total subscription cost of all periods in the given range.\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n \"\"\"\n periods = self.in_range(from_timestamp, to_timestamp)\n return sum_or_none(\n period.subscription_cost_sum(\n *period.overlapping(from_timestamp, to_timestamp))\n for period in periods)\n\n def value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n A sequence of tariff samples of all periods in the given range.\n\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n :return: A sequence of ranged tariff samples in one hour resolutions.\n \"\"\"\n for sample in super(TariffPeriodManager, self).value_sequence(\n from_timestamp, to_timestamp):\n assert RelativeTimeDelta(\n sample.to_timestamp, sample.from_timestamp) == \\\n RelativeTimeDelta(hours=1)\n yield sample\n\n\nclass Period(piecewiseconstant.PiecewiseConstantPeriodBase):\n datasequence = models.ForeignKey(\n Tariff,\n verbose_name=_('data sequence'),\n editable=False)\n\n objects = TariffPeriodManager()\n\n class Meta:\n verbose_name = _('tariff period')\n verbose_name_plural = _('tariff periods')\n ordering = ('from_timestamp',)\n\n def subscription_cost_sum(self, from_timestamp, to_timestamp):\n assert from_timestamp >= self.from_timestamp\n assert self.to_timestamp is None or to_timestamp <= self.to_timestamp\n return self._subscription_cost_sum(from_timestamp, to_timestamp)\n\n @virtual\n def _subscription_cost_sum(self, from_timestamp, to_timestamp):\n raise NotImplementedError(self.__class__)\n\n @property\n def currency_unit(self):\n return self.datasequence.currency_unit\n\n\nclass SubscriptionMixin(models.Model):\n # how awesome it would have been if these were represented as\n # their corresponding unit strings in the db.\n SUBSCRIPTION_PERIODS = Choices(\n (1, 'monthly', _('monthly')),\n (2, 'quarterly', _('quarterly')),\n (3, 'yearly', _('yearly')),\n )\n # The unit this value is currency unit from the datasequence,\n # i.e. either currency_dkk or currency_eur. Quite obvious\n # considering the currency_unit property.\n subscription_fee = models.DecimalField(\n _('subscription fee'), max_digits=12, decimal_places=3)\n subscription_period = models.IntegerField(\n _('subscription period'), choices=SUBSCRIPTION_PERIODS)\n\n class Meta:\n abstract = True\n\n @classmethod\n def time_quantity(cls, db_value):\n \"\"\"\n Translates a ``subscription_period`` ``db_value`` to the corresponding\n :class:`PhysicalQuantity` time quantity.\n \"\"\"\n if db_value == cls.SUBSCRIPTION_PERIODS.monthly:\n return PhysicalQuantity(1, 'month')\n elif db_value == cls.SUBSCRIPTION_PERIODS.quarterly:\n return PhysicalQuantity(1, 'quarteryear')\n else:\n assert db_value == cls.SUBSCRIPTION_PERIODS.yearly\n return PhysicalQuantity(1, 'year')\n\n def _subscription_cost_sum(self, from_timestamp, to_timestamp):\n # NOTE: This appraoch does not work if we really care about\n # calendar months, quarters and years (none of which\n # correspond to a fixed number of seconds). So the result may\n # be off by up to 4%, but that should be insignificant\n # compared to the actual utility costs that goes with the\n # subscription cost.\n subscription_fee = PhysicalQuantity(\n self.subscription_fee, self.currency_unit)\n subscription_time = self.time_quantity(self.subscription_period)\n duration_time = PhysicalQuantity(\n (to_timestamp - from_timestamp).total_seconds(), 'second')\n return subscription_fee * duration_time / subscription_time\n\n\nclass FixedPricePeriod(\n piecewiseconstant.FixedPiecewiseConstantPeriodValueSequenceMixin,\n SubscriptionMixin, Period):\n \"\"\"\n A tariff period defining a fixed price and subscription costs.\n\n :ivar datasequence: The aggregating tariff.\n :ivar subscription_fee: The subscription fee.\n :ivar subscription_period: The rate at which the subscription fee should be\n payed. Must be one of\n :py:attr:`~.SubscriptionMixin.SUBSCRIPTION_PERIODS`.\n :ivar value: The value of the fixed price.\n :ivar unit: The unit of the fixed price value. Must be in the ones\n returned by :py:meth:`.get_unit_choices`.\n \"\"\"\n value = models.DecimalField(_('value'), max_digits=12, decimal_places=3)\n unit = BuckinghamField(_('unit'), choices=units.TARIFF_CHOICES)\n resolution = condense.HOURS\n\n class Meta:\n verbose_name = _('fixed price period')\n verbose_name_plural = _('fixed price periods')\n\n def __unicode__(self):\n return '%s - %s: Fixed price period' % (\n self.from_timestamp, self.to_timestamp)\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.unit`` and ``self.datasequence.unit``\n are not compatible.\n \"\"\"\n super(FixedPricePeriod, self).clean()\n if not PhysicalQuantity.compatible_units(\n self.unit, self.datasequence.unit):\n raise ValidationError(_('Incompatible unit.'))\n\n @cached_property\n def _quantity(self):\n return PhysicalQuantity(self.value, self.unit)\n\n def get_unit_choices(self):\n \"\"\"\n :return: A list of valid unit choices for this period.\n \"\"\"\n return [\n (unit, label) for unit, label in units.TARIFF_CHOICES\n if PhysicalQuantity.compatible_units(unit, self.datasequence.unit)]\n\n\nclass SpotPricePeriod(SubscriptionMixin, Period):\n \"\"\"\n A tariff period defined in terms of a\n :py:class:`~gridplatform.datasources.models.DataSource`, and subscription\n costs.\n\n :ivar datasequence: The aggregating tariff.\n :ivar subscription_fee: The subscription fee.\n :ivar subscription_period: The rate at which the subscription fee should be\n payed. Must be one of\n :py:attr:`~.SubscriptionMixin.SUBSCRIPTION_PERIODS`.\n :ivar spotprice: The\n :py:class:`~gridplatform.datasources.models.DataSource` defining the\n spot price.\n :ivar coefficient: A unitless coefficient that each spot price value is\n multiplied by.\n :ivar unit_for_constant_and_ceiling: The unit for ``self.constant`` and\n ``self.ceiling``.\n\n :ivar constant: A constant added to the spot price value after it has been\n multiplied with ``self.coefficient``.\n\n :ivar ceiling: A ceiling for the resulting tariff value after\n ``self.coefficient`` and ``self.constant`` has been applied.\n \"\"\"\n\n spotprice = models.ForeignKey(\n DataSource, verbose_name=_('spot price'))\n coefficient = models.DecimalField(\n _('coefficient'), max_digits=12, decimal_places=3)\n unit_for_constant_and_ceiling = BuckinghamField(\n _('unit for constant and ceiling'),\n choices=units.TARIFF_CHOICES)\n constant = models.DecimalField(\n _('constant'), max_digits=12, decimal_places=3)\n ceiling = models.DecimalField(\n _('ceiling'), max_digits=12, decimal_places=3, null=True, blank=True)\n\n def __unicode__(self):\n return '%s - %s: Spot price period' % (\n self.from_timestamp, self.to_timestamp)\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.unit_for_constant_and_ceiling`` is\n not compatible with the aggregating tariff.\n :raise ValidationError: If the spot price unit and the unit of the\n aggregating tariff are not compatible.\n \"\"\"\n super(SpotPricePeriod, self).clean()\n if not PhysicalQuantity.compatible_units(\n self.unit_for_constant_and_ceiling, self.datasequence.unit):\n raise ValidationError(\n _('Incompatible unit for constant and ceiling.'))\n if not PhysicalQuantity.compatible_units(\n self.spotprice.unit, self.datasequence.unit):\n raise ValidationError(\n _('Incompatible spot price unit.'))\n\n def _get_unit(self):\n return self.spotprice.unit\n\n def _value_sequence(self, from_timestamp, to_timestamp):\n unit = self.spotprice.unit\n constant = PhysicalQuantity(\n self.constant, self.unit_for_constant_and_ceiling)\n coefficient = self.coefficient\n\n if self.ceiling is not None:\n def value(spot_value):\n ceiling = PhysicalQuantity(\n self.ceiling, self.unit_for_constant_and_ceiling)\n return min(\n PhysicalQuantity(\n spot_value, unit) * coefficient + constant,\n ceiling)\n else:\n def value(spot_value):\n return PhysicalQuantity(\n spot_value, unit) * coefficient + constant\n\n # NOTE: this assumes that the \"spotprice\" datasource delivers hourly\n # data.\n spot_data = self.spotprice.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp\n ).order_by('timestamp').values_list('timestamp', 'value')\n\n for timestamp, spot_value in spot_data:\n # BUG: timezone retreived from db as utc. RelativeTimeDelta is\n # equivalent with datetime.timedelta in that case, and the DST\n # transitions may not be handled correctly.\n yield Sample(\n timestamp,\n timestamp + RelativeTimeDelta(hours=1), value(spot_value),\n False, False)\n" }, { "alpha_fraction": 0.8082191944122314, "alphanum_fraction": 0.8082191944122314, "avg_line_length": 35.5, "blob_id": "bba715891c81c82df703749bf4c0520e8f13e263", "content_id": "2aa9dd403286cfc5f3a0c174bf63c96a180c7d86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 219, "license_type": "no_license", "max_line_length": 77, "num_lines": 6, "path": "/README.txt", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "The documentation is made with Sphinx and a precompiled version in both HTML\nand PDF format is delivered with this package. You can find it in the folder:\n\ndocumentation/dist\n\nGo read that documentation to get started.\n" }, { "alpha_fraction": 0.6581640243530273, "alphanum_fraction": 0.6599436402320862, "avg_line_length": 35.84699630737305, "blob_id": "c969449253536cc0e1b7d2abadfcfac4acacc7d9", "content_id": "6c92666e8b7e5a2202429eea47b72f57258b234a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6743, "license_type": "no_license", "max_line_length": 79, "num_lines": 183, "path": "/gridplatform/users/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth import hashers\nfrom django.contrib.auth.models import UserManager as DjangoUserManager\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\nfrom django.db.models.query_utils import Q\nfrom django.utils import timezone\nfrom django.utils.encoding import smart_str\n\nfrom gridplatform.encryption.managers import DecryptingManager\nfrom gridplatform.encryption.managers import DecryptingQuerySet\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_provider_id\nfrom gridplatform.trackuser.managers import FilteringQuerySetMixinBase\n\n\ndef hash_username(username):\n \"\"\"\n Hash the username, to get uniform 30-character \"username\" strings.\n The salt is hardcoded, to allow us to make lookups based on provided\n \"plain\" usernames.\n\n (A salt per entry, as is common for passwords, only works when we otherwise\n know which entry to check and thus which salt to use when hashing the\n comparison string.)\n\n This *does* make brute-force attacks on usernames \"easier\", as each\n potential username may be hashed and then checked against all existing\n usernames...\n \"\"\"\n algorithm = 'pbkdf2_sha1'\n iterations = 10000\n salt = 'qXopipOboNOG'\n hasher = hashers.get_hasher(algorithm)\n username = smart_str(username)\n encoded = hasher.encode(username.lower(), salt, iterations)\n algorithm_, iterations_, salt_, hashed = encoded.split('$')\n assert algorithm_ == algorithm\n assert iterations_ == str(iterations)\n assert salt_ == salt\n return hashed[:30]\n\n\nclass UserManager(DecryptingManager, DjangoUserManager):\n \"\"\"\n Base user manager without filtering --- implementing a variant of the user\n creation interface from the ``django.contrib.auth`` ``UserManager``.\n\n Provided separately from the manager applying filtering, as implementing\n ``create_user()`` and providing filtering is separate concerns, and\n besides, the ``User`` class in particular needs a non-filtering manager for\n the login-page and for collision-checks on creation.\n \"\"\"\n def _create_user(self, *args, **kwargs):\n raise NotImplementedError(\n b'Encrypted users cannot be created with \"_create_user()\"')\n\n def create(self, *args, **kwargs):\n raise NotImplementedError(\n b'Encrypted users cannot be created with \"create()\"')\n\n def create_user(\n self, username, password, user_type,\n customer=None, provider=None, groups=None):\n \"\"\"\n Creates and saves a User with the given username and password.\n \"\"\"\n now = timezone.now()\n if not username:\n raise ValueError('The given username must be set')\n if not password:\n raise ValueError('The given password must be set')\n hashed_username = hash_username(username)\n # Using self.model._all_users to allow the bound manager subclass to\n # still check against unfiltered here...\n if self.model._all_users.filter(username=hashed_username).exists():\n raise ValueError('The given username already exists')\n\n user = self.model(\n username=hashed_username,\n is_staff=False, is_superuser=False,\n last_login=now, date_joined=now,\n customer=customer, provider=provider,\n user_type=user_type)\n user.set_password(password)\n # self.model should be User --- avoiding circular import...\n user.e_mail_plain = username\n user.name_plain = ''\n user.phone_plain = ''\n user.mobile_plain = ''\n user.save(using=self._db)\n if groups:\n user.groups = groups\n user.save(using=self._db)\n return user\n\n\nclass UserQuerySetMixin(FilteringQuerySetMixinBase):\n \"\"\"\n Slightly modified variant of code from\n :class:`gridplatform.trackuser.managers.CustomerBoundQuerySetMixin`\n \"\"\"\n def _apply_filtering(self):\n \"\"\"\n Ensures that only User objects that the currently logged in user should\n have access to can be queried.\n\n The current user must be authenticated, or the empty queryset is\n returned.\n\n For customer users, and provider users who has selected a customer, the\n customer must be active or the empty queryset is returned. If the\n customer is active, users belonging to that customer and to the\n provider related to the customer are visible.\n\n For provider users without a selected customer all users related to the\n same provider or related with a customer associated with the same\n provider are visible.\n \"\"\"\n user = get_user()\n customer = get_customer()\n provider_id = get_provider_id()\n\n if user is None:\n pass\n elif not user.is_authenticated():\n self.query.set_empty()\n elif customer is not None:\n if not customer.is_active:\n self.query.set_empty()\n else:\n self.query.add_q(\n Q(customer_id=customer.id) | Q(provider_id=provider_id))\n elif provider_id:\n self.query.add_q(\n Q(provider_id=provider_id) |\n Q(customer__provider_id=provider_id))\n else:\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n pass\n\n\nclass BoundUserManager(UserManager):\n \"\"\"\n Manager that mixes :class:`.UserQuerySetMixin` into all the querysets it\n works with.\n \"\"\"\n _field = None\n\n class _QuerySet(UserQuerySetMixin, DecryptingQuerySet):\n pass\n\n class _ValuesQuerySet(UserQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(UserQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(UserQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(UserQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(UserManager, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_filter_field': self._field,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n" }, { "alpha_fraction": 0.8048229217529297, "alphanum_fraction": 0.8048229217529297, "avg_line_length": 43.233333587646484, "blob_id": "c6f453399d36fb2fc0a53426fc2359c772d4c0ee", "content_id": "496bc6453bcc8dfc469349ceac462517c86a2a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1327, "license_type": "no_license", "max_line_length": 70, "num_lines": 30, "path": "/documentation/source/costcompensations.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": ".. _cost-compensations:\n\nCost Compensations\n==================\n\nCertain uses of energy are considered in the general interest of\nsociety, and are eligible for tax refunds. Or in general, the tariff\non the same utility may come with a rebate for certain energy uses.\nThis is where cost compensations come in.\n\nCost compensations are subtracted from tariff values when calculating\nvariable costs.\n\nWe assume that taxes may only be refunded once for a particular energy\nuse. So a cost compensation may apply to all energy uses for a\ncertain main consumption, with explicit exceptions. That is, the\nenergy uses with a specific cost compensation are excluded when\napplying a general cost compensation to a main consumption.\n\nEventually the cost compensations of each energy use of a main\nconsumption along with the general cost compensation for the same main\nconsumption will all be applied when calculating the variable costs of\nthe particular main consumption.\n\nWhen calculating the variable costs of an energy use, any cost\ncompensation related directly to the energy use is applied. If no\nsuch cost compensation exists, we shall fall back to the general cost\ncompensation of the aggregating main consumption. Finally if no\ngeneral cost compansation is defined for the main consumption no cost\ncompensation will be applied.\n" }, { "alpha_fraction": 0.6634638905525208, "alphanum_fraction": 0.6639566421508789, "avg_line_length": 32.97071075439453, "blob_id": "c76a6543e2f3c399559acb1b0f4297a8cec04028", "content_id": "6e489023aa63ea2645fe004a3ced28eac911d203", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8118, "license_type": "no_license", "max_line_length": 107, "num_lines": 239, "path": "/energymanager/project_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.formats import date_format\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import forms\nfrom django.core.urlresolvers import reverse\n\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.consumptions.tasks import consumptions_weekly_utility_task, consumptions_weekly_time_task\nfrom gridplatform.utils.forms import YearWeekPeriodForm\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.utilitytypes import ENERGY_UTILITY_TYPE_TO_DISPLAY_UNIT_MAP\nfrom gridplatform.utils.views import CustomerInKwargsMixin, FinalizeTaskView, JsonResponse\nfrom gridplatform.utils.views import StartTaskView\nfrom gridplatform.utils import generic_views, PhysicalQuantity\nfrom gridplatform.utils.breadcrumbs import Breadcrumb\nfrom gridplatform.utils.breadcrumbs import Breadcrumbs\nfrom gridplatform.utils.views import ChooseCustomerBase\nfrom gridplatform.utils.views import CustomerListMixin\nfrom gridplatform.utils.views import CustomerViewBase\nfrom gridplatform.utils.views import HomeViewBase\n\nfrom energymanager.energy_projects.models import EnergyProject, ENERGY_PROJECT_PHASES\n\n\nclass HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'project_site:project-list',\n kwargs={'customer_id': customer_id})\n\n def get_choose_customer_url(self):\n return reverse(\n 'project_site:choose-customer')\n\n\nclass ChooseCustomer(ChooseCustomerBase):\n template_name = 'project_site/choose_customer.html'\n\n\nclass CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'project_site:project-list',\n kwargs={'customer_id': customer_id})\n\n\nclass EnergyProjectList(CustomerListMixin, generic_views.TemplateView):\n template_name = 'project_site/project_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Projects'),\n reverse(\n 'project_site:project-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass EnergyProjectListContentView(\n CustomerListMixin,\n generic_views.ListView):\n search_fields = ['name_plain', ]\n sort_fields = ['name_plain', ]\n model = EnergyProject\n paginate_by = 100\n template_name = 'project_site/_project_list_content.html'\n\n\nclass EnergyProjectForm(forms.ModelForm):\n\n class Meta:\n model = EnergyProject\n fields = (\n 'name', 'baseline_from_date', 'baseline_to_date',\n 'datasource', 'time_datasource',\n 'result_from_date', 'result_to_date'\n )\n\n\nclass EnergyProjectCreateView(CustomerListMixin,\n generic_views.CreateView):\n model = EnergyProject\n template_name = 'project_site/project_form.html'\n form_class = EnergyProjectForm\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n result = super(EnergyProjectCreateView, self).form_valid(form)\n assert self.object.id\n self._customer.energyproject_set.add(self.object)\n return result\n\n def get_success_url(self):\n return reverse('project_site:project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return EnergyProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create Project'))\n\n\nclass EnergyProjectUpdateView(CustomerListMixin,\n generic_views.UpdateView):\n model = EnergyProject\n template_name = 'project_site/project_form.html'\n form_class = EnergyProjectForm\n\n def get_success_url(self):\n return reverse('project_site:project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_delete_url(self):\n return reverse('project_site:project-delete',\n kwargs={'customer_id':\n self._customer.id,\n 'pk':\n self.object.id})\n\n def get_breadcrumbs(self):\n return EnergyProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n\nclass EnergyProjectDeleteView(\n CustomerListMixin, generic_views.DeleteView):\n model = EnergyProject\n\n def get_success_url(self):\n return reverse('project_site:project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n\nclass EnergyProjectDetailView(\n CustomerListMixin, generic_views.DetailView):\n model = EnergyProject\n template_name = \\\n 'project_site/overview.html'\n\n def get_breadcrumbs(self):\n return EnergyProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n def get_context_data(self, **kwargs):\n context = super(EnergyProjectDetailView, self).get_context_data(**kwargs)\n\n context['phase'] = ENERGY_PROJECT_PHASES[self.object.project_phase()]\n context['baseline_sum'] = self.object.total_baseline_consumption()\n context['baseline_time_sum'] = self.object.total_baseline_time_consumption()\n return context\n\n\nclass StartHourConsumptionUtilityBarChartViewBase(\n CustomerInKwargsMixin, StartTaskView):\n task = consumptions_weekly_time_task\n finalize_url_name = 'project_site:utility-bar-chart-finalize'\n form_class = YearWeekPeriodForm\n\n def get_consumption_id(self, project):\n raise NotImplementedError()\n\n def get_task_kwargs(self, form):\n project = EnergyProject.objects.get(pk=self.kwargs['project_id'])\n from_timestamp, to_timestamp = project.baseline_timestamps()\n result = {}\n result['consumption_ids'] = [self.get_consumption_id(project)]\n result['from_timestamp'] = from_timestamp\n result['to_timestamp'] = to_timestamp\n return result\n\n def get_finalize_url(self):\n return reverse(\n self.finalize_url_name,\n kwargs={'customer_id': self._customer.id})\n\n\nclass StartBaselineHourConsumptionUtilityBarChartView(\n StartHourConsumptionUtilityBarChartViewBase):\n task = consumptions_weekly_utility_task\n\n def get_consumption_id(self, project):\n return project.datasource_id\n\n\nclass StartBaselineDayliConsumptionUtilityBarChartView(\n StartHourConsumptionUtilityBarChartViewBase):\n\n def get_consumption_id(self, project):\n return project.time_datasource_id\n\n\nclass FinalizeWeekUtilityBarChartView(CustomerInKwargsMixin, FinalizeTaskView):\n def finalize_task(self, task_result):\n consumption = Consumption.objects.get(pk=task_result['consumption_id'])\n\n unit = 'watt*hour'\n if PhysicalQuantity.compatible_units(\n consumption.unit, 'second'):\n unit = 'hour'\n\n self.unit_converter = PhysicalUnitConverter(unit)\n\n def format_label(timestamp):\n return date_format(\n timestamp.astimezone(self._customer.timezone),\n 'SHORT_DATETIME_FORMAT')\n\n result = {\n 'labels': [],\n 'week_selected': [],\n }\n\n selected_sequence = iter(task_result['week_selected'])\n\n selected = next(selected_sequence, None)\n\n while selected is not None:\n\n result['labels'].append(format_label(selected.from_timestamp))\n result['week_selected'].append(\n float(self.unit_converter.extract_value(\n selected.physical_quantity)))\n selected = next(selected_sequence, None)\n\n return JsonResponse(result)" }, { "alpha_fraction": 0.577418863773346, "alphanum_fraction": 0.5962105989456177, "avg_line_length": 38.18255615234375, "blob_id": "02189c4cb0242812e0a6edec4fe03f1dbd4b11e5", "content_id": "0d9b3066e7040836a034bc1477725e30ed8ea0e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19317, "license_type": "no_license", "max_line_length": 79, "num_lines": 493, "path": "/legacy/manage_devices/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.core.urlresolvers import reverse\nfrom django.test import RequestFactory\n\nfrom gridplatform import trackuser\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.models import Location\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.users.models import User\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom legacy.datasequence_adapters.models import ProductionAccumulationAdapter\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils.utilitytypes import OPTIONAL_METER_CHOICES\n\nfrom .views import ElectricityConsumptionCreateView\nfrom .views import GasConsumptionCreateView\nfrom .views import OilConsumptionCreateView\nfrom .views import DistrictHeatingConsumptionCreateView\nfrom .views import ProductionCreateView\nfrom .views import WaterConsumptionCreateView\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ElectricityConsumptionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = ElectricityConsumptionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'milliwatt*hour',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234)\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.CONSUMPTION,\n utility_type=OPTIONAL_METER_CHOICES.electricity)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass GasConsumptionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = GasConsumptionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'meter*meter*meter',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234)\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.CONSUMPTION,\n utility_type=OPTIONAL_METER_CHOICES.gas)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass OilConsumptionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = OilConsumptionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'meter*meter*meter',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234)\n\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.CONSUMPTION,\n utility_type=OPTIONAL_METER_CHOICES.oil)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DistrictHeatingConsumptionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = DistrictHeatingConsumptionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'milliwatt*hour',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234)\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.CONSUMPTION,\n utility_type=OPTIONAL_METER_CHOICES.district_heating)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass WaterConsumptionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = WaterConsumptionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'meter*meter*meter',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234)\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ConsumptionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.CONSUMPTION,\n utility_type=OPTIONAL_METER_CHOICES.water)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionCreateViewTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n production_a_unit_plain='Pøp Cörn')\n self.datasource = CustomerDataSource.objects.create(\n customer=self.customer)\n self.factory = RequestFactory()\n self.view = ProductionCreateView.as_view()\n\n def test_forms_valid_creates_adapter(self):\n request = self.factory.post(\n 'create/',\n {\n 'name': 'SOME NAME',\n 'pulseperiod_set-TOTAL_FORMS': 1,\n 'pulseperiod_set-INITIAL_FORMS': 0,\n 'pulseperiod_set-MAX_NUM_FORMS': 1000,\n 'pulseperiod_set-0-period_ptr': '',\n 'pulseperiod_set-0-datasequence': '',\n 'pulseperiod_set-0-from_timestamp': '2014-08-01 00:00',\n 'pulseperiod_set-0-to_timestamp': '31.12.9998 00:00:00',\n 'pulseperiod_set-0-pulse_quantity': 1,\n 'pulseperiod_set-0-output_quantity': 2,\n 'pulseperiod_set-0-output_unit': 'production_a',\n }\n )\n request.user = User()\n request.user.is_superuser = True\n with replace_customer(self.customer):\n response = self.view(\n request, physicalinput=self.datasource.id, meter=1234,\n production_unit='production_a')\n self.assertEqual(response.status_code, 302)\n\n self.assertTrue(\n ProductionAccumulationAdapter.objects.filter(\n datasequence__period__pulseperiod__datasource=self.datasource,\n role=DataRoleField.PRODUCTION,\n utility_type=OPTIONAL_METER_CHOICES.unknown)\n .exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ManageUserTest(TestCase):\n \"\"\"\n Test that admin user can view and edit customers devices\n \"\"\"\n\n fixtures = [\"display_measurementpoints_test.json\"]\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(name_plain='Test customer')\n self.customer.save()\n trackuser._set_customer(self.customer)\n assert self.customer is trackuser.get_customer()\n\n self.client.post('/login/', {'username': 'root',\n 'password': 'feet'})\n\n self.location = Location.objects.create(\n customer=self.customer,\n name_plain='Test location')\n\n self.agent = Agent.objects.create(\n customer=self.customer,\n location=self.location,\n mac='AB:CD:DE:F0:12:34')\n\n self.meter = Meter.objects.create(\n agent=self.agent,\n location=self.location,\n manufactoring_id='1234567891234',\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n relay_enabled=True,\n online=True,\n customer=self.customer,\n name_plain='Test meter')\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_admin_meter_list(self):\n \"\"\"\n Test that admin can view meters for a customer\n \"\"\"\n response = self.client.get(reverse('manage_customers-list-json'))\n self.assertContains(response, self.customer.name_plain)\n\n response = self.client.get(\n reverse('manage_customers-meter-list-json',\n kwargs={'customer': self.customer.id}))\n self.assertContains(response, self.meter.name_plain)\n\n def test_unauthorized_cannot_edit_meter(self):\n \"\"\"\n Test that super user for another customer cannot view or edit the meter\n \"\"\"\n self.client.post('/login/', {'username': 'super',\n 'password': '123'})\n\n response = self.client.get(reverse('manage_customers-list-json'))\n self.assertEqual(response.status_code, 403)\n\n response = self.client.get(\n reverse('manage_customers-meter-list-json',\n kwargs={'customer': self.customer.id}))\n self.assertEqual(response.status_code, 403)\n\n response = self.client.get(reverse('manage_devices-meter-update',\n kwargs={'pk': self.meter.id}))\n self.assertEqual(response.status_code, 404)\n\n response = self.client.post(\n reverse('manage_devices-meter-update',\n kwargs={'pk': self.meter.id}),\n {\n 'name': 'New name',\n 'location': self.location.id,\n })\n self.assertEqual(response.status_code, 404)\n\n def test_admin_agent_list(self):\n \"\"\"\n Test that admin can view agents for a customer\n \"\"\"\n response = self.client.get(reverse('manage_customers-list-json'))\n self.assertContains(response, self.customer.name_plain)\n\n response = self.client.get(\n reverse('manage_customers-agent-list-json',\n kwargs={'customer': self.customer.id}))\n self.assertContains(response, self.agent.mac)\n\n def test_admin_agent_edit(self):\n \"\"\"\n Test that admin can view and edit an agent for a customer\n \"\"\"\n response = self.client.get(\n reverse('manage_devices-agent-form', kwargs={'pk': self.agent.id}))\n self.assertContains(response, self.agent.mac)\n\n response = self.client.post(\n reverse('manage_devices-agent-update',\n kwargs={'pk': self.agent.id}),\n {\n 'location': '',\n })\n self.assertEqual(response.status_code, 200)\n self.assertNotIn('errorlist', response.content)\n\n def test_unauthorized_cannot_edit_agent(self):\n \"\"\"\n Test that super user for another customer cannot view or edit the agent\n \"\"\"\n self.client.post('/login/', {'username': 'super',\n 'password': '123'})\n\n response = self.client.get(reverse('manage_customers-list-json'))\n self.assertEqual(response.status_code, 403)\n\n response = self.client.get(\n reverse('manage_customers-agent-list-json',\n kwargs={'customer': self.customer.id}))\n self.assertEqual(response.status_code, 403)\n\n response = self.client.get(\n reverse('manage_devices-agent-form', kwargs={'pk': self.agent.id}))\n self.assertEqual(response.status_code, 404)\n\n response = self.client.post(\n reverse('manage_devices-agent-update',\n kwargs={'pk': self.agent.id}),\n {\n 'location': self.location.id,\n })\n self.assertEqual(response.status_code, 404)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass MeterTest(TestCase):\n def setUp(self):\n self.username = 'root'\n self.password = 'feeet'\n self.user = User.objects.create_user(\n self.username, self.password,\n user_type=User.ADMIN)\n self.user.is_staff = True\n self.user.name_plain = \"Test User {}\".format(self.username)\n self.user.e_mail_plain = '{}@gridmanager.dk'.format(self.username)\n self.user.save()\n self.client.post(\n '/login/',\n {'username': self.username, 'password': self.password})\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.agent = Agent.objects.create(\n mac='AB:CD:DE:F0:12:34',\n customer=self.customer)\n self.meter = Meter.objects.create(\n customer=self.customer,\n agent=self.agent,\n manufactoring_id='1234567891234',\n connection_type=Meter.GRIDPOINT,\n manual_mode=False,\n relay_on=False,\n relay_enabled=True,\n online=True,\n name_plain='Test meter')\n self.pulseinput = PhysicalInput.objects.create(\n customer=self.customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN,\n meter=self.meter,\n order=0,\n name_plain='')\n self.elinput = PhysicalInput.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n meter=self.meter,\n order=1,\n name_plain='')\n\n def test_meter_update(self):\n update_url = reverse(\n 'manage_devices-meter-update',\n kwargs={'pk': self.meter.id})\n\n response = self.client.get(update_url)\n self.assertContains(response, b'Test meter')\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n response = self.client.post(\n update_url, {\n 'item_id': self.meter.id,\n 'name': 'new name',\n 'location': '',\n 'relay_enabled': 'on'\n })\n self.assertEqual(response.status_code, 302)\n\n response = self.client.get(update_url)\n self.assertNotContains(response, b'Test meter')\n self.assertContains(response, b'new name')\n" }, { "alpha_fraction": 0.6129656434059143, "alphanum_fraction": 0.6134494543075562, "avg_line_length": 34.033897399902344, "blob_id": "00de3644632b5ba94bd010b64ab2b08e5361650b", "content_id": "213a6d69e5e88b601ad49e61579f7b58ae24cba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2067, "license_type": "no_license", "max_line_length": 68, "num_lines": 59, "path": "/legacy/manage_customers/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView, DetailView\n\nfrom gridplatform.users.decorators import admin_or_redirect\nfrom gridplatform.customers.models import Customer\n\n\nurlpatterns = patterns(\n 'legacy.manage_customers.views',\n url(r'^as_customer/(?P<pk>\\d+)/$',\n 'as_customer',\n name='manage_customers-as_customer'),\n url(r'^as_admin/$',\n 'as_admin',\n name='manage_customers-as_admin'),\n # customers\n url(r'^$',\n admin_or_redirect(TemplateView.as_view(\n template_name='manage_customers/customer_list.html')),\n name='manage_customers-list'),\n url(r'^json/customer/$',\n 'customer_list_json',\n name='manage_customers-list-json'),\n url(r'^customer/create/$',\n 'customer_form',\n name='manage_customers-create'),\n url(r'^customer/form/(?P<pk>\\d+)/$',\n 'customer_form',\n name=\"manage_customers-form\"),\n url(r'^customer/update/(?P<pk>\\d+)/$',\n 'customer_update',\n name=\"manage_customers-update\"),\n url(r'^customer/update/$',\n 'customer_update',\n name=\"manage_customers-update\"),\n url(r'^customer/(?P<pk>\\d+)/$',\n admin_or_redirect(DetailView.as_view(\n model=Customer,\n template_name='manage_customers/customer_detail.html')),\n name=\"manage_customers-detail\"),\n # customer agents\n url(r'^customer/(?P<customer>\\d+)/agent/$',\n 'customer_agent_list',\n name=\"manage_customers-agent-list\"),\n url(r'^customer/(?P<customer>\\d+)/json/agent/$',\n 'customer_agent_list_json',\n name=\"manage_customers-agent-list-json\"),\n # customer meters\n url(r'^customer/(?P<customer>\\d+)/meter/$',\n 'customer_meter_list',\n name=\"manage_customers-meter-list\"),\n url(r'^customer/(?P<customer>\\d+)/json/meter/$',\n 'customer_meter_list_json',\n name=\"manage_customers-meter-list-json\"),\n)\n" }, { "alpha_fraction": 0.7837837934494019, "alphanum_fraction": 0.7837837934494019, "avg_line_length": 19.55555534362793, "blob_id": "1f6087157dfb8d957f0280195b860c2e90db8ae5", "content_id": "2b7b4dbb1358192079451716ba4309b9cc39970c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "no_license", "max_line_length": 78, "num_lines": 9, "path": "/selenium_test_data.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nimport os\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"gridplatform.settings.local\")\n\nfrom legacy.website.tests import setup\n\nprint setup()\n" }, { "alpha_fraction": 0.6323943734169006, "alphanum_fraction": 0.6366197466850281, "avg_line_length": 30.910112380981445, "blob_id": "18e748756f10be73c285a0f4de5c444f3fff9a93", "content_id": "fbc0ce884c5e6f9d53da2e0ca62858d44f75b98e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2840, "license_type": "no_license", "max_line_length": 79, "num_lines": 89, "path": "/legacy/rules/util.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\nimport datetime\n\nfrom pytz import utc\n\nfrom legacy.ipc import agentserver\n\nfrom .models import TURN_ON\n\n\n# normal week + 1 hour; i.e. longer than actual week except on DST switch\nmax_week_seconds = int(datetime.timedelta(days=7, hours=1).total_seconds())\n\n\ndef week_start(date):\n return datetime.datetime.combine(\n date - datetime.timedelta(date.weekday()),\n datetime.time())\n\n\ndef to_week_second(timestamp):\n timestamp = timestamp.astimezone(utc).replace(tzinfo=None)\n return int((timestamp - week_start(timestamp.date())).total_seconds())\n\n\ndef agent_rules_to_duration_states(rules):\n \"\"\"\n Translate a list of simple (week_second, relay_on)-rules to appropriate\n (from_week_second, to_week_second, relay_on)-rules.\n \"\"\"\n if rules == []:\n return []\n\n # translate AgentRule object to reltime/relay_on pair\n rules = [(to_week_second(rule.activation_time),\n rule.relay_action.relay_action == TURN_ON)\n for rule in rules]\n rules = sorted(rules, key=lambda (time, relay_on): time)\n period_rules = [(start_time, end_time, relay_on)\n for (start_time, relay_on), (end_time, _ignored)\n in zip(rules, rules[1:])]\n start_time, relay_on = rules[-1]\n period_rules.append((start_time, max_week_seconds, relay_on))\n end_time, _ignored = rules[0]\n period_rules.insert(0, (0, end_time, relay_on))\n return filter(\n lambda (time_begin, time_end, relay_on): time_begin != time_end,\n period_rules)\n\n\ndef send_agent_rules(agent_rules):\n \"\"\"\n Translate L{AgentRule} objects to a format closer to the semantics used by\n current agents. (As of GridAgent 2.1.1?)\n \"\"\"\n # group rules by agent\n # for each agent:\n # group rules by meter/relay\n # translate rule format --- timestamp/action -> reltime-duration/action\n # send to agent server\n\n def get_agent(rule):\n return rule.relay_action.meter.agent\n\n def get_agent_id(rule):\n return get_agent(rule).id\n\n def get_meter(rule):\n return rule.relay_action.meter\n\n def get_meter_id(rule):\n return get_meter(rule).id\n\n agent_rules = itertools.groupby(sorted(agent_rules, key=get_agent_id),\n get_agent)\n\n for agent, rules in agent_rules:\n grouped = itertools.groupby(sorted(rules, key=get_meter_id), get_meter)\n\n relay_rules = {\n relay: agent_rules_to_duration_states(rules)\n for relay, rules in grouped}\n rulesets = [([(meter.connection_type, meter.manufactoring_id)], rules)\n for meter, rules in relay_rules.iteritems()]\n agentserver.agent_rules(agent.mac, rulesets)\n" }, { "alpha_fraction": 0.7859677076339722, "alphanum_fraction": 0.7859677076339722, "avg_line_length": 49.7400016784668, "blob_id": "bf6798fac415650baf6df6d1ce626617ec570521", "content_id": "42665ad6feaf88830db261797114bf3304005426", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2537, "license_type": "no_license", "max_line_length": 115, "num_lines": 50, "path": "/documentation/source/privacy.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "*******\nPrivacy\n*******\n\nWe encrypt sensitive information, and we take care to avoid having the\nencryption keys stored or communicated over the network.\n\nAs the primary function of the GridPlatform is to perform calculations on\nmeasurement it would be major performance problem if measurements were to be\nencrypted. To avoid this, all textual company information is instead\nconsidered to be confidential. That is, if you hacked the servers and dumped\nthe database, then you would get all the measurements but you would not know\nwho they belong to or in any way what they are for. Also, even if a develop\nmakes an access control logic error and by mistake gives a user from one customer\naccess to objects from another customer, the user will not be able to see the\nencrypted data that do not belong to his company. In fact, it will cause an\nexception to be raised and this will in turn cause the GridPlatform to send\nthe administrators an e-mail containing a stack trace describing exactly\nwhere the violation occurred.\n\nSo the privacy strategy is:\n\n- All textual and other information that may be used to identify a customer is\n encrypted; with one encryption key per customer. Not even user names are left\n unencrypted. So instead of storing user names directly in the database we are\n storing a hashed version of the user name, so when a user logs in, the user\n name is hashed and then matched against the user names in the database.\n- The keys to decrypt data are stored encrypted; one copy per user with access;\n encrypted with a private/public key pair associated with each user.\n- The private key per user is stored encrypted, with the users login password\n as passphrase.\n- On login, users must provide their user name and passwords; which enables us\n to load the relevant keys.\n- To keep keys accessible during an active session, they are stored as part of\n the session state --- but encrypted, with a randomly generated key provided\n to the client in a cookie, to keep beside the session identifier.\n\n\nImplementation notes\n====================\n\nEncrypted fields on models are accessed using the attribute name\n``<fieldname>_plain`` instead of just ``fieldname`` and then\nencryption/decryption is handled automatically.\n\nThe ``EncryptionMiddleware`` is used to manage having encryption state in a\nthread-local while processing requests, and otherwise split between encrypted\nsession-state and a cookie.\n\nObjects with encrypted fields must override method ``get_encryption_id()`` to provide an encryption key identifier.\n" }, { "alpha_fraction": 0.6352553367614746, "alphanum_fraction": 0.6369028091430664, "avg_line_length": 33.4886360168457, "blob_id": "78a654f875ae888f44ab0d828028c1f1b9626dff", "content_id": "efcf32d4fd1bb231d73f45be1ffb99ffbe5e2b58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3035, "license_type": "no_license", "max_line_length": 79, "num_lines": 88, "path": "/gridplatform/utils/decorators.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom functools import wraps\nfrom exceptions import DeprecationWarning\nimport warnings\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib.auth.decorators import user_passes_test\n\nfrom gridplatform.trackuser import get_provider_id\n\n\ndef deprecated(message_or_function):\n \"\"\"\n Decorator to raise a deprecation warning on method call.\n\n Can be used either as ``@deprecated(message)`` or just\n ``@deprecated`` --- in the second form, the message will be\n constructed as ``\"'method name' is deprecated\"``\n \"\"\"\n def wrap_function(f, message):\n @wraps(f)\n def wrapper(*args, **kwargs):\n warnings.warn(message,\n DeprecationWarning, stacklevel=2)\n return f(*args, **kwargs)\n return wrapper\n if callable(message_or_function):\n f = message_or_function\n message = '%s is deprecated' % (f.__name__,)\n return wrap_function(f, message)\n else:\n message = message_or_function\n return lambda f: wrap_function(f, message)\n\n\ndef virtual(f):\n \"\"\"\n Helper for delegating methods to ``subclass_instance`` from classes based\n on ``StoreSubclass``.\n\n Use on the base class method to have it delegate to the subclass. The\n implementation of the base class will still be used if the subclass does\n not override it --- though it will then be run with the subclass instance\n as ``self``. This can be used to implement pure virtual methods; e.g.::\n\n @virtual\n def __unicode__(self):\n raise NotImplementedError(self.__class__)\n\n where ``self.__class__`` in the exception will indicate the concrete\n subclass.\n \"\"\"\n @wraps(f)\n def wrapper(self, *args, **kwargs):\n if self.__class__ != self.subclass.model_class():\n return getattr(self.subclass_instance, f.__name__)(*args, **kwargs)\n else:\n return f(self, *args, **kwargs)\n return wrapper\n\n\ndef permission_required(\n perm=None, requires_is_staff=False, requires_provider=False,\n login_url=None, raise_exception=False):\n \"\"\"\n Extended version of\n :func:`django.contrib.auth.decorators.permission_required`, to\n include ``requires_is_staff`` and ``requires_provider`` checks.\n \"\"\"\n def check_perms(user):\n passes = True\n if requires_is_staff and not user.is_staff:\n passes = False\n if requires_provider and \\\n not (user.is_authenticated() and get_provider_id()):\n passes = False\n if perm is not None and not user.has_perm(perm):\n passes = False\n if passes:\n return True\n # In case the 403 handler should be called raise the exception\n if raise_exception:\n raise PermissionDenied\n # As the last resort, show the login form\n return False\n return user_passes_test(check_perms, login_url=login_url)\n" }, { "alpha_fraction": 0.584031879901886, "alphanum_fraction": 0.5853729844093323, "avg_line_length": 41.990989685058594, "blob_id": "84d7702ce8ba5ba57fbac16d446cf266f94560cb", "content_id": "d12b7700ab6b80835f235f4f83c29b21f5b53778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23860, "license_type": "no_license", "max_line_length": 84, "num_lines": 555, "path": "/legacy/measurementpoints/models/mixins.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import first_last\nfrom gridplatform.utils import condense\n\n\ndef quotient_sequence(nominator_sequence, denominator_sequence):\n nominator_sequence = iter(nominator_sequence)\n denominator_sequence = iter(denominator_sequence)\n while True:\n # Will stop on either input raising StopIteration...\n nominator = next(nominator_sequence)\n denominator = next(denominator_sequence)\n if nominator.from_timestamp != denominator.from_timestamp:\n # Missing entries in either; skip in the other.\n # On missing data, we cannot provide any sensible output.\n while nominator.from_timestamp < denominator.from_timestamp:\n nominator = next(nominator_sequence)\n while denominator.from_timestamp < nominator.from_timestamp:\n denominator = next(denominator_sequence)\n assert nominator.from_timestamp == denominator.from_timestamp\n assert nominator.to_timestamp == denominator.to_timestamp\n if denominator.physical_quantity:\n val = nominator.physical_quantity / denominator.physical_quantity\n yield nominator._replace(physical_quantity=val)\n else:\n # No production but have consumption --- assume that consumption\n # should be taken to contribute to consumption in next period with\n # consumption... (This is a subtly different scenario with missing\n # data --- on seeing zero production, we assume that energy\n # consumption contributes to later production --- but on missing\n # data, the production is *unknown*, without strong reasons to\n # expect it to actually contribute to production registered\n # later...)\n while not denominator.physical_quantity:\n denominator = next(denominator_sequence)\n lst = [nominator]\n while nominator.from_timestamp < denominator.from_timestamp:\n nominator = next(nominator_sequence)\n if nominator.from_timestamp <= denominator.from_timestamp:\n lst.append(nominator)\n assert nominator.from_timestamp >= denominator.from_timestamp\n assert nominator.from_timestamp > denominator.from_timestamp or \\\n nominator in lst\n total_acc = sum(\n (acc.physical_quantity for acc in lst),\n nominator.physical_quantity * 0)\n val = total_acc / denominator.physical_quantity\n for x in lst:\n yield x._replace(physical_quantity=val)\n\n\nclass VariablyBoundAccumulationMixin(object):\n def calculate_development(self, from_timestamp, to_timestamp):\n \"\"\"\n Specialisation of ``calculate_development()`` for for variably bound\n accumulation --- where the \"default\" implementation of getting \"raw\"\n samples at ``to_timestamp`` and ``from_timestamp`` and subtracting\n fails.\n \"\"\"\n try:\n first, last = first_last(self.get_samples(\n from_timestamp, to_timestamp))\n return self.create_range_sample(\n from_timestamp, to_timestamp,\n last.physical_quantity - first.physical_quantity,\n uncachable=(\n first.uncachable or\n last.uncachable or\n from_timestamp != first.timestamp or\n to_timestamp != last.timestamp),\n extrapolated=(\n first.extrapolated or\n last.extrapolated or\n from_timestamp != first.timestamp or\n to_timestamp != last.timestamp))\n except ValueError:\n # @bug: Bug cammuflaging error handling.\n return self.create_range_sample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(0, self.unit),\n uncachable=True, extrapolated=True)\n\n\nclass CacheOptimizedCalculateDevelopmentMixin(object):\n \"\"\"\n Implement L{calculate_development()} via multiple calls to\n L{get_condensed_samples()} for clever choises of arguments in order to\n optimize cache utilization. For ranges where this does not work, we fall\n back to the super class implementation of L{calculate_development} (this\n can be customized in L{_calculate_development_fallback()}.\n \"\"\"\n @classmethod\n def _period_to_caching_periods(cls, from_timestamp, to_timestamp):\n \"\"\"\n Translate a time period into a combination of time periods aligned with\n cache resolutions and whatever is left over.\n \"\"\"\n # (sample_resolution, from_timestamp, to_timestamp) list\n cache_periods = []\n periods_left = [(from_timestamp, to_timestamp)]\n timezone = from_timestamp.tzinfo\n\n for delta in condense.RESOLUTIONS:\n # nothing, \"before\", \"after\", or both (or initial)\n assert len(periods_left) < 3\n new_periods_left = []\n for period_from, period_to in periods_left:\n aligned_from = condense.floor(period_from, delta, timezone)\n if aligned_from < period_from:\n aligned_from += delta\n aligned_to = condense.floor(period_to, delta, timezone)\n if aligned_from < aligned_to:\n if period_from < aligned_from:\n new_periods_left.append((period_from, aligned_from))\n if aligned_to < period_to:\n new_periods_left.append((aligned_to, period_to))\n cache_periods.append((delta, aligned_from, aligned_to))\n else:\n new_periods_left.append((period_from, period_to))\n periods_left = new_periods_left\n return (cache_periods, periods_left)\n\n def _calculate_development_fallback(self, from_timestamp, to_timestamp):\n return super(\n CacheOptimizedCalculateDevelopmentMixin,\n self).calculate_development(from_timestamp, to_timestamp)\n\n def calculate_development(self, from_timestamp, to_timestamp):\n \"\"\"\n Specialisation of ``calculate_development()``; using cached data for\n computation when possible.\n \"\"\"\n cache_periods, periods_left = self._period_to_caching_periods(\n from_timestamp, to_timestamp)\n\n samples = []\n\n for sample_resolution, period_from, period_to in cache_periods:\n samples.extend(self.get_condensed_samples(\n period_from, sample_resolution, period_to))\n\n for period_from, period_to in periods_left:\n val = self._calculate_development_fallback(period_from, period_to)\n if val is None:\n return None\n samples.append(val)\n\n uncachable = False\n extrapolated = False\n val = PhysicalQuantity(0, self.unit)\n for sample in samples:\n uncachable = uncachable or sample.uncachable\n extrapolated = extrapolated or sample.extrapolated\n val += sample.physical_quantity\n return self.create_range_sample(\n from_timestamp, to_timestamp, val, uncachable,\n extrapolated)\n\n\nclass DevelopmentRateComputation(VariablyBoundAccumulationMixin):\n \"\"\"\n A C{DevelopmentRateComputation} is a mixin class that helps implement\n L{DataSeries.get_samples()} using a formula like M{F(t) =\n S{integral}f(a'(t), r(t)) dt}, where M{F} is the resulting continuous\n accumulation function, M{a'} is the first derivative of a continuous\n accumulation M{a}, M{r} is a piece wise constant rate, M{t} is time and\n M{f} is customized by the child class in the method L{_compute_sample()}.\n \"\"\"\n\n def _compute_sample(self, development, rate):\n \"\"\"\n Abstract method for implementing the M{f} in M{F(t) =\n S{integral}f(a'(t), r(t)) dt}.\n\n @param development: A PhysicalQuantity equal to M{a(t+S{Delta}) - a(t)}\n for some time M{t}.\n\n @param rate: A PhysicalQuantity equal to M{r(t')} for all\n M{t'S{isin}[t; t + S{Delta}]}, for the same time M{t}.\n\n @return: A PhysicalQuantity equal to M{S{integral}f(a'(t'), r(t')) dt'}\n where M{t'} runs from M{t} to M{t+S{Delta}}.\n \"\"\"\n raise NotImplementedError()\n\n def _get_accumulation(self):\n \"\"\"\n Abstract method returning the L{DataSeries} defining M{a} in M{F(t) =\n S{integral}f(a'(t), r(t)) dt}.\n \"\"\"\n raise NotImplementedError()\n\n def _get_rate(self):\n \"\"\"\n Abstract method returning the L{DataSeries} defining M{r} in M{F(t) =\n S{integral}f(a'(t), r(t)) dt}.\n \"\"\"\n raise NotImplementedError()\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n C{DevelopmentRateComputation} implementation of\n L{DataSeries.get_raw_data_samples()}.\n\n @precondition: The abstract methods L{_compute_sample()},\n L{_get_accumulation()}, L{_get_rate()} must all be implemented.\n\n @bug: First sample appears to be skipped when entering domain.\n \"\"\"\n assert from_timestamp <= to_timestamp\n assert self._get_accumulation().is_accumulation()\n assert self.is_accumulation()\n\n raw_accumulation = pairwise(\n self._get_accumulation_samples(from_timestamp, to_timestamp))\n raw_rate = self._get_rate_samples(from_timestamp, to_timestamp)\n\n # Algorithm:\n #\n # The loop variable r spans a window of the rate.\n #\n # The loop variable pair (c0, c1) defines a window of the accumulation,\n # inside which we may interpolate the accumulation, conviniently bound\n # to the name c.\n #\n # The algorithm alternates between moving one of these two windows\n # forwards, such that there is an overlap at all times. The algorithm\n # does not assume one window needs to move more often than the other.\n #\n # c and old_c are chosen s.t. they are both included in the rate window\n # as well as the accumulation window.\n INITIAL_ACCUMULATED_RESULT = PhysicalQuantity(\n 0, self.unit)\n\n accumulated_result = INITIAL_ACCUMULATED_RESULT\n\n # To make it possible to yield the initial sample, we track if any\n # samples has been yielded.\n sample_yielded = False\n\n try:\n c0, c1 = next(raw_accumulation)\n\n for r in raw_rate:\n while c1.timestamp < r.from_timestamp:\n c0, c1 = next(raw_accumulation)\n\n assert r.from_timestamp <= c1.timestamp\n accumulation_start = self._get_accumulation().\\\n _interpolate_extrapolate_sample(\n max(r.from_timestamp, c0.timestamp),\n data_before=c0, data_after=c1)\n assert accumulation_start.timestamp == max(\n r.from_timestamp, c0.timestamp)\n\n while c1.timestamp < r.to_timestamp:\n c0, c1 = next(raw_accumulation)\n\n assert c0.timestamp <= r.to_timestamp <= c1.timestamp\n accumulation_end = self._get_accumulation().\\\n _interpolate_extrapolate_sample(\n r.to_timestamp, data_before=c0, data_after=c1)\n assert accumulation_end.timestamp == r.to_timestamp\n\n accumulated_result += self._compute_sample(\n accumulation_end.physical_quantity -\n accumulation_start.physical_quantity,\n r.physical_quantity)\n\n sample = self.create_point_sample(\n r.to_timestamp,\n accumulated_result,\n uncachable=(\n r.uncachable or\n accumulation_start.uncachable or\n accumulation_end.uncachable),\n extrapolated=(\n r.extrapolated or\n accumulation_start.extrapolated or\n accumulation_end.extrapolated))\n\n if not sample_yielded and sample.timestamp != from_timestamp:\n # yield a sample at from_timestamp, possibly extrapolated.\n yield self.create_point_sample(\n from_timestamp,\n INITIAL_ACCUMULATED_RESULT,\n uncachable=sample.uncachable or (\n max(r.from_timestamp,\n accumulation_start.timestamp) !=\n from_timestamp),\n extrapolated=sample.extrapolated or (\n max(r.from_timestamp,\n accumulation_start.timestamp) !=\n from_timestamp))\n\n if max(r.from_timestamp, accumulation_start.timestamp) != \\\n from_timestamp:\n # if the from_timestamp sample was extrapolated, the\n # first unextrapolated sample also needs to be\n # yielded.\n yield self.create_point_sample(\n max(r.from_timestamp,\n accumulation_start.timestamp),\n INITIAL_ACCUMULATED_RESULT,\n uncachable=(\n sample.uncachable or\n accumulation_start.uncachable),\n extrapolated=(\n sample.extrapolated or\n accumulation_start.extrapolated))\n\n sample_yielded = True\n yield sample\n\n # Ensure post-condition\n if sample_yielded and sample.timestamp != to_timestamp:\n yield self.create_point_sample(\n to_timestamp,\n sample.physical_quantity,\n uncachable=True, extrapolated=True)\n\n finally:\n if not sample_yielded:\n yield self.create_point_sample(\n from_timestamp,\n INITIAL_ACCUMULATED_RESULT,\n uncachable=True, extrapolated=True)\n yield self.create_point_sample(\n to_timestamp,\n self._compute_sample(\n PhysicalQuantity(0, self._get_accumulation().unit),\n PhysicalQuantity(\n 0, self._get_rate().unit)),\n uncachable=True, extrapolated=True)\n\n def get_underlying_function(self):\n \"\"\"\n C{DevelopmentRateComputation} override of\n L{DataSeries.get_underlying_function()}.\n \"\"\"\n return self.CONTINUOUS_ACCUMULATION\n\n def _get_accumulation_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Get accumulation samples for the given M{[C{from_timestamp},\n {to_timestamp}]} interval.\n \"\"\"\n return self._get_accumulation().subclass_instance.get_samples(\n from_timestamp, to_timestamp)\n\n def _get_rate_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Get rate samples for the given M{[C{from_timestamp}, {to_timestamp}]}\n interval.\n \"\"\"\n return self._get_rate().subclass_instance.get_samples(\n from_timestamp, to_timestamp)\n\n # subclasses must define this constant on their own.\n RATE_RESOLUTION = None\n\n def get_recursive_condense_resolution(self, resolution):\n \"\"\"\n Must recurse through as many resolutions as required to reach\n C{RATE_RESOLUTION}. resolutions below C{RATE_RESOLUTION} will not be\n reached through recursion, unless requested directly.\n \"\"\"\n return condense.next_resolution(resolution)\n\n def _condense_data_samples_recursive(\n self, from_timestamp, resolution, to_timestamp):\n assert self.RATE_RESOLUTION is not None\n if resolution == self.RATE_RESOLUTION:\n ZERO = PhysicalQuantity(0, self.unit)\n developments = self._get_accumulation().get_condensed_samples(\n from_timestamp, resolution, to_timestamp)\n rates = iter(\n self._get_rate().get_samples(\n from_timestamp, to_timestamp))\n rate = next(rates, None)\n for development in developments:\n while rate is not None and \\\n rate.to_timestamp <= development.from_timestamp:\n rate = next(rates, None)\n if rate is not None and \\\n rate.from_timestamp <= development.from_timestamp and \\\n rate.to_timestamp >= development.to_timestamp:\n\n yield self.create_range_sample(\n development.from_timestamp,\n development.to_timestamp,\n self._compute_sample(\n development.physical_quantity,\n rate.physical_quantity),\n uncachable=not (\n rate.cachable and development.cachable),\n extrapolated=(\n rate.extrapolated or development.extrapolated))\n\n # rates may be longer than development, and therefore\n # should only be next()'ed when the last valid subinterval\n # has been processed with the corresponding development.\n if rate.to_timestamp == development.to_timestamp:\n rate = next(rates, None)\n assert rate is None or rate.from_timestamp + resolution <= \\\n rate.to_timestamp\n else:\n yield self.create_range_sample(\n development.from_timestamp,\n development.to_timestamp,\n ZERO,\n uncachable=True,\n extrapolated=True)\n else:\n condensations = super(DevelopmentRateComputation, self).\\\n _condense_data_samples_recursive(from_timestamp,\n resolution, to_timestamp)\n for sample in condensations:\n yield sample\n\n\nclass ENPIMixin(object):\n \"\"\"\n An ENPI (Energy Performance Indicator) is the energy consumption (or other\n kind of consumption) per unit of energy driver.\n\n A typical example is the energy consumption of some production facility\n with the count of products produced as the energy driver.\n\n What makes an ENPI a performance indicator is that ENPI values across\n different intervals can be compared. For example 3.2 kWh/pcs last month is\n comparable with 3.1 kWh/pcs yesterday.\n\n For the ENPI to be statistically significant, it should be calculated\n across intervals with a statistically significant energy driver\n developments. It is up to the user to assess statistical significance.\n \"\"\"\n\n def _condense_energy_drivers(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Condense energy drivers between C{from_timestamp} and C{to_timestamp}\n with C{sample_resolution}.\n\n This method is abstract and required by\n L{ENPIMixin._condense_data_samples_recursive()}\n\n This method implements the same interface as\n L{DataSeries.get_condensed_samples()}.\n\n @return: Returns an iterable of ranged samples.\n \"\"\"\n raise NotImplementedError(\n '%r did not implement this method' % self.__class__)\n\n def _condense_energy_consumption(self, from_timestamp, sample_resolution,\n to_timestamp):\n \"\"\"\n Condense energy consumption between C{from_timestamp} and\n C{to_timestamp} with C{sample_resolution}.\n\n This method is abstract and required by\n L{ENPIMixin._condense_data_samples_recursive()}\n\n This method implements the same interface as\n L{DataSeries.get_condensed_samples()}.\n\n @return: Returns an iterable of ranged samples.\n \"\"\"\n raise NotImplementedError(\n '%r did not implement this method' % self.__class__)\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n C{ENPIMixin} override of\n L{DataSeries._condense_data_samples_recursive}.\n\n Yields ranged samples of ENPI across the interval represented by the\n range, or, if necessary across a containing interval.\n\n By definition all energy consumption is a contribution to the ENPI\n yielded by the next energy driver development. For periods without\n energy driver development, the energy consumption is therefore saved up\n and added to the energy consumption of the following period. This will\n by definition only happen when condensing for periods that are\n statistically insignificant.\n\n @precondition: C{self._condense_energy_drivers()} and\n C{self._condense_energy_consumption()} must both be implemented.\n \"\"\"\n return quotient_sequence(\n self._condense_energy_consumption(\n from_timestamp, sample_resolution, to_timestamp),\n self._condense_energy_drivers(\n from_timestamp, sample_resolution, to_timestamp))\n\n def _calculate_energy_development(self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate energy development between C{from_timestamp} and\n C{to_timestamp}.\n\n This method is abstract and required by L{calculate_enpi()}.\n\n @return: Returns a ranged sample.\n \"\"\"\n raise NotImplementedError(\n '%r did not implement this method' % self.__class__)\n\n def _calculate_energy_driver_development(\n self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate energy driver development between C{from_timestamp} and\n C{to_timestamp}.\n\n This method is abstract and required by L{calculate_enpi()}.\n\n @return: Returns a ranged sample.\n \"\"\"\n raise NotImplementedError(\n '%r did not implement this method' % self.__class__)\n\n def calculate_enpi(self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate the ENPI between C{from_timestamp} and C{to_timestamp}.\n\n @return: Returns a ranged sample holding the ENPI between\n C{from_timestamp} and C{to_timestamp}, or None if the ENPI for the\n given range is not well-defined.\n\n @precondition: C{self._calculate_energy_development()} and\n C{self._calculate_energy_driver_development()} are both implemented.\n \"\"\"\n energy_sample = self._calculate_energy_development(\n from_timestamp, to_timestamp)\n\n energy_driver_sample = self._calculate_energy_driver_development(\n from_timestamp, to_timestamp)\n\n if energy_sample is not None and energy_driver_sample:\n return self.create_range_sample(\n from_timestamp,\n to_timestamp,\n physical_quantity=(\n energy_sample.physical_quantity /\n energy_driver_sample.physical_quantity),\n uncachable=True,\n extrapolated=True)\n else:\n return None\n" }, { "alpha_fraction": 0.5189250707626343, "alphanum_fraction": 0.5205021500587463, "avg_line_length": 33.46086883544922, "blob_id": "91d0a2349a562bac726602b02869b3585a1b850f", "content_id": "0a14f72539e80ade1537dfb1df203ae4b75f6699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15852, "license_type": "no_license", "max_line_length": 79, "num_lines": 460, "path": "/gridplatform/bootstrap/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.template import Context\nfrom django.template import Template\nfrom django.template.base import TemplateSyntaxError\nfrom django.test import RequestFactory\nfrom django.test import SimpleTestCase\nfrom django.test.utils import override_settings\n\n\n@override_settings(BOOTSTRAP_THEME='base')\nclass IconTemplatetagTest(SimpleTestCase):\n def test_icon_normal(self):\n template = Template('{% load bootstrap_tags %}{% icon \"compass\" %}')\n self.assertInHTML(\n '<i class=\"fa fa-compass\"></i>',\n template.render(Context({})))\n\n def test_icon_2x(self):\n template = Template(\n '{% load bootstrap_tags %}{% icon \"eur\" size=\"2x\" %}')\n self.assertInHTML(\n '<i class=\"fa fa-eur fa-2x\"></i>',\n template.render(Context({})))\n\n def test_icon_doesnotexist(self):\n template = Template(\n '{% load bootstrap_tags %}{% icon \"doesnotexist\" %}')\n with self.assertRaises(TemplateSyntaxError):\n template.render(Context({}))\n\n def test_icon_invalidsize(self):\n template = Template(\n '{% load bootstrap_tags %}{% icon \"compass\" size=\"invalid\" %}')\n with self.assertRaises(TemplateSyntaxError):\n template.render(Context({}))\n\n\n@override_settings(BOOTSTRAP_THEME='base')\nclass PanelTemplateTagTest(SimpleTestCase):\n def test_simple(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% panel \"MyPanelTitle\" %}'\n '<p class=\"some-class\">text</p>'\n '{% endpanel %}')\n context = Context({})\n result = template.render(context)\n self.assertIn(\"MyPanelTitle\", result)\n self.assertInHTML('<p class=\"some-class\">text</p>', result)\n\n def test_var_title(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% with title=\"Hello\" %}'\n '{% panel title %}'\n '<p class=\"some-class\">text</p>'\n '{% endpanel %}'\n '{% endwith %}')\n context = Context({})\n result = template.render(context)\n self.assertIn(\"Hello\", result)\n self.assertInHTML('<p class=\"some-class\">text</p>', result)\n\n def test_buttons(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% panel \"MyPanelTitle\" %}'\n '<a href=\"http://example.com/\"><i class=\"icon-stuff\"></i></a>'\n '{% endpanelbuttons %}'\n '<p class=\"some-class\">text</p>'\n '{% endpanel %}')\n context = Context({})\n result = template.render(context)\n self.assertIn(\"MyPanelTitle\", result)\n self.assertInHTML(\n '<a href=\"http://example.com/\"><i class=\"icon-stuff\"></i></a>',\n result)\n self.assertInHTML('<p class=\"some-class\">text</p>', result)\n\n def test_vars_inside(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% with foo=\"hello\" %}'\n '{% panel \"MyPanelTitle\" %}'\n '{% with bar=\"world\" %}'\n '{{ foo }} {{ bar }}'\n '{% endwith %}'\n '{% endpanelbuttons %}'\n '{% with bar=\"x\" %}'\n '{{ foo }} {{ bar }}'\n '{% endwith %}'\n '{% endpanel %}'\n '{% endwith %}')\n context = Context({})\n result = template.render(context)\n self.assertIn(\"MyPanelTitle\", result)\n self.assertIn(\"hello world\", result)\n self.assertIn(\"hello x\", result)\n\n\nclass TestForm(forms.Form):\n name = forms.CharField(max_length=50)\n is_admin = forms.BooleanField(\n label='Is admin', help_text='User is administrator')\n\n def clean(self):\n # silly check to introduce non-field errors\n cleaned_data = super(TestForm, self).clean()\n name = cleaned_data.get('name')\n is_admin = cleaned_data.get('is_admin')\n if name and name.startswith('_') and not is_admin:\n raise forms.ValidationError(\n b'Invalid name for non-admin user: {}'.format(name))\n return cleaned_data\n\n\n@override_settings(\n BOOTSTRAP_THEME='base',\n BOOTSTRAP_FORM_LAYOUT='horizontal',\n BOOTSTRAP_FORM_LABEL_COLUMNS=2,\n BOOTSTRAP_FORM_INPUT_COLUMNS=10,\n)\nclass FormTagsTest(SimpleTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.request = self.factory.get('/')\n\n def test_no_form(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% endbootstrap_form %}'\n )\n context = Context({'request': self.request})\n result = template.render(context)\n self.assertIn('<form', result)\n self.assertIn('<button type=\"submit\"', result)\n self.assertIn('</form>', result)\n\n def test_form(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% form form %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertIn('type=\"text\"', result)\n self.assertIn('name=\"name\"', result)\n self.assertIn('type=\"checkbox\"', result)\n self.assertIn('name=\"is_admin\"', result)\n self.assertIn('Is admin', result)\n self.assertIn('User is administrator', result)\n\n def test_form_wrong_nesting(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% form form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_field(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field form.name %}'\n '{% field form.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertIn('type=\"text\"', result)\n self.assertIn('name=\"name\"', result)\n self.assertIn('type=\"checkbox\"', result)\n self.assertIn('name=\"is_admin\"', result)\n self.assertIn('Is admin', result)\n self.assertIn('User is administrator', result)\n\n def test_field_wrong_nesting(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% field form.name %}'\n '{% field form.is_admin %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_field_missing(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field form.name %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_field_repeated(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field form.name %}'\n '{% field form.is_admin %}'\n '{% field form.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_form_field_repeated(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field form.name %}'\n '{% form form %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_buttons(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% form_buttons %}'\n '{% endbootstrap_form %}'\n )\n context = Context({\n 'request': self.request,\n })\n result = template.render(context)\n self.assertIn('<button type=\"submit\"', result)\n\n def test_buttons_repeated(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% form_buttons %}'\n '{% form_buttons %}'\n '{% endbootstrap_form %}'\n )\n context = Context({\n 'request': self.request,\n })\n with self.assertRaises(TemplateSyntaxError):\n template.render(context)\n\n def test_input(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field_input form.name %}'\n '{% field_input form.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertIn('type=\"text\"', result)\n self.assertIn('name=\"name\"', result)\n self.assertIn('type=\"checkbox\"', result)\n self.assertIn('name=\"is_admin\"', result)\n self.assertNotIn('Is admin', result)\n self.assertIn('User is administrator', result)\n pass\n\n def test_label(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field_label form.name %}'\n '{% field_label form.is_admin %}'\n '{% field_input form.name %}'\n '{% field_input form.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertIn('type=\"text\"', result)\n self.assertIn('name=\"name\"', result)\n self.assertIn('type=\"checkbox\"', result)\n self.assertIn('name=\"is_admin\"', result)\n self.assertIn('Is admin', result)\n self.assertIn('User is administrator', result)\n\n def test_hidden(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% hidden_field form.name %}'\n '{% hidden_field form.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertNotIn('type=\"text\"', result)\n self.assertIn('name=\"name\"', result)\n self.assertNotIn('type=\"checkbox\"', result)\n self.assertIn('name=\"is_admin\"', result)\n self.assertNotIn('Is admin', result)\n self.assertNotIn('User is administrator', result)\n\n def test_outer_arguments(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form label_columns=7 '\n 'input_columns=3 form_action=\"/hello/\" form_method=\"get\" %}'\n '{% form form %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertIn('7', result)\n self.assertIn('3', result)\n self.assertIn('action=\"/hello/\"', result)\n self.assertIn('method=\"get\"', result)\n\n def test_form_arguments(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form label_columns=7 input_columns=3 %}'\n '{% form form label_columns=2 input_columns=4 %}'\n '{% form_buttons label_columns=1 input_columns=6 %}'\n '{% endbootstrap_form %}'\n )\n form = TestForm()\n context = Context({\n 'request': self.request,\n 'form': form,\n })\n result = template.render(context)\n self.assertNotIn('7', result)\n self.assertNotIn('3', result)\n self.assertIn('2', result)\n self.assertIn('4', result)\n self.assertIn('1', result)\n self.assertIn('6', result)\n\n def test_autoinsert_several_non_field_errors(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% field form_a.name %}'\n '{% field form_a.is_admin %}'\n '{% field form_b.name %}'\n '{% field form_b.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form_a = TestForm({'name': '_invalid_a', 'is_admin': False})\n form_b = TestForm({'name': '_invalid_b', 'is_admin': False})\n context = Context({\n 'request': self.request,\n 'form_a': form_a,\n 'form_b': form_b,\n })\n result = template.render(context)\n self.assertIn('Invalid name for non-admin user: _invalid_a', result)\n self.assertIn('Invalid name for non-admin user: _invalid_b', result)\n\n def test_autoinsert_single_non_field_errors(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% non_field_errors form_a %}'\n '{% field form_a.name %}'\n '{% field form_a.is_admin %}'\n '{% field form_b.name %}'\n '{% field form_b.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form_a = TestForm({'name': '_invalid_a', 'is_admin': False})\n form_b = TestForm({'name': '_invalid_b', 'is_admin': False})\n context = Context({\n 'request': self.request,\n 'form_a': form_a,\n 'form_b': form_b,\n })\n result = template.render(context)\n self.assertIn('Invalid name for non-admin user: _invalid_a', result)\n self.assertIn('Invalid name for non-admin user: _invalid_b', result)\n self.assertEqual(\n result.find('Invalid name for non-admin user: _invalid_a'),\n result.rfind('Invalid name for non-admin user: _invalid_a'))\n\n def test_non_field_errors_match_failing(self):\n template = Template(\n '{% load bootstrap_tags %}'\n '{% bootstrap_form %}'\n '{% non_field_errors form_a %}'\n '{% field form_a.name %}'\n '{% field form_a.is_admin %}'\n '{% field form_b.name %}'\n '{% field form_b.is_admin %}'\n '{% endbootstrap_form %}'\n )\n form_a = TestForm({'name': 'valid_a', 'is_admin': False})\n form_b = TestForm({'name': '_invalid_b', 'is_admin': False})\n context = Context({\n 'request': self.request,\n 'form_a': form_a,\n 'form_b': form_b,\n })\n result = template.render(context)\n self.assertNotIn('Invalid name for non-admin user: _invalid_a', result)\n self.assertNotIn('Invalid name for non-admin user: valid_a', result)\n self.assertIn('Invalid name for non-admin user: _invalid_b', result)\n" }, { "alpha_fraction": 0.6574074029922485, "alphanum_fraction": 0.6585648059844971, "avg_line_length": 38.272727966308594, "blob_id": "f1e701a2473d48b2914325d64df15b987566c80c", "content_id": "c1166e774a670ac9dbf287e0e3dcd69575b9fbf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 864, "license_type": "no_license", "max_line_length": 76, "num_lines": 22, "path": "/legacy/manage_users/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nfrom gridplatform.users.decorators import auth_or_redirect\n\n\nurlpatterns = patterns(\n 'legacy.manage_users.views',\n url(r'^$', auth_or_redirect(TemplateView.as_view(\n template_name='manage_users/list.html')),\n name='manage_users-list'),\n url(r'^json/users/$', 'list_json', name='manage_users-list-json'),\n url(r'^form/$', 'user_form', name='manage_users-form'),\n url(r'^form/(?P<pk>\\d+)$', 'user_form', name='manage_users-form'),\n url(r'^update/$', 'user_update', name='manage_users-update'),\n url(r'^update/(?P<pk>\\d+)$', 'user_update', name='manage_users-update'),\n url(r'^delete/$', 'user_delete', name='manage_users-delete'),\n)\n" }, { "alpha_fraction": 0.6718435287475586, "alphanum_fraction": 0.6721311211585999, "avg_line_length": 35.98936080932617, "blob_id": "bdc2334f605506c7ddcc6a0a27e692aea9158cda", "content_id": "6b3cbbfb77c997f74879f8b738029c6a48c63482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3477, "license_type": "no_license", "max_line_length": 75, "num_lines": 94, "path": "/gridplatform/datasequences/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils import units\n\nfrom . import models\n\n\nclass EnergyPerVolumeDataSequence(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set',\n view_name='api:datasequences:energypervolumeperiod-detail',\n many=True, read_only=True)\n hourly = serializers.SerializerMethodField('get_hourly')\n energy_per_volume_periods = serializers.HyperlinkedIdentityField(\n view_name='api:datasequences:energypervolumeperiod-list')\n unit = serializers.SerializerMethodField('get_unit')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.EnergyPerVolumeDataSequence\n fields = ('url', 'id', 'name', 'unit', 'display_unit', 'customer',\n 'periods', 'hourly', 'energy_per_volume_periods')\n\n def get_unit(self, obj):\n return obj.unit\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:datasequences:energypervolumedatasequence-hourly',\n kwargs={'pk': obj.id})\n\n\nclass EnergyPerVolumePeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.EnergyPerVolumePeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource')\n read_only_fields = ('datasequence',)\n\n\nclass NonaccumulationDataSequence(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set',\n view_name='api:datasequences:nonaccumulationperiod-detail',\n many=True, read_only=True)\n nonaccumulation_periods = serializers.HyperlinkedIdentityField(\n view_name='api:datasequences:nonaccumulationperiod-list')\n raw_data = serializers.SerializerMethodField('get_raw_data')\n offlinetolerance = serializers.HyperlinkedIdentityField(\n view_name='api:datasequences:nonaccumulationofflinetolerance-list')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.NonaccumulationDataSequence\n fields = ('url', 'id', 'name', 'unit', 'display_unit', 'customer',\n 'periods', 'nonaccumulation_periods', 'offlinetolerance',\n 'raw_data')\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n def get_raw_data(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:datasequences:nonaccumulationdatasequence-raw-data',\n kwargs={'pk': obj.id})\n\n\nclass NonaccumulationPeriod(serializers.DefaultSerializer):\n class Meta:\n model = models.NonaccumulationPeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'datasource')\n read_only_fields = ('datasequence',)\n\n\nclass NonaccumulationOfflineTolerance(serializers.DefaultSerializer):\n class Meta:\n model = models.NonaccumulationOfflineTolerance\n fields = ('url', 'id', 'hours', 'datasequence')\n read_only_fields = ('datasequence',)\n" }, { "alpha_fraction": 0.5685603618621826, "alphanum_fraction": 0.5687885284423828, "avg_line_length": 39.962615966796875, "blob_id": "74e38c58859246b7968ca5253fd944023c547864", "content_id": "45a455b8a356e5129eae874e0d9356501b109280", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4383, "license_type": "no_license", "max_line_length": 75, "num_lines": 107, "path": "/legacy/manage_measurementpoints/forms/measurementpointbase.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.display_widgets.models import DashboardWidget\nfrom gridplatform import trackuser\nfrom legacy.devices.models import Meter\n\nfrom .collection import CollectionForm\n\n\n# THIS FILE IS DEPRECATED!!!\n\nclass MeasurementPointBaseForm(CollectionForm):\n \"\"\"\n Abstract class\n \"\"\"\n\n class Meta (CollectionForm.Meta):\n fields = ('name', 'parent', 'billing_meter_number',\n 'billing_installation_number', 'gauge_lower_threshold',\n 'gauge_upper_threshold', 'gauge_max', 'gauge_min',\n 'gauge_colours', 'relay', 'gauge_preferred_unit',\n 'hidden_on_details_page')\n\n relay = forms.ModelChoiceField(\n queryset=None, required=False)\n\n def __init__(self, *args, **kwargs):\n super(MeasurementPointBaseForm, self).__init__(*args, **kwargs)\n\n self.fields[\"relay\"].queryset = Meter.objects.filter(\n relay_enabled=True, customer=trackuser.get_customer())\n\n # Localize gauge input fields\n for item in [self.fields['gauge_lower_threshold'],\n self.fields['gauge_upper_threshold'],\n self.fields['gauge_min'],\n self.fields['gauge_max']]:\n item.localize = True\n item.widget.is_localized = True\n\n def clean(self):\n cleaned_data = super(MeasurementPointBaseForm, self).clean()\n\n if self.errors:\n return cleaned_data\n\n # Checking if gauge_min is present;\n # when creating MP, gauge setup is unavailable.\n if cleaned_data.get('gauge_min') is not None:\n gauge_min = cleaned_data['gauge_min']\n gauge_max = cleaned_data['gauge_max']\n gauge_lower_threshold = cleaned_data['gauge_lower_threshold']\n gauge_upper_threshold = cleaned_data['gauge_upper_threshold']\n gauge_colours = cleaned_data['gauge_colours']\n\n # If Gauge widget is present on the Dashboard, verify that\n # that values are not corrupted by the user.\n widget = DashboardWidget.objects.filter(\n collection=self.instance.id,\n widget_type=DashboardWidget.GAUGE)\n if widget and (gauge_lower_threshold is None or\n gauge_upper_threshold is None or\n gauge_min is None or\n gauge_max is None or\n gauge_colours is None):\n raise forms.ValidationError(\n _('Gauge widget is present on the dashboard; \\\n corrupting these values are not allowed'))\n else:\n if gauge_max is not None and \\\n gauge_min is not None and \\\n gauge_max <= gauge_min:\n raise forms.ValidationError(\n _('Maximum value must be above minumum value'))\n if gauge_lower_threshold is not None and \\\n gauge_lower_threshold is not None and \\\n gauge_lower_threshold < gauge_min:\n raise forms.ValidationError(\n _('Lower threshold must be above minumum value'))\n if gauge_upper_threshold is not None and \\\n gauge_max is not None \\\n and gauge_upper_threshold > gauge_max:\n raise forms.ValidationError(\n _('Upper threshold must be below maximum value'))\n if gauge_upper_threshold is not None and \\\n gauge_lower_threshold is not None \\\n and gauge_upper_threshold <= gauge_lower_threshold:\n raise forms.ValidationError(\n _('Upper threshold must be above lower threshold'))\n\n return cleaned_data\n\n def save(self, commit=True):\n super(MeasurementPointBaseForm, self).save(commit=False)\n\n self.instance.relay = self.cleaned_data[\"relay\"]\n self.instance.hidden_on_details_page = \\\n self.cleaned_data['hidden_on_details_page']\n\n if commit:\n self.instance.save()\n return self.instance\n" }, { "alpha_fraction": 0.6224979162216187, "alphanum_fraction": 0.6226021647453308, "avg_line_length": 37.21514129638672, "blob_id": "e9b860592697431d31f97597f1b72a7a8a5eaaf6", "content_id": "bd55c2ef92ab3dc00cfa14e4b1da45fe8ac5a065", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9592, "license_type": "no_license", "max_line_length": 79, "num_lines": 251, "path": "/gridplatform/datasequences/models/nonaccumulation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom model_utils import FieldTracker\n\nfrom gridplatform.customer_datasources.models import DataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.utils import deprecated\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import NONACCUMULATION_BASE_UNITS\nfrom gridplatform.utils.units import NONACCUMULATION_BASE_UNIT_CHOICES\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.samples import Sample\n\nfrom .base import DataSequenceBase\nfrom .base import PeriodBase\n\n\nclass NonaccumulationDataSequence(DataSequenceBase):\n \"\"\"\n Data sequence class for sequences of continuous :class:`.PointSample`.\n\n :ivar unit: The unit of this :class:`.NonaccumulationDataSequence`.\n\n :see: :ref:`sequences-of-continuous-point-samples`\n \"\"\"\n\n # Do not update:\n unit = BuckinghamField(choices=NONACCUMULATION_BASE_UNIT_CHOICES)\n\n tracker = FieldTracker(fields=['unit'])\n\n class Meta:\n verbose_name = _('nonaccumulation data sequence')\n verbose_name_plural = _('nonaccumulation data sequences')\n app_label = 'datasequences'\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.unit`` is updated.\n \"\"\"\n super(NonaccumulationDataSequence, self).clean()\n previous_unit = self.tracker.previous('unit')\n if previous_unit is not None:\n if not PhysicalQuantity.compatible_units(previous_unit, self.unit):\n raise ValidationError(\n {\n 'unit': [\n ugettext('Field cannot be updated.'),\n ]})\n\n def raw_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: A sequence of continuous :class:`.PointSample` in the given\n timespan.\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n \"\"\"\n for period in self.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'):\n period_from, period_to = period.overlapping(\n from_timestamp, to_timestamp)\n for sample in period._raw_sequence(period_from, period_to):\n yield sample\n\n @deprecated\n def _get_samples(self, from_timestamp, to_timestamp):\n input_periods = self.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp')\n\n for input_period in input_periods:\n for sample in input_period.get_samples(\n max(from_timestamp, input_period.from_timestamp),\n min(to_timestamp, input_period.to_timestamp)):\n if sample.timestamp != input_period.to_timestamp or \\\n input_period.to_timestamp == to_timestamp:\n yield sample\n\n\nclass NonaccumulationPeriod(PeriodBase):\n \"\"\"\n A :class:`.PeriodBase` specialization defining the continuous\n :class:`PointSample` of a :class:`.NonaccumulationDataSequence` within its\n period in terms of a :class:`.DataSource`.\n \"\"\"\n datasequence = models.ForeignKey(\n NonaccumulationDataSequence,\n verbose_name=_('data sequence'),\n related_name='period_set')\n datasource = models.ForeignKey(\n DataSource,\n verbose_name=_('data source'),\n limit_choices_to={'unit__in': NONACCUMULATION_BASE_UNITS},\n on_delete=models.PROTECT)\n\n class Meta:\n verbose_name = _('nonaccumulation period')\n verbose_name_plural = _('nonaccumulation periods')\n app_label = 'datasequences'\n\n # HACK\n @property\n def subclass_instance(self):\n return self\n\n def _raw_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Delegate method for :meth:`.NonaccumulationDataSequence.raw_sequence`\n within this :class:`.NonaccumulationPeriod`.\n \"\"\"\n for timestamp, value in self.datasource.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lte=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', 'value'):\n yield Sample(\n timestamp, timestamp,\n PhysicalQuantity(value, self.datasource.unit),\n False, False)\n\n @deprecated\n def _get_samples_pure_implementation(self, from_timestamp, to_timestamp):\n assert hasattr(self, 'datasource')\n assert from_timestamp <= to_timestamp\n\n raw_data_iterator = iter(\n self.datasource.rawdata_set.filter(\n timestamp__gte=max(from_timestamp, self.from_timestamp),\n timestamp__lte=min(to_timestamp, self.to_timestamp)))\n\n try:\n first_raw_data = next(raw_data_iterator)\n except StopIteration:\n leading_raw_data = self._get_leading_raw_data(from_timestamp)\n following_raw_data = self._get_following_raw_data(to_timestamp)\n if leading_raw_data is not None and following_raw_data is not None:\n if from_timestamp == to_timestamp:\n # single sample interpolated\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, following_raw_data)\n else:\n # two samples interpolated\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, following_raw_data)\n yield self._interpolate_sample(\n to_timestamp, leading_raw_data, following_raw_data)\n return\n\n # yield sample before first raw data if missing\n if first_raw_data.timestamp != from_timestamp:\n leading_raw_data = self._get_leading_raw_data(from_timestamp)\n if leading_raw_data:\n yield self._interpolate_sample(\n from_timestamp, leading_raw_data, first_raw_data)\n\n # yield the sample of the first raw data\n yield self.create_point_sample(\n first_raw_data.timestamp,\n PhysicalQuantity(first_raw_data.value, self.unit))\n final_raw_data = first_raw_data\n\n # yield samples for remaining raw data\n for raw_data in raw_data_iterator:\n yield self.create_point_sample(\n raw_data.timestamp,\n PhysicalQuantity(raw_data.value, self.unit))\n final_raw_data = raw_data\n\n # yield final sample after final raw data if missing\n if final_raw_data.timestamp != to_timestamp:\n following_raw_data = self._get_following_raw_data(to_timestamp)\n if following_raw_data:\n yield self._interpolate_sample(\n to_timestamp, final_raw_data, following_raw_data)\n\n @deprecated\n def _get_samples(self, from_timestamp, to_timestamp):\n return self._get_samples_pure_implementation(\n from_timestamp, to_timestamp)\n\n # HACK: copy from legacy.py\n @deprecated\n def get_samples(self, from_timestamp, to_timestamp):\n assert from_timestamp <= to_timestamp\n assert from_timestamp >= self.from_timestamp\n assert to_timestamp <= self.to_timestamp\n return self._get_samples(from_timestamp, to_timestamp)\n\n # HACK: copy from legacy.py\n @deprecated\n def create_point_sample(self, timestamp, physical_quantity,\n cachable=True, extrapolated=False):\n return Sample(\n timestamp,\n timestamp,\n physical_quantity,\n cachable,\n extrapolated)\n\n # HACK: copy from legacy.py\n def _get_unit(self):\n return self.datasource.unit\n\n # HACK: copy from legacy.py\n @deprecated\n def _get_leading_raw_data(self, timestamp):\n assert hasattr(self, 'datasource')\n # last before or None\n return self.datasource.rawdata_set.filter(\n timestamp__lt=timestamp).order_by('timestamp').last()\n\n # HACK: copy from legacy.py\n @cached_property\n @deprecated\n def _leading_raw_data(self):\n assert hasattr(self, 'datasource')\n return self._get_leading_raw_data(self.from_timestamp)\n\n # HACK: copy from legacy.py\n @deprecated\n def _get_following_raw_data(self, timestamp):\n assert hasattr(self, 'datasource')\n # first after or None\n return self.datasource.rawdata_set.filter(\n timestamp__gt=timestamp).order_by('timestamp').first()\n\n # HACK: copy from legacy.py\n @cached_property\n @deprecated\n def _first_raw_data(self):\n assert hasattr(self, 'datasource')\n return self.datasource.rawdata_set.filter(\n timestamp__gte=self.from_timestamp,\n timestamp__lte=self.to_timestamp).order_by('timestamp').first()\n\n # HACK: copy from legacy.py\n @deprecated\n def _interpolate_sample(self, timestamp, raw_data_before, raw_data_after):\n return self.create_point_sample(\n timestamp,\n PhysicalQuantity(\n RawData.interpolate(\n timestamp,\n raw_data_before,\n raw_data_after),\n self.unit))\n" }, { "alpha_fraction": 0.6267789602279663, "alphanum_fraction": 0.6297438144683838, "avg_line_length": 30.34572410583496, "blob_id": "2c5779fa9bb7ff78b9564b3fe346ade2104413f4", "content_id": "b8ddc3617836d253a1b750dd00f989fd580cd06d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8432, "license_type": "no_license", "max_line_length": 79, "num_lines": 269, "path": "/legacy/display_widgets/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom django.views.decorators.http import require_POST\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.shortcuts import get_object_or_404\nfrom django.db.models import Max\nfrom django.db.models import F\nfrom django.utils.translation import ugettext as _\nfrom django.http import HttpResponseForbidden\n\nfrom gridplatform.utils.views import render_to\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.trackuser import get_customer\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Graph\nfrom gridplatform.users.decorators import auth_or_error, auth_or_redirect\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils import condense\nfrom legacy.display_widgets.models import DashboardWidget\nfrom gridplatform.trackuser import get_user\n\nfrom .tasks import gauge_task\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef async_gauge(request, pk):\n widget = get_object_or_404(\n DashboardWidget,\n id=pk)\n\n customer = get_customer()\n today = customer.now()\n day = RelativeTimeDelta(days=1)\n from_timestamp = condense.floor(today, day, customer.timezone)\n to_timestamp = from_timestamp + day\n\n async = gauge_task.delay(widget, from_timestamp, to_timestamp)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\ndef generate_widget(request, widget):\n graph = None\n if widget.widget_type == DashboardWidget.CONSUMPTION_GRAPH:\n graph = Graph.objects.get(\n role__in=[\n DataRoleField.CONSUMPTION,\n DataRoleField.REACTIVE_ENERGY,\n ],\n collection__dashboardwidget__id=widget.id)\n template_file = 'display_widgets/consumption_widget.html'\n elif widget.widget_type == DashboardWidget.COOLDOWN_GRAPH:\n graph = Graph.objects.get(role=DataRoleField.MEAN_COOLDOWN_TEMPERATURE,\n collection__dashboardwidget__id=widget.id)\n template_file = 'display_widgets/consumption_widget.html'\n elif widget.widget_type == DashboardWidget.PRODUCTION_GRAPH:\n graph = Graph.objects.get(role=DataRoleField.PRODUCTION,\n collection__dashboardwidget__id=widget.id)\n template_file = 'display_widgets/consumption_widget.html'\n elif widget.widget_type == DashboardWidget.GAUGE:\n template_file = 'display_widgets/gauge_widget.html'\n elif widget.widget_type == DashboardWidget.INDEX_GRAPH:\n template_file = 'display_widgets/index_widget.html'\n elif widget.widget_type == DashboardWidget.RATE_GRAPH:\n graph = Graph.objects.get(\n role__in=[\n DataRoleField.POWER,\n DataRoleField.VOLUME_FLOW,\n DataRoleField.RELATIVE_TEMPERATURE,\n DataRoleField.ABSOLUTE_TEMPERATURE,\n DataRoleField.CURRENT,\n DataRoleField.VOLTAGE,\n DataRoleField.REACTIVE_POWER,\n DataRoleField.POWER_FACTOR,\n ],\n collection__dashboardwidget__id=widget.id)\n template_file = 'display_widgets/consumption_widget.html'\n\n return {\n 'widget': render_to_string(\n template_file,\n {\n 'widget': widget,\n 'graph': graph,\n },\n RequestContext(request)),\n }\n\n\n@auth_or_redirect\n@render_to('display_widgets/dashboard.html')\ndef dashboard(request):\n widgets = DashboardWidget.objects.filter(\n user=get_user()).order_by('row')\n left_widgets = []\n right_widgets = []\n\n for w in widgets:\n widget_options = generate_widget(request, w)\n if w.column == DashboardWidget.LEFT_COLUMN:\n left_widgets += [widget_options]\n else:\n right_widgets += [widget_options]\n return {\n 'left_widgets': left_widgets,\n 'right_widgets': right_widgets,\n }\n\n\n@auth_or_redirect\n@render_to('display_widgets/dashboard_fullscreen.html')\ndef dashboard_fullscreen(request):\n widgets = DashboardWidget.objects.filter(\n user=get_user()).order_by('row')\n left_widgets = []\n right_widgets = []\n\n for w in widgets:\n widget_options = generate_widget(request, w)\n if w.column == DashboardWidget.LEFT_COLUMN:\n left_widgets += [widget_options]\n else:\n right_widgets += [widget_options]\n return {\n 'left_widgets': left_widgets,\n 'right_widgets': right_widgets,\n }\n\n\n@auth_or_error\n@json_response\ndef remove_from_dashboard(request):\n pk = request.GET['id']\n widget = get_object_or_404(DashboardWidget, pk=pk)\n if widget.user != get_user():\n return HttpResponseForbidden()\n\n widget.delete()\n\n DashboardWidget.objects.filter(\n column=widget.column, row__gt=widget.row).update(row=F('row') - 1)\n\n return {\n 'statustext': _('The widget has been removed from the dashboard'),\n }\n\n\n@auth_or_error\n@json_response\ndef remove_specific_widget(request, pk, widget_type):\n widget_type = int(widget_type)\n if widget_type == DashboardWidget.INDEX_GRAPH:\n widget = get_object_or_404(\n DashboardWidget,\n user=get_user(),\n index_id=pk,\n widget_type=widget_type)\n else:\n widget = get_object_or_404(\n DashboardWidget,\n user=get_user(),\n collection_id=pk,\n widget_type=widget_type)\n\n if widget.user != get_user():\n return HttpResponseForbidden()\n\n widget.delete()\n\n DashboardWidget.objects.filter(\n column=widget.column, row__gt=widget.row).update(row=F('row') - 1)\n\n return {\n 'statustext': _('The widget has been removed from the dashboard'),\n }\n\n\n@auth_or_error\n@json_response\ndef add_to_dashboard(request, pk, widget_type):\n widget_type = int(widget_type)\n if widget_type == DashboardWidget.INDEX_GRAPH:\n widget_object = Index.objects.get(pk=pk)\n else:\n widget_object = Collection.objects.get(pk=pk)\n if widget_object.dashboardwidget_set.filter(\n widget_type=widget_type,\n user=get_user()).exists():\n return {\n 'statustext': _('The widget is already on the dashboard'),\n }\n\n widget = DashboardWidget()\n if widget_type == DashboardWidget.INDEX_GRAPH:\n widget.index = widget_object\n else:\n widget.collection = widget_object\n\n widget.user = get_user()\n widget.column = DashboardWidget.LEFT_COLUMN\n widget.widget_type = widget_type\n row_max = DashboardWidget.objects.filter(\n user=get_user(),\n column=DashboardWidget.LEFT_COLUMN).aggregate(Max('row'))['row__max']\n if row_max:\n widget.row = row_max + 1\n else:\n widget.row = 1\n\n widget.save()\n return {\n 'statustext': _('The widget has been added to the dashboard'),\n }\n\n\n@json_response\ndef update_order(request):\n order = json.loads(request.POST['order'])\n left_column = order[DashboardWidget.LEFT_COLUMN]['widgets']\n right_column = order[DashboardWidget.RIGHT_COLUMN]['widgets']\n\n def update_widget(id, column, row):\n try:\n widget = DashboardWidget.objects.get(pk=id)\n widget.row = row\n widget.column = column\n widget.save()\n return True\n except DashboardWidget.DoesNotExist:\n return False\n\n row = 1\n for id in left_column:\n success = update_widget(id, DashboardWidget.LEFT_COLUMN, row)\n row += 1\n if not success:\n return {\n 'success': False,\n 'statusText':\n _('You need to reload the dashboard before rearanging '\n 'the widgets'),\n }\n\n row = 1\n for id in right_column:\n success = update_widget(id, DashboardWidget.RIGHT_COLUMN, row)\n row += 1\n if not success:\n return {\n 'success': False,\n 'statusText':\n _('You need to reload the dashboard before rearanging '\n 'the widgets'),\n }\n\n return {\n 'success': True,\n }\n" }, { "alpha_fraction": 0.6350037455558777, "alphanum_fraction": 0.6374968886375427, "avg_line_length": 33.87826156616211, "blob_id": "184f6e657576b6855eddffb663244a40b631a8e1", "content_id": "86c187eb1b8e11919efef1ab96f2b04890300d97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4011, "license_type": "no_license", "max_line_length": 79, "num_lines": 115, "path": "/legacy/enpi_reports/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.shortcuts import get_object_or_404\n\nfrom extra_views import CreateWithInlinesView\nfrom extra_views import UpdateWithInlinesView\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.reports.pdf import generate_pdf\nfrom gridplatform.reports.views import FinalizeReportView\nfrom gridplatform.reports.views import ReportInfo\nfrom gridplatform.reports.views import StartReportView\nfrom legacy.energy_use_reports.views import flotr2_to_gnuplot\n\nfrom .models import ENPIReport\nfrom .forms import ENPIUseAreaFormSet\nfrom .forms import GenerateENPIReportForm\nfrom .tasks import ENPIReportTask\n\n\nclass CreateENPIReportView(CreateWithInlinesView):\n model = ENPIReport\n fields = ['title']\n inlines = [ENPIUseAreaFormSet]\n\n def get_success_url(self):\n return reverse('manage_reports-index')\n\n def get_form(self, form_class):\n form = super(CreateENPIReportView, self).get_form(form_class)\n form.instance.energy_driver_unit = self.kwargs['energy_driver_unit']\n return form\n\n\nclass UpdateENPIReportView(UpdateWithInlinesView):\n model = ENPIReport\n fields = ['title']\n inlines = [ENPIUseAreaFormSet]\n\n def get_success_url(self):\n return reverse('manage_reports-index')\n\n def get_queryset(self):\n \"\"\"\n A C{UpdateENPIReportView} implementation of L{UpdateWithInlinesView}\n get_queryset. Adds a filter to the queryset to ensure that the customer\n owns the object.\n \"\"\"\n queryset = super(UpdateENPIReportView, self).get_queryset()\n return queryset.filter(customer=get_customer())\n\n\nclass FinalizeENPIReportView(FinalizeReportView):\n def generate_report(self, data, timestamp):\n \"\"\"\n Implementation of L{FinalizeReportView.generate_report}.\n\n @param data: Output from L{ENPIReportTask} Celery task.\n\n @param timestamp: The time the report is being build.\n \"\"\"\n enpi_report = get_object_or_404(\n ENPIReport, id=data['enpi_report'])\n\n # make the instance available during template rendering.\n data['enpi_report'] = enpi_report\n\n gnuplots = []\n for use_area_id, use_area_data in data['enpi_use_areas'].items():\n gnuplots.append(\n flotr2_to_gnuplot(\n use_area_data['graph_data'],\n use_area_data['graph_name'] + '.tex',\n sample_resolution=data['sample_resolution']))\n use_area_data['name'] = enpi_report.enpiusearea_set.get(\n id=use_area_id).name_plain\n\n if 'total_enpi' in data:\n gnuplots.append(\n flotr2_to_gnuplot(\n data['total_enpi']['graph_data'],\n data['total_enpi']['graph_name'] + '.tex',\n sample_resolution=data['sample_resolution']))\n\n return ReportInfo(\n '{}.pdf'.format(\n enpi_report.title_plain.encode('ascii', 'ignore')),\n 'application/pdf',\n generate_pdf(\n template='enpi_reports/enpi_report.tex',\n data=data,\n title=_('Energy Performance Indicator Report'),\n report_type='enpi_report',\n customer=enpi_report.customer,\n gnuplots=gnuplots))\n\n\nclass StartENPIReportView(StartReportView):\n form_class = GenerateENPIReportForm\n task = ENPIReportTask\n\n def get_task_data(self, form):\n data = form.cleaned_data\n return {\n 'enpi_report_id': data['enpi_report'].id,\n 'from_date': data['from_date'],\n 'to_date': data['to_date'],\n 'from_timestamp': data['from_timestamp'],\n 'to_timestamp': data['to_timestamp'],\n 'sample_resolution': data['sample_resolution'],\n }\n" }, { "alpha_fraction": 0.7427055835723877, "alphanum_fraction": 0.7453581094741821, "avg_line_length": 25.928571701049805, "blob_id": "e6d27a2f3cf637382219277b356d9a9e86662414", "content_id": "e3f268bb2702ffb5acde78a945d19b7838905fe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 377, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/gridplatform/customers/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom rest_framework import viewsets\n\nfrom .models import Customer\nfrom .serializers import CustomerSerializer\n\n\nclass CustomerViewSet(viewsets.ModelViewSet):\n model = Customer\n serializer_class = CustomerSerializer\n filter_fields = ('name', 'postal_code', 'city')\n" }, { "alpha_fraction": 0.7068965435028076, "alphanum_fraction": 0.7073070406913757, "avg_line_length": 36.476924896240234, "blob_id": "5080d5ba4ef5ed932ce56d227b0b7c5af810c230", "content_id": "c7488c0b705465ea852b8434b778493ce29d08a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2436, "license_type": "no_license", "max_line_length": 79, "num_lines": 65, "path": "/gridplatform/utils/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import url\nfrom django.core.urlresolvers import RegexURLPattern\nfrom django.core.urlresolvers import RegexURLResolver\nfrom django.core.urlresolvers import ResolverMatch\n\nfrom .decorators import permission_required\n\n\nclass _ResolverPermissionMixin(object):\n _permission_decorator = None\n\n def resolve(self, path):\n assert self._permission_decorator is not None, \\\n b'_permission_decorator attribute must be set before resolve call'\n match = super(_ResolverPermissionMixin, self).resolve(path)\n assert isinstance(match, ResolverMatch)\n match.func = self._permission_decorator(match.func)\n return match\n\n\nclass _PermissionURLPattern(_ResolverPermissionMixin, RegexURLPattern):\n pass\n\n\nclass _PermissionURLResolver(_ResolverPermissionMixin, RegexURLResolver):\n pass\n\n\ndef restricted_url(\n regex, view, kwargs=None, name=None,\n prefix='', permission=None, requires_is_staff=False,\n requires_provider=False):\n \"\"\"\n Specialisation of the urlconf `url()` function, which wraps the view --- or\n the views resulting from an `include()` --- with `permission_required()`\n decorator with the specified `permission`.\n \"\"\"\n assert permission or requires_is_staff or requires_provider\n\n base = url(regex, view, kwargs=None, name=None, prefix='')\n assert not isinstance(base, _ResolverPermissionMixin)\n\n # Metaprogramming hacks; we \"just\" want to inject the\n # _ResolverPermissionMixin resolve() method at the head of the MRO-chain.\n # This approach is less involved in implementation details of\n # RegexURLPattern/RegexURLResolver than reconstructing __init__()\n # parameters from the resulting objects...\n if isinstance(base, RegexURLPattern):\n base.__class__ = _PermissionURLPattern\n base._permission_decorator = permission_required(\n permission, requires_is_staff, requires_provider)\n return base\n elif isinstance(base, RegexURLResolver):\n base.__class__ = _PermissionURLResolver\n base._permission_decorator = permission_required(\n permission, requires_is_staff, requires_provider)\n return base\n else:\n raise Exception(\n b'base url() output not an instance of '\n b'RegexURLPattern or RegexURLResolver')\n" }, { "alpha_fraction": 0.6443914175033569, "alphanum_fraction": 0.6515513062477112, "avg_line_length": 33.20408248901367, "blob_id": "872ae7830a385f74e26b6db61fac554b1fe6b4b6", "content_id": "54a56a1b1d057fcc944e5d21e8ea1a16d40efa59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1676, "license_type": "no_license", "max_line_length": 77, "num_lines": 49, "path": "/legacy/manage_rules/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform import trackuser\nfrom gridplatform.users.models import User\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass RuleViewTest(TestCase):\n \"\"\"\n This test setup is an anti-pattern. Do not make new test cases inherit\n from it.\n \"\"\"\n fixtures = ['super_user_and_customer.json']\n\n def setUp(self):\n \"\"\"\n Setup test fixture as if we are logged in as some user called\n super.\n \"\"\"\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n\n self.user = User.objects.get(id=self.client.session[\"_auth_user_id\"])\n self.customer = self.user.customer\n trackuser._set_customer(self.customer)\n trackuser._set_user(self.user)\n\n assert self.user is trackuser.get_user()\n assert self.customer.id and self.customer == trackuser.get_customer()\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_get_rule_list(self):\n response = self.client.get(\"/rules/\")\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_get_minimize_rule_form(self):\n response = self.client.get(\"/rules/minimizerule/\")\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, 'XYZXYZXYZ')\n\n def test_get_triggered_rule_form(self):\n response = self.client.get(\"/rules/triggeredrule/\")\n self.assertEqual(response.status_code, 200)\n self.assertNotContains(response, 'XYZXYZXYZ')\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7028089761734009, "avg_line_length": 31.363636016845703, "blob_id": "acbf41fa8f1c6ce62d188500b175dbe946971a4d", "content_id": "dbdcefac15d6d58dd04bfa5663edbe1fc79a0eee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1780, "license_type": "no_license", "max_line_length": 79, "num_lines": 55, "path": "/gridplatform/reports/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import CustomerBoundManager\n\n\nclass Report(EncryptedModel):\n \"\"\"\n Model for storing generated documents.\n\n :cvar DATA_FORMAT_CHOICES: Data format choices (PDF or CSV).\n\n :ivar customer: A foreign key to the :class:`.Customer` for which\n this document is generated.\n :ivar title:\n :ivar generation_time: The generation time\n :ivar data_format: The data format of the generated document. One\n of the choices in ``self.DATA_FORMAT_CHOICES``.\n :ivar data: The encrypted contents of the document.\n \"\"\"\n PDF = 1\n CSV = 2\n\n DATA_FORMAT_CHOICES = (\n (PDF, 'application/pdf'),\n (CSV, 'text/csv'),\n )\n\n customer = models.ForeignKey(Customer, null=True, on_delete=models.PROTECT)\n title = EncryptedCharField(max_length=50)\n generation_time = models.DateTimeField()\n data_format = models.PositiveIntegerField(choices=DATA_FORMAT_CHOICES)\n data = EncryptedTextField()\n size = models.PositiveIntegerField()\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('report')\n verbose_name_plural = _('reports')\n ordering = ['generation_time', 'data_format', 'id']\n\n def __unicode__(self):\n return unicode(self.title_plain)\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n" }, { "alpha_fraction": 0.6867145299911499, "alphanum_fraction": 0.6870137453079224, "avg_line_length": 33.8125, "blob_id": "6a2891831a3070ad2e3c5673ab2f66233dd9e879", "content_id": "ca6f7e34fd34d05547cee9290f123a5160a95cff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3342, "license_type": "no_license", "max_line_length": 72, "num_lines": 96, "path": "/gridplatform/trackuser/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module contains tests for classes defined in the trackuser package.\n\"\"\"\n\nfrom mock import patch\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom celery import Task\nfrom celery import shared_task\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.users.models import User\nfrom gridplatform.providers.models import Provider\n\nfrom .tasks import trackuser_task\nfrom . import replace_user\nfrom . import replace_customer\nfrom . import get_user\nfrom . import get_customer\n\n\n@trackuser_task\n@shared_task(ignore_result=True)\nclass TrackUserTaskShunt(Task):\n def run(self, test_case):\n test_case.assertIsNotNone(get_user())\n test_case.assertIsNotNone(get_customer())\n test_case.assertEquals(test_case.user, get_user())\n test_case.assertEqual(test_case.customer, get_customer())\n\n\n@trackuser_task\n@shared_task(ignore_result=True)\ndef trackuser_task_shunt(test_case):\n test_case.assertIsNotNone(get_user())\n test_case.assertIsNotNone(get_customer())\n test_case.assertEquals(test_case.user, get_user())\n test_case.assertEqual(test_case.customer, get_customer())\n\n\n@override_settings(\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory',\n ENCRYPTION_TESTMODE=True)\nclass TrackUserTaskTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.user = User.objects.create_user(\n 'username', 'password', user_type=User.CUSTOMER_USER,\n customer=self.customer)\n self.customer_context = replace_customer(self.customer)\n self.user_context = replace_user(self.user)\n\n def test_task_class_run_in_trackuser_context(self):\n self.assertIsNone(get_user())\n self.assertIsNone(get_customer())\n TrackUserTaskShunt.run(\n self, _user_id=self.user.id, _customer_id=self.customer.id)\n\n def test_task_function_run_in_trackuser_context(self):\n self.assertIsNone(get_user())\n self.assertIsNone(get_customer())\n trackuser_task_shunt.run(\n self, _user_id=self.user.id, _customer_id=self.customer.id)\n\n def test_task_class_call_in_trackuser_context(self):\n TrackUserTaskShunt(\n self, _user_id=self.user.id, _customer_id=self.customer.id)\n\n def test_task_function_call_in_trackuser_context(self):\n trackuser_task_shunt(\n self, _user_id=self.user.id, _customer_id=self.customer.id)\n\n def test_delay_delegates_context_to_run(self):\n with self.customer_context, self.user_context:\n with patch.object(TrackUserTaskShunt, 'run') as mock:\n TrackUserTaskShunt.delay('foo', bar='baz')\n\n mock.assert_called_with(\n 'foo', bar='baz', _user_id=self.user.id,\n _customer_id=self.customer.id)\n\n def test_apply_async_noargs_delegates_context_to_run(self):\n with self.customer_context, self.user_context:\n with patch.object(TrackUserTaskShunt, 'run') as mock:\n TrackUserTaskShunt.apply_async()\n mock.assert_called_with(\n _user_id=self.user.id, _customer_id=self.customer.id)\n" }, { "alpha_fraction": 0.5347059965133667, "alphanum_fraction": 0.537359356880188, "avg_line_length": 40.324562072753906, "blob_id": "99135d3cc171c528f325e90fa4978f9d9384b261", "content_id": "0ec10d2a5b447a74e935192dd4d94c572752ae2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9422, "license_type": "no_license", "max_line_length": 79, "num_lines": 228, "path": "/legacy/manage_reports/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom cStringIO import StringIO\nimport contextlib\nimport datetime\nimport fractions\nimport gzip\n\nfrom django.template.defaultfilters import floatformat\nfrom django.utils.translation import ugettext as _\n\nfrom celery import current_task\nfrom celery import shared_task\n\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.reports.csv import generate_csv\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.energy_use_reports.tasks import DataCollectionError\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import Graph\n\n\n@trackuser_task\n@shared_task(\n time_limit=1860, soft_time_limit=1800,\n name='gridplatform.reports.tasks.graphdata_download_task')\ndef graphdata_download_task(data):\n from_timestamp = data['from_timestamp']\n to_timestamp = data['to_timestamp']\n graph_id = data['graph']\n graph = Graph.objects.get(\n collection__customer_id=get_customer().id, pk=graph_id)\n data = []\n for data_series in graph.dataseries_set.all():\n if PhysicalQuantity.compatible_units(data_series.unit, 'watt'):\n samples = data_series.subclass_instance.get_samples(\n from_timestamp, to_timestamp=to_timestamp)\n else:\n samples = data_series.get_condensed_samples(\n from_timestamp, RelativeTimeDelta(hours=1),\n to_timestamp=to_timestamp)\n data.append({\n 'dataseries_id': data_series.id,\n 'samples': list(samples),\n })\n\n tz = from_timestamp.tzinfo\n\n def format_time(val):\n normalized = tz.normalize(val.astimezone(tz))\n # Using danish date format to satisfy import requirements\n return normalized.strftime(\"%d-%m-%Y %H:%M\")\n\n def format(val):\n if isinstance(val, datetime.datetime):\n normalized = tz.normalize(val.astimezone(tz))\n return normalized.strftime(\"%Y-%m-%d %H:%M:%S\")\n elif isinstance(val, fractions.Fraction):\n return float(val)\n else:\n return val\n\n lines = []\n for entry in data:\n dataseries_id = entry['dataseries_id']\n dataseries = DataSeries.objects.get(pk=dataseries_id)\n converter = dataseries.get_preferred_unit_converter()\n lines.append([_(u\"Data series for {data_series_name}\").format(\n data_series_name=dataseries.get_role_display())])\n lines.append([\"---\"])\n samples = entry['samples']\n for sample in samples:\n line = [\n format_time(sample.from_timestamp) + ' - ' +\n format_time(sample.to_timestamp),\n floatformat(\n float(\n converter.extract_value(\n sample.physical_quantity)), 6),\n unicode(\n dataseries.get_preferred_unit_converter().\n get_display_unit()),\n ]\n lines.append(line)\n csvfilename = '{}.csv'.format(graph)\n with contextlib.closing(StringIO()) as f:\n gz = gzip.GzipFile(mode='wb', fileobj=f)\n gz.write(generate_csv(lines))\n gz.close()\n\n return {\n 'csvfilename': csvfilename,\n 'gzippedfile': f.getvalue(),\n }\n\n\n# Softly kill using exception after 30 minutes. Kill for real after 31 minutes.\n@trackuser_task\n@shared_task(\n time_limit=1860, soft_time_limit=1800,\n name='gridplatform.reports.tasks.collect_consumption_data')\ndef collect_consumption_data(mp_ids, from_timestamp, to_timestamp, from_date,\n to_date, include_cost):\n measurementpoints = \\\n ConsumptionMeasurementPoint.objects.subclass_only().filter(\n id__in=mp_ids).select_related('customer')\n mp_data = {}\n errors = []\n include_degree_days_corrected = False\n\n for i, mp in enumerate(measurementpoints):\n current_task.update_state(state='PROGRESS',\n meta={'current': i,\n 'total': len(measurementpoints)})\n if mp.consumption:\n ds = mp.consumption\n preferred_unit_converter = ds.get_preferred_unit_converter()\n assert ds.is_accumulation()\n\n development = ds.calculate_development(\n from_timestamp, to_timestamp)\n if development is not None:\n consumption = preferred_unit_converter.extract_value(\n development.physical_quantity)\n if development.extrapolated:\n errors.append(\n DataCollectionError(\n _('Consumption for {measurement_point} is '\n 'calculated from incomplete data.'),\n measurement_point=mp))\n else:\n consumption = 0\n assert development is None\n errors.append(\n DataCollectionError(\n _('Consumption and therefore also cost is undefined '\n 'for {measurement_point}'),\n measurement_point=mp))\n\n if mp.heating_degree_days_corrected_consumption is not None:\n include_degree_days_corrected = True\n cds = mp.heating_degree_days_corrected_consumption\n corrected_development = cds.calculate_development(\n from_timestamp, to_timestamp)\n if corrected_development is not None:\n if corrected_development.extrapolated:\n errors.append(\n DataCollectionError(\n _('Heating degree days corrected consumption '\n 'for {measurement_point} is calculated '\n 'from incomplete data'),\n measurement_point=mp))\n corrected_consumption = \\\n preferred_unit_converter.extract_value(\n corrected_development.physical_quantity)\n else:\n corrected_consumption = None\n errors.append(\n DataCollectionError(\n _('Heating degree days corrected consumption '\n 'undefined for '\n '{measurement_point}'),\n mp))\n else:\n corrected_consumption = None\n\n cost = None\n currency_unit = None\n if include_cost:\n if mp.cost is not None:\n costds = mp.cost\n currency_unit = costds.unit\n cost_development = costds.calculate_development(\n from_timestamp, to_timestamp)\n if cost_development is not None:\n cost_preferred_unit_converter = \\\n costds.get_preferred_unit_converter()\n cost = cost_preferred_unit_converter.extract_value(\n cost_development.physical_quantity)\n if cost_development.extrapolated:\n errors.append(\n DataCollectionError(\n _('Cost for {measurement_point} is '\n 'calculated from incomplete data'),\n measurement_point=mp))\n else:\n cost = 0\n errors.append(\n DataCollectionError(\n _('Cost undefined for '\n '{measurement_point}'),\n mp))\n else:\n assert mp.cost is None\n errors.append(\n DataCollectionError(\n _('Unable to calculate cost for '\n '{measurement_point} '\n 'because it has no tariff attached.'),\n measurement_point=mp))\n else:\n cost = None\n currency_unit = None\n mp_data[mp.id] = {\n 'unit': preferred_unit_converter.physical_unit,\n 'consumption': consumption,\n 'degreedays_corrected_consumption': corrected_consumption,\n 'cost': cost,\n 'currency_unit': currency_unit,\n 'billing_meter_number': mp.billing_meter_number,\n 'billing_installation_number': mp.billing_installation_number,\n }\n return {\n 'mp_ids': mp_ids,\n 'mp_data': mp_data,\n 'from_timestamp': from_timestamp,\n 'to_timestamp': to_timestamp,\n 'from_date': from_date,\n 'to_date': to_date,\n 'include_degree_days_corrected': include_degree_days_corrected,\n 'include_cost': include_cost,\n 'errors': errors,\n }\n" }, { "alpha_fraction": 0.6336100101470947, "alphanum_fraction": 0.6339012384414673, "avg_line_length": 38.465518951416016, "blob_id": "08cb6a4fbe98762b3dc55d29b8e11ef023f43c60", "content_id": "6d07849e54b94fa27fd7afdc2ffd99bda5c45337", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6867, "license_type": "no_license", "max_line_length": 79, "num_lines": 174, "path": "/legacy/measurementpoints/interpolationcloud.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom operator import attrgetter\nfrom gridplatform.utils.iter_ext import pairwise\n\n\nclass InterpolationFrame(object):\n \"\"\"\n An C{InterpolationFrame} is a frame of a L{DataSeries} inside which\n interpolations can be made efficiently; see L{get_sample_at()}.\n\n C{InterpolationFrame}s can be advanced, to efficiently interpolate the next\n range of samples; see L{advance()}.\n\n @ivar pivot_timestamp: The interpolation frame ends at this timestamp. To\n get interpolations beyond this timestamp, this C{InterpolationFrame} must\n be advanced. Interpolation is only well-defined between the previous\n C{pivot_timestamp} and the current C{pivot_timestamp}, both ends included.\n\n @invariant: C{from_timestamp <= pivot_timestamp <= to_timestamp}, where\n C{from_timestamp} and C{to_timestamp} are defined as C{__init__()}\n arguments.\n \"\"\"\n\n def __init__(self, data_series, from_timestamp, to_timestamp):\n \"\"\"\n Construct a new C{InterpolationFrame} ready to iterate across a\n L{DataSeries} in a given time interval.\n\n @param data_series: The given L{DataSeries}.\n\n @param from_timestamp: The start of the time interval.\n\n @param to_timestamp: The end of the time interval.\n \"\"\"\n self.data_series = data_series\n self._from_time = from_timestamp\n self._to_time = to_timestamp\n if from_timestamp == to_timestamp:\n # Only one sample. next(self.iterator) must raise StopIteration,\n # and both _from_sample and _to_sample are set to the same sample.\n self.iterator = iter([])\n self._from_sample = self._to_sample = next(\n data_series.get_samples(\n from_timestamp,\n to_timestamp),\n None)\n else:\n self.iterator = pairwise(\n data_series.get_samples(self._from_time, self._to_time))\n self._from_sample, self._to_sample = \\\n next(self.iterator, (None, None))\n\n def advance(self):\n \"\"\"\n Attempt to advance this C{InterpolationFrame}.\n\n @return: Returns C{True} if this C{InterpolationFrame} was successfully\n advanced, C{False} otherwise.\n\n @postcondition: C{from_timestamp < pivot_timestamp <= to_timestamp},\n where C{from_timestamp} and C{to_timestamp} are defined as\n C{__init__()} arguments.\n\n @postcondition: If the return value was C{False}, C{pivot_timestamp ==\n to_timestamp}, where C{to_timestamp} is defined as C{__init__()}\n arguments.\n \"\"\"\n try:\n self._from_sample, self._to_sample = next(self.iterator)\n assert self._from_time < self.pivot_timestamp <= self._to_time\n return True\n except StopIteration:\n assert self.pivot_timestamp == self._to_time\n return False\n\n def get_sample_at(self, timestamp):\n \"\"\"\n @precondition: C{timestamp} lies between the current C{pivot_timestamp}\n and the previous C{pivot_timestamp}.\n\n @return: Returns a sample representing C{timestamp}, possibly using\n interpolation or extrapolation. If no such sample can be constructed,\n C{None} is returned.\n \"\"\"\n assert self._from_sample is None or \\\n self._from_sample.timestamp <= timestamp\n assert self._to_sample is None or \\\n timestamp <= self._to_sample.timestamp\n return self.data_series._interpolate_extrapolate_sample(\n timestamp, self._from_sample, self._to_sample)\n\n @property\n def pivot_timestamp(self):\n if self._to_sample is not None:\n return self._to_sample.timestamp\n else:\n return self._to_time\n\n\nclass InterpolationCloud(object):\n \"\"\"\n An C{InterpolationCloud} is a sample vector iterator, keeping track of\n which sample pairs for each of a number of L{DataSeries} surround a given\n timestamp (the timestamp of the currently yielded sample vector).\n Example::\n\n interpolation_cloud = InterpolationCloud(data_series_list,\n from_timestamp, to_timestamp)\n for sample_vector in interpolation_cloud:\n # do stuff here\n\n This class is intended to be used in L{DataSeries} that are defined in\n terms of a number of continuous L{DataSeries}; i.e. C{DataSeries} whose raw\n samples are point samples, where linear interpolation is sound.\n \"\"\"\n\n def __init__(self, data_series_list, from_timestamp, to_timestamp):\n \"\"\"\n For each timestamp between C{from_timestamp} and C{to_timestamp} that\n holds a sample in any of the underlying L{DataSeries}, a sample vector\n will constructed. Each entry in such a sample vector is a sample of\n the corresponding L{DataSeries}. The sample index in the sample vector\n equals the corresponding L{DataSeries} index in the\n C{data_series_list}.\n \"\"\"\n self.data_series_list = data_series_list\n self.from_timestamp = from_timestamp\n self.to_timestamp = to_timestamp\n self.interpolation_iterators = [\n InterpolationFrame(\n data_series, self.from_timestamp, self.to_timestamp)\n for data_series in self.data_series_list]\n self.current_timestamp = self.from_timestamp\n self.final_sample_yielded = False\n\n def __iter__(self):\n return self\n\n def next(self):\n \"\"\"\n The next sample vector.\n\n @return: Returns the next vector of samples. All samples in this\n sample vector share the same timestamp. If one or more of the\n underlying C{DataSeries} is unable to define a sample at this\n timestamp, their sample is replaced with None.\n\n @postcondition: The next sample vector being yielded (if any) has a\n larger timestamp than the one returned this time (loop variant).\n\n @raise StopIteration: when called after the final sample has been\n yielded.\n \"\"\"\n if self.final_sample_yielded or len(self.interpolation_iterators) == 0:\n raise StopIteration()\n\n sample_vector = [interpolation_iterator.get_sample_at(\n self.current_timestamp) for\n interpolation_iterator in\n self.interpolation_iterators]\n\n for i in self.interpolation_iterators:\n if i.pivot_timestamp == self.current_timestamp and not i.advance():\n self.final_sample_yielded = True\n\n if not self.final_sample_yielded:\n self.current_timestamp = min(\n self.interpolation_iterators,\n key=attrgetter('pivot_timestamp')).pivot_timestamp\n\n return sample_vector\n" }, { "alpha_fraction": 0.6602563858032227, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 18.5, "blob_id": "cebf33613e48b7a639c795853eec6026b706da7f", "content_id": "89c2ca58ca948fd8dbfad636552ab9cc9c3a13b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "no_license", "max_line_length": 39, "num_lines": 8, "path": "/gridplatform/bootstrap/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .conf import settings\n\n\n__all__ = ['settings']\n" }, { "alpha_fraction": 0.6598901152610779, "alphanum_fraction": 0.6737637519836426, "avg_line_length": 31.35555648803711, "blob_id": "892a18ff4cf8920f6d67f4d3fe1f6101f2a20382", "content_id": "5e94102ef4e451ed00ebcad608bfe585fd6c4658", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14560, "license_type": "no_license", "max_line_length": 90, "num_lines": 450, "path": "/fixture_hack.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n#\n# ./manage.py syncdb --noinput\n# ./manage.py create_encrypted_user root feet\n# ./manage.py create_encrypted_user super 123\n# ./manage.py create_encrypted_user test 123\n#\n# python fixture_hack.py\n\nimport datetime\nfrom decimal import Decimal\nimport math\nimport os\nimport pytz\n\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"gridplatform.settings.local\")\n\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.models import Location\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.proxies import TemperatureMeasurementPoint\nfrom gridplatform.encryption.testutils import encryption_context\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import utilitytypes\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.devices.models import PhysicalInput\nfrom legacy.devices.models import RawData\nfrom legacy.devices.models import SoftwareImage\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import CostCalculation\nfrom legacy.measurementpoints.models import DataSeries\n\n\ndef create_customer():\n customer = Customer()\n customer.provider_id = 1\n customer.name_plain = 'test customer'\n customer.vat_plain = '4242'\n customer.address_plain = 'address'\n customer.postal_code_plain = '1234'\n customer.city_plain = 'city'\n customer.phone_plain = '12341234'\n customer.country_code_plain = 'dnk'\n customer.timezone = pytz.timezone('Europe/Copenhagen')\n customer.contact_name_plain = ''\n customer.contact_email_plain = ''\n customer.contact_phone_plain = ''\n customer.created_by = User.objects.get(id=1)\n customer.save()\n return customer\n\n\ndef setup_users(customer):\n superuser = User.objects.create_user(\n 'super', '123',\n user_type=User.CUSTOMER_SUPERUSER,\n customer=customer)\n testuser = User.objects.create_user(\n 'test', '123',\n user_type=User.CUSTOMER_USER,\n customer=customer)\n\n superuser.is_staff = False\n superuser.is_superuser = True\n superuser.save()\n\n testuser.is_staff = False\n testuser.is_superuser = False\n testuser.save()\n\n\ndef create_location(customer):\n location = Location(customer=customer, name_plain='test location')\n location.save()\n return location\n\n\ndef create_agent(customer, location):\n agent = Agent(\n customer=customer, location=location, mac='08:00:27:03:fe:c7',\n device_type=1, hw_major=5, hw_minor=0, hw_revision=0,\n sw_major=2, sw_minor=2, sw_revision=1, sw_subrevision='fixture',\n online=True)\n agent.save()\n return agent\n\n\ndef create_meter(agent, manufactoring_id, connection_type, name):\n customer = agent.customer\n location = agent.location\n meter = Meter(\n customer=customer,\n agent=agent,\n manufactoring_id=manufactoring_id,\n connection_type=connection_type,\n location=location,\n name_plain=name,\n relay_enabled=True,\n online=True)\n meter.save()\n return meter\n\n\ndef create_meters(agent):\n kamstrup_meter = create_meter(\n agent, 155173425101, Meter.GRIDLINK,\n 'Kamstrup meter')\n mbus_meter = create_meter(\n agent, 1980720117449728, Meter.GRIDLINK,\n 'Mbus meter')\n meter = create_meter(\n agent, 456789, Meter.GRIDLINK,\n 'ZigBee elec. test meter')\n gas = create_meter(\n agent, 456790, Meter.GRIDLINK,\n 'ZigBee gas meter')\n heat = create_meter(\n agent, 456791, Meter.GRIDLINK,\n 'ZigBee heat meter')\n water = create_meter(\n agent, 456792, Meter.GRIDLINK,\n 'ZigBee water meter')\n gridlink = create_meter(\n agent, 456793, Meter.GRIDLINK,\n 'GridLink')\n return kamstrup_meter, mbus_meter, meter, gas, heat, water, gridlink\n\n\ndef create_physicalinputs(kamstrup_meter, mbus_meter, meter, gas, heat,\n water, gridlink):\n accum = PhysicalInput(\n customer=mbus_meter.customer,\n unit='milliwatt*hour', type=1,\n meter=mbus_meter, order=0,\n name_plain='M-Bus consumption')\n accum.save()\n power = PhysicalInput(\n customer=mbus_meter.customer,\n unit='milliwatt', type=1,\n meter=mbus_meter, order=0, name_plain='M-Bus power')\n power.save()\n current = PhysicalInput(\n customer=mbus_meter.customer,\n unit='milliampere', type=1,\n meter=mbus_meter, order=0,\n name_plain='M-Bus current')\n current.save()\n voltage = PhysicalInput(\n customer=mbus_meter.customer,\n unit='millivolt', type=1,\n meter=mbus_meter, order=0,\n name_plain='M-Bus voltage')\n voltage.save()\n physicalinput = PhysicalInput(\n customer=meter.customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN,\n meter=meter, order=2,\n name_plain='Pulse meter')\n physicalinput.save()\n\n gas = PhysicalInput(\n customer=gas.customer,\n unit='milliliter',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gas, order=0,\n name_plain=\"Gas consumption\")\n gas.save()\n\n heat = PhysicalInput(\n customer=heat.customer,\n unit='milliwatt*hour',\n type=PhysicalInput.DISTRICT_HEATING, meter=heat, order=0,\n name_plain=\"Heat consumption\")\n heat.save()\n\n water = PhysicalInput(\n customer=water.customer,\n unit='milliliter',\n type=PhysicalInput.WATER, meter=water,\n order=0, name_plain=\"Water consumption\")\n water.save()\n\n gl1 = PhysicalInput(\n customer=gridlink.customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=0, name_plain=\"GridLink input 1\")\n gl2 = PhysicalInput(\n customer=gridlink.customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=1, name_plain=\"GridLink input 2\")\n gl3 = PhysicalInput(\n customer=gridlink.customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=2, name_plain=\"GridLink input 3\")\n gl1.save()\n gl2.save()\n gl3.save()\n\n powerfactor = PhysicalInput(\n customer=mbus_meter.customer,\n unit='millinone', type=1,\n meter=mbus_meter, order=0,\n name_plain='M-Bus Power Factor')\n powerfactor.save()\n\n return accum, power, physicalinput, heat\n\n\ndef create_groups(customer):\n collection = Collection(\n customer=customer,\n name_plain='Hal A',\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n collection.save()\n\n collection = Collection(\n customer=customer,\n name_plain='Hal B',\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n collection.save()\n\n collection = Collection(\n customer=customer,\n parent=collection,\n name_plain='Hal C',\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n collection.save()\n\n collection = Collection.objects.get(id=1)\n\n return collection\n\n\ndef create_indexes():\n timezone = pytz.timezone(\"Europe/Copenhagen\")\n\n elindex = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n data_format=Index.SPOT,\n name_plain=\"Random el\",\n timezone=timezone)\n elindex.save()\n\n start_time = timezone.localize(datetime.datetime.now()).replace(\n hour=0, minute=0, second=0, microsecond=0)\n current_time = start_time\n for i in range(24 * 7):\n elindex.entry_set.create(\n from_timestamp=current_time,\n to_timestamp=current_time + datetime.timedelta(hours=1),\n value=Decimal(0.3 * math.sin(i * 7.0 / 24.0) + 0.3))\n current_time += datetime.timedelta(hours=1)\n\n gasindex = Index(\n unit=\"currency_dkk*liter^-1\",\n role=DataRoleField.GAS_TARIFF,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas,\n data_format=Index.SPOT,\n name_plain=\"Random Gas\",\n timezone=timezone)\n gasindex.save()\n\n start_time = timezone.localize(datetime.datetime.now()).replace(\n hour=0, minute=0, second=0, microsecond=0)\n current_time = start_time\n for i in range(24 * 7):\n gasindex.entry_set.create(\n from_timestamp=current_time,\n to_timestamp=current_time + datetime.timedelta(hours=1),\n value=Decimal(0.1 * math.sin(i * 3.0 / 24.0) + 0.15))\n current_time += datetime.timedelta(hours=1)\n\n return elindex, gasindex\n\n\ndef create_swimage():\n swimage = SoftwareImage(device_type=1,\n hw_major=5, hw_minor=0, hw_revision=0,\n sw_major=2, sw_minor=2, sw_revision=1)\n swimage.save()\n return swimage\n\n\ndef main():\n root = User.objects.create_user(\n 'root', 'feet',\n user_type=User.ADMIN)\n root.is_staff = True\n root.is_superuser = True\n root.save()\n\n Provider.objects.create(name_plain='GridManager Energy Service')\n\n customer = create_customer()\n setup_users(customer)\n from gridplatform.trackuser import _set_customer\n _set_customer(customer)\n location = create_location(customer)\n agent = create_agent(customer, location)\n kamstrup_meter, mbus_meter, meter, gas, heat, water, gridlink = \\\n create_meters(agent)\n accum, power, physicalinput, heat_accum = create_physicalinputs(\n kamstrup_meter, mbus_meter, meter, gas, heat, water, gridlink)\n\n ph_production = meter.physicalinput_set.create(\n customer=meter.customer,\n unit='milliwatt*hour',\n type=PhysicalInput.ELECTRICITY,\n order=10,\n name_plain='Production data')\n from productiondata import MEASUREMENTS\n RawData.objects.bulk_create(\n [\n RawData(\n datasource=ph_production,\n value=value,\n timestamp=timestamp)\n for timestamp, value in MEASUREMENTS])\n\n collection = create_groups(customer)\n\n mpa = ConsumptionMeasurementPoint(\n customer=customer, parent=collection,\n name_plain='Lighting',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n from gridplatform.consumptions.models import NonpulsePeriod\n from legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter # noqa\n period = NonpulsePeriod.objects.get(datasource=accum)\n ds = ConsumptionAccumulationAdapter.objects.get(\n datasequence__period=period)\n mpa.consumption_input = ds\n mpa.consumption.customer = customer\n mpa.save()\n mpa.enable_rate = True\n\n meter = Meter.objects.get(manufactoring_id=456789)\n mpa.relay = meter\n mpa.save()\n\n mpb = ConsumptionMeasurementPoint(\n customer=customer, parent=collection, name_plain='Production',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n mpb.consumption_input = ds\n mpb.consumption.customer = customer\n mpb.save()\n\n mpc = ConsumptionMeasurementPoint(\n customer=customer, parent=collection,\n name_plain='Heating (total)',\n role=Collection.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n period = NonpulsePeriod.objects.get(datasource=heat_accum)\n ds = ConsumptionAccumulationAdapter.objects.get(\n datasequence__period=period)\n mpc.consumption_input = ds\n mpc.consumption.customer = customer\n mpc.save()\n mpc.enable_rate = True\n\n create_indexes()\n\n tariff = DataSeries.objects.filter(\n role=DataRoleField.ELECTRICITY_TARIFF)[0]\n\n cost_graph = mpa.graph_set.create(\n role=DataRoleField.COST)\n\n CostCalculation.objects.create(\n graph=cost_graph,\n role=DataRoleField.COST,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n unit=\"millicurrency_dkk\",\n customer=customer,\n tariff=tariff,\n consumption=mpa.consumption)\n\n create_swimage()\n\n temperature = PhysicalInput(\n customer=meter.customer,\n unit='millikelvin',\n type=PhysicalInput.TEMPERATURE,\n meter=meter,\n order=3,\n name_plain='Temperature input')\n temperature.save()\n\n temperature_measurement_point = TemperatureMeasurementPoint(\n name_plain='Outdoor temperature',\n customer=customer,\n parent=collection)\n\n assert customer\n\n from gridplatform.datasequences.models import NonaccumulationPeriod\n from legacy.datasequence_adapters.models import NonaccumulationAdapter # noqa\n period = NonaccumulationPeriod.objects.get(datasource=temperature)\n ds = NonaccumulationAdapter.objects.get(\n datasequence__period_set=period)\n\n temperature_measurement_point.input_configuration = ds\n temperature_measurement_point.save()\n\n # The automatically created input periods will be have their from_timestamp\n # initialized to creation time, which is naturally in real life, bug\n # useless in this fixture setup:\n import gridplatform.consumptions.models\n gridplatform.consumptions.models.Period.objects.all().update(\n from_timestamp=datetime.datetime(2000, 1, 1, tzinfo=pytz.utc))\n NonaccumulationPeriod.objects.all().update(\n from_timestamp=datetime.datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n from django.contrib.auth.models import Group, Permission\n all_permission_group = Group.objects.create(name='All permissions')\n all_permissions = Permission.objects.all()\n all_permission_group.permissions.add(*all_permissions)\n\n from gridplatform.customer_datasources.models import CustomerDataSource\n from gridplatform.utils.units import ENERGY_PER_VOLUME_BASE_UNITS\n conversion_rate = CustomerDataSource(\n name_plain='conversion rate',\n customer=customer,\n unit=ENERGY_PER_VOLUME_BASE_UNITS[0])\n conversion_rate.save()\n\n\nif __name__ == \"__main__\":\n with encryption_context():\n main()\n" }, { "alpha_fraction": 0.5558711886405945, "alphanum_fraction": 0.5558711886405945, "avg_line_length": 40.411766052246094, "blob_id": "fc480a3cf13a91d2d226e1188a3d7dd3a38171d9", "content_id": "05000b5af699238e44a3a3f2cbc4197bba7b39e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 149, "num_lines": 51, "path": "/gridplatform/bootstrap/static/bootstrap/genius.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true */\n/*global $, jQuery, gettext, pgettext, get_format */\n\n/* Genius Admin Template specific JavaScript */\n\n// Save state of menu whenever menu is shown/hidden or minimized/restored\n$(document).ready(function () {\n $('#main-menu-toggle, #main-menu-min').click(function () {\n if ($('#main-menu-toggle').hasClass('open')) {\n jQuery.cookie('main-menu-toggle', 'open', {path: '/'});\n } else if ($('#main-menu-toggle').hasClass('close')) {\n jQuery.cookie('main-menu-toggle', 'close', {path: '/'});\n }\n\n if ($('#main-menu-min').hasClass('full')) {\n jQuery.cookie('main-menu-min', 'full', {path: '/'});\n } else if ($('#main-menu-min').hasClass('minified')) {\n jQuery.cookie('main-menu-min', 'minified', {path: '/'});\n }\n });\n\n if (jQuery.cookie('main-menu-toggle') === 'close') {\n // Menu is initially hidden\n $('#main-menu-toggle').removeClass('open').addClass('close');\n $('#content').addClass('full');\n $('.navbar-brand').addClass('noBg');\n $('#sidebar-left').hide();\n }\n\n if (jQuery.cookie('main-menu-min') === 'minified') {\n // Menu is initially minimized\n $('#main-menu-min').removeClass('full').addClass('minified').find('i').removeClass('fa-angle-double-left').addClass('fa-angle-double-right');\n\n $('body').addClass('sidebar-minified');\n $('#content').addClass('sidebar-minified');\n $('#sidebar-left').addClass('minified');\n\n $('.dropmenu > .chevron').removeClass('opened').addClass('closed');\n $('.dropmenu').parent().find('ul').hide();\n\n $('#sidebar-left > div > ul > li > a > .chevron').removeClass('closed').addClass('opened');\n $('#sidebar-left > div > ul > li > a').addClass('open');\n }\n\n /* Hack to make dropdowns work in box headers. */\n $('.box-header .dropdown').on('show.bs.dropdown', function () {\n $('.box .box-header').css('overflow', 'visible');\n }).on('hide.bs.dropdown', function () {\n $('.box .box-header').css('overflow', 'hidden');\n });\n});\n" }, { "alpha_fraction": 0.5971636772155762, "alphanum_fraction": 0.5979302525520325, "avg_line_length": 37.367645263671875, "blob_id": "b25fdb1518acf29670dabdd72c5d1af13df9ae93", "content_id": "3f0a01f02b149a4f2c396b28f1d57523468aa19a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2609, "license_type": "no_license", "max_line_length": 97, "num_lines": 68, "path": "/gridplatform/datasequences/management/commands/bulk_update_quality_control.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.management.base import BaseCommand\nfrom django.core.management.base import CommandError\nfrom optparse import make_option\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.datasequences.models.qualitycontrol import AccumulationOfflineTolerance # noqa\n\n\nclass Command(BaseCommand):\n help = 'Can set offline tolerance for all data sequences on a customer'\n\n option_list = BaseCommand.option_list + (\n make_option(\n '-c',\n '--customer_id',\n dest='customer_id',\n help='Customer ID',\n type=int\n ),\n make_option(\n '-o',\n '--offlinetolerance',\n dest='offlinetolerance',\n help='Set the offline tolerance. '\n 'Specified as number of clock hours',\n type=int\n ),\n )\n\n def handle(self, *args, **options):\n verbosity = int(options.get('verbosity'))\n customer_id = options['customer_id']\n offlinetolerance = options['offlinetolerance']\n\n if customer_id is None:\n raise CommandError('You must specify a customer ID')\n try:\n Customer.objects.get(id=customer_id)\n except Customer.DoesNotExist:\n raise CommandError(\n 'Customer with ID %d does not exist' % (customer_id,))\n\n if offlinetolerance is None:\n raise CommandError('You have not told the script to anything! '\n 'Run with --help for a list of options')\n else:\n # Update existing offline tolerances\n exiting_count = AccumulationOfflineTolerance.objects.filter(\n datasequence__customer_id=customer_id).update(\n hours=offlinetolerance)\n # Create all missing offline tolerances\n new_offlinetolerances = [\n AccumulationOfflineTolerance(datasequence=ds,\n hours=offlinetolerance)\n for ds in Consumption.objects.filter(\n customer_id=customer_id,\n accumulationofflinetolerance__isnull=True)\n ]\n AccumulationOfflineTolerance.objects.bulk_create(\n new_offlinetolerances)\n if verbosity >= 1:\n print 'Updated %d existing offline tolerances and created '\n '%d new.' % (exiting_count, len(new_offlinetolerances))\n" }, { "alpha_fraction": 0.5831745862960815, "alphanum_fraction": 0.5920634865760803, "avg_line_length": 31.8125, "blob_id": "29a2986a883916c0816085156d11396edcc580ab", "content_id": "43486992bcc8b146e79fb69c5114af724686ee36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9450, "license_type": "no_license", "max_line_length": 79, "num_lines": 288, "path": "/gridagentserver-protocol/gridagentserver_protocol/server_messages.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"Messages to be sent from the GridAgent server to the (virtual) agent.\"\"\"\n\nimport logging\nfrom struct import Struct\n\nfrom messages import Message, timestamp_to_datetime, datetime_to_timestamp\nfrom datatypes import Meter, Rule, RuleSet, Price\n\nlogger = logging.getLogger(__name__)\n\nuint32 = Struct('!I')\nuint16 = Struct('!H')\nuint8 = Struct('B')\n\n# ZigBee timestamp, i.e. seconds since 2000-01-01\ntimestamp_struct = Struct('!I')\n\n# major, minor, revision, extra string\nversion_struct = Struct('!BBB12s')\n\n\ndef normalise_version(version):\n \"\"\"\n Replace the received fixed-length \"extra\" string with its prefix before the\n first \\0 character.\n \"\"\"\n major, minor, revision, extra = version\n extra = extra.split('\\0', 1)[0]\n return (major, minor, revision, extra)\n\n\n# connection_type, ID\nmeter_struct = Struct('!bq')\n\n\n# DEPRECATED/useless:\n# We always want 1 minute interval; ignoring intervals configured in DB...\nclass ConfigGp(Message):\n # ID, interval\n config1_struct = Struct('!qi')\n\n def __init__(self, measurement_intervals):\n self.measurement_intervals = measurement_intervals\n\n @classmethod\n def unpack(cls, header, read, version):\n pass\n\n def pack(self, version):\n if version == 1:\n data = [uint32.pack(len(self.measurement_intervals))]\n data.extend([self.config1_struct.pack(meter.id, interval)\n for meter, interval\n in self.measurement_intervals.iteritems()])\n else:\n # deprecated...\n data = []\n return self._pack(data, version)\n\n\nclass ConfigGaRulesets(Message):\n # override timeout, rule-count, meter-count\n ruleset_head_struct = Struct('!ihh')\n # relay-on?, start-time, end-time\n rule_struct = Struct('!xxx?II')\n # ID\n meter1_struct = Struct('!q')\n # connection type, ID\n meter2_struct = Struct('!bq')\n\n def __init__(self, rulesets):\n self.rulesets = rulesets\n\n @classmethod\n def unpack(cls, header, read, version):\n ruleset_count, = read(uint32)\n rulesets = []\n for n in range(ruleset_count):\n override_timeout, rule_count, meter_count = \\\n read(cls.ruleset_head_struct)\n rules = [Rule(*entry)\n for entry in read(cls.rule_struct, rule_count)]\n if version == 1:\n meters = [Meter(0, id)\n for id, in read(cls.meter1_struct, meter_count)]\n else:\n meters = [Meter(*entry)\n for entry in read(cls.meter2_struct, meter_count)]\n rulesets.append(RuleSet(override_timeout, rules, meters))\n return cls(rulesets)\n\n def pack(self, version):\n data = [uint32.pack(len(self.rulesets))]\n for override_timeout, rules, meters in self.rulesets:\n data.append(self.ruleset_head_struct.pack(override_timeout,\n len(rules), len(meters)))\n data.extend([self.rule_struct.pack(*rule) for rule in rules])\n if version == 1:\n data.extend([self.meter1_struct.pack(meter.id)\n for meter in meters])\n else:\n data.extend([self.meter2_struct.pack(*meter)\n for meter in meters])\n return self._pack(data, version)\n\n\nclass ConfigGaTime(Message):\n def __init__(self, timestamp):\n self.timestamp = timestamp\n\n @classmethod\n def unpack(cls, header, read, version):\n timestamp = timestamp_to_datetime(*read(timestamp_struct))\n return cls(timestamp)\n\n def pack(self, version):\n data = timestamp_struct.pack(datetime_to_timestamp(self.timestamp))\n return self._pack([data], version)\n\n\nclass ConfigGaPrices(Message):\n # count\n price_head_struct = Struct('!xxH')\n # start timestamp, end timestamp, price per GWh\n # (price in some unspecified unit...)\n price_struct = Struct('!III')\n\n def __init__(self, prices):\n self.prices = prices\n\n @classmethod\n def unpack(cls, header, read, version):\n price_count, = read(cls.price_head_struct)\n prices = [Price(timestamp_to_datetime(start),\n timestamp_to_datetime(end), price)\n for start, end, price in read(cls.price_struct, price_count)]\n return cls(prices)\n\n def pack(self, version):\n data = [self.price_head_struct.pack(len(self.prices))]\n data.extend([self.price_struct.pack(datetime_to_timestamp(start),\n datetime_to_timestamp(end), price)\n for start, end, price in self.prices])\n return self._pack(data, version)\n\n\nclass ConfigGpSoftware(Message):\n def __init__(self, sw_version, hw_model, target_hw_version, image, meters):\n # version: major, minor, revision\n self.sw_version = sw_version\n self.hw_model = hw_model\n self.target_hw_version = target_hw_version\n self.image = image\n self.meters = meters\n\n @classmethod\n def unpack(cls, header, read, version):\n image_offset, = read(uint32)\n sw_version = normalise_version(read(version_struct))\n hw_model, = read(uint8)\n target_hw_version = normalise_version(read(version_struct))\n meter_count, = read(uint32)\n meters = [Meter(*entry)\n for entry in read(meter_struct, meter_count)]\n image = read.raw()\n return cls(sw_version, hw_model, target_hw_version, image, meters)\n\n def pack(self, version):\n assert version >= 3\n # differ from agent software message with inclusion of model, meter ids\n image_offset = (uint32.size + 2 * version_struct.size + uint8.size +\n uint32.size + len(self.meters) * meter_struct.size)\n data = [uint32.pack(image_offset),\n version_struct.pack(*self.sw_version),\n uint8.pack(self.hw_model),\n version_struct.pack(*self.target_hw_version)]\n # meter_ids\n data.append(uint32.pack(len(self.meters)))\n data.extend([meter_struct.pack(*meter) for meter in self.meters])\n # image\n data.append(self.image)\n return self._pack(data, version)\n\n\nclass ConfigGaSoftware(Message):\n def __init__(self, sw_version, hw_model, target_hw_version, image):\n # version: major, minor, revision\n self.sw_version = sw_version\n self.hw_model = hw_model\n self.target_hw_version = target_hw_version\n self.image = image\n\n @classmethod\n def unpack(cls, header, read, version):\n image_offset, = read(uint32)\n sw_version = normalise_version(read(version_struct))\n hw_model, = read(uint8)\n hw_version = normalise_version(read(version_struct))\n image = read.raw()\n return cls(sw_version, hw_model, hw_version, image)\n\n def pack(self, version):\n assert version >= 3\n image_offset = uint32.size + 2 * version_struct.size + uint8.size\n data = [uint32.pack(image_offset),\n version_struct.pack(*self.sw_version),\n uint8.pack(self.hw_model),\n version_struct.pack(*self.target_hw_version),\n self.image]\n return self._pack(data, version)\n\n\nclass CommandGaPollMeasurements(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass CommandGaPropagateTime(Message):\n # no members...\n @classmethod\n def unpack(cls, header, read, version):\n return cls()\n\n def pack(self, version):\n return self._pack([], version)\n\n\nclass CommandGpSwitchControl(Message):\n # ID\n meter1_struct = Struct('!q')\n # ID, connection type\n meter2_struct = Struct('!bq')\n\n def __init__(self, meter, control_manual):\n self.meter = meter\n self.control_manual = control_manual\n\n @classmethod\n def unpack(cls, header, read, version):\n control_manual = bool(header.flags)\n if version == 1:\n id, = read(cls.meter1_struct)\n meter = Meter(0, id)\n else:\n meter = Meter(*read(cls.meter2_struct))\n return cls(meter, control_manual)\n\n def pack(self, version):\n if version == 1:\n data = self.meter1_struct.pack(self.meter.id)\n else:\n data = self.meter2_struct.pack(*self.meter)\n flags = int(self.control_manual)\n return self._pack([data], version, flags)\n\n\nclass CommandGpSwitchRelay(Message):\n # ID\n meter1_struct = Struct('!q')\n # ID, connection type\n meter2_struct = Struct('!bq')\n\n def __init__(self, meter, relay_on):\n self.meter = meter\n self.relay_on = relay_on\n\n @classmethod\n def unpack(cls, header, read, version):\n relay_on = bool(header.flags)\n if version == 1:\n id, = read(cls.meter1_struct)\n meter = Meter(0, id)\n else:\n meter = Meter(*read(cls.meter2_struct))\n return cls(meter, relay_on)\n\n def pack(self, version):\n if version == 1:\n data = self.meter1_struct.pack(self.meter.id)\n else:\n data = self.meter2_struct.pack(*self.meter)\n flags = int(self.relay_on)\n return self._pack([data], version, flags)\n" }, { "alpha_fraction": 0.6158832907676697, "alphanum_fraction": 0.6369529962539673, "avg_line_length": 13.690476417541504, "blob_id": "e1adb387af5e3aabdc905a23003c4c2d5d740e8a", "content_id": "15cb75831a79ae9a4e29834cefb7b63497f64024", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 617, "license_type": "no_license", "max_line_length": 76, "num_lines": 42, "path": "/documentation/source/index.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": ".. GridPlatform documentation master file, created by\n sphinx-quickstart on Fri Oct 24 08:38:29 2014.\n You can adapt this file completely to your liking, but it should at least\n contain the root `toctree` directive.\n\nGridManager ApS Developer Documentation\n========================================\n\n.. Contents:\n\n.. toctree::\n :maxdepth: 2\n\n introduction\n\n domainmodel\n\n architecture\n\n security\n\n privacy\n\n developer_handbook\n\n deployment\n\n apps\n\n gridagent_server\n\n known_issues\n\n future_work\n\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n" }, { "alpha_fraction": 0.7844690680503845, "alphanum_fraction": 0.7844690680503845, "avg_line_length": 32.21052551269531, "blob_id": "c5572f72ad63cc7a85aba9c058e5fa7b9d787987", "content_id": "857f1dc76190ae7d93e619a7b518af8d6b3702ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 631, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/documentation/source/apps/gridplatform/token_auth.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Token Auth\n==========\n\nThe built-in token authentication of Django REST framework knows little about\nour encryption scheme. This app provides the necessary customizations to\ninclude the additionally needed information in the token string.\n\n.. autofunction:: gridplatform.token_auth.models.create_token\n\n.. autoclass:: gridplatform.token_auth.models.TokenData\n :members: provide_token, decrypt_password, lookup_token\n\n.. autoclass:: gridplatform.token_auth.authentication.EncryptionTokenAuthentication\n :members: authenticate, authenticate_credentials\n\nConfiguration\n-------------\n\n.. automodule:: gridplatform.token_auth.conf\n" }, { "alpha_fraction": 0.6085003018379211, "alphanum_fraction": 0.6088597178459167, "avg_line_length": 37.243988037109375, "blob_id": "cd3640176ae470327f821bad74c5dba50a40021b", "content_id": "d7d4797005e8935c329ec11b77164caf8e71807e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11129, "license_type": "no_license", "max_line_length": 78, "num_lines": 291, "path": "/gridplatform/rest/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nfrom collections import OrderedDict\n\nimport urlparse\nimport functools\n\nfrom django.core import urlresolvers\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.exceptions import ValidationError\nfrom django.utils import six\nfrom rest_framework import serializers\nfrom rest_framework import pagination\nimport rest_framework.reverse\n\nfrom .conf import settings\n\n\nField = serializers.Field\nCharField = serializers.CharField\nChoiceField = serializers.ChoiceField\nDateTimeField = serializers.DateTimeField\nSerializerMethodField = serializers.SerializerMethodField\nSerializer = serializers.Serializer\nModelSerializer = serializers.ModelSerializer\n\n\nclass HyperlinkedAutoResolveMixin(object):\n \"\"\"\n Mixin for :class:`.HyperlinkedRelatedField` and\n :class:`.HyperlinkedIdentityField` to allow them to generate correct\n relation URLs in the case of nested routing.\n \"\"\"\n @property\n def is_identity_field(self):\n return isinstance(self, serializers.HyperlinkedIdentityField)\n\n def build_kwargs(self, possibility, obj, parent_kwargs):\n for result, params in possibility:\n if params and 'format' not in params:\n # We found a usable match\n kwargs = {}\n for param in params:\n if param in parent_kwargs:\n # We only have request_kwargs in the case of\n # HyperlinkedIdentityFields, in which case we trust\n # parent_kwargs.\n kwargs[param] = parent_kwargs[param]\n elif self.is_identity_field and param != 'pk':\n # In the case of HyperlinkedIndentityFields and top\n # level list views.\n kwargs[param] = obj.id\n else:\n # As a last try we see if the model has a field with\n # same name as param. This is often the case for\n # HyperlinkedRelatedFields.\n kwargs[param] = getattr(obj, param)\n return kwargs\n raise AttributeError\n\n def get_url(self, obj, namespace_view_name, request, format):\n if self.is_identity_field:\n kwargs = request.parser_context['kwargs']\n else:\n kwargs = {}\n urlconf = urlresolvers.get_urlconf()\n resolver = urlresolvers.get_resolver(urlconf)\n parts = namespace_view_name.split(':')\n parts.reverse()\n view_name = parts[0]\n namespace_path = parts[1:]\n resolved_path = []\n ns_pattern = ''\n while namespace_path:\n namespace = namespace_path.pop()\n resolved_path.append(namespace)\n if namespace in resolver.app_dict and \\\n namespace not in resolver.app_dict[namespace]:\n # default instance namespace\n namespace = resolver.app_dict[namespace][0]\n try:\n pattern, resolver = resolver.namespace_dict[namespace]\n except KeyError:\n raise urlresolvers.NoReverseMatch(\n \"%s is not a registered namespace inside '%s'\" %\n (namespace, ':'.join(resolved_path)))\n ns_pattern += pattern\n if ns_pattern:\n resolver = urlresolvers.get_ns_resolver(\n ns_pattern, resolver)\n possibilities = resolver.reverse_dict.getlist(view_name)\n for possibility, pattern, defaults in possibilities:\n try:\n kwargs = self.build_kwargs(possibility, obj, kwargs)\n return rest_framework.reverse.reverse(\n namespace_view_name, kwargs=kwargs, request=request,\n format=format)\n except AttributeError:\n continue\n return super(HyperlinkedAutoResolveMixin, self).get_url(\n obj, namespace_view_name, request=request, format=format)\n\n\nclass HyperlinkedLookupMixin(object):\n \"\"\"\n Mixin for :class:`.HyperlinkedRelatedField` and\n :class:`.HyperlinkedIdentityField` to make easy to specify a\n :attr:`lookup_map` used for nesting routing.\n \"\"\"\n def __init__(self, *args, **kwargs):\n self.lookup_map = kwargs.pop('lookup_map', None)\n super(HyperlinkedLookupMixin, self).__init__(*args, **kwargs)\n\n def get_url(self, obj, view_name, request, format):\n if self.lookup_map:\n kwargs = {\n key: functools.reduce(getattr, value.split('.'), obj)\n for key, value in self.lookup_map.items()\n }\n return rest_framework.reverse.reverse(\n view_name, kwargs=kwargs, request=request, format=format)\n return super(HyperlinkedLookupMixin, self).get_url(\n obj, view_name, request=request, format=format)\n\n\nclass HyperlinkedSubclassRelatedMixin(object):\n \"\"\"\n Mixin for :class:`.HyperlinkedRelatedField` to add support for models that\n have polymorphic behaviour.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # view_name isn't required for subclass related models\n kwargs['view_name'] = kwargs.get('view_name', '')\n super(HyperlinkedSubclassRelatedMixin, self).__init__(*args, **kwargs)\n\n def initialize(self, parent, field_name):\n super(HyperlinkedSubclassRelatedMixin, self).initialize(\n parent, field_name)\n if getattr(self, 'queryset', None) is None:\n manager = getattr(\n self.parent.opts.model, self.source or field_name)\n if hasattr(manager, 'related'): # Forward\n self.queryset = manager.related.model._default_manager.all()\n else: # Reverse\n self.queryset = manager.field.rel.to._default_manager.all()\n model = self.queryset.model\n self._subclass_related = hasattr(model, 'subclass')\n\n def _subclass_related_view_name(self, obj):\n subclass_instance = obj.subclass_instance\n format_kwargs = {\n 'app_label': subclass_instance._meta.app_label,\n 'model_name': subclass_instance._meta.object_name.lower()\n }\n return ':'.join([\n settings.REST_API_NAMESPACE,\n '{}-detail'.format(settings.REST_SERIALIZER_VIEW_NAME_BASE) %\n format_kwargs\n ])\n\n def get_url(self, obj, view_name, request, format):\n if self._subclass_related:\n try:\n return super(HyperlinkedSubclassRelatedMixin, self).get_url(\n obj,\n view_name=self._subclass_related_view_name(obj),\n request=request, format=format)\n except urlresolvers.NoReverseMatch:\n pass\n return super(HyperlinkedSubclassRelatedMixin, self).get_url(\n obj, view_name=view_name, request=request, format=format)\n\n def from_native(self, value):\n if self._subclass_related:\n try:\n http_prefix = value.startswith(('http:', 'https:'))\n except AttributeError:\n msg = self.error_messages['incorrect_type']\n raise ValidationError(msg % type(value).__name__)\n if http_prefix:\n value = urlparse.urlparse(value).path\n prefix = urlresolvers.get_script_prefix()\n if value.startswith(prefix):\n value = '/' + value[len(prefix):]\n try:\n match = urlresolvers.resolve(value)\n except Exception:\n raise ValidationError(self.error_messages['no_match'])\n try:\n obj = self.get_object(\n self.queryset, match.view_name, match.args, match.kwargs)\n except (ObjectDoesNotExist, TypeError, ValueError):\n # NOTE: This error might actually have been an\n # \"incorrect_match\".\n raise ValidationError(self.error_messages['does_not_exist'])\n if match.view_name != self._subclass_related_view_name(obj):\n raise ValidationError(self.error_messages['incorrect_match'])\n return obj\n else:\n return super(\n HyperlinkedSubclassRelatedMixin, self).from_native(value)\n\n\nclass HyperlinkedRelatedField(\n HyperlinkedSubclassRelatedMixin,\n HyperlinkedLookupMixin,\n HyperlinkedAutoResolveMixin,\n serializers.HyperlinkedRelatedField):\n \"\"\"\n The GridPlatform default HyperlinkedRelatedField.\n \"\"\"\n pass\n\n\nclass HyperlinkedIdentityField(\n HyperlinkedLookupMixin,\n HyperlinkedAutoResolveMixin,\n serializers.HyperlinkedIdentityField):\n \"\"\"\n The GridPlatform default HyperlinkedIdentityField.\n \"\"\"\n pass\n\n\nclass DefaultSerializerOptions(serializers.HyperlinkedModelSerializerOptions):\n \"\"\"\n Options class for the :class:`.DefaultSerializer`\n \"\"\"\n def __init__(self, meta):\n super(DefaultSerializerOptions, self).__init__(meta)\n if meta.model and \\\n getattr(meta.model, 'subclass', None) and \\\n 'subclass' not in self.exclude:\n # Don't try to generate hyperlink to ContentType\n self.exclude += ('subclass',)\n\n\nclass DefaultSerializer(serializers.HyperlinkedModelSerializer):\n \"\"\"\n The GridPlatform default serializer.\n \"\"\"\n _options_class = DefaultSerializerOptions\n _hyperlink_field_class = HyperlinkedRelatedField\n _hyperlink_identify_field_class = HyperlinkedIdentityField\n _default_view_name = ':'.join([\n settings.REST_API_NAMESPACE,\n '{}-detail'.format(settings.REST_SERIALIZER_VIEW_NAME_BASE)\n ])\n\n def get_pk_field(self, model_field):\n # Always include pk field\n return self.get_field(model_field)\n\n def reverse(self, viewname, *args, **kwargs):\n request = kwargs.pop('request', None) or self.context.get('request')\n url = urlresolvers.reverse(viewname, *args, **kwargs)\n if request:\n return request.build_absolute_uri(url)\n return url\n\n @property\n def filter_fields(self):\n return getattr(self.context['view'], 'filter_fields', [])\n\n def metadata(self):\n def metadata_with_filter_fields(field_name, field):\n metadata = field.metadata()\n if field_name in self.filter_fields:\n metadata['filter_field'] = field_name\n else:\n metadata['filter_field'] = None\n return field_name, metadata\n\n return OrderedDict([\n metadata_with_filter_fields(field_name, field)\n for field_name, field in six.iteritems(self.fields)\n ])\n\n\nclass DefaultPaginationSerializer(pagination.PaginationSerializer):\n \"\"\"\n The GridPlatform default serializer when pagination is needed\n \"\"\"\n filter_fields = SerializerMethodField('get_filter_fields')\n\n def get_filter_fields(self, obj):\n return getattr(self.context['view'], 'filter_fields', [])\n" }, { "alpha_fraction": 0.665680468082428, "alphanum_fraction": 0.6807692050933838, "avg_line_length": 35.739131927490234, "blob_id": "53ea3eb69573522de344ae4e26a9972a21de180c", "content_id": "ab788b03db94eadc381e0f0a0f3dc983964ce5a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3380, "license_type": "no_license", "max_line_length": 79, "num_lines": 92, "path": "/gridagentserver-protocol/gridagentserver_protocol/twisted_protocol_test.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from struct import Struct\nimport copy\nimport datetime\nimport random\n\nfrom twisted.trial import unittest\nfrom twisted.test import proto_helpers\nfrom twisted.internet.protocol import ServerFactory\n\nfrom . import PROTOCOL_VERSION, SECRET\nfrom client_messages import NotificationGpState\nfrom datatypes import Meter\nfrom encryption import Encrypter\nfrom twisted_protocol import (\n EncryptedProtocol,\n BaseAgentProtocol,\n BaseAgentProtocolFactory,\n)\n\n# version, id/nonce\nhandshake_struct = Struct('!IQ')\nuint64 = Struct('!Q')\n\n\ndef make_key(client_id, nonce):\n return bytearray(map(lambda a, b, c: (a or 0) ^ (b or 0) ^ (c or 0),\n bytearray(SECRET),\n bytearray(uint64.pack(client_id)),\n bytearray(uint64.pack(nonce))))\n\n\nclass EncryptionProtocolFactory(ServerFactory):\n protocol = EncryptedProtocol\n\n\nclass EncryptionProtocolTestCase(unittest.TestCase):\n def setUp(self):\n factory = EncryptionProtocolFactory()\n self.proto = factory.buildProtocol(('127.0.0.1', 0))\n self.tr = proto_helpers.StringTransport()\n self.proto.makeConnection(self.tr)\n\n def test_handshake(self):\n handshake = handshake_struct.pack(2, 0x3c970e1e8e4e)\n self.proto.dataReceived(handshake)\n version, nonce = handshake_struct.unpack(self.tr.value())\n self.assertEqual(version, PROTOCOL_VERSION)\n\n def test_init_encryption(self):\n client_id = 0x3c970e1e8e4e\n client_version = 2\n handshake = handshake_struct.pack(client_version, client_id)\n self.proto.dataReceived(handshake)\n server_version, nonce = handshake_struct.unpack(self.tr.value())\n key = make_key(client_id, nonce)\n encrypter = Encrypter(key)\n self.assertEqual(encrypter, self.proto._encrypt)\n self.assertEqual(encrypter, self.proto._decrypt)\n\n\nclass BaseAgentProtocolTestCase(unittest.TestCase):\n def setUp(self):\n self.factory = BaseAgentProtocolFactory()\n self.proto = self.factory.buildProtocol(('127.0.0.1', 0))\n self.tr = proto_helpers.StringTransport()\n self.proto.makeConnection(self.tr)\n self.agent_mac = random.randint(0, 0xffffffffffff) # 6 bytes...\n client_version = 2\n handshake = handshake_struct.pack(client_version, self.agent_mac)\n self.proto.dataReceived(handshake)\n server_version, nonce = handshake_struct.unpack(self.tr.value())\n key = make_key(self.agent_mac, nonce)\n self.encrypter = Encrypter(key)\n self.decrypter = copy.deepcopy(self.encrypter)\n\n def test_register(self):\n self.assertEqual(self.factory.handlers.keys(), [self.agent_mac])\n\n def test_unregister(self):\n self.assertEqual(self.factory.handlers.keys(), [self.agent_mac])\n self.proto.connectionLost()\n self.assertEqual(self.factory.handlers.keys(), [])\n\n def test_message(self):\n meter = Meter(2, 24)\n timestamp = datetime.datetime.now().replace(microsecond=0)\n notification = NotificationGpState(meter, True, False, True, timestamp)\n data = self.encrypter(notification.pack(2))\n splitpoint = random.randint(0, len(data))\n self.proto.dataReceived(data[:splitpoint])\n self.proto.dataReceived(data[splitpoint:])\n self.assertEqual(self.proto.incoming.pending, [notification])\n" }, { "alpha_fraction": 0.6502557396888733, "alphanum_fraction": 0.6518542170524597, "avg_line_length": 37.93775939941406, "blob_id": "45803e5680ab4081f314c703672810b041b62e88", "content_id": "91529d0220d8c195b5d4b758038d0c34c0cd095b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9384, "license_type": "no_license", "max_line_length": 79, "num_lines": 241, "path": "/gridplatform/datasequences/models/base.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.db import models\nfrom django.db.models import Q\nfrom django.forms import ValidationError\nfrom django.template import defaultfilters\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import StoredSubclassCustomerBoundManager\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import deprecated\nfrom gridplatform.utils.decorators import virtual\n\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.models import TimestampRangeModelMixin\nfrom gridplatform.utils.managers import TimestampRangeManagerMixin\nfrom gridplatform.utils.validators import clean_overlapping\n\n\ndef is_clock_hour(timestamp):\n \"\"\"\n :return: True if given timestamp is on the hour.\n\n :param timestamp: The given timestamp.\n \"\"\"\n return timestamp.minute == timestamp.second == timestamp.microsecond == 0\n\n\ndef is_five_minute_multiplum(timestamp):\n \"\"\"\n :return: True if given timestamp is on a five minute multiplum after the\n hour.\n\n :param timestamp: The given timestamp.\n \"\"\"\n return timestamp.minute % 5 == timestamp.second == \\\n timestamp.microsecond == 0\n\n\nclass DataSequenceBase(\n EncryptionCustomerFieldMixin, EncryptedModel, StoreSubclass):\n \"\"\"\n Base class for all data sequences. This is an abstract model, so it cannot\n be queried directly.\n\n :ivar customer: The owning :class:`.Customer`.\n :ivar name: The name of this data sequence.\n :objects: The manager of data sequences are by default a\n :class:`.StoredSubclassCustomerBoundManager`.\n \"\"\"\n name = EncryptedCharField(_('name'), max_length=200, blank=False)\n\n objects = StoredSubclassCustomerBoundManager()\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n @virtual\n def __unicode__(self):\n return self.name_plain\n\n def next_valid_date(self, date, timezone):\n \"\"\"\n Get the first date after the specified that has overlap with a period\n for this datasequence --- ``None`` if no such date exists.\n \"\"\"\n end_of_day = timezone.localize(\n datetime.datetime.combine(\n date + datetime.timedelta(days=1), datetime.time()))\n future_period = self.period_set.filter(\n Q(to_timestamp__gt=end_of_day) | Q(to_timestamp__isnull=True)\n ).order_by('from_timestamp').first()\n if future_period is None:\n # No periods ending after the specified date --- no future data.\n return None\n elif future_period.from_timestamp <= end_of_day:\n # Found period contains > epsilon of day after specified date.\n return date + datetime.timedelta(days=1)\n else:\n # Found period contains > epsilon of day of its from_timestamp.\n return timezone.normalize(\n future_period.from_timestamp.astimezone(timezone)).date()\n\n def previous_valid_date(self, date, timezone):\n \"\"\"\n Get the last date before the specified that has overlap with a period\n for this datasequence --- `None` if no such date exists.\n \"\"\"\n beginning_of_day = timezone.localize(\n datetime.datetime.combine(date, datetime.time()))\n past_period = self.period_set.filter(\n from_timestamp__lt=beginning_of_day).order_by(\n 'from_timestamp').last()\n if past_period is None:\n return None\n elif past_period.to_timestamp is None or \\\n past_period.to_timestamp >= beginning_of_day:\n return date - datetime.timedelta(days=1)\n else:\n # midnight is 00:00 --- so this might give the day after the last\n # one we have data for...\n past_to_time = timezone.normalize(\n past_period.to_timestamp.astimezone(timezone))\n if past_to_time.replace(tzinfo=None).time() == datetime.time():\n return past_to_time.date() - datetime.timedelta(days=1)\n else:\n return past_to_time.date()\n\n @deprecated\n def get_recursive_condense_resolution(self, resolution):\n if condense.RESOLUTIONS.index(resolution) >= \\\n condense.RESOLUTIONS.index(condense.DAYS):\n return None\n else:\n return condense.next_resolution(resolution)\n\n def validate_requirements(self, from_date, to_date):\n \"\"\"\n Validates offline tolerance requirements in given date range.\n\n :param from_date: First date in the given date range.\n :param to_date: Last date in the given date range.\n :rtype: dict\n\n :see: :meth:`.OfflineToleranceMixin.validate_requirement`.\n \"\"\"\n invalidations = {}\n if hasattr(self, 'offlinetolerance'):\n offlinetolerance_validations = \\\n self.offlinetolerance.validate_requirement(\n from_date, to_date)\n if offlinetolerance_validations:\n invalidations[\n 'offlinetolerance'] = offlinetolerance_validations\n return invalidations\n\n\nclass PeriodBaseManager(TimestampRangeManagerMixin, models.Manager):\n \"\"\"\n Default manager for :class:`.PeriodBase`.\n \"\"\"\n use_for_related_fields = True\n\n\nclass PeriodBase(TimestampRangeModelMixin, models.Model):\n \"\"\"\n Base class for data sequence periods. This is an abstract model, and has\n :class:`.TimestampRangeModelMixin` mixed into it.\n\n Assumes concrete specialization has a ``datasequence`` foreign key to some\n :class:`.DataSequenceBase` specialization.\n\n :ivar objects: The default manager for data sequence periods is\n :class:`.PeriodBaseManager`\n\n :ivar _clean_overlapping_periods: Can be used to disable overlap checking\n by :meth:`.PeriodBase.clean`. This is needed when multiple periods for\n the same data sequence are updated simultaneously via a formset. The\n formset should then make sure to validate the periods for overlap. The\n default value is ``True`` (i.e. overlap checking is enabled by\n default). See also :meth:`.PeriodBase.clean_overlapping_periods`.\n \"\"\"\n objects = PeriodBaseManager()\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n def __init__(self, *args, **kwargs):\n super(PeriodBase, self).__init__(*args, **kwargs)\n\n # Set to false to prevent clean of overlapping periods against the db.\n # it is a bug if formsets don't do this.\n self._clean_overlapping_periods = True\n\n def __unicode__(self):\n timezone = self.datasequence.customer.timezone\n formatted_from_timestamp = defaultfilters.date(\n timezone.normalize(\n self.from_timestamp.astimezone(timezone)),\n 'SHORT_DATETIME_FORMAT')\n if self.to_timestamp:\n formatted_to_timestamp = defaultfilters.date(\n timezone.normalize(\n self.to_timestamp.astimezone(timezone)),\n 'SHORT_DATETIME_FORMAT')\n else:\n formatted_to_timestamp = _('unspecified')\n return ugettext(\n '{from_timestamp} - {to_timestamp}: {datasequence}').format(\n from_timestamp=formatted_from_timestamp,\n to_timestamp=formatted_to_timestamp,\n datasequence=self.datasequence)\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.from_timestamp`` is not on the hour.\n :raise ValidationError: If ``self.to_timestamp`` is not on the hour.\n :raise ValidationError: If ``self._clean_overlapping_periods`` is True\n and there are overlapping periods.\n\n :see: :meth:`.PeriodBase.clean_overlapping_periods`.\n \"\"\"\n super(PeriodBase, self).clean()\n if self.from_timestamp and not is_clock_hour(self.from_timestamp):\n raise ValidationError(_('Period must start on a clock hour'))\n if self.to_timestamp and not is_clock_hour(self.to_timestamp):\n raise ValidationError(_('Period must end on a clock hour'))\n\n if self._clean_overlapping_periods and hasattr(self, 'datasequence'):\n periods = [\n period\n for period in self.datasequence.period_set.all()\n if period.id != self.id]\n periods.append(self)\n self.clean_overlapping_periods(periods)\n\n @cached_property\n def unit(self):\n return self._get_unit()\n\n @staticmethod\n def clean_overlapping_periods(periods):\n \"\"\"\n At all times no two periods belonging to the same data sequence must be\n overlapping. This needs to be ensured towards the database from model\n forms (the default) and towards other surviving instances in inline\n formsets (set _clean_overlapping_periods to False and call this method\n explicitly in formset.clean()).\n \"\"\"\n clean_overlapping(periods)\n" }, { "alpha_fraction": 0.732408344745636, "alphanum_fraction": 0.7356518507003784, "avg_line_length": 58.35293960571289, "blob_id": "b21ec0f5f55f17544cf5b9b3389438e795586f28", "content_id": "78e7eb1812425c67c54040822b8734a050a39b8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 11099, "license_type": "no_license", "max_line_length": 383, "num_lines": 187, "path": "/documentation/source/developer_handbook.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "******************\nDeveloper Handbook\n******************\n\n\nSystem requirements\n===================\n\nThe servers on which the software is currently deployed run Ubuntu 14.04 LTS, and this is also the recommended development environment.\n\nUsing other Unix-like systems should be possible, though we cannot provide specific lists of package names to install for those.\n\nWindows is not supported. At least some of the third-party Python libraries used involve C extensions that are distributed in source code form, which are difficult to install under Windows.\\ [#compiler]_ Various scripts are written as Bash shell-scripts. It may be *possible* to run the software under Windows, but running it in a Linux VM is likely to be a simpler solution.\n\n.. [#compiler] According to Python documentation, under Windows, extensions should preferably be compiled with the same version of Microsoft Visual C++ as used to compile the Python interpreter.\n\n\nRepository root folder structure\n================================\n\nThe code is split up into four major components:\n\n- :file:`documentation/`: This documentation.\n- :file:`energymanager/`: Energy Manager. An example Energy Management System\n based on the GridPlatform.\n- :file:`gridagentserver/`: GridAgent Server code base.\n- :file:`gridagentserver-protocol/`: GridAgent Server protocol code (used by GridAgent Server).\n- :file:`gridplatform/`: The GridPlatform code base.\n- :file:`legacy/`: GridPlatform 2.0 code base.\n- :file:`qunit/`: QUnit (http://qunitjs.com/).\n- :file:`requirements/`: PyPI requirement files.\n- :file:`scripts/`: Scripts for easing the used of the system once deployed.\n- :file:`static/`: Static website assets.\n- :file:`templates/`: Top level Django templates that did not fit anywhere else.\n\n\nInstalling needed software\n==========================\n\n\n\"Global\" software installation\n------------------------------\n\nFor local development, you will need:\n\n* Python 2.7.\n* virtualenv to enable \"local\" installation of Python libraries.\n* An appropriate C-compiler/build tools and Python development headers, to support installation of Python libraries that include C-extensions.\n* PostgreSQL and development headers for building a client library. The PostgreSQL DBMS is used for deployment, and due to subtle differences between DBMS behavior, using the same locally simplifies development.\\ [#dbms]_\n* Memcached and development headers for building a client library. Memcached is used for \"cache\" and for communicating computed results from background tasks to the web-part.\n* libjpeg and development headers to support resizing uploaded images.\n* The RabbitMQ message queue server, used to schedule background tasks.\n* LaTeX and various TeX packages used for building PDF reports.\n\n.. [#dbms] This is a tradeoff. Using different database systems may help ensure that the application can later be deployed with a different DBMS for production --- but the \"overhead\" can be significant. Use of the Django ORM for database access which *should* preserve this portability, though database schema migrations in particular can be difficult to express without \"raw\" SQL.\n\nOn a computer with Ubuntu 14.04 LTS, this can all be installed with::\n\n sudo apt-get install \\\n python-virtualenv \\\n virtualenvwrapper \\\n python-dev \\\n build-essential \\\n libgmp-dev \\\n postgresql \\\n libpq-dev \\\n memcached \\\n libmemcached-dev \\\n libjpeg-dev \\\n rabbitmq-server \\\n texlive-latex-recommended \\\n texlive-xetex \\\n fonts-linuxlibertine \\\n ttf-mscorefonts-installer \\\n texlive-latex-extra \\\n texlive-science \\\n texlive-fonts-recommended\n\nOn deployment, you will also need:\n\n* nginx (or a different HTTP-server) to serve \"static\" files, handle SSL and communicate with the backend WSGI server.\n* A local mail server, to enable the system to send error mails and any other emails. We use Postfix.\n\nOn a computer with Ubuntu 14.04 LTS, this can all be installed with::\n\n sudo apt-get install \\\n nginx \\\n postfix\n\n\nPython packages\n---------------\n\nCreate virtual Python environment and set the current directory as \"working directory\" for it::\n\n mkvirtualenv gridportal\n setvirtualenvproject\n\nVarious Python packages are specified in ``requirements/base.txt``, ``requirements/local.txt`` and ``requirements/production.txt``; including short comments on what they do/what we use them for. For development, the \"base\" and \"local\" packages should be installed::\n\n pip install --requirement=requirements/local.txt\n\nThis will take some time, as a number of packages are downloaded, and some C-extensions compiled.\n\nTo later use this virtual Python environment::\n\n workon gridportal\n\n\nSetting up a database server locally\n====================================\n\nFor development, the current user needs to be able to create and delete databases, as a \"new\" database is created and destroyed for unit test runs.\nThe easiest option is to make the current user a PostgreSQL superuser::\n\n sudo -u postgres createuser --superuser $USER\n\nIf/when the current user is PostgreSQL superuser, creating the database with the current user as owner is simple::\n\n createdb --encoding=utf-8 portal\n\nWith the Python virtual environment with Django and other packages installed active (``workon gridportal``), database the tables may be set up::\n\n ./manage.py syncdb --noinput\n ./manage.py migrate --all\n\n\n.. _developer-handbook-scripts-and-commands:\n\nScripts and commands\n====================\n\nTo get started/run the software locally, you will need to use:\n\n* ``./manage.py runserver``: Run the Django development server. By default, it will listen on port 8000.\n* ``./manage.py celery worker``: Run a Celery worker process. This is used for asynchroneous/background tasks like collecting data for graphs or compiling PDF reports.\n\nFor other commands that are built-in or provided by third-party Django apps, refer to their respective documentation.\n\n\nCustom Django management commands\n---------------------------------\n\n* ``./manage.py generate_cache``: Generate the five-minute-/hour-\"cache\" for accumulated data sources.\n* ``./manage.py get_agent_events``: Get event log for a specified GridAgent.\n* ``./manage.py hickup_detection``: Check for specific outliers/measurement errors in raw data.\n* ``./manage.py import_energinet_co2``: Import CO2 data from Energinet.dk to \"legacy\" indexes. Requires an Energinet.dk FTP-account, with login-credentials specified in settings ``ENERGINET_CO2_USER`` and ``ENERGINET_CO2_PASS``.\n* ``./manage.py setup_nordpool``: Set up \"legacy\" indexes for import of Nordpool spot prices.\n* ``./manage.py import_nordpool``: Import Nordpool spot prices to \"legacy\" indexes. Requires a Nordpool FTP-account, with login-credentials specified in settings ``NORDPOOL_USER`` and ``NORDPOOL_PASS``.\n* ``./manage.py import_nordpool_spot_prices``: Import Nordpool spot prices to global datasources. Requires a Nordpool FTP-account, with login-credentials specified in settings ``NORDPOOL_USER`` and ``NORDPOOL_PASS``.\n* ``./manage.py ruleengine``: Run the GridPlatform rule engine.\n* ``./manage.py send_rules``: Send rules that are evaluated on GridAgents to the GridAgents.\n* ``./manage.py check_db_connection``: Check whether Django can connect to the database backend; exits with code 0 for success, 1 for failure.\n* ``./manage.py fix_contenttypes_and_permissions``: Add/remove ``ContentType`` entries to match the current set of existing ``Model`` classes; create ``Permission`` instances that exist in code but are missing in the database. Mismatch may be caused by schema migrations that fail to fire the appropriate events on ``Model`` changes or the addition of new permissions in code.\n* ``./manage.py rebuild_group_tree``: Rebuilds the measurement point group trees used in the left menu in GridPortal 2.0. There is a known issue regarding the group tree being corrupted and this a short term fix. This command is run by cron on the servers at every midnight.\n\n\nScripts\n-------\n\n* ``fixture_hack.sh``: Script to wipe the local cache and database, recreate tables and populate the database with dynamic \"fixture\" data.\n* ``compilemessages.sh``: Call the Django translation system to build ``gettext`` ``.mo`` files from ``.po`` files.\n* ``rabbitmq-check.sh``: Check whether there are more than 100 pending messages in any RabbitMQ queues. This may indicate that task arrive to be run in the background faster than they are currently processed.\n* ``run_all_tests.py``: Run unit tests with coverage check.\n* ``test_javascript.sh``: Run QUnit unit-tests for JavaScript with PhantomJS.\n* ``translate.sh``: Call the Django translation system to create ``.po``-files for the Danish locale for each Django app, open the resulting files with \"missing\" translations in the default editor, and compile the ``.po``-files to ``.mo``-files.\n\n\nMakefile rules\n--------------\n\n* ``make dist``: Build ``gridplatform-<branch>-<commit>.tar.gz`` from last commit with ``<branch>-<commit>`` as version. Use to build untagged \"test\" releases.\n* ``make release``: Build ``gridplatform-<tag>[-<commit>].tar.gz`` from last commit with ``<tag>[-<commit>]`` as version. Use after git tag to build relases --- the \"commit\"-part of the version is absent when last commit *is* the tag.\n* ``make makemessages``: Run ``django-admin makemessages`` with appropriate parameters to create ``.po``-files for Danish and Spanish translation for each Django app in the project.\n* ``make compilemessages``: Run ``django-admin compilemessages`` to generate ``.mo``-files from ``.po``-files for each Django app in the project.\n* ``make flake8``: Run the ``flake8`` checker on Python code files changed since the last commit according to git.\n* ``make test``: Run unit tests for all Django apps in the project.\n* ``make test-rerun``: Run only those unit tests that failed on last test run.\n* ``make test-coverage``: Run unit tests with code coverage check.\n* ``make selenium-test``: Run normal unit tests *and* Selenium-based tests. This requires ``chromedriver`` to be present in ``PATH`` or in the current directory.\n* ``make tags``, ``make TAGS``: Build Emacs tag file for the Python code.\n* ``make test-failures``: Run only those unit tests that failed on last test run. This version includes workarounds for the test runners failure to correctly identify the failing tests in case of issues with Python module imports.\n* ``make parallel-test``: Run unit tests with separate test databases and as separate \"jobs\" per Django app tested. This allows tests to be run in parallel, e.g. as ``make parallel-test --jobs=20``.\n* ``make scss``: Build ``legacy/website/static/style.css`` from ``legacy/website/static/style.scss`` and the SCSS files in ``legacy/website/static/scss/``.\n* ``make html``: Compile documentation to HTML in ``documentation/build/``.\n* ``make pdf``: Compile documentation to PDFs as ``GridPlatform.pdf`` and ``GridPlatformDomainModel.pdf``.\n* ``make clean``: Delete Python bytecode files, unit test \"rerun\"-files, log files and the documentation PDF documents.\n" }, { "alpha_fraction": 0.5657553672790527, "alphanum_fraction": 0.5726618766784668, "avg_line_length": 35.19791793823242, "blob_id": "1275f76b87d2316eedbcdc89d05acfa111bb65c5", "content_id": "f5bf93333dbbfa9e94896a0b46992c98dc8b657e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3475, "license_type": "no_license", "max_line_length": 76, "num_lines": 96, "path": "/legacy/display_indexes/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport math\n\nfrom django import template\nfrom django.shortcuts import get_object_or_404\nfrom django.template.defaultfilters import floatformat\nfrom django.utils.translation import ugettext as _\n\nfrom celery import shared_task\n\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.indexes.models import Index\nfrom gridplatform.trackuser.tasks import trackuser_task\n\n\ndef get_ticks(count, maximum):\n return int(math.floor(count / math.ceil(float(count) / float(maximum))))\n\n\n@trackuser_task\n@shared_task(name='legacy.display_indexes.tasks.graph_task')\ndef graph_task(pk, from_timestamp, to_timestamp):\n index = get_object_or_404(Index, pk=pk).subclass_instance\n\n class RuntimeGraph(Graph):\n class Meta:\n proxy = True\n\n def __init__(self, index, *args, **kwargs):\n super(RuntimeGraph, self).__init__(*args, **kwargs)\n self.index = index\n\n def _get_caption_text(self, data_samples, converter, is_rate,\n is_condensed):\n \"\"\"\n Override of L{AbstractGraph._condense_caption_text}.\n\n @note: The is_condensed paramter is ignored for index so far.\n\n \"\"\"\n floatformat_decimals = '-3'\n if is_rate:\n if data_samples:\n min_value = min(\n sample.physical_quantity for sample in data_samples)\n\n max_value = max(\n sample.physical_quantity for sample in data_samples)\n\n caption = _('Min: {{ min_value }} {{ unit }} | '\n 'Max: {{ max_value }} {{ unit }}')\n subcontext = template.Context({\n 'min_value': converter.extract_value(min_value),\n 'max_value': converter.extract_value(max_value),\n 'unit': converter.get_display_unit()})\n else:\n subcontext = template.Context({})\n caption = _('No values in this range.')\n\n for elem in ['min_value', 'max_value']:\n if elem in subcontext:\n subcontext[elem] = floatformat(\n subcontext[elem], floatformat_decimals)\n return template.Template(unicode(caption)).render(subcontext)\n\n graph = RuntimeGraph(index)\n\n days = int((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(days=1).total_seconds())\n\n if days <= 1:\n hours = int((to_timestamp - from_timestamp).total_seconds() / 3600)\n result = graph.get_graph_data(\n get_ticks(hours, 5), from_timestamp,\n to_timestamp=to_timestamp, data_series_set=[index])\n\n elif days < 31:\n # display hours\n result = graph.get_graph_data(\n get_ticks(days, 12),\n from_timestamp, to_timestamp=to_timestamp,\n data_series_set=[index])\n else:\n result = graph.get_graph_data(\n get_ticks(days, 12), from_timestamp,\n to_timestamp=to_timestamp, data_series_set=[index])\n\n result[\"options\"].update({\"grid\": {\"outlineWidth\": 0,\n \"verticalLines\": True}})\n result[\"options\"][\"yaxis\"].update({\"titleAngle\": 90})\n result[\"options\"].update({\"HtmlText\": False})\n return result\n" }, { "alpha_fraction": 0.7278481125831604, "alphanum_fraction": 0.7295136451721191, "avg_line_length": 46.650794982910156, "blob_id": "f9df463582d6c16721a110282628e352ad451d3a", "content_id": "4bde76ae98fa923ef7369a5cb6f33f0fa4147794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9006, "license_type": "no_license", "max_line_length": 79, "num_lines": 189, "path": "/legacy/legacy_utils/preferredunits.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils import choices_extract_python_identifier\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.preferredunits import AbsoluteCelsiusUnitConverter\nfrom gridplatform.utils.preferredunits import AbsoluteFahrenheitUnitConverter\nfrom gridplatform.utils.preferredunits import AreaENPIUnitConverter\nfrom gridplatform.utils.preferredunits import EfficiencyUnitConverter\nfrom gridplatform.utils.preferredunits import PersonsENPIUnitConverter\nfrom gridplatform.utils.preferredunits import PhysicalQuantity\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionAENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionBENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionCENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionDENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionEENPIUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionUnitConverter\nfrom gridplatform.utils.preferredunits import RelativeCelsiusUnitConverter\nfrom gridplatform.utils.preferredunits import RelativeFahrenheitUnitConverter\nfrom gridplatform.utils.preferredunits import KvarUnitConverter\nfrom gridplatform.utils.preferredunits import KvarhUnitConverter\nfrom gridplatform.utils.preferredunits import PowerFactorUnitConverter\nfrom legacy.measurementpoints.fields import DataRoleField\n\n\ndef get_preferred_unit_converter(\n role, utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n customer=None, unit=None):\n \"\"\"\n Get preferred unit converter for the given arguments.\n\n @param role: A data role as defined in L{DataRoleField.CHOICES}\n\n @keyword utility_type: An optional utility type as defined in\n L{utilitytypes.METER_CHOICES}.\n\n @keyword customer: An optional customer instance. This is required in\n contexts such as Celery tasks, where get_customer() does not work.\n\n @precondition: If C{customer} is not given, get_customer() returns a\n Customer instance.\n\n @raise ValueError: This exception is raised if no preferred unit object can\n be found for the given arguments.\n \"\"\"\n if customer is None:\n customer = get_customer()\n assert customer is not None\n\n assert role in (db_value for db_value, _ in DataRoleField.CHOICES)\n assert utility_type in (db_value for db_value, _ in\n utilitytypes.OPTIONAL_METER_CHOICES), utility_type\n\n if role == DataRoleField.RELATIVE_TEMPERATURE:\n if customer.temperature == 'celsius':\n return RelativeCelsiusUnitConverter()\n elif customer.temperature == 'fahrenheit':\n return RelativeFahrenheitUnitConverter()\n\n elif role == DataRoleField.ABSOLUTE_TEMPERATURE:\n if customer.temperature == 'celsius':\n return AbsoluteCelsiusUnitConverter()\n elif customer.temperature == 'fahrenheit':\n return AbsoluteFahrenheitUnitConverter()\n\n elif role in (DataRoleField.CONSUMPTION,\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION):\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return PhysicalUnitConverter(customer.electricity_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return PhysicalUnitConverter(customer.gas_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n return PhysicalUnitConverter(customer.water_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return PhysicalUnitConverter(customer.oil_consumption)\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return PhysicalUnitConverter(customer.heat_consumption)\n\n elif role == DataRoleField.POWER:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return PhysicalUnitConverter(customer.electricity_instantaneous)\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return PhysicalUnitConverter(customer.heat_instantaneous)\n\n elif role == DataRoleField.REACTIVE_POWER:\n return KvarUnitConverter()\n\n elif role == DataRoleField.REACTIVE_ENERGY:\n return KvarhUnitConverter()\n\n elif role == DataRoleField.POWER_FACTOR:\n return PowerFactorUnitConverter()\n\n elif role == DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return PersonsENPIUnitConverter(customer.electricity_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return PersonsENPIUnitConverter(customer.gas_consumption)\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return PersonsENPIUnitConverter(customer.heat_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return PersonsENPIUnitConverter(customer.oil_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n return PersonsENPIUnitConverter(customer.water_consumption)\n\n elif role == DataRoleField.CONSUMPTION_UTILIZATION_AREA:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return AreaENPIUnitConverter(customer.electricity_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return AreaENPIUnitConverter(customer.gas_consumption)\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return AreaENPIUnitConverter(customer.heat_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return AreaENPIUnitConverter(customer.oil_consumption)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n return AreaENPIUnitConverter(customer.water_consumption)\n\n elif role == DataRoleField.VOLUME_FLOW:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return PhysicalUnitConverter(customer.gas_instantaneous)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return PhysicalUnitConverter(customer.oil_instantaneous)\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n return PhysicalUnitConverter(customer.water_instantaneous)\n\n elif role == DataRoleField.COST and unit is not None:\n normalized_unit = PhysicalQuantity(1, unit).units\n assert re.match('currency_[a-z]{3}', normalized_unit)\n return PhysicalUnitConverter(normalized_unit)\n\n elif role == DataRoleField.HEATING_DEGREE_DAYS:\n return PhysicalUnitConverter('kelvin*day')\n\n elif role == DataRoleField.CO2:\n return PhysicalUnitConverter('tonne')\n\n elif role == DataRoleField.VOLTAGE:\n return PhysicalUnitConverter('volt')\n\n elif role == DataRoleField.CURRENT:\n return PhysicalUnitConverter('ampere')\n\n elif role == DataRoleField.PRODUCTION:\n return ProductionUnitConverter(unit)\n\n elif role == DataRoleField.PRODUCTION_ENPI:\n if unit.endswith('production_a^-1'):\n return ProductionAENPIUnitConverter(\n unit[:-len('*production_a^-1')])\n elif unit.endswith('production_b^-1'):\n return ProductionBENPIUnitConverter(\n unit[:-len('*production_b^-1')])\n elif unit.endswith('production_c^-1'):\n return ProductionCENPIUnitConverter(\n unit[:-len('*production_c^-1')])\n elif unit.endswith('production_d^-1'):\n return ProductionDENPIUnitConverter(\n unit[:-len('*production_d^-1')])\n elif unit.endswith('production_e^-1'):\n return ProductionEENPIUnitConverter(\n unit[:-len('*production_e^-1')])\n\n elif role == DataRoleField.HEAT_LOSS_COEFFICIENT:\n return PhysicalUnitConverter('watt*kelvin^-1')\n\n elif role == DataRoleField.MEAN_COOLDOWN_TEMPERATURE:\n if customer.temperature == 'celsius':\n return RelativeCelsiusUnitConverter()\n elif customer.temperature == 'fahrenheit':\n return RelativeFahrenheitUnitConverter()\n\n elif role == DataRoleField.VOLUME and \\\n utility_type == utilitytypes.METER_CHOICES.district_heating:\n return PhysicalUnitConverter(customer.water_consumption)\n\n elif role == DataRoleField.EFFICIENCY:\n return EfficiencyUnitConverter()\n\n raise ValueError(\n 'A preferred unit object for role=%s and utility_type=%s '\n 'is not defined.' % (\n unicode(dict(DataRoleField.CHOICES)[role]),\n choices_extract_python_identifier(\n utilitytypes.OPTIONAL_METER_CHOICES, utility_type)))\n" }, { "alpha_fraction": 0.5733020901679993, "alphanum_fraction": 0.5901639461517334, "avg_line_length": 21.473684310913086, "blob_id": "dd1990403cf030de9932c48df057d1a3f7f3b21e", "content_id": "82256f7e25e37e7c305db530a420d86a5d22c417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2135, "license_type": "no_license", "max_line_length": 78, "num_lines": 95, "path": "/gridagentserver/agentserver/settings.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# Django/agent server configuration\nimport datetime\n\nfrom configurations import Settings\n\n\nclass Base(Settings):\n TIME_ZONE = 'UTC'\n USE_TZ = True\n\n INSTALLED_APPS = (\n 'gridplatform.encryption',\n 'gridplatform.users',\n 'gridplatform.customers',\n 'legacy.devices',\n 'legacy.measurementpoints',\n 'gridplatform.datasequences',\n )\n\n SECRET_KEY = 'abc'\n\n # agent server config...\n POLL_INTERVAL = 60.0\n POLL_START_DELAY = 15.0\n\n TIME_SYNC_INTERVAL = datetime.timedelta(days=1)\n TIME_SYNC_TOLERANCE = 15.0\n\n LISTEN_PORT = 30001\n\n AMQP_PORT = 5672\n AMQP_VHOST = '/'\n AMQP_USER = \"guest\"\n AMQP_PASSWORD = \"guest\"\n AMQP_SPEC = 'amqp0-8.stripped.rabbitmq.xml'\n\n SITE_NAME = 'gridplatform'\n\n\nclass Prod(Base):\n SITE_MAIL_ADDRESS = \"[email protected]\"\n AMQP_HOST = \"engine.grid-manager.com\"\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'gridportal',\n 'USER': 'grid',\n 'PASSWORD': 'ugOk9Blim',\n 'HOST': '77.66.29.230',\n 'PORT': '5432',\n }\n }\n\n\nclass Local(Base):\n AMQP_HOST = 'localhost'\n\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2',\n 'NAME': 'portal',\n # Current *nix user have local sockec access...\n 'USER': '',\n 'PASSWORD': '',\n 'HOST': '',\n 'PORT': '',\n }\n }\n\n\n# Configuration for the GreenTech Center server. The server is physically\n# located at the GTC in Vejle, Denmark.\nclass GreenTech(Local):\n SITE_MAIL_ADDRESS = \"[email protected]\"\n\n\n# Configuration for the server at Cheminova. Will be running for approximately\n# 3 months.\nclass Cheminova(Local):\n SITE_MAIL_ADDRESS = \"[email protected]\"\n\n\n# For the GridManager Iberia server. Located in Spain, managed by Netgroup.\nclass Iberia(Local):\n SITE_MAIL_ADDRESS = \"[email protected]\"\n\n\nclass Test(Local):\n SITE_MAIL_ADDRESS = \"[email protected]\"\n\n\nclass Dev(Local):\n DEBUG = True\n EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n" }, { "alpha_fraction": 0.7448166012763977, "alphanum_fraction": 0.7671451568603516, "avg_line_length": 32, "blob_id": "fd7ec87a63821868fa9bf43a4c2e9a7b6c95a08a", "content_id": "153e47c20c9a582193f929dfd3e88ab83cee86a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 633, "license_type": "no_license", "max_line_length": 70, "num_lines": 19, "path": "/documentation/source/apps/gridplatform/co2conversions.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": ".. _co2-conversions:\n\nCO₂ Conversions\n===============\n\nThe CO₂ Conversions app define a small class hierachy of CO₂\nConversions. The base class is :py:class:`Co2Conversion`, which is\nabstract in the OO sense. :py:class:`Co2Conversion` is inherited by\n:py:class:`DynamicCo2Conversion` and :py:class:`FixedCo2Conversion`\nwhich are both concrete.\n\n.. autoclass:: gridplatform.co2conversions.models.Co2Conversion\n :members: clean, _value_sequence\n\n.. autoclass:: gridplatform.co2conversions.models.DynamicCo2Conversion\n :members: clean\n\n.. autoclass:: gridplatform.co2conversions.models.FixedCo2Conversion\n :members: clean\n" }, { "alpha_fraction": 0.668545663356781, "alphanum_fraction": 0.6689214706420898, "avg_line_length": 41.238094329833984, "blob_id": "b7df996257c5896a154fa87b06fe383b17a0af5b", "content_id": "3787e746b6b7e0c3ab04315a881d28dca6d43833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2661, "license_type": "no_license", "max_line_length": 75, "num_lines": 63, "path": "/legacy/legacy_utils/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.fields import DataRoleField\n\n\ndef get_customer_preferred_unit_attribute_name(\n customer, role, utility_type=None):\n \"\"\"\n Get preferred attribute unit name for given role and resource type.\n\n @param role: The given DataRoleField value.\n\n @param utility_type: The given resource type, as defined by the\n L{utilitytypes.OPTIONAL_METER_CHOICES}. If not given\n C{utilitytypes.OPTIONAL_METER_CHOICES.unknown} is assumed.\n\n @return: Returns either a valid field name, or C{None}.\n \"\"\"\n if not utility_type:\n utility_type = utilitytypes.OPTIONAL_METER_CHOICES.unknown\n\n result = None\n if role in (DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n DataRoleField.CONSUMPTION):\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n result = 'electricity_consumption'\n elif utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n result = 'heat_consumption'\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n result = 'gas_consumption'\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n result = 'water_consumption'\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n result = 'oil_consumption'\n elif role == DataRoleField.POWER:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n result = 'electricity_instantaneous'\n elif utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n result = 'heat_instantaneous'\n elif role == DataRoleField.VOLUME_FLOW:\n if utility_type == utilitytypes.OPTIONAL_METER_CHOICES.water:\n result = 'water_instantaneous'\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.gas:\n result = 'gas_instantaneous'\n elif utility_type == utilitytypes.OPTIONAL_METER_CHOICES.oil:\n result = 'oil_instantaneous'\n elif role == DataRoleField.VOLUME:\n if utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n result = 'water_consumption'\n elif role in [DataRoleField.ABSOLUTE_TEMPERATURE,\n DataRoleField.RELATIVE_TEMPERATURE,\n DataRoleField.MEAN_COOLDOWN_TEMPERATURE]:\n result = 'temperature'\n\n if result is not None:\n assert hasattr(customer, result)\n return result\n" }, { "alpha_fraction": 0.5576323866844177, "alphanum_fraction": 0.5620827674865723, "avg_line_length": 31.802919387817383, "blob_id": "ee73d53f7df1b47fe924316209df7bad0382024f", "content_id": "6b9527c76fd9a3c8d218c82f3336720eb56d8aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4494, "license_type": "no_license", "max_line_length": 103, "num_lines": 137, "path": "/emonhub/src/interfacers/EmonHubSCNordicHTTPInterfacer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"class EmonHubEmoncmsHTTPInterfacer\n\"\"\"\nimport time\n\nfrom configobj import ConfigObj\nfrom pydispatch import dispatcher\nfrom emonhub_interfacer import EmonHubInterfacer\nimport emonhub_coder as ehc\nfrom interfacers.portal_package import PortalPackage\nfrom scnordic_bridge import RequestHandler\n\n\nclass EmonHubSCNordicHTTPInterfacer(EmonHubInterfacer):\n\n def __init__(self, name):\n # Initialization\n super(EmonHubSCNordicHTTPInterfacer, self).__init__(name)\n \n self._name = name\n \n self._settings = {\n 'subchannels':['ch1'],\n 'pubchannels':['ch2'],\n \n 'apikey': \"\",\n 'url': \"http://emoncms.org\",\n 'sendinterval': 20,\n 'prev_values_path': \"/home/pi/data/prev_values.conf\"\n }\n \n self.buffer = []\n self.lastsent = time.time()\n self.queue = []\n\n self.prev_values = {}\n self.correction_values = {}\n\n def receiver(self, cargo):\n '''\n Append cargo to sendbuffer if it's not in it allready\n '''\n\n if not [c for c in self.buffer if c.nodeid == cargo.nodeid]:\n self._log.debug(str(cargo.uri) + \" adding cargo to buffer\")\n self.buffer.append(cargo)\n\n def cargo_to_portal_packages(self, cargo):\n packages = []\n\n for index, value in enumerate(cargo.realdata):\n senddata = ehc.nodelist[str(cargo.nodeid)]['rx']['senddata'][index]\n if senddata == '1':\n unit = ehc.nodelist[str(cargo.nodeid)]['rx']['units'][index]\n name = \"%s-%s\" % (cargo.nodename, cargo.names[index])\n name = name.upper()\n value = float(value)\n if unit in ['Wh', 'p', 'sec']:\n value = self.value_check(name, value)\n\n packages.append(PortalPackage(name, cargo.timestamp, value, unit))\n\n if unit in ['Wh', 'p', 'sec']:\n self.prev_values[name] = value\n\n self.prev_values.write()\n\n return packages\n\n def action(self):\n now = time.time()\n \n if (now-self.lastsent) > (int(self._settings['sendinterval'])):\n self.lastsent = now\n # print json.dumps(self.buffer)\n\n self.bulkpost(self.buffer)\n self.buffer = []\n \n def bulkpost(self, databuffer):\n \n if not 'apikey' in self._settings.keys() or str.__len__(str(self._settings['apikey'])) != 104 \\\n or str.lower(str(self._settings['apikey'])) == 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx':\n return\n\n request = RequestHandler(self._settings['apikey'], self._settings['url'])\n failed_packages = []\n\n for data in databuffer:\n packages = self.cargo_to_portal_packages(data)\n\n for package in packages:\n self.queue.append(package)\n\n failure = False\n for package in self.queue:\n\n sent = 500\n if not failure:\n sent = request.send_measurement(package)\n\n if sent in (500, 502):\n failure = True\n self._log.warning(\"send failure: wanted '200' but got '\" + str(sent) + \"'\")\n failed_packages.append(package)\n\n self.queue = failed_packages\n\n return True\n \n def set(self, **kwargs):\n for key,setting in self._settings.iteritems():\n if key in kwargs.keys():\n # replace default\n self._settings[key] = kwargs[key]\n\n # Subscribe to internal channels\n for channel in self._settings[\"subchannels\"]:\n dispatcher.connect(self.receiver, channel)\n self._log.debug(self._name+\" Subscribed to channel' : \" + str(channel))\n\n self.prev_values = ConfigObj(self._settings['prev_values_path'])\n\n def value_correction(self, name, value):\n return value + float(self.correction_values[name])\n\n def value_check(self, name, value):\n\n if name in self.correction_values:\n self._log.debug(\"Correcting value for: \" + name)\n value = self.value_correction(name, value)\n\n if name in self.prev_values and value < self.prev_values[name]:\n self._log.debug(\"New value lower than the last. Setting up correction for: \" + name)\n self.correction_values[name] = float(self.prev_values[name])\n value = self.value_correction(name, value)\n\n return value\n" }, { "alpha_fraction": 0.6442080140113831, "alphanum_fraction": 0.6446020603179932, "avg_line_length": 35.78260803222656, "blob_id": "9db4ac9d7ebde8dfc58f755f9903cca39c762fa5", "content_id": "935fbc8413dea78364f575d054b5027ef1f8d13c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2538, "license_type": "no_license", "max_line_length": 78, "num_lines": 69, "path": "/gridplatform/tariffs/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext\n\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils import units\nfrom gridplatform.utils.forms import HalfOpenTimePeriodModelForm\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom . import models\n\n\nclass SubscriptionFeeFormLabelMixin(object):\n \"\"\"\n Include customers currency in label of subscription fee field.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(SubscriptionFeeFormLabelMixin, self).__init__(*args, **kwargs)\n self.fields['subscription_fee'].label = \\\n ugettext('subscription fee ({currency})').format(\n currency=get_customer().get_currency_unit_display())\n\n\nclass FixedPricePeriodForm(\n SubscriptionFeeFormLabelMixin, HalfOpenTimePeriodModelForm):\n class Meta:\n model = models.FixedPricePeriod\n fields = (\n 'value', 'unit', 'subscription_fee', 'subscription_period')\n localized_fields = ('subscription_fee',)\n\n\nclass SpotPricePeriodForm(\n SubscriptionFeeFormLabelMixin, HalfOpenTimePeriodModelForm):\n class Meta:\n model = models.SpotPricePeriod\n fields = (\n 'subscription_fee', 'subscription_period', 'spotprice',\n 'coefficient', 'unit_for_constant_and_ceiling',\n 'constant', 'ceiling')\n localized_fields = (\n 'subscription_fee', 'coefficient', 'constant', 'ceiling')\n\n def __init__(self, *args, **kwargs):\n # If a tariff is given to the constructor then the spot prices choices\n # are updated accordingly.\n\n tariff = kwargs.pop('tariff', None)\n super(SpotPricePeriodForm, self).__init__(*args, **kwargs)\n if tariff:\n compatible_spotprice_units = [\n unit for unit in units.TARIFF_BASE_UNITS\n if PhysicalQuantity.compatible_units(unit, tariff.unit)\n ]\n\n self.fields['spotprice'].queryset = \\\n self.fields['spotprice'].queryset.filter(\n unit__in=compatible_spotprice_units)\n\n compatible_tariff_choices = [\n (unit, label) for unit, label in units.TARIFF_CHOICES\n if PhysicalQuantity.compatible_units(unit, tariff.unit)\n ]\n self.fields['unit_for_constant_and_ceiling'] = \\\n forms.ChoiceField(choices=compatible_tariff_choices)\n" }, { "alpha_fraction": 0.6316839456558228, "alphanum_fraction": 0.632082998752594, "avg_line_length": 34.79999923706055, "blob_id": "e6a7916c651472617e164b409a2e62385eb96372", "content_id": "35c48719a430f4744c97f634608d7aad8b0b32ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5012, "license_type": "no_license", "max_line_length": 79, "num_lines": 140, "path": "/gridplatform/users/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.views import redirect_to_login\nfrom django.contrib.auth import authenticate\nfrom django.core.exceptions import PermissionDenied\nfrom django import forms\nfrom django.utils.translation import ugettext as _\nfrom django.core.exceptions import ValidationError\nfrom django.http import HttpResponse\nfrom django.utils.functional import cached_property\n\nfrom braces.views._access import AccessMixin\n\nfrom gridplatform.utils import generic_views\nfrom gridplatform.users.models import User\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_customer\n\n\nclass CustomerAdminOrAdminRequiredMixin(AccessMixin):\n \"\"\"\n View mixin that ensures user is customer superuser or admin.\n\n :cvar raise_exception=False: Boolean class member attribute inherited from\n :class:`braces.views._access.AccessMixin`. Controls what happens when\n unauthorized access is attempted. If set to ``True`` a\n :class:`django.core.exceptions.PermissionDenied` exception is raised,\n if ``False`` redirect to login page.\n \"\"\"\n def dispatch(self, request, *args, **kwargs):\n \"\"\"\n Handle authorization checks and delegate to super ``dispatch()``\n implementation.\n \"\"\"\n if not (request.user.is_authenticated() and\n (request.user.is_customer_superuser or request.user.is_admin)):\n if self.raise_exception:\n raise PermissionDenied\n else:\n return redirect_to_login(\n request.get_full_path(),\n self.get_login_url(),\n self.get_redirect_field_name())\n return super(CustomerAdminOrAdminRequiredMixin, self).dispatch(\n request, *args, **kwargs)\n\n\nclass UserProfileForm(forms.ModelForm):\n \"\"\"\n :class:`~django.forms.ModelForm` for :class:`.User` model.\n\n Besides updating regular fields, this form also supports changing password.\n Old password and the new password repeated twice must be entered to update\n the password.\n \"\"\"\n old_password = forms.CharField(\n label=_('password'), widget=forms.PasswordInput, required=False)\n new_password = forms.CharField(\n label=_('new password'),\n widget=forms.PasswordInput, min_length=8, required=False)\n new_password_check = forms.CharField(\n label=_('new password again'),\n widget=forms.PasswordInput, required=False)\n\n class Meta:\n model = User\n fields = ('name', 'phone', 'mobile',)\n localized_fields = '__all__'\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If new password is set, but old password is not\n provided or does not authenticate the currently loged in user.\n :raise ValidationError: If new password and password confirmation field\n do not contain the same password.\n \"\"\"\n\n cleaned_data = super(UserProfileForm, self).clean()\n user = get_user()\n\n if cleaned_data.get('new_password'):\n if cleaned_data['old_password'] == \"\":\n raise ValidationError(_(\"Please provide your password\"))\n else:\n authenticated = authenticate(\n username=user.e_mail_plain,\n password=cleaned_data['old_password'])\n if not authenticated:\n raise ValidationError(_(\"The password is not correct\"))\n\n if cleaned_data['new_password'] != \\\n cleaned_data['new_password_check']:\n raise ValidationError(_(\"The passwords doesn't match\"))\n\n return cleaned_data\n\n\nclass UserProfileView(generic_views.FormView):\n \"\"\"\n View for updating :class:`.User` details.\n \"\"\"\n form_class = UserProfileForm\n template_name = \"users/_user_profile_form.html\"\n\n def get_cancel_url(self):\n return '#'\n\n def get_form_kwargs(self):\n \"\"\"\n Ensures that ``form.instance`` is set to the :class:`.User` currently\n logged in.\n \"\"\"\n kwargs = super(UserProfileView, self).get_form_kwargs()\n kwargs['instance'] = get_user()\n return kwargs\n\n def form_valid(self, form):\n \"\"\"\n Changes the password if new password was provided. Otherwise somewhat\n similar to :meth:`django.views.generic.UpdateView.form_valid`\n \"\"\"\n user = get_user()\n user.name_plain = form.cleaned_data['name']\n user.phone_plain = form.cleaned_data['phone']\n user.mobile_plain = form.cleaned_data['mobile']\n\n if form.cleaned_data['new_password'] != \"\":\n user.set_password(\n form.cleaned_data['new_password'],\n old_password=form.cleaned_data['old_password']\n )\n\n user.save()\n return HttpResponse('success')\n\n @cached_property\n def _customer(self):\n return get_customer()\n" }, { "alpha_fraction": 0.6458333134651184, "alphanum_fraction": 0.6458333134651184, "avg_line_length": 18.200000762939453, "blob_id": "a8c7307f2de942bd5e3d66a640858dadf02f6dae", "content_id": "9293e5189f0e965e2d3c9ea1caf8b6d3bfb0575c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 96, "license_type": "no_license", "max_line_length": 32, "num_lines": 5, "path": "/legacy/manage_measurementpoints/forms/Makefile", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "classes.pdf: classes_No_Name.dot\n\tdot $< -Tpdf -o $@\n\nclasses_No_Name.dot: *.py\n\tpyreverse -A .\n" }, { "alpha_fraction": 0.7034934759140015, "alphanum_fraction": 0.703930139541626, "avg_line_length": 35.935482025146484, "blob_id": "ffa31aba7deb96d3bbc8fea9971ae3c8d80c8a7c", "content_id": "23e1abf3c6949b0144c11d0180011f9a6df7f876", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2290, "license_type": "no_license", "max_line_length": 88, "num_lines": 62, "path": "/legacy/manage_measurementpoints/forms/efficiency.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom gridplatform.datasequences.models import NonaccumulationDataSequence # noqa\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\nfrom legacy.efficiencymeasurementpoints.models import EfficiencyMeasurementPoint # noqa\n\nfrom .measurementpointform import MeasurementPointForm\n\n\nclass EfficiencyMeasurementPointForm(MeasurementPointForm):\n \"\"\"\n A C{EfficiencyMeasurementPointForm} sets properties on a\n L{EfficiencyMeasurementPoint} that can be both set when creating and when\n updating.\n \"\"\"\n class Meta:\n model = EfficiencyMeasurementPoint\n fields = ('name', 'parent',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super(EfficiencyMeasurementPointForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n def _get_edit_headline_display(self):\n return _(u'Edit Efficiency Measurement Point')\n\n\nclass InputEfficiencyMeasurementPointForm(EfficiencyMeasurementPointForm):\n \"\"\"\n An C{InputEfficiencyMeasurementPointForm} is a\n L{EfficiencyMeasurementPointForm}, that in addition also sets properties\n that can only be set when creating a L{EfficiencyMeasurementPointForm}.\n \"\"\"\n input_configuration = forms.ModelChoiceField(\n required=True,\n queryset=NonaccumulationAdapter.objects.none())\n\n class ProxyMeta:\n fields = ('input_configuration', )\n\n def __init__(self, *args, **kwargs):\n super(InputEfficiencyMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['input_configuration'].queryset = \\\n EfficiencyMeasurementPoint.get_input_configuration_choices()\n\n def _get_new_headline_display(self):\n return _(u'New Efficiency Measurement Point')\n" }, { "alpha_fraction": 0.728675901889801, "alphanum_fraction": 0.7319252490997314, "avg_line_length": 33.19444274902344, "blob_id": "4dbe4dd24ca2c32e0b64b8c317adcbb44f3dad9b", "content_id": "e6d2c4d6b85d507f30d84d3e894fe77df43ea147", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/gridplatform/customers/test_mixins.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.fields import EncryptedCharField\n\nfrom .models import Customer\nfrom .mixins import EncryptionCustomerFieldMixin\n\n\nclass TestModel(EncryptionCustomerFieldMixin, EncryptedModel):\n name = EncryptedCharField('name', max_length=200)\n\n\nclass EncryptionCustomerFieldMixinTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n\n def test_encryption_id(self):\n instance = TestModel(\n customer=self.customer)\n self.assertEqual(\n (Customer, self.customer.id), instance.get_encryption_id())\n\n @override_settings(ENCRYPTION_TESTMODE=True)\n def test_encrypted_model_integration(self):\n instance = TestModel.objects.create(\n customer=self.customer, name_plain='pöp cørn')\n self.assertEqual(\n TestModel.objects.get(id=instance.id).name_plain, 'pöp cørn')\n" }, { "alpha_fraction": 0.6528141498565674, "alphanum_fraction": 0.6636125445365906, "avg_line_length": 37.20000076293945, "blob_id": "ca55484a504bd39995e5fa515c8e284e29a05e57", "content_id": "7c4824d95f69a70b573ac00913878f9a11b29c80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3056, "license_type": "no_license", "max_line_length": 74, "num_lines": 80, "path": "/legacy/datasequence_adapters/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nimport pytz\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.devices.models import PhysicalInput\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.consumptions.models import NonpulsePeriod\n\nfrom .models import ConsumptionAccumulationAdapter\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass AccumulationAdapterTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n self.agent = Agent.objects.create(\n customer=self.customer,\n mac='BE:EF:FD:EA:D0:00')\n self.meter = Meter.objects.create(\n agent=self.agent,\n customer=self.customer,\n manufactoring_id=0,\n connection_type=Meter.GRIDPOINT,\n name_plain='METER_NAME',\n )\n self.physicalinput = PhysicalInput.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n hardware_id='foobarbaz',\n name_plain='PHYSICAL_INPUT',\n type=PhysicalInput.ELECTRICITY,\n meter=self.meter,\n order=0)\n self.consumption = Consumption.objects.create(\n name_plain='CONSUMPTION_NAME',\n customer=self.customer,\n unit='joule')\n self.adapter = ConsumptionAccumulationAdapter(\n datasequence=self.consumption)\n\n def test_unicode_single_physical_input(self):\n NonpulsePeriod.objects.create(\n datasequence=self.consumption,\n datasource=self.physicalinput,\n from_timestamp=datetime.datetime(2014, 1, 1, tzinfo=pytz.utc))\n self.assertIn('PHYSICAL_INPUT', unicode(self.adapter))\n\n def test_unicode_multiple_physical_inputs(self):\n physicalinput2 = PhysicalInput.objects.create(\n customer=self.customer,\n unit='milliwatt*hour',\n hardware_id='foobarbaz',\n name_plain='PHYSICAL_INPUT',\n type=PhysicalInput.ELECTRICITY,\n meter=self.meter,\n order=0)\n NonpulsePeriod.objects.create(\n datasequence=self.consumption,\n datasource=self.physicalinput,\n from_timestamp=datetime.datetime(2014, 1, 1, tzinfo=pytz.utc),\n to_timestamp=datetime.datetime(2014, 1, 2, tzinfo=pytz.utc))\n NonpulsePeriod.objects.create(\n datasequence=self.consumption,\n datasource=physicalinput2,\n from_timestamp=datetime.datetime(2014, 1, 2, tzinfo=pytz.utc))\n self.assertIn('CONSUMPTION_NAME', unicode(self.adapter))\n\n def test_unicode_no_physical_input_but_named(self):\n self.assertIn('CONSUMPTION_NAME', unicode(self.adapter))\n" }, { "alpha_fraction": 0.5844210982322693, "alphanum_fraction": 0.5848467946052551, "avg_line_length": 36.2910041809082, "blob_id": "8691ae445124b33e9f49eab1a2aadba4e5a2ea37", "content_id": "87a87f2875a72340e4f3d8e58b189fbbf15fec52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7048, "license_type": "no_license", "max_line_length": 84, "num_lines": 189, "path": "/gridplatform/rest/routers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport collections\nfrom collections import OrderedDict\n\nimport django.conf.urls\nimport rest_framework.response\nimport rest_framework.reverse\nimport rest_framework.routers\nimport rest_framework.views\n\nfrom .conf import settings\n\n\nclass NestingMixin(object):\n \"\"\"\n Mixes :meth:`.NestingMixin.register` into a\n :class:`rest_framework.routers.BaseRouter` specialization.\n\n The signature of :meth:`rest_framework.routers.BaseRouter.register` is\n changed to return a :class:`.NestingMixin.Nested` instance rather than not\n having a return value at all.\n \"\"\"\n class Nested(object):\n \"\"\"\n Allows nesting of registered viewsets.\n\n :ivar root: The root :class:`rest_framework.routers.BaseRouter`\n specialization to register nested viewsets on.\n :ivar prefix: The prefix used to register parent viewsets.\n \"\"\"\n def __init__(self, root, prefix):\n self.root = root\n self.prefix = prefix\n\n def register(self, prefix, viewset, base_name=None, **kwargs):\n \"\"\"\n Delegates to :meth:`.NestingMixin.register` but with prefix rewritten to\n simulate nesting under parent viewset.\n \"\"\"\n filter_by = kwargs.pop('filter_by', ())\n if not isinstance(filter_by, (tuple, list)):\n filter_by = (filter_by,)\n parent_prefix = self.prefix\n filter_args = '/'.join(\n '(?P<{}>[^/.]+)'.format(field)\n for field in filter_by\n )\n if filter_args:\n nested_prefix = \\\n '{parent_prefix}/{filter_args}/{prefix}'.format(\n parent_prefix=parent_prefix, filter_args=filter_args,\n prefix=prefix)\n else:\n nested_prefix = '{parent_prefix}/{prefix}'.format(\n parent_prefix=parent_prefix, prefix=prefix)\n return self.root.register(\n prefix=nested_prefix, viewset=viewset, base_name=base_name,\n filter_by=filter_by, **kwargs)\n\n def register(self, prefix, viewset, base_name=None, **kwargs):\n \"\"\"\n Specialization of :meth:`rest_framework.routers.BaseRouter.register`\n changed to return a :class:`.NestingMixin.Nested` that may be used to\n further register more viewsets under the URLs given viewset argument.\n \"\"\"\n filter_by = kwargs.pop('filter_by', ())\n viewset.filter_by = filter_by\n super(NestingMixin, self).register(\n prefix=prefix, viewset=viewset, base_name=base_name, **kwargs)\n return self.Nested(root=self, prefix=prefix)\n\n\nclass AppNamespaceMixin(object):\n \"\"\"\n Mixes :attr:`.AppNamespaceMixin.urls` into a\n :class:`rest_framework.routers.BaseRouter` specialization, so that\n registered viewsets have their urls defined according to the scheme defined\n by :data:`settings.REST_API_NAMESPACE` and\n :data:`settings.REST_SERIALIZER_VIEW_NAME_BASE`.\n \"\"\"\n def get_default_base_name(self, viewset):\n model_cls = getattr(viewset, 'model', None)\n queryset = getattr(viewset, 'queryset', None)\n if model_cls is None and queryset is not None:\n model_cls = queryset.model\n model_meta = model_cls._meta\n format_kwargs = {\n 'app_label': model_meta.app_label,\n 'model_name': model_meta.object_name.lower()\n }\n return settings.REST_SERIALIZER_VIEW_NAME_BASE % format_kwargs\n\n @property\n def urls(self):\n bad_urls = super(AppNamespaceMixin, self).get_urls()\n global_namespace_urls = []\n namespaces = collections.defaultdict(list)\n for urlpattern in bad_urls:\n regex = urlpattern.regex\n parts = urlpattern.name.rpartition(':')\n name = parts[2]\n namespace_path = parts[0] or None\n view = urlpattern.callback\n url = django.conf.urls.url(regex.pattern, view, name=name)\n if namespace_path:\n namespaces[namespace_path].append(url)\n else:\n global_namespace_urls.append(url)\n namespace_urls = []\n for namespace_path, urls in namespaces.items():\n namespace_list = namespace_path.split(':')\n nested = urls\n while namespace_list:\n namespace = namespace_list.pop()\n nested = [django.conf.urls.url(\n r'',\n django.conf.urls.include((nested, namespace, namespace)))]\n namespace_urls.append(nested.pop())\n return django.conf.urls.patterns(\n r'', *(global_namespace_urls + namespace_urls))\n\n\nclass ExtendedRouterMixin(AppNamespaceMixin, NestingMixin):\n \"\"\"\n Mixed both :class:`.AppNamespaceMixin` and :class:`.NestingMixin` into a\n :class:`rest_framework.routers.BaseRouter` specialization.\n \"\"\"\n pass\n\n\nclass DefaultRouter(ExtendedRouterMixin, rest_framework.routers.DefaultRouter):\n \"\"\"\n :class:`rest_framework.routers.DefaultRouter` specialization mixed with\n :class:`.ExtendedRouterMixin`.\n \"\"\"\n description = ''\n\n def __init__(self, *args, **kwargs):\n super(DefaultRouter, self).__init__(*args, **kwargs)\n self._api_root = {}\n\n def register(self, prefix, viewset, base_name=None, **kwargs):\n if not kwargs:\n if base_name is None:\n base_name = self.get_default_base_name(viewset)\n self._api_root[prefix] = base_name\n\n return super(DefaultRouter, self).register(\n prefix=prefix, viewset=viewset, base_name=base_name, **kwargs)\n\n def get_api_root_view(self):\n api_root = self._api_root\n\n class ApiRootView(rest_framework.views.APIView):\n __doc__ = self.description\n _ignore_model_permissions = True\n\n def get_view_name(view_cls, suffix=None):\n if self.__doc__ != '':\n return ''\n else:\n return super(DefaultRouter, self).get_view_name(\n view_cls, suffix)\n\n def get(self, request, format=None):\n return rest_framework.response.Response(OrderedDict(sorted([\n (url,\n rest_framework.reverse.reverse(\n ':'.join([\n settings.REST_API_NAMESPACE,\n '{}-list'.format(base_name),\n ]),\n request=request,\n format=format))\n for url, base_name in api_root.items()\n ])))\n\n return ApiRootView.as_view()\n\n\nclass SimpleRouter(ExtendedRouterMixin, rest_framework.routers.SimpleRouter):\n \"\"\"\n :class:`rest_framework.routers.SimpleRouter` specialization mixed with\n :class:`.ExtendedRouterMixin`.\n \"\"\"\n pass\n" }, { "alpha_fraction": 0.7051126956939697, "alphanum_fraction": 0.7070510983467102, "avg_line_length": 37.21296310424805, "blob_id": "2a296680b8a74b27a63e6dcd3c7a1f094aef6528", "content_id": "416d17dfa983045999c327fdea5e5d0866dbb1ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4127, "license_type": "no_license", "max_line_length": 79, "num_lines": 108, "path": "/legacy/energy_use_reports/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.utils.units import UNIT_CHOICES\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.units import CURRENCY_CHOICES\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.legacy_utils.preferredunits import get_preferred_unit_converter\nfrom legacy.legacy_utils import get_customer_preferred_unit_attribute_name\n\n\nclass EnergyUseReport(EncryptionCustomerFieldMixin, EncryptedModel):\n \"\"\"\n A report presenting an overview of areas of energy use, their consumptions\n and their costs.\n\n @seealso: L{EnergyUseArea}\n \"\"\"\n title = EncryptedCharField(max_length=50)\n currency_unit = BuckinghamField(_('currency'), choices=CURRENCY_CHOICES,\n default='currency_dkk')\n utility_type = models.IntegerField(\n _('utility type'), choices=utilitytypes.METER_CHOICES)\n main_measurement_points = models.ManyToManyField(\n ConsumptionMeasurementPoint, blank=True, null=True)\n\n objects = CustomerBoundManager()\n\n def __unicode__(self):\n return self.title_plain\n\n def get_preferred_unit_display(self):\n return get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, self.utility_type).get_display_unit()\n\n def get_preferred_unit(self):\n return getattr(\n self.customer,\n get_customer_preferred_unit_attribute_name(\n self.customer, DataRoleField.CONSUMPTION, self.utility_type))\n\n def get_preferred_co2_emission_unit_display(self):\n return dict(UNIT_CHOICES)[self.get_preferred_co2_emission_unit()]\n\n def get_preferred_co2_emission_unit(self):\n return 'kilogram'\n\n def get_utility_type_report_name(self):\n if self.utility_type == utilitytypes.METER_CHOICES.electricity:\n return _('Electricity Use Report')\n elif self.utility_type == utilitytypes.METER_CHOICES.water:\n return _('Water Use Report')\n elif self.utility_type == utilitytypes.METER_CHOICES.gas:\n return _('Gas Use Report')\n elif self.utility_type == utilitytypes.METER_CHOICES.district_heating:\n return _('Heat Use Report')\n elif self.utility_type == utilitytypes.METER_CHOICES.oil:\n return _('Oil Use Report')\n else:\n raise IndexError()\n\n def get_all_measurementpoint_ids(self):\n \"\"\"\n Returns a list of ids for all the measurement points\n used in the report.\n \"\"\"\n mps = ConsumptionMeasurementPoint.objects.filter(\n energyusearea__report=self).values_list('id', flat=True)\n\n return list(mps) + [mp.id for mp in self.main_measurement_points.all()]\n\n\nclass ReportCustomerBoundManager(CustomerBoundManager):\n _field = 'report__customer'\n\n\nclass EnergyUseArea(EncryptedModel):\n \"\"\"\n C{EnergyUseArea} is an area of energy use included in an\n L{EnergyUseReport}. In particular, an area of energy use has a C{name} and\n aggregates a number of C{measurement_points}.\n \"\"\"\n report = models.ForeignKey(EnergyUseReport)\n name = EncryptedCharField(max_length=50)\n measurement_points = models.ManyToManyField(ConsumptionMeasurementPoint)\n\n objects = ReportCustomerBoundManager()\n\n def __unicode__(self):\n return self.name_plain\n\n def get_encryption_id(self):\n if self.report_id and self.report.customer_id:\n customer_id = self.report.customer_id\n else:\n customer_id = None\n return (Customer, customer_id)\n" }, { "alpha_fraction": 0.7051646113395691, "alphanum_fraction": 0.7116912603378296, "avg_line_length": 40.9523811340332, "blob_id": "791524341ae59634256b6cf90fbd9997b3e9a200", "content_id": "4eb634d3db5086d597f793578f63dba9415157e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3524, "license_type": "no_license", "max_line_length": 77, "num_lines": 84, "path": "/gridplatform/customers/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db.models import Model\nfrom django.forms import ModelForm\nfrom django.test import TestCase\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import preferred_unit_bases\n\nfrom .fields import UnitNormalisingField\nfrom .models import Customer\n\n\nclass ModelWithUnitNormalisingField(Model):\n field = UnitNormalisingField(\n preferred_unit_getter=lambda obj: 'kilowatt')\n\n\nclass ModelWithUnitNormalisingFieldForm(ModelForm):\n class Meta:\n model = ModelWithUnitNormalisingField\n\n\nclass TestUnitNormalisingField(TestCase):\n def test_form_input(self):\n form = ModelWithUnitNormalisingFieldForm({'field': '5'})\n self.assertTrue(form.is_valid())\n obj = form.save(commit=False)\n preferred_unit_value = float(\n PhysicalQuantity(5, 'kilowatt').convert(\n preferred_unit_bases['kilowatt']))\n self.assertEqual(obj.field, preferred_unit_value)\n\n def test_form_output(self):\n preferred_unit_value = float(\n PhysicalQuantity('140.2', 'kilowatt').convert(\n preferred_unit_bases['kilowatt']))\n obj = ModelWithUnitNormalisingField(field=preferred_unit_value)\n self.assertEqual(obj.field, preferred_unit_value)\n form = ModelWithUnitNormalisingFieldForm(instance=obj)\n self.assertEqual(form.initial['field'], 140.2)\n\n def test_save_load(self):\n obj = ModelWithUnitNormalisingField(field=123456)\n obj.save()\n loaded = ModelWithUnitNormalisingField.objects.get(id=obj.id)\n self.assertEqual(loaded.field, 123456)\n\n\nclass CustomerGetProductionUnitChoicesTest(TestCase):\n def setUp(self):\n self.customer = Customer()\n\n def test_no_production_units(self):\n production_unit_choices = self.customer.get_production_unit_choices()\n\n self.assertFalse(hasattr(production_unit_choices, 'production_a'))\n self.assertFalse(hasattr(production_unit_choices, 'production_b'))\n self.assertFalse(hasattr(production_unit_choices, 'production_c'))\n self.assertFalse(hasattr(production_unit_choices, 'production_d'))\n self.assertFalse(hasattr(production_unit_choices, 'production_e'))\n\n def test_one_production_unit(self):\n self.customer.production_b_unit_plain = 'barrels of coffee'\n production_unit_choices = self.customer.get_production_unit_choices()\n\n self.assertFalse(hasattr(production_unit_choices, 'production_a'))\n self.assertTrue(hasattr(production_unit_choices, 'production_b'))\n self.assertFalse(hasattr(production_unit_choices, 'production_c'))\n self.assertFalse(hasattr(production_unit_choices, 'production_d'))\n self.assertFalse(hasattr(production_unit_choices, 'production_e'))\n\n def test_multiple_production_units(self):\n self.customer.production_b_unit_plain = 'barrels of coffee'\n self.customer.production_e_unit_plain = 'tonnes of cake'\n production_unit_choices = self.customer.get_production_unit_choices()\n\n self.assertFalse(hasattr(production_unit_choices, 'production_a'))\n self.assertTrue(hasattr(production_unit_choices, 'production_b'))\n self.assertFalse(hasattr(production_unit_choices, 'production_c'))\n self.assertFalse(hasattr(production_unit_choices, 'production_d'))\n self.assertTrue(hasattr(production_unit_choices, 'production_e'))\n" }, { "alpha_fraction": 0.7314638495445251, "alphanum_fraction": 0.7319391369819641, "avg_line_length": 34.06666564941406, "blob_id": "978719151b3d5ec2d7d16b1af110b042b65ae739", "content_id": "070007190ff2bc6cc59c1e99058dc6c0c1504a59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2108, "license_type": "no_license", "max_line_length": 76, "num_lines": 60, "path": "/legacy/efficiencymeasurementpoints/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.datasequences.models import NonaccumulationDataSequence\nfrom gridplatform.utils.preferredunits import EfficiencyUnitConverter\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\n\nfrom .models import EfficiencyLink\nfrom .models import EfficiencyMeasurementPoint\n\n\nclass EfficiencyLinkTest(TestCase):\n def setUp(self):\n self.link = EfficiencyLink()\n\n def test_get_preferred_unit_converter(self):\n self.assertIsInstance(\n self.link.get_preferred_unit_converter(),\n EfficiencyUnitConverter)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass EfficiencyMeasurementPointTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n\n self.datasequence = NonaccumulationDataSequence.objects.create(\n customer=self.customer,\n unit='millibar')\n\n self.mp = EfficiencyMeasurementPoint(\n name_plain='Æffiktivitætsmålepønkt',\n customer=self.customer)\n self.mp.input_configuration = NonaccumulationAdapter.objects.create(\n unit='millibar',\n role=DataRoleField.EFFICIENCY,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n datasequence=self.datasequence)\n self.mp.save()\n\n def test_graph_has_efficiencylink(self):\n self.assertIsInstance(\n self.mp.graph_set.get().dataseries_set.get().subclass_instance,\n EfficiencyLink)\n\n def test_resave_doesnt_crash(self):\n self.mp.save()\n" }, { "alpha_fraction": 0.7249448299407959, "alphanum_fraction": 0.7253863215446472, "avg_line_length": 36.13114929199219, "blob_id": "a5ca845300a1c170f91654c25c25fd094751f99b", "content_id": "0ec0724c263bd4fb56baa7448dc7cfab0fdcb47a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2265, "license_type": "no_license", "max_line_length": 76, "num_lines": 61, "path": "/legacy/manage_measurementpoints/forms/districtheatingform.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.proxies import DistrictHeatingMeasurementPoint\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.consumptions.models import Consumption\n\nfrom .consumption import ConsumptionMeasurementPointForm\nfrom .consumption import InputConsumptionMeasurementPointForm\n\n\nclass DistrictHeatingMeasurementPointCreateForm(\n InputConsumptionMeasurementPointForm):\n volume_input = forms.ModelChoiceField(\n queryset=Consumption.objects.none())\n\n class Meta(InputConsumptionMeasurementPointForm.Meta):\n model = DistrictHeatingMeasurementPoint\n\n class ProxyMeta(InputConsumptionMeasurementPointForm.ProxyMeta):\n fields = InputConsumptionMeasurementPointForm.ProxyMeta.fields + (\n 'volume_input', )\n\n def __init__(self, *args, **kwargs):\n super(DistrictHeatingMeasurementPointCreateForm,\n self).__init__(*args, **kwargs)\n\n self.fields['consumption_input'].queryset = \\\n Consumption.objects.subclass_only().filter(\n customer=trackuser.get_customer(),\n utility_type=utilitytypes.METER_CHOICES.district_heating)\n\n self.fields['volume_input'].queryset = \\\n Consumption.objects.subclass_only().filter(\n customer=trackuser.get_customer(),\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water)\n\n def _get_new_headline_display(self):\n return _(u'New District Heating Measurement Point')\n\n def _get_edit_headline_display(self):\n return _(u'Edit District Heating Measurement Point')\n\n\nclass DistrictHeatingMeasurementPointEditForm(\n ConsumptionMeasurementPointForm):\n\n class Meta(InputConsumptionMeasurementPointForm.Meta):\n model = DistrictHeatingMeasurementPoint\n exclude = ('consumption_input', 'volume_input')\n\n def _get_new_headline_display(self):\n return _(u'New District Heating Measurement Point')\n\n def _get_edit_headline_display(self):\n return _(u'Edit District Heating Measurement Point')\n" }, { "alpha_fraction": 0.6903669834136963, "alphanum_fraction": 0.6926605701446533, "avg_line_length": 26.25, "blob_id": "59b4986ab4874a23a8ad2c6c8b0756b85e5245bf", "content_id": "4ca14e79c6a36f5ffc2fc6169b3d1fe9fad4aa27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 79, "num_lines": 16, "path": "/gridplatform/bootstrap/context_processors.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom .conf import settings\n\n\ndef bootstrap(request):\n \"\"\"\n Provide template context variable boostrap_template for identifying what\n theme is currently being used. This is needed in boostrap/base.html to load\n the correct js and css files.\n \"\"\"\n return {\n 'bootstrap_theme': settings.BOOTSTRAP_THEME,\n }\n" }, { "alpha_fraction": 0.49674901366233826, "alphanum_fraction": 0.5213697552680969, "avg_line_length": 47.87711715698242, "blob_id": "967fdbc3dcfc89d12692c7179a712932bf46146e", "content_id": "773e1f245abdb8ced2fbde1b10eae544d38067f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23070, "license_type": "no_license", "max_line_length": 78, "num_lines": 472, "path": "/legacy/manage_indexes/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module contains tests for the manage_indexes Django app.\n\"\"\"\n\nimport json\nfrom collections import namedtuple\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform import trackuser\nfrom gridplatform.encryption.shell import Request\nfrom gridplatform.encryption.middleware import KeyLoaderMiddleware\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils import choices_extract_python_identifier\nfrom gridplatform.users.models import User\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ViewTest(TestCase):\n \"\"\"\n Tests for the view module.\n \"\"\"\n fixtures = [\"manage_indexes_test.json\"]\n\n def setUp(self):\n \"\"\"\n Setup test fixture as if we are logged in as some user called\n super.\n \"\"\"\n self.client.post('/login/', {\"username\": \"super\",\n 'password': \"123\"})\n self.user = User.objects.get(\n id=self.client.session[\"_auth_user_id\"])\n self.customer = self.user.customer\n trackuser._set_customer(self.customer)\n\n self.request = Request('super', '123')\n KeyLoaderMiddleware().process_request(self.request)\n\n Index_map = namedtuple('Index_map', 'role, utility_types')\n self.index_matrix = (\n Index_map(\n role='tariff',\n utility_types=('electricity', 'water', 'gas',\n 'district_heating', 'oil')),\n Index_map(role='employees',\n utility_types=('unknown',)),\n Index_map(role='area',\n utility_types=('unknown',)))\n\n def tearDown(self):\n KeyLoaderMiddleware().process_response(self.request, None)\n trackuser._set_customer(None)\n\n def get_all_indexes(self):\n \"\"\"\n This method creates all possible index types and returns\n a list with the created objects.\n \"\"\"\n index_el = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"electricity index\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n index_el.save()\n\n index_water = Index(\n unit=\"currency_dkk*liter^-1\",\n name_plain=\"water index\",\n role=DataRoleField.WATER_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water,\n timezone='Europe/Copenhagen')\n index_water.save()\n\n index_gas = Index(\n unit=\"currency_dkk*liter^-1\",\n name_plain=\"gas index\",\n role=DataRoleField.GAS_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas,\n timezone='Europe/Copenhagen')\n index_gas.save()\n\n index_heat = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"heat index\",\n role=DataRoleField.HEAT_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating,\n timezone='Europe/Copenhagen')\n index_heat.save()\n\n index_oil = Index(\n unit=\"currency_dkk*liter^-1\",\n name_plain=\"oil index\",\n role=DataRoleField.OIL_TARIFF,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil,\n timezone='Europe/Copenhagen')\n index_oil.save()\n\n index_area = Index(\n unit=\"meter^2\",\n name_plain=\"area index\",\n role=DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n timezone='Europe/Copenhagen')\n index_area.save()\n\n index_employee = Index(\n unit=\"person\",\n name_plain=\"employees index\",\n role=DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n data_format=Index.SEASONS,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown,\n timezone='Europe/Copenhagen')\n index_employee.save()\n\n return (index_el, index_water, index_gas, index_heat,\n index_oil, index_area, index_employee)\n\n def test_list_json(self):\n \"\"\"\n Test the C{list_json()} view.\n \"\"\"\n response = self.client.get(\"/indexes/list-json/\")\n self.assertEqual(response.status_code, 200)\n self.assertNotEqual(response.content, \"\")\n result = json.loads(response.content)\n self.assertIn(\"total\", result)\n self.assertIn(\"data\", result)\n\n def test_list(self):\n \"\"\"\n Test the C{list()} view.\n \"\"\"\n self.assertEqual(self.client.get(\"/indexes/\").status_code, 200)\n\n def test_form_create_derived(self):\n \"\"\"\n Test the C{form()} view when creating a derived index.\n Only tariff indexes can be derived indexes.\n \"\"\"\n for index in [index for index in self.get_all_indexes()\n if index.role in DataRoleField.TARIFFS]:\n utility_type_string = choices_extract_python_identifier(\n utilitytypes.METER_CHOICES, index.utility_type)\n response = self.client.get(\n \"/indexes/form/derived/tariff/%s\" % utility_type_string)\n self.assertContains(response, index.name_plain)\n\n # Creating derived index with valid input\n response = self.client.post(\n \"/indexes/form/derived/tariff/%s\" % utility_type_string,\n {\n \"name\": \"Derived index\",\n \"collection\": \"\",\n 'unit': index.unit,\n \"timezone\": \"Europe/Copenhagen\",\n \"derivedindexperiod_set-TOTAL_FORMS\": \"1\",\n \"derivedindexperiod_set-INITIAL_FORMS\": \"0\",\n \"derivedindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"derivedindexperiod_set-0-id\": \"\",\n \"derivedindexperiod_set-0-index\": \"\",\n \"derivedindexperiod_set-0-from_date\": \"2013-05-01\",\n \"derivedindexperiod_set-0-other_index\": str(index.id),\n \"derivedindexperiod_set-0-coefficient\": \"1.000\",\n \"derivedindexperiod_set-0-constant\": \"2\",\n \"derivedindexperiod_set-0-roof\": \"3\",\n \"save_return\": \"Save and return to list\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n # Creating derived index with invalid input\n response = self.client.post(\n \"/indexes/form/derived/tariff/%s\" % utility_type_string,\n {\n \"name\": \"Yet another derived index\",\n \"collection\": \"\",\n \"timezone\": \"Europe/Copenhagen\",\n \"derivedindexperiod_set-TOTAL_FORMS\": \"1\",\n \"derivedindexperiod_set-INITIAL_FORMS\": \"0\",\n \"derivedindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"derivedindexperiod_set-0-id\": \"\",\n \"derivedindexperiod_set-0-index\": \"\",\n \"derivedindexperiod_set-0-from_date\": \"2013-05-01\",\n \"derivedindexperiod_set-0-other_index\": str(index.id),\n \"derivedindexperiod_set-0-coefficient\": \"1.000\",\n \"derivedindexperiod_set-0-constant\": \"2\",\n \"derivedindexperiod_set-0-roof\": \"3\",\n \"save_return\": \"Save and return to list\"})\n self.assertContains(response, 'error')\n\n def test_form_update_derived(self):\n \"\"\"\n Test the C{form()} view when updating a derived index.\n Only derived tariff indexes can be updated.\n \"\"\"\n indexes = []\n for base_index in [base_index for base_index in self.get_all_indexes()\n if base_index.role in DataRoleField.TARIFFS]:\n\n derived_index = Index(\n unit=base_index.unit,\n name_plain=\"Derived \" + base_index.name_plain,\n role=base_index.role,\n data_format=Index.DERIVED,\n customer=self.customer,\n utility_type=base_index.utility_type,\n timezone='Europe/Copenhagen')\n derived_index.save()\n indexes.append((base_index, derived_index))\n\n for base_index, derived_index in indexes:\n self.assertContains(\n self.client.get(derived_index.get_absolute_url()),\n derived_index.name_plain)\n\n # Updating derived index with valid input\n response = self.client.post(\n derived_index.get_absolute_url(),\n {\n \"name\": \"Altered\",\n \"timezone\": \"Europe/Copenhagen\",\n \"derivedindexperiod_set-TOTAL_FORMS\": \"1\",\n \"derivedindexperiod_set-INITIAL_FORMS\": \"0\",\n \"derivedindexperiod_set-MAX_NUM_FORMS\": \"\",\n \"derivedindexperiod_set-0-from_date\": \"01.11.2012\",\n \"derivedindexperiod_set-0-other_index\": \"%d\" % (\n base_index.id),\n \"derivedindexperiod_set-0-coefficient\": \"1.00\",\n \"derivedindexperiod_set-0-constant\": \"0.12\",\n \"derivedindexperiod_set-0-roof\": \"0.70\",\n \"derivedindexperiod_set-0-id\": \"\",\n \"derivedindexperiod_set-0-index\": str(derived_index.id),\n \"save_return\": \"Save and return to list\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n # Updating derived index with 'save' button\n response = self.client.post(\n derived_index.get_absolute_url(),\n {\n \"name\": \"Altered\",\n \"timezone\": \"Europe/Copenhagen\",\n \"derivedindexperiod_set-TOTAL_FORMS\": \"1\",\n \"derivedindexperiod_set-INITIAL_FORMS\": \"0\",\n \"derivedindexperiod_set-MAX_NUM_FORMS\": \"\",\n \"derivedindexperiod_set-0-from_date\": \"01.11.2012\",\n \"derivedindexperiod_set-0-other_index\": \"%d\" % (\n base_index.id),\n \"derivedindexperiod_set-0-coefficient\": \"1.00\",\n \"derivedindexperiod_set-0-constant\": \"0.12\",\n \"derivedindexperiod_set-0-roof\": \"0.70\",\n \"derivedindexperiod_set-0-id\": \"\",\n \"derivedindexperiod_set-0-index\": str(derived_index.id),\n \"save\": \"Save\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n # Updating derived index with invalid other index\n response = self.client.post(\n derived_index.get_absolute_url(),\n {\n \"name\": \"Altered\",\n \"timezone\": \"Europe/Copenhagen\",\n \"derivedindexperiod_set-TOTAL_FORMS\": \"1\",\n \"derivedindexperiod_set-INITIAL_FORMS\": \"0\",\n \"derivedindexperiod_set-MAX_NUM_FORMS\": \"\",\n \"derivedindexperiod_set-0-from_date\": \"01.11.2012\",\n \"derivedindexperiod_set-0-other_index\": \"%d\" % (\n derived_index.id),\n \"derivedindexperiod_set-0-coefficient\": \"1.00\",\n \"derivedindexperiod_set-0-constant\": \"0.12\",\n \"derivedindexperiod_set-0-roof\": \"0.70\",\n \"derivedindexperiod_set-0-id\": \"\",\n \"derivedindexperiod_set-0-index\": str(derived_index.id),\n \"save_return\": \"Save and return to list\"})\n self.assertContains(response, 'error')\n\n def test_form_create_seasons(self):\n \"\"\"\n Create seasons indexes with all index combinations.\n \"\"\"\n for index in self.index_matrix:\n for utility_type in index.utility_types:\n self.assertEqual(self.client.get(\n \"/indexes/form/seasons/%s/%s\"\n % (index.role, utility_type)).status_code, 200)\n\n if utility_type in ('electricity', 'district_heating'):\n unit = 'currency_eur*kilowatt^-1*hour^-1'\n elif utility_type in ('water', 'gas', 'oil'):\n unit = 'currency_dkk*meter^-3'\n else:\n unit = 'some string that certainly is not used'\n\n response = self.client.post(\n \"/indexes/form/seasons/%s/%s\" % (\n index.role, utility_type),\n {\n \"name\": \"Test index\",\n \"collection\": \"\",\n 'unit': unit,\n \"timezone\": \"Europe/Copenhagen\",\n \"seasonindexperiod_set-TOTAL_FORMS\": \"1\",\n \"seasonindexperiod_set-INITIAL_FORMS\": \"0\",\n \"seasonindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"seasonindexperiod_set-0-id\": \"\",\n \"seasonindexperiod_set-0-index\": \"\",\n \"seasonindexperiod_set-0-from_date\": \"2013-08-02\",\n \"seasonindexperiod_set-0-value_at_hour_0\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_1\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_2\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_3\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_4\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_5\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_6\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_7\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_8\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_9\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_10\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_11\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_12\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_13\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_14\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_15\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_16\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_17\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_18\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_19\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_20\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_21\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_22\": \"1\",\n \"seasonindexperiod_set-0-value_at_hour_23\": \"1\",\n \"save_return\": \"Save and return to list\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n def test_form_update_seasons(self):\n \"\"\"\n Update seasons indexes with all roles.\n \"\"\"\n indexes = self.get_all_indexes()\n\n for index in indexes:\n assert index.data_format == Index.SEASONS\n\n self.assertEqual(\n self.client.get(index.get_absolute_url()).status_code,\n 200)\n\n # Update the form with valid data\n response = self.client.post(\n index.get_absolute_url(), {\n \"name\": \"New name\",\n \"collection\": \"\",\n \"seasonindexperiod_set-TOTAL_FORMS\": \"1\",\n \"seasonindexperiod_set-INITIAL_FORMS\": \"0\",\n \"seasonindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"seasonindexperiod_set-0-id\": \"\",\n \"seasonindexperiod_set-0-index\": \"\",\n \"seasonindexperiod_set-0-from_date\": \"2012-01-01\",\n \"seasonindexperiod_set-0-value_at_hour_0\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_1\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_2\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_3\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_4\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_5\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_6\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_7\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_8\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_9\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_10\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_11\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_12\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_13\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_14\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_15\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_16\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_17\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_18\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_19\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_20\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_21\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_22\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_23\": \"2\",\n \"save_return\": \"Save and return to list\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n # Update the form with valid data, using 'save' button\n response = self.client.post(\n index.get_absolute_url(), {\n \"name\": \"New name\",\n \"collection\": \"\",\n \"timezone\": \"Europe/Copenhagen\",\n \"seasonindexperiod_set-TOTAL_FORMS\": \"1\",\n \"seasonindexperiod_set-INITIAL_FORMS\": \"0\",\n \"seasonindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"seasonindexperiod_set-0-id\": \"\",\n \"seasonindexperiod_set-0-index\": \"\",\n \"seasonindexperiod_set-0-from_date\": \"2012-01-01\",\n \"seasonindexperiod_set-0-value_at_hour_0\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_1\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_2\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_3\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_4\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_5\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_6\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_7\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_8\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_9\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_10\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_11\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_12\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_13\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_14\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_15\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_16\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_17\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_18\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_19\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_20\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_21\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_22\": \"2\",\n \"seasonindexperiod_set-0-value_at_hour_23\": \"2\",\n \"save\": \"Save\"})\n self.assertNotContains(response, 'error', status_code=302)\n\n # Update the form with invalid data\n response = self.client.post(\n index.get_absolute_url(), {\n \"name\": \"New name\",\n \"collection\": \"\",\n \"seasonindexperiod_set-TOTAL_FORMS\": \"1\",\n \"seasonindexperiod_set-INITIAL_FORMS\": \"0\",\n \"seasonindexperiod_set-MAX_NUM_FORMS\": \"1000\",\n \"seasonindexperiod_set-0-id\": \"\",\n \"seasonindexperiod_set-0-index\": \"\",\n \"seasonindexperiod_set-0-from_date\": \"2012-01-01\",\n \"seasonindexperiod_set-0-value_at_hour_0\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_1\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_2\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_3\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_4\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_5\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_6\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_7\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_8\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_9\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_10\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_11\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_12\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_13\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_14\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_15\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_16\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_17\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_18\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_19\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_20\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_21\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_22\": \"a\",\n \"seasonindexperiod_set-0-value_at_hour_23\": \"a\",\n \"save_return\": \"Save and return to list\"})\n self.assertContains(response, 'error')\n" }, { "alpha_fraction": 0.5232884883880615, "alphanum_fraction": 0.5664762258529663, "avg_line_length": 39.104854583740234, "blob_id": "3c27c5efc66ee4c72d14ca34b7b4de6a056225e3", "content_id": "53f11f8edab75a2cfb33fd03185e2f33658041a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41308, "license_type": "no_license", "max_line_length": 79, "num_lines": 1030, "path": "/legacy/indexes/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module contains unittests for the indexes app.\n\"\"\"\n\nfrom decimal import Decimal\nfrom fractions import Fraction\nimport datetime\nimport math\nimport warnings\n\nfrom django.db.models import ProtectedError\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nimport pytz\n\nfrom gridplatform import trackuser\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.encryption.shell import Request\nfrom gridplatform.encryption.middleware import KeyLoaderMiddleware\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.users.models import User\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.encryption.testutils import encryption_context\n\nfrom . import IndexWarning\nfrom .models import Period\nfrom .models import Index\nfrom .models import Entry\nfrom .models.period import normalize_periods\nfrom .models import StandardMonthIndex\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass NormalizePeriodsTest(TestCase):\n \"\"\"\n Test the L{normalize_periods()} procedure of the L{indexes}\n application.\n \"\"\"\n\n def test_no_periods(self):\n \"\"\"\n Test that the empty list of periods remains the empty list of\n periods.\n \"\"\"\n self.assertEqual([], list(normalize_periods([])))\n\n def test_noncontiguous_periods(self):\n \"\"\"\n Test that noncontiguous periods are not modified.\n \"\"\"\n periods = [\n (datetime.datetime(2012, 12, 24, 1),\n datetime.datetime(2012, 12, 24, 3)),\n (datetime.datetime(2012, 12, 24, 4),\n datetime.datetime(2012, 12, 24, 7))]\n\n self.assertEqual(periods, list(normalize_periods(periods)))\n\n def test_contiguous_periods(self):\n \"\"\"\n Test that contiguous periods are coalesced.\n \"\"\"\n periods = [\n (datetime.datetime(2012, 12, 24, 1),\n datetime.datetime(2012, 12, 24, 3)),\n (datetime.datetime(2012, 12, 24, 3),\n datetime.datetime(2012, 12, 24, 7))]\n\n self.assertIn(\n (datetime.datetime(2012, 12, 24, 1),\n datetime.datetime(2012, 12, 24, 7)),\n normalize_periods(periods))\n\n def test_overlapping_periods(self):\n \"\"\"\n Test that normalizing overlapping periods causes an assertion\n error.\n \"\"\"\n periods = [\n (datetime.datetime(2012, 12, 24, 1),\n datetime.datetime(2012, 12, 24, 4)),\n (datetime.datetime(2012, 12, 24, 3),\n datetime.datetime(2012, 12, 24, 7))]\n\n with self.assertRaises(AssertionError):\n [p for p in normalize_periods(periods)]\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass IndexTest(TestCase):\n \"\"\"\n Test L{Index}, L{Entry}, L{DerivedIndexPeriod} and\n L{SeasonIndexPeriod} classes of the L{indexes} application.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Initializes the Index and Entry tables with a power price cost\n index, from around an interresting period.\n\n @postcondition: self.unit contains an Index instance,\n representing the mentioned interresting period.\n \"\"\"\n self.unit = Index(unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE pristabel\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SPOT,\n customer=None,\n utility_type=utilitytypes.METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n self.unit.save()\n\n hour = 0\n # 2011-03-27 2:00 happens to be a point in time where Denmark\n # enters daylight saving time (the clock is set back one\n # hour).\n self.DATETIME = datetime.datetime(2011, 3, 26, 0, tzinfo=pytz.utc)\n for price in [0.20, 0.22, 0.21, 0.25, 0.31, 0.37, # 0:00\n 0.41, 0.52, 0.52, 0.50, 0.47, 0.47, # 06:00\n 0.40, 0.40, 0.39, 0.58, 0.63, 0.70, # 12:00\n 0.65, 0.58, 0.51, 0.46, 0.33, 0.28, # 18:00\n 0.25, 0.22, 0.21, 0.25, 0.31, 0.37, # 0:00\n 0.41, 0.51, 0.52, 0.50, 0.41, 0.47, # 06:00\n 0.40, 0.40, 0.39, 0.58, 0.63, 0.70, # 12:00\n 0.65, 0.58, 0.56, 0.46, 0.33, 0.28]: # 18:00\n if hour != 15:\n entry = Entry(\n index=self.unit,\n from_timestamp=(\n self.DATETIME + datetime.timedelta(hours=hour)),\n to_timestamp=(\n self.DATETIME + datetime.timedelta(hours=hour + 1)),\n value=price)\n entry.save()\n hour += 1\n\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def assert_warning_category(self, warning_list, category,\n minimum_count=1):\n \"\"\"\n Assert that a C{warning} within a given C{category} has been\n issued a C{minimum_count} of times.\n \"\"\"\n if len(filter(lambda w: w.category == IndexWarning,\n warning_list)) < minimum_count:\n raise AssertionError(\n \"Less than %d warning(s) of category %r was issued\" %\n (minimum_count, category))\n\n def test_assert_warning_category(self):\n \"\"\"\n Test L{assert_warning_category()}.\n \"\"\"\n with self.assertRaises(AssertionError):\n self.assert_warning_category([], IndexWarning)\n\n with warnings.catch_warnings(record=True) as w:\n warnings.warn(\"this is an IndexWarning!\", IndexWarning)\n self.assert_warning_category(w, IndexWarning)\n\n with warnings.catch_warnings(record=True) as w:\n warnings.warn(\"this is an IndexWarning!\", IndexWarning)\n warnings.warn(\"this is not an IndexWarning!\")\n self.assert_warning_category(w, IndexWarning)\n\n with warnings.catch_warnings(record=True) as w:\n warnings.warn(\"this is not an IndexWarning!\")\n with self.assertRaises(AssertionError):\n self.assert_warning_category(w, IndexWarning)\n\n def test_minimize_contiguous_missing_entries(self):\n \"\"\"\n Test that contiguous minimization across missing entries does not fail.\n \"\"\"\n result = self.unit.minimize_contiguous(\n self.DATETIME + datetime.timedelta(\n days=1, hours=23),\n self.DATETIME + datetime.timedelta(\n days=2, hours=23),\n datetime.timedelta(hours=2))\n\n self.assertIsNotNone(result)\n\n def test_minimize_noncontiguous_missing_entries(self):\n \"\"\"\n Test that noncontiguous minimization across missing entries does not\n fail.\n \"\"\"\n result = list(\n self.unit.minimize_noncontiguous(\n self.DATETIME,\n self.DATETIME + datetime.timedelta(\n days=3),\n datetime.timedelta(hours=60)))\n\n self.assertNotEqual(len(result), 0)\n\n def test_minimize_noncontiguous_missing_entries_before(self):\n \"\"\"\n Test that noncontiguous minimization across missing entries in start of\n interval does not fail.\n \"\"\"\n self.assertEqual(\n [(self.DATETIME - datetime.timedelta(hours=1),\n self.DATETIME - datetime.timedelta(minutes=30)),\n (self.DATETIME, self.DATETIME + datetime.timedelta(hours=1))],\n list(\n self.unit.minimize_noncontiguous(\n self.DATETIME - datetime.timedelta(hours=1),\n self.DATETIME + datetime.timedelta(hours=1),\n datetime.timedelta(hours=1, minutes=30))))\n\n def test_minimize_noncontiguous_missing_entries_after(self):\n \"\"\"\n Test that noncontiguous minimization across missing entries in end of\n interval does not fail.\n \"\"\"\n self.assertEqual(\n [(self.DATETIME + datetime.timedelta(days=1, hours=23),\n self.DATETIME + datetime.timedelta(days=2, minutes=30))],\n list(\n self.unit.minimize_noncontiguous(\n self.DATETIME + datetime.timedelta(days=1, hours=23),\n self.DATETIME + datetime.timedelta(days=2, hours=1),\n datetime.timedelta(hours=1, minutes=30))))\n\n def test_minimize_noncontiguous_missing_entries_middle(self):\n \"\"\"\n Test that noncontiguous minimization across missing entries in middle\n of interval does not fail.\n \"\"\"\n self.assertEqual(\n [(self.DATETIME + datetime.timedelta(hours=14),\n self.DATETIME + datetime.timedelta(hours=15, minutes=30)),\n (self.DATETIME + datetime.timedelta(hours=16),\n self.DATETIME + datetime.timedelta(hours=17))],\n list(\n self.unit.minimize_noncontiguous(\n self.DATETIME + datetime.timedelta(hours=14),\n self.DATETIME + datetime.timedelta(hours=17),\n datetime.timedelta(hours=2, minutes=30))))\n\n def test_noncontiguous_minimization_a_bit_expensive(self):\n \"\"\"\n Test noncontiguous minimization that will include part of the\n most expensive period.\n \"\"\"\n result = list(\n self.unit.minimize_noncontiguous(\n self.DATETIME + datetime.timedelta(hours=16, minutes=53),\n self.DATETIME + datetime.timedelta(hours=18, minutes=30),\n datetime.timedelta(hours=1, minutes=7)))\n\n self.assertEqual(len(result), 2)\n self.assertIn(\n (self.DATETIME + datetime.timedelta(hours=16, minutes=53),\n self.DATETIME + datetime.timedelta(hours=17, minutes=30)), result)\n self.assertIn(\n (self.DATETIME + datetime.timedelta(hours=18),\n self.DATETIME + datetime.timedelta(hours=18, minutes=30)), result)\n\n def test_minimize_contiguous_cheapest_at_end_of_entry(self):\n \"\"\"\n Test that the L{minimize_contiguous()} method returns the\n right result when the result is at the end of an entry.\n \"\"\"\n self.assertEqual(\n self.DATETIME + datetime.timedelta(hours=1, minutes=45),\n self.unit.minimize_contiguous(\n self.DATETIME + datetime.timedelta(hours=1, minutes=30),\n self.DATETIME + datetime.timedelta(hours=3, minutes=30),\n datetime.timedelta(hours=1, minutes=15)))\n\n def test_minimize_contiguous_cheapest_at_start_of_entry(self):\n \"\"\"\n Test that the L{minimize_contiguous()} method returns the\n right result, when the result is at the start of an entry.\n \"\"\"\n self.assertEqual(\n self.DATETIME + datetime.timedelta(hours=2),\n self.unit.minimize_contiguous(\n self.DATETIME + datetime.timedelta(hours=2),\n self.DATETIME + datetime.timedelta(hours=4, minutes=30),\n datetime.timedelta(hours=1, minutes=15)))\n\n def test_minimize_contiguous_cheapest_at_end_of_interval(self):\n \"\"\"\n Test that the L{Index.minimize_contiguous()} method returns the\n right result, when the result is at the end of the interval.\n \"\"\"\n self.assertEqual(\n self.DATETIME + datetime.timedelta(days=1, hours=1, minutes=34),\n self.unit.minimize_contiguous(\n self.DATETIME + datetime.timedelta(days=1),\n self.DATETIME + datetime.timedelta(days=1,\n hours=2, minutes=34),\n datetime.timedelta(hours=1)))\n\n def test_generate_true_periods(self):\n \"\"\"\n Test the L{Index.generate_true_periods()} method against a selected\n number of operators.\n \"\"\"\n periods = self.unit.generate_true_periods(\n self.DATETIME,\n self.DATETIME + datetime.timedelta(days=1),\n lambda x: x <= PhysicalQuantity('0.29', self.unit.unit))\n self.assertIn((self.DATETIME,\n self.DATETIME + datetime.timedelta(hours=4)),\n periods)\n self.assertIn((self.DATETIME + datetime.timedelta(hours=23),\n self.DATETIME + datetime.timedelta(hours=24)),\n periods)\n\n periods = self.unit.generate_true_periods(\n self.DATETIME,\n self.DATETIME + datetime.timedelta(days=1),\n lambda x: x != PhysicalQuantity('0.40', self.unit.unit))\n self.assertIn((self.DATETIME,\n self.DATETIME + datetime.timedelta(hours=12)),\n periods)\n self.assertIn((self.DATETIME + datetime.timedelta(hours=14),\n self.DATETIME + datetime.timedelta(hours=15)),\n periods)\n self.assertIn((self.DATETIME + datetime.timedelta(hours=16),\n self.DATETIME + datetime.timedelta(hours=24)),\n periods)\n\n def test_derived_index_with_offset_scenario(self):\n \"\"\"\n Test the \"Derived Index with Offset\" scenario.\n \"\"\"\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE gr&oslash;n tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.07\"))\n\n with warnings.catch_warnings(record=True):\n periods = derived.generate_true_periods(\n self.DATETIME - datetime.timedelta(days=1),\n self.DATETIME + datetime.timedelta(days=3),\n lambda x: x <= PhysicalQuantity('0.29', derived.unit))\n self.assertIn(\n (self.DATETIME,\n self.DATETIME + datetime.timedelta(hours=3)),\n periods)\n self.assertIn(\n (self.DATETIME + datetime.timedelta(days=1, hours=1),\n self.DATETIME + datetime.timedelta(days=1, hours=3)),\n periods)\n self.assertEqual(len(periods), 2)\n\n def test_dependency(self):\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE gr&oslash;n tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.07\"))\n\n self.assertRaises(\n ProtectedError, lambda:\n self.unit.delete())\n\n def test_derived_index_with_roof_scenario(self):\n \"\"\"\n Test the \"Derived Index with Roof\" scenario.\n \"\"\"\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE lofttariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.12\"),\n roof=Decimal(\"0.50\"))\n\n with warnings.catch_warnings(record=True):\n # The small saving at 2011-03-27 15:00 along with the\n # large savings around 2011-03-27 03:00 is included in the\n # minimal contiguous usage when considering the derived\n # index.\n result = derived.minimize_contiguous(\n self.DATETIME + datetime.timedelta(hours=18),\n self.DATETIME + datetime.timedelta(days=1, hours=18),\n datetime.timedelta(hours=8))\n self.assertEqual(self.DATETIME + datetime.timedelta(hours=22),\n result)\n\n # The cost increment at 2011-03-27 17.00 is larger than\n # that of 2011-03-26 19.00 in the original index.\n non_derived_result = self.unit.minimize_contiguous(\n self.DATETIME + datetime.timedelta(hours=18),\n self.DATETIME + datetime.timedelta(days=1, hours=18),\n datetime.timedelta(hours=20))\n self.assertEqual(self.DATETIME + datetime.timedelta(hours=19),\n non_derived_result)\n\n def test_derived_index_half_flat_scenario(self):\n \"\"\"\n Test the \"Derived Index - Half Flat\" scenario.\n \"\"\"\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE 50/50 tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.20\"),\n coefficient=Decimal(\"0.50\"))\n\n with warnings.catch_warnings(record=True):\n periods = derived.generate_true_periods(\n self.DATETIME - datetime.timedelta(days=1),\n self.DATETIME + datetime.timedelta(days=3),\n lambda x: x <= PhysicalQuantity('0.35', derived.unit))\n self.assertIn(\n (self.DATETIME,\n self.DATETIME + datetime.timedelta(hours=4)),\n periods)\n self.assertIn(\n (self.DATETIME + datetime.timedelta(hours=23),\n self.DATETIME + datetime.timedelta(days=1, hours=4)),\n periods)\n self.assertIn(\n (self.DATETIME + datetime.timedelta(days=1, hours=23),\n self.DATETIME + datetime.timedelta(days=2, hours=0)),\n periods)\n self.assertEqual(len(periods), 3)\n\n def test_manual_index_with_seasons_scenario(self):\n \"\"\"\n Test the \"Manual Index with Seasons\" scenario.\n \"\"\"\n seasons = Index(\n unit=\"currency_eur*kilowatt^-1*hour^-1\",\n name=\"Temporada Alta/Temporada Baja\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SEASONS,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n seasons.save()\n\n alta_value_at_hour = [Decimal(\"0.043\") for _ in range(24)]\n for i in range(7, 9) + range(17, 20):\n alta_value_at_hour[i] = Decimal(\"0.052\")\n\n season = seasons.seasonindexperiod_set.create(\n from_date=datetime.date(year=2012, month=4, day=1),\n value_at_hour=alta_value_at_hour)\n\n self.assertEqual(\n Decimal(\"0.052\"),\n list(\n season.generate_entries(\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(\n year=2012, month=5, day=1, hour=8)),\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(\n year=2012, month=5, day=1, hour=9))))[0].value)\n\n self.assertAlmostEqual(\n seasons.calculate_average_value(\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=5, day=1, hour=8)),\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=5, day=1, hour=9))).\n convert(seasons.unit),\n Fraction('0.052'))\n\n seasons.seasonindexperiod_set.create(\n from_date=datetime.date(year=2012, month=12, day=20),\n value_at_hour=alta_value_at_hour)\n\n baja_value_at_hour = [Decimal(\"0.032\") for _ in range(24)]\n for i in range(7, 9) + range(17, 20):\n baja_value_at_hour[i] = Decimal(\"0.049\")\n\n seasons.seasonindexperiod_set.create(\n from_date=datetime.date(year=2012, month=1, day=1),\n value_at_hour=baja_value_at_hour)\n\n seasons.seasonindexperiod_set.create(\n from_date=datetime.date(year=2012, month=9, day=1),\n value_at_hour=baja_value_at_hour)\n\n self.assertAlmostEqual(\n seasons.calculate_average_value(\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=1, day=1, hour=0)),\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=1, day=1, hour=1))).\n convert(seasons.unit),\n Fraction('0.032'))\n\n # Manually figure out what the definite integral of 2012\n # should equal:\n alta_days = ((datetime.date(year=2012, month=9, day=1)\n - datetime.date(year=2012, month=4, day=1))\n + (datetime.date(year=2013, month=1, day=1)\n - datetime.date(year=2012, month=12, day=20))).days\n baja_days = (\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2013, month=1, day=1)) -\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=1, day=1))).days - alta_days\n\n expected_result = \\\n alta_days * (19 * Fraction('0.043') + 5 * Fraction('0.052')) + \\\n baja_days * (19 * Fraction('0.032') + 5 * Fraction('0.049'))\n\n self.assertAlmostEqual(\n expected_result,\n (\n seasons.calculate_average_value(\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=1, day=1)),\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2013, month=1, day=1))) * (\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2013, month=1, day=1)) -\n pytz.timezone(\"Europe/Copenhagen\").localize(\n datetime.datetime(year=2012, month=1, day=1))\n ).total_seconds() / 3600).convert(seasons.unit))\n\n def test_satisfies_search(self):\n \"\"\"\n Check the L{Index.satisfies_search()} method.\n \"\"\"\n self.assertTrue(self.unit.satisfies_search(\"ist\"))\n self.assertFalse(self.unit.satisfies_search(\"table\"))\n\n def test_derived_index_period_transition(self):\n \"\"\"\n Test transition from one period into another for derived\n indexes.\n \"\"\"\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE 50/50 tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n\n first_constant = Decimal(\"0.20\")\n first_coefficient = Decimal(\"0.50\")\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=datetime.date(year=2011, month=3, day=26),\n constant=first_constant,\n coefficient=first_coefficient)\n\n second_constant = Decimal(\"1.40\")\n second_coefficient = Decimal(\"0.90\")\n\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=datetime.date(year=2011, month=3, day=27),\n constant=second_constant,\n coefficient=second_coefficient)\n\n timezone = pytz.timezone(\"Europe/Copenhagen\")\n\n start = timezone.localize(datetime.datetime(2011, 3, 26, 12))\n transition = timezone.localize(datetime.datetime(2011, 3, 27, 0))\n end = timezone.localize(datetime.datetime(2011, 3, 27, 12))\n\n # start to transition has 11 values since 15:00 is excluded (see setUp)\n # transition to end has 11 values due to daylight savings\n expected_result = self.unit.calculate_average_value(\n start, transition) * first_coefficient + \\\n PhysicalQuantity(first_constant, derived.unit) * 11 + \\\n self.unit.calculate_average_value(transition, end) * \\\n second_coefficient + \\\n PhysicalQuantity(second_constant, derived.unit) * 11\n\n actual_result = derived.calculate_average_value(start, end)\n\n self.assertEqual(actual_result.units, expected_result.units)\n self.assertAlmostEqual(actual_result.value, expected_result.value)\n\n def test_get_derivatives(self):\n \"\"\"\n Test the L{Index.get_derivatives()} method.\n \"\"\"\n # Create derived as a derivative of self.unit.\n derived = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE gr&oslash;n tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived.save()\n derived.derivedindexperiod_set.create(\n other_index=self.unit,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.07\"))\n\n # The derived Index should be a derivative of self.unit, but\n # not vice versa.\n self.assertIn(derived, self.unit.get_derivatives())\n self.assertNotIn(self.unit, derived.get_derivatives())\n\n # Create derived2 as a derivative of derived.\n derived2 = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"NOE gr&oslash;n tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.DERIVED,\n timezone=\"Europe/Copenhagen\",\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n derived2.save()\n derived2.derivedindexperiod_set.create(\n other_index=derived,\n from_date=self.DATETIME.date(),\n constant=Decimal(\"0.07\"))\n\n # Derived2 is a derivative of derived, but not vice versa.\n self.assertIn(derived2, derived.get_derivatives())\n self.assertNotIn(derived, derived2.get_derivatives())\n\n # Derived 2 is a derivative of self.unit since it is a\n # derivative of derived which is a derivative of self.unit.\n self.assertIn(derived2, self.unit.get_derivatives())\n\n # Since derived2 is a derivative of self.unit, the inverse\n # does not hold.\n self.assertNotIn(self.unit, derived2.get_derivatives())\n\n\nclass IndexEncryptionTest(TestCase):\n \"\"\"\n Tests for L{Index} encryption capabilities.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Establish a C{self.request} L{Request} that can be used to\n encrypt/decrypt L{EncryptedModel} instances having\n C{self.customer} as encryption ID.\n \"\"\"\n with encryption_context():\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n User.objects.create_user(\n 'testuser', 'password',\n user_type=User.CUSTOMER_USER, customer=self.customer)\n\n self.request = Request('testuser', 'password')\n KeyLoaderMiddleware().process_request(self.request)\n\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n KeyLoaderMiddleware().process_response(self.request, None)\n\n def test_encryption_with_customer(self):\n \"\"\"\n Test L{Index._encrypt()} and L{Index._decrypt()} for L{Index}es\n with C{customer != None}.\n \"\"\"\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name_plain=\"NOE 50/50 tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=\"Europe/Copenhagen\",\n data_format=Index.DERIVED,\n customer=self.customer,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.assertEqual(\"NOE 50/50 tariff\", index.name_plain)\n self.assertIsNone(index.name)\n index.save()\n self.assertIsNotNone(index.name)\n\n loaded_index = Index.objects.get(id=index.id)\n self.assertEqual(\"NOE 50/50 tariff\", loaded_index.name_plain)\n\n def test_encryption_without_customer(self):\n \"\"\"\n Test L{Index._encrypt()} and L{Index._decrypt()} for L{Index}es\n with C{customer is None}.\n \"\"\"\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"Nordpool spot-tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=\"Europe/Copenhagen\",\n data_format=Index.SPOT,\n customer=None,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n index.save()\n\n loaded_index = Index.objects.get(id=index.id)\n self.assertEqual(\"Nordpool spot-tariff\", loaded_index.name)\n self.assertEqual(\"Nordpool spot-tariff\", loaded_index.name_plain)\n\n def test_get_condensed_samples(self):\n \"\"\"\n \"\"\"\n timezone = pytz.timezone(\"Europe/Copenhagen\")\n index = Index(\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n name=\"Nordpool spot-tariff\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=timezone,\n data_format=Index.SPOT,\n customer=None,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n index.save()\n\n start_time = timezone.localize(datetime.datetime(2012, 1, 1))\n current_time = start_time\n for i in range(24 * 7):\n index.entry_set.create(\n from_timestamp=current_time,\n to_timestamp=current_time + datetime.timedelta(hours=1),\n value=Decimal(math.sin(i)))\n current_time += datetime.timedelta(hours=1)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass PeriodTest(TestCase):\n \"\"\"\n Test the Period abstract class.\n \"\"\"\n\n def test_abstract_method(self):\n \"\"\"\n Test that abstract methods raise L{NotImplementedError}.\n \"\"\"\n unit = Period()\n self.assertRaises(\n NotImplementedError,\n unit.generate_entries,\n datetime.datetime(year=2012, month=11, day=19, hour=3),\n datetime.datetime(year=2012, month=11, day=19, hour=9))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestStandardMonthIndex(TestCase):\n \"\"\"\n Test the L{StandardMonthIndex} model.\n \"\"\"\n\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.unit = StandardMonthIndex.objects.create(\n customer=self.customer,\n role=DataRoleField.STANDARD_HEATING_DEGREE_DAYS,\n unit='kelvin*day',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating,\n name_plain='standard month index',\n data_format=Index.STANDARD_MONTH_INDEX,\n timezone='Europe/Copenhagen',\n january=Decimal('1.234'),\n february=Decimal('5.678'),\n march=Decimal('9.10'),\n april=Decimal('11.12'),\n may=Decimal('13.14'),\n june=Decimal('151.617'),\n july=Decimal('181.920'),\n august=Decimal('212.223'),\n september=Decimal('242.526'),\n october=Decimal('272.829'),\n november=Decimal('3.0'),\n december=Decimal('31.32'))\n\n def tearDown(self):\n pass\n\n def test_get_samples(self):\n \"\"\"\n Test the L{StandardMonthIndex.get_samples()} method\n \"\"\"\n samples_iterator = iter(\n self.unit.get_samples(\n datetime.datetime(2012, 12, 24, tzinfo=pytz.utc),\n datetime.datetime(2013, 12, 25, tzinfo=pytz.utc)))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.physical_quantity, PhysicalQuantity(0, 'kelvin*day'))\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2012, 12, 24, tzinfo=pytz.utc))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2012, 12, 31, 23, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity((7 * 24 + 23) * Fraction('31.32') / (31 * 24),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 1, 31, 23, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') /\n Fraction(31 * 24) + Fraction('1.234'), 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 2, 28, 23, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / Fraction(31 * 24) +\n Fraction('1.234') + Fraction('5.678'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 3, 31, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 4, 30, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 5, 31, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') +\n Fraction('9.10') + Fraction('11.12') +\n Fraction('13.14'), 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 6, 30, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 7, 31, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 8, 31, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920') + Fraction('212.223'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 9, 30, 22, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920') + Fraction('212.223') +\n Fraction('242.526'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 10, 31, 23, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920') + Fraction('212.223') +\n Fraction('242.526') + Fraction('272.829'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 11, 30, 23, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920') + Fraction('212.223') +\n Fraction('242.526') + Fraction('272.829') + Fraction('3.0'),\n 'kelvin*day'))\n\n sample = next(samples_iterator)\n self.assertEqual(\n sample.timestamp,\n datetime.datetime(2013, 12, 25, tzinfo=pytz.utc))\n self.assertEqual(\n sample.physical_quantity,\n PhysicalQuantity(\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) +\n Fraction('1.234') + Fraction('5.678') + Fraction('9.10') +\n Fraction('11.12') + Fraction('13.14') + Fraction('151.617') +\n Fraction('181.920') + Fraction('212.223') +\n Fraction('242.526') + Fraction('272.829') + Fraction('3.0') +\n (24 * 24 + 1) * Fraction('31.32') / (31 * 24),\n 'kelvin*day'))\n\n with self.assertRaises(StopIteration):\n sample = next(samples_iterator)\n\n def test_calculate_development(self):\n \"\"\"\n Test the L{StandardMonthIndex.calculate_development()} method\n \"\"\"\n # Check that our calculation equals the actual fraction result.\n self.assertEqual(\n Fraction(35238237, 31000),\n (7 * 24 + 23) * Fraction('31.32') / (31 * 24) + Fraction('1.234') +\n Fraction('5.678') + Fraction('9.10') + Fraction('11.12') +\n Fraction('13.14') + Fraction('151.617') + Fraction('181.920') +\n Fraction('212.223') + Fraction('242.526') + Fraction('272.829') +\n Fraction('3.0') + (24 * 24 + 1) * Fraction('31.32') / (31 * 24))\n\n self.assertEqual(\n self.unit.calculate_development(\n datetime.datetime(2012, 12, 24, tzinfo=pytz.utc),\n datetime.datetime(2013, 12, 25, tzinfo=pytz.utc)),\n self.unit.create_range_sample(\n datetime.datetime(2012, 12, 24, tzinfo=pytz.utc),\n datetime.datetime(2013, 12, 25, tzinfo=pytz.utc),\n PhysicalQuantity(Fraction(35238237, 31000), self.unit.unit)))\n" }, { "alpha_fraction": 0.6193771362304688, "alphanum_fraction": 0.6243944764137268, "avg_line_length": 32.410404205322266, "blob_id": "f40dc0d2e4e506eef7b88998bb94a57ee476348b", "content_id": "53ce510e18796622f712757f5505167eb3f3e27d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5780, "license_type": "no_license", "max_line_length": 79, "num_lines": 173, "path": "/gridagentserver-protocol/gridagentserver_protocol/messages.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"Helper module and entry-point with the parse()/write() functions.\"\"\"\n\nimport calendar\nimport datetime\nimport re\nimport logging\nfrom struct import Struct\n\nfrom pytz import utc\n\nlogger = logging.getLogger(__name__)\n\n# 1970-01-01 base to 2000-01-01 base ...\nepochoffset = calendar.timegm(datetime.date(2000, 1, 1).timetuple())\n\n\ndef timestamp_to_datetime(timestamp):\n return datetime.datetime.utcfromtimestamp(\n timestamp + epochoffset).replace(tzinfo=utc)\n\n\ndef datetime_to_timestamp(datetime):\n return calendar.timegm(datetime.timetuple()) - epochoffset\n\n\nclass UnknownMessageTypeError(ValueError):\n pass\n\n\nclass Header(object):\n # message-size, type-id, flags\n struct = Struct('!IxxBB')\n\n def __init__(self, length, MessageType, flags=0):\n self.length = length\n self.datalength = length - self.struct.size\n self.MessageType = MessageType\n self.flags = flags\n\n @classmethod\n def unpack(cls, read, version):\n length, type_id, flags = read(cls.struct)\n from message_types import message_types\n try:\n message_type = message_types[type_id]\n except IndexError:\n raise UnknownMessageTypeError(\n 'Message type %s unknown' % (type_id,))\n return cls(length, message_type, flags)\n\n def pack(self, version):\n from message_types import message_types\n type_id = message_types.index(self.MessageType)\n return self.struct.pack(self.length, type_id, self.flags)\n\n def __repr__(self):\n return '<{} {}>'.format(\n self.__class__.__name__,\n ', '.join(['{}={}'.format(k, repr(v))\n for k, v in self.__dict__.iteritems()])\n )\n\n\nclass Message(object):\n def accept(self, visitor):\n classname = self.__class__.__name__\n underscores_classname = re.sub('([a-z0-9])([A-Z])',\n r'\\1_\\2',\n classname).lower()\n methodname = 'visit_{}'.format(underscores_classname)\n # only catch/handle the immediate failure if the method does not exist\n try:\n method = getattr(visitor, methodname)\n except AttributeError:\n return\n method(self)\n\n # implement in children\n # (method signature here as a reminder...)\n # return child instance\n @classmethod\n def unpack(cls, read, version):\n # \"read\" is an instance of BufferReader\n raise Exception('Implementation missing')\n\n # implement in children\n # return data string\n def pack(self, version):\n # should normally use self._pack internallyb\n raise Exception('Implementation missing')\n\n # Helper for pack() implementations --- data should be a list of strings.\n # This is convenient for use with Struct.pack() --- each call returns a\n # string. (And building a list rather than a string is more efficient and\n # feels \"cleaner\" from my point of view. (I may use list comprehensions\n # \"directly\".))\n #\n # (Using Struct.pack_into() instead of Struct.pack() is inconvenient, as\n # that requires a preallocated buffer and management of the write offset.\n # Computing the size for preallocating the buffer for nested structures\n # takes about as much code as subsequently actually writing the data to the\n # buffer.)\n def _pack(self, data, version, header_flags=0):\n content_bytes = ''.join(data)\n package_size = Header.struct.size + len(content_bytes)\n header = Header(package_size, self.__class__, header_flags)\n return header.pack(version) + content_bytes\n\n # for debugging/logging\n def __repr__(self):\n return '<{} {}>'.format(\n self.__class__.__name__,\n ', '.join(['{}={}'.format(k, repr(v))\n for k, v in self.__dict__.iteritems()])\n )\n\n\nclass BufferReader(object):\n \"\"\"\n Helper class for deserialising data with struct.Struct: Keep track of\n offset for reading, read sequence of same Struct to list.\n \"\"\"\n def __init__(self, data):\n self.offset = 0\n self.data = data\n\n def _read_single(self, struct):\n result = struct.unpack_from(self.data, self.offset)\n self.offset += struct.size\n return result\n\n def _read_list(self, struct, count):\n result = []\n for n in range(count):\n result.append(self._read_single(struct))\n return result\n\n def __call__(self, struct, count=None):\n if count is not None:\n return self._read_list(struct, count)\n else:\n return self._read_single(struct)\n\n def raw(self, count=None):\n if count is not None:\n new_offset = self.offset + count\n else:\n new_offset = len(self.data)\n assert new_offset <= len(self.data)\n result = self.data[self.offset:new_offset]\n self.offset = new_offset\n return result\n\n\ntimestamp_struct = Struct('!I')\n\n\n# Decrypt stream; we read from that; it reads from actual input and decrypts.\n# Makes testing easier; we can provide a directly unencrypted \"stream\".\ndef parse(stream, version):\n header_read = BufferReader(stream.read(Header.struct.size))\n header = Header.unpack(header_read, version)\n read = BufferReader(stream.read(header.datalength))\n logger.debug('Received header: %r, payload: %r', header, read.data)\n return header.MessageType.unpack(header, read, version)\n\n\n# Encrypt stream; we write to that; it encrypts and writes to actual output.\n# Makes testing easier; we may use an unencrypted \"stream\".\ndef write(stream, message, version):\n bytes = message.pack(version)\n logger.debug('Sending message: %r, bytes: %r', message, bytes)\n stream.write(bytes)\n" }, { "alpha_fraction": 0.5489667654037476, "alphanum_fraction": 0.5516621470451355, "avg_line_length": 38.05263137817383, "blob_id": "abb8ac492803a25f2a4f2ca1aa08a2f676b1cd5a", "content_id": "e5009086fc6dc91e695bfe6a916d9601a4f16ce9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2226, "license_type": "no_license", "max_line_length": 78, "num_lines": 57, "path": "/legacy/energinet_co2/importer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom legacy.indexes.models import Entry\n\nfrom .ftpclient import fetch_online\nfrom .models import ModelBinding\nfrom .parser import parse_online\n\n\ndef fetch_import_day(date):\n bindings = ModelBinding.objects.all()\n if not len(bindings):\n # not set up\n return\n\n # forecast = fetch_forecast(date)\n # if forecast is not None:\n # forecast = parse_forecast(forecast)\n # assert forecast['date'] == date\n online = fetch_online(date)\n if online is not None:\n online = parse_online(online)\n for binding in bindings:\n # normally just one, but might as well handle several...\n # if forecast:\n # for from_hour, to_hour, value in forecast['data']:\n # from_timestamp = datetime.datetime.combine(date, from_hour)\n # to_timestamp = datetime.datetime.combine(date, to_hour)\n # if to_timestamp < from_timestamp:\n # to_timestamp = to_timestamp + datetime.timedelta(days=1)\n # aware_from_timestamp = tz.localize(from_timestamp)\n # aware_to_timestamp = tz.localize(to_timestamp)\n # binding.forecast_index.entry_set.get_or_create(\n # from_timestamp=aware_from_timestamp,\n # to_timestamp=aware_to_timestamp,\n # value=value)\n if online:\n for line in online['data']:\n from_timestamp = line[0]\n to_timestamp = from_timestamp + datetime.timedelta(minutes=5)\n value = line[16]\n try:\n entry = binding.index.entry_set.get(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp)\n if entry.value != value:\n entry.value = value\n entry.save()\n except Entry.DoesNotExist:\n binding.index.entry_set.create(\n from_timestamp=from_timestamp,\n to_timestamp=to_timestamp,\n value=value)\n" }, { "alpha_fraction": 0.7055359482765198, "alphanum_fraction": 0.7096584439277649, "avg_line_length": 32.959999084472656, "blob_id": "3095233dabbbffbae2bac2821d6e2af681242f00", "content_id": "aa4d33926790c10294bab56f1226ae3027528498", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 70, "num_lines": 50, "path": "/gridplatform/cost_compensations/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nimport rest_framework.reverse\n\nfrom gridplatform.datasequences.views import HourlyDataView\nfrom gridplatform.rest.viewsets import NestedMixin\n\nfrom . import models\nfrom . import serializers\n\n\nclass HourlyView(NestedMixin, HourlyDataView):\n method_name = 'value_sequence'\n\n def get(self, request, datasequence_id=None, format=None):\n datasequence = get_object_or_404(\n models.CostCompensation, pk=datasequence_id)\n timezone = datasequence.customer.timezone\n return self._get(request, datasequence, timezone)\n\n\nclass CostCompensation(NestedMixin, viewsets.ModelViewSet):\n model = models.CostCompensation\n serializer_class = serializers.CostCompensation\n filter_fields = ('name', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyView.as_view()\n return view_fn(request, datasequence_id=pk)\n\n\nclass FixedCompensationPeriod(NestedMixin, viewsets.ModelViewSet):\n model = models.FixedCompensationPeriod\n serializer_class = serializers.FixedCompensationPeriod\n\n def create(self, request, *args, **kwargs):\n request.DATA['datasequence'] = rest_framework.reverse.reverse(\n viewname='api:cost_compensations:costcompensation-detail',\n kwargs={\n 'pk': kwargs.pop('datasequence_id'),\n }\n )\n return super(FixedCompensationPeriod, self).create(\n request, *args, **kwargs)\n" }, { "alpha_fraction": 0.6330492496490479, "alphanum_fraction": 0.6354166865348816, "avg_line_length": 26.428571701049805, "blob_id": "1dd2e465316b0fed7f26fce5d3fca1dfcce7eddd", "content_id": "4402feb63e3806a03361ebd5729f1d9ea722f081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2112, "license_type": "no_license", "max_line_length": 79, "num_lines": 77, "path": "/gridagentserver-protocol/gridagentserver_protocol/datatypes.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"Data types used for members in message objects on the Python side.\"\"\"\n\n# also used outside the protocol module --- but in code depending on the\n# protocol module, so extracting this to a separate module/repository would not\n# provide any clear benefits\n\nfrom collections import namedtuple\n\n# Measurement data format:\n#\n# list of \"meter_data\"\n# meter_data: \"meter_id\", list of \"measurement_set\"\n# meter_id: \"connection_type\", \"id_number\"\n# connection_type: enum;\n# \"unknown\",\n# \"ZigBee\",\n# \"MBus primary\",\n# \"MBus secondary\",\n# \"Kamstrup UtiliDriver\"\n# ...?\n# id_number: a local numeric ID specific to the connection technology\n# measurement_set: timestamp, list of \"measurement\"\n# measurement: \"type\", \"unit\", \"input number\", \"value\"\n# type: enum;\n# \"unknown\",\n# \"electricity consumption\",\n# ... (whatever from M-Bus medium)\n# unit: enum; \"unknown\", \"mWh\", \"mW\", ...?\n\nMeterData = namedtuple('MeterData', ['meter', 'measurement_sets'])\nMeter = namedtuple('Meter', ['connection_type', 'id'])\nMeasurementSet = namedtuple('MeasurementSet', ['timestamp', 'measurements'])\nMeasurement = namedtuple('Measurement',\n ['type', 'unit', 'input_number', 'value'])\n\nRule = namedtuple('Rule', ['relay_on', 'start_time', 'end_time'])\nRuleSet = namedtuple('RuleSet', ['override_timeout', 'rules', 'meters'])\nPrice = namedtuple('Price', ['start_timestamp', 'end_timestamp', 'price'])\n\nVersion = namedtuple(\n 'Version', ['major', 'minor', 'revision', 'revisionstring'])\n\nconnection_types = [\n 'unknown',\n 'ZigBee',\n 'MBus primary',\n # Meter IDs in MBus GM legacy follow a spec. from the old GridPortal 1.5\n # days. This should be removed in future software version of the GridAgents\n 'MBus GM legacy',\n 'Kamstrup UtiliDriver',\n 'PLC Mitsubishi FX1S',\n 'Modbus',\n 'Aux Serial',\n 'MBus secondary',\n]\n\nmeasurement_types = [\n 'unknown',\n 'electricity',\n 'heat',\n]\n\nmeasurement_units = [\n 'unknown',\n 'mWh',\n 'mW',\n 'pulse count',\n 'um^3',\n 'um^3/h',\n 'mdegC',\n 'mV',\n 'mA',\n 'mHz',\n 'g',\n 'mbar',\n 's',\n]\n" }, { "alpha_fraction": 0.6397188305854797, "alphanum_fraction": 0.6405975222587585, "avg_line_length": 36.93333435058594, "blob_id": "4ea3bb7a1c260dc652afe690bed1026d24c50ff1", "content_id": "51fa0b77eb905340ed1fa6fa7109cc8819c542df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1138, "license_type": "no_license", "max_line_length": 62, "num_lines": 30, "path": "/energymanager/led_light_site/restricted_urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns\nfrom django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = patterns(\n 'energymanager.led_light_view.views',\n url(r'^project/(?P<customer_id>\\d+)/$',\n views.LedLightProjectList.as_view(),\n name='led-light-project-list'),\n url(r'^project/content/(?P<customer_id>\\d+)/$',\n views.LedLightProjectListContentView.as_view(),\n name='led-light-project-list-content'),\n url(r'^project/create/(?P<customer_id>\\d+)/$',\n views.LedLightProjectCreateView.as_view(),\n name='led-light-project-create'),\n url(r'^project/update/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.LedLightProjectUpdateView.as_view(),\n name='led-light-project-update'),\n url(r'^project/delete/(?P<customer_id>\\d+)/(?P<pk>\\d+)/$',\n views.LedLightProjectDeleteView.as_view(),\n name='led-light-project-delete'),\n url(r'^(?P<customer_id>\\d+)/dashboard_burn/$',\n views.DashboardBurnDetailView.as_view(),\n name='dashboard_burn'),\n)\n" }, { "alpha_fraction": 0.6976743936538696, "alphanum_fraction": 0.6976743936538696, "avg_line_length": 29.714284896850586, "blob_id": "e1dd01fa1da1cd09692321841ec20b2c57f4eeb3", "content_id": "a477f531cb39e73e81abe5a43c85ac154099904b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 73, "num_lines": 14, "path": "/forecast-daemon/forecast_configuration.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from configobj import ConfigObj\n\n\nclass ForecastConfiguration:\n def __init__(self, config_path):\n configuration = ConfigObj(config_path)\n\n self.validate_config(configuration)\n\n self.configuration = configuration\n\n def validate_config(self, configuration):\n if \"url\" not in configuration or \"api_key\" not in configuration:\n raise Exception(\"url or key not found in configuration file\")\n" }, { "alpha_fraction": 0.6911196708679199, "alphanum_fraction": 0.69305020570755, "avg_line_length": 27.77777862548828, "blob_id": "b2e08fdf8fa08145d8fc33f15d4214b23347ab6c", "content_id": "b6ba8195645253af76aa4bc4a37f118053def53c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 518, "license_type": "no_license", "max_line_length": 45, "num_lines": 18, "path": "/legacy/enpi_reports/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import FinalizeENPIReportView\nfrom .views import StartENPIReportView\n\nurlpatterns = patterns(\n 'legacy.enpi_reports.views',\n url(r'^start_report/$',\n StartENPIReportView.as_view(),\n name='enpi_reports-start_report'),\n url(r'^finalize_report/$',\n FinalizeENPIReportView.as_view(),\n name='enpi_reports-finalize_report'),\n)\n" }, { "alpha_fraction": 0.6579350829124451, "alphanum_fraction": 0.6601073145866394, "avg_line_length": 33.48017501831055, "blob_id": "9369886944773a6f9e13d8b5ca9147f227bbe2c2", "content_id": "b97a6c1ea2ea98525aa291fa4b831fd4f24c0639", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7826, "license_type": "no_license", "max_line_length": 118, "num_lines": 227, "path": "/energymanager/price_relay_site/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.utils.formats import date_format\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import forms\nfrom django.core.urlresolvers import reverse\nfrom rest_framework.generics import RetrieveAPIView\n\nfrom energymanager.price_relay_site.tasks import price_relay_tariff_hourly_task\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom gridplatform.tariffs.tasks import tariff_hourly_task\nfrom gridplatform.utils import generic_views\nfrom gridplatform.utils.breadcrumbs import Breadcrumb\nfrom gridplatform.utils.breadcrumbs import Breadcrumbs\nfrom gridplatform.utils.forms import YearWeekPeriodForm\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.views import ChooseCustomerBase, CustomerInKwargsMixin, StartTaskView, JsonResponse, \\\n FinalizeTaskView\nfrom gridplatform.utils.views import CustomerListMixin\nfrom gridplatform.utils.views import CustomerViewBase\nfrom gridplatform.utils.views import HomeViewBase\n\nfrom .models import PriceRelayProject\n\n\nclass HomeView(HomeViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'price_relay_site:dashboard',\n kwargs={'customer_id': customer_id})\n\n def get_choose_customer_url(self):\n return reverse(\n 'price_relay_site:choose-customer')\n\n\nclass ChooseCustomer(ChooseCustomerBase):\n template_name = 'price_relay_site/choose_customer.html'\n\n\nclass CustomerView(CustomerViewBase):\n def get_redirect_with_customer_url(self, customer_id):\n return reverse(\n 'price_relay_site:dashboard',\n kwargs={'customer_id': customer_id})\n\n\nclass PriceRelayProjectList(CustomerListMixin, generic_views.TemplateView):\n template_name = 'price_relay_site/price_relay_project_list.html'\n\n @staticmethod\n def build_breadcrumbs(customer_id):\n return Breadcrumbs() + Breadcrumb(\n _('Price Relay Projects'),\n reverse(\n 'price_relay_site:price-relay-project-list',\n kwargs={'customer_id': customer_id}))\n\n def get_breadcrumbs(self):\n return self.build_breadcrumbs(self._customer.id)\n\n\nclass PriceRelayProjectListContentView(\n CustomerListMixin, generic_views.ListView):\n search_fields = ['name_plain', ]\n sort_fields = ['name_plain', ]\n model = PriceRelayProject\n paginate_by = 100\n template_name = 'price_relay_site/_price_relay_project_list_content.html'\n\n\nclass PriceRelayProjectForm(forms.ModelForm):\n class Meta:\n model = PriceRelayProject\n fields = (\n 'name', 'look_ahead', 'tariff', 'relay_one_on_at', 'relay_two_on_at', 'relay_tree_on_at',\n 'relay_four_on_at', 'relay_five_on_at', 'relay_six_on_at', 'relay_seven_on_at',\n 'relay_eight_on_at')\n\n\nclass PriceRelayProjectCreateView(CustomerListMixin,\n generic_views.CreateView):\n model = PriceRelayProject\n template_name = 'price_relay_site/price_relay_project_form.html'\n form_class = PriceRelayProjectForm\n\n def form_valid(self, form):\n form.instance.customer_id = self._customer.id\n result = super(PriceRelayProjectCreateView, self).form_valid(form)\n assert self.object.id\n self._customer.pricerelayproject_set.add(self.object)\n return result\n\n def get_success_url(self):\n return reverse('price_relay_site:price-relay-project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return PriceRelayProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(_('Create LED Light Project'))\n\n\nclass PriceRelayProjectUpdateView(CustomerListMixin,\n generic_views.UpdateView):\n model = PriceRelayProject\n template_name = 'price_relay_site/price_relay_project_form.html'\n form_class = PriceRelayProjectForm\n\n def get_success_url(self):\n return reverse('price_relay_site:price-relay-project-list',\n kwargs={'customer_id':\n self._customer.id})\n\n def get_cancel_url(self):\n return self.get_success_url()\n\n def get_breadcrumbs(self):\n return PriceRelayProjectList.build_breadcrumbs(self._customer.id) + \\\n Breadcrumb(self.object)\n\n\nclass PriceRelayProjectDashboardCustomerDetailView(\n CustomerListMixin, generic_views.DetailView):\n model = Customer\n template_name = \\\n 'price_relay_site/dashboard.html'\n\n def get_breadcrumbs(self):\n return (\n (_('Price Relay Dashboard'), ''),\n )\n\n def get_object(self, queryset=None):\n projects = self.model.objects.get(pk=self.kwargs['customer_id']).pricerelayproject_set.all()\n\n if len(projects) > 0:\n return projects[0]\n\n return None\n\n def get_context_data(self, **kwargs):\n context = super(\n PriceRelayProjectDashboardCustomerDetailView, self).get_context_data(**kwargs)\n\n return context\n\n\nclass StartTariffHourlyLineChartView(\n CustomerInKwargsMixin, StartTaskView):\n task = price_relay_tariff_hourly_task\n finalize_url_name = 'price_relay_site:forecast-chart-finalize'\n form_class = YearWeekPeriodForm\n\n def get_task_kwargs(self, form):\n from_timestamp = datetime.datetime.now().replace(tzinfo=self._customer.timezone) - datetime.timedelta(hours=3)\n to_timestamp = from_timestamp + datetime.timedelta(hours=24)\n\n project = PriceRelayProject.objects.get(pk=self.kwargs['project_id'])\n\n\n result = {}\n result['tariff_id'] = project.tariff_id\n result['project_id'] = project.id\n result['from_timestamp'] = from_timestamp\n result['to_timestamp'] = to_timestamp\n return result\n\n def get_finalize_url(self):\n return reverse(\n self.finalize_url_name,\n kwargs={'customer_id': self._customer.id})\n\n\nclass FinalizeTariffHourlyLineChartView(CustomerInKwargsMixin, FinalizeTaskView):\n def finalize_task(self, task_result):\n tariff = EnergyTariff.objects.get(pk=task_result['tariff_id'])\n\n self.unit_converter = PhysicalUnitConverter(tariff.unit)\n\n def format_label(timestamp):\n return timestamp.astimezone(self._customer.timezone).isoformat()\n\n result = {\n 'labels': [],\n 'data': [],\n }\n\n selected_sequence = iter(task_result['data'])\n\n selected = next(selected_sequence, None)\n\n while selected is not None:\n\n result['labels'].append(format_label(selected.from_timestamp))\n result['labels'].append(format_label(selected.to_timestamp))\n result['data'].append(\n float(self.unit_converter.extract_value(\n selected.physical_quantity)))\n result['data'].append(\n float(self.unit_converter.extract_value(\n selected.physical_quantity)))\n selected = next(selected_sequence, None)\n\n project = PriceRelayProject.objects.get(pk=task_result['project_id'])\n\n result['set_points'] = {\n '1': project.relay_one_on_at,\n '2': project.relay_two_on_at,\n '3': project.relay_tree_on_at,\n '4': project.relay_four_on_at,\n '5': project.relay_five_on_at,\n '6': project.relay_six_on_at,\n '7': project.relay_seven_on_at,\n '8': project.relay_eight_on_at\n }\n\n\n return JsonResponse(result)" }, { "alpha_fraction": 0.6483839154243469, "alphanum_fraction": 0.6500163078308105, "avg_line_length": 34.61627960205078, "blob_id": "bc7bd2a9b112b24310f67d564d380011824c0f70", "content_id": "6c0701260af8bcc17dc1b5b104156ed09838ecd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3063, "license_type": "no_license", "max_line_length": 77, "num_lines": 86, "path": "/legacy/measurementpoints/models/indexcalculation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\nfrom .mixins import DevelopmentRateComputation\nfrom .mixins import CacheOptimizedCalculateDevelopmentMixin\n\n\nclass IndexCalculation(CacheOptimizedCalculateDevelopmentMixin,\n DevelopmentRateComputation,\n DataSeries):\n \"\"\"\n A C{Indexcalculation} is a L{DataSeries} derived from a consumption\n L{DataSeries} and a index L{DataSeries}.\n\n @ivar index: The index L{DataSeries} used in the index calculation.\n\n @ivar consumption: The consumption L{DataSeries} used in the consumption\n calculation.\n \"\"\"\n index = models.ForeignKey(DataSeries, on_delete=models.PROTECT,\n related_name='indexcalculation_derivative_set')\n consumption = models.ForeignKey(\n DataSeries, on_delete=models.CASCADE,\n related_name='indexcalculation_consumption_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('index calculation')\n verbose_name_plural = _('index calculations')\n app_label = 'measurementpoints'\n\n def clean_fields(self, exclude=None):\n super(IndexCalculation, self).clean_fields(exclude=exclude)\n\n if exclude and 'unit' in exclude:\n # unit not given by user, and should be inferred if possible and\n # not previously set.\n if not self.unit and self.index and self.consumption:\n self.unit = (\n PhysicalQuantity(1, self.index.unit) *\n PhysicalQuantity(1, self.consumption.unit)).units\n\n def save(self, *args, **kwargs):\n \"\"\"\n Save various components of this C{IndexCalculation}.\n \"\"\"\n # Will raise an exception if units are not compatible.\n (\n PhysicalQuantity(1, self.index.unit) *\n PhysicalQuantity(1, self.consumption.unit)).convert(self.unit)\n\n return super(IndexCalculation, self).save(*args, **kwargs)\n\n def _compute_sample(self, development, rate):\n \"\"\"\n C{IndexCalculation} implementation of\n L{DevelopmentRateComputation._compute_sample()}.\n \"\"\"\n return rate * development\n\n def _get_accumulation(self):\n \"\"\"\n C{IndexCalculation} implementation of\n L{DevelopmentRateComputation._get_accumulation()}.\n \"\"\"\n return self.consumption.subclass_instance\n\n def _get_rate(self):\n \"\"\"\n C{IndexCalculation} implementation of\n L{DevelopmentRateComputation._get_rate()}.\n \"\"\"\n return self.index.subclass_instance\n\n def depends_on(self):\n \"\"\"\n C{IndexCalculation} implementation of L{DataSeries.depends_on()}.\n \"\"\"\n return self.consumption.subclass_instance.depends_on() + \\\n self.index.subclass_instance.depends_on()\n" }, { "alpha_fraction": 0.7347066402435303, "alphanum_fraction": 0.7347066402435303, "avg_line_length": 44.771427154541016, "blob_id": "690e0f7bbabbcf0a5d45f1473f5d4b8cb8e29352", "content_id": "012c7fc33d326186fe61bb5a3c7cb87047b3557c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1602, "license_type": "no_license", "max_line_length": 78, "num_lines": 35, "path": "/documentation/source/apps/gridplatform/condensing.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Condensing\n========================================================\n\nThis app defines models and utilities to optimize the data of\n:py:class:`DataSources<.DataSource>` for further computations. In particular\nmany computations benifit from working on samples with fixed durations, mostly\nthis duration is one hour, but some times it is five minutes.\n\nThe the timestamps of :py:class:`.RawData` are not always guaranteed to be on\nthe hour (or a five minute multiplum), in particular not those that stem from\nmeters. Therefore interpolation is often required. Interpolation is\ncomputation wise relative expensive on :class:`datetime.datetime` objects.\n\nSo what this app does is compute relevant\n:py:class:`RangedSamples<.RangedSample>` for relevant\n:py:class:`DataSources<.DataSource>` and store them in the database (as\n:py:class:`.HourAccumulatedData` and :py:class:`.FiveMinuteAccumulatedData`).\nThis gives a performance boost by order of magnitude as they only need to be\ncomputed once, and the extra space taken up by these values is not an issue.\n\nModels\n------\n\n.. automodule:: gridplatform.condensing.models\n :members: validate_hour, validate_five_minutes, AccumulatedData,\n HourAccumulatedData, FiveMinuteAccumulatedData,\n cleanup_cache_for_rawdata_delete, get_hourly_accumulated,\n get_five_minute_accumulated, get_accumulated, generate_cache,\n missing_periods, generate_period_data, raw_data_for_cache,\n adjust_from_to, period_aligned\n\nCommands\n--------\n\n.. automodule:: gridplatform.condensing.management.commands.generate_cache\n" }, { "alpha_fraction": 0.6327109336853027, "alphanum_fraction": 0.6330654621124268, "avg_line_length": 36.608890533447266, "blob_id": "c1c97814b8cd0d9109c6526cbd574a68829a52f5", "content_id": "2a41c4df18cabf51e52e137486d6a65a5ae60a5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8462, "license_type": "no_license", "max_line_length": 79, "num_lines": 225, "path": "/legacy/measurementpoints/proxies/temperaturemeasurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import DegreeDayCorrection\nfrom legacy.measurementpoints.models import Graph\nfrom legacy.measurementpoints.models import HeatingDegreeDays\nfrom legacy.measurementpoints.models import Link\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\n\nfrom .measurementpoint import MeasurementPoint\n\n\nclass TemperatureMeasurementPoint(MeasurementPoint):\n \"\"\"\n A C{TemperatureMeasurementPoint} is a L{MeasurementPoint} that measures\n absolute or relative temperatures.\n\n @ivar temperature: A L{DataSeries} of temperature measurements.\n\n @ivar temperature_graph: A graph holding the C{temperature} L{DataSeries}.\n \"\"\"\n class Meta:\n proxy = True\n verbose_name = _('Temperature measurement point')\n verbose_name_plural = _('Temperature measurement points')\n app_label = 'customers'\n\n def __init__(self, *args, **kwargs):\n super(TemperatureMeasurementPoint, self).__init__(*args, **kwargs)\n if self.utility_type is None:\n self.utility_type = utilitytypes.OPTIONAL_METER_CHOICES.unknown\n\n if self.role is None:\n self.role = self.MEASUREMENT_POINT_TEMPERATURE\n\n def clean(self):\n \"\"\"\n Check define heating degree days: If it's used by another\n measerementpoint, it shouldn't be deleted.\n \"\"\"\n super(TemperatureMeasurementPoint, self).clean()\n if not self.defines_heating_degree_days:\n reason = self.get_delete_prevention_reason(\n return_dependents_only=True)\n if reason:\n # @bug: Use ngettext to handle plural forms.\n raise ValidationError(\n _('Heating degree days of this temperature measurement '\n 'point cannot be disabled because they are used by '\n 'the measurement points {measurement_points}').\n format(measurement_points=unicode(reason)))\n\n if self.relative and self.defines_heating_degree_days:\n raise ValidationError(_('Heating degree days cannot be specified '\n 'in terms of relative temperatures.'))\n\n def save(self, *args, **kwargs):\n super(TemperatureMeasurementPoint, self).save(*args, **kwargs)\n assert self.input_configuration\n\n graph, created = Graph.objects.get_or_create(\n collection=self,\n role=DataRoleField.ABSOLUTE_TEMPERATURE)\n if created:\n Link.objects.create(\n customer=self.customer,\n graph=graph,\n role=DataRoleField.ABSOLUTE_TEMPERATURE,\n unit='millikelvin',\n utility_type=self.utility_type,\n target=self._input_configuration)\n\n if self.defines_heating_degree_days:\n heating_degree_days_graph, graph_created = \\\n self.graph_set.get_or_create(\n role=DataRoleField.HEATING_DEGREE_DAYS)\n heating_degree_days, created = \\\n HeatingDegreeDays.objects.get_or_create(\n graph=heating_degree_days_graph,\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=(\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating),\n defaults={'derived_from': self._input_configuration})\n if not created:\n assert heating_degree_days.derived_from.id == \\\n self._input_configuration.id\n else:\n self.graph_set.filter(\n role=DataRoleField.HEATING_DEGREE_DAYS).delete()\n\n def _get_input_configuration(self):\n self._input_configuration = getattr(self, '_input_configuration', None)\n if self.id and not self._input_configuration:\n self._input_configuration = \\\n NonaccumulationAdapter.objects.get(\n link_derivative_set__graph__collection=self.id)\n return self._input_configuration\n\n def _set_input_configuration(self, input_configuration):\n self._input_configuration = input_configuration\n\n input_configuration = property(\n _get_input_configuration, _set_input_configuration)\n\n def _get_relative(self):\n if not hasattr(self, '_relative'):\n self._relative = self.input_configuration and \\\n self.input_configuration.role == \\\n DataRoleField.RELATIVE_TEMPERATURE\n return self._relative\n\n def _set_relative(self, relative):\n # @bug: It seem non-intuitive that physical_input must be set before\n # relative is set.\n self._relative = relative\n\n relative = property(_get_relative, _set_relative)\n\n def _get_heating_degree_days(self):\n return self.graph_set.get(\n role=DataRoleField.HEATING_DEGREE_DAYS).dataseries_set.all()\n\n heating_degree_days = property(_get_heating_degree_days)\n\n def _get_absolute(self):\n return not self.relative\n\n def _set_absolute(self, absolute):\n self.relative = not absolute\n\n absolute = property(_get_absolute, _set_absolute)\n\n @cached_property\n def defines_heating_degree_days(self):\n if not self.id:\n return False\n return HeatingDegreeDays.objects.filter(\n graph__collection=self,\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.METER_CHOICES.district_heating).\\\n exists()\n\n def get_delete_prevention_reason(self, return_dependents_only=False):\n \"\"\"\n Returns a HTML formated string with a description of why\n this temperature measurement point cannot be deleted.\n Returning None, if no reason exist, meaning the MP can\n be deleted without breaking anything.\n\n @param return_dependents_only: If true, only return a string of\n the units that depends on this resource.\n \"\"\"\n degree_day_corrections = DegreeDayCorrection.objects.filter(\n degreedays__in=HeatingDegreeDays.objects.filter(\n graph__collection=self,\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.METER_CHOICES.district_heating))\n\n if len(degree_day_corrections) == 0:\n return None\n\n mp_string = \"\"\n for degree_day_correction in degree_day_corrections:\n if mp_string != \"\":\n mp_string += \", \"\n mp_string += degree_day_correction.graph.collection.name_plain\n\n if return_dependents_only:\n return mp_string\n\n # @bug: Use ngettext to handle plural forms.\n return _('This index cannot be deleted because the following \\\n depends on it: <br /> ' + mp_string)\n\n def is_deletable(self):\n \"\"\"\n Returns true or false whether\n this temperature measurement point can be deleted or not.\n \"\"\"\n degree_day_corrections = DegreeDayCorrection.objects.filter(\n degreedays__in=HeatingDegreeDays.objects.filter(\n graph__collection=self,\n role=DataRoleField.HEATING_DEGREE_DAYS,\n utility_type=utilitytypes.METER_CHOICES.district_heating))\n\n if len(degree_day_corrections) > 0:\n return False\n return True\n\n def get_gauge_data_series(self):\n \"\"\"\n C{TemperatureMeasurementPoint} implementation of\n L{MeasurementPoint.get_gauge_data_series()}\n \"\"\"\n return self.input_configuration\n\n @property\n def has_consumption(self):\n return False\n\n @property\n def has_gauge(self):\n return False\n\n @property\n def has_rate(self):\n return True\n\n @staticmethod\n def get_input_configuration_choices():\n \"\"\"\n Get L{NonaccumulationAdapter} choices.\n \"\"\"\n # NOTE: We actually only support absolute temperature\n return NonaccumulationAdapter.objects.filter(\n unit='millikelvin',\n customer=trackuser.get_customer())\n" }, { "alpha_fraction": 0.6357142925262451, "alphanum_fraction": 0.636734664440155, "avg_line_length": 35.296295166015625, "blob_id": "8a8b33a38e719cd4a0c4a8c92979fc754bb541fe", "content_id": "930766583f01578ac4a7ceed67a4eeddcef421ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/legacy/setup_agents/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\nfrom gridplatform.users.decorators import admin_or_redirect\n\n\nurlpatterns = patterns(\n 'legacy.setup_agents.views',\n url(r'^$',\n admin_or_redirect(TemplateView.as_view(\n template_name='setup_agents/agent_list.html')),\n name='setup_agents-list'),\n url(r'^json/agent/$', 'agent_list_json', name='setup_agents-list-json'),\n url(r'^agent/form/$', 'agent_form', name=\"setup_agents-form\"),\n url(r'^agent/form/(?P<pk>\\d+)/$', 'agent_form', name=\"setup_agents-form\"),\n url(r'^agent/update/$', 'agent_update', name=\"setup_agents-update\"),\n url(r'^agent/update/(?P<pk>\\d+)/$',\n 'agent_update',\n name=\"setup_agents-update\"),\n url(r'^agent/swupgrade/(?P<pk>\\d+)/$',\n 'agent_swupgrade',\n name=\"setup_agents-swupgrade\"),\n)\n" }, { "alpha_fraction": 0.6219272613525391, "alphanum_fraction": 0.6248770952224731, "avg_line_length": 26.472972869873047, "blob_id": "9175055ed249cda9c2ea5206147190aa3d34fb10", "content_id": "906c84e034f1bf3b0b05f17948e36198c6f0fcbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2034, "license_type": "no_license", "max_line_length": 116, "num_lines": 74, "path": "/forecast-daemon/forecast.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import argparse\nimport sys\nimport signal\nimport time\n\nimport datetime\nfrom RPi import GPIO\n\nfrom forecast_configuration import ForecastConfiguration\nfrom relay_handler import RelayHandler\nfrom request_handler import RequestHandler\n\n\nclass Forecast:\n __version__ = \"Forecast v0.1\"\n\n def __init__(self, configuration):\n self._exit = False\n self.configuration = configuration\n self.last_request_time = None\n\n def run(self):\n signal.signal(signal.SIGINT, self._sigint_handler)\n request = RequestHandler(self.configuration)\n relay = RelayHandler(self.configuration)\n forecast_data = None\n\n while not self._exit:\n if not self.last_request_time or \\\n datetime.datetime.now() >= self.last_request_time + datetime.timedelta(seconds=10):\n new_data = request.fetch_forecast()\n print new_data\n if new_data:\n forecast_data = new_data\n self.last_request_time = datetime.datetime.now()\n\n relay.update_ports(forecast_data)\n\n time.sleep(0.2)\n\n def _sigint_handler(self, signal, frame):\n self._exit = True\n GPIO.cleanup()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"SC Nordic Forecast Relay\")\n\n parser.add_argument(\"--config-file\", action=\"store\", help=\"Path to configuration file\", default=\"forecast.conf\")\n\n parser.add_argument(\"--version\", action=\"store_true\", help=\"Display version number\")\n\n args = parser.parse_args()\n\n if args.version:\n print Forecast.__version__\n sys.exit()\n\n configuration = None\n try:\n configuration = ForecastConfiguration(args.config_file)\n \n except Exception as e:\n print e.message\n sys.exit()\n \n try:\n forecast = Forecast(configuration.configuration)\n \n except Exception as e:\n print e.message\n sys.exit(\"Could not start Forecast daemon\")\n else:\n forecast.run()\n\n" }, { "alpha_fraction": 0.6900212168693542, "alphanum_fraction": 0.691082775592804, "avg_line_length": 27.545454025268555, "blob_id": "2f7c75f23740e76e710dde8d011f4409f6410c36", "content_id": "de3120500c8362950d8c7e85e0f0cfb5fc7b9416", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 942, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/gridplatform/utils/middleware.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.trackuser import get_customer, get_user\nfrom django.utils import timezone\n\n\nclass ExceptionRemoveInfoMiddleware(object):\n \"\"\"\n Remove cookies from error mails, as these contain decryption information.\n \"\"\"\n\n def process_exception(self, request, exception):\n request.META.pop('HTTP_COOKIE', None)\n\n\nclass ExceptionAddInfoMiddleware(object):\n \"\"\"\n Adds current user and customer to exception mail.\n \"\"\"\n\n def process_exception(self, request, exception):\n request.META['Customer'] = get_customer()\n request.META['User'] = unicode(get_user())\n\n\nclass TimezoneMiddleware(object):\n \"\"\"Set active timezone to the customers timezone\"\"\"\n def process_request(self, request):\n customer = get_customer()\n if customer:\n timezone.activate(customer.timezone)\n" }, { "alpha_fraction": 0.611801266670227, "alphanum_fraction": 0.6149068474769592, "avg_line_length": 35.59090805053711, "blob_id": "7d7a9c7153590b9c45a79a9f16a04b57d452649a", "content_id": "5855ae1d2e5a3ee546a3ae1cbb77ef5478bda3c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3220, "license_type": "no_license", "max_line_length": 79, "num_lines": 88, "path": "/legacy/manage_measurementpoints/forms/tariff.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django import forms\nfrom django.forms.models import ModelForm\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.models import ChainLink\nfrom gridplatform.trackuser import get_customer\n\n\nclass IsoDateField(forms.DateField):\n \"\"\"\n Crippled forms.DateField for use with JavaScript datepicker.\n\n In particular this field implements work-arounds for localization issues\n (the format is always ISO 8601 'YYYY-MM-DD') and the input HTML element has\n the right class, so that website.js will attach the datepicker on it\n automatically.\n \"\"\"\n\n def __init__(self, **kwargs):\n super(IsoDateField, self).__init__(\n ['%Y-%m-%d'],\n widget=forms.DateInput(attrs={'class': 'date'}, format='%Y-%m-%d'),\n **kwargs)\n\n\nclass TariffPeriodForm(ModelForm):\n \"\"\"\n A C{TariffPeriodForm} makes a ChainLink appear to know that it is being\n used for defining a tariff in a given period.\n\n The C{valid_from} is set using a date on the from which is converted to a\n datetime object as needed by the model by combining the date with 0:00 in\n the current customers timezone.\n \"\"\"\n valid_from = IsoDateField(label=_('valid from'))\n\n class Meta:\n model = ChainLink\n fields = ('data_series', )\n localized_fields = '__all__'\n error_messages = {\n 'data_series': {\n 'incompatible_units': _(\n 'The selected tariff has a different currency than '\n 'existing cost calculation.'),\n }\n }\n\n def __init__(self, *args, **kwargs):\n super(TariffPeriodForm, self).__init__(*args, **kwargs)\n if 'valid_from' not in self.initial:\n if self.instance.valid_from is not None:\n tz = get_customer().timezone\n self.initial['valid_from'] = tz.normalize(\n self.instance.valid_from.astimezone(tz)).date()\n else:\n self.initial['valid_from'] = get_customer.now().date()\n\n def clean(self):\n super(TariffPeriodForm, self).clean()\n if 'valid_from' in self.cleaned_data:\n self.instance.valid_from = datetime.datetime.combine(\n self.cleaned_data['valid_from'],\n datetime.time(0, 0, tzinfo=get_customer().timezone))\n return self.cleaned_data\n\n def has_changed(self):\n \"\"\"\n Reimplementation of C{models.ModelForm.has_changed()}.\n\n This is really a work-around for a bug in Django, where the original\n dynamic initial value is not considered when detecting if a field has\n changed.\n \"\"\"\n if self.empty_permitted:\n # If empty_permitted, this is one of the extra forms in a formset.\n # In that case, we don't considder a valid_from different from the\n # current time as an actual change.\n return bool([name for name in\n self.changed_data if name != 'valid_from'])\n else:\n return super(TariffPeriodForm, self).has_changed()\n" }, { "alpha_fraction": 0.5650289058685303, "alphanum_fraction": 0.6141618490219116, "avg_line_length": 36.07143020629883, "blob_id": "419384c7860ddd0e887a858ba7c5b362a9ad51da", "content_id": "a93981b6118f2713ad7a5e48e7e43a42e8974214", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2077, "license_type": "no_license", "max_line_length": 74, "num_lines": 56, "path": "/legacy/energinet_co2/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport codecs\nimport datetime\nimport operator\nimport os.path\nimport pytz\n\nfrom django.test import TestCase\n\nfrom .parser import parse_forecast, parse_online\n\n\nfile_base = os.path.abspath(os.path.dirname(__file__))\n\nforecast_file = os.path.join(file_base, '20130529_CO2prognose.txt')\nonline_file = os.path.join(file_base, '20130529_onlinedata.txt')\n\n\nclass ParserTest(TestCase):\n def test_parse_forecast(self):\n with open(forecast_file, 'r') as f:\n forecast = parse_forecast(f)\n # date for the example file\n self.assertEqual(forecast['date'], datetime.date(2013, 5, 29))\n self.assertEqual(forecast['header'], ('Timeinterval', 'CO2'))\n # should have 24 hours\n self.assertEqual(len(forecast['data']), 24)\n # should be sorted by \"from\" timestamp\n self.assertListEqual(\n forecast['data'],\n sorted(forecast['data'], key=operator.itemgetter(0)))\n # entries should be (datetime.time, datetime.time, int); check an\n # instance from the example file\n self.assertEqual(forecast['data'][1],\n (datetime.time(1, 0), datetime.time(2, 0), 389))\n\n def test_parse_online(self):\n with codecs.open(online_file, 'r', 'iso8859-1') as f:\n online = parse_online(f)\n # date/time entry in header is handled separately...\n self.assertEqual(online['header'][0], 'Dato og tid')\n # normal header entry --- including a non-ASCII character\n self.assertEqual(online['header'][2], u'Centrale kraftværker DK2')\n # each entry is timestamp and 16 data values\n self.assertEqual(len(online['header']), 17)\n\n self.assertTupleEqual(\n online['data'][2],\n (\n pytz.timezone('Europe/Copenhagen').localize(\n datetime.datetime(2013, 5, 29, 0, 10)),\n 1094, 536, 197, 90, 593, 332, 291, 607,\n -897, 174, 98, -4, 0, 12, 6, 380))\n" }, { "alpha_fraction": 0.5685232877731323, "alphanum_fraction": 0.5718622207641602, "avg_line_length": 39.6728401184082, "blob_id": "fcdd82fa85824084289a8406f22eb19747aa9d0f", "content_id": "6d1de9e3e3dfad8d19338bfc3738b5a215fadc08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6589, "license_type": "no_license", "max_line_length": 120, "num_lines": 162, "path": "/energymanager/price_relay_site/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nimport pytz\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _, ugettext\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.tariffs.models import EnergyTariff\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils import PhysicalQuantity\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\n\n\nclass PriceRelayProject(\n EncryptionCustomerFieldMixin, EncryptedModel):\n name = EncryptedCharField(_('name'), max_length=50)\n look_ahead = models.PositiveIntegerField(\n _('Look ahead'), help_text=_('in hours'))\n relay_one_on_at = models.FloatField(\n _('Relay one on at'), help_text=_('kr'))\n relay_two_on_at = models.FloatField(\n _('Relay two on at'), help_text=_('kr'))\n relay_tree_on_at = models.FloatField(\n _('Relay tree on at'), help_text=_('kr'))\n relay_four_on_at = models.FloatField(\n _('Relay four on at'), help_text=_('kr'))\n relay_five_on_at = models.FloatField(\n _('Relay five on at'), help_text=_('kr'))\n relay_six_on_at = models.FloatField(\n _('Relay six on at'), help_text=_('kr'))\n relay_seven_on_at = models.FloatField(\n _('Relay seven on at'), help_text=_('kr'))\n relay_eight_on_at = models.FloatField(\n _('Relay eight on at'), help_text=_('kr'))\n tariff = models.ForeignKey(\n EnergyTariff,\n verbose_name=_('tariff'))\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('Price relay project')\n verbose_name_plural = _('Price relay projects')\n\n def __unicode__(self):\n return unicode(self.name_plain)\n\n def clean(self):\n \"\"\"\n :raises ValidationError: if ``self.relay_one_at`` value is gte ``self.relay_two_at``\n :raises ValidationError: if ``self.relay_two_at`` value is gte ``self.relay_tree_at``\n :raises ValidationError: if ``self.relay_tree_at`` value is gte ``self.relay_four_at``\n :raises ValidationError: if ``self.relay_four_at`` value is gte ``self.relay_five_at``\n :raises ValidationError: if ``self.relay_five_at`` value is gte ``self.relay_six_at``\n :raises ValidationError: if ``self.relay_six_at`` value is gte ``self.relay_seven_at``\n :raises ValidationError: if ``self.relay_seven_at`` value is gte ``self.relay_eight_at``\n\n \"\"\"\n super(PriceRelayProject, self).clean()\n\n if self.relay_one_on_at >= self.relay_two_on_at:\n raise ValidationError(\n {\n 'relay_one_on_at': [\n ugettext(\n 'Value must be lesser than Relay two value at')]})\n\n if self.relay_two_on_at >= self.relay_tree_on_at:\n raise ValidationError(\n {\n 'relay_two_on_at': [\n ugettext(\n 'Value must be lesser than Relay tree value at')]})\n\n if self.relay_tree_on_at >= self.relay_four_on_at:\n raise ValidationError(\n {\n 'relay_tree_on_at': [\n ugettext(\n 'Value must be lesser than Relay four value at')]})\n\n if self.relay_four_on_at >= self.relay_five_on_at:\n raise ValidationError(\n {\n 'relay_four_on_at': [\n ugettext(\n 'Value must be lesser than Relay five value at')]})\n\n if self.relay_five_on_at >= self.relay_six_on_at:\n raise ValidationError(\n {\n 'relay_five_on_at': [\n ugettext(\n 'Value must be lesser than Relay six value at')]})\n\n if self.relay_six_on_at >= self.relay_seven_on_at:\n raise ValidationError(\n {\n 'relay_six_on_at': [\n ugettext(\n 'Value must be lesser than Relay seven value at')]})\n\n if self.relay_seven_on_at >= self.relay_eight_on_at:\n raise ValidationError(\n {\n 'relay_seven_on_at': [\n ugettext(\n 'Value must be lesser than Relay eight value at')]})\n\n def _get_relay_number(self, price):\n if price < self.relay_one_on_at:\n return 0\n if self.relay_one_on_at <= price < self.relay_two_on_at:\n return 1\n elif self.relay_two_on_at <= price < self.relay_tree_on_at:\n return 2\n elif self.relay_tree_on_at <= price < self.relay_four_on_at:\n return 3\n elif self.relay_four_on_at <= price < self.relay_five_on_at:\n return 4\n elif self.relay_five_on_at <= price < self.relay_six_on_at:\n return 5\n elif self.relay_six_on_at <= price < self.relay_seven_on_at:\n return 6\n elif self.relay_seven_on_at <= price < self.relay_eight_on_at:\n return 7\n elif self.relay_eight_on_at <= price:\n return 8\n\n def calculate_relay_settings(self):\n settings = []\n now = datetime.datetime.now().replace(tzinfo=self.customer.timezone) - datetime.timedelta(hours=2)\n\n prices = list(self.tariff.period_set.value_sequence(now, now + datetime.timedelta(hours=24)))\n #print prices\n unit_converter = PhysicalUnitConverter(self.tariff.unit)\n print self.tariff.unit, self.tariff.pk\n for i in range(0, len(prices)):\n sample = prices[i]\n look_ahead_sample = None\n try:\n look_ahead_sample = prices[i+self.look_ahead]\n except IndexError:\n pass\n if look_ahead_sample:\n change = PhysicalQuantity(100) - (sample.physical_quantity / look_ahead_sample.physical_quantity * 100)\n relay_number = self._get_relay_number(float(unit_converter.extract_value(\n look_ahead_sample.physical_quantity)))\n\n # todo fix pris delta\n\n settings.append(\n {'sample': sample, 'look_ahead_sample': look_ahead_sample, 'change': change, 'relay': relay_number})\n \n\treturn settings\n" }, { "alpha_fraction": 0.6304125189781189, "alphanum_fraction": 0.6362086534500122, "avg_line_length": 37.09090805053711, "blob_id": "4780a62e27bc050257d1bc674e0d4716ecab50ef", "content_id": "5ed48d8d0ce400a95208d7500ecddf62e26fb4a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2933, "license_type": "no_license", "max_line_length": 78, "num_lines": 77, "path": "/legacy/projects/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\n\nfrom celery import shared_task\nfrom celery import Task\n\nfrom legacy.energy_use_reports.tasks import TaskProgressMixin\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\n\nfrom .models import BenchmarkProject\nfrom .models import payback_period_years\n\n\n@trackuser_task\n@shared_task(\n timelimit=1860, soft_time_limit=1800,\n name='legacy.projects.tasks.AnnualSavingsPotentialReportTask')\nclass AnnualSavingsPotentialReportTask(TaskProgressMixin, Task):\n def run(self, data):\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': 0,\n 'total': 0\n }\n )\n\n self.PROGRESS_TOTAL = len(data['projects'])\n self.progress = 0\n\n total_expected_annual_cost_savings = Fraction(0)\n total_subsidy = Fraction(0)\n total_investment = Fraction(0)\n for project in BenchmarkProject.objects.filter(\n id__in=data['projects'].keys()):\n expected_annual_cost_savings = Fraction(\n project.expected_savings_in_yearly_total_costs or 0)\n subsidy = Fraction(project.subsidy or 0)\n investment = Fraction(project.investment)\n\n total_expected_annual_cost_savings += expected_annual_cost_savings\n total_subsidy += subsidy\n total_investment += investment\n\n data['projects'][project.id]['baseline_annual_consumption'] = \\\n project.baseline_annual_consumption\n data['projects'][project.id]['expected_annual_cost_savings'] = \\\n expected_annual_cost_savings\n data['projects'][project.id]['baseline_annual_costs'] = \\\n project.baseline_annual_costs\n data['projects'][project.id]['subsidy'] = subsidy\n data['projects'][project.id]['investment'] = investment\n data['projects'][project.id]['expected_payback_period_years'] = \\\n project.expected_payback_period_years\n self.tick_progress()\n\n total_expected_payback_period = payback_period_years(\n total_investment,\n total_subsidy,\n total_expected_annual_cost_savings)\n\n data['total_expected_annual_cost_savings'] = \\\n total_expected_annual_cost_savings\n data['total_subsidy'] = total_subsidy\n data['total_investment'] = total_investment\n data['total_expected_payback_period'] = total_expected_payback_period\n data['currency_unit'] = \\\n Customer.objects.get(id=get_customer().id).\\\n get_currency_unit_display()\n return data\n" }, { "alpha_fraction": 0.7135325074195862, "alphanum_fraction": 0.7152900099754333, "avg_line_length": 30.61111068725586, "blob_id": "0b988e5eefd1ce2fd5a4e5f944858ca08b85cc2e", "content_id": "a247aacf616fea94f4b28df47c3efba275d08567", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/legacy/projects/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.db.models import F\n\nfrom .models import BenchmarkProject\n\n\nclass AnnualSavingsPotentialReportGenerationForm(forms.Form):\n projects = forms.ModelMultipleChoiceField(\n BenchmarkProject.objects.none())\n\n def __init__(self, *args, **kwargs):\n super(AnnualSavingsPotentialReportGenerationForm, self).__init__(\n *args, **kwargs)\n self.fields['projects'].queryset = BenchmarkProject.objects.all()\n" }, { "alpha_fraction": 0.6944980025291443, "alphanum_fraction": 0.6966459155082703, "avg_line_length": 32.31559753417969, "blob_id": "33aba65f1c1aeff414cfa37ceb38f95fe0949f0b", "content_id": "2da68338bac4622d8542f298674a3324a62d933b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18157, "license_type": "no_license", "max_line_length": 110, "num_lines": 545, "path": "/gridplatform/settings/base.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\nCommon settings and globals.\n\"\"\"\n\nimport json\nimport os\nimport os.path\nimport socket\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom unipath import Path\n\nimport kombu\n\n\ndef get_secret_setting(setting):\n try:\n settings_module = os.environ['DJANGO_SETTINGS_MODULE']\n except KeyError:\n error_msg = \"Set the DJANGO_SETTINGS_MODULE environment variable\" % \\\n setting\n raise ImproperlyConfigured(error_msg)\n secret_filename = '{}.json'.format(settings_module.split('.')[-1])\n user_dir = os.path.expanduser('~')\n secret_path = os.path.join(user_dir, secret_filename)\n try:\n with open(secret_path, 'r') as f:\n data = json.load(f)\n except IOError:\n error_msg = \"Failed to read secrets file %s\" % secret_path\n raise ImproperlyConfigured(error_msg)\n except ValueError:\n error_msg = \"Failed to parse JSON from secrets file %s\" % \\\n secret_path\n raise ImproperlyConfigured(error_msg)\n try:\n return data[setting]\n except KeyError:\n error_msg = \"Setting %s missing from secrets file %s\" % \\\n (setting, secret_path)\n raise ImproperlyConfigured(error_msg)\n\n\n# ######### PATH CONFIGURATION\n# Absolute filesystem path to the Django project directory:\nDJANGO_ROOT = Path(__file__).absolute().parent.parent\n\n# Absolute filesystem path to the top-level project folder:\nSITE_ROOT = DJANGO_ROOT.parent\n\n# Site name:\nSITE_NAME = DJANGO_ROOT.name\n# ######### END PATH CONFIGURATION\n\nGRIDMANAGER_ADDRESS = \"GridManager ApS\\nNupark 51\\n7500 Holstebro\"\n\n# ######### DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = False\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\nTEMPLATE_DEBUG = DEBUG\n# ######### END DEBUG CONFIGURATION\n\n\n# ######### MANAGER CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#admins\nADMINS = (\n ('Michael Nielsen', '[email protected]'),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#managers\nMANAGERS = ADMINS\n# ######### END MANAGER CONFIGURATION\n\n\n# ######### DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {}\n# ######### END DATABASE CONFIGURATION\n\n\n# ######### GENERAL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#time-zone\nTIME_ZONE = 'Europe/Copenhagen'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#language-code\nLANGUAGE_CODE = 'da'\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#languages\nLANGUAGES = (\n ('en', _('English')),\n ('da', _('Danish')),\n ('es', _('Spanish')),\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#site-id\nSITE_ID = 1\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-i18n\nUSE_I18N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-l10n\nUSE_L10N = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-tz\nUSE_TZ = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#use-thousand-separator # noqa\nUSE_THOUSAND_SEPARATOR = True\n\nAUTH_PROFILE_MODULE = 'customers.UserProfile'\nAUTHENTICATION_BACKENDS = (\n 'gridplatform.users.auth_backends.HashedUsernameBackend',\n)\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')\n\nSESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'\n# Encryption system keeps binary data in session; default/JSON serialisation\n# would fail.\nSESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer'\n\nLOGIN_URL = reverse_lazy('start_site:login')\nLOGOUT_URL = reverse_lazy('website-logout')\nLOGIN_REDIRECT_URL = reverse_lazy('start_site:apps')\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#server-email\nSERVER_EMAIL = 'no-reply@' + socket.gethostname()\n# ######### END GENERAL CONFIGURATION\n\n\n# ######### MEDIA CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root\nMEDIA_ROOT = os.path.normpath(os.path.join(SITE_ROOT, 'media/'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url\nMEDIA_URL = '/media/'\n# ######### END MEDIA CONFIGURATION\n\n\n# ######### STATIC FILE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root\nSTATIC_ROOT = os.path.normpath(os.path.join(SITE_ROOT, 'static/'))\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-url\nSTATIC_URL = '/static/'\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS # noqa\nSTATICFILES_DIRS = ()\n\n# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders # noqa\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\nSTATICFILES_STORAGE = \\\n 'django.contrib.staticfiles.storage.CachedStaticFilesStorage'\n# ######### END STATIC FILE CONFIGURATION\n\n\n# ######### SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\nSECRET_KEY = None\n# ######### END SECRET CONFIGURATION\n\n\n# ######### DATA IMPORT LOGIN CONFIGURATION\nENERGINET_CO2_USER = None\nENERGINET_CO2_PASS = None\nNORDPOOL_USER = None\nNORDPOOL_PASS = None\n# ######### END DATA IMPORT LOGIN CONFIGURATION\n\n\n# ######### SITE CONFIGURATION\n# Hosts/domain names that are valid for this site\n# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\nALLOWED_HOSTS = []\n# ######### END SITE CONFIGURATION\n\n\n# ######### FIXTURE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FIXTURE_DIRS # noqa\nFIXTURE_DIRS = (\n os.path.normpath(os.path.join(SITE_ROOT, 'fixtures')),\n)\n# ######### END FIXTURE CONFIGURATION\n\n\n# ######### TEMPLATE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors # noqa\nTEMPLATE_CONTEXT_PROCESSORS = (\n # Variables user, perms:\n 'django.contrib.auth.context_processors.auth',\n # Variable boostrap_template\n 'gridplatform.bootstrap.context_processors.bootstrap',\n # Variables current_user, current_customer:\n 'gridplatform.trackuser.context_processors.trackuser',\n # If settings.DEBUG, variables debug=True, sql_queries:\n 'django.core.context_processors.debug',\n # Variables LANGUAGES, LANGUAGE_CODE:\n 'django.core.context_processors.i18n',\n # Variable MEDIA_URL:\n 'django.core.context_processors.media',\n # Variable STATIC_URL:\n 'django.core.context_processors.static',\n # Variable TIME_ZONE --- name af current \"active\" timezone:\n 'django.core.context_processors.tz',\n # Variable request:\n 'django.core.context_processors.request',\n # Variable messages (see documentation for Django messages framework):\n 'django.contrib.messages.context_processors.messages',\n # Variable app_selection\n 'energymanager.start_site.context_processors.app_selection',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-loaders\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-dirs\nTEMPLATE_DIRS = (\n os.path.normpath(os.path.join(SITE_ROOT, 'templates')),\n)\n# ######### END TEMPLATE CONFIGURATION\n\n\n# ######### MIDDLEWARE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#middleware-classes\nMIDDLEWARE_CLASSES = (\n # Allow cross origin resource aquisition\n 'corsheaders.middleware.CorsMiddleware',\n # Various convenience actions. Only active/relevant is redirecting by\n # appending \"/\" to URL if requested URL does not exist but variant with\n # added \"/\" does.\n 'django.middleware.common.CommonMiddleware',\n # Session support.\n 'django.contrib.sessions.middleware.SessionMiddleware',\n # Locale support.\n 'django.middleware.locale.LocaleMiddleware',\n # Cross site request forgery protection.\n 'django.middleware.csrf.CsrfViewMiddleware',\n # Add \"user\" attribute, obtained from session, to request object.\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n # Load/decrypt encryption keys in session using key from cookie.\n 'gridplatform.encryption.middleware.EncryptionMiddleware',\n 'gridplatform.encryption.middleware.KeyLoaderMiddleware',\n # One database transaction per request; commit on success/response,\n # rollback on error.\n 'django.middleware.transaction.TransactionMiddleware',\n # Message support (see documentation for Django messages framework).\n 'django.contrib.messages.middleware.MessageMiddleware',\n # Uncomment the next line for simple clickjacking protection:\n # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n # Keep current user/current customer in thread-locals...\n # (Against Django convention, but makes a lot of logic simpler/less\n # error-prone by allowing us to use \"default=trackuser.get_user\" and\n # \"default=trackuser.get_customer\" on model fields.)\n # Also adds \"customer\" variable to request from session/logged in user.\n 'gridplatform.trackuser.middleware.TrackUserMiddleware',\n 'gridplatform.utils.middleware.ExceptionRemoveInfoMiddleware',\n 'gridplatform.utils.middleware.ExceptionAddInfoMiddleware',\n 'gridplatform.utils.middleware.TimezoneMiddleware',\n)\n# ######### END MIDDLEWARE CONFIGURATION\n\n# Allow javascript running on other sites to access the REST API.\nCORS_ORIGIN_ALLOW_ALL = True\nCORS_URLS_REGEX = '^/api/.*$'\n\n# ######### URL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf\nROOT_URLCONF = '%s.urls' % SITE_NAME\n# ######### END URL CONFIGURATION\n\n\n# ######### APP CONFIGURATION\nDJANGO_APPS = (\n # Authentication/user login:\n 'django.contrib.auth',\n # Generic relations:\n 'django.contrib.contenttypes',\n # Sessions:\n 'django.contrib.sessions',\n # Helpers for sharing backend/data between multiple websites:\n # 'django.contrib.sites',\n # Attach \"messages\" to session, to be displayed on next request:\n 'django.contrib.messages',\n # Collect/manage per-app static files (collect for deployment, serve in\n # development, templatetag for URL):\n 'django.contrib.staticfiles',\n # Numerous variants of \"lorem ipsum\" paragraphs:\n 'django.contrib.webdesign',\n # Useful template tags:\n # 'django.contrib.humanize',\n # Admin panel and documentation:\n 'django.contrib.admin',\n # 'django.contrib.admindocs',\n)\n\n\n# GridPortal 2.0 legacy or just dead apps that still have to linger in a zombie\n# state due to their migrations.\nLEGACY_APPS = (\n 'legacy.legacy_utils',\n 'legacy.devices',\n 'legacy.display_indexes',\n 'legacy.display_measurementpoints',\n 'legacy.display_projects',\n 'legacy.display_widgets',\n 'legacy.edit_userprofile',\n 'legacy.energinet_co2',\n 'legacy.energy_use_reports',\n 'legacy.enpi_reports',\n 'legacy.indexes',\n 'legacy.manage_collections',\n 'legacy.manage_customers',\n 'legacy.manage_devices',\n 'legacy.manage_indexes',\n 'legacy.manage_locations',\n 'legacy.manage_measurementpoints',\n 'legacy.manage_reports',\n 'legacy.manage_rules',\n 'legacy.manage_users',\n 'legacy.measurementpoints',\n 'legacy.datasequence_adapters',\n 'legacy.projects',\n 'legacy.rules',\n 'legacy.setup_agents',\n 'legacy.website',\n 'legacy.efficiencymeasurementpoints',\n 'legacy.nordpool',\n)\n\n# Apps specific for this project go here.\nPLATFORM_APPS = (\n 'gridplatform.encryption',\n 'gridplatform.users',\n 'gridplatform.customers',\n 'gridplatform.providers',\n 'gridplatform.rest',\n 'gridplatform.condensing',\n 'gridplatform.utils',\n 'gridplatform.reports',\n 'gridplatform.datasources',\n 'gridplatform.global_datasources',\n 'gridplatform.provider_datasources',\n 'gridplatform.customer_datasources',\n 'gridplatform.datasequences',\n 'gridplatform.consumptions',\n 'gridplatform.productions',\n 'gridplatform.tariffs',\n 'gridplatform.cost_compensations',\n 'gridplatform.trackuser',\n 'gridplatform.bootstrap',\n 'gridplatform.token_auth',\n 'gridplatform.jserror',\n 'gridplatform.energyperformances',\n 'gridplatform.co2conversions',\n 'gridplatform.smilics',\n 'gridplatform.datahub',\n)\n\nENERGYMANAGER_APPS = (\n 'energymanager.start_site',\n 'energymanager.provider_site',\n 'energymanager.energy_projects',\n 'energymanager.led_light_site',\n 'energymanager.price_relay_site',\n 'energymanager.configuration_site',\n 'energymanager.project_site',\n 'energymanager.datahub_site',\n)\n\nTHIRD_PARTY_APPS = (\n # Tree structured model relations.\n 'mptt',\n # Template filters for HTML/CSS attributes on form fields\n 'widget_tweaks',\n # asset packing\n 'compressor',\n # Pytz integration/timezone helpers (model fields, middleware)\n # NOTE: We will *only* use the timezone model fields --- for the rest,\n # we use the built-in features from Django 1.4.\n 'timezones2',\n # Django REST framework\n 'rest_framework',\n 'django_filters',\n 'djangorestframework_camel_case',\n 'corsheaders',\n # Images\n 'imagekit',\n 'model_utils',\n)\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#installed-apps\nINSTALLED_APPS = PLATFORM_APPS + LEGACY_APPS + ENERGYMANAGER_APPS + \\\n DJANGO_APPS + THIRD_PARTY_APPS\n# ######### END APP CONFIGURATION\n\n\n# ######### LOGGING CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error when DEBUG=False.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n },\n 'stderr': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n },\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n 'pika': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n },\n },\n 'root': {\n 'handlers': ['stderr'],\n 'level': 'INFO',\n },\n}\n# ######### END LOGGING CONFIGURATION\n\n\n# ######### WSGI CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application\nWSGI_APPLICATION = '%s.wsgi.application' % SITE_NAME\n# ######### END WSGI CONFIGURATION\n\n\n# ######### SOUTH CONFIGURATION\n# See: http://south.readthedocs.org/en/latest/installation.html#configuring-your-django-installation # noqa\nINSTALLED_APPS += (\n # Database migration helpers:\n 'south',\n)\n# Don't need to use South when setting up a test database.\nSOUTH_TESTS_MIGRATE = False\n# ######### END SOUTH CONFIGURATION\n\n\n# ######### CELERY CONFIGURATION\nINSTALLED_APPS += (\n # Celery/Django integration; used for cache result backend\n 'djcelery',\n)\n# Only assign one task to each celery worker thread at the time:\n# http://docs.celeryproject.org/en/latest/userguide/optimizing.html#reserve-one-task-at-a-time # noqa\n# http://docs.celeryproject.org/en/latest/faq.html#should-i-use-retry-or-acks-late # noqa\nCELERY_ACKS_LATE = True\nCELERYD_PREFETCH_MULTIPLIER = 1\n\n# Don't persist Celery queues to disk...\n# http://docs.celeryproject.org/en/latest/userguide/optimizing.html#using-transient-queues # noqa\n# http://kombu.readthedocs.org/en/latest/reference/kombu.html?highlight=queue#kombu.Queue # noqa\nCELERY_QUEUES = (\n kombu.Queue('celery', routing_key='celery', durable=False),\n kombu.Queue('reports', routing_key='reports', durable=False),\n kombu.Queue('sanitize', routing_key='sanitize', durable=True),\n)\nCELERY_DEFAULT_QUEUE = 'celery'\nCELERY_CREATE_MISSING_QUEUES = False\n\n# We don't currently use rate limiting for any tasks...\n# http://docs.celeryproject.org/en/latest/userguide/tasks.html#disable-rate-limits-if-they-re-not-used # noqa\nCELERY_DISABLE_RATE_LIMITS = True\n\n# Store Celery results in Django cache\nCELERY_RESULT_BACKEND = 'djcelery.backends.cache:CacheBackend'\n\nCELERY_TRACK_STARTED = True\n\n# Send error mail to ADMINS if errors occur during task execution.\nCELERY_SEND_TASK_ERROR_EMAILS = True\n# ######### END CELERY CONFIGURATION\n\n\n# ######### DJANGO REST FRAMEWORK CONFIGURATION\nREST_FRAMEWORK = {\n 'FILTER_BACKEND': 'rest_framework.filters.DjangoFilterBackend',\n 'DEFAULT_MODEL_SERIALIZER_CLASS':\n 'gridplatform.rest.serializers.DefaultSerializer',\n 'DEFAULT_PAGINATION_SERIALIZER_CLASS':\n 'gridplatform.rest.serializers.DefaultPaginationSerializer',\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'gridplatform.token_auth.authentication.EncryptionTokenAuthentication',\n 'rest_framework.authentication.SessionAuthentication',\n ),\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.DjangoModelPermissions',\n ),\n 'DEFAULT_RENDERER_CLASSES': (\n 'djangorestframework_camel_case.render.CamelCaseJSONRenderer',\n 'rest_framework.renderers.BrowsableAPIRenderer',\n ),\n 'DEFAULT_PARSER_CLASSES': (\n 'djangorestframework_camel_case.parser.CamelCaseJSONParser',\n 'rest_framework.parsers.FormParser',\n 'rest_framework.parsers.MultiPartParser'\n ),\n 'PAGINATE_BY': 10000,\n 'EXCEPTION_HANDLER': (\n 'gridplatform.rest.gridplatform_rest_api_exception_handler'),\n}\n# ######### END DJANGO REST FRAMEWORK CONFIGURATION\n\n\nBOOTSTRAP_THEME = 'genius'\n\nSESSION_SAVE_EVERY_REQUEST = True\n\n\nQUARTER_FORMAT = 'Q Y'\nYEAR_FORMAT = 'Y'\n\nSITE_MAIL_ADDRESS = \"[email protected]\"\n" }, { "alpha_fraction": 0.7063403725624084, "alphanum_fraction": 0.7074527144432068, "avg_line_length": 28.96666717529297, "blob_id": "33e6a07e41afb97e3e9df47e8639ceedc8523755", "content_id": "5b6327ebcd1777c051331b310906b0d769787190", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 899, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/gridplatform/global_datasources/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport django_filters\nfrom rest_framework import viewsets\n\nfrom . import models\nfrom . import serializers\n\n\nclass GlobalDataSourceFilter(django_filters.FilterSet):\n hardware_id_contains = django_filters.CharFilter(\n name='hardware_id', lookup_type='contains')\n name_contains = django_filters.CharFilter(\n name='name', lookup_type='icontains')\n\n class Meta:\n model = models.GlobalDataSource\n fields = (\n 'name', 'unit', 'hardware_id',\n 'hardware_id_contains', 'name_contains'\n )\n\n\nclass GlobalDataSourceViewSet(viewsets.ModelViewSet):\n model = models.GlobalDataSource\n serializer_class = serializers.GlobalDataSourceSerializer\n filter_class = GlobalDataSourceFilter\n filter_fields = GlobalDataSourceFilter.Meta.fields\n" }, { "alpha_fraction": 0.5469241142272949, "alphanum_fraction": 0.5493938326835632, "avg_line_length": 40.62616729736328, "blob_id": "1e2bce10406ecdeadaf243f4bf2db522538c3ba3", "content_id": "e4642e5333f8acc44d1f56080a7dcd57f4cb70e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4454, "license_type": "no_license", "max_line_length": 100, "num_lines": 107, "path": "/gridplatform/datahub/management/commands/fetch_datahub.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\nimport StringIO\nfrom operator import itemgetter\n\nimport dateutil.parser\nimport pycurl\nimport pytz\n\nfrom django.core.management.base import BaseCommand\nfrom django.conf import settings\n\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.datahub.models import DatahubConnection\n\n\nclass Command(BaseCommand):\n help = \"Import data from datahub\"\n\n def handle(self, *args, **options):\n b = StringIO.StringIO()\n c = pycurl.Curl()\n url = 'https://eloverblik.dk/api/authorizationsv2'\n c.setopt(pycurl.URL, url)\n c.setopt(pycurl.WRITEFUNCTION, b.write)\n c.setopt(pycurl.SSLKEY, settings.NETS_KEY_DIR + \"/plainkey.pem\")\n c.setopt(pycurl.SSLCERT, settings.NETS_KEY_DIR + \"/crt.pem\")\n c.perform()\n c.close()\n response_body = b.getvalue()\n\n authorizations = json.loads(response_body)\n\n connections = DatahubConnection.objects.all()\n now = datetime.date.today()\n\n for connection in connections:\n if not connection.end_date or connection.end_date < now:\n for customer in authorizations:\n for meter in customer[\"ListOfMeteringPoints\"]:\n if meter[\"MeteringPointIdentification\"] == connection.customer_meter_number:\n connection.start_date = dateutil.parser.parse(\n customer[\"StartDate\"]).date()\n connection.end_date = dateutil.parser.parse(\n customer[\"EndDate\"]).date()\n connection.authorization_id = customer[\"Id\"]\n connection.save()\n\n if connection.end_date and connection.end_date >= now:\n b = StringIO.StringIO()\n c = pycurl.Curl()\n url = 'https://eloverblik.dk/api/timeseries?authorizationid=' + \\\n str(connection.authorization_id) + '&meteringpointid=' + \\\n str(connection.customer_meter_number) + '&period=Month'\n c.setopt(pycurl.URL, url)\n c.setopt(pycurl.WRITEFUNCTION, b.write)\n c.setopt(pycurl.SSLKEY, settings.NETS_KEY_DIR + \"/plainkey.pem\")\n c.setopt(pycurl.SSLCERT, settings.NETS_KEY_DIR + \"/crt.pem\")\n c.perform()\n c.close()\n response_body = b.getvalue()\n measurements = json.loads(response_body)\n\n input_id = connection.meter.physicalinput_set.first().id\n last_value = 0\n last_timestamp = None\n try:\n last_data = RawData.objects.filter(\n datasource_id=input_id\n ).latest('timestamp')\n last_value = last_data.value\n last_timestamp = last_data.timestamp\n except RawData.DoesNotExist:\n pass\n\n if \"Message\" in measurements:\n print measurements[\"Message\"]\n else:\n sorted_measurements = sorted(\n measurements, key=itemgetter('DateFrom'))\n for m in sorted_measurements:\n timestamp = dateutil.parser.parse(m[\"DateTo\"]).replace(\n tzinfo=pytz.timezone('Europe/Copenhagen'))\n if last_timestamp and last_timestamp >= timestamp:\n continue\n last_value += int(float(m[\"Usage\"]) * 1000 * 1000)\n last_timestamp = timestamp\n\n RawData.objects.create(\n timestamp=timestamp, datasource_id=input_id, value=last_value)\n\n def _update_or_create(self, timestamp, datasource_id, updated_values):\n try:\n obj = RawData.objects.get(\n timestamp=timestamp, datasource_id=datasource_id)\n for key, value in updated_values.iteritems():\n setattr(obj, key, value)\n obj.save()\n except RawData.DoesNotExist:\n updated_values.update(\n {'timestamp': timestamp, 'datasource_id': datasource_id, 'unit': \"milliwatt*hour\"})\n obj = RawData(**updated_values)\n obj.save()\n" }, { "alpha_fraction": 0.6522988677024841, "alphanum_fraction": 0.6580459475517273, "avg_line_length": 25.846153259277344, "blob_id": "da196671e53e1c0c96f7c121ae98e4b298311772", "content_id": "ab5de964129f41af268f67f5304576042c39160f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 348, "license_type": "no_license", "max_line_length": 51, "num_lines": 13, "path": "/legacy/manage_measurementpoints/templates/manage_measurementpoints/form_includes/meter_options_form.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% load i18n %}\n{% load widget_tweaks %}\n\n<fieldset>\n <label>{% trans 'Meter number:' %}</label>\n {{ form.billing_meter_number }}\n {{ form.billing_meter_number.errors }}\n</fieldset>\n<fieldset>\n <label>{% trans 'Installation number:' %}</label>\n {{ form.billing_installation_number }}\n {{ form.billing_installation_number.errors }}\n</fieldset>" }, { "alpha_fraction": 0.6342512965202332, "alphanum_fraction": 0.6437177062034607, "avg_line_length": 35.50261688232422, "blob_id": "1d7d5880dc271288d377e693913cc8d68cd36d6f", "content_id": "4870797fda9985765bbc8b75556b316d9c7c34ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6975, "license_type": "no_license", "max_line_length": 78, "num_lines": 191, "path": "/gridplatform/productions/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom mock import patch\n\nimport pytz\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.test import RequestFactory\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import condense\nfrom gridplatform.users.models import User\nfrom gridplatform.rest.serializers import HyperlinkedIdentityField\nfrom gridplatform.rest.serializers import HyperlinkedRelatedField\nfrom gridplatform.trackuser import replace_customer\n\nfrom .models import SingleValuePeriod\nfrom .models import Production\nfrom .models import ProductionGroup\nfrom . import viewsets\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create(\n production_b_unit_plain='Pöp Cørn',\n production_c_unit_plain='Ikeä')\n\n # simulate how ModelForm.instance would be initialized.\n with replace_customer(self.customer):\n self.production = Production()\n\n def test_unit_choices(self):\n self.assertNotIn('production_a', self.production.unit_choices)\n self.assertIn('production_b', self.production.unit_choices)\n\n def test_get_unit_display(self):\n self.production.unit = 'production_b'\n unicode(self.production.get_unit_display())\n\n def test_clean_happy(self):\n self.production.unit = 'production_b'\n self.production.clean()\n\n def test_clean_invalid_unit(self):\n self.production.unit = 'production_a'\n with self.assertRaises(ValidationError) as ctx:\n self.production.clean()\n self.assertIn('unit', ctx.exception.message_dict)\n\n def test_clean_unit_change(self):\n self.production.unit = 'production_c'\n self.production.save()\n self.production.unit = 'production_b'\n with self.assertRaises(ValidationError) as ctx:\n self.production.clean()\n self.assertIn('unit', ctx.exception.message_dict)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass ProductionGroupTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.provider = Provider.objects.create()\n self.customer = Customer.objects.create()\n\n def test_production_sequence_integration(self):\n productiongroup = ProductionGroup.objects.create(\n customer=self.customer,\n unit='production_a')\n\n productiongroup.productions.add(\n Production.objects.create(\n unit='production_a',\n customer=self.customer))\n productiongroup.productions.add(\n Production.objects.create(\n unit='production_a',\n customer=self.customer))\n\n productions = list(productiongroup.productions.all())\n self.assertEqual(len(productions), 3) # the above + historical\n\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n patched_development_sequence = patch.object(\n Production,\n 'development_sequence',\n return_value=[\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(42, 'production_a'))],\n autospec=True)\n\n with patched_development_sequence as mock:\n result = list(\n productiongroup.production_sequence(\n from_timestamp, to_timestamp, condense.DAYS))\n\n mock.assert_any_call(\n productions[0], from_timestamp, to_timestamp, condense.DAYS)\n mock.assert_any_call(\n productions[1], from_timestamp, to_timestamp, condense.DAYS)\n mock.assert_any_call(\n productions[2], from_timestamp, to_timestamp, condense.DAYS)\n\n self.assertEqual(mock.call_count, 3)\n\n self.assertEqual(\n [\n RangedSample(\n from_timestamp, to_timestamp,\n PhysicalQuantity(126, 'production_a'))],\n result)\n\n\ndef get_url_mock(self, obj, view_name, request, format):\n \"\"\"Mock used to render HyperlinkedModelSerializer\"\"\"\n return \"/%s\" % view_name\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass ProductionGroupViewSetTest(TestCase):\n\n def setUp(self):\n self.provider = Provider.objects.create()\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.customer = Customer.objects.create(\n timezone=self.timezone,\n production_a_unit_plain='whatever')\n\n self.factory = RequestFactory()\n\n self.productiongroup = ProductionGroup.objects.create(\n customer=self.customer,\n name_plain='Die Produktionsgruppe',\n unit='production_a')\n\n production = Production.objects.create(\n unit='production_a',\n customer=self.customer)\n self.productiongroup.productions.add(production)\n\n SingleValuePeriod.objects.create(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 10, 1)),\n datasequence=production,\n value=1024,\n unit='production_a')\n\n def test_get(self):\n request = self.factory.get('/', content_type='application/json')\n request.user = User(name_plain='test user')\n view = viewsets.ProductionGroup.as_view(actions={'get': 'list'})\n with patch.object(\n HyperlinkedIdentityField, 'get_url',\n get_url_mock), \\\n patch.object(\n HyperlinkedRelatedField, 'get_url',\n get_url_mock):\n response = view(request, pk=self.productiongroup.id)\n self.assertContains(response, 'Die Produktionsgruppe')\n\n def test_get_hourly(self):\n request = self.factory.get(\n '/?date=2014-08-19', content_type='application/json')\n request.user = User(name_plain='test user')\n\n view = viewsets.ProductionGroup.as_view(actions={'get': 'hourly'})\n with patch.object(\n HyperlinkedIdentityField, 'get_url',\n get_url_mock), \\\n patch.object(\n HyperlinkedRelatedField, 'get_url',\n get_url_mock):\n response = view(request, pk=self.productiongroup.id)\n self.assertContains(response, '2014-08-19T00:00:00+02:00')\n" }, { "alpha_fraction": 0.5971184372901917, "alphanum_fraction": 0.5989861488342285, "avg_line_length": 32.76576614379883, "blob_id": "f857e41febd26b888cbcfc38b30b1be11d29412d", "content_id": "b48f5009098df6b623e6a5f8e55474b22f7ca4da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3748, "license_type": "no_license", "max_line_length": 76, "num_lines": 111, "path": "/legacy/devices/management/commands/check_inputs.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport contextlib\nimport datetime\nimport cStringIO\n\nfrom django.conf import settings\nfrom django.core.mail import EmailMessage\nfrom django.core.management.base import BaseCommand\nfrom django.db import connection\nimport pytz\nimport unicodecsv\n\n\nfrom gridplatform.datasequences.models import NonpulseAccumulationPeriod\nfrom gridplatform.datasequences.models import PulseAccumulationPeriod\nfrom gridplatform.consumptions.models import Consumption\n\n\nclass _excel_semicolon(unicodecsv.excel):\n delimiter = b';'\n\n\ndef _format_csv(data, header=None):\n with contextlib.closing(cStringIO.StringIO()) as outfile:\n # BOM included for Excel-compatibility --- assuming that this is the\n # \"start of the file\"\n bom = b'\\xef\\xbb\\xbf'\n outfile.write(bom)\n writer = unicodecsv.writer(outfile, dialect=_excel_semicolon)\n if header is not None:\n writer.writerow(header)\n for mp in sorted(data, key=lambda x: (getattr(x, 'customer_id'),\n getattr(x, 'id'))):\n writer.writerow((mp.id, mp.customer.id))\n return outfile.getvalue()\n\n\n_csv_header = ('measurementpoint id', 'customer id')\n\n\ndef _physicalinput_data(pi):\n return (\n pi.meter.agent.mac,\n pi.meter.get_manufactoring_id_display(),\n pi.get_type_display(),\n pi.order,\n pi.meter.customer_id)\n\n\nclass Command(BaseCommand):\n args = '[email_recipient]'\n help = 'Get lists of inputs with no measurements or no change in '\n ' measurements for the last 24 hours.'\n\n def handle(self, *args, **options):\n try:\n email = args[0]\n except IndexError:\n email = None\n now = datetime.datetime.now(pytz.utc).replace(microsecond=0)\n day_ago = now - datetime.timedelta(days=1)\n\n cursor = connection.cursor()\n cursor.execute(\n 'SELECT datasource_id '\n 'FROM datasources_rawdata WHERE timestamp > %s '\n 'GROUP BY datasource_id '\n 'HAVING MIN(value) = MAX(value)', [day_ago])\n ids = [n for (n,) in cursor.fetchall()]\n\n nonpulseaccum_inputperiods = \\\n NonpulseAccumulationPeriod.objects.filter(\n data_source_id__in=ids)\n pulseaccum_inputperiods = \\\n PulseAccumulationPeriod.objects.filter(\n data_source_id__in=ids)\n inputconfiguration_ids = set(\n list(nonpulseaccum_inputperiods.values_list(\n 'input_configuration_id', flat=True)) +\n list(pulseaccum_inputperiods.values_list(\n 'input_configuration_id', flat=True)))\n\n mps = []\n for inputconfiguration_id in inputconfiguration_ids:\n inputconfiguration = Consumption.objects.get(\n id=inputconfiguration_id)\n if inputconfiguration.link_derivative_set.exists():\n mps.append(inputconfiguration.\n link_derivative_set.all()[0].graph.\n collection.subclass_instance)\n\n no_change = _format_csv(\n mps,\n _csv_header)\n if email:\n message = EmailMessage(\n 'Input check report',\n 'Period: {} -- {}'.format(day_ago, now),\n settings.SITE_MAIL_ADDRESS,\n [email])\n message.attach(\n 'no_change.csv', no_change, 'text/csv')\n message.send(fail_silently=False)\n else:\n print 'Period: {} -- {}'.format(day_ago, now)\n print\n print 'No change in measurements:'\n print no_change\n" }, { "alpha_fraction": 0.594482421875, "alphanum_fraction": 0.597412109375, "avg_line_length": 41.226802825927734, "blob_id": "836fce66c7a1e3e758884e57b44dbe5e1c268891", "content_id": "6028a94841e368ae91f6f9c8bb6528076a92dd2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4096, "license_type": "no_license", "max_line_length": 78, "num_lines": 97, "path": "/legacy/display_widgets/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\n\nfrom celery import shared_task\n\nfrom legacy.measurementpoints.proxies import MeasurementPoint\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.trackuser.tasks import trackuser_task\n\n\n@trackuser_task\n@shared_task(name='legacy.display_widgets.tasks.gauge_task')\ndef gauge_task(widget, from_timestamp, to_timestamp):\n \"\"\"\n @bug: What is the desired return values when no data is available. A\n today_min of 0 might be violating gauge_min, so it is in no way neutral to\n replace missing values with 0. On the other hand, if the interpolation\n later shows that the gauge thresholds were violated at a certain time, it\n would be eroneuous to have the gauge indicate anything different.\n \"\"\"\n measurement_point = get_object_or_404(\n MeasurementPoint.objects.subclass_only(),\n id=widget.collection_id).subclass_instance\n\n gauge_lower_threshold = measurement_point.gauge_lower_threshold\n gauge_upper_threshold = measurement_point.gauge_upper_threshold\n gauge_min = measurement_point.gauge_min\n gauge_max = measurement_point.gauge_max\n today_avg, today_min, today_max = \\\n measurement_point.get_gauge_data_series().aggregated_samples(\n from_timestamp, to_timestamp)\n last_rate = measurement_point.get_gauge_data_series().latest_sample(\n from_timestamp, to_timestamp)\n gauge_unit = widget.collection.gauge_preferred_unit\n\n preferred_unit_converter = measurement_point.rate.\\\n get_preferred_unit_converter()\n\n if last_rate is None:\n return {\n 'last_rate': None,\n 'minimum': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_min, gauge_unit))),\n 'low': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_lower_threshold, gauge_unit))),\n 'high': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(\n gauge_upper_threshold, gauge_unit))),\n 'maximum': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_max, gauge_unit))),\n 'color': widget.collection.gauge_colours,\n 'unit': unicode(preferred_unit_converter.get_display_unit()),\n 'today_min': None,\n 'today_max': None,\n 'today_avg': None}\n else:\n return {\n 'last_rate': float(\n preferred_unit_converter.extract_value(\n last_rate.physical_quantity)),\n 'minimum': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_min, gauge_unit))),\n 'low': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_lower_threshold, gauge_unit))),\n 'high': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_upper_threshold, gauge_unit))),\n 'maximum': float(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(gauge_max, gauge_unit))),\n 'color': widget.collection.gauge_colours,\n 'unit': unicode(preferred_unit_converter.get_display_unit()),\n 'today_min': round(\n float(\n preferred_unit_converter.extract_value(\n today_min.physical_quantity)),\n 3),\n 'today_max': round(\n float(\n preferred_unit_converter.extract_value(\n today_max.physical_quantity)),\n 3),\n 'today_avg': round(\n float(\n preferred_unit_converter.extract_value(\n today_avg.physical_quantity)),\n 3),\n }\n" }, { "alpha_fraction": 0.6858071684837341, "alphanum_fraction": 0.6868906021118164, "avg_line_length": 27.84375, "blob_id": "6df62d4c0efe32a7d6f96596c451052eb564a3ad", "content_id": "8e0876027feb9f26bef3c0bae7549171a3fc5d60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 923, "license_type": "no_license", "max_line_length": 87, "num_lines": 32, "path": "/gridplatform/rest/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nThese settings control the view names and namespaces used for the REST API.\n\n.. data:: settings.REST_API_NAMESPACE = 'api'\n\n URL namespace used to generically define view names when combined with\n :data:`settings.REST_SERIALIZER_VIEW_NAME_BASE` and generic postfixes such\n as ``'-list'`` or ``'-detail'``.\n\n.. data:: settings.REST_SERIALIZER_VIEW_NAME_BASE = '%(app_label)s:%(model_name)s'\n\n Format string used to generically define base of view names of REST views. Will be\n formatted with the arguments ``app_label`` and ``model_name``.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom appconf import AppConf\nfrom django.conf import settings\n\n\n__all__ = ['settings', 'RestConf']\n\n\nclass RestConf(AppConf):\n\n class Meta:\n prefix = 'rest'\n\n API_NAMESPACE = 'api'\n SERIALIZER_VIEW_NAME_BASE = '%(app_label)s:%(model_name)s'\n" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6681159138679504, "avg_line_length": 29, "blob_id": "cd9de9922d03107d2b02b8ed3441eac71dd6f2a8", "content_id": "3fbb711c77699d988f7148ea4a656b24f584285c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 694, "license_type": "no_license", "max_line_length": 72, "num_lines": 23, "path": "/legacy/display_measurementpoints/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nTest module for the L{legacy.display_measurementpoints} Django\napp.\n\"\"\"\n\nfrom django.test import TestCase\nfrom django.utils import translation\n\nfrom .templatetags.display_measurementpoints import physicalquantity\n\n\nclass TemplateFilterTest(TestCase):\n def test_physicalquantity(self):\n with translation.override('da-dk'):\n self.assertEqual(\n u'0,3333333333 Å', physicalquantity((1 / 3., u'Å'), 10))\n\n with translation.override('en-uk'):\n self.assertEqual(\n u'0.3333333333 Å', physicalquantity((1 / 3., u'Å'), 10))\n" }, { "alpha_fraction": 0.4890264570713043, "alphanum_fraction": 0.49859312176704407, "avg_line_length": 28.131147384643555, "blob_id": "4f62c8ea396259eb27269bd3e5155ef7b0110ee0", "content_id": "67e7f428a0133eaae882922b81cc040f49858079", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1777, "license_type": "no_license", "max_line_length": 64, "num_lines": 61, "path": "/legacy/nordpool/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom appconf import AppConf\nfrom django.utils.translation import ugettext_noop\n\n__all__ = ['settings', 'NordpoolConf']\n\n\nclass NordpoolConf(AppConf):\n HOST = 'ftp.nordpoolspot.com'\n\n SPOT_PRICES = (\n {\n 'CODENAME': 'denmark_west',\n 'NORDPOOL_UNIT': 'currency_dkk*megawatt^-1*hour^-1',\n 'UNIT': 'currency_dkk*gigawatt^-1*hour^-1',\n 'NAME': ugettext_noop('Nordpool Denmark West DKK'),\n 'CURRENCY': 'DKK',\n 'COUNTRY': 'DK',\n 'TIMEZONE': 'Europe/Copenhagen',\n 'AREA': 'DK1',\n },\n {\n 'CODENAME': 'denmark_east',\n 'NORDPOOL_UNIT': 'currency_dkk*megawatt^-1*hour^-1',\n 'UNIT': 'currency_dkk*gigawatt^-1*hour^-1',\n 'NAME': ugettext_noop('Nordpool Denmark East DKK'),\n 'CURRENCY': 'DKK',\n 'COUNTRY': 'DK',\n 'TIMEZONE': 'Europe/Copenhagen',\n 'AREA': 'DK2',\n },\n )\n\n # Legacy\n AUTO_INDEXES = [\n {\n # index\n 'COUNTRY': 'denmark',\n 'UNIT': 'currency_dkk*megawatt^-1*hour^-1',\n 'NAME': ugettext_noop('Nordpool Denmark West DKK'),\n # nordpool\n 'AREA': 'DK1',\n 'TIMEZONE': 'Europe/Copenhagen',\n },\n {\n # index\n 'COUNTRY': 'denmark',\n 'UNIT': 'currency_dkk*megawatt^-1*hour^-1',\n 'NAME': ugettext_noop('Nordpool Denmark East DKK'),\n # nordpool\n 'AREA': 'DK2',\n 'TIMEZONE': 'Europe/Copenhagen',\n }\n ]\n\n class Meta:\n required = ['USER', 'PASS']\n" }, { "alpha_fraction": 0.7277598977088928, "alphanum_fraction": 0.729903519153595, "avg_line_length": 31.172412872314453, "blob_id": "423492bd6350140066e5f0f941b62fb4e889fc44", "content_id": "5b76998facbd2e97a11be066fd378380f316e64e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 933, "license_type": "no_license", "max_line_length": 74, "num_lines": 29, "path": "/gridplatform/utils/management/commands/fix_contenttypes_and_permissions.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nDefines a ``fix_contenttypes_and_permissions`` command, which runs\n:func:`django.contrib.contenttypes.management.update_all_contenttypes`\nand then runs\n:func:`django.contrib.auth.management.create_permissions` for each\napp. This ensures that there are no missing content types and no\nmissing permissions.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.contrib.auth.management import create_permissions\nfrom django.contrib.contenttypes.management import update_all_contenttypes\nfrom django.core.management.base import BaseCommand\nfrom django.db.models import get_apps\n\n\nclass Command(BaseCommand):\n args = ''\n help = ''\n\n def handle(self, *args, **options):\n # Add any missing content types\n update_all_contenttypes()\n\n # Add any missing permissions\n for app in get_apps():\n create_permissions(app, None, 2)\n" }, { "alpha_fraction": 0.6209150552749634, "alphanum_fraction": 0.6230936646461487, "avg_line_length": 37.25, "blob_id": "c1cd0f29429a4ee83cb806c27831a7e3bf71523b", "content_id": "29fa2f859121e9182febf6cb9d11f0623298cbdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 918, "license_type": "no_license", "max_line_length": 116, "num_lines": 24, "path": "/legacy/setup_agents/templates/setup_agents/agent_list.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends \"list_page.html\" %}\n{% load i18n %}\n{% load static from staticfiles %}\n\n\n{% block page_id %}agents-page{% endblock %}\n{% block list_url %}{% url 'setup_agents-list-json' %}{% endblock %}\n{% block default_sort_by %}mac{% endblock %}\n\n{% block title %}{% trans \"Agent Administration\" %}{% endblock %}\n{% block content_heading %}{% trans \"Agent Administration\" %}{% endblock content_heading %}\n{% block list_title %}{% trans \"Agents\" %}{% endblock %}\n\n{% block add_button %}\n<a class=\"right list-modifier\" href=\"#\" data-targeturl=\"{% url 'setup_agents-form'%}\" data-targetlist=\"#model-list\">\n <span>{% trans \"Add agent\" %}&nbsp;</span>\n <img src=\"{% static 'images/add-icon.png' %}\" alt=\"{% trans \"Add agent\" %}\">\n</a>\n{% endblock %}\n\n{% block sort_by %}\n<span class=\"sort\" data-sort=\"mac\">{% trans \"MAC\" %}</span>\n<span class=\"sort\" data-sort=\"customer\">{% trans \"Customer\" %}</span>\n{% endblock sort_by %}\n" }, { "alpha_fraction": 0.7724936008453369, "alphanum_fraction": 0.7724936008453369, "avg_line_length": 32.826087951660156, "blob_id": "facc5635dca0865ee73ba2fe49c803d1435bb509", "content_id": "d8458978c35288d72f9a31dd1d03f75c6a524b98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 778, "license_type": "no_license", "max_line_length": 83, "num_lines": 23, "path": "/documentation/source/apps/gridplatform/datasources.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Data Sources\n============\n\n.. autoclass:: gridplatform.datasources.models.DataSource\n :members: hourly_accumulated, five_minute_accumulated, _get_interpolate_fn,\n raw_sequence, next_valid_date, previous_valid_date\n\n.. autoclass:: gridplatform.datasources.models.RawData\n :members: clean, interpolate\n\nManagers\n--------\n\n.. autoclass:: gridplatform.datasources.managers.DataSourceQuerySetMixinBase\n :members: _apply_filtering, _apply_customer_filtering, _apply_provider_filtering\n\n\n.. autoclass:: gridplatform.datasources.managers.DataSourceQuerySetMixin\n :members: _apply_customer_filtering, _apply_provider_filtering\n\n.. autoclass:: gridplatform.datasources.managers.DataSourceManagerBase\n\n.. autoclass:: gridplatform.datasources.managers.DataSourceManager\n" }, { "alpha_fraction": 0.6239941716194153, "alphanum_fraction": 0.6283833384513855, "avg_line_length": 26.897958755493164, "blob_id": "a4f50107ec68a60112fae9753b0aaa09028beeb8", "content_id": "2007deb3661a8d0a577dd5f98fa19270c7e17ce5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1367, "license_type": "no_license", "max_line_length": 78, "num_lines": 49, "path": "/run_all_tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nRun all our tests\n\"\"\"\n\nimport os\nimport re\nimport coverage\nimport sys\n\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"gridplatform.settings.local\")\n\nfrom django.conf import settings\nfrom django.core.management import execute_from_command_line\n\n\ndef main():\n \"\"\"\n Run all our tests\n \"\"\"\n\n if len(sys.argv) > 1:\n apps = sys.argv[1:]\n else:\n apps = settings.PLATFORM_APPS + settings.LEGACY_APPS + \\\n settings.ENERGYMANAGER_APPS\n\n omit = ['*/*/migrations/*']\n cov = coverage.coverage(source=apps, omit=omit, branch=True)\n cov.use_cache(0)\n cov.start()\n # NOTE: collectstatic is necessary for staticfiles {% static %} when\n # STATICFILES_STORAGE is CachedStaticFilesStorage; URLs will contain\n # MD5-sums of contents of files read from the CachedStaticFilesStorage,\n # i.e. from files under STATIC_ROOT, i.e. from the \"output\" directory of\n # collectstatic\n execute_from_command_line([\"\", \"collectstatic\",\n \"--noinput\", \"--traceback\"])\n\n execute_from_command_line([\"\", \"test\", \"--noinput\",\n \"--traceback\"] + list(apps))\n cov.stop()\n cov.report(show_missing=1)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5715585350990295, "alphanum_fraction": 0.5793325901031494, "avg_line_length": 93.46875, "blob_id": "1c33c8d7cf3ba204772e7a01dbe47b20307d0566", "content_id": "f4b2a7f9d3c4180d8dacb529f96b3043d962ef0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24183, "license_type": "no_license", "max_line_length": 211, "num_lines": 256, "path": "/legacy/energy_use_reports/migrations/0001_initial.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n pass\n\n def backwards(self, orm):\n pass\n\n models = {\n u'auth.group': {\n 'Meta': {'object_name': 'Group'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),\n 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u\"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'})\n },\n u'auth.permission': {\n 'Meta': {'ordering': \"(u'content_type__app_label', u'content_type__model', u'codename')\", 'unique_together': \"((u'content_type', u'codename'),)\", 'object_name': 'Permission'},\n 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['contenttypes.ContentType']\"}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n },\n u'auth.user': {\n 'Meta': {'object_name': 'User'},\n 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),\n 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': \"u'user_set'\", 'blank': 'True', 'to': u\"orm['auth.Group']\"}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),\n 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),\n 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),\n 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': \"u'user_set'\", 'blank': 'True', 'to': u\"orm['auth.Permission']\"}),\n 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})\n },\n u'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n u'customers.collection': {\n 'Meta': {'object_name': 'Collection'},\n 'billing_installation_number': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),\n 'billing_meter_number': ('django.db.models.fields.CharField', [], {'max_length': '20', 'blank': 'True'}),\n 'comment': ('gridplatform.encryption.fields.EncryptedTextField', [], {'blank': 'True'}),\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u\"orm['customers.Customer']\", 'on_delete': 'models.PROTECT', 'blank': 'True'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'gauge_colours': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True', 'blank': 'True'}),\n 'gauge_lower_threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),\n 'gauge_max': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),\n 'gauge_min': ('django.db.models.fields.DecimalField', [], {'default': '0', 'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),\n 'gauge_preferred_unit': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),\n 'gauge_upper_threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '10', 'decimal_places': '2', 'blank': 'True'}),\n 'hidden_on_details_page': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'hidden_on_reports_page': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'image': ('imagekit.models.fields.ProcessedImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': \"u'children'\", 'null': 'True', 'to': u\"orm['customers.Collection']\"}),\n 'relay': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['devices.Meter']\", 'null': 'True', 'on_delete': 'models.PROTECT', 'blank': 'True'}),\n 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'role': ('django.db.models.fields.IntegerField', [], {}),\n 'subclass': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"u'+'\", 'on_delete': 'models.PROTECT', 'to': u\"orm['contenttypes.ContentType']\"}),\n 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'utility_type': ('django.db.models.fields.IntegerField', [], {})\n },\n u'customers.customer': {\n 'Meta': {'ordering': \"[u'id']\", 'object_name': 'Customer'},\n 'address': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'city': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '30', 'blank': 'True'}),\n 'contact_email': ('gridplatform.encryption.fields.EncryptedEmailField', [], {'max_length': '50', 'blank': 'True'}),\n 'contact_name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'contact_phone': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'country_code': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '3', 'blank': 'True'}),\n 'created': ('model_utils.fields.AutoCreatedField', [], {'default': 'datetime.datetime.now'}),\n 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"u'+'\", 'null': 'True', 'to': u\"orm['users.User']\"}),\n 'currency_unit': ('gridplatform.utils.fields.BuckinghamField', [], {'default': \"u'currency_dkk'\", 'max_length': '100'}),\n 'electricity_consumption': ('django.db.models.fields.CharField', [], {'default': \"u'kilowatt*hour'\", 'max_length': '50'}),\n 'electricity_instantaneous': ('django.db.models.fields.CharField', [], {'default': \"u'kilowatt'\", 'max_length': '50'}),\n 'electricity_tariff': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"u'electricity_tariff_set'\", 'null': 'True', 'to': u\"orm['measurementpoints.DataSeries']\"}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'gas_consumption': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter'\", 'max_length': '50'}),\n 'gas_instantaneous': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter*hour^-1'\", 'max_length': '50'}),\n 'gas_tariff': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"u'gas_tariff_set'\", 'null': 'True', 'to': u\"orm['measurementpoints.DataSeries']\"}),\n 'heat_consumption': ('django.db.models.fields.CharField', [], {'default': \"u'kilowatt*hour'\", 'max_length': '50'}),\n 'heat_instantaneous': ('django.db.models.fields.CharField', [], {'default': \"u'kilowatt'\", 'max_length': '50'}),\n 'heat_tariff': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"u'heat_tariff_set'\", 'null': 'True', 'to': u\"orm['measurementpoints.DataSeries']\"}),\n 'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}),\n 'industry_types': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u\"orm['salesopportunities.IndustryType']\", 'null': 'True', 'blank': 'True'}),\n 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'modified': ('model_utils.fields.AutoLastModifiedField', [], {'default': 'datetime.datetime.now'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'oil_consumption': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter'\", 'max_length': '50'}),\n 'oil_instantaneous': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter*hour^-1'\", 'max_length': '50'}),\n 'oil_tariff': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"u'oil_tariff_set'\", 'null': 'True', 'to': u\"orm['measurementpoints.DataSeries']\"}),\n 'phone': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'postal_code': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '10', 'blank': 'True'}),\n 'production_a_unit': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'production_b_unit': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'production_c_unit': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'production_d_unit': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'production_e_unit': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'provider': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'to': u\"orm['providers.Provider']\"}),\n 'temperature': ('django.db.models.fields.CharField', [], {'default': \"u'celsius'\", 'max_length': '50'}),\n 'timezone': ('timezones2.models.TimeZoneField', [], {'max_length': '64'}),\n 'vat': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '20', 'blank': 'True'}),\n 'water_consumption': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter'\", 'max_length': '50'}),\n 'water_instantaneous': ('django.db.models.fields.CharField', [], {'default': \"u'meter*meter*meter*hour^-1'\", 'max_length': '50'}),\n 'water_tariff': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': \"u'water_tariff_set'\", 'null': 'True', 'to': u\"orm['measurementpoints.DataSeries']\"})\n },\n u'customers.location': {\n 'Meta': {'object_name': 'Location'},\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u\"orm['customers.Customer']\", 'blank': 'True'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'parent': ('mptt.fields.TreeForeignKey', [], {'blank': 'True', 'related_name': \"u'children'\", 'null': 'True', 'on_delete': 'models.PROTECT', 'to': u\"orm['customers.Location']\"}),\n 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),\n 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})\n },\n u'customers.measurementpoint': {\n 'Meta': {'object_name': 'MeasurementPoint', 'db_table': \"u'customers_collection'\", '_ormbases': [u'customers.Collection'], 'proxy': 'True'}\n },\n u'devices.agent': {\n 'Meta': {'ordering': \"[u'location', u'mac']\", 'object_name': 'Agent'},\n 'add_mode': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Customer']\", 'on_delete': 'models.PROTECT'}),\n 'device_serial': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),\n 'device_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),\n 'hw_major': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_minor': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_revision': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_subrevision': ('django.db.models.fields.CharField', [], {'max_length': '12'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Location']\", 'null': 'True', 'on_delete': 'models.PROTECT', 'blank': 'True'}),\n 'mac': ('gridplatform.utils.fields.MacAddressField', [], {'unique': 'True'}),\n 'no_longer_in_use': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'online': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'online_since': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),\n 'sw_major': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_minor': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_revision': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_subrevision': ('django.db.models.fields.CharField', [], {'max_length': '12'})\n },\n u'devices.meter': {\n 'Meta': {'ordering': \"[u'connection_type', u'manufactoring_id', u'id']\", 'object_name': 'Meter'},\n 'agent': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['devices.Agent']\", 'on_delete': 'models.PROTECT'}),\n 'connection_type': ('django.db.models.fields.IntegerField', [], {}),\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Customer']\", 'on_delete': 'models.PROTECT'}),\n 'device_serial': ('django.db.models.fields.IntegerField', [], {'null': 'True'}),\n 'device_type': ('django.db.models.fields.IntegerField', [], {'default': '0'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'hw_major': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_minor': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_revision': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'hw_subrevision': ('django.db.models.fields.CharField', [], {'max_length': '12'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'joined': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),\n 'location': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Location']\", 'null': 'True', 'on_delete': 'models.PROTECT', 'blank': 'True'}),\n 'manual_mode': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'manufactoring_id': ('django.db.models.fields.BigIntegerField', [], {}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50', 'blank': 'True'}),\n 'online': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'online_since': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),\n 'relay_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'relay_on': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n 'sw_major': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_minor': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_revision': ('django.db.models.fields.PositiveIntegerField', [], {'null': 'True'}),\n 'sw_subrevision': ('django.db.models.fields.CharField', [], {'max_length': '12'})\n },\n u'energy_use_reports.energyusearea': {\n 'Meta': {'object_name': 'EnergyUseArea'},\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'measurement_points': ('django.db.models.fields.related.ManyToManyField', [], {'to': u\"orm['customers.MeasurementPoint']\", 'symmetrical': 'False'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'report': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['energy_use_reports.EnergyUseReport']\"})\n },\n u'energy_use_reports.energyusereport': {\n 'Meta': {'object_name': 'EnergyUseReport'},\n 'currency_unit': ('gridplatform.utils.fields.BuckinghamField', [], {'default': \"u'currency_dkk'\", 'max_length': '100'}),\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u\"orm['customers.Customer']\"}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'main_measurement_points': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'to': u\"orm['customers.MeasurementPoint']\", 'null': 'True', 'blank': 'True'}),\n 'title': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'utility_type': ('django.db.models.fields.IntegerField', [], {})\n },\n u'measurementpoints.dataseries': {\n 'Meta': {'ordering': \"[u'role', u'id']\", 'object_name': 'DataSeries'},\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u\"orm['customers.Customer']\", 'null': 'True', 'on_delete': 'models.PROTECT', 'blank': 'True'}),\n 'graph': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['measurementpoints.Graph']\", 'null': 'True', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'role': ('legacy.measurementpoints.fields.DataRoleField', [], {}),\n 'subclass': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"u'+'\", 'on_delete': 'models.PROTECT', 'to': u\"orm['contenttypes.ContentType']\"}),\n 'unit': ('gridplatform.utils.fields.BuckinghamField', [], {'max_length': '100', 'blank': 'True'}),\n 'utility_type': ('django.db.models.fields.IntegerField', [], {})\n },\n u'measurementpoints.graph': {\n 'Meta': {'ordering': \"[u'role', u'id']\", 'unique_together': \"((u'collection', u'role'),)\", 'object_name': 'Graph'},\n 'collection': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Collection']\"}),\n 'hidden': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'role': ('legacy.measurementpoints.fields.DataRoleField', [], {})\n },\n u'providers.provider': {\n 'Meta': {'object_name': 'Provider'},\n 'address': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'city': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'cvr': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'zipcode': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'})\n },\n u'salesopportunities.industrytype': {\n 'Meta': {'ordering': \"[u'name']\", 'object_name': 'IndustryType'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'})\n },\n u'users.user': {\n 'Meta': {'ordering': \"[u'user_type', u'name', u'id']\", 'object_name': 'User', '_ormbases': [u'auth.User']},\n 'customer': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['customers.Customer']\", 'null': 'True', 'blank': 'True'}),\n 'e_mail': ('gridplatform.encryption.fields.EncryptedEmailField', [], {'max_length': '75'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'encryption_key_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'encryption_private_key': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'encryption_public_key': ('gridplatform.encryption.fields.Base64Field', [], {}),\n 'mobile': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '20', 'blank': 'True'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '60'}),\n 'phone': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '20'}),\n 'provider': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['providers.Provider']\", 'null': 'True', 'blank': 'True'}),\n u'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u\"orm['auth.User']\", 'unique': 'True', 'primary_key': 'True'}),\n 'user_type': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'})\n }\n }\n\n complete_apps = ['energy_use_reports']" }, { "alpha_fraction": 0.6649746298789978, "alphanum_fraction": 0.6717427968978882, "avg_line_length": 24.69565200805664, "blob_id": "98b0546f1159e6caec2dc3b0d121a3454d5a58ca", "content_id": "99f01360f250601cbea8e11d02bfeef922dfd6e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "no_license", "max_line_length": 79, "num_lines": 23, "path": "/legacy/energinet_co2/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom appconf import AppConf\n\n__all__ = ['settings', 'EnerginetConf']\n\n\nclass EnerginetConf(AppConf):\n HOST = 'ftp.energinet.dk'\n\n # Whether to automatically create index instances on syncdb, if not already\n # created.\n AUTO_SETUP = True\n # Options used for creating index instances.\n UNIT = 'gram*kilowatt^-1*hour^-1'\n NAME = 'Energinet.dk CO₂'\n TIMEZONE = \"Europe/Copenhagen\"\n\n class Meta:\n required = ['USER', 'PASS']\n" }, { "alpha_fraction": 0.7133296132087708, "alphanum_fraction": 0.7133296132087708, "avg_line_length": 21.412500381469727, "blob_id": "e80d65fd5e30027be05ffb3b0649c25733133eb4", "content_id": "a2e4a0587fe65c4f393f9cf519629595f7a10ed4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1793, "license_type": "no_license", "max_line_length": 85, "num_lines": 80, "path": "/documentation/source/apps/gridplatform/encryption.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Encryption\n==========\n\nTo make sure no customer's confidential data is ever leaked we encrypt all\ntexts written by our users with a key specific to the organization of that\nuser.\n\n\nModels\n------\n\n.. autoclass:: gridplatform.encryption.models.EncryptedModel\n :members: __init__, save, _encrypt, _decrypt, reset_encryption, get_encryption_id,\n clean_fields\n\n.. autoclass:: gridplatform.encryption.models.EncryptionUser\n :members: generate_private_key, update_private_key, grant_key,\n decrypt_private_key, decrypt_keys\n\n.. autoclass:: gridplatform.encryption.models.BaseEncryptionKey\n :members: key_id, generate, share\n\n.. autoclass:: gridplatform.encryption.models.EncryptionKey\n\n.. autofunction:: gridplatform.encryption.models.auto_grant_to_current_user\n\n\nBase\n----\n\n.. automodule:: gridplatform.encryption.base\n :members: _get_cipher_module, get_cipher_module, MissingEncryptionKeyError,\n _CachedKeys, EncryptionContext\n\nCipher\n------\n\n.. automodule:: gridplatform.encryption.cipher\n :members: generate_iv, generate_symmetric_key, hash_symmetric_key,\n symmetric_cipher, generate_private_public_keypair,\n load_private_key, load_public_key, private_key_cipher,\n public_key_cipher\n\nSettings\n--------\n\n.. automodule:: gridplatform.encryption.conf\n\nFields\n------\n\n.. automodule:: gridplatform.encryption.fields\n :members:\n\nFilters\n-------\n\n.. autoclass:: gridplatform.encryption.filters.DecryptingSearchFilter\n\nManagers\n--------\n\n.. automodule:: gridplatform.encryption.managers\n :members:\n\nMiddleware\n----------\n\n.. automodule:: gridplatform.encryption.middleware\n :members:\n\nShell\n-----\n\n.. autoclass:: gridplatform.encryption.shell.Request\n\nSignals\n-------\n\n.. automodule:: gridplatform.encryption.signals\n" }, { "alpha_fraction": 0.7696933150291443, "alphanum_fraction": 0.7733012437820435, "avg_line_length": 35.9555549621582, "blob_id": "62de43c40020c386928e010278e02da920e975a2", "content_id": "c23b6dd7631314b98bf7ebe80802f4b12d2b9fc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 84, "num_lines": 45, "path": "/documentation/source/introduction.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "************\nIntroduction\n************\n\n\nThis is the GridManager ApS final documentation of the GridPlatform. It was\ncompiled in the last months before the final termination of the\nGridManager ApS Research & Development department.\n\n\nDisclaimer\n==========\nThis documentation is intended as a minimalistic form of *hand over*\ndocumentation to help future developers understand the code and the thoughts\nbehind it. The documentation here is basically all we had time to compile\nbefore our time with GridManager ApS was up.\n\n\nTarget audience\n===============\nThe readers of this document are expected to be experienced software developers,\ncomfortable with the following technologies:\n\n- Python programming language\n- Django web framework\n- Celery (used for background tasks for Django)\n- HTML and JavaScript\n- RESTful web services\n- Django REST Framework\n\nPreferably the reader is also experienced within the field of energy\nmanagement, and thus know the terminology used within that field.\n\n\nWhat is documented and what is not\n==================================\nThere are four software components that were developed by GridManager ApS. They are:\nGridPlatform, GridAgent Server, GridPortal 2.0, and Energy Manager.\n\nOnly GridAgent Server and GridPlatform are documented in detail here. The\nGridPortal 2.0 is legacy and no documentation exists apart from what is found\nas code comments in the code itself. However, if a developer with the right\ntechnical skill set reads this documentation then he/she should also be able to\nunderstand the GridPortal 2.0 design and code simply by inspecting it, as both\nare software systems for use in the energy management domain.\n" }, { "alpha_fraction": 0.537431001663208, "alphanum_fraction": 0.5483923554420471, "avg_line_length": 44.61481475830078, "blob_id": "cf3ddd17fd0c75bdc4a51bf6ebc2e37ecc1607b2", "content_id": "51f25e2dd262e7302f649920bf31516cbebcf447", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12318, "license_type": "no_license", "max_line_length": 91, "num_lines": 270, "path": "/legacy/display_projects/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nfrom django.utils.translation import ugettext as _\nfrom django.db.models import Q\n\nfrom celery import shared_task\nfrom celery import Task\n\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.legacy_utils import get_customer_preferred_unit_attribute_name\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.projects.models import BenchmarkProject\n\n\n# Softly kill using exception after 30 minutes. Kill for real after 31 minutes.\n@trackuser_task\n@shared_task(\n time_limit=1860, soft_time_limit=1800,\n name='legacy.display_projects.tasks.ProjectReportTask')\nclass ProjectReportTask(Task):\n def report_progress(self, progress, total):\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': progress,\n 'total': total,\n }\n )\n\n def run(self, data):\n PROGRESS_TOTAL = 6\n project_id = data['project']\n # DB: BenchmarkProject by ID; should be cheap\n project = BenchmarkProject.objects.get(id=project_id)\n self.report_progress(1, PROGRESS_TOTAL)\n consumption_unit_attribute_name = \\\n get_customer_preferred_unit_attribute_name(\n project.customer, DataRoleField.CONSUMPTION,\n project.utility_type)\n consumption_unit_display_attribute_name = \\\n 'get_{consumption_unit_attribute_name}_display'.format(\n consumption_unit_attribute_name=consumption_unit_attribute_name) # noqa\n consumption_unit = getattr(project.customer,\n consumption_unit_attribute_name)\n consumption_unit_display = getattr(\n project.customer, consumption_unit_display_attribute_name)()\n cost_unit = project.customer.currency_unit\n cost_unit_display = project.customer.get_currency_unit_display()\n co2_unit = 'tonne'\n co2_unit_display = unicode(_('CO₂ (ton)'))\n\n # DB: obtaining a bunch of dataseries, calling calculate_development()\n # on them...\n project_savings = {}\n # Call sequences until DB queries:\n # project_consumption_savings -> self.yearly_consumption_savings ->\n # yearly_measured_consumption_savings -> consumption_saving_rate ->\n # baseline_stage.mean_consumption_rate -> ...\n #\n # project_consumption_savings -> self.yearly_consumption_savings ->\n # yearly_measured_consumption_savings -> consumption_saving_rate ->\n # result_stage.mean_consumption_rate ->\n # result_measurement_points.all().all()/subclass_instance/\n # consumption.calculate_development()\n #\n # project_consumption_savings -> self.yearly_consumption_savings ->\n # yearly_additional_consumption_savings ->\n # yearly_additional_consumption -> additionalsaving_set.all()\n project_savings['consumption'] = float(\n project.project_consumption_savings().convert(consumption_unit))\n self.report_progress(2, PROGRESS_TOTAL)\n project_savings['cost'] = \\\n float(project.project_cost_savings().convert(cost_unit))\n self.report_progress(3, PROGRESS_TOTAL)\n project_savings['co2'] = \\\n float(project.project_co2_savings().convert(co2_unit))\n self.report_progress(4, PROGRESS_TOTAL)\n # Just reads fields on the BenchmarkProject instance\n expected = {\n 'consumption': (\n project.expected_savings_in_yearly_consumption_after /\n 12 * project.runtime),\n 'cost': (project.expected_savings_in_yearly_total_costs /\n 12 * project.runtime),\n 'co2': (project.expected_reduction_in_yearly_co2_emissions /\n 12 * project.runtime),\n }\n\n goal_diff = {}\n try:\n goal_diff['consumption_pct'] = (\n (project_savings['consumption'] -\n float(expected['consumption'])) * 100 /\n float(expected['consumption']))\n except:\n goal_diff['consumption_pct'] = None\n\n try:\n goal_diff['cost_pct'] = ((project_savings['cost'] -\n float(expected['cost'])) * 100 /\n float(expected['cost']))\n except:\n goal_diff['cost_pct'] = None\n\n try:\n goal_diff['co2_pct'] = ((project_savings['co2'] -\n float(expected['co2'])) * 100 /\n float(expected['co2']))\n except:\n goal_diff['co2_pct'] = None\n\n # Uses @cached_property for mean_consumption_rate, mean_cost_rate,\n # mean_co2_rate; so avoids new queries for that...\n yearly_stage1 = {\n 'consumption': float((\n (project.baseline_stage.mean_consumption_rate *\n PhysicalQuantity(365, 'day'))).convert(consumption_unit)),\n 'cost': float((\n (project.baseline_stage.mean_cost_rate * PhysicalQuantity(\n 365, 'day'))).convert(cost_unit)),\n 'co2': float(\n (project.baseline_stage.mean_co2_rate * PhysicalQuantity(\n 365, 'day')).convert(co2_unit)),\n }\n yearly_stage2 = {\n 'consumption': float((\n (project.result_stage.mean_consumption_rate * PhysicalQuantity(\n 365, 'day'))).convert(consumption_unit)),\n 'cost': float((\n (project.result_stage.mean_cost_rate * PhysicalQuantity(\n 365, 'day'))).convert(cost_unit)),\n 'co2': float(\n (project.result_stage.mean_co2_rate * PhysicalQuantity(\n 365, 'day')).convert(co2_unit)),\n }\n # NTS: \"yearly\" means \"yearly measured consumption\"; \"total\" means\n # \"yearly measured consumption + additional consumption\" DB: repeats\n # additionalsaving_set.all() query for consumption, cost, co2\n total_stage1 = {\n 'consumption': float(\n (\n (\n project.baseline_stage.mean_consumption_rate *\n PhysicalQuantity(365, 'day')) +\n project.yearly_additional_consumption()['before']).\n convert(consumption_unit)),\n 'cost': float(\n (\n (\n project.baseline_stage.mean_cost_rate *\n PhysicalQuantity(365, 'day')) +\n project.yearly_additional_cost()['before']).\n convert(cost_unit)),\n 'co2': float(\n (\n project.baseline_stage.mean_co2_rate * PhysicalQuantity(\n 365, 'day') +\n project.yearly_additional_co2()['before']).\n convert(co2_unit)),\n }\n # DB: repeats additionalsaving_set.all() query for consumption, cost,\n # co2\n total_stage2 = {\n 'consumption': float(\n (\n (\n project.result_stage.mean_consumption_rate *\n PhysicalQuantity(365, 'day')) +\n project.yearly_additional_consumption()['after']).\n convert(consumption_unit)),\n 'cost': float(\n (\n (\n project.result_stage.mean_cost_rate * PhysicalQuantity(\n 365, 'day')) +\n project.yearly_additional_cost()['after'] +\n project.average_yearly_project_costs()).convert(\n cost_unit)),\n 'co2': float(\n (\n project.result_stage.mean_co2_rate * PhysicalQuantity(\n 365, 'day') +\n project.yearly_additional_co2()['after']).convert(\n co2_unit)),\n }\n self.report_progress(5, PROGRESS_TOTAL)\n measurement_points = []\n # DB: measurementpoints that fulfill one or the other criteria...\n for mp in ConsumptionMeasurementPoint.objects.filter(\n Q(benchmarkproject_baseline_member__id=project.id) |\n Q(benchmarkproject_result_member__id=project.id)).distinct():\n rate_data = None\n if mp.rate is not None:\n rate_data = project.get_graph_data(mp)\n # DB: unsurprisingly, two queries per MP to determine which of the\n # criteria put it in the set to be processed...\n # DB: mp.consumption.get_condensed_samples() for stage1\n # DB: mp.consumption.get_condensed_samples() for stage2\n measurement_points.append(\n {\n 'id': mp.id,\n 'graph_data': rate_data,\n 'consumption_graph_data': (\n project.get_consumption_graph_data(mp)),\n })\n self.report_progress(6, PROGRESS_TOTAL)\n return {\n 'project_id': project.id,\n # NTS: \"estimated\" are fields from BenchmarkProject instance\n 'estimated': {\n 'consumption': project.estimated_yearly_consumption_before,\n 'cost': project.estimated_yearly_consumption_costs_before,\n 'co2': project.estimated_co2_emissions_before,\n },\n 'expected': expected,\n 'goal_diff': goal_diff,\n # DB: additionalsaving_set.all() repeated for each of consumption,\n # consumption_pct, cost, cost_pct, co2, co2_pct\n # DB: ... actually, additionalsaving_set.all() repeated once more\n # for each of the percent-variants...?\n # NTS: yearly_measured_... are eventually based on @cached_property\n # members on the Stage objects\n 'yearly_savings': {\n 'consumption': float(\n project.yearly_consumption_savings().convert(\n consumption_unit)),\n 'consumption_pct': project.yearly_consumption_savings_pct(),\n 'cost': float(project.resulting_annual_cost_savings().convert(\n cost_unit)),\n 'cost_pct': project.resulting_annual_cost_savings_pct(),\n 'co2': float(project.yearly_co2_savings().convert(co2_unit)),\n 'co2_pct': project.yearly_co2_savings_pct(),\n },\n 'unit': {\n 'consumption': consumption_unit_display,\n 'cost': cost_unit_display,\n 'co2': co2_unit_display,\n },\n 'project_savings': project_savings,\n 'yearly_stage1': yearly_stage1,\n 'yearly_stage2': yearly_stage2,\n 'yearly_stage_diff': {\n 'consumption': yearly_stage1['consumption'] -\n yearly_stage2['consumption'],\n 'cost': yearly_stage1['cost'] - yearly_stage2['cost'],\n 'co2': yearly_stage1['co2'] - yearly_stage2['co2'],\n },\n 'total_stage1': total_stage1,\n 'total_stage2': total_stage2,\n 'project_costs_results': {\n # DB: cost_set.all() --- but via @cached_property investment,\n # so only once...\n 'monthly': float(\n project.average_monthly_project_costs().convert(\n cost_unit)),\n 'yearly': float(\n project.average_yearly_project_costs().convert(cost_unit)),\n },\n 'measurement_points': measurement_points,\n 'baseline_tariff_domain_warning_measurement_point_ids':\n project.baseline_stage.tariff_domain_warning_measurement_point_ids, # noqa\n 'result_tariff_domain_warning_measurement_point_ids':\n project.result_stage.tariff_domain_warning_measurement_point_ids, # noqa\n }\n" }, { "alpha_fraction": 0.6934413909912109, "alphanum_fraction": 0.6938098669052124, "avg_line_length": 34.71052551269531, "blob_id": "eb3a6b9af39cff239a76db38b9ca8c100881a880", "content_id": "3dc6d13a9bbbaeec6c764945fed2c16e1f43cbc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2714, "license_type": "no_license", "max_line_length": 78, "num_lines": 76, "path": "/legacy/manage_measurementpoints/forms/temperature.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom legacy.devices.models import Meter\nfrom legacy.measurementpoints.proxies import TemperatureMeasurementPoint\nfrom legacy.measurementpoints.models import Collection\n\nfrom .measurementpointform import MeasurementPointForm\n\nfrom gridplatform.datasequences.models import \\\n NonaccumulationDataSequence\n\n\nclass TemperatureMeasurementPointForm(MeasurementPointForm):\n \"\"\"\n A C{TemperatureMeasurementPointForm} sets properties on a\n L{TemperatureMeasurementPoint} that can be both set when creating and when\n updating.\n \"\"\"\n defines_heating_degree_days = forms.BooleanField(required=False)\n\n class Meta:\n model = TemperatureMeasurementPoint\n fields = ('name', 'parent', 'relay',\n 'hidden_on_details_page', 'hidden_on_reports_page')\n localized_fields = '__all__'\n\n class ProxyMeta:\n fields = ('defines_heating_degree_days',)\n\n def __init__(self, *args, **kwargs):\n super(TemperatureMeasurementPointForm, self).__init__(*args, **kwargs)\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n self.fields['relay'].queryset = \\\n Meter.objects.filter(\n customer=trackuser.get_customer(), relay_enabled=True)\n\n def _get_edit_headline_display(self):\n if self.instance.relative:\n return _(u'Edit Relative Temperature Measurement Point')\n else:\n return _(u'Edit Absolute Temperature Measurement Point')\n\n\nclass InputTemperatureMeasurementPointForm(TemperatureMeasurementPointForm):\n \"\"\"\n An C{InputTemperatureMeasurementPointForm} is a\n L{TemperatureMeasurementPointForm}, that in addition also sets properties\n that can only be set when creating a L{TemperatureMeasurementPoint}.\n \"\"\"\n input_configuration = forms.ModelChoiceField(\n required=True,\n queryset=NonaccumulationDataSequence.objects.none())\n\n class ProxyMeta:\n fields = TemperatureMeasurementPointForm.ProxyMeta.fields + \\\n ('input_configuration', )\n\n def __init__(self, *args, **kwargs):\n super(InputTemperatureMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['input_configuration'].queryset = \\\n TemperatureMeasurementPoint.get_input_configuration_choices()\n\n def _get_new_headline_display(self):\n return _(u'New Temperature Measurement Point')\n" }, { "alpha_fraction": 0.6111456155776978, "alphanum_fraction": 0.6113008260726929, "avg_line_length": 38.6430778503418, "blob_id": "330b09e34d48aaaf28f919aa1e34e95c4f3dd353", "content_id": "71662f0c38759f7867b30c517bc69e7513944028", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12884, "license_type": "no_license", "max_line_length": 79, "num_lines": 325, "path": "/legacy/measurementpoints/proxies/measurementpoint.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import cached_property\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import Link\nfrom legacy.measurementpoints.models import Multiplication\nfrom legacy.measurementpoints.models import Summation\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom legacy.datasequence_adapters.models import ProductionAccumulationAdapter\nfrom legacy.datasequence_adapters.models import NonaccumulationAdapter\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\n\n\nclass MeasurementPoint(Collection):\n \"\"\"\n A C{MeasurementPoint} is a special application of a L{Collection}.\n\n This class is a proxy model of L{Collection}. The idea is to make it easier\n to create and modify measurement point L{Collection}s through relevant\n property methods for retrieving and modifying the entities which, when\n combined, form an actual measurement point.\n \"\"\"\n class Meta:\n proxy = True\n verbose_name = _('Measurement point')\n verbose_name_plural = _('Measurement points')\n app_label = 'customers'\n\n def save(self, *args, **kwargs):\n \"\"\"\n C{MeasurementPoint} override of C{Collection.save()}.\n\n Create a hidden graph related to this C{MeasurementPoint} and add\n hidden data series to it. The idea is that these data series are\n automatically deleted when this C{MeasurementPoint} is.\n \"\"\"\n\n super(MeasurementPoint, self).save(*args, **kwargs)\n\n if self._hidden:\n hidden_graph, created = self.graph_set.get_or_create(\n role=DataRoleField.HIDDEN, hidden=True)\n for ds in self._hidden:\n ds.graph = hidden_graph\n ds.save()\n\n def clean(self):\n super(MeasurementPoint, self).clean()\n # If Gauge widget is present on the Dashboard, verify that\n # that values are not corrupted by the user.\n from legacy.display_widgets.models import DashboardWidget\n widget = DashboardWidget.objects.filter(\n collection=self.id,\n widget_type=DashboardWidget.GAUGE)\n if widget and (self.gauge_lower_threshold is None or\n self.gauge_upper_threshold is None or\n self.gauge_min is None or\n self.gauge_max is None or\n self.gauge_colours is None):\n raise ValidationError(\n _('Gauge widget is present on the dashboard; \\\n corrupting these values are not allowed'))\n else:\n if self.gauge_max is not None and \\\n self.gauge_min is not None and \\\n self.gauge_max <= self.gauge_min:\n raise ValidationError(\n _('Maximum value must be above minumum value'))\n if self.gauge_lower_threshold is not None and \\\n self.gauge_lower_threshold is not None and \\\n self.gauge_lower_threshold < self.gauge_min:\n raise ValidationError(\n _('Lower threshold must be above minumum value'))\n if self.gauge_upper_threshold is not None and \\\n self.gauge_max is not None \\\n and self.gauge_upper_threshold > self.gauge_max:\n raise ValidationError(\n _('Upper threshold must be below maximum value'))\n if self.gauge_upper_threshold is not None and \\\n self.gauge_lower_threshold is not None \\\n and self.gauge_upper_threshold <= \\\n self.gauge_lower_threshold:\n raise ValidationError(\n _('Upper threshold must be above lower threshold'))\n\n def get_verbose_name_display(self):\n return self.subclass_instance._meta.verbose_name\n\n def get_gauge_data_series(self):\n \"\"\"\n This abstract method defines which L{DataSeries} (if any) should be\n displayed in a gauge widget, if any.\n \"\"\"\n return None\n\n def get_input_configurations(self):\n return \\\n list(ConsumptionAccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self)) + \\\n list(ProductionAccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self)) + \\\n list(NonaccumulationAdapter.objects.filter(\n link_derivative_set__graph__collection=self))\n\n def has_gauge(self):\n \"\"\"\n Check if this MeasurementPoint has a gauge that can be displayed.\n\n @return: C{True} if a gauge can be displayed, false otherwise.\n \"\"\"\n\n return self.get_gauge_data_series() is not None and \\\n self.gauge_lower_threshold is not None and \\\n self.gauge_upper_threshold is not None and \\\n self.gauge_min is not None and \\\n self.gauge_max is not None and \\\n self.gauge_colours is not None and \\\n self.gauge_preferred_unit is not None\n\n def has_consumption(self):\n \"\"\"\n Check if this MeasurementPoint has a consumption data_series\n that can be displayed.\n\n @return: C{True} if consumption widget can be displayed, false\n otherwise.\n \"\"\"\n return bool(self.consumption)\n\n def has_rate(self):\n \"\"\"\n Check if this MeasurementPoint has a rate data_series\n that can be displayed.\n\n @return: C{True} if rate widget can be displayed, false\n otherwise.\n \"\"\"\n return bool(self.rate)\n\n def has_cooldown(self):\n \"\"\"\n Check if this MeasurementPoint has a cooldown data_series\n that can be displayed\n\n @return: C{True} if cooldown widgets can be displayed. false\n otherwise\n \"\"\"\n\n return self.graph_set.filter(\n role=DataRoleField.MEAN_COOLDOWN_TEMPERATURE).exists()\n\n def has_widgets(self):\n \"\"\"\n Check if this MeasurementPoint has anything that\n can be displayed as a widget.\n\n @return: C{True} if widgets can be displayed, false otherwise.\n \"\"\"\n return bool(\n self.has_consumption or\n self.has_gauge or self.has_rate or\n self.has_cooldown or self.has_production)\n\n def has_production(self):\n return self.graph_set.filter(\n role=DataRoleField.PRODUCTION).exists()\n\n @cached_property\n def _hidden(self):\n # \"lazy\" initialisation of self._hidden; put here to be close to use in\n # add_hidden and completely remove __init__()\n return []\n\n def add_hidden(self, data_series):\n \"\"\"\n Add a hidden L{DataSeries} to this C{MeasurementPoint}.\n\n The idea is that these data series are automatically deleted when this\n C{MeasurementPoint} is.\n \"\"\"\n self._hidden.append(data_series)\n\n def get_gauge_unit_display(self):\n \"\"\"\n Returns a humam readable gauge preferred unit string.\n Using customers preferred unit for the rate dataseries,\n if gauge preferred unit has not yet been saved.\n \"\"\"\n if self.gauge_preferred_unit:\n return self.get_gauge_preferred_unit_display()\n elif self.rate:\n return self.rate.get_preferred_unit_converter().get_display_unit()\n else:\n return None\n\n def get_delete_prevention_reason(self):\n \"\"\"\n Returns a HTML formated string with a description of why\n this measurement point cannot be deleted.\n Returning None, if no reason exist, meaning the measurement point can\n be deleted without breaking anything.\n \"\"\"\n from legacy.projects.models import BenchmarkProject\n from legacy.energy_use_reports.models import EnergyUseReport\n\n if self.is_deletable():\n return None\n\n dependents = []\n projects = set(BenchmarkProject.objects.filter(\n baseline_measurement_points__id=self.id)) | \\\n set(BenchmarkProject.objects.filter(\n result_measurement_points__id=self.id))\n if projects:\n dependents.append(unicode(_(\"Projects:\")))\n dependents.append('<ul>')\n for project in projects:\n dependents.append('<li>%s</li>' % (escape(unicode(project)),))\n dependents.append('</ul>')\n\n summations = Summation.objects.filter(\n terms__data_series=self.consumption).prefetch_related(\n 'graph__collection').distinct()\n if summations:\n dependents.append(unicode(_(\"Summation Measurement Points:\")))\n dependents.append('<ul>')\n for summation in summations:\n dependents.append(\n '<li>%s</li>' % (\n escape(unicode(summation.graph.collection)), ))\n dependents.append('</ul>')\n\n multiplications = Multiplication.objects.filter(\n source_data_series=self.consumption).prefetch_related(\n 'graph__collection').distinct()\n if multiplications:\n dependents.append(unicode(_(\"Multiplication Measurement Points:\")))\n dependents.append('<ul>')\n for multiplication in multiplications:\n dependents.append(\n '<li>%s</li>' % (\n escape(unicode(multiplication.graph.collection)),))\n dependents.append('</ul>')\n\n links = Link.objects.filter(\n target=self.consumption).prefetch_related(\n 'graph__collection').distinct()\n if links:\n dependents.append(\n unicode(_(\"District Heating Measurement Points:\")))\n dependents.append('<ul>')\n for link in links:\n dependents.append(\n '<li>%s</li>' % (escape(unicode(link.graph.collection)),))\n dependents.append('</ul>')\n\n energy_use_reports = EnergyUseReport.objects.filter(\n energyusearea__measurement_points=self)\n if energy_use_reports:\n dependents.append(unicode(_(\"Energy Use Reports:\")))\n dependents.append('<ul>')\n for report in energy_use_reports:\n dependents.append('<li>%s</li>' % (escape(unicode(report)),))\n dependents.append('</ul>')\n\n constraints = CollectionConstraint.objects.filter(\n collection=self)\n if constraints:\n dependents.append(unicode(_(\"Users:\")))\n dependents.append('<ul>')\n for constraint in constraints:\n dependents.append('<li>%s</li>' % (\n escape(unicode(constraint.userprofile.user)),))\n dependents.append('</ul>')\n\n if dependents:\n return _(\n 'This measurement point cannot be deleted '\n 'because the following depends on it:') + \"<br />\" + \\\n \"\".join(dependents)\n\n def used_in_report(self):\n \"\"\"Checks if this measurementpoint is used in an energy use report\"\"\"\n from legacy.energy_use_reports.models import EnergyUseReport\n energy_use_reports = EnergyUseReport.objects.filter(\n energyusearea__measurement_points=self)\n\n return len(energy_use_reports) > 0\n\n def is_deletable(self):\n \"\"\"\n Returns true or false whether\n this measurement point can be deleted or not.\n \"\"\"\n # Importing inline because\n from legacy.energy_use_reports.models import EnergyUseReport\n\n links = Link.objects.filter(target=self.consumption).count()\n multiplication = Multiplication.objects.filter(\n source_data_series=self.consumption).count()\n from legacy.projects.models import BenchmarkProject\n baselineinclusion = BenchmarkProject.objects.filter(\n baseline_measurement_points__id=self.id).exists()\n resultinclusion = BenchmarkProject.objects.filter(\n result_measurement_points__id=self.id).exists()\n summation = Summation.objects.filter(\n terms__data_series=self.consumption).count()\n energy_use_reports = EnergyUseReport.objects.filter(\n energyusearea__measurement_points=self)\n constraints = CollectionConstraint.objects.filter(\n collection=self).count()\n\n return not any([\n links, multiplication,\n baselineinclusion, resultinclusion,\n summation, energy_use_reports, constraints\n ])\n" }, { "alpha_fraction": 0.6950231194496155, "alphanum_fraction": 0.6961805820465088, "avg_line_length": 25.18181800842285, "blob_id": "3d9619ef96e8780628c39889d84e5276e113bf44", "content_id": "d07af4f26c0d26eefe4dc188073fdcb9f82a88df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1728, "license_type": "no_license", "max_line_length": 75, "num_lines": 66, "path": "/gridplatform/utils/templatetags/utils.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom django import template\nfrom django.utils.safestring import mark_safe\n\nfrom gridplatform.utils import units\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils.decorators import deprecated\n\nregister = template.Library()\n\n\[email protected]\ndef insertnbsp(value):\n \"\"\"\n Inserts four times the given value of non-breakable space and mark\n it safe. Useful for indentation.\n\n :param value: The given value.\n \"\"\"\n try:\n return mark_safe('&nbsp;' * int(value) * 4)\n except TypeError:\n return ''\n\n\[email protected]\ndef jsonify(object):\n \"\"\"\n Dump the given object as JSON and mark it safe.\n\n :param object: The given object.\n \"\"\"\n return mark_safe(json.dumps(object))\n\n\[email protected]\ndef buckingham_display(buckingham_str):\n \"\"\"\n Convert a Buckingham unit to its predefiend human readable\n counterpart.\n\n :warning: Not all valid Buckingham units have a predefined human\n readable counterpart.\n :warning: Some Buckingham units correspond to multiple predefined\n human readable counterpart, some of which may be wrong in the\n given application.\n\n :deprecated: Use specializations of\n :class:`gridplatform.utils.preferredunits.UnitConverter`\n instead. Some units need to be displayed differently\n depending on their application.\n \"\"\"\n try:\n return units.UNIT_DISPLAY_NAMES[buckingham_str]\n except KeyError:\n pass\n try:\n return get_customer().get_production_unit_choices()[buckingham_str]\n except KeyError:\n pass\n return buckingham_str\n" }, { "alpha_fraction": 0.6662383675575256, "alphanum_fraction": 0.6678445339202881, "avg_line_length": 36.05952453613281, "blob_id": "90bc6d3ca7b04d8c5c2a179c6ac84d9958dd500e", "content_id": "a5b138778999db91e144cff5d43f01e074501c1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3113, "license_type": "no_license", "max_line_length": 91, "num_lines": 84, "path": "/gridplatform/token_auth/authentication.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport binascii\n\nfrom django.conf import settings\nfrom rest_framework.authentication import BaseAuthentication\nfrom rest_framework.authentication import get_authorization_header\nfrom rest_framework.exceptions import AuthenticationFailed\n\nfrom gridplatform.encryption import _set_ephemeral_private_key\nfrom gridplatform.trackuser import _set_user\nfrom gridplatform.trackuser import _set_customer\n\nfrom .models import TokenData\nfrom .models import TOKEN_LENGTH\n\n\nclass EncryptionTokenAuthentication(BaseAuthentication):\n \"\"\"\n :class:`rest_framework.authentication.BaseAuthentication` specialization,\n replacing :class:`rest_framework.authentication.TokenAuthentication` using\n :class:`.TokenData`.\n \"\"\"\n\n def authenticate(self, request):\n \"\"\"\n Similar to\n :meth:`rest_framework.authentication.TokenAuthentication.authenticate`\n but with the addition that if the request is not being made using HTTPS\n while settings are not set to ``DEBUG``, the authentication fails.\n \"\"\"\n if not request.is_secure() and not settings.DEBUG:\n return None\n auth = get_authorization_header(request).split()\n if not auth or auth[0].lower() != b'token':\n return None\n if len(auth) == 1:\n raise AuthenticationFailed(\n 'Invalid token header. No credentials provided.')\n elif len(auth) > 2:\n raise AuthenticationFailed(\n 'Invalid token header. '\n 'Token string should not contain spaces.')\n\n return self.authenticate_credentials(auth[1])\n\n def authenticate_credentials(self, key):\n \"\"\"\n Similar to\n :meth:`rest_framework.authentication.TokenAuthentication.authenticate_credentials`,\n except ``key`` isn't really key, rather its a token from which key is\n to be extracted.\n\n Also global encryption context and user tracking is set according to\n the authenticated user if credentials were authentic.\n\n :see: :meth:`.TokenData.lookup_token`.\n \"\"\"\n assert isinstance(key, bytes)\n if len(key) != TOKEN_LENGTH:\n raise AuthenticationFailed('Invalid token')\n try:\n binascii.unhexlify(key)\n except TypeError:\n raise AuthenticationFailed('Invalid token')\n try:\n token_data = TokenData.lookup_token(key)\n except TokenData.DoesNotExist:\n raise AuthenticationFailed('Invalid token')\n user = token_data.user\n if not user.is_active:\n raise AuthenticationFailed('User inactive or deleted')\n password = token_data.decrypt_password(key)\n if not user.check_password(password):\n raise AuthenticationFailed('Invalid token')\n _set_user(user)\n _set_ephemeral_private_key(user.decrypt_private_key(password))\n _set_customer(user.customer)\n return (user, None)\n\n def authenticate_header(self, request):\n return 'Token'\n" }, { "alpha_fraction": 0.5662482380867004, "alphanum_fraction": 0.5774058699607849, "avg_line_length": 25.55555534362793, "blob_id": "13cee357f398443734f0756ceab440c9cd19aa83", "content_id": "4158bbb9894e77a24cc80bb50d55359403c8e463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 717, "license_type": "no_license", "max_line_length": 76, "num_lines": 27, "path": "/gridagentserver/gas-check.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd $(dirname $0)\n\nmaxmemusage=$((300*1024))\npidfile='twistd.pid'\nif [ -a $pidfile ]; then\n pid=`cat $pidfile`\n mem=`ps --pid $pid -o rss --no-headers`\n\n if [ -z $mem ]; then\n echo 'GridAgent ERROR: GAS was dead. Reviving it now!'\n source $HOME/ve/bin/activate\n ./start.sh\n else\n if [ $pid -gt $maxmemusage ]; then\n echo 'GridAgent ERROR: GAS used too much memory! Restarting it!'\n source $HOME/ve/bin/activate\n ./stop.sh\n ./start.sh\n fi\n fi\nelif [ ! -e $HOME/gas-stopped-intentionally ]; then\n echo 'GridAgent ERROR: GAS was not started. Starting it now!'\n source $HOME/ve/bin/activate\n ./start.sh\nfi\n" }, { "alpha_fraction": 0.6343695521354675, "alphanum_fraction": 0.6383146643638611, "avg_line_length": 29.912195205688477, "blob_id": "2b2ffc4e7ed56d39ed674ff600039b77c45af9ae", "content_id": "7545f1d72b4767811bbc1dcb0828481b7a048692", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6337, "license_type": "no_license", "max_line_length": 78, "num_lines": 205, "path": "/legacy/manage_customers/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\nfrom django.forms import ModelForm, ValidationError\nfrom django.shortcuts import get_object_or_404, redirect\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext as _\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.users.decorators import admin_or_error\nfrom gridplatform.users.managers import hash_username\nfrom gridplatform.users.models import User\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import render_to\n\nfrom legacy.manage_devices.views import agent_list_json\nfrom legacy.manage_devices.views import meter_list_json\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import DataSeries\n\n\n@admin_or_error\n@json_response\ndef customer_list_json(request):\n options = json_list_options(request)\n data = list(Customer.objects.all())\n if options['search']:\n data = filter(\n lambda customer:\n customer.satisfies_search(options['search']),\n data)\n order_map = {\n 'name': lambda customer: customer.name_plain.lower()\n if customer.name_plain else _('Encrypted'),\n }\n if options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_customers/customer_block.html', {'customer': customer},\n RequestContext(request))\n for customer in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass CustomerProfileForm(ModelForm):\n def __init__(self, *args, **kwargs):\n defaults = {\n 'auto_id': False\n }\n defaults.update(kwargs)\n super(CustomerProfileForm, self).__init__(*args, **defaults)\n\n base_tariff_queryset = DataSeries.objects.filter(\n Q(customer=self.instance) | Q(customer__isnull=True))\n\n self.fields['electricity_tariff'].queryset = \\\n base_tariff_queryset.filter(role=DataRoleField.ELECTRICITY_TARIFF)\n self.fields['gas_tariff'].queryset = \\\n base_tariff_queryset.filter(role=DataRoleField.GAS_TARIFF)\n self.fields['water_tariff'].queryset = \\\n base_tariff_queryset.filter(role=DataRoleField.WATER_TARIFF)\n self.fields['heat_tariff'].queryset = \\\n base_tariff_queryset.filter(role=DataRoleField.HEAT_TARIFF)\n self.fields['oil_tariff'].queryset = \\\n base_tariff_queryset.filter(role=DataRoleField.OIL_TARIFF)\n\n class Meta:\n model = Customer\n localized_fields = '__all__'\n\n\nclass UserForm(ModelForm):\n def __init__(self, *args, **kwargs):\n defaults = {\n 'auto_id': False\n }\n defaults.update(kwargs)\n super(UserForm, self).__init__(*args, **defaults)\n\n class Meta:\n model = User\n fields = ('e_mail', 'phone', 'mobile', 'name')\n localized_fields = '__all__'\n\n def clean_username(self):\n username = self.cleaned_data['username']\n if User.objects.filter(username=hash_username(username)).exists():\n raise ValidationError(_('The username already exists'))\n return username\n\n\n@admin_or_error\n@render_to('manage_customers/customerprofile_edit_form.html')\ndef customer_form(request, pk=None):\n if pk:\n customer = get_object_or_404(Customer, pk=pk)\n instance = customer\n else:\n instance = None\n customer = None\n\n form = CustomerProfileForm(instance=instance, auto_id=False)\n return {\n 'form': form,\n 'object': instance,\n 'customerprofile': instance,\n 'customer': customer,\n }\n\n\n@admin_or_error\n@json_response\ndef customer_update(request, pk=None):\n if pk:\n customer = get_object_or_404(Customer, pk=pk)\n instance = customer\n else:\n instance = None\n customer = None\n\n form = CustomerProfileForm(request.POST, instance=instance, auto_id=False)\n if form.is_valid():\n customer = form.save()\n return {\n 'success': True,\n 'statusText': _('The customer has been saved'),\n 'html': render_to_string(\n 'manage_customers/customer_block.html',\n {'customer': customer},\n RequestContext(request)\n ),\n }\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_customers/customerprofile_edit_form.html',\n {\n 'form': form,\n 'object': instance,\n 'customerprofile': instance,\n 'customer': customer\n },\n RequestContext(request)\n ),\n }\n\n\n@admin_or_error\n@render_to('manage_customers/customer_agent_list.html')\ndef customer_agent_list(request, customer):\n customer = get_object_or_404(Customer, pk=customer)\n return {\n 'customer': customer,\n }\n\n\n@admin_or_error\n@json_response\ndef customer_agent_list_json(request, customer):\n customer = get_object_or_404(Customer, pk=customer)\n return agent_list_json(request, customer)\n\n\n@admin_or_error\n@render_to('manage_customers/customer_meter_list.html')\ndef customer_meter_list(request, customer):\n customer = get_object_or_404(Customer, pk=customer)\n return {\n 'customer': customer,\n }\n\n\n@admin_or_error\n@json_response\ndef customer_meter_list_json(request, customer):\n customer = get_object_or_404(Customer, pk=customer)\n return meter_list_json(request, customer)\n\n\n@admin_or_error\ndef as_customer(request, pk):\n # sanity check\n customer = get_object_or_404(Customer, pk=pk)\n request.session['customer_id'] = customer.id\n return redirect(settings.LOGIN_REDIRECT_URL)\n\n\n@admin_or_error\ndef as_admin(request):\n request.session['customer_id'] = None\n return redirect(settings.LOGIN_REDIRECT_URL)\n" }, { "alpha_fraction": 0.6168490648269653, "alphanum_fraction": 0.6182286143302917, "avg_line_length": 39.57089614868164, "blob_id": "14b337dbd8a1d0ce69f5aa5ecc62239b601cffab", "content_id": "471d3442438459106a74084f795be18226a10eb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21746, "license_type": "no_license", "max_line_length": 83, "num_lines": 536, "path": "/gridplatform/encryption/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport base64\nimport binascii\nimport warnings\n\nfrom django.contrib.contenttypes import generic\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core import validators\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.dispatch import receiver\n\nfrom gridplatform.trackuser import get_user\n\nfrom . import fields\nfrom . import get_encryption_context\nfrom .conf import settings\nfrom .managers import DecryptingManager\nfrom .signals import encryption_key_created\nfrom .base import get_cipher_module\n\n\nclass EncryptedModel(models.Model):\n \"\"\"\n The :class:`.EncryptedModel` is a :class:`.Model` class that allows for\n some of its fields to be encrypted; that is, if they subclass\n :class:`.EncryptedField`. Normal fields can be used together with\n encrypted fields. These will never be encrypted though, and will otherwise\n work as they do on normal :class:`Models<.Model>`.\n\n Any :class:`.EncryptedField`, ``field``, will appear as multiple member\n variables on the :class:`.EncryptedModel` ``model``: ``model.field`` and\n ``model.field_plain``. ``model.field`` holds the encrypted field value if\n available and ``model.field_plain`` holds the decrypted field value if\n available. See :class:`.EncryptedField` for the details.\n\n :class:`.EncryptedModel` works well with :class:`Forms<.Form>`.\n\n An `EncryptedModel` can be decrypted using the\n :meth:`.EncryptedModel._decrypt` method and encrypted using the\n :meth:`.EncryptedModel._encrypt()` method. This happens automatically upon\n loading from the data base and on saving, given an encryption context is\n available.\n\n Setting a decrypted field will clear the corresponding encrypted field and\n vice versa.\n\n :ivar encryption_data_initialization_vector: An encryption data\n initialization vector. This is generated by the\n :meth:`.EncryptionContext.generate_iv`, and used to construct the\n cipher (see :meth:`.EncryptionContext.get_cipher`).\n\n :cvar objects: The default manager for :class:`.EncryptedModel` is\n :class:`.DecryptingManager`.\n \"\"\"\n\n encryption_data_initialization_vector = fields.Base64Field(editable=False)\n\n objects = DecryptingManager()\n\n class Meta:\n abstract = True\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Construct a new :class:`.EncryptedModel` such that encrypted fields,\n ``field``, may have their plain text members instantiated through\n ``field_plain`` keyword arguments.\n \"\"\"\n encrypted_fields = [\n f for f in self._meta.fields\n if isinstance(f, fields.EncryptedField)\n ]\n plain = {}\n for field in encrypted_fields:\n plain_name = field._plain_property\n if plain_name in kwargs:\n plain[plain_name] = kwargs.pop(plain_name)\n\n super(EncryptedModel, self).__init__(*args, **kwargs)\n if not self.pk:\n # New object...\n for field in encrypted_fields:\n val = getattr(self, field._ciphertext_attribute)\n if val != '':\n warnings.warn(\n 'Ciphertext value provided for field \\'{}\\' on new '\n '(no-pk) {} object -- error in unit test?'.format(\n field.name, self.__class__.__name__),\n stacklevel=2)\n warnings.warn(\n 'Ciphertext value provided for field \\'{}\\' on new '\n '(no-pk) {} object -- error in unit test?.'.format(\n field.name, self.__class__.__name__),\n stacklevel=3)\n # NOTE: setting plaintext anyway --- plaintext for blank allows\n # create-forms to omit the field without weird SQL errors; the\n # other case is a workaround for models that are \"sometimes\n # encrypted\" and for unit tests that intend to use an identity\n # cipher but initialise the ciphertext member...\n setattr(self, field._plaintext_attribute, val)\n elif get_encryption_context() is not None:\n self._decrypt(get_encryption_context())\n for plain_name, plain_value in plain.iteritems():\n setattr(self, plain_name, plain_value)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Lazily encrypt self and then delegate save to parent model\n \"\"\"\n encrypted_fields = [\n f for f in self._meta.fields\n if isinstance(f, fields.EncryptedField)\n ]\n if any([getattr(self, f._plain_property) is not None and\n getattr(self, f._cipher_property) is None\n for f in encrypted_fields]):\n self._encrypt(get_encryption_context())\n super(EncryptedModel, self).save(*args, **kwargs)\n\n def __repr__(self):\n # NOTE: EncryptedModels are very likely to include encrypted fields in\n # their unicode, which leads to a crash when inspected via repr from\n # shell.\n return '<%s(id=%s)>' % (self.__class__.__name__, self.id)\n\n def __reduce__(self):\n \"\"\"\n Sanity check for pickling --- disallow/fail if encrypted data present.\n \"\"\"\n encrypted_fields = [\n f for f in self._meta.fields\n if isinstance(f, fields.EncryptedField)\n ]\n if any([getattr(self, f._plain_property) for f in encrypted_fields]):\n raise ValueError(b'Pickling disallowed for decrypted objects.')\n return super(EncryptedModel, self).__reduce__()\n\n def _encrypt(self, encryption_context):\n \"\"\"\n Encrypt data for :class:`.EncryptedField` fields of this instance.\n\n :param encryption_context: The :class:`.EncryptionContext` to use for\n encryption.\n \"\"\"\n if encryption_context is None:\n if settings.ENCRYPTION_TESTMODE:\n warnings.warn(\n 'Cannot encrypt; missing encryption context.',\n stacklevel=3)\n return\n raise ValueError('Cannot encrypt; missing encryption context.')\n\n key_id = self.get_encryption_id()\n assert key_id is not None\n model, pk = key_id\n assert pk is not None, \\\n '{}.get_encryption_id() must return (modelclass, integer), ' \\\n 'returned {}'.format(self.__class__, repr(key_id))\n\n iv = encryption_context.generate_iv()\n self.encryption_data_initialization_vector = bytearray(iv)\n cipher = encryption_context.get_cipher(key_id, iv)\n\n encrypted_fields = [\n f for f in self._meta.fields\n if isinstance(f, fields.EncryptedField)\n ]\n for field in encrypted_fields:\n plaintext = getattr(self, field._plaintext_attribute)\n if plaintext is None:\n raise AttributeError(\n 'Missing data for encryption: No plaintext data in '\n '\\'{}\\''.format(field._plaintext_attribute))\n ciphertext = cipher.encrypt(plaintext.encode('utf-8'))\n encoded = base64.encodestring(ciphertext)\n setattr(self, field._ciphertext_attribute, encoded)\n\n def _decrypt(self, encryption_context):\n \"\"\"\n Decrypt data for :class:`.EncryptedField` fields on this instance.\n\n :param encryption_context: The :class:`.EncryptionContext` to use for\n encryption.\n \"\"\"\n if encryption_context is None:\n if not get_user() is None:\n warnings.warn(\n 'Cannot decrypt; missing encryption context.',\n stacklevel=3)\n return\n key_id = self.get_encryption_id()\n if key_id is None:\n warnings.warn(\n 'Cannot decrypt; object missing encryption ID.',\n stacklevel=3)\n return\n iv = str(self.encryption_data_initialization_vector)\n if not iv:\n iv = '\\0' * 16\n cipher = encryption_context.get_cipher(key_id, iv)\n\n encrypted_fields = [\n f for f in self._meta.fields\n if isinstance(f, fields.EncryptedField)\n ]\n try:\n for field in encrypted_fields:\n encoded = getattr(self, field._ciphertext_attribute)\n if encoded is None:\n raise AttributeError('Missing data for decryption')\n try:\n ciphertext = base64.decodestring(encoded)\n except (UnicodeEncodeError, binascii.Error):\n warnings.warn(\n 'Ciphertext was invalid base64 -- '\n 'using ciphertext as plaintext ({}).'.format(\n self.__class__.__name__))\n plaintext = encoded\n else:\n plaintext_bytes = cipher.decrypt(ciphertext)\n plaintext = plaintext_bytes.decode('utf-8')\n setattr(self, field._plaintext_attribute, plaintext)\n except UnicodeDecodeError:\n warnings.warn(\n 'Output from decryption was invalid utf-8 -- '\n 'wrong cipher/error in unit test ({})?'.format(\n self.__class__.__name__))\n for field in encrypted_fields:\n self._plaintext_attribute = None\n\n def reset_encryption(self):\n \"\"\"\n Reinitializes ``self.encryption_data_initialization_vector`` and clears all\n encrypted fields.\n \"\"\"\n self.encryption_data_initialization_vector = \\\n get_cipher_module().generate_iv()\n for field in self._meta.fields:\n attname, column = field.get_attname_column()\n plain_name = '_{}_plain'.format(column)\n if hasattr(self, plain_name):\n setattr(self, attname, '')\n setattr(self, plain_name, '')\n\n def get_encryption_id(self):\n \"\"\"\n Return identity of the encryption key used to\n :meth:`.EncryptedModel._encrypt` and :meth:`.EncryptedModel._decrypt`\n this instance. Subclasses should implement this method.\n\n By convention the encryption key identity (encryption id) is a\n tuple of the owning EncryptionModel specialization and the\n primary key of the owner, for example::\n\n return (Customer, self.customer_id)\n\n We have this convention because:\n\n - we don't want to force loading of the concrete objects\n from the DB (the encryption \"owner\" ID can often be read\n from the foreign key of the object to be\n encrypted/decrypted)\n\n - we *do* want to ensure that only objects with an ID\n assigned can be used, we don't want to involve object\n state apart from identity; hence this pair rather than the\n concrete model objects with that class and ID.\n\n :return: Returns identity of encryption key, e.g.::\n return (OwnerModelClass, owner_id)\n\n :raise NotImplementedError: This exception is raised when a subclass\n failed to reimplement this method.\n \"\"\"\n raise NotImplementedError(\"Subclasses must implement this method\")\n\n def clean_fields(self, exclude=None):\n \"\"\"\n Cleans all fields and raises a :class:`.ValidationError` containing\n message_dict of all validation errors if any occur.\n\n Overridden for :class:`.EncryptedField` support.\n \"\"\"\n if exclude is None:\n exclude = []\n\n errors = {}\n for f in self._meta.fields:\n if f.name in exclude:\n continue\n # difference from base: using f._plain_property for EncryptedField;\n # rather than f.attname always\n if isinstance(f, fields.EncryptedField):\n attname = f._plain_property\n else:\n attname = f.attname\n # Skip validation for empty fields with blank=True. The developer\n # is responsible for making sure they have a valid value.\n raw_value = getattr(self, attname)\n if f.blank and raw_value in validators.EMPTY_VALUES:\n continue\n try:\n setattr(self, attname, f.clean(raw_value, self))\n except ValidationError, e:\n errors[f.name] = e.messages\n\n if errors:\n raise ValidationError(errors)\n\n\nclass EncryptionUser(models.Model):\n \"\"\"\n Mixes encryption user fields and methods into a user model.\n\n :ivar encryption_public_key: Public key for encrypting stuff that the mixed\n user may read.\n :ivar encryption_private_key: Private key for decrypting stuff that the\n mixed user may read (this is of course an encrypted version of the private\n key).\n :ivar encryption_key_initialization_vector: The encryption key\n initialization vector used to encrypt ``self.encryption_private_key``.\n \"\"\"\n encryption_public_key = fields.Base64Field()\n encryption_private_key = fields.Base64Field()\n encryption_key_initialization_vector = fields.Base64Field()\n\n class Meta:\n abstract = True\n\n def generate_private_key(self, password, save=False):\n \"\"\"\n Construct the private key for the user.\n \"\"\"\n cipher_module = get_cipher_module()\n # generate new private/public keypair\n private_key, public_key = \\\n cipher_module.generate_private_public_keypair()\n # set up for encryption of the private key:\n # get initialisation vector\n iv = cipher_module.generate_iv()\n # hash password to fixed length for AES key\n password_hash = cipher_module.hash_symmetric_key(password)\n # initialise cipher and encrypt the private key\n cipher = cipher_module.symmetric_cipher(password_hash, iv)\n private_key_ciphertext = cipher.encrypt(private_key)\n # store initialisation vector, public key and encrypted private key\n self.encryption_key_initialization_vector = bytearray(iv)\n self.encryption_public_key = bytearray(public_key)\n self.encryption_private_key = bytearray(private_key_ciphertext)\n if save:\n self.save()\n\n def update_private_key(self, old_password, new_password, save=False):\n \"\"\"\n Update the encryption of a users private key, from using the old to the\n new password.\n \"\"\"\n cipher_module = get_cipher_module()\n # read current initialisation vector and encrypted private key\n old_iv = str(self.encryption_key_initialization_vector)\n old_ciphertext = str(self.encryption_private_key)\n # hash old password to fixed length for AES key\n old_password_hash = cipher_module.hash_symmetric_key(old_password)\n # make cipher to decrypt currently stored private key, decrypt it\n decrypt_cipher = \\\n cipher_module.symmetric_cipher(old_password_hash, old_iv)\n plaintext = decrypt_cipher.decrypt(old_ciphertext)\n # NOTE: try to import the key as a sanity check only;\n cipher_module.load_private_key(plaintext)\n # now, we will reencrypt with a key based on the new password\n # generate new initialisation vector\n iv = cipher_module.generate_iv()\n # hash new password to fixed length for AES key\n new_password_hash = cipher_module.hash_symmetric_key(new_password)\n # make new cipher to encrypt private, encrypt it\n cipher = cipher_module.symmetric_cipher(new_password_hash, iv)\n ciphertext = cipher.encrypt(plaintext)\n # store new initialisation vector, reencrypted private key\n self.encryption_key_initialization_vector = bytearray(iv)\n self.encryption_private_key = bytearray(ciphertext)\n if save:\n self.save()\n\n def grant_key(self, key_id, plaintext):\n \"\"\"\n Grant someone elses private key to this user.\n\n :param key_id: The identity (encryption id) of the owner of the private\n key.\n :param plaintext: The private key in plaintext.\n\n The given private key will be stored encrypted in\n ``self.encryptionkey_set``. The encryption will happen using this\n users public key.\n \"\"\"\n cipher_module = get_cipher_module()\n public_key = cipher_module.load_public_key(\n str(self.encryption_public_key))\n # Initialize cipher based on users public key, encrypt the secret.\n # This is the only place we use private/public keys --- for exactly\n # this use; being able to give secret data to another user without\n # knowing their private decryption code...\n cipher = cipher_module.public_key_cipher(public_key)\n ciphertext = cipher.encrypt(plaintext)\n model_class, object_id = key_id\n content_type = ContentType.objects.get_for_model(model_class)\n # Only create key if key with same ID does not already exist for user.\n self.encryptionkey_set.get_or_create(\n content_type=content_type, object_id=object_id,\n defaults={'key': bytearray(ciphertext)})\n\n def decrypt_private_key(self, password):\n \"\"\"\n Decrypt private key for user logging in.\n \"\"\"\n cipher_module = get_cipher_module()\n # read initialisation vector\n iv = str(self.encryption_key_initialization_vector)\n # hash password to fixed length for AES key\n password_hash = cipher_module.hash_symmetric_key(password)\n # initialise cipher to decrypt private key\n cipher = cipher_module.symmetric_cipher(password_hash, iv)\n # read private key, decrypt it and initialise RSA key...\n ciphertext = str(self.encryption_private_key)\n return cipher.decrypt(ciphertext)\n\n def decrypt_keys(self, private_key):\n \"\"\"\n Decrypt encryption keys for the current user and set them as attribute\n 'encryption_context' on the request.\n \"\"\"\n cipher_module = get_cipher_module()\n # initialise new/other cipher with the RSA key\n rsa_key = cipher_module.load_private_key(private_key)\n cipher = cipher_module.private_key_cipher(rsa_key)\n # decrypt all of the per-customer/per-? keys accessible to this user,\n # using the cipher with the RSA key\n encryption_context = {\n elem.key_id(): cipher.decrypt(str(elem.key))\n for elem in self.encryptionkey_set.all()\n }\n return encryption_context\n\n\nclass BaseEncryptionKey(models.Model):\n \"\"\"\n Abstract base model for storing private keys shared with a trusted entity\n by a foreign entity.\n\n :ivar key: The private key of the foreign entity, encrypted using the\n public key of the trusted entity.\n :ivar content_type: The\n :class:`django.contrib.contenttypes.models.ContentType` of the foreign\n entity.\n :ivar object_id: The primary key of the foreign entity.\n :ivar content_object: A :class:`.GenericForeignKey` to the foreign entity\n whose private key is being held.\n \"\"\"\n key = fields.Base64Field()\n content_type = models.ForeignKey(\n 'contenttypes.ContentType', on_delete=models.PROTECT)\n object_id = models.PositiveIntegerField()\n content_object = generic.GenericForeignKey('content_type', 'object_id')\n\n class Meta:\n abstract = True\n\n def key_id(self):\n \"\"\"\n :return: The encryption ID of the foreign entity.\n \"\"\"\n content_type = ContentType.objects.get_for_id(self.content_type_id)\n return (content_type.model_class(), self.object_id)\n\n @classmethod\n def generate(cls, key_id):\n \"\"\"\n Generate a new encryption key, and grant access to the current\n logged-in user.\n \"\"\"\n if settings.ENCRYPTION_TESTMODE:\n return\n\n model_class, object_id = key_id\n key = get_cipher_module().generate_symmetric_key()\n\n encryption_key_created.send(sender=model_class, key=key, key_id=key_id)\n\n @classmethod\n def share(cls, key_id, user):\n \"\"\"\n Grant a user access to an element from an encryption context. This may\n be used to share access available to the current user with another\n user.\n \"\"\"\n if settings.ENCRYPTION_TESTMODE:\n return\n\n encryption_context = get_encryption_context()\n key = encryption_context.keys[key_id]\n user.grant_key(key_id, key)\n\n\nclass EncryptionKey(BaseEncryptionKey):\n \"\"\"\n :class:`.BaseEncryptionKey` specialization where the trusted entity is a\n :class:`auth.User`.\n\n :ivar user: The user that is the trusted entity.\n \"\"\"\n user = models.ForeignKey('auth.User', on_delete=models.CASCADE)\n\n\n@receiver(encryption_key_created)\ndef auto_grant_to_current_user(sender, key, key_id, **kwargs):\n \"\"\"\n Grant any created encryption keys to the current active user when the key\n was/is created.\n \"\"\"\n user = get_user()\n encryption_context = get_encryption_context()\n if user is None:\n warnings.warn('No \"current user\"; will not grant key')\n else:\n user.grant_key(key_id, key)\n if encryption_context is None:\n warnings.warn('No \"current encryption context\"; cannot add key')\n elif key_id in encryption_context.keys:\n raise ValueError(\n 'Key with given ID already exists in encryption context')\n else:\n encryption_context.keys[key_id] = key\n" }, { "alpha_fraction": 0.6170905828475952, "alphanum_fraction": 0.6181169152259827, "avg_line_length": 34.4588623046875, "blob_id": "bdc1ecc945afc2a244fc7d233473fbc61c7bde8b", "content_id": "edc4231b936e9c63cb062b837a50b8ea89ae3354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 22410, "license_type": "no_license", "max_line_length": 101, "num_lines": 632, "path": "/gridplatform/bootstrap/templatetags/bootstrap_tags.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport collections\nimport os.path\n\nfrom django import template\nfrom django.forms import ModelMultipleChoiceField\nfrom django.forms.fields import FileField\nfrom django.forms.widgets import CheckboxInput\nfrom django.forms.widgets import TextInput\nfrom django.template.base import Node\nfrom django.template.base import NodeList\nfrom django.template.base import TemplateSyntaxError\nfrom django.template.base import parse_bits\nfrom django.template.defaulttags import CsrfTokenNode\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext\nfrom django.utils.translation import ugettext_lazy\n\nfrom ..conf import settings\n\n\nregister = template.Library()\n\n\nUNSET_OPTION = object()\n\n\ndef parse_token_arguments(parser, token, mandatory, optional):\n \"\"\"\n Parse arguments/keyword arguments to template tag. ``mandatory`` and\n ``optional`` specify names of mandatory and optional arguments. Output is\n a dictionary whose values must resolved at render-time.\n \"\"\"\n # The (internal) Django parse_bits() function is designed for use with the\n # Django function-to-tag-wrappers; the parameters params, varargs, varkw,\n # defaults are on the form returned by inspect.getargspec(), and the output\n # are args, kwargs to be resolved and used to call the fuction on\n # render-time. Getting separate args and kwargs values as a result is\n # somewhat inconvenient unless we actually have a function that will\n # combine the argument appropriately when called with *args, **kwargs ---\n # so here, we combine them into the \"kwargs\" dictionary instead.\n bits = token.split_contents()\n tag_name = bits[0]\n params = mandatory + optional\n # parse_bits uses defaults only to determine the number of optional\n # arguments (to raise TemplateSyntaxError on missing positional arguments);\n # the actual values are not used.\n defaults = optional\n # takes_context=True would check that the first argument was named\n # \"context\" and skip it; for it to be handled in other code at render time.\n args, kwargs = parse_bits(\n parser, bits[1:], params=params,\n varargs=None, varkw=None, defaults=defaults,\n takes_context=False, name=tag_name)\n # We trust parse_bits to raise TemplateSyntaxError on conflicts between\n # args and kwargs; so just add positional arguments as appropriate to the\n # kwargs dictionary.\n for key, value in zip(params, args):\n kwargs[key] = value\n return tag_name, kwargs\n\n\nclass BootstrapNode(Node):\n \"\"\"\n A base node for other bootstrap nodes defined in this module.\n \"\"\"\n template_basename = None\n default_options = {}\n\n def __init__(self, tag_name, options):\n self.tag_name = tag_name\n self.options = options\n\n def __repr__(self):\n return '<{}>'.format(self.__class__.__name__)\n\n def get_templates(self):\n \"\"\"\n :return: List of templates to use, based on ``self.template_basename`` and\n :data:`settings.BOOTSTRAP_THEME`. Defaults to 'base' theme if\n ``self.template_basename`` could not be resolved using the\n :data:`settings.BOOTSTRAP_THEME` theme.\n \"\"\"\n return [\n 'bootstrap/{}/{}'.format(\n settings.BOOTSTRAP_THEME, self.template_basename),\n 'bootstrap/base/{}'.format(self.template_basename),\n ]\n\n def get_default_options(self, context):\n # NOTE: This returns a new dictionary on each call; so users are free\n # to modify it...\n options = {\n 'request': context.get('request', None),\n 'view': context.get('view', None),\n 'object': context.get('object', None),\n }\n options.update(self.default_options)\n return options\n\n def resolve_options(self, context):\n # Start with copy of default/outer tag options.\n options = self.get_default_options(context)\n for key, value in self.options.items():\n resolved = value.resolve(context, ignore_failures=True)\n if resolved is not None:\n options[key] = resolved\n return options\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n return render_to_string(templates, options)\n\n\nICON_NAMES_FILE = 'font-awesome-icon-names.txt'\nwith open(os.path.join(os.path.dirname(__file__), ICON_NAMES_FILE), 'r') as f:\n ICON_NAMES = {l.strip() for l in f}\nICON_SIZES = ('', 'lg', '2x', '3x', '4x', '5x', 'fw')\n\n\nclass IconNode(BootstrapNode):\n template_basename = 'icon.html'\n default_options = {'size': '', 'spin': False}\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n name = options['name']\n size = options['size']\n if name not in ICON_NAMES:\n raise TemplateSyntaxError(\n 'Not a valid icon name: {}; valid are {}'.format(\n name, ICON_NAMES))\n if size not in ICON_SIZES:\n raise TemplateSyntaxError(\n 'Not a valid icon size: {}; valid are {}'.format(\n size, ICON_SIZES))\n return render_to_string(templates, options)\n\n\[email protected](name='icon')\ndef do_icon(parser, token):\n \"\"\"\n Insert a Font Awesome icon; specifying name and optional size. Reduces the\n boilerplate to insert an icon and includes sanity checks to catch\n misspelled icon names.\n\n Usage::\n\n {% icon name [size=\"lg\"|\"2x\"|\"3x\"|\"4x\"|\"5x\"|\"fw\"] [spin=False] %}\n\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['name'], ['size', 'spin'])\n return IconNode(tag_name, options)\n\n\[email protected]()\ndef checkbox_icon_name(value):\n \"\"\"\n Filter for extracting icon name given a boolean value for check box icons.\n\n Usage::\n\n {% icon value|checkbox_icon_name [size=\"lg\"|\"2x\"|\"3x\"|\"4x\"|\"5x\"|\"fw\"] [spin=False] %} # noqa\n \"\"\"\n if value:\n return 'check-square-o'\n else:\n return 'square-o'\n\n\nclass PanelNode(BootstrapNode):\n template_basename = 'panel.html'\n\n def __init__(self, tag_name, options, buttons, body):\n super(PanelNode, self).__init__(tag_name, options)\n self.buttons = buttons\n self.body = body\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n options['buttons'] = self.buttons.render(context)\n options['body'] = self.body.render(context)\n return render_to_string(templates, options)\n\n\[email protected](name='panel')\ndef do_panel(parser, token):\n \"\"\"\n Usage::\n\n {% panel title %}\n [ buttons ... {% endpanelbuttons %}]\n [ body contents... ]\n {% endpanel %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['title'], ['search'])\n buttons_or_body = parser.parse(('endpanelbuttons', 'endpanel'))\n token = parser.next_token()\n if token.contents == 'endpanelbuttons':\n buttons = buttons_or_body\n body = parser.parse(('endpanel',))\n token = parser.next_token()\n else:\n buttons = NodeList()\n body = buttons_or_body\n assert token.contents == 'endpanel'\n return PanelNode(tag_name, options, buttons, body)\n\n\nLAYOUT_OPTION_NAMES = [\n 'layout', 'label_columns', 'input_columns',\n 'label_class', 'input_class', 'checkbox_class',\n]\nFORM_OPTION_NAMES = [\n 'form_action', 'form_method',\n]\nLAYOUT_NAMES = [\"horizontal\", \"inline\", \"basic\"]\n\nFORM_BUTTON_OPTION_NAMES = [\n 'submit_label',\n 'delete_label',\n 'cancel_label',\n 'cancel_target',\n 'delete_target',\n]\n\n\nclass FormNodeBase(BootstrapNode):\n def get_default_options(self, context):\n if '_bootstrap_form_options' not in context:\n raise TemplateSyntaxError(\n '{{% {} %}} only valid inside {{% bootstrap_form %}}'.format(\n self.tag_name))\n options = super(FormNodeBase, self).get_default_options(context)\n options.update(context['_bootstrap_form_options'])\n return options\n\n\nclass FieldInputNode(FormNodeBase):\n template_basename = 'field_input.html'\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n field = options['field']\n input_css_classes = options['input_class'].split()\n # decorate with field class name\n input_css_classes.append(\n field.field.__class__.__name__.lower())\n # decorate with widget class name\n input_css_classes.append(\n field.field.widget.__class__.__name__.lower())\n if not isinstance(field.field.widget, CheckboxInput):\n # If not a checkbox, set form-control class.\n input_css_classes.append('form-control')\n attrs = {\n 'class': ' '.join(input_css_classes),\n }\n if 'placeholder' in options:\n if isinstance(field.field.widget, TextInput):\n # Text field or HTML5-specialisation thereof\n attrs['placeholder'] = options['placeholder']\n else:\n raise TemplateSyntaxError(\n '\\\"placeholder\\\" parameter only valid'\n ' for text field variants')\n if isinstance(field.field, ModelMultipleChoiceField):\n # Avoid adding translation string to this app --- we need to match\n # whatever Django inserted.\n unwanted_base = \\\n 'Hold down \"Control\", or \"Command\" on a Mac, ' + \\\n 'to select more than one.'\n unwanted = ugettext(unwanted_base)\n field.help_text = field.help_text.replace(unwanted, '').strip()\n options['widget'] = field.as_widget(attrs=attrs)\n # NOTE: registering that field has been rendered\n options['touched_fields'].append(field)\n return render_to_string(templates, options)\n\n\[email protected](name='field_input')\ndef do_field_input(parser, token):\n \"\"\"\n Usage::\n\n {% field_input field [layout options...] [placeholder=...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['field'], LAYOUT_OPTION_NAMES + ['placeholder'])\n return FieldInputNode(tag_name, options)\n\n\nclass FieldLabelNode(FormNodeBase):\n template_basename = 'field_label.html'\n\n\[email protected](name='field_label')\ndef do_field_label(parser, token):\n \"\"\"\n Usage::\n\n {% field_label field [layout options...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['field'], LAYOUT_OPTION_NAMES)\n return FieldLabelNode(tag_name, options)\n\n\nclass FieldNode(FormNodeBase):\n template_basename = 'field.html'\n field_label = FieldLabelNode(None, {})\n field_input = FieldInputNode(None, {})\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n field = options['field']\n if field.is_hidden:\n raise TemplateSyntaxError(\n 'Attempting to render hidden field {} as visible'.format(\n field.name))\n # While Bootstrap has special forms for varius checkbox and radiobutton\n # comibinations, and Django also includes widgets for some such\n # combinations, those are not the default widgets on any form/modelform\n # fields.\n options['is_checkbox'] = isinstance(field.field.widget, CheckboxInput)\n context.update({'_bootstrap_form_options': options})\n rendered_field_label = self.field_label.render(context)\n rendered_field_input = self.field_input.render(context)\n context.pop()\n options.update({\n 'rendered_field_label': rendered_field_label,\n 'rendered_field_input': rendered_field_input,\n })\n return render_to_string(templates, options)\n\n\[email protected](name='field')\ndef do_field(parser, token):\n \"\"\"\n Usage::\n\n {% field field [layout options...] [placeholder=...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['field'], LAYOUT_OPTION_NAMES + ['placeholder'])\n return FieldNode(tag_name, options)\n\n\nclass HiddenFieldNode(FormNodeBase):\n template_basename = 'hidden_field.html'\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n field = options['field']\n # NOTE: registering that field has been rendered\n options['touched_fields'].append(field)\n return render_to_string(templates, options)\n\n\[email protected](name='hidden_field')\ndef do_hidden_field(parser, token):\n \"\"\"\n Usage::\n\n {% hidden_field field [layout options...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['field'], LAYOUT_OPTION_NAMES)\n return HiddenFieldNode(tag_name, options)\n\n\nclass NonFieldErrorsNode(FormNodeBase):\n template_basename = 'non_field_errors.html'\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n form = options['form']\n if form in options['non_field_errors_included']:\n raise TemplateSyntaxError(\n 'Non-field errors added multiple times for same form')\n options['non_field_errors_included'].add(form)\n return render_to_string(templates, options)\n\n\[email protected](name='non_field_errors')\ndef do_non_field_errors(parser, token):\n \"\"\"\n Usage::\n\n {% non_field_errors form [layout options...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['form'], LAYOUT_OPTION_NAMES)\n return NonFieldErrorsNode(tag_name, options)\n\n\nclass FormNode(FormNodeBase):\n template_basename = 'form.html'\n non_field_errors = NonFieldErrorsNode(None, {})\n hidden_field = HiddenFieldNode(None, {})\n visible_field = FieldNode(None, {})\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n form = options['form']\n context.update({'_bootstrap_form_options': options})\n # NOTE: FormBaseNode instances take defaults for options from \"parent\"\n # by reading from context['_bootstrap_form_options'] --- this includes\n # the options that are mandatory for the tags constructing them ---\n # thus the NonFieldErrorsNode will automatically use the form specified\n # as an option to the FormNode\n rendered_non_field_errors = self.non_field_errors.render(context)\n # ... slightly more work for the FieldNode instances\n rendered_hidden_fields = []\n for field in form.hidden_fields():\n options['field'] = field\n rendered_hidden_fields.append(self.hidden_field.render(context))\n rendered_visible_fields = []\n for field in form.visible_fields():\n options['field'] = field\n rendered_visible_fields.append(self.visible_field.render(context))\n context.pop()\n options.update({\n 'rendered_non_field_errors': rendered_non_field_errors,\n 'rendered_hidden_fields': rendered_hidden_fields,\n 'rendered_visible_fields': rendered_visible_fields,\n })\n return render_to_string(templates, options)\n\n\[email protected](name='form')\ndef do_form(parser, token):\n \"\"\"\n Usage::\n\n {% form form [layout options...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, ['form'], LAYOUT_OPTION_NAMES)\n return FormNode(tag_name, options)\n\n\nclass FormButtonsNode(FormNodeBase):\n template_basename = 'form_buttons.html'\n default_options = {\n 'submit_label': ugettext_lazy('Save'),\n 'delete_label': ugettext_lazy('Delete'),\n 'cancel_label': ugettext_lazy('Cancel'),\n }\n\n def get_cancel_target(self, resolved_options):\n view = resolved_options['view']\n if hasattr(view, 'get_cancel_url'):\n return view.get_cancel_url()\n return None\n\n def get_delete_target(self, resolved_options):\n view = resolved_options['view']\n if hasattr(view, 'get_delete_url'):\n return view.get_delete_url()\n return None\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n if options['buttons_included']:\n raise TemplateSyntaxError(\n 'Form buttons added multiple times to same form')\n options['buttons_included'].append(self)\n if 'cancel_target' not in options:\n options['cancel_target'] = self.get_cancel_target(options)\n if 'delete_target' not in options:\n options['delete_target'] = self.get_delete_target(options)\n return render_to_string(templates, options)\n\n\[email protected](name='form_buttons')\ndef do_form_buttons(parser, token):\n \"\"\"\n Usage::\n\n {% form_buttons [layout options...] [button options...] %}\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, [], LAYOUT_OPTION_NAMES + FORM_BUTTON_OPTION_NAMES)\n return FormButtonsNode(tag_name, options)\n\n\nclass BootstrapFormNode(BootstrapNode):\n template_basename = 'bootstrap_form.html'\n default_options = {\n 'label_class': '',\n 'input_class': '',\n 'checkbox_class': '',\n 'form_method': 'post',\n }\n\n csrf_token = CsrfTokenNode()\n non_field_errors = NonFieldErrorsNode(None, {})\n form_buttons = FormButtonsNode(None, {})\n\n def __init__(self, tag_name, options, nodelist):\n super(BootstrapFormNode, self).__init__(tag_name, options)\n self.nodelist = nodelist\n\n def get_default_options(self, context):\n if '_bootstrap_form_options' in context:\n raise TemplateSyntaxError(\n '{% {} %} should not be used recursively'.format(\n self.tag_name))\n options = super(BootstrapFormNode, self).get_default_options(context)\n request = context.get('request', None)\n options.update({\n 'layout': settings.BOOTSTRAP_FORM_LAYOUT,\n 'label_columns': settings.BOOTSTRAP_FORM_LABEL_COLUMNS,\n 'input_columns': settings.BOOTSTRAP_FORM_INPUT_COLUMNS,\n 'form_action': getattr(request, 'path', ''),\n 'touched_fields': [],\n 'buttons_included': [],\n 'non_field_errors_included': set(),\n })\n return options\n\n def render(self, context):\n templates = self.get_templates()\n options = self.resolve_options(context)\n context.update({'_bootstrap_form_options': options})\n rendered_csrf_token = self.csrf_token.render(context)\n rendered_content = self.nodelist.render(context)\n if options['buttons_included']:\n rendered_form_buttons = ''\n else:\n rendered_form_buttons = self.form_buttons.render(context)\n context.pop()\n form_enctype = None\n touched_form_fields = collections.defaultdict(list)\n for field in options['touched_fields']:\n touched_form_fields[field.form].append(field.name)\n # If any file fields included, we need to specify enctype...\n if isinstance(field.field, FileField):\n form_enctype = \"multipart/form-data\"\n for form, fields in touched_form_fields.items():\n # Sanity check: Any field included more than once for the same\n # form?\n for fieldname, count in collections.Counter(fields).items():\n if count > 1:\n raise TemplateSyntaxError(\n 'Field {} added {} times '\n 'for a form of class {}'.format(\n fieldname, count, form.__class__.__name__))\n # Sanity check: Any field present on form but *not* included in\n # template?\n missing = set(form.fields.keys()) - set(fields)\n if missing:\n raise TemplateSyntaxError(\n 'Fields {} missing for a form af class {}'.format(\n list(missing), form.__class__.__name__))\n\n rendered_non_field_errors = []\n context.update({'_bootstrap_form_options': options})\n for form in touched_form_fields.keys():\n if form in options['non_field_errors_included']:\n continue\n options['form'] = form\n rendered_non_field_errors.append(\n self.non_field_errors.render(context))\n context.pop()\n\n options.update({\n 'rendered_csrf_token': rendered_csrf_token,\n 'rendered_non_field_errors': rendered_non_field_errors,\n 'rendered_content': rendered_content,\n 'rendered_form_buttons': rendered_form_buttons,\n 'form_enctype': form_enctype,\n })\n return render_to_string(templates, options)\n\n\[email protected](name='bootstrap_form')\ndef do_bootstrap_form(parser, token):\n \"\"\"\n Usage::\n\n {% bootstrap_form [layout options...] [form options...] [button options...] %} # noqa\n ...\n [{% form form [layout options...] %}...]\n [{% field formfield [layout options...] %}...]\n [{% field_label formfield [layout options...] %}...]\n [{% field_input formfield [layout options...] %}...]\n ...\n {% endbootstrap_form %}\n\n Layout options:\n\n * layout: \"horizontal\" | \"inline\" | \"basic\"\n * label_columns: 1..12\n * input_columns: 1..12\n * label_class: css_class_string\n * input_class: css_class_string\n * checkbox_class: css_class_string\n\n Form options:\n\n * form_action: URL\n * form_method: \"post\" | \"get\" | ...\n\n Button options:\n\n * submit_label: string\n * delete_label: string\n * cancel_label: string\n * cancel_target: URL, False/None for no \"cancel\"\n * delete_target: URL, False/None for no \"delete\"\n \"\"\"\n tag_name, options = parse_token_arguments(\n parser, token, [],\n LAYOUT_OPTION_NAMES + FORM_OPTION_NAMES + FORM_BUTTON_OPTION_NAMES)\n nodelist = parser.parse(('endbootstrap_form',))\n parser.delete_first_token()\n return BootstrapFormNode(tag_name, options, nodelist)\n" }, { "alpha_fraction": 0.7529677748680115, "alphanum_fraction": 0.7546636462211609, "avg_line_length": 35.85416793823242, "blob_id": "19d9c1ddc52f1248ebf0132e2d338141dc3a5ea0", "content_id": "fe7943b5149561319387a7abfc6bfa59bb99f3de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1769, "license_type": "no_license", "max_line_length": 79, "num_lines": 48, "path": "/gridplatform/customer_datasources/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.db import models\n\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import StoredSubclassCustomerBoundManager\n\n\n# NOTE: only managers defined on abstract base classes are inherited. So this\n# is a trick to make sure all CustomerDataSource specializations by default\n# will have StoredSubclassCustomerBoundManager as their objects.\nclass CustomerDataSourceManagerMixin(models.Model):\n objects = StoredSubclassCustomerBoundManager()\n\n class Meta:\n abstract = True\n\n\nclass CustomerDataSource(\n CustomerDataSourceManagerMixin, EncryptionCustomerFieldMixin,\n EncryptedModel, DataSource):\n \"\"\"\n Specialization of :class:`~gridplatform.datasources.models.DataSource` that\n is owned by :class:`~gridplatform.providers.models.Customer`.\n\n :ivar customer: The owning\n :class:`~gridplatform.customers.models.Customer`.\n :ivar name: The name.\n\n :cvar objects: The manager of :class:`.CustomerDataSource` is a\n :class:`.StoredSubclassCustomerBoundManager`. Care has been taken to\n make sure that subclasses inherit this manager.\n \"\"\"\n\n name = EncryptedCharField(_('name'), max_length=50, blank=False)\n\n class Meta:\n verbose_name = _('customer data source')\n verbose_name_plural = _('customer data sources')\n\n def __unicode__(self):\n return self.name_plain or self.hardware_id\n" }, { "alpha_fraction": 0.6406202912330627, "alphanum_fraction": 0.6525142788887024, "avg_line_length": 34.14285659790039, "blob_id": "acb0143f0b2f8b140ac3af48d19b36a673374872", "content_id": "de591f83c6385e0ddc7d8b46afd8645f97aaa976", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13284, "license_type": "no_license", "max_line_length": 78, "num_lines": 378, "path": "/legacy/website/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nTests for the C{website} django app.\n\"\"\"\n\nimport os\nimport time\nimport pytz\n\nfrom pyvirtualdisplay import Display\n\n\nfrom django.test import LiveServerTestCase\nfrom django.test.utils import override_settings\nfrom django.utils.unittest import skipIf\nfrom django.conf import settings\n\n\nfrom gridplatform.utils.tests import CustomWebDriver\nfrom django.core.management import call_command\n\nfrom gridplatform.encryption.shell import Request\nfrom gridplatform.encryption.base import EncryptionContext\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.models import Location\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.devices.models import PhysicalInput\nfrom gridplatform.users.models import User\nfrom gridplatform import trackuser\nfrom gridplatform.encryption import _store as encryption_store\nfrom gridplatform.trackuser import _store as trackuser_store\nfrom gridplatform.providers.models import Provider\n\nfrom legacy.manage_users.views import UserForm\nfrom legacy.manage_users.views import UserProfileForm\nfrom legacy.manage_users.views import create_user\n\n\ndef setup():\n Provider.objects.create()\n\n # Setup root user and request\n call_command('create_encrypted_user', 'root', 'feet', 'admin')\n request = Request('root', 'feet')\n\n encryption_store.encryption_context = EncryptionContext()\n trackuser_store.user = request.user\n\n # Setup customer\n customer = Customer(\n name_plain='test customer',\n vat_plain='4242',\n address_plain='address',\n postal_code_plain='1234',\n city_plain='city',\n phone_plain='12341234',\n country_code_plain='dnk',\n timezone=pytz.timezone('Europe/Copenhagen'),\n contact_name_plain='',\n contact_email_plain='',\n contact_phone_plain='')\n customer.save()\n\n trackuser._store.customer = customer\n assert customer is trackuser.get_customer()\n\n # setup customer super user\n username = '[email protected]'\n user_form = UserForm({\n 'e_mail': username,\n 'phone': '33334433',\n 'mobile': '34343333',\n 'name': 'Super User',\n 'user_type': str(User.CUSTOMER_SUPERUSER),\n })\n\n user_profile = UserProfileForm({\n 'collections': ''\n })\n\n user_form.is_valid()\n user_profile.is_valid()\n user, password = create_user(request, customer, user_form, user_profile)\n\n # Location\n location = Location.objects.create(\n customer=customer, name_plain=\"Test Location\")\n\n # Agent\n agent = Agent.objects.create(\n customer=customer, location=location, mac='08:00:27:03:fe:c7',\n device_type=1, hw_major=5, hw_minor=0, hw_revision=0,\n sw_major=2, sw_minor=2, sw_revision=1, sw_subrevision='fixture',\n online=True)\n\n # Meters\n def create_meter(agent, manufactoring_id, connection_type, name, request):\n customer = agent.customer\n location = agent.location\n meter = Meter(\n customer=customer,\n agent=agent,\n manufactoring_id=manufactoring_id,\n connection_type=connection_type,\n location=location,\n name_plain=name,\n relay_enabled=True,\n online=True)\n meter.save()\n return meter\n\n create_meter(\n agent, 155173425101, Meter.GRIDLINK,\n 'Kamstrup meter', request)\n mbus_meter = create_meter(\n agent, 1980720117449728, Meter.GRIDLINK,\n 'Mbus meter', request)\n meter = create_meter(\n agent, 456789, Meter.GRIDLINK,\n 'ZigBee elec. test meter', request)\n gas = create_meter(\n agent, 456790, Meter.GRIDLINK,\n 'ZigBee gas meter', request)\n heat = create_meter(\n agent, 456791, Meter.GRIDLINK,\n 'ZigBee heat meter', request)\n water = create_meter(\n agent, 456792, Meter.GRIDLINK,\n 'ZigBee water meter', request)\n oil = create_meter(\n agent, 456794, Meter.GRIDLINK,\n 'ZigBee oil meter', request)\n gridlink = create_meter(\n agent, 456793, Meter.GRIDLINK,\n 'GridLink', request)\n\n # Physical inputs\n PhysicalInput.objects.create(\n customer=customer,\n unit='milliwatt*hour', type=1,\n meter=mbus_meter, order=0,\n name_plain='M-Bus consumption')\n\n PhysicalInput.objects.create(\n customer=customer,\n unit='milliwatt', type=1,\n meter=mbus_meter, order=0, name_plain='M-Bus power')\n\n PhysicalInput.objects.create(\n customer=customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN,\n meter=meter, order=2,\n name_plain='Pulse meter')\n\n gas = PhysicalInput.objects.create(\n customer=customer,\n unit='milliliter',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gas, order=0,\n name_plain=\"Gas consumption\")\n\n heat = PhysicalInput.objects.create(\n customer=customer,\n unit='milliwatt*hour',\n type=PhysicalInput.DISTRICT_HEATING, meter=heat, order=0,\n name_plain=\"Heat consumption\")\n\n water = PhysicalInput.objects.create(\n customer=customer,\n unit='milliliter',\n type=PhysicalInput.WATER, meter=water,\n order=0, name_plain=\"Water consumption\")\n\n oil = PhysicalInput.objects.create(\n customer=customer,\n unit='milliliter',\n type=PhysicalInput.OIL, meter=oil,\n order=1, name_plain=\"Oil consumption\")\n\n PhysicalInput.objects.create(\n customer=customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=0, name_plain=\"GridLink input 1\")\n PhysicalInput.objects.create(\n customer=customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=1, name_plain=\"GridLink input 2\")\n PhysicalInput.objects.create(\n customer=customer,\n unit='impulse',\n type=PhysicalInput.UNKNOWN_ORIGIN, meter=gridlink,\n order=2, name_plain=\"GridLink input 3\")\n\n return username, password, customer\n\n\n@override_settings(\n DEBUG=True,\n MIDDLEWARE_CLASSES=[\n x for x in settings.MIDDLEWARE_CLASSES\n if x != \"debug_toolbar.middleware.DebugToolbarMiddleware\"],\n INSTALLED_APPS=[\n x for x in settings.INSTALLED_APPS if x != \"debug_toolbar\"])\nclass SeleniumLiveServerTestCase(LiveServerTestCase):\n def setUp(self, *args, **kwargs):\n super(SeleniumLiveServerTestCase, self).setUp(*args, **kwargs)\n self.username, self.password, self.customer = setup()\n\n def tearDown(self):\n encryption_store.encryption_context = None\n trackuser_store.user = None\n trackuser._store.customer = None\n\n\n# DB DUMP:\n# ./manage.py dumpdata --format=json --indent=2 --natural rules.rule\n# customers.customer customers.location auth.user users.user\n# customers.userprofile encryption.encryptionkey >\n# gridplatform/website/fixtures/website_rule_test.json\n\n\n@skipIf(os.environ.get('SELENIUM_SERVER') != \"TRUE\", 'Selenium test')\nclass WebsiteUITest(SeleniumLiveServerTestCase):\n\n def setUp(self):\n super(WebsiteUITest, self).setUp()\n self.display = Display(visible=0, size=(1024, 768))\n self.display.start()\n self.driver = CustomWebDriver()\n self.driver.implicitly_wait(30)\n self.base_url = self.live_server_url\n self.verificationErrors = []\n\n def test_login(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.assertTrue(self.driver.find_css('#dashboard'))\n\n def tearDown(self):\n super(WebsiteUITest, self).tearDown()\n self.driver.logout()\n self.driver.quit()\n self.display.stop()\n self.assertEqual([], self.verificationErrors)\n\n\n@skipIf(os.environ.get('SELENIUM_SERVER') != \"TRUE\", 'Selenium test')\nclass WebsiteMenuUITest(SeleniumLiveServerTestCase):\n def setUp(self):\n super(WebsiteMenuUITest, self).setUp()\n\n self.display = Display(visible=0, size=(1024, 768))\n self.display.start()\n self.driver = CustomWebDriver()\n self.driver.implicitly_wait(5)\n self.base_url = self.live_server_url\n self.verificationErrors = []\n\n def test_details(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\"div.menu-item.mp a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#mp-page #measurementpoints'))\n\n def test_indexes(self):\n self.driver.set_page_load_timeout(10)\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\"div.menu-item.indexes a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#indexes-page #indexes'))\n\n def test_reports(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\"div.menu-item.reports a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#reports-page'))\n\n def test_projects(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\"div.menu-item.projects a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#projects-page'))\n\n def test_detail_settings(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.mps a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#mps-page'))\n\n def test_groups(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.groups a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#groups-page'))\n\n def test_rules(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.rules a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#rules-page'))\n\n def test_index_settings(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.indexsettings a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#indexsettings-page'))\n\n def test_devices(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.devices a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#devices-page'))\n\n def test_locations(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.locations a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#locations-page'))\n\n def test_users(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.users a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#users-page'))\n\n def test_userprofile(self):\n self.driver.login(\n self.base_url, self.username, self.password)\n self.driver.find_css(\".settings-btn\").click()\n # wait for settings menu to move down\n time.sleep(1)\n self.driver.find_css(\"div.menu-item.userprofile a span\").click()\n self.assertNotIn('XYZXYZXYZ', self.driver.page_source)\n self.assertTrue(self.driver.find_css('#userprofile-page'))\n\n def tearDown(self):\n super(WebsiteMenuUITest, self).tearDown()\n self.driver.logout()\n self.driver.quit()\n self.display.stop()\n self.assertEqual([], self.verificationErrors)\n" }, { "alpha_fraction": 0.5873042345046997, "alphanum_fraction": 0.5966344475746155, "avg_line_length": 33.895347595214844, "blob_id": "8aa69be54564b032967e3cfa630ff221a5ff1ea2", "content_id": "23177d2608e74095219995e986df7c851afb4568", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6002, "license_type": "no_license", "max_line_length": 79, "num_lines": 172, "path": "/gridagentserver/agentserver/db.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\nDatabase interface exposing (limited) functionality as functions.\n\"\"\"\n# TODO: calculation points and rules are not yet defined in GridPlatform\nimport logging\nimport numbers\n\nfrom legacy.devices.models import Agent, Meter, PhysicalInput, AgentEvent\n\nlogger = logging.getLogger(__name__)\n\n\nBUCKINGHAM_MAP = {\n 0: 'none', # unknown unit\n 1: \"milliwatt*hour\",\n 2: \"milliwatt\",\n 3: \"impulse\",\n 4: \"milliliter\",\n 5: \"milliliter*hour^-1\",\n 6: \"millikelvin\",\n 7: \"millivolt\",\n 8: \"milliampere\",\n 9: \"millihertz\",\n 10: \"gram\",\n 11: \"millibar\",\n 12: \"second\",\n 13: \"none\", # \"binary states\"\n 14: \"millinone\", # \"milli\" power factor\n}\n\n\n# for models with encrypted fields, we store the empty string for those fields\n# (representing the encrypted form of the empty string) but we still need\n# \"something\" for an initialisation vector to avoid special cases in decryption\nfake_iv = bytearray('\\x00' * 16)\n\n# TODO: We need a cache clean-up method once we introduce GAS load\n# balancing\nvalue_cache = {}\n\n\ndef agent_exists(agent_mac):\n return Agent.objects.filter(mac=agent_mac).exists()\n\n\ndef get_agent(agent_mac):\n if isinstance(agent_mac, Agent):\n return agent_mac\n elif isinstance(agent_mac, numbers.Number):\n return Agent.objects.get(mac=agent_mac)\n else:\n raise Exception('Invalid data type for agent MAC: {}'.format(\n agent_mac))\n\n\ndef set_agent_info(agent_mac, serial, device_type, hw_version, sw_version):\n agent = get_agent(agent_mac)\n agent._set_info(serial, device_type, hw_version, sw_version)\n\n\ndef get_meter(meter_id, agent_mac):\n agent = get_agent(agent_mac)\n connection_type, manufactoring_id = meter_id\n obj, created = Meter.objects.get_or_create(\n connection_type=connection_type,\n manufactoring_id=manufactoring_id,\n agent=agent,\n customer_id=agent.customer_id,\n defaults={\n 'encryption_data_initialization_vector': fake_iv,\n 'location_id': agent.location_id,\n })\n return obj\n\n\ndef get_physicalinput(datatype, agent_unit, input_number, meter):\n if agent_unit in BUCKINGHAM_MAP:\n obj, created = PhysicalInput.objects.get_or_create(\n customer_id=meter.customer_id,\n type=datatype, unit=BUCKINGHAM_MAP[agent_unit],\n order=input_number, meter=meter,\n defaults={\n 'encryption_data_initialization_vector': fake_iv,\n 'store_measurements': True,\n 'hardware_id':\n 'GA-{agent_id:012x}-{meter_id:016x}-{input_id}'.format(\n agent_id=int(meter.agent.mac),\n meter_id=meter.manufactoring_id,\n input_id=input_number,\n )\n })\n return obj\n else:\n logger.warning(\n 'Unsupported unit %s from meter %d input %d.' % (\n agent_unit, meter, input_number))\n return None\n\n\ndef set_meter_state(control_manual, relay_on, online, timestamp,\n meter_id, agent_mac):\n meter = get_meter(meter_id, agent_mac)\n meter._set_state(control_manual, relay_on, online, timestamp)\n\n\ndef set_agent_online(online, timestamp, agent_mac):\n agent = get_agent(agent_mac)\n agent._set_online(online, timestamp)\n\n\ndef set_agent_add_mode(add_mode, timestamp, agent_mac):\n agent = get_agent(agent_mac)\n agent._set_add_mode(add_mode, timestamp)\n\n\ndef store_event(mac, timestamp, code, text):\n agent = Agent.objects.get(mac=mac)\n AgentEvent.objects.create(\n agent=agent, timestamp=timestamp, code=code, message=text)\n\n\ndef set_meters_online(mac, meter_list, version_list, device_opts_list):\n agent = get_agent(mac)\n if version_list and device_opts_list:\n for meter_id, versions, device_opts in \\\n zip(meter_list, version_list, device_opts_list):\n connection_type, manufactoring_id = meter_id\n try:\n meter = Meter.objects.get(\n connection_type=connection_type,\n manufactoring_id=manufactoring_id,\n agent=agent,\n customer_id=agent.customer_id)\n except Meter.DoesNotExist:\n # Quick fix for bug in GridAgent SW version 2.3.0.\n # It sometimes sends junk in the meters connected set.\n continue\n meter.online = True\n meter.device_type = device_opts[0]\n meter.hw_major = versions[0].major\n meter.hw_minor = versions[0].minor\n meter.hw_revision = versions[0].revision\n meter.hw_subrevision = \\\n versions[0].revisionstring.decode('iso8859-1')\n meter.sw_major = versions[1].major\n meter.sw_minor = versions[1].minor\n meter.sw_revision = versions[1].revision\n meter.sw_subrevision = \\\n versions[1].revisionstring.decode('iso8859-1')\n meter.save(update_fields=[\n 'online',\n 'device_type',\n 'hw_major', 'hw_minor', 'hw_revision', 'hw_subrevision',\n 'sw_major', 'sw_minor', 'sw_revision', 'sw_subrevision',\n ])\n else:\n # missing version_list or device_opts_list --- data from old agent\n # sw version which does not provide this...\n for meter_id in meter_list:\n connection_type, manufactoring_id = meter_id\n try:\n meter = Meter.objects.get(\n connection_type=connection_type,\n manufactoring_id=manufactoring_id,\n agent=agent,\n customer_id=agent.customer_id)\n except Meter.DoesNotExist:\n # Quick fix for bug in GridAgent SW version 2.3.0.\n # It sometimes sends junk in the meters connected set.\n continue\n meter.online = True\n meter.save(update_fields=['online'])\n" }, { "alpha_fraction": 0.5994123220443726, "alphanum_fraction": 0.6036677956581116, "avg_line_length": 38.42609786987305, "blob_id": "1fb1d3f9d135c6a0f4d5bda4a9f07071cbc38e3d", "content_id": "d197b088afc321603ecbf4e82be13eb058bdbc66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 29629, "license_type": "no_license", "max_line_length": 81, "num_lines": 751, "path": "/legacy/energy_use_reports/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom datetime import time\nfrom datetime import timedelta # RelativeTimeDelta does not work for dates.\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom celery import shared_task\nfrom celery import Task\n\nfrom legacy.measurementpoints import default_unit_for_data_series\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils.utilitytypes import UTILITY_TYPE_TO_COLOR\nfrom legacy.measurementpoints.models.graph import AbstractGraph\nfrom legacy.measurementpoints.models import Summation\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.trackuser import get_user\n\nfrom .models import EnergyUseReport\nfrom .models import EnergyUseArea\n\n\nclass DataCollectionError(object):\n \"\"\"\n Class for reporting errors during data collection in Celery tasks where\n encryption context is absent.\n\n Intended for use with L{EnergyUseReportTask}\n\n Actual localization and the string interpolation that follows is intended\n to happen once the a view receives C{DataCollectionError}s from the\n task that created these.\n \"\"\"\n\n def __init__(self, error_message_format, measurement_point=None,\n energy_use_area=None):\n \"\"\"\n @param error_message_format: A ugettext_lazy object optionally\n containing formatters depending on other arguments.\n\n @param measurement_point: An optional measurement point. If given the\n C{error_message_format} must contain C{'{measurement_point}'}.\n\n @param energy_use_area: An optional area of energy use. If given the\n C{error_message_format} must contain C{'{energy_use_area}'}.\n \"\"\"\n assert measurement_point is None or \\\n '{measurement_point}' in unicode(error_message_format)\n assert energy_use_area is None or \\\n '{energy_use_area}' in unicode(error_message_format)\n self.error_message_format = error_message_format\n\n if measurement_point is not None:\n self.measurement_point_id = measurement_point.id\n else:\n self.measurement_point_id = None\n\n if energy_use_area is not None:\n self.energy_use_area_id = energy_use_area.id\n else:\n self.energy_use_area_id = None\n\n def __unicode__(self):\n if self.measurement_point_id is not None:\n measurement_point = ConsumptionMeasurementPoint.objects.get(\n id=self.measurement_point_id)\n else:\n measurement_point = None\n\n if self.energy_use_area_id is not None:\n energy_use_area = EnergyUseArea.objects.get(\n id=self.energy_use_area_id)\n else:\n energy_use_area = None\n\n return self.error_message_format.format(\n measurement_point=measurement_point,\n energy_use_area=energy_use_area)\n\n\nclass ErrorCollector(object):\n \"\"\"\n Collect errors during data collection.\n\n @ivar errors: A list of L{DataCollectionErrors} collected.\n\n @ivar consumption_error_collector: A PeriodErrorCollector for consumption.\n\n @ivar cost_error_collector: A PeriodErrorCollector for cost.\n\n @ivar co2_error_collector: A PeriodErrorCollector for co2.\n\n @cvar PeriodErrorCollector: Adaptor aggregate with two methods that will\n forward to the revelant method in C\n {ErrorCollector}. C{extrapolated_current_period()} is for telling this\n error collector about current period being extrapolated and\n C{extrapolated_previous_period()} is for telling this error collector about\n previous period being extrapolated.\n \"\"\"\n\n PeriodErrorCollector = namedtuple(\n 'PeriodErrorCollector',\n [\n 'extrapolated_current_period',\n 'extrapolated_previous_period'])\n\n def __init__(self, errors, mp):\n \"\"\"\n Construct an error collector for a given error list and a given\n measurement point.\n\n @param errors: The list to be used as C{self.errors}. Note that lists\n in Python are mutable, so the same list can be shared between multiple\n error collectors.\n\n @param mp: The L{ConsumptionMeasurementPoint} to collect errors about.\n \"\"\"\n self.errors = errors\n self.mp = mp\n\n self.consumption_error_collector = self.PeriodErrorCollector(\n self.extrapolated_consumption_current_period,\n self.extrapolated_consumption_previous_period)\n\n self.cost_error_collector = self.PeriodErrorCollector(\n self.extrapolated_cost_current_period,\n self.extrapolated_cost_previous_period)\n\n self.co2_error_collector = self.PeriodErrorCollector(\n self.extrapolated_co2_current_period,\n self.extrapolated_co2_previous_period)\n\n def extrapolated_consumption_current_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that consumption of C{mp} has been\n extrapolated for the current period.\n \"\"\"\n raise NotImplementedError()\n\n def extrapolated_consumption_previous_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that consumption of C{mp} has been\n extrapolated for the previous period.\n \"\"\"\n raise NotImplementedError()\n\n def no_tariff(self):\n \"\"\"\n Tell this C{ErrorCollector} that there is no tariff associtated with\n this C{mp}, and cost therefore cannot be calculated.\n \"\"\"\n raise NotImplementedError()\n\n def bad_currency(self):\n \"\"\"\n Tell this C{ErrorCollector} that the cost currency of C{mp} is\n incompatible with that of the energy use report, and cost therefore\n will not be inclued.\n \"\"\"\n raise NotImplementedError()\n\n def extrapolated_cost_current_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that the cost of C{mp} for the current\n period is extrapolated.\n \"\"\"\n raise NotImplementedError()\n\n def extrapolated_cost_previous_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that the cost of C{mp} for the previous\n period is extrapolated.\n \"\"\"\n raise NotImplementedError()\n\n def no_co2_index(self):\n \"\"\"\n Tell this C{ErrorCollector} that the CO2 emissions of C{mp} cannot be\n calculated because no CO2 index has been assigned.\n \"\"\"\n raise NotImplementedError()\n\n def extrapolated_co2_current_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that the CO2 emissions of C{mp} for the\n current period are extrapolated.\n \"\"\"\n raise NotImplementedError()\n\n def extrapolated_co2_previous_period(self):\n \"\"\"\n Tell this C{ErrorCollector} that the CO2 emissions of C{mp} for the\n previous period are extrapolated.\n \"\"\"\n raise NotImplementedError()\n\n\nclass MainMeasurementPointErrorCollector(ErrorCollector):\n def extrapolated_consumption_current_period(self):\n self.errors.append(\n DataCollectionError(\n _('The consumption of the main measurement point '\n '{measurement_point}, is calculated from incomplete data '\n 'in the current period'), self.mp))\n\n def extrapolated_consumption_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _('The consumption of the main measurement point '\n '{measurement_point}, is calculated from incomplete data '\n 'in the previous period'), self.mp))\n\n def no_tariff(self):\n self.errors.append(\n DataCollectionError(\n _('Unable to calculate cost for '\n 'the main measurement point '\n '{measurement_point}, because it has no tariff'), self.mp))\n\n def bad_currency(self):\n self.errors.append(\n DataCollectionError(\n _('Unable to calculate cost for '\n 'the main measurement point '\n '{measurement_point}, because the '\n 'tariff currency is different '\n 'from the report currency'), self.mp))\n\n def extrapolated_cost_current_period(self):\n self.errors.append(\n DataCollectionError(\n _('The cost of the main measurement point '\n '{measurement_point}, is calculated from incomplete data '\n 'in the current period'), self.mp))\n\n def extrapolated_cost_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _('The cost of the main measurement point '\n '{measurement_point}, is calculated from incomplete data '\n 'in the previous period'), self.mp))\n\n def no_co2_index(self):\n self.errors.append(\n DataCollectionError(\n _(u'Unable to calculate CO₂ emissions for '\n 'the main measurement point {measurement_point}, '\n 'because the '\n u'measurement point has no CO₂ index assigned'),\n self.mp))\n\n def extrapolated_co2_current_period(self):\n self.errors.append(\n DataCollectionError(\n _(u'The CO₂ emissions of the main measurement point '\n '{measurement_point} are calculated from incomplete data '\n 'in the current period'), self.mp))\n\n def extrapolated_co2_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _(u'The CO₂ emissions of the main measurement point '\n '{measurement_point} are calculated from incomplete data '\n 'in the previous period'), self.mp))\n\n\nclass AreaErrorCollector(ErrorCollector):\n def __init__(self, errors, mp, area):\n super(AreaErrorCollector, self).__init__(errors, mp)\n self.area = area\n\n def extrapolated_consumption_current_period(self):\n self.errors.append(\n DataCollectionError(\n _('The consumption of the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, is calculated from incomplete data '\n 'in the current period'),\n self.mp, self.area))\n\n def extrapolated_consumption_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _('The consumption of the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, is calculated from incomplete data '\n 'in the previous period'),\n self.mp, self.area))\n\n def no_tariff(self):\n self.errors.append(\n DataCollectionError(\n _('Unable to calculate cost for the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, because the measurement point has '\n 'no tariff'), self.mp, self.area))\n\n def bad_currency(self):\n self.errors.append(\n DataCollectionError(\n _('Unable to calculate cost for the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, because the tariff currency is '\n 'different from the report currency'), self.mp, self.area))\n\n def extrapolated_cost_current_period(self):\n self.errors.append(\n DataCollectionError(\n _('The cost of the measurement point {measurement_point} '\n 'in the area of energy use {energy_use_area}, is calculated '\n 'from incomplete data in the current period'),\n self.mp, self.area))\n\n def extrapolated_cost_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _('The cost of the measurement point {measurement_point} '\n 'in the area of energy use {energy_use_area}, is calculated '\n 'from incomplete data in the previous period'),\n self.mp, self.area))\n\n def no_co2_index(self):\n self.errors.append(\n DataCollectionError(\n _(u'Unable to calculate CO₂ emissions for the measurement '\n 'point {measurement_point} in the area of energy use '\n '{energy_use_area}, because the '\n u'measurement point has no CO₂ index assigned'),\n self.mp, self.area))\n\n def extrapolated_co2_current_period(self):\n self.errors.append(\n DataCollectionError(\n _(u'The CO₂ emissions of the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, is calculated from incomplete data in '\n 'the current period'), self.mp, self.area))\n\n def extrapolated_co2_previous_period(self):\n self.errors.append(\n DataCollectionError(\n _(u'The CO₂ emissions of the measurement point '\n '{measurement_point} in the area of energy use '\n '{energy_use_area}, is calculated from incomplete data in '\n 'the previous period'), self.mp, self.area))\n\n\nclass EnergyUseGraph(AbstractGraph):\n def __init__(self, energy_use_report_task, errors):\n self.energy_use_report_task = energy_use_report_task\n self.errors = errors\n\n MAX_SAMPLES = 1000\n\n @classmethod\n def get_sample_resolution(cls, from_timestamp, to_timestamp):\n \"\"\"\n Derive desired sample resolution from from_timestamp and to_timestamp\n \"\"\"\n if from_timestamp + RelativeTimeDelta(hours=cls.MAX_SAMPLES) > \\\n to_timestamp:\n sample_resolution = RelativeTimeDelta(hours=1)\n elif from_timestamp + RelativeTimeDelta(days=cls.MAX_SAMPLES) > \\\n to_timestamp:\n sample_resolution = RelativeTimeDelta(days=1)\n else:\n assert from_timestamp + RelativeTimeDelta(months=cls.MAX_SAMPLES) > \\\n to_timestamp\n sample_resolution = RelativeTimeDelta(months=1)\n return sample_resolution\n\n def get_bar_graph_data(self, from_timestamp, to_timestamp):\n sample_resolution = self.get_sample_resolution(\n from_timestamp, to_timestamp)\n num_samples = 0\n while from_timestamp + sample_resolution * (num_samples + 1) <= \\\n to_timestamp:\n num_samples += 1\n assert from_timestamp + num_samples * sample_resolution <= to_timestamp\n assert num_samples <= self.MAX_SAMPLES\n\n result = self.get_graph_data(\n num_ticks=min(5, num_samples),\n from_timestamp=from_timestamp,\n num_samples=num_samples,\n sample_resolution=sample_resolution,\n weekends_are_special=False)\n\n return result\n\n def tick_progress(self):\n \"\"\"\n Update progress on L{EnergyUseReportTask} task.\n \"\"\"\n self.energy_use_report_task.tick_progress()\n\n\nclass EnergyUseConsumptionGraph(EnergyUseGraph):\n def _get_data_series(self):\n consumptions = []\n if self.energy_use_report_task.energy_use_report.\\\n main_measurement_points.exists():\n consumptions = [\n mp.subclass_instance.consumption.subclass_instance for mp in\n self.energy_use_report_task.energy_use_report.\n main_measurement_points.all()]\n else:\n for area in self.energy_use_report_task.energy_use_report.\\\n energyusearea_set.all():\n for mp in area.measurement_points.all():\n consumptions.append(\n mp.subclass_instance.consumption.subclass_instance)\n result = Summation()\n result.role = DataRoleField.CONSUMPTION\n result.unit = default_unit_for_data_series(\n DataRoleField.CONSUMPTION,\n self.energy_use_report_task.energy_use_report.utility_type)\n result.utility_type = self.energy_use_report_task.\\\n energy_use_report.utility_type\n result.plus_data_series = consumptions\n result.customer = self.energy_use_report_task.energy_use_report.\\\n customer\n return [result]\n\n def get_colors(self):\n return [\n UTILITY_TYPE_TO_COLOR[\n self.energy_use_report_task.energy_use_report.utility_type]]\n\n\nclass EnergyUseCo2EmissionGraph(EnergyUseGraph):\n def _get_data_series(self):\n co2 = []\n if self.energy_use_report_task.energy_use_report.\\\n main_measurement_points.exists():\n measurement_points = self.energy_use_report_task.\\\n energy_use_report.main_measurement_points.all()\n else:\n measurement_points = ConsumptionMeasurementPoint.objects.filter(\n energyusearea__report=self.energy_use_report_task.\n energy_use_report)\n\n for mp in measurement_points:\n if mp.subclass_instance.co2calculation is not None:\n co2.append(mp.subclass_instance.co2calculation)\n else:\n self.errors.append(\n DataCollectionError(\n _('CO₂ emissions for the measurement point '\n '{measurement_point} are not defined, and '\n 'therefore not included in the CO₂ emissions '\n 'graph.'), mp))\n\n result = Summation()\n result.role = DataRoleField.CO2\n result.unit = default_unit_for_data_series(\n DataRoleField.CO2,\n self.energy_use_report_task.energy_use_report.utility_type)\n result.utility_type = self.energy_use_report_task.energy_use_report.\\\n utility_type\n result.plus_data_series = co2\n result.customer = self.energy_use_report_task.energy_use_report.\\\n customer\n return [result]\n\n def _get_unit_display(self):\n return self.energy_use_report_task.energy_use_report.\\\n get_preferred_co2_emission_unit_display()\n\n def get_colors(self):\n return ['#444444']\n\n\nclass TaskProgressMixin(object):\n \"\"\"\n Celery Task mixin that provides means for progress reporting.\n \"\"\"\n\n def tick_progress(self):\n \"\"\"\n Make the progress state of this Task tick.\n\n @precondition: C{self.PROGRESS_TOTAL} must be set.\n\n @precondition: C{self.progress} must have been reset once for current\n task invocation.\n\n @precondition: This method must not be called more than\n C{self.PROGRESS_TOTAL} times for each invocation; i.e. C{self.progress\n <= self.PROGRESS_TOTAL}.\n\n @precondition: get_user() must return a User. (decorate your task with\n L{trackuser_task} if it doesn't)\n \"\"\"\n assert self.progress <= self.PROGRESS_TOTAL, \\\n (self.progress, self.PROGRESS_TOTAL)\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': self.progress,\n 'total': self.PROGRESS_TOTAL\n }\n )\n self.progress += 1\n\n\n# Softly kill using exception after 30 minutes. Kill for real after 31 minutes.\n@trackuser_task\n@shared_task(\n time_limit=1860, soft_time_limit=1800,\n name='legacy.energy_use_reports.tasks.EnergyUseReportTask')\nclass EnergyUseReportTask(TaskProgressMixin, Task):\n \"\"\"\n Celery task for collecting energy use report data.\n\n Intended to work with L{StartReportView} and\n L{GenerateEnergyUseReportForm}.\n \"\"\"\n ZERO_CO2_EMISSION = PhysicalQuantity(0, 'gram')\n\n def _collect_data_series_period_data(self, data_series, error_collector):\n data_sample = data_series.calculate_development(\n self.from_timestamp, self.to_timestamp)\n if data_sample is None:\n data = PhysicalQuantity(0, data_series.unit)\n error_collector.extrapolated_current_period()\n elif data_sample.extrapolated:\n data = data_sample.physical_quantity\n error_collector.extrapolated_current_period()\n else:\n data = data_sample.physical_quantity\n\n data_sample = data_series.calculate_development(\n self.previous_from_time, self.previous_to_time)\n if data_sample is None:\n previous_data = PhysicalQuantity(0, data_series.unit)\n error_collector.extrapolated_previous_period()\n elif data_sample.extrapolated:\n previous_data = data_sample.physical_quantity\n error_collector.extrapolated_previous_period()\n else:\n previous_data = data_sample.physical_quantity\n\n return {\n 'data': data,\n 'previous_data': previous_data,\n }\n\n def _collect_measurement_point_period_data(self, mp, error_collector):\n consumption_data = self._collect_data_series_period_data(\n mp.consumption, error_collector.consumption_error_collector)\n self.consumption += consumption_data['data']\n self.previous_consumption += consumption_data['previous_data']\n\n if self.include_cost:\n if mp.cost is None:\n error_collector.no_tariff()\n elif not PhysicalQuantity.compatible_units(\n mp.cost.unit, self.energy_use_report.currency_unit):\n error_collector.bad_currency()\n else:\n cost_data = self._collect_data_series_period_data(\n mp.cost, error_collector.cost_error_collector)\n self.cost += cost_data['data']\n self.previous_cost += cost_data['previous_data']\n\n if self.include_co2:\n if mp.co2calculation is None:\n error_collector.no_co2_index()\n else:\n co2_data = self._collect_data_series_period_data(\n mp.co2calculation, error_collector.co2_error_collector)\n self.co2 += co2_data['data']\n self.previous_co2 += co2_data['previous_data']\n\n def _reset_period_variables(self):\n self.consumption = self.ZERO_CONSUMPTION\n self.previous_consumption = self.ZERO_CONSUMPTION\n self.cost = self.ZERO_COST\n self.previous_cost = self.ZERO_COST\n self.co2 = self.ZERO_CO2_EMISSION\n self.previous_co2 = self.ZERO_CO2_EMISSION\n\n def run(self, data):\n \"\"\"\n @return: Returns a dictionary containing the keys\n C{'energy_use_report'}, C{'errors'} and C{'data'}. C{'errors'} maps to\n a list of L{DataCollectionError}, and C{'data'} maps to another\n dictionary of L{EnergyUseArea} ids mapped to yet another dictionary\n mapping C{'cost'} to the combined cost of the particular area of energy\n use, and C{'consumption'} to the combined consumption of the particular\n area of energy use. For example::\n\n {\n 'energy_use_report': 11,\n 'errors': [],\n 'data': {\n 42: {\n 'cost': Fraction(3, 2),\n 'consumption': Fraction(5, 2)\n }\n }\n }\n\n \"\"\"\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': 0,\n 'total': 0\n }\n )\n self.energy_use_report = EnergyUseReport.objects.get(\n id=data['energy_use_report_id'])\n\n self.ZERO_CONSUMPTION = PhysicalQuantity(\n 0,\n default_unit_for_data_series(\n DataRoleField.CONSUMPTION,\n self.energy_use_report.utility_type))\n self.ZERO_COST = PhysicalQuantity(\n 0, self.energy_use_report.currency_unit)\n\n customer = self.energy_use_report.customer\n self.from_timestamp = customer.timezone.localize(\n datetime.combine(\n data['from_date'], time()))\n self.to_timestamp = customer.timezone.localize(\n datetime.combine(\n data['to_date'], time())) + \\\n RelativeTimeDelta(days=1)\n self.include_cost = data['include_cost']\n self.include_co2 = data['include_co2']\n\n self.previous_from_time = customer.timezone.localize(\n datetime.combine(\n data['previous_period_from_date'], time()))\n self.previous_to_time = customer.timezone.localize(\n datetime.combine(\n data['previous_period_to_date'], time())) + \\\n RelativeTimeDelta(days=1)\n\n self.PROGRESS_TOTAL = ConsumptionMeasurementPoint.objects.filter(\n energyusearea__report_id=self.energy_use_report.id).count() + \\\n self.energy_use_report.main_measurement_points.count() + \\\n EnergyUseConsumptionGraph.PROGRESS_TOTAL\n\n if data['include_co2']:\n self.PROGRESS_TOTAL += EnergyUseCo2EmissionGraph.PROGRESS_TOTAL\n\n self.progress = 0\n self.tick_progress()\n\n errors = []\n consumption_graph = EnergyUseConsumptionGraph(self, errors)\n\n result = {\n 'energy_use_report': self.energy_use_report.id,\n 'errors': errors,\n 'data': {},\n 'from_date': self.from_timestamp.date(),\n 'to_date': self.to_timestamp.date() - timedelta(days=1),\n 'previous_from_date': self.previous_from_time.date(),\n 'previous_to_date': (\n self.previous_to_time.date() - timedelta(days=1)),\n 'graph_data': consumption_graph.get_bar_graph_data(\n self.from_timestamp, to_timestamp=self.to_timestamp),\n 'include_cost': self.include_cost,\n 'include_co2': self.include_co2\n }\n\n if data['include_co2']:\n co2_emission_graph = EnergyUseCo2EmissionGraph(self, errors)\n result['co2_graph_data'] = co2_emission_graph.get_bar_graph_data(\n self.from_timestamp, to_timestamp=self.to_timestamp)\n\n for area in self.energy_use_report.energyusearea_set.all():\n self._reset_period_variables()\n # period variables are now collecting data for area\n for mp in area.measurement_points.all():\n self.tick_progress()\n\n mp = mp.subclass_instance\n\n error_collector = AreaErrorCollector(\n result['errors'], mp, area)\n\n self._collect_measurement_point_period_data(\n mp, error_collector)\n\n result['data'][area.id] = {\n 'consumption': self.consumption.convert(\n self.energy_use_report.get_preferred_unit()),\n 'cost': self.cost.convert(\n self.energy_use_report.currency_unit),\n 'co2': self.co2.convert(\n self.energy_use_report.get_preferred_co2_emission_unit()),\n 'previous_consumption': self.previous_consumption.convert(\n self.energy_use_report.get_preferred_unit()),\n 'previous_cost': self.previous_cost.convert(\n self.energy_use_report.currency_unit),\n 'previous_co2': self.previous_co2.convert(\n self.energy_use_report.get_preferred_co2_emission_unit()),\n }\n\n self._reset_period_variables()\n # period variables are now collecting data for main measurement points.\n if self.energy_use_report.main_measurement_points.exists():\n for mp in self.energy_use_report.main_measurement_points.all():\n\n self.tick_progress()\n\n mp = mp.subclass_instance\n\n error_collector = MainMeasurementPointErrorCollector(\n result['errors'], mp)\n\n self._collect_measurement_point_period_data(mp,\n error_collector)\n else:\n result['errors'].append(\n DataCollectionError(\n _('No main measurement point has been selected. '\n 'Assuming all measurement points are main '\n 'measurement points, and that no costs nor consumptions '\n 'are unaccounted for.')))\n\n result['total_consumption'] = self.consumption.convert(\n self.energy_use_report.get_preferred_unit())\n result['total_cost'] = self.cost.convert(\n self.energy_use_report.currency_unit)\n result['total_co2'] = self.co2.convert(\n self.energy_use_report.get_preferred_co2_emission_unit())\n result['total_previous_consumption'] = \\\n self.previous_consumption.convert(\n self.energy_use_report.get_preferred_unit())\n result['total_previous_cost'] = self.previous_cost.convert(\n self.energy_use_report.currency_unit)\n result['total_previous_co2'] = self.previous_co2.convert(\n self.energy_use_report.get_preferred_co2_emission_unit())\n\n return result\n" }, { "alpha_fraction": 0.4834303855895996, "alphanum_fraction": 0.49708807468414307, "avg_line_length": 32.980735778808594, "blob_id": "1e7fdd7ef421b695b5ffc2c4d9b5c2256e8a64b8", "content_id": "7baa5f7deaa3f5dc4662c1d9cc5cd32274ef2369", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 19403, "license_type": "no_license", "max_line_length": 252, "num_lines": 571, "path": "/gridplatform/utils/static/utils/utils.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true */\n/*global $, jQuery, Flotr, gettext, pgettext, get_format, ui */\n\nvar utils = window.utils || {};\n\n\nutils.asyncTask = function (url, parameters) {\n 'use strict';\n // NOTE: Cleaning up wrt. old API: Response to initial request should\n // provide status URL and finalize/result URL.\n // (Ideally, status should include finalize URL when done, but with the\n // limited \"metadata\"-concept with Celery, that would imply writing\n // separate status-views for every task type...)\n // Attach event handlers to Deferred with done(), fail(), progress().\n var deferred = new jQuery.Deferred(),\n handleInitial,\n handleStatus,\n handleError,\n handleSuccess,\n recheckStatus,\n recheckStatusAfterDelay,\n statusUrl,\n finalizeUrl,\n taskId;\n handleInitial = function (data) {\n statusUrl = data.status_url;\n finalizeUrl = data.finalize_url;\n taskId = data.task_id;\n recheckStatusAfterDelay();\n };\n handleStatus = function (data) {\n if (data.status === 'PENDING' || data.status === 'RECEIVED' || data.status === 'STARTED' || data.status === 'RETRY') {\n // Do nothing...?\n // NOTE: \"PENDING\" means that no worker has observed the task ---\n // but Celery trusts your word in that it's a valid task ID, hence\n // it would be expected to be in a broker input queue. (Might\n // warrant extra handling; might behave strangely on server\n // restart...)\n recheckStatusAfterDelay();\n } else if (data.status === 'PROGRESS') {\n deferred.notify.apply(this, arguments);\n recheckStatusAfterDelay();\n } else if (data.status === 'SUCCESS') {\n jQuery.post(finalizeUrl, {task_id: taskId}).done(handleSuccess).fail(handleError);\n } else if (data.status === 'FAILURE' || data.status === 'REVOKED') {\n deferred.reject.apply(this, arguments);\n }\n };\n handleError = function () {\n deferred.reject.apply(this, arguments);\n };\n handleSuccess = function () {\n deferred.resolve.apply(this, arguments);\n };\n recheckStatus = function () {\n jQuery.post(statusUrl, {task_id: taskId}).done(handleStatus).fail(handleError);\n };\n recheckStatusAfterDelay = function () {\n window.setTimeout(recheckStatus, 500);\n };\n jQuery.post(url, parameters).done(handleInitial).fail(handleError);\n // Caller should attach event handlers with done(), fail(), progress()...\n return deferred.promise();\n};\n\n\nutils.loadGraph = function (container, url, urlParameters, graphOptions) {\n 'use strict';\n var deferred,\n contains_data = false;\n container.html('<p class=\"text-center\"><i class=\"fa fa-spinner fa-spin\"></i></p><p class=\"text-center graph-progress\"></p>');\n deferred = utils.asyncTask(url, urlParameters);\n deferred.done(function (data) {\n container.empty();\n //Hack to prevent Flotr2 from printing NaN% when all values are 0\n if (graphOptions['bars'] === undefined) {\n jQuery.each(data, function(key, value) {\n if (!contains_data) {\n jQuery.each(this.data[0], function(key, value) {\n if (value !== 0) {\n contains_data = true;\n return false;\n }\n });\n } else {\n return false;\n }\n });\n } else {\n contains_data = true;\n }\n if (contains_data) {\n Flotr.draw(container[0], data, graphOptions);\n $(window).off('resize.graph');\n $(window).on('resize.graph', _.debounce(function () {\n Flotr.draw(container[0], data, graphOptions);\n }, 100));\n } else {\n container.text(gettext('No data for this period'));\n }\n });\n deferred.fail(function () {\n container.html('<p class=\"text-center\"><i class=\"fa fa-ban\"></i></p>');\n });\n deferred.progress(function (data) {\n var result = data.result,\n current,\n total,\n percent;\n if (result) {\n current = result.current;\n total = result.total;\n if (current && total) {\n percent = Math.round(100 * current / total);\n container.find('.graph-progress').text(percent + '%');\n }\n }\n });\n};\n\nutils.loadGraphJs = function (container, url, urlParameters, graphOptions) {\n 'use strict';\n var deferred,\n contains_data = false,\n canvas = $('<canvas height=\"400\"></canvas>'),\n ctx,\n graphData,\n barChart,\n colors = graphOptions.colors,\n datasets;\n delete graphOptions.colors;\n container.html('<p class=\"text-center\"><i class=\"fa fa-spinner fa-spin\"></i></p><p class=\"text-center graph-progress\"></p>');\n deferred = utils.asyncTask(url, urlParameters);\n deferred.done(function (data) {\n container.empty();\n container.append(canvas);\n ctx = container.find('canvas').get(0).getContext(\"2d\");\n\n datasets = [\n {\n label: \"Baseline\",\n backgroundColor: colors[1].fillColor,\n borderColor: colors[1].strokeColor,\n hoverBackgroundColor: colors[1].highlightFill,\n hoverBorderColor: colors[1].highlightStroke,\n data: data.week_selected\n }\n ]\n graphData = {\n labels: data.labels,\n datasets: datasets\n };\n barChart = new Chart(ctx, {type: 'bar', data: graphData, options: graphOptions});\n });\n deferred.fail(function () {\n container.html('<p class=\"text-center\"><i class=\"fa fa-ban\"></i></p>');\n });\n deferred.progress(function (data) {\n var result = data.result,\n current,\n total,\n percent;\n if (result) {\n current = result.current;\n total = result.total;\n if (current && total) {\n percent = Math.round(100 * current / total);\n container.find('.graph-progress').text(percent + '%');\n }\n }\n });\n};\n\nutils.genericLoadGraphJs = function (container, url, urlParameters, graphOptions, type) {\n 'use strict';\n var deferred,\n contains_data = false,\n canvas = $('<canvas height=\"400\"></canvas>'),\n ctx,\n graphData,\n barChart,\n colors = graphOptions.colors,\n datasets;\n delete graphOptions.colors;\n container.html('<p class=\"text-center\"><i class=\"fa fa-spinner fa-spin\"></i></p><p class=\"text-center graph-progress\"></p>');\n deferred = utils.asyncTask(url, urlParameters);\n deferred.done(function (data) {\n container.empty();\n container.append(canvas);\n ctx = container.find('canvas').get(0).getContext(\"2d\");\n\n datasets = [\n {\n label: \"Forecast\",\n backgroundColor: colors[1].fillColor,\n borderColor: colors[1].strokeColor,\n hoverBackgroundColor: colors[1].highlightFill,\n hoverBorderColor: colors[1].highlightStroke,\n data: data.data,\n tension: 0\n }\n ]\n _.forEach(data.set_points, function(setPoint, key) {\n console.log(key);\n if (key != 9) {\n var setPointPoints = [];\n for (var i = 0; i < data.labels.length; i++) {\n setPointPoints.push(setPoint);\n }\n datasets.unshift({\n label: \"Set point \" + key,\n backgroundColor: \"rgba(220,220,220,0)\",\n radius: 1.2,\n borderColor: '#000000',\n data: setPointPoints,\n tension: 0,\n pointHoverRadius: 3,\n })\n }\n });\n\n graphData = {\n labels: data.labels,\n datasets: datasets\n };\n barChart = new Chart(ctx, {type: type, data: graphData, options: graphOptions});\n console.log(barChart);\n });\n deferred.fail(function () {\n container.html('<p class=\"text-center\"><i class=\"fa fa-ban\"></i></p>');\n });\n deferred.progress(function (data) {\n var result = data.result,\n current,\n total,\n percent;\n if (result) {\n current = result.current;\n total = result.total;\n if (current && total) {\n percent = Math.round(100 * current / total);\n container.find('.graph-progress').text(percent + '%');\n }\n }\n });\n};\n\nutils.barChart = function (container, form, url, unit, colors, showLegend) {\n 'use strict';\n var legend = \"\";//\"<ul class=\\\"<%=name.toLowerCase()%>-legend\\\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\\\"background-color:<%=datasets[i].fillColor%>\\\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>\";\n utils.loadGraphJs(\n container,\n url,\n form.serialize(),\n {\n colors: colors,\n responsive: true,\n maintainAspectRatio: false,\n multiTooltipTemplate:\n \"<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %> \" + unit,\n legend: {\n display: false\n },\n scales: {\n\n yAxes: [{\n ticks: {\n beginAtZero: true\n }\n }]\n }\n\n }\n );\n};\n\nutils.lineChart = function (container, form, url, unit, colors, showLegend) {\n 'use strict';\n var legend = \"\";//\"<ul class=\\\"<%=name.toLowerCase()%>-legend\\\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\\\"background-color:<%=datasets[i].fillColor%>\\\"><%if(datasets[i].label){%><%=datasets[i].label%><%}%></span></li><%}%></ul>\";\n utils.genericLoadGraphJs(\n container,\n url,\n form.serialize(),\n {\n colors: colors,\n responsive: true,\n maintainAspectRatio: false,\n multiTooltipTemplate:\n \"<%if (datasetLabel){%><%=datasetLabel%>: <%}%><%= value %> \" + unit,\n legend: {\n display: false\n },\n scales: {\n\n xAxes: [{\n type: 'time',\n time: {\n displayFormats: {\n 'minute': 'HH:mm:ss'\n }\n\t\t\t\t\t\t\t//format: 'MM/DD/YYYY HH:mm'\n\t\t\t\t\t\t\t// round: 'day'\n\t\t\t\t\t\t}\n }]\n }\n\n },\n 'line'\n );\n};\n\nutils.pieChart = function (container, form, url, unit) {\n 'use strict';\n utils.loadGraph(\n container,\n url,\n form.serialize(),\n {\n HtmlText: true,\n grid: {\n outline: \"\",\n verticalLines: false,\n horizontalLines: false\n },\n xaxis: { showLabels: false },\n yaxis: { showLabels: false },\n pie: {\n show: true,\n explode: 0,\n labelFormatter: function (total, value) {\n if (value * 100 / total >= 2) {\n return (100 * value / total).toFixed(1)+'%';\n }\n return '';\n }\n },\n mouse: {\n track: true,\n relative: true,\n trackFormatter: function (obj) {\n var roundedPercent = (obj.fraction * 100).toFixed(1);\n return obj.series.label + ': ' + obj.y + ' ' + unit + ' (' + roundedPercent + '%)';\n }\n },\n legend: {\n position: 'ne',\n backgroundColor: '#FFFFFF',\n labelBoxBorderColor: '#FFFFFF'\n }\n }\n );\n};\n\nutils.html = function (container, form, url) {\n 'use strict';\n var deferred;\n container.html('<p class=\"text-center\"><i class=\"fa fa-spinner fa-spin\"></i></p>');\n deferred = utils.asyncTask(url, form.serialize());\n deferred.done(function (data) {\n container.html(data);\n });\n deferred.fail(function () {\n container.html('<p class=\"text-center\"><i class=\"fa fa-ban\"></i></p>');\n });\n};\n\nutils.hashHelpers = utils.hashHelpers || {};\n\nutils.hashHelpers.updateLocation = function (id, form) {\n 'use strict';\n var hashObject = {};\n var formFields = form.find('input[type=text], select');\n hashObject[id] = {};\n formFields.each(function () {\n if (this.id !== \"\") {\n hashObject[id][this.name] = $(this).val();\n }\n });\n ui.updateLocationHash(hashObject);\n};\n\nutils.hashHelpers.setFormValues = function (formValues, form) {\n 'use strict';\n if (formValues) {\n $.each(formValues, function(key, value) {\n form.find('[name=' + key + ']').val(value);\n });\n form.find('select').trigger(\"chosen:updated\");\n }\n};\n\nutils.hashHelpers.loadFromUrlHash = function (hashId, form, callback) {\n 'use strict';\n var formValues = ui.getHashValueFromKey(hashId);\n\n if (formValues !== \"\") {\n utils.hashHelpers.setFormValues(formValues, form);\n if (callback) {\n callback();\n }\n } else {\n utils.hashHelpers.updateLocation(hashId, form);\n callback();\n }\n};\n// Include CSRF token in AJAX requests made via jQuery. Django CSRF protection\n// is described at https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/\n// NOTE: Per the HTTP specification, some methods are considered \"safe\".\n// Django does not apply CSRF protection to these. (Including the header for\n// these --- when it is meaningless to the server --- would be misleading...)\n$(document).ready(function () {\n 'use strict';\n var csrftoken = jQuery.cookie('csrftoken'),\n safeMethods = /^(GET|HEAD|OPTIONS|TRACE)$/;\n jQuery.ajaxSetup({\n crossDomain: false, // obviates need for sameOrigin test\n beforeSend: function (xhr, settings) {\n if (!safeMethods.test(settings.type)) {\n xhr.setRequestHeader('X-CSRFToken', csrftoken);\n }\n }\n });\n\n $('.load-chart-line').each(function (index) {\n var container = $(this),\n form = $(container.data('form')),\n url = container.data('url'),\n unit = container.data('unit'),\n hashId = 'barchart' + index,\n color = container.data('color'),\n colors = [];\n\n if (color === undefined || color === 'normal') {\n colors = [\n {\n fillColor: \"rgba(151,187,205,0.5)\",\n strokeColor: \"rgba(151,187,205,0.8)\",\n highlightFill: \"rgba(151,187,205,0.75)\",\n highlightStroke: \"rgba(151,187,205,1)\",\n },\n {\n fillColor: \"#dce5a9\",\n strokeColor: \"#92c36c\",\n highlightFill: \"#92c36c\",\n highlightStroke: \"#4c8b4b\",\n }\n ]\n } else if (color === 'cost') {\n colors = [\n {\n fillColor: \"#9e67ab\",\n strokeColor: \"#662c91\",\n highlightFill: \"#662c91\",\n highlightStroke: \"#4a2069\",\n },\n {\n fillColor: \"#d77fb4\",\n strokeColor: \"#b43894\",\n highlightFill: \"#b43894\",\n highlightStroke: \"#97307c\",\n }\n ]\n\n }\n\n utils.hashHelpers.loadFromUrlHash(hashId, form, function () {\n utils.lineChart(container, form, url, unit, colors);\n\n });\n\n form.find('button').click(function (event) {\n event.preventDefault();\n utils.hashHelpers.updateLocation(hashId, form);\n utils.lineChart(container, form, url, unit, colors);\n });\n\n });\n\n $('.load-chart-bar').each(function (index) {\n var container = $(this),\n form = $(container.data('form')),\n url = container.data('url'),\n unit = container.data('unit'),\n hashId = 'barchart' + index,\n color = container.data('color'),\n colors = [],\n showLegend = container.data('show-legend') === \"true\" ? true : false;\n\n if (color === undefined || color === 'normal') {\n colors = [\n {\n fillColor: \"rgba(151,187,205,0.5)\",\n strokeColor: \"rgba(151,187,205,0.8)\",\n highlightFill: \"rgba(151,187,205,0.75)\",\n highlightStroke: \"rgba(151,187,205,1)\",\n },\n {\n fillColor: \"#dce5a9\",\n strokeColor: \"#92c36c\",\n highlightFill: \"#92c36c\",\n highlightStroke: \"#4c8b4b\",\n }\n ]\n } else if (color === 'cost') {\n colors = [\n {\n fillColor: \"#9e67ab\",\n strokeColor: \"#662c91\",\n highlightFill: \"#662c91\",\n highlightStroke: \"#4a2069\",\n },\n {\n fillColor: \"#d77fb4\",\n strokeColor: \"#b43894\",\n highlightFill: \"#b43894\",\n highlightStroke: \"#97307c\",\n }\n ]\n\n }\n\n utils.hashHelpers.loadFromUrlHash(hashId, form, function () {\n utils.barChart(container, form, url, unit, colors);\n\n });\n\n form.find('button').click(function (event) {\n event.preventDefault();\n utils.hashHelpers.updateLocation(hashId, form);\n utils.barChart(container, form, url, unit, colors, showLegend);\n });\n\n });\n\n $('.load-chart-pie').each(function (index) {\n var container = $(this),\n form = $(container.data('form')),\n url = container.data('url'),\n unit = container.data('unit'),\n hashId = 'piechart' + index;\n\n utils.hashHelpers.loadFromUrlHash(hashId, form, function () {\n utils.pieChart(container, form, url, unit);\n\n });\n\n form.find('button').click(function (event) {\n event.preventDefault();\n utils.hashHelpers.updateLocation(hashId, form);\n utils.pieChart(container, form, url, unit);\n });\n\n });\n\n $('.load-html').each(function (index) {\n var container = $(this),\n form = $(container.data('form')),\n url = container.data('url'),\n hashId = 'html' + index;\n\n utils.hashHelpers.loadFromUrlHash(hashId, form, function () {\n utils.html(container, form, url);\n });\n\n form.find('button').click(function (event) {\n event.preventDefault();\n utils.hashHelpers.updateLocation(hashId, form);\n utils.html(container, form, url);\n });\n });\n});\n" }, { "alpha_fraction": 0.7225251793861389, "alphanum_fraction": 0.7226300239562988, "avg_line_length": 50.826087951660156, "blob_id": "bfe3e5713db672a8a71d6f23e05bd0420e379bd7", "content_id": "dbd1cc65cecaeb0dfa447f7eea33eb48ede36499", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9536, "license_type": "no_license", "max_line_length": 90, "num_lines": 184, "path": "/legacy/manage_measurementpoints/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\nfrom gridplatform.utils import utilitytypes\n\nfrom . import views\n\nfrom legacy.manage_measurementpoints.forms.imported import \\\n ImportedMeasurementPointForm\n\nfrom gridplatform.users.decorators import auth_or_redirect\n\nurlpatterns = patterns(\n 'legacy.manage_measurementpoints.views',\n url(r'^$',\n auth_or_redirect(TemplateView.as_view(\n template_name='manage_measurementpoints/'\n 'measurementpoint_list.html')),\n name='measurement_point-list'),\n url(r'^json/measurementpoints/$',\n 'list_json',\n name='measurement_point-json-list'),\n url(r'^update/(?P<pk>\\d+)$',\n 'measurementpoint_form',\n name='measurement_point-update'),\n url(r'^delete/$',\n 'measurementpoint_delete',\n name='measurement_point-delete'),\n\n # CONSUMPTION MEASUREMENT POINT CREATE VIEWS\n url(r'^consumption_measurement_point/electricity$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity),\n name='consumption_measurement_point-electricity-create'),\n url(r'^consumption_measurement_point/gas$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas),\n name='consumption_measurement_point-gas-create'),\n url(r'^consumption_measurement_point/water$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water),\n name='consumption_measurement_point-water-create'),\n url(r'^consumption_measurement_point/district_heating$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating),\n name='consumption_measurement_point-district_heating-create'),\n url(r'^consumption_measurement_point/oil$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil),\n name='consumption_measurement_point-oil-create'),\n\n # CONSUMPTION MEASUREMENT POINT UPDATE VIEW\n url(r'^consumption_measurement_point/(?P<pk>\\d+)$',\n views.ConsumptionMeasurementPointUpdateView.as_view(),\n name='consumption_measurement_point-update'),\n\n # IMPORTED MEASUREMENT POINTS CREATE VIEWS\n url(r'^imported_measurement_point/electricity$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n form_class=ImportedMeasurementPointForm,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n template_name='manage_measurementpoints/imported.html'),\n name='imported_measurement_point-electricity-create'),\n url(r'^imported_measurement_point/district_heating$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n form_class=ImportedMeasurementPointForm,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating,\n template_name='manage_measurementpoints/imported.html'),\n name='imported_measurement_point-district_heating-create'),\n url(r'^imported_measurement_point/water$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n form_class=ImportedMeasurementPointForm,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water,\n template_name='manage_measurementpoints/imported.html'),\n name='imported_measurement_point-water-create'),\n url(r'^imported_measurement_point/gas$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n form_class=ImportedMeasurementPointForm,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas,\n template_name='manage_measurementpoints/imported.html'),\n name='imported_measurement_point-gas-create'),\n url(r'^imported_measurement_point/oil$',\n views.ConsumptionMeasurementPointCreateView.as_view(\n form_class=ImportedMeasurementPointForm,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil,\n template_name='manage_measurementpoints/imported.html'),\n name='imported_measurement_point-oil-create'),\n\n # MISC MEASUREMENT POINT CREATE VIEWS\n url(r'^production_measurement_point$',\n views.ProductionMeasurementPointCreate.as_view(),\n name='production_measurement_point-create'),\n url(r'^current_measurement_point$',\n views.CurrentMeasurementPointCreate.as_view(),\n name='current_measurement_point-create'),\n url(r'^voltage_measurement_point$',\n views.VoltageMeasurementPointCreate.as_view(),\n name='voltage_measurement_point-create'),\n url(r'^power_measurement_point$',\n views.PowerMeasurementPointCreate.as_view(),\n name='power_measurement_point-create'),\n url(r'^reactive_power_measurement_point$',\n views.ReactivePowerMeasurementPointCreate.as_view(),\n name='reactive_power_measurement_point-create'),\n url(r'^reactive_energy_measurement_point$',\n views.ReactiveEnergyMeasurementPointCreate.as_view(),\n name='reactive_energy_measurement_point-create'),\n url(r'^power_factor_measurement_point$',\n views.PowerFactorMeasurementPointCreate.as_view(),\n name='power_factor_measurement_point-create'),\n url(r'^temperature_measurement_point/$',\n 'temperaturepoint_create_form',\n name='temperature_measurement_point-create'),\n url(r'^efficiency_measurement_point$',\n views.EfficiencyMeasurementPointCreate.as_view(),\n name='efficiency_measurement_point-create'),\n\n # CONSUMPTION MEASUREMENT POINT SUMMATION CREATE VIEWS\n url(r'^consumption_measurement_point_summation/electricity$',\n views.ConsumptionMeasurementPointSummationCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity),\n name='consumption_measurement_point_summation-electricity-create'),\n url(r'^consumption_measurement_point_summation/district_heating$',\n views.ConsumptionMeasurementPointSummationCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating),\n name=('consumption_measurement_point_summation-district_heating-create')), # noqa\n url(r'^consumption_measurement_point_summation/water$',\n views.ConsumptionMeasurementPointSummationCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water),\n name='consumption_measurement_point_summation-water-create'),\n url(r'^consumption_measurement_point_summation/gas$',\n views.ConsumptionMeasurementPointSummationCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas),\n name='consumption_measurement_point_summation-gas-create'),\n url(r'^consumption_measurement_point_summation/oil$',\n views.ConsumptionMeasurementPointSummationCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil),\n name='consumption_measurement_point_summation-oil-create'),\n\n # CONSUMPTION MEASUREMENT POINT SUMMATION UPDATE VIEW\n url(r'^consumption_measurement_point_summation/(?P<pk>\\d+)$',\n views.ConsumptionMeasurementPointSummationUpdateView.as_view(),\n name='consumption_measurement_point_summation-update'),\n\n # CONSUMPTION MULTIPLICATION POINT CREATE VIEWS\n url(r'^consumption_multiplication_point/electricity$',\n views.ConsumptionMultiplicationPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity),\n name='consumption_multiplication_point-electricity-create'),\n url(r'^consumption_multiplication_point/district_heating$',\n views.ConsumptionMultiplicationPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.district_heating),\n name='consumption_multiplication_point-district_heating-create'),\n url(r'^consumption_multiplication_point/water$',\n views.ConsumptionMultiplicationPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water),\n name='consumption_multiplication_point-water-create'),\n url(r'^consumption_multiplication_point/gas$',\n views.ConsumptionMultiplicationPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas),\n name='consumption_multiplication_point-gas-create'),\n url(r'^consumption_multiplication_point/oil$',\n views.ConsumptionMultiplicationPointCreateView.as_view(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil),\n name='consumption_multiplication_point-oil-create'),\n\n # CONSUMPTION MULTIPLICATION POINT UPDATE VIEW\n url(r'^consumption_multiplication_point/(?P<pk>\\d+)$',\n views.ConsumptionMultiplicationPointUpdateView.as_view(),\n name='consumption_multiplication_point-update'),\n\n # DISTRICT HEATING MEASUREMENT POINT CREATE VIEW\n url(r'^district_heating_measurement_point$',\n views.DistrictHeatingMeasurementPointCreateView.as_view(),\n name='district_heating_measurement_point-create'),\n\n # DISTRICT HEATING MEASUREMENT POINT UPDATE VIEW\n url(r'^district_heating_measurement_point/(?P<pk>\\d+)$',\n views.DistrictHeatingMeasurementPointUpdateView.as_view(),\n name='district_heating_measurement_point-update'),\n)\n" }, { "alpha_fraction": 0.5821428298950195, "alphanum_fraction": 0.5976190567016602, "avg_line_length": 32.599998474121094, "blob_id": "3d0a419c040dd8e8e72f97d735c9506c074cc1b6", "content_id": "93f31eab7c1742f5575ae39d255c38a1fb5c7e0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 840, "license_type": "no_license", "max_line_length": 72, "num_lines": 25, "path": "/legacy/display_widgets/templatetags/relay.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom django.contrib.staticfiles.templatetags.staticfiles import static\n\nregister = template.Library()\n\n\[email protected]_tag\ndef relay_image(meter):\n if meter:\n agent = meter.agent\n if not agent.online:\n return '<img src=\"' + static('images/relay_offline.png') + \\\n '\" height=\"16\" width=\"16\" class=\"relayStatus\">'\n state = 'relay_off.png'\n if meter.relay_on:\n state = 'relay_on.png'\n return '<img src=\"' + static('images/' + state) + \\\n '\" height=\"16\" width=\"16\" class=\"relayStatus\">'\n else:\n return '<img src=\"' + static('images/transparent.png') + \\\n '\" height=\"16\" width=\"16\" class=\"relayStatus\">'\n" }, { "alpha_fraction": 0.517494797706604, "alphanum_fraction": 0.5381051301956177, "avg_line_length": 33.772220611572266, "blob_id": "86e78216c98c7257c9092e04bdcd7921483d4d2e", "content_id": "f294b21fe1e0744169186e2023ef5ea684ad9959", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6259, "license_type": "no_license", "max_line_length": 71, "num_lines": 180, "path": "/energymanager/energy_projects/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport pytz\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\nfrom gridplatform.customer_datasources.models import CustomerDataSource\nfrom gridplatform.datasources.models import RawData\n\nfrom .models import LedLightProject\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass LedLightProjectTest(TestCase):\n def setUp(self):\n self.provider = Provider.objects.create()\n self.user = User(provider=self.provider)\n self.customer = Customer(provider=self.provider)\n self.customer.save()\n\n def test_save_and_load(self):\n with replace_user(self.user), replace_customer(self.customer):\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4\n )\n\n loaded_project = LedLightProject.objects.get(\n id=project.id)\n\n self.assertEqual(\n project.name_plain,\n loaded_project.name_plain)\n\n def test_measured_price_without_datasource(self):\n with replace_user(self.user), replace_customer(self.customer):\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4\n )\n\n self.assertEqual(\n project.measured_price(),\n None)\n\n def test_measured_price_with_datasource_without_data(self):\n with replace_user(self.user), replace_customer(self.customer):\n data_source = CustomerDataSource.objects.create(\n name_plain='test name',\n unit='watt*hour')\n\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4,\n datasource=data_source\n )\n\n self.assertEqual(\n project.measured_price(),\n 0)\n\n def test_measured_price(self):\n with replace_user(self.user), replace_customer(self.customer):\n data_source = CustomerDataSource.objects.create(\n name_plain='test name',\n unit='watt')\n\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4,\n datasource=data_source\n )\n\n timestamp = datetime.datetime(\n 2015, 6, 2, 10, 0, 0, tzinfo=pytz.timezone('UTC'))\n startvalue = 0\n for x in xrange(1, 120):\n RawData.objects.create(\n datasource=data_source,\n value=10,\n unit='milwatt*',\n timestamp=timestamp\n )\n startvalue += 10\n timestamp += datetime.timedelta(minutes=1)\n\n self.assertEqual(\n project.measured_price(),\n 1.44)\n\n def test_calculated_previous_price(self):\n with replace_user(self.user), replace_customer(self.customer):\n data_source = CustomerDataSource.objects.create(\n name_plain='test name',\n unit='watt*hour')\n\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4,\n datasource=data_source\n )\n\n timestamp = datetime.datetime(\n 2015, 6, 2, 10, 0, 0, tzinfo=pytz.timezone('UTC'))\n startvalue = 0\n for x in xrange(1, 120):\n RawData.objects.create(\n datasource=data_source,\n value=startvalue,\n unit='milwatt*hour',\n timestamp=timestamp\n )\n startvalue += 10\n timestamp += datetime.timedelta(minutes=1)\n\n self.assertEqual(\n project.calculated_previous_price(),\n 3.456)\n\n def test_calculate_savings(self):\n with replace_user(self.user), replace_customer(self.customer):\n data_source = CustomerDataSource.objects.create(\n name_plain='test name',\n unit='watt*hour')\n\n project = LedLightProject.objects.create(\n name_plain='Office',\n previous_tube_count=32,\n previous_consumption_per_tube=45,\n led_tube_count=30,\n led_consumption_per_tube=20,\n price=2.4,\n datasource=data_source\n )\n\n timestamp = datetime.datetime(\n 2015, 6, 2, 10, 0, 0, tzinfo=pytz.timezone('UTC'))\n startvalue = 0\n for x in xrange(1, 120):\n RawData.objects.create(\n datasource=data_source,\n value=startvalue,\n unit='milwatt*hour',\n timestamp=timestamp\n )\n startvalue += 10\n timestamp += datetime.timedelta(minutes=1)\n\n self.assertEqual(\n project.calculate_savings(),\n 2.016)\n" }, { "alpha_fraction": 0.6231802105903625, "alphanum_fraction": 0.6233692765235901, "avg_line_length": 32.687896728515625, "blob_id": "f40bed5a88701a7c818f97a6f8c11a9145a42752", "content_id": "7be48b1a129c942ca88df5c8c691f6ff5ee07a13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5289, "license_type": "no_license", "max_line_length": 78, "num_lines": 157, "path": "/gridplatform/utils/samples.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nDefiens various sample types.\n\n.. class:: RangedSample(from_timestamp, to_timestamp, physical_quantity)\n\n A sample in the forms of a :class:`.PhysicalQuantity` covering a\n timestamp range.\n\n.. class:: PointSample(timestamp, physical_quantity)\n\n A sample in the forms of a :class:`.PhysicalQuantity` of a point\n in time.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\nimport datetime\nfrom collections import namedtuple\n\nfrom .unitconversion import PhysicalQuantity\nfrom .decorators import deprecated\n\n\nRangedSample = namedtuple(\n 'RangedSample', ('from_timestamp', 'to_timestamp', 'physical_quantity'))\n\n\nPointSample = namedtuple(\n 'PointSample', ('timestamp', 'physical_quantity'))\n\n\n_Sample = namedtuple(\n 'Sample', ('from_timestamp', 'to_timestamp', 'physical_quantity',\n 'cachable', 'extrapolated'))\n\n\nclass Sample(_Sample):\n \"\"\"\n Class for measurement/data samples.\n\n :deprecated: This class is deprecated (due to overly complex\n implementation of features not needed), use\n :class:`.RangedSample` or :class:`PointSample` instead. The\n implementation resembles a C-style union of\n :class:`.RangedSample` and :class:`PointSample`.\n \"\"\"\n __slots__ = ()\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Immutable subclass of tuple --- members are set up in __new__; this is\n for sanity checks, and to support use in multiple inheritance.\n\n :warning: Does not support multiple inheritance, as ``__init__()`` is\n not forwarded to super. Forwarding causes run-time warnings, and\n should only be introduced when needed.\n \"\"\"\n self._check_valid()\n\n def _check_valid(self):\n \"\"\"\n Basic checks that this specifies a valid sample.\n \"\"\"\n assert isinstance(self.from_timestamp, datetime.datetime), \\\n 'not a datetime: %r' % (self.from_timestamp,)\n assert self.from_timestamp.tzinfo is not None\n assert isinstance(self.to_timestamp, datetime.datetime), \\\n 'not a datetime: %r' % (self.to_timestamp,)\n assert self.to_timestamp.tzinfo is not None\n assert self.from_timestamp <= self.to_timestamp, \\\n 'from_timestamp=%r > to_timestamp=%r' % (\n self.from_timestamp, self.to_timestamp)\n assert isinstance(self.physical_quantity, PhysicalQuantity), \\\n 'not a PhysicalQuantity: %r' % (self.physical_quantity,)\n assert isinstance(self.cachable, bool)\n assert isinstance(self.extrapolated, bool)\n\n def _replace(self, **kwargs):\n \"\"\"\n Return a new Sample object replacing specified fields with new\n values. Taskes the \"extra\" parameter ``timestamp`` to set\n both ``from_timestamp`` and ``to_timestamp`` for a point\n sample.\n \"\"\"\n if 'timestamp' in kwargs:\n if not self.is_point:\n raise ValueError('Setting timestamp not legal for range ')\n if 'from_timestamp' in kwargs:\n raise ValueError(\n 'Cannot specify both from_timestamp and timestamp')\n if 'to_timestamp' in kwargs:\n raise ValueError(\n 'Cannot specify both to_timestamp and timestamp')\n timestamp = kwargs.pop('timestamp')\n kwargs['from_timestamp'] = timestamp\n kwargs['to_timestamp'] = timestamp\n obj = super(Sample, self)._replace(**kwargs)\n obj._check_valid()\n return obj\n\n def in_closed_interval(self, from_timestamp, to_timestamp):\n \"\"\"\n Check whether the time point or range defined by this sample is\n entirely contained within the closed interval specified by\n [``from_timestamp``, ``to_timestamp``].\n\n :param from_timestamp: The start-point of the given range.\n :param to_timestamp: The end-point of the given range.\n \"\"\"\n return from_timestamp <= self.from_timestamp <= \\\n self.to_timestamp <= to_timestamp\n\n @property\n def timestamp(self):\n \"\"\"\n For point samples --- samples with identical ``from_timestamp`` and\n ``to_timestamp`` --- return the timestamp.\n \"\"\"\n if not self.is_point:\n raise ValueError('%r is not a point sample.' % (self,))\n return self.from_timestamp\n\n @property\n def is_point(self):\n \"\"\"\n A point sample is a sample with ``from_timestamp`` equal to\n ``to_timestamp``.\n \"\"\"\n return self.from_timestamp == self.to_timestamp\n\n @property\n def is_range(self):\n \"\"\"\n A range sample is a sample with ``from_timestamp`` strictly less than\n ``to_timestamp``.\n \"\"\"\n return self.from_timestamp < self.to_timestamp\n\n @property\n def uncachable(self):\n return not self.cachable\n\n def __nonzero__(self):\n return bool(self.physical_quantity)\n\n\ndef wrap_ranged_sample(sample):\n return Sample(\n sample.from_timestamp, sample.to_timestamp, sample.physical_quantity,\n True, False)\n\n\ndef wrap_ranged_sample_sequence(ranged_sample_sequence):\n return itertools.imap(wrap_ranged_sample, ranged_sample_sequence)\n" }, { "alpha_fraction": 0.6606451869010925, "alphanum_fraction": 0.6619355082511902, "avg_line_length": 25.724138259887695, "blob_id": "355543bfe9a0cdb05022a26dbd82dfe9c715aa4c", "content_id": "6ec5e53ffa31640f7e01202d487e9c5857e1e2b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 78, "num_lines": 29, "path": "/legacy/measurementpoints/models/storeddataseries.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .dataseries import DataSeries\n\n\nclass StoredDataSeries(DataSeries):\n \"\"\"\n A non-abstract proxy model of DataSeries that is intended for working with\n StoredData.\n\n @see L{ImportedMeasurementPoint}.\n \"\"\"\n\n class Meta(DataSeries.Meta):\n proxy = True\n verbose_name = _('stored data series')\n verbose_name = _('stored data series')\n app_label = 'measurementpoints'\n\n def get_recursive_condense_resolution(self, resolution):\n \"\"\"\n Data is stored directly, and recursive condensation is hardly ever\n bennificial.\n \"\"\"\n return None\n" }, { "alpha_fraction": 0.706944465637207, "alphanum_fraction": 0.7076388597488403, "avg_line_length": 52.33333206176758, "blob_id": "41abe2ce2669a3ecc438a0ce1f5b4189f9f52b29", "content_id": "d5383236b7428c6f917a940a7689decec2a2fadf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 95, "num_lines": 27, "path": "/gridplatform/customers/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom .models import Customer\n\n\nclass CustomerSerializer(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n vat = serializers.CharField(source='vat_plain', required=False)\n address = serializers.CharField(source='address_plain', required=False)\n postal_code = serializers.CharField(source='postal_code_plain', required=False)\n city = serializers.CharField(source='city_plain', required=False)\n phone = serializers.CharField(source='phone_plain', required=False)\n production_a_unit = serializers.CharField(source='production_a_unit_plain', required=False)\n production_b_unit = serializers.CharField(source='production_b_unit_plain', required=False)\n production_c_unit = serializers.CharField(source='production_c_unit_plain', required=False)\n production_d_unit = serializers.CharField(source='production_d_unit_plain', required=False)\n production_e_unit = serializers.CharField(source='production_e_unit_plain', required=False)\n\n class Meta:\n model = Customer\n fields = ('url', 'id', 'name', 'vat', 'address', 'postal_code', 'city',\n 'phone', 'timezone', 'production_a_unit',\n 'production_b_unit', 'production_c_unit',\n 'production_d_unit', 'production_e_unit')\n" }, { "alpha_fraction": 0.5773074626922607, "alphanum_fraction": 0.5861257910728455, "avg_line_length": 27.830509185791016, "blob_id": "2b84c2963f8c389054169ec0f62a68ea5124a64a", "content_id": "8e5499cf23e7cf4e849da91693877360d89fbb23", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1701, "license_type": "no_license", "max_line_length": 71, "num_lines": 59, "path": "/gridagentserver/client.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from string import hexdigits\nfrom struct import Struct\nimport json\nimport re\n\nimport pika\n\n\nmqhost = 'engine.grid-manager.com'\n#mqhost = 'localhost'\n\n\ndef send_message(routing_key, message, verbose=False, dry_run=False):\n if not dry_run:\n connection = pika.BlockingConnection(pika.ConnectionParameters(\n host=mqhost))\n channel = connection.channel()\n channel.exchange_declare(exchange='agentservers',\n exchange_type='topic')\n channel.basic_publish(exchange='agentservers',\n routing_key=routing_key,\n properties=pika.BasicProperties(\n content_type='application/json'),\n body=json.dumps(message))\n connection.close()\n if verbose:\n print 'message:\\n%s\\n(routing key %s)' % (\n json.dumps(message, indent=2), routing_key)\n if dry_run:\n print '(not sent)'\n else:\n print '(sent)'\n\n\ndef normalise_mac(mac, bytes=6):\n norm = filter(lambda c: c in hexdigits, mac.lower())\n if len(norm) != bytes * 2:\n raise Exception('invalid mac address %s (%s)' % (mac, norm))\n return norm\n\n\nnumber_splitter = re.compile(r'^(\\d+)(.*)$')\n\n\ndef normalise_version(version):\n major, minor, revision = version.split('.')\n revision, extra = number_splitter.match(revision).groups()\n return (int(major), int(minor), int(revision), extra)\n\n\nuint64 = Struct('!Q')\nint64 = Struct('!q')\n\n\ndef gridpoint_id(mac):\n n = int(mac, base=16)\n m, = int64.unpack(uint64.pack(n))\n # 1 for connection type ZigBee\n return {'connection_type': 1, 'id': m}\n" }, { "alpha_fraction": 0.6224256157875061, "alphanum_fraction": 0.6270022988319397, "avg_line_length": 28.133333206176758, "blob_id": "4600fa997e0a878720ffe24b7954ef08602447f0", "content_id": "bacb1e035f551596215d1e19427db3cd8633d778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 437, "license_type": "no_license", "max_line_length": 119, "num_lines": 15, "path": "/energymanager/provider_site/templates/provider_site/customer_list.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends \"provider_site/base.html\" %}\n{% load i18n %}\n{% load bootstrap_tags %}\n\n\n{% block content %}\n\n{% panel _(\"Customers\") search=True %}\n<a href=\"{% url 'provider_site:customer-create' %}\" title=\"{% trans 'Add' %}\">\n <i class=\"fa fa-plus\"></i>\n</a>\n{% endpanelbuttons %}\n<div class=\"content-loader\" data-url=\"{% url 'provider_site:customer-list-content' %}\" data-orderby=\"name_plain\"></div>\n{% endpanel %}\n{% endblock content %}\n" }, { "alpha_fraction": 0.72124183177948, "alphanum_fraction": 0.7235293984413147, "avg_line_length": 35, "blob_id": "a8f791efe28e0abd298db4ac0a667bdfedda0156", "content_id": "788080d806f531e19544dd7d715d60d77eb8d3f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3060, "license_type": "no_license", "max_line_length": 76, "num_lines": 85, "path": "/gridplatform/datasequences/viewsets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import get_object_or_404\nfrom rest_framework import viewsets\nfrom rest_framework.decorators import action\nimport rest_framework.reverse\n\nfrom gridplatform.datasources.viewsets import RawDataViewSet\nfrom gridplatform.datasequences.views import HourlyDataView\nfrom gridplatform.rest.viewsets import NestedMixin\n\nfrom . import models\nfrom . import serializers\n\n\nclass HourlyEnergyPerVolumeView(NestedMixin, HourlyDataView):\n method_name = 'rate_sequence'\n\n def get(self, request, datasequence_id=None, format=None):\n datasequence = get_object_or_404(\n models.EnergyPerVolumeDataSequence, pk=datasequence_id)\n timezone = datasequence.customer.timezone\n return self._get(request, datasequence, timezone)\n\n\nclass EnergyPerVolumeDataSequence(viewsets.ModelViewSet):\n model = models.EnergyPerVolumeDataSequence\n serializer_class = serializers.EnergyPerVolumeDataSequence\n filter_fields = ('name', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def hourly(self, request, pk=None):\n view_fn = HourlyEnergyPerVolumeView.as_view()\n return view_fn(request, datasequence_id=pk)\n\n\nclass EnergyPerVolumePeriod(NestedMixin, viewsets.ModelViewSet):\n model = models.EnergyPerVolumePeriod\n serializer_class = serializers.EnergyPerVolumePeriod\n\n def create(self, request, *args, **kwargs):\n request.DATA['datasequence'] = rest_framework.reverse.reverse(\n viewname='api:datasequences:energypervolumedatasequence-detail',\n kwargs={\n 'pk': kwargs.pop('datasequence_id'),\n }\n )\n return super(EnergyPerVolumePeriod, object).create(\n request, *args, **kwargs)\n\n\nclass NonaccumulationDataSequence(viewsets.ModelViewSet):\n model = models.NonaccumulationDataSequence\n serializer_class = serializers.NonaccumulationDataSequence\n filter_fields = ('name', 'unit', 'customer')\n\n @action(methods=['GET', 'OPTIONS'])\n def raw_data(self, request, pk=None):\n return RawDataViewSet().list(request, datasource_id=pk)\n\n\nclass NonaccumulationParentMixin(object):\n def create(self, request, *args, **kwargs):\n request.DATA['datasequence'] = rest_framework.reverse.reverse(\n viewname='api:datasequences:nonaccumulationdatasequence-detail',\n kwargs={\n 'pk': kwargs.pop('datasequence_id'),\n }\n )\n return super(NonaccumulationParentMixin, object).create(\n request, *args, **kwargs)\n\n\nclass NonaccumulationPeriod(\n NestedMixin, NonaccumulationParentMixin, viewsets.ModelViewSet):\n model = models.NonaccumulationPeriod\n serializer_class = serializers.NonaccumulationPeriod\n\n\nclass NonaccumulationOfflineTolerance(\n NestedMixin, NonaccumulationParentMixin, viewsets.ModelViewSet):\n model = models.NonaccumulationOfflineTolerance\n serializer_class = serializers.NonaccumulationOfflineTolerance\n" }, { "alpha_fraction": 0.6001855134963989, "alphanum_fraction": 0.6011132001876831, "avg_line_length": 29.799999237060547, "blob_id": "41a9fc1c827a15560dd997efa9d187f959424512", "content_id": "7a28f76780c5cbc44565fb5019566dbeca92fcf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1078, "license_type": "no_license", "max_line_length": 53, "num_lines": 35, "path": "/legacy/manage_rules/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView\n\n\nurlpatterns = patterns(\n 'legacy.manage_rules.views',\n url(r'^$', TemplateView.as_view(\n template_name='manage_rules/rule_list.html'),\n name='manage_rules-list'),\n url(r'^json/rule/$',\n 'rule_list_json',\n name='manage_rules-list-json'),\n url(r'^form/(?P<pk>\\d+)$',\n 'form',\n name='manage_rules-form'),\n url(r'^minimizerule/$',\n 'minimizerule_form',\n name='manage_rules-minimizerule_form'),\n url(r'^minimizerule/(?P<pk>\\d+)$',\n 'minimizerule_form',\n name='manage_rules-minimizerule_form'),\n url(r'^triggeredrule/$',\n 'triggeredrule_form',\n name='manage_rules-triggeredrule_form'),\n url(r'^triggeredrule/(?P<pk>\\d+)$',\n 'triggeredrule_form',\n name='manage_rules-triggeredrule_form'),\n url(r'^delete/$',\n 'delete',\n name='manage_rules-delete'),\n)\n" }, { "alpha_fraction": 0.6189376711845398, "alphanum_fraction": 0.6215770244598389, "avg_line_length": 35.51807403564453, "blob_id": "f555f600eac47b84a47e724bc97428a3bc38a148", "content_id": "4e6b297d39a4065f859d751719565278cd1a2719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3031, "license_type": "no_license", "max_line_length": 83, "num_lines": 83, "path": "/legacy/nordpool/management/commands/import_nordpool_spot_prices.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport ftplib\n\nfrom isoweek import Week\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.transaction import commit_on_success\n\nfrom gridplatform.global_datasources.models import GlobalDataSource\nfrom legacy.nordpool.importer import fetch_import_week\nfrom legacy.nordpool.conf import settings\n\n\ndef create_nordpool_datasources(spotprices):\n \"\"\"\n The list of spot prices in conf.py are the list of currently supported\n spot prices. If GlobalDataSources corresponding to them do not exist,\n create them by calling this funnction before import continues. If there are\n other nordpool GlobalDataSoures (app_label='nordpool') then that must mean\n that we previously supported a different set of spot prices. They are just\n left alone and should no longer get new data imported.\n \"\"\"\n for spotprice in spotprices:\n if not GlobalDataSource.objects.filter(\n app_label='nordpool',\n codename=spotprice['CODENAME'],\n country=spotprice['COUNTRY']).exists():\n GlobalDataSource.objects.create(\n unit=spotprice['UNIT'],\n name=spotprice['NAME'],\n app_label='nordpool',\n codename=spotprice['CODENAME'],\n country=spotprice['COUNTRY'])\n\n\nclass Command(BaseCommand):\n args = '[week [year]]'\n help = 'Import data for all currently supported Nordpool spot prices ' \\\n 'for specific week plus one. Data is imported into global data sources, ' \\\n 'creating new ones if needed. Week/year defaults to current week/year.'\n\n def handle(self, *args, **options):\n week_number = None\n year = None\n\n try:\n week_number = int(args[0])\n year = int(args[1])\n except IndexError:\n pass\n\n today = datetime.datetime.now().date()\n if week_number is None:\n assert year is None\n this_week = Week.withdate(today)\n elif year is None:\n assert week_number is not None\n year = today.year\n this_week = Week(year, week_number)\n else:\n assert week_number is not None\n assert year is not None\n this_week = Week(year, week_number)\n next_week = this_week + 1\n\n spotprices = settings.NORDPOOL_SPOT_PRICES\n create_nordpool_datasources(spotprices)\n try:\n with commit_on_success():\n fetch_import_week(this_week.year, this_week.week, spotprices)\n with commit_on_success():\n fetch_import_week(next_week.year, next_week.week, spotprices)\n except ftplib.error_perm as e:\n if e.args[0].startswith('550'):\n # File not found error --- usually caused by file not yet\n # uploaded to Nordpool FTP server...\n pass\n else:\n raise\n" }, { "alpha_fraction": 0.7278911471366882, "alphanum_fraction": 0.7291280031204224, "avg_line_length": 34.93333435058594, "blob_id": "920255e655cad8668e185f8d4e39612c0c61f2c7", "content_id": "51d4dbcf9c2e33d7a13831a075550d7b690a2695", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1617, "license_type": "no_license", "max_line_length": 145, "num_lines": 45, "path": "/documentation/source/security.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "********\nSecurity\n********\n\nVarious security mechanisms are used in order to maximise the security of the\nGridPlatform. They are explained in this chapter.\n\n\nSecure Socket Layer (SSL)\n=========================\nWhen deploying GridPlatform to a production environment, the web servers must\nalways be set up with valid SSL certificates and web server communication must\nonly allow SSL connections from clients.\n\n\nCross Site Request Forgery (CSRF) protection\n============================================\nCRSF protection is part of the Django framework. Refer to the Django documentation for details (https://docs.djangoproject.com/en/dev/ref/csrf/).\n\n\nModel Permissions\n=================\nThe permission and groups available in ``django.contrib.auth`` are use\nimplement access control. Refer to the Django documentation for details.\n\n\nOther Access Control mechanisms\n===============================\n\nThe user model has a ``user_type`` field, which in GridPortal 2.0 is used for access control purposes.\n\n\nAPI tokens\n==========\n\nTo allow secure access to the GridPlatform via the REST API an API key scheme\nhas been implemented. API users can be created using the Energy Manager\nadministration site and a key generated for them. The key is only shown on\ncreation, and if in any way forgotten a new must be generated for that user.\n\nThese keys are as confidential as user names as password as they enable the\nowner to login and decrypt the data belonging to the customer associated with that user.\n\nIn the case of provider API users the user has the ability to decrypt all data\nfor all customers belonging to that provider.\n" }, { "alpha_fraction": 0.585970938205719, "alphanum_fraction": 0.5996578335762024, "avg_line_length": 27.512195587158203, "blob_id": "147c7f34a012bbf787de479813a82e8be190bb6f", "content_id": "312c9158ab49a70f6454e5ed7f632e477d6c58d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/legacy/energinet_co2/ftpclient.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport ftplib\n\nfrom gridplatform.utils.ftpclient import ftpconnection\n\nfrom .conf import settings\n\n\ndef _fetch_energinet(base_dir, filename):\n assert settings.ENERGINET_CO2_HOST\n assert settings.ENERGINET_CO2_USER\n assert settings.ENERGINET_CO2_PASS\n with ftpconnection(settings.ENERGINET_CO2_HOST,\n settings.ENERGINET_CO2_USER,\n settings.ENERGINET_CO2_PASS) as ftp:\n ftp.cwd(base_dir)\n try:\n lines = []\n ftp.retrlines('RETR %s' % (filename,), lines.append)\n return lines\n except ftplib.error_perm as e:\n if e.args[0].startswith('550'):\n # \"file unavailable\" (FTP error code 550)\n return None\n else:\n raise\n\n\ndef fetch_forecast(date):\n return _fetch_energinet(\n 'CO2Prognoser',\n '{}_CO2prognose.txt'.format(date.strftime('%Y%m%d')))\n\n\ndef fetch_online(date):\n return _fetch_energinet(\n 'Onlinedata',\n '{}_onlinedata.txt'.format(date.strftime('%Y%m%d')))\n" }, { "alpha_fraction": 0.6517218947410583, "alphanum_fraction": 0.6523716449737549, "avg_line_length": 33.977272033691406, "blob_id": "98eb16018574a54f86d6445b775f910e2f0ad21a", "content_id": "109e87b38483496b14e269e04d6b8d64691b0dff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1539, "license_type": "no_license", "max_line_length": 76, "num_lines": 44, "path": "/legacy/display_widgets/templatetags/widgets.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n# from django import template\n# from django.utils import simplejson\n# from django.utils.safestring import mark_safe\n\n# from ..models import Dashboard\n# from ..views import dashboard_data\n\n# register = template.Library()\n\n\n# @register.simple_tag(takes_context=True)\n# def user_dashboard(context):\n# request = context['request']\n# user = context['user']\n# try:\n# dashboard = Dashboard.objects.prefetch_related(\n# 'container_set',\n# 'container_set__element_set',\n# 'container_set__element_set__content_object'\n# ).get(user=user, type=Dashboard.DASHBOARD)\n# except Dashboard.DoesNotExist:\n# dashboard = Dashboard.objects.create(\n# user=user, type=Dashboard.DASHBOARD)\n# return mark_safe(simplejson.dumps(dashboard_data(request, dashboard)))\n\n\n# @register.simple_tag(takes_context=True)\n# def user_sidepane(context):\n# request = context['request']\n# user = context['user']\n# try:\n# dashboard = Dashboard.objects.prefetch_related(\n# 'container_set',\n# 'container_set__element_set',\n# 'container_set__element_set__content_object'\n# ).get(user=user, type=Dashboard.SIDEPANE)\n# except Dashboard.DoesNotExist:\n# dashboard = Dashboard.objects.create(\n# user=user, type=Dashboard.SIDEPANE)\n# return mark_safe(simplejson.dumps(dashboard_data(request, dashboard)))\n" }, { "alpha_fraction": 0.5845043659210205, "alphanum_fraction": 0.5907058119773865, "avg_line_length": 35.77704620361328, "blob_id": "1f4dfd1a30f87332566e9e92f7850d993d40c110", "content_id": "6f8896837ce93ee931167763978436cf5ed88ef1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 50317, "license_type": "no_license", "max_line_length": 79, "num_lines": 1368, "path": "/legacy/projects/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom collections import namedtuple\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom fractions import Fraction\nimport itertools\n\nfrom django.db import models\nfrom django.db.models import Sum\nfrom django.forms import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.functional import cached_property\nfrom django.db.models import Q\n\nimport pytz\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import deprecated\nfrom gridplatform.utils import unix_timestamp\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.legacy_utils.preferredunits import get_preferred_unit_converter\nfrom legacy.measurementpoints import default_unit_for_data_series\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import DataSeries\n\n\ndef payback_period_years(investment, subsidy, annual_cost_savings):\n \"\"\"\n Calculate payback period in years given an investment, subsidy (possibly\n 0), and annual cost savings. If annual_cost_savings <= 0 then None is\n returned.\n \"\"\"\n if annual_cost_savings:\n return (investment - subsidy) / annual_cost_savings\n else:\n return None\n\n\nclass BenchmarkProjectManager(models.Manager):\n def get_query_set(self):\n customer = get_customer()\n user = get_user()\n qs = super(BenchmarkProjectManager, self).get_query_set()\n\n if customer is None or user is None:\n assert user is None\n return qs\n\n qs = qs.filter(customer=customer)\n\n constraints = CollectionConstraint.objects.filter(\n userprofile__user=user)\n if constraints:\n with replace_user(None):\n customer_collections = set(\n Collection.objects.all().values_list('id', flat=True))\n user_collections = set(\n Collection.objects.all().values_list('id', flat=True))\n hidden_collections = customer_collections - user_collections\n qs = qs.exclude(\n baseline_measurement_points__in=hidden_collections)\n qs = qs.exclude(result_measurement_points__in=hidden_collections)\n return qs\n\n\nclass BenchmarkProject(EncryptedModel):\n \"\"\"\n Django model for holding benchmark projects.\n\n @note: The contents of this model is probably generic enough for all kinds\n of projects, and a role/delegate scheme might be applied in the future.\n This change is expected to be small, and therefore only prematurely\n mentioned here, and not prematurely implemented.\n\n @ivar name: The name of this C{Project}.\n\n @ivar customer: A customer which the project is bound to.\n\n @ivar background: The background of this C{Project}.\n\n @ivar customer: The customer owning this C{Project}.\n\n @ivar goal: The goal of this C{BenchmarkProject}. This value is a\n percentage with two decimals between 0 % and 100 %.\n\n @ivar currency_unit: Legacy field. Should always equal the customers\n currency_unit for new projects.\n\n @invariant: currency_unit may not be modified after a C{Project} has been\n saved the first time. Changing currency_unit potentially invalidates all\n involved MeasurementPoints.\n\n @ivar utility_type: With current specifications, C{BenchmarkProject}s are\n not well-defined if they mix L{MeasurementPoint}s of different data\n origin. This field serves to help validate that only L{MeasurementPoint}s\n of same data origin are selected.\n\n @invariant: C{utility_type} may not be modified after a C{Project} has been\n saved the first time. Changing C{utility_type} for sure will invalidate\n all involved L{MeasurementPoint}s.\n\n @bug: Consumption unit is not stored. Consumption values are invalidated\n when customer changes consumption unit.\n \"\"\"\n name = EncryptedCharField(\n _('name'),\n max_length=50)\n customer = models.ForeignKey(\n Customer, on_delete=models.PROTECT, editable=False, blank=True,\n default=get_customer, verbose_name=_('customer'))\n background = EncryptedTextField(_('background'), blank=True)\n expectations = EncryptedTextField(_('expectations'), blank=True)\n actions = EncryptedTextField(_('actions'), blank=True)\n\n subsidy = models.DecimalField(\n _('subsidy'), blank=True, null=True, max_digits=19, decimal_places=2)\n\n result = EncryptedTextField(_('result'), blank=True)\n comments = EncryptedTextField(\n _('comments'),\n blank=True,\n help_text=_(\n 'Comments about project schedules, project changes, contact '\n 'persons and so on.'))\n # FIMXE: Rename to 'months' or 'duration_in_months'.\n runtime = models.IntegerField(\n _('project duration'),\n default=1)\n\n estimated_yearly_consumption_costs_before = models.DecimalField(\n _('estimated yearly costs before'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n\n estimated_yearly_consumption_before = models.DecimalField(\n _('estimated yearly consumption before'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n\n estimated_co2_emissions_before = models.DecimalField(\n _(u'estimated yearly CO₂ emissions before'), blank=True, null=True,\n max_digits=19, decimal_places=2)\n\n expected_savings_in_yearly_total_costs = models.DecimalField(\n _('expected savings in yearly total costs'), default=0, max_digits=19,\n decimal_places=2)\n\n expected_savings_in_yearly_consumption_after = models.DecimalField(\n _('expected savings in yearly consumption after'), default=0,\n max_digits=19, decimal_places=2)\n\n expected_reduction_in_yearly_co2_emissions = models.DecimalField(\n _('expected reduction in yearly CO₂ emissions'), default=0,\n max_digits=19, decimal_places=2)\n\n utility_type = models.IntegerField(\n _('utility type'), choices=utilitytypes.METER_CHOICES)\n\n include_measured_costs = models.BooleanField(\n _('include measured costs'),\n default=False)\n\n baseline_from_timestamp = models.DateTimeField(blank=True, null=True)\n baseline_to_timestamp = models.DateTimeField(blank=True, null=True)\n baseline_measurement_points = models.ManyToManyField(\n ConsumptionMeasurementPoint,\n related_name='benchmarkproject_baseline_member',\n blank=True)\n\n result_from_timestamp = models.DateTimeField(blank=True, null=True)\n result_to_timestamp = models.DateTimeField(blank=True, null=True)\n result_measurement_points = models.ManyToManyField(\n ConsumptionMeasurementPoint,\n related_name='benchmarkproject_result_member',\n blank=True)\n\n objects = BenchmarkProjectManager()\n\n def state_description(self):\n now = self.customer.now()\n if self.from_timestamp is None or self.to_timestamp is None or \\\n now <= self.from_timestamp:\n return _('In planning')\n elif self.from_timestamp < now < self.to_timestamp:\n return _('In progress')\n else:\n assert self.to_timestamp <= now\n return _('Completed')\n\n def __unicode__(self):\n state = self.state_description()\n name = self.name_plain or self.name\n return unicode(\"{name} ({state})\".format(name=name, state=state))\n\n def cost_currency_conflicts(self):\n \"\"\"\n @return: C{True} if there are any cost currency conflicts, in which\n case measured costs cannot be included in the resulting benchmark\n report.\n \"\"\"\n measurement_points = list(\n self.baseline_measurement_points.values_list(\n 'id', flat=True)) + \\\n list(self.result_measurement_points.values_list(\n 'id', flat=True))\n\n return DataSeries.objects.filter(\n role=DataRoleField.COST,\n graph__collection_id__in=measurement_points).exclude(\n unit__contains=self.customer.currency_unit).exists()\n\n def clean(self):\n dates = (self.baseline_from_timestamp, self.baseline_to_timestamp,\n self.result_from_timestamp, self.result_to_timestamp)\n if any(dates) and not all(dates):\n raise ValidationError(\n _('Fill in all \"baseline\" and \"result\" dates.'))\n elif all(dates):\n if self.baseline_from_timestamp >= self.baseline_to_timestamp:\n raise ValidationError(\n _('Baseline \"to\" is not after \"from\".'))\n if self.result_from_timestamp >= self.result_to_timestamp:\n raise ValidationError(\n _('Result \"to\" is not after \"from\".'))\n\n return super(BenchmarkProject, self).clean()\n\n @property\n def from_timestamp(self):\n return min(self.baseline_from_timestamp, self.result_from_timestamp)\n\n @property\n def to_timestamp(self):\n return max(self.baseline_to_timestamp, self.result_to_timestamp)\n\n @cached_property\n def baseline_stage(self):\n return BaselineStage(self)\n\n @cached_property\n def result_stage(self):\n return ResultStage(self)\n\n def get_encryption_id(self):\n return (Customer, self.customer_id)\n\n @classmethod\n def active(cls, timestamp=None):\n if timestamp is None:\n timestamp = datetime.now(pytz.utc)\n return cls.objects.filter(\n Q(baseline_to_timestamp__gt=timestamp) |\n Q(result_to_timestamp__gt=timestamp) |\n Q(result_to_timestamp__isnull=True) |\n Q(baseline_to_timestamp__isnull=True))\n\n @classmethod\n def done(cls, timestamp=None):\n if timestamp is None:\n timestamp = datetime.now(pytz.utc)\n return cls.objects.filter(\n Q(baseline_to_timestamp__lte=timestamp) &\n Q(result_to_timestamp__lte=timestamp))\n\n def active_stages(self, timestamp=None):\n \"\"\"\n The active Stage(s).\n\n @param timestamp: Optional specify time at which the returned stages\n should be active. If not given now is assumed.\n\n @return: Returns a list of stages that are currently active.\n \"\"\"\n if timestamp is None:\n timestamp = datetime.now(pytz.utc)\n stages = []\n if self.baseline_from_timestamp <= timestamp <= \\\n self.baseline_to_timestamp:\n stages.append(_('Baseline'))\n if self.result_from_timestamp <= timestamp <= self.result_to_timestamp:\n stages.append(_('Result'))\n return stages\n\n def yearly_additional_co2(self):\n unit = 'tonne'\n before = PhysicalQuantity(0, unit)\n after = PhysicalQuantity(0, unit)\n for saving in self.additionalsaving_set.all():\n before += PhysicalQuantity(\n saving.before_co2 or 0, unit)\n after += PhysicalQuantity(\n saving.after_co2 or 0, unit)\n return {\n 'before': before,\n 'after': after,\n }\n\n def yearly_additional_co2_savings(self):\n sums = self.yearly_additional_co2()\n yearly = sums['before'] - sums['after']\n return yearly\n\n def yearly_co2_savings(self):\n return self.co2_saving_rate * PhysicalQuantity(365, 'day') + \\\n self.yearly_additional_co2_savings()\n\n def project_co2_savings(self):\n return self.yearly_co2_savings() * (float(self.runtime) / 12)\n\n def yearly_co2_savings_pct(self):\n \"\"\"\n @return: CO2 savings in %.\n Returns None if no CO2 data exists for stage_1 and no additional\n co2 savings has been provided.\n \"\"\"\n yearly_additional_co2_savings = \\\n self.yearly_additional_co2()['before'] - \\\n self.yearly_additional_co2()['after']\n try:\n return (\n (\n self.co2_saving_rate +\n yearly_additional_co2_savings /\n PhysicalQuantity(365, 'day')) * 100 /\n (\n self.baseline_stage.mean_co2_rate +\n self.yearly_additional_co2()['before'] /\n PhysicalQuantity(365, 'day')\n )).convert('none')\n except ZeroDivisionError:\n return None\n\n def yearly_measured_consumption_savings(self):\n \"\"\"\n @return: A PhysicalQuantity holding the yearly consumption savings.\n \"\"\"\n return self.consumption_saving_rate * PhysicalQuantity(365, 'day')\n\n def yearly_additional_consumption(self):\n unit = default_unit_for_data_series(\n DataRoleField.CONSUMPTION, self.utility_type)\n before = PhysicalQuantity(0, unit)\n after = PhysicalQuantity(0, unit)\n for saving in self.additionalsaving_set.all():\n before += PhysicalQuantity(\n saving.before_energy or 0, saving.energy_unit)\n after += PhysicalQuantity(\n saving.after_energy or 0, saving.energy_unit)\n return {\n 'before': before,\n 'after': after,\n }\n\n def yearly_additional_consumption_savings(self):\n sums = self.yearly_additional_consumption()\n yearly = sums['before'] - sums['after']\n return yearly\n\n def yearly_consumption_savings(self):\n return self.yearly_measured_consumption_savings() + \\\n self.yearly_additional_consumption_savings()\n\n def project_consumption_savings(self):\n return self.yearly_consumption_savings() * (self.runtime / 12)\n\n def yearly_consumption_savings_pct(self):\n try:\n stage1_consumption = self.baseline_stage.mean_consumption_rate * \\\n PhysicalQuantity(365, 'day') + \\\n self.yearly_additional_consumption()['before']\n return float(\n (\n self.yearly_consumption_savings() * 100 /\n stage1_consumption).convert('none'))\n except ZeroDivisionError:\n return None\n\n def yearly_consumption_savings_display(self):\n \"\"\"\n Method for giving tuple suitable for the L{physicalquantity} template\n filter.\n\n @return: A tuple (n, u) where n is a numeric yearly consumption savings\n in customers preferred unit, and u is the human readable preferred unit\n for the customer.\n \"\"\"\n preferred_unit_converter = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, utility_type=self.utility_type)\n\n return (\n preferred_unit_converter.extract_value(\n self.yearly_consumption_savings()),\n preferred_unit_converter.get_display_unit())\n\n def yearly_additional_cost(self):\n sums = self.additionalsaving_set.aggregate(\n Sum('before_cost'),\n Sum('after_cost'))\n before_cost = sums['before_cost__sum'] or 0\n after_cost = sums['after_cost__sum'] or 0\n return {\n 'before': PhysicalQuantity(\n before_cost, self.customer.currency_unit),\n 'after': PhysicalQuantity(after_cost, self.customer.currency_unit),\n }\n\n def yearly_additional_cost_savings(self):\n sums = self.yearly_additional_cost()\n yearly = sums['before'] - sums['after']\n return yearly\n\n def yearly_measured_cost_savings(self):\n if not self.include_measured_costs or self.cost_currency_conflicts():\n return PhysicalQuantity(0, self.customer.currency_unit)\n return self.cost_saving_rate * PhysicalQuantity(365, 'day')\n\n @cached_property\n def investment(self):\n \"\"\"\n The total expenses for all investments in this project.\n \"\"\"\n return sum(\n (\n investment.get_total_costs() for\n investment in self.cost_set.all()),\n 0)\n\n def average_monthly_project_costs(self):\n total = self.investment / self.runtime\n return PhysicalQuantity(total, self.customer.currency_unit)\n\n def average_yearly_project_costs(self):\n return self.average_monthly_project_costs() * 12\n\n def resulting_annual_cost_savings(self):\n return self.yearly_measured_cost_savings() + \\\n self.yearly_additional_cost_savings() - \\\n self.average_yearly_project_costs()\n\n def project_cost_savings(self):\n return self.resulting_annual_cost_savings() * \\\n (self.runtime / float(12))\n\n def resulting_annual_cost_savings_pct(self):\n try:\n stage1_cost = self.yearly_additional_cost()['before']\n if self.include_measured_costs and \\\n not self.cost_currency_conflicts():\n stage1_cost += self.baseline_stage.mean_cost_rate * \\\n PhysicalQuantity(365, 'day')\n\n return float((self.resulting_annual_cost_savings() * 100 /\n stage1_cost).convert('none'))\n except ZeroDivisionError:\n return None\n\n def resulting_annual_cost_savings_display(self):\n \"\"\"\n Method for giving tuple suitable for the L{physicalquantity} template.\n\n @return: A tuple (n, u) where n is the yearly cost savings and u is the\n human readable currency of the cost savings.\n \"\"\"\n return (self.resulting_annual_cost_savings().convert(\n self.customer.currency_unit),\n self.customer.get_currency_unit_display())\n\n @deprecated\n @property\n def duration(self):\n \"\"\"\n The duration of this C{Project} is defined as the the earliest stage\n start and the latest stage end.\n\n @precondition: Both STAGE_1 and STAGE_2 stages have been stored for\n this C{Project}.\n\n @return: Returns a named tuple C{(from_timestamp, to_timestamp)}\n \"\"\"\n FromTimeToTime = namedtuple(\n 'FromTimeToTime', ['from_timestamp', 'to_timestamp'])\n return FromTimeToTime(self.from_timestamp, self.to_timestamp)\n\n @deprecated\n @property\n def duration_from_time(self):\n return min(self.baseline_from_timestamp, self.result_from_timestamp)\n\n @deprecated\n @property\n def duration_to_time(self):\n return max(self.baseline_to_timestamp, self.result_to_timestamp)\n\n @property\n def consumption_saving_rate(self):\n \"\"\"\n The consumption saving rate.\n \"\"\"\n return self.baseline_stage.mean_consumption_rate - \\\n self.result_stage.mean_consumption_rate\n\n @property\n def cost_saving_rate(self):\n \"\"\"\n The cost saving rate.\n \"\"\"\n return self.baseline_stage.mean_cost_rate - \\\n self.result_stage.mean_cost_rate\n\n @property\n def co2_saving_rate(self):\n return self.baseline_stage.mean_co2_rate - \\\n self.result_stage.mean_co2_rate\n\n def _samples_to_data_set(self, measurement_point, samples, time_offset):\n \"\"\"\n Converts a collection of samples to data set suitable for rendering\n (converting values, converting format of timestamp).\n\n @param measurement_point: The measurement point that these rate\n C{samples} belong to.\n\n @param samples: The rate samples to convert into a renderable data set.\n\n @param time_offset: To allow for time alligment of data sets from\n different periods of time, this offset will be subtracted from the\n timestamp in the C{samples}.\n \"\"\"\n preferred_unit_converter = measurement_point.rate.\\\n get_preferred_unit_converter()\n\n data_set = []\n for sample in samples:\n converted_value = float(\n preferred_unit_converter.extract_value(\n sample.physical_quantity))\n data_set.append(\n [unix_timestamp(sample.timestamp - time_offset),\n converted_value])\n return data_set\n\n def _consumption_samples_to_data_set(self, measurement_point, samples,\n time_offset):\n \"\"\"\n Converts a collection of samples to data set suitable for rendering\n (converting values, converting format of timestamp).\n\n @param measurement_point: The measurement point that these rate\n C{samples} belong to.\n\n @param samples: The consumption samples to convert into a renderable\n data set.\n\n @param time_offset: To allow for time alligment of data sets from\n different periods of time, this offset will be subtracted from the\n timestamp in the C{samples}.\n \"\"\"\n preferred_unit_converter = measurement_point.consumption.\\\n get_preferred_unit_converter()\n\n data_set = []\n for sample in samples:\n converted_value = float(\n preferred_unit_converter.extract_value(\n sample.physical_quantity))\n data_set.append(\n [unix_timestamp(sample.from_timestamp - time_offset),\n converted_value])\n return data_set\n\n def _get_ticks(self):\n \"\"\"\n Get ticks.\n\n @return: Returns a pair C{(ticks_unit, ticks_list)} where C{ticks_unit}\n is a localized unit for the ticks, and C{ticks_list} is a list of\n actual ticks; timestamp-counter pairs.\n\n @postcondition: The C{ticks_unit} is always representing either\n minutes, hours or days.\n\n @postcondition: The C{ticks_list} is constructed such that C{0 <\n len(ticks_list) <= 12} and the ticks are evenly distributed across the\n graph.\n \"\"\"\n SHOW_HOURS = timedelta(hours=1)\n SHOW_DAYS = timedelta(days=1)\n SHOW_MONTHS = timedelta(days=30)\n SHOW_YEARS = timedelta(days=365)\n\n duration_time = max(\n self.baseline_to_timestamp - self.baseline_from_timestamp,\n self.result_to_timestamp - self.result_from_timestamp)\n\n resolution = self.get_sample_resolution()\n\n raw_tick_increment = (duration_time // 12)\n\n if duration_time < SHOW_HOURS:\n # Show minutes\n ticks_unit = _('minutes')\n tick_factor = (raw_tick_increment.seconds / 60) + 1\n tick_increment = timedelta(minutes=tick_factor)\n elif duration_time < SHOW_DAYS:\n # Show hours\n ticks_unit = _('hours')\n tick_factor = (raw_tick_increment.seconds / (60 * 60)) + 1\n tick_increment = timedelta(hours=tick_factor)\n elif duration_time < SHOW_MONTHS:\n # Show days\n ticks_unit = _('days')\n tick_factor = raw_tick_increment.days + 1\n tick_increment = timedelta(days=tick_factor)\n elif duration_time < SHOW_YEARS:\n # Show months\n ticks_unit = _('months')\n tick_factor = (raw_tick_increment.days / 30) + 1\n tick_increment = timedelta(days=30 * tick_factor)\n else:\n # Show years\n ticks_unit = _('years')\n tick_factor = (raw_tick_increment.days / 365) + 1\n tick_increment = timedelta(days=365 * tick_factor)\n\n ticks_list = []\n\n for i in itertools.count():\n if tick_increment * i > duration_time:\n break\n ticks_list.append(\n [\n unix_timestamp(\n self.customer.timezone.normalize(\n condense.floor(\n self.from_timestamp,\n resolution,\n self.customer.timezone) +\n tick_increment * i)),\n i * tick_factor])\n\n assert 0 < len(ticks_list) <= 12, '%r' % ticks_list\n return (ticks_unit, ticks_list)\n\n CONDENSE_TO_HOURS = timedelta(hours=12)\n CONDENSE_TO_DAYS = timedelta(days=12)\n CONDENSE_TO_MONTHS = timedelta(days=30 * 12)\n CONDENSE_TO_YEARS = timedelta(days=12 * 365)\n\n def get_sample_resolution(self):\n duration_time = max(\n self.baseline_to_timestamp - self.baseline_from_timestamp,\n self.result_to_timestamp - self.result_from_timestamp)\n return self._get_resolution(duration_time)\n\n def _get_resolution(self, duration_time):\n \"\"\"\n Converts a C{timedelta} C{duration_time} to a L{RelativeTimeDelta}\n resolution.\n\n @postcondition: The result shall be no less M{1/1000} of\n C{duration_time}\n \"\"\"\n if duration_time < self.CONDENSE_TO_HOURS:\n # Condense to minutes\n resolution = RelativeTimeDelta(minutes=1)\n elif duration_time < self.CONDENSE_TO_DAYS:\n # Condense to hours\n resolution = RelativeTimeDelta(hours=1)\n elif duration_time < self.CONDENSE_TO_MONTHS:\n # Condense to days\n resolution = RelativeTimeDelta(days=1)\n elif duration_time < self.CONDENSE_TO_YEARS:\n # Condense to months\n resolution = RelativeTimeDelta(months=1)\n else:\n # Condense to years\n resolution = RelativeTimeDelta(years=1)\n assert self.from_timestamp + (resolution * 1000) > \\\n self.from_timestamp + duration_time\n return resolution\n\n def get_graph_data(self, measurement_point):\n \"\"\"\n Get graph data for the given L{ConsumptionMeasurementPoint}\n C{measurement_point}.\n\n The rate curve of C{measurement_point} from C{stage_1} and C{stage_2}\n are alligned at the start of the graph.\n\n @return: Returns flotr2 compliant graph data.\n \"\"\"\n\n STAGE_1_COLOR = '#A800F0'\n STAGE_2_COLOR = '#00A8F0'\n\n duration_time = max(\n self.baseline_to_timestamp - self.baseline_from_timestamp,\n self.result_to_timestamp - self.result_from_timestamp)\n\n xticks_unit, xticks_list = self._get_ticks()\n\n result = {\n \"data\": [],\n \"options\": {\n \"colors\": [],\n \"xaxis\": {\n # Implementation note: tick at\n # unix_timestamp(self.from_timestamp) is never\n # displayed.\n \"ticks\": xticks_list,\n \"min\": unix_timestamp(self.from_timestamp),\n \"max\": unix_timestamp(self.from_timestamp +\n duration_time),\n 'title': xticks_unit,\n },\n \"yaxis\": {\n \"title\": (\n measurement_point.rate.get_preferred_unit_converter().\n get_display_unit()),\n }\n }\n }\n\n include_stage_1 = self.baseline_measurement_points.filter(\n id=measurement_point.id).exists()\n include_stage_2 = self.result_measurement_points.filter(\n id=measurement_point.id).exists()\n\n resolution = self._get_resolution(duration_time)\n\n if include_stage_1:\n # calculate stage 1 data\n result['data'].append(\n {\n 'data': self._samples_to_data_set(\n measurement_point,\n measurement_point.rate.get_condensed_samples(\n condense.floor(\n self.baseline_from_timestamp, resolution,\n self.customer.timezone),\n resolution,\n condense.floor(\n self.baseline_to_timestamp, resolution,\n self.customer.timezone)),\n self.baseline_from_timestamp - self.from_timestamp),\n 'lines': {\n 'show': True,\n },\n 'label': _('Baseline'),\n })\n result['options']['colors'].append(STAGE_1_COLOR)\n\n if include_stage_2:\n # calculate stage 2 data\n result['data'].append(\n {\n 'data': self._samples_to_data_set(\n measurement_point,\n measurement_point.rate.get_condensed_samples(\n condense.floor(\n self.result_from_timestamp, resolution,\n self.customer.timezone),\n resolution,\n condense.floor(\n self.result_to_timestamp, resolution,\n self.customer.timezone)),\n self.result_from_timestamp - self.from_timestamp),\n 'lines': {\n 'show': True,\n },\n 'label': _('Result'),\n })\n result['options']['colors'].append(STAGE_2_COLOR)\n\n return result\n\n def get_consumption_graph_data(self, measurement_point):\n \"\"\"\n Get consumption graph data for the given L{ConsumptionMeasurementPoint}\n C{measurement_point}.\n\n The consumption bars of C{measurement_point} from C{stage_1} and\n C{stage_2} are alligned at the start of the graph.\n\n @return: Returns flotr2 compliant graph data.\n \"\"\"\n\n STAGE_1_COLOR = '#A800F0'\n STAGE_2_COLOR = '#00A8F0'\n\n duration_time = max(\n self.baseline_to_timestamp - self.baseline_from_timestamp,\n self.result_to_timestamp - self.result_from_timestamp)\n\n xticks_unit, xticks_list = self._get_ticks()\n\n result = {\n \"data\": [],\n \"options\": {\n \"colors\": [],\n \"xaxis\": {\n # Implementation note: tick at\n # unix_timestamp(self.from_timestamp) is never\n # displayed.\n \"ticks\": xticks_list,\n \"min\": unix_timestamp(self.from_timestamp),\n \"max\": unix_timestamp(self.from_timestamp +\n duration_time),\n 'title': xticks_unit,\n },\n \"yaxis\": {\n \"title\": (\n measurement_point.consumption.\n get_preferred_unit_converter().get_display_unit()),\n }\n }\n }\n\n include_stage_1 = self.baseline_stage.measurement_points.filter(\n id=measurement_point.id).exists()\n include_stage_2 = self.result_stage.measurement_points.filter(\n id=measurement_point.id).exists()\n\n resolution = self._get_resolution(duration_time)\n\n if include_stage_1:\n # calculate stage 1 data\n result['data'].append(\n {\n 'data': self._consumption_samples_to_data_set(\n measurement_point,\n measurement_point.consumption.get_condensed_samples(\n condense.floor(\n self.baseline_stage.from_timestamp, resolution,\n self.customer.timezone),\n resolution,\n condense.ceil(\n self.baseline_stage.to_timestamp, resolution,\n self.customer.timezone)),\n condense.floor(\n self.baseline_stage.from_timestamp,\n resolution,\n self.customer.timezone) -\n condense.floor(\n self.from_timestamp,\n resolution,\n self.customer.timezone)),\n 'bars': {\n 'show': True,\n },\n 'label': _('Baseline'),\n })\n result['options']['colors'].append(STAGE_1_COLOR)\n\n if include_stage_2:\n # calculate stage 2 data\n result['data'].append(\n {\n 'data': self._consumption_samples_to_data_set(\n measurement_point,\n measurement_point.consumption.get_condensed_samples(\n condense.floor(\n self.result_stage.from_timestamp, resolution,\n self.customer.timezone),\n resolution,\n condense.ceil(\n self.result_stage.to_timestamp, resolution,\n self.customer.timezone)),\n condense.floor(\n self.result_stage.from_timestamp,\n resolution,\n self.customer.timezone) -\n condense.floor(\n self.from_timestamp,\n resolution,\n self.customer.timezone)),\n 'bars': {\n 'show': True,\n },\n 'label': _('Result'),\n })\n result['options']['colors'].append(STAGE_2_COLOR)\n\n return result\n\n def get_preferred_consumption_unit_converter(self):\n return get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, self.utility_type,\n customer=self.customer)\n\n def get_consumption_unit_display(self):\n \"\"\"\n @deprecated: Method is redundant -- replace invocations with\n implementation.\n \"\"\"\n return self.get_preferred_consumption_unit_converter().\\\n get_display_unit()\n\n def get_co2_emissions_unit_display(self):\n return get_preferred_unit_converter(\n DataRoleField.CO2, customer=self.customer).get_display_unit()\n\n @cached_property\n def _now(self):\n return datetime.now(pytz.utc)\n\n @cached_property\n def baseline_period_completed(self):\n \"\"\"\n C{True} if base-line period is complete, C{False} otherwise.\n \"\"\"\n if self.from_timestamp:\n return self.baseline_to_timestamp <= self._now\n else:\n return False\n\n @cached_property\n def result_period_completed(self):\n \"\"\"\n C{True} if result period is complete, C{False} otherwise.\n \"\"\"\n if self.to_timestamp:\n return self.result_to_timestamp <= self._now\n else:\n return False\n\n @cached_property\n def project_completed(self):\n \"\"\"\n C{True} if both base-line period and result period are complete,\n C{False} otherwise.\n \"\"\"\n return self.baseline_period_completed and self.result_period_completed\n\n @cached_property\n def baseline_annual_consumption(self):\n \"\"\"\n Base-line annual consumption.\n\n @return: If the base-line period is complete, the measured base-line\n yearly consumption is returned, otherwise the\n C{estimated_yearly_consumption_before} is returned.\n \"\"\"\n ONE_YEAR = PhysicalQuantity(365, 'day')\n if self.baseline_period_completed:\n return self.get_preferred_consumption_unit_converter().\\\n extract_value(\n self.baseline_stage.mean_consumption_rate * ONE_YEAR)\n else:\n return self.estimated_yearly_consumption_before\n\n @cached_property\n def baseline_annual_costs(self):\n \"\"\"\n Base-line annual cost.\n\n @return: If the base-line period is complete and\n C{include_measured_costs} is C{True}, the measured base-line yearly\n costs are returned, otherwise the\n C{estimated_yearly_consumption_costs_before} is returned.\n \"\"\"\n ONE_YEAR = PhysicalQuantity(365, 'day')\n if self.baseline_period_completed and self.include_measured_costs and \\\n not self.cost_currency_conflicts():\n return (self.baseline_stage.mean_cost_rate * ONE_YEAR).convert(\n self.customer.currency_unit)\n else:\n return self.estimated_yearly_consumption_costs_before\n\n @cached_property\n def annual_cost_savings(self):\n \"\"\"\n Annual cost savings.\n\n @return: If the project is completed, the measured yearly cost savings,\n additional yearly cost savings and yearly investment costs are included\n in the result. Otherwise the\n C{expected_savings_in_yearly_total_costs} is returned.\n \"\"\"\n if self.project_completed:\n return self.resulting_annual_cost_savings().convert(\n self.customer.currency_unit)\n else:\n return self.expected_savings_in_yearly_total_costs\n\n @cached_property\n def payback_period_years(self):\n \"\"\"\n Payback period for this project in years.\n\n If this is undefined, C{None} is returned.\n \"\"\"\n return payback_period_years(Fraction(self.investment),\n Fraction(self.subsidy or 0),\n Fraction(self.annual_cost_savings))\n\n @cached_property\n def expected_payback_period_years(self):\n \"\"\"\n Estimated payback period for this project in years.\n\n If this is undefined, C{None} is returned.\n \"\"\"\n return payback_period_years(\n Fraction(self.investment),\n Fraction(self.subsidy or 0),\n Fraction(self.expected_savings_in_yearly_total_costs))\n\n\nMeanRateResult = namedtuple(\n 'MeanRateResult', ['physical_quantity', 'extrapolated_mps'])\n\n\nclass Stage(object):\n def __init__(self, benchmarkproject):\n self.benchmarkproject = benchmarkproject\n\n @property\n def currency_unit(self):\n return self.benchmarkproject.customer.currency_unit\n\n @cached_property\n def _measurement_points(self):\n return self.measurement_points.all()\n\n def _mean_rate(self, accumulation_attribute_name, accumulation_unit):\n \"\"\"\n Calculate the total accumulation of this stage normalized with the\n duration of this stage.\n\n @param accumulation_attribute_name: The L{MeasurementPoint} attribute\n name of the accumulation.\n\n @param accumulation_unit: The unit of which to accumulate.\n\n @return: Returns a PhysicalQuantity holding the mean rate with the\n given unit.\n\n @postcondition: C{report_%s_extrapolated} has been called for all the\n measurement point for which the accumulation sample has been\n extrapolated. Here C{%s} is replaced by the value of the\n C{accumulation_attribute_name} argument.\n \"\"\"\n total = PhysicalQuantity(0, accumulation_unit)\n\n extrapolated_mps = []\n\n time_now = datetime.now(pytz.utc)\n # round from_timestamp down to nearest 5 minutes\n from_timestamp = self.from_timestamp.replace(\n minute=self.from_timestamp.minute - self.from_timestamp.minute % 5,\n second=0,\n microsecond=0)\n # select to_timestamp and round up to nearest 5 minutes\n to_timestamp = min(self.to_timestamp, time_now)\n to_timestamp = to_timestamp.replace(\n minute=(to_timestamp.minute / 5) * 5,\n second=0,\n microsecond=0)\n if from_timestamp < time_now:\n for mp in [mp.subclass_instance for mp in self._measurement_points\n if getattr(mp, accumulation_attribute_name, None)]:\n development = getattr(\n mp, accumulation_attribute_name).calculate_development(\n from_timestamp, to_timestamp)\n if development is not None:\n if development.extrapolated:\n extrapolated_mps.append(mp)\n total += development.physical_quantity\n return MeanRateResult(\n total / PhysicalQuantity(\n (to_timestamp - from_timestamp).total_seconds(), 'second'),\n extrapolated_mps)\n\n @cached_property\n def mean_consumption_rate(self):\n \"\"\"\n The mean consumption rate is the total consumption of this stage\n normalized with the duration of this stage.\n \"\"\"\n return self._mean_rate(\n 'consumption', default_unit_for_data_series(\n DataRoleField.CONSUMPTION,\n self.benchmarkproject.utility_type)).physical_quantity\n\n @cached_property\n def _mean_cost_rate(self):\n \"\"\"\n The mean cost rate is the total cost of this stage normalized with the\n duration of this stage.\n \"\"\"\n if not self.benchmarkproject.cost_currency_conflicts():\n return self._mean_rate('cost', self.currency_unit)\n else:\n return MeanRateResult(\n PhysicalQuantity(0, self.currency_unit) /\n PhysicalQuantity(1, 'second'),\n [])\n\n @property\n def mean_cost_rate(self):\n return self._mean_cost_rate.physical_quantity\n\n @cached_property\n def mean_co2_rate(self):\n \"\"\"\n The mean CO2 rate is the total CO2 of this stage normalized with the\n duration of this stage.\n \"\"\"\n return self._mean_rate('co2calculation', 'gram').physical_quantity\n\n @property\n def tariff_domain_warning_measurement_point_ids(self):\n # technically, the result also depends on consumptions being\n # extrapolated.\n return [mp.id for mp in self._mean_cost_rate.extrapolated_mps]\n\n def tariff_domain_warning(self,\n tariff_domain_warning_measurement_point_ids):\n \"\"\"\n Returns a warning text if any of the MP's in this stage\n has a tariff assigned to it, which is not covering the\n consumption domain.\n\n @param tariff_domain_warning_measurement_point_ids: A list of ids of\n ConsumptionMeasurementPoints whose tariff domain does not cover this\n stage.\n \"\"\"\n if tariff_domain_warning_measurement_point_ids:\n mps = [\n mp.subclass_instance.name_plain for mp in\n ConsumptionMeasurementPoint.objects.filter(\n id__in=tariff_domain_warning_measurement_point_ids)]\n\n return _(\n 'Tariff for {mps} does not cover '\n 'the duration of {stage}').format(\n mps=', '.join(mps), stage=self.get_role_display())\n\n\nclass BaselineStage(Stage):\n @cached_property\n def from_timestamp(self):\n return self.benchmarkproject.baseline_from_timestamp\n\n @cached_property\n def to_timestamp(self):\n return self.benchmarkproject.baseline_to_timestamp\n\n @property\n def measurement_points(self):\n return self.benchmarkproject.baseline_measurement_points.all()\n\n def get_role_display(self):\n return _('Baseline')\n\n\nclass ResultStage(Stage):\n @cached_property\n def from_timestamp(self):\n return self.benchmarkproject.result_from_timestamp\n\n @cached_property\n def to_timestamp(self):\n return self.benchmarkproject.result_to_timestamp\n\n @property\n def measurement_points(self):\n return self.benchmarkproject.result_measurement_points.all()\n\n def get_role_display(self):\n return _('Result')\n\n\nclass AdditionalSaving(EncryptedModel):\n \"\"\"\n C{AdditionalSaving} of a C{Project} Stores supplements to annual savings\n \"\"\"\n project = models.ForeignKey(BenchmarkProject, verbose_name=_('project'))\n description = EncryptedCharField(_('description'), max_length=50)\n before_energy = models.DecimalField(\n _('energy before'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n after_energy = models.DecimalField(\n _('energy after'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n before_cost = models.DecimalField(\n _('cost before'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n after_cost = models.DecimalField(\n _('cost after'),\n blank=True, null=True,\n max_digits=19, decimal_places=2)\n before_co2 = models.DecimalField(\n _('CO² before'),\n blank=True, null=True,\n max_digits=19, decimal_places=6)\n after_co2 = models.DecimalField(\n _('CO² after'),\n blank=True, null=True,\n max_digits=19, decimal_places=6)\n energy_unit = models.CharField(\n _('unit for energy'),\n editable=False, max_length=50, default='kilowatt*hour')\n\n def diff_energy(self):\n return (self.before_energy or 0) - (self.after_energy or 0)\n\n def diff_cost(self):\n return (self.before_cost or 0) - (self.after_cost or 0)\n\n def diff_co2(self):\n return (self.before_co2 or 0) - (self.after_co2 or 0)\n\n def get_encryption_id(self):\n if self.project_id:\n return (Customer, self.project.customer_id)\n else:\n return None\n\n\ndef validate_positive(value):\n if value is not None and value <= 0:\n raise ValidationError(\n _(u'Must be positive.'))\n\n\nclass Cost(EncryptedModel):\n \"\"\"\n C{Cost} of a C{Project} Stores the cost of the project. Eg. costs\n for Grid Manager solution, installation, replacement of machinery, etc.\n\n When both C{amortization_period} and C{interest_rate} are not C{None} we\n are in finance mode.\n\n @invariant: When not in finance mode, both C{amortization_period} and\n C{interrest_rate} must be C{None}.\n\n @invariant: C{scrap_value} may only be set when in finance mode.\n \"\"\"\n project = models.ForeignKey(BenchmarkProject, verbose_name=_('project'))\n description = EncryptedCharField(max_length=50)\n cost = models.DecimalField(\n _('cost'), max_digits=19, decimal_places=2)\n amortization_period = models.IntegerField(\n _('amortization period in months'),\n null=True, blank=True,\n validators=[validate_positive])\n interest_rate = models.DecimalField(\n _('interest rate'),\n null=True, blank=True,\n max_digits=19, decimal_places=2,\n validators=[validate_positive])\n\n # scrap value is used in some leasing agreements.\n scrap_value = models.DecimalField(\n _('scrap value'),\n null=True, blank=True,\n max_digits=19, decimal_places=2)\n\n def save(self, *args, **kwargs):\n self._assert_invariants()\n super(Cost, self).save(*args, **kwargs)\n\n def _finance_mode(self):\n \"\"\"\n C{True} when both C{amortization_period} and C{interrest_rate} are\n C{None}.\n \"\"\"\n return self.amortization_period is not None and \\\n self.interest_rate is not None\n\n def _assert_invariants(self):\n \"\"\"\n Assert invariants.\n \"\"\"\n if not self._finance_mode():\n assert self.amortization_period is None\n assert self.interest_rate is None\n\n if self.scrap_value is not None:\n assert self._finance_mode()\n\n def clean(self):\n super(Cost, self).clean()\n if self.amortization_period and not self.interest_rate:\n raise ValidationError(\n _(u'Interest rate must be set when amortization period is '\n u'non-zero.'))\n\n if self.interest_rate and not self.amortization_period:\n raise ValidationError(\n _(u'Amortization period must be non-zero when interest '\n u'rate is set.'))\n\n if self.scrap_value and not self.amortization_period and \\\n not self.interest_rate:\n raise ValidationError(\n _(u'Scrap value requires amortization period and interest '\n u'rate to be both non-zero.'))\n\n self._assert_invariants()\n\n def get_total_costs(self):\n \"\"\"\n Total costs\n\n @return: Returns a Fraction. In finance mode the result will include\n interests, otherwise the bare costs are returned.\n \"\"\"\n self._assert_invariants()\n if self.amortization_period is None:\n return Fraction(self.cost)\n else:\n return Fraction(self.amortization_period * self.monthly_payment())\n\n def monthly_payment(self):\n \"\"\"\n When the C{Cost} is financed, there will be a monthly payment.\n\n @precondition: This C{Cost} instance is in finance mode.\n \"\"\"\n self._assert_invariants()\n assert self._finance_mode()\n\n PERCENT = 1.0 / 100\n ANNUAL_TO_MONTHLY = 1.0 / 12\n c = float(self.cost)\n r = float(self.interest_rate) * PERCENT * ANNUAL_TO_MONTHLY\n n = self.amortization_period\n\n scrap = float(self.scrap_value)\n\n # formula requires interest rate being non-zero and amortization\n # period being positive.\n assert r != 0\n assert n > 0\n\n # see doc/rje-notes/annuity-formula.jpeg for how to derive this\n # formula without the scrap value. Scrap value may be seen as the\n # final payment, and the following formula emerges. When scrap\n # value is zero, the normal annuity formula applies. The result of\n # this formula is a single payment.\n return (c * r * (1 + r) ** n - scrap * r) / ((1 + r) ** n - 1)\n\n def get_encryption_id(self):\n if self.project_id:\n return (Customer, self.project.customer_id)\n else:\n return None\n" }, { "alpha_fraction": 0.6640183329582214, "alphanum_fraction": 0.6688661575317383, "avg_line_length": 31.147186279296875, "blob_id": "33e06729791e77930e6ac6e29c2d74fc7833463b", "content_id": "920a4dc9e0a4bad422e4f46a928fa0ed28783516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 7426, "license_type": "no_license", "max_line_length": 153, "num_lines": 231, "path": "/Makefile", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# Software releases\n# =================\n\n# Branch and commit ID\nDISTVERSION := $(shell git rev-parse --abbrev-ref HEAD)-$(shell git rev-parse HEAD)\n\n# Most recent tag --- or abbreviated commit as fallback\nRELEASEVERSION := $(shell git describe --always)\n\n# Use `make dist` to package the current develop/branch\n.PHONY: dist\ndist: gridplatform-$(DISTVERSION).tar.gz\n\n# Use `make release` on master branch after tagging for official releases\n.PHONY: release\nrelease: gridplatform-$(RELEASEVERSION).tar.gz\n\n# Package a \"clean\" git clone without the .git directory\ngridplatform-%.tar.gz:\n\tTMPDIR=`mktemp -d`; \\\n\tgit clone . $$TMPDIR/gridplatform; \\\n\trm $$TMPDIR/gridplatform/.git -fr; \\\n\tsed \"s/^__version__\\s*=[^=]*$\\/__version__ = '$*'/\" -i \\\n\t $$TMPDIR/gridplatform/gridplatform/__init__.py; \\\n\ttar czf $@ --directory $$TMPDIR gridplatform; \\\n\trm -fr $$TMPDIR\n\n\n# Common\n# ======\n\n# Django (< 1.7) recognizes apps on the presence of a \"models\" module\nAPPS := $(patsubst %/models.py,%,$(wildcard gridplatform/*/models.py)) $(patsubst %/models/__init__.py,%,$(wildcard gridplatform/*/models/__init__.py)) \\\n $(patsubst %/models.py,%,$(wildcard energymanager/*/models.py)) $(patsubst %/models/__init__.py,%,$(wildcard energymanager/*/models/__init__.py)) \\\n $(patsubst %/models.py,%,$(wildcard legacy/*/models.py)) $(patsubst %/models/__init__.py,%,$(wildcard legacy/*/models/__init__.py))\n\n.DEFAULT_GOAL := test\n\n\n# I18n and l10n\n# =============\n#\n# Use-case: in-house Danish Translation\n# -------------------------------------\n#\n# 1) Just run the `./translate.sh` script.\n#\n# Use-case: External Translation for locale $LC\n# ----------------------------------------------\n#\n# 0) Run `make makemessages LOCALES=\"$LC\"`\n# 1) Run `make $LC_translation.zip`\n# 2) Send `$LC_translation.zip` to translators.\n# 3) Receive translated `$LC_translation.zip` from translators.\n# 4) Extract the translated `$LC_translation.zip` into same directory\n# as this `Makefile`\n# 5) Run `make compilemessages LOCALES=$LC`\n#\n# Note: to speed up things, run make with `-j6` or similar.\n#\n# See also `info gettext Introduction Overview`\n\n# Locales to be processed. May be overriden from command line to process more\n# or fewer locales than default.\nLOCALES := da es\n\n# PO_FILES are considdered up to date if the po files exist.\nPO_FILES = $(foreach lc, $(LOCALES), $(foreach app, $(APPS), ./$(app)/locale/$(lc)/LC_MESSAGES/django.po ./$(app)/locale/$(lc)/LC_MESSAGES/djangojs.po))\n\nPOT_FILES = $(PO_FILES:.po=.pot)\n.PHONY: $(POT_FILES)\n\n# extract messages from gettext invocations and merge them into po files.\n.PHONY: makemessages\nmakemessages: $(POT_FILES)\n\n$(filter %django.pot, $(POT_FILES)):\n\t@echo makemessages $$(dirname $$(dirname $@))/django.po\n\t-@APP=$$(dirname $$(dirname $$(dirname $$(dirname $@))));\\\n\tLC=$$(basename $$(dirname $$(dirname $@)));\\\n\tmkdir -p $$APP/locale;\\\n\tcd $$APP;\\\n\tdjango-admin.py makemessages -l $$LC -e html -e tex 2> /dev/null > /dev/null\n\n$(filter %/djangojs.pot, $(POT_FILES)):\n\t@echo makemessages $$(dirname $$(dirname $@))/djangojs.po\n\t-@APP=$$(dirname $$(dirname $$(dirname $$(dirname $@))));\\\n\tLC=$$(basename $$(dirname $$(dirname $@)));\\\n\tmkdir -p $$APP/locale;\\\n\tcd $$APP;\\\n\tdjango-admin.py makemessages -d djangojs -l $$LC 2> /dev/null > /dev/null\n\n$(PO_FILES:.po=.mo) : %.mo : %.po\n\t@APP=$$(dirname $$(dirname $$(dirname $$(dirname $*))));\\\n\techo compilemessages $$APP;\\\n\tcd $$APP;\\\n\tdjango-admin.py compilemessages\n\n.PHONY: compilemessages\ncompilemessages: $(patsubst %.po,%.mo,$(filter $(shell find . -name \"*.po\"), $(PO_FILES)))\n\n# Create zip file of PO-files for a given locale, preserving directory\n# structure. Usage::\n#\n# make es_translation.zip\n$(addsuffix _translation.zip, $(LOCALES)) : %_translation.zip :\n\t@echo zip $@\n\t@find . -path \"*/locale/$*/*\" -name \"*.po\" | xargs zip $@\n\n\n# Flake8\n# ======\nMODIFIED_FILES = $(shell git status --porcelain | awk '/^ ?[AMU].*\\.py$$/ {print $$2}' | grep -v '/migrations/')\n\n.PHONY: flake8\nflake8:\nifneq ($(MODIFIED_FILES), )\n\tflake8 $(MODIFIED_FILES) $(FLAKE8FLAGS)\nelse\n\t@echo \"No modifications, skipping flake8\"\nendif\n\n\n# Unit tests\n# ==========\nTESTS := $(subst /,.,$(APPS))\nRERUN_TESTS := $(if $(wildcard test_rerun.txt),$(shell grep -v '^unittest.loader.ModuleImportFailure' test_rerun.txt),$(TESTS))\nTESTFLAGS := --noinput --traceback\n\nDJANGO_SETTINGS_MODULE := gridplatform.settings.test\n\n# Run tests for all our apps\n.PHONY: test\ntest: flake8\n\tDJANGO_SETTINGS_MODULE=$(DJANGO_SETTINGS_MODULE) \\\n\t./manage.py test $(TESTS) $(TESTFLAGS)\n\n# Run tests marked for rerun by the test runner\n.PHONY: test-rerun\ntest-rerun: flake8\n\tDJANGO_SETTINGS_MODULE=$(DJANGO_SETTINGS_MODULE) \\\n\t./manage.py test $(RERUN_TESTS) $(TESTFLAGS)\n\nCOVERAGE_INCLUDE_PATTERN = *gridplatform/*,*energymanager/*,*legacy/*\n\n.PHONY: test-coverage\ntest-coverage: flake8\n\tDJANGO_SETTINGS_MODULE=$(DJANGO_SETTINGS_MODULE) \\\n\tcoverage run --branch \\\n\t./manage.py test $(TESTS) $(TESTFLAGS) && \\\n\tcoverage report --include=\"$(COVERAGE_INCLUDE_PATTERN)\" --omit=\"*/migrations/*\" --show-missing\n\n# Prerequisites of running selenium-test target:\n#\n# - pip install selenium\n# - apt-get install xvfb\n# - download and extract the relevant chromedriver to the current directory:\n# wget http://chromedriver.storage.googleapis.com/2.9/chromedriver_linux64.zip\n# unzip chromedriver_linux64.zip\n.PHONY: selenium-test\nselenium-test: export PATH+=:$(abspath .)\nselenium-test: export SELENIUM_SERVER=TRUE\nselenium-test: test\n\n\n# Playground...\n# =============\n.PHONY: tags\ntags: TAGS\n\n.PHONY: TAGS\nTAGS:\n\tfind . -name \"[a-z_]*.py\" | xargs etags\n\n.PHONY: test-failures\ntest-failures: flake8 failure-list.txt\n\ttest -s failure-list.txt\n\tDJANGO_SETTINGS_MODULE=$(DJANGO_SETTINGS_MODULE) \\\n\t./manage.py test $(shell cat failure-list.txt) $(TESTFLAGS)\n\n\nTESTRUNNERS = $(addsuffix .run, $(TESTS))\n\n.PHONY: $(TESTRUNNERS)\n$(TESTRUNNERS): %.run : flake8\n\tDJANGO_SETTINGS_MODULE=$(DJANGO_SETTINGS_MODULE) \\\n\tTEST_DATABASE_NAME=test_$* \\\n\tTEST_LOG_FILE=$*.log \\\n\tTEST_RERUN_FILE=$*.rerun \\\n\t./manage.py test $* $(TESTFLAGS) --verbosity=0\n\n.PHONY: parallel-test\nparallel-test: $(TESTRUNNERS)\n\n# Intentionally fail rebuilding this target if there were any import errors.\nfailure-list.txt: $(wildcard *.rerun) $(wildcard test_rerun.txt)\n\ttest -n \"$?\"\n\tcat $? | grep -q '^unittest.loader.ModuleImportFailure'; test $$? -ne 0\n\tcat $? | sort | uniq > $@\n\nSCSS_FILES = $(shell find legacy/website/static/ -type f -name \"*.scss\")\n\nlegacy/website/static/style.css : $(SCSS_FILES)\n\tscss legacy/website/static/style.scss:legacy/website/static/style.css\n\n.PHONY: scss\nscss: legacy/website/static/style.css\n\n\n.PHONY: clean\nclean:\n\tfind . -name \"*.pyc\" -delete\n\trm -f *.rerun\n\trm -f *.log\n\trm -f GridPlatform.pdf GridPlatformDomainModel.pdf\n\n.PHONY: html\nhtml:\n\tPYTHONPATH=$(abspath .) sphinx-build -b html documentation/source documentation/build\n\n.PHONY: pdf\npdf: GridPlatform.pdf GridPlatformDomainModel.pdf\n\nRST_FILES = $(shell find documentation/source . -name \"*.rst\")\nPY_FILES = $(shell find documentation/source . -name \"*.py\")\n\nGridPlatform.pdf GridPlatformDomainModel.pdf: $(RST_FILES) $(PY_FILES)\n\tPYTHONPATH=$(abspath .) sphinx-build -b latex documentation/source documentation/build\n\tmake -C documentation/build\n\tcp documentation/build/GridPlatform.pdf ./\n\tcp documentation/build/GridPlatformDomainModel.pdf ./\n" }, { "alpha_fraction": 0.5449968576431274, "alphanum_fraction": 0.5490874648094177, "avg_line_length": 33.17204284667969, "blob_id": "abf83cb0070960992a2d835bd3d04e9b54f4ceb1", "content_id": "7ee5ded0cc2d1540d0ab96b575525fb4ddab49e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 3178, "license_type": "no_license", "max_line_length": 232, "num_lines": 93, "path": "/legacy/display_measurementpoints/templates/display_measurementpoints/index.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% extends \"base.html\" %}\n{% load url from future %}\n{% load i18n %}\n{% load l10n %}\n{% load widget_tweaks %}\n{% load static from staticfiles %}\n{% load mptt_tags %}\n{% load display_measurementpoints %}\n{% load dropdown %}\n\n{% block page_id %}mp-page{% endblock %}\n\n{% block page_js %}\n<script type=\"text/javascript\">\n/*jslint browser: true, devel: true */\n/*global $, jQuery, gridportal */\n$(document).ready(function () {\n 'use strict';\n var tree = jQuery(\".in-page-menu .menu-content\");\n\n tree.bind('loaded.jstree', function (e, data) {\n tree.find('a ins').remove();\n {% if group.pk %}\n $(\"#node_{{ group.pk|unlocalize }}\").parents(\".jstree-closed\").each(function () {\n tree.jstree(\"open_node\", this, false, true);\n });\n {% endif %}\n gridportal.website.initInpageMenu('{% static 'images/arrow-right.png' %}', '{% static 'images/arrow-left.png' %}');\n }).bind(\"after_open.jstree\", function (event, data) {\n var menuHeight = $('.in-page-menu').height(),\n contentHeight = $('#content-main').height();\n if (contentHeight < menuHeight) {\n $('#content-main').height(menuHeight + 20);\n }\n }).jstree({\n themes: {\n \"theme\": \"default\",\n \"url\": \"{% static 'jstree/themes/default/style.css' %}\",\n \"dots\": false,\n \"icons\": false,\n \"open_parents\": false\n },\n plugins: [\"themes\", \"html_data\"]\n });\n});\n</script>\n{% block detail_js %}{% endblock detail_js %}\n{% endblock page_js %}\n\n{% block page_css %}\n<style>\n #content-main {\n overflow-x: hidden;\n }\n</style>\n{% endblock %}\n\n{% block title %}{% trans \"Details\" %}{% endblock title %}\n{% block content_heading %}{% trans \"Details\" %}{% endblock content_heading %}\n\n{% block content %}\n<div id=\"measurementpoints\" class=\"grid_23 prefix_1\">\n <span>{% trans \"Choose a group or measurement point from the menu to the left\" %} </span>\n</div>\n{% endblock content %}\n\n{% block in_page_menu %}\n <div class=\"in-page-menu\">\n <div class=\"scroller\">\n <div class=\"menu-content\">\n {% for grouptree in groups %}\n {% for node, structure in grouptree|tree_info %}\n {% if structure.new_level %}\n <ul><li id=\"node_{{ node.id|unlocalize }}\">\n {% else %}\n </li><li id=\"node_{{ node.id|unlocalize }}\">\n {% endif %}\n <a href=\"{% url 'display_measurementpoints-group' pk=node.id %}{% if period_form.from_date.value and period_form.to_date.value %}?from_date={{period_form.from_date.value}}&to_date={{period_form.to_date.value}}{%endif%}\">\n <span class=\"left\"><img src=\"{% static 'images/mpicons/small.'|add:node.get_icon|add:'.png' %}\" height=\"16\" width=\"16\"> {{ node }}</span>\n </a>\n {% for level in structure.closed_levels %}</li></ul>{% endfor %}\n {% endfor %}\n {% endfor %}\n </div>\n </div>\n <div class=\"menu-btn\">\n <div class=\"rotate\">\n <span>{% trans \"Measurement Points\" %}</span>\n </div>\n <img src=\"{% static 'images/arrow-right.png' %}\" />\n </div>\n </div>\n{% endblock %}\n" }, { "alpha_fraction": 0.5938888788223267, "alphanum_fraction": 0.5969444513320923, "avg_line_length": 32.027523040771484, "blob_id": "a85c53612d6d16616827fd0a21c4d93d5f028109", "content_id": "1bf661f5a81ca764e3b10a908b04d89c1bff2fe7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3600, "license_type": "no_license", "max_line_length": 77, "num_lines": 109, "path": "/legacy/edit_userprofile/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import get_object_or_404\nfrom django.http import HttpResponseForbidden\nfrom django.forms.util import ErrorList\n\nfrom gridplatform.users.models import User\nfrom gridplatform.utils.views import render_to, json_response\nfrom gridplatform.users.decorators import auth_or_redirect\nfrom gridplatform.trackuser import get_user\n\n\nclass UserProfileForm(forms.ModelForm):\n class Meta:\n model = User\n fields = ('phone', 'mobile', 'name')\n localized_fields = '__all__'\n\n\nclass PasswordForm(forms.Form):\n password = forms.CharField(widget=forms.PasswordInput, min_length=8)\n old_password = forms.CharField(widget=forms.PasswordInput)\n\n\n# AMMH: Consider; is pk argument useful? If it *has* to be the same as\n# get_user().id; why not just use get_user() for the User instance? (\"In\n# case the code should later be generalised to let admins change users via\n# this\"?)\n@auth_or_redirect\n@render_to('edit_userprofile/userprofile.html')\ndef userprofile_form(request, pk):\n if get_user().id != int(pk):\n return HttpResponseForbidden()\n instance = get_object_or_404(User, pk=pk)\n form = UserProfileForm(instance=instance)\n password_form = PasswordForm()\n return {\n 'form': form,\n 'password_form': password_form,\n 'object': instance,\n 'user': instance,\n }\n\n\n# AMMH: Template in edit_userprofile/form.html does not include any rendering\n# of non_field_errors.\n# MCL: We don't get non_field_errors and we don't have\n# a concept for it\n@json_response\ndef userprofile_update(request, pk):\n if get_user().id != int(pk):\n return HttpResponseForbidden()\n instance = get_object_or_404(User, pk=pk)\n form = UserProfileForm(request.POST, instance=instance)\n password_form = PasswordForm()\n valid = False\n if form.is_valid():\n instance = form.save(commit=False)\n valid = True\n\n if request.POST['password'] != '' or request.POST['old_password'] != '':\n password_form = PasswordForm(request.POST)\n valid = False\n if password_form.is_valid():\n try:\n instance.set_password(\n password_form.cleaned_data['password'],\n old_password=password_form.cleaned_data['old_password']\n )\n valid = True\n except ValueError as e:\n password_form._errors[\"old_password\"] = ErrorList([e])\n\n if valid:\n instance.save()\n return {\n 'success': True,\n 'statusText': _('Your profile has been saved'),\n 'html': render_to_string(\n 'edit_userprofile/form.html',\n {\n 'form': form,\n 'password_form': password_form,\n 'object': instance,\n 'user': instance,\n },\n RequestContext(request)\n ),\n }\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'edit_userprofile/form.html',\n {\n 'form': form,\n 'password_form': password_form,\n 'object': instance,\n 'user': instance,\n },\n RequestContext(request)\n ),\n }\n" }, { "alpha_fraction": 0.7991631627082825, "alphanum_fraction": 0.8015540838241577, "avg_line_length": 34.59574508666992, "blob_id": "e597dc5465723001b676949a631096680fe48c36", "content_id": "d8d0ccb072f212db34a41443864ff49f68a920b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1673, "license_type": "no_license", "max_line_length": 71, "num_lines": 47, "path": "/legacy/measurementpoints/models/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom south.modelsinspector import add_introspection_rules\n\nfrom .chain import Chain\nfrom .chain import ChainLink\nfrom .co2calculation import Co2Calculation\nfrom .collections import Collection\nfrom .collections import CollectionConstraint\nfrom .collections import Location\nfrom .costcalculation import CostCalculation\nfrom .dataseries import DataSeries\nfrom .dataseries import StoredData\nfrom .degreedays import DegreeDayCorrection\nfrom .degreedays import HeatingDegreeDays\nfrom .graph import AbstractGraph\nfrom .graph import Graph\nfrom .indexcalculation import IndexCalculation\nfrom .integral import PiecewiseConstantIntegral\nfrom .link import Link\nfrom .meantemperaturechange import MeanTemperatureChange\nfrom .multiplication import Multiplication\nfrom .rateconversion import RateConversion\nfrom .simplelinearregression import SimpleLinearRegression\nfrom .storeddataseries import StoredDataSeries\nfrom .summation import Summation\nfrom .summation import SummationTerm\nfrom .utilization import Utilization\n\n\nadd_introspection_rules([], [\n r\"^gridplatform\\.measurementpoints\\.fields.DataRoleField\"])\n\n\n__all__ = [\n 'Graph', 'DataSeries', 'StoredData',\n 'Summation', 'SummationTerm', 'RateConversion', 'IndexCalculation',\n 'CostCalculation', 'Co2Calculation', 'Chain', 'ChainLink',\n 'Multiplication',\n 'HeatingDegreeDays', 'DegreeDayCorrection', 'Utilization', 'Link',\n 'MeanTemperatureChange', 'AbstractGraph',\n 'StoredDataSeries', 'SimpleLinearRegression',\n 'PiecewiseConstantIntegral', 'Collection', 'CollectionConstraint',\n 'Location',\n]\n" }, { "alpha_fraction": 0.6130267977714539, "alphanum_fraction": 0.6136654019355774, "avg_line_length": 32.319149017333984, "blob_id": "42d559cd89246b11697563b5b75777aeab1710d6", "content_id": "03daa721d91f0fca19d1743746565753fda8ab46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1566, "license_type": "no_license", "max_line_length": 69, "num_lines": 47, "path": "/legacy/manage_locations/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\nfrom django.views.generic import TemplateView, DetailView\n\nfrom legacy.measurementpoints.models import Location\nfrom gridplatform.users.decorators import auth_or_redirect\n\n\nurlpatterns = patterns(\n 'legacy.manage_locations.views',\n url(r'^$',\n auth_or_redirect(TemplateView.as_view(\n template_name='manage_locations/location_list.html')),\n name='manage-locations-list'),\n url(r'^form/$',\n 'location_form',\n name='manage-locations-form'),\n url(r'^form/(?P<pk>\\d+)$',\n 'location_form',\n name='manage-locations-form'),\n url(r'^json/locations/$',\n 'location_list_json',\n name='manage-locations-list-json'),\n url(r'^update/$',\n 'location_update',\n name='manage-locations-update'),\n url(r'^update/(?P<pk>\\d+)$',\n 'location_update',\n name='manage-locations-update'),\n url(r'^delete/$',\n 'location_delete',\n name='manage-locations-delete'),\n url(r'^(?P<pk>\\d+)$',\n auth_or_redirect(DetailView.as_view(\n model=Location,\n template_name='manage_locations/location_details.html')),\n name='manage-locations-details'),\n url(r'^json/agent/(?P<location>\\d+)$',\n 'agent_list_json',\n name='manage-locations-agent-list-json'),\n url(r'^json/meter/(?P<location>\\d+)$',\n 'meter_list_json',\n name='manage-locations-meter-list-json'),\n)\n" }, { "alpha_fraction": 0.543482780456543, "alphanum_fraction": 0.55474454164505, "avg_line_length": 31.619047164916992, "blob_id": "bed39d389b4a5811ed031e2c4be62e3dc75d4abb", "content_id": "469f5d1843ad21f693cb183d1c742d840333c2d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4795, "license_type": "no_license", "max_line_length": 78, "num_lines": 147, "path": "/gridagentserver-protocol/gridagentserver_protocol/encryption.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"ARCFOUR encryption, implemented as partial file object interface.\"\"\"\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\n# deprecated; replaced\n# Encrypter/StreamEncrypter splits responsibility for encryption state away\n# from wrapping stream... (Mostly to be able to use encryption without\n# streams...)\nclass Encryption(object):\n \"\"\"\n Simple ARCFOUR encryption implementation. Wrapping an object with read()\n and write() operations to do encryption on read() and write().\n \"\"\"\n def __init__(self, key, stream):\n \"\"\"Initialize encryption/cipher state with the specified key.\n Key may be string or bytearray.\n (Or an iterable yielding integers [0,255]...)\"\"\"\n key = bytearray(key)\n state = bytearray(range(256))\n j = 0\n for i in range(256):\n j = (j + state[i] + key[i % len(key)]) % 256\n state[i], state[j] = state[j], state[i]\n self._i = 0\n self._j = 0\n self._state = state\n self.stream = stream\n\n def _crypt(self, data):\n \"\"\"\n Encrypt/decrypt data and update the state of the stream cipher.\n Input/output data is represented as strings, for convenient use with\n the Python socket interface. Returns the transformed data.\n \"\"\"\n i = self._i\n j = self._j\n state = self._state\n result = bytearray(len(data))\n for n in range(len(data)):\n i = (i + 1) % 256\n j = (j + state[i]) % 256\n state[i], state[j] = state[j], state[i]\n k = state[(state[i] + state[j]) % 256]\n result[n] = (ord(data[n]) ^ k) % 256\n self._i = i\n self._j = j\n return str(result)\n\n def read(self, count):\n \"\"\"\n Read and decrypt data from configured file/stream.\n \"\"\"\n # rfile.read does not throw exception if connection closed...\n data = self._crypt(self.stream.read(count))\n # we check the length; we only get less than requested on \"EOF\";\n # i.e. if the connection was closed\n if len(data) != count:\n raise EOFError\n return data\n\n def write(self, data):\n \"\"\"\n Encrypt and write data to configured file/stream.\n \"\"\"\n # wfile.write throws exception if connection closed\n self.stream.write(self._crypt(data))\n self.stream.flush()\n\n def flush(self):\n self.stream.flush()\n\n\nclass Encrypter(object):\n def __init__(self, key):\n key = bytearray(key)\n state = bytearray(range(256))\n j = 0\n for i in range(256):\n j = (j + state[i] + key[i % len(key)]) % 256\n state[i], state[j] = state[j], state[i]\n self._i = 0\n self._j = 0\n self._state = state\n\n def __call__(self, data):\n \"\"\"\n Encrypt/decrypt data and update the state of the stream cipher.\n Input/output data is represented as strings, for interoperability with\n Python APIs representing byte arrays as strings. Returns the\n transformed data.\n \"\"\"\n i = self._i\n j = self._j\n state = self._state\n result = bytearray(len(data))\n for n in range(len(data)):\n i = (i + 1) % 256\n j = (j + state[i]) % 256\n state[i], state[j] = state[j], state[i]\n k = state[(state[i] + state[j]) % 256]\n result[n] = (ord(data[n]) ^ k) % 256\n self._i = i\n self._j = j\n return str(result)\n\n def __cmp__(self, other):\n # note that object changes wrt. comparison on use...\n # (that's kind of the point of the object...)\n return cmp((self._i, self._j, self._state),\n (other._i, other._j, other._state))\n\n def __hash__(self):\n # not a very good hash function, but agrees with __cmp__, correctness\n # before performance...\n return hash((self._i, self._j))\n\n\nclass StreamEncrypter(object):\n def __init__(self, key, stream):\n self._crypt = Encrypter(key)\n self.stream = stream\n\n def read(self, count):\n \"\"\"\n Read and decrypt data from configured file/stream.\n \"\"\"\n # rfile.read does not throw exception if connection closed...\n data = self._crypt(self.stream.read(count))\n # we check the length; we only get less than requested on \"EOF\";\n # i.e. if the connection was closed\n if len(data) != count:\n raise EOFError\n return data\n\n def write(self, data):\n \"\"\"\n Encrypt and write data to configured file/stream.\n \"\"\"\n # wfile.write throws exception if connection closed\n self.stream.write(self._crypt(data))\n self.stream.flush()\n\n def flush(self):\n self.stream.flush()\n" }, { "alpha_fraction": 0.5843678116798401, "alphanum_fraction": 0.5871264338493347, "avg_line_length": 36.629756927490234, "blob_id": "d7cbb05a8522ac88e118442232e38583e5be1b53", "content_id": "87cecd62d5bbae39856b3a499dd8f729a19ddf11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10875, "license_type": "no_license", "max_line_length": 79, "num_lines": 289, "path": "/gridagentserver/agentserver/amqp.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import json\nimport logging\n\nfrom twisted.internet import protocol, reactor\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.python import log\nfrom txamqp.client import TwistedDelegate\nfrom txamqp.content import Content\nfrom txamqp.protocol import AMQClient\nfrom txamqp.spec import load as load_spec\n\nfrom gridagentserver_protocol.server_messages import (\n CommandGpSwitchRelay,\n CommandGpSwitchControl,\n ConfigGaSoftware,\n ConfigGpSoftware,\n ConfigGaRulesets,\n)\nfrom gridagentserver_protocol.datatypes import (\n Meter,\n RuleSet,\n Rule,\n)\n\nlogger = logging.getLogger(__name__)\n\n\n# factory has:\n# * user\n# * password\n# * exchange\n# * exchange_type\n# * incoming (queue)\n# * outgoing (queue)\n# * routes\n\n# connect -> authenticate -> open channel ->\n# declare exchange -> declare \"private\" (exclusive=True) queue for input\nclass AmqpProtocol(AMQClient):\n def __init__(self, *args, **kwargs):\n AMQClient.__init__(self, *args, **kwargs)\n self._routes = set()\n self._adding_routes = set()\n self._removing_routes = set()\n\n @inlineCallbacks\n def connectionMade(self):\n # connected to server --- not ready to communicate...\n AMQClient.connectionMade(self)\n log.msg('connected to server')\n self.connected = False\n # authenticate\n yield self.authenticate(self.factory.user, self.factory.password)\n log.msg('authenticated as %s' % (self.factory.user,))\n # open channel\n self.chan = yield self.channel(1)\n log.msg('got channel')\n yield self.chan.channel_open()\n log.msg('channel opened')\n # declare exchange\n yield self.chan.exchange_declare(\n exchange=self.factory.exchange,\n type=self.factory.exchange_type)\n log.msg('exchange (%s, %s) declared' % (\n self.factory.exchange, self.factory.exchange_type))\n # declare queue\n result = yield self.chan.queue_declare(exclusive=True)\n self.queue_name = result.queue\n log.msg('queue (%s) declared' % (self.queue_name,))\n # consume\n result = yield self.chan.basic_consume(\n queue=self.queue_name, no_ack=True)\n self.consumer_tag = result.consumer_tag\n log.msg('started consuming (tag: %s)' % (self.consumer_tag,))\n queue = yield self.queue(self.consumer_tag)\n d = queue.get()\n d.addCallback(self._read_item, queue)\n\n self.connected = True\n\n self.routes_updated()\n # self.send()\n\n def routes_updated(self):\n \"\"\"\n Tries to bring the current set of registered routes to the state\n specified on the factory.\n \"\"\"\n # We have/use this rather than direct access to add and remove methods,\n # to handle the edge cases where a route is to be added/removed while\n # it is in the process of being removed/added.\n desired_routes = self.factory._routes\n to_add = desired_routes - self._routes\n to_remove = self._routes - desired_routes\n for route in to_add - self._adding_routes:\n self._add_route(route)\n for route in to_remove - self._removing_routes:\n self._remove_route(route)\n\n @inlineCallbacks\n def _add_route(self, routing_key):\n assert routing_key not in self._routes\n assert routing_key not in self._adding_routes\n self._adding_routes.add(routing_key)\n yield self.chan.queue_bind(queue=self.queue_name,\n exchange=self.factory.exchange,\n routing_key=routing_key)\n self._adding_routes.remove(routing_key)\n self._routes.add(routing_key)\n # Check the overall current state of routes --- we might need to remove\n # the route we just added again...\n log.msg('route (%s) added' % (routing_key,))\n self.routes_updated()\n\n @inlineCallbacks\n def _remove_route(self, routing_key):\n assert routing_key in self._routes\n assert routing_key not in self._removing_routes\n self._removing_routes.add(routing_key)\n yield self.chan.queue_unbind(queue=self.queue_name,\n exchange=self.factory.exchange,\n routing_key=routing_key)\n self._removing_routes.remove(routing_key)\n self._routes.remove(routing_key)\n # Check the overall current state of routes --- we might need to add\n # the route we just removed back in...\n log.msg('route (%s) removed' % (routing_key,))\n self.routes_updated()\n\n def _read_item(self, item, queue):\n self.factory.received(item)\n queue.get().addCallback(self._read_item, queue)\n\n def send(self, routing_key, msg):\n msg = Content(msg)\n self.chan.basic_publish(exchange=self.factory.exchange,\n routing_key=routing_key,\n content=msg)\n\n\ndef clean_version(major, minor, revision, extra):\n return (int(major), int(minor), int(revision), str(extra))\n\n\nclass AmqpFactory(protocol.ReconnectingClientFactory):\n protocol = AmqpProtocol\n\n def __init__(self, spec_file=None, vhost=None, user=None, password=None):\n spec_file = spec_file or 'amqp0-8.stripped.rabbitmq.xml'\n self.spec = load_spec(spec_file)\n self.user = user or 'guest'\n self.password = password or 'guest'\n self.vhost = vhost or '/'\n self.delegate = TwistedDelegate()\n self.exchange = 'agentservers'\n self.exchange_type = 'topic'\n self._routes = set(['agentserver'])\n self.p = None\n reactor.addSystemEventTrigger('before', 'shutdown', self.cleanup)\n\n def cleanup(self):\n logger.info('cleaning up twisted connection')\n return self.p.chan.channel_close()\n\n def buildProtocol(self, addr):\n self.p = self.protocol(self.delegate, self.vhost, self.spec)\n self.p.factory = self\n # Reset the reconnection delay since we're connected now.\n self.resetDelay()\n return self.p\n\n # ... WTF?\n def clientConnectionFailed(self, connector, reason):\n print \"Connection failed.\"\n protocol.ReconnectingClientFactory.clientConnectionLost(\n self, connector, reason)\n\n def clientConnectionLost(self, connector, reason):\n print \"Client connection lost.\"\n self.p = None\n protocol.ReconnectingClientFactory.clientConnectionFailed(\n self, connector, reason)\n\n def add_route(self, routing_key):\n self._routes.add(routing_key)\n if self.p and self.p.connected:\n self.p.routes_updated()\n\n def remove_route(self, routing_key):\n self._routes.remove(routing_key)\n if self.p and self.p.connected:\n self.p.routes_updated()\n\n def send(self, routing_key, msg):\n if self.p is not None and self.p.connected:\n self.p.send(routing_key, msg)\n\n def received(self, msg):\n try:\n body = msg.content.body\n properties = msg.content.properties\n content_type = properties.get('content type', None)\n assert content_type == 'application/json'\n data = json.loads(body)\n command = data['command']\n logger.debug('handling command: %s', command)\n assert command in self.commands\n method = getattr(self, command)\n agent = data.get('agent', None)\n logger.debug('IPC message: %s', body)\n if agent is not None:\n agent_mac = int(data['agent'], base=16)\n handler = self.agentprotocol.handlers.get(agent_mac, None)\n if handler is not None:\n method(agent_mac, handler, data)\n else:\n method(data)\n except Exception as e:\n logger.warning('Error handling IPC message: %s', e)\n logger.debug('Error handling IPC message: %s, message: %s', e, msg)\n\n commands = {\n 'current_agents',\n 'relay_state',\n 'control_mode',\n 'gridagent_rules',\n 'gridagent_software',\n 'gridpoint_software',\n }\n\n def current_agents(self, data):\n logger.info('Connected agents: %s', [\n 'agent: %s, serial: %s, sw: %s, hw: %s' % (\n h.agent_mac, h.serial, h.sw_version, h.hw_revision)\n for h in self.agentprotocol.handlers.values()])\n\n def relay_state(self, agent_mac, handler, data):\n relay_on = data['relay_on']\n meters = [Meter(m['connection_type'], m['id']) for m in data['meters']]\n for meter in meters:\n message = CommandGpSwitchRelay(meter, relay_on)\n handler.outgoing.put(message)\n\n def control_mode(self, agent_mac, handler, data):\n control_manual = data['control_manual']\n meters = [Meter(m['connection_type'], m['id']) for m in data['meters']]\n for meter in meters:\n message = CommandGpSwitchControl(meter, control_manual)\n handler.outgoing.put(message)\n\n def gridagent_software(self, agent_mac, handler, data):\n name_template = 'sw/{}-hw{:02d}_{:02d}_{:02d}{}-' \\\n 'sw{:02d}_{:02d}_{:02d}{}.hex'\n filename = name_template.format(\n data['hw_model'],\n *(data['target_hw_version'] + data['sw_version']))\n with open(filename) as f:\n image = f.read()\n message = ConfigGaSoftware(clean_version(*data['sw_version']),\n data['hw_model'],\n clean_version(*data['target_hw_version']),\n image)\n handler.outgoing.put(message)\n\n def gridpoint_software(self, agent_mac, handler, data):\n meters = [Meter(m['connection_type'], m['id']) for m in data['meters']]\n name_template = 'sw/{}-hw{:02d}_{:02d}_{:02d}{}-' \\\n 'sw{:02d}_{:02d}_{:02d}{}.hex'\n filename = name_template.format(\n data['hw_model'],\n *(data['target_hw_version'] + data['sw_version']))\n with open(filename) as f:\n image = f.read()\n message = ConfigGpSoftware(clean_version(*data['sw_version']),\n data['hw_model'],\n clean_version(*data['target_hw_version']),\n image,\n meters)\n handler.outgoing.put(message)\n\n def gridagent_rules(self, agent_mac, handler, data):\n rulesets = [\n RuleSet(0,\n [Rule(**rule) for rule in ruleset['rules']],\n [Meter(**meter) for meter in ruleset['meters']])\n for ruleset in data['rulesets']]\n\n message = ConfigGaRulesets(rulesets)\n handler.outgoing.put(message)\n" }, { "alpha_fraction": 0.6309860348701477, "alphanum_fraction": 0.6323027610778809, "avg_line_length": 32.671592712402344, "blob_id": "d06ea9bbc224fe61ab7f784aa1232b065f35752a", "content_id": "68d0d153aacc3f60091921c742c49f2cb67dc006", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 20506, "license_type": "no_license", "max_line_length": 79, "num_lines": 609, "path": "/gridplatform/utils/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\nimport time\nfrom functools import wraps\nfrom mimetypes import guess_type\n\nfrom celery.result import AsyncResult\nfrom django import forms\nfrom django.conf import settings\nfrom django.core import urlresolvers\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.core.urlresolvers import reverse\nfrom django.http import Http404\nfrom django.http import HttpResponse\nfrom django.http import HttpResponseBadRequest\nfrom django.http import HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nfrom django.utils.cache import add_never_cache_headers\nfrom django.utils.decorators import available_attrs\nfrom django.utils.functional import cached_property\nfrom django.views.decorators.http import require_POST\nfrom django.views.generic import DetailView\nfrom django.views.generic import RedirectView\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import replace_selected_customer\n\nfrom . import generic_views\n\n\ndef json_response(view_func):\n \"\"\"\n Decorator to simplify returning JSON, and make a clear declaration of\n intent. Use::\n\n @json_response\n def my_function(response, ...):\n ...\n\n To have the return value serialised with json and wrapped in a\n HttpResponse. You may \"escape\" this by directly returning a HttpResponse,\n e.g. in order to respond with a redirect or an error message.\n\n :note: Will wrap output in HTML for non-AJAX requests in debug\n mode. This allows us to use Django Debug Toolbar to check SQL\n queries and other information about the handling of the\n request.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n data = view_func(request, *args, **kwargs)\n if isinstance(data, HttpResponse):\n return data\n try:\n json_data = json.dumps(data, cls=DjangoJSONEncoder)\n except TypeError as e:\n raise TypeError(b'%s while serializing %r' % (e, data))\n if not settings.DEBUG or request.is_ajax():\n response = HttpResponse(json_data, content_type='application/json')\n else:\n response = render_to_response('utils/json_data.html',\n {'data': json_data})\n add_never_cache_headers(response)\n return response\n return wrapper\n\n\ndef json_list_response(view_func):\n \"\"\"\n Decorator to give filter and pagify in JSON list responses.\n\n Decorate a function that return a tripple, like::\n\n @json_list_response\n def json_list_response(request, ...):\n ...\n return (order_map, object_list, template_name)\n\n where ``order_map`` is a mapping from the name of what to order to\n a function that returns the value of what to order given an\n object. For example::\n\n order_map = {\n \"name\": lambda obj: unicode(obj.name),\n \"location\": lambda obj: unicode(obj.location.name)}\n\n and ``object_list`` is a list of objects, say a query set turned\n into a list, and ``template_name`` is a path to a HTML file\n relative to the ``templates/`` directory of your application, where\n the object that this template is instantiated for will be bound to\n the name ``\"object\"``.\n \"\"\"\n @json_response\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n order_map, object_list, template_name = \\\n view_func(request, *args, **kwargs)\n options = json_list_options(request)\n\n if options[\"search\"]:\n object_list = filter(\n lambda obj: obj.satisfies_search(options[\"search\"]),\n object_list)\n\n if options[\"order_by\"] in order_map:\n object_list.sort(key=order_map[options[\"order_by\"]])\n if options[\"direction\"].lower() == \"desc\":\n object_list.reverse()\n\n return {\n \"total\": len(object_list),\n \"data\": [render_to_string(template_name,\n {\"object\": obj},\n RequestContext(request))\n for obj\n in object_list[options[\"offset\"]: options[\"offset\"] +\n options[\"count\"]]]}\n return wrapper\n\n\nclass JsonResponse(HttpResponse):\n \"\"\"\n :class:`~django.http.HttpResponse` specialisation that serialises\n data to a JSON string.\n \"\"\"\n def __init__(self, data={}, cachable=False):\n content = json.dumps(data, cls=DjangoJSONEncoder)\n super(JsonResponse, self).__init__(\n content, content_type='application/json')\n if not cachable:\n add_never_cache_headers(self)\n\n def _get_data(self):\n \"\"\"\n DjangoJSONEncoder formats datetime objects as strings; reading\n them back gives strings.\n \"\"\"\n return json.loads(self.content)\n\n def _set_data(self, data):\n self.content = json.dumps(data, cls=DjangoJSONEncoder)\n\n data = property(_get_data, _set_data)\n\n\nclass JsonResponseBadRequest(JsonResponse, HttpResponseBadRequest):\n \"\"\"\n A :class:`.JsonResponse` that is also a\n :class:`django.http.HttpResponseBadRequest`.\n \"\"\"\n pass\n\n\nclass DateLocalEpoch(json.JSONEncoder):\n \"\"\"\n :class:`json.JSONEncoder` specialization that adds support for\n :class:`datetime.datetime` and :class:`datetime.date`.\n \"\"\"\n def default(self, o):\n \"\"\"\n Specialization of :meth:`json.JSONEncoder.default`.\n\n :param o: The object to be encoded.\n\n :return: If ``o`` is a :class:`~datetime.datetime` it is\n converted to a naive local timestamp counting milliseconds\n since the epoch. If ``o`` is a :class:`~datetime.date` it\n is converted to a naive local timestamp at the start of\n that date counting milliseconds since the epoch. Both\n these encodings are along the lines of what Javascript\n expects. Otherwise the call is delegated to the super\n implementation.\n \"\"\"\n if isinstance(o, datetime.datetime):\n naive = timezone.make_naive(o, timezone.get_current_timezone())\n return int(time.mktime(naive.timetuple()) * 1000)\n elif isinstance(o, datetime.date):\n return int(time.mktime(o.timetuple()) * 1000)\n else:\n return super(DateLocalEpoch, self).default(o)\n\n\ndef date_epoch_json_response(view_func):\n \"\"\"\n Decorator similar to :func:`.json_response` except it uses\n :class:`.DateLocalEpoch` for JSON encoding, and is less smart\n about debugging.\n \"\"\"\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(*args, **kwargs):\n data = view_func(*args, **kwargs)\n if isinstance(data, HttpResponse):\n return data\n response = HttpResponse(json.dumps(data, cls=DateLocalEpoch),\n content_type='application/json')\n add_never_cache_headers(response)\n return response\n return wrapper\n\n\ndef render_to(template):\n \"\"\"\n Decorator to simplify a common use of template rendering: Views where the\n template to use is always the same, though there may be several independent\n code paths for determining the data to render with. The intent is twofold:\n To support the convention that each view function should normally be\n associated with only a single template, and to make it easier for a reader\n to immediately identify which template is associated with the view. Use::\n\n @render_to('some_template.html')\n def my_view(request, ...):\n ...\n\n and return a dictionary from the function, to get the template rendered\n into a HttpResponse with the provided dictionary. You may \"escape\" this by\n directly returning a HttpResponse, e.g. in order to respond with a redirect\n or an error message.\n \"\"\"\n def renderer(view_func):\n @wraps(view_func, assigned=available_attrs(view_func))\n def wrapper(request, *args, **kwargs):\n data = view_func(request, *args, **kwargs)\n if isinstance(data, HttpResponse):\n return data\n return render(request, template, data)\n return wrapper\n return renderer\n\n\ndef json_list_options(request):\n \"\"\"\n Extracts JSON list options from a request.\n\n :return: A dictionary with keys ``'search'``, ``'order_by'``,\n ``'offset'``, ``'count'``, ``'direction'`` mapping to the\n corresponding query arguments or their default values.\n \"\"\"\n return {\n 'search': request.GET.get('search', ''),\n 'order_by': request.GET.get('order', None),\n 'offset': int(request.GET.get('offset', 0)),\n 'count': int(request.GET.get('count', 20)),\n 'direction': request.GET.get('direction', 'asc'),\n }\n\n\n# ... perhaps others missing\n\n# Usage example:\n# urls.py:\n# url('^(?P<pk>\\d+)/photo/$',\n# generic.FileView.as_view(model=Car, field='photo')\n# name='cars-photo'),\n\n\nclass FileView(DetailView):\n \"\"\"\n Generic :class:`.DetailView` serving a file stored on the instane\n whose details are being inspected.\n\n :cvar model: The model class of which instance is an instance.\n :cvar str field: The name of the field on the instance whose\n details are bing inspected.\n \"\"\"\n field = None\n\n def get(self, request, *args, **kwargs):\n \"\"\"\n :return: The contents of the DB FieldFile specified by\n ``self.field`` as a :class:`~django.http.HttpResponse`.\n \"\"\"\n self.object = self.get_object()\n fieldfile = getattr(self.object, self.field)\n mimetype, encoding = guess_type(str(fieldfile))\n if not mimetype:\n mimetype = 'application/octet-stream'\n response = HttpResponse(content_type=mimetype)\n fieldfile.open()\n response.write(fieldfile.read())\n fieldfile.close()\n return response\n\n\nclass NoCustomerMixin(object):\n \"\"\"\n Mixes a ``_customer`` property that is None into a view.\n \"\"\"\n @cached_property\n def _customer(self):\n return None\n\n\nclass CustomerContextMixin(object):\n \"\"\"\n Mixes a specialization of\n :meth:`django.views.generic.TemplateView.get_context_data` into a\n view, that makes ``customer`` available in template context.\n \"\"\"\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Makes ``customer`` available in temmplate context.\n\n Requires ``self._customer`` to be set. For example via\n :class:`.CustomerInKwargsMixin` or :class:`.NoCustomerMixin`.\n \"\"\"\n context = super(CustomerContextMixin, self).get_context_data(**kwargs)\n if 'customer' not in context:\n context['customer'] = self._customer\n return context\n\n\nclass CustomerInKwargsMixin(CustomerContextMixin):\n \"\"\"\n Mixes a ``_customer`` cached property into a view.\n\n :ivar _customer: A property that extracts a\n :class:`~gridplatform.customers.models.Customer` from the\n ``self.kwargs['customer_id']``.\n \"\"\"\n @cached_property\n def _customer(self):\n return get_object_or_404(Customer, pk=int(self.kwargs['customer_id']))\n\n\nclass CustomersContextMixin(CustomerContextMixin):\n \"\"\"\n Bastard mixin that specializes :class:`.CustomerContextMixin`.\n\n :see: :class:`.CustomerListMixin` if ``self._customer`` should be\n defined by ``self.kwargs['customer_id']``.\n\n Mixes a `customers` property, and a\n :meth:`django.views.generic.TemplateView.get_context_data`\n specialization into a view.\n\n :ivar customers: A\n :class:`~gridplatform.customers.models.Customer` list ordered\n by decrypted name.\n \"\"\"\n @cached_property\n def customers(self):\n with replace_selected_customer(None):\n return list(\n Customer.objects.filter(\n is_active=True).decrypting_order_by('name_plain', 'id'))\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Makes ``self.customers`` available as ``customers`` in template\n context.\n \"\"\"\n context = {\n 'customers': self.customers,\n }\n context.update(kwargs)\n return super(CustomersContextMixin, self).get_context_data(**context)\n\n\nclass CustomerListMixin(CustomersContextMixin):\n \"\"\"\n A :class:`.CustomerContextMixin` specialization that in addition\n mixes a ``self._customer`` into a view.\n\n :ivar _customer: :class:`~gridplatform.customers.models.Customer`\n defined from ``self.kwargs['customer_id']`` but avoiding extra\n DB query. The selected customer must be in\n ``self.customers``.\n \"\"\"\n @cached_property\n def _customer(self):\n customer_id = int(self.kwargs['customer_id'])\n for customer in self.customers:\n if customer.id == customer_id:\n return customer\n raise Http404\n\n\n@json_response\n@require_POST\ndef task_status(request):\n \"\"\"\n View giving JSON response about status of a given task.\n\n :deprecated: Use :func:`gridplatform.reports.views.status` instead\n as it has better error handling (and has almost the same\n interface, except it also protects against csrf).\n \"\"\"\n if 'task_id' not in request.POST:\n return HttpResponseBadRequest('task_id not specified')\n task_id = request.POST['task_id']\n async = AsyncResult(task_id)\n\n if async.status == 'PROGRESS' and isinstance(async.result, dict):\n if 'task_user_id' in async.result:\n if get_user().id != async.result['task_user_id']:\n return HttpResponseForbidden()\n return {\n 'task_id': async.id,\n 'status': async.status,\n 'result': async.result,\n }\n else:\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\nclass StartTaskView(generic_views.FormView):\n \"\"\"\n Generic view to, when configured with a form class and a Celery\n task, start the Celery task with data from the form.\n \"\"\"\n task = None\n status_url_name = 'task_status'\n finalize_url_name = None\n http_method_names = ['options', 'post']\n\n def get_task_kwargs(self, form):\n \"\"\"\n Must be overwritten by subclass. This methods returns the data\n for the task itself, it must not contain any sensitive data!\n \"\"\"\n raise NotImplementedError()\n\n def get_task(self):\n \"\"\"\n Return the Celery task to run.\n \"\"\"\n if self.task is None:\n raise ImproperlyConfigured('No task to run. Provide a task.')\n return self.task\n\n def get_status_url(self):\n \"\"\"\n Reverse ``self.status_url_name`` for use in returned\n :class:`JsonResponse` of :meth:`StartTaskview.form_valid`.\n \"\"\"\n if self.status_url_name is None:\n raise ImproperlyConfigured('Missing status_url_name')\n return urlresolvers.reverse(self.status_url_name)\n\n def get_finalize_url(self):\n if self.finalize_url_name is None:\n raise ImproperlyConfigured('Missing finalize_url_name')\n return urlresolvers.reverse(self.finalize_url_name)\n\n def start_task(self, kwargs):\n \"\"\"\n Start the Celery task.\n \"\"\"\n task = self.get_task()\n return task.delay(**kwargs)\n\n def form_valid(self, form):\n \"\"\"\n Start Celery task with data from form; called when the form is found\n valid.\n \"\"\"\n kwargs = self.get_task_kwargs(form)\n async = self.start_task(kwargs)\n return JsonResponse({\n 'task_id': async.id,\n 'status_url': self.get_status_url(),\n 'finalize_url': self.get_finalize_url(),\n 'status': async.status,\n })\n\n def form_invalid(self, form):\n \"\"\"\n Format form errors as JSON error response.\n \"\"\"\n return JsonResponseBadRequest(form.errors)\n\n\nclass TaskForm(forms.Form):\n \"\"\"\n Same as :class:`gridplatform.reports.views.TaskForm`.\n \"\"\"\n task_id = forms.CharField()\n\n\nclass FinalizeTaskView(generic_views.FormView):\n \"\"\"\n Abstract view for finalizing a Celery task. Specializations must\n implement :meth:`~.FinalizeTaskView.finalize_task`.\n \"\"\"\n form_class = TaskForm\n http_method_names = ['options', 'post']\n\n def finalize_task(self, task_result):\n \"\"\"\n Abstract method for finalizing task.\n\n :param task_result: The result returned by the Celery task to\n be finalized.\n\n :return: Should return some kind of http resonse.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n def form_valid(self, form):\n \"\"\"\n If task was successful delegate to\n :meth:`~.FinalizeTaskView.finalize_task`.\n \"\"\"\n task_id = form.cleaned_data['task_id']\n async = AsyncResult(task_id)\n if not async.successful():\n return JsonResponseBadRequest({'task_status': async.status})\n\n return self.finalize_task(async.result)\n\n def form_invalid(self, form):\n \"\"\"\n Format form errors as JSON error response.\n \"\"\"\n return JsonResponseBadRequest(form.errors)\n\n\nclass HomeViewBase(CustomerListMixin, RedirectView):\n \"\"\"\n An abstract :class:`.RedirectView` used when a site depends on a\n customer.\n\n .. method:: get_redirect_with_customer_url()\n\n Should return a url to redirect to if the customer is allready set\n\n .. method:: get_choose_customer_url()\n\n Should return a url to the site specialisation of ChooseCustomerBase\n \"\"\"\n def get_redirect_url(self, *args, **kwargs):\n \"\"\"\n Redirects to customer list if no customer has been defined yet.\n If only one customer is defined or a customer is currently\n selected, delegate to\n :meth:`~.HomeViewBase.get_redirect_with_customer_url`. If\n more than one customer is defined and none are selected\n delegate to :meth:`~.HomeViewBase.get_choose_customer_url`.\n \"\"\"\n if len(self.customers) == 0:\n return reverse('provider_site:customer-list')\n elif len(self.customers) == 1:\n return self.get_redirect_with_customer_url(self.customers[0].id)\n else:\n customer_id = self.request.session.get('chosen_customer_id', None)\n if customer_id and Customer.objects.filter(\n is_active=True, pk=customer_id).exists():\n return self.get_redirect_with_customer_url(customer_id)\n else:\n return self.get_choose_customer_url()\n\n def get_redirect_with_customer_url(self, customer_id):\n raise NotImplementedError()\n\n def get_choose_customer_url(self):\n raise NotImplementedError()\n\n\nclass ChooseCustomerBase(generic_views.TemplateView):\n \"\"\"\n Used when site depends on a customer\n\n The specialisation needs to define a template_name\n The template should be a blank page that contains\n javascript to open the customer select modal on load\n \"\"\"\n @property\n def _customer(self):\n return None\n\n def get_context_data(self, **kwargs):\n context = {\n 'customers': list(\n Customer.objects.filter(\n is_active=True).decrypting_order_by('name_plain', 'id')),\n }\n context.update(kwargs)\n return super(ChooseCustomerBase, self).get_context_data(**context)\n\n\nclass CustomerViewBase(CustomerListMixin, RedirectView):\n \"\"\"\n Used when site depends on a customer\n\n .. method:: get_redirect_with_customer_url()\n\n Should return a url to redirect to\n \"\"\"\n def get_redirect_url(self, *args, **kwargs):\n self.request.session['chosen_customer_id'] = self._customer.id\n return self.get_redirect_with_customer_url(self._customer.id)\n\n def get_redirect_with_customer_url(self, customer_id):\n raise NotImplementedError()\n" }, { "alpha_fraction": 0.8055105209350586, "alphanum_fraction": 0.8055105209350586, "avg_line_length": 48.36000061035156, "blob_id": "7df3e9cff0fdd02924810089bcb866e7469398ed", "content_id": "edcb713860f1f88a273018e587b5e280024c2081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 90, "num_lines": 25, "path": "/documentation/source/apps/gridplatform/bootstrap.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Bootstrap\n=========\n\nConfiguration\n-------------\n\n.. automodule:: gridplatform.bootstrap.conf\n\nTemplate Tags\n-------------\n\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.parse_token_arguments\n.. autoclass:: gridplatform.bootstrap.templatetags.bootstrap_tags.BootstrapNode\n :members: get_templates\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_icon\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.checkbox_icon_name\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_panel\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_field_input\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_field_label\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_field\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_hidden_field\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_non_field_errors\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_form\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_form_buttons\n.. autofunction:: gridplatform.bootstrap.templatetags.bootstrap_tags.do_bootstrap_form\n" }, { "alpha_fraction": 0.71856290102005, "alphanum_fraction": 0.7197604775428772, "avg_line_length": 32.400001525878906, "blob_id": "17bf61ffc6874246b8acb83992c8310ca091b151", "content_id": "5e15fcebea608b89bb4e8e9b44e15fb72c1eb7fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 835, "license_type": "no_license", "max_line_length": 76, "num_lines": 25, "path": "/gridplatform/encryption/signals.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nSignals of the encryption app.\n\n.. data:: encryption_key_created = Signal(providing_args=['key', 'key_id'])\n\n :class:`django.dispatch.Signal` signalled when an encryption key is\n created. Can be used to grant the key to user currently logged in.\n\n.. data:: encryption_user_created = Signal(providing_args=['user'])\n\n Creation of encryption users cannot reasonably be observed with model\n signals --- user must be created/saved to get ID, before being assigned\n private key and userprofile. *Must* be explicitly sent by code creating\n users.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.dispatch import Signal\n\n\nencryption_key_created = Signal(providing_args=['key', 'key_id'])\n\nencryption_user_created = Signal(providing_args=['user'])\n" }, { "alpha_fraction": 0.6086666584014893, "alphanum_fraction": 0.6359999775886536, "avg_line_length": 34.15625, "blob_id": "76affaf7cf3a2d43bb57d6e6b5bdb0c78e43cf56", "content_id": "f9c1786fa431b2118da988fe874ed9811a237c37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4500, "license_type": "no_license", "max_line_length": 75, "num_lines": 128, "path": "/gridplatform/datasequences/test_periods.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.core.exceptions import ValidationError\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nimport pytz\nfrom mock import patch\nfrom mock import MagicMock\n\nfrom .models import PeriodBase\nfrom .models import SingleValueAccumulationPeriodMixin\nfrom .models import AccumulationPeriodBase\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass PeriodBaseTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_clean_happy(self):\n period = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n period.clean()\n\n def test_clean_to_timestamp_not_after_from_timestamp(self):\n period = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)))\n\n with self.assertRaises(ValidationError):\n period.clean()\n\n def test_clean_from_timestamp_not_clock_hour(self):\n period = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1, 1, 42)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n\n with self.assertRaises(ValidationError):\n period.clean()\n\n def test_clean_to_timestamp_not_clock_hour(self):\n period = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2, 1, 42)))\n\n with self.assertRaises(ValidationError):\n period.clean()\n\n def test_clean_overlapping_periods_happy(self):\n period_1 = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n period_2 = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n\n PeriodBase.clean_overlapping_periods([period_2, period_1])\n\n def test_clean_overlapping_periods_unhappy(self):\n period_1 = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n period_2 = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1, 12)))\n\n with self.assertRaises(ValidationError):\n PeriodBase.clean_overlapping_periods([period_1, period_2])\n\n def test_clean_delegates_to_overlapping_periods(self):\n period = PeriodBase(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)))\n\n period.datasequence = MagicMock()\n period.datasequence.period_set = MagicMock()\n period.datasequence.period_set.all = lambda: []\n\n # autospec doesn't work well for descriptors, so we use side_effect\n # instead (for delegation checks this doesn't matter).\n patched_clean_overlapping_periods = patch.object(\n PeriodBase, 'clean_overlapping_periods',\n side_effect=PeriodBase.clean_overlapping_periods)\n\n with patched_clean_overlapping_periods as mock:\n period.clean()\n\n mock.assert_called_with([period])\n\n\nclass TestSingleValueAccumulationPeriod(\n SingleValueAccumulationPeriodMixin, AccumulationPeriodBase):\n datasequence = None\n\n\nclass SingleValueAccumulationPeriodMixinTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n\n def test_clean_empty_period(self):\n # recreates a bug\n period = TestSingleValueAccumulationPeriod(\n from_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 2)),\n to_timestamp=self.timezone.localize(\n datetime.datetime(2014, 1, 1)),\n value=1234,\n unit='kilowatt*hour')\n\n with self.assertRaises(ValidationError):\n period.clean()\n" }, { "alpha_fraction": 0.6125503778457642, "alphanum_fraction": 0.6367300152778625, "avg_line_length": 27.950000762939453, "blob_id": "ce66ba02847d47da68bfc75f171d91a95988a4e5", "content_id": "7c8c97b2bb183343f7323963de065e679e8b3736", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1737, "license_type": "no_license", "max_line_length": 76, "num_lines": 60, "path": "/gridplatform/datasources/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.core.exceptions import ValidationError\nimport pytz\n\nfrom .models import RawData\nfrom .models import DataSource\n\n\nclass TariffRawDataTest(TestCase):\n def setUp(self):\n self.datasource = DataSource(\n unit='currency_dkk*kilowatt^-1*hour^-1')\n\n def test_tariff_clean_accepts_valid_timestamp(self):\n rawdata = RawData(\n datasource=self.datasource,\n value=1,\n timestamp=datetime.datetime(2014, 1, 1, 1, tzinfo=pytz.utc))\n\n rawdata.clean()\n\n def test_tariff_clean_detects_invalid_timestamp(self):\n rawdata = RawData(\n datasource=self.datasource,\n value=1,\n timestamp=datetime.datetime(2014, 1, 1, 0, 5, tzinfo=pytz.utc))\n\n with self.assertRaises(ValidationError) as e:\n rawdata.clean()\n\n self.assertIn('timestamp', e.exception.message_dict)\n\n\nclass Co2ConversionRawDataTest(TestCase):\n def setUp(self):\n self.datasource = DataSource(\n unit='gram*kilowatt^-1*hour^-1')\n\n def test_tariff_clean_accepts_valid_timestamp(self):\n rawdata = RawData(\n datasource=self.datasource,\n value=1,\n timestamp=datetime.datetime(2014, 1, 1, 1, 25, tzinfo=pytz.utc))\n\n rawdata.clean()\n\n def test_tariff_clean_detects_invalid_timestamp(self):\n rawdata = RawData(\n datasource=self.datasource,\n value=1,\n timestamp=datetime.datetime(2014, 1, 1, 0, 3, tzinfo=pytz.utc))\n\n with self.assertRaises(ValidationError):\n rawdata.clean()\n" }, { "alpha_fraction": 0.6073660254478455, "alphanum_fraction": 0.6086892485618591, "avg_line_length": 39.364986419677734, "blob_id": "0899c5248f9e0c4770f8a81fb472ca4ae6925f9e", "content_id": "0c170ee03bfc501466e3904f9eec36658eb44f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13603, "license_type": "no_license", "max_line_length": 79, "num_lines": 337, "path": "/gridagentserver/agentserver/twisted_server.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\n\nimport datetime\nimport logging\nimport traceback\n\nfrom django.db import DatabaseError\nfrom django.db import close_connection\nfrom django.db import transaction\nfrom pytz import utc\nfrom twisted.internet import reactor\nfrom twisted.internet import task\nfrom twisted.internet import threads\n\nfrom gridagentserver_protocol import server_messages\nfrom gridagentserver_protocol.client_messages import AcknowledgementGaSoftware\nfrom gridagentserver_protocol.client_messages import AcknowledgementGpSoftware\nfrom gridagentserver_protocol.client_messages import ErrorGaSoftware\nfrom gridagentserver_protocol.client_messages import ErrorGpSoftware\nfrom gridagentserver_protocol.server_messages import ConfigGaSoftware\nfrom gridagentserver_protocol.server_messages import ConfigGpSoftware\nfrom gridagentserver_protocol.twisted_protocol import BaseAgentProtocol\nfrom gridagentserver_protocol.twisted_protocol import BaseAgentProtocolFactory\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import RawData\n\nfrom . import db\nfrom . import settings\n\n\nlogger = logging.getLogger(__name__)\n\n\nWATER_FREEZING_POINT_MILLIKELVIN = 273150\n\n\nclass AgentProtocol(BaseAgentProtocol):\n def __init__(self):\n BaseAgentProtocol.__init__(self)\n self.polling = None\n self.syncing = None\n self.incoming.get().addCallback(self.process_message)\n self.agent_mac = None\n # self.software_message = None\n self.sw_version = None\n self.hw_revision = None\n self.serial = None\n self.poll_response_pending = False\n\n def pause_sending_after(self, message):\n if isinstance(message, (ConfigGpSoftware, ConfigGaSoftware)):\n # self.software_message = message\n return True\n else:\n return False\n\n def resume_sending_after(self, message):\n if isinstance(message, (AcknowledgementGpSoftware,\n AcknowledgementGaSoftware)):\n # self.software_message = None\n return True\n elif isinstance(message, (ErrorGpSoftware, ErrorGaSoftware)):\n # self.send_message(self.software_message)\n # return False\n # NOTE: continue normal processing on \"error\"\n # TODO: put in event log...?\n return True\n else:\n return False\n\n # Messages from the \"incoming\" queue should be handled in background\n # threads for the database access, but one at a time to serialise the\n # database access per agent connection...\n def process_message(self, message):\n logger.debug('Processing message %s for %X', message, self.agent_mac)\n background_task = threads.deferToThread(\n self.do_process_message, message)\n\n # Attach (and possibly immediately call) callback to handle next\n # incoming message as soon as the background processing of the current\n # message is done. (The return value of the background call is\n # provided as argument.)\n def attach_next_callback(_ignored):\n deferred = self.incoming.get()\n deferred.addCallback(self.process_message)\n background_task.addCallback(attach_next_callback)\n\n def do_process_message(self, message):\n try:\n message.accept(self)\n except DatabaseError as e:\n logger.warning('DatabaseError on processing message: %s', e)\n logger.warning(traceback.format_exc())\n close_connection()\n\n def register(self):\n logger.info('Agent %X connected', self.other_id)\n old_replaced = BaseAgentProtocol.register(self)\n if old_replaced:\n logger.info('Replaced old handler for %X', self.agent_mac)\n self.store_online(initial=True)\n\n def store_online(self, initial=False):\n timestamp = datetime.datetime.utcnow().replace(tzinfo=utc)\n\n def does_not_exist_handler(failure):\n failure.trap(Agent.DoesNotExist)\n logger.info('Unknown agent %X; disconnecting', self.agent_mac)\n self.transport.loseConnection()\n return failure\n\n @transaction.commit_on_success\n def background_store_online():\n db.set_agent_online(True, timestamp, self.agent_mac)\n\n background_task = threads.deferToThread(background_store_online)\n background_task.addErrback(does_not_exist_handler)\n background_task.addCallback(self.stored_online)\n if initial:\n background_task.addCallback(self.delayed_start_periodic)\n\n def stored_online(self, _ignored=None):\n assert self.agent_mac\n if self.agent_mac not in self.factory.handlers:\n # currently offline, so undo setting it online\n self.store_offline()\n\n def unregister(self):\n replaced = BaseAgentProtocol.unregister(self)\n self.stop_periodic()\n if not self.agent_mac:\n return\n if replaced:\n logger.info('Agent %X already reconnected', self.agent_mac)\n else:\n logger.info('Agent %X disconnected', self.agent_mac)\n self.store_offline()\n\n def store_offline(self):\n timestamp = datetime.datetime.utcnow().replace(tzinfo=utc)\n\n @transaction.commit_on_success\n def background_store_offline():\n db.set_agent_online(False, timestamp, self.agent_mac)\n background_task = threads.deferToThread(background_store_offline)\n background_task.addCallback(self.stored_offline)\n\n def stored_offline(self, _ignored=None):\n if self.agent_mac and self.agent_mac in self.factory.handlers:\n # currently online, so undo setting it offline...\n self.store_online()\n\n def start_periodic(self, _ignored=None):\n logger.debug('Starting periodic tasks for %X', self.agent_mac)\n\n def poll():\n if self.poll_response_pending:\n logger.info(\n 'Agent %s did not respond to poll in time; disconnecting',\n self.agent_mac)\n self.transport.loseConnection()\n else:\n self.poll_response_pending = True\n self.outgoing.put(server_messages.CommandGaPollMeasurements())\n\n self.polling = task.LoopingCall(poll)\n self.polling.start(settings.POLL_INTERVAL, now=False)\n\n def sync():\n timestamp = datetime.datetime.utcnow().replace(tzinfo=utc)\n self.outgoing.put(server_messages.ConfigGaTime(timestamp))\n\n self.syncing = task.LoopingCall(sync)\n self.syncing.start(settings.TIME_SYNC_INTERVAL.total_seconds(),\n now=True)\n\n def delayed_start_periodic(self, _ignored=None):\n reactor.callLater(10, self.start_periodic)\n\n def stop_periodic(self):\n if self.agent_mac:\n logger.debug('Stopping periodic tasks for %X', self.agent_mac)\n if self.polling:\n self.polling.stop()\n if self.syncing:\n self.syncing.stop()\n\n @transaction.commit_on_success\n def visit_bulk_measurements(self, message):\n self.poll_response_pending = False\n meter_ids = set([\n meter\n for meter, measurement_sets in message.meter_data])\n meters = {\n meter_id: db.get_meter(meter_id, self.agent_mac)\n for meter_id in meter_ids}\n\n physicalinput_params = set()\n\n for meter_id, measurement_sets in message.meter_data:\n for timestamp, measurements in measurement_sets:\n for measurement in measurements:\n datatype, agent_unit, input_number, value = measurement\n physicalinput_params.add(\n (datatype, agent_unit, input_number, meter_id))\n physicalinputs = {\n (datatype, agent_unit, input_number, meter_id):\n db.get_physicalinput(\n datatype, agent_unit, input_number, meters[meter_id])\n for (datatype, agent_unit, input_number, meter_id)\n in physicalinput_params\n if db.get_physicalinput(\n datatype, agent_unit, input_number, meters[meter_id])\n }\n\n result_measurements = []\n\n for meter_id, measurement_sets in message.meter_data:\n for timestamp, measurements in measurement_sets:\n if timestamp.tzinfo is None:\n aware_timestamp = timestamp.replace(tzinfo=utc)\n else:\n aware_timestamp = timestamp\n for measurement in measurements:\n datatype, agent_unit, input_number, value = measurement\n if (datatype, agent_unit, input_number, meter_id) not in \\\n physicalinputs:\n # Ignore inputs with unsupported units\n continue\n physicalinput = physicalinputs[\n (datatype, agent_unit, input_number, meter_id)]\n if aware_timestamp > datetime.datetime.now(utc) + \\\n datetime.timedelta(days=1):\n # FIXME: Temporary workaround for GridLink bug;\n # sometimes gives spurious future data. To be removed\n # ASAP, after making/deploying GridLink fix.\n # skip storing this wrong data to the database...\n continue\n if physicalinput.store_measurements:\n # FIXME: Temporary work-around for GridAgents reporting\n # absolute temperatures in Celsius.\n MILLIKELVIN = 6\n if agent_unit == MILLIKELVIN:\n result_measurements.append(\n RawData(\n datasource=physicalinput,\n value=(\n measurement.value +\n WATER_FREEZING_POINT_MILLIKELVIN),\n timestamp=aware_timestamp))\n else:\n result_measurements.append(\n RawData(\n datasource=physicalinput,\n value=measurement.value,\n timestamp=aware_timestamp))\n RawData.objects.bulk_create(result_measurements)\n\n @transaction.commit_on_success\n def visit_notification_ga_add_mode(self, message):\n db.set_agent_add_mode(message.in_add_mode, message.timestamp,\n self.agent_mac)\n\n # avoid background thread?\n def visit_notification_ga_time(self, message):\n now = datetime.datetime.utcnow().replace(tzinfo=utc)\n diff = message.timestamp.replace(tzinfo=utc) - now\n if abs(diff.total_seconds()) < settings.TIME_SYNC_TOLERANCE:\n reactor.callFromThread(self.outgoing.put,\n server_messages.CommandGaPropagateTime())\n else:\n reactor.callFromThread(self.outgoing.put,\n server_messages.ConfigGaTime(now))\n\n @transaction.commit_on_success\n def visit_notification_ga_connected_set(self, message):\n logger.debug('Agent %X reported meters %s',\n self.agent_mac, message.meters)\n db.set_meters_online(self.agent_mac, message.meters, message.versions,\n message.device_opts)\n\n @transaction.commit_on_success\n def visit_notification_gp_state(self, message):\n db.set_meter_state(message.control_manual, message.relay_on,\n message.online, message.timestamp,\n message.meter, self.agent_mac)\n\n @transaction.commit_on_success\n def visit_info_agent_versions(self, message):\n self.sw_version = message.sw_version\n self.device_type = message.device_type\n self.hw_revision = message.hw_revision\n self.serial = message.serial\n if self.serial < 0:\n logger.warning('Invalid serial#: %s, agent: %X',\n self.serial, self.agent_mac)\n self.serial = 0\n db.set_agent_info(self.agent_mac, self.serial, self.device_type,\n self.hw_revision, self.sw_version)\n\n @transaction.commit_on_success\n def visit_info_event_log(self, message):\n db.store_event(\n self.agent_mac,\n message.timestamp,\n message.code,\n message.text)\n\n # @transaction.commit_on_success\n def send_complete_configuration(self, conn):\n \"\"\"Obtain and send configuration for agent.\"\"\"\n # TODO: implement...\n\n\n# must initialise self.amqp after init\nclass AgentProtocolFactory(BaseAgentProtocolFactory):\n protocol = AgentProtocol\n\n def __init__(self):\n BaseAgentProtocolFactory.__init__(self)\n\n def register(self, handler):\n result = BaseAgentProtocolFactory.register(self, handler)\n self.amqp.add_route('agent.{:012x}'.format(handler.agent_mac))\n return result\n\n def unregister(self, handler):\n replaced = BaseAgentProtocolFactory.unregister(self, handler)\n if not replaced and handler.agent_mac:\n self.amqp.remove_route('agent.{:012x}'.format(handler.agent_mac))\n return replaced\n\n def startFactory(self):\n logger.info('Started')\n\n def stopFactory(self):\n logger.info('Stopping')\n" }, { "alpha_fraction": 0.5903614163398743, "alphanum_fraction": 0.5938037633895874, "avg_line_length": 22.239999771118164, "blob_id": "5a3081fa25ad6e34b2c14652cc0f6e3dbd2d01c5", "content_id": "c561eb5beefedcd36cd18ab39e536bb701dcc0ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 581, "license_type": "no_license", "max_line_length": 48, "num_lines": 25, "path": "/legacy/website/templates/admin_menu.html", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "{% spaceless %}\n{% load static from staticfiles %}\n{% load url from future %}\n{% load i18n %}\n\n<div class=\"menu-item customers\">\n <a href=\"{% url 'manage_customers-list' %}\">\n <div class=\"icon\"></div>\n <span>{% trans \"Customers\" %}</span>\n </a>\n</div>\n\n<div class=\"menu-item devices\">\n <a href=\"{% url 'setup_agents-list' %}\">\n <div class=\"icon\"></div>\n <span>{% trans \"Agents\" %}</span>\n </a>\n</div>\n\n{% if user.is_admin and request.customer %}\n{% include \"admin_superuser_menu_points.html\" %}\n{% endif %}\n\n<div class=\"menu-right-border\"></div>\n{% endspaceless %}\n" }, { "alpha_fraction": 0.6713641285896301, "alphanum_fraction": 0.6719278693199158, "avg_line_length": 33.7843132019043, "blob_id": "d2003aae329a03a5a4b25e3833107b50cbbb645d", "content_id": "1219c121f8b37812c10ab5bd813e73f8a6038175", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1774, "license_type": "no_license", "max_line_length": 74, "num_lines": 51, "path": "/gridplatform/cost_compensations/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils import units\n\nfrom . import models\n\n\nclass CostCompensation(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n periods = serializers.HyperlinkedRelatedField(\n source='period_set', many=True, read_only=True)\n hourly = serializers.SerializerMethodField('get_hourly')\n fixed_compensation_periods = serializers.HyperlinkedIdentityField(\n view_name='api:cost_compensations:fixedcompensationperiod-list')\n unit = serializers.SerializerMethodField('get_unit')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.CostCompensation\n fields = ('url', 'id', 'name', 'unit', 'display_unit', 'customer',\n 'periods', 'fixed_compensation_periods', 'hourly')\n\n def get_unit(self, obj):\n return obj.unit\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n\n def get_hourly(self, obj):\n if not obj:\n return ''\n return self.reverse(\n 'api:cost_compensations:costcompensation-hourly',\n kwargs={'pk': obj.id})\n\n\nclass FixedCompensationPeriod(serializers.DefaultSerializer):\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.FixedCompensationPeriod\n fields = (\n 'url', 'id', 'from_timestamp', 'to_timestamp', 'datasequence',\n 'value', 'unit', 'display_unit')\n read_only_fields = ('datasequence',)\n\n def get_display_unit(self, obj):\n return units.UNIT_DISPLAY_NAMES[obj.unit]\n" }, { "alpha_fraction": 0.6384934782981873, "alphanum_fraction": 0.6429418921470642, "avg_line_length": 39.62650680541992, "blob_id": "34843ab320947012adeee025a46095ffbfabbac0", "content_id": "57cb1e52a47e1610c44b2a398f3c86ee40a372ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3372, "license_type": "no_license", "max_line_length": 79, "num_lines": 83, "path": "/legacy/nordpool/importer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport itertools\n\nfrom isoweek import Week\nimport pytz\n\nfrom gridplatform.global_datasources.models import GlobalDataSource\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom . import ftpclient\nfrom . import parser\n\n\ndef update_rawdata(\n from_timestamp, to_timestamp, datasource, preliminary, final,\n timezone, nordpool_unit, unit):\n rawdata_qs = datasource.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lt=to_timestamp)\n existing_rawdata = {rawdata.timestamp: rawdata for rawdata in rawdata_qs}\n final_dates = set([date for date, hourly in final])\n preliminary_rawdata = []\n for date, hourly in preliminary:\n if date not in final_dates:\n preliminary_rawdata.extend(\n parser.day_entries(date, hourly, timezone))\n final_rawdata = []\n for date, hourly in final:\n final_rawdata.extend(parser.day_entries(date, hourly, timezone))\n for from_ts, to_ts, value in itertools.chain(preliminary_rawdata,\n final_rawdata):\n if value is None:\n # As of October 19th 2014 Nordpool started to document the prices\n # using 25 hours for each day, to (in their opinion) better support\n # the one day every year where 03:00 is two hours long. They could\n # of course just have documented hourly prices with UTC timestamps\n # and thus have completely avoided the daylight savings issues!\n # Nordpool news about the format change:\n # http://www.nordpoolspot.com/TAS/Power-Data-Services/PDS-news/\n continue\n if from_ts in existing_rawdata:\n rawdata = existing_rawdata[from_ts]\n assert rawdata.timestamp == from_ts\n rawdata.value = \\\n int(PhysicalQuantity(value, nordpool_unit).convert(unit))\n rawdata.save()\n else:\n datasource.rawdata_set.create(\n timestamp=from_ts,\n value=int(\n PhysicalQuantity(value, nordpool_unit).convert(unit)))\n\n\ndef import_week(data, spotprices):\n year, week, _day, _hour, _total_hours, _clock, _date = data['ST'][0]\n year = int(year)\n week = int(week)\n naive_week_start = datetime.datetime.combine(\n Week(year, week).monday(), datetime.time())\n naive_week_end = datetime.datetime.combine(\n naive_week_start + datetime.timedelta(days=7), datetime.time())\n for spotprice in spotprices:\n datasource = GlobalDataSource.objects.get(\n app_label='nordpool', codename=spotprice['CODENAME'])\n tz = pytz.timezone(spotprice['TIMEZONE'])\n area = spotprice['AREA']\n currency = spotprice['CURRENCY']\n week_start = tz.localize(naive_week_start)\n week_end = tz.localize(naive_week_end)\n preliminary, final = parser.extract_prices(data, area, currency)\n update_rawdata(\n week_start, week_end, datasource, preliminary, final, tz,\n spotprice['NORDPOOL_UNIT'], spotprice['UNIT'])\n\n\ndef fetch_import_week(year, week, spotprices):\n lines = ftpclient.fetch_spot(year, week)\n data = parser.parse_lines(lines)\n import_week(data, spotprices)\n" }, { "alpha_fraction": 0.6485148668289185, "alphanum_fraction": 0.6509901285171509, "avg_line_length": 25.933332443237305, "blob_id": "ff4d00bab05903b38c13084f0c97233fa3dd9aa9", "content_id": "b222bf0a31cf58cd66260a3b4d122fbd9e71ae11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 45, "num_lines": 15, "path": "/gridplatform/smilics/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\n 'gridplatform.smilics.views',\n url(r'^receiver$',\n 'wibeee_receiver',\n name='smillics-wibeee-reciver'),\n url(r'^receiverJSON$',\n 'wibeee_receiver_json',\n name='smillics-wibeee-reciver-json'),\n)\n" }, { "alpha_fraction": 0.66558837890625, "alphanum_fraction": 0.6659927368164062, "avg_line_length": 36.469696044921875, "blob_id": "2fc4c4efcb57bc92faa7b6dd5821772850b42a76", "content_id": "42b093641b3bcb078aaa16d94bdaf6ca18c8a3b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2473, "license_type": "no_license", "max_line_length": 78, "num_lines": 66, "path": "/gridplatform/energyperformances/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom . import models\n\n\nclass ComputeMixin(object):\n def get_default_fields(self):\n result = super(ComputeMixin, self).get_default_fields()\n result['compute'] = serializers.SerializerMethodField('compute')\n return result\n\n\nclass ProductionEnergyPerformance(\n ComputeMixin, serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n description = serializers.CharField(source='description_plain')\n display_production_unit = serializers.SerializerMethodField(\n 'get_display_production_unit')\n\n class Meta:\n model = models.ProductionEnergyPerformance\n fields = (\n 'url', 'id', 'customer', 'name', 'description',\n 'production_unit', 'display_production_unit', 'consumptiongroups',\n 'productiongroups', 'compute')\n\n def __init__(self, *args, **kwargs):\n super(ProductionEnergyPerformance, self).__init__(*args, **kwargs)\n customer = self.context['request'].user.customer\n if customer:\n self.fields['production_unit'] = serializers.ChoiceField(\n choices=customer.get_production_unit_choices())\n\n def get_display_production_unit(self, obj):\n return obj.unit_converter.get_display_unit()\n\n def compute(self, instance):\n request = self.context['request']\n return self.reverse(\n 'api:energyperformances:productionenergyperformance-compute',\n args=[getattr(instance, 'id', None)], request=request)\n\n\nclass TimeEnergyPerformance(\n ComputeMixin, serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n description = serializers.CharField(source='description_plain')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n\n class Meta:\n model = models.TimeEnergyPerformance\n fields = (\n 'url', 'id', 'customer', 'name', 'description',\n 'unit', 'display_unit', 'consumptiongroups', 'compute')\n\n def get_display_unit(self, obj):\n return obj.unit_converter.get_display_unit()\n\n def compute(self, instance):\n request = self.context['request']\n return self.reverse(\n 'api:energyperformances:timeenergyperformance-compute',\n args=[getattr(instance, 'id', None)], request=request)\n" }, { "alpha_fraction": 0.545279860496521, "alphanum_fraction": 0.5464808940887451, "avg_line_length": 35.20000076293945, "blob_id": "aa1ee8ad7e63cc33142af6771ce18fbfc3f2e815", "content_id": "87b1468ab08f42434e92586bb89e24cd7fadebd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4163, "license_type": "no_license", "max_line_length": 78, "num_lines": 115, "path": "/legacy/measurementpoints/models/simplelinearregression.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nfrom fractions import Fraction\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\nfrom .dataseries import UndefinedSamples\nfrom ..fields import DataRoleField\n\n\nclass SimpleLinearRegression(DataSeries):\n data = models.ForeignKey(\n DataSeries, related_name='simple_linear_regression')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('Simple linear regression')\n verbose_name_plural = _('Simple linear regressions')\n app_label = 'measurementpoints'\n\n def clean_fields(self, exclude=None):\n def should_clean_field(field_name):\n return not (exclude and field_name in exclude)\n\n if self.data:\n if should_clean_field('role'):\n self.role = DataRoleField.LINEAR_REGRESSION\n if should_clean_field('unit'):\n self.unit = self.data.unit\n if should_clean_field('utility_type'):\n self.utility_type = self.data.utility_type\n if should_clean_field('customer'):\n self.customer_id = self.data.customer_id\n\n super(SimpleLinearRegression, self).clean_fields(exclude=exclude)\n\n def depends_on(self):\n return [self.data.subclass_instance] + \\\n self.data.subclass_instance.depends_on()\n\n def _get_samples(self, from_timestamp, to_timestamp):\n raise UndefinedSamples(\n 'not supported by this linear regression implementation')\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n data_samples = [\n sample for sample in\n self.data.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp) if\n not (not sample and sample.extrapolated)]\n\n if data_samples:\n n = len(data_samples)\n y_list = [s.physical_quantity for s in data_samples]\n # x is offset as seconds after from_timestamp\n x_list = [\n PhysicalQuantity(\n Fraction(\n (s.from_timestamp - from_timestamp).total_seconds() +\n (\n s.to_timestamp -\n s.from_timestamp).total_seconds() / 2),\n 'second')\n for s in data_samples]\n\n y_sum = reduce(operator.add, y_list)\n x_sum = reduce(operator.add, x_list)\n xy_sum = reduce(\n operator.add, (x * y for x, y in zip(x_list, y_list)))\n xx_sum = reduce(operator.add, (x * x for x in x_list))\n\n assert x_sum\n assert xx_sum\n if n / x_sum - x_sum / xx_sum:\n b = (y_sum / x_sum - xy_sum / xx_sum) / \\\n (n / x_sum - x_sum / xx_sum)\n\n # the following two definitions of a, must be equal, otherwise\n # b is wrong. Also there is only one b that will satisfy the\n # following equation, so if the assertion pass, b is indeed\n # correct.\n a = (y_sum - n * b) / x_sum\n a_ = -1 * (b * x_sum - xy_sum) / xx_sum\n assert a == a_\n\n def y(x):\n return a * x + b\n else:\n ZERO = PhysicalQuantity(0, self.unit)\n\n def y(x):\n return ZERO\n\n yield self.create_point_sample(\n from_timestamp,\n y(PhysicalQuantity(0, 'second')),\n uncachable=True)\n\n yield self.create_point_sample(\n to_timestamp,\n y(\n PhysicalQuantity(\n (to_timestamp - from_timestamp).total_seconds(),\n 'second')),\n uncachable=True)\n\n def get_preferred_unit_converter(self):\n return self.data.subclass_instance.get_preferred_unit_converter()\n" }, { "alpha_fraction": 0.601915180683136, "alphanum_fraction": 0.601915180683136, "avg_line_length": 26.074073791503906, "blob_id": "69e8d4e1f119e325181fb74439ceffd7ea94362c", "content_id": "999237f4808575d1e7b4964afb85685e81c2ba8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 731, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/gridplatform/users/static/users/users.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "$(function() {\n\t// Cancel button\n\t$('body').on('click', '#userprofile-modal .btn-warning', function(event) {\n\t\tevent.preventDefault();\n\t\t$('#userprofile-modal').modal('hide');\n\t});\n\n\t$('body').on('submit', '#userprofile-modal form', function(event) {\n\t\tvar form = $(this)\n\t\tevent.preventDefault();\n\t\tjQuery.post(form.attr('action'), form.serialize(), function(data) {\n\t\t\tif (data === \"success\"){\n\t\t\t\t$('#userprofile-modal').modal('hide');\n\t\t\t} else {\n\t\t\t\t$('#userprofile-modal .profileform').html(data);\n\t\t\t}\n\t\t});\n\t});\n\n\n\t$('body').on('show.bs.modal', '#userprofile-modal', function() {\n\t\tvar modal = $(this)\n\t\tjQuery.get(modal.data('form-url'), function(data) {\n\t\t\t$('#userprofile-modal .profileform').html(data);\n\t\t});\n\t});\n});\n" }, { "alpha_fraction": 0.727946400642395, "alphanum_fraction": 0.7470428943634033, "avg_line_length": 50.21897888183594, "blob_id": "71a5101bd286ef0ab98d0a304c42912fa34c1fb3", "content_id": "ff99b6b39ae787dc6e3ce97d873b2f1030eb97c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 7017, "license_type": "no_license", "max_line_length": 319, "num_lines": 137, "path": "/documentation/source/deployment.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "**********\nDeployment\n**********\n\nFabric is used to management server deployment. For Fabric usage please\nrefer to https://pypi.python.org/pypi/fabric. The fabric rules in\n:file:`fabfile.py` explains how to deploy to single server targets (e.g. the\ntarget `deploy_staging`) as well as cloud deployment (the target\n`deploy_production`). In cloud deployment please note the order in which\nthe various services are started and stopped. For example, it is not\nrecommended to start the upgrade of the database while over services that\ndepend on it are still running.\n\n\nVirgin deployment\n==================\n\nIf you are deploying to a new server with clean database you want to create a\nstaff user for administrators to use.\n\nAs with most Django projects the first user is added using the following command:\n\n.. code-block:: none\n\n ./manage.py createsuperuser\n\nThe command creates a user with both `is_staff = True` and `is_superuser =\nTrue`.\n\n\nDjango admin\n------------\nStaff users (i.e. users with `is_staff = True`) can log into the Django admin\nwebsite at `/django_admin`.\n\nThe Django admin site allows the administrator to create providers and provider\nusers, as well as administering groups and permissions. That is all that is\nsupposed to be done from this site. Once provider administrators have been\ncreated they can log in and administer the rest them using either GridPortal\n2.0 or Energy Manager.\n\n\nWeb server locale setup\n=======================\n\nEnsure that the locale specified in\n:file:`gridplatform/scripts/production/start_uwsgi.sh`\nis unicode/utf-8-compatible and actually exists on server.\nOtherwise, when interacting with the file system (e.g. when handling file\nuploads) you will experience errors on the form (if the file name contains non-ASCII characters):\n\n.. code-block:: none\n\n UnicodeEncodeError: 'ascii' codec can't encode character u'\\xf3' in position 46: ordinal not in range(128)\n\n\nCrontab\n=======\n\nPlease refer to :ref:`developer-handbook-scripts-and-commands` for descriptions\nof the scripts used in the crontabs listed in this section.\n\nSingle server\n-------------\nFor single server deployment `crontab` contains the following:\n\n.. code-block:: none\n\n5 0 * * * $HOME/gridplatform/scripts/production/manage.sh clearsessions\n15 * * * * $HOME/gridplatform/scripts/production/manage.sh hickup_detection --previous-hour --quiet && ./gridplatform/scripts/production/manage.sh generate_cache --hours_back=2 --verbosity=0\n15 7 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool\n15 12 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool\n15 14 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool\n15 16 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool\n15 22 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool\n15 7 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool_spot_prices\n15 22 * * * $HOME/gridplatform/scripts/production/manage.sh import_nordpool_spot_prices\n1 0 * * * $HOME/gridplatform/scripts/production/manage.sh import_energinet_co2\n*/15 * * * * $HOME/gridplatform/scripts/production/manage.sh import_energinet_co2 $(date +\\%Y-\\%m-\\%d)\n*/15 * * * * $HOME/gridplatform/scripts/production/manage.sh send_rules\n5 * * * * $HOME/gridplatform/gridagentserver/gas-check.sh\n15 * * * * $HOME/gridplatform/rabbitmq-check.sh\n1 0 * * * $HOME/gridplatform/scripts/production/manage.sh rebuild_group_tree\n@reboot while ! $HOME/gridplatform/scripts/production/manage.sh check_db_connection ; do sleep 10; done; $HOME/start.sh\n\n# Portal\n@reboot while ! $HOME/gridplatform/scripts/production/manage.sh check_db_connection ; do sleep 10; done; $HOME/start.sh > /dev/null\n5 0 * * * $HOME/gridplatform/scripts/production/manage.sh clearsessions\n15 * * * * $HOME/gridplatform/scripts/production/manage.sh hickup_detection --previous-hour --quiet && ./gridplatform/scripts/production/manage.sh generate_cache --hours_back=2 --verbosity=0\n*/15 * * * * $HOME/gridplatform/scripts/production/manage.sh send_rules\n15 * * * * $HOME/gridplatform/rabbitmq-check.sh\n1 0 * * * $HOME/gridplatform/scripts/production/manage.sh rebuild_group_tree\n\n# GAS\n@reboot while ! $HOME/gridplatform/scripts/production/manage.sh check_db_connection ; do sleep 10; done; sleep 10; $HOME/restart-gas.sh\n5 * * * * export DJANGO_CONFIGURATION=Prod && $HOME/gridplatform/gridagentserver/gas-check.sh\n10 * * * * if [ $(ps -ho rss $(cat $HOME/gridplatform/gridagentserver/twistd.pid)) -gt 500000 ]; then $HOME/restart-gas.sh; fi\n\nFor cloud deployment\n--------------------\n\nFor cloud deployment, here follows the crontab for the web, engine and GridAgent servers. For a description of the cloud architecture please refer to :ref:`architecture-cloud-architecture`.\n\nWeb server:\n\n.. code-block:: none\n\n @reboot while ! $HOME/gridplatform/scripts/production_nordic/manage.sh check_db_connection ; do sleep 10; done; cd $HOME/gridplatform/scripts/production_nordic; ./start_gunicorn.sh; ./start_celery.sh\n\n\nEngine server:\n\n.. code-block:: none\n\n @reboot while ! $HOME/gridplatform/scripts/production_nordic/manage.sh check_db_connection ; do sleep 10; done; $HOME/gridplatform/scripts/production_nordic/manage.sh ruleengine; $HOME/gridplatform/scripts/production_nordic/start_reports.sh; $HOME/gridplatform/scripts/production_nordic/start_store_data_sanitize.sh\n 15 * * * * $HOME/gridplatform/rabbitmq-check.sh\n 5 0 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh clearsessions\n 15 * * * * $HOME/gridplatform/scripts/production_nordic/manage.sh hickup_detection --previous-hour --quiet && ./gridplatform/scripts/production_nordic/manage.sh generate_cache --hours_back=2 --verbosity=0\n 15 7 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool\n 15 12 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool\n 15 14 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool\n 15 16 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool\n 15 22 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool\n 15 7 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool_spot_prices\n 15 22 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_nordpool_spot_prices\n 1 0 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_energinet_co2\n */15 * * * * $HOME/gridplatform/scripts/production_nordic/manage.sh import_energinet_co2 $(date +\\%Y-\\%m-\\%d)\n */15 * * * * $HOME/gridplatform/scripts/production_nordic/manage.sh send_rules\n 1 0 * * * $HOME/gridplatform/scripts/production_nordic/manage.sh rebuild_group_tree\n\n\nGridAgent Server:\n\n.. code-block:: none\n\n @reboot while ! $HOME/gridplatform/scripts/production_nordic/manage.sh check_db_connection ; do sleep 10; done; cd $HOME/gridplatform/gridagentserver; ./start.sh\n 5 * * * * export DJANGO_CONFIGURATION=Prod && $HOME/gridplatform/gridagentserver/gas-check.sh\n" }, { "alpha_fraction": 0.6773333549499512, "alphanum_fraction": 0.6853333115577698, "avg_line_length": 25.785715103149414, "blob_id": "5bf76cbd81e1beaafc1356dd29b853acd5089f92", "content_id": "f80d2c8d04b015970b413cdcdb444290aff47aa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 52, "num_lines": 14, "path": "/gridplatform/global_datasources/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\n\nfrom . import models\n\n\nclass GlobalDataSourceTest(TestCase):\n def test_tariff_creation(self):\n models.GlobalDataSource.objects.create(\n name='global data source',\n unit='currency_dkk*kilowatt^-1*hour^-1')\n" }, { "alpha_fraction": 0.6344445943832397, "alphanum_fraction": 0.634590208530426, "avg_line_length": 37.80791091918945, "blob_id": "d8c7a782c9612ea4e56800a18db52c33aab3be90", "content_id": "c1e2bf77018524699d58f9146cf9bb785a27cc66", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13738, "license_type": "no_license", "max_line_length": 79, "num_lines": 354, "path": "/gridplatform/utils/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom collections import namedtuple\n\nimport pytz\nfrom django.db import models\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.contenttypes import generic\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.core.exceptions import ValidationError\nfrom django.template.defaultfilters import date as date_format\nfrom history.models import HistoricalRecords as ProDjangoHistoricalRecords\n\nfrom gridplatform.trackuser import get_current_date\n\nfrom .decorators import virtual\n\n\ndef raise_if_none(subject, exception):\n \"\"\"\n Raise C{exception} if C{subject is None}.\n \"\"\"\n if subject is None:\n raise exception\n\n\n# TODO: Delete. This is not used anywhere.\nclass HistoricalRecords(ProDjangoHistoricalRecords):\n \"\"\"\n Specialization of C{ProDjangoHistoricalRecords} that avoids naive\n timestamp warnings.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @keyword app_label: Optional argument for setting Meta.app_label on the\n generated historical records model. This is necessary to support\n historical records for Models defined outside models.py.\n \"\"\"\n self.app_label = kwargs.pop('app_label', None)\n super(HistoricalRecords, self).__init__(*args, **kwargs)\n\n def get_meta_options(self, model):\n \"\"\"\n L{LogicalInput} specialization of\n L{HistoricalRecords.get_meta_options()}. Controls meta options for\n generated historical record model.\n \"\"\"\n result = super(HistoricalRecords, self).get_meta_options(model)\n if self.app_label is not None:\n result['app_label'] = self.app_label\n return result\n\n def get_extra_fields(self, model):\n \"\"\"\n Overload of C{ProDjangoHistoricalRecords.get_extra_fields()},\n to avoid naive timestamps.\n \"\"\"\n res = super(HistoricalRecords, self).get_extra_fields(model)\n res[\"history_date\"].default = lambda: datetime.datetime.now(pytz.utc)\n return res\n\n def copy_fields(self, model):\n \"\"\"\n Overload of C{ProDjangoHistoricalRecords.copy_fields()},\n to avoid specific errors wrt. unique foreign keys:\n C{OneToOneField} is implicitly unique, and clearing the \"unique\"\n attribute (as the inherited C{copy_fields()} does) has no effect.\n\n For now, we support use of C{OneToOneField} only as used for\n multi-table inheritance in Django --- the historical model includes all\n fields from the parent models in its single table, and the relation to\n a \"parent\" instance may thus be removed without loss of information.\n\n On other uses of C{OneToOneField}, we report error.\n \"\"\"\n base_fields = super(HistoricalRecords, self).copy_fields(model)\n fields = {}\n for (name, field) in base_fields.iteritems():\n if isinstance(field, models.OneToOneField):\n assert field.rel.parent_link\n fields[name] = models.IntegerField(null=True)\n if isinstance(field, models.ForeignKey):\n fields[\"%s_id\" % name] = models.IntegerField(null=True)\n else:\n fields[name] = field\n\n return fields\n\n\nclass StoredSubclassManager(models.Manager):\n \"\"\"\n Manager which injects the appropriate ``prefetch_related()`` call\n for :class:`.StoreSubclass` instances. This manager also provides\n the :meth:`.subclass_only` method.\n \"\"\"\n use_for_related_fields = False\n\n def get_query_set(self):\n qs = super(StoredSubclassManager, self).get_query_set()\n return qs.prefetch_related('subclass_instance')\n\n def subclass_only(self):\n \"\"\"\n Returns a queryset that will only contain objects whose subclass field\n indicate that they are subclasses of the model on which the query is\n performed.\n\n The objects yielded by the resulting query will still be\n instanses of the model on which the query is performed, so you\n still need to follow the ``subclass_instance``\n :class:`~django.contrib.contenttypes.generic.GenericForeignKey`\n on each object in the result, if you need the concrete\n subclass instance.\n\n :note: Only useful for proxy models --- queries on concrete\n models are already limited to those objects that are\n present in the relevant table, i.e. instances of the model\n we run the query on (possibly through subclasses).\n\n :deprecated: This is only useful as a workaround for the mess\n we've made with proxy models to save a few db tables (the\n :class:`legacy.measurementpoints.proxies.MeasurementPoint`\n class hierachy in particular). We strongly recommend\n normal subclassing, also when there are no new fields, but\n in particular when there are new fields, as is the case\n with\n :class:`legacy.measurementpoints.proxies.MeasurementPoint`\n and its subclasses.\n \"\"\"\n # The for_concrete_models=False ensures that proxy models are included\n # in the result.\n content_types_dict = ContentType.objects.get_for_models(\n *self._model_subclasses(), for_concrete_models=False)\n return self.get_query_set().filter(\n subclass__in=content_types_dict.values())\n\n def _model_subclasses(self, model=None):\n \"\"\"\n List of all ``model`` subclasses.\n \"\"\"\n if model is None:\n model = self.model\n result = [model]\n else:\n result = []\n\n for subclass in model.__subclasses__():\n result.append(subclass)\n result.extend(self._model_subclasses(subclass))\n\n return result\n\n\nclass StoreSubclass(models.Model):\n \"\"\"\n Model mixin class intended to simplify work with multi-table inheritance\n trees. Saves concrete class via the Django contenttypes framework, and\n injects a ``prefetch_related()`` for this on later model access.\n\n Accessing the concrete subclass instance from a base class instance must\n still be done explicitly by accessing ``self.subclass_instance``.\n\n :ivar subclass: A foreign key to the\n :class:`django.contrib.contenttypes.models.ContentType` that\n hold the class information of this instance.\n :ivar subclass_instance: A\n :class:`django.contrib.contenttypes.generic.GenericForeignKey`\n to ``self`` as an instance of ``self.subclass``.\n \"\"\"\n subclass = models.ForeignKey(\n ContentType, on_delete=models.PROTECT,\n editable=False, related_name='+')\n subclass_instance = generic.GenericForeignKey('subclass', 'id')\n\n objects = StoredSubclassManager()\n\n class Meta:\n abstract = True\n\n @virtual\n def __unicode__(self):\n return unicode(super(StoreSubclass, self))\n\n def __repr__(self):\n return '<%s(id=%s)>' % (self.__class__.__name__, self.id)\n\n def __init__(self, *args, **kwargs):\n super(StoreSubclass, self).__init__(*args, **kwargs)\n if not self.subclass_id:\n # NOTE: For_concrete_model=False uses proxy class when applicable,\n # rather than the \"default\" behaviour of taking first concrete\n # parent.\n self.subclass = ContentType.objects.get_for_model(\n self, for_concrete_model=False)\n\n self._allow_subclass_change = True\n else:\n self._allow_subclass_change = False\n self._initial_subclass = self.subclass\n\n if not hasattr(self, '_subclass_cache'):\n # Explicitly use ContentType manager --- the lookups will be cached\n # in the manager; normal access to foreign key does not do that.\n self._subclass_cache = ContentType.objects.get_for_id(\n self.subclass_id)\n # Initialise \"cache\" for subclass_instance if the current object is\n # already of the appropriate class, to avoid implicitly reloading it on\n # accessing the subclass_instance property.\n if not hasattr(self, '_subclass_instance_cache'):\n if self.__class__ == self.subclass.model_class():\n self._subclass_instance_cache = self\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.subclass`` is changed.\n \"\"\"\n super(StoreSubclass, self).clean()\n if not self._allow_subclass_change:\n if self._initial_subclass != self.subclass:\n raise ValidationError(\n ugettext('Changing class is not allowed.'))\n\n\nTimestampRange = namedtuple(\n 'TimestampRange', ['from_timestamp', 'to_timestamp'])\n\n\nclass DateRangeModelMixin(models.Model):\n \"\"\"\n Adds fields defining a date range to the model this mixin is mixed\n into.\n\n :ivar from_date: The first date in the date range.\n :ivar to_date: The final date in the date range. This may be ``None``.\n\n :see: :class:`gridplatform.utils.managers.DateRangeManagerMixin`\n \"\"\"\n from_date = models.DateField(_('from date'), default=get_current_date)\n to_date = models.DateField(_('to date'), null=True, blank=True)\n\n class Meta:\n abstract = True\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If date range is empty.\n \"\"\"\n if self.from_date and self.to_date and self.from_date > self.to_date:\n raise ValidationError(_('Period of existense must be non-empty.'))\n\n def timestamp_range_intersection(\n self, from_timestamp, to_timestamp, timezone):\n \"\"\"\n :return: The timestamp range intersection between a given\n timestamp range and this date range. If the result is empty\n ``None`` is returned.\n\n :param from_timestamp: The start of the given timestamp range.\n :param to_timestamp: The end of the given timestamp range.\n :param timezone: The timestamp range that corresponds to this\n date range is only well-defined given a timezone.\n \"\"\"\n range_from_timestamp = timezone.localize(\n datetime.datetime.combine(self.from_date, datetime.time()))\n result_from_timestamp = max([from_timestamp, range_from_timestamp])\n\n if self.to_date is not None:\n range_to_timestamp = timezone.localize(\n datetime.datetime.combine(\n self.to_date + datetime.timedelta(days=1),\n datetime.time()))\n result_to_timestamp = min([to_timestamp, range_to_timestamp])\n else:\n result_to_timestamp = to_timestamp\n\n if result_from_timestamp <= result_to_timestamp:\n return TimestampRange(result_from_timestamp, result_to_timestamp)\n else:\n return None\n\n\nclass TimestampRangeModelMixin(models.Model):\n \"\"\"\n Adds fields defining a timestamp range to the model this mixin is\n mixed into.\n\n :ivar from_timestamp: The first timestamp in the timestamp range.\n :ivar to_timestamp: The final timestamp in the timestamp range.\n This may be ``None``.\n\n :see: :class:`gridplatform.utils.managers.TimestampRangeManagerMixin`\n \"\"\"\n from_timestamp = models.DateTimeField(_('from time'))\n to_timestamp = models.DateTimeField(_('to time'), blank=True, null=True)\n\n class Meta:\n abstract = True\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If timestamp range is empty.\n \"\"\"\n super(TimestampRangeModelMixin, self).clean()\n if self.from_timestamp and self.to_timestamp and \\\n self.from_timestamp >= self.to_timestamp:\n raise ValidationError(_('Period of existense must be non-empty.'))\n\n def format_timestamp_range_unicode(self, description, timezone):\n \"\"\"\n Helper function for implementing ``unicode()`` in subclasses.\n\n :return: A given ``description`` prefixed with a human\n readable representation of the timestamp range in given\n ``timezone``.\n \"\"\"\n if self.to_timestamp is not None:\n return '{from_timestamp} - {to_timestamp}: {description}'.format(\n from_timestamp=date_format(\n timezone.normalize(\n self.from_timestamp.astimezone(timezone)),\n 'SHORT_DATETIME_FORMAT'),\n to_timestamp=date_format(\n timezone.normalize(\n self.to_timestamp.astimezone(timezone)),\n 'SHORT_DATETIME_FORMAT'),\n description=description)\n else:\n return '{from_timestamp} - ...: {description}'.format(\n from_timestamp=date_format(\n timezone.normalize(\n self.from_timestamp.astimezone(timezone)),\n 'SHORT_DATETIME_FORMAT'),\n description=description)\n\n def overlapping(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: The intersection between a given timestamp range and this\n timestamp range. If the intersection is empty an interval\n with negative duration is returned.\n\n :param from_timestamp: The start of the given timestamp range.\n :param to_timestamp: The end of the given timestamp range.\n \"\"\"\n result_from = max(from_timestamp, self.from_timestamp)\n if self.to_timestamp:\n result_to = min(to_timestamp, self.to_timestamp)\n else:\n result_to = to_timestamp\n return (result_from, result_to)\n" }, { "alpha_fraction": 0.6454231142997742, "alphanum_fraction": 0.6502590775489807, "avg_line_length": 43.652957916259766, "blob_id": "365b15f3bbef01ddf49b71412300d9caf05d9d76", "content_id": "d5d80951e07f016b25d0e5187cb61dbeeb0120c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17373, "license_type": "no_license", "max_line_length": 83, "num_lines": 389, "path": "/legacy/measurementpoints/models/degreedays.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport itertools\nimport logging\n\nfrom django.db import models\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.iter_ext import count_extended\nfrom gridplatform.utils.iter_ext import flatten\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.iter_ext import pairwise_extended\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import condense\n\nfrom .dataseries import DataSeries\nfrom .dataseries import UndefinedSamples\nfrom .mixins import VariablyBoundAccumulationMixin\nfrom ..fields import DataRoleField\n\n\nlogger = logging.getLogger(__name__)\n\n\ncelsius_base = PhysicalQuantity('273.15', 'kelvin')\ndegree_day_base = celsius_base + PhysicalQuantity(17, 'kelvin')\n\n\ndef _inject_interpolated(ds, from_timestamp, to_timestamp, timestamp_sequence):\n # Assuming that ds.get_samples(from_timestamp, to_timestamp) includes\n # interpolated or extrapolated samples at the endpoints, and that\n # from_timestamp and to_timestamp are elements in timestamp_sequence, this\n # returns a sequence of samples where samples at the time points specified\n # in timestamp_sequence (until to_timestamp) are guaranteed to be included;\n # either from the \"raw\" sequence or through interpolation of elements from\n # the \"raw\" sequence.\n\n # NTS: generalise/make into DS method raw_with_interpolated()?\n def interpolate(t, before, after):\n return ds._interpolate_extrapolate_sample(\n t, data_before=before, data_after=after)\n\n temperatures = ds.get_samples(from_timestamp, to_timestamp)\n temperature_pairs = pairwise_extended(temperatures)\n\n timestamp = next(timestamp_sequence)\n for t0, t1 in temperature_pairs:\n # requested period may start before available data...\n while timestamp < t0.timestamp:\n timestamp = next(timestamp_sequence)\n yield t0\n if t1 is None:\n return\n if t1.timestamp > timestamp:\n # may need to inject one or more interpolated values...\n if t0.timestamp == timestamp:\n # timestamp is represented; has been yielded\n timestamp = next(timestamp_sequence)\n assert t0.timestamp < timestamp\n while timestamp < t1.timestamp:\n assert from_timestamp <= timestamp <= to_timestamp\n yield interpolate(timestamp, t0, t1)\n timestamp = next(timestamp_sequence)\n\n\ndef _temperature_pair_value(t0, t1):\n # NOTE: module-level rather than inner function in get_samples()\n # to make explicit that it does not use variables from that context...\n assert t0 is not None\n assert t1 is not None\n seconds = (t1.timestamp - t0.timestamp).total_seconds()\n val0 = degree_day_base - t0.physical_quantity\n val1 = degree_day_base - t1.physical_quantity\n return ((val0 + val1) / 2) * PhysicalQuantity(seconds, 'second')\n\n\nclass HeatingDegreeDays(VariablyBoundAccumulationMixin, DataSeries):\n \"\"\"\n Data series computing \"degree days\" based on some temperature data series.\n\n For each day with an average temperature under 17 °C, the number of \"degree\n days\" is the difference between 17 °C and the average temperature for that\n day. For days with average temperature at or above 17 °C, the number of\n \"degree days\" is 0. For a period of several days, the number of degree\n days is the sum of the degree days for each day contained therein. The\n concept of degree days is not defined for timespans shorter than a day.\n\n C{HeatingDegreeDays} are only defined for whole days, and L{get_samples}\n and L{get_condensed_samples} will raise L{UndefinedSamples} if called with\n odd or too short periods (C{from_timestamp}, C{to_timestamp}) or too small\n sample_resolution.\n \"\"\"\n derived_from = models.ForeignKey(\n DataSeries, on_delete=models.CASCADE,\n related_name='heatingdegreedays_derivative_set')\n\n class Meta(DataSeries.Meta):\n app_label = 'measurementpoints'\n\n def clean(self):\n if self.role is None:\n self.role = DataRoleField.HEATING_DEGREE_DAYS\n if not self.unit:\n self.unit = 'kelvin*day'\n if self.derived_from is not None:\n if self.derived_from.role != DataRoleField.ABSOLUTE_TEMPERATURE:\n raise ValidationError(\n _('Heating degree days can only be defined in '\n 'terms of absolute temperatures.'))\n if not PhysicalQuantity.compatible_units(\n self.derived_from.unit, 'kelvin'):\n raise ValidationError('Unit %s on temperature data series not '\n 'usable for HeatingDegreeDays')\n super(HeatingDegreeDays, self).clean()\n\n def _get_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n Return a sequence of computed daily accumulated degree days since\n from_timestamp.\n\n @raise UndefinedSamples: If C{from_timestamp} or C{to_timestamp} are\n not midnights.\n \"\"\"\n # For each day, compute average temperature, subtract 17 degrees\n # Celsius, round negative numbers to 0, and return as kelvin*day ...\n\n # Unit should be \"kelvin*day\" --- but need not be represented by that\n # exact string...\n sample_resolution = RelativeTimeDelta(days=1)\n timezone = from_timestamp.tzinfo\n assert timezone is not None\n assert PhysicalQuantity.same_unit(self.unit, 'kelvin*day')\n if condense.floor(\n from_timestamp, sample_resolution, timezone) != from_timestamp or \\\n condense.floor(\n to_timestamp, sample_resolution, timezone) != to_timestamp:\n raise UndefinedSamples(\n _('Warning: Heating degree days are only defined for '\n 'days or larger resolutions.'))\n\n # temperature sample pairs, extended with (interpolated) values for\n # each \"midnight\"\n temperature_pairs = pairwise_extended(_inject_interpolated(\n self.derived_from, from_timestamp, to_timestamp,\n count_extended(from_timestamp, sample_resolution)))\n\n try:\n t0, t1 = next(temperature_pairs)\n except StopIteration:\n # no data at all...\n # NOTE: Just letting the StopIteration exception pass through\n # should work, but this makes handling of that edge case --- that\n # nothing should be returned if there is no \"raw\" data to base the\n # computation on --- clearer/more explicit.\n return\n\n accumulated = PhysicalQuantity(0, self.unit)\n # We yield accumulated values since from_timestamp --- the accumulated\n # value at from_timestamp should be 0.\n #\n # NOTE: *After* reading from temperature_pairs --- if there is no data\n # at all, we already returned without yielding anything at all.\n if t0.timestamp > from_timestamp:\n # Extrapolate to 0 degree-days before first actual measurement.\n for t in count_extended(from_timestamp, RelativeTimeDelta(days=1)):\n if t < t0.from_timestamp:\n yield self.create_point_sample(\n t, accumulated, uncachable=True, extrapolated=True)\n else:\n break\n\n from_timestamp = t\n # \"Real\" data starts at this new from_timestamp ...\n while t1 is not None and t1.timestamp <= from_timestamp:\n # Skip ahead in temperature input until the start of the first\n # \"whole\" day. When t1.timestamp == from_timestamp, next will\n # have t0.timestamp == from_timestamp ...\n t0, t1 = next(temperature_pairs)\n yield self.create_point_sample(\n from_timestamp, accumulated,\n uncachable=t0.uncachable, extrapolated=t0.extrapolated)\n if t1 is None and from_timestamp != to_timestamp:\n assert from_timestamp != to_timestamp\n yield self.create_point_sample(\n to_timestamp, accumulated,\n uncachable=True, extrapolated=t0.extrapolated)\n return\n\n time_periods = itertools.takewhile(\n lambda (t0, t1): t0 < to_timestamp,\n pairwise(\n count_extended(from_timestamp, RelativeTimeDelta(days=1))))\n\n zero_kelvin_days = PhysicalQuantity(0, 'kelvin*day')\n\n for day_begin, day_end in time_periods:\n day_accumulated = PhysicalQuantity(0, self.unit)\n uncachable = False\n extrapolated = False\n assert t1 is None or t0.timestamp == day_begin\n while t1 is not None and t1.timestamp <= day_end:\n uncachable = uncachable or t0.uncachable or t1.uncachable\n extrapolated = extrapolated or \\\n t0.extrapolated or t1.extrapolated\n day_accumulated += _temperature_pair_value(t0, t1)\n t0, t1 = next(temperature_pairs)\n if t0.timestamp == day_end:\n # Increment total accumulated normally for day\n assert t1 is None or t1.timestamp > day_end\n day_accumulated = max(day_accumulated, zero_kelvin_days)\n accumulated += day_accumulated\n else:\n # No more data; total accumulated stays constant; data is\n # extrapolation\n assert t1 is None\n uncachable = True\n extrapolated = True\n # Yield real or extrapolated data...\n assert from_timestamp <= day_end <= to_timestamp\n yield self.create_point_sample(\n day_end, accumulated,\n uncachable=uncachable, extrapolated=extrapolated)\n\n def depends_on(self):\n return [self.derived_from] + self.derived_from.depends_on()\n\n def get_recursive_condense_resolution(self, resolution):\n if condense.is_coarser_resolution(resolution, condense.DAYS):\n return condense.next_resolution(resolution)\n else:\n return None\n\n\nclass DegreeDayCorrection(DataSeries):\n \"\"\"\n Data series computing \"degree day corrected consumption\", based on actual\n consumption, actual degree days, and \"standard degree days\" to normalise\n against.\n\n For any requested period, the total consumption is normalised against the\n total number of actual and standard degree days. In particular, this means\n that partitioning a period and computing corrected consumption for each\n part is unlikely to give results that sum up to the same as the corrected\n consumption for the entire period...\n\n @note: This is a generalisation of the specification of \"monthly corrected\n consumption\" and \"yearly corrected consumption\" --- both defined in terms\n of total consumption and total number of degree days in the periods.\n\n get_samples() will raise NotImplementedError, as it cannot be\n correctly implemented.\n \"\"\"\n consumption = models.ForeignKey(\n DataSeries, on_delete=models.PROTECT,\n related_name='degreedayscorrectionconsumption_derivative_set')\n\n standarddegreedays = models.ForeignKey(\n DataSeries, on_delete=models.PROTECT,\n related_name='degreedayscorrectionstandardegreedays_derivative_set')\n\n degreedays = models.ForeignKey(\n DataSeries, on_delete=models.PROTECT,\n related_name='degreedayscorrectiondegreedaysn_derivative_set')\n\n class Meta(DataSeries.Meta):\n app_label = 'measurementpoints'\n\n def clean(self):\n if self.role is None:\n self.role = DataRoleField.CONSUMPTION\n if self.consumption and \\\n self.consumption.role != DataRoleField.CONSUMPTION:\n raise ValidationError('DegreeDayCorrection must apply to a '\n 'CONSUMPTION data series')\n # will probably need to check for HEATING_XXX or COOLING_XXX, when\n # cooling degree days are introduced (if ever).\n if self.standarddegreedays and \\\n self.standarddegreedays.role != \\\n DataRoleField.STANDARD_HEATING_DEGREE_DAYS:\n raise ValidationError(\n 'standarddegreedays for DegreeDayCorrection '\n 'does not have role STANDARD_HEATING_DEGREE_DAYS')\n if self.degreedays and \\\n self.degreedays.role != DataRoleField.HEATING_DEGREE_DAYS:\n raise ValidationError(\n 'degreedays for DegreeDayCorrection does not '\n 'have role HEATING_DEGREE_DAYS')\n return super(DegreeDayCorrection, self).clean()\n\n def save(self, *args, **kwargs):\n self.clean()\n super(DegreeDayCorrection, self).save(*args, **kwargs)\n\n def _get_samples(self, from_timestamp, to_timestamp):\n raise NotImplementedError('raw data samples is not well-defined for '\n 'DegreeDayCorrection')\n\n @staticmethod\n def _corrected_sample(consumption, standarddegreedays, degreedays):\n \"\"\"\n \"Correct\" a single consumption sample wrt. the ratio between the\n specified standarddegreedays and degreedays samples. If the numeric\n value for standarddegreedays or degreedays is 0, the value in the\n \"corrected\" sample is the same as in the original.\n \"\"\"\n samples = [consumption, standarddegreedays, degreedays]\n cachable = any([s.cachable for s in samples])\n extrapolated = any([s.extrapolated for s in samples])\n\n if not standarddegreedays.physical_quantity or \\\n not degreedays.physical_quantity:\n # no \"correction\" --- but still mark as cachable/not depending on\n # whether the degree days values leading to this are cachable...\n return consumption._replace(\n cachable=cachable,\n extrapolated=extrapolated)\n\n val = consumption.physical_quantity * \\\n standarddegreedays.physical_quantity / degreedays.physical_quantity\n return consumption._replace(\n physical_quantity=val,\n cachable=cachable,\n extrapolated=extrapolated)\n\n def calculate_development(self, from_timestamp, to_timestamp):\n \"\"\"\n Calculate corrected development over a period, i.e. \"normalise\" total\n consumption in period wrt. total degree days in period.\n \"\"\"\n assert PhysicalQuantity.same_unit(self.unit, self.consumption.unit)\n consumption = self.consumption.subclass_instance.calculate_development(\n from_timestamp, to_timestamp)\n standarddegreedays = \\\n self.standarddegreedays.subclass_instance.calculate_development(\n from_timestamp, to_timestamp)\n degreedays = self.degreedays.subclass_instance.calculate_development(\n from_timestamp, to_timestamp)\n if any([s is None\n for s in consumption, standarddegreedays, degreedays]):\n return None\n\n return self._corrected_sample(\n consumption, standarddegreedays, degreedays)\n\n def _condense_data_samples_recursive(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Compute/construct condensed data samples in the specified resoulution,\n based on condensed data from the consumption, standarddegreedays and\n degreedays data series with the same resolution.\n\n Overrides DataSeries._condense_data_samples_recursive(); used by\n get_condensed_samples().\n \"\"\"\n assert PhysicalQuantity.same_unit(self.unit, self.consumption.unit)\n consumption = self.consumption.subclass_instance\n consumption_condensed = consumption.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n standarddegreedays = self.standarddegreedays.subclass_instance\n standarddegreedays_condensed = \\\n standarddegreedays.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n degreedays = self.degreedays.subclass_instance\n degreedays_condensed = degreedays.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n\n for consumption, standarddegreedays, degreedays in itertools.izip(\n consumption_condensed, standarddegreedays_condensed,\n degreedays_condensed):\n assert consumption.from_timestamp == \\\n standarddegreedays.from_timestamp\n assert standarddegreedays.from_timestamp == \\\n degreedays.from_timestamp\n\n yield self._corrected_sample(\n consumption, standarddegreedays, degreedays)\n\n def depends_on(self):\n \"\"\"\n @see L{DataSeries.depends_on()}\n \"\"\"\n others = [self.consumption.subclass_instance,\n self.standarddegreedays.subclass_instance,\n self.degreedays.subclass_instance]\n return others + list(flatten([o.depends_on() for o in others]))\n" }, { "alpha_fraction": 0.5313959717750549, "alphanum_fraction": 0.5346133708953857, "avg_line_length": 35.80290222167969, "blob_id": "f497753d7f9db2a14baec4d24c5d7b9536071647", "content_id": "d32939d442377aa9afe1c34862d931b869262cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 48175, "license_type": "no_license", "max_line_length": 145, "num_lines": 1309, "path": "/legacy/website/static/website.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true, devel: true */\n/*global $, jQuery, gettext, pgettext, get_format, noty */\n\nvar gridportal = gridportal || {};\ngridportal.website = gridportal.website || {};\n\n// http://blogs.msdn.com/b/ie/archive/2010/09/03/same-markup-using-canvas-audio-and-video.aspx\ngridportal.website.isCanvasSupported = !!window.HTMLCanvasElement;\ngridportal.website.generateGraphs = function (graphs, callback) {\n 'use strict';\n if (gridportal.website.isCanvasSupported) {\n if (callback !== undefined) {\n callback(graphs);\n }\n } else {\n graphs.html(gettext(\"Can't display graph, please upgrade your browser\"));\n }\n};\n\n\ngridportal.website.notify = function (type, msg, timeout) {\n 'use strict';\n var timeout_time = 3000;\n if (typeof(timeout) != 'undefined') {\n timeout_time = timeout;\n }\n\n noty({\n text: msg,\n type: type,\n dismissQueue: true,\n theme: 'gridmanager',\n layout: 'topCenter',\n timeout: timeout_time\n });\n};\n\n// Set up open/close animation for the settings menu.\ngridportal.website.slideSettings = function () {\n 'use strict';\n var slide = $('#settings-menu .slide'),\n sideId = $('body').attr('id');\n if (sideId === 'devices-page' ||\n sideId === 'locations-page' ||\n sideId === 'groups-page' ||\n sideId === 'mps-page' ||\n sideId === 'indexsettings-page' ||\n sideId === 'rules-page' ||\n sideId === 'users-page' ||\n sideId === 'userprofile-page') {\n slide.addClass('active');\n }\n slide.find('.settings-btn').click(function () {\n // when \"active\", the settings slider is open/visible\n\n if (slide.hasClass('active')) {\n // hide by sliding out\n slide.animate({top: '-67px'}, function () {\n // \"cleanup\"; use the class, remove explicit pixel value used\n // for animation\n slide.removeClass('active');\n slide.css('top', '');\n });\n } else {\n // show by sliding in\n slide.animate({top: '0px'}, function () {\n // \"cleanup\"; use the class, remove explicit pixel value used\n // for animation\n slide.addClass('active');\n slide.css('top', '');\n });\n }\n return false;\n });\n};\n\n\ngridportal.website.initInpageMenu = function (openIcon, closeIcon) {\n 'use strict';\n var inpageMenu = $('.in-page-menu'),\n contentWidth,\n menuWidth;\n inpageMenu.find('.scroller').mCustomScrollbar({\n theme: 'dark',\n scrollButtons: {\n enable: true\n },\n advanced: {\n updateOnBrowserResize: true,\n updateOnContentResize: true\n }\n });\n\n contentWidth = $('.in-page-menu .scroller').width();\n menuWidth = parseInt(contentWidth, 10) + 2;\n\n\n $('#content-main').css('min-height', inpageMenu.height() + 'px');\n\n if (contentWidth > 900) {\n menuWidth = 922;\n $('.in-page-menu .menu-content').css({\n 'overflow-x': 'scroll',\n width: '900px'\n });\n }\n\n $('.in-page-menu').css({left: '-' + menuWidth + 'px'});\n\n $('.in-page-menu .menu-btn').click(function () {\n var menu = $(this).closest('.in-page-menu'),\n menuImg = $(this).find('img');\n\n if (menu.hasClass('open')) {\n contentWidth = $('.in-page-menu .scroller').width();\n menuWidth = parseInt(contentWidth, 10) + 2;\n menu.removeClass('open');\n menuImg.attr('src', openIcon);\n menu.animate({left: '-' + menuWidth + 'px'});\n } else {\n contentWidth = $('.in-page-menu .scroller').width();\n menuWidth = parseInt(contentWidth, 10) + 12;\n menu.addClass('open');\n menuImg.attr('src', closeIcon);\n menu.animate({left: '-2px'});\n }\n });\n};\n\n// Error handler for ajax requests --- show noty-notification with error message reported by browser.\n// NOTE: Must be explicitly bound to the error callbacks; i.e. not implicitly used.\n// NOTE: The error message from the browser (textStatus) might not be all that useful; consider removing it again...\ngridportal.website.ajaxError = function (jqXHR, textStatus) {\n 'use strict';\n var status = jqXHR.status,\n errorType;\n if (500 <= status && status < 600) {\n // server error\n errorType = gettext('Server error.');\n } else if (400 <= status && status < 500) {\n // client error\n errorType = gettext('Error.');\n } else {\n // no connection to server?\n errorType = gettext('Could not contact server.');\n }\n gridportal.website.notify('error', errorType + ' (' + textStatus + ')');\n};\n\n\ngridportal.website.overlay = {};\n\ngridportal.website.overlay.placement = function (listItem, form) {\n 'use strict';\n var listItemPosition = listItem.position(),\n initialLeft = listItem.closest('.content-element').width(),\n left = listItemPosition.left,\n top = listItemPosition.top;\n\n listItem.css({overflow: 'hidden'});\n form.css({\n left: initialLeft,\n top: top,\n position: 'absolute',\n width: listItem.width()\n });\n form.insertAfter(listItem);\n\n return {\n height: form.height(),\n left: left\n };\n};\n\n\n// Insert overlay, make it cover content as overlay with slide-in animation\ngridportal.website.overlay.slidein = function (content, overlay) {\n 'use strict';\n var li = content.closest('li'),\n deleteBtn = overlay.find('.delete'),\n height;\n overlay.css({\n position: 'absolute',\n left: $('#content-main').width(),\n top: content.position().top,\n width: content.width()\n });\n overlay.insertAfter(content);\n deleteBtn.each(function () {\n var btn = $(this);\n btn.tooltip({\n content: btn.data('reason')\n });\n });\n overlay.find('select').chosen({enable_split_word_search: true, search_contains: true});\n\n $('input[type=submit], button').click(function () {\n overlay.find('.overlay-header .right').prepend('<img src=\"' + $('.list-block').data('spinner') + '\" class=\"list-spinner\">');\n });\n height = overlay.height();\n\n if (height < content.height()) {\n height = content.height();\n overlay.css({height: height});\n }\n overlay.find('.image a').fancybox({type: 'image'});\n overlay.find('.date').datepicker();\n\n overlay.find('.datetime').datetimepicker({\n timeFormat: 'HH:mm:ss',\n addSliderAccess: true,\n sliderAccessArgs: { touchonly: false }\n });\n overlay.find('select').on('change', function () {\n content.animate({height: overlay.height()});\n });\n content.animate({height: height});\n overlay.animate({left: content.position().left}, function () {\n li.css('overflow', 'visible');\n li.parents('li').css('overflow', 'visible');\n });\n\n};\n\n\n// Slide overlay out and readjust content height to its \"natural\" height.\n// Remove the parent li after the animation if \"remove\" is specified.\n// (\"Remove\" is used when adding a list item is cancelled, i.e. the newly\n// inserted element should be completely removed rather than reverted to some\n// previous state.)\ngridportal.website.overlay.slideout = function (content, overlay, remove) {\n 'use strict';\n // Check the required height of the content by making a copy with\n // \"automatic\" height, inserting that in the DOM inside the same li as the\n // content, measuring it and removing the copy again.\n var li = content.closest('li'),\n copy = content.clone().css('height', '').appendTo(li),\n height = copy.height();\n copy.remove();\n li.css('overflow', 'hidden');\n li.parents('li').css('overflow', 'hidden');\n content.animate({height: height}, function () {\n content.css('height', '');\n });\n overlay.animate({left: content.width()}, function () {\n overlay.remove();\n if (remove) {\n li.remove();\n }\n });\n};\n\n\n// Open/slide in a form to edit a specific list-item entry.\n// The original contents (to be hidden) must be inside an element with class\n// \"list-item\", and that element should have the url to fetch the form in its\n// \"url\" data property. (data-url attribute or otherwise accessible to jQuerys\n// .data())\n// NOTE: To be bound to the \"open\" button/elemen.\ngridportal.website.overlay.open = function (event) {\n 'use strict';\n var listItem = $(this).closest('li'),\n content = $(this).closest('li > div'),\n overlayUrl = content.data('url'),\n dialog;\n // When executing this open method, and the listitem already has\n // isOpen class set, stop doing anything; let the slide-in method\n // do it's job.\n if (listItem.hasClass('isOpen')) {\n return;\n }\n\n // If another form is open, warn the user about this\n if ($('.isOpen').length > 0) {\n dialog = $('<div>').attr('id', 'formDialog').html(gettext(\"Another form is currently open.<br> Do you want to discard this?\"));\n dialog.dialog({\n title: gettext(\"Information\"),\n modal: true,\n width: 350,\n buttons: [\n {\n text: gettext('Discard'),\n click: function () {\n // Sliding out previous form\n var li = $('.isOpen'),\n previousContent = li.children('div').first(),\n previousOverlay = li.find('div:nth-child(2)');\n\n if (li.hasClass('new')) {\n gridportal.website.overlay.slideout(previousContent, previousOverlay, true);\n } else {\n gridportal.website.overlay.slideout(previousContent, previousOverlay, content.html() === '');\n li.removeClass('isOpen');\n }\n\n // Now sliding in desired form\n jQuery.get(overlayUrl).success(function (data) {\n gridportal.website.overlay.slidein(content, $(data));\n }).error(gridportal.website.ajaxError);\n listItem.addClass('isOpen');\n\n $(this).dialog('close');\n }\n },\n {\n text: gettext('Jump to form'),\n click: function () {\n $('html, body').animate({\n scrollTop: $(\".isOpen\").offset().top\n }, 100);\n\n $(this).dialog('close');\n }\n },\n {\n text: gettext('Abort'),\n click: function () {\n $(this).dialog('close');\n }\n }\n ]\n });\n } else {\n jQuery.get(overlayUrl).success(function (data) {\n gridportal.website.overlay.slidein(content, $(data));\n }).error(gridportal.website.ajaxError);\n listItem.addClass('isOpen');\n }\n if (event) {\n event.preventDefault();\n event.stopPropagation();\n }\n};\n\n\n// Close/slide out an edit form. The \"original\" content should be the first\n// div under the parent li, while the form to slide out should be the div\n// containing the element triggering the event... If the \"original\" content is\n// empty (i.e. a div with no children or text inside), we also remove the li.\n// (... that should normally be the case when \"cancel\" adding a new item ---\n// but in any concievably other case where we have no actual content, not\n// displaying that particular lack of content should be fine.)\n// NOTE: To be bound to the \"close\" button/elemen.\ngridportal.website.overlay.close = function (event) {\n 'use strict';\n var li = $(this).closest('li'),\n content = li.children('div').first(),\n overlay = $(this).closest('li > div');\n\n gridportal.website.overlay.slideout(content, overlay, content.html() === '');\n li.removeClass('isOpen');\n if (event) {\n event.preventDefault();\n event.stopPropagation();\n }\n};\n\n\n// Special case of overlay.open for new objects; adds list item to list\n// element, sets special case close to remove the list item if closed without\n// saving.\n// NOTE: Not reusing gridportal.website.overlay.open --- that would entail\n// adding the li to the DOM before the ajax-call --- or adding extra complexity\n// to that function...\ngridportal.website.overlay.openNew = function (list, url, callback) {\n 'use strict';\n if ($('.isOpen').length > 0) {\n var dialog = $('<div>').attr('id', 'formDialog').html(gettext(\"Another form is currently open.<br> Do you want to discard this?\"));\n dialog.dialog({\n title: gettext(\"Information\"),\n modal: true,\n width: 350,\n buttons: [\n {\n text: gettext('Discard'),\n click: function () {\n // Sliding out previous form\n var li = $('.isOpen'),\n previousContent = li.children('div').first(),\n previousOverlay = li.find('div:nth-child(2)');\n\n if (li.hasClass('new')) {\n gridportal.website.overlay.slideout(previousContent, previousOverlay, true);\n } else {\n gridportal.website.overlay.slideout(previousContent, previousOverlay, false);\n li.removeClass('isOpen');\n }\n\n // Now sliding in desired form\n gridportal.website.overlay.doOpenNew(list, url, callback);\n\n $(this).dialog('close');\n }\n },\n {\n text: gettext('Jump to form'),\n click: function () {\n $('html, body').animate({\n scrollTop: $(\".isOpen\").offset().top\n }, 100);\n\n $(this).dialog('close');\n }\n },\n {\n text: gettext('Abort'),\n click: function () {\n $(this).dialog('close');\n }\n }\n ]\n });\n } else {\n gridportal.website.overlay.doOpenNew(list, url, callback);\n }\n};\n\n\ngridportal.website.overlay.doOpenNew = function (list, url, callback) {\n 'use strict';\n jQuery.get(url).success(function (data, textStatus, jqXHR) {\n // check content-type --- on wizards, all pages return JSON; on simple\n // forms, the initial form is plain html\n var contentType = jqXHR.getResponseHeader('Content-Type'),\n isHtml = contentType.indexOf('text/html') !== -1,\n html = isHtml ? $(data) : $(data.html),\n li = $('<li class=\"new isOpen\"></li>'),\n content = $('<div></div>').appendTo(li);\n li.prependTo(list);\n gridportal.website.overlay.slidein(content, html);\n if (callback) {\n callback(li);\n }\n }).error(gridportal.website.ajaxError);\n};\n\n\n// Special case of overlay.close for new objects; removes the list item. (To\n// be used for close without saving.) Returns false, so that, when used as an\n// event handler, the event is not propagated --- useful when the event would\n// otherwise propagate to the \"common-case\" close() function.\ngridportal.website.overlay.closeNew = function (event) {\n 'use strict';\n var li = $(this).closest('li'),\n content = li.children('div').first(),\n overlay = $(this).closest('li > div');\n gridportal.website.overlay.slideout(content, overlay, true);\n if (event) {\n event.preventDefault();\n event.stopPropagation();\n }\n return false;\n};\n\n\n// Error handler for overlay submit\ngridportal.website.overlay.removeSpinnerajaxError = function (jqXHR, textStatus) {\n 'use strict';\n var spinner = $('.list-spinner'),\n header = spinner.parent();\n gridportal.website.ajaxError(jqXHR, textStatus);\n spinner.remove();\n header.find('.error').remove();\n header.prepend('<span class=\"error\">'+ gettext('An error accurred while saving. Please try again.') + '</span>');\n header.find('input[type=submit]').removeAttr('disabled');\n};\n\n\n// Submit handler for overlay/inline forms.\n//\n// URL from action attribute of form.\n//\n// Expects JSON dictionary with entries success, statusText, html from\n// back-end. \"success\" should be true and \"statusText\" set to something\n// appropriate to display on successful save. \"html\" should contain the\n// rendered non-form data element on success; rendered form with errors on\n// failure. Callback can be used to modify the resulting html to insert ---\n// should normally not be specified.\n//\n// The area that will be replaced with the \"html\" given to us on both failure\n// and success must have the class \"slide-in-overlay\".\ngridportal.website.overlay.submit = function (event, callback) {\n 'use strict';\n event.preventDefault();\n var form = $(this),\n form_data,\n content_type,\n request;\n form.find(\"input[type=submit]\").attr(\"disabled\", \"disabled\");\n function successHandler(data, statusText, jqXHR) {\n //check content-type --- we have multi-page creation (measuring\n //points/...) where the first page is a POST returning a HTML form...\n var contentType = jqXHR.getResponseHeader('Content-Type'),\n isHtml = contentType.indexOf('text/html') !== -1,\n html = isHtml ? $(data) : $(data.html),\n li = form.closest('li'),\n content = li.children('div').first(),\n overlay = form.closest('.slide-in-overlay'),\n list,\n searchField;\n if (callback) {\n callback.call(html);\n }\n if (!data.success) {\n overlay = html.css({\n position: overlay.css('position'),\n left: overlay.css('left'),\n top: overlay.css('top'),\n width: overlay.css('width')\n }).replaceAll(overlay);\n\n noty({\n text: data.statusText,\n type: 'error',\n dismissQueue: true,\n theme: 'gridmanager',\n layout: 'topCenter',\n timeout: 3000\n });\n\n $('select').not('.empty-form select').chosen({enable_split_word_search: true, search_contains: true});\n $('select').on('change', function () {\n content.animate({height: overlay.height()});\n });\n content.animate({height: overlay.height()});\n overlay.find('input[type=submit], button').click(function () {\n overlay.find('.overlay-header .right').prepend('<img src=\"' + $('.list-block').data('spinner') + '\" class=\"list-spinner\">');\n });\n } else {\n // success...\n content = html.css({\n height: content.css('height')\n }).replaceAll(content);\n list = li.closest('.list-block');\n searchField = list.find('input[name=search]');\n\n // tree structured data --- item has a \"parent\", and we're not in\n // search mode...\n if (data.parent !== undefined && searchField.filter('.labelinside').size() > 0) {\n (function () {\n var parent,\n parentLi,\n ul;\n if (data.parent > 0) {\n parent = list.find('div[data-id=' + data.parent + ']');\n parentLi = parent.closest('li');\n ul = parentLi.children('ul');\n if (!ul.size()) {\n ul = $('<ul></ul>').appendTo(parentLi);\n }\n li.appendTo(ul);\n }\n }());\n }\n gridportal.website.overlay.close.call(overlay);\n noty({\n text: data.statusText,\n type: 'success',\n dismissQueue: true,\n theme: 'gridmanager',\n layout: 'topCenter',\n timeout: 3000\n });\n }\n }\n if (form.find('input[type=file]').length > 0) {\n // Setting contentType option to false,\n // forcing jQuery not to add a Content-Type header,\n // otherwise, the boundary string will be missing from it.\n form_data = new FormData(form[0]);\n content_type = false;\n } else {\n form_data = form.serialize();\n content_type = \"application/x-www-form-urlencoded\";\n }\n request = jQuery.ajax({\n url: form.attr('action'),\n type: \"POST\",\n data: form_data,\n contentType: content_type,\n processData: false,\n success: successHandler,\n error: gridportal.website.overlay.removeSpinnerajaxError\n });\n};\n\ngridportal.website.deleteItem = function (event) {\n 'use strict';\n var deleteBtn = $(this),\n self = this,\n btns = {},\n url = deleteBtn.data('deleteurl'),\n dialog;\n event.preventDefault();\n if (!deleteBtn.data('reason')) {\n dialog = $('<div>').attr('id', 'formDialog').html(gettext(\"Are you sure you want to delete?\"));\n $('body').append(dialog);\n dialog.find(':submit').hide();\n btns[gettext('Ok')] = function () {\n jQuery.getJSON(url, {pk: deleteBtn.closest('form').find('[name=item_id]').val()}, function (data) {\n gridportal.website.overlay.closeNew.call(self);\n noty({\n text: data.statusText,\n type: 'success',\n dismissQueue: true,\n theme: 'gridmanager',\n layout: 'topCenter',\n timeout: 3000\n });\n });\n $(this).dialog('close');\n };\n btns[gettext('Cancel')] = function () {\n $(this).dialog('close');\n $('.list-spinner').remove();\n };\n dialog.dialog({\n title: gettext(\"Delete\"),\n modal: true,\n buttons: btns,\n close: function () {$(this).remove(); },\n width: 'auto',\n open: function (event, ui) {\n var dialog = $(event.target).parents(\".ui-dialog.ui-widget\"),\n buttons = dialog.find(\".ui-dialog-buttonpane\").find(\"button\");\n buttons.each(function () {\n $(this).addClass('btn').removeClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover');\n });\n }\n });\n } else {\n dialog = $('<div>').attr('id', 'formDialog').html(deleteBtn.data(\"reason\"));\n $('body').append(dialog);\n dialog.find(':submit').hide();\n dialog.dialog({\n title: gettext(\"Delete\"),\n modal: true,\n buttons: {\n 'Ok': function () {\n $(this).dialog('close');\n }\n },\n close: function () {$(this).remove();\n $('.list-spinner').remove();},\n width: 'auto',\n open: function (event, ui) {\n var dialog = $(event.target).parents(\".ui-dialog.ui-widget\"),\n buttons = dialog.find(\".ui-dialog-buttonpane\").find(\"button\");\n // TOOD: fix, as for the other one...\n buttons.each(function () {\n $(this).addClass('btn').removeClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover');\n });\n }\n });\n }\n};\n\n\n// Show delete dialog, and if user clicks OK, send a synchroneous POST of the\n// specified pk to the url.\n// csrftoken should be HTML for CSRF form hidden field --- what we get from {%\n// csrf_token %} in a Django template.\n// (This constructs a form, and then submits it, not using AJAX.)\ngridportal.website.synchroneousDelete = function (url, pk, redirectUrl) {\n 'use strict';\n var deleteBtn = $('input[name=delete]'), dialog, buttons, message;\n if (!deleteBtn.data('message')){\n message = gettext(\"Are you sure you want to delete this?\");\n } else {\n message = deleteBtn.data('message');\n }\n\n if (!deleteBtn.data('reason')) {\n $('<div></div>').text(message).dialog({\n title: gettext(\"Delete\"),\n modal: true,\n buttons: [\n {\n text: gettext(\"Ok\"),\n click: function () {\n $.post(url, {pk: pk, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()}, function () {\n document.location = redirectUrl;\n });\n $(this).dialog('close');\n }\n },\n {\n text: gettext(\"Cancel\"),\n click: function () {\n $(this).dialog('close');\n }\n }\n ],\n close: function () {\n $(this).remove();\n },\n open: function (event) {\n dialog = $(event.target).closest(\".ui-dialog.ui-widget\");\n dialog.find(\".ui-dialog-buttonpane button\").each(function () {\n $(this).addClass('btn').removeClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover');\n });\n },\n width: 'auto'\n });\n } else {\n dialog = $('<div>').attr('id', 'formDialog').html(deleteBtn.data(\"reason\"));\n $('body').append(dialog);\n dialog.find(':submit').hide();\n dialog.dialog({\n title: gettext(\"Delete\"),\n modal: true,\n buttons: [\n {\n text: gettext(\"Ok\"),\n click: function () {\n $(this).dialog('close');\n }\n }\n ],\n close: function () {$(this).remove(); },\n width: 'auto',\n open: function (event) {\n dialog = $(event.target).parents(\".ui-dialog.ui-widget\");\n buttons = dialog.find(\".ui-dialog-buttonpane\").find(\"button\");\n // TOOD: fix, as for the other one...\n buttons.each(function () {\n $(this).addClass('btn').removeClass('ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only ui-state-hover');\n });\n }\n });\n }\n};\n\n\n\n// Set up object list with GridPortal UI conventions --- query server with sort\n// from sort buttons, filtering from search field; display pagination buttons.\n//\n// @param list: Some <div> containing the following:\n//\n// - <ul>: The list into which the loaded objects will be inserted as\n// <li></li> elements.\n//\n// - Elements with \"data-sort\" attributes. The attribute value must be valid\n// as request.GET[\"order\"] in the view. These elements will be\n// instrumented with on-click behavior that causes the ordering to change\n// to the column identified by the attribute value of \"data-sort\".\n// Repeating a click on the same element will toggle between ascending and\n// descending ordering. This is conveyed to the view through\n// request.GET[\"direction\"] which will be either \"asc\" or \"desc\".\n//\n// - <input> elements with name=\"search\": These elements will be instrumented\n// with a behaviour that causes the entire list to be reloaded with\n// request.GET[\"search\"] set to the value of the input field whenever it is\n// modified (after a reasonable time of staling).\n//\n// @param baseUrl: The full URL to the view that will render the JSON response.\n//\n// @resultsPerPage: The number of results pr page. This corresponds to\n// request.GET[\"count\"].\n//\n// @orderBy: A string corresponding to the request.GET[\"order\"] in the view\n//\n// @param callback: A function called when JSON response is received.\ngridportal.website.gmList = function (list, baseUrl, resultsPerPage, orderBy, callback) {\n \"use strict\";\n var sortButtons = list.find(\"[data-sort]\"),\n searchField = list.find(\"input[name=search]\"),\n ul = list.find(\"ul\"),\n loaderIcon = list.find(\".loader\"),\n paginator = list.find(\".paginator\"),\n orderDirection = \"asc\",\n search = \"\",\n getData,\n renderPaginator,\n renderItems,\n searchTimeout;\n\n orderBy = orderBy || \"\";\n list.find(\"[data-sort=\" + orderBy + \"]\").addClass('active');\n\n // Search field settings\n searchField.labelify({labelledClass: \"labelinside\"});\n list.find(\".clear-search-btn\").css('left', searchField.width() + 35);\n list.find(\".loader\").css('left', searchField.width() + 35);\n\n renderPaginator = function (paginator, pageCount, currentPage) {\n var i, btn;\n paginator.empty();\n for (i = 0; i < pageCount; i += 1) {\n btn = $('<span class=\"page-button\"></span>').text(i + 1).data('page', i);\n if (i === currentPage) {\n btn.addClass('active');\n }\n btn.appendTo(paginator);\n }\n paginator.find('.page-button').click(function () {\n var page = $(this).data('page');\n getData(page);\n // Scroll to the list top\n $.scrollTo(list.prev(), 400);\n });\n };\n\n renderItems = function (ul, data) {\n ul.empty();\n $.each(data, function (id, item) {\n $('<li></li>').append(item).appendTo(ul);\n });\n };\n\n getData = function (page) {\n loaderIcon.show();\n var getParams = {\n order: orderBy,\n direction: orderDirection,\n count: resultsPerPage,\n offset: page * resultsPerPage,\n search: search\n };\n jQuery.getJSON(baseUrl, getParams).success(function (response) {\n var pageCount = Math.ceil(response.total / resultsPerPage);\n renderItems(ul, response.data);\n if (callback) {\n callback();\n }\n renderPaginator(paginator, pageCount, page);\n loaderIcon.hide();\n }).error(gridportal.website.ajaxError);\n };\n\n searchField.on('keydown keyup change cut paste input', function () {\n var field = $(this);\n if (searchTimeout !== undefined) {\n window.clearTimeout(searchTimeout);\n }\n searchTimeout = window.setTimeout(function () {\n var val = field.val();\n if (field.hasClass('labelinside')) {\n val = '';\n }\n // don't trigger request/anything on e.g. releasing the shift key\n if (val !== search) {\n search = val;\n if (search.length > 0) {\n list.find('.clear-search-btn').fadeIn(300);\n } else {\n list.find('.clear-search-btn').fadeOut(300);\n }\n getData(0);\n }\n }, 200);\n });\n\n list.find('.clear-search-btn').click(function () {\n searchField.val('');\n // let labelify do its thing\n searchField.trigger('blur');\n // search/reset by triggering the normal change event handler\n searchField.trigger('change');\n });\n\n sortButtons.click(function (event) {\n var btn = $(this),\n column = btn.data('sort');\n sortButtons.not(btn).removeClass('active');\n btn.addClass('active');\n if (orderBy === column) {\n if (orderDirection === \"asc\") {\n orderDirection = \"desc\";\n } else {\n orderDirection = \"asc\";\n }\n } else {\n orderBy = column;\n orderDirection = \"asc\";\n }\n getData(0);\n });\n\n getData(0);\n};\n\n\n\n(function () {\n 'use strict';\n if (!jQuery.datepicker) {\n\treturn;\n }\n\n var pythonFormat = get_format('SHORT_DATE_FORMAT'),\n jsFormat = '',\n i,\n c,\n // Python/Django format to jQuery Datepicker format: d, j, m, n, Y, y -> dd, d, mm, m, yy, y\n // 'dd' is two-digit day, 'mm' is two-digit month, 'y' is two-digit year while 'yy' is four-digit year --- WTF?\n mapping = {\n d: 'dd',\n j: 'd',\n m: 'mm',\n n: 'm',\n Y: 'yy',\n y: 'y'\n },\n capitalize = function (str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n },\n regional = jQuery.datepicker.regional[''];\n for (i = 0; i < pythonFormat.length; i += 1) {\n c = pythonFormat.charAt(i);\n if (mapping[c]) {\n jsFormat += mapping[c];\n } else {\n jsFormat += c;\n }\n }\n regional.closeText = gettext('Done');\n regional.prevText = gettext('Prev');\n regional.nextText = gettext('Next');\n regional.currentText = gettext('Today');\n regional.monthNames = [\n capitalize(gettext('January')),\n capitalize(gettext('February')),\n capitalize(gettext('March')),\n capitalize(gettext('April')),\n capitalize(gettext('May')),\n capitalize(gettext('June')),\n capitalize(gettext('July')),\n capitalize(gettext('August')),\n capitalize(gettext('September')),\n capitalize(gettext('October')),\n capitalize(gettext('November')),\n capitalize(gettext('December'))\n ];\n regional.monthNamesShort = [\n capitalize(gettext('jan')),\n capitalize(gettext('feb')),\n capitalize(gettext('mar')),\n capitalize(gettext('apr')),\n capitalize(gettext('may')),\n capitalize(gettext('jun')),\n capitalize(gettext('jul')),\n capitalize(gettext('aug')),\n capitalize(gettext('sep')),\n capitalize(gettext('oct')),\n capitalize(gettext('nov')),\n capitalize(gettext('dec'))\n ];\n regional.dayNames = [\n gettext('Sunday'),\n gettext('Monday'),\n gettext('Tuesday'),\n gettext('Wednesday'),\n gettext('Thursday'),\n gettext('Friday'),\n gettext('Saturday'),\n gettext('Sunday')\n ];\n regional.dayNamesShort = [\n gettext('Sun'),\n gettext('Mon'),\n gettext('Tue'),\n gettext('Wed'),\n gettext('Thu'),\n gettext('Fri'),\n gettext('Sat'),\n gettext('Sun')\n ];\n regional.daysNamesMin = [\n pgettext('weekday', 'Su'),\n pgettext('weekday', 'Mo'),\n pgettext('weekday', 'Tu'),\n pgettext('weekday', 'We'),\n pgettext('weekday', 'Th'),\n pgettext('weekday', 'Fr'),\n pgettext('weekday', 'Sa'),\n pgettext('weekday', 'Su')\n ];\n regional.weekHeader = pgettext('week-header', 'Wk');\n //regional.dateFormat = jsFormat;\n regional.dateFormat = 'yy-mm-dd';\n regional.firstDay = parseInt(get_format('FIRST_DAY_OF_WEEK'), 10);\n jQuery.datepicker.setDefaults(jQuery.datepicker.regional[\"\"]);\n}());\n\n// It is not necessary to explicitly call Javascript directly in the Django\n// templates. It is enough to instrument HTML elements with proper classes and\n// attributes.\n//\n// Usage::\n//\n// <div class=\"list-block\"\n// data-url=\"http://get-me-some-json-list-of-objects/\"\n// data-showcount=\"15\"\n// data-orderby=\"order-by-this-colum-name\">\n// <span data-sort=\"name\">Name</span>\n// <span data-sort=\"location\">Location</span>\n// <input type=\"text\" name=\"search\">\n// <span class=\"clear-search-btn\">Clear search</span>\n// <img src=\"http://some-awesome-loader-icon.png\" class=\"loader\">\n// <ul class=\"model-tree\"></ul>\n// <div class=\"paginator\"></div>\n// </div>\n//\n// The <ul> will be populated by the response from data-url in the list-block\n// <div>. data-showcount models will be shown pr page. They will be ordered\n// by data-orderby by default, but this is changed by clicking one of the\n// data-sort <span>s. The shown models may be filtered by entering text into\n// the search <input>. The filter is disabled by clicking the clear-search-btn\n// <span>. While models are being loaded the loader <img> is visible, and when\n// models have been loaded, the loader <img> is hidden again. The paginator\n// <div> provides means to browse through the filtered and sorted pages of\n// models.\n//\n// @see: L{@json_list_response} decorator and L{gmList()} for details on how to\n// implement the corresponding view.\n$(function () {\n \"use strict\";\n // Instruct elements with class=\"open\", or class=\"close\" to open or close\n // the update-form of a model in a model-list or model-tree. Also instruct\n // <form> elements to replace themselves with the normal model\n // representation when submitted.\n\n var listBlock = $('.list-block'),\n modelList = $('.model-list, .model-tree');\n modelList.on('click', '.open', gridportal.website.overlay.open);\n modelList.on('click', '.close', gridportal.website.overlay.close);\n modelList.on('submit', '.slide-in-overlay form', gridportal.website.overlay.submit);\n modelList.on('click', '.delete', gridportal.website.deleteItem);\n\n listBlock.each(function () {\n var url = $(this).data('url'),\n showCount = $(this).data('showcount') || 10,\n orderBy = $(this).data('orderby');\n if (url !== undefined) {\n gridportal.website.gmList($(this), url, showCount, orderBy);\n }\n });\n\n // Use an element to modify a model-list or model-tree\n //\n // Elements with class=\"list-modifier\" and attributes\n // data-targetlist=\"<targetList>\", data-targeturl=\"<targetUrl>\", will add a\n // new element to the top of <targetList>, where this element is retrived\n // asynchronuously from <targetUrl>.\n $('.list-modifier').click(function (event) {\n var targetList = $(this).data('targetlist'),\n targetUrl = $(this).data('targeturl');\n gridportal.website.overlay.openNew($(targetList), targetUrl);\n event.preventDefault();\n });\n});\n\n\n// NOTE: only used in gridplatform/manage_reports/templates/manage_reports/generate_report.html\ngridportal.website.requestReport = function (csrfToken, requestUrl, statusUrl,\n finalizeUrl, resultElem, spinnerUrl, formData, outputType, noticeField, buttons) {\n 'use strict';\n var progressbar = $(\"#progressbar\").progressbar({ value: 0 }),\n progressLabel = $(\".progress-label\");\n\n var requestTaskStatus,\n disableButtons = function () {\n if (buttons) {\n buttons.attr('disabled', 'disabled');\n }\n },\n enableButtons = function () {\n if (buttons) {\n buttons.removeAttr('disabled');\n }\n },\n startSpinner = function () {\n resultElem.html('<img src=\"' + spinnerUrl + '\">');\n disableButtons();\n },\n stopSpinner = function () {\n resultElem.empty();\n enableButtons();\n },\n hideNoticeField = function () {\n if (typeof(noticeField) != 'undefined'){\n noticeField.hide();\n }\n },\n showNoticeField = function () {\n if (typeof(noticeField) != 'undefined'){\n noticeField.show();\n }\n },\n failStatus = function (text) {\n stopSpinner();\n hideNoticeField();\n gridportal.website.notify('error', text, false);\n },\n successStatus = function (text) {\n stopSpinner();\n hideNoticeField();\n },\n finalizeFail = function (xhr) {\n if (xhr.status != 0) {\n failStatus(gettext(\"Failed to construct output files\"));\n }\n },\n finalizeDone = function (data) {\n progressbar.progressbar(\"value\", 100);\n successStatus(gettext(\"Report created\"));\n if (outputType === 'pdf') {\n window.open(data.pdf.url, '_blank');\n } else {\n window.open(data.csv.url, '_blank');\n }\n },\n requestFinalize = function (taskId) {\n jQuery.post(\n finalizeUrl,\n {task_id: taskId, csrfmiddlewaretoken: csrfToken}\n ).done(finalizeDone).fail(finalizeFail);\n },\n taskStatusFail = function (jqXHR, textStatus) {\n if (textStatus === 'timeout') {\n failStatus(\n gettext(\"Lost contact to the server. Please check your internet connetion.\"));\n } else if (jqXHR.status != 0) {\n failStatus(gettext(\"Failed to collect data\"));\n }\n },\n taskStatusDone = function (data) {\n var taskId = data.task_id,\n status = data.status,\n errors = data.form_errors,\n result = data.result,\n procent = 0;\n $('.errorlist').remove();\n if (taskId) {\n if (status === 'SUCCESS') {\n requestFinalize(taskId);\n progressbar.progressbar(\"value\", 80);\n } else if (status === 'PENDING' || status === 'STARTED' ||\n status === 'RETRY') {\n window.setTimeout(jQuery.proxy(requestTaskStatus, {}, data.task_id), 1000);\n } else if (status === 'PROGRESS') {\n procent = result.current / result.total * 100 * 0.8;\n progressbar.progressbar(\"value\", procent);\n window.setTimeout(jQuery.proxy(requestTaskStatus, {}, data.task_id), 1000);\n } else if (status === 'FAILURE') {\n taskStatusFail();\n } else {\n taskStatusFail();\n }\n } else {\n if (errors) {\n jQuery.each(errors, function (key, val) {\n $('#id_' + key).after('<ul class=\"errorlist\"><li>' + val[0] + '</li></ul>');\n });\n stopSpinner();\n hideNoticeField();\n } else {\n taskStatusFail();\n }\n }\n };\n requestTaskStatus = function (taskId) {\n jQuery.ajax({\n url: statusUrl,\n data: {task_id: taskId, csrfmiddlewaretoken: csrfToken},\n type: 'POST',\n timeout: 30000\n }).done(taskStatusDone).fail(taskStatusFail);\n };\n outputType = outputType || 'pdf';\n startSpinner();\n showNoticeField();\n jQuery.post(requestUrl, formData).done(taskStatusDone).fail(taskStatusFail);\n};\n\n\n// This function can be used to start and follow a celery background task\n// Runs failedCallback (if set) when task fails\ngridportal.website.startAsyncTask = function (requestUrl, statusUrl, resultUrl,\n successFn, resultElem, spinnerUrl, useSpinner, failedCallback) {\n 'use strict';\n var startSpinner = function () {\n if (useSpinner !== false){\n resultElem.html('<img src=\"' + spinnerUrl + '\">');\n }\n },\n stopSpinner = function () {\n if (useSpinner !== false){\n resultElem.empty();\n }\n },\n failStatus = function (text) {\n stopSpinner();\n gridportal.website.notify('error', text);\n },\n taskStartFail = function (xhr) {\n if (xhr.status != 0) {\n failStatus(gettext(\"Failed to start background task\"));\n }\n if (failedCallback) {\n failedCallback();\n }\n },\n runTask = function (data) {\n startSpinner();\n var catchTask = function (data) {\n gridportal.website.catchAsyncTask(data.task_id,\n statusUrl, resultUrl, successFn, resultElem, spinnerUrl, failedCallback)();\n };\n jQuery.post(requestUrl, data).done(catchTask).fail(taskStartFail);\n };\n return runTask;\n};\n\n// This function can be used to catch and follow a celery background task.\ngridportal.website.catchAsyncTask = function (taskId, statusUrl, resultUrl, successFn,\n resultElem, spinnerUrl, failedCallback) {\n 'use strict';\n var requestTaskStatus,\n stopSpinner = function () {\n resultElem.empty();\n },\n failStatus = function (text) {\n stopSpinner();\n gridportal.website.notify('error', text);\n },\n // successStatus = function (text) {\n // stopSpinner();\n // },\n requestResult = function (taskId) {\n jQuery.post(resultUrl, {task_id: taskId}).done(successFn).fail(taskStatusFail);\n },\n taskStatusFail = function (jqXHR, textStatus) {\n if (textStatus === 'timeout') {\n failStatus(\n gettext(\"Lost contact to the server. Please check your internet connetion.\"));\n } else if (jqXHR === undefined || jqXHR.status != 0) {\n failStatus(gettext(\"Background task failed\"));\n }\n if (failedCallback) {\n failedCallback();\n }\n },\n taskStatusDone = function (data) {\n var taskId = data.task_id,\n status = data.status;\n if (taskId) {\n if (status === 'SUCCESS') {\n requestResult(taskId);\n } else if (status === 'PENDING' || status === 'STARTED' || status === 'RETRY') {\n window.setTimeout(jQuery.proxy(requestTaskStatus, {}, data.task_id), 1000);\n } else if (status === 'FAILURE') {\n taskStatusFail();\n } else {\n taskStatusFail();\n }\n } else {\n taskStatusFail();\n }\n },\n catchTask = function () {\n requestTaskStatus(taskId);\n };\n requestTaskStatus = function (taskId) {\n jQuery.ajax({\n url: statusUrl,\n data: {task_id: taskId},\n type: 'POST',\n timeout: 30000\n }).done(taskStatusDone).fail(taskStatusFail);\n };\n\n return catchTask;\n};\n\n\n// Include CSRF token in AJAX requests made via jQuery. Django CSRF protection\n// is described at https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/\n// NOTE: Per the HTTP specification, some methods are considered \"safe\".\n// Django does not apply CSRF protection to these. (Including the header for\n// these --- when it is meaningless to the server --- would be misleading...)\n$(document).ready(function () {\n 'use strict';\n var csrftoken = jQuery.cookie('csrftoken'),\n safeMethods = /^(GET|HEAD|OPTIONS|TRACE)$/;\n jQuery.ajaxSetup({\n crossDomain: false, // obviates need for sameOrigin test\n beforeSend: function (xhr, settings) {\n if (!safeMethods.test(settings.type)) {\n xhr.setRequestHeader('X-CSRFToken', csrftoken);\n }\n }\n });\n});\n\n// Enable chosen on all selects that are not in empty forms when document is\n// ready. All other selects must manually enable chosen (e.g. empty forms\n// being rendered and forms rendered as a result of some ajax call).\n$(document).ready(function () {\n 'use strict';\n $('select').not('.empty-form select').chosen({enable_split_word_search: true, search_contains: true});\n $('.datetime').datetimepicker({\n timeFormat: 'HH:mm:ss',\n addSliderAccess: true,\n sliderAccessArgs: { touchonly: false }\n });\n});\n" }, { "alpha_fraction": 0.6492509245872498, "alphanum_fraction": 0.6505618095397949, "avg_line_length": 36.21254348754883, "blob_id": "3893de683972ff297ca6ba3db9f80bf25bb87592", "content_id": "d5df640af3e673d75bd3811b4e27038516176151", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10680, "license_type": "no_license", "max_line_length": 78, "num_lines": 287, "path": "/legacy/manage_measurementpoints/forms/consumption.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.db.models import Q\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform import trackuser\nfrom gridplatform.consumptions.models import Consumption\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils import utilitytypes\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom legacy.devices.models import Meter\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import DataSeries\n\nfrom .measurementpointform import MeasurementPointForm\n\n\nclass ConsumptionMeasurementPointForm(MeasurementPointForm):\n \"\"\"\n Abstract base class for consumption measurement point forms.\n\n The abstract protected methods\n L{MeasurementPointForm._get_new_headline_display()} and\n L{MeasurementPointForm._get_edit_headline_display()} methods are\n implemented by fanned out to the abstract protected methods\n C{_get_new_UTILITY_TYPE_headline_display()} and\n C{_get_edit_UTILITY_TYPE_headline_display()} for each utility type.\n\n @invariant: C{self.instance.utility_type is not None}.\n\n @invariant: C{self.instance.utility_type} is in\n C{utilitytypes.METER_CHOICES}.\n \"\"\"\n\n heating_degree_days = forms.ModelChoiceField(\n queryset=DataSeries.objects.none(),\n required=False)\n\n standard_heating_degree_days = forms.ModelChoiceField(\n queryset=DataSeries.objects.none(),\n required=False)\n\n employees = forms.ModelChoiceField(\n queryset=DataSeries.objects.none(),\n required=False)\n\n area = forms.ModelChoiceField(\n queryset=DataSeries.objects.none(),\n required=False)\n\n co2 = forms.ModelChoiceField(\n queryset=DataSeries.objects.none(),\n required=False)\n\n show_rate = forms.BooleanField(\n initial=False, required=False)\n\n class Meta:\n model = ConsumptionMeasurementPoint\n fields = ('name', 'parent', 'billing_meter_number',\n 'billing_installation_number', 'gauge_lower_threshold',\n 'gauge_upper_threshold', 'gauge_max', 'gauge_min',\n 'gauge_colours', 'relay', 'gauge_preferred_unit',\n 'hidden_on_details_page', 'hidden_on_reports_page',\n 'comment', 'image')\n localized_fields = '__all__'\n\n class ProxyMeta(MeasurementPointForm.ProxyMeta):\n fields = ('heating_degree_days', 'standard_heating_degree_days',\n 'employees', 'area', 'co2')\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n @keyword utility_type: If instance is not given, this keyword argument\n must be given. It should be one of the integer values defined in\n L{utilitytypes.METER_CHOICES}.\n \"\"\"\n utility_type = kwargs.pop(\n 'utility_type', None)\n super(ConsumptionMeasurementPointForm, self).__init__(*args, **kwargs)\n if utility_type is not None and self.instance.utility_type is None:\n self.instance.utility_type = utility_type\n\n self.fields['parent'].queryset = \\\n Collection.objects.filter(\n role=Collection.GROUP,\n customer=trackuser.get_customer())\n\n self.fields['relay'].queryset = \\\n Meter.objects.filter(\n customer=trackuser.get_customer(), relay_enabled=True)\n\n self.fields[\"heating_degree_days\"].queryset = \\\n DataSeries.objects.filter(\n role=DataRoleField.HEATING_DEGREE_DAYS,\n customer=trackuser.get_customer())\n\n self.fields[\"standard_heating_degree_days\"].queryset = \\\n DataSeries.objects.filter(\n role=DataRoleField.STANDARD_HEATING_DEGREE_DAYS).filter(\n Q(customer=trackuser.get_customer()) |\n Q(customer__isnull=True))\n\n self.fields[\"employees\"].queryset = \\\n DataSeries.objects.filter(\n role=DataRoleField.EMPLOYEES,\n customer=trackuser.get_customer())\n\n self.fields[\"area\"].queryset = \\\n DataSeries.objects.filter(\n role=DataRoleField.AREA,\n customer=trackuser.get_customer())\n\n self.fields['co2'].queryset = DataSeries.objects.filter(\n role=DataRoleField.CO2_QUOTIENT,\n utility_type=self.instance.utility_type)\n\n # populate form fields from instance, which cannot\n # be handled by ProxyMeta.fields\n if self.instance.id:\n self.initial['show_rate'] = self.instance.rate is not None\n\n # Set the initial value of co2 to the first co2 index found\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n co2 = DataSeries.objects.filter(\n role=DataRoleField.CO2_QUOTIENT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n if co2:\n self.initial['co2'] = co2[0]\n\n self.__assert_invariants()\n\n def clean(self):\n \"\"\"\n Forward proxy properties to instance.\n \"\"\"\n self.instance.enable_rate = \\\n self.cleaned_data['show_rate']\n\n self.cleaned_data['gauge_min'] = 0\n\n super(ConsumptionMeasurementPointForm, self).clean()\n\n return self.cleaned_data\n\n def __assert_invariants(self):\n assert self.instance.utility_type in [\n db_value for db_value, dummy in\n utilitytypes.OPTIONAL_METER_CHOICES]\n\n def _get_new_headline_display(self):\n \"\"\"\n Implementation of L{MeasurementPointForm._get_new_headline_display()}.\n \"\"\"\n self.__assert_invariants()\n\n if self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return self._get_new_electricity_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.water:\n return self._get_new_water_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return self._get_new_gas_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n return self._get_new_heat_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return self._get_new_oil_headline_display()\n assert False, 'unreachable'\n\n def _get_new_electricity_headline_display(self):\n raise NotImplementedError()\n\n def _get_new_water_headline_display(self):\n raise NotImplementedError()\n\n def _get_new_gas_headline_display(self):\n raise NotImplementedError()\n\n def _get_new_heat_headline_display(self):\n raise NotImplementedError()\n\n def _get_new_oil_headline_display(self):\n raise NotImplementedError()\n\n def _get_edit_headline_display(self):\n \"\"\"\n Implementation of L{MeasurementPointForm._get_edit_headline_display()}\n \"\"\"\n self.__assert_invariants()\n\n if self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.electricity:\n return self._get_edit_electricity_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.water:\n return self._get_edit_water_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.gas:\n return self._get_edit_gas_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating:\n return self._get_edit_heat_headline_display()\n elif self.instance.utility_type == \\\n utilitytypes.OPTIONAL_METER_CHOICES.oil:\n return self._get_edit_oil_headline_display()\n assert False, 'unreachable'\n\n def _get_edit_electricity_headline_display(self):\n raise NotImplementedError()\n\n def _get_edit_water_headline_display(self):\n raise NotImplementedError()\n\n def _get_edit_gas_headline_display(self):\n raise NotImplementedError()\n\n def _get_edit_heat_headline_display(self):\n raise NotImplementedError()\n\n def _get_edit_oil_headline_display(self):\n raise NotImplementedError()\n\n\nclass ConsumptionMeasurementPointUpdateForm(ConsumptionMeasurementPointForm):\n def _get_edit_electricity_headline_display(self):\n return _(u'Edit Electricity Measurement Point')\n\n def _get_edit_water_headline_display(self):\n return _(u'Edit Water Measurement Point')\n\n def _get_edit_gas_headline_display(self):\n return _(u'Edit Gas Measurement Point')\n\n def _get_edit_heat_headline_display(self):\n return _(u'Edit Heat Measurement Point')\n\n def _get_edit_oil_headline_display(self):\n return _(u'Edit Oil Measurement Point')\n\n\nclass InputConsumptionMeasurementPointForm(ConsumptionMeasurementPointForm):\n\n consumption_input = forms.ModelChoiceField(\n queryset=Consumption.objects.none(), required=True)\n\n class Meta(ConsumptionMeasurementPointForm.Meta):\n exclude = ('gauge_lower_threshold', 'gauge_upper_threshold',\n 'gauge_max', 'gauge_min', 'gauge_colours',\n 'gauge_preferred_unit')\n\n class ProxyMeta(ConsumptionMeasurementPointForm.ProxyMeta):\n fields = ConsumptionMeasurementPointForm.ProxyMeta.fields + \\\n ('consumption_input',)\n\n def __init__(self, *args, **kwargs):\n super(InputConsumptionMeasurementPointForm, self).__init__(\n *args, **kwargs)\n\n self.fields['consumption_input'].queryset = \\\n ConsumptionAccumulationAdapter.objects.filter(\n utility_type=self.instance.utility_type,\n customer=get_customer())\n\n def _get_new_electricity_headline_display(self):\n return _(u'New Electricity Measurement Point')\n\n def _get_new_water_headline_display(self):\n return _(u'New Water Measurement Point')\n\n def _get_new_gas_headline_display(self):\n return _(u'New Gas Measurement Point')\n\n def _get_new_heat_headline_display(self):\n return _(u'New Heat Measurement Point')\n\n def _get_new_oil_headline_display(self):\n return _(u'New Oil Measurement Point')\n" }, { "alpha_fraction": 0.7555886507034302, "alphanum_fraction": 0.757079005241394, "avg_line_length": 30.952381134033203, "blob_id": "87a9c3807322fe9d3bd6ca6d49e5a3cf1e3ab981", "content_id": "36665130cebf4ff4ee7e02c0ce887ad03d7ad448", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "no_license", "max_line_length": 62, "num_lines": 21, "path": "/legacy/projects/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom .views import StartAnnualSavingsPotentialReportView\nfrom .views import FinalizeAnnualSavingsPotentialReportView\n\n\nurlpatterns = patterns(\n 'legacy.projects.views',\n\n url('^start_annual_savings_potential_report/$',\n StartAnnualSavingsPotentialReportView.as_view(),\n name='projects-startannualsavingspotentialreport'),\n\n url('^finalize_annual_savings_potential_report/$',\n FinalizeAnnualSavingsPotentialReportView.as_view(),\n name='projects-finalizeannualsavingspotentialreport'),\n)\n" }, { "alpha_fraction": 0.5679491758346558, "alphanum_fraction": 0.5806565284729004, "avg_line_length": 56.836734771728516, "blob_id": "8321c9c8a6184ba6ed0369587862b56a43ec5354", "content_id": "48b30b6243abe143f0a692bbd892c0e89677d1d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2833, "license_type": "no_license", "max_line_length": 174, "num_lines": 49, "path": "/gridplatform/provider_datasources/migrations/0001_initial.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n pass\n\n def backwards(self, orm):\n pass\n\n models = {\n u'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n u'datasources.datasource': {\n 'Meta': {'object_name': 'DataSource'},\n 'hardware_id': ('django.db.models.fields.CharField', [], {'max_length': '120', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'subclass': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"u'+'\", 'on_delete': 'models.PROTECT', 'to': u\"orm['contenttypes.ContentType']\"}),\n 'unit': ('gridplatform.utils.fields.BuckinghamField', [], {'max_length': '100'})\n },\n u'provider_datasources.providerdatasource': {\n 'Meta': {'object_name': 'ProviderDataSource'},\n u'datasource_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': u\"orm['datasources.DataSource']\", 'unique': 'True', 'primary_key': 'True'}),\n 'provider': ('django.db.models.fields.related.ForeignKey', [], {'default': 'None', 'to': u\"orm['providers.Provider']\"})\n },\n u'providers.provider': {\n 'Meta': {'object_name': 'Provider'},\n 'address': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'city': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'cvr': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'}),\n 'encryption_data_initialization_vector': ('gridplatform.encryption.fields.Base64Field', [], {}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'logo': ('django.db.models.fields.files.ImageField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),\n 'name': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '50'}),\n 'zipcode': ('gridplatform.encryption.fields.EncryptedCharField', [], {'max_length': '100'})\n }\n }\n\n complete_apps = ['provider_datasources']" }, { "alpha_fraction": 0.6013213992118835, "alphanum_fraction": 0.6050595641136169, "avg_line_length": 36.96369552612305, "blob_id": "a08e358ea2562d80b153836c1fd271c840e07f8c", "content_id": "1297e06af781692f14927bf2e03efd38da4f020d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11503, "license_type": "no_license", "max_line_length": 79, "num_lines": 303, "path": "/legacy/enpi_reports/tasks.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom celery import shared_task\nfrom celery import Task\n\nfrom legacy.measurementpoints.models import AbstractGraph\nfrom legacy.measurementpoints.models import Summation\nfrom legacy.measurementpoints.models import Utilization\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import SimpleLinearRegression\nfrom legacy.measurementpoints.models import PiecewiseConstantIntegral\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.energy_use_reports.tasks import TaskProgressMixin\nfrom gridplatform.utils.condense import get_date_formatter\nfrom gridplatform.trackuser.tasks import trackuser_task\nfrom gridplatform.trackuser import get_user\n\nfrom .models import ENPIReport\nfrom .models import ENPIUseArea\n\n\nclass AbstractENPIGraph(AbstractGraph):\n def __init__(self, enpi_report_task):\n self.enpi_report_task = enpi_report_task\n\n # @bug: utility_types can be mixed, but the term preferred unit for\n # mixed resource types makes no sense. Hopefully we find a solution\n # before non-energies are to be used.\n self.utility_type = utilitytypes.OPTIONAL_METER_CHOICES.electricity\n\n def get_energy_data_series(self):\n raise NotImplementedError('not implemented by %r' % self.__class__)\n\n def get_enpi_data_series(self, energy):\n raise NotImplementedError('not implemented by %r' % self.__class__)\n\n def no_enpi_data(self):\n raise NotImplementedError('not implemented by %r' % self.__class__)\n\n def initial_enpi_is_zero(self):\n raise NotImplementedError('not implemented by %r' % self.__class__)\n\n def _get_data_series(self):\n energy = Summation(\n role=DataRoleField.CONSUMPTION,\n unit=self.enpi_report_task.enpi_report.energy_unit,\n utility_type=self.utility_type,\n customer=self.enpi_report_task.enpi_report.customer)\n energy.plus_data_series = self.get_energy_data_series()\n enpi = self.get_enpi_data_series(energy)\n\n trendline = SimpleLinearRegression(data=enpi)\n trendline.full_clean(exclude=['data'])\n\n return [enpi, trendline]\n\n def tick_progress(self):\n self.enpi_report_task.tick_progress()\n\n def get_colors(self):\n return ['#00A8F0', '#A80000']\n\n def collect_data(self, from_timestamp, to_timestamp, sample_resolution):\n \"\"\"\n Collect data for this graph.\n\n The data is not only used in the graph plot, but also for other\n purposes.\n\n @postcondition: The result of L{get_graph_data()} can be found in\n self.graph_data.\n \"\"\"\n self.errors = []\n\n # calculate num_samples\n num_samples = 0\n while from_timestamp + num_samples * sample_resolution < to_timestamp:\n num_samples += 1\n\n self.graph_data = self.get_graph_data(\n min(num_samples, 12),\n from_timestamp,\n sample_resolution=sample_resolution,\n num_samples=num_samples,\n weekends_are_special=False)\n enpi_data = self.graph_data['data'][0]['data']\n self.table_data = []\n\n if enpi_data:\n SAMPLE_VALUE = 1\n first_value = enpi_data[0][SAMPLE_VALUE]\n date_formatter = get_date_formatter(\n from_timestamp, to_timestamp, resolution=sample_resolution)\n for i, s in enumerate(enpi_data, start=0):\n self.table_data.append(\n {\n 'label': date_formatter(\n from_timestamp + sample_resolution * i),\n 'enpi': s[SAMPLE_VALUE],\n })\n if first_value != 0:\n saved_pct = (\n first_value - s[SAMPLE_VALUE]) * 100.0 / first_value\n self.table_data[-1]['saved_pct'] = saved_pct\n if first_value == 0:\n self.initial_enpi_is_zero()\n else:\n self.no_enpi_data()\n\n\nclass TotalENPIGraph(AbstractENPIGraph):\n\n def get_energy_data_series(self):\n result = []\n\n for enpi_use_area in \\\n self.enpi_report_task.enpi_report.enpiusearea_set.all():\n result.extend([\n ds.subclass_instance for ds in DataSeries.objects.filter(\n role=DataRoleField.CONSUMPTION,\n graph__hidden=False,\n graph__collection_id__in=enpi_use_area.measurement_points.\n all().values_list('id', flat=True))])\n return result\n\n def get_enpi_data_series(self, energy):\n if self.enpi_report_task.enpi_report.energy_driver_role in (\n DataRoleField.AREA, DataRoleField.EMPLOYEES):\n energy_drivers = [\n PiecewiseConstantIntegral(\n role=DataRoleField.ENERGY_DRIVER,\n data=enpi_use_area.energy_driver.subclass_instance)\n for enpi_use_area in\n self.enpi_report_task.enpi_report.enpiusearea_set.all()]\n\n elif self.enpi_report_task.enpi_report.energy_driver_role == \\\n DataRoleField.PRODUCTION:\n energy_drivers = [\n enpi_use_area.energy_driver.subclass_instance for\n enpi_use_area in\n self.enpi_report_task.enpi_report.enpiusearea_set.all()]\n\n assert energy_drivers\n\n for energy_driver in energy_drivers:\n energy_driver.full_clean()\n\n enpi = Utilization(\n role=self.enpi_report_task.enpi_report.enpi_role,\n unit=self.enpi_report_task.enpi_report.enpi_unit,\n consumption=energy,\n utility_type=self.utility_type,\n customer=self.enpi_report_task.enpi_report.customer)\n enpi.energy_driver = Summation(\n role=DataRoleField.ENERGY_DRIVER,\n unit=energy_drivers[0].unit,\n utility_type=self.utility_type,\n customer=self.enpi_report_task.enpi_report.customer)\n\n enpi.energy_driver.plus_data_series = energy_drivers\n\n return enpi\n\n def no_enpi_data(self):\n # avoid non-ascii characters here\n self.errors.append(_('No total EnPI data available.'))\n\n def initial_enpi_is_zero(self):\n # avoid non-ascii characters here\n self.errors.append(\n _('EnPI for first period in total EnPI is zero. '\n 'Savings in percent cannot be calculated'))\n\n\nclass NoENPIUseAreaData(object):\n def __init__(self, enpi_use_area_id):\n self.enpi_use_area_id = enpi_use_area_id\n\n def __unicode__(self):\n return _('No EnPI data available for {use_area_name}'). \\\n format(\n use_area_name=ENPIUseArea.objects.get(\n id=self.enpi_use_area_id).name_plain)\n\n\nclass InitialUseAreaENPIIsZero(object):\n def __init__(self, enpi_use_area_id):\n self.enpi_use_area_id = enpi_use_area_id\n\n def __unicode__(self):\n return _(\n 'EnPI for first period in {use_area_name} is zero. '\n 'Savings in percent cannot be calculated'). \\\n format(\n use_area_name=ENPIUseArea.objects.get(\n id=self.enpi_use_area_id).name_plain)\n\n\nclass ENPIUseAreaGraph(AbstractENPIGraph):\n def __init__(self, enpi_report_task, enpi_use_area):\n super(ENPIUseAreaGraph, self).__init__(enpi_report_task)\n self.enpi_use_area = enpi_use_area\n\n def get_energy_data_series(self):\n return [\n ds.subclass_instance for ds in DataSeries.objects.filter(\n role=DataRoleField.CONSUMPTION,\n graph__hidden=False,\n graph__collection_id__in=self.enpi_use_area.measurement_points.\n all().values_list('id', flat=True))]\n\n def get_enpi_data_series(self, energy):\n if self.enpi_report_task.enpi_report.energy_driver_role in (\n DataRoleField.AREA, DataRoleField.EMPLOYEES):\n enpi = Utilization(\n role=self.enpi_report_task.enpi_report.enpi_role,\n unit=self.enpi_report_task.enpi_report.enpi_unit,\n consumption=energy,\n needs=self.enpi_use_area.energy_driver,\n utility_type=self.utility_type,\n customer=self.enpi_report_task.enpi_report.customer)\n else:\n assert self.enpi_report_task.enpi_report.energy_driver_role in (\n DataRoleField.PRODUCTION, DataRoleField.HEATING_DEGREE_DAYS)\n enpi = Utilization(\n role=self.enpi_report_task.enpi_report.enpi_role,\n unit=self.enpi_report_task.enpi_report.enpi_unit,\n consumption=energy,\n utility_type=self.utility_type,\n customer=self.enpi_report_task.enpi_report.customer)\n enpi.energy_driver = self.enpi_use_area.energy_driver\n return enpi\n\n def no_enpi_data(self):\n self.errors.append(NoENPIUseAreaData(self.enpi_use_area.id))\n\n def initial_enpi_is_zero(self):\n self.errors.append(InitialUseAreaENPIIsZero(self.enpi_use_area.id))\n\n\n# Softly kill using exception after 30 minutes. Kill for real after 31 minutes.\n@trackuser_task\n@shared_task(\n time_limit=1860, soft_time_limit=1800,\n name='legacy.enpi_reports.tasks.ENPIReportTask')\nclass ENPIReportTask(TaskProgressMixin, Task):\n def run(self, data):\n self.update_state(\n state='PROGRESS',\n meta={\n 'task_user_id': get_user().id,\n 'current': 0,\n 'total': 0\n }\n )\n self.enpi_report = ENPIReport.objects.get(id=data['enpi_report_id'])\n self.enpi_use_areas = list(self.enpi_report.enpiusearea_set.all())\n self.PROGRESS_TOTAL = ENPIUseAreaGraph.PROGRESS_TOTAL * \\\n len(self.enpi_use_areas)\n if len(self.enpi_use_areas) > 1:\n self.PROGRESS_TOTAL += TotalENPIGraph.PROGRESS_TOTAL\n self.progress = 0\n\n result = {\n 'enpi_report': self.enpi_report.id,\n 'errors': [],\n 'data': {'something': ['something']},\n 'enpi_use_areas': dict(),\n 'sample_resolution': data['sample_resolution']\n }\n\n from_timestamp = data['from_timestamp']\n to_timestamp = data['to_timestamp']\n sample_resolution = data['sample_resolution']\n\n if len(self.enpi_use_areas) > 1:\n graph = TotalENPIGraph(self)\n graph.collect_data(from_timestamp, to_timestamp, sample_resolution)\n\n result['total_enpi'] = {\n 'graph_data': graph.graph_data,\n 'table_data': graph.table_data,\n 'graph_name': 'total-enpi-graph'\n }\n result['errors'].extend(graph.errors)\n\n for use_area in self.enpi_use_areas:\n graph = ENPIUseAreaGraph(self, use_area)\n graph.collect_data(from_timestamp, to_timestamp, sample_resolution)\n\n result['enpi_use_areas'][use_area.id] = {\n 'graph_data': graph.graph_data,\n 'table_data': graph.table_data,\n 'graph_name': 'enpi-use-area-graph-%d' % use_area.id,\n }\n result['errors'].extend(graph.errors)\n\n return result\n" }, { "alpha_fraction": 0.6914153099060059, "alphanum_fraction": 0.6937354803085327, "avg_line_length": 19.5238094329834, "blob_id": "af8b648cd370f8d94fdf1a4094691cae9a0381ab", "content_id": "fdf427822a06b1029b4c078c342329b76fb16dcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 431, "license_type": "no_license", "max_line_length": 57, "num_lines": 21, "path": "/legacy/website/templatetags/customer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom gridplatform.trackuser import get_user, get_customer\n\nregister = template.Library()\n\n\[email protected]_tag\ndef customer_name():\n if get_customer():\n return get_customer().name_plain\n else:\n return \"\"\n\n\[email protected]_tag\ndef username():\n return get_user().e_mail_plain\n" }, { "alpha_fraction": 0.5452983975410461, "alphanum_fraction": 0.5942464470863342, "avg_line_length": 27.06024169921875, "blob_id": "a7cd038284fbcad96e8b4c20928339308ba4fe12", "content_id": "848c76d69fbcdff72bbfaebbb97ed047012d0814", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2329, "license_type": "no_license", "max_line_length": 72, "num_lines": 83, "path": "/gridplatform/utils/format_id.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef format_mac(val, bytes=6):\n \"\"\"\n Formats a given integer value as a MAC address.\n\n :param val: The integer value to be formatted.\n :keyword bytes: The number of bytes significant in the given\n integer value.\n \"\"\"\n bytelist = []\n for _ignore in range(bytes):\n bytelist.append(val & 0xff)\n val >>= 8\n return (':'.join(['{:02x}'] * bytes)).format(*reversed(bytelist))\n\n\ndef format_mbus_manufacturer(val):\n \"\"\"\n From section 6.3.1 in http://www.m-bus.com/mbusdoc/md6.php\n\n The association of three-letter-codes to manufactorers is\n available on http://dlms.com/organization/flagmanufacturesids/\n \"\"\"\n charlist = []\n for _ignore in range(3):\n charlist.append(chr((val & 0x1f) + 64))\n val >>= 5\n return ''.join(reversed(charlist))\n\n\n# From section 8.4.1 in\n# http://www.m-bus.com/mbusdoc/md8.php\nmbus_medium = {\n 0x00: _(u'Other'),\n 0x01: _(u'Oil'),\n 0x02: _(u'Electricity'),\n 0x03: _(u'Gas'),\n 0x04: _(u'Heat outlet'),\n 0x05: _(u'Steam'),\n 0x06: _(u'Hot water'),\n 0x07: _(u'Water'),\n 0x08: _(u'Heat cost allocator'),\n 0x09: _(u'Compressed air'),\n 0x0A: _(u'Cooling load meter outlet'),\n 0x0B: _(u'Cooling load meter inlet'),\n 0x0C: _(u'Heat inlet'),\n 0x0D: _(u'Heat/cooling load meter'),\n 0x0E: _(u'Bus/system'),\n 0x0F: _(u'Unknown medium'),\n # 0x10--0x15 reserved\n 0x16: _(u'Cold water'),\n 0x17: _(u'Dual water'),\n 0x18: _(u'Pressure'),\n 0x19: _(u'A/D converter'),\n # 0x20--0xff reserved\n}\n\n# 0x10--0x15 reserved\nfor n in range(0x10, 0x15 + 1):\n mbus_medium[n] = _('Reserved')\n# 0x20--0xff reserved\nfor n in range(0x20, 0xff + 1):\n mbus_medium[n] = _('Reserved')\n\n\ndef format_mbus_enhanced(val):\n \"\"\"\n Formats the information contained in a integer mbus ID in a human\n readable fashion.\n \"\"\"\n return _(\n u'{id}, manufacturer: {manufacturer}, '\n 'generation: {generation}, medium: {medium}').format(\n id=val >> 32,\n manufacturer=format_mbus_manufacturer((val >> 16) & 0xffff),\n generation=(val >> 8) & 0xff,\n medium=mbus_medium[val & 0xff])\n" }, { "alpha_fraction": 0.6614518165588379, "alphanum_fraction": 0.6867960095405579, "avg_line_length": 46.6716423034668, "blob_id": "35450a3cd8ea4205fcf0c2506208d202d1fa151e", "content_id": "07f2ddd5f223311b1e1cfee18b297d37468111e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3196, "license_type": "no_license", "max_line_length": 81, "num_lines": 67, "path": "/wifiagent/wifiagent/relay/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .request_handler import RequestHandler\nfrom .models import Measurement\n\n# Create your views here.\n\ndef receiver(request):\n mac = request.GET.get('mac', None) #device mac\n ip = request.GET.get('ip', None) #device local ip\n vrms1 = request.GET.get('v1', None) #VRMS Phase 1\n vrms2 = request.GET.get('v2', None) #VRMS Phase 2\n vrms3 = request.GET.get('v3', None) #VRMS Phase 3\n vrms_total = request.GET.get('vT', None) #VRMS Total\n irms1 = request.GET.get('i1', None) #IRMS Phase 1\n irms2 = request.GET.get('i2', None) #IRMS Phase 2\n irms3 = request.GET.get('i3', None) #IRMS Phase 3\n irms_total = request.GET.get('iT', None) #IRMS Total\n apparent_power1 = request.GET.get('p1', None) #Apparent power Phase 1\n apparent_power2 = request.GET.get('p2', None) #Apparent power Phase 2\n apparent_power3 = request.GET.get('p3', None) #Apparent power Phase 3\n apparent_power_total = request.GET.get('pT', None) #pt = Apparent power Total\n active_power1 = request.GET.get('a1', None) #Active power Phase 1\n active_power2 = request.GET.get('a2', None) #Active power Phase 2\n active_power3 = request.GET.get('a3', None) #Active power Phase 3\n active_power_total = request.GET.get('at', None) #Active power Total\n reactive_power1 = request.GET.get('r1', None) #Reactive power Phase 1\n reactive_power2 = request.GET.get('r2', None) #Reactive power Phase 2\n reactive_power3 = request.GET.get('r3', None) #Reactive power Phase 3\n reactive_power_total = request.GET.get('rt', None) #Reactive power Total\n frequency1 = request.GET.get('q1', None) #Frequency Phase 1\n frequency2 = request.GET.get('q2', None) #Frequency Phase 2\n frequency3 = request.GET.get('q3', None) #Frequency Phase 3\n frequency_total = request.GET.get('qT', None) #Frequency Total\n power_factor1 = request.GET.get('f1', None) #Power factor Phase 1\n power_factor2 = request.GET.get('f2', None) #Power factor Phase 2\n power_factor3 = request.GET.get('f3', None) #Power factor Phase 3\n power_factor_total = request.GET.get('fT', None) #Power factor Total\n active_energy1 = request.GET.get('e1', None) #Active energy Phase 1\n active_energy2 = request.GET.get('e2', None) #Active energy Phase 2\n active_energy3 = request.GET.get('e3', None) #Active energy Phase 3\n active_energy_total = request.GET.get('et', None) #Active energy Total\n reactive_energy1 = request.GET.get('o1', None) #Reactive energy Phase 1\n reactive_energy2 = request.GET.get('o2', None) #Reactive energy Phase 2\n reactive_energy3 = request.GET.get('o3', None) #Reactive energy Phase 3\n reactive_energy_total = request.GET.get('ot', None) #Reactive energy Total\n\n request_handler = RequestHandler()\n\n measurement = Measurement()\n\n measurement.mac = mac\n measurement.ip = ip\n measurement.vrms_total = vrms_total\n measurement.timestamp = datetime.datetime.now()\n\n try:\n if not request_handler.send_measurement(measurement):\n measurement.save()\n except:\n measurement.save()\n\n\n return HttpResponse(\"OK\" + mac)\n\n\n" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6426767706871033, "avg_line_length": 28.33333396911621, "blob_id": "37b8da1f52ec5633fb00fb8eb15cb77b8081503b", "content_id": "cac135ded5d160b0c451ad402702ed9739d635c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 74, "num_lines": 27, "path": "/legacy/energinet_co2/management/commands/import_energinet_co2.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.transaction import commit_on_success\n\nfrom legacy.energinet_co2.importer import fetch_import_day\n\nDATE_FORMAT = '%Y-%m-%d'\n\n\nclass Command(BaseCommand):\n args = '[date]'\n help = 'Import Energinet.dk CO2 data. ' + \\\n 'Date format YYYY-MM-DD; defaults to yesterday.'\n\n def handle(self, *args, **options):\n try:\n date = datetime.datetime.strptime(args[0], DATE_FORMAT).date()\n except IndexError:\n date = (datetime.datetime.now() -\n datetime.timedelta(days=1)).date()\n with commit_on_success():\n fetch_import_day(date)\n" }, { "alpha_fraction": 0.657516598701477, "alphanum_fraction": 0.6579676270484924, "avg_line_length": 37.60447692871094, "blob_id": "59630136c8ba55317fe0943e486dc52d109ce6e8", "content_id": "5af519f69435b29a5394fb373319db955efeffeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15519, "license_type": "no_license", "max_line_length": 107, "num_lines": 402, "path": "/gridplatform/datasequences/models/accumulation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport itertools\n\nfrom django.db import models\nfrom django.utils.functional import cached_property\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.customer_datasources.models import DataSource\nfrom gridplatform.utils.decorators import virtual\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.iter_ext import count_extended\nfrom gridplatform.utils.iter_ext import pairwise\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.models import StoredSubclassManager\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import ACCUMULATION_BASE_UNITS\nfrom gridplatform.utils.units import IMPULSE_BASE_UNITS\nfrom gridplatform.utils.samples import Sample\n\nfrom .base import PeriodBaseManager\nfrom .base import DataSequenceBase\nfrom .base import PeriodBase\nfrom .base import is_clock_hour\nfrom ..utils import aggregate_sum_ranged_sample_sequence\n\n\nclass AccumulationBase(DataSequenceBase):\n \"\"\"\n Abstract implementation of accumulation interface in terms of\n ``self.period_set``. Note that the actual relation with periods must be\n defined on concrete subclasses.\n \"\"\"\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: a sequence of accumulating ranged samples for given timespan in\n hourly resolution.\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n\n :see: Used to implement :meth:`.AccumulationBase.development_sequence`.\n \"\"\"\n for period in self.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'):\n period_from, period_to = period.overlapping(\n from_timestamp, to_timestamp)\n for sample in period._hourly_accumulated(\n period_from, period_to):\n yield sample\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: a sequence of accumulating ranged samples for given timespan in\n five-minute resolution.\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n\n :see: Used to implement :meth:`.AccumulationBase.development_sequence`.\n \"\"\"\n for period in self.period_set.in_range(\n from_timestamp, to_timestamp).order_by('from_timestamp'):\n period_from, period_to = period.overlapping(\n from_timestamp, to_timestamp)\n for sample in period._five_minute_accumulated(\n period_from, period_to):\n yield sample\n\n def development_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n :return: a sequence of accumulating ranged samples for given period in\n given resolution.\n\n :param from_timestamp: the start of the given period.\n :param to_timestamp: the end of the given period.\n :param resolution: the given resolution.\n \"\"\"\n if resolution == RelativeTimeDelta(minutes=5):\n return self._five_minute_accumulated(from_timestamp, to_timestamp)\n elif resolution == RelativeTimeDelta(hours=1):\n return self._hourly_accumulated(from_timestamp, to_timestamp)\n else:\n data = self._hourly_accumulated(from_timestamp, to_timestamp)\n return aggregate_sum_ranged_sample_sequence(\n data, resolution, self.customer.timezone)\n\n def development_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: The total accumulated in the given timespan.\n :rtype: :class:`.PhysicalQuantity`\n\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n\n :note: Will return PhysicalQuantity(0, self.unit) if no samples in period.\n For occasions where zero due to no samples should somehow be considered\n different from zero from actual samples, if that ever occurs, use\n separate quality control\n\n :precondition: The given timespan must be on the hour.\n \"\"\"\n assert is_clock_hour(from_timestamp), \\\n '%r does not match clock hour' % from_timestamp\n assert is_clock_hour(to_timestamp), \\\n '%r does not match clock hour' % to_timestamp\n samples = self._hourly_accumulated(from_timestamp, to_timestamp)\n value = sum(\n (s.physical_quantity for s in samples),\n PhysicalQuantity(0, self.unit))\n return value\n\n\nclass AccumulationPeriodManager(\n PeriodBaseManager, StoredSubclassManager):\n \"\"\"\n Manager for :class:`.AccumulationPeriodBase` that inherits from both\n :class:`.PeriodBaseManager` and :class:`.StoredSubclassManager`.\n \"\"\"\n pass\n\n\nclass AccumulationPeriodBase(StoreSubclass, PeriodBase):\n \"\"\"\n Abstract :class:`.PeriodBase` specialisation that delegates accumulation\n period interface to subclasses. This is also an abstract Django model\n (e.g. this model cannot be queried, but subclasses inherit the manager).\n\n Assumes concrete specialization has a ``datasequence`` foreign key to some\n :class:`.AccumulationDataSequence` specialization.\n\n :ivar objects: The default manager for :class:`.AccumulationPeriodBase` is\n :class:`.AccumulationPeriodManager`.\n \"\"\"\n objects = AccumulationPeriodManager()\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n @virtual\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Abstract delegate of :meth:`.AccumulationBase._hourly_accumulated` within\n the timespan of this period.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n @virtual\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Abstract delegate of :meth:`.AccumulationBase._hourly_accumulated` within\n the timespan of this period.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n @virtual\n def _get_unit(self):\n \"\"\"\n Abstract method returning the unit of this period.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n\nclass NonpulseAccumulationPeriodMixin(models.Model):\n \"\"\"\n Mixes nonpulse datasource implementations of abstract methods defined in\n :class:`.AccumulationPeriodBase` into a :class:`.AccumulationPeriodBase`\n specialization.\n\n :ivar datasource: The non-pulse, accumulating :class:`.DataSource` defining\n the data of owning accumulation within the mixed period.\n \"\"\"\n datasource = models.ForeignKey(\n DataSource,\n verbose_name=_('data source'),\n limit_choices_to={'unit__in': ACCUMULATION_BASE_UNITS},\n on_delete=models.PROTECT,\n related_name='+')\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If the units of data source and data sequence don't\n match.\n \"\"\"\n super(NonpulseAccumulationPeriodMixin, self).clean()\n if self.datasource_id and self.datasequence_id and not \\\n PhysicalQuantity.compatible_units(\n self.datasource.unit, self.datasequence.unit):\n raise ValidationError(\n _('Input configuration and data source '\n 'units are not compatible'))\n\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Delegates to data source.\n \"\"\"\n return self.datasource.hourly_accumulated(\n from_timestamp, to_timestamp)\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Delegates to data source.\n \"\"\"\n return self.datasource.five_minute_accumulated(\n from_timestamp, to_timestamp)\n\n def _get_unit(self):\n \"\"\"\n Delegates to data source.\n \"\"\"\n return self.datasource.unit\n\n\nclass PulseAccumulationPeriodMixin(models.Model):\n \"\"\"\n Mixes pulse datasource implementations of abstract methods defined in\n :class:`.AccumulationPeriodBase` into a :class:`.AccumulationPeriodBase`\n specialization.\n\n :ivar datasource: The pulse accumulating :class:`.DataSource` defining the\n data of owning accumulation within the mixed period.\n\n Pulses are converted to nonpulse data using the pulse conversion equation\n stating that ``PhysicalQuantity(self.pulse_quantity, 'impulse')``\n corresponds to ``PhysicalQuantity(self.output_quantity,\n self.output_unit)``.\n\n :ivar pulse_quantity: quantity of pulse side of conversion equation.\n :ivar output_quantity: quantity of output side of conversion equation.\n :ivar output_unit: unit of output side of conversion equation.\n\n :ivar _conversion_factor: Cached property holding a\n :class:`.PysicalQuantity` that when multiplied with a pulse\n :class:`.PysicalQuantity` result in an output\n :class:`.PysicalQuantity`.\n \"\"\"\n\n datasource = models.ForeignKey(\n DataSource,\n verbose_name=_('data source'),\n limit_choices_to={'unit__in': IMPULSE_BASE_UNITS},\n on_delete=models.PROTECT,\n related_name='+')\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n pulse_quantity = models.IntegerField(_('pulse quantity'))\n output_quantity = models.IntegerField(_('output quantity'))\n output_unit = BuckinghamField(_('output unit'))\n\n def clean(self):\n super(PulseAccumulationPeriodMixin, self).clean()\n if self.output_unit and self.datasequence_id:\n datasequence = self._meta.get_field('datasequence').rel.to.objects.get(pk=self.datasequence_id)\n\n if not PhysicalQuantity.compatible_units(\n self.output_unit, datasequence.unit):\n raise ValidationError(\n _('Input configuration and output '\n 'units are not compatible'))\n\n @cached_property\n def _conversion_factor(self):\n pulse_quantity = PhysicalQuantity(self.pulse_quantity, 'impulse')\n output_quantity = PhysicalQuantity(\n self.output_quantity, self.output_unit)\n return output_quantity / pulse_quantity\n\n def _convert_sample(self, sample):\n \"\"\"\n Converts a given pulse sample to an output sample using\n ``self._conversion_factor``.\n \"\"\"\n return sample._replace(\n physical_quantity=self._conversion_factor *\n sample.physical_quantity)\n\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :meth:`.AccumulationPeriodBase._hourly_accumulated`\n yielding pulse samples converted to output samples.\n \"\"\"\n return itertools.imap(\n self._convert_sample,\n self.datasource.hourly_accumulated(\n from_timestamp, to_timestamp))\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :meth:`.AccumulationPeriodBase._five_minute_accumulated`\n yielding pulse samples converted to output samples.\n \"\"\"\n return itertools.imap(\n self._convert_sample,\n self.datasource.five_minute_accumulated(\n from_timestamp, to_timestamp))\n\n def _get_unit(self):\n return self.datasource.unit\n\n\nclass SingleValueAccumulationPeriodMixin(models.Model):\n \"\"\"\n Mixes fixed value implementations of abstract methods defined in\n :class:`.AccumulationPeriodBase` into a :class:`.AccumulationPeriodBase`\n specialization.\n\n :ivar value: The value accumulated uniformly over this period.\n :ivar unit: The unit of ``self.value``.\n\n :ivar _accumulation_rate: The slope of the uniformly accumulated value of\n this period in the forms of a :class:`.PhysicalQuantity`.\n \"\"\"\n value = models.BigIntegerField(_('value'))\n # Is actually used as a choice field, thus the get_unit_display method is\n # defined below.\n unit = BuckinghamField(_('unit'))\n\n class Meta:\n abstract = True\n app_label = 'datasequences'\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.to_timestamp`` is not set.\n :raise ValidationError: If ``self.unit`` and the unit of owning data\n sequence are not compatible.\n \"\"\"\n super(SingleValueAccumulationPeriodMixin, self).clean()\n if not self.to_timestamp:\n raise ValidationError(\n _('The \"to time\" is required for single value periods.')\n )\n if self.datasequence and self.unit and not \\\n PhysicalQuantity.compatible_units(\n self.datasequence.unit, self.unit):\n raise ValidationError(\n _('The chosen unit is not compatible.')\n )\n\n @cached_property\n def _accumulation_rate(self):\n total_quantity = PhysicalQuantity(self.value, self.unit)\n total_duration = PhysicalQuantity(\n (self.to_timestamp - self.from_timestamp).total_seconds(),\n 'second')\n return total_quantity / total_duration\n\n def _period_accumulated(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Returns a sequence of ranged accumulation samples across given timespan in\n given resolution.\n\n The slope of the accumulation in each sample will equal\n ``self._accumulation_rate``.\n\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n :param datetime.timedelta resolution: The given resolution. Note this\n is not a :class:`.RelativeTimeDelta` instance.\n \"\"\"\n assert self.from_timestamp <= from_timestamp <= self.to_timestamp\n assert self.from_timestamp <= to_timestamp <= self.to_timestamp\n sample_duration = PhysicalQuantity(\n resolution.total_seconds(), 'second')\n quantity = self._accumulation_rate * sample_duration\n\n for from_timestamp_, to_timestamp_ in pairwise(\n count_extended(from_timestamp, resolution)):\n yield Sample(from_timestamp_, to_timestamp_, quantity, True, False)\n if to_timestamp_ >= to_timestamp:\n break\n\n def _hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :meth:`.AccumulationPeriodBase._hourly_accumulated`\n delegating to :meth:`._period_accumulated` with resolution of one hour.\n \"\"\"\n return self._period_accumulated(\n from_timestamp, to_timestamp, datetime.timedelta(hours=1))\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Implementation of :meth:`.AccumulationPeriodBase._five_minute_accumulated`\n delegating to :meth:`._period_accumulated` with resolution of five minutes.\n \"\"\"\n return self._period_accumulated(\n from_timestamp, to_timestamp, datetime.timedelta(minutes=5))\n" }, { "alpha_fraction": 0.5807096362113953, "alphanum_fraction": 0.6466766595840454, "avg_line_length": 34.105262756347656, "blob_id": "44d2fa0968e51a6033d5143cb1de7f25faf5d109", "content_id": "2e4dc562a302510f5e0d2a97ffa13b363550a45f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2001, "license_type": "no_license", "max_line_length": 323, "num_lines": 57, "path": "/gridplatform/smilics/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport pytz\nimport json\n\nfrom decimal import Decimal\nfrom django.http import HttpResponse\n\nfrom legacy.devices.models import PhysicalInput, Meter\nfrom gridplatform.datasources.models import RawData\nfrom django.views.decorators.csrf import csrf_exempt\n\nDOUBLE_INPUTS = [\n \"e1\", \"e2\", \"e3\", \"et\",\n]\n\n\ndef convert_to_base(input, value):\n if input in DOUBLE_INPUTS:\n return Decimal(value) * 1000\n\ndef save_to_db(hardware_id, value_dict, timestamp):\n meter = Meter.objects_encrypted.get(hardware_id=hardware_id)\n inputs = PhysicalInput.objects_encrypted.filter(meter_id=meter.id)\n dt = datetime.datetime.utcfromtimestamp(float(timestamp)).replace(\n tzinfo=pytz.utc)\n for physical_input in inputs:\n value = value_dict.get(physical_input.hardware_id, None)\n if value:\n RawData.objects.create(\n datasource_id=physical_input.id,\n timestamp=dt,\n value=convert_to_base(physical_input.hardware_id, value)\n )\n\n\ndef wibeee_receiver(request):\n hardware_id = request.GET.get(\"mac\", None)\n timestamp = request.GET.get(\"time\", None)\n if hardware_id and timestamp:\n save_to_db(hardware_id, request.GET, timestamp)\n return HttpResponse(\"OK\")\n else:\n return HttpResponse(\"fail\")\n\n\n@csrf_exempt\ndef wibeee_receiver_json(request):\n # {\"time\":\"1495802646\",\"v1\":\"227.164\",\"v2\":\"227.164\",\"v3\":\"227.164\",\"i1\":\"0.160\",\"i2\":\"0.000\",\"i3\":\"0.000\",\"p1\":\"36.263\",\"p2\":\"0.000\",\"p3\":\"0.000\",\"pt\":\"36.263\",\"a1\":\"6.062\",\"a2\":\"0.000\",\"a3\":\"0.000\",\"at\":\"6.062\",\"r1\":\"0.000\",\"r2\":\"0.000\",\"r3\":\"0.000\",\"rt\":\"0.000\",\"f1\":\"-0.167\",\"f2\":\"1.000\",\"f3\":\"1.000\",\"ft\":\"-0.167\"}\n data = json.loads(request.body)\n hardware_id = data['mac']\n for measurement in data['measures']:\n save_to_db(hardware_id, measurement, measurement['time'])\n return HttpResponse(\"OK\")\n" }, { "alpha_fraction": 0.6298051476478577, "alphanum_fraction": 0.636519193649292, "avg_line_length": 32.7599983215332, "blob_id": "3d06253c73cde96fecea512223e7207be1bd27b5", "content_id": "4d28245f89965da38e8f8eaf693b0d15deefeb6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7596, "license_type": "no_license", "max_line_length": 79, "num_lines": 225, "path": "/legacy/display_indexes/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport math\n\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.http import require_POST\nfrom django.utils.translation import ugettext\nfrom django.http import Http404\n\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.indexes.models import Index\nfrom legacy.indexes.models import StandardMonthIndex\nfrom legacy.measurementpoints.models import Graph\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.users.decorators import auth_or_error, auth_or_redirect\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.views import render_to, json_response\nfrom legacy.display_measurementpoints.views import PeriodForm\nfrom legacy.display_widgets.models import DashboardWidget\nfrom gridplatform.utils import condense\n\nfrom .tasks import graph_task\n\n\n@auth_or_redirect\n@render_to('display_indexes/index.html')\ndef index(request):\n customer = request.customer\n root_groups = get_user().userprofile.collections.filter(\n role=Collection.GROUP)\n\n if root_groups:\n # if user is bound to groups, use those\n groups = [g\n for r in root_groups\n for g in r.get_descendants(include_self=True)]\n else:\n # otherwise, show all groups for customer\n groups = list(Collection.objects.filter(\n customer=customer, role=Collection.GROUP))\n\n group_ids = [g.id for g in groups]\n global_indexes = list(Index.objects.filter(\n Q(customer=customer) | Q(customer=None)).filter(\n Q(collection__isnull=True) | Q(collection_id__in=group_ids)))\n global_indexes.sort(key=lambda index: unicode(index).lower())\n\n return {\n 'indexes': global_indexes,\n }\n\n\n@auth_or_redirect\n@render_to('display_indexes/index_detail.html')\ndef detail(request, pk):\n period_form = PeriodForm(request.GET, months_limit=2)\n if not period_form.is_valid():\n from_timestamp = condense.floor(\n get_customer().now(),\n RelativeTimeDelta(days=1),\n get_customer().timezone)\n to_timestamp = from_timestamp + RelativeTimeDelta(days=1)\n else:\n from_timestamp, to_timestamp = period_form.get_period()\n\n customer = get_customer()\n root_groups = get_user().userprofile.collections.exclude(\n graph__isnull=False).all()\n if root_groups:\n # if user is bound to groups, use those\n groups = [g\n for r in root_groups\n for g in r.get_descendants(include_self=True)]\n else:\n # otherwise, show all groups for user\n groups = list(Collection.objects.exclude(graph__isnull=False).filter(\n customer=customer))\n group_ids = [g.id for g in groups]\n global_indexes = Index.objects.filter(\n Q(customer=customer) | Q(customer=None)).filter(\n Q(collection__isnull=True) | Q(collection_id__in=group_ids))\n\n index = get_object_or_404(global_indexes, pk=pk).subclass_instance\n global_indexes = list(global_indexes)\n global_indexes.sort(key=lambda index: ugettext(index.name_plain).lower())\n\n is_standard_month = False\n if isinstance(index, StandardMonthIndex):\n is_standard_month = True\n\n widgets = DashboardWidget.objects.filter(\n index=index, user=get_user())\n\n return {\n 'indexes': global_indexes,\n 'id': pk,\n 'period_form': period_form,\n 'name': index.name_plain,\n 'standart_month': is_standard_month,\n 'widgets': widgets\n }\n\n\ndef get_ticks(count, maximum):\n return int(math.floor(count / math.ceil(float(count) / float(maximum))))\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef async_graph(request, pk):\n period_form = PeriodForm(request.POST)\n if not period_form.is_valid():\n from_timestamp = condense.floor(\n get_customer().now(),\n RelativeTimeDelta(days=1),\n request.customer.timezone)\n to_timestamp = from_timestamp + RelativeTimeDelta(days=1)\n else:\n from_timestamp, to_timestamp = period_form.get_period()\n\n async = graph_task.delay(pk, from_timestamp, to_timestamp)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\n@auth_or_error\n@json_response\n@require_POST\ndef async_graph_last_24h(request, pk):\n if not get_customer():\n raise Http404\n to_timestamp = condense.floor(\n request.customer.now() + RelativeTimeDelta(hours=1),\n RelativeTimeDelta(hours=1),\n request.customer.timezone)\n from_timestamp = to_timestamp - RelativeTimeDelta(hours=24)\n\n async = graph_task.delay(pk, from_timestamp, to_timestamp)\n return {\n 'task_id': async.id,\n 'status': async.status,\n }\n\n\n@auth_or_error\n@json_response\ndef graph(request, pk):\n \"\"\"\n @deprecated: Use the L{async_graph} instead.\n \"\"\"\n period_form = PeriodForm(request.GET)\n if not period_form.is_valid():\n from_timestamp = condense.floor(\n get_customer().now(), RelativeTimeDelta(days=1),\n get_customer().timezone)\n to_timestamp = from_timestamp + RelativeTimeDelta(days=1)\n else:\n from_timestamp, to_timestamp = period_form.get_period()\n customer = request.customer\n\n qs = Index.objects.filter(Q(customer=customer) | Q(customer=None))\n root_groups = get_user().userprofile.collections.all()\n if root_groups:\n # if user is restricted to groups, filter...\n groups = [group.get_descendants(include_self=True)\n for group in root_groups]\n group_ids = [c.id for grouptree in groups\n for c in grouptree]\n qs = qs.filter(Q(collection_id__isnull=True) |\n Q(collection_id__in=group_ids))\n index = get_object_or_404(qs, pk=pk).subclass_instance\n\n class RuntimeGraph(Graph):\n class Meta:\n proxy = True\n\n def __init__(self, index, *args, **kwargs):\n super(RuntimeGraph, self).__init__(*args, **kwargs)\n self.index = index\n\n graph = RuntimeGraph(index)\n\n days = int((to_timestamp - from_timestamp).total_seconds() /\n datetime.timedelta(days=1).total_seconds())\n\n if isinstance(index, StandardMonthIndex):\n result = graph.get_graph_data(\n 12, from_timestamp, num_samples=12,\n sample_resolution=RelativeTimeDelta(months=1),\n data_series_set=[index])\n else:\n if days <= 1:\n # display hours\n hours = int((to_timestamp - from_timestamp).total_seconds() / 3600)\n result = graph.get_graph_data(\n get_ticks(hours, 12), from_timestamp,\n to_timestamp=to_timestamp,\n data_series_set=[index])\n\n elif days < 31:\n # display hours\n result = graph.get_graph_data(\n get_ticks(days, 12), from_timestamp,\n to_timestamp=to_timestamp,\n data_series_set=[index])\n else:\n result = graph.get_graph_data(\n get_ticks(days, 12), from_timestamp,\n to_timestamp=to_timestamp,\n data_series_set=[index])\n\n result[\"options\"].update({\"grid\": {\"outlineWidth\": 0,\n \"verticalLines\": True}})\n result[\"options\"][\"yaxis\"].update({\"titleAngle\": 90})\n result[\"options\"].update({\"HtmlText\": False})\n\n return result\n" }, { "alpha_fraction": 0.6638655662536621, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 22.799999237060547, "blob_id": "696013ccb0e2a3c9e12ced5e14e2ab453a862a5f", "content_id": "48fa6d414456f90eabe4e1bbbae50fbd9e980d30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 238, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/scripts/production_nordic/start_celery.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nsource $(dirname $0)/base.sh\n\nPIDFILE=$PID_DIR/%n.pid\nLOGFILE=%n.log\n\ncelery multi start celery --app=gridplatform -Q celery \\\n --time-limit=3600 --concurrency=2 \\\n --pidfile=$PIDFILE --logfile=$LOGFILE --loglevel=INFO\n" }, { "alpha_fraction": 0.5012751817703247, "alphanum_fraction": 0.5816429257392883, "avg_line_length": 45.5745849609375, "blob_id": "87909b71aad48d5abe0160968d71f5503ccd415a", "content_id": "1e5f3a6e62c92cca61a256f0cabf9a0e93a6b8b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33720, "license_type": "no_license", "max_line_length": 78, "num_lines": 724, "path": "/gridplatform/condensing/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.test import SimpleTestCase\nfrom django.test.utils import override_settings\n\nimport pytz\n\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom gridplatform.customer_datasources.models import DataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.datasources.models import interpolate\n\nfrom .models import adjust_from_to\nfrom .models import generate_cache\nfrom .models import generate_period_data\nfrom .models import missing_periods\nfrom .models import period_aligned\nfrom .models import raw_data_for_cache\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass CleanupCacheForRawdataDeleteTest(TestCase):\n def setUp(self):\n self.datasource = DataSource.objects.create(unit='milliwatt*hour')\n\n def test_delete(self):\n # NOTE: Cleanup is slightly conservative --- removes periods touching\n # endpoints of tainted period (which might not be strictly\n # necessary...)\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 13, 0, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 13, 2, tzinfo=pytz.utc), 8),\n (datetime.datetime(2014, 4, 14, 14, 0, tzinfo=pytz.utc), 17),\n (datetime.datetime(2014, 4, 14, 15, 0, tzinfo=pytz.utc), 29),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(self.datasource, from_timestamp, to_timestamp)\n obj = RawData.objects.get(\n timestamp=datetime.datetime(2014, 4, 14, 13, 2, tzinfo=pytz.utc))\n obj.delete()\n expected_hours = []\n self.assertEqual(\n list(self.datasource.houraccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_hours)\n expected_minutes = [\n (datetime.datetime(2014, 4, 14, 14, 5, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 10, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 15, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 20, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 25, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 30, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 35, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 40, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 45, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 50, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 55, tzinfo=pytz.utc), 1),\n ]\n self.assertEqual(\n list(self.datasource.fiveminuteaccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_minutes)\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass GetAccumulatedTest(TestCase):\n def setUp(self):\n self.datasource = DataSource.objects.create(unit='milliwatt*hour')\n\n def test_all_cached(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 77),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 77),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(self.datasource, from_timestamp, to_timestamp)\n expected_hours = [\n Sample(\n datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n PhysicalQuantity(12, 'milliwatt*hour'), False, False),\n Sample(\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc),\n PhysicalQuantity(12, 'milliwatt*hour'), False, False),\n ]\n self.assertEqual(\n self.datasource.hourly_accumulated(from_timestamp, to_timestamp),\n expected_hours)\n expected_minutes = [\n Sample(\n datetime.datetime(2014, 4, 14, 13, 0, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 13, 5, tzinfo=pytz.utc),\n PhysicalQuantity(1, 'milliwatt*hour'), False, False),\n Sample(\n datetime.datetime(2014, 4, 14, 13, 5, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 13, 10, tzinfo=pytz.utc),\n PhysicalQuantity(1, 'milliwatt*hour'), False, False),\n Sample(\n datetime.datetime(2014, 4, 14, 13, 10, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 13, 15, tzinfo=pytz.utc),\n PhysicalQuantity(1, 'milliwatt*hour'), False, False),\n ]\n self.assertEqual(\n self.datasource.five_minute_accumulated(\n from_timestamp,\n from_timestamp + datetime.timedelta(minutes=15)),\n expected_minutes)\n\n def test_partial_data(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, 0, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, 30, tzinfo=pytz.utc), 47),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(self.datasource, from_timestamp, to_timestamp)\n expected_hours = [\n Sample(\n datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n PhysicalQuantity(12, 'milliwatt*hour'), False, False),\n ]\n self.assertEqual(\n self.datasource.hourly_accumulated(from_timestamp, to_timestamp),\n expected_hours)\n\n def test_partial_cache(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n cache_from_timestamp = datetime.datetime(\n 2014, 4, 14, 13, tzinfo=pytz.utc)\n cache_to_timestamp = datetime.datetime(\n 2014, 4, 14, 14, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 77),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 77),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(\n self.datasource, cache_from_timestamp, cache_to_timestamp)\n expected_hours = [\n Sample(\n datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n PhysicalQuantity(12, 'milliwatt*hour'), False, False),\n Sample(\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc),\n PhysicalQuantity(12, 'milliwatt*hour'), False, False),\n ]\n self.assertEqual(\n self.datasource.hourly_accumulated(from_timestamp, to_timestamp),\n expected_hours)\n\n def test_pulse(self):\n self.datasource.unit = 'impulse'\n self.datasource.save()\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n cache_from_timestamp = datetime.datetime(\n 2014, 4, 14, 13, tzinfo=pytz.utc)\n cache_to_timestamp = datetime.datetime(\n 2014, 4, 14, 14, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 77),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 77),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(\n self.datasource, cache_from_timestamp, cache_to_timestamp)\n expected_hours = [\n Sample(\n datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n PhysicalQuantity(72, 'impulse'), False, False),\n Sample(\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc),\n PhysicalQuantity(0, 'impulse'), False, False),\n ]\n self.assertEqual(\n self.datasource.hourly_accumulated(from_timestamp, to_timestamp),\n expected_hours)\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass GenerateCacheTest(TestCase):\n def setUp(self):\n self.datasource = DataSource.objects.create(unit='milliwatt*hour')\n\n def test_complete(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 77),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 77),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(self.datasource, from_timestamp, to_timestamp)\n expected_hours = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 12),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 12),\n ]\n self.assertEqual(\n list(self.datasource.houraccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_hours)\n expected_minutes = [\n (datetime.datetime(2014, 4, 14, 13, 0, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 5, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 10, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 15, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 20, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 25, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 30, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 35, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 40, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 45, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 50, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 55, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 0, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 5, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 10, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 15, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 20, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 25, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 30, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 35, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 40, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 45, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 50, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 55, tzinfo=pytz.utc), 1),\n ]\n self.assertEqual(\n list(self.datasource.fiveminuteaccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_minutes)\n\n def test_partial(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 29),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n generate_cache(self.datasource, from_timestamp, to_timestamp)\n expected_hours = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 12),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 12),\n ]\n self.assertEqual(\n list(self.datasource.houraccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_hours)\n expected_minutes = [\n (datetime.datetime(2014, 4, 14, 13, 0, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 5, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 10, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 15, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 20, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 25, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 30, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 35, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 40, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 45, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 50, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 13, 55, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 0, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 5, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 10, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 15, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 20, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 25, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 30, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 35, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 40, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 45, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 50, tzinfo=pytz.utc), 1),\n (datetime.datetime(2014, 4, 14, 14, 55, tzinfo=pytz.utc), 1),\n ]\n self.assertEqual(\n list(self.datasource.fiveminuteaccumulateddata_set.order_by(\n 'timestamp').values_list('timestamp', 'value')),\n expected_minutes)\n\n\nclass MissingPeriodsTest(SimpleTestCase):\n def test_missing_periods(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n present = [\n datetime.datetime(2014, 4, 14, 12, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc),\n ]\n expected_missing = [\n (\n datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc),\n ),\n (\n datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc),\n datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc),\n ),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n list(missing_periods(\n from_timestamp, to_timestamp, present, period_length)),\n expected_missing)\n\n\nclass GeneratePeriodDataTest(SimpleTestCase):\n def test_empty(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = []\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n list(generate_period_data(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n [])\n\n def test_matching(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 20),\n (datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc), 35),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 45),\n (datetime.datetime(2014, 4, 14, 18, tzinfo=pytz.utc), 50),\n (datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc), 50),\n ]\n period_length = datetime.timedelta(hours=1)\n expected = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 15),\n (datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 18, tzinfo=pytz.utc), 0),\n ]\n self.assertEqual(\n list(generate_period_data(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n expected)\n\n def test_interpolate(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc), 45),\n ]\n period_length = datetime.timedelta(hours=1)\n expected = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n ]\n self.assertEqual(\n list(generate_period_data(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n expected)\n\n def test_partial(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 25),\n (datetime.datetime(2014, 4, 14, 16, tzinfo=pytz.utc), 45),\n ]\n period_length = datetime.timedelta(hours=1)\n expected = [\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n ]\n self.assertEqual(\n list(generate_period_data(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n expected)\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass RawDataForCacheTest(TestCase):\n def setUp(self):\n self.datasource = DataSource.objects.create(unit='milliwatt*hour')\n\n def test_no_data(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n [])\n\n def test_edges(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (from_timestamp, 50),\n (to_timestamp, 100),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data)\n\n def test_close_outside(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, 59, 15, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 7),\n (datetime.datetime(2014, 4, 14, 19, 1, 45, tzinfo=pytz.utc), 8),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data)\n\n def test_outside(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 7),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 8),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data)\n\n def test_missing_end(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 7),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data)\n\n def test_missing_start(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 7),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 8),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data)\n\n def test_filtering(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, 58, 15, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 12, 59, 15, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc), 7),\n (datetime.datetime(2014, 4, 14, 19, 1, 45, tzinfo=pytz.utc), 8),\n (datetime.datetime(2014, 4, 14, 19, 2, 45, tzinfo=pytz.utc), 8),\n ]\n RawData.objects.bulk_create([\n RawData(\n datasource=self.datasource, value=value, timestamp=timestamp)\n for timestamp, value in data])\n self.assertEqual(\n raw_data_for_cache(self.datasource, from_timestamp, to_timestamp),\n data[1:-1])\n\n\nclass AdjustFromToTest(SimpleTestCase):\n def test_noop_covered(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 20, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (from_timestamp, to_timestamp))\n\n def test_noop_edges(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (from_timestamp, 5),\n (to_timestamp, 10),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (from_timestamp, to_timestamp))\n\n def test_adjust_from(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 14, 5, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 20, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n expected_from = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (expected_from, to_timestamp))\n\n def test_adjust_to(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 17, 35, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n # NTS: Data is measured at timestamp; *not* representing periods\n # period_length periods here.\n expected_to = datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (from_timestamp, expected_to))\n\n def test_adjust_both(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 14, 20, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 17, 35, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n expected_from = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n expected_to = datetime.datetime(2014, 4, 14, 17, tzinfo=pytz.utc)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (expected_from, expected_to))\n\n def test_only_before(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 11, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 12, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 12, 35, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (None, None))\n\n def test_only_after(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 19, 20, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 20, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 22, tzinfo=pytz.utc), 20),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (None, None))\n\n def test_partial_inside(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 15, 20, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 15, 55, tzinfo=pytz.utc), 10),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (None, None))\n\n def test_aligned_inside(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (data_timestamp, 5),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (data_timestamp, data_timestamp))\n\n def test_empty(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 19, tzinfo=pytz.utc)\n data = []\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n adjust_from_to(data, from_timestamp, to_timestamp, period_length),\n (None, None))\n\n\nclass PeriodAlignedTest(SimpleTestCase):\n def test_matching(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 15),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n list(period_aligned(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n data)\n\n def test_interpolate_middle(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 15),\n ]\n expected = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 15),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n list(period_aligned(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n expected)\n\n def test_interpolate(self):\n from_timestamp = datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc)\n to_timestamp = datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc)\n data = [\n (datetime.datetime(2014, 4, 14, 12, 30, tzinfo=pytz.utc), 5),\n (datetime.datetime(2014, 4, 14, 13, 30, tzinfo=pytz.utc), 7),\n (datetime.datetime(2014, 4, 14, 14, 30, tzinfo=pytz.utc), 13),\n (datetime.datetime(2014, 4, 14, 15, 30, tzinfo=pytz.utc), 15),\n ]\n expected = [\n (datetime.datetime(2014, 4, 14, 13, tzinfo=pytz.utc), 6),\n (datetime.datetime(2014, 4, 14, 14, tzinfo=pytz.utc), 10),\n (datetime.datetime(2014, 4, 14, 15, tzinfo=pytz.utc), 14),\n ]\n period_length = datetime.timedelta(hours=1)\n self.assertEqual(\n list(period_aligned(\n data, from_timestamp, to_timestamp,\n period_length, interpolate)),\n expected)\n" }, { "alpha_fraction": 0.6535656452178955, "alphanum_fraction": 0.6643320322036743, "avg_line_length": 37.99774169921875, "blob_id": "43afa9df99849629869a8937f6c0c277fff3d9c5", "content_id": "1e234a4ccb4bf288672b49b770c44836a885c683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17276, "license_type": "no_license", "max_line_length": 79, "num_lines": 443, "path": "/legacy/legacy_utils/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom fractions import Fraction\n\nfrom django.test import TestCase\n\nfrom gridplatform.customers.models import Customer\nfrom gridplatform import trackuser\nfrom gridplatform.utils.preferredunits import AbsoluteCelsiusUnitConverter\nfrom gridplatform.utils.preferredunits import AbsoluteFahrenheitUnitConverter\nfrom gridplatform.utils.preferredunits import AreaENPIUnitConverter\nfrom gridplatform.utils.preferredunits import PersonsENPIUnitConverter\nfrom gridplatform.utils.preferredunits import PhysicalQuantity\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.preferredunits import RelativeCelsiusUnitConverter\nfrom gridplatform.utils.preferredunits import RelativeFahrenheitUnitConverter\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.fields import DataRoleField\n\nfrom .preferredunits import get_preferred_unit_converter\n\n\nclass GetPreferredUnitConverterCelsiusTest(TestCase):\n def setUp(self):\n self.customer = Customer(temperature='celsius')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_relative(self):\n self.assertIsInstance(\n get_preferred_unit_converter(DataRoleField.RELATIVE_TEMPERATURE),\n RelativeCelsiusUnitConverter)\n\n def test_absolute(self):\n self.assertIsInstance(\n get_preferred_unit_converter(DataRoleField.ABSOLUTE_TEMPERATURE),\n AbsoluteCelsiusUnitConverter)\n\n\nclass GetPreferredUnitConverterFahrenheitTest(TestCase):\n def setUp(self):\n self.customer = Customer(temperature='fahrenheit')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_relative(self):\n self.assertIsInstance(\n get_preferred_unit_converter(DataRoleField.RELATIVE_TEMPERATURE),\n RelativeFahrenheitUnitConverter)\n\n def test_absolute(self):\n self.assertIsInstance(\n get_preferred_unit_converter(DataRoleField.ABSOLUTE_TEMPERATURE),\n AbsoluteFahrenheitUnitConverter)\n\n\nclass GetPreferredUnitConverterMiscTest(TestCase):\n def setUp(self):\n self.customer = Customer()\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_cost(self):\n preferred_unit_converter = get_preferred_unit_converter(\n DataRoleField.COST, unit='currency_dkk')\n self.assertIsInstance(preferred_unit_converter, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(1, 'currency_dkk')),\n 1)\n\n def test_heating_degree_days(self):\n preferred_unit_converter = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS)\n self.assertIsInstance(preferred_unit_converter, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(1, 'kelvin*day')),\n 1)\n\n def test_co2(self):\n preferred_unit_converter = get_preferred_unit_converter(\n DataRoleField.CO2)\n self.assertIsInstance(preferred_unit_converter, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit_converter.extract_value(\n PhysicalQuantity(1, 'tonne')),\n 1)\n\n\nclass GetPreferredUnitConverterUtilityTypeTest(object):\n def test_instantaneous(self):\n raise NotImplementedError()\n\n def test_consumption(self):\n raise NotImplementedError()\n\n def test_heating_degree_days_corrected_consumption(self):\n raise NotImplementedError()\n\n def test_energy_performance_indicator_persons(self):\n raise NotImplementedError()\n\n def test_energy_performance_indicator_area(self):\n raise NotImplementedError()\n\n\nclass GetPreferredUnitConverterElectricityTest(\n GetPreferredUnitConverterUtilityTypeTest, TestCase):\n def setUp(self):\n self.customer = Customer(\n electricity_consumption='kilowatt*hour',\n electricity_instantaneous='watt')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantaneous(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.POWER, utilitytypes.METER_CHOICES.electricity)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'watt')),\n 42)\n\n def test_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'kilowatt*hour')),\n 42)\n\n def test_heating_degree_days_corrected_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'kilowatt*hour')),\n 42)\n\n def test_energy_performance_indicator_persons(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.assertIsInstance(preferred_unit, PersonsENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'kilowatt*hour*person^-1*day^-1')),\n 42)\n\n def test_energy_performance_indicator_area(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.assertIsInstance(preferred_unit, AreaENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'kilowatt*hour*meter^-2*day^-1')),\n 42)\n\n\nclass GetPreferredUnitConverterHeatTest(\n GetPreferredUnitConverterUtilityTypeTest, TestCase):\n def setUp(self):\n self.customer = Customer(\n heat_consumption='kilowatt*hour',\n heat_instantaneous='watt')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantaneous(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.POWER,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'watt')),\n 42)\n\n def test_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'kilowatt*hour')),\n 42)\n\n def test_heating_degree_days_corrected_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'kilowatt*hour')),\n 42)\n\n def test_energy_performance_indicator_persons(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.assertIsInstance(preferred_unit, PersonsENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'kilowatt*hour*person^-1*day^-1')),\n 42)\n\n def test_energy_performance_indicator_area(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating)\n self.assertIsInstance(preferred_unit, AreaENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'kilowatt*hour*meter^-2*day^-1')),\n 42)\n\n\nclass GetPreferredUnitConverterGasTest(\n GetPreferredUnitConverterUtilityTypeTest, TestCase):\n def setUp(self):\n self.customer = Customer(\n gas_consumption='meter*meter*meter',\n gas_instantaneous='meter*meter*meter*hour^-1')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantaneous(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.VOLUME_FLOW, utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3*hour^-1')),\n 42)\n\n def test_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_heating_degree_days_corrected_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_energy_performance_indicator_persons(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, PersonsENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*person^-1*day^-1')),\n 42)\n\n def test_energy_performance_indicator_area(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, AreaENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*meter^-2*day^-1')),\n 42)\n\n\nclass GetPreferredUnitConverterWaterTest(\n GetPreferredUnitConverterUtilityTypeTest, TestCase):\n\n def setUp(self):\n self.customer = Customer(\n water_consumption='meter*meter*meter',\n water_instantaneous='meter*meter*meter*hour^-1')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantaneous(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.VOLUME_FLOW, utilitytypes.METER_CHOICES.water)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3*hour^-1')),\n 42)\n\n def test_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, utilitytypes.METER_CHOICES.water)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_heating_degree_days_corrected_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.water)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_energy_performance_indicator_persons(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utilitytypes.OPTIONAL_METER_CHOICES.water)\n self.assertIsInstance(preferred_unit, PersonsENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*person^-1*day^-1')),\n 42)\n\n def test_energy_performance_indicator_area(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utilitytypes.OPTIONAL_METER_CHOICES.gas)\n self.assertIsInstance(preferred_unit, AreaENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*meter^-2*day^-1')),\n 42)\n\n\nclass GetPreferredUnitConverterOilTest(\n GetPreferredUnitConverterUtilityTypeTest, TestCase):\n def setUp(self):\n self.customer = Customer(\n oil_consumption='meter*meter*meter',\n oil_instantaneous='meter*meter*meter*hour^-1')\n trackuser._set_customer(self.customer)\n\n def tearDown(self):\n trackuser._set_customer(None)\n\n def test_instantaneous(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.VOLUME_FLOW, utilitytypes.OPTIONAL_METER_CHOICES.oil)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3*hour^-1')),\n 42)\n\n def test_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION, utilitytypes.OPTIONAL_METER_CHOICES.oil)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_heating_degree_days_corrected_consumption(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.HEATING_DEGREE_DAYS_CORRECTED_CONSUMPTION,\n utilitytypes.OPTIONAL_METER_CHOICES.oil)\n self.assertIsInstance(preferred_unit, PhysicalUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(42, 'meter^3')),\n 42)\n\n def test_energy_performance_indicator_persons(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_EMPLOYEES,\n utilitytypes.OPTIONAL_METER_CHOICES.oil)\n self.assertIsInstance(preferred_unit, PersonsENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*person^-1*day^-1')),\n 42)\n\n def test_energy_performance_indicator_area(self):\n preferred_unit = get_preferred_unit_converter(\n DataRoleField.CONSUMPTION_UTILIZATION_AREA,\n utilitytypes.OPTIONAL_METER_CHOICES.oil)\n self.assertIsInstance(preferred_unit, AreaENPIUnitConverter)\n self.assertEqual(\n preferred_unit.extract_value(\n PhysicalQuantity(\n Fraction(42, 365), 'meter^3*meter^-2*day^-1')),\n 42)\n\n\nclass EfficiencyUnitConverterTest(TestCase):\n def setUp(self):\n self.customer = Customer()\n self.converter = get_preferred_unit_converter(\n DataRoleField.EFFICIENCY,\n customer=self.customer)\n\n def test_extract_value(self):\n quantity = PhysicalQuantity(1, 'millibar')\n self.assertEqual(\n Fraction(1, 1000), self.converter.extract_value(quantity))\n\n def test_display_unit(self):\n unicode(self.converter.get_display_unit())\n" }, { "alpha_fraction": 0.673092782497406, "alphanum_fraction": 0.6735051274299622, "avg_line_length": 36.02289962768555, "blob_id": "994ff3a5567d5243bbedd2cfb2d61a699bafce71", "content_id": "c4f72cdaf14679764c73c962344b5c45be50b352", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9700, "license_type": "no_license", "max_line_length": 81, "num_lines": 262, "path": "/gridplatform/productions/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport re\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.core.exceptions import ValidationError\nfrom django.utils.functional import cached_property\nfrom model_utils import Choices\nfrom model_utils import FieldTracker\n\nimport gridplatform.datasequences.models\nfrom gridplatform.datasequences.utils import add_ranged_sample_sequences\nfrom gridplatform.customers.mixins import EncryptionCustomerFieldMixin\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedTextField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.trackuser.managers import CustomerBoundManager\nfrom gridplatform.utils import development_sum\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.api import next_valid_date_for_datasequence\nfrom gridplatform.utils.api import previous_valid_date_for_datasequence\n\n\nclass Production(gridplatform.datasequences.models.AccumulationBase):\n \"\"\"\n An accumulation data sequence for production. This is a specialization of\n :class:`gridplatform.datasequences.models.AccumulationBase`.\n\n :cvar STATIC_UNIT_CHOICES: Choices for the ``unit`` field.\n ``STATIC_UNIT_CHOICES`` gives too many choices, so creation forms\n should really use the ``unit_choices`` property. A default\n :class:`.ModelForm` will be as user friendly as possible without form\n customization regarding the unit field (were there no choices given,\n the default form field would be a text field rather than a choice\n field).\n :ivar unit: The unit of production. This should never be changed.\n :ivar unit_choices: Dynamic choices for the ``unit`` field. Gives the\n human readable form of choices for the associated customer. See also\n :meth:`.Customer.get_production_unit_choices`.\n :ivar period_set: A reverse relation to\n :class:`gridplatform.productions.models.Period` instances that define\n the data of this production data sequence.\n \"\"\"\n STATIC_UNIT_CHOICES = Choices(\n *('production_%s' % letter for letter in 'abcde'))\n # DO NOT UPDATE\n unit = BuckinghamField(_('unit'), choices=STATIC_UNIT_CHOICES)\n\n tracker = FieldTracker(fields=['unit'])\n\n class Meta:\n verbose_name = _('production')\n verbose_name_plural = _('productions')\n\n @cached_property\n def unit_choices(self):\n return self.customer.get_production_unit_choices()\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.unit`` was updated.\n :raise ValidationError: If ``self.unit`` is not in ``self.unit_choices``.\n \"\"\"\n previous_unit = self.tracker.previous('unit')\n if previous_unit is not None:\n if previous_unit != self.unit:\n raise ValidationError(\n {'unit': [ugettext('Cannot be changed.')]})\n\n if self.unit not in self.unit_choices:\n raise ValidationError({'unit': [ugettext('Invalid choice.')]})\n\n def get_unit_display(self):\n \"\"\"\n :return: A human readable representation of ``self.unit``.\n \"\"\"\n return self.unit_choices[self.unit]\n\n\nclass ProductionGroup(EncryptionCustomerFieldMixin, EncryptedModel):\n \"\"\"\n A group of :class:`.Production`.\n\n :ivar customer: The owning customer.\n :ivar name: The name of this group.\n :ivar description: A description of this group.\n :ivar productions: The :class:`.Production` in this group.\n :ivar unit: The unit shared among the :class:`.Production` in this group.\n Updating this field should be avoided.\n :cvar objects: A :class:`.CustomerBoundManager`.\n \"\"\"\n name = EncryptedCharField(_('name'), max_length=100)\n description = EncryptedTextField(_('description'), blank=True)\n\n # WARNING: removing a production from this relation is almost always an\n # error.\n productions = models.ManyToManyField(\n Production, verbose_name=_('productions'), blank=True)\n\n # TODO: rename to production_unit.\n #\n # TODO: prevent modification.\n unit = BuckinghamField(_('production unit'))\n\n objects = CustomerBoundManager()\n\n class Meta:\n verbose_name = _('production group')\n verbose_name_plural = _('production groups')\n\n def save(self, *args, **kwargs):\n \"\"\"\n :precondition: ``self.unit`` matches 'production_[abcde]'.\n \"\"\"\n assert re.match('production_[abcde]', self.unit), self.unit\n return super(ProductionGroup, self).save(*args, **kwargs)\n\n def clean(self):\n \"\"\"\n :raise ValidationError: If ``self.unit`` is not found in the choices\n returned by :meth:`.Customer.get_production_unit_choices` for the\n owning :class:`.Customer`.\n \"\"\"\n if self.unit not in self.customer.get_production_unit_choices():\n raise ValidationError({'unit': ugettext('Invalid choice.')})\n\n def __unicode__(self):\n return self.name_plain\n\n # TODO: rename to production_sum\n def development_sum(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: The total production of all :class:`.Production` in this\n :class:`.ProductionGroup` in the given timespan.\n :rtype: :class:`.PhysicalQuantity`\n\n :param from_timestamp: The start of the given timespan.\n :param to_timestamp: The end of the given timespan.\n \"\"\"\n return development_sum(\n self.productions.all(), self.unit, from_timestamp, to_timestamp)\n\n def production_sequence(self, from_timestamp, to_timestamp, resolution):\n \"\"\"\n Ranged sample sequence of productions between ``from_timestamp`` and\n ``to_timestamp`` with given ``resolution``.\n \"\"\"\n return add_ranged_sample_sequences(\n [\n production.development_sequence(\n from_timestamp, to_timestamp, resolution)\n for production in self.productions.all()\n ],\n from_timestamp, to_timestamp, resolution)\n\n def next_valid_date(self, date, timezone):\n \"\"\"\n :return: The next date with data among ``self.productions``. If no\n such date exist, ``None`` is returned.\n\n :param date: The date to find a date after.\n :param tzinfo timezone: The timezone used to translate dates into\n timestamp ranges.\n \"\"\"\n return next_valid_date_for_datasequence(\n self.productions.all(), date, timezone)\n\n def previous_valid_date(self, date, timezone):\n \"\"\"\n :return: The previous date with data among ``self.productions``. If no\n such date exist, ``None`` is returned.\n\n :param date: The date to find a date before.\n :param tzinfo timezone: The timezone used to translate dates into\n timestamp ranges.\n \"\"\"\n return previous_valid_date_for_datasequence(\n self.productions.all(), date, timezone)\n\n\nclass Period(gridplatform.datasequences.models.AccumulationPeriodBase):\n \"\"\"\n Base class for periods of :class:`.Production`. This is a specialization\n of :class:`gridplatform.datasequences.models.AccumulationPeriodBase`.\n\n :ivar datasequence: The :class:`.Production` this period is part of.\n \"\"\"\n datasequence = models.ForeignKey(\n Production,\n verbose_name=_('data sequence'),\n editable=False)\n\n class Meta:\n verbose_name = _('production period')\n verbose_name_plural = _('production periods')\n\n\nclass NonpulsePeriod(\n gridplatform.datasequences.models.NonpulseAccumulationPeriodMixin,\n Period):\n \"\"\"\n A specialization of :class:`gridplatform.productions.models.Period` mixed\n with\n :class:`gridplatform.datasequences.models.NonpulseAccumulationPeriodMixin`\n\n Defines a period of a :class:`.Production` in terms of a nonpulse data\n source.\n \"\"\"\n\n class Meta:\n verbose_name = _('non-pulse production period')\n verbose_name_plural = _('non-pulse production periods')\n\n\nclass PulsePeriod(\n gridplatform.datasequences.models.PulseAccumulationPeriodMixin,\n Period):\n \"\"\"\n A specialization of :class:`gridplatform.productions.models.Period` mixed\n with\n :class:`gridplatform.datasequences.models.PulseAccumulationPeriodMixin`\n\n Defines a period of a :class:`.Production` in terms of a pulse data source.\n \"\"\"\n\n class Meta:\n verbose_name = _('pulse production period')\n verbose_name_plural = _('pulse production periods')\n\n\nclass SingleValuePeriod(\n gridplatform.datasequences.models.SingleValueAccumulationPeriodMixin,\n Period):\n \"\"\"\n A specialization of :class:`gridplatform.productions.models.Period` mixed\n with\n :class:`gridplatform.datasequences.models.SingleValueAccumulationPeriodMixin`\n\n Defines a period of a :class:`.Production` in terms of a fixed value.\n \"\"\"\n\n class Meta:\n verbose_name = _('single value production period')\n verbose_name_plural = _('single value production periods')\n\n\nclass OfflineTolerance(\n gridplatform.datasequences.models.OfflineToleranceMixin):\n \"\"\"\n A :class:`gridplatform.datasequences.models.OfflineToleranceMixin`\n specialization for :class:`.Production`.\n\n :ivar datasequence: The :class:`.Production` for which this offline\n tolerance is defined.\n \"\"\"\n datasequence = models.OneToOneField(\n Production,\n editable=False)\n" }, { "alpha_fraction": 0.5779845118522644, "alphanum_fraction": 0.6055110096931458, "avg_line_length": 40.27964782714844, "blob_id": "3a4b4b62f170e906bcd171b3276eaf756dead2a0", "content_id": "06e1ea2c9de673fce9d94594916288147338d7e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 69969, "license_type": "no_license", "max_line_length": 89, "num_lines": 1695, "path": "/legacy/projects/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines tests for the C{projects} app.\n\"\"\"\n\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom mock import patch\nfrom decimal import Decimal\nfrom fractions import Fraction\nimport unittest\n\nfrom django.forms import ValidationError\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nfrom django.utils.translation import ugettext_lazy as _\n\nimport pytz\n\nfrom gridplatform import trackuser\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom gridplatform.customers.models import Customer\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.indexes.models import Index\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import CostCalculation\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.tests import TestDataSeries\nfrom gridplatform.trackuser import replace_customer\nfrom gridplatform.trackuser import replace_user\nfrom gridplatform.users.models import User\nfrom gridplatform.utils import DATETIME_MAX\nfrom gridplatform.utils import DATETIME_MIN\nfrom gridplatform.utils import condense\nfrom gridplatform.utils import unix_timestamp\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.providers.models import Provider\n\nfrom .models import AdditionalSaving\nfrom .models import BenchmarkProject\nfrom .models import Cost\nfrom .models import Stage\nfrom .tasks import AnnualSavingsPotentialReportTask\nfrom .views import FinalizeAnnualSavingsPotentialReportView\nfrom .forms import AnnualSavingsPotentialReportGenerationForm\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectEncryptionTest(TestCase):\n \"\"\"\n Test the encryption properties of the L{BenchmarkProject} model.\n \"\"\"\n def setUp(self):\n \"\"\"\n Create and store a L{BenchmarkProject}.\n \"\"\"\n Provider.objects.create()\n self.customer = Customer(\n timezone=pytz.utc,\n currency_unit='currency_dkk')\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.unit = BenchmarkProject(\n name_plain='Some test project',\n background_plain='Some test description',\n expectations_plain='Some exspections',\n actions_plain='Some actions',\n comments_plain='Some comments',\n runtime=52,\n estimated_yearly_consumption_costs_before=Decimal('2000.33'),\n estimated_yearly_consumption_before=Decimal('2000.33'),\n estimated_co2_emissions_before=Decimal('2000.33'),\n expected_savings_in_yearly_total_costs=Decimal(\n '2000.33'),\n expected_savings_in_yearly_consumption_after=Decimal('2000.33'),\n expected_reduction_in_yearly_co2_emissions=Decimal('2000.33'),\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n self.unit.save()\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_basic_usage(self):\n \"\"\"\n Test if storing and loading results in sensible values.\n \"\"\"\n loaded_unit = BenchmarkProject.objects.get(id=self.unit.id)\n\n self.assertEqual(\n loaded_unit.name_plain, 'Some test project')\n self.assertEqual(\n loaded_unit.background_plain, 'Some test description')\n self.assertEqual(\n loaded_unit.expectations_plain, 'Some exspections')\n self.assertEqual(\n loaded_unit.actions_plain, 'Some actions')\n self.assertEqual(\n loaded_unit.comments_plain, 'Some comments')\n self.assertEqual(\n loaded_unit.runtime, 52)\n self.assertEqual(\n loaded_unit.estimated_yearly_consumption_costs_before,\n Decimal('2000.33'))\n self.assertEqual(\n loaded_unit.estimated_yearly_consumption_before,\n Decimal('2000.33'))\n self.assertEqual(\n loaded_unit.estimated_co2_emissions_before, Decimal('2000.33'))\n self.assertEqual(\n loaded_unit.expected_savings_in_yearly_total_costs,\n Decimal('2000.33'))\n self.assertEqual(\n loaded_unit.expected_savings_in_yearly_consumption_after,\n Decimal('2000.33'))\n self.assertEqual(\n loaded_unit.expected_reduction_in_yearly_co2_emissions,\n Decimal('2000.33'))\n\n def test_get_encryption_id(self):\n \"\"\"\n Test that L{BenchmarkProject} has a conventional implementation of\n L{EncryptedModel.get_encryption_id()}\n \"\"\"\n self.assertEqual(\n (Customer, self.customer.id),\n self.unit.get_encryption_id())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectCleanCostCurrencyTest(TestCase):\n \"\"\"\n Test the L{BenchmarkProject} class.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.utc,\n currency_unit='currency_dkk',)\n trackuser._set_customer(self.customer)\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n\n self.project = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 2, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 1, 12, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 2, 13, tzinfo=pytz.utc),\n include_measured_costs=True)\n\n def test_conflict(self):\n consumption_mp = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n consumption_mp.consumption = DataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n consumption_mp.save()\n cost_graph = consumption_mp.graph_set.create(role=DataRoleField.COST)\n cost_graph.dataseries_set.create(\n role=DataRoleField.COST, unit='currency_eur',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n self.project.baseline_measurement_points.add(consumption_mp)\n\n self.assertTrue(self.project.cost_currency_conflicts())\n\n def test_no_conflicts(self):\n self.assertFalse(self.project.cost_currency_conflicts())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectTest(TestCase):\n \"\"\"\n Test the L{BenchmarkProject} class.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.utc,\n currency_unit='currency_dkk')\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n trackuser._set_customer(self.customer)\n\n self.unit = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 2, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 1, 12, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 2, 13, tzinfo=pytz.utc))\n\n self.tariff1 = Index.objects.create(\n name_plain=\"test tariff\",\n unit=\"currency_dkk*kilowatt^-1*hour^-1\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SPOT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n self.tariff_entry = self.tariff1.entry_set.create(\n from_timestamp=DATETIME_MIN,\n to_timestamp=DATETIME_MAX,\n value=Decimal(10))\n\n self.measurement_point = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n cost_graph = self.measurement_point.graph_set.create(\n role=DataRoleField.COST)\n cost = CostCalculation(\n graph=cost_graph,\n role=DataRoleField.COST,\n consumption=self.measurement_point.consumption,\n index=self.tariff1,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n cost.full_clean(exclude=['unit'])\n cost.save()\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n @unittest.skip('Warning currently not provided')\n def test_baseline_and_result_tariff_domain_warning(self):\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=2000, timestamp=datetime(2013, 1, 30, tzinfo=pytz.utc))\n self.unit.baseline_measurement_points.add(self.measurement_point)\n\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(\n 2013, 1, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_measurement_points.add(self.measurement_point)\n self.unit.result_from_timestamp = datetime(\n 2013, 1, 15, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(2013, 1, 30, tzinfo=pytz.utc)\n self.unit.save()\n\n # Assign tariff which will not not be covering\n # the whole stage 1 consumption domain\n self.tariff_entry.from_timestamp = datetime(\n 2013, 1, 10, tzinfo=pytz.utc)\n self.tariff_entry.save()\n\n # Change valid from date on tariff so that\n # no stages will have valid tariffs.\n self.tariff_entry.from_timestamp = datetime(\n 2013, 1, 20, tzinfo=pytz.utc)\n self.tariff_entry.save()\n\n self.assertTrue(\n self.unit.baseline_stage.tariff_domain_warning_measurement_point_ids) # noqa\n self.assertTrue(\n self.unit.result_stage.tariff_domain_warning_measurement_point_ids) # noqa\n\n def test_no_tariff_domain_warning(self):\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=2000, timestamp=datetime(2013, 1, 30, tzinfo=pytz.utc))\n self.unit.baseline_measurement_points.add(self.measurement_point)\n\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(\n 2013, 1, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_measurement_points.add(self.measurement_point)\n self.unit.result_from_timestamp = datetime(\n 2013, 1, 15, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(2013, 1, 30, tzinfo=pytz.utc)\n self.unit.save()\n\n self.assertFalse(\n self.unit.baseline_stage.tariff_domain_warning_measurement_point_ids) # noqa\n self.assertFalse(\n self.unit.result_stage.tariff_domain_warning_measurement_point_ids) # noqa\n\n @unittest.skip('Warning currently not provided')\n def test_baseline_tariff_domain_warning(self):\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=2000, timestamp=datetime(2013, 1, 30, tzinfo=pytz.utc))\n self.unit.baseline_measurement_points.add(self.measurement_point)\n\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(\n 2013, 1, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_measurement_points.add(self.measurement_point)\n self.unit.result_from_timestamp = datetime(\n 2013, 1, 15, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(2013, 1, 30, tzinfo=pytz.utc)\n self.unit.save()\n\n # Assign tariff which will not not be covering\n # the whole stage 1 consumption domain\n self.tariff_entry.from_timestamp = datetime(\n 2013, 1, 10, tzinfo=pytz.utc)\n self.tariff_entry.save()\n\n self.assertTrue(\n self.unit.baseline_stage.tariff_domain_warning_measurement_point_ids) # noqa\n self.assertFalse(\n self.unit.result_stage.tariff_domain_warning_measurement_point_ids) # noqa\n\n def test_active_and_done(self):\n \"\"\"\n Test the L{BenchmarkProject.active_and_done()} method.\n \"\"\"\n active = BenchmarkProject.active(\n datetime(2013, 1, 1, tzinfo=pytz.utc))\n done = BenchmarkProject.done(\n datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.assertIn(self.unit, active)\n self.assertNotIn(self.unit, done)\n\n active = BenchmarkProject.active(\n datetime(2013, 1, 3, tzinfo=pytz.utc))\n done = BenchmarkProject.done(\n datetime(2013, 1, 3, tzinfo=pytz.utc))\n self.assertNotIn(self.unit, active)\n self.assertIn(self.unit, done)\n\n # Assuming today is later than January 3rd, 2013.\n active = BenchmarkProject.active()\n done = BenchmarkProject.done()\n self.assertNotIn(self.unit, active)\n self.assertIn(self.unit, done)\n\n def test_yearly_consumption_savings(self):\n \"\"\"\n Test the L{BenchmarkProject.yearly_consumption_savings()} method.\n\n Create data so that the savings are 10 kWh pr day; 3650 kWh pr year.\n \"\"\"\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 11, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1900, timestamp=datetime(2013, 1, 21, tzinfo=pytz.utc))\n self.unit.baseline_measurement_points.add(self.measurement_point)\n\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(2013, 1, 3, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_measurement_points.add(self.measurement_point)\n self.unit.result_from_timestamp = datetime(\n 2013, 1, 11, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(2013, 1, 13, tzinfo=pytz.utc)\n self.unit.save()\n\n self.assertEqual(\n self.unit.yearly_measured_consumption_savings(),\n PhysicalQuantity(10 * 365, 'kilowatt*hour'))\n\n def test_yearly_consumption_savings_with_zero_consumption(self):\n \"\"\"\n Test the L{BenchmarkProject.yearly_consumption_savings()} method with\n zero consumption, and thus zero savings.\n \"\"\"\n self.assertEqual(\n self.unit.yearly_measured_consumption_savings(),\n PhysicalQuantity(0, 'kilowatt*hour'))\n\n def test_resulting_annual_cost_savings_with_zero_cost(self):\n \"\"\"\n Test the L{BenchmarkProject.resulting_annual_cost_savings()} method\n with zero cost, and thus zero savings.\n \"\"\"\n self.assertEqual(\n self.unit.yearly_measured_cost_savings(),\n PhysicalQuantity(0, 'currency_dkk'))\n\n def test_resulting_annual_cost_savings(self):\n \"\"\"\n Test the L{BenchmarkProject.resulting_annual_cost_savings()} method.\n\n Create data so that the savings are 10 DKK pr day; 3650 DKK pr year.\n \"\"\"\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=100, timestamp=datetime(2013, 1, 11, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=190, timestamp=datetime(2013, 1, 21, tzinfo=pytz.utc))\n\n self.unit.baseline_measurement_points.add(self.measurement_point)\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(2013, 1, 3, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_measurement_points.add(self.measurement_point)\n self.unit.result_from_timestamp = datetime(\n 2013, 1, 11, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(2013, 1, 13, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.include_measured_costs = True\n\n self.assertEqual(\n tuple(self.unit.yearly_measured_cost_savings()),\n tuple(PhysicalQuantity(10 * 365, 'currency_dkk')))\n\n def test_active_stages(self):\n \"\"\"\n Test that the different stages are active at relevant times.\n \"\"\"\n self.assertIn(\n _('Result'),\n self.unit.active_stages(datetime(2013, 1, 1, 20, tzinfo=pytz.utc)))\n\n self.assertIn(\n _('Result'),\n self.unit.active_stages(datetime(2013, 1, 1, 20, tzinfo=pytz.utc)))\n\n self.assertNotIn(\n _('Baseline'),\n self.unit.active_stages(datetime(2013, 1, 2, 2, tzinfo=pytz.utc)))\n\n self.assertIn(\n _('Result'),\n self.unit.active_stages(datetime(2013, 1, 2, 2, tzinfo=pytz.utc)))\n\n self.assertEqual(\n [],\n self.unit.active_stages(datetime(2013, 1, 20, tzinfo=pytz.utc)))\n\n self.assertEqual(\n [],\n self.unit.active_stages(datetime(2012, 12, 20, tzinfo=pytz.utc)))\n\n # Assume that now is later than January 3rd, 2013.\n self.assertEqual([], self.unit.active_stages())\n\n def test_yearly_consumption_savings_display(self):\n \"\"\"\n Test that nothing bad happens when calling\n yearly_consumption_savings_display.\n \"\"\"\n self.unit.yearly_consumption_savings_display()\n\n def test_resulting_annual_cost_savings_display(self):\n \"\"\"\n Test that nothing bad happens when calling\n resulting_annual_cost_savings_display.\n \"\"\"\n self.unit.resulting_annual_cost_savings_display()\n\n def test_duration(self):\n \"\"\"\n Test the L{BenchmarkProject.duration} method.\n \"\"\"\n unit = BenchmarkProject(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 2, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 1, 12, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 2, 13, tzinfo=pytz.utc))\n\n self.assertIsInstance(unit.from_timestamp, datetime)\n self.assertIsInstance(unit.to_timestamp, datetime)\n\n self.assertEqual(unit.from_timestamp,\n datetime(2013, 1, 1, tzinfo=pytz.utc))\n\n self.assertEqual(unit.to_timestamp,\n datetime(2013, 1, 2, 13, tzinfo=pytz.utc))\n\n def test_dependencies(self):\n self.unit.baseline_measurement_points.add(self.measurement_point)\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = datetime(2013, 1, 3, tzinfo=pytz.utc)\n self.unit.save()\n\n self.assertEqual(self.measurement_point.is_deletable(), False)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectInvestmentTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(currency_unit='currency_dkk')\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_before=Decimal('456.78'),\n customer=self.customer,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n def test_empty(self):\n self.assertEqual(self.project.investment, 0)\n\n def test_nonempty_delegates_to_cost_get_total_costs(self):\n EXPECTED_COST = Decimal('678.91')\n UNUSED_COST = Decimal('123.45')\n\n self.project.cost_set.create(cost=UNUSED_COST)\n\n with patch.object(Cost, 'get_total_costs',\n return_value=EXPECTED_COST) as get_total_costs_mock:\n\n self.assertEqual(self.project.investment, EXPECTED_COST)\n get_total_costs_mock.assert_called_with()\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectBaselineAnnualConsumptionTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(currency_unit='currency_dkk')\n self.customer.save()\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_before=Decimal('456.78'),\n customer=self.customer,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n def test_baseline_period_completed(self):\n self.project.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.project.baseline_to_timestamp = datetime(\n 2013, 2, 1, tzinfo=pytz.utc)\n\n self.assertTrue(self.project.baseline_period_completed)\n\n with patch.object(Stage, 'mean_consumption_rate',\n PhysicalQuantity(1, 'watt')):\n self.assertEqual(\n self.project.baseline_annual_consumption,\n self.project.get_preferred_consumption_unit_converter().\n extract_value(PhysicalQuantity(365, 'watt*day')))\n\n def test_baseline_incomplete(self):\n with patch.object(self.project, 'baseline_period_completed', False):\n self.assertEqual(\n self.project.baseline_annual_consumption,\n self.project.estimated_yearly_consumption_before)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectBaselineAnnualCostsTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(currency_unit='currency_dkk')\n self.customer.save()\n\n def test_include_measured_costs(self):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=True,\n customer=self.customer,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 2, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n self.assertTrue(self.project.baseline_period_completed)\n\n with patch.object(Stage, 'mean_cost_rate',\n PhysicalQuantity(1, 'currency_dkk*day^-1')):\n self.assertEqual(\n self.project.baseline_annual_costs,\n 365)\n\n def test_exclude_calculated_cost(self):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_costs_before=Decimal('456.78'),\n customer=self.customer,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n with patch.object(self.project, 'baseline_period_completed', True):\n self.assertEqual(\n self.project.baseline_annual_costs,\n self.project.estimated_yearly_consumption_costs_before)\n\n def test_baseline_period_incomplete(self):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=True,\n estimated_yearly_consumption_costs_before=Decimal('456.78'),\n customer=self.customer,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n with patch.object(self.project, 'baseline_period_completed', False):\n self.assertEqual(\n self.project.baseline_annual_costs,\n self.project.estimated_yearly_consumption_costs_before)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectAnnualCostSavingsTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n with replace_customer(self.customer):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_before=Decimal('456.78'),\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n def test_project_completed(self):\n with patch.object(self.project, 'project_completed', True), \\\n patch.object(\n self.project, 'resulting_annual_cost_savings',\n return_value=PhysicalQuantity(\n 1234, 'currency_dkk')):\n\n self.assertEqual(\n self.project.annual_cost_savings,\n self.project.resulting_annual_cost_savings().\n convert('currency_dkk'))\n\n def test_project_incomplete(self):\n with patch.object(self.project, 'project_completed', False):\n self.assertEqual(\n self.project.annual_cost_savings,\n self.project.\n expected_savings_in_yearly_total_costs)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectPaybackPeriodTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.timezone('Europe/Copenhagen'))\n with replace_customer(self.customer):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n subsidy=Decimal('456.78'),\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n def test_undefined(self):\n with patch.object(self.project, 'annual_cost_savings', 0):\n self.assertIsNone(self.project.payback_period_years)\n\n def test_welldefined(self):\n with patch.object(self.project, 'annual_cost_savings', 2), \\\n patch.object(self.project, 'investment', 7):\n self.assertEquals(\n self.project.payback_period_years,\n (self.project.investment - Fraction(self.project.subsidy)) /\n self.project.annual_cost_savings)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectGetGraphDataTest(TestCase):\n \"\"\"\n Test the L{BenchmarkProject} class.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.utc,\n currency_unit='currency_dkk')\n trackuser._set_customer(self.customer)\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n self.unit = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 3, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 11, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 13, tzinfo=pytz.utc))\n\n self.measurement_point = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.consumption = TestDataSeries(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=10, timestamp=datetime(2013, 1, 1, 0, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 11, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1010, timestamp=datetime(2013, 1, 11, 0, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1900, timestamp=datetime(2013, 1, 21, tzinfo=pytz.utc))\n\n self.unit.baseline_measurement_points.add(self.measurement_point)\n self.unit.result_measurement_points.add(self.measurement_point)\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_samples_to_data_set(self):\n result = self.unit._samples_to_data_set(\n self.measurement_point,\n [\n self.measurement_point.rate.create_point_sample(\n datetime(2013, 1, 2, tzinfo=pytz.utc),\n PhysicalQuantity(42, self.measurement_point.rate.unit)),\n ],\n timedelta(minutes=4))\n self.assertEqual(\n result,\n [[unix_timestamp(datetime(2013, 1, 1, 23, 56, tzinfo=pytz.utc)),\n 0.000042]])\n\n @unittest.skip('')\n def test_adjusted_start_time(self):\n data = self.unit.get_graph_data(self.measurement_point)\n\n # stage_1 should be rendered at duration start. Currently, rate\n # conversion will skip the first consumption sample it is made across,\n # hence the additional one minute.\n self.assertEqual(\n data['data'][0]['data'][0][0],\n unix_timestamp(self.unit.from_timestamp +\n timedelta(minutes=1)))\n\n # stage 2 should be rendered at duration start. Currently, rate\n # conversion will skip the first consumption sample it is made across,\n # hence the additional one minute.\n self.assertEqual(\n data['data'][1]['data'][0][0],\n unix_timestamp(self.unit.from_timestamp +\n timedelta(minutes=1)))\n\n def test_get_ticks_one_minute(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 1, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(\n 2013, 1, 1, 0, 1, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n self.assertEqual(\n ticks_list[0],\n [\n unix_timestamp(\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)), 0])\n self.assertEqual(\n ticks_list[-1],\n [\n unix_timestamp(\n datetime(2013, 1, 1, 0, 1, tzinfo=pytz.utc)), 1])\n gettext_mock.assert_called_with('minutes')\n\n def test_get_ticks_59_minutes(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 1, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 20, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2013, 1, 1, 0, 59, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = 59 / 12\n for i in range(0, len(ticks_list)):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n datetime(\n 2013, 1, 1, 0, i * tick_increment,\n tzinfo=pytz.utc)), i * tick_increment])\n\n gettext_mock.assert_called_with('minutes')\n\n def test_get_ticks_1_hour_1_minute(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(\n 2013, 1, 1, 1, 1, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = 1\n for i in range(0, len(ticks_list)):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n datetime(\n 2013, 1, 1, i * tick_increment,\n tzinfo=pytz.utc)), i * tick_increment])\n\n gettext_mock.assert_called_with('hours')\n\n def test_get_ticks_23_hours_59_minutes(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2013, 1, 1, 23, 59, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = 23 / 12 + 1\n for i in range(0, len(ticks_list) - 1):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n datetime(\n 2013, 1, 1, i * tick_increment,\n tzinfo=pytz.utc)), i * tick_increment])\n\n gettext_mock.assert_called_with('hours')\n\n def test_get_ticks_24_hours(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2013, 1, 2, 0, 1, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n self.assertEqual(\n ticks_list[0],\n [\n unix_timestamp(\n datetime(2013, 1, 1, 0, tzinfo=pytz.utc)),\n 0])\n\n self.assertEqual(\n ticks_list[-1],\n [\n unix_timestamp(\n datetime(\n 2013, 1, 2, 0, tzinfo=pytz.utc)),\n 1])\n\n gettext_mock.assert_called_with('days')\n\n def test_get_ticks_29_days_23_hours_59_minutes(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = datetime(2013, 1, 1, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2013, 1, 30, 23, 59, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = (30 / 12) + 1\n for i in range(0, len(ticks_list)):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 1 + i * tick_increment))),\n i * tick_increment])\n\n gettext_mock.assert_called_with('days')\n\n def test_get_ticks_1_month(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2013, 1, 31, 0, 0, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n self.assertEqual(\n ticks_list[0],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 1, 0))),\n 0])\n\n self.assertEqual(\n ticks_list[-1],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 31, 0))),\n 1])\n\n gettext_mock.assert_called_with('months')\n\n def test_get_ticks_1_year_minus_1_minute(self):\n self.unit.baseline_from_timestamp = self.unit.customer.timezone.\\\n localize(datetime(2013, 1, 1))\n self.unit.baseline_to_timestamp = self.unit.customer.timezone.localize(\n datetime(2013, 1, 1, 0, 14))\n self.unit.save()\n\n self.unit.result_from_timestamp = self.unit.customer.timezone.localize(\n datetime(2013, 1, 1))\n self.unit.result_to_timestamp = self.unit.customer.timezone.localize(\n datetime(2013, 12, 31, 23, 59))\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = ((364 / 30) / 12) + 1\n\n for i in range(0, len(ticks_list)):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n self.unit.customer.timezone.normalize(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 1)) +\n timedelta(days=30 * i * tick_increment))),\n i * tick_increment])\n\n gettext_mock.assert_called_with('months')\n\n def test_get_ticks_1_year(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = datetime(\n 2014, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n self.assertEqual(\n ticks_list[0],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 1, 0))),\n 0])\n\n self.assertEqual(\n ticks_list[-1],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2014, 1, 1, 0))),\n 1])\n\n gettext_mock.assert_called_with('years')\n\n def test_get_ticks_42_years_two_minutes(self):\n self.unit.baseline_from_timestamp = datetime(\n 2013, 1, 1, tzinfo=pytz.utc)\n self.unit.baseline_to_timestamp = \\\n datetime(2013, 1, 1, 0, 14, tzinfo=pytz.utc)\n self.unit.save()\n\n self.unit.result_from_timestamp = \\\n datetime(2013, 1, 1, 0, 0, tzinfo=pytz.utc)\n self.unit.result_to_timestamp = \\\n datetime(2056, 1, 1, 0, 2, tzinfo=pytz.utc)\n self.unit.save()\n\n with patch('legacy.projects.models._') as gettext_mock:\n ticks_unit, ticks_list = self.unit._get_ticks()\n tick_increment = (42 / 12) + 1\n for i in range(0, len(ticks_list)):\n self.assertEqual(\n ticks_list[i],\n [\n unix_timestamp(\n self.unit.customer.timezone.localize(\n datetime(2013, 1, 1) +\n timedelta(days=365 * i * tick_increment))),\n i * tick_increment])\n\n gettext_mock.assert_called_with('years')\n\n def test_get_resolution(self):\n \"\"\"\n Assuming C{_get_resolution} will check its own post-conditions, this\n test will just invoke the method with border arguments.\n \"\"\"\n some_datetime = datetime(2013, 1, 1, 1, 1, 1, tzinfo=pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_HOURS -\n timedelta(seconds=1)), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_HOURS), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_DAYS -\n timedelta(seconds=1)), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_DAYS), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_MONTHS -\n timedelta(seconds=1)), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_MONTHS), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_YEARS -\n timedelta(seconds=1)), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_YEARS), pytz.utc)\n condense.floor(some_datetime, self.unit._get_resolution(\n duration_time=self.unit.CONDENSE_TO_YEARS\n * 42), pytz.utc)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestStage(TestCase):\n \"\"\"\n Test the L{Stage} model.\n \"\"\"\n def setUp(self):\n \"\"\"\n Instantiate a L{Stage} model for a C{Project}.\n \"\"\"\n Provider.objects.create()\n self.customer = Customer(\n timezone=pytz.utc,\n currency_unit='currency_eur',\n )\n self.customer.save()\n trackuser._set_customer(self.customer)\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n self.measurement_point = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.consumption = TestDataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=2000, timestamp=datetime(2013, 1, 9, tzinfo=pytz.utc))\n\n self.project = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 9, tzinfo=pytz.utc))\n\n self.project.baseline_measurement_points.add(self.measurement_point)\n self.project.result_measurement_points.add(self.measurement_point)\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_clean_duration_invalid(self):\n \"\"\"\n Test the L{Stage.clean()} method.\n \"\"\"\n self.project.baseline_from_timestamp = datetime(\n 2013, 5, 23, 12, tzinfo=pytz.utc)\n self.project.baseline_to_timestamp = datetime(\n 2013, 5, 23, 11, tzinfo=pytz.utc)\n\n with self.assertRaises(ValidationError):\n self.project.clean()\n\n def test_clean_valid(self):\n \"\"\"\n Extend this test case as clean() validates more.\n \"\"\"\n self.project.baseline_from_timestamp = datetime(\n 2013, 5, 23, 12, tzinfo=pytz.utc)\n self.project.baseline_to_timestamp = datetime(\n 2013, 5, 23, 13, tzinfo=pytz.utc)\n self.project.clean()\n\n def test_mean_consumption_rate(self):\n \"\"\"\n Test mean_consumption_rate with various datateimes\n \"\"\"\n # Testing where from time and to time has passed\n self.assertEqual(\n PhysicalQuantity(1000, 'kilowatt*hour') /\n PhysicalQuantity(4 * 24, 'hour'),\n self.project.baseline_stage.mean_consumption_rate)\n\n # Testing where now time is between from time and to time.\n time_now = datetime.now(pytz.utc).replace(\n minute=0, second=0, microsecond=0)\n from_timestamp = time_now - timedelta(days=4)\n to_timestamp = time_now + timedelta(days=1)\n\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=from_timestamp)\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=to_timestamp)\n\n self.project.baseline_from_timestamp = from_timestamp\n self.project.baseline_to_timestamp = to_timestamp\n self.project.save()\n\n # Reloading project because of cache\n self.project = BenchmarkProject.objects.get(id=self.project.id)\n\n self.assertEqual(PhysicalQuantity(1000, 'kilowatt*hour') /\n PhysicalQuantity(5 * 24, 'hour'),\n self.project.baseline_stage.mean_consumption_rate)\n\n # Testing where whole stage is in the future\n self.project.baseline_from_timestamp = time_now + timedelta(days=1)\n self.project.baseline_to_timestamp = time_now + timedelta(days=5)\n self.project.save()\n\n # Reloading project because of cache\n self.project = BenchmarkProject.objects.get(id=self.project.id)\n\n self.assertEqual(\n PhysicalQuantity(0, 'kilowatt'),\n self.project.baseline_stage.mean_consumption_rate)\n\n def test_mean_cost_rate(self):\n \"\"\"\n Test mean_cost_rate with various datateimes\n \"\"\"\n tariff1 = Index.objects.create(\n name_plain=\"test tariff\",\n unit=\"currency_eur*kilowatt^-1*hour^-1\",\n role=DataRoleField.ELECTRICITY_TARIFF,\n data_format=Index.SPOT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n timezone='Europe/Copenhagen')\n tariff1.entry_set.create(\n from_timestamp=DATETIME_MIN,\n to_timestamp=DATETIME_MAX,\n value=Decimal(1))\n\n cost_graph = self.measurement_point.graph_set.create(\n role=DataRoleField.COST)\n cost = CostCalculation(\n graph=cost_graph,\n role=DataRoleField.COST,\n consumption=self.measurement_point.consumption,\n index=tariff1,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n cost.full_clean(exclude=['unit'])\n cost.save()\n\n # Testing where from time and to time has passed\n self.assertEqual(PhysicalQuantity(1000, 'currency_eur') /\n PhysicalQuantity(4 * 24 * 60 * 60, 'second'),\n self.project.baseline_stage.mean_cost_rate)\n\n # Testing where now time is between from time and to time.\n time_now = datetime.now(pytz.utc).replace(\n minute=0, second=0, microsecond=0)\n from_timestamp = time_now - timedelta(days=4)\n to_timestamp = time_now + timedelta(days=1)\n\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=from_timestamp)\n self.measurement_point.consumption.stored_data.create(\n value=100, timestamp=to_timestamp)\n\n self.project.baseline_from_timestamp = from_timestamp\n self.project.baseline_to_timestamp = to_timestamp\n self.project.save()\n\n # Reloading project because of cache\n self.project = BenchmarkProject.objects.get(id=self.project.id)\n\n self.assertEqual(PhysicalQuantity(100, 'currency_eur') /\n PhysicalQuantity(5 * 24 * 60 * 60, 'second'),\n self.project.baseline_stage.mean_cost_rate)\n\n # Testing where whole stage is in the future\n self.project.baseline_from_timestamp = time_now + timedelta(days=1)\n self.project.baseline_to_timestamp = time_now + timedelta(days=5)\n self.project.save()\n\n # Reloading project because of cache\n self.project = BenchmarkProject.objects.get(id=self.project.id)\n\n self.assertEqual(PhysicalQuantity(0, 'second^-1*currency_eur'),\n self.project.baseline_stage.mean_cost_rate)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestAdditinalSaving(TestCase):\n \"\"\"\n Test the L{AdditionalSaving} class.\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(\n timezone=pytz.utc,\n currency_unit='currency_eur')\n self.customer.save()\n trackuser._set_customer(self.customer)\n self.project = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n self.project.save()\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_save(self):\n self.unit = AdditionalSaving.objects.create(\n project=self.project,\n description_plain=\"Some description\",\n before_energy=8,\n after_energy=7,\n before_cost=6,\n after_cost=5,\n before_co2=2,\n after_co2=1)\n\n loaded_unit = AdditionalSaving.objects.get(pk=self.unit.id)\n\n self.assertEqual(loaded_unit.project, self.project)\n self.assertEqual(loaded_unit.description_plain, \"Some description\")\n self.assertEqual(loaded_unit.before_energy, 8)\n self.assertEqual(loaded_unit.after_energy, 7)\n self.assertEqual(loaded_unit.before_cost, 6)\n self.assertEqual(loaded_unit.after_cost, 5)\n self.assertEqual(loaded_unit.before_co2, 2)\n self.assertEqual(loaded_unit.after_co2, 1)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass TestCalculations(TestCase):\n \"\"\"\n Test the different calculation methods on the L{BenchmarkProject} class\n \"\"\"\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer(\n timezone=pytz.utc,\n currency_unit='currency_eur')\n self.customer.save()\n trackuser._set_customer(self.customer)\n\n self.measurement_point = ConsumptionMeasurementPoint(\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.consumption = TestDataSeries.objects.create(\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n self.measurement_point.consumption.stored_data.create(\n value=0, timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=1000, timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc))\n self.measurement_point.consumption.stored_data.create(\n value=2000, timestamp=datetime(2013, 1, 9, tzinfo=pytz.utc))\n\n self.project = BenchmarkProject.objects.create(\n name_plain='Some test project',\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 9, tzinfo=pytz.utc))\n\n self.project.baseline_measurement_points.add(self.measurement_point)\n self.project.result_measurement_points.add(self.measurement_point)\n\n def tearDown(self):\n trackuser._set_customer(None)\n trackuser._set_user(None)\n\n def test_save(self):\n self.unit = AdditionalSaving.objects.create(\n project=self.project,\n description_plain=\"Some description\",\n before_energy=8,\n after_energy=7,\n before_cost=6,\n after_cost=5,\n before_co2=2,\n after_co2=1)\n\n loaded_unit = AdditionalSaving.objects.get(pk=self.unit.id)\n\n self.assertEqual(loaded_unit.project, self.project)\n self.assertEqual(loaded_unit.description_plain, \"Some description\")\n self.assertEqual(loaded_unit.before_energy, 8)\n self.assertEqual(loaded_unit.after_energy, 7)\n self.assertEqual(loaded_unit.before_cost, 6)\n self.assertEqual(loaded_unit.after_cost, 5)\n self.assertEqual(loaded_unit.before_co2, 2)\n self.assertEqual(loaded_unit.after_co2, 1)\n\n def test_co2_calculations(self):\n AdditionalSaving.objects.create(\n project=self.project,\n description_plain=\"Some description\",\n before_energy=8,\n after_energy=7,\n before_cost=6,\n after_cost=5,\n before_co2=5,\n after_co2=1)\n\n AdditionalSaving.objects.create(\n project=self.project,\n description_plain=\"Some description\",\n before_energy=8,\n after_energy=7,\n before_cost=6,\n after_cost=5,\n before_co2=5,\n after_co2=1)\n\n self.assertEqual(self.project.yearly_additional_co2(),\n {'after': PhysicalQuantity(2, u'tonne'),\n 'before': PhysicalQuantity(10, u'tonne')})\n\n self.assertEqual(self.project.yearly_additional_co2_savings(),\n PhysicalQuantity(8, u'tonne'))\n\n self.assertEqual(self.project.yearly_co2_savings(),\n PhysicalQuantity(8, u'tonne'))\n\n self.assertEqual(self.project.yearly_co2_savings_pct(), 80)\n\n self.assertEqual(self.project.project_co2_savings(),\n PhysicalQuantity(8, u'tonne') * (float(1) / 12))\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True,\n CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,\n CELERY_ALWAYS_EAGER=True,\n BROKER_BACKEND='memory')\nclass AnnualSavingsPotentialReportTaskTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n\n def test_empty_run(self):\n with replace_customer(self.customer), replace_user(self.user):\n task_status = AnnualSavingsPotentialReportTask.delay(\n {\n 'projects': dict(),\n })\n\n self.assertTrue(task_status.successful())\n\n def test_baselined_project(self):\n with replace_customer(self.customer), replace_user(self.user):\n project = BenchmarkProject.objects.create(\n name_plain='base-lined project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_costs_before=Decimal('456.78'),\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 2, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2014, 1, 1, tzinfo=pytz.utc))\n\n project.cost_set.create(\n cost=Decimal(246))\n\n with patch.object(Stage, 'mean_consumption_rate',\n PhysicalQuantity(1, 'watt')), \\\n patch.object(BenchmarkProject,\n 'resulting_annual_cost_savings',\n return_value=PhysicalQuantity(123,\n 'currency_dkk'),\n autospec=True):\n\n task_status = AnnualSavingsPotentialReportTask.delay(\n {\n 'projects': {project.id: dict()},\n })\n\n self.assertTrue(task_status.successful())\n\n self.assertEqual(\n task_status.result['projects'][project.id][\n 'baseline_annual_consumption'],\n project.get_preferred_consumption_unit_converter().\n extract_value(PhysicalQuantity(365, 'watt*day')))\n\n self.assertEqual(\n task_status.result['projects'][project.id][\n 'baseline_annual_costs'],\n project.estimated_yearly_consumption_costs_before)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass FinalizeAnnualSavingsPotentialReportViewTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n timezone=pytz.utc,\n currency_unit='currency_eur')\n with replace_customer(self.customer):\n self.project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_before=Decimal('456.78'),\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n\n def test_generate_report(self):\n with replace_customer(self.customer):\n view = FinalizeAnnualSavingsPotentialReportView()\n view.generate_report(\n {\n 'projects': {\n self.project.id: {\n 'baseline_annual_consumption': 592932,\n 'baseline_annual_costs': 563285,\n 'expected_annual_cost_savings': 337971,\n 'subsidy': 102743,\n 'investment': 850000,\n 'payback_period_years': 2.52,\n },\n },\n 'total_expected_annual_cost_savings': 1.23,\n 'total_subsidy': 6.66,\n 'total_investment': 9.99,\n 'total_payback_period': 2.34,\n },\n datetime.now(pytz.utc))\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass BenchmarkProjectManagerTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer.objects.create(\n currency_unit='currency_dkk')\n self.user = User.objects.create_user(\n '[email protected]',\n 'password222w2222',\n user_type=User.CUSTOMER_USER,\n customer=self.customer)\n\n with replace_customer(self.customer), replace_user(self.user):\n self.measurement_point = ConsumptionMeasurementPoint(\n customer=self.customer,\n name_plain='Test measurement point',\n role=ConsumptionMeasurementPoint.CONSUMPTION_MEASUREMENT_POINT,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.consumption = TestDataSeries.objects.create(\n customer=self.customer,\n role=DataRoleField.CONSUMPTION,\n unit='kilowatt*hour',\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity)\n\n self.measurement_point.save()\n\n self.project = BenchmarkProject.objects.create(\n name_plain='Some test project',\n customer=self.customer,\n background_plain='Some test description',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n baseline_from_timestamp=datetime(2013, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2013, 1, 5, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2013, 1, 9, tzinfo=pytz.utc))\n\n self.project.baseline_measurement_points.add(self.measurement_point)\n self.project.result_measurement_points.add(self.measurement_point)\n\n def test_no_customer_and_no_user(self):\n self.assertEqual(\n self.project, BenchmarkProject.objects.get())\n\n def test_constraint_customer(self):\n with replace_customer(self.customer), replace_user(self.user):\n self.assertEqual(\n self.project, BenchmarkProject.objects.get())\n\n def test_constraint_wrong_customer(self):\n customer = Customer()\n customer.save()\n self.project.customer = customer\n self.project.save()\n with replace_customer(self.customer), replace_user(self.user):\n self.assertFalse(BenchmarkProject.objects.all().exists())\n\n def test_user_contraint(self):\n CollectionConstraint.objects.create(\n collection=self.measurement_point,\n userprofile=self.user.userprofile)\n with replace_customer(self.customer), replace_user(self.user):\n self.assertEqual(\n self.project, BenchmarkProject.objects.get())\n\n def test_wrong_user_constraint(self):\n self.user.userprofile.collections.clear()\n self.user.userprofile.save()\n\n group = Collection.objects.create(\n customer=self.customer,\n role=Collection.GROUP,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n CollectionConstraint.objects.create(\n collection=group, userprofile=self.user.userprofile)\n with replace_customer(self.customer), replace_user(self.user):\n self.assertFalse(BenchmarkProject.objects.all().exists())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass AnnualSavingsPotentialReportGenerationFormTest(TestCase):\n def test_projects_queryset(self):\n Provider.objects.create()\n customer = Customer(currency_unit='currency_dkk')\n customer.save()\n project = BenchmarkProject.objects.create(\n name_plain='test project',\n utility_type=utilitytypes.METER_CHOICES.electricity,\n runtime=1,\n include_measured_costs=False,\n estimated_yearly_consumption_before=Decimal('456.78'),\n customer=customer,\n baseline_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n baseline_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_from_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc),\n result_to_timestamp=datetime(2000, 1, 1, tzinfo=pytz.utc))\n form = AnnualSavingsPotentialReportGenerationForm()\n self.assertTrue(\n form.fields['projects'].queryset.filter(id=project.id).exists())\n" }, { "alpha_fraction": 0.736330509185791, "alphanum_fraction": 0.7375455498695374, "avg_line_length": 23.939393997192383, "blob_id": "417a87f7f3eb70e9243fd2f7db79a0c4d469396a", "content_id": "cbf25bc603f749b575fd261831b7248f663905d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 823, "license_type": "no_license", "max_line_length": 79, "num_lines": 33, "path": "/legacy/website/templatetags/version.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines Django template tags for showing versions.\n\"\"\"\n\nfrom django import template\nfrom django.utils.translation import ugettext_lazy as _\n\nimport gridplatform\nfrom gridplatform.reports.templatetags.reports import texescape\n\n\nregister = template.Library()\n\n\[email protected]_tag\ndef gridplatform_version():\n \"\"\"\n Display version information.\n\n Version will be marked as unknown when working on code not released through\n C{make dist} or C{make release}.\n\n To change the version number, update C{Makefile} accordingly.\n \"\"\"\n return _(u'Version: {}').format(gridplatform.__version__)\n\n\[email protected]_tag\ndef gridplatform_version_tex():\n return texescape(gridplatform_version())\n" }, { "alpha_fraction": 0.6640199422836304, "alphanum_fraction": 0.6654211282730103, "avg_line_length": 37.92727279663086, "blob_id": "e11ae9cf19f55d399ffc83119986ad67b3be7937", "content_id": "6c65186da36ac0014924f6327d19d0c562044d07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6423, "license_type": "no_license", "max_line_length": 82, "num_lines": 165, "path": "/gridplatform/datasequences/models/energyconversion.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.customer_datasources.models import DataSource\nfrom gridplatform.utils.iter_ext import pairwise_extended\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils.units import ENERGY_PER_VOLUME_BASE_UNITS\nfrom gridplatform.utils.samples import RangedSample\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils import condense\n\nfrom .piecewiseconstant import PiecewiseConstantBase\nfrom .base import PeriodBase\nfrom .base import is_clock_hour\nfrom .base import is_five_minute_multiplum\nfrom .piecewiseconstant import PiecewiseConstantPeriodManagerBase\n\n\ndef _break_into_hourly_samples(ranged_samples, from_timestamp, to_timestamp):\n \"\"\"\n Yield hourly subsamples (RangedSamples) of each RangedSample in\n ranged_samples\n \"\"\"\n assert is_five_minute_multiplum(from_timestamp), \\\n '%r is not a 5 minute multiplum' % from_timestamp\n assert is_five_minute_multiplum(to_timestamp), \\\n '%r is not a 5 minute multiplum' % to_timestamp\n\n timestamp = from_timestamp\n for sample in ranged_samples:\n while timestamp < sample.from_timestamp:\n timestamp += condense.HOURS\n while timestamp < sample.to_timestamp:\n subsample = sample._replace(\n from_timestamp=timestamp,\n to_timestamp=timestamp + condense.HOURS)\n assert sample.from_timestamp <= subsample.from_timestamp\n assert sample.to_timestamp >= subsample.to_timestamp\n yield subsample\n\n timestamp = subsample.to_timestamp\n\n\nclass EnergyPerVolumeDataSequence(PiecewiseConstantBase):\n \"\"\"\n Data sequence for energy conversion. Inherits from\n :class:`PiecewiseConstantBase`.\n\n :cvar unit: The unit is always energy per volume.\n \"\"\"\n class Meta:\n verbose_name = _('energy conversion data sequence')\n verbose_name_plural = _('energy conversion data sequences')\n app_label = 'datasequences'\n\n unit = 'milliwatt*hour/meter^3'\n\n\nclass VolumeToEnergyConversionPeriodManager(\n PiecewiseConstantPeriodManagerBase):\n \"\"\"\n A :class:`.PiecewiseConstantPeriodManagerBase` specialization whose samples\n are always in one-hour resolution.\n \"\"\"\n use_for_related_fields = True\n\n def value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Specialization of\n :meth:`.PiecewiseConstantPeriodManagerBase.value_sequence`. Yields\n :class:`.RangedSample` in one-hour resolution.\n \"\"\"\n for sample in super(\n VolumeToEnergyConversionPeriodManager, self).value_sequence(\n from_timestamp, to_timestamp):\n assert RelativeTimeDelta(\n sample.to_timestamp, sample.from_timestamp) == \\\n RelativeTimeDelta(hours=1)\n yield sample\n\n\nclass EnergyPerVolumePeriod(PeriodBase):\n \"\"\"\n A :class:`.PeriodBase` specialization for\n :class:`.EnergyPerVolumeDataSequence`. Defines data in terms of a\n :class:`.DataSource`.\n\n :ivar datasequence: The owning :class:`.EnergyPerVolumeDataSequence`.\n :ivar datasource: The :class:`.DataSource` defining the data sequence\n within this period.\n :cvar objects: The default manager of :class:`.EnergyPerVolumePeriod` is\n :class:`.VolumeToEnergyConversionPeriodManager`.\n\n :see: :ref:`sequences-of-conversion-ranged-samples`\n \"\"\"\n datasequence = models.ForeignKey(\n EnergyPerVolumeDataSequence,\n verbose_name=_('data sequence'),\n related_name='period_set')\n datasource = models.ForeignKey(\n DataSource,\n verbose_name=_('data source'),\n limit_choices_to={'unit__in': ENERGY_PER_VOLUME_BASE_UNITS},\n on_delete=models.PROTECT)\n\n objects = VolumeToEnergyConversionPeriodManager()\n\n class Meta:\n verbose_name = _('volume to energy conversion period')\n verbose_name_plural = _('volume to energy conversion periods')\n app_label = 'datasequences'\n\n def _raw_samples(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: a sequence of conversion ranged samples in the given timespan.\n The conversion samples may have mixed duration, so for efficient\n conversion use :meth:`.EnergyPerVolumePeriod._value_sequence` instead.\n\n :param from_timestamp: the start of the given timespan.\n :param to_timestamp: the end of the given timespan.\n \"\"\"\n start = self.datasource.rawdata_set.filter(\n timestamp__lte=from_timestamp\n ).order_by('-timestamp')[0:1].values_list('timestamp', 'value')\n in_period = self.datasource.rawdata_set.filter(\n timestamp__gt=from_timestamp,\n timestamp__lt=to_timestamp\n ).order_by('timestamp').values_list('timestamp', 'value')\n if start:\n raw = [start[0]] + list(in_period)\n else:\n raw = list(in_period)\n\n for current_raw, next_raw in pairwise_extended(raw):\n sample_from_timestamp, value = current_raw\n if next_raw is None:\n sample_to_timestamp = to_timestamp\n else:\n sample_to_timestamp = next_raw[0]\n yield RangedSample(\n sample_from_timestamp,\n sample_to_timestamp,\n PhysicalQuantity(value, self.datasource.unit))\n\n def _value_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n :return: A sequence of conversion :class:`.RangedSample` in hourly\n resolution in the given timespan.\n\n :param from_timestamp: the start of the given timespan.\n :param to_timestamp: the end of the given timespan.\n \"\"\"\n assert is_clock_hour(from_timestamp), \\\n '%r does not match clock hour' % from_timestamp\n assert is_clock_hour(to_timestamp), \\\n '%r does not match clock hour' % to_timestamp\n data = self._raw_samples(from_timestamp, to_timestamp)\n # For energy conversion the convention is that each RawData defines the\n # conversion quotient until the next raw data value.\n return _break_into_hourly_samples(\n data, from_timestamp, to_timestamp)\n" }, { "alpha_fraction": 0.6783665418624878, "alphanum_fraction": 0.678704023361206, "avg_line_length": 34.698795318603516, "blob_id": "a5b7b260f1cf45a3b07e787e2461146d585c7f9c", "content_id": "73cfef272fd52302bc4ebd24b7a68558aa1142ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2963, "license_type": "no_license", "max_line_length": 77, "num_lines": 83, "path": "/gridplatform/utils/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.rest import serializers\nfrom gridplatform.utils import units\nfrom gridplatform.utils.preferredunits import PhysicalUnitConverter\nfrom gridplatform.utils.preferredunits import ProductionUnitConverter\n\n\nclass SampleBase(serializers.Serializer):\n \"\"\"\n Base :class:`~gridplatform.rest.serializers.Serializer` for\n :class:`~gridplatform.utils.samples.RangedSample` and\n :class:`~gridplatform.utils.samples.PointSample`.\n\n :ivar unit: The unit that the\n :class:`~gridplatform.utils.unitconversion.PhysicalQuantity`\n of serialized sample should be converted to.\n :ivar display_unit: A human readable version of ``self.unit``.\n :ivar value: The converted\n :class:`~gridplatform.utils.unitconversion.PhysicalQuantity`\n of serialized sample.\n \"\"\"\n unit = serializers.SerializerMethodField('get_unit')\n display_unit = serializers.SerializerMethodField('get_display_unit')\n value = serializers.SerializerMethodField('get_value')\n\n def get_unit(self, obj):\n \"\"\"\n :return: The unit that the\n :class:`~gridplatform.utils.unitconversion.PhysicalQuantity`\n of serialized sample should be converted to.\n \"\"\"\n return self.context['unit']\n\n def get_display_unit(self, obj):\n \"\"\"\n A human readable version of ``self.unit``. Only production units\n and plain physical units are supported.\n \"\"\"\n unit = self.get_unit(obj)\n if unit in units.PRODUCTION_UNITS:\n return ProductionUnitConverter(unit).get_display_unit()\n else:\n return PhysicalUnitConverter(unit).get_display_unit()\n\n def get_value(self, obj):\n \"\"\"\n :return: The converted\n :class:`~gridplatform.utils.unitconversion.PhysicalQuantity`\n of given sample.\n :rtype: int\n :param obj: The sample to serialize.\n \"\"\"\n if not obj:\n return None\n unit = self.get_unit(obj)\n # We don't care about decimals. If the unit isn't fine grained enough\n # then the problem is with the unit, not the lack of decimals.\n return int(obj.physical_quantity.convert(unit))\n\n\nclass PointSampleSerializer(SampleBase):\n \"\"\"\n Serializer for :class:`~gridplatform.utils.samples.PointSample`.\n\n :see:\n :class:`gridplatform.datasources.viewsets.RawDataViewSetBase`\n for example usage.\n \"\"\"\n timestamp = serializers.DateTimeField(source='timestamp')\n\n\nclass RangedSampleSerializer(SampleBase):\n \"\"\"\n Serializer for :class:`~gridplatform.utils.samples.RangedSample`.\n\n :see: :class:`gridplatform.datasequences.views.HourlyDataView` for\n example usage.\n \"\"\"\n from_timestamp = serializers.DateTimeField(source='from_timestamp')\n to_timestamp = serializers.DateTimeField(source='to_timestamp')\n" }, { "alpha_fraction": 0.5670962929725647, "alphanum_fraction": 0.5735405683517456, "avg_line_length": 55.1489372253418, "blob_id": "91821af0eec15be39d2e25b34f95e92cb363243e", "content_id": "2ac75dc6ccf4b7fcfd5ee4c67de9993435ca5e03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2638, "license_type": "no_license", "max_line_length": 174, "num_lines": 47, "path": "/gridplatform/condensing/migrations/0001_initial.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n pass\n\n def backwards(self, orm):\n pass\n\n models = {\n u'condensing.fiveminuteaccumulateddata': {\n 'Meta': {'ordering': \"[u'timestamp']\", 'unique_together': \"((u'datasource', u'timestamp'),)\", 'object_name': 'FiveMinuteAccumulatedData'},\n 'datasource': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['datasources.DataSource']\", 'db_index': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'timestamp': ('django.db.models.fields.DateTimeField', [], {}),\n 'value': ('django.db.models.fields.BigIntegerField', [], {})\n },\n u'condensing.houraccumulateddata': {\n 'Meta': {'ordering': \"[u'timestamp']\", 'unique_together': \"((u'datasource', u'timestamp'),)\", 'object_name': 'HourAccumulatedData'},\n 'datasource': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['datasources.DataSource']\", 'db_index': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'timestamp': ('django.db.models.fields.DateTimeField', [], {}),\n 'value': ('django.db.models.fields.BigIntegerField', [], {})\n },\n u'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n u'datasources.datasource': {\n 'Meta': {'object_name': 'DataSource'},\n 'hardware_id': ('django.db.models.fields.CharField', [], {'max_length': '120', 'blank': 'True'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'subclass': ('django.db.models.fields.related.ForeignKey', [], {'related_name': \"u'+'\", 'on_delete': 'models.PROTECT', 'to': u\"orm['contenttypes.ContentType']\"}),\n 'unit': ('gridplatform.utils.fields.BuckinghamField', [], {'max_length': '100'})\n }\n }\n\n complete_apps = ['condensing']" }, { "alpha_fraction": 0.6962457299232483, "alphanum_fraction": 0.6996586918830872, "avg_line_length": 23.41666603088379, "blob_id": "abe9d7284b10c31e98964ce0d51e4aa3fe62840d", "content_id": "ef53677834a49b21feee4577c3ceace76ff3683a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 293, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/gridplatform/users/urls.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf.urls import patterns, url\n\nfrom gridplatform.users import views\n\nurlpatterns = patterns(\n '',\n url(r'^profile/$', views.UserProfileView.as_view(), name='profile'),\n)\n" }, { "alpha_fraction": 0.607770562171936, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 29.02777862548828, "blob_id": "4c3cf616839ed1399844868ea24bc75e531128f9", "content_id": "2c9053dec39ed031c77ceb29c895310a15e93455", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 78, "num_lines": 36, "path": "/legacy/website/templatetags/tabs.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import template\nfrom django.core.urlresolvers import reverse\n\nregister = template.Library()\n\n\[email protected]_tag(takes_context=True)\ndef tab_li(context, text, urlname, *args, **kwargs):\n \"\"\"\n Construct list-item code for a tab --- marking any tab linking to the\n current URL as active.\n\n Usage::\n\n {% trans 'Meters' as meters %}\n <ul class=\"tabs\">\n {% tab_li meters 'manage_devices-meter-list' %}\n ...\n </ul>\n\n @note: Text/title translation is not done by C{tab_li} --- a lot of effort\n would have to be spent on integrating it with the code for extracting\n strings to be translated from Django templates...\n \"\"\"\n url = reverse(urlname, args=args, kwargs=kwargs)\n request = context['request']\n if url == request.path:\n return '<li class=\"selected\"><a href=\"%s\">%s</a></li>' % (\n url, text)\n else:\n return '<li><a href=\"%s\">%s</a></li>' % (\n url, text)\n" }, { "alpha_fraction": 0.35321101546287537, "alphanum_fraction": 0.49770641326904297, "avg_line_length": 14.034482955932617, "blob_id": "f1f9f0a63d91f71d3ef6d9f5fd8228dd606ddbf3", "content_id": "d2d754d274352ad80ca2b6548e0c7cc42aa6701e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 39, "num_lines": 29, "path": "/gridplatform/reports/colors.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\n\nPIE_CHART_COLORS = (\n '3366A4',\n 'A83734',\n '83A440',\n '684C8B',\n '3093AE',\n 'EB9659',\n '9CBEFD',\n 'FD9A99',\n 'D4F89F',\n 'C2ADE2',\n '96E5FD',\n 'FFB579',\n 'A9C8FC',\n 'FCA7A6',\n 'DEFCAD',\n 'CFBBED',\n '8BD8ED',\n 'FFA868',\n 'B2C4E4',\n 'E5B2B1',\n 'D0E3B4',\n 'C5BAD6',\n)\n" }, { "alpha_fraction": 0.6608770489692688, "alphanum_fraction": 0.6610490083694458, "avg_line_length": 35.118011474609375, "blob_id": "da561843a64f6025eea70a355402cd1920d76dc9", "content_id": "fdf3ed9755b12fedd457d3b1abf3025024ecd22a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5815, "license_type": "no_license", "max_line_length": 97, "num_lines": 161, "path": "/gridplatform/datasources/managers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.db.models.query import QuerySet\nfrom django.db import models\nfrom django.db.models.query import DateQuerySet\nfrom django.db.models.query import DateTimeQuerySet\nfrom django.db.models.query import ValuesListQuerySet\nfrom django.db.models.query import ValuesQuerySet\n\nfrom gridplatform.trackuser.managers import FilteringQuerySetMixinBase\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.trackuser import get_provider_id\nfrom gridplatform.utils.models import StoredSubclassManager\n\n\nclass DataSourceQuerySetMixinBase(FilteringQuerySetMixinBase):\n \"\"\"\n Help ensuring that only DataSources that should be visible are visible.\n \"\"\"\n\n def _apply_filtering(self):\n \"\"\"\n Implementation of :meth:`FilteringQuerySetMixinBase._apply_filtering`.\n\n If no user is logged in, no filtering is applied (for shell command).\n For unauthenticated users the queryset is emptied.\n\n If user is limited to only one\n :class:`~gridplatform.customers.models.Customer` (at this time) and\n that customer is inactive, the queryset is emptied, if the customer is\n active, further filtering is delegated to\n :meth:`.DataSourceQuerySetMixinBase._apply_customer_filtering`.\n\n If user is a provider user and not limited to a particular customer at\n this time, further filtering is delegated to\n :meth:`.DataSourceQuerySetMixinBase._apply_provider_filtering`.\n\n Finally, if user is neither customer user nor provider user, he must be\n admin, and no filtering is applied.\n \"\"\"\n user = get_user()\n if user is None:\n return\n if not user.is_authenticated():\n self.query.set_empty()\n return\n # user customer or override customer or selected customer\n customer = get_customer()\n if customer is not None:\n if not customer.is_active:\n self.query.set_empty()\n return\n self._apply_customer_filtering(customer.id)\n return\n provider_id = get_provider_id()\n if provider_id:\n self._apply_provider_filtering(provider_id)\n return\n assert user.is_staff, \\\n 'non-staff user {} without customer or provider; ' + \\\n 'should not exist'.format(user.id)\n return\n\n def _apply_customer_filtering(self, customer_id):\n \"\"\"\n Abstract method for filtering on a given customer.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n def _apply_provider_filtering(self, provider_id):\n \"\"\"\n Abstract method for filtering on a given provider.\n \"\"\"\n raise NotImplementedError(self.__class__)\n\n\nclass DataSourceQuerySetMixin(DataSourceQuerySetMixinBase):\n \"\"\"\n Ensures that only DataSources that should be visible are visible. In\n particular DataSources that are CustomerDataSources may only be seen by\n users that are authorized to see that particular customer.\n \"\"\"\n\n def _apply_customer_filtering(self, customer_id):\n \"\"\"\n Rows that represent :class:`.CustomerDataSource` must belong to given :class:`.Customer`.\n\n Rows that represent :class:`.ProviderDataSource` must belong to the\n :class:`.Provider` of the given :class:`.Customer`.\n\n :param customer_id: The id of the given :class:`.Customer`.\n \"\"\"\n self.query.add_q(\n models.Q(customerdatasource__customer__id=customer_id) |\n models.Q(customerdatasource__isnull=True))\n self.query.add_q(\n models.Q(providerdatasource__provider__customer__id=customer_id) |\n models.Q(providerdatasource__isnull=True))\n\n def _apply_provider_filtering(self, provider_id):\n \"\"\"\n Rows that represent :class:`.CustomerDataSource` must belong to a\n :class:`.Customer` of the given :class:`.Provider`.\n\n Rows that represent :class:`.ProviderDataSource` must belong to the\n given :class:`.Provider`.\n\n :param provider_id: The id of the given :class:`.Provider`.\n \"\"\"\n self.query.add_q(\n models.Q(\n customerdatasource__customer__provider_id=provider_id) |\n models.Q(customerdatasource__isnull=True))\n self.query.add_q(\n models.Q(\n providerdatasource__provider_id=provider_id) |\n models.Q(providerdatasource__isnull=True))\n\n\nclass DataSourceManagerBase(models.Manager):\n \"\"\"\n A manager that mixes :class:`.DataSourceQuerySetMixin` into all its\n queryset classes.\n \"\"\"\n class _QuerySet(DataSourceQuerySetMixin, QuerySet):\n pass\n\n class _ValuesQuerySet(DataSourceQuerySetMixin, ValuesQuerySet):\n pass\n\n class _ValuesListQuerySet(DataSourceQuerySetMixin, ValuesListQuerySet):\n pass\n\n class _DateQuerySet(DataSourceQuerySetMixin, DateQuerySet):\n pass\n\n class _DateTimeQuerySet(DataSourceQuerySetMixin, DateTimeQuerySet):\n pass\n\n def get_queryset(self):\n qs = super(DataSourceManagerBase, self).get_queryset()\n kwargs = {\n 'klass': self._QuerySet,\n '_ValuesQuerySet': self._ValuesQuerySet,\n '_ValuesListQuerySet': self._ValuesListQuerySet,\n '_DateQuerySet': self._DateQuerySet,\n '_DateTimeQuerySet': self._DateTimeQuerySet,\n }\n return qs._clone(**kwargs)\n\n\nclass DataSourceManager(\n StoredSubclassManager, DataSourceManagerBase):\n \"\"\"\n A manager that is both a :class:`.StoredSubclassManager` and a\n :class:`DataSourceManagerBase`.\n \"\"\"\n use_for_related_fields = False\n" }, { "alpha_fraction": 0.6431884765625, "alphanum_fraction": 0.6448925733566284, "avg_line_length": 37.2717399597168, "blob_id": "4cc7f714f372e3090a324d613f3795234a8a3e2e", "content_id": "272b2c7b8356f5ae796aece2c8ffc5a13fda6285", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10563, "license_type": "no_license", "max_line_length": 83, "num_lines": 276, "path": "/gridplatform/datasources/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom fractions import Fraction\n\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.core.exceptions import ValidationError\n\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.utils import units\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.fields import BigAutoField\nfrom gridplatform.utils.units import BASE_UNIT_CHOICES\nfrom gridplatform.utils.models import StoreSubclass\nfrom gridplatform.utils.decorators import virtual\n\nfrom .managers import DataSourceManager\n\n\ndef interpolate(timestamp, point_a, point_b):\n timestamp_a, value_a = point_a\n timestamp_b, value_b = point_b\n assert timestamp_a <= timestamp < timestamp_b\n assert timestamp.microsecond == 0\n assert timestamp_a.microsecond == 0\n assert timestamp_b.microsecond == 0\n return value_a + (value_b - value_a) * \\\n Fraction(int((timestamp - timestamp_a).total_seconds()),\n int((timestamp_b - timestamp_a).total_seconds()))\n\n\ndef impulse_interpolate(timestamp, point_a, point_b):\n timestamp_a, value_a = point_a\n timestamp_b, value_b = point_b\n assert timestamp_a <= timestamp < timestamp_b\n assert timestamp.microsecond == 0\n assert timestamp_a.microsecond == 0\n assert timestamp_b.microsecond == 0\n return value_a\n\n\nclass DataSourceBase(models.Model):\n unit = BuckinghamField(_('unit'), choices=BASE_UNIT_CHOICES)\n hardware_id = models.CharField(\n _('hardware id'), max_length=120, blank=True)\n\n class Meta:\n abstract = True\n\n def hourly_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Yields :class:`~gridplatform.utils.samples.RangedSample` with a duration of\n one hour in the given range. Each sample yielded holds the development\n of the accumulation across the timespan of the sample.\n\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n \"\"\"\n from gridplatform.condensing.models import get_hourly_accumulated\n return get_hourly_accumulated(self, from_timestamp, to_timestamp)\n\n def five_minute_accumulated(self, from_timestamp, to_timestamp):\n \"\"\"\n Yields :class:`~gridplatform.utils.samples.RangedSample` with a duration of\n five minutes in the given range. Each sample yielded holds the\n development of the accumulation across the timespan of the sample.\n\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n \"\"\"\n from gridplatform.condensing.models import get_five_minute_accumulated\n return get_five_minute_accumulated(self, from_timestamp, to_timestamp)\n\n def _get_interpolate_fn(self):\n \"\"\"\n :return: :func:`.impulse_interpolate` if ``self.unit`` is 'impulse' and\n :func:`.interpolate` otherwise.\n \"\"\"\n if self.unit == 'impulse':\n return impulse_interpolate\n else:\n return interpolate\n\n def raw_sequence(self, from_timestamp, to_timestamp):\n \"\"\"\n Yields :class:`~gridplatform.utils.samples.PointSample` for each\n :class:`.RawData` in the given range.\n\n :param from_timestamp: The start of the given range.\n :param to_timestamp: The end of the given range.\n \"\"\"\n for timestamp, value in self.rawdata_set.filter(\n timestamp__gte=from_timestamp,\n timestamp__lte=to_timestamp).order_by('timestamp').values_list(\n 'timestamp', 'value'):\n yield Sample(\n timestamp, timestamp,\n PhysicalQuantity(value, self.unit),\n False, False)\n\n def next_valid_date(self, date, timezone):\n \"\"\"\n :return: The next date that holds :class:`.RawData` for this data source or\n ``None``.\n\n :param date: The date after which `next valid date` is found.\n :param timezone: :class:`.RawData` are stored using timestamps, so to\n translate a date to a timestamp range we need a timezone; this is\n the timezone.\n \"\"\"\n end_of_day = timezone.localize(\n datetime.datetime.combine(\n date + datetime.timedelta(days=1), datetime.time()))\n next_rawdata = self.rawdata_set.filter(\n timestamp__gt=end_of_day).order_by('timestamp').first()\n if next_rawdata is not None:\n return timezone.normalize(\n next_rawdata.timestamp.astimezone(timezone)).date()\n else:\n return None\n\n def previous_valid_date(self, date, timezone):\n \"\"\"\n :return: The previous date that holds :class:`.RawData` for this data\n source or ``None``.\n\n :param date: The date before which `previous valid date` is found.\n :param timezone: :class:`.RawData` are stored using timestamps, so to\n translate a date to a timestamp range we need a timezone; this is\n the timezone.\n \"\"\"\n beginning_of_day = timezone.localize(\n datetime.datetime.combine(date, datetime.time()))\n previous_rawdata = self.rawdata_set.filter(\n timestamp__lt=beginning_of_day).order_by('timestamp').last()\n if previous_rawdata is not None:\n return timezone.normalize(\n previous_rawdata.timestamp.astimezone(timezone)).date()\n else:\n None\n\n\nclass RawDataBase(models.Model):\n id = BigAutoField(primary_key=True)\n value = models.BigIntegerField(_('value'))\n timestamp = models.DateTimeField(_('timestamp'))\n\n class Meta:\n abstract = True\n\n @staticmethod\n def interpolate(timestamp, raw_data_before, raw_data_after):\n \"\"\"\n :return: Returns an interpolated value at the given ``timestamp``\n interpolated from ``raw_data_before`` and ``raw_data_after``.\n\n :precondition: The open interval (``raw_data_before.timestamp``;\n ``raw_data_after.timestamp``) contains ``timestamp``.\n \"\"\"\n assert raw_data_before.timestamp < timestamp\n assert raw_data_after.timestamp > timestamp\n return interpolate(\n timestamp.replace(microsecond=0),\n (raw_data_before.timestamp.replace(microsecond=0),\n raw_data_before.value),\n (raw_data_after.timestamp.replace(microsecond=0),\n raw_data_after.value))\n\n @property\n def unit(self):\n if self.id:\n return self.datasource.unit\n return None\n\n\nclass DataSource(StoreSubclass, DataSourceBase):\n \"\"\"\n :class:`.DataSource` is the base class for\n :class:`~gridplatform.customer_datasources.models.CustomerDataSource`,\n :class:`~gridplatform.provider_datasources.models.ProviderDataSource` and\n :class:`~gridplatform.global_datasources.models.GlobalDataSource`.\n\n :ivar rawdata_set: The data of data sources are stored as\n :class:`.RawData`.\n\n However, accessing the raw data directly via the ``rawdata_set``\n manager is rarely needed. Use :meth:`.hourly_accumulated` and\n :meth:`.five_minute_accumulated` for accumulated data and\n :meth:`~gridplatform.datasources.models.DataSource.raw_sequence`\n for raw data. All these methods will yield samples which are more\n lightwight than\n :class:`.RawData`, and case of accumulated data fewer samples will\n be yielded than the amount of potential :class:`.RawData` in the same\n range.\n\n :see: :class:`gridplatform.utils.samples.RangedSample` and\n :class:`gridplatform.utils.samples.PointSample`.\n\n :ivar unit: A Buckingham unit that holds for all the :class:`RawData`\n associated with this data source.\n\n :ivar hardware_id: A char field used by external components (say REST\n enabled meters) to identify this data source.\n\n :cvar objects: A :class:`.DataSourceManager` that ensures that noone gets\n their hands on data sources that they shouldn't see. Note that this\n manager is not inherited and will not work on any subclass model.\n \"\"\"\n objects = DataSourceManager()\n\n class Meta:\n verbose_name = _('data source')\n verbose_name_plural = _('data sources')\n\n @virtual\n def __unicode__(self):\n raise NotImplementedError(self.__class__)\n\n\ndef is_clock_hour(timestamp):\n return timestamp.minute == timestamp.second == timestamp.microsecond == 0\n\n\ndef is_five_minute_multiplum(timestamp):\n return timestamp.minute % 5 == timestamp.second == \\\n timestamp.microsecond == 0\n\n\nclass RawData(RawDataBase):\n \"\"\"\n Used for storing raw data of data sources.\n\n :ivar value: The value of this raw data. Can be converted to a\n :class:`gridplatform.utils.unitconversion.PhysicalQuantity` using\n :attr:`.DataSource.unit`.\n\n :ivar timestamp: A timestamp describing when this raw data was sampled.\n\n :ivar datasource: The owning :class:`.DataSource`.\n \"\"\"\n datasource = models.ForeignKey(\n DataSource,\n verbose_name=_('data source'),\n on_delete=models.PROTECT,\n db_index=False)\n\n class Meta:\n verbose_name = _('raw data')\n verbose_name_plural = _('raw data')\n # NOTE: unique_together creates an index; index_together would create\n # an extra, redundant index\n unique_together = ('datasource', 'timestamp')\n ordering = ['timestamp']\n\n def clean(self):\n super(RawData, self).clean()\n if hasattr(self, 'datasource') and self.timestamp:\n if any(PhysicalQuantity.compatible_units(\n self.datasource.unit, unit)\n for unit in units.TARIFF_BASE_UNITS):\n if not is_clock_hour(self.timestamp):\n raise ValidationError(\n {'timestamp': [ugettext('Must be clock hour.')]})\n\n if any(PhysicalQuantity.compatible_units(\n self.datasource.unit, unit)\n for unit in units.CO2_CONVERSION_BASE_UNITS):\n if not is_five_minute_multiplum(self.timestamp):\n raise ValidationError(\n {'timestamp': [\n ugettext('Must be five-minute multiplum.')]})\n" }, { "alpha_fraction": 0.66131192445755, "alphanum_fraction": 0.66131192445755, "avg_line_length": 28.8799991607666, "blob_id": "987488e3161db69c9ac18bcc3adc03b54a19fd1b", "content_id": "796c75ad7e111628c7ab5cbbbcdf2eac80233604", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 747, "license_type": "no_license", "max_line_length": 119, "num_lines": 25, "path": "/energymanager/price_relay_site/serializers.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "import json\n\nfrom gridplatform.rest import serializers\n\nfrom energymanager.price_relay_site.models import PriceRelayProject\n\n\nclass PriceRelayProjectSerializer(serializers.DefaultSerializer):\n name = serializers.CharField(source='name_plain')\n\n class Meta:\n model = PriceRelayProject\n fields = ('name', )\n read_only = True\n\n def to_native(self, obj):\n native = super(PriceRelayProjectSerializer, self).to_native(obj)\n if obj:\n settings = []\n for setting in obj.calculate_relay_settings():\n settings.append({'timestamp': setting['sample'].from_timestamp.isoformat(), 'relay': setting['relay']})\n\n native['relay_settings'] = settings\n\n return native\n" }, { "alpha_fraction": 0.5832328796386719, "alphanum_fraction": 0.5858295559883118, "avg_line_length": 31.675758361816406, "blob_id": "a2abee8e51d8dd1a32e09e5d7e980a720b5810b8", "content_id": "06b2b488f8961dc7c0522060499c8849457b839e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10783, "license_type": "no_license", "max_line_length": 78, "num_lines": 330, "path": "/legacy/manage_users/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django import forms\nfrom django.template.loader import render_to_string\nfrom django.template import RequestContext\nfrom django.utils.translation import ugettext as _\nfrom django.shortcuts import get_object_or_404\nfrom django.forms import ModelForm\nfrom django.utils.safestring import mark_safe\nfrom django.utils.html import escape\nfrom django.http import HttpResponseForbidden\nfrom django.http import Http404\nfrom django.conf import settings\nfrom django.core.mail import send_mail\n\nfrom gridplatform.utils.views import render_to\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.users.models import User\nfrom gridplatform.users.managers import hash_username\nfrom legacy.measurementpoints.models import Collection\nfrom legacy.measurementpoints.models import CollectionConstraint\nfrom gridplatform.users.decorators import customer_admin_or_error\nfrom legacy.legacy_utils.models import UserProfile\n\n\n@customer_admin_or_error\n@json_response\ndef list_json(request):\n options = json_list_options(request)\n customer = request.customer\n data = list(UserProfile.objects.filter(\n user__customer=customer, user__is_active=True).select_related('user'))\n if options['search']:\n data = filter(\n lambda userprofile:\n userprofile.user.satisfies_search(options['search']),\n data)\n order_map = {\n 'name': lambda userprofile: userprofile.user.name_plain.lower(),\n 'email': lambda userprofile: userprofile.user.e_mail_plain,\n }\n if options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_users/user_block.html', {'userprofile': userprofile},\n RequestContext(request))\n for userprofile in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass UserForm(ModelForm):\n send_password = forms.BooleanField(required=False)\n\n def __init__(self, *args, **kwargs):\n super(UserForm, self).__init__(*args, **kwargs)\n self.fields['user_type'].choices = [\n (User.CUSTOMER_USER, _('User')),\n (User.CUSTOMER_SUPERUSER, _('Superuser'))]\n\n def clean_e_mail(self):\n e_mail = self.cleaned_data['e_mail']\n if User.objects.filter(username=hash_username(e_mail)):\n raise forms.ValidationError(\n _(\"A user with that e-mail already exists\"))\n return e_mail\n\n class Meta:\n model = User\n fields = ('name', 'e_mail', 'phone', 'mobile', 'user_type')\n localized_fields = '__all__'\n\n\nclass UserEditForm(UserForm):\n def clean_e_mail(self):\n e_mail = self.cleaned_data['e_mail']\n current_email = User.objects.get(id=self.instance.id).e_mail_plain\n\n if User.objects.filter(username=hash_username(e_mail)) \\\n .exclude(username=hash_username(current_email)).exists():\n raise forms.ValidationError(\n _(\"A user with that e-mail already exists\"))\n return e_mail\n\n\nclass UserProfileForm(ModelForm):\n\n collections = forms.MultipleChoiceField(required=False)\n\n class Meta:\n model = UserProfile\n fields = ()\n localized_fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n if 'instance' in kwargs and kwargs['instance'] is not None:\n initial = kwargs.setdefault('initial', {})\n initial['collections'] = \\\n kwargs['instance'].collections.values_list(\n 'id', flat=True)\n super(UserProfileForm, self).__init__(*args, **kwargs)\n\n self.fields[\"collections\"].choices = [\n (group.id,\n mark_safe('&nbsp;' * 2 * group.level +\n escape(unicode(group))))\n for group in Collection.objects.filter(\n customer=get_customer(), role=Collection.GROUP)]\n\n def save(self, commit=True):\n super(UserProfileForm, self).save(False)\n\n def save_m2m():\n self.instance.collections.clear()\n for collection in self.cleaned_data['collections']:\n CollectionConstraint.objects.create(\n collection_id=collection,\n userprofile=self.instance)\n self.save_m2m = save_m2m\n\n if commit:\n self.instance.save()\n self.save_m2m()\n\n return self.instance\n\n\n@customer_admin_or_error\n@render_to('manage_users/user_form.html')\ndef user_form(request, pk=None):\n user = get_user()\n reason = None\n instance = None\n userprofile = None\n\n if pk:\n instance = get_object_or_404(User, pk=pk)\n userprofile = instance.get_profile()\n\n if instance.customer != get_customer():\n return HttpResponseForbidden()\n\n if instance.is_active is False:\n raise Http404\n\n if instance.id == user.id:\n reason = {'reason': _('It is not allowed to delete yourself')}\n user_form = UserEditForm(instance=instance, auto_id=False)\n else:\n user_form = UserForm(instance=instance, auto_id=False)\n\n userprofile_form = UserProfileForm(instance=userprofile, auto_id=False)\n\n return {\n 'user_form': user_form,\n 'userprofile_form': userprofile_form,\n 'delete': (reason or {'reason': ''}),\n }\n\n\n# Used by user_update\ndef create_user(request, customer, user_form, userprofile_form):\n user = None\n password = User.objects.make_random_password()\n\n user = User.objects.create_user(\n user_form.cleaned_data['e_mail'],\n password,\n user_type=user_form.cleaned_data['user_type'],\n customer=customer)\n user_profile = userprofile_form.save(commit=False)\n user_profile.user = user\n user_profile.id = user.get_profile().id\n user_profile.save()\n userprofile_form.save_m2m()\n\n user.e_mail_plain = user_form.cleaned_data['e_mail']\n user.phone_plain = user_form.cleaned_data['phone']\n user.mobile_plain = user_form.cleaned_data['mobile']\n user.name_plain = user_form.cleaned_data['name']\n user.save()\n\n send_password = user_form.cleaned_data['send_password']\n\n if send_password:\n subject = _('%(site_name)s user information') % {\n 'site_name': settings.SITE_NAME\n }\n message = _(\"\"\"Username: %(username)s\nPassword: %(password)s\"\"\") % {\n 'username': user_form.cleaned_data['e_mail'],\n 'password': password\n }\n\n send_mail(\n subject,\n message,\n settings.SITE_MAIL_ADDRESS,\n [user_form.cleaned_data['e_mail']],\n fail_silently=False)\n\n return user, password\n\n\n@customer_admin_or_error\n@json_response\ndef user_delete(request):\n instance = get_object_or_404(User, pk=request.GET['pk'])\n if instance.customer != get_customer():\n return HttpResponseForbidden()\n\n instance.is_active = False\n instance.save()\n return {\n 'success': True,\n 'statusText': _('The user has been deleted'),\n }\n\n\n@customer_admin_or_error\n@json_response\ndef user_update(request, pk=None):\n customer = request.customer\n if pk:\n instance = get_object_or_404(User, pk=pk)\n userprofile = instance.get_profile()\n if instance.customer != customer:\n return HttpResponseForbidden()\n if instance.id == get_user().id:\n reason = {'reason': _('It is not allowed to delete yourself')}\n else:\n reason = None\n user_form = UserEditForm(\n request.POST,\n instance=instance,\n auto_id=False)\n else:\n userprofile = None\n instance = None\n reason = None\n user_form = UserForm(\n request.POST,\n instance=instance,\n auto_id=False)\n\n userprofile_form = UserProfileForm(\n request.POST,\n instance=userprofile,\n auto_id=False)\n\n groups = list(customer.collection_set.all())\n\n userprofile_form.fields[\"collections\"].choices = [\n (group.id,\n mark_safe('&nbsp;' * 2 * group.level +\n escape(unicode(group))))\n for group in groups]\n\n if all([user_form.is_valid(), userprofile_form.is_valid()]):\n if pk:\n user = user_form.save(commit=False)\n user.username = hash_username(user.e_mail_plain)\n user.save()\n if request.POST.get('send_password', False):\n password = User.objects.make_random_password()\n user.reset_password(request, password)\n user.save()\n subject = _('%(site_name)s user information') % {\n 'site_name': settings.SITE_NAME\n }\n message = _(\n \"Username: %(username)s\\n\"\n \"Password: %(password)s\") % {\n 'username': user_form.cleaned_data['e_mail'],\n 'password': password}\n\n send_mail(\n subject,\n message,\n settings.SITE_MAIL_ADDRESS,\n [user_form.cleaned_data['e_mail']],\n fail_silently=False)\n\n userprofile_form.save()\n statusText = _('The user has been updated')\n returnDict = {'userprofile': user.get_profile()}\n else:\n user_info = create_user(\n request, customer, user_form, userprofile_form)\n returnDict = {'userprofile': user_info[0].get_profile(),\n 'password': user_info[1]}\n statusText = _('The user has been created')\n\n return {\n 'success': True,\n 'statusText': statusText,\n 'html': render_to_string(\n 'manage_users/user_block.html',\n returnDict,\n RequestContext(request)\n ),\n }\n\n else:\n return {\n 'success': False,\n 'html': render_to_string(\n 'manage_users/user_form.html',\n {\n 'user_form': user_form,\n 'userprofile_form': userprofile_form,\n 'object': instance,\n 'user': instance,\n 'delete': reason or {'reason': ''},\n },\n RequestContext(request)\n ),\n }\n" }, { "alpha_fraction": 0.6715421080589294, "alphanum_fraction": 0.6791732907295227, "avg_line_length": 27.08035659790039, "blob_id": "f87a132bdc99cf60cc3698c60e40dfdadc5155b3", "content_id": "1e903dbaf96c788f7a801bab14f3b7a5e68ad671", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3145, "license_type": "no_license", "max_line_length": 101, "num_lines": 112, "path": "/gridplatform/settings/local.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\nDevelopment settings and globals.\n\"\"\"\n\nfrom __future__ import absolute_import\n\nimport dj_database_url\n\nfrom .base import * # noqa\n\n\ndef local_secret_setting(setting, default):\n # If you need secret settings then create a file 'local.json' in your home\n # dir containing the needed settings.\n try:\n return get_secret_setting(setting)\n except ImproperlyConfigured:\n return default\n\n\n# ######### DEBUG CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#debug\nDEBUG = True\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-debug\nTEMPLATE_DEBUG = DEBUG\n\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#template-string-if-invalid # noqa\nTEMPLATE_STRING_IF_INVALID = '\\XYZXYZXYZ'\n# ######### END DEBUG CONFIGURATION\n\n\n# ######### EMAIL CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#email-backend\nEMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'\n# ######### END EMAIL CONFIGURATION\n\n\n# ######### DATABASE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#databases\nDATABASES = {\n 'default': dj_database_url.parse('postgres:///portal'),\n}\n# ######### END DATABASE CONFIGURATION\n\n\n# ######### CACHE CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#caches\n'''CACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.PyLibMCCache',\n 'LOCATION': [\n 'localhost:11211',\n ]\n }\n}'''\n# ######### END CACHE CONFIGURATION\n\n\n# ######### SECRET CONFIGURATION\n# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key\n# Note: This key should only be used for development and testing.\nSECRET_KEY = r\"SECRET SECRET SECRET\"\n# ######### END SECRET CONFIGURATION\n\n\n# ######### DATA IMPORT LOGIN CONFIGURATION\nENERGINET_CO2_USER = local_secret_setting('ENERGINET_CO2_USER', None)\nENERGINET_CO2_PASS = local_secret_setting('ENERGINET_CO2_PASS', None)\nNORDPOOL_USER = local_secret_setting('NORDPOOL_USER', None)\nNORDPOOL_PASS = local_secret_setting('NORDPOOL_PASS', None)\n# ######### END DATA IMPORT LOGIN CONFIGURATION\n\n\n# ######### QUNIT CONFIGURATION\nINSTALLED_APPS += (\n 'django_qunit',\n)\nQUNIT_TEST_PATH = 'qunit/'\n\nTEMPLATE_LOADERS += (\n 'django_qunit.snippet_loader.Loader',\n)\n\n# ######### END QUNIT CONFIGURATION\n\n# ######### TOOLBAR CONFIGURATION\n# See: http://django-debug-toolbar.readthedocs.org/en/latest/installation.html#explicit-setup # noqa\n# INSTALLED_APPS += (\n#'debug_toolbar',\n#'debug_panel',\n# )\n# MIDDLEWARE_CLASSES += (\n# 'debug_toolbar.middleware.DebugToolbarMiddleware',\n# 'debug_panel.middleware.DebugPanelMiddleware',\n#)\n#DEBUG_TOOLBAR_PATCH_SETTINGS = False\n# http://django-debug-toolbar.readthedocs.org/en/latest/installation.html\n#INTERNAL_IPS = ('127.0.0.1', '10.0.2.2', )\n# DEBUG_TOOLBAR_CONFIG = {\n# 'HIDE_IN_STACKTRACES': (\n# 'SocketServer', 'threading', 'wsgiref', 'debug_toolbar'),\n#}\n# ######### END TOOLBAR CONFIGURATION\n\n\n# ######### CELERY CONFIGURATION\nBROKER_URL = \"amqp://guest:guest@localhost:5672//\"\n# ######### END CELERY CONFIGURATION\n\n\nNETS_KEY_DIR = \"/home/code/keys\"\n" }, { "alpha_fraction": 0.6184640526771545, "alphanum_fraction": 0.6184640526771545, "avg_line_length": 41.94736862182617, "blob_id": "72f7462f41f3c6e4db81ac9c0f778e7361eda4b8", "content_id": "5f21fb01bedaf1b4f2e4d1c32da9645251df9357", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2448, "license_type": "no_license", "max_line_length": 84, "num_lines": 57, "path": "/gridplatform/utils/static/qunit/utils/utils.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "test('Test utils.hashHelpers.updateLocation', function () {\n var form = $('<form>');\n form.append('<input type=\"textfield\" name=\"from_date\" value=\"test_from_date\">');\n form.append('<input type=\"textfield\" name=\"to_date\" value=\"test_to_date\">');\n form.append('<input type=\"textfield\" name=\"from_hour\" value=\"test_from_hour\">');\n form.append('<input type=\"textfield\" name=\"to_hour\" value=\"test_to_hour\">');\n utils.hashHelpers.updateLocation('test', form);\n\n unit = ui.getHashValueFromKey('test');\n\n equal('test_from_date', unit['from_date']);\n equal('test_to_date', unit['to_date']);\n equal('test_from_hour', unit['from_hour']);\n equal('test_to_hour', unit['to_hour']);\n});\n\ntest('Test utils.hashHelpers.setFormValues', function () {\n var form = $('<form>')\n formValues = {\n from_date: 'test_from_date',\n from_hour: 'test_from_hour',\n to_date: 'test_to_date',\n to_hour: 'test_to_hour'\n };\n form.append('<input type=\"textfield\" name=\"from_date\">');\n form.append('<input type=\"textfield\" name=\"to_date\">');\n form.append('<input type=\"textfield\" name=\"from_hour\">');\n form.append('<input type=\"textfield\" name=\"to_hour\">');\n\n utils.hashHelpers.setFormValues(formValues, form);\n\n equal('test_from_date', form.find('[name=from_date]').val());\n equal('test_to_date', form.find('[name=to_date]').val());\n equal('test_from_hour', form.find('[name=from_hour]').val());\n equal('test_to_hour', form.find('[name=to_hour]').val());\n});\n\ntest('Test utils.hashHelpers.loadFromUrlHash', function() {\n var form = $('<form>'),\n callbackRan = false;\n form.append('<input type=\"textfield\" name=\"from_date\" value=\"test_from_date\">');\n form.append('<input type=\"textfield\" name=\"to_date\" value=\"test_to_date\">');\n form.append('<input type=\"textfield\" name=\"from_hour\" value=\"test_from_hour\">');\n form.append('<input type=\"textfield\" name=\"to_hour\" value=\"test_to_hour\">');\n utils.hashHelpers.updateLocation('test', form);\n\n utils.hashHelpers.loadFromUrlHash('test', form, function() {\n callbackRan = true;\n });\n\n ok(callbackRan, 'Callback called');\n equal('test_from_date', form.find('[name=from_date]').val());\n equal('test_to_date', form.find('[name=to_date]').val());\n equal('test_from_hour', form.find('[name=from_hour]').val());\n equal('test_to_hour', form.find('[name=to_hour]').val());\n\n});\n" }, { "alpha_fraction": 0.57929927110672, "alphanum_fraction": 0.5956137776374817, "avg_line_length": 31.513044357299805, "blob_id": "1da4fa67d86111c07eee0dafccdad379f3e0c0bb", "content_id": "13765304cf286f982ace7d59f0dc35801fa1ce6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3742, "license_type": "no_license", "max_line_length": 79, "num_lines": 115, "path": "/gridplatform/reports/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport os\nfrom shutil import rmtree\nfrom tempfile import mkdtemp\nfrom decimal import Decimal\n\nfrom django.template import Context\nfrom django.template import Template\nfrom django.template.defaultfilters import floatformat as django_floatformat\nfrom django.test import TestCase\n\nfrom .templatetags.reports import pgfcolor\nfrom .templatetags.reports import texescape\nfrom .templatetags.reports import floatformat\nfrom .pdf import _generate_gnuplot\nfrom .csv import generate_csv\n\n\nclass TranslationTest(TestCase):\n def test_trans(self):\n t = Template('{% load reports %}{% trans \"Some$\" %}')\n val = t.render(Context({}))\n self.assertEqual(val, texescape('Some$'))\n\n def test_trans_as(self):\n t = Template(\n '{% load reports %}{% trans \"Some$\" as testvar %}{{ testvar }}')\n val = t.render(Context({}))\n self.assertEqual(val, texescape('Some$'))\n\n def test_blocktrans(self):\n t = Template(\n '{% load reports %}{% blocktrans with foo=\"bar$\" %}'\n 'Blah% {{ foo }}{% endblocktrans %}')\n val = t.render(Context({}))\n self.assertEqual(val, texescape('Blah% bar$'))\n\n\nclass PgfColorTest(TestCase):\n\n def test_pgfcolor(self):\n \"\"\"\n Test that some HTML style color can be converted to the desired pgfplot\n compliant RGB format.\n \"\"\"\n self.assertEqual(\n '{rgb:red,138;green,82;blue,232}', pgfcolor('#8A52E8'))\n\n def test_pgfcolor_failure(self):\n \"\"\"\n Template filters must output their argument or the empty string in case\n of errors. We test that the argument is returned, since that makes\n debugging that much easier, in case the argument is not valid.\n \"\"\"\n self.assertEqual('this is not a HTML style color',\n pgfcolor('this is not a HTML style color'))\n\n\nclass GnuPlotTest(TestCase):\n def test_generate_gnuplot(self):\n tmp_dir = mkdtemp(prefix='django-unit-test')\n try:\n _generate_gnuplot(\n \"\"\"\n set boxwidth 1.0\n set style fill solid\n set output \"test.tex\"\n set terminal epslatex color\n plot \"-\" using 1:3:xtic(2) with boxes\n 0 label 100\n 1 label2 450\n 2 \"bar label\" 75\n e\n set output\n \"\"\",\n tmp_dir)\n\n self.assertTrue(os.path.exists(os.path.join(tmp_dir, 'test.tex')))\n self.assertTrue(os.path.exists(os.path.join(tmp_dir, 'test.eps')))\n finally:\n rmtree(tmp_dir)\n\n\nclass CSVTest(TestCase):\n def test_generate_cvs(self):\n data = [[\"test\", \"test\", \"°C\"], [\"something\", \"something\", \"°C\"]]\n unit = generate_csv(data)\n self.assertIn(\"°C\".encode('utf-8'), unit)\n\n\nclass FloatFormatTest(TestCase):\n \"\"\"\n Apparently the Django floatformat is implemented in terms of Decimal\n methods that take significant digits into account.\n \"\"\"\n\n def test_insignificant_digits_workaround(self):\n \"\"\"\n Test that the work-around fixes the issue.\n \"\"\"\n self.assertEqual(\n '740.000',\n floatformat(str(Decimal(666000) / Decimal('0.9')), 0))\n\n def test_insignificant_digits_bug(self):\n \"\"\"\n Test that the django floatformat still has the bug (once this test\n fails, the L{templatetags.reports.floatformat} should be deleted again.\n \"\"\"\n self.assertNotEqual(\n '740.000',\n django_floatformat(str(Decimal(666000) / Decimal('0.9')), 0))\n" }, { "alpha_fraction": 0.4598448872566223, "alphanum_fraction": 0.4946209788322449, "avg_line_length": 35.345455169677734, "blob_id": "ca1eb27e906c803248de0ab6d8fc207a958f837b", "content_id": "e9d6fc1fc1efeb867489a9bcacf4e4ec383164fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3997, "license_type": "no_license", "max_line_length": 88, "num_lines": 110, "path": "/emonhub/configuration.md", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#########################################################\n####################### emonhub.conf #########################\n#######################################################################\n###\n### SPECIMEN emonHub configuration file\n### Note that when installed from apt, a new config file is written\n### by the debian/postinst script, so changing this file will do\n### nothing in and of itself.\n###\n### Each Interfacer and each Reporter has\n### - a [[name]]: a unique string\n### - a type: the name of the class it instantiates\n### - a set of init_settings (depends on the type)\n### - a set of runtimesettings (depends on the type)\n### Both init_settings and runtimesettings sections must be defined,\n### even if empty. Init settings are used at initialization,\n### and runtime settings are refreshed on a regular basis.\n### Many settings below are \"commented out\" as they are not mandatory and\n### have been included as a template or to provide alternative options\n### removing the leading # will enable the setting and override the default\n### Default settings are shown as comments on the same line as the setting\n### eg #(default:xyz) \"xyz\" is set if the setting is \"commented out\".\n###\n### All lines beginning with '###' are comments and can be safely removed.\n###\n#######################################################################\n####################### emonHub settings #######################\n#######################################################################\n\n[hub]\n\n### loglevel must be one of DEBUG, INFO, WARNING, ERROR, and CRITICAL\n### see here : http://docs.python.org/2/library/logging.html\nloglevel = DEBUG #(default:WARNING)\n\n#######################################################################\n####################### Interfacers #######################\n#######################################################################\n\n[interfacers]\n\n### This interfacer manages the RFM2Pi module\n[[RFM2Pi]]\n Type = EmonHubJeeInterfacer\n [[[init_settings]]]\n com_port = /dev/ttyAMA0\n com_baud = 38400\n [[[runtimesettings]]]\n pubchannels = ToCloud,\n subchannels = ToRFM12,\n\n # datacode = B #(default:h)\n # scale = 100 #(default:1)\n group = 210 #(default:210)\n frequency = 433 #(default:433)\n baseid = 5 #(emonPi default:5)\n quiet = false #(default:true)\n calibration = 230V #(UK/EU: 230V, US: 110V)\n # interval = 300 #(default:0)\n # nodeoffset = 32 #(default:0)\n\n### This interfacer manages the RFM2Pi module\n[[MQTT]]\n\n Type = EmonHubMqttInterfacer\n [[[init_settings]]]\n mqtt_host = 127.0.0.1\n mqtt_port = 1883\n mqtt_user = emonpi\n mqtt_passwd = emonpimqtt2016\n\n [[[runtimesettings]]]\n pubchannels = ToRFM12,\n subchannels = ToEmonCMS,\n basetopic = emonhub/\n\n\n[[scnordic]]\n Type = EmonHubSCNordicHTTPInterfacer\n [[[init_settings]]]\n [[[runtimesettings]]]\n pubchannels = ToRFM12,\n subchannels = ToCloud,\n url = https://scsmartgrid.dk/api/v3\n apikey = fd9b1def9a1cb1f5e387ab153de0332bfb0f3b48d8359ca5384b07c7c8a763eee9d9de33fde04291b8bceac354d8273ab67c3e5a\n\n#######################################################################\n####################### Nodes #######################\n#######################################################################\n\n[nodes]\n[[5]]\n nodename = emonpi\n [[[rx]]]\n names = power1,power2,power1pluspower2********,vrms,t1,t2,t3,t4,t5,t6,pulsecount\n datacodes = h, h, h, h, h, h, h, h, h, h, L\n scales = 1,1,1,0.01,0.1,0.1,0.1,0.1,0.1,0.1,1\n units = W,W,W,V,C,C,C,C,C,C,p\n senddata = 0,0,0,0,0,0,0,0,0,0,0\n\n[[10]]\n nodename = EMONTX10\n firmware =V120\n hardware = SC-EmonTx\n [[[rx]]]\n names = power1, power2, power3, power4, Vrms, pulse, Wh1, Wh2, Wh3, Wh4\n datacodes = h, h, h, h, h, L, l, l, l, l\n scales = 1, 1, 1, 1, 0.01, 1, 1, 1, 1, 1\n units = W, W, W, W, V, p, Wh, Wh, Wh, Wh\n senddata = 0,0,0,0,0,0,1,1,1,1" }, { "alpha_fraction": 0.6127167344093323, "alphanum_fraction": 0.6184971332550049, "avg_line_length": 21.322580337524414, "blob_id": "1a7f8b5aec08bc3d3b412b42e26cd90561ab4b64", "content_id": "b3843b108549747d49e3f80c0ec43855bd3c5fb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "no_license", "max_line_length": 62, "num_lines": 31, "path": "/gridplatform/utils/management/commands/check_db_connection.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nDefines a ``check_db_connection`` command that checks if it is\npossible to execute a noop command via the current database\nconnection.\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport sys\n\nfrom django.core.management.base import BaseCommand\nfrom django.db import connection\n\n\nclass Command(BaseCommand):\n args = ''\n help = ''\n\n def handle(self, *args, **options):\n try:\n cursor = connection.cursor()\n cursor.execute(\"select 1\")\n success = 0\n print 'connected'\n except:\n success = 1\n print 'Not connected'\n\n sys.exit(success)\n" }, { "alpha_fraction": 0.661912739276886, "alphanum_fraction": 0.6635906100273132, "avg_line_length": 26.720930099487305, "blob_id": "8ded9f5d4079dc6452dfbe8ed1d046979ed87e40", "content_id": "27678bc2606711a969a5b4ade26b76bd9bd26607", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1192, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/gridplatform/utils/validators.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\nfrom datetime import datetime\n\nimport pytz\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom .iter_ext import pairwise\n\n\ndef nonzero_validator(value):\n \"\"\"\n :raise ValidationError: If ``value`` is zero.\n \"\"\"\n if value == 0:\n raise ValidationError(_(u'Must be non-zero.'))\n\n\ndef in_the_past_validator(value):\n \"\"\"\n :raise ValidationError: If ``value`` is in the future.\n \"\"\"\n if value > datetime.now(pytz.utc):\n raise ValidationError(_(u'Must be in the past.'))\n\n\ndef clean_overlapping(models):\n \"\"\"\n :raise ValidationError: If ``models`` seem overlapping.\n\n :param models: An iterable of :class:`~.TimestampRangeModelMixin` mixed\n models.\n \"\"\"\n sorted_models = sorted(\n models, key=operator.attrgetter('from_timestamp'))\n for model, next_model in pairwise(sorted_models):\n if model.to_timestamp is None or \\\n model.to_timestamp > next_model.from_timestamp:\n raise ValidationError(_('There are overlaps.'))\n" }, { "alpha_fraction": 0.7253205180168152, "alphanum_fraction": 0.7336538434028625, "avg_line_length": 35.27906799316406, "blob_id": "69f9e0947f4973150958de74ff8c10f1bbfed0e2", "content_id": "65a52651dc5a52184e00a62047252bc4fa839d44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3120, "license_type": "no_license", "max_line_length": 79, "num_lines": 86, "path": "/gridplatform/encryption/conf.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n.. data:: settings.ENCRYPTION_RSA_KEYLENGTH = 1024\n\n Key length for generated RSA keys; bits, multiple of 256, at least 1024.\n\n.. data:: settings.ENCRYPTION_AES_KEYLENGTH = 16\n\n Key length for generated AES keys; bytes, 16, 24 or 32.\n\n.. data:: settings.ENCRYPTION_COOKIE_NAME = 'gmkey'\n\n Cookie to store the session data decryption key in.\n\n.. data:: settings.ENCRYPTION_SESSION_KEY = 'encryption_private_key'\n\n Key for session dictionary entry holding the encrypted private key (and the\n applied encryption data initialization vector) for the user with that\n session. This encrypted private key is encrypted symmetrically using a key\n encoded into a cookie, named by :data:`settings.ENCRYPTION_COOKIE_NAME`.\n\n.. data:: settings.ENCRYPTION_SIGN_SALT = 'gridmanager.encryption.middleware.'\n\n Salt used for converting cookie key value to symmetric key and back. See\n also :class:`.EncryptionMiddleware`.\n\n.. data:: settings.ENCRYPTION_STORE_KEY = 'private_key'\n\n Name of thread-local store attribute used to hold private key during\n processing of request (for normal session-based authentication). See also\n :class:`.EncryptionContext`.\n\n.. data:: settings.ENCRYPTION_EPHEMERAL_STORE_KEY = 'ephemeral_private_key'\n\n Name of thread-local store attribute used to hold private key during\n processing of request (when authenticating per request via token auth).\n See also :meth:`.EncryptionTokenAuthentication.authenticate_credentials`\n and :class:`.EncryptionContext`\n\n.. data:: settings.ENCRYPTION_ORIGINAL_STORE_KEY = '_original_private_key'\n\n Name of thread-local store attribute used to detect if the thread-local\n store attribute named by :data:`settings.ENCRYPTION_STORE_KEY` has changed.\n See also :class:`.EncryptionMiddleware`.\n\n.. data:: settings.ENCRYPTION_CONTEXT_STORE_KEY = 'encryption_context'\n\n The thread-local store attribute used to hold the\n :class:`.EncryptionContext` of this request.\n\n.. data:: settings.ENCRYPTION_TESTMODE = False\n\n Set to ``True`` to disable encryption. This is useful for unit testing\n were the subject under test is some kind of :class:`.EncryptedModel` but\n the purpose of the test is not to test encryption mechanisms.\n\n.. data:: settings.ENCRYPTION_CIPHER_MODULE = 'gridplatform.encryption.cipher'\n\n Path to cipher module. See also :mod:`gridplatform.encrytion.cipher`.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.conf import settings\n\nfrom appconf import AppConf\n\n\n__all__ = ['settings', 'EncryptionConf']\n\n\nclass EncryptionConf(AppConf):\n RSA_KEYLENGTH = 1024\n AES_KEYLENGTH = 16\n # cookie to store the session data decryption key in\n COOKIE_NAME = 'gmkey'\n SESSION_KEY = 'encryption_private_key'\n SIGN_SALT = 'gridmanager.encryption.middleware.'\n\n STORE_KEY = 'private_key'\n EPHEMERAL_STORE_KEY = 'ephemeral_private_key'\n ORIGINAL_STORE_KEY = '_original_private_key'\n CONTEXT_STORE_KEY = 'encryption_context'\n\n TESTMODE = False\n CIPHER_MODULE = 'gridplatform.encryption.cipher'\n" }, { "alpha_fraction": 0.8180439472198486, "alphanum_fraction": 0.8180439472198486, "avg_line_length": 46.10714340209961, "blob_id": "4d808820f9fc1e82d6dff332927e5f1fae372009", "content_id": "8fde252d8458e0181b5d5cfc6c7f5ab2591fed18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1319, "license_type": "no_license", "max_line_length": 79, "num_lines": 28, "path": "/documentation/source/projects.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "Projects\n========\n\nFor energy performances, energy performance indicators, and normalized energy\nconsumptions it is possible to define a project. A project has a goal, which\nis an percentwise improvement of the involved energy performance, energy\nperformance indicator or normalized energy consumption.\n\nIf the goal is (or can be translated into) a yearly cost reduction and the\ninvestment costs of the project is well-known it is possible to calculated an\nexpected payback period, which may be used to prioritize which projects to\nexecute next.\n\nProjects are executed by first measuring a benchmark energy performance or\nnormalized energy consumption. Then implement the action of the project. And\nfinally measure the resulting energy performance or normalized energy\nconsumption.\n\nThe change in percent between the benchmark and the result gives the achieved\nimprovement. If the achieved improvement is better than the goal originally\nset out, the goal has been achieved.\n\nAfter the project has been completed, and costs are well-defined it is possible\nto calculate the actual payback period, which may be longer or shorter than\nthe expected payback period.\n\nThat the goal remains acheived can be automatically checked by measuring new\nresults periodically, and comparing these results to the benchmark and goal.\n" }, { "alpha_fraction": 0.616119921207428, "alphanum_fraction": 0.617423415184021, "avg_line_length": 37.68067169189453, "blob_id": "60b1df728b52f946dd709435aab8a6bf2ce04c32", "content_id": "2456450c5152a38c5b2659c2eaf5abe501b1328f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4603, "license_type": "no_license", "max_line_length": 79, "num_lines": 119, "path": "/legacy/measurementpoints/models/utilization.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.forms import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.functional import cached_property\n\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\n\nfrom .dataseries import DataSeries\nfrom .mixins import ENPIMixin\nfrom .integral import PiecewiseConstantIntegral\nfrom ..fields import DataRoleField\n\n\nclass Utilization(ENPIMixin, DataSeries):\n \"\"\"\n A C{Utilization} is a L{DataSeries} that describe how well a C{consumption}\n is utilized according to current C{needs}.\n\n Formally, this is done by M{u(t) = S{integral} c'(t) / (n(t) * t) dt},\n where M{u} is the resulting utilization function, M{c'} is the first\n derivative of C{consumption}, M{n} is the C{needs} function and M{t} is the\n time. In the event M{n(t)=0} we say that M{c'(t) / n(t) = 0} also.\n\n @ivar consumption: A continuous accumulation DataSeries defining the\n consumption.\n\n @ivar needs: A piece wise constant rate DataSeries defining needs as a\n function of time.\n \"\"\"\n consumption = models.ForeignKey(DataSeries, on_delete=models.CASCADE,\n related_name='utilization_consumption'\n '_derivative_set')\n needs = models.ForeignKey(DataSeries, on_delete=models.PROTECT,\n related_name='utilization_needs_derivative_set')\n\n class Meta(DataSeries.Meta):\n verbose_name = _('normalization')\n verbose_name_plural = _('normalizations')\n app_label = 'measurementpoints'\n\n def clean(self):\n \"\"\"\n C{Utilization} specialization of C{Model.clean()}\n \"\"\"\n super(Utilization, self).clean()\n if not (\n PhysicalQuantity(1, self.consumption.unit) / (\n PhysicalQuantity(1, self.needs.unit) *\n PhysicalQuantity(1, 'hour'))).\\\n compatible_unit(self.unit):\n raise ValidationError(\n _('Consumption unit {consumption_unit} and needs unit '\n '{needs_unit} are not compatible with target unit '\n '{target_unit}').\n format(\n consumption_unit=self.consumption.unit,\n needs_unit=self.needs.unit,\n target_unit=self.unit))\n\n def save(self, *args, **kwargs):\n \"\"\"\n C{Utilization} specialization of C{Model.save()}\n \"\"\"\n self.clean()\n super(Utilization, self).save(*args, **kwargs)\n\n def depends_on(self):\n \"\"\"\n C{Utilization} implementation of L{DataSeries.depends_on()}.\n \"\"\"\n return [\n self.consumption.subclass_instance,\n self.energy_driver] + \\\n self.consumption.subclass_instance.depends_on() + \\\n self.energy_driver.depends_on()\n\n def __energy_driver(self, sample):\n return (\n sample.physical_quantity *\n PhysicalQuantity(\n (sample.to_timestamp - sample.from_timestamp).total_seconds(),\n 'second'))\n\n @cached_property\n def energy_driver(self):\n energy_driver = PiecewiseConstantIntegral(\n role=DataRoleField.ENERGY_DRIVER,\n data=self.needs.subclass_instance)\n energy_driver.full_clean(exclude=['role'])\n return energy_driver\n\n def _condense_energy_drivers(\n self, from_timestamp, sample_resolution, to_timestamp):\n \"\"\"\n Implementation of L{ENPIMixin._condense_energy_drivers()}.\n \"\"\"\n return self.energy_driver.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp)\n\n def _condense_energy_consumption(self, from_timestamp, sample_resolution,\n to_timestamp):\n for sample in self.consumption.subclass_instance.get_condensed_samples(\n from_timestamp, sample_resolution, to_timestamp):\n assert from_timestamp <= sample.from_timestamp\n assert sample.to_timestamp <= to_timestamp\n yield sample\n\n def _calculate_energy_development(self, from_timestamp, to_timestamp):\n return self.consumption.subclass_instance.calculate_development(\n from_timestamp, to_timestamp)\n\n def _calculate_energy_driver_development(\n self, from_timestamp, to_timestamp):\n return self.energy_driver.calculate_development(\n from_timestamp, to_timestamp)\n" }, { "alpha_fraction": 0.5988724231719971, "alphanum_fraction": 0.600334107875824, "avg_line_length": 31.578231811523438, "blob_id": "fb80568d750f49bd1082684e59513b9566932090", "content_id": "0d30676f0b735d3b46db4470c7e99beb23b7d7a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4789, "license_type": "no_license", "max_line_length": 79, "num_lines": 147, "path": "/legacy/website/templatetags/dropdown.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\"\"\"\nThis module defines Django template tags for using jQuery-dropdown.\n\nThe template tag C{{% dropdown %}} is used to define everything where the\ndrop-down is to be shown. A secondary C{{% dropdown_bodies %}} template tag is\nused to insert bodies with the correct id for all drop-downs that have been\nrendered earlier in the same document.\n\nYes, you can have any number of drop-downs on the same page, and you don't need\nto manually couple each drop down with its anchor.\n\n@see: U{http://labs.abeautifulsite.net/jquery-dropdown/}\n\nThe jQuery-dropdown javascript inserts the contents of a named C{<div>} as\ndropdown on elements (anchors) that have their C{data-dropdown} set to the id\nof that C{<div>}. The C{<div>} needs to be defined in a place where it is not\nstyled, and so, it will usually be a different place in the document than where\nthe drop-down is to be shown, thus creating a high coupling between these two\nlocations.\n\"\"\"\nfrom django import template\n\n\nregister = template.Library()\n\n\[email protected]\ndef dropdown(parser, token):\n \"\"\"\n Construct an anchor which will drop-down a body when clicked.\n\n Usage::\n\n {% dropdown %}\n {% anchor %}\n {% trans 'Add' %} <img ... >\n {% endanchor %}\n {% body %}\n <ul>\n <li>\n <a href=\"{% url ... %}\">\n {% trans \"Drop-down link 1\" %}\n </a>\n </li>\n <li>\n <a href=\"{% url ... %}\">\n {% trans \"Drop-down link 2\" %}\n </a>\n </li>\n </ul>\n {% endbody %}\n {% enddropdown %}\n\n ...\n\n {% dropdown_bodies %}\n </body>\n\n The popup direction defaults to 'anchor-right' to change this add an\n argument to the dropdown tag:\n {% dropdown \"anchor-left\" %}\n\n The tag should be used where the drop-down should be rendered. A seperate\n tag, C{{% dropdown_bodies %}} is used to insert the C{dropdown_body}\n outside formatting context, so that it will be placed correctly when\n rendered.\n\n @see: L{dropdown_bodies} for details on the C{{% dropdown_bodies %}} tag.\n \"\"\"\n menu_direction = 'anchor-right'\n tokens = token.split_contents()\n if len(tokens) > 1:\n menu_direction = tokens[1][1:-1]\n parser.parse(\"anchor\")\n parser.delete_first_token()\n anchor_nodes = parser.parse(\"endanchor\")\n parser.delete_first_token()\n parser.parse(\"body\")\n parser.delete_first_token()\n body_nodes = parser.parse(\"endbody\")\n parser.delete_first_token()\n parser.parse(\"enddropdown\")\n parser.delete_first_token()\n return DropDownNode(anchor_nodes, body_nodes, menu_direction)\n\n\[email protected]_tag(takes_context=True)\ndef dropdown_bodies(context):\n \"\"\"\n Insert drop-down bodies from all drop-downs that has been rendered so far.\n\n Usage::\n\n ...\n {% dropdown_bodies %}\n </body>\n\n This tag should be inserted just before the C{</body>} element, as\n prescribed by the jQuery dropdown documentation.\n\n @see: L{do_dropdown} for a full example of using C{{% dropdown %}}\n \"\"\"\n result = \"\"\n if \"dropdown\" in context.render_context:\n for dropdown_id, dropdown_body in \\\n context.render_context[\"dropdown\"].iteritems():\n result += \\\n u'<div id=\"%s\" class=\"dropdown-menu %s\">%s</div>' % (\n dropdown_id,\n dropdown_body['direction'],\n dropdown_body['node'])\n return result\n\n\nclass DropDownNode(template.Node):\n \"\"\"\n A C{DropDownNode} keeps track of C{anchor_nodes} and C{body_nodes}, and\n inserts the C{anchor_nodes} when rendered.\n \"\"\"\n\n def __init__(self, anchor_nodes, body_nodes, direction):\n \"\"\"\n Create a C{DropDownNode} from given C{anchor_nodes} and C{body_nodes}.\n \"\"\"\n self.anchor_nodes = anchor_nodes\n self.body_nodes = body_nodes\n self.direction = direction\n\n def render(self, context):\n \"\"\"\n Renders C{self.anchor_nodes} and stores C{self.body_nodes},\n C{self.direction} and an ID string in the C{context.render_context}.\n \"\"\"\n if \"dropdown\" not in context.render_context:\n context.render_context[\"dropdown\"] = {}\n\n dropdown_id = \"dropdown-%d\" % len(context.render_context[\"dropdown\"])\n context.render_context[\"dropdown\"][dropdown_id] = \\\n {'direction': self.direction,\n 'node': self.body_nodes.render(context)}\n\n return u'<a href=\"#\" data-dropdown=\"#%s\">%s</a>' % (\n dropdown_id,\n self.anchor_nodes.render(context))\n" }, { "alpha_fraction": 0.6869584321975708, "alphanum_fraction": 0.6888900995254517, "avg_line_length": 33.05826950073242, "blob_id": "9ececa63eb5a6808d8ca86116c4dda900ee63bf1", "content_id": "dd98960836b43e9ba586e72b14f92b8b35266b7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18119, "license_type": "no_license", "max_line_length": 120, "num_lines": 532, "path": "/legacy/manage_devices/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.core import urlresolvers\nfrom django.db.models import Q\nfrom django.forms import ValidationError\nfrom django.forms.models import BaseInlineFormSet\nfrom django.http import HttpResponseForbidden\nfrom django.shortcuts import get_object_or_404\nfrom django.shortcuts import redirect\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import ugettext as _\nfrom extra_views import CreateWithInlinesView\nfrom extra_views import InlineFormSet\nfrom extra_views import UpdateWithInlinesView\n\nfrom gridplatform import trackuser\nfrom gridplatform.consumptions.models import Consumption\nfrom gridplatform.consumptions.models import PulsePeriod\nfrom gridplatform.productions.models import Production\nfrom gridplatform.productions.models import PulsePeriod as ProductionPulsePeriod # noqa\nfrom gridplatform.users.decorators import auth_or_error\nfrom gridplatform.users.decorators import auth_or_redirect\nfrom gridplatform.users.decorators import customer_admin_or_admin_or_error\nfrom gridplatform.users.decorators import customer_admin_or_error\nfrom gridplatform.users.views import CustomerAdminOrAdminRequiredMixin\nfrom gridplatform.utils.views import json_list_options\nfrom gridplatform.utils.views import json_response\nfrom gridplatform.utils.views import render_to\nfrom gridplatform.utils.formsets import SurvivingFormsModelFormSetMixin\nfrom legacy.devices.models import Agent\nfrom legacy.devices.models import Meter\nfrom legacy.ipc import agentserver\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.datasequence_adapters.models import ConsumptionAccumulationAdapter\nfrom legacy.datasequence_adapters.models import ProductionAccumulationAdapter\nfrom gridplatform.utils.utilitytypes import OPTIONAL_METER_CHOICES\n\nfrom .forms import AgentForm\nfrom .forms import MeterForm\nfrom .forms import RelayForm\nfrom .forms import ElectricityConsumptionForm\nfrom .forms import WaterConsumptionForm\nfrom .forms import DistrictHeatingConsumptionForm\nfrom .forms import GasConsumptionForm\nfrom .forms import OilConsumptionForm\nfrom .forms import ProductionForm\nfrom .forms import EnergyInputPeriodForm\nfrom .forms import VolumeInputPeriodForm\nfrom .forms import ProductionInputPeriodForm\n\n\n@auth_or_redirect\n@render_to('manage_devices/agent_list.html')\ndef agent_list(request):\n customer = trackuser.get_customer()\n agents = Agent.objects.filter(\n customer=customer,\n no_longer_in_use=False).select_related(\n 'location', 'customer')\n return {\n 'agent_list': agents,\n }\n\n\n@auth_or_redirect\n@render_to('manage_devices/meter_list.html')\ndef meter_list(request):\n customer = trackuser.get_customer()\n meters = Meter.objects.filter(\n customer=customer).select_related('agent', 'location')\n return {\n 'meter_list': meters,\n }\n\n\n@auth_or_error\n@json_response\ndef agent_list_json(request, customer=None):\n if not customer:\n customer = trackuser.get_customer()\n assert customer\n\n options = json_list_options(request)\n data = list(Agent.objects.filter(\n customer=customer, no_longer_in_use=False).select_related('location'))\n\n if options['search']:\n data = filter(\n lambda agent: agent.satisfies_search(options['search']), data)\n order_map = {\n 'location': lambda agent: unicode(agent.location),\n 'mac': lambda agent: unicode(agent.mac),\n }\n if options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_devices/agent_block.html',\n {'agent': agent},\n RequestContext(request))\n for agent in data_slice\n ]\n\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\n@customer_admin_or_admin_or_error\n@render_to('manage_devices/agent_form.html')\ndef agent_form(request, pk):\n customer = trackuser.get_customer()\n if customer:\n instance = get_object_or_404(Agent, pk=pk, customer=customer)\n else:\n instance = get_object_or_404(Agent, pk=pk)\n\n form = AgentForm(instance=instance, auto_id=False)\n\n return {\n 'form': form,\n 'agent': instance,\n }\n\n\n@customer_admin_or_admin_or_error\n@json_response\ndef agent_update(request, pk):\n customer = trackuser.get_customer()\n if customer:\n instance = get_object_or_404(Agent, pk=pk, customer=customer)\n else:\n instance = get_object_or_404(Agent, pk=pk)\n\n form = AgentForm(request.POST, instance=instance, auto_id=False)\n if form.is_valid():\n agent = form.save()\n return {\n 'success': True,\n 'statusText': _('The agent has been saved'),\n 'html': render_to_string(\n 'manage_devices/agent_block.html',\n {'agent': agent},\n RequestContext(request)\n ),\n }\n else:\n # Form contains only location, which may legally be blank, i.e. this\n # error should not be possible...\n assert False\n\n\n@auth_or_error\n@json_response\ndef meter_list_json(request, customer=None):\n if not customer:\n customer = trackuser.get_customer()\n assert customer\n\n options = json_list_options(request)\n data = list(Meter.objects.filter(customer=customer).select_related(\n 'agent', 'location'))\n\n if options['search']:\n data = filter(\n lambda meter: meter.satisfies_search(options['search']), data)\n order_map = {\n 'name': lambda meter: meter.name_plain.lower(),\n 'location': lambda meter: unicode(meter.location),\n 'agent': lambda meter: unicode(meter.agent),\n }\n if options['order_by'] in order_map:\n data.sort(key=order_map[options['order_by']])\n if options['direction'].lower() == 'desc':\n data.reverse()\n\n data_slice = data[options['offset']:options['offset'] + options['count']]\n rendered = [\n render_to_string(\n 'manage_devices/meter_block.html',\n {'meter': meter}, RequestContext(request))\n for meter in data_slice\n ]\n return {\n 'total': len(data),\n 'data': rendered,\n }\n\n\nclass MeterUpdateView(\n CustomerAdminOrAdminRequiredMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/meter_form.html'\n model = Meter\n form_class = MeterForm\n\n def get_success_url(self):\n return urlresolvers.reverse('manage_devices-meter-list')\n\n def _get_pulse_conversions(self):\n pulse_conversion_filter = Q(\n datasequence__period__pulseperiod__datasource__customerdatasource__physicalinput__meter=self.object) # noqa\n consumptions = ConsumptionAccumulationAdapter.objects.filter(\n pulse_conversion_filter)\n productions = ProductionAccumulationAdapter.objects.filter(\n pulse_conversion_filter)\n return list(consumptions) + list(productions)\n\n def get_context_data(self, **context):\n if 'pulse_conversions' not in context:\n context['pulse_conversions'] = self._get_pulse_conversions()\n return super(MeterUpdateView, self).get_context_data(**context)\n\n\n@customer_admin_or_error\n@json_response\ndef meter_relay(request, pk):\n customer = trackuser.get_customer()\n meter = get_object_or_404(Meter, pk=pk)\n if meter.agent.customer != customer:\n return HttpResponseForbidden()\n relay_form = RelayForm(request.POST)\n if not relay_form.is_valid():\n return {\n 'success': False,\n 'statusText': _('Invalid relay state choice')\n }\n agent = meter.agent\n if not agent.online:\n return {\n 'success': False,\n 'statusText': _('Agent currently offline'),\n }\n relay_on = relay_form.cleaned_data['relay_state'] == 'on'\n agentserver.relay_state(\n agent.mac, [(meter.connection_type, meter.manufactoring_id)], relay_on)\n return {\n 'success': True,\n 'statusText': _('Sending relay state change request')\n }\n\n\n@customer_admin_or_error\n@json_response\ndef meter_relay_toggle(request, pk, action):\n customer = trackuser.get_customer()\n meter = get_object_or_404(Meter, pk=pk)\n if meter.agent.customer != customer:\n return HttpResponseForbidden()\n\n agent = meter.agent\n if not agent.online:\n return {\n 'success': False,\n 'statusText': _('Agent currently offline'),\n }\n relay_on = action == 'on'\n agentserver.relay_state(\n agent.mac, [(meter.connection_type, meter.manufactoring_id)], relay_on)\n return {\n 'success': True,\n 'statusText': _('Sending relay state change request')\n }\n\n\n@customer_admin_or_error\n@json_response\ndef meter_relay_state(request, pk):\n customer = trackuser.get_customer()\n meter = get_object_or_404(Meter, pk=pk)\n if meter.agent.customer != customer:\n return HttpResponseForbidden()\n\n agent = meter.agent\n if not agent.online:\n return {\n 'success': False,\n 'statusText': _('Agent currently offline'),\n }\n state = 'off'\n if meter.relay_on:\n state = 'on'\n\n return {\n 'success': True,\n 'state': state,\n }\n\n\nclass InputPeriodFormSetFormSet(\n SurvivingFormsModelFormSetMixin, BaseInlineFormSet):\n def clean(self):\n super(InputPeriodFormSetFormSet, self).clean()\n\n if any(self.errors):\n return\n\n surviving_forms = self.surviving_forms()\n\n if not surviving_forms:\n raise ValidationError(\n _('Must define at least one period'))\n\n periods = [form.instance for form in surviving_forms]\n self.model.clean_overlapping_periods(periods)\n\n\nclass InputPeriodFormSetBase(InlineFormSet):\n formset_class = InputPeriodFormSetFormSet\n\n\nclass EnergyInputPeriodInline(InputPeriodFormSetBase):\n model = PulsePeriod\n form_class = EnergyInputPeriodForm\n extra = 1\n\n\nclass VolumeInputPeriodInline(InputPeriodFormSetBase):\n model = PulsePeriod\n form_class = VolumeInputPeriodForm\n extra = 1\n\n\nclass ProductionInputPeriodInline(InputPeriodFormSetBase):\n model = ProductionPulsePeriod\n form_class = ProductionInputPeriodForm\n extra = 1\n\n\nclass MeterPulseConversionViewMixin(object):\n def forms_valid(self, form, inlines):\n physicalinput_id = self.kwargs.get('physicalinput', None)\n if physicalinput_id is None:\n # NOTE: Ugly hack; but this code is doomed anyway; DataSequences\n # are supposed to work with different inputs, possibly from\n # different meters; meaning that input IDs should become explicit\n # in the form... (... this was less of a hack than putting it in\n # the URL, as the same hack would then have to be used to obtain\n # the URL...)\n physicalinput_id = inlines[0].forms[0].instance.datasource_id\n for inlineform in inlines[0].forms:\n inlineform.instance.datasource_id = physicalinput_id\n return super(MeterPulseConversionViewMixin, self).forms_valid(\n form, inlines)\n\n def get_success_url(self):\n return urlresolvers.reverse('manage_devices-meter-update',\n kwargs={'pk': self.kwargs['meter']})\n\n\nclass CreateConsumptionAccumulationAdapterMixin(object):\n def forms_valid(self, form, inlines):\n \"\"\"\n requires `self.utility_type` to be set.\n \"\"\"\n response = super(\n CreateConsumptionAccumulationAdapterMixin, self).forms_valid(\n form, inlines)\n ConsumptionAccumulationAdapter.objects.get_or_create(\n datasequence=self.object,\n role=DataRoleField.CONSUMPTION,\n utility_type=self.utility_type,\n unit=self.object.unit)\n return response\n\n\nclass ElectricityConsumptionCreateView(\n CreateConsumptionAccumulationAdapterMixin,\n MeterPulseConversionViewMixin,\n CreateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = ElectricityConsumptionForm\n inlines = [EnergyInputPeriodInline]\n utility_type = OPTIONAL_METER_CHOICES.electricity\n\n\nclass ElectricityConsumptionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = ElectricityConsumptionForm\n inlines = [EnergyInputPeriodInline]\n\n\nclass WaterConsumptionCreateView(\n CreateConsumptionAccumulationAdapterMixin,\n MeterPulseConversionViewMixin,\n CreateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = WaterConsumptionForm\n inlines = [VolumeInputPeriodInline]\n utility_type = OPTIONAL_METER_CHOICES.water\n\n\nclass WaterConsumptionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = WaterConsumptionForm\n inlines = [VolumeInputPeriodInline]\n\n\nclass DistrictHeatingConsumptionCreateView(\n CreateConsumptionAccumulationAdapterMixin,\n MeterPulseConversionViewMixin,\n CreateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = DistrictHeatingConsumptionForm\n inlines = [EnergyInputPeriodInline]\n utility_type = OPTIONAL_METER_CHOICES.district_heating\n\n\nclass DistrictHeatingConsumptionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = DistrictHeatingConsumptionForm\n inlines = [EnergyInputPeriodInline]\n\n\nclass GasConsumptionCreateView(\n CreateConsumptionAccumulationAdapterMixin,\n MeterPulseConversionViewMixin,\n CreateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = GasConsumptionForm\n inlines = [VolumeInputPeriodInline]\n utility_type = OPTIONAL_METER_CHOICES.gas\n\n\nclass GasConsumptionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = GasConsumptionForm\n inlines = [VolumeInputPeriodInline]\n\n\nclass OilConsumptionCreateView(\n CreateConsumptionAccumulationAdapterMixin,\n MeterPulseConversionViewMixin,\n CreateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = OilConsumptionForm\n inlines = [VolumeInputPeriodInline]\n utility_type = OPTIONAL_METER_CHOICES.oil\n\n\nclass OilConsumptionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/consumption_form.html'\n model = Consumption\n form_class = OilConsumptionForm\n inlines = [VolumeInputPeriodInline]\n\n\nclass ProductionCreateView(\n MeterPulseConversionViewMixin, CreateWithInlinesView):\n template_name = 'manage_devices/production_form.html'\n model = Production\n form_class = ProductionForm\n inlines = [ProductionInputPeriodInline]\n\n def get_form_kwargs(self, **kwargs):\n kwargs = super(\n ProductionCreateView, self).get_form_kwargs(\n **kwargs)\n kwargs['unit'] = self.kwargs['production_unit']\n return kwargs\n\n def construct_inlines(self):\n inlines = super(\n ProductionCreateView, self).construct_inlines()\n for inlineform in inlines[0].forms:\n inlineform.instance.output_unit = self.kwargs['production_unit']\n return inlines\n\n def forms_valid(self, form, inlines):\n response = super(\n ProductionCreateView, self).forms_valid(\n form, inlines)\n ProductionAccumulationAdapter.objects.get_or_create(\n datasequence=self.object,\n role=DataRoleField.PRODUCTION,\n utility_type=OPTIONAL_METER_CHOICES.unknown,\n unit=self.object.unit)\n return response\n\n\nclass ProductionUpdateView(\n MeterPulseConversionViewMixin, UpdateWithInlinesView):\n template_name = 'manage_devices/production_form.html'\n model = Production\n form_class = ProductionForm\n inlines = [ProductionInputPeriodInline]\n\n\ndef pulseconversion_update(request, meter, pk):\n ds = get_object_or_404(DataSeries, id=pk)\n adapter = ds.subclass_instance\n if adapter.utility_type == OPTIONAL_METER_CHOICES.electricity:\n return redirect('manage_devices-pulseconversion-electricity-update',\n meter=meter, pk=adapter.datasequence_id)\n elif adapter.utility_type == OPTIONAL_METER_CHOICES.water:\n return redirect('manage_devices-pulseconversion-water-update',\n meter=meter, pk=adapter.datasequence_id)\n elif adapter.utility_type == \\\n OPTIONAL_METER_CHOICES.district_heating:\n return redirect(\n 'manage_devices-pulseconversion-district_heating-update',\n meter=meter, pk=adapter.datasequence_id)\n elif adapter.utility_type == OPTIONAL_METER_CHOICES.gas:\n return redirect('manage_devices-pulseconversion-gas-update',\n meter=meter, pk=adapter.datasequence_id)\n elif adapter.utility_type == OPTIONAL_METER_CHOICES.oil:\n return redirect('manage_devices-pulseconversion-oil-update',\n meter=meter, pk=adapter.datasequence_id)\n elif adapter.role == DataRoleField.PRODUCTION:\n return redirect('manage_devices-pulseconversion-production-update',\n meter=meter, pk=adapter.datasequence_id)\n" }, { "alpha_fraction": 0.673693060874939, "alphanum_fraction": 0.6745362281799316, "avg_line_length": 29.41025733947754, "blob_id": "28181b68f48d40cde30dd70f9ca011466e1f95d6", "content_id": "4da3d6a3379bad2c9a86ef364984945ac8542e31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1186, "license_type": "no_license", "max_line_length": 65, "num_lines": 39, "path": "/gridplatform/customer_datasources/tests.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\nfrom gridplatform.providers.models import Provider\nfrom gridplatform.customers.models import Customer\nfrom gridplatform.trackuser import replace_customer\n\nfrom .models import CustomerDataSource\n\n\n@override_settings(\n ENCRYPTION_TESTMODE=True)\nclass CustomerDataSourceEncryptionTest(TestCase):\n def setUp(self):\n Provider.objects.create()\n self.customer = Customer()\n self.customer.save()\n\n def test_name(self):\n with replace_customer(self.customer):\n pk = CustomerDataSource.objects.create(\n name_plain='test name',\n unit='milliwatt*hour').id\n\n self.assertEqual(\n CustomerDataSource.objects.get(id=pk).name_plain,\n 'test name')\n\n def test_blank_name(self):\n with replace_customer(self.customer):\n pk = CustomerDataSource.objects.create(\n unit='milliwatt*hour').id\n\n self.assertEqual(\n CustomerDataSource.objects.get(id=pk).name_plain, '')\n" }, { "alpha_fraction": 0.6965630054473877, "alphanum_fraction": 0.7011456489562988, "avg_line_length": 40.283782958984375, "blob_id": "4e0d6fa35d276b2df82b61c2303d7dca78b2a1e0", "content_id": "6c13844d1585c126f94ed85ccd3dc9ec70fd8421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3059, "license_type": "no_license", "max_line_length": 91, "num_lines": 74, "path": "/legacy/measurementpoints/models/co2calculation.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport operator\n\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom gridplatform.utils.samples import Sample\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom gridplatform.datasequences.utils import aggregate_sum_ranged_sample_sequence # noqa\nfrom gridplatform.utils.samples import wrap_ranged_sample_sequence\nfrom gridplatform.datasequences.utils import multiply_ranged_sample_sequences\nfrom gridplatform.utils import condense\n\nfrom .indexcalculation import IndexCalculation\nfrom .costcalculation import _break_into_fiveminutes_samples\n\n\nclass Co2Calculation(IndexCalculation):\n \"\"\"\n A C{Co2Calculation} is a L{DataSeries} derived from a consumption\n L{DataSeries} and a index L{DataSeries}.\n\n @ivar index: The index L{DataSeries} used in the CO2 calculation.\n\n @ivar consumption: The consumption L{DataSeries} used in the consumption\n calculation.\n \"\"\"\n\n class Meta:\n proxy = True\n verbose_name = _('CO₂ calculation')\n verbose_name_plural = _('CO₂ calculations')\n app_label = 'measurementpoints'\n\n RATE_RESOLUTION = RelativeTimeDelta(minutes=5)\n\n def _five_minute_accumulated(self, from_timestamp, to_timestamp):\n assert self.RATE_RESOLUTION == RelativeTimeDelta(minutes=5)\n\n co2conversion_samples = _break_into_fiveminutes_samples(\n self._get_rate().get_samples(\n from_timestamp, to_timestamp), from_timestamp, to_timestamp)\n consumption_samples = self._get_accumulation().get_condensed_samples(\n from_timestamp, condense.FIVE_MINUTES, to_timestamp)\n\n return multiply_ranged_sample_sequences(\n consumption_samples, co2conversion_samples)\n\n def _get_condensed_samples(\n self, from_timestamp, sample_resolution, to_timestamp):\n # NOTE: API from DataSeries\n data = self._five_minute_accumulated(from_timestamp, to_timestamp)\n if sample_resolution == RelativeTimeDelta(minutes=5):\n return data\n else:\n return wrap_ranged_sample_sequence(\n aggregate_sum_ranged_sample_sequence(\n data, sample_resolution, self.customer.timezone))\n\n def calculate_development(self, from_timestamp, to_timestamp):\n from gridplatform.datasequences.models.base import is_five_minute_multiplum # noqa\n assert is_five_minute_multiplum(from_timestamp), \\\n '%r is not a 5 minute multiplum' % from_timestamp\n assert is_five_minute_multiplum(to_timestamp), \\\n '%r is not a 5 minute multiplum' % to_timestamp\n samples = self._five_minute_accumulated(from_timestamp, to_timestamp)\n value = reduce(\n operator.add,\n (s.physical_quantity for s in samples),\n PhysicalQuantity(0, self.unit))\n return Sample(from_timestamp, to_timestamp, value, False, False)\n" }, { "alpha_fraction": 0.617075502872467, "alphanum_fraction": 0.6196240782737732, "avg_line_length": 31.69791603088379, "blob_id": "96dd6e9fee71f058ec66d4c96ddeb16071c4badc", "content_id": "8aa76fd69a5e3e01e8c01738d1e90daf85c38fd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3139, "license_type": "no_license", "max_line_length": 76, "num_lines": 96, "path": "/legacy/ipc/agentserver.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport logging\nimport json\n\nimport pika\nfrom django.conf import settings\n\nlogger = logging.getLogger(__name__)\n\n\n# 1 for connection type ZigBee\ndef gridpoint_id(connection_type, nid):\n return {'connection_type': connection_type, 'id': nid}\n\n\ndef format_mac(mac):\n return '{:012x}'.format(int(mac))\n\n\ndef agent_routing_key(agent_mac):\n return 'agent.{:012x}'.format(int(agent_mac))\n\n\ndef send_message(routing_key, message):\n connection = pika.BlockingConnection(pika.URLParameters(\n str(settings.BROKER_URL)))\n channel = connection.channel()\n channel.exchange_declare(exchange='agentservers', exchange_type='topic')\n channel.basic_publish(\n exchange='agentservers',\n routing_key=routing_key,\n properties=pika.BasicProperties(\n content_type='application/json'),\n body=json.dumps(message))\n connection.close()\n logger.debug('sent; routing key: %s, message: %s', routing_key, message)\n\n\ndef control_mode(agent_mac, meters, control_manual):\n routing_key = agent_routing_key(agent_mac)\n message = {\n 'command': 'control_mode',\n 'agent': format_mac(agent_mac),\n 'control_manual': bool(control_manual),\n 'meters': [gridpoint_id(connection_type, nid)\n for connection_type, nid in meters],\n }\n send_message(routing_key, message)\n\n\ndef relay_state(agent_mac, meters, relay_on):\n routing_key = agent_routing_key(agent_mac)\n message = {\n 'command': 'relay_state',\n 'agent': format_mac(agent_mac),\n 'relay_on': bool(relay_on),\n 'meters': [gridpoint_id(connection_type, nid)\n for connection_type, nid in meters],\n }\n send_message(routing_key, message)\n\n\ndef agent_swupdate(agent_mac, software_image):\n sw_version = (software_image.sw_major, software_image.sw_minor,\n software_image.sw_revision, software_image.sw_subrevision)\n hw_version = (software_image.hw_major, software_image.hw_minor,\n software_image.hw_revision, software_image.hw_subrevision)\n routing_key = agent_routing_key(agent_mac)\n message = {\n 'command': 'gridagent_software',\n 'agent': format_mac(agent_mac),\n 'sw_version': sw_version,\n 'hw_model': software_image.device_type,\n 'target_hw_version': hw_version,\n }\n send_message(routing_key, message)\n\n\ndef agent_rules(agent_mac, rulesets):\n rulesets = [{'meters': [gridpoint_id(connection_type, nid)\n for connection_type, nid in meters],\n 'rules': [{'start_time': start_time,\n 'end_time': end_time,\n 'relay_on': relay_on}\n for start_time, end_time, relay_on in rules]}\n for meters, rules in rulesets]\n routing_key = agent_routing_key(agent_mac)\n message = {\n 'command': 'gridagent_rules',\n 'agent': format_mac(agent_mac),\n 'rulesets': rulesets,\n }\n send_message(routing_key, message)\n" }, { "alpha_fraction": 0.6017651557922363, "alphanum_fraction": 0.6075888276100159, "avg_line_length": 30.847036361694336, "blob_id": "3ffc39a33d23c947aee0445a22efdff2fc97f290", "content_id": "348e33fd49088b02528a380401f5df3bcae5dff1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16656, "license_type": "no_license", "max_line_length": 79, "num_lines": 523, "path": "/gridplatform/utils/fields.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom decimal import Decimal\nimport json\nimport numbers\nimport re\nimport sys\nimport datetime\nfrom io import BytesIO\n\nfrom PIL import Image\n\nfrom django import forms\nfrom django.utils import six\nfrom django.core import validators\nfrom django.core.exceptions import ValidationError\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ungettext_lazy\n\nfrom durationfield.db.models.fields import duration\nfrom south.modelsinspector import add_introspection_rules\n\nfrom gridplatform.utils import unitconversion\nfrom .format_id import format_mac\n\n# supported input formats for MAC addresses:\n# 6 groups of two hex digits, separated by \":\", \"-\" or \".\"\n# 12 hex digits\nMAC_FORMATS = [\n '^' + ':'.join(['([0-9A-F]{2})'] * 6) + '$',\n '^' + '-'.join(['([0-9A-F]{2})'] * 6) + '$',\n '^' + '.'.join(['([0-9A-F]{2})'] * 6) + '$',\n '^([0-9A-F]{12})$',\n]\n\nHEXDIGITS = re.compile('[0-9A-F]+', re.IGNORECASE)\n\nMAC_RE = re.compile('|'.join(MAC_FORMATS), re.IGNORECASE)\n\n\ndef parse_mac(val):\n \"\"\"\n :return: The integer value that correspond to the MAC address given.\n :param val: The given MAC address (many representations supported)\n\n :see: :func:`gridplatform.utils.format_id.format_mac`.\n \"\"\"\n if isinstance(val, MacAddress):\n return int(val)\n elif isinstance(val, numbers.Integral):\n return val\n elif isinstance(val, basestring) and MAC_RE.match(val):\n return int(''.join(HEXDIGITS.findall(val)), 16)\n elif isinstance(val, tuple) and len(val) == 1:\n return int(val[0])\n else:\n raise ValueError('Invalid MAC address: %s' % val)\n\n\nclass MacAddress(tuple):\n \"\"\"\n An immutable MAC address supporting conversion to string and int.\n Can be instantiated from many representations (as supported by\n :func:`.parse_mac`).\n \"\"\"\n def __new__(cls, addr):\n num_addr = parse_mac(addr)\n return super(MacAddress, cls).__new__(cls, (num_addr,))\n\n def __repr__(self):\n return '<MacAddress {!s}>'.format(self)\n\n def __str__(self):\n return format_mac(*self)\n\n def __int__(self):\n val, = self\n return val\n\n\nclass MacAddressFormField(forms.fields.RegexField):\n \"\"\"\n A form field for MAC addresses.\n \"\"\"\n default_error_messages = {\n 'invalid': _(u'Invalid MAC address.'),\n }\n\n def __init__(self, *args, **kwargs):\n defaults = {\n # 6 groups of 2 chars + 5 separators\n 'max_length': 17,\n }\n defaults.update(kwargs)\n super(MacAddressFormField, self).__init__(MAC_RE, *args, **defaults)\n\n\nclass MacAddressField(models.Field):\n \"\"\"\n A model field for MAC addresses.\n \"\"\"\n description = 'Simple MAC address field'\n __metaclass__ = models.SubfieldBase\n\n def to_python(self, value):\n \"\"\"\n :return: A :class:`.MacAddress`, ``None`` or the empty string.\n \"\"\"\n if value is None or value == \"\":\n return value\n else:\n try:\n return MacAddress(value)\n except ValueError:\n raise ValidationError(\n _(u'not a valid MAC address: %s') % (value,))\n\n def get_internal_type(self):\n \"\"\"\n A MAC address is stored in database as a BigIntegerField.\n \"\"\"\n return 'BigIntegerField'\n\n def get_prep_lookup(self, lookup_type, value):\n mac = self.to_python(value)\n return super(MacAddressField, self).get_prep_lookup(lookup_type, mac)\n\n def get_prep_value(self, value):\n if value is None:\n return None\n return int(value)\n\n def formfield(self, **kwargs):\n \"\"\"\n The form field of a MacAddressField is by default a\n MacAddressFormField.\n \"\"\"\n defaults = {\n 'form_class': MacAddressFormField,\n }\n defaults.update(kwargs)\n return super(MacAddressField, self).formfield(**defaults)\n\n\nadd_introspection_rules([], [r'^gridplatform.utils.fields.MacAddressField$'])\n\n\nclass JSONEncoder(DjangoJSONEncoder):\n \"\"\"\n JSON encoder that in addition to what :class:`.DjangoJSONEncoder`\n supports also have limited support (HH:MM:SS) for\n :class:`datetime.timedelta`.\n \"\"\"\n\n def default(self, value):\n \"\"\"\n Adds support for encoding :class:`datetime.timedelta`.\n \"\"\"\n if isinstance(value, datetime.timedelta):\n assert(value.days == 0)\n assert(value.microseconds == 0)\n hours = value.seconds / (60 * 60)\n minutes = value.seconds / 60 % 60\n seconds = value.seconds % (60 * 60)\n return u\"%d:%d:%d\" % (hours, minutes, seconds)\n return super(JSONEncoder, self).default(value)\n\n\nclass JSONField(models.TextField):\n \"\"\"\n Stores the Python representation of JSON in a TextField. The\n member made available is equivalent with that of C{json.loads()}\n evaluated on the text field.\n \"\"\"\n\n description = \"JSON field (stored as a string)\"\n\n __metaclass__ = models.SubfieldBase\n\n def __init__(self, object_hook=None, *args, **kwargs):\n \"\"\"\n Construct a JSONField.\n\n All arguments except ``object_hook`` are forwarded directly to\n :class:`django.models.TextField`.\n\n :param object_hook: An ``object_hook`` that will be forwarded\n to :func:`json.dumps`. Object hooks are used to convert\n named members to more useful types than the default.\n I.e. if you want anything other than dictionaries, lists,\n unicode strings, integers, float, booleans and None, this\n is where to go.\n\n :warning: When giving the ``object_hook`` parameter, make sure\n to unittest serialization and deserialization of the\n containing Django model thoroughly. There is a risk that\n your object hook will output an object that either cannot\n be reserialized, or when reserialized, cannot be\n recognized by your object hook. Serialization and\n deserialization must be each others inverse.\n \"\"\"\n self.json_object_hook = object_hook\n super(JSONField, self).__init__(*args, **kwargs)\n\n def to_python(self, value):\n \"\"\"\n Convert JSON string fetched from wherever (e.g. database or\n the browser) to Python object.\n \"\"\"\n if value is None or value == \"\":\n return None\n\n if isinstance(value, basestring):\n return json.loads(value, object_hook=self.json_object_hook)\n\n return value\n\n def get_prep_value(self, value):\n \"\"\"\n Convert Python object to a JSON string.\n \"\"\"\n if value == \"\" or value is None:\n return \"\"\n\n return json.dumps(value, cls=JSONEncoder)\n\n def value_to_string(self, obj):\n \"\"\"\n Convert field from Python object to a JSON string.\n \"\"\"\n value = self._get_val_from_obj(obj)\n return self.get_prep_value(value)\n\n def value_from_object(self, obj):\n \"\"\"\n Convert object to value, suitable for a Form. In this case the\n JSON string.\n \"\"\"\n return self.value_to_string(obj)\n\n\nclass SplitHourMinuteWidget(forms.MultiWidget):\n \"\"\"\n Widget for hour/minute choice.\n \"\"\"\n def __init__(self, hour_choices=(), minute_choices=(), attrs=None):\n widgets = (forms.Select(attrs=attrs, choices=hour_choices),\n forms.Select(attrs=attrs, choices=minute_choices))\n super(SplitHourMinuteWidget, self).__init__(widgets, attrs)\n self.hour_choices = hour_choices\n self.minute_choices = minute_choices\n\n def decompress(self, value):\n if value:\n assert value.total_seconds() >= 0\n hours = int(value.total_seconds() / 60 / 60)\n minutes = int(value.total_seconds() / 60 % 60)\n return [hours, minutes]\n return [None, None]\n\n def _get_hour_choices(self):\n return self._hour_choices\n\n def _set_hour_choices(self, value):\n self._hour_choices = self.widgets[0].choices = value\n\n hour_choices = property(_get_hour_choices, _set_hour_choices)\n\n def _get_minute_choices(self):\n return self._minute_choices\n\n def _set_minute_choices(self, value):\n self._minute_choices = self.widgets[1].choices = value\n\n minute_choices = property(_get_minute_choices, _set_minute_choices)\n\n\nclass SplitHiddenHourMinuteWidget(SplitHourMinuteWidget):\n \"\"\"\n Hidden widget for hour/minute choice.\n \"\"\"\n is_hidden = True\n\n def __init__(self, attrs=None):\n super(SplitHiddenHourMinuteWidget, self).__init__(attrs)\n for widget in self.widgets:\n widget.input_type = 'hidden'\n widget.is_hidden = True\n\n\nclass DurationFormField(forms.MultiValueField):\n \"\"\"\n Form field for hour/minute choice.\n\n :ivar hour_choices: A property that makes sure to set hour choices\n correctly.\n :ivar minute_choices: A property that makes sure to set minute\n choices correctly.\n \"\"\"\n widget = SplitHourMinuteWidget\n hidden_widget = SplitHiddenHourMinuteWidget\n default_error_messages = {\n 'invalid_hour': _(u'Select a valid hour.'),\n 'invalid_minute': _(u'Select a valid minute.'),\n }\n\n def __init__(self, hour_choices=None, minute_choices=None,\n *args, **kwargs):\n errors = self.default_error_messages.copy()\n if 'error_messages' in kwargs:\n errors.update(kwargs['error_messages'])\n localize = kwargs.get('localize', False)\n if hour_choices is None:\n hour_choices = [\n (n, ungettext_lazy('%d hour', '%d hours', n) % n)\n for n in range(24)]\n if minute_choices is None:\n minute_choices = [\n (n, ungettext_lazy('%02d minute', '%02d minutes', n) % n)\n for n in range(60)]\n fields = (\n forms.TypedChoiceField(\n error_messages={'invalid': errors['invalid_hour']},\n localize=localize, choices=hour_choices,\n coerce=int),\n forms.TypedChoiceField(\n error_messages={'invalid': errors['invalid_minute']},\n localize=localize, choices=minute_choices,\n coerce=int),\n )\n super(DurationFormField, self).__init__(fields, *args, **kwargs)\n self.hour_choices = hour_choices\n self.minute_choices = minute_choices\n\n def compress(self, data_list):\n if data_list:\n if data_list[0] in validators.EMPTY_VALUES:\n raise ValidationError(self.error_messages['invalid_hour'])\n if data_list[1] in validators.EMPTY_VALUES:\n raise ValidationError(self.error_messages['invalid_minute'])\n return datetime.timedelta(hours=data_list[0], minutes=data_list[1])\n return None\n\n def _get_hour_choices(self):\n return self._hour_choices\n\n def _set_hour_choices(self, value):\n self._hour_choices = self.widget.hour_choices = value\n\n hour_choices = property(_get_hour_choices, _set_hour_choices)\n\n def _get_minute_choices(self):\n return self._minute_choices\n\n def _set_minute_choices(self, value):\n self._minute_choices = self.widget.minute_choices = value\n\n minute_choices = property(_get_minute_choices, _set_minute_choices)\n\n\nclass DurationField(duration.DurationField):\n \"\"\"\n Model field for duration with hour/minute choice form.\n \"\"\"\n def formfield(self, **kwargs):\n \"\"\"\n The default form field of a :class:`.DurationField` is a\n :class:`.DurationFormField`.\n \"\"\"\n defaults = {'form_class': DurationFormField}\n defaults.update(kwargs)\n return super(DurationField, self).formfield(**defaults)\n\n\nadd_introspection_rules([], [r'^gridplatform.utils.fields.DurationField$'])\n\n\nclass PercentField(models.DecimalField):\n \"\"\"\n A :class:`~django.db.models.DecimalField` with three digits before\n decimal marker, to include special case of 100%.\n \"\"\"\n DEFAULT_VALIDATORS = [\n validators.MaxValueValidator(Decimal('100.0')),\n validators.MinValueValidator(Decimal('0.0')),\n ]\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n :keyword default: Default value is 0%.\n :keyword validators: Default validators allow values in the range\n 0% ... 100%.\n \"\"\"\n defaults = {\n 'max_digits': 4,\n 'decimal_places': 1,\n 'default': Decimal('0.0'),\n 'validators': self.DEFAULT_VALIDATORS,\n }\n defaults.update(kwargs)\n return super(PercentField, self).__init__(*args, **defaults)\n\nadd_introspection_rules([], [r'^gridplatform.utils.fields.PercentField$'])\n\n\nclass ImageFieldWithLoadCheck(forms.ImageField):\n \"\"\"\n Image Form field with check for corrupted image\n \"\"\"\n def to_python(self, data):\n \"\"\"\n :raise ValidationError: If ``data`` is a corrupted image.\n \"\"\"\n f = super(ImageFieldWithLoadCheck, self).to_python(data)\n if f is None:\n return None\n # We need to get a file object for Pillow. We might have a path or\n # we might have to read the data into memory.\n if hasattr(data, 'temporary_file_path'):\n file = data.temporary_file_path()\n else:\n if hasattr(data, 'read'):\n file = BytesIO(data.read())\n else:\n file = BytesIO(data['content'])\n try:\n Image.open(file).load()\n except Exception:\n # Pillow doesn't recognize it as an image.\n six.reraise(ValidationError, ValidationError(\n _('The image you have uploaded is corrupted'),\n code='invalid_image',\n ), sys.exc_info()[2])\n\n if hasattr(f, 'seek') and callable(f.seek):\n f.seek(0)\n return f\n\n\nclass ImageModelFieldWithLoadCheck(models.ImageField):\n \"\"\"\n Image model field to set ImageFieldWithLoadCheck as default formfield\n \"\"\"\n def formfield(self, **kwargs):\n \"\"\"\n The form field of an :class:`.ImageModelFieldWithLoadCheck` is a\n :class:`.ImageFieldWithLoadCheck`.\n \"\"\"\n defaults = {'form_class': ImageFieldWithLoadCheck}\n defaults.update(kwargs)\n return super(ImageModelFieldWithLoadCheck, self).formfield(**defaults)\n\n\nadd_introspection_rules([], [\n r'^gridplatform.utils.fields.ImageModelFieldWithLoadCheck$'])\n\n\nclass BigAutoField(models.AutoField):\n \"\"\"\n from https://djangosnippets.org/snippets/1244/\n\n Updated to work with present version of Python and Django, at the expense\n of losing support for other database backends than postgresql.\n \"\"\"\n\n def db_type(self, connection):\n # only support for postgres\n return 'bigserial'\n\n def get_internal_type(self):\n return \"BigAutoField\"\n\n def to_python(self, value):\n if value is None:\n return value\n try:\n return long(value)\n except (TypeError, ValueError):\n raise ValidationError(\n _(\"This value must be a long integer.\"))\n\n\nadd_introspection_rules([], [\n r'^gridplatform.utils.fields.BigAutoField$'])\n\n\nclass BuckinghamField(models.CharField):\n \"\"\"\n Field for strings representing Buckingham units and validated as\n such.\n \"\"\"\n def __init__(self, *args, **kwargs):\n defaults = {'max_length': 100}\n defaults.update(kwargs)\n super(BuckinghamField, self).__init__(*args, **defaults)\n\n def validate(self, value, model_instance):\n \"\"\"\n :raise ValidationError: If given value is not a valid Buckingham\n unit.\n \"\"\"\n if value:\n try:\n unitconversion.PhysicalQuantity(1, value)\n except:\n raise ValidationError('invalid unit %s' % value)\n super(BuckinghamField, self).validate(value, model_instance)\n\n def get_prep_value(self, value):\n \"\"\"\n Overload of :meth:`django.db.models.CharField.get_prep_value` to\n make sure that no invalid buckingham unit is saved ever.\n \"\"\"\n unitconversion.PhysicalQuantity(1, value)\n return super(BuckinghamField, self).get_prep_value(value)\n\n\nadd_introspection_rules([], [\n r\"^gridplatform\\.utils\\.fields\\.BuckinghamField\"])\n" }, { "alpha_fraction": 0.663484513759613, "alphanum_fraction": 0.6658711433410645, "avg_line_length": 37.09090805053711, "blob_id": "35d3e92e0b7b7b2876b14e78137fff164e5f8563", "content_id": "8400e71967a125e389c9b714bf04d97feae5e4d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2933, "license_type": "no_license", "max_line_length": 74, "num_lines": 77, "path": "/legacy/measurementpoints/__init__.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom gridplatform.utils import utilitytypes\n\nfrom .fields import DataRoleField\n\n\ndef default_unit_for_data_series(data_role, utility_type=None):\n \"\"\"\n Default unit for L{DataSeries} given a data role and optionally a data\n origin.\n\n @param data_role: A data role (see L{DataRoleField}) to lookup the\n default data series unit for.\n\n @param utility_type: A member of L{utilitytypes.METER_CHOICES} to\n further narrow down the default data series unit.\n\n @precondition: The C{utility_type} argument is required for\n C{DataRoleField.CONSUMPTION} and C{DataRoleField.CO2_QUOTIENT}\n C{data_role}s, and otherwise ignored.\n\n @precondition: When C{utility_type} is given it must be in\n L{utilitytypes.METER_CHOICES}.\n\n @return: Returns a default unit for L{DataSeries} in the form of a\n L{buckingham} unit string.\n\n @deprecated: Some data roles may be meaningfull with different units\n that are not compatible with each other. Most of the time we would be\n better of not to use this method at all.\n \"\"\"\n assert utility_type is None or utility_type in (\n db_value for db_value, _ in utilitytypes.METER_CHOICES), \\\n 'invalid utility_type %d for this function' % utility_type\n\n assert data_role not in \\\n [DataRoleField.CONSUMPTION] or \\\n utility_type is not None, 'utility_type required for ' \\\n 'data_role %d' % data_role\n\n unit_map = {\n DataRoleField.CO2: 'gram',\n DataRoleField.CURRENT: 'milliampere',\n DataRoleField.EMPLOYEES: 'none',\n DataRoleField.FREQUENCY: 'millihertz',\n DataRoleField.MASS: 'gram',\n DataRoleField.POWER: 'milliwatt',\n DataRoleField.PRESSURE: 'millibar',\n DataRoleField.STATE: 'none',\n DataRoleField.ABSOLUTE_TEMPERATURE: 'millikelvin',\n DataRoleField.RELATIVE_TEMPERATURE: 'millikelvin',\n DataRoleField.TIME: 'second',\n DataRoleField.VOLTAGE: 'millivolt',\n DataRoleField.VOLUME_FLOW: 'milliliter*hour^-1',\n }\n\n if utility_type in [utilitytypes.METER_CHOICES.electricity,\n utilitytypes.METER_CHOICES.district_heating]:\n unit_map.update({\n DataRoleField.CONSUMPTION: 'milliwatt*hour',\n DataRoleField.PRODUCTION_ENPI: 'milliwatt*hour*unit^-1'\n })\n elif utility_type == utilitytypes.METER_CHOICES.gas:\n unit_map.update({\n DataRoleField.CONSUMPTION: 'milliliter',\n DataRoleField.PRODUCTION_ENPI: 'milliliter*unit^-1'\n })\n elif utility_type in [utilitytypes.METER_CHOICES.water,\n utilitytypes.METER_CHOICES.oil]:\n unit_map.update({\n DataRoleField.CONSUMPTION: 'milliliter',\n DataRoleField.PRODUCTION_ENPI: 'milliliter*unit^-1'\n })\n return unit_map[data_role]\n" }, { "alpha_fraction": 0.6317460536956787, "alphanum_fraction": 0.632539689540863, "avg_line_length": 30.5, "blob_id": "338fdb8132530a5b940c4e901a80d8df475f30c0", "content_id": "be9e348017cb1e5fc4fa2b395aab0be8f92603e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 76, "num_lines": 40, "path": "/gridplatform/jserror/views.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\n\nfrom django.core.mail import mail_admins\nfrom django.http import HttpResponse\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.http import require_POST\nfrom gridplatform.trackuser import get_customer\n\n\n@require_POST\ndef jserror(request):\n \"\"\"\n Format an error from JavaScript and send it to settings.ADMINS --- where\n normal server errors are sent.\n\n Expects to receive a JSON dictionary with keys \"errorMsg\", \"url\" and\n \"lineNumber\" from the client. \"Invalid\" requests --- non-JSON data,\n expected keys not present --- are ignored.\n \"\"\"\n try:\n data = json.loads(request.body)\n context = {\n 'message': data['message'],\n 'url': data['url'],\n 'line': data['line'],\n 'location': data['location'],\n 'customer': get_customer(),\n 'user': request.user,\n 'user_agent': request.META.get('HTTP_USER_AGENT', ''),\n }\n except (ValueError, KeyError):\n pass\n else:\n text = render_to_string('jserror/mail.txt', context)\n mail_admins('JS ERROR', text)\n return HttpResponse()\n" }, { "alpha_fraction": 0.5167953968048096, "alphanum_fraction": 0.5254176259040833, "avg_line_length": 29.420764923095703, "blob_id": "ecba0f4b4990fc412aed3bbf45face50f4f0eca1", "content_id": "0278445afe861de5024a0ed1abccc99759c373c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5567, "license_type": "no_license", "max_line_length": 89, "num_lines": 183, "path": "/scnordic-bridge/utils/pyfina.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"\n\n This code is released under the GNU Affero General Public License.\n \n OpenEnergyMonitor project:\n http://openenergymonitor.org\n\n\"\"\"\n\nimport struct, math, os\n\nclass pyfina(object):\n\n # Data directory of pyfina files\n datadir = \"\"\n \n # Cache meta data in memory\n metadata_cache = {}\n \n # Buffer timeseries data\n buffers = {}\n \n def __init__(self,datadir):\n self.buffers = {}\n self.datadir = datadir\n\n # Prepare inserts datapoint into in-memory data buffer\n # Data is then saved to disk using the save method \n def prepare(self,filename,timestamp,value,interval):\n \n if not value:\n return False\n \n # 1) Load meta data\n \n meta = self.get_meta(filename)\n \n if not meta:\n meta = {\n 'interval': interval,\n 'start_time': math.floor(timestamp / interval) * interval\n }\n self.create_meta(filename,meta)\n\n # Load meta data\n meta['npoints'] = self.get_npoints(filename)\n \n # 2) Write datapoint to buffer and padding if needed\n \n pos = int(math.floor((timestamp - meta['start_time']) / meta['interval']))\n last_pos = meta['npoints'] - 1;\n \n # Implementation does not currently allow for updating existing values\n # Ensure that new value is a new value\n if pos>last_pos:\n \n npadding = (pos - last_pos)-1\n \n if not filename in self.buffers:\n self.buffers[filename] = \"\"\n \n if npadding>0:\n for n in range(npadding):\n self.buffers[filename] += struct.pack(\"f\",float('nan'))\n \n self.buffers[filename] += struct.pack(\"f\",float(value))\n\n\n # Save data in data buffers to disk\n # Writing data in larger blocks saves reduces disk write load as \n # filesystems have a minimum IO size which are usually 512 bytes or more.\n def save(self):\n byteswritten = 0\n for name, data in self.buffers.iteritems():\n fh = open(self.datadir+name+\".dat\",\"ab\")\n fh.write(data)\n fh.close()\n \n byteswritten += len(data)\n\n # Reset buffers\n self.buffers = {}\n \n return byteswritten\n \n \n def get_npoints(self,filename):\n\n bytesize = 0\n \n if os.path.isfile(self.datadir+filename+\".dat\"):\n bytesize += os.stat(self.datadir+filename+\".dat\").st_size\n \n if filename in self.buffers:\n bytesize += len(self.buffers[filename])\n \n return int(math.floor(bytesize / 4.0))\n \n \n def create_meta(self,filename,meta):\n # Create meta data file\n fh = open(self.datadir+filename+\".meta\",\"ab\")\n fh.write(struct.pack(\"I\",meta['start_time']))\n fh.write(struct.pack(\"I\",meta['interval']))\n fh.close()\n \n # Save metadata to cache\n self.metadata_cache[filename] = meta\n \n \n def get_meta(self,filename):\n \n # Load metadata from cache if it exists\n if filename in self.metadata_cache:\n return self.metadata_cache[filename]\n \n elif os.path.isfile(self.datadir+filename+\".meta\"):\n # Open and read meta data file\n # The start_time and interval are saved as two consequative unsigned integers\n fh = open(self.datadir+filename+\".meta\",\"rb\")\n fh.seek(8)\n tmp = struct.unpack(\"II\",fh.read(8))\n fh.close()\n \n meta = {'start_time': tmp[1], 'interval': tmp[0]}\n \n # Save to metadata_cache so that we dont need to open the file next time\n self.metadata_cache[filename] = meta\n return meta\n else:\n return False\n \n \n def data(self,filename,start,end):\n\n start = float(start) / 1000.0\n end = float(end) / 1000.0\n outinterval = int((end - start) / 800)\n \n meta = self.get_meta(filename)\n bytesize = os.stat(self.datadir+filename+\".dat\").st_size\n meta['npoints'] = int(bytesize/4.0)\n\n # If start is 0 then set start to the start time of the feed\n if start==0 or start<meta['start_time']:\n start = meta['start_time']\n \n # If end is 0 set the end time to the end of the feed\n if end==0:\n end = meta['start_time'] + (meta['interval'] * meta['npoints'])\n \n startpos = math.ceil((start - meta['start_time']) / meta['interval'])\n \n \n skip_size = 1\n \n data = []\n timestamp = 0\n i = 0\n \n fh = open(self.datadir+filename+\".dat\",\"rb\")\n while timestamp<=end:\n # position steps forward by skipsize every loop\n pos = int(startpos + (i * skip_size))\n\n # Exit the loop if the position is beyond the end of the file\n if (pos > meta['npoints']-1):\n break;\n\n # read from the file\n fh.seek(pos*4)\n val = struct.unpack(\"f\",fh.read(4))\n\n # calculate the datapoint time\n timestamp = int(meta['start_time'] + pos * meta['interval'])\n\n # add to the data array if its not a nan value\n if not math.isnan(val[0]):\n data.append([timestamp*1000,val[0]])\n\n i += 1\n \n return data\n" }, { "alpha_fraction": 0.6375510096549988, "alphanum_fraction": 0.6494460701942444, "avg_line_length": 39.44811248779297, "blob_id": "a2bb99d8baa23f402330c6bf9987b1e76618eb1b", "content_id": "39b50a1304f188a726b049ecefa1c784ff092265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8575, "license_type": "no_license", "max_line_length": 78, "num_lines": 212, "path": "/legacy/indexes/models/test_datasourceadapter.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\n\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\nimport pytz\n\nfrom gridplatform.datasources.models import DataSource\nfrom gridplatform.datasources.models import RawData\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.unitconversion import PhysicalQuantity\nfrom legacy.measurementpoints.fields import DataRoleField\n\nfrom .datasourceadapter import DataSourceTariffAdapter\nfrom .datasourceadapter import DataSourceCo2ConversionAdapter\n\n\nclass DataSourceMock(DataSource):\n class Meta:\n proxy = True\n\n def __unicode__(self):\n return 'DATASOURCEMOCK'\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DataSourceTariffAdapterTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*gigawatt^-1*hour^-1')\n self.adapter = DataSourceTariffAdapter.objects.create(\n data_format=DataSourceTariffAdapter.DATASOURCEADAPTER,\n datasource=self.datasource,\n unit=self.datasource.unit,\n role=DataRoleField.ELECTRICITY_TARIFF,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n def test_get_samples_no_rawdata(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n self.assertEqual(\n [],\n list(self.adapter.get_samples(from_timestamp, to_timestamp)))\n\n def test_get_samples_rawdata(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n self.datasource.rawdata_set.bulk_create(\n [\n RawData(\n timestamp=from_timestamp + datetime.timedelta(hours=h),\n value=h,\n datasource=self.datasource)\n for h in range(24)])\n\n self.assertEqual(\n [\n self.adapter.create_range_sample(\n from_timestamp + datetime.timedelta(hours=h),\n from_timestamp + datetime.timedelta(hours=h + 1),\n PhysicalQuantity(h, self.adapter.unit))\n for h in range(24)],\n list(self.adapter.get_samples(from_timestamp, to_timestamp)))\n\n def test_unicode(self):\n unicode(self.adapter)\n\n def test_get_preferred_unit_converter_gives_dkk_pr_kwh(self):\n quantity = PhysicalQuantity(1, 'currency_dkk*kilowatt^-1*hour^-1')\n converter = self.adapter.get_preferred_unit_converter()\n self.assertEqual(1, converter.extract_value(quantity))\n unicode(converter.get_display_unit())\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass DataSourceCo2ConversionAdapterTest(TestCase):\n def setUp(self):\n self.timezone = pytz.timezone('Europe/Copenhagen')\n self.datasource = DataSourceMock.objects.create(\n unit='gram*kilowatt^-1*hour^-1')\n self.adapter = DataSourceCo2ConversionAdapter.objects.create(\n data_format=DataSourceCo2ConversionAdapter.DATASOURCEADAPTER,\n datasource=self.datasource,\n unit=self.datasource.unit,\n role=DataRoleField.CO2_QUOTIENT,\n timezone=pytz.utc,\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.unknown)\n\n def test_get_samples_no_rawdata(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n self.assertEqual(\n [],\n list(self.adapter.get_samples(from_timestamp, to_timestamp)))\n\n def test_get_samples_rawdata(self):\n from_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 1))\n to_timestamp = self.timezone.localize(datetime.datetime(2014, 1, 2))\n\n self.datasource.rawdata_set.bulk_create(\n [\n RawData(\n timestamp=from_timestamp + datetime.timedelta(\n minutes=5 * i),\n value=i,\n datasource=self.datasource)\n for i in range(24 * 60 / 5)])\n\n self.assertEqual(\n [\n self.adapter.create_range_sample(\n from_timestamp + datetime.timedelta(minutes=5 * i),\n from_timestamp + datetime.timedelta(minutes=5 * (i + 1)),\n PhysicalQuantity(i, self.adapter.unit))\n for i in range(24 * 60 / 5)],\n list(self.adapter.get_samples(from_timestamp, to_timestamp)))\n\n def test_unicode(self):\n unicode(self.adapter)\n\n\n@override_settings(ENCRYPTION_TESTMODE=True)\nclass AutocreateDataSourceAdapterTest(TestCase):\n def test_electricity_datasourceco2conversionadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='gram*kilowatt^-1*hour^-1')\n\n self.assertTrue(\n DataSourceCo2ConversionAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.\n electricity,\n datasource=self.datasource).exists())\n\n def test_district_heating_datasourceco2conversionadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='gram*kilowatt^-1*hour^-1')\n\n self.assertTrue(\n DataSourceCo2ConversionAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.\n district_heating,\n datasource=self.datasource).exists())\n\n def test_gas_datasourceco2conversionadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='gram*meter^-3')\n\n self.assertTrue(\n DataSourceCo2ConversionAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas,\n datasource=self.datasource).exists())\n\n def test_oil_datasourceco2conversionadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='gram*meter^-3')\n\n self.assertTrue(\n DataSourceCo2ConversionAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil,\n datasource=self.datasource).exists())\n\n def test_gas_datasourcetariffadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*meter^-3')\n\n self.assertTrue(\n DataSourceTariffAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.gas,\n datasource=self.datasource).exists())\n\n def test_oil_datasourcetariffadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*meter^-3')\n\n self.assertTrue(\n DataSourceTariffAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.oil,\n datasource=self.datasource).exists())\n\n def test_water_datasourcetariffadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*meter^-3')\n\n self.assertTrue(\n DataSourceTariffAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.water,\n datasource=self.datasource).exists())\n\n def test_electricity_datasourcetariffadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*kilowatt^-1*hour^-1')\n\n self.assertTrue(\n DataSourceTariffAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n datasource=self.datasource).exists())\n\n def test_district_heating_datasourcetariffadapter_created(self):\n self.datasource = DataSourceMock.objects.create(\n unit='currency_dkk*kilowatt^-1*hour^-1')\n\n self.assertTrue(\n DataSourceTariffAdapter.objects.subclass_only().filter(\n utility_type=utilitytypes.OPTIONAL_METER_CHOICES.\n district_heating,\n datasource=self.datasource).exists())\n" }, { "alpha_fraction": 0.6094674468040466, "alphanum_fraction": 0.61834317445755, "avg_line_length": 20.125, "blob_id": "99c92a9c978d884559c7c5cd6404634fc62d1100", "content_id": "69c628b6df240cf23eee6f99e90646b0afcaabdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 338, "license_type": "no_license", "max_line_length": 46, "num_lines": 16, "path": "/emonhub/conf/nodes/emonpi_auto_add_nodes.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\nemonhub_location=/home/pi/data/emonhub.conf\n\nmax=31\nfor var in `seq 2 $max`\ndo\n if ! grep \"\\[$var\\]\" $emonhub_location; then\n if [ -f $var ]; then\n cat $var >> $emonhub_location\n echo \"\">>$emonhub_location\n echo \"Added node $var to emonhub.conf\"\n fi\n else\n echo \"Node $var already present\"\n fi\ndone\n" }, { "alpha_fraction": 0.533496618270874, "alphanum_fraction": 0.5422424077987671, "avg_line_length": 34.28395080566406, "blob_id": "57dbe07b57bdb492bdb72d2b1406e84ea763d822", "content_id": "6654918a3de1d6acef9958e953df34a12e54e0c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5717, "license_type": "no_license", "max_line_length": 102, "num_lines": 162, "path": "/emonhub/src/interfacers/EmonHubEmoncmsHTTPInterfacer.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "\"\"\"class EmonHubEmoncmsHTTPInterfacer\n\"\"\"\nimport time\nimport json\nimport urllib2\nimport httplib\nfrom pydispatch import dispatcher\nfrom emonhub_interfacer import EmonHubInterfacer\n\nclass EmonHubEmoncmsHTTPInterfacer(EmonHubInterfacer):\n\n def __init__(self, name):\n # Initialization\n super(EmonHubEmoncmsHTTPInterfacer, self).__init__(name)\n \n self._name = name\n \n self._settings = {\n 'subchannels':['ch1'],\n 'pubchannels':['ch2'],\n \n 'apikey': \"\",\n 'url': \"http://emoncms.org\",\n 'senddata': 1,\n 'sendstatus': 0,\n 'sendinterval': 30\n }\n \n self.buffer = []\n self.lastsent = time.time()\n self.lastsentstatus = time.time()\n\n def receiver(self, cargo):\n \n # Create a frame of data in \"emonCMS format\"\n f = []\n f.append(int(cargo.timestamp))\n f.append(cargo.nodeid)\n for i in cargo.realdata:\n f.append(i)\n if cargo.rssi:\n f.append(cargo.rssi)\n\n self._log.debug(str(cargo.uri) + \" adding frame to buffer => \"+ str(f))\n \n # Append to bulk post buffer\n self.buffer.append(f)\n \n def action(self):\n \n now = time.time()\n \n if (now-self.lastsent) > (int(self._settings['sendinterval'])):\n self.lastsent = now\n # print json.dumps(self.buffer)\n if int(self._settings['senddata']):\n self.bulkpost(self.buffer)\n self.buffer = []\n \n if (now-self.lastsentstatus)> (int(self._settings['sendinterval'])):\n self.lastsentstatus = now\n if int(self._settings['sendstatus']):\n self.sendstatus()\n \n def bulkpost(self,databuffer):\n \n if not 'apikey' in self._settings.keys() or str.__len__(str(self._settings['apikey'])) != 32 \\\n or str.lower(str(self._settings['apikey'])) == 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx':\n return\n \n data_string = json.dumps(databuffer, separators=(',', ':'))\n \n # Prepare URL string of the form\n # http://domain.tld/emoncms/input/bulk.json?apikey=12345\n # &data=[[0,10,82,23],[5,10,82,23],[10,10,82,23]]\n # &sentat=15' (requires emoncms >= 8.0)\n\n # time that the request was sent at\n sentat = int(time.time())\n\n # Construct post_url (without apikey)\n post_url = self._settings['url']+'/input/bulk'+'.json?apikey='\n post_body = \"data=\"+data_string+\"&sentat=\"+str(sentat)\n\n # logged before apikey added for security\n self._log.info(\"sending: \" + post_url + \"E-M-O-N-C-M-S-A-P-I-K-E-Y&\" + post_body)\n\n # Add apikey to post_url\n post_url = post_url + self._settings['apikey']\n\n # The Develop branch of emoncms allows for the sending of the apikey in the post\n # body, this should be moved from the url to the body as soon as this is widely\n # adopted\n\n reply = self._send_post(post_url, post_body)\n if reply == 'ok':\n self._log.debug(\"acknowledged receipt with '\" + reply + \"' from \" + self._settings['url'])\n return True\n else:\n self._log.warning(\"send failure: wanted 'ok' but got '\" +reply+ \"'\")\n \n def _send_post(self, post_url, post_body=None):\n \"\"\"\n\n :param post_url:\n :param post_body:\n :return: the received reply if request is successful\n \"\"\"\n \"\"\"Send data to server.\n\n data (list): node and values (eg: '[node,val1,val2,...]')\n time (int): timestamp, time when sample was recorded\n\n return True if data sent correctly\n\n \"\"\"\n\n reply = \"\"\n request = urllib2.Request(post_url, post_body)\n try:\n response = urllib2.urlopen(request, timeout=60)\n except urllib2.HTTPError as e:\n self._log.warning(self.name + \" couldn't send to server, HTTPError: \" +\n str(e.code))\n except urllib2.URLError as e:\n self._log.warning(self.name + \" couldn't send to server, URLError: \" +\n str(e.reason))\n except httplib.HTTPException:\n self._log.warning(self.name + \" couldn't send to server, HTTPException\")\n except Exception:\n import traceback\n self._log.warning(self.name + \" couldn't send to server, Exception: \" +\n traceback.format_exc())\n else:\n reply = response.read()\n finally:\n return reply\n \n def sendstatus(self):\n if not 'apikey' in self._settings.keys() or str.__len__(str(self._settings['apikey'])) != 32 \\\n or str.lower(str(self._settings['apikey'])) == 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx':\n return\n \n # MYIP url\n post_url = self._settings['url']+'/myip/set.json?apikey='\n # Print info log\n self._log.info(\"sending: \" + post_url + \"E-M-O-N-C-M-S-A-P-I-K-E-Y\")\n # add apikey\n post_url = post_url + self._settings['apikey']\n # send request\n reply = self._send_post(post_url,None)\n \n def set(self, **kwargs):\n for key,setting in self._settings.iteritems():\n if key in kwargs.keys():\n # replace default\n self._settings[key] = kwargs[key]\n \n # Subscribe to internal channels\n for channel in self._settings[\"subchannels\"]:\n dispatcher.connect(self.receiver, channel)\n self._log.debug(self._name+\" Subscribed to channel' : \" + str(channel))\n\n" }, { "alpha_fraction": 0.6208076477050781, "alphanum_fraction": 0.6250513195991516, "avg_line_length": 38.918033599853516, "blob_id": "a661c4306694c19e53979656ea1745bcb5085e68", "content_id": "a04e4fe67be16eb503c169885436c6ce694a035a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7305, "license_type": "no_license", "max_line_length": 79, "num_lines": 183, "path": "/legacy/enpi_reports/forms.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom datetime import datetime\nfrom datetime import time\nfrom datetime import timedelta\n\nfrom django import forms\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ValidationError\nfrom django.forms.models import BaseInlineFormSet\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom extra_views import InlineFormSet\n\nfrom legacy.measurementpoints.proxies import ConsumptionMeasurementPoint\nfrom legacy.measurementpoints.fields import DataRoleField\nfrom gridplatform.utils import utilitytypes\nfrom legacy.measurementpoints.models import DataSeries\nfrom legacy.measurementpoints.models import Link\nfrom gridplatform.trackuser import get_customer\nfrom gridplatform.utils import condense\nfrom gridplatform.utils.relativetimedelta import RelativeTimeDelta\nfrom gridplatform.utils.formsets import SurvivingFormsModelFormSetMixin\n\nfrom .models import ENPIUseArea\nfrom .models import ENPIReport\n\n\nclass BaseENPIUseAreaFormSet(SurvivingFormsModelFormSetMixin,\n BaseInlineFormSet):\n def __init__(self, *args, **kwargs):\n self.measurement_point_queryset = ConsumptionMeasurementPoint.\\\n objects.subclass_only().filter(\n utility_type__in=[\n utilitytypes.OPTIONAL_METER_CHOICES.electricity,\n utilitytypes.OPTIONAL_METER_CHOICES.district_heating\n ],\n hidden_on_reports_page=False).decrypting_order_by(\n 'name')\n\n self.energy_driver_queryset = DataSeries.objects.exclude(\n subclass=ContentType.objects.get_for_model(\n Link, for_concrete_model=False)\n ).filter(\n unit=kwargs.pop('energy_driver_unit'),\n role__in=[\n DataRoleField.EMPLOYEES,\n DataRoleField.AREA,\n DataRoleField.PRODUCTION,\n DataRoleField.HEATING_DEGREE_DAYS]).decrypting_order_by(\n 'name')\n\n super(BaseENPIUseAreaFormSet, self).__init__(*args, **kwargs)\n\n def add_fields(self, form, index):\n \"\"\"\n Override of C{BaseInlineFormSet.add_fields()}.\n\n The parent method is used to add all fields to all forms created by\n C{BaseInlineFormSet}, including the C{empty_form}.\n\n This override is used as a hook to make sure these fields are\n configured correctly. In particular formset specific querysets and\n choices are set on relevant fields.\n \"\"\"\n super(BaseENPIUseAreaFormSet, self).add_fields(form, index)\n\n form.fields['measurement_points'].queryset = \\\n self.measurement_point_queryset\n form.fields['energy_driver'].queryset = \\\n self.energy_driver_queryset\n\n def clean(self):\n super(BaseENPIUseAreaFormSet, self).clean()\n if any(self.errors):\n return\n\n # An enpi report has to include at least one form\n if not self.surviving_forms():\n raise forms.ValidationError(\n _('Include at least one area of energy use'))\n\n\nclass ENPIUseAreaFormSet(InlineFormSet):\n model = ENPIUseArea\n formset_class = BaseENPIUseAreaFormSet\n extra = 1\n\n def get_formset_kwargs(self):\n kwargs = super(ENPIUseAreaFormSet, self).get_formset_kwargs()\n if self.object:\n kwargs['energy_driver_unit'] = self.object.energy_driver_unit\n else:\n kwargs['energy_driver_unit'] = self.kwargs['energy_driver_unit']\n return kwargs\n\n\nclass GenerateENPIReportForm(forms.Form):\n \"\"\"\n A C{Form} for generating a particular EnPI report.\n\n Such a report is generated from a L{ENPIReport} instance,\n C{enpi_report}, a C{from_date} and a C{to_date}.\n \"\"\"\n enpi_report = forms.ModelChoiceField(\n queryset=ENPIReport.objects.none())\n from_date = forms.DateField()\n to_date = forms.DateField()\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Expands the valid choices of L{ENPIReport} instances to all those\n available to current customer.\n \"\"\"\n super(GenerateENPIReportForm, self).__init__(*args, **kwargs)\n self.fields['enpi_report'].queryset = \\\n ENPIReport.objects.filter(customer=get_customer())\n\n def clean(self):\n \"\"\"\n Checks that C{from_date} is before C{to_date} if both are set.\n\n @return: The usual C{cleaned_data} dictionary, but with a few extra key\n value pairs. Notably C{'from_timestamp'}, C{'to_timestamp'} and\n C{'sample_resolution'}.\n \"\"\"\n super(GenerateENPIReportForm, self).clean()\n if self.cleaned_data['from_date'] > self.cleaned_data['to_date']:\n raise ValidationError(\n _(u'The start date must be before the end date.'))\n\n from_date = self.cleaned_data['from_date']\n to_date = self.cleaned_data['to_date']\n timezone = get_customer().timezone\n time_span = to_date - from_date + timedelta(days=1)\n\n if time_span.days > 365 * 2:\n if from_date.day != 1 or from_date.month != 1:\n raise ValidationError(\n _(u'From date must be the first day of the year when '\n u'selecting more than two years'))\n if to_date.day != 31 or to_date.month != 12:\n raise ValidationError(\n _(u'To date must be the last day of the year when '\n u'selecting more than two years'))\n self.cleaned_data['sample_resolution'] = condense.YEARS\n elif time_span.days > 365:\n if from_date.day != 1 or from_date.month not in [1, 4, 7, 10]:\n raise ValidationError(\n _(u'From date must be the first day in a quarter when '\n u'selecting more than one year'))\n\n check_month = to_date + timedelta(days=1)\n if to_date.month == check_month.month or to_date.month not in (\n 3, 6, 9, 12):\n raise ValidationError(\n _(u'To date must be the last day in a quarter when '\n u'selecting more than one year'))\n self.cleaned_data['sample_resolution'] = condense.QUARTERS\n else:\n if from_date.day != 1:\n raise ValidationError(\n _(u'From date must be the first day in a month'))\n\n check_month = to_date + timedelta(days=1)\n if to_date.month == check_month.month:\n raise ValidationError(\n _(u'To date must be the last day in a month'))\n self.cleaned_data['sample_resolution'] = condense.MONTHS\n\n if not self.cleaned_data['enpi_report'].enpiusearea_set.exists():\n raise ValidationError(\n _('This EnPI report does not cover any area of energy use.'))\n\n assert 'sample_resolution' in self.cleaned_data\n self.cleaned_data['from_timestamp'] = timezone.localize(\n datetime.combine(from_date, time()))\n self.cleaned_data['to_timestamp'] = timezone.localize(\n datetime.combine(to_date, time())) + RelativeTimeDelta(days=1)\n\n return self.cleaned_data\n" }, { "alpha_fraction": 0.6465227007865906, "alphanum_fraction": 0.6490984559059143, "avg_line_length": 40.20000076293945, "blob_id": "5c2254a9bcf2e7be3f3b931429b1accd418a5854", "content_id": "20a6bd61937b1ee7baafdf4de6151e2f944c77aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10094, "license_type": "no_license", "max_line_length": 84, "num_lines": 245, "path": "/gridplatform/encryption/fields.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport base64\n\nimport django.db.models\nimport django.forms\nfrom django.utils.translation import ugettext_lazy as _\nfrom south.modelsinspector import add_introspection_rules\n\n\nclass Base64Field(django.db.models.TextField):\n \"\"\"\n Store binary data (bytearrays) as base64-encoded text in the database.\n\n :note: While strings may contain binary data in Python, using strings for\n the binary data, when we also use strings for the base64-encoded data,\n would leave us unable to detect whether a string had already been\n decoded.\n \"\"\"\n # trying to decode and catching the exception might be reasonably reliably\n # for current use, but would break mysteriously for decoded strings that\n # are also valid as base64-encodings of something else...\n\n __metaclass__ = django.db.models.SubfieldBase\n\n def __init__(self, *args, **kwargs):\n # not \"editable\" by default; intended for binary data which does not\n # make sense to use directly in forms\n defaults = {'editable': False}\n defaults.update(kwargs)\n super(Base64Field, self).__init__(*args, **defaults)\n\n def to_python(self, value):\n if isinstance(value, bytearray):\n return value\n return bytearray(base64.decodestring(value))\n\n def get_prep_value(self, value):\n return base64.encodestring(value)\n\n def value_to_string(self, obj):\n value = self._get_val_from_obj(obj)\n return self.get_prep_value(value)\n\n\nadd_introspection_rules([], [\"^gridplatform\\.encryption\\.fields\\.Base64Field\"])\n\n\nclass EncryptionMembersAccessor(object):\n \"\"\"\n Descriptor for accessing encrypted/plaintext values on an object.\n\n This is used for some simple business logic: Modifying the plaintext\n invalidates the ciphertext, modifying the ciphertext invalidates the\n plaintext.\n\n Parameterised on the object member names to read/write --- the logic for\n the plaintext and ciphertext is the same, just with the member names\n swapped.\n\n We assume that the members are accessible directly; in particular, this\n will not work to wrap a field with the same name as itself. For the\n current use, those members will need to be accessible for\n encryption/decryption anyway, as in that case, we *do* add a value for one\n field without invalidating the other, i.e. it should not go through this\n descriptor.\n \"\"\"\n\n def __init__(self, name, other_name):\n self.name = name\n self.other_name = other_name\n\n def __get__(self, obj, type=None):\n if obj is None:\n raise AttributeError('Can only be accessed via an instance.')\n return getattr(obj, self.name)\n\n def __set__(self, obj, value):\n setattr(obj, self.name, value)\n setattr(obj, self.other_name, None)\n\n\nclass EncryptedField(object):\n \"\"\"\n Base class for encrypted fields; wraps its data values in EncryptedData\n objects --- the ciphertext used towards the database; the plaintext used as\n the 'string representation' otherwise.\n\n Rules for conversion between plaintext and ciphertext are implemented by\n the EncryptedData class.\n\n :note: ``field.attname`` and ``field.name`` should be equal; that they *can* be\n set to different values is only relevant for foreign keys; as Django code\n assumes them to be equivalent otherwise.\n\n Interface towards forms:\n\n * form field name is taken from ``field.name``\n * data is read with ``field.value_from_object(obj)``\n * data is written with ``field.save_form_data(obj, val)``\n\n Interface towards serialisation:\n\n * on serialisation, field._get_val_from_obj(obj) is checked for \"primitives\"\n --- the relevant part being that None here means that the result is None\n * if not a \"primitive\", the serialised form is ``field.value_to_string(obj)``\n * data is deserialised with ``field.to_python(val)``\n * deserialised data will be stored/set with ``setattr(obj, field.attname, val)``\n\n For :class:`.EncryptedField`, ``field.name``/``field.attname`` is the name of a\n property which gives the encrypted data in base64-encoded form; so the methods\n inherited from :class:`models.Field` do the right thing.\n \"\"\"\n def __init__(self, *args, **kwargs):\n super(EncryptedField, self).__init__(*args, **kwargs)\n\n if kwargs.get('null', False):\n # We can't have that EncryptedFields are created with null=True.\n # However, that does not apply to south.\n import traceback\n stack = traceback.extract_stack()\n via_south = any([\n filename.endswith(\"site-packages/south/migration/migrators.py\")\n for (filename, line_number, function_name, text)\n in stack])\n assert via_south\n\n def contribute_to_class(self, cls, name):\n \"\"\"\n An ecrypted field, ``field``, will attach to its owning\n L{EncryptedModel} class the following members:\n\n - ``field``: holding the encrypted field value.\n - ``field_plain``: holding the decrypted field value.\n - ``_field_decrypt()``: a field specific private decryption method.\n - ``_field_encrypt()``: a field specific private encryption method.\n\n The ``field`` and ``field_plain`` members are designed so that\n when setting either, the other will be set to ``None``.\n \"\"\"\n if not cls._meta.abstract:\n from .models import EncryptedModel\n # Should only be used on EncryptedModel instances --- this is a\n # sanity check/detector of broken code during development.\n if not issubclass(cls, EncryptedModel):\n # Somewhat complicated check; model classes generated by South\n # should be allowed to work...\n import traceback\n stack = traceback.extract_stack()\n via_south = any([\n filename.endswith(\"site-packages/south/orm.py\")\n for (filename, line_number, function_name, text)\n in stack])\n if not via_south:\n assert issubclass(cls, EncryptedModel), \\\n 'EncryptedField requires a subclass of EncryptedModel'\n # Only act on concrete classes (on abstract base classes, we get\n # called both on the base and on the concrete subclass).\n #\n # The one field becomes 4 members of the model class:\n # * 2 member variables, holding the plaintext and ciphertext.\n # * 2 descriptors, giving access to the member variables with the\n # appropriate business logic --- setting one clears the other,\n # reading a cleared value is an error.\n #\n cipher_member = '_{}_ciphertext'.format(name)\n plain_member = '_{}_plaintext'.format(name)\n # NOTE: Intentionally unwieldy names to discourage use...\n self._ciphertext_attribute = cipher_member\n self._plaintext_attribute = plain_member\n # NOTE: _cipher_property will become the \"real\" name --- using the\n # plain name here means that form fields will get the plain name,\n # but also means that accessing model_obj.name in code gives the\n # encrypted version...\n self._cipher_property = name\n self._plain_property = '{}_plain'.format(name)\n #\n # Set up the descriptors for wrapping the actual data members.\n setattr(cls, self._plain_property,\n EncryptionMembersAccessor(plain_member, cipher_member))\n setattr(cls, self._cipher_property,\n EncryptionMembersAccessor(cipher_member, plain_member))\n # Ensure that we use the business logic for access to the encrypted\n # field towards the database and serialisation. When set,\n # self.name overrides the name parameter to contribute_to_class.\n self.name = self._cipher_property\n super(EncryptedField, self).contribute_to_class(cls, name)\n\n def save_form_data(self, instance, data):\n \"\"\"\n Forms access the \"plaintext\" property, with the same business logic\n as when accessing the specified member name on the model object.\n \"\"\"\n setattr(instance, self._plain_property, data)\n\n def value_from_object(self, instance):\n \"\"\"\n Read \"plaintext\" for use in form.\n \"\"\"\n return getattr(instance, self._plain_property)\n\n def get_internal_type(self):\n \"\"\"\n Always store as \"arbitrary length\" text; trying to give a sensible\n \"max_length\" towards the database becomes too messy with\n base64-encoding and when would entail some hacks to use different\n max_lengths for input-validation and database field length.\n \"\"\"\n return \"TextField\"\n\n\n# Does *not* use the SubfieldBase metaclass --- we need our own magic\n# instead...\nclass EncryptedTextField(EncryptedField, django.db.models.TextField):\n \"\"\"\n TextField with encrypted data via EncryptedField.\n \"\"\"\n description = _('Encrypted text')\n\n\n# Does *not* use the SubfieldBase metaclass --- we need our own magic\n# instead...\nclass EncryptedCharField(EncryptedField, django.db.models.CharField):\n \"\"\"\n CharField with encrypted data via EncryptedField.\n \"\"\"\n description = _(\"Encrypted string (up to %(max_length)s)\")\n\n\n# Does *not* use the SubfieldBase metaclass --- we need our own magic\n# instead...\nclass EncryptedEmailField(EncryptedField, django.db.models.EmailField):\n \"\"\"\n EmailField with encrypted data via EncryptedField.\n \"\"\"\n description = _(\"encrypted E-mail address\")\n\n\nadd_introspection_rules([], [\n \"^gridplatform\\.encryption\\.fields\\.EncryptedTextField\",\n \"^gridplatform\\.encryption\\.fields\\.EncryptedCharField\",\n \"^gridplatform\\.encryption\\.fields\\.EncryptedEmailField\",\n])\n" }, { "alpha_fraction": 0.6465398669242859, "alphanum_fraction": 0.6514203548431396, "avg_line_length": 39.256927490234375, "blob_id": "d607faa17365209bda6eb09fcb17c2d8c403ebc3", "content_id": "92088485daa24365030bdbd8754a43fa0663b321", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15982, "license_type": "no_license", "max_line_length": 85, "num_lines": 397, "path": "/gridplatform/customers/models.py", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport random\n\nimport pytz\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom model_utils import Choices\nfrom model_utils.models import TimeStampedModel\nfrom south.modelsinspector import add_introspection_rules\nfrom timezones2.models import TimeZoneField\n\nfrom gridplatform.encryption.fields import EncryptedCharField\nfrom gridplatform.encryption.fields import EncryptedEmailField\nfrom gridplatform.encryption.models import EncryptedModel\nfrom gridplatform.encryption.models import EncryptionKey\nfrom gridplatform.trackuser import get_user\nfrom gridplatform.utils import deprecated\nfrom gridplatform.utils import utilitytypes\nfrom gridplatform.utils.fields import BuckinghamField\nfrom gridplatform.utils.units import CURRENCY_CHOICES\nfrom gridplatform.utils.units import ENERGY_CHOICES\nfrom gridplatform.utils.units import POWER_CHOICES\nfrom gridplatform.utils.units import TEMPERATURE_CHOICES\nfrom gridplatform.utils.units import VOLUME_CHOICES\nfrom gridplatform.utils.units import VOLUME_FLOW_CHOICES\nfrom gridplatform.utils.units import WATT_HOUR_ENERGY_CHOICES\nfrom gridplatform.utils.units import WATT_POWER_CHOICES\n\nfrom .managers import CustomerManager\n\n\nadd_introspection_rules([], [\"^timezones2\\.models\\.TimeZoneField\"])\n\n\ndef get_default_provider():\n # NOTE: Currently getting id rather than object, to avoid attempting to\n # decrypt, to avoid crashing in existing fixture_hack code.\n from gridplatform.providers.models import Provider\n return Provider.objects.order_by(\n 'id').values_list('id', flat=True).first()\n\n\nclass Customer(EncryptedModel, TimeStampedModel):\n \"\"\"\n Represents a GridManager customer. Customer is the target of foreign keys\n from various other models.\n\n :ivar id: The ``id`` for customers is randomly generated on creation/first\n save. The ``id`` is randomized to hide the number of customers from\n our users.\n :ivar provider: A foreign key to the\n :class:`~gridplatform.providers.models.Provider` that facilitates the\n energy management system to this customer.\n :ivar name:\n :ivar vat: The VAT number of this customer.\n :ivar address:\n :ivar postal_code: The zip code of this customer.\n :ivar city:\n :ivar phone:\n :ivar country_code:\n :ivar timezone: The timezone in which the customer operates.\n\n Details of contact person:\n\n :ivar contact_name:\n :ivar contact_email:\n :ivar contact_phone:\n\n Various preferred units applied in GridPortal 2.0. These are not used\n elsewhere in the gridplatform.\n\n :ivar electricity_instantaneous: Preferred unit for electric power.\n :ivar electricity_consumption: Preferred unit for electric energy.\n :ivar gas_instantaneous: Preferred unit for volume flow of gas.\n :ivar gas_consumption: Preferred unit for gas volume.\n :ivar water_instantaneous: Preferred unit for volume flow of water.\n :ivar water_consumption: Preferred unit for water volume.\n :ivar heat_instantaneous: Preferred unit for thermal power of district heating.\n :ivar heat_consumption: Preferred unit for thermal energy of district heating.\n :ivar temperature: Preferred unit for temperatures. Note that these need\n not be bucking ham units.\n :ivar oil_instantaneous: Preferred unit for volume flow of oil.\n :ivar oil_consumption: Preferred unit for oil volume.\n :ivar currency_unit: Customers unit of currency.\n :ivar electricity_tariff: Default tariff for new electricity measurement points.\n :ivar gas_tariff: Default tariff for new gas measurement points.\n :ivar water_tariff: Default tariff for new water measurement points.\n :ivar heat_tariff: Default tariff for new district heating measurement points.\n :ivar oil_tariff: Default tariff for new oil measurement points.\n\n Filtering specific columns:\n\n :ivar is_active: A Boolean indicating if customer is active. Inactive\n customers will be filtered out by\n :class:`~gridplatform.customers.managers.CustomerManager`.\n\n The units ``\"production_a\"`` ... ``\"production_e\"`` identify per\n customer unit dimensions whose human readable representation is defined by\n the following fields:\n\n :ivar production_a_unit:\n :ivar production_b_unit:\n :ivar production_c_unit:\n :ivar production_d_unit:\n :ivar production_e_unit:\n\n Energy manager specific fields:\n\n Additional meta data fields:\n\n :ivar created_by: The :class:`~gridplatform.users.models.User` that created\n this customer.\n \"\"\"\n id = models.IntegerField(primary_key=True, editable=False)\n provider = models.ForeignKey(\n 'providers.Provider', editable=False, default=get_default_provider)\n name = EncryptedCharField(\n _('name'), max_length=50, blank=False)\n vat = EncryptedCharField(\n _('VAT no.'), max_length=20, blank=True)\n address = EncryptedCharField(\n _('address'), max_length=50, blank=True)\n postal_code = EncryptedCharField(\n _('postal code'), max_length=10, blank=True)\n city = EncryptedCharField(\n _('city'), max_length=30, blank=True)\n phone = EncryptedCharField(\n _('phone'), max_length=50, blank=True)\n country_code = EncryptedCharField(\n _('country code'), max_length=3, blank=True)\n timezone = TimeZoneField()\n # Contact person details\n contact_name = EncryptedCharField(\n _('contact person'), max_length=50, blank=True)\n contact_email = EncryptedEmailField(\n _('e-mail'), max_length=50, blank=True)\n contact_phone = EncryptedCharField(\n _('phone'), max_length=50, blank=True)\n # Preferred units\n electricity_instantaneous = models.CharField(\n _('Electricity instantaneous unit'), choices=WATT_POWER_CHOICES,\n default=\"kilowatt\", max_length=50)\n electricity_consumption = models.CharField(\n _('Electricity consumption unit'), choices=WATT_HOUR_ENERGY_CHOICES,\n default=\"kilowatt*hour\", max_length=50)\n gas_instantaneous = models.CharField(\n _('Gas instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n gas_consumption = models.CharField(\n _('Gas consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n water_instantaneous = models.CharField(\n _('Water instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n water_consumption = models.CharField(\n _('Water consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n heat_instantaneous = models.CharField(\n _('Heat instantaneous unit'), choices=POWER_CHOICES,\n default=\"kilowatt\", max_length=50)\n heat_consumption = models.CharField(\n _('Heat consumption unit'), choices=ENERGY_CHOICES,\n default=\"kilowatt*hour\", max_length=50)\n temperature = models.CharField(\n _('Temperature unit'), choices=TEMPERATURE_CHOICES,\n default=\"celsius\", max_length=50)\n oil_instantaneous = models.CharField(\n _('Oil instantaneous unit'), choices=VOLUME_FLOW_CHOICES,\n default=\"meter*meter*meter*hour^-1\", max_length=50)\n oil_consumption = models.CharField(\n _('Oil consumption unit'), choices=VOLUME_CHOICES,\n default=\"meter*meter*meter\", max_length=50)\n currency_unit = BuckinghamField(_('currency'), choices=CURRENCY_CHOICES,\n default='currency_dkk')\n\n electricity_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"electricity_tariff_set\",\n blank=True, null=True)\n gas_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"gas_tariff_set\",\n blank=True, null=True)\n water_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"water_tariff_set\",\n blank=True, null=True)\n heat_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"heat_tariff_set\",\n blank=True, null=True)\n oil_tariff = models.ForeignKey(\n \"measurementpoints.DataSeries\", related_name=\"oil_tariff_set\",\n blank=True, null=True)\n\n is_active = models.BooleanField(_('is active'), default=True)\n\n production_a_unit = EncryptedCharField(\n _('production A unit'), max_length=50, blank=True)\n\n production_b_unit = EncryptedCharField(\n _('production B unit'), max_length=50, blank=True)\n\n production_c_unit = EncryptedCharField(\n _('production C unit'), max_length=50, blank=True)\n\n production_d_unit = EncryptedCharField(\n _('production D unit'), max_length=50, blank=True)\n\n production_e_unit = EncryptedCharField(\n _('production E unit'), max_length=50, blank=True)\n\n created_by = models.ForeignKey(\n 'users.User',\n related_name='+',\n null=True,\n editable=False)\n\n objects = CustomerManager()\n\n class Meta:\n verbose_name = _('customer')\n verbose_name_plural = _('customers')\n ordering = ['id']\n\n def clean_fields(self, exclude=None):\n \"\"\"\n :raise ValidationError: if an applied production unit is cleared.\n \"\"\"\n super(Customer, self).clean_fields(exclude)\n\n def clean_production_unit(letter):\n do_check_production_unit = (\n exclude is None or exclude is not None and\n 'production_%s_unit' % letter not in exclude)\n production_unit_is_set = getattr(\n self, 'production_%s_unit_plain' % letter)\n data_series_using_production_unit = self.dataseries_set.filter(\n unit='production_%s' % letter)\n\n if do_check_production_unit and \\\n not production_unit_is_set and \\\n data_series_using_production_unit.exists():\n raise ValidationError(\n _(\n 'Production unit {production_unit_letter} is in use '\n 'and cannot be empty').format(\n production_unit_letter=letter.upper()))\n for letter in ['a', 'b', 'c', 'd', 'e']:\n clean_production_unit(letter)\n\n def __unicode__(self):\n return unicode(self.name_plain or self.name)\n\n def save(self, *args, **kwargs):\n \"\"\"\n Initializes ``id`` to something random on initial save.\n \"\"\"\n if not self.id:\n self.created_by = get_user()\n\n # NOTE: Will fail if another customer is assigned the same random\n # ID between the exists-check and the save --- for now, we assume\n # that the occasion of several customers being added in the same\n # millisecond and the random-generator returning the same number\n # for each is sufficiently unlikely that we won't add code to\n # handle it. (... apart from the force_insert, so at least we\n # would get an error rather than overwriting existing data...)\n #\n # ID is random from 1 to 10^8 - 1 inclusive --- printable as 8\n # decimal digits, no customer gets ID 0, representable in signed\n # and unsigned 32-bit.\n\n id = random.randint(1, (10 ** 8) - 1)\n while Customer.objects.filter(id=id).exists():\n id = random.randint(1, (10 ** 8) - 1)\n\n # HACK: Create other customer object to get encryption set up\n # before we actually store encrypted fields\n if self.provider_id:\n tmp_customer = Customer(provider_id=self.provider_id)\n else:\n tmp_customer = Customer()\n tmp_customer.id = id\n tmp_customer.save(force_insert=True, force_update=False)\n self.id = tmp_customer.id\n # NOTE: Create encryption key to enable logic\n # for sharing key with users on provider associated with\n # customer...\n EncryptionKey.generate((Customer, self.id))\n\n opts = kwargs.copy()\n opts.update({'force_insert': False, 'force_update': True})\n super(Customer, self).save(*args, **opts)\n else:\n opts = {'force_update': True}\n opts.update(kwargs)\n super(Customer, self).save(*args, **opts)\n\n @deprecated\n def get_preffered_tariff(self, utility_type):\n if utility_type == utilitytypes.METER_CHOICES.electricity:\n return self.electricity_tariff\n elif utility_type == utilitytypes.METER_CHOICES.gas:\n return self.gas_tariff\n elif utility_type == utilitytypes.METER_CHOICES.water:\n return self.water_tariff\n elif utility_type == utilitytypes.METER_CHOICES.district_heating:\n return self.heat_tariff\n elif utility_type == utilitytypes.METER_CHOICES.oil:\n return self.oil_tariff\n raise ValueError('unsupported utility type: %r' % utility_type)\n\n @deprecated\n def count_measurementpoints(self):\n # WTF? (Number of collections with graphs?)\n return self.collection_set.filter(\n graph__isnull=False).distinct().count()\n\n @deprecated\n def count_collections(self):\n # WTF? (Number of collections without graphs?)\n return self.collection_set.filter(\n graph__isnull=True).distinct().count()\n\n @deprecated\n def count_agents(self):\n return {\n 'total': self.agent_set.count(),\n 'online': self.agent_set.filter(online=True).count(),\n 'offline': self.agent_set.filter(online=False).count(),\n }\n\n @deprecated\n def count_meters(self):\n return {\n 'total': self.meter_set.count(),\n 'online': self.meter_set.filter(online=True).count(),\n 'offline': self.meter_set.filter(online=False).count(),\n }\n\n def now(self):\n \"\"\"\n A :class:`~datetime.datetime` object representing the current time in this\n :class:`.Customer`'s timezone.\n \"\"\"\n tz = self.timezone\n if isinstance(tz, basestring):\n tz = pytz.timezone(tz)\n return tz.normalize(datetime.datetime.now(tz))\n\n def get_encryption_id(self):\n \"\"\"\n Implementation of abstract method declared by\n :class:`gridplatform.encryption.models.EncryptedModel`.\n \"\"\"\n return (Customer, self.id)\n\n def satisfies_search(self, search):\n \"\"\"\n Implementation of interface required by\n :py:func:`gridplatform.utils.views.json_list_response` view function\n decorator.\n\n :param search: A string to search for.\n\n :return: True if the ``search`` argument is found in any relevant\n property of this customer.\n \"\"\"\n elems = [\n self.name_plain,\n self.address_plain,\n self.postal_code_plain,\n self.country_code_plain,\n ]\n search = search.lower()\n return any([search in unicode(elem).lower() for elem in elems])\n\n def get_production_unit_choices(self):\n \"\"\"\n Production unit choices for forms.\n\n :return: A Choices object of non-empty production units. The database\n representation will be the relevant buckingham unit, and the human\n readable representation will be the decrypted contents of the\n corresponding production unit field.\n \"\"\"\n result_tuples = []\n\n for letter in ['a', 'b', 'c', 'd', 'e']:\n plain_text = getattr(self, 'production_%s_unit_plain' % letter)\n unit = 'production_%s' % letter\n if plain_text:\n result_tuples.append((unit, plain_text))\n\n return Choices(*result_tuples)\n" }, { "alpha_fraction": 0.8136932253837585, "alphanum_fraction": 0.8150098919868469, "avg_line_length": 30, "blob_id": "f874b53f7396cc742e5112d852cac43db6040053", "content_id": "f733afa114367b75d21783f151e25c994d455f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 78, "num_lines": 49, "path": "/gridagentserver/agentserver.tac", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# NOTE: this is not intended as a demonstration of correct use of Twisted\n# conventions...\n\nimport logging.config\nimport os\n\nfrom twisted.application import internet, service\nfrom twisted.internet import reactor\nfrom twisted.internet.endpoints import TCP4ClientEndpoint\nfrom twisted.python.log import ILogObserver, PythonLoggingObserver\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'agentserver.settings')\nos.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')\n\nimport configurations.importer\nconfigurations.importer.install()\nfrom agentserver import settings\n\n\nlogging.config.fileConfig('logging.ini')\n\n\nfrom agentserver.amqp import AmqpFactory\nfrom agentserver.twisted_server import AgentProtocolFactory\n\n\napplication = service.Application('gridagent')\n# logging from Twisted to standard Python logging\napplication.setComponent(ILogObserver, PythonLoggingObserver().emit)\n\nagentprotocol_factory = AgentProtocolFactory()\n\nagentService = internet.TCPServer(settings.LISTEN_PORT, agentprotocol_factory)\nagentService.setServiceParent(application)\n\namqp_factory = AmqpFactory(\n vhost=settings.AMQP_VHOST,\n user=settings.AMQP_USER,\n password=settings.AMQP_PASSWORD,\n spec_file=settings.AMQP_SPEC)\n\n# set up circular references...\nagentprotocol_factory.amqp = amqp_factory\namqp_factory.agentprotocol = agentprotocol_factory\n\namqp_endpint = TCP4ClientEndpoint(\n reactor, settings.AMQP_HOST, settings.AMQP_PORT)\namqp_connection = amqp_endpint.connect(amqp_factory)\n# amqp_connection.addCallback(gotProtocol)\n" }, { "alpha_fraction": 0.7235462069511414, "alphanum_fraction": 0.7254528403282166, "avg_line_length": 42.70833206176758, "blob_id": "a8ab4ba04af45274674afa6c25dc899b8b2f4acf", "content_id": "55967f072b0b34b39cbfda4bb8bb4b7f0f53164f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1049, "license_type": "no_license", "max_line_length": 100, "num_lines": 24, "path": "/documentation/source/known_issues.rst", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "============\nKnown issues\n============\n\n\nGridPortal 2.0 Super user can break measurement point groups\n============================================================\n\nCustomer *superusers* that are bound to groups and create new *root* groups or\nmove existing groups to be *root* groups may lead to the absolute order of\n*root* groups for the customer to **not** be well-defined. The reason for this is\nthat the order saved will be constructed taking only those existing groups\nthat are *currently visible* into account. This can lead to several groups\nspecifying the same position at which point the relative order among those is\nunspecified and may vary when loaded/reloaded in different pages or at\ndifferent times. Displaying the *children* of such conflicting groups may also\nmix/associate them wrongly. The feature of restricting a user to a certain\ngroup is inherently broken if that user is a super user.\n\nTo rebuild all the trees run `./manage.py rebuild_group_tree` or use the following Python statement:\n\n::\n\n Collection.tree.rebuild()\n" }, { "alpha_fraction": 0.5820105671882629, "alphanum_fraction": 0.5873016119003296, "avg_line_length": 14.75, "blob_id": "e701a98d7eda953e4353a1a4d645d2698ff782c9", "content_id": "bad4c32a8c1b47130112c6eead7e8266c9f15c15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 189, "license_type": "no_license", "max_line_length": 48, "num_lines": 12, "path": "/compilemessages.sh", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfor d in `find gridplatform -maxdepth 1 -type d`\ndo\n if [ $d = 'gridplatform' ]\n then\n continue\n fi\n cd $d\n django-admin.py compilemessages\n cd -\ndone\n" }, { "alpha_fraction": 0.47458627820014954, "alphanum_fraction": 0.47783687710762024, "avg_line_length": 40.26829147338867, "blob_id": "91d92e62ff75677cc123daafbb37833818005cf9", "content_id": "4cb34958cb0dd537d524a427963e4e3b51731c20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3384, "license_type": "no_license", "max_line_length": 230, "num_lines": 82, "path": "/legacy/manage_measurementpoints/static/measurementpoints.js", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "/*jslint browser: true, devel: true */\n/*global $, jQuery, gettext, */\n\nvar gridportal = gridportal || {};\ngridportal.measurementpoints = gridportal.measurementpoints || {};\n\n// What is the purpose of this function. Please document!\ngridportal.measurementpoints.formEvents = function () {\n 'use strict';\n $('#measurementpoints').on('click', '.add-form', function () {\n var parent = $(this).closest('div'),\n emptyBlock = parent.find('div.empty-form'),\n emptyForm = emptyBlock.children(),\n newForm = emptyForm.clone(),\n totalForms = parent.find('input[name$=\"TOTAL_FORMS\"]'),\n newId = totalForms.val(),\n firstDiv = parent.closest('li').find(':first');\n\n newForm.find('input, select, textarea').each(function () {\n var input = $(this),\n name = input.attr('name');\n\n input.attr('name', input.attr('name').replace('__prefix__', newId));\n input.attr('id', input.attr('id').replace('__prefix__', newId));\n\n });\n\n totalForms.val(parseInt(totalForms.val(), 10) + 1);\n newForm.insertBefore(emptyBlock);\n newForm.find('select').chosen({enable_split_word_search: true, search_contains: true});\n firstDiv.animate({height: firstDiv.next().height()});\n event.preventDefault();\n });\n};\n$(function() {\n $('#measurementpoints').on('click', '[name=show_rate]', function () {\n var checkbox = $(this);\n if (!checkbox.is(':checked') && checkbox.closest('form').find('[name=item_id]').length > 0) {\n dialog = $('<div>').attr('id', 'formDialog').html(gettext(\"Are you sure you want to disable the rate graph?<br>Disabling the rate graph will delete all rate and gauge widgets assosiated with this measurement point!\"));\n dialog.dialog({\n title: gettext(\"Warning\"),\n modal: true,\n width: 350,\n buttons: [\n {\n text: gettext('Ok'),\n click: function () {\n $(this).dialog('close');\n }\n },\n {\n text: gettext('Cancel'),\n click: function () {\n checkbox.prop('checked', true);\n $(this).dialog('close');\n }\n }\n ]\n });\n }\n });\n $('#measurementpoints').on('click', '[name=hidden_on_reports_page]', function () {\n var checkbox = $(this);\n if (checkbox.is(':checked') && checkbox.closest('form').find('[name=used_in_report]').length > 0) {\n dialog = $('<div>').attr('id', 'formDialog').html(gettext(\"You are not allowed to to hide this measurement point from reports while it is used in a report\"));\n dialog.dialog({\n title: gettext(\"Warning\"),\n modal: true,\n width: 350,\n buttons: [\n {\n text: gettext('Ok'),\n click: function () {\n checkbox.prop('checked', false);\n $(this).dialog('close');\n }\n }\n ]\n });\n }\n });\n});\n" }, { "alpha_fraction": 0.6962962746620178, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 15.75, "blob_id": "c4f0c7e192e0fd1fc5b969827e2a246badc9de9c", "content_id": "0fc31c651c5c0c6b428d410127015b2d9bced095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 135, "license_type": "no_license", "max_line_length": 47, "num_lines": 8, "path": "/doc/wifiagent_setup.mdown", "repo_name": "pije76/scportal", "src_encoding": "UTF-8", "text": "# Wifi Agent Software Setup\n\n## Database\n\n### User\n`sudo -u postgres createuser --superuser $USER`\n\n`createdb --encoding=utf-8 agent`\n\n" } ]
515
miguelgondu/qdboard
https://github.com/miguelgondu/qdboard
468723d81973081a7017a153e48af65e94d23bf6
3209de7ffb596742d486527a42760b78a5e30da2
4580e057f3033ab2d2458a0664a001a355f6e897
refs/heads/master
2021-01-05T05:09:02.759595
2019-11-13T16:20:10
2019-11-13T16:20:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4882005751132965, "alphanum_fraction": 0.4882005751132965, "avg_line_length": 27.20833396911621, "blob_id": "24ac0392fdf85802ec83298edb16aa882eaa2a7b", "content_id": "54835a127a42014eedd0bdef83d29ce358a7cfc4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 678, "license_type": "no_license", "max_line_length": 82, "num_lines": 24, "path": "/qdboard/static/js/services.js", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "\nappServices.factory('RunService', function($http) {\n return {\n get: function(id) {\n return $http.get(options.api.base_url + '/runs/' + id);\n },\n\n getArchive: function(id) {\n return $http.get(options.api.base_url + '/runs/' + id + '/archive');\n },\n \n findAll: function() {\n return $http.get(options.api.base_url + '/runs/');\n },\n\n delete: function(id) {\n return $http.delete(options.api.base_url + '/runs/' + id + \"/delete\");\n },\n\n create: function(run) {\n return $http.put(options.api.base_url + '/runs/create', {'run': run});\n }\n\n };\n});\n" }, { "alpha_fraction": 0.5417108535766602, "alphanum_fraction": 0.5566976070404053, "avg_line_length": 34.566036224365234, "blob_id": "0f35f0bb691a8a042ce4af23ec72b2d01c965533", "content_id": "666cd029fa1461abbbe4af3ac29c381ea5aedf7c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15080, "license_type": "no_license", "max_line_length": 180, "num_lines": 424, "path": "/examples/zelda_example.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport os\nimport json\nimport numpy as np\nimport uuid\nimport qdboard\nfrom qdboard.algos.map_elites import MapElites\nfrom qdboard.api import add_run\nimport qdboard.server as server\nfrom qdboard.model import Problem, Dimension, Solution, ImgVisualizer\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport matplotlib.image as mpimg\nfrom PIL import Image\n\n\nclass NoPathError(Exception):\n pass\n\n\nclass Node():\n \"\"\"A node class for A* Pathfinding\"\"\"\n\n def __init__(self, parent=None, position=None):\n self.parent = parent\n self.position = position\n\n self.g = 0\n self.h = 0\n self.f = 0\n\n def __eq__(self, other):\n return self.position == other.position\n\n\n# Define problem to optimize\nclass Zelda(Problem):\n\n def __init__(self, width=13, height=9, b_dims=2, min_fit=-100, max_fit=0, max_danger=24, vary=None):\n super().__init__(f\"Zelda-{width}-{height}D-{b_dims}D\", width*height, b_dims, min_fit, max_fit, continuous=False, blocks=['.','w','1','2','3','g','A','+'])\n self.width = width\n self.height = height\n self.max_danger = max_danger\n self.vary = vary\n\n def evaluate(self, genotype):\n\n free = self.__count(genotype, ['.'])\n danger = self.__danger(genotype)\n if self.vary is None:\n fitness = self.__fitness(genotype)\n else:\n fitness = self.__fitness_similarity(genotype)\n\n #if fitness > 0:\n # self.__print(genotype)\n\n behavior = [\n min(self.max_danger, danger),\n free\n ]\n\n return Solution(str(uuid.uuid1()), genotype, behavior, phenotype=genotype, fitness=fitness, img=None)\n\n def __fitness_similarity(self, genotype):\n diff = [(1 if genotype[i] == self.vary[i] else 0) for i in range(len(genotype))]\n return np.sum(diff) / (self.width * self.height)\n\n def __danger(self, genotype):\n enemies1 = self.__count(genotype, ['1'])\n enemies2 = self.__count(genotype, ['2'])\n enemies3 = self.__count(genotype, ['3'])\n danger = enemies1 * 2 + enemies2 * 3 + enemies3 * 4\n return danger\n\n def __fitness(self, genotype):\n padding = self.__count(genotype, ['w'], padding=True)\n keys = self.__count(genotype, ['+'])\n doors = self.__count(genotype, ['g'])\n agents = self.__count(genotype, ['A'])\n danger = self.__danger(genotype)\n\n path_to_key_bonus = -20\n path_to_door_bonus = -20\n\n if agents == 1:\n\n maze = self.__get_maze(genotype)\n\n agent_location = self.__get_location(genotype, 'A')\n\n if keys == 1:\n key_location = self.__get_location(genotype, '+')\n try:\n from_agent_to_key = self.__astar(maze, agent_location, key_location)\n if from_agent_to_key is not None:\n path_to_key_bonus = len(from_agent_to_key)\n except NoPathError as e:\n pass\n\n if doors == 1:\n door_location = self.__get_location(genotype, 'g')\n try:\n from_key_to_door = self.__astar(maze, key_location, door_location)\n if from_key_to_door is not None:\n path_to_door_bonus = len(from_key_to_door)\n except NoPathError as e:\n pass\n\n danger_bonus = 0\n #if danger > self.max_danger:\n # danger_bonus = self.max_danger - danger\n\n return -abs(agents - 1)*5 - abs(keys - 1)*5 - abs(doors - 1)*5 - (self.width*2 + (self.height-2)*2) + padding + danger_bonus - 20*2 + path_to_key_bonus + path_to_door_bonus\n\n def __get_location(self, genotype, block):\n for y in range(self.height):\n for x in range(self.width):\n i = y*self.width + x\n if genotype[i] == block:\n return (x, y)\n raise Exception(\"No block found of type \" + block)\n\n def __get_maze(self, genotype):\n maze = np.zeros((self.height, self.width))\n for y in range(self.height):\n for x in range(self.width):\n i = y * self.width + x\n if genotype[i] == 'w':\n maze[y][x] = 1\n return maze\n\n def __print(self, genotype):\n print(\"--------------\")\n padding = self.__count(genotype, ['w'], padding=True)\n keys = self.__count(genotype, ['+'])\n doors = self.__count(genotype, ['g'])\n agents = self.__count(genotype, ['A'])\n # enemies = self.__count(genotype, ['1', '2', '3'])\n enemies1 = self.__count(genotype, ['1'])\n enemies2 = self.__count(genotype, ['2'])\n enemies3 = self.__count(genotype, ['3'])\n # blocks = self.__count(genotype, ['w'])\n free = self.__count(genotype, ['.'])\n fitness = self.__fitness(genotype)\n print(f\"FITNESS: {fitness}\")\n print(f\"PADDING: {padding}\")\n print(f\"KEYS: {keys}\")\n print(f\"DOORS: {doors}\")\n print(f\"AGENTS: {agents}\")\n print(f\"ENEMIES1: {enemies1}\")\n print(f\"ENEMIES2: {enemies2}\")\n print(f\"ENEMIES3: {enemies3}\")\n print(f\"FREE: {free}\")\n print(f\"LEVEL:\")\n\n for y in range(self.height):\n line = \"\"\n for x in range(self.width):\n i = y*self.width + x\n line += genotype[i]\n print(line)\n print(\"--------------\")\n fitness = self.__fitness(genotype)\n\n def __count(self, genotype, blocks, padding=False):\n c = 0\n for y in range(self.height):\n for x in range(self.width):\n i = y*self.width + x\n if not padding or (x == 0 or y == 0 or x == self.width-1 or y == self.height-1):\n if genotype[i] in blocks:\n c += 1\n\n return c\n\n def __astar(self, maze, start, end, max_iterations=200):\n \"\"\"Returns a list of tuples as a path from the given start to the given end in the given maze\"\"\"\n\n # Create start and end node\n start_node = Node(None, start)\n start_node.g = start_node.h = start_node.f = 0\n end_node = Node(None, end)\n end_node.g = end_node.h = end_node.f = 0\n\n # Initialize both open and closed list\n open_list = []\n closed_list = []\n\n # Add the start node\n open_list.append(start_node)\n\n adjacent = [(0, -1), (0, 1), (-1, 0), (1, 0)]\n\n # Loop until you find the end\n iterations = 0\n while len(open_list) > 0:\n\n iterations += 1\n\n # Get the current node\n current_node = open_list[0]\n current_index = 0\n for index, item in enumerate(open_list):\n if item.f < current_node.f:\n current_node = item\n current_index = index\n\n # Pop current off open list, add to closed list\n open_list.pop(current_index)\n closed_list.append(current_node)\n\n # Found the goal\n if current_node == end_node:\n path = []\n current = current_node\n while current is not None:\n path.append(current.position)\n current = current.parent\n return path[::-1] # Return reversed path\n\n # Generate children\n children = []\n for new_position in adjacent: # Adjacent squares\n\n # Get node position\n node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])\n\n # Make sure within range\n if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (\n len(maze[len(maze) - 1]) - 1) or node_position[1] < 0:\n continue\n\n # Make sure walkable terrain\n if maze[node_position[0]][node_position[1]] != 0:\n continue\n\n # Create new node\n new_node = Node(current_node, node_position)\n\n # Append\n children.append(new_node)\n\n # Loop through children\n for child in children:\n\n # Child is on the closed list\n for closed_child in closed_list:\n if child == closed_child:\n continue\n\n # Create the f, g, and h values\n child.g = current_node.g + 1\n child.h = ((child.position[0] - end_node.position[0]) ** 2) + (\n (child.position[1] - end_node.position[1]) ** 2)\n child.f = child.g + child.h\n\n # Child is already in the open list\n for open_node in open_list:\n if child == open_node and child.g > open_node.g:\n continue\n\n # Add the child to the open list\n open_list.append(child)\n\n if iterations >= max_iterations:\n raise NoPathError(\"No path \")\n\n\nclass SpriteSheetReader:\n\n def __init__(self, imageName, tileSize):\n self.spritesheet = Image.open(imageName)\n self.tileSize = tileSize\n self.margin = 1\n\n def getTile(self, tileX, tileY):\n posX = (self.tileSize * tileX) + (self.margin * (tileX + 1))\n posY = (self.tileSize * tileY) + (self.margin * (tileY + 1))\n box = (posX, posY, posX + self.tileSize, posY + self.tileSize)\n return self.spritesheet.crop(box)\n\n\nclass SpriteSheetWriter:\n\n def __init__(self, tileSize, width, height):\n self.tileSize = tileSize\n self.width = width\n self.height = height\n self.spritesheet = Image.new(\"RGBA\", (self.width*tileSize, self.height*tileSize), (0, 0, 0, 0))\n self.tileX = 0\n self.tileY = 0\n self.margin = 0\n\n def getCurPos(self):\n self.posX = (self.tileSize * self.tileX) + (self.margin * (self.tileX + 1))\n self.posY = (self.tileSize * self.tileY) + (self.margin * (self.tileY + 1))\n if (self.posX + self.tileSize > self.width*self.tileSize):\n self.tileX = 0\n self.tileY = self.tileY + 1\n self.getCurPos()\n if (self.posY + self.tileSize > self.height*self.tileSize):\n raise Exception('Image does not fit within spritesheet!')\n\n def addImage(self, image):\n self.getCurPos()\n destBox = (self.posX, self.posY, self.posX + image.size[0], self.posY + image.size[1])\n self.spritesheet.paste(image, destBox)\n self.tileX = self.tileX + 1\n\n def save(self, filename):\n self.spritesheet.save(filename)\n\n def close(self):\n self.spritesheet.close()\n\n\nclass ZeldaImgVisualizer(ImgVisualizer):\n\n def __init__(self, path, width=13, height=9):\n super().__init__('ZeldaVisualizer', path)\n self.width = width\n self.height = height\n self.tiles = {\n '.': Image.open('/Users/njustesen/git/qdboard/examples/img/f.png'),\n '1': Image.open('/Users/njustesen/git/qdboard/examples/img/1.png'),\n '2': Image.open('/Users/njustesen/git/qdboard/examples/img/2.png'),\n '3': Image.open('/Users/njustesen/git/qdboard/examples/img/3.png'),\n 'A': Image.open('/Users/njustesen/git/qdboard/examples/img/A.png'),\n 'f': Image.open('/Users/njustesen/git/qdboard/examples/img/f.png'),\n 'g': Image.open('/Users/njustesen/git/qdboard/examples/img/g.png'),\n 'w': Image.open('/Users/njustesen/git/qdboard/examples/img/w.png'),\n '+': Image.open('/Users/njustesen/git/qdboard/examples/img/+.png')\n }\n\n def save_visualization(self, solution):\n fname = os.path.join(self.path, f'{solution.solution_id}.png')\n if not os.path.isfile(fname):\n self.__visualize_level(solution.phenotype, title=str(solution.solution_id))\n\n def get_rel_path(self, solution):\n title = str(solution.solution_id)\n path = os.path.join('static', self.path.split('/static/')[1])\n return os.path.join(path, f'{title}.png')\n\n def __visualize_level(self, level, title=None):\n\n writer = SpriteSheetWriter(24, width=self.width, height=self.height)\n\n for i in range(len(level)):\n writer.addImage(self.tiles[level[i]])\n\n writer.save(os.path.join(self.path, f'{title}.png'))\n writer.close()\n\n\nclass FileHandler:\n\n def load_level(self, path):\n level = []\n with open(path) as f:\n for line in f:\n for c in line:\n if c != '\\n':\n level.append(c)\n return level\n\n\ndef get_data_path(rel_path):\n root_dir = qdboard.__file__.replace(\"__init__.py\", \"\")\n filename = os.path.join(root_dir, rel_path)\n return os.path.abspath(os.path.realpath(filename))\n\n\nconfig_zelda = {\n \"cvt_samples\": 25000,\n \"batch_size\": 100,\n \"random_init\": 50,\n \"random_init_batch\": 50,\n \"sigma_iso\": 0.01,\n \"sigma_line\": 0.2,\n \"dump_period\": 10,\n \"parallel\": True,\n \"cvt_use_cache\": True,\n \"archive_path\": get_data_path(\"map-elites/runs/\"),\n \"centroids_path\": get_data_path(\"map-elites/centroids/\"),\n \"num_niches\": 1000,\n \"num_gens\": 100000,\n \"discrete_muts\": 20,\n \"discrete_mut_prob\": 0.2,\n \"block_probs\": [0.2, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1],\n}\n\nwidth = 13\nheight = 9\nspaces = ((width*height)-(width*2+height*2))\nb_dimensions_zelda = [\n Dimension(\"Danger\", max_value=spaces, min_value=0),\n Dimension(\"Openness\", max_value=spaces, min_value=0),\n]\nrun_id = str(uuid.uuid1())\n\nhuman_level = FileHandler().load_level(get_data_path(\"data/zelda/zelda_lvl0.txt\"))\nproblem_zelda = Zelda(width, height, len(b_dimensions_zelda), min_fit=-150, max_fit=0, max_danger=spaces)\nproblem_zelda_vary = Zelda(width, height, len(b_dimensions_zelda), min_fit=0, max_fit=1, max_danger=spaces, vary=human_level)\nhuman_level_solution = problem_zelda_vary.evaluate(human_level)\n\n'''\ndim_lens = [b_dimensions_zelda[i].max_value - b_dimensions_zelda[i].min_value for i in range(len(b_dimensions_zelda))]\nb_dimensions_zelda_vary = [\n Dimension(\"Danger\", max_value=human_level_solution.behavior[0] + dim_lens[0]/2, min_value=human_level_solution.behavior[0] - dim_lens[0]/2),\n Dimension(\"Openness\", max_value=human_level_solution.behavior[1] + dim_lens[1]/2, min_value=human_level_solution.behavior[1] - dim_lens[1]/2),\n]\n'''\n\nvisualizer = ZeldaImgVisualizer(get_data_path(os.path.join('static/img/zelda/', run_id)))\nalgo_zelda = MapElites(run_id, config_zelda, b_dimensions=b_dimensions_zelda, problem=problem_zelda, img_visualizer=visualizer)\n# algo_zelda = MapElites(run_id, config_zelda, b_dimensions=b_dimensions_zelda, problem=problem_zelda_vary, img_visualizer=visualizer)\nadd_run(algo_zelda)\nalgo_zelda.start()\n\n# Run server\nserver.start_server(debug=True, use_reloader=False, port=5000)\n" }, { "alpha_fraction": 0.5988593101501465, "alphanum_fraction": 0.6356146931648254, "avg_line_length": 28.773584365844727, "blob_id": "852fdc0265651608add9123a07ec3af3960a94dd", "content_id": "92dcf91eae1966e1201dae403aca436a45fe94b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1578, "license_type": "no_license", "max_line_length": 104, "num_lines": 53, "path": "/examples/rastrigin_example.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\nimport math\nimport uuid\nimport qdboard.server as server\nfrom qdboard.model import Problem, Dimension, Solution\nfrom qdboard.algos.map_elites import MapElites\nfrom qdboard.api import add_run\n\n\nclass Rastrigin(Problem):\n\n def __init__(self, x_dims, b_dims, min_fit=-100, max_fit=0):\n super().__init__(f\"Rastrigin-{x_dims}D-{b_dims}D\", x_dims, b_dims, min_fit, max_fit)\n\n def evaluate(self, genotype):\n fitness = self.__rastrigin(genotype)\n behavior = genotype[:2]\n return Solution(uuid.uuid1(), genotype, behavior, phenotype=genotype, fitness=fitness, img=None)\n\n def __rastrigin(self, xx):\n x = xx * 10.0 - 5.0\n f = 10 * x.shape[0]\n for i in range(0, x.shape[0]):\n f += x[i] * x[i] - 10 * math.cos(2 * math.pi * x[i])\n return -f\n\nconfig = {\n \"cvt_samples\": 25000,\n \"batch_size\": 100,\n \"random_init\": 1000,\n \"random_init_batch\": 100,\n \"sigma_iso\": 0.01,\n \"sigma_line\": 0.2,\n \"dump_period\": 100,\n \"parallel\": True,\n \"cvt_use_cache\": True,\n \"archive_path\": \"/Users/njustesen/git/qdboard/qdboard/map-elites/runs/\",\n \"centroids_path\": \"/Users/njustesen/git/qdboard/qdboard/map-elites/centroids/\",\n \"num_niches\": 5000,\n \"num_gens\": 10000\n}\n\nx_dims = 6\nb_dims = 2\nb_dimensions = [Dimension(str(i+1), 0, 1) for i in range(b_dims)]\nproblem = Rastrigin(x_dims, b_dims)\nalgo = MapElites(str(uuid.uuid1()), config, b_dimensions=b_dimensions, problem=problem)\nadd_run(algo)\nalgo.start()\n\n# Run server\nserver.start_server(debug=True, use_reloader=False)\n" }, { "alpha_fraction": 0.4730392098426819, "alphanum_fraction": 0.4828431308269501, "avg_line_length": 20.473684310913086, "blob_id": "cc5fa0adea8b8742ea345846ed3ceb26dbfffe8f", "content_id": "a50680da68ca35d733cd2a3d8440b50595dbbd79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 43, "num_lines": 19, "path": "/setup.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(name='qdboard',\n version=\"0.0.1\",\n include_package_data=True,\n install_requires=[\n 'numpy',\n 'untangle',\n 'Flask',\n 'Jinja2',\n 'python-interface',\n 'stopit',\n 'scikit-learn',\n 'scipy',\n 'matplotlib',\n 'Pillow'\n ],\n packages=find_packages()\n)\n" }, { "alpha_fraction": 0.6261319518089294, "alphanum_fraction": 0.6313065886497498, "avg_line_length": 17.404762268066406, "blob_id": "6b20762f7a5518cfda701a958ae50f9bd81320bd", "content_id": "bbd952f9e9824567c91159c275b3f373e5a5ad50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 79, "num_lines": 42, "path": "/qdboard/api.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "\"\"\"\n==========================\nAuthor: Niels Justesen\nYear: 2018\n==========================\nThis module contains functions to communicate with a game host to manage games.\n\"\"\"\n\nimport pickle\nimport uuid\nfrom qdboard.model import *\nfrom qdboard.algos.map_elites import MapElites\n\n# Store runs in memory\nruns = {}\n\n\ndef add_run(algorithm):\n runs[algorithm.run_id] = algorithm\n\n\ndef remove_run(run_id):\n if run_id in runs:\n del runs[run_id]\n\n\ndef create_run(algorithm):\n runs[algorithm.run_id] = algorithm\n\n\ndef get_runs():\n return [run for key, run in runs.items()]\n\n\ndef get_run(run_id):\n return runs[run_id]\n\n\ndef get_archive(run_id):\n if run_id not in runs:\n raise Exception(f\"Run not found with id {run_id}\")\n return runs[run_id].get_archive()\n" }, { "alpha_fraction": 0.5851601958274841, "alphanum_fraction": 0.5870339274406433, "avg_line_length": 30.585798263549805, "blob_id": "ab198ad45224c89ba85405964aa67cbf37ced376", "content_id": "08028dde58975d103fd71334984ee5909ad76dcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5337, "license_type": "no_license", "max_line_length": 111, "num_lines": 169, "path": "/qdboard/model.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\nimport numpy\nimport os\n\n\nclass Dimension:\n\n def __init__(self, name, min_value, max_value):\n self.name = name\n self.min_value = min_value\n self.max_value = max_value\n\n def to_json(self):\n return {\n 'name': self.name,\n 'min_value': self.min_value,\n 'max_value': self.max_value\n }\n\n\nclass Archive:\n\n def __init__(self, dimensions, cells, solutions):\n self.cells = cells\n self.dimensions = dimensions\n self.solutions = solutions\n self.fitnesses = [solution.fitness for solution in solutions]\n\n def to_json(self):\n return {\n 'cells': [cell.to_json() for cell in list(self.cells.values())],\n #'solutions': [solution.to_json() for solution in self.solutions],\n 'dimensions': [dim.to_json() for dim in self.dimensions],\n 'fitness_std': np.std(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_mean': np.mean(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_min': np.min(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_max': np.max(self.fitnesses) if len(self.fitnesses) > 0 else None\n }\n\n\nclass Cell:\n\n def __init__(self, points, solutions):\n self.points = points\n self.solutions = solutions\n self.fitnesses = [solution.fitness for solution in solutions]\n\n def add_solution(self, solution):\n self.solutions.append(solution)\n self.fitnesses.append(solution.fitness)\n\n def to_json(self):\n return {\n 'points': self.points,\n 'solutions': [solution.to_json() for solution in self.solutions],\n 'fitness_mean': np.mean(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_std': np.std(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_min': np.min(self.fitnesses) if len(self.fitnesses) > 0 else None,\n 'fitness_max': np.max(self.fitnesses) if len(self.fitnesses) > 0 else None\n }\n\n\nclass Solution:\n\n def __init__(self, solution_id, genotype, behavior, fitness, phenotype=None, img=None):\n self.solution_id = solution_id\n self.genotype = genotype\n self.behavior = behavior\n self.fitness = fitness\n self.phenotype = phenotype\n self.img = img\n\n def to_json(self):\n return {\n 'genotype': self.genotype,\n 'behavior': self.behavior,\n 'fitness': self.fitness,\n 'phenotype': self.phenotype,\n 'img': self.img\n }\n\n\nclass QDAlgorithm:\n\n def __init__(self, run_id, config, b_dimensions, problem, img_visualizer=None):\n self.run_id = run_id\n self.config = config\n self.b_dimensions = b_dimensions\n self.b_dims = len(self.b_dimensions)\n self.problem = problem\n self.b_mins = [dimension.min_value for dimension in self.b_dimensions]\n self.b_maxs = [dimension.max_value for dimension in self.b_dimensions]\n self.img_visualizer = img_visualizer\n\n def start(self):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def stop(self):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def get_archive(self):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def is_done(self):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def to_json(self):\n return {\n 'run_id': self.run_id,\n 'b_dimensions': [dim.to_json() for dim in self.b_dimensions],\n 'problem': self.problem.to_json(),\n 'is_done': self.is_done(), # Fix this\n 'b_mins': self.b_mins,\n 'b_maxs': self.b_maxs,\n 'img_visualizer': self.img_visualizer.to_json() if self.img_visualizer is not None else None\n }\n\n\nclass Problem:\n\n def __init__(self, name, x_dims, b_dims, min_fit, max_fit, x_min=0, x_max=1, continuous=True, blocks=None):\n self.name = name\n self.x_dims = x_dims\n self.b_dims = b_dims\n self.continuous = continuous\n self.blocks = blocks\n self.x_min = x_min\n self.x_max = x_max\n self.min_fit = min_fit\n self.max_fit = max_fit\n\n def evaluate(self, genotype):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def evaluate_batch(self, genotype):\n raise NotImplementedError(\"Must be overridden by sub-class\")\n\n def to_json(self):\n return {\n 'name': self.name,\n 'x_dims': self.x_dims,\n 'b_dims': self.b_dims,\n 'continous': self.continuous,\n 'x_min': self.x_min,\n 'x_max': self.x_max,\n 'min_fit': self.min_fit,\n 'max_fit': self.max_fit\n }\n\n\nclass ImgVisualizer:\n\n def __init__(self, name, path):\n self.name = name\n self.path = path\n os.makedirs(path, exist_ok=True)\n\n def save_visualization(self, solution):\n raise Exception('Must be implemented by derived class.')\n\n def get_rel_path(self, solution):\n raise Exception('Must be implemented by derived class.')\n\n def to_json(self):\n return {\n 'name': self.name,\n 'path': self.path\n }" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 10, "blob_id": "32f1ca039e55d2797bf7db83322d4dc30f430405", "content_id": "9dd660e3c7e6b0033605b9198a367f1db2aa37bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11, "license_type": "no_license", "max_line_length": 10, "num_lines": 1, "path": "/README.md", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "# QD Board\n" }, { "alpha_fraction": 0.5339503884315491, "alphanum_fraction": 0.5411570072174072, "avg_line_length": 37.00251388549805, "blob_id": "8e9a40f1f82426f46232463610c6336ce0648e27", "content_id": "071a3b1a538871409c1b79958000d4b3537660b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15125, "license_type": "no_license", "max_line_length": 199, "num_lines": 398, "path": "/qdboard/algos/map_elites.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "from sklearn.neighbors import KDTree\nfrom sklearn.cluster import KMeans\nfrom qdboard.model import *\nimport glob\nimport os\nimport math\nimport time\nimport numpy as np\nfrom multiprocessing import Process, Queue\nfrom scipy.spatial import Voronoi, voronoi_plot_2d\nfrom qdboard.model import QDAlgorithm\nimport multiprocessing\nimport threading\nimport random\nfrom pathlib import Path\nimport pickle\nimport os.path\n\n\nclass MapElites(QDAlgorithm):\n\n def __init__(self, run_id, config, b_dimensions, problem, img_visualizer=None):\n super().__init__(run_id, config, b_dimensions, problem, img_visualizer)\n self.map_elites = MapElitesRunner(run_id, config, b_dimensions, problem, img_visualizer=img_visualizer)\n\n def start(self):\n self.t = threading.Thread(name='child procs', target=self.map_elites.compute)\n #self.p = Process(target=self.map_elites.compute)\n self.t.stop = False\n self.t.start()\n #self.p.start()\n print(\"P started\")\n\n def stop(self):\n #self.p.kill()\n self.t.stop = True\n self.t.join()\n\n def is_done(self):\n latest_gen = self.__latest_gen()\n if latest_gen is None:\n return False\n return latest_gen == self.config['num_gens']\n\n def get_archive(self):\n\n filename = self.map_elites.get_archive_filename()\n latest_gen = self.__latest_gen()\n if latest_gen is None:\n return {}\n\n filename = filename.replace(\"*\", str(latest_gen))\n archive = pickle.load(open(f'{filename}', \"rb\"))\n\n # fit, desc, x = self.__load_data()\n\n filename = self.map_elites.get_centroids_filename()\n centroids = self.map_elites.load_centroids(filename)\n vor = Voronoi(centroids[:, 0:2])\n regions, vertices = self.__voronoi_finite_polygons_2d(vor)\n\n kdt = KDTree(centroids, leaf_size=30, metric='euclidean')\n\n # contours\n solutions = []\n cells = {}\n for i, region in enumerate(regions):\n polygon = vertices[region]\n cells[i] = Cell(polygon.tolist(), solutions=[])\n\n for key, solution in archive.items():\n img = None\n if self.img_visualizer is not None:\n img = self.img_visualizer.get_rel_path(solution)\n s = Solution(solution.solution_id, solution.genotype.tolist(), solution.behavior, solution.fitness, solution.phenotype.tolist(), img=img)\n q = kdt.query([solution.behavior], k=1)\n index = q[1][0][0]\n region = regions[index]\n # polygon = vertices[region]\n cell = cells[index]\n cell.add_solution(s)\n solutions.append(s)\n\n archive = Archive(self.b_dimensions, cells, solutions)\n\n return archive\n\n def __load_data(self):\n filename = self.map_elites.get_archive_filename()\n latest_gen = self.__latest_gen()\n filename = filename.replace(\"*\", str(latest_gen))\n print(\"Loading \", filename)\n data = np.loadtxt(filename, dtype='str')\n fit = data[:, 0:1]\n fit = fit.astype(np.float)\n desc = data[:, 1: self.b_dims + 1]\n desc = desc.astype(np.float)\n x = data[:, self.b_dims + 1:self.b_dims + 1 + self.problem.x_dims]\n #x = x.astype(np.float)\n return fit, desc, x\n\n def __latest_gen(self):\n filename = self.map_elites.get_archive_filename()\n archive_files = glob.glob(filename)\n latest_gen = -1\n for file in archive_files:\n # gen = int(file.split(\".dat\")[0].split(\"_\")[-1])\n gen = int(file.split(\".p\")[0].split(\"_\")[-1])\n if gen > latest_gen:\n latest_gen = gen\n if latest_gen == -1:\n return None\n return latest_gen\n\n def __voronoi_finite_polygons_2d(self, vor, radius=None):\n \"\"\"\n Reconstruct infinite voronoi regions in a 2D diagram to finite\n regions.\n\n Parameters\n ----------\n vor : Voronoi\n Input diagram\n radius : float, optional\n Distance to 'points at infinity'.\n\n Returns\n -------\n regions : list of tuples\n Indices of vertices in each revised Voronoi regions.\n vertices : list of tuples\n Coordinates for revised Voronoi vertices. Same as coordinates\n of input vertices, with 'points at infinity' appended to the\n end.\n\n \"\"\"\n\n if vor.points.shape[1] != 2:\n raise ValueError(\"Requires 2D input\")\n\n new_regions = []\n new_vertices = vor.vertices.tolist()\n\n center = vor.points.mean(axis=0)\n if radius is None:\n radius = vor.points.ptp().max()\n\n # Construct a map containing all ridges for a given point\n all_ridges = {}\n for (p1, p2), (v1, v2) in zip(vor.ridge_points, vor.ridge_vertices):\n all_ridges.setdefault(p1, []).append((p2, v1, v2))\n all_ridges.setdefault(p2, []).append((p1, v1, v2))\n\n # Reconstruct infinite regions\n for p1, region in enumerate(vor.point_region):\n vertices = vor.regions[region]\n\n if all(v >= 0 for v in vertices):\n # finite region\n new_regions.append(vertices)\n continue\n\n # reconstruct a non-finite region\n ridges = all_ridges[p1]\n new_region = [v for v in vertices if v >= 0]\n\n for p2, v1, v2 in ridges:\n if v2 < 0:\n v1, v2 = v2, v1\n if v1 >= 0:\n # finite ridge: already in the region\n continue\n\n # Compute the missing endpoint of an infinite ridge\n\n t = vor.points[p2] - vor.points[p1] # tangent\n t /= np.linalg.norm(t)\n n = np.array([-t[1], t[0]]) # normal\n\n midpoint = vor.points[[p1, p2]].mean(axis=0)\n direction = np.sign(np.dot(midpoint - center, n)) * n\n far_point = vor.vertices[v2] + direction * radius\n\n new_region.append(len(new_vertices))\n new_vertices.append(far_point.tolist())\n\n # sort region counterclockwise\n vs = np.asarray([new_vertices[v] for v in new_region])\n c = vs.mean(axis=0)\n angles = np.arctan2(vs[:, 1] - c[1], vs[:, 0] - c[0])\n new_region = np.array(new_region)[np.argsort(angles)]\n\n # finish\n new_regions.append(new_region.tolist())\n\n return new_regions, np.asarray(new_vertices)\n\n\nclass MapElitesRunner:\n\n def __init__(self, run_id, config, b_dimensions, problem, img_visualizer=None):\n self.run_id = run_id\n self.config = config\n self.b_dimensions = b_dimensions\n self.b_dims = len(self.b_dimensions)\n self.problem = problem\n self.p = None\n self.b_mins = [dimension.min_value for dimension in self.b_dimensions]\n self.b_maxs = [dimension.max_value for dimension in self.b_dimensions]\n # init archive (empty)\n self.img_visualizer = img_visualizer\n self.archive = {}\n\n def __variation_continous(self, x, archive):\n y = x.copy()\n keys = list(archive.keys())\n z = archive[keys[np.random.randint(len(keys))]].genotype\n for i in range(0, len(y)):\n # iso mutation\n a = np.random.normal(0, (self.problem.x_max - self.problem.x_min) / 300.0, 1)\n y[i] = y[i] + a\n # line mutation\n b = np.random.normal(0, 20 * (self.problem.x_max - self.problem.x_min) / 300.0, 1)\n y[i] = y[i] + b * (x[i] - z[i])\n y_bounded = []\n for i in range(0, len(y)):\n elem_bounded = min(y[i], self.problem.x_max)\n elem_bounded = max(elem_bounded, self.problem.x_min)\n y_bounded.append(elem_bounded)\n return np.array(y_bounded)\n\n def __variation_discrete(self, x, archive):\n y = x.copy()\n keys = list(archive.keys())\n z = archive[keys[np.random.randint(len(keys))]].genotype\n # Uniform Crossover\n for i in range(self.problem.x_dims):\n if random.random() < 0.5:\n y[i] = z[i]\n # Mutation\n for i in range(self.config['discrete_muts']):\n if random.random() <= self.config['discrete_mut_prob']:\n b = random.randint(0, len(self.problem.blocks)-1)\n block = self.problem.blocks[b]\n y[i] = block\n return np.array(y)\n\n def __write_centroids(self, centroids):\n filename = self.get_centroids_filename()\n with open(filename, 'w') as f:\n for p in centroids:\n for item in p:\n f.write(str(item) + ' ')\n f.write('\\n')\n\n def __cvt(self, k, cvt_use_cache=True):\n # check if we have cached values\n if cvt_use_cache:\n fname = self.get_centroids_filename()\n if Path(fname).is_file():\n print(\"WARNING: using cached CVT:\", fname)\n return np.loadtxt(fname)\n # otherwise, compute cvt\n x = np.random.uniform(self.b_mins, self.b_maxs, size=(self.config['cvt_samples'], self.b_dims))\n #x = np.random.uniform(self.mins, self.maxs, self.config['cvt_samples'])\n k_means = KMeans(init='k-means++', n_clusters=k,\n n_init=1, n_jobs=-1, verbose=1, algorithm=\"full\")\n k_means.fit(x)\n return k_means.cluster_centers_\n\n def __make_hashable(self, array):\n return tuple(map(float, array))\n\n # format: centroid fitness desc x \\n\n # centroid, desc and x are vectors\n def __save_archive(self, archive, gen):\n '''\n def write_array(a, f):\n for i in a:\n f.write(str(i) + ' ')\n\n filename = archive_filename(self.config, self.run_id)\n filename = filename.replace(\"*\", str(gen))\n with open(filename, 'w') as f:\n for k in archive.values():\n f.write(str(k.fitness) + ' ')\n write_array(k.behavior, f)\n write_array(k.genotype, f)\n f.write(\"\\n\")\n '''\n\n if self.img_visualizer is not None:\n for key, solution in archive.items():\n self.img_visualizer.save_visualization(solution)\n\n filename = self.get_archive_filename()\n filename = filename.replace(\"*\", str(gen))\n pickle.dump(archive, open(f'{filename}', 'wb'))\n\n def __add_to_archive(self, s, kdt):\n niche_index = kdt.query([s.behavior], k=1)[1][0][0]\n niche = kdt.data[niche_index]\n n = self.__make_hashable(niche)\n elite = self.archive[n] if n in self.archive else None\n if elite is not None:\n if s.fitness > elite.fitness:\n if self.img_visualizer is not None:\n elite_path = self.img_visualizer.get_rel_path(elite)\n if os._exists(elite_path):\n os.remove(elite_path)\n self.archive[n] = s\n else:\n self.archive[n] = s\n\n # map-elites algorithm (CVT variant)\n def compute(self):\n\n # Save empty archive\n self.__save_archive(self.archive, 0)\n\n num_cores = multiprocessing.cpu_count()\n pool = multiprocessing.Pool(num_cores)\n\n # create the CVT\n c = self.__cvt(self.config['num_niches'], self.config['cvt_use_cache'])\n kdt = KDTree(c, leaf_size=30, metric='euclidean')\n self.__write_centroids(c)\n\n init_count = 0\n t = threading.currentThread()\n # main loop\n for g in range(0, self.config['num_gens'] + 1):\n\n if getattr(t, \"stop\", True):\n return\n\n to_evaluate = []\n if g == 0: # random initialization\n while init_count <= self.config['random_init']:\n for i in range(0, self.config['random_init_batch']):\n if self.problem.vary is not None and len(to_evaluate) == 0:\n x = self.problem.vary\n elif self.problem.continuous:\n x = np.random.uniform(self.problem.x_min, self.problem.x_max, self.problem.x_dims)\n else:\n x = np.random.choice(self.problem.blocks, self.problem.x_dims, p=self.config['block_probs'])\n to_evaluate += [np.array(x)]\n if self.config['parallel']:\n s_list = pool.map(self.problem.evaluate, to_evaluate)\n elif self.config['batched']:\n s_list = self.problem.evaluate_batch(to_evaluate)\n else:\n s_list = map(self.problem.evaluate, to_evaluate)\n for s in s_list:\n self.__add_to_archive(s, kdt)\n init_count = len(self.archive)\n to_evaluate = []\n print(\"---\" + str(init_count))\n else: # variation/selection loop\n keys = list(self.archive.keys())\n for n in range(0, self.config['batch_size']):\n # parent selection\n x = self.archive[keys[np.random.randint(len(keys))]]\n # copy & add variation\n if self.problem.continuous:\n z = self.__variation_continous(x.genotype, self.archive)\n else:\n z = self.__variation_discrete(x.genotype, self.archive)\n to_evaluate += [np.array(z)]\n # parallel evaluation of the fitness\n if self.config['parallel']:\n s_list = pool.map(self.problem.evaluate, to_evaluate)\n elif self.config['batched']:\n s_list = self.problem.evaluate_batch(to_evaluate)\n else:\n s_list = map(self.problem.evaluate, to_evaluate)\n # natural selection\n for s in s_list:\n self.__add_to_archive(s, kdt)\n # write archive\n if self.config['num_gens'] == g or g == 0 or (g % self.config['dump_period'] == 0 and self.config['dump_period'] != -1):\n print(\"generation:\", g)\n self.__save_archive(self.archive, g)\n\n #max_fitness = np.max([solution.fitness for key, solution in self.archive.items()])\n #print(\"Sum fit=\", max_fitness)\n\n def get_centroids_filename(self):\n filename = f'centroids_{self.problem.name.strip()}_{self.problem.x_dims}_{self.problem.b_dims}_{self.config[\"num_niches\"]}_{\"-\".join([dimension.name for dimension in self.b_dimensions])}.dat'\n return os.path.join(self.config['centroids_path'], filename)\n\n def get_archive_filename(self):\n filename = f'archive_{self.run_id}_*.p'\n return os.path.join(self.config['archive_path'], filename)\n\n def load_centroids(self, filename):\n points = np.loadtxt(filename)\n return points\n" }, { "alpha_fraction": 0.5801056623458862, "alphanum_fraction": 0.5889084339141846, "avg_line_length": 31.428571701049805, "blob_id": "78f74a5793090b4d974ba4195202da3e7386f656", "content_id": "96d65721bb1bb302fc18790c960a976c8e316bba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 123, "num_lines": 35, "path": "/qdboard/static/js/app.js", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "'use strict';\n\nvar app = angular.module('app', ['ngRoute', 'ngSanitize', 'appControllers', 'appServices', 'appDirectives', 'appFilters']);\n\nvar appServices = angular.module('appServices', []);\nvar appControllers = angular.module('appControllers', []);\nvar appDirectives = angular.module('appDirectives', []);\nvar appFilters = angular.module('appFilters', []);\n\nvar options = {};\noptions.api = {};\noptions.api.base_url = \"http://127.0.0.1:5000\";\n\n\napp.config(['$locationProvider', '$routeProvider', \n function($location, $routeProvider) {\n $routeProvider.\n when('/', {\n templateUrl: 'static/partials/run.list.html',\n controller: 'RunListCtrl'\n }).\n when('/run/create', {\n templateUrl: 'static/partials/run.create.html',\n controller: 'RunListCtrl',\n access: { requiredAuthentication: true }\n }).\n when('/run/:id', {\n templateUrl: 'static/partials/run.show.html',\n controller: 'RunShowCtrl',\n access: { requiredAuthentication: true }\n }).\n otherwise({\n redirectTo: '/'\n });\n}]);\n\n" }, { "alpha_fraction": 0.6180278658866882, "alphanum_fraction": 0.6220119595527649, "avg_line_length": 26.135135650634766, "blob_id": "08e24b15990edca72aaa9448b1cbf7f39b4c8ef1", "content_id": "be7e039781609b89b3a62fa815686ec8416dd5b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2008, "license_type": "no_license", "max_line_length": 103, "num_lines": 74, "path": "/qdboard/server.py", "repo_name": "miguelgondu/qdboard", "src_encoding": "UTF-8", "text": "\"\"\"\n==========================\nAuthor: Niels Justesen\nYear: 2018\n==========================\nRun this script to start a Flask server locally. The server will start a Host, which will manage games.\n\"\"\"\n\nfrom flask import Flask, request, render_template\nfrom qdboard import api\nimport json\nimport numpy as np\n\napp = Flask(__name__, template_folder='templates')\napp.config['EXPLAIN_TEMPLATE_LOADING'] = True\n\n\[email protected]('/', methods=['GET'])\ndef home():\n return render_template('index.html')\n\n\[email protected]('/runs/create', methods=['PUT'])\ndef create():\n data = json.loads(request.data)\n run = api.create_run(data['name'], data['config'])\n return json.dumps(run.to_json())\n\n\[email protected]('/runs/', methods=['GET'])\ndef get_all_runs():\n runs = api.get_runs()\n run_list = [run.to_json() for run in runs]\n return json.dumps(run_list)\n\n\nclass NpEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n elif isinstance(obj, np.floating):\n return float(obj)\n elif isinstance(obj, np.ndarray):\n return obj.tolist()\n else:\n return super(NpEncoder, self).default(obj)\n\n\[email protected]('/runs/<run_id>/archive', methods=['GET'])\ndef get_archive(run_id):\n return json.dumps(api.get_archive(run_id).to_json(), cls=NpEncoder)\n\n\[email protected]('/runs/<run_id>', methods=['GET'])\ndef get(run_id):\n return json.dumps(api.get_run(run_id).to_json())\n\n\ndef start_server(debug=False, use_reloader=False, port=5005):\n \n # Change jinja notation to work with angularjs\n jinja_options = app.jinja_options.copy()\n jinja_options.update(dict(\n block_start_string='<%',\n block_end_string='%>',\n variable_start_string='%%',\n variable_end_string='%%',\n comment_start_string='<#',\n comment_end_string='#>'\n ))\n app.jinja_options = jinja_options\n\n app.config['TEMPLATES_AUTO_RELOAD']=True\n app.run(debug=debug, use_reloader=use_reloader, port=port)\n" } ]
10
nieves-abalos/aind-recognizer
https://github.com/nieves-abalos/aind-recognizer
4687fed44fa9ad89f0152c4b847c7f092471eb4c
ca9bcab51459ba74a067f97483b5fb8ae85b4d48
ca396212da461ce83690eba700f0119d7633cf74
refs/heads/master
2021-01-20T06:03:56.992835
2017-08-28T14:35:38
2017-08-28T14:35:38
101,479,841
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.554770290851593, "alphanum_fraction": 0.5608166456222534, "avg_line_length": 47.980770111083984, "blob_id": "ede5a108e9f6d39ad37a19d92e0f2aae9efbf156", "content_id": "9b152fb1dbb5de9af8d3508c5b1608df5995ed31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12740, "license_type": "no_license", "max_line_length": 219, "num_lines": 260, "path": "/my_model_selectors.py", "repo_name": "nieves-abalos/aind-recognizer", "src_encoding": "UTF-8", "text": "import math\nimport statistics\nimport warnings\n\nimport numpy as np\nfrom hmmlearn.hmm import GaussianHMM\nfrom sklearn.model_selection import KFold\nfrom asl_utils import combine_sequences\n\n\nclass ModelSelector(object):\n '''\n base class for model selection (strategy design pattern)\n '''\n\n def __init__(self, all_word_sequences: dict, all_word_Xlengths: dict, this_word: str,\n n_constant=3,\n min_n_components=2, max_n_components=10,\n random_state=14, verbose=False):\n self.words = all_word_sequences\n self.hwords = all_word_Xlengths\n self.sequences = all_word_sequences[this_word]\n self.X, self.lengths = all_word_Xlengths[this_word]\n self.this_word = this_word\n self.n_constant = n_constant\n self.min_n_components = min_n_components\n self.max_n_components = max_n_components\n self.random_state = random_state\n self.verbose = verbose\n\n def select(self):\n raise NotImplementedError\n\n def base_model(self, num_states):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(self.X, self.lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n \n def base_model_CV(self, num_states, X, lengths):\n # with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # warnings.filterwarnings(\"ignore\", category=RuntimeWarning)\n try:\n hmm_model = GaussianHMM(n_components=num_states, covariance_type=\"diag\", n_iter=1000,\n random_state=self.random_state, verbose=False).fit(X, lengths)\n if self.verbose:\n print(\"model created for {} with {} states\".format(self.this_word, num_states))\n return hmm_model\n except:\n if self.verbose:\n print(\"failure on {} with {} states\".format(self.this_word, num_states))\n return None\n\n\nclass SelectorConstant(ModelSelector):\n \"\"\" select the model with value self.n_constant\n\n \"\"\"\n\n def select(self):\n \"\"\" select based on n_constant value\n\n :return: GaussianHMM object\n \"\"\"\n best_num_components = self.n_constant\n return self.base_model(best_num_components)\n\n\nclass SelectorBIC(ModelSelector):\n \"\"\" select the model with the lowest Bayesian Information Criterion(BIC) score\n\n http://www2.imm.dtu.dk/courses/02433/doc/ch6_slides.pdf\n Bayesian information criteria: BIC = -2 * logL + p * logN\n \"\"\"\n\n def select(self):\n \"\"\" select the best model for self.this_word based on\n BIC score for n between self.min_n_components and self.max_n_components\n\n :return: GaussianHMM object\n \"\"\"\n # SelectorBIC(sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14).select()\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n #print(\"\\n WORD: {}\".format(self.this_word))\n \n selected_model = None\n selected_score = float('+inf')\n selected_num_states = float('-inf')\n bic_score = float('+inf')\n for num_states in range(self.min_n_components, self.max_n_components):\n # lets find best model\n #print(\"\\n Num states: {}\".format(num_states))\n model = self.base_model(num_states)\n if model is not None: \n try:\n logL = model.score(self.X,self.lengths)\n #print(\"score: logL {} and {} states\".format(logL, num_states))\n # p = n_components ** 2 + 2 * n_components * n_features - 1\n # n_features >> variable defined in the model\n # N = number of data points or sequences > sequences are self.sequences\n parameters = num_states * num_states + 2 * num_states * len(self.X[0]) - 1\n bic_score = - 2 * logL + parameters * math.log(len(self.X))\n #print(\"BIC score: {} \".format(bic_score))\n except:\n #print(\"Exception at model.score() with word {} and states {}\".format(self.this_word, num_states))\n pass\n else:\n #print(\"Not able to train HMM model (self.base_model) for word {} with the train samples and {} states.\".format(self.this_word, num_states)) \n pass \n \n # update best model if BIC is better than the other BICs (LOWER)\n if bic_score < selected_score:\n selected_score = bic_score\n selected_num_states = num_states\n selected_model = model\n #print(\"UPDATED selected_score {} and selected_num_states {}\".format(selected_score, selected_num_states))\n \n return selected_model\n\nclass SelectorDIC(ModelSelector):\n ''' select best model based on Discriminative Information Criterion\n\n Biem, Alain. \"A model selection criterion for classification: Application to hmm topology optimization.\"\n Document Analysis and Recognition, 2003. Proceedings. Seventh International Conference on. IEEE, 2003.\n http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.58.6208&rep=rep1&type=pdf\n DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n '''\n\n def select(self):\n # SelectorDIC(sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14).select()\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\n # TODO implement model selection based on DIC scores\n #print(\"\\n WORD: {}\".format(self.this_word))\n \n selected_model = None\n selected_score = float('-inf')\n dic_score = float('-inf')\n selected_num_states = float('-inf')\n for num_states in range(self.min_n_components, self.max_n_components):\n # lets find best model\n #print(\"\\n Num states: {}\".format(num_states))\n model = self.base_model(num_states)\n if model is not None: \n try:\n # DIC is that we are trying to find the model that gives a high likelihood(small negative number) to the original word and low likelihood(very big negative number) to the other words. So DIC score is\n # DIC = log(P(original world)) - average(log(P(otherwords)))\n # DIC = log(P(X(i)) - 1/(M-1)SUM(log(P(X(all but i))\n\n # log(P(X(i))) in terms of hmmlearn is simply the model's score for that particular word\n logL = model.score(self.X,self.lengths)\n #print(\"score: logL {} and {} states\".format(logL, num_states))\n logL_others = 0\n num_words = 0\n for other_word in self.hwords:\n if other_word != self.this_word:\n X_other, lengths_other = self.hwords[other_word]\n # SUM(log(P(X(all but i))\n try:\n logL_others = logL_others + model.score(X_other, lengths_other)\n num_words = num_words + 1 \n except:\n #print(\"Exception at model.score(other_word) with word {} and states {}\".format(self.this_word, num_states))\n pass\n \n # all logLs calculated, now average:\n logL_others = logL_others / num_words\n # DIC = log(P(original world)) - average(log(P(otherwords)))\n dic_score = logL - logL_others\n #print(\"DIC score: {} \".format(dic_score))\n except:\n #print(\"Exception at model.score() with word {} and states {}\".format(self.this_word, num_states))\n pass\n else:\n #print(\"Not able to train HMM model (self.base_model) for word {} with the train samples and {} states.\".format(self.this_word, num_states)) \n pass \n \n # update best model if DIC is HIGHER\n if dic_score > selected_score:\n selected_score = dic_score\n selected_num_states = num_states\n selected_model = model\n #print(\"UPDATED selected_score {} and selected_num_states {}\".format(selected_score, selected_num_states))\n \n return selected_model\n\n\nclass SelectorCV(ModelSelector):\n ''' select best model based on average log Likelihood of cross-validation folds\n\n '''\n \n def select(self):\n # (sequences, Xlengths, word, min_n_components=2, max_n_components=15, random_state = 14)\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n # print(\"\\nSelectorCV > WORD: {}\".format(self.this_word))\n selected_model = None\n selected_score = float('-inf')\n selected_num_states = float('-inf')\n if len(self.lengths) > 1:\n # k-fold cross-validation requires at least one train/test split by setting n_splits=2 or more\n n_splits = min(3, len(self.sequences))\n split_method = KFold(n_splits) \n\n for num_states in range(self.min_n_components, self.max_n_components):\n # break the training set into \"folds\" and rotate which fold is left out of training. \n #print(\"\\n Num states: {}\".format(num_states))\n avgLogL = 0\n num_splits = 0\n for cv_train_idx, cv_test_idx in split_method.split(self.sequences): \n X_train, lengths_train = combine_sequences(cv_train_idx, self.sequences)\n model = self.base_model_CV(num_states, X_train, lengths_train)\n if model is not None: \n try:\n # The \"left out\" fold scored, this gives us a proxy method of finding the best model to use on \"unseen data\"\n X_test, lengths_test = combine_sequences(cv_test_idx, self.sequences)\n logL = model.score(X_test, lengths_test)\n #print(\"score: logL {} and {} states\".format(logL, num_states))\n avgLogL = avgLogL + logL\n num_splits = num_splits + 1\n except:\n #print(\"Exception at model.score() with word {} and states {}\".format(self.this_word, num_states))\n pass\n else:\n #print(\"Not able to train HMM model (self.base_model_CV) for word {} with the train samples and {} states.\".format(self.this_word, num_states)) \n pass \n \n # Calculate avg log likelihood of all splits\n #print(\"> sum LogL {} and {} num_splits\".format(avgLogL, num_splits))\n if num_splits != 0:\n avgLogL = avgLogL / num_splits\n else:\n avgLogL = float('-inf')\n #print(\"> avgLogL {} for {} states\".format(avgLogL, num_states))\n # update best model if avgLogL is better than the other states\n if avgLogL > selected_score:\n selected_score = avgLogL\n selected_num_states = num_states\n #print(\"UPDATED selected_score {} and selected_num_states {}\".format(selected_score, selected_num_states))\n \n # rebuild model with all samples (that is fit with self.X and self.lengths)\n #print(\"Average Log Likelihood: {}\".format(selected_score))\n #print(\"Best number of states: {}\".format(selected_num_states))\n try:\n selected_model = self.base_model(selected_num_states)\n except:\n print(\"Exception at creating the selected HMM model self.base_model >> model.initialize and fit. All samples. {} states.\".format(self.this_word, num_states)) \n pass\n \n return selected_model\n" }, { "alpha_fraction": 0.6028558611869812, "alphanum_fraction": 0.6050870418548584, "avg_line_length": 42.960784912109375, "blob_id": "8ae4de128498f42461a16be06609804c523ac034", "content_id": "43cbb8b6c0e86e0d9e60d6611ab5c3cd3a5a41f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2241, "license_type": "no_license", "max_line_length": 142, "num_lines": 51, "path": "/my_recognizer.py", "repo_name": "nieves-abalos/aind-recognizer", "src_encoding": "UTF-8", "text": "import warnings\nfrom asl_data import SinglesData\n\n\ndef recognize(models: dict, test_set: SinglesData):\n \"\"\" Recognize test word sequences from word models set\n\n :param models: dict of trained models\n {'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...}\n :param test_set: SinglesData object\n :return: (list, list) as probabilities, guesses\n both lists are ordered by the test set word_id\n probabilities is a list of dictionaries where each key a word and value is Log Liklihood\n [{SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... },\n {SOMEWORD': LogLvalue, 'SOMEOTHERWORD' LogLvalue, ... },\n ]\n guesses is a list of the best guess words ordered by the test set word_id\n ['WORDGUESS0', 'WORDGUESS1', 'WORDGUESS2',...]\n \"\"\"\n\n #recognize(models, test_set)\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n probabilities = []\n guesses = []\n # TODO implement the recognizer\n for index_uword, unknown_word in test_set.get_all_Xlengths().items():\n X = unknown_word[0] \n lengths = unknown_word[1]\n dict_words = {}\n best_word = None\n selected_score = float('-inf')\n # Let's see what word based on its model is more likely to be\n for word, model in models.items():\n # calculate the scores for each model(word) and update the 'probabilities' list.\n try:\n logL = model.score(X, lengths)\n #print(\"logL: {} for word {}\".format(logL, word))\n dict_words[word] = logL\n # determine the maximum score for each model.\n if logL > selected_score:\n best_word = word\n selected_score = logL\n except:\n #print(\"Can't get the score from model.score() for {}\".format(word))\n dict_words[word] = float(\"-inf\")\n pass \n \n # Append the corresponding word (the tested word is deemed to be the word for which with the model was trained) to the list 'guesses'.\n guesses.append(best_word) \n probabilities.append(dict_words)\n return probabilities, guesses" } ]
2
shaohaojiecoder/GAD
https://github.com/shaohaojiecoder/GAD
84a38c75917b8bf71a248c00e431f049e623019a
0ca2fe1fd8a547fdfc52cd14158387d752ba82bb
bee7ad22c3d1efdbe554d259897cc9ac16e24bbe
refs/heads/master
2021-03-30T20:49:23.354213
2018-04-04T09:58:23
2018-04-04T09:58:23
124,831,779
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5559055209159851, "alphanum_fraction": 0.5606299042701721, "avg_line_length": 30.774999618530273, "blob_id": "dc927995f57c9ad07e3915066ad569dea6aeb3c8", "content_id": "1e9e149311019592935646d49e823daea1d282c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 107, "num_lines": 40, "path": "/getInfo/getInfo/pipelines.py", "repo_name": "shaohaojiecoder/GAD", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport sqlite3\n\nclass GetinfoPipeline(object):\n\n def __init__(self, sqlite_file, sqlite_table):\n self.sqlite_file = sqlite_file\n self.sqlite_table = sqlite_table\n\n\n @classmethod\n def from_crawler(cls,crawler):\n return cls(\n sqlite_file = crawler.settings.get('SQLITE_FILE'), # 从 settings.py 提取\n sqlite_table = crawler.settings.get('SQLITE_TABLE', 'items')\n )\n\n\n def open_spider(self, spider):\n self.conn = sqlite3.connect(self.sqlite_file)\n self.cur = self.conn.cursor()\n\n def close_spider(self, spider):\n self.conn.close()\n\n def process_item(self, item, spider):\n insert_sql = \"insert into {0}({1}) values ({2})\".format(self.sqlite_table, \n ', '.join(item.fields.keys()),\n ', '.join(['?'] * len(item.fields.keys())))\n self.cur.execute(insert_sql, item.fields.values())\n self.conn.commit()\n \n return item\n\nmy = GetinfoPipeline()" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6951219439506531, "avg_line_length": 12.666666984558105, "blob_id": "6f380651fea1e60d03dcfc6f03a5bdb0d4482af2", "content_id": "0f601e776a9b9c897d7cf199cf3f7dee72a19107", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 28, "num_lines": 6, "path": "/global_setting.py", "repo_name": "shaohaojiecoder/GAD", "src_encoding": "UTF-8", "text": "import os\n\n# 测试数据库 使用sqlite3 数据库\ndir_path = os.path.abspath()\n\ndatabase_path = ''\n" }, { "alpha_fraction": 0.7148289084434509, "alphanum_fraction": 0.7376425862312317, "avg_line_length": 19.30769157409668, "blob_id": "f146d01f646912df9764da5908046eadca7acf04", "content_id": "56b525764d00dc19a7d79c52f353c6a5a98d6753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 55, "num_lines": 13, "path": "/site/cbgdata/models.py", "repo_name": "shaohaojiecoder/GAD", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\n\nclass Snippets(models.Model):\n\tuid = models.CharField(max_length=30,primary_key=True)\n\tprice = models.IntegerField(default=0)\n\turl = models.URLField(max_length=250)\n\n\n\n\tdef __str__(self):\n\t\treturn self.uid" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 9.666666984558105, "blob_id": "ff2187d9a8a804aaa5935aec54de43d50887fa43", "content_id": "7572730615f31d0894aaea2993fcc8b183a21b95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 179, "license_type": "no_license", "max_line_length": 22, "num_lines": 9, "path": "/readme.txt", "repo_name": "shaohaojiecoder/GAD", "src_encoding": "UTF-8", "text": "项目目的:\n\t从网上抓取数据:\n\t\tscrapy\n\t\t数据类型:\n\t\t数据来源:\n\t分析数据:\n\t\t使用matplotlia和pandas \n\t呈现数据:\n\t\tdjango rest接口开发\n\t\t\n" }, { "alpha_fraction": 0.7528089880943298, "alphanum_fraction": 0.7528089880943298, "avg_line_length": 16.799999237060547, "blob_id": "307136580799fe28eaf920c1f810f690360239a6", "content_id": "e0e91d113898c0decfed6e46dab42545ea0e6a74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 89, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/site/cbgdata/apps.py", "repo_name": "shaohaojiecoder/GAD", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass CbgdataConfig(AppConfig):\n name = 'cbgdata'\n" } ]
5
kakarotte22/PythonDemo
https://github.com/kakarotte22/PythonDemo
cbb3506d30e69e272c6733f269ad94d17415468a
1bf2a2b3bb27ba24b0fc21c72baa1421b5594e92
4519180c34fcf87f700b24cb8c0e08f0c85ddc00
refs/heads/master
2020-03-30T17:34:40.046432
2018-10-03T18:26:42
2018-10-03T18:26:42
151,461,354
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.571107804775238, "alphanum_fraction": 0.6444610953330994, "avg_line_length": 24.69230842590332, "blob_id": "9c189e972379b3b19cc87b998bd14282441b5770", "content_id": "8e12515cbd35c22425c2b89262d697ed78dc426f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 140, "num_lines": 52, "path": "/helloworld/time模块.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import time\n#获取时间戳 时间戳为当前时间到1970年1月1日0时0分0秒的秒数差,浮点型\nresult = time.time()\nyear = result/(24 * 60 * 60 * 365) + 1970\nprint(year)\n#year大致等于当前年份\nprint(result)\n#获取时间元组 :0~9 :time.localtime([seconds = 当前时间戳])\nprint(time.localtime())\n#time.struct_time(tm_year=2018, tm_mon=8, tm_mday=15, tm_hour=23, tm_min=12, tm_sec=47, tm_wday=2(0~6,0:周日), tm_yday=227, tm_isdst=0(夏令时标记))\n#获取格式化的时间\n#秒—>可读时间:import time time.ctime([seconds=localtime])\nresult = time.ctime()\nprint(result)\n#时间元组—>可读时间:import time time.asctime([tuple=local-tuple])\nresult = time.asctime()\nprint(result)\n#--------------------格式化时间日期---------------------------------------------------\n#时间元组—>格式化时间日期:time.strftime(格式字符串,时间元组)\nresult = time.strftime('%Y-%m-%d %A %H:%M:%S',time.localtime())\nprint(result)\n#格式化时间日期—>时间元组:time.strptime(时间元组,格式字符串)\n#time.mktime(时间元组) 返回时间戳\n#time.clock() 获取当前cpu时间,浮点数秒数,通常用于计算代码耗时\n#time.sleep(sec) 休眠sec秒\n\n\n\n\n#python中时间日期格式化符号:\n# %y 两位数的年份表示(00-99)\n# %Y 四位数的年份表示(000-9999)\n# %m 月份(01-12)\n# %d 月内中的一天(0-31)\n# %H 24小时制小时数(0-23)\n# %I 12小时制小时数(01-12)\n# %M 分钟数(00=59)\n# %S 秒(00-59)\n# %a 本地简化星期名称\n# %A 本地完整星期名称\n# %b 本地简化的月份名称\n# %B 本地完整的月份名称\n# %c 本地相应的日期表示和时间表示\n# %j 年内的一天(001-366)\n# %p 本地A.M.或P.M.的等价符\n# %U 一年中的星期数(00-53)星期天为星期的开始\n# %w 星期(0-6),星期天为星期的开始\n# %W 一年中的星期数(00-53)星期一为星期的开始\n# %x 本地相应的日期表示\n# %X 本地相应的时间表示\n# %Z 当前时区的名称\n# %% %号本身\n" }, { "alpha_fraction": 0.4302862286567688, "alphanum_fraction": 0.4644505977630615, "avg_line_length": 32.875, "blob_id": "63f12718dc52845d0bd079c0caafccc7c9304d99", "content_id": "d9cdfc60bca035f1bfcb891f97e571244de62bba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1381, "license_type": "no_license", "max_line_length": 106, "num_lines": 32, "path": "/helloworld/列表顺序相关.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#------------------------------列表升降序----------------------------------------------------------------------\n#sorted(iterable,key=none,reverse=false)返回一个排好序的列表。key为排序关键字,值为一个函数,且函数只有一个参数,返回一个值用来比较,默认false升序,不改变列表本身\nnum =[('c',2),('a',5),('b',4),('d',3),('e',1)]\nprint(num,sorted(num))\ndef getKey(x):\n return x[1]\nresult = sorted(num,key= getKey)\n#getKey不加(),加了表示调用,不加表示指向\nprint(result)\n#列表对象方法:.sorted(key=none,reverse=false) 直接改变列表本身,返回none。key同内置函数sorted\nnum = [('c',2),('a',5),('b',4),('d',3),('e',1)]\nresult = num.sort()\nprint(result,num)\n#------------------------------列表乱序----------------------------------------------------------------------\n#import random\n#random.shuffle(list) 返回none,直接改变列表\nimport random\nnum =[1, 2, 3, 4, 5, 6, 7, 8]\nres = random.shuffle(num)\nprint(res,num)\n\n#------------------------------列表乱反转----------------------------------------------------------------------\n#l.reverse() 改变列表,返回none\nnum = [1, 2, 3, 4, 5, 6, 7, 8]\nres = num.reverse()\nprint(res,num)\n\n\n#切片反转:l[::-1] 不改变列表,返回反转后的列表\nnum = [1, 2, 3, 4, 5, 6, 7, 8]\nres = num[::-1]\nprint(res,num)" }, { "alpha_fraction": 0.5216262936592102, "alphanum_fraction": 0.5337370038032532, "avg_line_length": 28.64102554321289, "blob_id": "83ab15cde25abbf859355a56683a413bfa401643", "content_id": "36294557b74525bf6b1f61724931758f3162e618", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1246, "license_type": "no_license", "max_line_length": 67, "num_lines": 39, "path": "/venv/Lib/site-packages/comm_libs/rsa_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# encoding: utf-8\nimport os\n\nfrom M2Crypto import RSA\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nRSA_PRIV_KEY_PATH = BASE_DIR + \"/net/privkey.pem\"\nRSA_PUB_KEY_PATH = BASE_DIR + \"/net/pubkey.pem\"\n\n\nclass RsaUtil():\n def encrypt(self, data):\n '''\n 加密或者解密\n @param data: 要加密或者解密的数据\n @param is_encrypt: 加密操作或者解密操作(加密:True,解密:False)\n @return: 加密或者解密后的数据\n '''\n rsa_pub = RSA.load_pub_key(RSA_PUB_KEY_PATH)\n rsa_len = 117\n if len(data) > rsa_len:\n tmp = ''\n for i in range(len(data) / rsa_len + 1):\n t = data[i * rsa_len:(i + 1) * rsa_len]\n tmp += rsa_pub.public_encrypt(t, RSA.pkcs1_padding)\n print len(tmp), tmp\n return tmp\n else:\n return rsa_pub.public_encrypt(data, RSA.pkcs1_padding)\n\n def decrypt(self, data):\n rsa_len = 128\n rsa_pri = RSA.load_key(RSA_PRIV_KEY_PATH)\n tmp = ''\n for i in range(len(data) / rsa_len):\n t = data[i * rsa_len:(i + 1) * rsa_len]\n tmp += rsa_pri.private_decrypt(t, RSA.pkcs1_padding)\n return tmp\n" }, { "alpha_fraction": 0.46640753746032715, "alphanum_fraction": 0.5136035680770874, "avg_line_length": 31.160715103149414, "blob_id": "29b5f4593aa30a67ae7e98ca461d3be2c4a94be1", "content_id": "44e5c34b9cfb4a5d0d9ff44a28aca9c5bbf7ddee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2585, "license_type": "no_license", "max_line_length": 88, "num_lines": 56, "path": "/helloworld/列表创建、增删改.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#列表:有序、可变的元素集合,lis = [2,'str',True,'\\n',[2,3,4]]\n#----------------------------列表产生-------------------------------------------------\n# lst = range(1,99,2)\n# print(lst)\n#----------------------------列表推导出新列表-------------------------------------------------\n#[表达式 for 变量 in 列表 if 条件]\nlst = [1, 2, 3, 4, 5]\nresultLst = [num ** 2 for num in lst if num % 2 != 0]\nprint(resultLst)\n#----------------------------列表增加,改变原列表-------------------------------------------------\n#append(obj):末尾增加列表元素,没有返回值,所有 print(lst.append(5))为None,obj直接作为一个元素追加到末尾\nlst.append('wo shi zhui jia de')\nprint(lst)\n#insert(index,object):将object插入在index位置前,没有返回值\nlst.insert(3, 'obj')\nprint(lst)\n#extend(iterable):往列表中扩展另一个可迭代序列,没有返回值,将iterable中元素拆开追加到末尾\nnum = [1, 2, 3]\nstr = 'abc'\nnum.extend(str)\nprint(num)\n#列表乘法:lst * (int)n :将列表内所有元素重复n次\nlst = [1, 2, 3]\nprint(lst * 3)\n#列表加法,只能列表+列表,不能为字符串\nnum1 = [1, 2, 3]\nnum2 = ['a','bcd', 4]\nnum3 = 'abcd'\nprint(num1 + num2)\n#print(num1 + num3) 此行会直接报错,不能加字符串\n#----------------------------列表删除,改变原列表-------------------------------------------------\n# del 语句:可以删除一个变量、列表或某个元素如:num = 10 del num 那么num变量将被删除\ndel num2[1]\nprint(num2)\n# .pop(index=-1):移除并返回列表中指定索引对应的元素;返回值为被移除的元素\nnum = [1, 2, 3, 'abc', 3]\nresult = num.pop(1)\nprint(result, num)\n#.remove(obj):移除列表中的指定元素,如果元素不存在会报错,如果存在多个会移除最左边的一个,返回值为None;注意遍历移除的坑\nresult = num.remove(3)\nprint(result, num)\n#移除列表中所有的某个值的元素做法(不能再循环遍历体中移除):遍历查找看有多少个,之后遍历移除那么多次。\nnum = [1, 2, 3, 'abc', 3, 4, 5, 3, 3, 3, 3, 3, 4, 5, 3, 4]\ncount = 0\nfor a in num :\n if a == 3:\n count +=1\nwhile count :\n num.remove(3)\n count -=1\nprint(num)\n#----------------------------列表修改,改变原列表-------------------------------------------------\n#修改列表:当我们想要操作列表中某个元素时,一定是通过索引(下标)来操作指定元素\nnum = [1, 2, 3, 'abc', 3, 4, 5, 3, 3, 3, 3, 3, 4, 5, 3, 4]\nnum[3] = 4\nprint(num)\n" }, { "alpha_fraction": 0.8527131676673889, "alphanum_fraction": 0.8604651093482971, "avg_line_length": 64, "blob_id": "57cddcd0fda3fa6cb66aefeff734578bd64a9ec3", "content_id": "b09bae9d030f1a5b9559a6419f09ba0b0001e1b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 249, "license_type": "no_license", "max_line_length": 68, "num_lines": 2, "path": "/包和模块/模块安装.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#单文件安装:直接把文件拷贝放到sys.path路径列表的任意1个路径,一般放在Lib/site-package文件夹下\n#带有setup.py文件的安装:打开命令行工具—>切换到setup.py所在路径—>执行python setup.py install" }, { "alpha_fraction": 0.7342657446861267, "alphanum_fraction": 0.7342657446861267, "avg_line_length": 34.75, "blob_id": "ffa09019cfc677d2ce2c1c6738fb858ad5b11397", "content_id": "d888d9289ed4d9ae387bba531b1d21bfb959e838", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 203, "license_type": "no_license", "max_line_length": 77, "num_lines": 4, "path": "/机器学习/词性标注.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import jieba.posseg as pesg\nsegList = pesg.cut('把这篇报道修改一下。', HMM=True) #带词性模式,隐马可夫模型,jieba.cut只是分词,不带词性\nfor word in segList:\n print(word)\n" }, { "alpha_fraction": 0.5156453847885132, "alphanum_fraction": 0.5521512627601624, "avg_line_length": 16.295454025268555, "blob_id": "7160d23e26df75427fbd74ae63555c0ab039a498", "content_id": "d6cc46d715cad3409d9dd9f4f1aa22ee5dfa46cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1596, "license_type": "no_license", "max_line_length": 62, "num_lines": 88, "path": "/venv/Lib/site-packages/comm_libs/session.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\n\n\"\"\"\nsession 操作相关\n\ncreated by : xiaochun\n\n\"\"\"\n\nimport hashlib\nimport time\nimport memcache\n\n\n\nclass SessionClient(object):\n \"\"\"\n session 操作类\n \"\"\"\n\n def __init__(self, addr_list):\n \"\"\"\n addr_list : [\"127.0.0.1:11000\"]\n \"\"\"\n\n self.mem_client = memcache.Client(addr_list)\n\n\n def gen_session_key(self, client_ip, user_id):\n \"\"\"\n 生成session key\n \"\"\"\n\n time_str = str(time.time())\n clock_str = str(time.clock())\n\n src = client_ip + str(user_id) + time_str + clock_str\n\n return hashlib.md5(src).hexdigest()\n\n def get_session(self, key):\n \"\"\"\n 获取session\n return : 内容\n \"\"\"\n\n return self.mem_client.get(key)\n\n def set_session(self, key, value, expire=15*60):\n \"\"\"\n 更新session\n return : True: 成功\n \"\"\"\n\n return self.mem_client.set(key, value, expire)\n\n def del_session(self, key):\n \"\"\"\n 删除session\n return : 非0,表示成功\n \"\"\"\n\n return self.mem_client.delete(key)\n\n\n\nif __name__ == \"__main__\":\n\n\n # 服务地址\n addr_list = [\"127.0.0.1:11000\"]\n\n session_client = SessionClient(addr_list)\n\n # 生成session key\n #skey = session_client.gen_session_key(\"127.0.0.1\", \"123\")\n\n skey = \"d6f731287a5babd0bbea5874d031fb76\"\n\n print skey\n\n #print session_client.set_session(skey, \"xxxd\")\n\n print session_client.get_session(skey)\n\n #print session_client.del_session(skey)\n\n #print session_client.get_session(skey)\n\n\n\n\n\n\n \n\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.6060606241226196, "avg_line_length": 10.166666984558105, "blob_id": "7999da629fd14c00714f8ee0399676d09c91cd02", "content_id": "9091c7ad6071ec3adf1e05a83a234fe1a3fbe20b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 17, "num_lines": 6, "path": "/helloworld/交换数据.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "a = 10\nb = 20\nprint(a,b)\n#直接通过赋值语句实现交换两个数值\na, b = b, a\nprint(a, b)" }, { "alpha_fraction": 0.45054423809051514, "alphanum_fraction": 0.48177945613861084, "avg_line_length": 20.752687454223633, "blob_id": "edc1a6f415a5062337750ca803e5174410008abe", "content_id": "208d6282b0105943a4ebb6b1cfb58b4f74955308", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3079, "license_type": "no_license", "max_line_length": 87, "num_lines": 93, "path": "/函数/函数的定义.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#---------------------函数定义-----------------------------------------------------------\n#注:函数应遵循单一原则:一个函数只实现一个功能\n#指定参数赋值可以实现不按照顺序写实参\ndef myHs(num1, num2):\n print('num1:%d,num2:%d'%(num1 , num2))\n\n\nmyHs(3, 5)\nmyHs(num2=5, num1=3)\n#def 函数名(*args):参数为元组实现不定长参数 (*可以进行拆包、装包)\n# 函数体\n#控制台输入:help(函数名) 查看函数帮助\n\ndef noLongSum(*t):\n \"\"\"\n 实现不定长参数的和\n :param t: 可迭代对象\n :return: none\n \"\"\"\n sum = 0\n itr = iter(t)\n for v in itr:\n sum += v\n print(sum)\n\n\nnoLongSum(3, 4, 5, 6, 7)\n#def 函数名(**kwargs):参数以字典实现不定长参数,但调用时必须使用关键字参数赋值的方式\n# 函数体\n#在python中,参数的传递全部是地址传递,参数为变量时,会改变原变量,参数不可变时则不会更改\n#赋值语句:b = 666 实际操作是,在内存中开一个区域存放666,让b指向它,b实际是666的地址\n\n\n#--------------------偏函数--------------------------------------------------------------\n#偏函数:当我们写一个参数比较多的函数时,有些时候某些参数都是一个固定的值,为了简化使用可以创建一个新函数,指定要使用的函数的某个参数为固定值,这个函数就叫偏函数\n\nimport functools\n\n\ndef test(a, b, c, d, e):\n print(a + b + c + d + e)\n\n\nnewFuntest = functools.partial(test, d=5, e=5)\nnewFuntest(1, 2, 3)\n\n#--------------------高阶函数--------------------------------------------------------------\n#高阶函数:当一个函数A的参数也是一个函数的时候,称A为高阶函数\ndef cal(num1, num2 ,calFun):\n result = calFun(num1, num2)\n print(result)\n\n\ndef plus(num1, num2):\n return num1 + num2\n\n\ndef sub(num1,num2):\n return num1 -num2\n\n\ncal(1, 2, plus)\ncal(1, 2, sub)\n\n#--------------------返回函数--------------------------------------------------------------\n#返回函数:是指一个函数内部,返回得数据是另一个函数,称这样的操作为返回函数\ndef getFun(flag):\n \"\"\"\n\n :param flag:只能为\"+\"或\"-\"\n :return: 函数\n \"\"\"\n #内层函数引用了外层函数的变量或参数,外层函数又把内层函数作为返回值,这就叫闭包,当内部需要更改外部变量时,需要申明:nonlocal 外层变量\n def plus(num1,num2):\n return num1 + num2\n def sub(num1,num2):\n return num1 - num2\n if flag == '+':\n return plus\n else:\n return sub\ndef cal(num1,num2,flag):\n flagFun = getFun(flag)\n print(flagFun(num1, num2))\n\n\ncal(5, 6, '+')\ncal(5, 6, '-')\n\n\n#--------------------匿名函数--------------------------------------------------------------\n#lambda 参数1,参数2 。。。。: 表达式\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\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\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\n\n\n\n\n" }, { "alpha_fraction": 0.7301037907600403, "alphanum_fraction": 0.7508650422096252, "avg_line_length": 27.899999618530273, "blob_id": "641fc242967f9e67f3f28a6ec0ee484d001893cf", "content_id": "eac60c39c90fa844a7655bf86bf301dae93891de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 88, "num_lines": 10, "path": "/helloworld/迭代器.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import collections\nlst = [1, 2, 3, 'asd', True, 5]\n#1、创建一个迭代器(可以自动记录当前位置,从第一个元素开始,通过next()函数往后,不能往前,迭代完之后继续next迭代会报错StopIteration,一般不能多次迭代)\nit = iter(lst)\n# isIter = isinstance(it, collections.Iterator)\n# print(isIter)\n#2、通过迭代器遍历\nfor v in it:\n print(v)\n#本行执行之后it不会继续迭代了,如需继续迭代需要重新创建迭代器\n" }, { "alpha_fraction": 0.6917900443077087, "alphanum_fraction": 0.7012113332748413, "avg_line_length": 23.766666412353516, "blob_id": "2e5ab6e25bf40232b35bf59f17f5d4e41e3db280", "content_id": "6263797fbf212969dbd96bab8c1c12ed8b7acb6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 92, "num_lines": 30, "path": "/文件操作/py/文件操作案例1.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#需求:给定一批文件,将不同文件后缀的文件移动到同一个文件夹下,文件夹名称为后缀名,并生产一个txt格式的文件清单\n#0、获取所有的文件名称列表\nimport os\nimport shutil\n# os.chdir('文件操作') #切换目录到文件操作下,当前已经是的了,故本条多余\nfileNameList = os.listdir() #获取当前文件所在目录的所有文件名,返回文件名列表(如果目录是一个文件夹,且文件夹里还有子文件或文件夹,这些文件不会被列入列表)\n#1、遍历所有的文件\nfileName: str #添加类型提示,解决了部分情况下不出现方法提示的情况\nfor fileName in fileNameList:\n # print(fileName, type(fileName))\n index = fileName.rfind('.')\n # print(index)\n# #1、分解文件名,找到文件后缀\n# fileName.rfind()\n #2、判断是否存在文件后缀的文件夹\n foldName = fileName[index + 1:]\n if index == -1:\n continue\n # print(foldName)\n #存在,则移动过去\n #不存在,创建并移动\n if not os.path.exists(foldName):\n os.mkdir(foldName)\n shutil.move(fileName,foldName) #导入shutil,调用里面的move方法\n\n\n\n\n\n#2、生成.txt格式的文件清单\n" }, { "alpha_fraction": 0.5408284068107605, "alphanum_fraction": 0.5680473446846008, "avg_line_length": 15.56862735748291, "blob_id": "ef0eb3f297fac22ea3a6d96fa698b1181ddb9e11", "content_id": "6671e19fae6d1857dfe9bf5733a4426b4694909d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2875, "license_type": "no_license", "max_line_length": 76, "num_lines": 153, "path": "/venv/Lib/site-packages/comm_libs/time_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding=utf8\nimport calendar\n\nimport datetime\nimport time\n\n\ndef get_now_datetime():\n \"\"\"\n 获取当前时间date对象\n \"\"\"\n t = datetime.datetime.now()\n return t\n\n\ndef get_now_timestamp():\n \"\"\"\n 获取当前时间戳\n :return:\n \"\"\"\n return int(time.time())\n\n\ndef get_now_date():\n \"\"\"\n 获取当前时间date对象\n \"\"\"\n t = get_now_datetime().date()\n return t\n\n\ndef get_now_time_str():\n \"\"\"\n 获取当前时间字符串 格式 \"2010-10-10 12:59:40\"\n \"\"\"\n\n t = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n return t\n\n\ndef get_time_str_before(days):\n \"\"\"\n 获取当前时间以前某天的时间字符串 格式 \"2010-10-10 12:59:40\"\n \"\"\"\n\n time_delta = datetime.timedelta(days=days)\n\n t = (datetime.datetime.now() - time_delta).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n return t\n\n\ndef get_now_date_str():\n \"\"\"\n 获取当前日期字符串 格式\"2010-10-10\"\n \"\"\"\n t = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n\n return t\n\n\ndef get_date_str_before(days):\n \"\"\"\n 获取当前时间以前某天的时间字符串 格式 \"2010-10-10\"\n \"\"\"\n\n time_delta = datetime.timedelta(days=days)\n\n t = (datetime.datetime.now() - time_delta).strftime(\"%Y-%m-%d\")\n\n return t\n\n\ndef get_chinese_date_str(date_str):\n \"\"\"\n 把 yyyy-mm-dd 转成 yyyy年mm月dd日\n \"\"\"\n\n tmp = date_str.split(\"-\")\n\n year = tmp[0]\n month = tmp[1]\n day = tmp[2]\n\n result = u\"%s年%s月%s日\" % (year, month, day)\n\n return result\n\n\ndef add_months(dt, months):\n month = dt.month - 1 + months\n year = dt.year + month / 12\n month = month % 12 + 1\n day = min(dt.day, calendar.monthrange(year, month)[1])\n return dt.replace(year=year, month=month, day=day)\n\n\ndef get_month_total_days(date):\n \"\"\"\n 获取一个月有多少天\n :param date:\n :return:\n \"\"\"\n return calendar.monthrange(date.year, date.month)[1]\n\n\ndef diff_seconds(date1, date2):\n \"\"\"\n 两个日期之间相差的秒数,存在正负\n :param date1: 小时间\n :param date2: 大时间\n :return:\n \"\"\"\n timedelta = date2 - date1\n return timedelta.days * 24 * 3600 + timedelta.seconds\n\n\ndef parse_date(date_str):\n \"\"\"\n 解析日期字符串,风格为:%Y-%m-%d\n\n :param date_str:\n :return:\n \"\"\"\n return parse(date_str, '%Y-%m-%d')\n\n\ndef parse_datetime(date_str):\n \"\"\"\n 解析日期字符串,风格为:%Y-%m-%d\n\n :param date_str:\n :return:\n \"\"\"\n\n return parse(date_str, '%Y-%m-%d %H:%M:%S')\n\n\ndef parse(date_str, pattern):\n \"\"\"\n 通过指定的样式来解析日期字符串为日期\n :param date_str: 日期字符串\n :param pattern: 样式\n :return:\n \"\"\"\n\n return datetime.datetime.strptime(date_str, pattern)\n\n\nif __name__ == \"__main__\":\n print get_now_date_str()\n print get_date_str_before(7)\n" }, { "alpha_fraction": 0.5543259382247925, "alphanum_fraction": 0.6197183132171631, "avg_line_length": 27.399999618530273, "blob_id": "71035e4047f7ff5075b41bafcc4fa5d042706854", "content_id": "cdef8ad03219a5c3bff9e65317886b4af586bc18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 72, "num_lines": 35, "path": "/机器学习/画图和特征向量.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import *\n# #a1,a2,a3分别表示在直角坐标系中的坐标,现将原坐标系变换成a1,a2为基地的坐标系中,求变换后的a3在哪(直角坐标系)\n# a1 = [3, 1]\n# a2 = [1, 3]\n# a3 = [1, 2]\n# a = mat([a1, a2])\n# print(a3 * a)\n# print(a)\n# #需要变换的向量或向量组 * 基地向量组 = 变换后的向量位置,因此矩阵乘法是一种‘变换’\n# #线性变换要求必须通过基地向量构成的坐标系原点,而线性变换只要是原向量发生旋转、伸缩,故比如存在一个向量,只发生了伸缩变换,\n# # 这个向量就是特征向量,故A *v = r * v,(v是A的特征向量,r是对应的特征值)\n# print('*' * 30)\n# A =[[8, 1, 6], [3, 5, 7], [4, 9, 2]]\n# evals, evecs = linalg.eig(A)\n# print(evals)\n# print(evecs)\n# print('*' * 30)\n# print(np.indices((3, 3))) #得到形状为3 * 3的矩阵的 行索引矩阵,和列索引矩阵,\n# print('*' * 30)\n\n\nimport matplotlib.pyplot as plt\nx = np.linspace(-5, 5, 200) #-5 到5 直接均匀的取200个点,返回的是ndarray类型\nprint(type(x))\ny =np.sin(x) #每个元素的正弦值\nyn = y + random.rand(1, len(y)) *1.5 #加入噪声点集\n#绘图\nfig = plt.figure() #创建一个图\n# print(type(fig))\nax = fig.add_subplot(111) #增加一个子图,位置为1,1,1,等价:fig.add_subplot(1, 1, 1)\nprint(type(ax))\nax.scatter(x, yn, c='blue') #(x,yn)离散图,蓝色\nax.plot(x, y + 0.75, 'r') #把y+0.75对x划线,红色\nplt.show()\n" }, { "alpha_fraction": 0.6791443824768066, "alphanum_fraction": 0.7112299203872681, "avg_line_length": 17.75, "blob_id": "a7438dc2c80f6f822873d78efadbfe0468fd2dfc", "content_id": "906a19a2591f6a4f69b023e54473e7a72ad09e85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 642, "license_type": "no_license", "max_line_length": 84, "num_lines": 20, "path": "/文件操作/py/文件操作基础.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import os\n#导入os可以实现rename,renames,romove等函数的调用\n#1、打开文件\nf = open('test.txt', 'r')\n#f是一个迭代器\n\n#2、操作文件\n#f.write('abc')\nprint(f.tell()) #tell函数返回当前的指针位置\nf.seek(2, 1) #往后移动当前指针2个位置,seek的第二个参数可以写(0,1,2):0:最前面;(1:当前位置;2:末尾。只能在二进制文件中使用)\nprint(f.tell())\ncontent = f.read()\n#read函数比较耗内存,当操作文件很大时,可以使用readline函数,按需取某一行,或者采用for遍历\n\n\nprint(content)\nprint(f.tell())\n\n#3、关闭文件\nf.close()" }, { "alpha_fraction": 0.638972818851471, "alphanum_fraction": 0.6540785431861877, "avg_line_length": 21.86206817626953, "blob_id": "c898f214189b5a91774b3c83c77933dd6e7d65b9", "content_id": "3b1c66eab7d07baae8efbfe84d86a75aa73cd310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1096, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/面向对象/面向对象三大特性.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# MRO:Method Resolution Order,即方法解析顺序\n#super:沿着MRO链条,找到下一级节点,并调用相应的方法:尽量全部使用super方法调用\n#suoer(参数1[,参数2]):沿着参数2的mro链条,找到参数1的下一个节点,返回下一个节点\n# def super(cls,inst):\n# mro = inst.__class__.mro()\n# return mro[mro.index(cls) +1]\n#如何应对类方法、静态方法以及实例方法的传参问题:使用参数2进行调用(第二个参数会被传送调用的方法内作为参数)\n#3.x版本:super()\n#python中无法直接实现抽象类(不能直接创建实例,创建会报错)和抽象方法(不具体实现,不能直接调用,子类必须实现该方法),需要:\n#1、导入abc模块:import abc\n#2、设置类的元类为:abc.ABCMeta\n#3、使用装饰器修饰抽象方法:@abc.abstractmethod\n\n\nclass A:\n def __init__(self):\n self.a = 'a'\n pass\n\n\nclass B(A):\n def __init__(self):\n super().__init__() #等同于 : super(B, self).__init__()\n self.b = 'b'\n pass\n\n\nb = B()\nprint(b.a)" }, { "alpha_fraction": 0.6083188652992249, "alphanum_fraction": 0.6481802463531494, "avg_line_length": 25.86046600341797, "blob_id": "a4f5fc4624669ef4b5a3daa76a7e4e686563cc3a", "content_id": "b7f3294e62aa2dcc9bd39b7b7556907e816c10a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1374, "license_type": "no_license", "max_line_length": 83, "num_lines": 43, "path": "/机器学习/CART预测回归数.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#数据可视化函数:\nimport matplotlib.pyplot as plt #画图必须导入该包\n\n\ndef plot_figure(X, X_test, y, yp): #注意矩阵对象不是1-D,不是1维的,调用tolist()方法,转换成列表\n plt.figure()\n plt.scatter(X.tolist(), y, c='k', label='data')\n plt.plot(X_test.tolist(), yp.tolist(), c='r', label='max_depth=5', linewidth=2)\n plt.xlabel('data')\n plt.ylabel('target')\n plt.title('Decision Trenn Regression')\n plt.legend()\n plt.show()\n\n\nimport numpy as np\nfrom numpy import *\nfrom sklearn.tree import DecisionTreeRegressor\n\n\nx = np.linspace(-5, 5, 200) #-5到5,均匀取200个点\nsiny = np.sin(x)\nX = mat(x).T\nprint(X.shape) #X.shape 为(200,1)\ny = siny + np.random.rand(1, len(siny)) * 1.5 #加入噪声点集:y.shape(1,200)的随机噪声\n# print(y.shape)\n# print(y.tolist())\ny = y.tolist()[0] #y是一个嵌套list,取第0个,得list\nclf = DecisionTreeRegressor(max_depth=4) #选择深度为4的回归树\nclf.fit(X, y) #从(X,y)中构建一个回归树训练集,返回self\n\n\n#预测回归\nX_test = np.arange(-5.0, 5.0, 10/200)[:, np.newaxis] #X_test.shape为(200,1)\n\nprint(X_test.shape)\nyp = clf.predict(X_test) #yp.shape:[200,]\n\nprint('yp.shape:', yp.shape)\nprint(type(yp))\n# print('x')\n# print(X.shape, X_test.shape, y1.shape, yp.shape)\nplot_figure(X, X_test, y, yp)" }, { "alpha_fraction": 0.5518292784690857, "alphanum_fraction": 0.5579268336296082, "avg_line_length": 18.352941513061523, "blob_id": "9f063bd846cfb78e380c50aa3dc2b8ce97a9bfa0", "content_id": "b7dd71d3f7e6d527b224480c75ba0764dded3847", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 36, "num_lines": 17, "path": "/helloworld/斐波那契数列.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import time\na, b = 0, 1\n# print(a)\nfbnqlst = [a, b]\nmax = eval(input(\"您需要多大以内的菲波那切数列?\"))\nstart = time.clock()\nwhile a+b < max:\n # print(b, end=',')\n a, b = b, a + b\n fbnqlst.append(b)\nelse:\n for le in fbnqlst :\n print(le,end=',')\n print('End!')\n # print(zhishulist)\nend = time.clock()\nprint(end - start)" }, { "alpha_fraction": 0.4479166567325592, "alphanum_fraction": 0.5520833134651184, "avg_line_length": 16.545454025268555, "blob_id": "3412a80541a525d4ba6af3d676765287c49f825b", "content_id": "54ed1d44094fe953b40109087bad26a28c33b86f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 36, "num_lines": 11, "path": "/helloworld/元组.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#元组:有序的,不可变的集合(可哈希的)\n#定义\nt1 = (1,)\nt2 = (1, '2', True, t1)\nt3 = 1, '3', t2\nprint(type(t1), type(t2), type(t3),)\n#从列表中转换\nt1 = [1, 'sz', True]\nct = tuple(t1)\nprint(ct, type(ct))\nprint(t1[0:14:])" }, { "alpha_fraction": 0.6470588445663452, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 16, "blob_id": "c753686314c553e9124b2b48cf4ac8f79a7ba495", "content_id": "9d41e2be8823ea05673365164d3b5d9a5fa10062", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 152, "license_type": "no_license", "max_line_length": 23, "num_lines": 6, "path": "/helloworld/反转字符串.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#利用字符串的加法顺序实现反转\nstr1 = '为社会服务,为人民服务'\nrusult = ''\nfor c in str1:\n rusult = c + rusult\nprint(rusult)\n" }, { "alpha_fraction": 0.6516854166984558, "alphanum_fraction": 0.6554307341575623, "avg_line_length": 15.6875, "blob_id": "5a2b632531839bdc89a1041ec987e25a9b1ca0a4", "content_id": "2d7ed517191965b34ad573e878870415b2a2ef51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 279, "license_type": "no_license", "max_line_length": 40, "num_lines": 16, "path": "/venv/Lib/site-packages/comm_libs/db_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding=utf8\nfrom django.db import connection\nfrom libs.log_tool import write_info_log\n\n\ndef execute_sql(sql):\n \"\"\"直接执行sql语句\n\n :param sql:\n :return:\n \"\"\"\n\n cursor = connection.cursor()\n write_info_log(sql)\n cursor.execute(sql)\n return cursor\n" }, { "alpha_fraction": 0.6705882549285889, "alphanum_fraction": 0.7176470756530762, "avg_line_length": 16.894737243652344, "blob_id": "9a01993cc6d974b4f0a65f79b42860608ff0d0dd", "content_id": "0cd56ef59ec169ed8ea36937be08f4fe9cc4563c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 548, "license_type": "no_license", "max_line_length": 46, "num_lines": 19, "path": "/文件操作/py/图片操作.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#需求:将一个图片信息的钱半部分写入到另一个文件中\n#1、打开文件,取出文件前半部分\n#1.1 打开源文件\nfromFile = open('顺序.png', 'rb')\n#1.2 取出前半部分数据\nfromContent = fromFile.read()\ncontent = fromContent[0:len(fromContent) // 2]\n#1.3 关闭文件\nfromFile.close()\n\n\n\n#2、打开另一个文件,将取出的内容写入\n#2.1 打开目标文件\ntoFile = open('顺序一半.png', 'wb')\n#2.2 将取出前半部分数据写入到目标文件\ntoFile.write(content)\n#2.3 关闭文件\ntoFile.close()\n" }, { "alpha_fraction": 0.5377358198165894, "alphanum_fraction": 0.5448113083839417, "avg_line_length": 16.625, "blob_id": "84c1c7ea460766e23afb6cf9634969501158dc57", "content_id": "30da2efaee9a42a182ca1277304f84b781f4cda8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 444, "license_type": "no_license", "max_line_length": 51, "num_lines": 24, "path": "/venv/Lib/site-packages/comm_libs/file_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding=utf8\n\nimport datetime\nimport hashlib\nfrom libs.codec_utils import _code\n\n\ndef get_random_filename(files):\n \"\"\"\n 获取一个随机名称\n\n :param files: 文件\n :return:\n \"\"\"\n\n after = ''\n if str(files).__contains__('.'):\n after = '.%s' % (str(files).split('.')[-1])\n\n now = datetime.datetime.now()\n h = hashlib.md5()\n h.update('%s%s' % (now, _code()))\n\n return '%s%s' % (h.hexdigest(), after)\n\n" }, { "alpha_fraction": 0.6545064449310303, "alphanum_fraction": 0.6566523313522339, "avg_line_length": 30.08888816833496, "blob_id": "ac4a1383ab33c9805fc53d46de843c3681e72795", "content_id": "d744505d14383482a4aa141bcc20b2f482fb437f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2430, "license_type": "no_license", "max_line_length": 255, "num_lines": 45, "path": "/函数/装饰器.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#-----------------------装饰器----------------------------------------------------------------\n#装饰器:在不改变函数名和函数体的前提下,给函数增加一些额外代码.(利用闭包的特性实现不改变函数单一功能且不改变业务逻辑代码,注:装饰器是立即执行的)\n#语法:函数上面一行加语句:@额外代码块或函数\n\n\n# class ChekLogin:\n# def __init__(self, needBeDecFunc):\n# self.f = needBeDecFunc #因为@CheckLogin(语法糖) 等同于语句:fss = CheckLogin(fss),创建一个CheckLogin实例,参数为fss函数,并赋值给fss,在执行 CheckLogin(fss)时会调用init函数,需要将原被装饰的函数存储在实例对象的一个属性中去,因此业务逻辑模块中,被装饰函数就成了装饰器的一个实例,当调用被装饰函数的时候,就需要实现call函数,在call函数中加入需要添加的代码块,并执行被装饰函数即可\n#\n# def __call__(self, *args, **kwargs): #实现该方法可以做到:实例对象可以像调用方法一样被调用,执行该方法\n# print('验证登录.......')\n# self.f()\n\n\ndef chekLogin(needDec): #needDec 需要被装饰的函数,也可以用类来实现,如ChekLogin类\n def inner(*args, **kwargs):#inner函数里面加上通用参数可以实现装饰器通用,可以装饰具有不同参数长度的函数,此为约定俗成的做法,名称也可以更改,注意inner函数体格式应该与被装饰函数体一致\n print('验证登录.......')\n res = needDec(*args, **kwargs)\n return res #被装饰的函数内有返回值也是需要保持同样格式\n return inner #inner函数实际上就是指向被装饰的函数,将inner返回\n#该装饰器已经为通用装饰器,可以装饰不同参数,和是否有返回值\n\n# @chek_login\n@chekLogin #等同于语句:fss = checkLogin(fss)\ndef fss():\n print('发说说')\n\n\n@chekLogin\n#@checkLogin 等同于在函数后面 执行了一条语句:ftp = checkLogin(ftp)\ndef ftp():\n print('发图片')\n\n@chekLogin\ndef flj(str):\n print(str)\n#相关业务逻辑代码\nindex = 3\nif index == 0:\n fss()\nelif index == 1:\n ftp()\nelse:\n flj('www.baidu.com')\n#以上代码实现了在发说说和发图片之前验证登录,而不变更业务逻辑代码,且不违反函数单一功能原则" }, { "alpha_fraction": 0.4720982015132904, "alphanum_fraction": 0.4799107015132904, "avg_line_length": 22.906665802001953, "blob_id": "8da898560971a8cfc0e95f3477d291293ae60d36", "content_id": "94a66aa09e76fbb8e5a3618d2688ffce2abe8aec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2250, "license_type": "no_license", "max_line_length": 109, "num_lines": 75, "path": "/面向对象/面向对象综合案例.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import inspect\n#inspect.getmro(class) 或 class.mro() 返回class类的资源查找顺序 3.x版本全是新式类,采用C3算法\n#需求:定义猫、狗、人三个类\n#狗:姓名、年龄(默认1):吃饭、玩、睡觉、看家(格式:我的名字是xx,年龄xx的小狗在XX)\n#猫:姓名、年龄(默认1):吃饭、玩、睡觉、捉老鼠(格式:名字是xx,年龄xx的小狗在XX)\n#人:姓名、年龄(默认1),宠物:吃饭、玩、睡觉、捉老鼠(格式:名字是xx,年龄xx的小狗在XX)\n# 养宠物(让所有的宠物吃饭、玩、睡觉)\n# 让宠物工作(让所有的宠物根据自己的职责开始工作)\n#--------------------------------代码实现------------------------------------------------------------------------\n#需求:定义猫、狗、人三个类\nimport abc\n\n\nclass Animal:\n def __init__(self, name, age):\n if isinstance(name, str) and isinstance(age, int):\n if 0 < age < 200:\n self.age = age\n self.name = name\n else:\n print('age error')\n else:\n print('格式错误!')\n\n def eat(self):\n print('%s eat' % self)\n\n def drink(self):\n print('%s drink' % self)\n\n def sleep(self):\n print('%s sleep' % self)\n\n def play(self):\n print('%s play' % self)\n\n def __str__(self):\n return '我的名字是{},年龄{}岁的{}在'.format(self.name, self.age, self.__class__.__name__)\n\n\nclass Dog(Animal):\n def job(self):\n print('%s kan_jia' % self)\n\n\nclass Cat(Animal):\n def job(self):\n print('%s catch_mouse' % self)\n\n\nclass People(Animal):\n def __init__(self, name, pet, age=1):\n super().__init__(name, age)\n self.pets = pet\n\n def yang_pets(self):\n pet: Animal\n for pet in self.pets:\n pet.eat()\n pet.drink()\n pet.play()\n pet.sleep()\n\n def pets_job(self):\n for pet in self.pets:\n pet.job()\n\n\nd = Dog('dog-d', 5)\nc = Cat('cat-c', 7)\np = People('ZYF', [d, c], 28)\nprint(p.__dict__)\np.yang_pets()\np.pets_job()\n# print(c.__class__.__name__)" }, { "alpha_fraction": 0.44760212302207947, "alphanum_fraction": 0.5310834646224976, "avg_line_length": 33.15151596069336, "blob_id": "b40cc25826a530150d7670800e5aa2aba1bd9e1a", "content_id": "36f4b2e64dfce269d7ba385b127322ee94c19917", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 90, "num_lines": 33, "path": "/venv/Lib/site-packages/comm_libs/regular_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\nimport re\nimport sys\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n# 业务配置\nREGULAR_MATCH = {\n \"user_name\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\·]+$',\n \"user_mobile\": ur'^1[34578]\\d{9}$',\n \"community_name\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\#\\-\\-\\_\\–\\*\\#\\(\\)\\#\\—\\*\\(\\)\\w]+$',\n \"house_number\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\#\\-\\-\\_\\–\\*\\#\\(\\)\\#\\—\\*\\(\\)\\w]+$',\n \"room_number\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\#\\-\\-\\_\\–\\*\\#\\(\\)\\,\\#\\—\\*\\(\\)\\,\\w]+$',\n \"monthly_amount\": ur'^[1-9]+(\\d)*$',\n \"broker_uniq_id\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\#\\-\\-\\_\\–\\*\\#\\(\\)\\#\\—\\*\\(\\)\\s\\w]+$',\n \"owner_name\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\·]+$',\n \"owner_phone\": ur'^1[34578]\\d{9}$',\n \"owner_bank_account\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\·]+$',\n \"owner_bank\": ur'^[\\u4E00-\\u9FA5\\uf900-\\ufa2d]+$',\n \"owner_card_no\": ur'^\\d{16,20}$'\n}\n\ndef regular_match_params(regular_rule, param):\n \"\"\"\n 正则校验\n :param regular_rule:\n :param param:\n :return:\n \"\"\"\n pattern = re.compile(regular_rule)\n # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None\n match_remark = pattern.match(param)\n return match_remark" }, { "alpha_fraction": 0.7086834907531738, "alphanum_fraction": 0.7226890921592712, "avg_line_length": 43.66666793823242, "blob_id": "903a7533e40be5ca1b23e1645e4448b7157ae2f5", "content_id": "2626522bedd5cf8f22707ac4022a5fe55fe774eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 123, "num_lines": 24, "path": "/机器学习/knn_cos.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import *\nimport operator\n# from Nbayes_lib import *\n\n\ndef cosdist(vector1, vector2):\n return dot(vector1, vector2)/(linalg.norm(vector1) * linalg.norm(vector2))\n\n\ndef clssify(testDate, trainSet, listClasses, k): #listClasses:类别标签\n dataSetSize = trainSet.shape[0] #返回样本集的行数\n distances = array(zeros(dataSetSize))\n for index in range(dataSetSize):\n distances[index] = cosdist(testDate, trainSet[index])\n sortedDistIndicies = argsort(-distances) #返回对数据排序的索引,这里是-distances表示从余弦值从大到小排列,越大说明夹角越小\n classCount = {}\n for i in range(k): #获取角度最小的前k项作为参考项\n voteIlabel = listClasses[sortedDistIndicies[i]] #按排序顺序返回样本集对应的类别标签\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 #为字典clssCount赋值(标签,标签出现次数),如果key相同,则value +1,如果不存在则赋值为0\n #get(key, default) 函数返回指定键的值,如果值不在字典中返回默认值\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)\n #sorted(可迭代对象,key=operator.itemgetter(1),reverse = True)是sorted的固定用法\n return sortedClassCount[0][0]" }, { "alpha_fraction": 0.662866473197937, "alphanum_fraction": 0.6970683932304382, "avg_line_length": 21.77777862548828, "blob_id": "336f779c8c28da6bf634e3ca877472135cade6fc", "content_id": "71a98f7878a76675bad37458fedc06a814d9bd96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 119, "num_lines": 27, "path": "/面向对象/内存管理.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#python 使用引用计数器机制、“标记-清除”和垃圾回收机制并存。计数器机制无法解决循环引用的问题,垃圾回收机制可以\nimport gc\nimport weakref\n#------------自动回收-----------\nprint(gc.isenabled()) #查看垃圾自动回收机制是否开启\nprint(gc.get_threshold()) #查看当前机制的默认参数,返回元组(700,10,10):新增对象个数-消亡对象个数 达到700触发,0代触发10次则触发0代和1代的检测,1代触发10次,会触发0代、1代和2代的检测\n#-----------手动回收-------------\n\nimport objgraph\nclass Person:\n pass\n\n\nclass Dog:\n pass\n\n\np = Person()\nd = Dog()\np.pet = d\nd.master = p\n#创造了一个循环引用,以后写代码的时候开业通过弱引用来规避循环引用,d.master = weakref.ref(p) 弱引用,不会造成计数器增减\ndel p\ndel d\ngc.collect() #参数不写,则回收所有代的垃圾\nprint(objgraph.count('Person')) #打印Person类产生的对象有多少个\nprint(objgraph.count('Dog'))" }, { "alpha_fraction": 0.5339758992195129, "alphanum_fraction": 0.5498794913291931, "avg_line_length": 24.623456954956055, "blob_id": "1a27acbbb98d41508325505bd34a5f42bbf4bdf8", "content_id": "e4a344a658d998ed1d5ea516804eba1779f459df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4614, "license_type": "no_license", "max_line_length": 93, "num_lines": 162, "path": "/venv/Lib/site-packages/comm_libs/security.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\nimport base64\nimport hashlib\n\nimport OpenSSL\nfrom Crypto.Hash import SHA\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.PublicKey import RSA\n\n\nclass RsaEncryptor(object):\n \"\"\"Rsa加解密实现类\n\n 公钥格式必须是 pkcs#8 pem\n 私钥格式必须是 x509 der\n\n Example:\n rsa_encryptor = security.RsaEncryptor(\"d:/public_key.der\", \"d:/private_key.pk8\")\n\n param_dict = {\n 'name' : 'hello',\n 'pass' : '123',\n 'date' : '2012-12-12 00:00:00'\n }\n\n # 生成参数签名\n sig = rsa_encryptor.sign(param_dict)\n\n #检查签名\n print rsa_encryptor.check_sign(param_dict, sig)\n\n\n Attributes:\n pubkey_path (str): 公钥文件路径\n prikey_path (str): 私钥文件路径\n \"\"\"\n def __init__(self, pubkey_path = None, prikey_path = None,\n pubkey_bytes = None, prikey_bytes = None):\n if (not pubkey_path and not pubkey_bytes) or (not prikey_path and not prikey_bytes):\n raise RsaEncryptorException(\"初始化失败,找不到密钥文件!\")\n\n pubkey_der = None\n pubkey_pk8 = None\n\n if pubkey_path and prikey_path:\n # 加载公钥\n pubkey_der = open(pubkey_path, 'rb').read()\n # 加载私钥\n pubkey_pk8 = open(prikey_path, 'rb').read()\n elif pubkey_bytes and prikey_bytes:\n pubkey_der = pubkey_bytes\n pubkey_pk8 = prikey_bytes\n pass\n else:\n raise RsaEncryptorException(\"初始化失败找,不到密钥文件!\")\n\n # 转换公钥格式DER为PEM\n pubkey = OpenSSL.crypto.load_publickey(OpenSSL.crypto.FILETYPE_ASN1, pubkey_der)\n pem_pubkey = OpenSSL.crypto.dump_publickey(OpenSSL.crypto.FILETYPE_PEM, pubkey)\n\n # 公钥\n self.__pubkey = RSA.importKey(pem_pubkey)\n # 私钥\n self.__prikey = RSA.importKey(pubkey_pk8)\n\n def encrypt(self, plaintxt):\n \"\"\"使用rsa公钥对文本进行加密返回文本是经过BASE64编码过的\n Args:\n plaintxt (str): 需要加密的原文\n Returns:\n str: Base64编码的密文\n \"\"\"\n raw_bytes = self.__pubkey.encrypt(plaintxt, 32)[0]\n\n return base64.encodestring(raw_bytes)\n\n def decrypt(self, ciphertxt):\n \"\"\"使用rsa私钥对加密文本进行解密\n Args:\n ciphertxt (str): 经过base64编码的密文\n Returns:\n str: 原文\n \"\"\"\n raw_bytes = base64.decodestring(ciphertxt)\n return self.__prikey.decrypt(raw_bytes)\n\n\n def sign(self, params_dict):\n \"\"\"使用rsa私钥对参数进行签名\n Args:\n params_dict (dict): 需要签名的参数字典 eg.{'name': 'li', 'password': '123456'}\n Returns:\n str: 签名\n \"\"\"\n param_str = self.concat_params(params_dict)\n\n digest = self.md5digest(param_str)\n\n signer = PKCS1_v1_5.new(self.__prikey)\n\n h = SHA.new(digest)\n\n sign = signer.sign(h)\n\n return base64.encodestring(sign)\n\n def check_sign(self, params_dict, signature):\n \"\"\"使用rsa公钥对签名进行验证\n Args:\n params_dict (dict): 待验证参数字典\n signature (str): 参数签名\n Returns:\n bool: true 通过 false 不通过\n \"\"\"\n\n param_str = self.concat_params(params_dict)\n digest = self.md5digest(param_str)\n\n verifier = PKCS1_v1_5.new(self.__pubkey)\n\n h = SHA.new(digest)\n\n return verifier.verify(h, base64.decodestring(signature))\n\n def concat_params(self, params_dict):\n \"\"\"将参数字典以key=value&key2=value2的形式凭借\n Args:\n params_dict (dict): 参数字典\n Returns:\n str: 拼接后的参数字符串\n \"\"\"\n keys = params_dict.keys()\n keys.sort()\n\n param_str = ''\n for i in keys:\n if not param_str:\n param_str += '%s=%s' % (i, params_dict[i])\n else:\n param_str += '&%s=%s' % (i, params_dict[i])\n\n return param_str\n\n def md5digest(self, txt):\n \"\"\"md5摘要方法\n Args:\n txt (str): 需要处理的文本\n Returns:\n str: 摘要信息\n \"\"\"\n md5 = hashlib.md5()\n md5.update(txt)\n return md5.hexdigest()\n\n\nclass RsaEncryptorException(Exception):\n def __init__(self, msg):\n self.message = msg\n\n def __str__(self):\n return self.message" }, { "alpha_fraction": 0.5872378349304199, "alphanum_fraction": 0.6215975284576416, "avg_line_length": 32.44776153564453, "blob_id": "59b856f3f1787f5e37b3b4f88324b39665539456", "content_id": "573b685c9c8c6cca8b83e1548afea9256a37357e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2457, "license_type": "no_license", "max_line_length": 99, "num_lines": 67, "path": "/venv/Lib/site-packages/comm_libs/subrent_pay_date_amend.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\nimport datetime\n\nfrom db_models.tables.agency import Agency\nfrom libs.log_tool import write_error_log\n\n__author__ = 'zeqiang'\n\n\ndef amend_subrent_pay_date(subrent, agency_id):\n \"\"\"\n 修正打款时间\n :return:\n \"\"\"\n pay_date = subrent.pay_date\n if not agency_id:\n agency_id = 10000\n write_error_log(agency_id)\n today = datetime.date.today()\n # today = datetime.date(2015, 11, 30)\n agency = Agency.objects.get(agencyid=agency_id)\n\n if agency.agency_type in [2, 3]: # 中介或公寓延后1天打款\n pay_date = pay_date + datetime.timedelta(days=1)\n elif agency.agency_type == 1: # 如果是C端,打款天数减1\n pay_date = pay_date + datetime.timedelta(days=-1)\n\n diff_month = pay_date.year * 12 + pay_date.month - (today.year * 12 + today.month)\n\n if agency.agency_type == 2 and pay_date.day <= 6 and diff_month > 0: # 普通中介,提前打至下个月5号,含5号。\n pay_date = pay_date - datetime.timedelta(days=pay_date.day)\n elif agency_id in [1717, 1472] and diff_month > 0: # 如果是天地昊和中润,打款时间为上月最后一天\n pay_date = pay_date - datetime.timedelta(days=pay_date.day)\n\n if today >= pay_date:\n if agency.agency_type in [2, 3]:\n pay_date = today + datetime.timedelta(days=1)\n else:\n pay_date = today\n\n subrent.pay_date = pay_date\n\n\ndef amend_subrent_pay_date_for_subrent_list(subrent_list, agency_id):\n \"\"\"\n 修正打款时间\n :return:\n \"\"\"\n if len(subrent_list) > 0:\n if not agency_id:\n agency_id = 10000\n\n agency = Agency.objects.get(agencyid=agency_id)\n\n today = datetime.date.today()\n subrent = subrent_list[0]\n pay_date = datetime.datetime.strptime(subrent[\"pay_date\"], \"%Y-%m-%d\").date()\n diff_month = pay_date.year * 12 + pay_date.month - (today.year * 12 + today.month)\n\n if agency.agency_type == 2 and pay_date.day <= 6 and diff_month > 0: # 普通中介,提前打至下个月5号,含5号。\n pay_date = pay_date - datetime.timedelta(days=pay_date.day)\n elif agency_id in [1717, 1472, 1000000004] and diff_month > 0: # 如果是天地昊和中润,打款时间为上月最后一天\n pay_date = pay_date - datetime.timedelta(days=pay_date.day)\n\n subrent[\"pay_date\"] = datetime.datetime.strftime(pay_date, '%Y-%m-%d')\n\n return subrent_list\n" }, { "alpha_fraction": 0.539229691028595, "alphanum_fraction": 0.56148362159729, "avg_line_length": 26.817461013793945, "blob_id": "148d6b9c1139f20e583fac39fce953a8d0831c65", "content_id": "e98744417d3f09cbe113bf1ba48ba8901f79cb51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3971, "license_type": "no_license", "max_line_length": 144, "num_lines": 126, "path": "/venv/Lib/site-packages/comm_libs/template_msg.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\nimport json\n\nimport requests\nfrom libs.log_tool import write_info_log\n\n\nclass TemplateMsg:\n __mq_url = \"http://www.huifenqi.com/mq/sendtemplatemsg/\"\n\n def __init__(self, template_id=\"\", user_type=1):\n self.template_id = template_id\n self.user_type = user_type\n self.to_users = []\n self.properties = {}\n self.wx_properties = {}\n self.transmission = {}\n\n def set_template_id(self, template_id):\n \"\"\"\n 设置模板id\n :param template_id:\n :return:\n \"\"\"\n self.template_id = template_id\n\n def set_to_users(self, to_users):\n \"\"\"\n 设置接收消息手机号,数组\n :param to_users:\n :return:\n \"\"\"\n self.to_users = to_users\n\n def add_to_users(self, phone):\n \"\"\"\n 添加接收消息手机号,数组\n :param phone:\n :return:\n \"\"\"\n self.to_users.append(phone)\n\n def set_user_type(self, user_type):\n \"\"\"\n 设置接受者用户类型 0:租客 1:经纪人\n :param to_users:\n :return:\n \"\"\"\n self.user_type = user_type\n\n def set_transmission(self, transmission):\n \"\"\"\n 设置短信透传内容\n :param transmission:\n :return:\n \"\"\"\n self.transmission = transmission\n\n def add_transmission_param(self, key, value):\n \"\"\"\n 添加透传 transmission 参数\n :param key:\n :param value:\n :return:\n \"\"\"\n self.transmission[key] = value\n\n def set_properties(self, properties):\n \"\"\"\n 设置接受者用户类型 0:租客 1:经纪人\n :param to_users:\n :return:\n \"\"\"\n self.properties = properties\n\n def add_properties_param(self, key, value):\n \"\"\"\n 添加 properties 参数\n :param key:\n :param value:\n :return:\n \"\"\"\n self.properties[key] = value\n\n def add_wx_properties_param(self, key, value):\n \"\"\"\n 添加 properties 参数\n :param key:\n :param value:\n :return:\n \"\"\"\n self.wx_properties[key] = value\n\n\n def send_mq(self):\n msg = {\"msg\": json.dumps({\n \"template_id\": self.template_id,\n \"to_users\": self.to_users,\n \"user_type\": self.user_type,\n \"transmission\": self.transmission,\n \"properties\": self.properties,\n \"wx_properties\": self.wx_properties,\n })}\n response = requests.post(self.__mq_url, msg)\n # print \"send_template_msg[%s] response[%s]\" % (msg, response.text)\n write_info_log(\"send_template_msg[%s] response[%s]\" % (msg, response.text))\n\n\nif __name__ == '__main__':\n # properties = {\n # \"first\": \"您好,您申请的分期未通过审核\",\n # \"keyword1\": \"未通过\",\n # \"keyword2\": \"信息录入错误需修改\",\n # \"remark\": \"您的分期合同信息录入时出现错误,现经纪人已经帮您修改完成,请您再次确认!\",\n # \"url\": \"http://www.huifenqi.com/c/scansinged/?cno=2016195222&phone=15652486096&platform=inner\"\n # }\n template_msg = TemplateMsg('0001NMC14gy2KOe1B2a820160928171352', 0)\n template_msg.add_to_users(15311432059)\n\n template_msg.add_properties_param(\"k1\", \"1\")\n template_msg.add_wx_properties_param(\"first\", \"本月还款提醒\")\n template_msg.add_wx_properties_param(\"keyword1\", \"亲爱的会分期用户,10月1号是您的分期还款日,请在9月30号之前保证绑定的银行卡内余额充足,避免国庆期间因银行放假导致延迟到账或者扣款失败而产生逾期滞纳金,提前祝您国庆节快乐!\")\n template_msg.add_wx_properties_param(\"keyword2\", \"每月1号\")\n template_msg.add_wx_properties_param(\"keyword3\", \"2期\")\n template_msg.add_properties_param(\"url\", \"http://www.huifenqi.com/wx/repayment/html/select.html\")\n template_msg.send_mq()\n" }, { "alpha_fraction": 0.4270923137664795, "alphanum_fraction": 0.47713544964790344, "avg_line_length": 32.14285659790039, "blob_id": "a6783fc81a9e0d9173edad72f6f42124c4264345", "content_id": "c17780da09195289712bfa10098516f2c49f8e6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1625, "license_type": "no_license", "max_line_length": 87, "num_lines": 35, "path": "/helloworld/集合.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#不可重复,不可通过下标访问,无序的序列;与数学中集合类似,可以进行交、并、补运算; s = {直接输入};s = set(iter);frozenset为不可变集合\n#集合中的元素必须是可哈希的:1,\"abc\",true,不能为列表、字典等\n#当iter为字典的时候集合为key的集合\ns = {1, 2, 3, 4, 1}\ns = {x ** 2 for x in range(11) if x % 2 == 0}\n# s = set(x ** 2 for x in range(11) if x % 2 == 0)\nprint(s, type(s))\ns = {1, 2, 3, 4, 1}\ns.add('5')\nprint(s)\n#----------------------删除集合中元素---------------------------------------------------------\n#s.remove(element):移除元素中element元素,若没有则报错\n#s.discard(element):删除集合中element元素,没有则什么都不做\n#s.pop():随机删除并返回一个集合中的元素,若集合为空,则报错\ns = {1, 2, 3, 4, 1}\ns.pop()\nprint(s)\ns.pop()\nprint(s)\n#s.clear():清空集合中所有元素\n#----------------------遍历集合中元素---------------------------------------------------------\ns = {1, 2, 3, 4, 1}\nitr = iter(s)\nfor v in itr:\n print(v)\n\n#----------------------集合的运算---------------------------------------------------------\n#交集:s1.intersection(s2) 返回的集合类型同s1;s1 & s2\n#并集:s1.union(s2) 返回并集;s1 | s2;(s1.update(s2)会更新s1)\n#差集:s1.difference(s2);s1 - s2;(difference_update()对象函数会更新原对象)\n\n#----------------------集合的判断---------------------------------------------------------\n#s1.isdisjoint(s2) 是够不相交\n#s1.superset(s2) s1是否包含s2\n#s1.subset(s2) s1是否为s2的子集" }, { "alpha_fraction": 0.5593841671943665, "alphanum_fraction": 0.599706768989563, "avg_line_length": 29.33333396911621, "blob_id": "401973674795c6655aa05a8fa6d13aaf39999a86", "content_id": "5a0b4d235d5b5dfee81565d420fe2c056d24a2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2004, "license_type": "no_license", "max_line_length": 113, "num_lines": 45, "path": "/机器学习/SVD奇异值分解.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nimport svdRec\nfrom svdRec import *\nfrom numpy import *\n#A的每一行表示每一个用户,每一列表示每一种物品,数值表示为用户对物品的偏好。\nA = np.array([[5, 5, 3, 0, 5, 5], [5, 0, 4, 0, 4, 4], [0, 3, 0, 5, 4, 5], [5, 4, 3, 3, 5, 5]]) #A的形状(6,4)\nA = mat(A)\n# A.H() A的共轭转置\nprint(A)\na_SVD = np.linalg.svd(A) #一个元组类型,有3个元素\nprint(type(a_SVD))\nprint(a_SVD.__len__())\nprint(a_SVD[0]) #第一个元素为u:向量,正交,(4,4)\nprint('*' * 30)\nprint(a_SVD[1]) #第二个元素为s:奇异值矩阵,ndarray,降序,(打印出为4个元素的list,是为了numpy节省空间的做法,因为除了对角线的元素为奇异值之外,其余都是0)\nprint(a_SVD[1][1])\nprint('奇异值的类型是:', type(a_SVD[1]), len(a_SVD[1]))\nprint('*' * 30)\nprint(a_SVD[2]) #第三个元素为vh:向量,正交(6,6)\nprint('*' * 30)\nu = a_SVD[0]\ns = a_SVD[1]\nvh= a_SVD[2]\n\n#原理A = u * sigma * vh\n# 若保留r个奇异值,则A近似等于:u[:,:r] * sigma[:r, :r] * vh[:3, :]。u的前r列,vh的前r行\n#其中:u会将物品(列)映射到A中;vh会将用户(行)映射到A中。通常用户数量远大于物品数量,为了节省计算时间,采用Item CF方式。\n#给定一些用户行testV,采用Item CF方式,即将物品映射到空间去. #result = testV * A--->result = testV *u[:,:r] *linalg.inv(sigma[:r, :r])\n#保留奇异值个数r的取值问题:平方和接近总值90%;或根据经验取.\ndef get_sigma(r, s):\n zero = np.zeros((r, r))\n i = 0\n s = s.tolist()\n while i < len(s):\n zero[i][i] = s[i]\n i += 1\n return zero\n#该函数等同于:return diag(s)[:r,:r] 等同于:eye(r) * s[]\nr = 4\nsigma = get_sigma(r, s)\n# print(sigma.shape)\nprint(u[:, :r] * sigma * vh[:r, :])\nprint('END!')\n#原理A =vh * 奇异值对角矩阵 * u.T\nsvdRec.recommends_for_user() #创建一个svdRec实例,调用该方法可以" }, { "alpha_fraction": 0.5995671153068542, "alphanum_fraction": 0.6046175956726074, "avg_line_length": 28.510639190673828, "blob_id": "92ab9f9439b8c7885d29f4d4d7feb6044fb27461", "content_id": "a0f1184ea852bee556154378ea5c1dde48fc627f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2142, "license_type": "no_license", "max_line_length": 94, "num_lines": 47, "path": "/面向对象/只读属性优化版.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "class Person:\n \"\"\"\n 这是一个人,类\n \"\"\"\n #setatter方法只有在使用'对象.属性 = 值'方式给实例增加一个属性,或者更改属性值的时候回调用,在这个方法内部才会真正将这个属性以及对应得值,存储到__dict__中\n def __setattr__(self, key, value):\n if key == 'age' and key in self.__dict__.keys(): #假设要设置age为只读属性\n print('这是一个只读属性,不能设置,更改')\n else:\n self.__dict__[key] = value\n\n def __str__(self):\n '''\n 当以后出现print这个实例对象时会触发这个函数,主要用于格式化输出信息\n :return: 格式化的输出信息\n '''\n return '这个人的年龄是:%d' % self.age\n\n def __init__(self):\n self.dicAttr = {'name': 'zyf', 'high': 180} #构造函数创建一个sx属性,为字典,当对象使用字典操作时可以实现存储到sx属性里\n\n def __getitem__(self, item):\n print('实现get、set、del三个内置函数可以把实例对象当成字典或列表一样操作,如索引,切片')\n return self.dicAttr[item]\n\n def __setitem__(self, key, value):\n print('实现get、set、del三个内置函数可以把实例对象当成字典或列表一样操作,如索引,切片')\n self.dicAttr[key] = value\n\n def __delitem__(self, key):\n print('实现get、set、del三个内置函数可以把实例对象当成字典或列表一样操作,如索引,切片')\n del self.dicAttr[key]\n\n def __call__(self, *args, **kwargs):\n print('实现该方法可以做到:实例对象可以像调用方法一样被调用,执行该方法')\n\np = Person()\np.age = 18 #此时会调用__setattr__方法,age此时不在字典里,故添加该属性和值\nprint(p.__dict__)\np.age = 99 #此时age已经存在在字典里,故不会再添加,也不会更改age的值\nprint(p.age)\nprint(Person.__bases__) #父类元组\nprint(Person.__module__) #类定义所在模块\nprint(Person.__doc__) #类的说明文档\nprint(p)\nprint(p.dicAttr['name'])\np()" }, { "alpha_fraction": 0.6372670531272888, "alphanum_fraction": 0.6559005975723267, "avg_line_length": 31.239999771118164, "blob_id": "3da17dc4c3499ac514e04e5f45151f2850b714ae", "content_id": "9a1d9ec6de75c946ba3e0a670660d20d80838f1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1453, "license_type": "no_license", "max_line_length": 116, "num_lines": 25, "path": "/函数/生成器.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#--------------------生成器----------------------------------------------\n#生成器:特殊的迭代器,抽象层级更高。使用生成器可以不保存数据,只在next用的时候计算,省内存\n#1、直接将表达式导出列表的方式中的[]换成()\nlst = (i for i in range(1, 101) if i % 2 == 0) #此时l式一个生成器,可通过for循环迭代和next()函数访问;next函数不能将最后一个field语句后面的代码执行,而for遍历可以\nprint(lst)\nprint(next(lst))\nprint(next(lst))\nprint(lst.__next__()) #和上面的next(lst)式等同的\n\n\n#2、生成器函数:函数中包含yield 语句,该函数的执行结果就是生成器\n#yield 会阻断当前函数的执行,并把yield后面的状态值返回,当使用next()函数时会继续执行,直到被下一个field语句阻断;遇到return就会抛出异常,并将return 后面的值返回\nprint('=' *30)\ndef ouShu():\n for i in range(1,11):\n if i % 2 == 0:\n yield i #阻断程序执行,并返回i\n\n\ng = ouShu() #到当前位置为止,函数都未被执行,返回的是一个生成器,只有当执行next()函数时,函数才会被启动\nprint(g)\nfor i in g:\n print(i)\ng.close() #关闭生成器 等同于将生成器指向最后一个\n#.send(num) 可以给上一次yield语句一条返回值,为num,send与next一样也会继续执行,指定碰到新的yield语句" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5423728823661804, "avg_line_length": 18.75, "blob_id": "037a5d7bedc91403a179c3cdba605819cd4cf7d9", "content_id": "d595316750c3a18f77fbe1406ea208bfdc8cc7e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/helloworld/递归实现斐波那契.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "def fibonacci(n):\n '''\n\n :param n: 菲波那切数列的第几位数,第0位是0,第1位是1\n :return: 第n位菲波那切数列的值\n '''\n if (n == 0 or n == 1):\n return n\n return fibonacci(n - 1) + fibonacci( n - 2)\n\nfor i in range(0, 8):\n print(fibonacci(i))" }, { "alpha_fraction": 0.44915252923965454, "alphanum_fraction": 0.5112994313240051, "avg_line_length": 24.285715103149414, "blob_id": "870eff3809bf21470eee23b3872edf65bcded4f0", "content_id": "4c5b250298966fd29ce274007dd41081d1267bff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 43, "num_lines": 14, "path": "/helloworld/break和continue应用.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "while True :\n num1 = float(input('请输入第一个数字(0,100):'))\n if not(0 <= num1 <= 100) :\n print('InputErr')\n continue\n num2 = float(input('请输入第二个数字(0,100):'))\n if not(0 <= num1 <= 100):\n print('InputErr')\n continue\n result = num1 + num2\n print(result)\n isQ = input('任意键继续,q退出!')\n if isQ == 'q':\n break\n" }, { "alpha_fraction": 0.515625, "alphanum_fraction": 0.5625, "avg_line_length": 18.299999237060547, "blob_id": "0bfa55f9ad5317234a02121054112d6b67d0f94d", "content_id": "b5fa369c8f0ff9d6e9cb336abb982610f327cd38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 192, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/helloworld/递归实现求数组和.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "def sum_array(array):\n if len(array) == 1:\n return array[-1]\n else:\n return array.pop() + sum_array(array)\n\n\nlst = [1, 2, 3, 4, 5, 10]\narrsum = sum_array(lst)\nprint(arrsum)" }, { "alpha_fraction": 0.31640625, "alphanum_fraction": 0.34375, "avg_line_length": 24.700000762939453, "blob_id": "8e9fc74ef7b6188e266ebf51af700deeefc5608f", "content_id": "ce55ce6061745849c13f2350668f9966452df4a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/helloworld/九九乘法表.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "num1 = num2 =range(1 , 10)\nfor l in num1:\n for h in num2:\n if h <=l:\n print('%d * %d = %d'%(h,l,h*l),end='\\t')\n print('')\n # elif h == l:\n # print('%d * %d = %d' % (h, l, h * l))\n # else:\n # break" }, { "alpha_fraction": 0.5574468374252319, "alphanum_fraction": 0.5872340202331543, "avg_line_length": 19.478260040283203, "blob_id": "081cc1a620f5f407c8e819c74ce1d1786fae71b4", "content_id": "0d68ba8e6430fd131544c3fb1dc1e425931ad8ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 76, "num_lines": 23, "path": "/面向对象/对象比较大小.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import functools\n\n\[email protected]_ordering #通过该装饰器可以实现组合比较,如大于等于\nclass A:\n def __init__(self, age, weight):\n self.age = age\n self.weight = weight\n\n def __eq__(self, other): #重构相等方法\n print(\"比较操作执行\")\n return self.age == other.age\n\n def __gt__(self, other): #大于,实现了大于比较,在使用其相反操作的时候(小于),系统会采用自动调换参数顺序的方法实现\n pass\n\n def __bool__(self): #设定实例对象的bool值\n return True\n\n\na1 = A(18, 180)\na2 = A(18, 188)\nprint(a1 == a2)" }, { "alpha_fraction": 0.6026666760444641, "alphanum_fraction": 0.6240000128746033, "avg_line_length": 21.117647171020508, "blob_id": "023ba99d3cc9ebae3a5ce1f35c1e2067fddf79db", "content_id": "a1b1fee4ce62ea28e71730275eeaf86986427f1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 56, "num_lines": 17, "path": "/helloworld/判断数字.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#程序内定一个数字,让用户猜,正确则提示正确,退出;错误则提示大了或者小了,继续猜\n#程序内定一个数字\nimport random\nnum = random.randint(1,100)\n# 让用户猜,正确则提示正确,退出;错误则提示大了或者小了,继续猜\n#接收一个用户猜的数字\n\n#判断对错\nwhile True:\n userNum = int(input('please guss the num(1~100) :'))\n if userNum == num :\n print('Yes,Exit!')\n exit()\n elif userNum > num:\n print('大了,Going on!')\n else:\n print('小了,Going on!')" }, { "alpha_fraction": 0.49000000953674316, "alphanum_fraction": 0.5266666412353516, "avg_line_length": 26.363636016845703, "blob_id": "d4d6287bee0c26fea15530bb80cdbe429c770ec9", "content_id": "8e40ced72751016e1ff705abd53df27b3aa4c944", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "no_license", "max_line_length": 57, "num_lines": 11, "path": "/helloworld/递归实现快速排序.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "def qsort(arr):\n if len(arr) < 2:\n return arr\n else:\n middle_value = arr[0]\n small = [i for i in arr[1:] if i <= middle_value]\n big = [i for i in arr[1:] if i > middle_value]\n return qsort(small) + [middle_value] + qsort(big)\n\n\nprint(qsort([10, 5, 4, 7, 20]))" }, { "alpha_fraction": 0.5732172131538391, "alphanum_fraction": 0.57485032081604, "avg_line_length": 19.41111183166504, "blob_id": "3ae6478bd6fc0e6254147bd2ee94abfa82251c86", "content_id": "a2a5250e9a13811a76e0d287f3937892e18da572", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1983, "license_type": "no_license", "max_line_length": 62, "num_lines": 90, "path": "/venv/Lib/site-packages/comm_libs/django_wrap.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\n\n# 这里存放对django库的二次封装的相关代码\nimport json\n\nfrom django.http import HttpResponse\n\n\nclass HzfHttpResponse(HttpResponse):\n \"\"\"\n hzf http响应对象,所有view函数均需要返回此对象\n \"\"\"\n\n def __init__(self, value):\n '''\n 功能:value为参数字典\n '''\n\n if type(value) != dict:\n raise KeyError('param value must be a dict.')\n\n super(HzfHttpResponse, self).__init__()\n self.value = value\n\n\ndef gen_hzf_http_rsp(code, desc, value):\n \"\"\"\n 生成特定格式返回\n \"\"\"\n\n if type(value) != dict:\n raise KeyError('param value must be a dict')\n\n output_template = {\n \"status\":\n {\n \"code\": \"0\",\n \"description\": \"success\"\n },\n \"result\":\n {\n\n }\n }\n\n output_template[\"status\"][\"code\"] = code\n output_template[\"status\"][\"description\"] = desc\n output_template[\"result\"] = value\n\n res = HttpResponse()\n\n json_str = json.dumps(output_template, ensure_ascii=False)\n\n res.content = json_str\n\n res['Content-Type'] = 'application/json; charset=utf-8'\n\n return res\n\n\ndef get_request_value(request, key, default_val=\"\"):\n \"\"\"\n 获取客户端参数\n :param request:\n :param key: 参数\n :param default_val: 默认值\n :return:\n \"\"\"\n if not request.REQUEST.get(key):\n return default_val\n return request.REQUEST.get(key, default_val).strip()\n\n\ndef get_request_cookies(request, key, default_val=\"\"):\n \"\"\"\n 获取客户端参数\n :param request:\n :param key: 参数\n :param default_val: 默认值\n :return:\n \"\"\"\n if not request.COOKIES.get(key):\n return default_val\n return request.COOKIES.get(key, default_val).strip()\n\n\ndef get_dict_value(data_dict, key, default_val=\"\"):\n if not data_dict.get(key):\n return default_val\n return data_dict.get(key, default_val).strip()\n" }, { "alpha_fraction": 0.5282692909240723, "alphanum_fraction": 0.5308588743209839, "avg_line_length": 23.24210548400879, "blob_id": "90f15abb50b101d938eac9f709efa069488b745a", "content_id": "45c36de127bc6ba86f7fe6f0ceec185ba5d4ad19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2397, "license_type": "no_license", "max_line_length": 79, "num_lines": 95, "path": "/venv/Lib/site-packages/comm_libs/sendmail.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n#coding=utf8\n\nimport smtplib\nfrom email.MIMEMultipart import MIMEMultipart\nfrom email.MIMEText import MIMEText\nfrom email.MIMEBase import MIMEBase\n#from email.mime.application import MIMEApplication\nfrom email import Encoders\n\nclass MailSender:\n '''\n 邮件发送客户端\n '''\n def __init__(self, mail_server, user, password, port=25):\n '''\n 初始化\n '''\n self.mail_server = mail_server\n self.port = port\n self.user = user\n self.password = password\n self.mail = MIMEMultipart()\n self.sender = None\n self.receiver = None\n \n def add_content(self, content, encoding = \"gbk\"):\n '''\n 增加邮件正文\n '''\n self.mail.attach(MIMEText(content, \"html\", encoding))\n #MIMEApplication\n #self.mail.attach(MIMEApplication(content, \"excel\", encoding))\n \n def add_attachment(self, filepath):\n '''\n 增加附件\n '''\n import os\n fd = open(filepath, \"rb\")\n file_content = fd.read()\n fd.close()\n \n fn = os.path.basename(filepath)\n attachment = MIMEBase(\"application\",\"octet-stream\")\n attachment.set_payload(file_content)\n Encoders.encode_base64(attachment)\n attachment.add_header(\"Content-disposition\", \"attachment\", filename=fn)\n \n self.mail.attach(attachment)\n \n def set_sender(self, sender):\n '''\n 设置发件人\n '''\n self.sender = sender\n self.mail[\"From\"] = sender\n \n def set_receiver(self, reveicer_list):\n '''\n 设置收件人\n '''\n self.receiver = reveicer_list\n self.mail[\"To\"] = \",\".join(reveicer_list)\n \n \n def set_subject(self, subject):\n '''\n 设置邮件主题\n '''\n self.mail[\"Subject\"] = subject\n \n def sendmail(self):\n '''\n 发送邮件\n '''\n smtp = smtplib.SMTP()\n \n #smtp.set_debuglevel(1)\n \n smtp.connect(self.mail_server, self.port)\n \n #smtp.ehlo_or_helo_if_needed()\n \n smtp.login(self.user, self.password)\n \n smtp.sendmail(self.sender, self.receiver, self.mail.as_string())\n \n smtp.quit()\n \n \n \nif __name__ == '__main__':\n \n pass\n \n \n" }, { "alpha_fraction": 0.5240128040313721, "alphanum_fraction": 0.5293489694595337, "avg_line_length": 20.813953399658203, "blob_id": "80459c3f3b522b713d46d85c9e40093890a5ec52", "content_id": "8e8e11b18382f33760fef37f130b234b74981acd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1179, "license_type": "no_license", "max_line_length": 109, "num_lines": 43, "path": "/函数/带参数装饰器.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#-----------------------带参数装饰器(根据不同情况生成不同装饰器)----------------------------------------------------------------\ndef getCheckLogin(char=''):\n def chekLogin(needDec):\n def inner(*args, **kwargs):\n print('验证登录' + char * 30)\n res = needDec(*args, **kwargs)\n return res\n return inner\n return chekLogin #将装饰器返回\n\n\n\n# def chekLogin(needDec):\n# def inner(*args, **kwargs):\n# print('验证登录.......')\n# res = needDec(*args, **kwargs)\n# return res\n# return inner\n\n\n@getCheckLogin('*')\n#@checkLogin(语法糖) 等同于语句:fss = checkLogin(fss)\ndef fss():\n print('发说说')\n\n\n@getCheckLogin('=')\n#@checkLogin 等同于在函数后面 执行了一条语句:ftp = checkLogin(ftp)\ndef ftp():\n print('发图片')\n\n@getCheckLogin('+')\ndef flj(str):\n print(str)\n#相关业务逻辑代码\nindex = 1\nif index == 0:\n fss()\nelif index == 1:\n ftp()\nelse:\n flj('www.baidu.com')\n#以上代码实现了在发说说和发图片之前验证登录,而不变更业务逻辑代码,且不违反函数单一功能原则" }, { "alpha_fraction": 0.4958563446998596, "alphanum_fraction": 0.5013812184333801, "avg_line_length": 31.200000762939453, "blob_id": "a0657ce6922be23430179cd1bd660952b00db136", "content_id": "05fa132a12127715cc12ff35a19892b9df460ad4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2128, "license_type": "no_license", "max_line_length": 123, "num_lines": 45, "path": "/异常处理/异常处理.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#---------------------------方法1--------------------------------------------------------------------------------------------\n# try:\n# 可能出现异常的代码块(从上往下检测,检测到异常之后里面往下匹配,不会多次检测)\n# except 要捕捉的异常类型 as 接受异常的形参:(可多个) 异常类型可以多个,组成元组,或分别写except,更或者直接用Except类名,接受异常的形参为要捕捉的异常的返回值\n# 对于异常的处理\n# else:\n# 没有异常时的处理(可省略)\n# finally:\n# 不管有无异常都会处理(可省)\n#---------------------------方法2--------------------------------------------------------------------------------------------\nimport contextlib\nimport traceback\n\n\nclass Test:\n \"\"\"\n 实现了__enter__和__exit__方法,叫上下文管理器,在使用上下文管理器处理异常的时候,不管中间body部分是否有异常,enter和exit都会被执行\n \"\"\"\n def __enter__(self):\n print('enter')\n\n def __exit__(self, exc_type, exc_val, exc_tb): #exc_type, exc_val, exc_tb 分别为异常类型,异常的值,异常的追踪(什么地方出错了)\n print(self, exc_type, exc_val, exc_tb)\n print(traceback.extract_tb(exc_tb))\n print('exit')\n return True #返回true则异常不会返回给外界,否则会返回给外界,即报错\n\n#x是Test()实例中enter方法的返回值\nwith Test() as x:\n print('body', x)\n 1/0\n#----------------------方法2的简写--------------------------------------------------------------------------------------\nimport contextlib\n#contextlib.closing(实现了close方法的对象) 把该对象变为上下文管理器,并把对象本身返回,即enter方法返回self\n\n\[email protected] #把函数装饰城上下文管理器,配合yield使用\ndef demo():\n print('1')\n yield 'xxx' #yield之前的代码会作为enter方法,之后的会作为exit方法,后面的值会传递给x\n print('3')\n\n\nwith demo() as x:\n print('2', x)" }, { "alpha_fraction": 0.7460674047470093, "alphanum_fraction": 0.7561797499656677, "avg_line_length": 34.63999938964844, "blob_id": "05aeaa8c808dfac84c57e6beabe19876af800f59", "content_id": "053a5e2f8a89304728ad6beb19ae6cd8fd5a666b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1768, "license_type": "no_license", "max_line_length": 100, "num_lines": 25, "path": "/包和模块/__init__.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#导入包的时候会执行这个文件里面的内容\n#import M\n#import M1, M2\n#import M as p 导入模块,并把该模块起别名p\n#import package 在__init__.py 文件中写import package.M\n#from A import B as C 从A中导入B,并起个别名C\n#from A import * 在A中写__all__=['主动告知导入者有用的模块部分1','主动告知导入者有用的模块部分2'](不写则默认导入所有非'_'开头的资源) 不建议使用\n#from package import * 在__init__.py文件中中写__all__=['主动告知导入者有用的模块部分1','主动告知导入者有用的模块部分2'] 不建议使用\n#from . import M 从当前文件的上一级导入M (脚本运行不可用)\n#from .. import M 从当前文件的上上一级导入M (脚本运行不可用)\n#import M 第一次导入的时候,会在自己当下的命名空间执行M中的代码,并在当前命名空间创建一个模块对象M,将M中的顶层(最外层)属性和方法以属性的形式绑定到对象M中,在\n#import的位置将import后面的变量名称引入到当前命名空间\n#第二次导入,直接执行:import的位置将import后面的变量名称引入到当前命名空间\n#查找顺序:内置模块——>sys.path列表顺序查找\n#追加查找路径的三种方式:\n#1、直接修改sys.path\n#2、修改环境变量(仅在shell中可用,pycharm需要在setting里面改)\n#3、添加.path文件\nimport site\nprint(site.getsitepackages()) #打印可添加path文件的地方\n#在该地方添加path文件,文件内写需要添加的查找路径\n\n\n#相对导入:用.来代替相对路径 包内导入使用较好\n#绝对导入:指明包名和模块名 包外导入使用较好" }, { "alpha_fraction": 0.6233453750610352, "alphanum_fraction": 0.6281588673591614, "avg_line_length": 28.714284896850586, "blob_id": "8554f52d3e3a9f0c31e4f801d2a30da3e621fc25", "content_id": "68f05c22ee942bf531f981d783159806b26b2484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1253, "license_type": "no_license", "max_line_length": 87, "num_lines": 28, "path": "/函数/描述器副本.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#描述器:可以描述一个属性操作的对象,必须实现属性的:__set__ __get__ __delete__方法,且必须都是新式类\n#可以用@property 装饰器实现\n#可以用 age = property(__set__,__get__,__delete__)实现\n#最佳方法是把该属性操作封装在一个类里面,并实现__set__,__get__,__delete__方法\n#资料描述器:实现了 __get__、 __set__\n#非资料描述器:只实现了__get__\n#优先级:资料描述器 >实例属性>非资料描述器\nclass Age:\n def __get__(self, instance, owner): #重写了__getattribute__方法后会影响该方法的调用(instance:实例)\n # print('get')\n return isinstance.v\n\n def __set__(self, instance, value):\n # print('set')\n instance.v = value #把赋值数据存储到age实例对象的v属性中去\n\n def __delete__(self, instance):\n print('delete')\n del instance.v\n\nclass Person:\n age = Age()\n\n\np = Person()\np.age = 10 #自动调用Age类里面的set方法(通过实例操作) 参数传递为:self = age;instance = p;value = 10\nprint(p.age) #自动调用Age类里面的get方法,但get方法没有返回值,故打印none\ndel p.age #自动调用Age类里面的delete方法" }, { "alpha_fraction": 0.49463579058647156, "alphanum_fraction": 0.5117779970169067, "avg_line_length": 33.71794891357422, "blob_id": "d0c1536b65a2950dcf2265290022c7feacc53d8a", "content_id": "b65ac4a0b205918ce36ca131b6fa854ef8484934", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 26066, "license_type": "no_license", "max_line_length": 111, "num_lines": 741, "path": "/venv/Lib/site-packages/comm_libs/contract.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding: utf8\n\nimport datetime\nfrom datetime import date\nimport logging\nfrom project.agency_confs import a_pair_of_a_agency_id_list\nfrom libs.exception import HzfException\nfrom libs.subrent_pay_date_amend import amend_subrent_pay_date\nfrom libs.time_utils import add_months\nfrom project.error_code import ERR_LAST_SUBRENT_GT_THIRTY\n\ntry:\n from huizhaofang.models import SubPay, SubRent, Pay, User, ContractSnapshot, ContractNo\nexcept:\n from db_models.tables.subpay import SubPay\n from db_models.tables.subrent import SubRent\n from db_models.tables.pay import Pay\n from db_models.tables.user import User\n from db_models.tables.contract_snapshot import ContractSnapshot\n from db_models.tables.contract_no import ContractNo\n\ntry:\n from libs.log_tool import write_debug_log\nexcept:\n def write_debug_log(string):\n print string\n\n\n#### 合同日期相关转换函数\n\ndef get_date(year, month, day, plus=False):\n \"\"\" 某个理论日期不存在时,需要根据场景向前/向后推移,找到一个有效日期\"\"\"\n #printLog(\"get_date: [%s/%s/%s]\" % (year, month, day))\n if day <= 0:\n raise Exception('无效的day %s' % day)\n invalid = False\n while True:\n try:\n ret = datetime.date(year, month, day)\n break #已经找到有效日期\n except: #无效日期,需要循环继续寻找\n #printLog(\"[%s/%s/%s]\" % (year, month, day))\n invalid = True\n day -= 1\n if day == 0:\n raise\n continue\n if plus and invalid:\n ret += datetime.timedelta(days=1)\n return ret\n\ndef get_delta_date(month, date, plus=False):\n #printLog(\"delta: [%s/%s]\" % (str(date), month))\n if date.month <= month:\n year = date.year - (month - date.month + 12) / 12\n month = (12 + date.month - month) % 12\n if month == 0:\n month = 12\n day = date.day\n else:\n year = date.year\n month = date.month - month\n day = date.day\n return get_date(year, month, day, plus=plus)\n\ndef get_future_date(date, month, plus=False):\n #printLog(\"future: [%s/%s]\" % (str(date), month))\n if date.month + month > 12:\n year = date.year + (date.month + month) / 12\n month = (date.month + month) % 12\n if month == 0:\n month = 12\n year -= 1\n day = date.day\n else:\n year = date.year\n month = date.month + month\n day = date.day\n #printLog(\"future 0-[%s/%s/%s]\" % (year, month, day))\n return get_date(year, month, day, plus=plus)\n\n\ndef get_contract_cycle(start, end, fix_mode=True):\n if type(start) in [str, unicode]:\n start = datetime.datetime.strptime(start, '%Y-%m-%d').date()\n if type(end) in [str, unicode]:\n end = datetime.datetime.strptime(end, '%Y-%m-%d').date()\n\n m = 1\n d = 0\n nextend = start - datetime.timedelta(days=1)\n while True:\n if fix_mode:\n cur_start = get_future_date(start, m - 1 , plus=True)\n nextend = get_future_date(start, m, plus=True) - datetime.timedelta(days=1)\n else:\n cur_start = nextend + datetime.timedelta(days=1)\n nextend = get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n logging.info(\"akpm %s\" % nextend)\n if nextend == end:\n break\n if nextend > end:\n if end.day >= start.day:\n d = end.day - cur_start.day + 1\n elif not fix_mode:\n d = (end - cur_start).days + 1\n else:\n d = end.day + 30 - start.day + 1\n m -= 1\n break\n m += 1\n if d == 30 and fix_mode:\n d = 0\n m += 1\n\n return m,d\n\ndef get_subrent_list(lease_begin, lease_end, hzf_pay_type, amount,\n prepay_days, down_payment_month, agency_id, hzf_final_payment=1,\n lease_type=2, fix_mode=True, service_fee_payer=6):\n ret = []\n hzf_pay_rate = [3, 6, 12]\n rate = hzf_pay_rate[hzf_pay_type - 1]\n\n if lease_type == 3:\n down_payment_month = 0\n\n months, days = get_contract_cycle(lease_begin, lease_end, fix_mode=fix_mode)\n tm = months\n if days > 0:\n tm += 1\n stages = tm / rate\n if tm % rate > 0:\n stages += 1\n last_end_date = lease_begin - datetime.timedelta(days=1)\n for i in range(stages):\n s = SubRent()\n s.index = i + 1\n diff = 0\n if i == 0:\n diff = down_payment_month\n print '................'\n print str(lease_begin)\n print str(diff)\n print str(down_payment_month)\n\n if not fix_mode:\n for j in range(diff):\n cur_start = last_end_date + datetime.timedelta(days=1)\n if j == 0:\n s.pay_date = cur_start\n last_end_date = get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n for j in range(rate-diff):\n cur_start = last_end_date + datetime.timedelta(days=1)\n if j == 0:\n s.start_date = cur_start\n if diff == 0 and j == 0:\n s.pay_date = cur_start\n last_end_date = get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n s.end_date = last_end_date\n else:\n s.start_date = get_future_date(lease_begin,\n i * rate + diff)\n s.end_date = get_future_date(lease_begin - datetime.timedelta(days=1),\n (i + 1) * rate)\n s.pay_date = get_future_date(lease_begin,\n i * rate) # - datetime.timedelta(days=1)\n\n if service_fee_payer and service_fee_payer == 6 and i == 0:\n if hzf_pay_type == 3:\n d_rate = 0.92\n r_rate = 0.94\n elif hzf_pay_type == 2:\n d_rate = 0.95\n\n #s.price = int(round(amount * (rate - diff + (1-d_rate)/d_rate * 3)))\n s.price = int(round(amount * (rate - diff)))\n elif service_fee_payer == 7 and i == 0:\n if hzf_pay_type == 3:\n d_rate = (1 * 2 + 0.92 * 9) / 11\n amount = amount / 0.92 * d_rate\n s.price = int(round(amount * (rate - diff)))\n else:\n s.price = int(round(amount * (rate - diff)))\n if stages == 1:\n ret.append(s)\n elif i < stages - 1:\n ret.append(s)\n elif ret and hzf_final_payment == 2:\n s.end_date = lease_end\n if agency_id in [10630]:\n check_hzf_payment(s, agency_id)\n ret[0].price += s.price\n elif ret and hzf_final_payment == 3:\n s.end_date = lease_end\n if agency_id in [10630]:\n check_hzf_payment(s, agency_id)\n ret[-1].end_date = lease_end\n ret[-1].price += s.price\n else:\n ret.append(s)\n\n #payrate = float((lease_end - s.start_date).days + 1) / 30\n ret[-1].end_date = lease_end\n #ret[-1].price = int(round(ret[-1].price * payrate))\n amend_subrent_pay_date(ret[0], agency_id)\n return ret\n\ndef check_hzf_payment(subrent, agency_id):\n if agency_id in [1969, 1717, 10465]: # 如果是有家置地和天地昊、同程 不检查尾款同上期合并和尾款首付\n return\n last_subrent_days = (subrent.end_date - subrent.start_date).days\n if last_subrent_days > 30:\n raise HzfException(ERR_LAST_SUBRENT_GT_THIRTY[0], ERR_LAST_SUBRENT_GT_THIRTY[1])\n\npayment_params = [\n { 'rate': 1, },\n { 'rate': 2, },\n { 'rate': 3, },\n { 'rate': 4, },\n { 'rate': 5, },\n { 'rate': 6, },\n { 'rate': 7, },\n { 'rate': 8, },\n { 'rate': 9, },\n { 'rate': 10, },\n { 'rate': 11, },\n { 'rate': 12, },\n]\n\ndef yuan2fen(amount):\n s = \"%s00\" % (int(amount))\n return int(s)\n\ndef fen2yuan(amount):\n str_fen = str(amount)\n str_yuan = \"%s.%s\" % (str_fen[:-2], str_fen[-2:])\n return str_yuan\n\ndef get_month_days(date):\n for day in [28, 29, 30, 31]:\n try:\n datetime.date(date.year, date.month, day)\n ret = day\n except:\n pass\n \n return ret\n\n\ndef get_subpay_list(lease_begin, lease_end, user_pay_type, prepay_day,\n service_fee, amount, down_payment_month, agency_id,\n prepay_days=15, final_payment=1, final_price=-1,\n final_service_fee=-1, lease_type=1, service_fee_payer=1, fix_mode=True):\n ret = []\n if lease_type == 3:\n down_payment_month = 0\n params = payment_params[user_pay_type - 1]\n rate = params['rate']\n down_payment_stage = down_payment_month / rate\n\n logging.info(\"akpm %s - %s\" % (lease_begin, lease_end))\n total_months, total_days = get_contract_cycle(lease_begin, lease_end, fix_mode)\n logging.info(\"akpm %s - %s\" % (total_months, total_days))\n i = 0\n orig_service_fee = service_fee\n\n start = lease_begin\n end = lease_end\n nextend = start - datetime.timedelta(days=1)\n last_end_date = start - datetime.timedelta(days=1)\n\n for i in range(down_payment_stage):\n cur_start = last_end_date + datetime.timedelta(days=1) #get_future_date(start, m - 1 , plus=True)\n last_end_date = get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n\n i = 0\n m = 1\n while True:\n #if fix_mode:\n # cur_start = get_future_date(start, m - 1 , plus=True)\n # last_end_date = get_future_date(cur_start, m, plus=True) - datetime.timedelta(days=1)\n #else:\n # cur_start = last_end_date + datetime.timedelta(days=1) #get_future_date(start, m - 1 , plus=True)\n # last_end_date= get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n\n if service_fee_payer in [4] and i < 3:\n service_fee = 0\n else:\n service_fee = orig_service_fee\n\n s = SubPay()\n s.price = int(round((amount + service_fee) * rate))\n s.base_price = int(round(amount * rate))\n s.unpay_price = int(round((amount + service_fee) * rate))\n s.service_fee = int(round(service_fee * rate))\n s.index = i+1\n\n if not fix_mode:\n cur_start = last_end_date + datetime.timedelta(days=1) #get_future_date(start, m - 1 , plus=True)\n s.end_date = get_future_date(cur_start, 1, plus=True) - datetime.timedelta(days=1)\n elif lease_begin.day == 1:\n s.end_date = get_future_date(lease_begin,\n (i + down_payment_stage + 1) *\n rate) - datetime.timedelta(days=1) \n else:\n s.end_date = get_future_date(lease_begin - datetime.timedelta(days=1), \n (i + down_payment_stage + 1) *\n rate) \n\n m += 1\n s.start_date = last_end_date + datetime.timedelta(days=1)\n last_end_date = s.end_date\n\n pay_date = s.start_date\n\n if lease_type == 3 or lease_type == 4: #C端 公寓目前只支持5天后还款\n prepay_days = -4\n\n for j in range(0, 32):\n date1 = pay_date - datetime.timedelta(days=prepay_days + j)\n write_debug_log(\"date1: \" + str(date1))\n if date1.day == prepay_day:\n pay_date2 = date1\n break\n date2 = pay_date - datetime.timedelta(days=prepay_days - j)\n write_debug_log(\"date2: \" + str(date2))\n if date2.day == prepay_day:\n pay_date2 = date2\n break\n if date1.day == prepay_day or date1 == get_date(date1.year, date1.month, prepay_day):\n pay_date2 = date1\n break\n if date2.day == prepay_day or date2 == get_date(date2.year, date2.month, prepay_day):\n pay_date2 = date2\n break\n \n write_debug_log(\"pay_date2: \" + str(pay_date2))\n orig = pay_date2\n\n s.pay_date = get_date(orig.year, orig.month, prepay_day)\n\n if s.end_date == lease_end:\n ret.append(s)\n break\n\n if s.end_date > lease_end:\n orig_end = s.end_date\n s.end_date = lease_end\n\n if fix_mode:\n month_days = 30\n else:\n month_days = get_month_days(s.start_date)\n write_debug_log('%s month_days: %d' % (s.start_date, month_days))\n\n if total_days > 0 and total_days < month_days:\n payrate = total_days / (month_days * 1.0)\n else:\n payrate = 1\n\n s.price = int(round((amount + service_fee) * rate * payrate))\n\n if final_price != -1:\n s.price = final_price + final_service_fee\n s.service_fee = int(round(service_fee * rate * payrate))\n s.base_price = int(round(amount * rate * payrate))\n s.unpay_price = s.price\n\n #if final_service_fee != -1:\n # s.service_fee = final_service_fee\n # s.base_price = final_price\n\n if final_payment == 1:\n ret.append(s)\n elif final_payment == 2:\n pass\n elif final_payment == 3:\n ret[-1].price += s.price\n ret[-1].end_date = s.end_date\n ret[-1].base_price += s.base_price\n ret[-1].unpay_price += s.unpay_price\n ret[-1].service_fee += s.service_fee\n break\n\n ret.append(s)\n i += 1\n\n if final_price != -1:\n ret[-1].price = final_price\n ret[-1].unpay_price = final_price\n ret[-1].service_fee = int(round(final_price * service_fee / (service_fee + amount)))\n ret[-1].base_price = final_price - s.service_fee\n\n if lease_type == 4:\n count = 0\n pay_date = lease_begin - datetime.timedelta(days=5)\n # 为了快速实现 新公寓算法,对生成的数据进行修改,之后会对按照整理的算法进行重构\n for subpay in ret:\n if count > 0:\n subpay.pay_date = add_months(pay_date, count)\n if agency_id in a_pair_of_a_agency_id_list: # 如果是押一付一,付款日期加一个月\n subpay.pay_date = add_months(pay_date, count + 1)\n ret[count] = subpay\n count += 1\n\n return ret\n\ndef get_service_rate(hzf_pay_type, lease_type=None):\n if lease_type == 4:\n return 100 * 8 / 92.0\n rate_list = [4, 5, 8]\n if hzf_pay_type <= 0 or hzf_pay_type > len(rate_list):\n raise Exception('invalid hzf_pay_type')\n return rate_list[hzf_pay_type - 1]\n\ndef get_down_payment_month(prepay_days):\n if prepay_days == 3:\n down_payment_month = 0\n elif prepay_days in [2, 30]:\n down_payment_month = 2\n else: #15/1\n down_payment_month = 1\n return down_payment_month\n\ndef get_prepay_day(lease_begin, prepay_days, down_payment_month, lease_type=2):\n if lease_begin.day == 1:\n if prepay_days == 15: \n prepay_day = 16\n elif prepay_days == 30:\n prepay_day = 1 \n else:\n prepay_day = 5\n else:\n lastday = (get_future_date(lease_begin-datetime.timedelta(days=1),\n down_payment_month)).day\n prepay_day = lastday - (prepay_days - 1)\n if prepay_day <= 0:\n prepay_day += 30\n if prepay_day > 30:\n prepay_day -= 30\n return prepay_day\n\ndef obj_waper(obj):\n \"\"\"\n \"\"\"\n ret = {}\n\n for k,v in vars(obj).items():\n if k == '_state':\n continue\n hump_key = k\n ret[hump_key] = v\n\n return ret\n\ndef subpay_waper(subpayList):\n new = []\n for i in subpayList:\n if type(i) == dict:\n if 'base_price' not in i.keys():\n i['base_price'] = int(i['price']) - int(i['service_fee'])\n if 'unpay_price' not in i.keys():\n i['unpay_price'] = int(i['price'])\n paid_price = 0\n if 'paid_price' not in i.keys():\n paid_price = int(i['price']) - int(i['unpay_price'])\n if 'pay_time' in i.keys() and i['pay_time']:\n pay_time = str(i['pay_time'])\n else:\n pay_time = ''\n if 'remark_pay_time' in i.keys() and i['remark_pay_time']:\n remark_pay_time = str(i['remark_pay_time'])\n else:\n remark_pay_time = ''\n \n if 'overdue_fine' in i.keys() and i['overdue_fine']:\n overdue_fine = int(i['overdue_fine'])\n else:\n overdue_fine = 0\n \n new.append({\n 'index': i['index'],\n 'pay_date': i['pay_date'],\n 'price': i['price'],\n 'base_price': i['base_price'],\n 'unpay_price': i['unpay_price'],\n 'overdue_fine': overdue_fine,\n 'paid_price': paid_price,\n 'pay_time': pay_time,\n 'remark_pay_time': remark_pay_time,\n 'service_fee': i['service_fee'],\n 'start_date': str(i['start_date']),\n 'end_date': str(i['end_date']),\n 'status': '0',\n })\n else:\n if i.pay_time:\n pay_time = str(i.pay_time)\n else:\n pay_time = ''\n remark_pay_time = i.remark_pay_time\n if i.offline_pay_time:\n remark_pay_time = i.offline_pay_time\n if i.status == 0:\n pay_time = \"\"\n remark_pay_time = \"\"\n if hasattr(i, 'overdue_fine'):\n overdue_fine = int(i.overdue_fine_nature - i.overdue_fine_reduce)\n else:\n overdue_fine = 0\n \n new.append({\n 'index': i.index,\n 'price': i.price,\n 'base_price': i.base_price,\n 'unpay_price': i.unpay_price,\n 'paid_price': (i.price - i.unpay_price),\n 'pay_time': pay_time,\n 'remark_pay_time': str(remark_pay_time),\n 'pay_date': str(i.pay_date),\n 'service_fee': i.service_fee,\n 'overdue_fine':overdue_fine,\n 'start_date': str(i.start_date),\n 'end_date': str(i.end_date),\n 'status': str(i.status),\n })\n subrentList = new\n return new\n\ndef subrent_waper(subrentList):\n new = []\n count_idx = 1\n for i in subrentList:\n if type(i) == dict:\n i['index'] = count_idx\n if 'paid' in i.keys():\n paid = i['paid']\n elif 'status' in i.keys():\n paid = i['status']\n else:\n paid = 0\n i['unpay_price'] = i['price']\n new.append({\n 'index': i['index'],\n 'pay_date': i['pay_date'],\n 'price': i['price'],\n 'paid': paid,\n 'unpay_price': i['unpay_price'],\n 'paid_price': int(i['price']) - int(i['unpay_price']),\n })\n else:\n new.append({\n 'index': i.index,\n 'pay_date': str(i.pay_date),\n 'price': i.price,\n 'paid': i.status,\n 'paid_price': i.price - i.unpay_price,\n 'cashing_time': str(i.cashing_time),\n 'unpay_price': i.unpay_price,\n 'start_date': str(i.start_date),\n 'end_date': str(i.end_date),\n 'subrent_id': i.subrent_id,\n 'status': i.status,\n })\n count_idx += 1\n subrentList = new\n return subrentList\n\n\ndef fix_final_subrent(subrent_list, subpay_list, service_fee_payer=1, orig_fee_rate=5,\n hzf_final_payment=1,\n hzf_pay_type=3):\n\n if hzf_pay_type == 3:\n d_rate = 0.92\n d_rate = 0.94\n elif hzf_pay_type == 2:\n d_rate = 0.95\n\n total_rent = 0\n for i in subrent_list:\n total_rent += i.price\n total_base_price = 0\n for i in subpay_list:\n total_base_price += i.base_price\n first_amount = subpay_list[0]['price']\n if hzf_final_payment == 2:\n rent = subrent_list[0]\n else:\n rent = subrent_list[-1]\n\n if service_fee_payer in [2]:\n rent.price = int(round(rent.price -\n (total_rent -\n float(total_base_price) / (orig_fee_rate + 100) * 100.0\n )))\n for i in subrent_list:\n i.price = int(i.price / 100)\n i.price = i.price * 100\n elif service_fee_payer in [5]:\n rent.price = int(round(rent.price -\n (total_rent -\n float(total_base_price) * d_rate\n )))\n for i in subrent_list:\n i.price = int(i.price / 100)\n i.price = i.price * 100\n elif service_fee_payer in [6]:\n rent.price = int(round(rent.price\n #+ float(first_amount) * (1-d_rate) * 3\n - (total_rent -\n float(total_base_price) * (d_rate)\n )))\n for i in subrent_list:\n i.price = int(i.price / 100)\n i.price = i.price * 100\n else:\n rent.price = int(round(rent.price -\n (total_rent - total_base_price)))\n rent = subrent_list[0]\n return subrent_list\n\ndef get_total_rent(subrent_list):\n total_rent = 0\n if not subrent_list:\n return 0\n for i in subrent_list:\n if type(i) == dict:\n total_rent += i['price']\n else:\n total_rent += i.price\n\n return int(round(total_rent))\n\ndef get_total_pay(subpay_list):\n total_base_price = 0\n total_service_fee = 0\n user_amount = 0\n for i in subpay_list:\n if type(i) == dict:\n if 'base_price' not in i.keys():\n i['base_price'] = int(i['price']) - int(i['service_fee'])\n total_base_price += i['base_price']\n total_service_fee += i['service_fee']\n user_amount += i['price']\n else:\n total_base_price += i.base_price\n total_service_fee += i.service_fee\n user_amount += i.price\n return user_amount, total_base_price\n\ndef calculator(lease_begin, lease_end, monthly_amount,\n service_fee_payer=1, prepay_days_type=1,\n hzf_pay_type=2, final_payment=1,\n user_pay_type=1,\n down_payment_month=-1,\n total_months=-1, total_days=-1, final_price=-1, final_service_fee=-1,\n hzf_final_payment=1, lease_type=2, fix_mode=True\n ):\n prepay_days = [15, 30, -4][prepay_days_type - 1]\n if down_payment_month == -1:\n down_payment_month = get_down_payment_month(prepay_days)\n\n\n if hzf_pay_type == 3:\n d_rate = 0.92\n elif hzf_pay_type == 2:\n d_rate = 0.95\n\n service_rate = get_service_rate(hzf_pay_type, lease_type)\n real_monthly_amount = monthly_amount\n if service_fee_payer in [2]:\n real_monthly_amount = float(monthly_amount) / (service_rate +\n 100) * 100.0\n if service_fee_payer in [5, 6]:\n real_monthly_amount = float(monthly_amount) * d_rate\n\n orig_service_rate = service_rate\n if service_fee_payer in [2, 3, 5, 6]:\n service_rate = 0\n\n service_fee = monthly_amount * service_rate / 100\n\n prepay_day = get_prepay_day(lease_begin, prepay_days,\n down_payment_month)\n\n subrent_list = get_subrent_list(lease_begin, lease_end,\n hzf_pay_type,\n real_monthly_amount, prepay_days,\n down_payment_month, hzf_final_payment,\n lease_type=lease_type, service_fee_payer=service_fee_payer) \n subpay_list = get_subpay_list(lease_begin, lease_end,\n user_pay_type,\n prepay_day, service_fee,\n monthly_amount, down_payment_month,\n prepay_days, final_payment, lease_type=lease_type, service_fee_payer=service_fee_payer)\n total_months,total_days = get_contract_cycle(lease_begin, lease_end, fix_mode)\n\n subrent_list = fix_final_subrent(subrent_list, subpay_list,\n service_fee_payer,orig_service_rate, hzf_final_payment, hzf_pay_type=hzf_pay_type)\n total_rent = get_total_rent(subrent_list)\n\n subrent_list = subrent_waper(subrent_list)\n\n user_amount,total_base_price = get_total_pay(subpay_list)\n #subpay_list = subpay_waper(subpay_list)\n\n final_service_fee = subpay_list[-1].service_fee\n #final_amount = subpay_list[-1]['price']\n final_amount = subpay_list[-1].price\n\n return subrent_list, subpay_list, prepay_day, total_months, total_days, total_rent\n\ndef allocate_contract_no(requester, type=1, disable_prefix=True):\n #type: 0租赁(Z) 1会分期(H) 其他未知(U)\n if type == 0:\n prefix = 'Z' \n elif type == 1:\n prefix = 'H' \n else:\n prefix = 'U' \n\n c = ContractNo(requester=requester, type=type)\n c.save()\n\n contract_no = datetime.datetime.now().strftime('%Y%m%d')\n numbers = ContractNo.objects.filter(create_time__gte=datetime.date.today()).order_by('create_time')\n index = c.contract_no_id - numbers[0].contract_no_id + 1\n if disable_prefix:\n prefix = ''\n\n contract_no = \"%s%s%.4d\" % (prefix, contract_no, index)\n ContractNo.objects.filter(contract_no_id=c.contract_no_id).update(no=contract_no)\n\n return contract_no\n\ndef get_date_from_str(date):\n if type(date) in [str, unicode]:\n date = datetime.datetime.strptime(date, '%Y-%m-%d').date()\n return date\n" }, { "alpha_fraction": 0.6698113083839417, "alphanum_fraction": 0.6698113083839417, "avg_line_length": 30.235294342041016, "blob_id": "edd07a5036ca91fd5bb385f8a813f4dae281babb", "content_id": "1f5461a12addde8b04fb9a1602057e353203e524", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/helloworld/协程.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#把函数编写成一个任务程序,用来处理发送给它的一系列输入,用(yield)的形式实现,用send()发送数据\ndef print_matches(matchText):\n print('looking for', matchText)\n while True:\n line = (yield ) #接受一行文本\n if matchText in line:\n print(line)\n\nmatch = print_matches('python')\nmatch.__next__() #必须调用next函数,协程才能执行第一个yield之前的语句,不调用next函数会报错\na = match.send('python') #send()函数的返回值为传递给下一个yield语句的值\nprint('a = ', a)\nb = match.send('hello world')\nprint('b=', b)\nc = match.send('python is cool')\nprint('c=', c)\nmatch.close() #协程一般会不断执行下去,直到显示关闭或者自己退出" }, { "alpha_fraction": 0.7374005317687988, "alphanum_fraction": 0.7533156275749207, "avg_line_length": 33.3636360168457, "blob_id": "7591dbd7fe1d423496ad82a7006f39ce042bc2d2", "content_id": "2251ef83b3ca541c4a5fdbe79052cecb8cab2f64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 85, "num_lines": 11, "path": "/机器学习/KMean聚类.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import *\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nnp.linalg.svd() #奇异值分解,返回u,s,vh,其中u:左奇异向量(正交单位矩阵);s:SIGMA,对角线元素为奇异值,降序,且减小速度特别快,\n# 从存储来说,前10%甚至1%的奇异值之和就占了全部奇异值之和的99%以上;vh,右奇异向量(正交单位矩阵) \ndataset = mat()\nkmeans = KMeans(init='k-means++', n_clusters=4) #创建一个KMean类的实例\nkmeans.fit(dataset) #计算KMean聚类\n#绘图,数据可视化\npass" }, { "alpha_fraction": 0.6394707560539246, "alphanum_fraction": 0.6618890166282654, "avg_line_length": 34.350650787353516, "blob_id": "b6159828cf990cdd948b98eebf4499dbc69ce19b", "content_id": "4536415b4c2da7d27023d84f5c0939e09a8c7bce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4629, "license_type": "no_license", "max_line_length": 88, "num_lines": 77, "path": "/helloworld/字符串.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#-------------------------------------字符串查找相关----------------------------------不改变原字符串\n#计算字符串长度\nname = ' abcdefg hijklmn ABCDEFG-HIJKLMN |'\nlenth = len(name)\nprint(lenth)\n#查找字符串(从左向右) 找不到返回-1,找到返回下标\nnum = name.find('cf',4,20)\nprint(num)\n#查找字符串(从右向左边),同find\nnum = name.rfind('cd')\nprint(num)\n#计算某个子字符串出现的个数\nprint(name.count('abc',0,7))\n#-------------------------------------字符串转换相关----------------------------------不改变原字符串\n#用新字符串替换原旧字符串,replace不会更改原字符串\n#替换个数count\ncount = 1\nprint(name.replace('b','B',count))\nprint(name)\n#首字母大写,不会改变原字符串\nprint(name.capitalize())\nprint(name)\n#将字符串中每个单词的首字母变为大写,不改变原字符串,凡中间不是字母的,都看作分隔符,之后都看成单词,汉字没有大小写\nprint(name.title())\nprint(name)\n#字符串字母全部变为大写、小写,不改变原字符串\nprint(name.lower())\nprint(name)\nprint(name.upper())\nprint(name)\n#-------------------------------------字符串填充压缩相关----------------------------------不改变原字符串\n#ljust:根据指定字符(1个),将原字符串填充够指定长度;l表示原字符串靠左;不改变原字符串;如果原串长度大于需求长度则不填充\nprint(name.ljust(50,'*'))\n# print(name)\n#rjust:根据指定字符(1个),将原字符串填充够指定长度;r表示原字符串靠右;不改变原字符串;如果原串长度大于需求长度则不填充\nprint(name.rjust(50,'*'))\n# print(name)\n#center:根据指定字符(1个),将原字符串填充够指定长度;center表示原字符串居中;不改变原字符串;如果原串长度大于需求长度则不填充\nprint(name.center(50,'*'))\n# print(name)\n#lstrip:移除原字符串中指定字符集合,默认为空格;l表示仅仅移除左侧的(rstrip为移除右侧的):从左侧还检索,查到则移除,没查到就结束\nname ='abcdeABCDE'\nprint(name.lstrip('abAB'))\nprint(name)\n#-------------------------------------字符串分割拼接相关----------------------------------不改变原字符串\n#split(sep,maxsplit):将一个大的字符串分割成几个子字符串,按照sep分割符分割,分割maxsplit次,返回分割后的子字符串列表\nname = 'zyf-28-man'\nprint(name.split('-',2))\n#partition:根据指定的分割符,返回元组:(分割符左侧的内容,分割符,分割符右侧的内容);如果没找到分割符,返回(原字符串,‘’,‘’)\nprint(name.partition('-'))\n#rpartition:表示从右侧开始检索\nprint(name.rpartition('-'))\n#splitlines(keepends):按照换行符(\\r,\\n)将原字符串拆成多个元素,保存到列表中;keepends表示是否保留换行符,bool类型,默认false\n#'\\r' 回车,回到当前行的行首,而不会换到下一行,如果接着输出的话,本行以前的内容会被逐一覆盖\nname = 'wo \\n you \\r ta'\nprint(name.splitlines(True))\n#join(iterable):根据指定字符串,将给定的可迭代对象(可以使用for循环进行遍历的都是,如list、元组、字符串。。。),进行拼接,得到拼接后的字符串\nit =['zyf','28','man','025-18115054967']\nprint('-'.join(it))\n#-------------------------------------字符串判断相关----------------------------------不改变原字符串\n#isalpha():字符串中是否所有的字符全是字母,不包含数字、特殊符号、标点符号、换行空格等,且至少要有1个字符(空串返回false),返回bool类型\nname = 'zyf1'\nprint(name.isalpha())\n#isdigit():字符串中是否所有的字符全是数字,不包含字母、特殊符号、标点符号、换行空格等,且至少要有1个字符(空串返回false),返回bool类型\nname = '789'\nprint(name.isdigit())\n#isalnum():字符串中是否所有的字符全是字母或数字,不包含特殊符号、标点符号、换行空格等,且至少要有1个字符(空串返回false),返回bool类型\nname = 'abc123'\nprint(name.isalnum())\n#isspace():字符串中是否所有的字符全是空格(缩进、回车、换行等不可见转义字符)\nname = '\\r '\nprint(name.isspace())\n#startswith(prefix,start = 0,end = len(str)):判断一个字符串是否以指定前缀开头\nname = '2018-9-14:xxxx.ppt'\nprint(name.startswith('2018-9-13'))\n#endswith(prefix,start = 0,end = len(str)):判断一个字符串是否以指定后缀结尾\nprint(name.endswith('.ppt'))" }, { "alpha_fraction": 0.45945945382118225, "alphanum_fraction": 0.5315315127372742, "avg_line_length": 21.399999618530273, "blob_id": "8d1773461e10fd11e6e42bb7ae1de492c29411e3", "content_id": "fa329605e58d83608187bb3702038de57fda0cb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 151, "license_type": "no_license", "max_line_length": 41, "num_lines": 5, "path": "/函数/迭代器.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#迭代器:任何实现了__iter__()和__next__()方法的对象都是迭代器\nl = [1, 2, 3, 4, 5, 6, 7, 8]\nitr = iter(l)\nfor i in itr:\n print(i)" }, { "alpha_fraction": 0.5776223540306091, "alphanum_fraction": 0.6503496766090393, "avg_line_length": 38.72222137451172, "blob_id": "b3d051868e5449d94d83c9eea685e3be11e6591d", "content_id": "7954901d0470920a2685ba63da85f6c4ff0d7ff8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 721, "license_type": "no_license", "max_line_length": 106, "num_lines": 18, "path": "/机器学习/基于SVD推荐系统.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import svdRec\nimport numpy as np\nfrom svdRec import svdRec\nfrom numpy import *\n\nA = np.array([[5, 5, 3, 0, 5, 5], [5, 0, 0, 0, 0, 0], [0, 3, 0, 5, 4, 5], [5, 4, 3, 3, 5, 5]]) #A的形状(6,4)\nA = mat(A)\nuserIdName = {1: 'user1', 2: 'user2', 3: 'user3', 4: 'user4'}\nitemDic = {'item1': 'i1', 'item2': 'i2', 'item3': 'i3', 'item4': 'i4', 'item5': 'i5', 'item6': 'i6'}\nsc = svdRec.svdRec()\nsc.load_data_numpy(A)\nsc.load_item_encoder(itemDic)\nsc.load_user_encoder(userIdName)\nsc.SVD(2)\nrecommandItemId = sc.recommends_for_user(2, num_recom=2, show_similarity=True)\n# recommandItemName = sc.get_item_name(recommandItemId[0])\n# print(recommandItemId[0], type(recommandItemId[0]))\nprint(recommandItemId, type(recommandItemId))\n" }, { "alpha_fraction": 0.4970553517341614, "alphanum_fraction": 0.5088339447975159, "avg_line_length": 18.76744270324707, "blob_id": "21174dc1b3af20a279322675ebe47bf0d9a18557", "content_id": "098621e81364598b8d98dd6346ff845a0755f8cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 76, "num_lines": 43, "path": "/面向对象/计算器案例.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "class Cal:\n def check_num(func):\n def inner(self, n):\n if not isinstance(n, int):\n raise TypeError('num type error,num should be a int object')\n return func(self, n)\n return inner\n @check_num\n def __init__(self, num):\n self.__res = num\n\n @check_num\n def jia(self,n):\n self.__res += n\n return self #返回对象本身可以实现多次点调用,这种方式叫链式编程\n\n @check_num\n def jian(self,n):\n self.__res -= n\n return self\n\n @check_num\n def cheng(self,n):\n self.__res *= n\n return self\n\n @check_num\n def chu_yi(self,n):\n self.__res /= n\n return self\n\n def show(self):\n print('计算结果是:%d'%self.__res)\n\n\na = Cal(2)\na.jia(3)\na.jian(2)\na.cheng(3)\na.chu_yi(3)\na.show()\nb = Cal(2)\nb.jia(3).jian(2).cheng(3).chu_yi(3).show()" }, { "alpha_fraction": 0.6815642714500427, "alphanum_fraction": 0.7402234673500061, "avg_line_length": 26.615385055541992, "blob_id": "da7719b0c7045d8b315920264f0c0f31eed5f29b", "content_id": "5f5614ba43044c0f29ec841bc3bece8240ed0de9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/helloworld/datetime模块.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#处理日期和时间的标准库,包含date对象和time对象\nimport datetime\nprint(datetime.datetime.now())\ntoday = datetime.datetime.now()\nprint(today.year)\n#计算n天后日期\nresult = today + datetime.timedelta(days= 7)\nprint(today, result)\n#计算时间差\nfir = datetime.datetime(2018, 8, 16, 0, 9, 0)\nsec = datetime.datetime(2018, 9, 15, 2, 3, 1)\ndeltime = sec - fir\nprint(deltime,deltime.total_seconds())" }, { "alpha_fraction": 0.5363724827766418, "alphanum_fraction": 0.6129971146583557, "avg_line_length": 34.55172348022461, "blob_id": "2d17b1a5f8e77336992328a356c2393f53b636b2", "content_id": "20368fadd7ec100820d259fbdc86a86bd761fc0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1613, "license_type": "no_license", "max_line_length": 150, "num_lines": 29, "path": "/机器学习/各种距离.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#1、两个n维向量A(x11,x12,x13,,,,,,,,,,,,,x1n),B(x21,x22,x23,,,,,,,,,,,,,x2n)之间的闵可夫斯基距离为:\n# sum = power((x11 - x21),p) + power((x12 - x22),p) + power((x13 - x23),p)+.......+ power((x1n - x2n),p)\n#d12 = sqrt(sum, p),\n# 当p=1时,为曼哈顿距离:差的绝对值之和: sum(abs(A - B))\n# p=2时为欧式距离(坐标物理距离):sqrt((A -B) * (A - B).T)\n# p=∞时,为切比雪夫距离,即对应位置差的绝对值的最大值:abs(A - B).max()\n\n\n#2、夹角余弦值:(A * B)/(|A| *|B|) dot(A, B)/(linalg.norm(A) * inalg.norm(B))\n\n\n#3、汉明距离:两个等长字符串s1,s2之间的汉明距离为:将其中一个变换为另一个所需要的最小替换次数。\nfrom numpy import *\nimport numpy as np\nmatA = np.array([[1, 1, 0, 1, 0, 1, 0, 0, 1],\n [0, 1, 1, 0, 0, 0, 1, 1, 1]])\nmatV = mat(matA)\nsmStr = nonzero(matV[0] - matV[1]) #返回非0元素的索引,是一个形式(array([0, 0, 0, 0, 0, 0], dtype=int32), array([0, 2, 3, 5, 6, 7], dtype=int32))的元组,第0个位行号,第二个位列号\nidx1 = np.transpose(smStr) #转置之后就可以组合成具体在二维数组中的索引\nprint(idx1)\n\n\n#4、杰拉德相似系数:两个集合A、B的交集在A和B的并集中占的比例。是两个集合相似度的一种治标\n#杰拉德距离:1- 杰拉德系数\nimport scipy.spatial.distance as dist\nprint(dist.pdist(matV, 'jaccard'))\n# 算术平均:mean()\n# 变量的协方差矩阵:cov()\n#马氏距离:优点是量纲无关,排除了变量之间相关性的干扰\n" }, { "alpha_fraction": 0.7238895297050476, "alphanum_fraction": 0.7599039673805237, "avg_line_length": 45.33333206176758, "blob_id": "d9c0131d2067db2a07e07778146f97a9db69089a", "content_id": "a57b40564b04e940cb4ae0d8f5ca2c1920bb28fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1229, "license_type": "no_license", "max_line_length": 152, "num_lines": 18, "path": "/机器学习/人脸检测.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#可以用几种特征来表示人脸的大致结构:眼睛、鼻子、前额、额骨和嘴,满足这些结构特征我们就认为这是一张人脸,为了提高运算速度,\n#我们选择排除图片中不包含人脸的位置,称这个过程为级联过程。,但人脸的特征远比这几个复杂的多,OpenCV里常用的人脸特征有Haar特征和LBP特征。\n#如果使用Haar特征,就需要使用Haar特征级联表作为训练集,在OpenCV根目录/sourse/data/ 文件夹下\nfrom numpy import *\nimport cv2\nface_cascade = cv2.CascadeClassifier(r'C:\\Users\\Administrator\\Desktop\\opencv-3.4.1\\opencv-3.4.1\\data\\haarcascades\\haarcascade_frontalface_alt_tree.xml')\nimg = cv2.imread('testPic.jpg')\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #转换成gray,opencv使用灰度图像处理\nfaces = face_cascade.detectMultiScale(gray, 1.1, 0)\n#detectMultiScale(需要识别的图片, 尺寸缩小比例, 3表示至少被检测4次才算真的目标)\n# print(faces, type(faces))\nfor (x, y, w, h) in faces: #绘制人脸边框\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\ncv2.imshow('img', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\ncv2.imwrite('testPic2.head.jpg', img)\nprint('end')" }, { "alpha_fraction": 0.5486981868743896, "alphanum_fraction": 0.566055953502655, "avg_line_length": 26.289474487304688, "blob_id": "63771eb8b11aa8e40f9aa253d112ede254120d47", "content_id": "acce245b6108f8d453e405d55c82e5807fd0e379", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1451, "license_type": "no_license", "max_line_length": 91, "num_lines": 38, "path": "/面向对象/字典或列表方式赋值修改实例对象.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "class A:\n def __init__(self):\n self.l = [1, 2, 3, 4, 5, 6, 7]\n\n def __setitem__(self, key, value): #key为slice类对象的一个实例,当实例使用列表或字典方式赋值操作的时候自动调用该方法\n self.l[key] = value\n print(key.start)\n print(key.stop)\n print(key.step)\n print(value)\n\n def __getitem__(self, item): #当实例对象采用列表或字典方式获取操作(遍历、访问)的时候自动调用该方法\n return self.l[item.start: item.stop: item.step]\n\n def __iter__(self): #重构该方法,当在遍历实例对象的时候会调用,必须返回一个迭代器,且优先级高于实现__getitem__方法\n return iter(self.l)\n\n def __next__(self): #与iter组合,必须设置终止条件\n i = 0 #添加这一条语句可以实现迭代器的重复使用,正常情况下一次迭代完毕之后指向了末尾,多了这条语句指向了开头\n if i < self.l.__len__():\n return self.l[i]\n else:\n raise StopIteration('END!')\n\n def __delitem__(self, key):\n del self.l[key]\n\n def __str__(self):\n return str(self.l)\n\na = A()\na[0: 4: 2] = ['a', 'b'] #执行到该条赋值语句时会自动调用__setitem__函数,key被赋值为[0: 4: 2]的slice实例,并完成相应的赋值操作\n# print(a.l)\nprint(a[0: 6: 1])\ndel a[1]\nprint(a)\nfor i in a:\n print(i)\n" }, { "alpha_fraction": 0.397298127412796, "alphanum_fraction": 0.483573853969574, "avg_line_length": 21.625, "blob_id": "cdc4ad2bf509cf7790d3c0a2fb02c765fbd2afb1", "content_id": "d2e08f3b315d317aa3f05cbbf2320eb0e694ba56", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3405, "license_type": "no_license", "max_line_length": 67, "num_lines": 144, "path": "/venv/Lib/site-packages/comm_libs/string_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf8\nimport re\nimport types\n\n\ndef num_to_capital_letter(num):\n \"\"\" 将数字转为大写字母 wjl\n\n :param num:\n :return:\n \"\"\"\n\n return chr(num + 64)\n\n\ndef letter_to_num(letter):\n \"\"\"将字母转为数字,无论大小写 wjl\n\n :param letter:\n :return:\n \"\"\"\n\n if isinstance(letter, types.IntType):\n return letter\n\n import logging\n logging.info(letter)\n\n return ord(letter.upper()) - 64\n\n\ndef convert_zh_to_spell(str_input):\n \"\"\"\n 取汉字字符串的首字母\n :param str_input: 汉字字符串\n :return: 首字母字符串,大写\n \"\"\"\n\n if isinstance(str_input, unicode):\n unicode_str = str_input\n else:\n try:\n unicode_str = str_input.decode('utf8')\n except:\n unicode_str = str_input.decode('gbk')\n\n return_list = []\n for one_unicode in unicode_str:\n return_list.append(_convert_single_char_to_zh(one_unicode))\n\n return \"\".join(return_list).upper()\n\n\ndef _convert_single_char_to_zh(zh_char):\n \"\"\"\n 将单个中文字符转为其拼音首字母\n :param zh_char: 中文字符\n :return: 拼音首字母\n \"\"\"\n str = zh_char.encode('gbk')\n\n try:\n ord(str)\n return str\n except:\n asc = ord(str[0]) * 256 + ord(str[1]) - 65536\n\n if -20319 <= asc <= -20284:\n return 'a'\n if -20283 <= asc <= -19776:\n return 'b'\n if -19775 <= asc <= -19219:\n return 'c'\n if -19218 <= asc <= -18711:\n return 'd'\n if -18710 <= asc <= -18527:\n return 'e'\n if -18526 <= asc <= -18240:\n return 'f'\n if -18239 <= asc <= -17923:\n return 'g'\n if -17922 <= asc <= -17418:\n return 'h'\n if -17417 <= asc <= -16475:\n return 'j'\n if -16474 <= asc <= -16213:\n return 'k'\n if -16212 <= asc <= -15641:\n return 'l'\n if -15640 <= asc <= -15166:\n return 'm'\n if -15165 <= asc <= -14923:\n return 'n'\n if -14922 <= asc <= -14915:\n return 'o'\n if -14914 <= asc <= -14631:\n return 'p'\n if -14630 <= asc <= -14150:\n return 'q'\n if -14149 <= asc <= -14091:\n return 'r'\n if -14090 <= asc <= -13119:\n return 's'\n if -13118 <= asc <= -12839:\n return 't'\n if -12838 <= asc <= -12557:\n return 'w'\n if -12556 <= asc <= -11848:\n return 'x'\n if -11847 <= asc <= -11056:\n return 'y'\n if -11055 <= asc <= -10247:\n return 'z'\n return ''\n\ndef string_to_xing(content, frontLen, endLen):\n length = len(content) - frontLen - endLen\n if length < 0:\n return None\n xing = ''\n for i in range(0, length):\n xing = xing + '*'\n a = content[0: frontLen]\n b = content[len(content) - endLen:len(content)]\n return a + xing + b\n\ndef isEmoji(comment):\n \"\"\"\n 替换表情\n :param comment:\n :return:\n \"\"\"\n try:\n # UCS-4\n highpoints = re.compile(u'[\\U00010000-\\U0010ffff]')\n except re.error:\n # UCS-2\n highpoints = re.compile(u'[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]')\n mytext = highpoints.sub('', comment)\n return mytext\n\n\n# if __name__ == '__main__':\n# print string_to_xing('15311432059', 3, 0)" }, { "alpha_fraction": 0.6419413685798645, "alphanum_fraction": 0.6703296899795532, "avg_line_length": 35.41666793823242, "blob_id": "8023e520b4192da866cf56d53df2cd3b9c03b6b0", "content_id": "7bf291d0815df79847ca291eff2e95cee10730c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2704, "license_type": "no_license", "max_line_length": 123, "num_lines": 60, "path": "/机器学习/knn分类算法.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#1、朴素贝叶斯算法:P(A)*P(B|A) = P(B)* P(A|B)\n#2、如果一个样本在特征空间中的k个最邻近(最相似)的样本大多数都属于某一个类别,则该样本也属于这个类别\n#knn算法分类,并且距离计算采用的是夹角余弦值。\nimport numpy as np\nfrom numpy import *\nimport operator\n# import sys\n# path = 'D:\\PythonDemo\\机器学习'\n# sys.path.append(path)\n# from .knn_cos import cosdist\n# from .knn_cos import clssify\nnp.seterr(invalid='ignore') #存在运行时警告,这里设置忽略\ndef creat_data_set():\n group = array([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])\n lables = ['A', 'A', 'B', 'B']\n return group, lables\n\n\ndef cosdist(vector1, vector2):\n return dot(vector1, vector2)/(linalg.norm(vector1) * linalg.norm(vector2))\n\n\ndef clssify(testDate, trainSet, listClasses, k): #listClasses:类别标签\n dataSetSize = trainSet.shape[0] #返回样本集的行数\n distances = array(zeros(dataSetSize))\n for index in range(dataSetSize):\n distances[index] = cosdist(testDate, trainSet[index])\n sortedDistIndicies = argsort(-distances) #返回对数据排序的索引,这里是-distances表示从余弦值从大到小排列,越大说明夹角越小\n classCount = {}\n for i in range(k): #获取角度最小的前k项作为参考项\n voteIlabel = listClasses[sortedDistIndicies[i]] #按排序顺序返回样本集对应的类别标签\n classCount[voteIlabel] = classCount.get(voteIlabel, 0) + 1 #为字典clssCount赋值(标签,标签出现次数),如果key相同,则value +1,如果不存在则赋值为0\n #get(key, default) 函数返回指定键的值,如果值不在字典中返回默认值\n sortedClassCount = sorted(classCount.items(), key=operator.itemgetter(1), reverse=True)\n #sorted(可迭代对象,key=operator.itemgetter(1),reverse = True)是sorted的固定用法\n return sortedClassCount[0][0]\n\n\n#画图\ndataSet, labels = creat_data_set()\n# print(dataSet, labels)\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_subplot(111)\nindex = 0\nfor point in dataSet:\n if labels[index] == 'A':\n ax.scatter(point[0], point[1], c='blue', marker='o', linewidths=0, s=300)\n plt.annotate('A', xy=(point[0], point[1]))\n # print(point)\n else:\n ax.scatter(point[0], point[1], c='red', marker='^', linewidths=0, s=300)\n plt.annotate('B', xy=(point[0], point[1]))\n index += 1\n# plt.show()\n#测试一个点属于哪一个类,绘图\ntestData = [0.2, 0.2]\nax.scatter(testData[0], testData[1], c='green', marker='*', linewidths=0, s=300)\nplt.show()\nprint(clssify(testData, dataSet, labels, 3))" }, { "alpha_fraction": 0.6054053902626038, "alphanum_fraction": 0.6926640868186951, "avg_line_length": 38.272727966308594, "blob_id": "f390f9d67ccf3721908664936b7dcc4340e6a593", "content_id": "a56841f2c94f98575dcf1da067ef5c1ead6174d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1591, "license_type": "no_license", "max_line_length": 111, "num_lines": 33, "path": "/机器学习/OpenCV.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import cv2\n#1、从窗口显示一副图片\n# cv2.namedWindow('winName', cv2.WINDOW_NORMAL) #参数为:窗口名称,可以手动调节窗口大小\n# img = cv2.imread('myPIC.jpg', 1) #1:原色图片;0:黑白图片\n# cv2.imshow('winName', img) #显示图片\n# cv2.waitKey(0)\n# cv2.destroyAllWindows() #销毁创建的对象\n# #2、保存图片:OpenCV可将图片转换为PGM格式\n# cv2.imwrite('pic2PGM.pgm', img)\n# #3、在matplotlib中显示图片\n# from matplotlib import pyplot as plt\n# img = cv2.imread('pic2PGM.pgm', 0)\n# plt.imshow(img, cmap='gray', interpolation='bicubic')\n# plt.xticks([]), plt.yticks([])\n# plt.show()\n#4、绘制直线和矩形\nfrom numpy import *\nimg = zeros((512, 512, 3))\n#起点:(0,0),终点:(511,511),颜色:(0,255,255),像素:2\ncv2.line(img, (0, 0), (511, 511), (0, 255, 255), 2)\n#左上角:(150,150);右下角:(350,350);颜色:(255,255,0)BGR;像素:2\ncv2.rectangle(img, (150, 150), (350, 510), (255, 255, 0), 2)\ncv2.imshow('image', img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n#5、绘制圆形和椭圆形:\n# cv2.circle(img, center, radius, color, thickness=None, lineType=None, shift=None)\n# cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness=None, lineType=None, shift=None)\n#6、绘制多边形\n# cv2.polylines(img, pts, isClosed, color, thickness=None, lineType=None, shift=None)\n#7、写入文字\n# font = cv2.FONT_HERSHEY_COMPLEX #字体\n# cv2.putText(img, text, org, fontFace, fontScale, color, thickness=None, lineType=None, bottomLeftOrigin=None)" }, { "alpha_fraction": 0.6225165724754333, "alphanum_fraction": 0.6401765942573547, "avg_line_length": 27.375, "blob_id": "0b657f0656707260abbf980c1388b6e40a89ef25", "content_id": "8c8fe006f42bf8153a4a3de09da9a54e8b51c172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 73, "num_lines": 16, "path": "/面向对象/属性方法相关.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "class Person(object): #严格来说,使用属性装饰器应该继承object类,python 3.x版本默认继承object类\n def __init__(self):\n self.__age = 18 #构造函数在创建实例对象的时候就会自动调用,创建私有的age属性\n\n @property #属性装饰器能够实现像读取属性一样使用方法\n def age(self):\n return self.__age #公开私有age属性的获取接口,可以实现私有属性的只读操作\n\n @age.setter #新式类中可以关联,经典类(没有继承object类)不可以\n def age(self, value):\n self.__age = value\n\n\np = Person()\n#p.age = 20 #没有9-11行的情况下,只读属性赋值会报错\nprint(p.age)" }, { "alpha_fraction": 0.4365079402923584, "alphanum_fraction": 0.5396825671195984, "avg_line_length": 24.399999618530273, "blob_id": "eed69ca4772c0faa4cb1bd95f4f29bab98946adb", "content_id": "948d2b4e35b573484aa218896792d0a89f061df5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 43, "num_lines": 5, "path": "/helloworld/列表的判定、比较.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#判定: 元素 in 列表\n# 元素 not in 列表\nnum = [1, 2, 56, 6, 7, 9, 10]\nprint(7 in num)\n#比较: >,< ,==等:从左到右依次比较,前面大返回1;相等返回0;后面大返回-1" }, { "alpha_fraction": 0.6651982665061951, "alphanum_fraction": 0.691629946231842, "avg_line_length": 49.44444274902344, "blob_id": "e4febd6abc94756bd82dcb33f8607a9d121c20d3", "content_id": "dd55bf0122012ed9b1e027d92cda598a0ccfe960", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 82, "num_lines": 9, "path": "/机器学习/jieba分词.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import jieba\nfrom sklearn.datasets.base import Bunch\nseg_list = jieba.cut('小明1995年毕业于北京清华大学', cut_all=False) #采用精准模式分词\nprint(type(seg_list)) #jieba.cut()得到的是一个生成器对象\nprint('//'.join(seg_list)) #Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'\nseg_list1 = jieba.cut('小明1995年毕业于北京清华大学', cut_all=True) #采用整体模式分词\nprint('//'.join(seg_list1))\nseg_list2 = jieba.cut_for_search('小明硕士毕业于中国科学院计算机所,后再日本京都大学深造') #采用搜索引擎模式分词\nprint('//'.join(seg_list2))\n" }, { "alpha_fraction": 0.4680851101875305, "alphanum_fraction": 0.4893617033958435, "avg_line_length": 17.875, "blob_id": "a7301415febe117c45f9f66961276367bb2ec95a", "content_id": "64b801460cc59c8fabf33626af55f8a294d569ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 61, "num_lines": 32, "path": "/venv/Lib/site-packages/comm_libs/exception.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# coding:utf8\n\n\"\"\"\n异常类定义\ncreated by : xiaochun\ndate : 2015-05-20\n\"\"\"\n\nclass HzfException(Exception):\n \"\"\"\n hzf异常基类\n \"\"\"\n\n def __init__(self, err_code, err_msg):\n '''\n err = (error_code, error_msg)\n '''\n super(HzfException, self).__init__(err_code, err_msg)\n self.__err = (err_code, err_msg)\n \n def msg(self):\n return self.__err[1]\n \n def code(self):\n return self.__err[0]\n \n def __str__(self):\n return '(%s %s)' %(self.__err[0], self.__err[1])\n \n def __tuple__(self):\n return self.__err\n\n \n\n" }, { "alpha_fraction": 0.6123347878456116, "alphanum_fraction": 0.6607929468154907, "avg_line_length": 22.66666603088379, "blob_id": "75987450c6de906f2fa80044aa642b3d9ca0673a", "content_id": "e148a00b789ea7f100a41a6403b2868b44ce0dde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1639, "license_type": "no_license", "max_line_length": 66, "num_lines": 48, "path": "/机器学习/矩阵基础操作.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import *\nmyZero = np.zeros((3, 5)) #生产3行5列的0矩阵\nprint(myZero)\nmyZero.A\nprint('*' * 30)\nmyOne = np.ones((5, 3)) #生产5行3列的元素全为1矩阵\nprint(myOne)\nprint('*' * 30)\nmyEye = np.eye(4) #单位矩阵\nprint(myEye)\nprint('*' * 30)\nmyRand = np.random.rand(3, 4)\nprint(myRand) #生成3行4列的0~1之间的随机数矩阵\nprint('*' * 30)\n#两个矩阵的‘+’、‘-’运算为矩阵各个元素的加减\nmyRand1 = np.random.rand(3, 4)\nprint(myRand1)\nmyRand2 = np.random.rand(3, 4)\nprint(myRand2)\nprint('*' * 30)\nprint(myRand2 + myRand1)\n#sum(矩阵M):矩阵所有元素和\n#num * M:一个数乘以矩阵M\n#multiply(M1, M2):表示矩阵对应元素的相乘,两个矩阵必须行列数都相同\n#矩阵的n次幂:power(M,n)\n#矩阵的乘法:M1 * M2\n#矩阵的转置:M.T 或者M.transpose()\n#M[idx] :行切片\n#M.T[idx] :列切片\n#M1 < M2 :对应元素的比较大小\n(m, n) = myRand1.shape #矩阵的行、列数\nprint(m, n)\nprint('*' * 30)\n#矩阵的行列式:linalg.det(M) M为方阵 (矩阵A的行列式detA就是线性变换A下的图形面积或体积的伸缩因子)\n#矩阵的秩(非0子式的最高阶数):linalg.matrix_rank(M)\nprint(linalg.det(myEye))\nprint(linalg.matrix_rank(myRand1))\n#矩阵的对称:M * M.T\nprint('*' * 30)\nm = np.matrix('[1, 2; 3, 4]')\n#逆矩阵: .I 或者M.getI()\nprint(m.I)\nprint(m.getI())\n#向量范数:向量到原点的距离:linalg.norm(M)\nprint(linalg.norm(myEye))\n# 逆矩阵:linalg.inv(M)\n# diag(v, k=0) 构造对角阵,k表示对角线与主对角线的关系" }, { "alpha_fraction": 0.6595744490623474, "alphanum_fraction": 0.682624101638794, "avg_line_length": 30.33333396911621, "blob_id": "3d494a2f90f59d48a7b2207ce1602e231e95742f", "content_id": "8555e3135545e87c69e6429f736a168af0ef616b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 948, "license_type": "no_license", "max_line_length": 112, "num_lines": 18, "path": "/函数/菲波那切数列生成器实现.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# 简单地讲,yield 的作用就是把一个函数变成一个 generator,带有 yield 的函数不再是一个普通函数,Python 解释器会将其视为一个 generator,调用 fab(50) 不会执行 fab 函数,\n# 而是返回一个 iterable 对象!在 for 循环执行时,每次循环都会执行 fab 函数内部的代码,执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,\n# 而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield。\n# 也可以手动调用 fab(50) 的 next() 方法(因为 fab(50) 是一个 generator 对象,该对象具有 next() 方法)\n\n\ndef fibinacci(num):\n pre = 0\n cur = 1\n count = 1\n while count < num:\n yield cur\n pre, cur = cur, pre + cur\n count += 1\n\n\nfor i in fibinacci(50):\n print(i, type(fibinacci(5)))\n" }, { "alpha_fraction": 0.4217686951160431, "alphanum_fraction": 0.44897958636283875, "avg_line_length": 12.272727012634277, "blob_id": "16f77012fabd846a3138474188e45e4cd1b033f8", "content_id": "3efb8c200510ee8f251c223586d2a382de16e62f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 147, "license_type": "no_license", "max_line_length": 29, "num_lines": 11, "path": "/函数/main.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "def func1():\n print('__name__ == main')\n\n\ndef func2():\n print('__name__ != main')\n\nif __name__ == '__main__':\n func1()\nelse:\n func2()\n\n" }, { "alpha_fraction": 0.49242424964904785, "alphanum_fraction": 0.5075757503509521, "avg_line_length": 9.230769157409668, "blob_id": "4006518cd92d39281e4c7ba4ff6d71914b9c6fbe", "content_id": "867568f2ab7f2187fae95f291e1675775129e889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 21, "num_lines": 13, "path": "/函数/高阶函数demo.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "def do(func, a, b):\n return func(a, b)\n\n\ndef add(a, b):\n return a + b\n\n\ndef sub(a, b):\n return a - b\n\n\nprint(do(sub, 5, 7))" }, { "alpha_fraction": 0.6710526347160339, "alphanum_fraction": 0.8026315569877625, "avg_line_length": 24.66666603088379, "blob_id": "565687220e40693d639f383915ca969b42b784ae", "content_id": "83c8db5195b5aba407c09f693eb073a00ea0fa06", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 90, "license_type": "no_license", "max_line_length": 30, "num_lines": 3, "path": "/helloworld/calendar模块.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import calendar\n#获取某月日历:calendar.month(2018,8)\nprint(calendar.month(2018,8))" }, { "alpha_fraction": 0.6058632135391235, "alphanum_fraction": 0.6156351566314697, "avg_line_length": 13.523809432983398, "blob_id": "7a9782865a6fe630fc851653e1bc8c221b89619d", "content_id": "89df3603d163b6140eb34cf195cb4449bffb5b76", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "no_license", "max_line_length": 57, "num_lines": 63, "path": "/venv/Lib/site-packages/comm_libs/log_tool.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# coding:utf8\n\n\"\"\"\n日志工具类函数\n\ncreate by: xiaochun\ndate : 2015-05-20\n\"\"\"\n\nimport logging\nimport logging.config \n\nimport os\n\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\nlogging.config.fileConfig(BASE_DIR+\"/confs/logging.conf\")\n\napplog = logging.getLogger('applog')\naccesslog = logging.getLogger('accesslog')\n\n\ndef write_debug_log(content):\n \"\"\"\n \"\"\"\n applog.debug(content)\n\n\ndef write_info_log(content):\n \"\"\"\n \"\"\"\n applog.info(content)\n \n \ndef write_warn_log(content):\n \"\"\"\n \"\"\"\n applog.warn(content)\n\ndef write_error_log(content):\n \"\"\"\n \"\"\"\n applog.error(content)\n\ndef write_access_log(content):\n \"\"\"\n \"\"\"\n accesslog.info(content)\n \n\n\nif __name__ == \"__main__\":\n\n write_debug_log(\"debug_test\")\n\n write_info_log(\"info_test\")\n\n write_warn_log(\"warn_test\")\n\n write_error_log(\"error_test\")\n\n write_access_log(\"accesslog_test\")\n\n \n" }, { "alpha_fraction": 0.5984455943107605, "alphanum_fraction": 0.5984455943107605, "avg_line_length": 21.764705657958984, "blob_id": "4119903cd8baae755ee5deffbfcdcd55554dac98", "content_id": "e258fdf66db279847a22a98e3a804da6cafdd69f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 426, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/文件操作/py/列表清单.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#生成.txt格式的文件清单\n#遍历打印函数:\nimport os\npath = 'D:\\PythonDemo'\ndef fileNamePrint(dir):\n fileLst = os.listdir(dir)\n for fileName in fileLst:\n new_file_name = dir + '/' + fileName\n if os.path.isdir(new_file_name):\n print(new_file_name)\n fileNamePrint(new_file_name)\n else:\n print('\\t' +fileName)\n\n\nos.chdir(path)\nfileNamePrint('文件操作')" }, { "alpha_fraction": 0.5518072247505188, "alphanum_fraction": 0.5686746835708618, "avg_line_length": 18.809524536132812, "blob_id": "0616467465c571f0f4f6434cf94c4ccdb950e28a", "content_id": "50817aafeafd52a206acf5fa742f23849a280686", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 93, "num_lines": 21, "path": "/面向对象/对象的生命周期案例.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "class Person:\n __count = 0\n\n def __init__(self):\n print('new one')\n Person.__count += 1 #注意:此处千万不能写成self.__count += 1,因为self为实例对象,那样会给实例对象的__count 赋值\n\n def __del__(self):\n print('delete one')\n Person.__count -= 1\n\n @classmethod\n def num_count_print(cls):\n print(cls.__count)\n\n\np1 = Person()\np2 = Person()\nPerson.num_count_print()\ndel p1\nPerson.num_count_print()" }, { "alpha_fraction": 0.6934046149253845, "alphanum_fraction": 0.7023172974586487, "avg_line_length": 33.367347717285156, "blob_id": "333677dbe25b70e2b3ab09778778289f009ccefa", "content_id": "f28ca5d1403981cbab442ad7f51906fd01e057a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3239, "license_type": "no_license", "max_line_length": 95, "num_lines": 49, "path": "/面向对象/class.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#类的创建遵循5大原则:\n#1、单一原则:1个类只负责一个功能\n#2、开放关闭原则:对扩展开放、对修改关闭\n#3、里氏替换原则:使用基类引用的地方必须能使用继承类的对象(任何时候都可以用子类对象替换父类对象)\n#4、接口分离原则:如果一个类包含过多的接口(简单理解为抽象方法)方法,而这些方法在使用的时候并非“不可分割”,那么应该把他们进行分离\n#5、依赖倒置原则:高层模块不应该直接依赖低层模块,应该依赖抽象类或接口(如:电脑类不应该依赖鼠标类,而应该是鼠标类的一个抽象(能单击、双击、右击、移动指针),到时可以是无线鼠标、触摸板等)\n\n#类的实例对象通过__class__属性而找的相应的类\n#类的创建:type(类型,继承的类元组,类的属性和方法字典)\ndef run(self):\n \"\"\"\n\n :param self:\n :return:\n \"\"\"\n print(self)\n\n\nxxx = type('Person', (), {'name': 'zyf', 'high': 180, 'weight': 63, 'run': run}) #创建一个类\nperson = xxx() #将创建的类实例化\nclass Money:\n \"\"\"\n 类相关注释\n \"\"\"\n # __slots__ = ['mianZhi', 'color'] #限制改类产生的对象添加的属性,也就是说Money类实例化的对象只能添加mianZhi、color两个属性\n moneyType = 'dollar' #类属性(公有),可以通过类访问和实例访问\n _a = '这是一个受保护的属性,访问会出警告'\n __b = '这是私有属性,只能类内部访问' #python无法实现真正私有,是通过名字重改机制实现的,如__x重改为:_class__x,不能版本python重改机制可能不一样\n def shi_li_method(self):\n print('这是一个实例方法', self) #self是实例的地址,实例方法的第一个参数必须是实例\n @classmethod #通过装饰器实现自动传递第一个参数\n def class_method(cls):\n print('这是一个类方法', cls) #cls为类名,类方法的第一个参数必须是类;类方法只能访问类属性\n @staticmethod\n def stat_method():\n print('这是一个静态方法') #第一个参数既不需要传递实例,也不需要传递类;不能直接访问对象属性和类属性\n #以上三种方法和类属性一样,都存储在类的__dict__属性字典里\nprint(Money.__name__) #类名\nmoney = Money() #创建一个Money对象\nmoney.mianZhi = 100 #创建一个对象属性:mainZhi,只能通过实例访问,不能通过类访问\nmoney.color = 'red'\nprint(money.__dict__) #dict函数访问所有的实例属性字典。\nmoney.shi_li_method() #实例方法的标准调用方法就是通过实例对象调用\nmoney.class_method() #通过实例也可以调用类方法,实例会被忽略,但实例对应的类会作为第一个参数传递过去,如果是子类调用则会把子类作为第一个参数传递\nmoney.stat_method()\n#通过实例可以调用所有存储在类中方法,而通过类名则不能调用实例方法\n# Money.shi_li_method() #通过类调用实例方法会报错,因为没有传第一个参数,确实第一个实例参数self\nMoney.class_method()\nMoney.stat_method()" }, { "alpha_fraction": 0.39579832553863525, "alphanum_fraction": 0.4252100884914398, "avg_line_length": 33.02857208251953, "blob_id": "efc8b3ad298a344463bf0fabbcdf65921de8756c", "content_id": "ba7db0b1844c8f651e757760bd354c4efc7d5ec9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1470, "license_type": "no_license", "max_line_length": 97, "num_lines": 35, "path": "/helloworld/列表的查询.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#--------------------------------获取列表单个元素------------------------------------------------------\nnum = range(1,10,2)\nprint(num[3])\n#--------------------------------获取列表某个元素的索引--------------------------------------------\n#.index(obj,start=0,stop=lst.len()),如果有多个则返回区间内第一个\nprint(num.index(7))\n\n#--------------------------------获取列表某个元素个数------------------------------------------------------\n#.count(obj),返回元素obj在列表中的个数\nnum = [1, 2, 2, 3, 4, 2, 4, 5]\nprint(num.count(4))\n#--------------------------------获取列表多个元素------------------------------------------------------\n# itms[start : end : step ]\nprint(num[2 : 5 : 1])\n#列表反转\nprint(num[::-1])\n#--------------------------------列表的遍历------------------------------------------------------\n#根据元素进行遍历,并同时打印当前元素对应的索引值\ncurrentIdx = 0\nfor v in num:\n print(v,num.index(v,currentIdx))\n currentIdx += 1\n#根据索引遍历\nnum = [1, 2, 2, 3, 4, 2, 4, 5]\nfor idx in range(len(num)):\n print(num[idx],end=\"\\n\")\n#创建枚举对象遍历 (key,value)\n#enumerate(itrObj,[start=0]):itrObj为一个序列、迭代器或其他支持迭代的对象\na = enumerate(num)\n# print(list(a))\nfor i in a:\n idx,val = i\n print(idx,val)\n# a1,a2=(a,b)执行之后a1==a;a2==b\n#判断是否可迭代:import collections isinstance(object, classinfo)" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 10, "blob_id": "8579157550f2d26d7139ed5e975a6e6df2437c9f", "content_id": "999cd5a14cd2b607e6e3e172308da1d609bbb67d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 33, "license_type": "no_license", "max_line_length": 14, "num_lines": 3, "path": "/helloworld/b.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import a\na.run()\nprint(\"World\")\n" }, { "alpha_fraction": 0.5279052257537842, "alphanum_fraction": 0.5504587292671204, "avg_line_length": 21.747825622558594, "blob_id": "676967a7f9939565082bc4f6f1285703eac11fa1", "content_id": "940575f6ca4006a10f840ecb12f1b915c2486f31", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2692, "license_type": "no_license", "max_line_length": 91, "num_lines": 115, "path": "/venv/Lib/site-packages/comm_libs/comm_utils.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "# coding:utf-8\nfrom time import gmtime\n\nfrom libs import sendmail\nfrom libs.log_tool import write_error_log\nfrom project.confs import MAIL_SERVER, SENDER_USER, SENDER_PASSWORD\n\ntry:\n from huizhaofang import settings\nexcept:\n from project import settings\n\n\ndef is_test_env():\n try:\n return settings.TESTENV\n except:\n return False\n\n\ndef check_user_id_no(id_str):\n \"\"\"\n copy from xiaochun's script\n 检查身份证号是否合法\n \"\"\"\n try:\n weight_num = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]\n tail_char = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']\n\n id_len = len(id_str)\n\n if id_len != 15 and id_len != 18:\n return False\n\n sum_num = 0\n for p in zip([int(i) for i in id_str[:-1]], weight_num):\n sum_num += p[0] * p[1]\n\n if tail_char[sum_num % 11] != id_str[-1]:\n return False\n except Exception, e:\n return False\n return True\n\n\ndef get_age(y, m, d):\n \"\"\"\n 根据时间得到年龄\n :param y:\n :param m:\n :param d:\n :return:\n \"\"\"\n # get the current time in tuple format\n a = gmtime()\n # difference in day\n dd = a[2] - d\n # difference in month\n dm = a[1] - m\n # difference in year\n dy = a[0] - y\n # checks if difference in day is negative\n if dd < 0:\n dd = dd + 30\n dm = dm - 1\n # checks if difference in month is negative when difference in day is also negative\n if dm < 0:\n dm = dm + 12\n dy = dy - 1\n # checks if difference in month is negative when difference in day is positive\n if dm < 0:\n dm = dm + 12\n dy = dy - 1\n return (dy, dm, dd)\n\n\ndef get_ip_address(request):\n \"\"\"\n 获取ip地址\n :param request:\n :return:\n \"\"\"\n ip = request.META.get(\"HTTP_X_FORWARDED_FOR\", \"\")\n if not ip:\n ip = request.META.get('REMOTE_ADDR', \"\")\n return ip\n\n\ndef get_http_referer(request):\n \"\"\"\n 获取referer\n :param request:\n :return:\n \"\"\"\n return request.META.get(\"HTTP_REFERER\", \"\")\n\n\ndef send_mail_notify(receiver_list, title, content):\n \"\"\"\n 发送通知邮件\n :param receiver_list:\n :param title:\n :param content:\n :return:\n \"\"\"\n title = \"【CRM】\" + title\n try:\n mail_client = sendmail.MailSender(MAIL_SERVER, SENDER_USER, SENDER_PASSWORD, 25)\n mail_client.set_subject(u\"%s\" % title)\n mail_client.add_content(content, \"utf8\")\n mail_client.set_sender(SENDER_USER)\n mail_client.set_receiver(receiver_list)\n mail_client.sendmail()\n except:\n write_error_log(\"%s邮件发送失败\" % title)\n" }, { "alpha_fraction": 0.5951219797134399, "alphanum_fraction": 0.642926812171936, "avg_line_length": 26, "blob_id": "7e44c6d2a97c67aabe4c19065e89fda26a519c3f", "content_id": "0395af83181dc4cfda7dadb693db15bae6c88b36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1389, "license_type": "no_license", "max_line_length": 119, "num_lines": 38, "path": "/helloworld/体脂率计算.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#输入身高、体重、年龄、性别\npersonHight = float(input('请输入身高(m)'))\npersonWight = float(input('请输入体重(kg)'))\npersonAge = int(input('请输入年龄'))\npersonSex = int(input('请输入性别(男:1 女:0)'))\n#验证数据有效性,取非操作可以简化改代码量\nif not (0 < personHight < 3 and 0 < personWight < 300 and (personSex == 0 or personSex == 1) and 0 < personAge < 150) :\n print('Input Error,the program will be eited')\n exit()\n#计算体脂率\nBMI = personWight / (personHight * personHight)\nTZL = 1.2 * BMI + 0.23 * personAge - 5.4 -18.8 * personSex\n#TZL = TZL * 100\n\n#判断体脂率是否在正常范围之内\n# minNum = 0.15 + 0.10 * (1 - personSex)\n# maxNum = 0.18 + 0.10 * (1 - personSex)\n# result = minNum < TZL < maxNum\n\n#告诉用户是否在正常范围内\n#print('您的体脂率是:%f%%,是否在正常范围内?'%(TZL) ,result)\n#判断性别,不同性别赋予不同的数值\nif personSex :\n wenhao = '先生您好,'\n minNum = 15\n maxNum = 25\nelse:\n wenhao = '女生您好,'\n minNum = 18\n maxNum = 28\nresult = minNum < TZL < maxNum\n#判断体脂率情况,告知用户\nif result :\n print(wenhao+'您的体脂率正常请继续保持!')\nelif TZL > maxNum :\n print(wenhao+'您的体脂率偏高,身体偏胖!')\nelse :\n print(wenhao+'您的体脂率偏低,身体偏瘦!')" }, { "alpha_fraction": 0.4506089389324188, "alphanum_fraction": 0.5121785998344421, "avg_line_length": 30.446807861328125, "blob_id": "12274469afdc53006df6258b207a9beecfc184d9", "content_id": "80fa813668f1b7ff329ab96bc0885cf2329d8b25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1916, "license_type": "no_license", "max_line_length": 110, "num_lines": 47, "path": "/机器学习/方程组迭代求解和消元求解.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom numpy import *\nimport matplotlib.pyplot as plt\n#1、消元求解\na = np.array([[8, -3, 2], [4, 11, -1], [6, 3, 12]])\n# print(a,type(a))\nb = np.array([20, 33, 36])\nresult = np.linalg.solve(a, b) #当a,b都是矩阵的时候,参数就应该是b.T,这里都是ndarray\nprint(result, type(result), len(result))\nprint('*' * 30)\n\n#-------------------------------------------------------------------------------------------------------------\n\n#2、迭代求解,又叫逐次逼近法,在训练大型数据集的时候使用\n#原理:对于给定方程组x = b0 * x +f,,(由方程组AX=B变换而来)使用公式:x^(k+1) = b0 * x^k +f ,\n# 其中k为迭代次数,如果k->∞时,x^(k+1)存在,称此迭代法收敛,极限值就是方程组的解,否则称此迭代法发散\nf = np.array([20/8, 3, 3])\nf = mat(f) #当计算2-D矩阵的时候,就要注意用np.array和mat数据类型的区别,使用乘法方面也不一样,最好是都用矩阵,即mat生成\nb0 =np.array([[0, 3/8, -2/8], [-4/11, 0, 1/11], [-6/12, -3/12, 0]])\nb0 = mat(b0)\n#把原多项式转换成x1=***;x2=***;x3=***的形式,可以得到b0和f\nerror = 1.0e-6\nsteps = 100\nxk = zeros((3, 1))\nerrorList =[]\nfor k in range(steps):\n xk_1 = xk\n xk = b0 * xk + f.T\n errorList.append(np.linalg.norm(xk - xk_1))\n if errorList[-1] < error:\n print('迭代次数:', k + 1)\n break\nprint(xk)\n#绘制误差点集\nmatplt = zeros((2, k + 1))\nmatplt[0] = linspace(1, k + 1, k +1)\nmatplt[1] = array(errorList)\nfig = plt.figure() #创建一个图\n# print(type(fig))\nax = fig.add_subplot(111) #增加一个子图,位置为1,1,1,等价:fig.add_subplot(1, 1, 1)\nax.scatter(matplt[0], matplt[1], c='blue') #(x,yn)离散图,蓝色\nplt.show()\nprint('*' * 30)\n\n#-------------------------------------------------------------------------------------------------------------\n\n#3、\n" }, { "alpha_fraction": 0.4945673942565918, "alphanum_fraction": 0.5303822755813599, "avg_line_length": 37.20000076293945, "blob_id": "3ce9fe07686d4a2628c22a8da3f536ad20f8e1e8", "content_id": "468ee5ed67f42003f5e430b969b9107069bc7ac8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3439, "license_type": "no_license", "max_line_length": 111, "num_lines": 65, "path": "/helloworld/字典.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#字典:无序的、可变的键值对集合。key不可重复,不可变,如重复则前面的会被后面的覆盖\n#----------------------------新建字典------------------------------------------------------------------------------\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\ninfo1 = dict.fromkeys('abc', 666)\n#dict.fromkeys('abc',666) 同{a:666,b:666,c:666}\nprint(info1)\n#---------------------------字典的增、删、改-----------------------------------------------------------------\ninfo['tel'] = '18115054967'\nprint(info)\n#语句删除\ndel info['sex']\nprint(info)\n#对象函数删除:.pop(key[,default]) 删除指定的键值对,返回对应的值,如果key不存在则不做删除,并返回给的default值,如果default也没给出则报错\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nd = info.pop('name1', 18)\nprint(d, info)\n#删除按升序排列后的第一个键值对,并以元组的形式返回改键值对,如果字典为空,则报错\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\ndlt = info.popitem()\nprint(dlt, info)\n#清空字典内容,字典对象还在: .clear()注意与del语句的差别,返回none\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nprint(info.clear(),info)\n#----------------------------修改单个键对应的值(key不能改) 同line 7---------------------------------\n#批量修改value:oldDict.update(newDict):根据newDict中的键值对更新oldDict中的键值对,如果oldDict中不存在对应的key,则新增键值对,返回值为none\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nrt = info.update({'tel': '18115054967','age': 35})\nprint(rt, info)\n#--------------------------字典查询相关--------------------------------------------------------------\n#直接通过key获取:dic[key]\n#函数获取:dic.get(key[,default]):key不存在则返回default值,如果没给定default则返回none,不会报错,不改变原字典\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nprint(info.get('age1', 666))\n#dic.setDefault(key[,default]):返回指定key对应的值,如果key不存在,则增加一个键值对:key:default,default未给则为none,\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nprint(info.setdefault('age1', 666))\nprint(info)\n\n\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\n#获取字典所有的值:dic.values(),返回的是字典视图对象,字典改变了,得到的视图对象也会改变,不管代码前后。(2.x版本是直接返回列表)\nprint(info.values())\n#获取字典所有的键:dic.keys()\nprint(info.keys())\n#获取字典所有的键值对:dic.items()\nprint(info.items())\n#-------------------------遍历-------------------------------------------------------------\n#1、通过key遍历\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nkey = info.keys()\nfor k in key:\n print(k)\n print(info[k])\n#2、直接遍历所有的键值对(推荐使用)\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nt = info.items()\ninfo['adress'] = 'shanghai'\n#即使在把键值对对象先赋值给了t,之后更改了字典,也不会影响遍历结果,这是字典视图对象的特性\nfor k, v in t:\n print(k, v)\n#------------------------计算和判断---------------------------------------------------------------\n#len(dic):计算键值对的个数\ninfo = {'name': 'zyf', 'age': 28, 'sex': 1}\nprint(len(info))\n#判断:判断的是key,不是value: xx in dic;xx not in dic;返回bool类型\n\n\n" }, { "alpha_fraction": 0.5704697966575623, "alphanum_fraction": 0.6577181220054626, "avg_line_length": 28.866666793823242, "blob_id": "6aaa56da0a1af9109759386e052e959755427984", "content_id": "aa33fc1c2931dffc370fe13a35d785b48b96708e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 72, "num_lines": 15, "path": "/机器学习/logistic函数图.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport matplotlib.lines as pltln\nfrom matplotlib.lines import Line2D\nx = np.linspace(-20, 20, 500)\ny = 1/(1 + np.e ** -x)\nfig = plt.figure() #创建一个图\n# print(type(fig))\nax = fig.add_subplot(111) #增加一个子图,位置为1,1,1,等价:fig.add_subplot(1, 1, 1)\nplt.plot(x, y)\nplt.plot([0, 0], [0, 1])\nplt.plot([-20, 20], [0.5, 0.5]) #绘制(-20,0.5),(20,0.5)的连线\nplt.title('Func:logistic')\nplt.show()" }, { "alpha_fraction": 0.6048879623413086, "alphanum_fraction": 0.6720977425575256, "avg_line_length": 23.600000381469727, "blob_id": "5d4987baa34c6a6d4cf30d2c2c17f223f999efd0", "content_id": "ab0307787e02b2d140718aa2a0579a7e321f2371", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 785, "license_type": "no_license", "max_line_length": 55, "num_lines": 20, "path": "/helloworld/判断水仙花数.py", "repo_name": "kakarotte22/PythonDemo", "src_encoding": "UTF-8", "text": "#需求:用户输入一个三位数字,暂不考虑非数字,判断是否为水仙花数,个十百位上数字的三次方和位数本身。\n#用户输入一个三位数字,暂不考虑非数字,\nnum = int(input('please enter the number(100~999):\\n'))\nif not(100 <= num <= 999):\n print('InputError,program excit')\n exit()\n# 判断是否为水仙花数,个十百位上数字的三次方和位数本身。\n#num // 100 求整除方法得到百位上的数字\nbaiWei = num // 100\n#num除100取余数之后再求整除得到百位上的数字\nshiWei = (num % 100) // 10\n#num除10求余得到个位数\ngeWei = num % 10\n#判断是否为水仙花数\nresult = (baiWei ** 3 +shiWei ** 3 + geWei ** 3) == num\n#打印结果\nif result :\n print('YES!')\nelse:\n print('NO!')" } ]
82
akshadapowar/-LB_DSC_JAN_24_WKND
https://github.com/akshadapowar/-LB_DSC_JAN_24_WKND
c00d3602dcc400e914b5f3eb7bf0e2645cec9ae2
6372e3e27b539326042b4196436d3aa2159a8dc1
877b5fd6034bf0858c4761364c1e1ffd0bcdf9e0
refs/heads/main
2023-02-23T14:27:55.384235
2021-01-31T01:46:05
2021-01-31T01:46:05
334,367,329
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7428571581840515, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 12.800000190734863, "blob_id": "c84b665125765f87568ccd5314fe6b2aac326484", "content_id": "10fbaaba021155f5aca0f956b73fc6bbb38b98a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 70, "license_type": "no_license", "max_line_length": 38, "num_lines": 5, "path": "/F1.py", "repo_name": "akshadapowar/-LB_DSC_JAN_24_WKND", "src_encoding": "UTF-8", "text": "This is Python class This got change..\nwow ...\nsdkfjsdkf\nsdkfj\nsdkmm\n\n" } ]
1
jasonqng/blocked-on-weibo
https://github.com/jasonqng/blocked-on-weibo
74b7c0215f6745df58264ab7765b5f4a2928fc18
691d5a2c8d1168daf3ae36a5eb94f380d315ca34
0e72c060671cce0aa4135d0e55c636d961ffc1d9
refs/heads/master
2023-04-15T03:41:13.513890
2023-04-10T18:01:34
2023-04-10T18:01:34
97,148,239
18
4
BSD-3-Clause
2017-07-13T17:21:00
2022-07-09T03:36:43
2023-04-10T18:01:34
Python
[ { "alpha_fraction": 0.5595763921737671, "alphanum_fraction": 0.5659759044647217, "avg_line_length": 40.5379753112793, "blob_id": "52258cebb06ea2d8c0d3bdf569d039396f98bd43", "content_id": "8a08910ae9c0ae45d8fd5ad5ceea970c6286e32d", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13176, "license_type": "permissive", "max_line_length": 207, "num_lines": 316, "path": "/blockedonweibo/weibo.py", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport urllib\nimport codecs\nimport time\nimport random\nimport sqlite3\nfrom datetime import datetime\nimport pandas as pd\nimport os\nimport io\nimport requests\nimport base64 \nimport re\nimport ast\nimport sys\ntry:\n from urllib.parse import urlparse\nexcept ImportError:\n from urlparse import urlparse\nimport rsa \nimport json \nimport binascii \nimport math\ntry:\n from . import weibo_credentials\nexcept ValueError:\n import weibo_credentials\n### SETTINGS\n\nCENSORSHIP_PHRASE = u'根据相关法律法规和政策'\nCAPTCHA_PHRASE = u'你的行为有些异常'\nNO_RESULTS_PHRASE = u'抱歉,未找到'\n\ndef has_censorship(keyword_encoded,\n cookie=None):\n\n \"\"\"\n Function which actually looks up whether a search for the given keyword returns text\n which is displayed during censorship.\n Can handle unicode and strings\n Currently no CAPTCHA handling, though it is detected\n Returns string of 'censored','no_results','reset',or 'has_results'\n ('has_results' is actually not a garuantee; it's merely a lack of other censorship indicators)\n \"\"\"\n url = (f'https://s.weibo.com/weibo?q={keyword_encoded}')\n cookies = {'required_cookie': cookie}\n headers = {'User-Agent': 'Mozilla/5.0'}\n try:\n r = requests.get(url,cookies=cookies, headers=headers).text\n i = 1\n while True:\n if CAPTCHA_PHRASE not in r:\n break\n else:\n print(\"CAPTCHA\", keyword_encoded, \"sleeping for %s seconds\" % 300*i)\n time.sleep(300*i)\n i+=1\n if i==50:\n print(\"Can't break out of CAPTCHA, aborting\")\n sys.exit(1)\n except IOError:\n wait_seconds = random.randint(90, 100)\n print(u\"%s caused connection reset, waiting %s\" % (keyword_encoded,wait_seconds))\n time.sleep(wait_seconds)\n return (\"reset\",None)\n\n num_results = re.findall(r'search_rese clearfix\\\\\">\\\\n <span>\\\\u627e\\\\u5230(\\d*)',r)\n if num_results:\n num_results = int(num_results[0])\n else:\n None\n if CENSORSHIP_PHRASE in r:\n return (\"censored\",None)\n elif NO_RESULTS_PHRASE in r:\n return (\"no_results\",None)\n else:\n return (\"has_results\",num_results)\n\ndef create_database(sqlite_file, overwrite=False):\n \"\"\"\n Generating a sqlite file for storing results\n Multi-index primary key on id, date, and source\n Set new_database to True in order to remove any existing file\n \"\"\"\n if overwrite and os.path.isfile(sqlite_file):\n os.remove(sqlite_file)\n if not os.path.isfile(sqlite_file):\n conn = sqlite3.connect(sqlite_file)\n c = conn.cursor()\n c.execute('''CREATE TABLE results (id int, date date, datetime_logged datetime, test_number int, keyword string, \n censored bool, no_results bool, reset bool, is_canonical bool, result string, source string, orig_keyword string, \n num_results int, notes string, PRIMARY KEY(date,source,test_number,keyword,orig_keyword))''')\n conn.commit()\n conn.close()\n\n\ndef insert_into_database(record_id,\n keyword_encoded,\n result,\n date=datetime.now().date(),\n source=\"default\",\n num_results=None,\n notes=None,\n sqlite_file=None,\n test_number=1,\n is_canonical=None,\n orig_keyword=None):\n \"\"\"\n Writing the results to the sqlite database file\n \"\"\"\n conn = sqlite3.connect(sqlite_file)\n conn.text_factory = str\n conn.execute(\"PRAGMA busy_timeout = 5000\")\n c = conn.cursor()\n \n dt_logged = datetime.now()\n if isinstance(notes, list):\n notes = str(notes)\n if isinstance(num_results, list):\n num_results = None\n \n if result == \"censored\":\n censored = True\n else:\n censored = False\n \n if result == \"no_results\":\n no_results = True\n else:\n no_results = False\n \n if result == \"reset\":\n reset = True\n else:\n reset = False\n\n query = u\"\"\"INSERT OR REPLACE INTO results (id, date, datetime_logged, test_number, keyword, censored, no_results, reset, is_canonical, result, source, orig_keyword, num_results, notes) \n VALUES (\n coalesce(\n (select id from results where date=date('{date}') and keyword='{keyword}' and test_number={test_number} and source='{source}'),\n ?),\n ?,?,?,?,?,?,?,?,?,?,?,?,?\n );\"\"\".format(date=date,keyword=keyword_encoded,test_number=test_number,source=source)\n c.execute(query, (record_id, date, dt_logged, test_number, keyword_encoded, censored, no_results, reset, is_canonical, result, source, orig_keyword, num_results, notes))\n\n conn.commit()\n conn.close()\n \ndef sqlite_to_df(sqlite_file,\n query=\"select * from results where source!='_meta_' or source is NULL;\"):\n conn = sqlite3.connect(sqlite_file)\n df = pd.read_sql_query(query, conn)\n return df\n\ndef verify_cookies_work(cookie,\n return_full_response_text=False):\n \"\"\"\n Returns True if cookies return profile indicator\n If no cookie or bad cookie is passed, you get a generic login page which doesn't have the indicator\n \"\"\"\n cookies = {'required_cookie': cookie}\n headers = {'User-Agent': 'Mozilla/5.0'}\n r = requests.get('https://s.weibo.com/weibo?q=test',cookies=cookies, headers=headers).text\n if return_full_response_text:\n return r\n if \"onick\" in r:\n return True\n else:\n return False\n\ndef load_cookies(cookie_file=\"_cookie.txt\"):\n with open(cookie_file, 'r') as f:\n #cookie = ast.literal_eval(f.read())\n cookie = f.read()\n return cookie\n\ndef run(keywords,\n verbose='all',\n insert=True,\n sqlite_file=None,\n return_df=False,\n sleep=True,\n cookie=None,\n sleep_secs=15,\n continue_interruptions=True,\n date=datetime.now().strftime('%Y-%m-%d'),\n test_number=1,\n list_source=\"list\",\n get_canonical=False\n ):\n \"\"\"\n Iterating through the keyword list and testing one at a time\n Handles when script or connection breaks; will pick up where it left off\n Set return_df to append each new result to a df in memory, which is returned at end of function\n verbose = 'some','all',or 'none'(technically anything besides 'some' or 'all' will not show anything)\n sleep = time in seconds to sleep between searches\n \"\"\"\n if sqlite_file:\n create_database(sqlite_file)\n\n count=0\n if return_df:\n results_df = pd.DataFrame()\n\n if isinstance(keywords, list):\n keywords = pd.DataFrame(keywords,columns=[\"keyword\"])\n keywords['source'] = list_source\n\n test_keywords = keywords.copy()\n\n if \"Index\" not in test_keywords.columns:\n test_keywords['Index'] = test_keywords.index\n if \"notes\" not in test_keywords.columns:\n test_keywords['notes'] = None\n if \"source\" not in test_keywords.columns:\n test_keywords['source'] = None\n source=test_keywords['source'][0]\n\n for r in test_keywords.itertuples():\n if isinstance(r.keyword, str):\n keyword_encoded = r.keyword\n\n if sqlite_file:\n if r.Index < len(sqlite_to_df(sqlite_file).query(\"date=='%s' & source=='%s' & test_number==%s & is_canonical!=1\" % (date,source,test_number))) and continue_interruptions:\n continue\n if len(sqlite_to_df(sqlite_file).query(u\"date=='%s' & source=='%s' & test_number==%s & keyword=='%s' & is_canonical!=1\" % (date,source,test_number,keyword_encoded)))>0 and continue_interruptions:\n continue\n result,num_results = has_censorship(keyword_encoded,cookie)\n if verbose==\"all\":\n print(r.Index,keyword_encoded, result)\n elif verbose==\"some\" and (count%10==0 or count==0):\n print(r.Index,keyword_encoded, result)\n\n min_str = None\n if get_canonical and result == \"censored\":\n if verbose==\"some\" or verbose==\"all\":\n print(\"Found censored search phrase; determining canonical censored keyword set\")\n sleep_recursive = sleep_secs if sleep else 0\n potential_kws = split_search_query(keyword_encoded, cookie, sleep_recursive, res_rtn=[], known_blocked=True, verbose=verbose)\n if verbose==\"all\":\n print(potential_kws)\n\n for kw in potential_kws:\n test_list = [kw[:i] + kw[i + 1:] for i in range(len(kw))]\n min_str = \"\"\n for i in range(len(test_list)):\n if kw[i].isspace():\n continue\n if verbose==\"all\":\n print(\"Testing %d of %d: omitting character %s\" %(i+1, len(test_list), kw[i]))\n if sleep:\n time.sleep(random.randint(math.ceil(sleep_secs * .90), math.ceil(sleep_secs * 1.10)))\n if has_censorship(test_list[i], cookie)[0] != \"censored\":\n min_str += (kw[i])\n result_min_str, num_results_min_str = has_censorship(min_str, cookie)\n if result_min_str == \"censored\": # minStr found properly\n if verbose==\"all\" or verbose==\"some\":\n print(\"the minimum phrase from '%s' is: '%s'\" % (kw, min_str))\n if insert:\n insert_into_database(len(sqlite_to_df(sqlite_file)), min_str, date=date, result=result_min_str,\n source=r.source, num_results=num_results_min_str, notes=r.notes,\n sqlite_file=sqlite_file, test_number=test_number, is_canonical=True,\n orig_keyword=keyword_encoded)\n else:\n print(\"Failed to find canonical phrase\")\n\n if insert:\n insert_into_database(len(sqlite_to_df(sqlite_file)), keyword_encoded, date=date, result=result, source=r.source,\n num_results=num_results, notes=r.notes, sqlite_file=sqlite_file, test_number=test_number,\n is_canonical=False)\n if return_df:\n results_df = pd.concat([results_df,\n pd.DataFrame([{\"date\":date,\n \"datetime\":datetime.now(),\n \"keyword\":min_str if min_str is not None else r.keyword,\n \"result\":result,\n \"source\":r.source,\n \"num_results\":num_results,\n \"test_number\":test_number,\n \"is_canonical\": True if min_str is not None else False,\n \"orig_keyword\":r.keyword if min_str is not None else None\n }])\n ])\n count+=1\n if sleep:\n time.sleep(random.randint(math.ceil(sleep_secs*.90), math.ceil(sleep_secs*1.10)))\n if insert:\n insert_into_database(int(test_keywords.index.max())+1,None,date=date,result=\"finished\",source=\"_meta_\",sqlite_file=sqlite_file,test_number=test_number)\n if return_df:\n return results_df\n\n\ndef split_search_query(query, cookie, sleep_secs=0, res_rtn=[], known_blocked=False, verbose=\"\"):\n \"\"\"\n Recursively halves a query and returns portions with blocked keywords as a list of strings.\n :param res_rtn: internal list holding found min keywords during recursive search, DO NOT SPECIFY.\n :param known_blocked: set to True to skip a redundant first-check if you know your query is blocked.\n :return: a list of one or more shortened keyword segments that trigger censorship\n \"\"\"\n if len(query) <= 1:\n return [-1]\n if sleep_secs:\n time.sleep(random.randint(math.ceil(sleep_secs * .90), math.ceil(sleep_secs * 1.10)))\n if (not known_blocked) and verbose=='all':\n print('Recursively shortening... testing query: \"%s\"' %(query))\n if (not known_blocked) and has_censorship(query, cookie)[0] != \"censored\": # known_blocked=True skips 1st check\n return [-1]\n else:\n mid = len(query) // 2\n left_half = query[:mid]\n right_half = query[mid:]\n left_res = split_search_query(left_half, cookie, sleep_secs, res_rtn, False, verbose)\n right_res = split_search_query(right_half, cookie, sleep_secs, res_rtn, False, verbose)\n if (left_res[0] == -1) and (right_res[0] == -1):\n res_rtn.append(query)\n return res_rtn\n" }, { "alpha_fraction": 0.8666666746139526, "alphanum_fraction": 0.9111111164093018, "avg_line_length": 8.199999809265137, "blob_id": "5fcbb04a146dcb0c6bf8c3437d83de500bac1a54", "content_id": "a84514617e7d66d4648fc3242269b066fb9653b6", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 45, "license_type": "permissive", "max_line_length": 14, "num_lines": 5, "path": "/requirements.txt", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "beautifulsoup4\npandas\nrequests\nrsa\ndf2gspread" }, { "alpha_fraction": 0.4322457015514374, "alphanum_fraction": 0.5026606917381287, "avg_line_length": 21.568435668945312, "blob_id": "82e59b6e8b7d3647ae6963474f512d0bb25a24ef", "content_id": "41c7494f177351362b32fd7c326e0dbfe3b8b57f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 48780, "license_type": "permissive", "max_line_length": 3746, "num_lines": 2148, "path": "/README.md", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "# What is blockedonweibo?\n\nThis python package allows you to automate tests to check if a keyword is censored or not on Sina Weibo, a Chinese social media site. It is an updated version of the script which was used to detect keywords on the site, http://blockedonweibo.com. It handles interrupted tests, multiple tests per day, storing results to a database, and a number of other features which simplify testing Weibo censorship at scale. The researcher merely has to feed the script a list of words for one-off tests. For recurring tests, simply wrap the script with a scheduler.\n\n<img src=\"screenshot.png\" alt=\"screenshot\" style=\"width: 700px;\"/>\n\n# IMPORTANT: Upgrading from v0.1 with an existing database? \nThe database table has been modified to accomodate tracking of minimum keyword strings triggering \ncensorship. If you used blockedonweibo v0.1 and you used a database to store results, you will \nneed to update your database file. \n\n**To migrate your older database file**\n1. Move `update_db.py` to the same file directory as your database file (\"results.sqlite\" if you followed\nthis setup guide)\n2. In terminal, run `python update_db.py` and confirm database file. \n\n### Version 0.2 changes \n* now includes a feature to find canonical censored keywords (minimum set of keywords required to trigger explicit censorship message)\n * to run, pass `get_canonical=True` with rest of variables into `run()`\n * see section 4.8\n\n\n# Table of Contents\n <p><div class=\"lev1 toc-item\"><a href=\"#What-is-blockedonweibo?\" data-toc-modified-id=\"What-is-blockedonweibo?-1\"><span class=\"toc-item-num\">1&nbsp;&nbsp;</span>What is blockedonweibo?</a></div><div class=\"lev1 toc-item\"><a href=\"#Install-the-blockedonweibo-package\" data-toc-modified-id=\"Install-the-blockedonweibo-package-2\"><span class=\"toc-item-num\">2&nbsp;&nbsp;</span>Install the blockedonweibo package</a></div><div class=\"lev1 toc-item\"><a href=\"#Adjust-your-settings\" data-toc-modified-id=\"Adjust-your-settings-3\"><span class=\"toc-item-num\">3&nbsp;&nbsp;</span>Adjust your settings</a></div><div class=\"lev1 toc-item\"><a href=\"#Let's-start-testing!\" data-toc-modified-id=\"Let's-start-testing!-4\"><span class=\"toc-item-num\">4&nbsp;&nbsp;</span>Let's start testing!</a></div><div class=\"lev2 toc-item\"><a href=\"#Pass-a-dictionary-of-keywords-to-start-testing\" data-toc-modified-id=\"Pass-a-dictionary-of-keywords-to-start-testing-41\"><span class=\"toc-item-num\">4.1&nbsp;&nbsp;</span>Pass a dictionary of keywords to start testing</a></div><div class=\"lev2 toc-item\"><a href=\"#Pass-in-cookies-so-you-can-also-get-the-number-of-results.-Pass-in-sqlite_file-to-save-the-results-to-disk-so-you-can-load-it-later\" data-toc-modified-id=\"Pass-in-cookies-so-you-can-also-get-the-number-of-results.-Pass-in-sqlite_file-to-save-the-results-to-disk-so-you-can-load-it-later-42\"><span class=\"toc-item-num\">4.2&nbsp;&nbsp;</span>Pass in cookies so you can also get the number of results. Pass in sqlite_file to save the results to disk so you can load it later</a></div><div class=\"lev2 toc-item\"><a href=\"#If-your-test-gets-interrupted-or-you-add-more-keywords,-you-can-pick-up-where-you-left-off\" data-toc-modified-id=\"If-your-test-gets-interrupted-or-you-add-more-keywords,-you-can-pick-up-where-you-left-off-43\"><span class=\"toc-item-num\">4.3&nbsp;&nbsp;</span>If your test gets interrupted or you add more keywords, you can pick up where you left off</a></div><div class=\"lev2 toc-item\"><a href=\"#You-can-attach-notes-or-categorizations-to-your-keywords-for-easy-querying-and-analysis-later\" data-toc-modified-id=\"You-can-attach-notes-or-categorizations-to-your-keywords-for-easy-querying-and-analysis-later-44\"><span class=\"toc-item-num\">4.4&nbsp;&nbsp;</span>You can attach notes or categorizations to your keywords for easy querying and analysis later</a></div><div class=\"lev2 toc-item\"><a href=\"#If-you-want-to-test-multiple-times-a-day,-just-pass-in-the-test_number-param\" data-toc-modified-id=\"If-you-want-to-test-multiple-times-a-day,-just-pass-in-the-test_number-param-45\"><span class=\"toc-item-num\">4.5&nbsp;&nbsp;</span>If you want to test multiple times a day, just pass in the <code>test_number</code> param</a></div><div class=\"lev2 toc-item\"><a href=\"#It-can-skip-redundant-keywords\" data-toc-modified-id=\"It-can-skip-redundant-keywords-46\"><span class=\"toc-item-num\">4.6&nbsp;&nbsp;</span>It can skip redundant keywords</a></div><div class=\"lev2 toc-item\"><a href=\"#You-can-also-pass-in-lists-if-you-prefer-(though-you-can't-include-the-source-or-notes)\" data-toc-modified-id=\"You-can-also-pass-in-lists-if-you-prefer-(though-you-can't-include-the-source-or-notes)-47\"><span class=\"toc-item-num\">4.7&nbsp;&nbsp;</span>You can also pass in lists if you prefer (though you can't include the source or notes)</a></div><div class=\"lev2 toc-item\"><a href=\"#It-can-detect-the-canonical-(minimum)-set-of-characters-in-the-search-query-triggering-censorship\" data-toc-modified-id=\"It-can-detect-the-canonical-(minimum)-set-of-characters-in-the-search-query-triggering-censorship-48\"><span class=\"toc-item-num\">4.8&nbsp;&nbsp;</span>It can detect the canonical (minimum) set of characters in the search query triggering censorship</a></div>\n\n# Install the blockedonweibo package\n\nThe github repo for this Weibo keyword testing script is located at https://github.com/jasonqng/blocked-on-weibo.\n\nTo begin using this python package, inside your terminal, run\n\n```\npip install blockedonweibo\n```\n\nAlternatively, you can clone this repo, `cd` into the repo directory and manually install the requirements and package:\n\n```\npip install -r requirements.txt\npython setup.py install\n```\n\nTo confirm the installation works, in a python shell (you can start by running `python` from terminal), try importing the package:\n\n```\nimport blockedonweibo\n```\n\nIf you don't get any errors, things have installed successfully. If not, you may need to fiddle with your python paths and settings to ensure it's being installed to the correct location.\n\n# Adjust your settings\n\nYour python script only requires the following. All other imports are handled by the package.\n\n\n```python\nfrom blockedonweibo import weibo\nimport pandas as pd\n```\n\nYou have the option of saving your test results to a file. You'll need to pass a path to to a file which will store the results in sqlite format. It can be helpful to set this at the top of your script and pass the variable each time you run the test.\n\n\n```python\nsqlite_file = 'results.sqlite' # name of sqlite file to read from/write to\n```\n\nIf you want to erase any existing data you have in the sqlite file defined above, just pass overwrite=True to the `create_database` function. Otherwise any new results will be appended to the end of the database.\n\n\n```python\nweibo.create_database(sqlite_file, overwrite=True)\n```\n\nThis testing script is enhanced if you allow it to log into Weibo, which increases your rate limit threshold as well as returns the number of results a search says it has. This script will work without your supplying credentials, but it is highly recommended. To do so, edit the `weibo_credentials.py` with your email address and password. The file is ignored and will not be uploaded by default when you push commits to github. You can inspect the code to verify that the credentials don't go anywhere except to weibo.\n\nUsing those credentials, the script logs you in and fetches a cookie for the user session you create. This cookie can be saved to a file by passing the `write_cookie` parameter in the `user_login` function.\n\n\n```python\nsession = weibo.user_login(write_cookie=True)\n```\n\nThere is a helper function to verify that the cookie actually works\n\n\n```python\ncookie = session.cookies.get_dict()\nprint(weibo.verify_cookies_work(cookie))\n```\n\n True\n\n\nIf you have the cookie already written to disk, you don't need to perform another `user_login` and instead, you can just use the `load_cookies` function to fetch the cookie from the file. Again, you can verify that it works. Just store the cookie's contents (a dictionary) to a variable and pass that to the `run` function below if you want to test as if you were logged in. Otherwise, it will emulate a search by a logged out user.\n\n\n```python\ncookie = weibo.load_cookies()\nprint(weibo.verify_cookies_work(cookie))\n```\n\n True\n\n\n# Let's start testing!\n\n## Pass a dictionary of keywords to start testing\n\n\n```python\nsample_keywords_df = pd.DataFrame(\n [{'keyword':'hello','source':'my dataframe'},\n {'keyword':'lxb','source':'my dataframe'},\n {'keyword':u'习胞子','source':'my dataframe'}\n ])\n```\n\n\n```python\nsample_keywords_df\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>keyword</th>\n <th>source</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>hello</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>1</th>\n <td>lxb</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>2</th>\n <td>习胞子</td>\n <td>my dataframe</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nweibo.run(sample_keywords_df,insert=False,return_df=True)\n```\n\n (0, u'hello', 'has_results')\n (1, u'lxb', 'censored')\n (2, u'\\u4e60\\u80de\\u5b50', 'no_results')\n\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>date</th>\n <th>datetime</th>\n <th>is_canonical</th>\n <th>keyword</th>\n <th>num_results</th>\n <th>orig_keyword</th>\n <th>result</th>\n <th>source</th>\n <th>test_number</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>2017-09-25</td>\n <td>2017-09-25 10:12:45.280812</td>\n <td>False</td>\n <td>hello</td>\n <td>[]</td>\n <td>None</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>1</td>\n </tr>\n <tr>\n <th>0</th>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:00.191900</td>\n <td>False</td>\n <td>lxb</td>\n <td>None</td>\n <td>None</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>1</td>\n </tr>\n <tr>\n <th>0</th>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:16.356805</td>\n <td>False</td>\n <td>习胞子</td>\n <td>None</td>\n <td>None</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>1</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n## Pass in cookies so you can also get the number of results. Pass in sqlite_file to save the results to disk so you can load it later\n\n\n```python\nweibo.run(sample_keywords_df,sqlite_file=sqlite_file,cookies=cookie)\n```\n\n (0, u'hello', 'has_results')\n (1, u'lxb', 'censored')\n (2, u'\\u4e60\\u80de\\u5b50', 'no_results')\n\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n## If your test gets interrupted or you add more keywords, you can pick up where you left off\n\nLet's pretend I wanted to test four total keywords, but I was only able to complete the first three above. I'll go ahead and add one more keyword to the test list to replicate an unfinished keyword.\n\n\n```python\nsample_keywords_df.loc[len(sample_keywords_df.index)] = ['刘晓波','my dataframe']\n```\n\n\n```python\nsample_keywords_df\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>keyword</th>\n <th>source</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>hello</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>1</th>\n <td>lxb</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>2</th>\n <td>习胞子</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>3</th>\n <td>刘晓波</td>\n <td>my dataframe</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nweibo.run(sample_keywords_df,sqlite_file=sqlite_file,cookies=cookie)\n```\n\n (3, u'\\u5218\\u6653\\u6ce2', 'censored')\n\n\nNeat-o, it was smart enough to start right at that new keyword and not start all over again!\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n## You can attach notes or categorizations to your keywords for easy querying and analysis later\n\n\n```python\nnew_keywords_df = pd.DataFrame(\n [{'keyword':'pokemon','source':'my dataframe',\"notes\":\"pop culture\"},\n {'keyword':'jay chou','source':'my dataframe',\"notes\":\"pop culture\"},\n {'keyword':u'weibo','source':'my dataframe',\"notes\":\"social media\"}\n ])\nmerged_keywords_df = pd.concat([sample_keywords_df,new_keywords_df]).reset_index(drop=True)\nmerged_keywords_df\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>keyword</th>\n <th>notes</th>\n <th>source</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>hello</td>\n <td>NaN</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>1</th>\n <td>lxb</td>\n <td>NaN</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>2</th>\n <td>习胞子</td>\n <td>NaN</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>3</th>\n <td>刘晓波</td>\n <td>NaN</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>4</th>\n <td>pokemon</td>\n <td>pop culture</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>5</th>\n <td>jay chou</td>\n <td>pop culture</td>\n <td>my dataframe</td>\n </tr>\n <tr>\n <th>6</th>\n <td>weibo</td>\n <td>social media</td>\n <td>my dataframe</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nweibo.run(merged_keywords_df,sqlite_file=sqlite_file,cookies=cookie)\n```\n\n (4, u'pokemon', 'has_results')\n (5, u'jay chou', 'has_results')\n (6, u'weibo', 'has_results')\n\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:28.100418</td>\n <td>1</td>\n <td>weibo</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>63401495.0</td>\n <td>social media</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nresults = weibo.sqlite_to_df(sqlite_file)\nresults.query(\"notes=='pop culture'\")\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nresults.query(\"notes=='pop culture'\").num_results.mean()\n```\n\n\n\n\n 2853070.5\n\n\n\n## If you want to test multiple times a day, just pass in the `test_number` param\n\nYou can off `verbose` output in case you don't need to troubleshoot anything...\n\n\n```python\nweibo.run(sample_keywords_df,sqlite_file=sqlite_file,cookies=cookie,verbose='none',test_number=2)\n```\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:28.100418</td>\n <td>1</td>\n <td>weibo</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>63401495.0</td>\n <td>social media</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:46.214464</td>\n <td>2</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454634.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:03.274804</td>\n <td>2</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:19.035805</td>\n <td>2</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>10</th>\n <td>10</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:36.021837</td>\n <td>2</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n## It can skip redundant keywords\n\n\n```python\nmore_keywords_df = pd.DataFrame(\n [{'keyword':'zhongnanhai','source':'my dataframe2',\"notes\":\"location\"},\n {'keyword':'cats','source':'my dataframe2',\"notes\":\"pop culture\"},\n {'keyword':'zhongnanhai','source':'my dataframe2',\"notes\":\"location\"}\n ])\n```\n\n\n```python\nmore_keywords_df\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>keyword</th>\n <th>notes</th>\n <th>source</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>zhongnanhai</td>\n <td>location</td>\n <td>my dataframe2</td>\n </tr>\n <tr>\n <th>1</th>\n <td>cats</td>\n <td>pop culture</td>\n <td>my dataframe2</td>\n </tr>\n <tr>\n <th>2</th>\n <td>zhongnanhai</td>\n <td>location</td>\n <td>my dataframe2</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n\n\n```python\nweibo.run(more_keywords_df,sqlite_file=sqlite_file,cookies=cookie)\n```\n\n (0, u'zhongnanhai', 'has_results')\n (1, u'cats', 'has_results')\n\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:28.100418</td>\n <td>1</td>\n <td>weibo</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>63401495.0</td>\n <td>social media</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:46.214464</td>\n <td>2</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454634.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:03.274804</td>\n <td>2</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:19.035805</td>\n <td>2</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>10</th>\n <td>10</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:36.021837</td>\n <td>2</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>11</th>\n <td>11</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:53.766351</td>\n <td>1</td>\n <td>zhongnanhai</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>109.0</td>\n <td>location</td>\n </tr>\n <tr>\n <th>12</th>\n <td>12</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:14.124440</td>\n <td>1</td>\n <td>cats</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>648313.0</td>\n <td>pop culture</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n## You can also pass in lists if you prefer (though you can't include the source or notes)\n\n\n```python\nsample_keywords_list = [\"cats\",'yes','自由亚洲电台','刘晓波','dhfjkdashfjkasdhf']\n```\n\n**See below how it handles connection reset errors (it waits a little extra to make sure your connection clears before continuing testing)**\n\n\n```python\nweibo.run(sample_keywords_list,sqlite_file=sqlite_file,cookies=cookie)\n```\n\n (0, u'cats', 'has_results')\n (1, u'yes', 'has_results')\n 自由亚洲电台 caused connection reset, waiting 95\n (2, u'\\u81ea\\u7531\\u4e9a\\u6d32\\u7535\\u53f0', 'reset')\n (3, u'\\u5218\\u6653\\u6ce2', 'censored')\n (4, u'dhfjkdashfjkasdsf87', 'no_results')\n\n\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:28.100418</td>\n <td>1</td>\n <td>weibo</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>63401495.0</td>\n <td>social media</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:46.214464</td>\n <td>2</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454634.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:03.274804</td>\n <td>2</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:19.035805</td>\n <td>2</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>10</th>\n <td>10</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:36.021837</td>\n <td>2</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>11</th>\n <td>11</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:53.766351</td>\n <td>1</td>\n <td>zhongnanhai</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>109.0</td>\n <td>location</td>\n </tr>\n <tr>\n <th>12</th>\n <td>12</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:14.124440</td>\n <td>1</td>\n <td>cats</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>648313.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>13</th>\n <td>13</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:36.205255</td>\n <td>1</td>\n <td>cats</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>list</td>\n <td>None</td>\n <td>648313.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>14</th>\n <td>14</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:54.330039</td>\n <td>1</td>\n <td>yes</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>list</td>\n <td>None</td>\n <td>28413048.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>15</th>\n <td>15</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:19:47.007930</td>\n <td>1</td>\n <td>自由亚洲电台</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>reset</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>16</th>\n <td>16</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:20:03.491231</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>17</th>\n <td>17</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:20:18.747414</td>\n <td>1</td>\n <td>dhfjkdashfjkasdsf87</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n\n## It can detect the canonical (minimum) set of characters in the search query triggering censorship\n\nSet `get_canonical=True` when running to find which part of a censored search query is actually triggering the censorship. Note: this will only work on explicitly censored search queries.\n\nFinding canonical censored keywords can take a large number of search cycles, especially with larger original queries. \n\n```python\nweibo.run(['江蛤','江泽民江蛤蟆'],sqlite_file=sqlite_file,cookies=cookie,continue_interruptions=False,get_canonical=True)\n```\n\nIf we find a minimum keyword component, we'll record it as a keyword, set column `is_canonical` to True, and record our full search query in `orig_keyword`. For completeness, we'll also include the original keyword as its own entry with `is_canonical=False`\n\n```python\nweibo.sqlite_to_df(sqlite_file)\n```\n\n\n<div>\n<table border=\"1\" class=\"dataframe\">\n <thead>\n <tr style=\"text-align: right;\">\n <th></th>\n <th>id</th>\n <th>date</th>\n <th>datetime_logged</th>\n <th>test_number</th>\n <th>keyword</th>\n <th>censored</th>\n <th>no_results</th>\n <th>reset</th>\n <th>is_canonical</th>\n <th>result</th>\n <th>source</th>\n <th>orig_keyword</th>\n <th>num_results</th>\n <th>notes</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <th>0</th>\n <td>0</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:37.816720</td>\n <td>1</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454701.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>1</th>\n <td>1</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:13:54.356722</td>\n <td>1</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>2</th>\n <td>2</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:11.489530</td>\n <td>1</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>3</th>\n <td>3</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:29.667395</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>4</th>\n <td>4</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:14:49.107078</td>\n <td>1</td>\n <td>pokemon</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>5705260.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>5</th>\n <td>5</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:09.762484</td>\n <td>1</td>\n <td>jay chou</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>881.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>6</th>\n <td>6</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:28.100418</td>\n <td>1</td>\n <td>weibo</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>63401495.0</td>\n <td>social media</td>\n </tr>\n <tr>\n <th>7</th>\n <td>7</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:15:46.214464</td>\n <td>2</td>\n <td>hello</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>80454634.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>8</th>\n <td>8</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:03.274804</td>\n <td>2</td>\n <td>lxb</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>9</th>\n <td>9</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:19.035805</td>\n <td>2</td>\n <td>习胞子</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>10</th>\n <td>10</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:36.021837</td>\n <td>2</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>my dataframe</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>11</th>\n <td>11</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:16:53.766351</td>\n <td>1</td>\n <td>zhongnanhai</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>109.0</td>\n <td>location</td>\n </tr>\n <tr>\n <th>12</th>\n <td>12</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:14.124440</td>\n <td>1</td>\n <td>cats</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>my dataframe2</td>\n <td>None</td>\n <td>648313.0</td>\n <td>pop culture</td>\n </tr>\n <tr>\n <th>13</th>\n <td>13</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:36.205255</td>\n <td>1</td>\n <td>cats</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>list</td>\n <td>None</td>\n <td>648313.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>14</th>\n <td>14</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:17:54.330039</td>\n <td>1</td>\n <td>yes</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>has_results</td>\n <td>list</td>\n <td>None</td>\n <td>28413048.0</td>\n <td>None</td>\n </tr>\n <tr>\n <th>15</th>\n <td>15</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:19:47.007930</td>\n <td>1</td>\n <td>自由亚洲电台</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>reset</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>16</th>\n <td>16</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:20:03.491231</td>\n <td>1</td>\n <td>刘晓波</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>17</th>\n <td>17</td>\n <td>2017-09-25</td>\n <td>2017-09-25 10:20:18.747414</td>\n <td>1</td>\n <td>dhfjkdashfjkasdsf87</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>no_results</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>18</th>\n <td>18</td>\n <td>2017-11-15</td>\n <td>2017-11-15 12:38:32.931313</td>\n <td>1</td>\n <td>江蛤</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>1</td>\n <td>censored</td>\n <td>list</td>\n <td>江蛤</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>19</th>\n <td>19</td>\n <td>2017-11-15</td>\n <td>2017-11-15 12:38:32.963135</td>\n <td>1</td>\n <td>江蛤</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>20</th>\n <td>20</td>\n <td>2017-11-15</td>\n <td>2017-11-15 12:40:21.294841</td>\n <td>1</td>\n <td>江蛤</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>1</td>\n <td>censored</td>\n <td>list</td>\n <td>江泽民江蛤蟆</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n <tr>\n <th>21</th>\n <td>21</td>\n <td>2017-11-15</td>\n <td>2017-11-15 12:40:21.326378</td>\n <td>1</td>\n <td>江泽民江蛤蟆</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>0</td>\n <td>censored</td>\n <td>list</td>\n <td>None</td>\n <td>NaN</td>\n <td>None</td>\n </tr>\n </tbody>\n</table>\n</div>\n\n \n" }, { "alpha_fraction": 0.6037599444389343, "alphanum_fraction": 0.6088213920593262, "avg_line_length": 39.10144805908203, "blob_id": "2418231d5e29f78ec21bffba7bdc461b21f652fd", "content_id": "ecfe6322ff0def9a7bcecc48feff51a2fbae643f", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2766, "license_type": "permissive", "max_line_length": 122, "num_lines": 69, "path": "/update_db.py", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "import sqlite3\nimport os, sys\n\n\ndef find_db():\n \"\"\"\n Search for database files in the current directory of this script file. Gets user input for confirmation of db file\n if only 1 match; user input for selection if >1 db file present.\n \"\"\"\n\n print(\"Finding database files...\")\n files = list(os.walk('.'))[0][2]\n db_files = [file for file in files if \".db\" in file or \".sqlite\" in file]\n if len(db_files)>0:\n if len(db_files) == 1:\n user_input = raw_input(\"Is database file %s/%s? (y/N) \" %(os.getcwd(), db_files[0]))\n if user_input.lower() == 'y':\n migrate_db(db_files[0])\n else:\n break_script()\n else:\n print(\"%d database files found in dir\" %(len(db_files)))\n for i in range(len(db_files)):\n print(\"%d. %s\" %(i+1, db_files[i]))\n print(\"**************\")\n user_input = raw_input(\"Which db file to upgrade? (Enter NUMBER) \")\n if user_input.isdigit() and 0 < int(user_input) < len(db_files):\n migrate_db(db_files[int(user_input) - 1])\n else:\n print(\"Invalid input.\")\n break_script()\n else:\n break_script()\n\n\ndef migrate_db(db_location):\n \"\"\"\n sqlite3 code that conducts the actual database modifications. Renames the previous table, creates a new table\n with new columns, moves contents of previous table over, then deletes the previous table.\n :param db_location: filename of database file.\n \"\"\"\n conn = sqlite3.connect(db_location)\n c = conn.cursor()\n c.execute('ALTER TABLE results RENAME TO resultsOld')\n c.execute('''CREATE TABLE results (id INT, date DATE, datetime_logged DATETIME, test_number INT, keyword string, \n censored bool, no_results bool, reset bool, is_canonical bool, result string, source string, orig_keyword string, \n num_results INT, notes string, PRIMARY KEY(date,source,test_number,keyword,orig_keyword))''')\n c.execute('''INSERT INTO results (id, date, datetime_logged, test_number, keyword, censored, no_results, reset,\n result, source, num_results, notes)\n SELECT id, date, datetime_logged, test_number, keyword, censored, no_results, reset, result, source,\n num_results, notes FROM resultsOld\n ''')\n c.execute('DROP TABLE resultsOld')\n conn.commit()\n conn.close()\n print(\"Updates completed successfully\")\n sys.exit()\n\n\ndef break_script():\n \"\"\"\n Print an error message to console before triggering sys.exit().\n \"\"\"\n print(\"Please place this .py script in the same directory as your database file, then re-run. No changes were made\")\n sys.exit()\n\n\nif __name__ == \"__main__\":\n find_db()" }, { "alpha_fraction": 0.6517150402069092, "alphanum_fraction": 0.6569920778274536, "avg_line_length": 33.45454406738281, "blob_id": "191344d189d160fd1356d8beeb8c3e9d276561e6", "content_id": "11acae76c58eb9f4ce733b18035ef783d00460df", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 379, "license_type": "permissive", "max_line_length": 74, "num_lines": 11, "path": "/setup.py", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "from setuptools import setup, find_packages\n\nsetup(name='blockedonweibo',\n version='0.2',\n description='Testing if search keywords are censored on Sina Weibo',\n url='http://github.com/jasonqng/blocked-on-weibo',\n author='Jason Q. Ng',\n author_email='[email protected]',\n license='BSD License',\n packages=find_packages(exclude=['docs']),\n zip_safe=False)\n" }, { "alpha_fraction": 0.5565217137336731, "alphanum_fraction": 0.5565217137336731, "avg_line_length": 28, "blob_id": "b71817df477d628a1f890e95e4de6baaa2a155e0", "content_id": "17db01e6a064484fe84f2e5822bc2b6a6f6227da", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 115, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/blockedonweibo/weibo_credentials.py", "repo_name": "jasonqng/blocked-on-weibo", "src_encoding": "UTF-8", "text": "class Creds(object):\n def __init__(self):\n self.username = '[email protected]'\n self.password = 'weibo_password'" } ]
6
SPARR0W1/SaLo
https://github.com/SPARR0W1/SaLo
cdf77e3e8c5e14bdbade411aaebc60c678919654
a5fb938c6224e8af816a4d1f0a1fc597ecfa80aa
eaebd0704f117c07b8f5ac2b1c10c36508a723a9
refs/heads/main
2023-03-28T02:59:18.617809
2021-04-03T09:00:22
2021-04-03T09:00:22
354,243,074
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6714285612106323, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 20.77777862548828, "blob_id": "e63866c2b78a82e49df44744bd72e23a61f694a2", "content_id": "f43616d482ef1b4e1f5adb7475d1d63ab6edcaaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 210, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/SaLo.py", "repo_name": "SPARR0W1/SaLo", "src_encoding": "UTF-8", "text": "#Import to Module\r\nimport pickle\r\n\r\n#Function\r\ndef save(object, namefile=\"dump.p\"):\r\n\tpickle.dump(object, open(namefile, \"wb\"))\r\n\r\ndef load(object, namefile):\r\n\tobject = pickle.load(open(namefile, \"rb\"))\r\n\r\n\r\n\t" }, { "alpha_fraction": 0.763012170791626, "alphanum_fraction": 0.763012170791626, "avg_line_length": 27.15625, "blob_id": "7e9fd55a45218ad512639b8dc31615a4dca25c9f", "content_id": "9bfb1a1b28b6ce31f2e02549800f680ea1e9a0b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 903, "license_type": "no_license", "max_line_length": 102, "num_lines": 32, "path": "/README.md", "repo_name": "SPARR0W1/SaLo", "src_encoding": "UTF-8", "text": "# SaLo\nI will try to simplify your life as a programmer.\nAnd I'll show you this library.\n\nIt is used to store variables, lists, tuples, dictionaries and other typical data in Python.\n\nThe library is made on the basis of the Pickle module.\n\nAnd be in beta mode.\n\n\nHow to use:\n\nFirst, transfer the downloaded SaLo.py file to the project folder. It is very important.\nThen import the functions with the given code:\nfrom SaLo import *\n\nThe end\n\nFunction:\n\nFunction - Save allows you to save the object\nIt looks like save (object, namefile). \nWhere object is the object itself, and namefile is the name of the document in which it will be saved.\n\nImportant: the name of the file must be with the extension .p\n\nFunction - Load allows you to load an object\nfrom file\n\nIt looks like load (object, namefile). \nWhere object is the object itself, and namefile is the name of the document in which it is located.\n\n\n" } ]
2
smithCoderLeo/MachineLearning
https://github.com/smithCoderLeo/MachineLearning
92af2ee518823ec2be80329040be32eb06672651
9dc5eaae19b84c3db5f1b359f4f56a6004c99ee3
222b56e008e8bf7ffb8c6d34f495e6837f3ae833
refs/heads/master
2020-05-07T21:31:40.885159
2019-11-13T01:59:00
2019-11-13T01:59:00
180,908,102
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8709677457809448, "alphanum_fraction": 0.8709677457809448, "avg_line_length": 14.5, "blob_id": "d33256a8643adb5df13d9e02f5fc30dd99a64af1", "content_id": "6fde82cc8796e7a92aba7009d61d4176cb94a0b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "no_license", "max_line_length": 17, "num_lines": 2, "path": "/README.md", "repo_name": "smithCoderLeo/MachineLearning", "src_encoding": "UTF-8", "text": "# MachineLearning\n机器学习中的常用函数代码\n" }, { "alpha_fraction": 0.6227678656578064, "alphanum_fraction": 0.6294642686843872, "avg_line_length": 36.33333206176758, "blob_id": "0693e891b0d1d9d168265a2b4df970826df6438d", "content_id": "94982e24f1fa711c323a540bf9edbc52b2f6ccea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 484, "license_type": "no_license", "max_line_length": 54, "num_lines": 12, "path": "/UtilFunction.py", "repo_name": "smithCoderLeo/MachineLearning", "src_encoding": "UTF-8", "text": "#data原始数据转为csv\ndef data2Csv(filename):\n handled_file = 'kdd99_handled.csv'\n data_to_file = open(handled_file, 'w', newline='')\n with open(filename, 'r') as fr: #读入的file为原始data文件\n csv_reader = csv.reader(fr)\n csv_writer = csv.writer(data_to_file)\n for each_line in csv_reader:\n temp_line = np.array(each_line) #转换类型\n csv_writer.writerow(temp_line)\n data_to_file.close()\n return handled_file\n" }, { "alpha_fraction": 0.649452269077301, "alphanum_fraction": 0.6674491167068481, "avg_line_length": 78.875, "blob_id": "24425468e7f665d9ae6c73e63fc14ab5b4a1bfd3", "content_id": "bbe42794730d913756f0f3b0d2aaf48451bd36d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1304, "license_type": "no_license", "max_line_length": 628, "num_lines": 16, "path": "/OneHotEncoder.py", "repo_name": "smithCoderLeo/MachineLearning", "src_encoding": "UTF-8", "text": "def oneHotEncoder_process():\n service_list=['aol','auth','bgp','courier','csnet_ns','ctf','daytime','discard','domain','domain_u','echo','eco_i','ecr_i','efs','exec','finger','ftp','ftp_data','gopher','harvest','hostnames','http','http_2784','http_443','http_8001','imap4','IRC','iso_tsap','klogin','kshell','ldap','link','login','mtp','name','netbios_dgm','netbios_ns','netbios_ssn','netstat','nnsp','nntp','ntp_u','other','pm_dump','pop_2','pop_3','printer','private','red_i','remote_job','rje','shell','smtp','sql_net','ssh','sunrpc','supdup','systat','telnet','tftp_u','tim_i','time','urh_i','urp_i','uucp','uucp_path','vmnet','whois','X11','Z39_50']\n values = np.array(service_list)\n label_encoder = LabelEncoder()\n integer_encoded = label_encoder.fit_transform(values)\n #source_file = 'corrected_handled2.csv'\n #handled_file_onehot = 'corrected_handled_onehot.csv'\n # binary encode\n onehot_encoder = OneHotEncoder(sparse=False)\n integer_encoded = integer_encoded.reshape(len(integer_encoded), 1) #调整为单列\n onehot_encoded = onehot_encoder.fit_transform(integer_encoded)\n print(onehot_encoded)\n return \n #invert first example 反编译第一个样例\n inverted = label_encoder.inverse_transform([np.argmax(onehot_encoded[0, :])])\n print(inverted)\n" } ]
3
grimmweeper/50.012-networks-OT
https://github.com/grimmweeper/50.012-networks-OT
bddc116e36bfccc596c20e90dfef6b8f3d7160c8
d9ff44cfd83e2b67fd8935f59ff1d0051e18c08d
5a4ee64aefbd917a46b5083635254fb5793e8ba8
refs/heads/main
2023-01-29T11:45:29.546852
2020-11-29T19:13:35
2020-11-29T19:13:35
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5560632944107056, "alphanum_fraction": 0.5775043964385986, "avg_line_length": 28.03061294555664, "blob_id": "beaf3d6bed0718696aa94de9b02feeb2f0fdfd83", "content_id": "7f9dc303f7a342da095a3d7152e351272202c91f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2845, "license_type": "no_license", "max_line_length": 85, "num_lines": 98, "path": "/convergence-test/multiclient.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "# import the socket module\nimport socket\n\n# Create a socket instance\nsocketObject = socket.socket()\nhost = '127.0.0.1'\nport = 2004\n\nclientNumber = int(input(\"Input the number of clients to spawn: \"))\n\nfor i in range(clientNumber):\n\n socketObject = socket.socket()\n host = '127.0.0.1'\n port = 2004\n print(\"Waiting for connection response\")\n\n try:\n socketObject.connect((host, port))\n print(\"Client {} connected to server.\".format(i+1))\n\n except socket.error as e:\n print(str(e))\n\n res = socketObject.recv(1024)\n # Writing something\n if(i == 0):\n message = \"Test message from Client {} \\n\".format(i+1)\n f = open(\"sharedfile.txt\", \"w\")\n f.write(message)\n f.close()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n #Adding on to client 1\n elif(i == 1):\n message = \"Test message from other client {} \\n\".format(i+1)\n f = open(\"sharedfile.txt\", \"a\")\n f.write(message)\n f.close()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n #Delete\n elif(i == 2):\n message = \"Client 3: I've deleted edits made by client 2 \\n\"\n open_file = open(\"sharedfile.txt\", \"r\")\n lines = open_file.readlines()\n open_file.close()\n del lines[1]\n f = open(\"sharedfile.txt\", \"w+\")\n for line in lines:\n f.write(line)\n f.write(message)\n f.close()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n #Insert \n elif(i == 3):\n open_file = open(\"sharedfile.txt\", \"r\")\n lines = open_file.readlines()\n open_file.close()\n message = \"Client 4 has inserted this message between the first two lines \\n\"\n lines.insert(1,message)\n f = open(\"sharedfile.txt\",\"w+\")\n for line in lines:\n f.write(line)\n f.close()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n #Move\n else: \n open_file = open(\"sharedfile.txt\",\"r\")\n lines = open_file.readlines()\n open_file.close()\n first_line = lines[0]\n lines.pop(0)\n lines.append(first_line)\n f = open(\"sharedfile.txt\",\"w+\")\n for line in lines:\n f.write(line)\n message = \"Client 5 has moved the edit made by client 1 \\n\"\n f.write(message)\n f.close()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n\n\n\nsocketObject.close()\n" }, { "alpha_fraction": 0.7173523902893066, "alphanum_fraction": 0.7450805306434631, "avg_line_length": 20.480770111083984, "blob_id": "ebc9fb8f7b8b754092c2ecf77a980416e52966df", "content_id": "21a50f79323728ece5480fb1a3cf5d24473a562b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 81, "num_lines": 52, "path": "/README.md", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "# 50.012 Networks - Group 2 Operational Transformation\n\n### Experiments involving client-server implementations with Quill-Delta Object\n\n### To start:\n```git clone https://github.com/GrimmWeeper/50.012-networks-OT.git```\n\n### Time analysis experiment\n\n```\n1) cd time-experiment\n2) Open 2 terminals\n3) python server.py\n4) python multiclient.py\n```\n\n### Concurrency experiment\n\n```\n1) cd concurrency-test\n2) Open 2 terminals\n3) python server.py\n4) python client.py\n5) Type in inputs from both terminals\n```\n\n### Convergence experiment\n\n```\n1) cd convergence-test\n2) Open >=2 terminals\n3) python server.py\n4) python client.py\n5) Type in inputs from terminals\n6) Abruptly close the server terminal\n7) Type in input from client terminal\n8) Reconnects back the server terminal\n```\n\n### Authors\n[GrimmWeeper](https://github.com/GrimmWeeper)\n\n[alicezhangjy](https://github.com/alicezhangjy)\n\n[xmliszt](https://github.com/xmliszt)\n\n[jesterlyn](https://github.com/jesterlyn)\n\n[cinnamon-rolling](https://github.com/cinnamon-rolling)\n\n### Credits\n[forgeworks/quill-delta-python](https://github.com/forgeworks/quill-delta-python)\n\n" }, { "alpha_fraction": 0.6343545913696289, "alphanum_fraction": 0.643897533416748, "avg_line_length": 23, "blob_id": "99a48dd135c29d1dd321980b8d182c6cf21eb94a", "content_id": "e2653794a52c1da08f7e0e6e015cdb5edfb9f8a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1991, "license_type": "no_license", "max_line_length": 88, "num_lines": 83, "path": "/concurrency-test/client.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "#import the socket module\nimport socket\n\nimport sys\nsys.path.append('../')\nfrom delta import Delta\n\nimport utils\n\n#Create a socket instance\nsocketObject = socket.socket()\nhost = '127.0.0.1'\nport = 2005\n\nprint(\"Waiting for connection response\")\n#Using the socket connect to a server...in this case localhost\n\ntry:\n socketObject.connect((host, port))\n print(\"Connected to localhost\")\n\nexcept socket.error as e:\n print(str(e))\n\nres = socketObject.recv(1024)\n\ndelta_object = Delta().insert('ABCD')\n\n# Receive the data\nwhile(True):\n\n operation = ''\n retain = ''\n\n retain = input(\"Input position value to retain: \")\n operation = input(\"Input Operation (insert/delete): \")\n value = input(\"Input value for operation (insert: text | delete: position value): \")\n\n\n if retain == '':\n if operation == 'insert':\n client_delta = Delta().insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().delete(int(value))\n \n else:\n if operation == 'insert':\n client_delta = Delta().retain(int(retain)).insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().retain(int(retain)).delete(int(value)) \n\n \n\n print(\"\\n\")\n print(\"[Initial State]:\", delta_object)\n print(\"[Client Operation]:\", client_delta)\n\n client_local = delta_object.compose(client_delta)\n\n print(\"[State after Client Operation]:\", client_local)\n print(\"\\n\")\n \n messageBytes = str.encode(str(client_delta))\n socketObject.sendall(messageBytes)\n\n data = socketObject.recv(1024).decode('utf-8')\n\n server_delta = utils.string_to_delta(data)\n\n print(\"[Server Operation]:\", server_delta)\n\n server_transform = client_delta.transform(server_delta)\n print(\"[Transformed Server Operation]:\", server_transform)\n print(\"\\n\")\n\n client_result = client_local.compose(server_transform)\n print(\"[Eventual State in Client]:\", client_result)\n\n\n\nsocketObject.close()" }, { "alpha_fraction": 0.5996860265731812, "alphanum_fraction": 0.6169544458389282, "avg_line_length": 25.58333396911621, "blob_id": "9a8d3be4b5433652c88f508afcc3a9368e7886c2", "content_id": "22a70827984d1dd57b1654e8eaeda8c9141ab7aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 67, "num_lines": 24, "path": "/time-experiment/counter.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import random\n\ndef gen_operation():\n value = str(random.randint(1,10))\n operation = random.choice([\"plus\",\"minus\",\"multiply\",\"divide\"])\n\n return operation + ',' + value\n\ndef compute(current, operation):\n operation_list = operation.split(',')\n\n if operation_list[0] == 'plus':\n result = current + int(operation_list[1])\n \n elif operation_list[0] == 'minus':\n result = current - int(operation_list[1])\n\n elif operation_list[0] == 'multiply':\n result = current * int(operation_list[1])\n\n elif operation_list[0] == 'divide':\n result = current / int(operation_list[1])\n\n return result" }, { "alpha_fraction": 0.6083385944366455, "alphanum_fraction": 0.6279216408729553, "avg_line_length": 21.614286422729492, "blob_id": "6047a5bf7c831c80ab5dce0d81dc6eb26796cd83", "content_id": "85127d520291e5793e7727943c5d3709b626b562", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "no_license", "max_line_length": 77, "num_lines": 70, "path": "/time-experiment/multiclient.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "# import the socket module\nimport socket\n\nimport counter\nimport time\nimport matplotlib.pyplot as plt\nimport csv\n\ntime_list = []\nidx_list = []\n\n\n\nfor i in range(30):\n start = time.time()\n time.sleep(0.2)\n \n for j in range(i+1):\n\n socketObject = socket.socket()\n host = '127.0.0.1'\n port = 2004\n print(\"Waiting for connection response\")\n\n try:\n socketObject.connect((host, port))\n print(\"Client {} connected to server.\".format(i+1))\n\n except socket.error as e:\n print(str(e))\n\n res = socketObject.recv(1024)\n\n message = counter.gen_operation()\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n data = socketObject.recv(1024)\n print(data)\n\n end = time.time() - start\n time_list.append(end)\n idx_list.append(i+1)\n\nprint(time_list)\n\n\n# Plot graph\nfig = plt.figure()\nax = fig.add_subplot(1, 1, 1)\nax.plot(idx_list, time_list, 'go-', alpha=0.5)\nax.set_title(\n \"Time Taken to Reach Eventual Consistency (ms) against Number of Clients\"\n)\nax.set_xlabel(\"Number of clients\")\nax.set_ylabel(\"Time Taken to reach eventual consistency (ms)\")\nplt.savefig('client_server.png', format='png')\n\n\n# Save values as csv file\nwith open('client_server.csv', 'w', encoding='utf-8', newline='') as fh:\n writer = csv.writer(fh)\n writer.writerow([\n \"Number of Clients\", \"Time Taken to Reach Eventual Consistency (ms)\"\n ])\n for _each in list(zip(idx_list, time_list)):\n writer.writerow(list(_each))\n\n\n\nsocketObject.close()\n" }, { "alpha_fraction": 0.5652173757553101, "alphanum_fraction": 0.6304348111152649, "avg_line_length": 14.666666984558105, "blob_id": "1e5f312df52ac6b3b4d0d962f7cf850bc9acc024", "content_id": "c347aecb363a477938743ce487a68abe14c8bcfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 46, "license_type": "no_license", "max_line_length": 23, "num_lines": 3, "path": "/delta/__init__.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "from .base import Delta\n\n__version__ = '1.0.1'" }, { "alpha_fraction": 0.5320637226104736, "alphanum_fraction": 0.557326078414917, "avg_line_length": 26.32978630065918, "blob_id": "037864af0d65bb2e1c27de1a1563e2deca66b77e", "content_id": "f4e50a3605660714b8a59553a7fb73e28f42d7bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2573, "license_type": "no_license", "max_line_length": 110, "num_lines": 94, "path": "/single/single.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('../')\nfrom delta import Delta\n\ndef string_to_delta(text):\n temp_text = text[7:]\n delta_text = temp_text[:-2]\n delta_list = delta_text.split(',')\n\n if len(delta_list) == 1:\n ops = delta_list[0][2:8]\n \n if ops == 'insert':\n value = delta_list[0][12:-2]\n print(value)\n return Delta().insert(value)\n \n elif ops == 'delete':\n value = int(delta_list[0][11:-1])\n return Delta().delete(value)\n\n elif len(delta_list) == 2:\n for i in range(2):\n if i == 0:\n ops_1 = delta_list[0][2:8]\n value_1 = int(delta_list[0][11:12])\n\n elif i == 1:\n ops_2 = delta_list[1][3:9]\n\n if ops_2 == 'insert':\n value_2 = delta_list[1][13:-2]\n return Delta().retain(value_1).insert(value_2)\n \n elif ops_2 == 'delete':\n value_2 = int(delta_list[1][12:-1])\n return Delta().retain(value_1).delete(value_2)\n\n return Delta()\n\n\n# Test on string_to_delta\ndef string_to_delta_test():\n a = Delta().insert('ABCDE')\n b = Delta().retain(3).delete(4)\n c = Delta().delete(4)\n\n print(a)\n print(string_to_delta(str(a)))\n print(b)\n print(string_to_delta(str(b)))\n print(c)\n print(string_to_delta(str(c)))\n\n# Operation test: Sequential insert/delete\ndef seq_OT():\n a = Delta().insert('ABCDE')\n print('a')\n print(a)\n b = Delta().retain(3).insert('Z')\n c = Delta().delete(4)\n\n result_1 = a.compose(b)\n result_2 = result_1.compose(c)\n print(\"result 1:\")\n print(result_1)\n print(\"result 2:\")\n print(result_2)\n\n\n# Transformation test: Concurrency\ndef concurrency_OT():\n\n initial = Delta().insert('ABCD')\n client_operation = Delta().retain(3).insert(\"X\") # ABCXD -> ACXD\n server_operation = Delta().retain(1).delete(1) # ACD -> ACDX, ACXD\n\n # Client\n client_local = initial.compose(client_operation)\n client_transform = client_operation.transform(server_operation)\n client_result = client_local.compose(client_transform)\n\n # Server\n server_local = initial.compose(server_operation)\n server_transform = server_operation.transform(client_operation) # Change from retaining 3rd pos to 2nd pos\n server_result = server_local.compose(server_transform)\n\n print(client_result) #ACXD\n print(server_result) #ACXD\n\nif __name__ == \"__main__\":\n string_to_delta_test()\n # seq_OT()\n # concurrency_OT()\n " }, { "alpha_fraction": 0.595162570476532, "alphanum_fraction": 0.6030927896499634, "avg_line_length": 25.840425491333008, "blob_id": "0ea5b64130075db812ca574636adf2c542640c1b", "content_id": "66899f0d45cc572b754bc49aa81ae5c1804b72f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2522, "license_type": "no_license", "max_line_length": 92, "num_lines": 94, "path": "/concurrency-test/server.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import socket\nimport os\nfrom _thread import *\n\nimport sys\nsys.path.append('../')\nfrom delta import Delta\n\nimport utils\n\nServerSideSocket = socket.socket()\nhost = '127.0.0.1'\nport = 2005\nThreadCount = 0\nclients= set()\n\ndelta_object = Delta().insert('ABCD')\n\ntry:\n ServerSideSocket.bind((host, port))\nexcept socket.error as e:\n print(str(e))\n\nprint('Socket is listening..')\nServerSideSocket.listen(5)\n\n\ndef multi_threaded_client(connection):\n global delta_object\n connection.send(str.encode('Server is working:'))\n while True:\n operation = ''\n retain = ''\n\n retain = input(\"Input position value to retain: \")\n operation = input(\"Input Operation (insert/delete): \")\n value = input(\"Input value for operation (insert: text | delete: position value): \")\n\n\n if retain == '':\n if operation == 'insert':\n server_delta = Delta().insert(value)\n \n elif operation == 'delete':\n server_delta = Delta().delete(int(value))\n \n else:\n if operation == 'insert':\n server_delta = Delta().retain(int(retain)).insert(value)\n \n elif operation == 'delete':\n server_delta = Delta().retain(int(retain)).delete(int(value)) \n\n\n print(\"\\n\")\n print(\"[Initial State]:\", delta_object)\n print(\"[Server Operation]:\", server_delta)\n\n server_local = delta_object.compose(server_delta)\n\n print(\"[State after Server Operation]:\", server_local)\n print(\"\\n\")\n \n data = connection.recv(2048)\n client_message = data.decode('utf-8')\n print(client_message)\n\n client_delta = utils.string_to_delta(client_message)\n\n print(\"[Client Operation]:\", client_delta)\n\n client_transform = server_delta.transform(client_delta)\n print(\"[Transformed Client Operation]:\", client_transform)\n\n server_result = server_local.compose(client_transform)\n print(\"\\n\")\n print(\"[Eventual State in Server]:\", server_result)\n\n response = str(server_delta)\n if not data:\n break\n connection.sendall(str.encode(response))\n connection.close()\n\nwhile True:\n\n Client, address = ServerSideSocket.accept()\n clients.add(Client)\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(multi_threaded_client, (Client, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\n\nServerSideSocket.close()" }, { "alpha_fraction": 0.40913161635398865, "alphanum_fraction": 0.452103853225708, "avg_line_length": 27.66666603088379, "blob_id": "052de38d8ccc721b4c31a44146f226a4946e4a60", "content_id": "b55b587c065b5caf14ac2687a856d3b1c4bfbc1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1117, "license_type": "no_license", "max_line_length": 66, "num_lines": 39, "path": "/convergence-test/utils.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import sys\nsys.path.append('../')\nfrom delta import Delta\n\ndef string_to_delta(text):\n temp_text = text[7:]\n delta_text = temp_text[:-2]\n delta_list = delta_text.split(',')\n\n if len(delta_list) == 1:\n ops = delta_list[0][2:8]\n \n if ops == 'insert':\n value = delta_list[0][12:-2]\n print(value)\n return Delta().insert(value)\n \n elif ops == 'delete':\n value = int(delta_list[0][11:-1])\n return Delta().delete(value)\n\n elif len(delta_list) == 2:\n for i in range(2):\n if i == 0:\n ops_1 = delta_list[0][2:8]\n value_1 = int(delta_list[0][11:12])\n\n elif i == 1:\n ops_2 = delta_list[1][3:9]\n\n if ops_2 == 'insert':\n value_2 = delta_list[1][13:-2]\n return Delta().retain(value_1).insert(value_2)\n \n elif ops_2 == 'delete':\n value_2 = int(delta_list[1][12:-1])\n return Delta().retain(value_1).delete(value_2)\n\n return Delta()" }, { "alpha_fraction": 0.5998507142066956, "alphanum_fraction": 0.609929084777832, "avg_line_length": 25.01941680908203, "blob_id": "4760c6b0c44c466269d9423d69dd5f5f1609d4cd", "content_id": "5b64fe8021bfbce7ea0237509fbcd2fc85533a19", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2679, "license_type": "no_license", "max_line_length": 88, "num_lines": 103, "path": "/convergence-test/client.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "#import the socket module\nimport socket\nimport random\n\nimport sys\nsys.path.append('../')\nfrom delta import Delta\n\n#Create a socket instance\nsocketObject = socket.socket()\nhost = '127.0.0.1'\nport = 2006\n\nprint(\"Waiting for connection response\")\n#Using the socket connect to a server...in this case localhost\n\ntry:\n socketObject.connect((host, port))\n print(\"Connected to localhost\")\n\nexcept socket.error as e:\n print(str(e))\n\nres = socketObject.recv(1024)\nwaitingForServerToComeback = True\nunsentBuffer = []\nsecondSocket = socket.socket()\n\n\n# Receive the data\nwhile(True):\n if len(unsentBuffer) > 0: \n print(\"Re-sending lost messages to server\")\n for i in range(len(unsentBuffer)):\n messageBytes = str.encode(unsentBuffer[i])\n secondSocket.sendall(messageBytes)\n res = secondSocket.recv(1024)\n print(res)\n unsentBuffer = []\n\n # message = input(\"Input message to send to server: \")\n\n operation = ''\n retain = ''\n\n retain = input(\"Input position value to retain: \")\n operation = input(\"Input Operation (insert/delete): \")\n value = input(\"Input value for operation (insert: text | delete: position value): \")\n\n\n if retain == '':\n if operation == 'insert':\n client_delta = Delta().insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().delete(int(value))\n \n else:\n if operation == 'insert':\n client_delta = Delta().retain(int(retain)).insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().retain(int(retain)).delete(int(value)) \n\n\n print(\"[Client Operation]:\", client_delta)\n\n message = str(client_delta)\n\n try:\n if waitingForServerToComeback == True:\n messageBytes = str.encode(message)\n socketObject.sendall(messageBytes)\n else:\n messageBytes = str.encode(message)\n secondSocket.sendall(messageBytes)\n\n\n except ConnectionResetError as e: #server connection shut down\n unsentBuffer.append(message) #place the unsent message in the buffer\n \n while(waitingForServerToComeback):\n \n try:\n secondSocket.connect((host,port))\n print(\"Server is back\")\n waitingForServerToComeback = False\n \n\n except ConnectionRefusedError:\n print(str(e))\n\n \n if waitingForServerToComeback == True:\n data = socketObject.recv(1024)\n print(data)\n else:\n data = secondSocket.recv(1024)\n print(data)\n\n\nsocketObject.close()\nsecondSocket.close()" }, { "alpha_fraction": 0.5302325487136841, "alphanum_fraction": 0.55898517370224, "avg_line_length": 25, "blob_id": "c6e1596a1661eff06c62830e8830d28b55e99c58", "content_id": "ee265e8c749ca9abcc2c765ae37849d324664c22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2365, "license_type": "no_license", "max_line_length": 66, "num_lines": 91, "path": "/cs-delta/server.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import socket\nimport os\nfrom _thread import *\n\nimport sys\nsys.path.append('../')\nfrom delta import Delta\n\nServerSideSocket = socket.socket()\nhost = '127.0.0.1'\nport = 2004\nThreadCount = 0\nclients= set()\n\ndelta_object = Delta().insert('ABCDE')\n\ntry:\n ServerSideSocket.bind((host, port))\nexcept socket.error as e:\n print(str(e))\n\nprint('Socket is listening..')\nServerSideSocket.listen(5)\n\ndef string_to_delta(text):\n temp_text = text[7:]\n delta_text = temp_text[:-2]\n delta_list = delta_text.split(',')\n\n if len(delta_list) == 1:\n ops = delta_list[0][2:8]\n \n if ops == 'insert':\n value = delta_list[0][12:-2]\n print(value)\n return Delta().insert(value)\n \n elif ops == 'delete':\n value = int(delta_list[0][11:-1])\n return Delta().delete(value)\n\n elif len(delta_list) == 2:\n for i in range(2):\n if i == 0:\n ops_1 = delta_list[0][2:8]\n value_1 = int(delta_list[0][11:12])\n\n elif i == 1:\n ops_2 = delta_list[1][3:9]\n\n if ops_2 == 'insert':\n value_2 = delta_list[1][13:-2]\n return Delta().retain(value_1).insert(value_2)\n \n elif ops_2 == 'delete':\n value_2 = int(delta_list[1][12:-1])\n return Delta().retain(value_1).delete(value_2)\n\n return Delta()\n\n\ndef multi_threaded_client(connection):\n global delta_object\n connection.send(str.encode('Server is working:'))\n while True:\n data = connection.recv(2048)\n client_message = data.decode('utf-8')\n print(client_message)\n\n client_delta = string_to_delta(client_message)\n delta_object = delta_object.compose(client_delta)\n\n print(client_delta)\n print(delta_object)\n\n response = 'Server message: ' + str(delta_object)\n if not data:\n break\n print(response)\n connection.sendall(str.encode(response))\n connection.close()\n\nwhile True:\n Client, address = ServerSideSocket.accept()\n clients.add(Client)\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(multi_threaded_client, (Client, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\n\nServerSideSocket.close()" }, { "alpha_fraction": 0.6200448870658875, "alphanum_fraction": 0.6335078477859497, "avg_line_length": 22.068965911865234, "blob_id": "ce88790b8d36205396d9821f9525051ae71b4f76", "content_id": "b6aa588edec7316de73e05a1adb25dd6159f190d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 88, "num_lines": 58, "path": "/cs-delta/client.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "#import the socket module\nimport socket\n\nimport sys\nsys.path.append('../')\nfrom delta import Delta\n\n#Create a socket instance\nsocketObject = socket.socket()\nhost = '127.0.0.1'\nport = 2004\n\nprint(\"Waiting for connection response\")\n#Using the socket connect to a server...in this case localhost\n\ntry:\n socketObject.connect((host, port))\n print(\"Connected to localhost\")\n\nexcept socket.error as e:\n print(str(e))\n\nres = socketObject.recv(1024)\n\n# Receive the data\nwhile(True):\n\n operation = ''\n retain = ''\n\n retain = input(\"Input position value to retain: \")\n operation = input(\"Input Operation (insert/delete): \")\n value = input(\"Input value for operation (insert: text | delete: position value): \")\n\n\n if retain == '':\n if operation == 'insert':\n client_delta = Delta().insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().delete(int(value))\n \n else:\n if operation == 'insert':\n client_delta = Delta().retain(int(retain)).insert(value)\n \n elif operation == 'delete':\n client_delta = Delta().retain(int(retain)).delete(int(value)) \n\n\n messageBytes = str.encode(str(client_delta))\n socketObject.sendall(messageBytes)\n\n data = socketObject.recv(1024)\n print(data)\n\n\nsocketObject.close()" }, { "alpha_fraction": 0.6352313160896301, "alphanum_fraction": 0.6539145708084106, "avg_line_length": 22.93617057800293, "blob_id": "351e38aa2621b468256dc172490920584985f745", "content_id": "84b110f1739c636b6a14cc16d43c8ce1e5b8d20a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "no_license", "max_line_length": 64, "num_lines": 47, "path": "/time-experiment/server.py", "repo_name": "grimmweeper/50.012-networks-OT", "src_encoding": "UTF-8", "text": "import socket\nimport os\nfrom _thread import *\n\nimport counter\n\nServerSideSocket = socket.socket()\nhost = '127.0.0.1'\nport = 2004\nThreadCount = 0\nclients= set()\n\nvalue = 1\n\ntry:\n ServerSideSocket.bind((host, port))\nexcept socket.error as e:\n print(str(e))\n\nprint('Socket is listening..')\nServerSideSocket.listen(5)\n\ndef multi_threaded_client(connection):\n global value\n connection.send(str.encode('Server is working:'))\n while True:\n data = connection.recv(2048)\n client_message = data.decode('utf-8')\n print(client_message)\n value = counter.compute(value, client_message)\n print(value)\n response = 'Server message: ' + str(value)\n if not data:\n break\n print(response)\n connection.sendall(str.encode(response))\n # connection.close()\n\nwhile True:\n Client, address = ServerSideSocket.accept()\n clients.add(Client)\n print('Connected to: ' + address[0] + ':' + str(address[1]))\n start_new_thread(multi_threaded_client, (Client, ))\n ThreadCount += 1\n print('Thread Number: ' + str(ThreadCount))\n\nServerSideSocket.close()" } ]
13
andrely/twitter-sentiment
https://github.com/andrely/twitter-sentiment
55f3ab7d0f4a28b5c0b6e5d277565f78d3dd580f
dc322fa9e0d0122ced2593093041cf953c9ef528
19aa225a4740a1550a73189d9ecf18fe2df17ca3
refs/heads/master
2021-01-18T12:34:49.912355
2015-01-22T22:11:21
2015-01-22T22:11:21
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49056604504585266, "alphanum_fraction": 0.6037735939025879, "avg_line_length": 9.399999618530273, "blob_id": "62342cbf29a874cc330cf91c8f4b412029bb8ecd", "content_id": "dea9531f8bae775a72727010b9f26668e5855afc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "no_license", "max_line_length": 24, "num_lines": 5, "path": "/models/__init__.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 28. sep. 2014\n\n@author: JohnArne\n'''\n\n" }, { "alpha_fraction": 0.4879491925239563, "alphanum_fraction": 0.5752250552177429, "avg_line_length": 45.900718688964844, "blob_id": "69bf16514460bf17014ba21563ef768ba20c8440", "content_id": "6b771c5670b92b9ae39c8bb76761fe0591f72fcc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39209, "license_type": "no_license", "max_line_length": 186, "num_lines": 836, "path": "/plotting.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nHandles plotting of different visualizations of data.\n@author: JohnArne\n'''\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport random\nimport numpy as np\nimport utils\nimport random\nimport pickle\nfrom Tkconstants import OFF\n\ndef plot_temporal_sentiment(data, filename=\"temporal\"):\n \"\"\"\n Plots the temporal sentiment using the given data.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)):\n r, g, b = tableau20[i]\n tableau20[i] = (r / 255., g / 255., b / 255.)\n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure(figsize=(8, 6)) \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False) \n \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n \n # Limit the range of the plot to only where the data is. \n # Avoid unnecessary whitespace. \n plt.ylim(0, 1) \n plt.xlim(0, 101) \n \n # Make sure your axis ticks are large enough to be easily read. \n # You don't want your viewers squinting to read your plot.\n# y_ticks = [] \n# plt.yticks(range(0, 1, 10), [str(x) for x in range(0, 91, 10)], fontsize=14) \n plt.xticks(fontsize=10) \n plt.yticks(fontsize=10)\n # Provide tick lines across the plot to help your viewers trace along \n # the axis ticks. Make sure that the lines are light and small so they \n # don't obscure the primary data lines. \n for y in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]: \n plt.plot(range(1,105), [y] * len(range(1,105)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\") \n \n # Now that the plot is prepared, it's time to actually plot the data! \n # Note that I plotted the labels in order of the highest % in the final year. \n labels = data.keys() \n y_poses = [] \n offsets = [0.02, 0.04,0.06,0.08,0.1,0.12, 0.14,0.16,0.18,0.2]\n for rank, column in enumerate(labels): \n # Plot each line separately with its own color, using the Tableau 20 \n # color set in order. \n plt.plot(data[column][0], data[column][1], lw=1.0, color=tableau20[rank]) \n \n # Add a text label to the right end of every line. Most of the code below \n # is adding specific offsets y position because some labels overlapped. \n y_pos = data[column][1][-1]\n# new_pos = None\n# offset_counter = 0\n for poses in y_poses:\n if y_pos < poses+0.01 and y_pos>poses:\n y_pos = y_pos+0.05\n# offset_counter += 1\n break\n if y_pos > poses-0.01 and y_pos<poses:\n y_pos = y_pos+0.05\n# offset_counter += 1\n break\n else:\n y_pos = y_pos\n y_poses.append(y_pos)\n # Again, make sure that all labels are large enough to be easily read \n # by the viewer. \n plt.text(101.5, y_pos, column, fontsize=8, color=tableau20[rank]) \n \n plt.savefig(\"figs/\"+filename+\".pdf\", bbox_inches=\"tight\");\n print \"Figure done.\" \n \ndef plot_performance_histogram(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n precisions = [data[key][0] for key in labels] \n recalls = [data[key][1] for key in labels]\n f1s = [data[key][2] for key in labels]\n accuracies = [data[key][3] for key in labels]\n\n #Create bars \n ind = (np.arange(len(labels))*2)+0.25\n width = 0.35\n ax.bar(ind, precisions, width, color=tableau20[0], edgecolor=\"none\")\n ax.bar(ind+width, recalls, width, color=tableau20[1], edgecolor=\"none\")\n ax.bar(ind+width*2, f1s, width, color=tableau20[2], edgecolor=\"none\")\n ax.bar(ind+width*3, accuracies, width, color=tableau20[3], edgecolor=\"none\")\n \n #Create top bar labels\n for p, i in zip(precisions, ind):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[0])\n for p, i in zip(recalls, ind+width):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[1])\n for p, i in zip(f1s, ind+width*2):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[2])\n for p, i in zip(accuracies, ind+width*3):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[3])\n \n ax.spines[\"top\"].set_visible(False) \n# ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*2) \n ax.set_xticklabels(labels) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]: \n plt.plot(range(0,7), [y] * len(range(0,7)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n \ndef plot_combined_histogram(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n precisions = [data[key][0] for key in labels] \n recalls = [data[key][1] for key in labels]\n f1s = [data[key][2] for key in labels]\n accuracies = [data[key][3] for key in labels]\n\n #Create bars \n ind = (np.arange(len(labels))*5.5)+0.55\n width = 1.1\n ax.bar(ind, precisions, width, color=tableau20[0], edgecolor=\"none\")\n ax.bar(ind+width, recalls, width, color=tableau20[1], edgecolor=\"none\")\n ax.bar(ind+(width)*2, f1s, width, color=tableau20[2], edgecolor=\"none\")\n ax.bar(ind+(width)*3, accuracies, width, color=tableau20[3], edgecolor=\"none\")\n \n #Create top bar labels\n for p, i in zip(precisions, ind):\n plt.text(i, p+0.01, \"%0.2f\" % p, fontsize=8, color=tableau20[0])\n for p, i in zip(recalls, ind+width):\n plt.text(i, p+0.01, \"%0.2f\" % p, fontsize=8, color=tableau20[1])\n for p, i in zip(f1s, ind+width*2):\n plt.text(i, p+0.01, \"%0.2f\" % p, fontsize=8, color=tableau20[2])\n for p, i in zip(accuracies, ind+width*3):\n plt.text(i, p+0.01, \"%0.2f\" % p, fontsize=8, color=tableau20[3])\n \n ax.spines[\"top\"].set_visible(False) \n# ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*2) \n ax.set_xticklabels([l.split('+')[0]+\"\\n\"+l.split('+')[1] for l in labels]) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]: \n plt.plot(range(0,29), [y] * len(range(0,29)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n print \"Done\"\n \ndef plot_pos_analysis(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n values = [data[key] for key in labels]\n print values\n print labels \n sorted_values_and_labels = [list(x) for x in zip(*sorted(zip(values,labels)))]\n print \"Sorted:\", sorted_values_and_labels\n values = sorted_values_and_labels[0]\n labels = sorted_values_and_labels[1]\n #Create bars \n ind = (np.arange(len(labels)))\n width = 0.7\n for v,i in zip(values,ind):\n ax.bar(i, v, width, color=tableau20[14], edgecolor=\"none\")\n \n #Create top bar labels\n for p, i, l in zip(values, ind, labels):\n plt.text(i, p+0.01 if p>0 else p-0.03, l, fontsize=8, color=tableau20[14])\n\n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*2) \n ax.set_xticklabels([\" \" for _ in labels]) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [-0.4,-0.3,-0.2,-0.1,0.0,0.1,0.2,0.3,0.4]: \n plt.plot(range(0,18), [y] * len(range(0,18)), \"--\", lw=0.1, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n\n \ndef average_wordclasses(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n precisions = [data[key][0] for key in labels] \n recalls = [data[key][1] for key in labels]\n f1s = [data[key][2] for key in labels]\n accuracies = [data[key][3] for key in labels]\n\n #Create bars \n ind = (np.arange(len(labels))*2)+0.25\n width = 0.35\n ax.bar(ind, precisions, width, color=tableau20[0], edgecolor=\"none\")\n ax.bar(ind+width, recalls, width, color=tableau20[1], edgecolor=\"none\")\n ax.bar(ind+width*2, f1s, width, color=tableau20[2], edgecolor=\"none\")\n ax.bar(ind+width*3, accuracies, width, color=tableau20[3], edgecolor=\"none\")\n \n #Create top bar labels\n for p, i in zip(precisions, ind):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[0])\n for p, i in zip(recalls, ind+width):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[1])\n for p, i in zip(f1s, ind+width*2):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[2])\n for p, i in zip(accuracies, ind+width*3):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[3])\n \n ax.spines[\"top\"].set_visible(False) \n# ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*2) \n ax.set_xticklabels(labels) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [1,2,3,4,5,6,7]: \n plt.plot(range(0,7), [y] * len(range(0,7)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n \ndef detailed_average_wordclasses(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n datalists = []\n for i in xrange(len(data[labels[0]])):\n datalists.append([data[key][i] for key in labels]) \n\n \n #Create bars \n ind = (np.arange(len(labels))*2.2)+0.2\n width = 0.1\n offset = np.arange(0.01, 1, 0.01)\n colorlist = [tableau20[0],tableau20[0],tableau20[0],tableau20[1],tableau20[4],tableau20[5],tableau20[6],tableau20[7],tableau20[2],tableau20[2],tableau20[2],tableau20[2],tableau20[2],\n tableau20[13],tableau20[14],tableau20[15],tableau20[16],tableau20[3]]\n for i in xrange(len(datalists)):\n bar = ax.bar(ind+width*i, datalists[i], width, color=colorlist[i], edgecolor=\"none\")\n #Create top bar labels\n# for p, i in zip(precisions, ind):\n# plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[0])\n# for p, i in zip(recalls, ind+width):\n# plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[1])\n# for p, i in zip(f1s, ind+width*2):\n# plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[2])\n# for p, i in zip(accuracies, ind+width*3):\n# plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[3])\n \n ax.spines[\"top\"].set_visible(False) \n# ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*9) \n ax.set_xticklabels(labels) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [0.2,0.4,0.6,0.8,1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4,2.6,2.8,3.0]: \n plt.plot(range(0,8), [y] * len(range(0,8)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n \ndef plot_entity_histogram(data, filename):\n \"\"\"\n Plots the performance of different algorithms.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)): \n r, g, b = tableau20[i] \n tableau20[i] = (r / 255., g / 255., b / 255.) \n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure() \n \n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n \n labels = data.keys()\n print labels\n precisions = [data[key][0] for key in labels] \n recalls = [data[key][1] for key in labels]\n f1s = [data[key][2] for key in labels]\n accuracies = [data[key][3] for key in labels]\n\n #Create bars \n ind = (np.arange(len(labels))*2)+0.25\n width = 0.35\n ax.bar(ind, precisions, width, color=tableau20[0], edgecolor=\"none\")\n ax.bar(ind+width, recalls, width, color=tableau20[1], edgecolor=\"none\")\n ax.bar(ind+width*2, f1s, width, color=tableau20[2], edgecolor=\"none\")\n ax.bar(ind+width*3, accuracies, width, color=tableau20[3], edgecolor=\"none\")\n \n #Create top bar labels\n for p, i in zip(precisions, ind):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[0])\n for p, i in zip(recalls, ind+width):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[1])\n for p, i in zip(f1s, ind+width*2):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[2])\n for p, i in zip(accuracies, ind+width*3):\n plt.text(i+0.03, p+0.01, \"%0.2f\" % p, fontsize=10, color=tableau20[3])\n \n ax.spines[\"top\"].set_visible(False) \n# ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False)\n ax.set_xticks(ind+width*2) \n ax.set_xticklabels(labels) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n\n for y in [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]: \n plt.plot(range(0,7), [y] * len(range(0,7)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\",labelcolor=tableau20[14]) \n \n plt.savefig('figs/'+filename+\".pdf\", bbox_inches=\"tight\"); \n\n \ndef plot_dataset_stats(data):\n \"\"\"\n Plots histograms of the dataset statistics using the given data.\n \"\"\"\n\ndef load_incremental_data():\n f1_data= pickle.load(open('incremental_f1100',\"rb\"))\n acc_data=pickle.load(open('incremental_acc100',\"rb\"))\n print f1_data\n print acc_data\n for key in f1_data.keys():\n f1list = f1_data[key]\n f1_data[key] = [range(5,101,5),f1list]\n acclist = acc_data[key]\n acc_data[key] = [range(5,101,5),acclist]\n f1svm_data = {}\n f1nb_data = {}\n f1me_data = {}\n accsvm_data = {}\n accnb_data = {}\n accme_data = {}\n for key in f1_data.keys():\n if key[:3]==\"SVM\":\n f1svm_data[key] = f1_data[key]\n elif key[:2]==\"NB\":\n f1nb_data[key] = f1_data[key]\n elif key[:6]==\"MaxEnt\":\n f1me_data[key] = f1_data[key]\n for key in acc_data.keys():\n if key[:3]==\"SVM\":\n accsvm_data[key] = acc_data[key]\n elif key[:2]==\"NB\":\n accnb_data[key] = acc_data[key]\n elif key[:6]==\"MaxEnt\":\n accme_data[key] = acc_data[key]\n \n \n return f1svm_data, f1nb_data, f1me_data, accsvm_data, accnb_data, accme_data\n \n\ndef plot_subjectivity_aggregates(data, filename=\"temporal\"):\n \"\"\"\n Plots the temporal sentiment using the given data.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)):\n r, g, b = tableau20[i]\n tableau20[i] = (r / 255., g / 255., b / 255.)\n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure(figsize=(9, 6)) \n ind = np.arange(len(data['Targets'][0]))\n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False) \n ax.set_xticks(ind+0.25)\n ax.set_xticklabels(['%.2f' % x for x in data['Targets'][0]]) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n ax.bar(ind, data['Frequencies'][1], 0.5, color=tableau20[14], edgecolor=\"none\")\n \n # Limit the range of the plot to only where the data is. \n # Avoid unnecessary whitespace. \n plt.ylim(0, 70) \n plt.xlim(0, 19)\n \n # Make sure your axis ticks are large enough to be easily read. \n # You don't want your viewers squinting to read your plot.\n# y_ticks = [] \n# plt.yticks(range(0, 1, 10), [str(x) for x in range(0, 91, 10)], fontsize=14) \n plt.xticks(fontsize=8) \n plt.yticks(fontsize=10)\n # Provide tick lines across the plot to help your viewers trace along \n # the axis ticks. Make sure that the lines are light and small so they \n # don't obscure the primary data lines. \n for y in [5,10,15,20,25,30,35,40,45,50, 55, 60, 65]: \n plt.plot(range(0,20), [y] * len(range(0,20)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\") \n \n # Now that the plot is prepared, it's time to actually plot the data! \n # Note that I plotted the labels in order of the highest % in the final year. \n labels = [label for label in data.keys() if label!='Frequencies'] \n y_poses = []\n offsets = [0.02, 0.04,0.06,0.08,0.1,0.12, 0.14,0.16,0.18,0.2]\n for rank, column in enumerate(labels): \n # Plot each line separately with its own color, using the Tableau 20 \n # color set in order. \n plt.plot(ind+0.25, data[column][1], lw=1.0, color=tableau20[rank+1]) \n \n # Add a text label to the right end of every line. Most of the code below \n # is adding specific offsets y position because some labels overlapped. \n y_pos = data[column][1][-1]\n# new_pos = None\n# offset_counter = 0\n for poses in y_poses:\n if y_pos < poses+1 and y_pos>=poses:\n y_pos = y_pos+2\n# offset_counter += 1\n break\n if y_pos > poses-1 and y_pos<=poses:\n y_pos = y_pos+2\n# offset_counter += 1\n break\n else:\n y_pos = y_pos\n y_poses.append(y_pos)\n # Again, make sure that all labels are large enough to be easily read \n # by the viewer. \n plt.text(19, y_pos, column, fontsize=8, color=tableau20[rank+1]) \n plt.savefig(\"figs/\"+filename+\".pdf\", bbox_inches=\"tight\");\n print \"Figure done.\" \n\ndef plot_polarity_aggregates(data, filename=\"temporal\"):\n \"\"\"\n Plots the temporal sentiment using the given data.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)):\n r, g, b = tableau20[i]\n tableau20[i] = (r / 255., g / 255., b / 255.)\n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure(figsize=(9, 6)) \n ind = np.arange(len(data['Targets'][0]))\n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False) \n ax.set_xticks(ind+0.25)\n ax.set_xticklabels(['%.2f' % x for x in data['Targets'][0]]) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n ax.bar(ind, data['Frequencies'][1], 0.5, color=tableau20[14], edgecolor=\"none\")\n \n # Limit the range of the plot to only where the data is. \n # Avoid unnecessary whitespace. \n plt.ylim(-1, 1) \n plt.xlim(0, 19.5)\n \n # Make sure your axis ticks are large enough to be easily read. \n # You don't want your viewers squinting to read your plot.\n# y_ticks = [] \n# plt.yticks(range(0, 1, 10), [str(x) for x in range(0, 91, 10)], fontsize=14) \n plt.xticks(fontsize=8) \n plt.yticks(fontsize=10)\n # Provide tick lines across the plot to help your viewers trace along \n # the axis ticks. Make sure that the lines are light and small so they \n # don't obscure the primary data lines. \n# for y in [5,10,15,20,25,30,35,40,45]: \n for y in [-0.8,-0.6,-0.4,-0.2,0.2,0.4,0.6,0.8]: \n plt.plot(range(0,20), [y] * len(range(0,20)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n plt.plot(range(0,20), [0] * len(range(0,20)), \"--\", lw=2.5, color=\"black\", alpha=0.3) \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\") \n \n # Now that the plot is prepared, it's time to actually plot the data! \n # Note that I plotted the labels in order of the highest % in the final year. \n labels = [label for label in data.keys() if label!='Frequencies'] \n y_poses = []\n offsets = [0.02, 0.04,0.06,0.08,0.1,0.12, 0.14,0.16,0.18,0.2]\n for rank, column in enumerate(labels): \n # Plot each line separately with its own color, using the Tableau 20 \n # color set in order. \n plt.plot(ind+0.25, data[column][1], lw=1.0, color=tableau20[rank+1]) \n \n # Add a text label to the right end of every line. Most of the code below \n # is adding specific offsets y position because some labels overlapped. \n y_pos = data[column][1][-1]\n# new_pos = None\n# offset_counter = 0\n for poses in y_poses:\n if y_pos < poses+0.1 and y_pos>=poses:\n y_pos = y_pos+0.2\n# offset_counter += 1\n break\n if y_pos > poses-0.1 and y_pos<=poses:\n y_pos = y_pos-0.2\n# offset_counter += 1\n break\n else:\n y_pos = y_pos\n y_poses.append(y_pos)\n # Again, make sure that all labels are large enough to be easily read \n # by the viewer. \n plt.text(19, y_pos, column, fontsize=8, color=tableau20[rank+1]) \n# plt.text(19, 29.5, \"Neutral\", fontsize=8, color=\"black\") \n plt.savefig(\"figs/\"+filename+\".pdf\", bbox_inches=\"tight\");\n print \"Figure done.\" \n\ndef plot_temporal_topics(data, filename=\"temporal_topics\"):\n \"\"\"\n Plots the temporal sentiment using the given data.\n \"\"\"\n tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), \n (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), \n (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), \n (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), \n (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] \n \n # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. \n for i in range(len(tableau20)):\n r, g, b = tableau20[i]\n tableau20[i] = (r / 255., g / 255., b / 255.)\n \n # You typically want your plot to be ~1.33x wider than tall. This plot is a rare \n # exception because of the number of lines being plotted on it. \n # Common sizes: (10, 7.5) and (12, 9) \n f = plt.figure(figsize=(9, 6))\n ind = np.arange(len(data[data.keys()[0]][0]))\n # Remove the plot frame lines. They are unnecessary chartjunk. \n ax = plt.subplot(111) \n ax.spines[\"top\"].set_visible(False) \n ax.spines[\"bottom\"].set_visible(False) \n ax.spines[\"right\"].set_visible(False) \n ax.spines[\"left\"].set_visible(False) \n ax.set_xticks(ind+0.25)\n ax.set_xticklabels(['%.2f' % x for x in data[data.keys()[0]][0]]) \n # Ensure that the axis ticks only show up on the bottom and left of the plot. \n # Ticks on the right and top of the plot are generally unnecessary chartjunk. \n ax.get_xaxis().tick_bottom() \n ax.get_yaxis().tick_left() \n # Limit the range of the plot to only where the data is. \n # Avoid unnecessary whitespace. \n plt.ylim(0, 100) \n plt.xlim(0, 8)\n \n # Make sure your axis ticks are large enough to be easily read. \n # You don't want your viewers squinting to read your plot.\n# y_ticks = [] \n# plt.yticks(range(0, 1, 10), [str(x) for x in range(0, 91, 10)], fontsize=14) \n plt.xticks(fontsize=6) \n plt.yticks(fontsize=6)\n # Provide tick lines across the plot to help your viewers trace along \n # the axis ticks. Make sure that the lines are light and small so they \n # don't obscure the primary data lines. \n# for y in [5,10,15,20,25,30,35,40,45]: \n for y in range(0,100,5): \n plt.plot(range(0,8), [y] * len(range(0,8)), \"--\", lw=0.5, color=\"black\", alpha=0.3) \n plt.plot(range(0,8), [50] * len(range(0,8)), \"--\", lw=2.5, color=\"black\", alpha=0.3) \n # Remove the tick marks; they are unnecessary with the tick lines we just plotted. \n plt.tick_params(axis=\"both\", which=\"both\", bottom=\"off\", top=\"off\", \n labelbottom=\"on\", left=\"off\", right=\"off\", labelleft=\"on\") \n \n # Now that the plot is prepared, it's time to actually plot the data! \n # Note that I plotted the labels in order of the highest % in the final year. \n labels = data.keys() \n y_poses = []\n offsets = [0.02, 0.04,0.06,0.08,0.1,0.12, 0.14,0.16,0.18,0.2]\n for rank, column in enumerate(labels): \n # Plot each line separately with its own color, using the Tableau 20 \n # color set in order. \n for i in range(len(data[column][1])):\n data[column][1][i] = data[column][1][i] +50\n plt.plot(ind+0.25, data[column][1], lw=1.0, color=tableau20[rank]) \n \n # Add a text label to the right end of every line. Most of the code below \n # is adding specific offsets y position because some labels overlapped. \n y_pos = data[column][1][-1]\n# new_pos = None\n# offset_counter = 0\n for poses in y_poses:\n if y_pos < poses+5 and y_pos>=poses:\n y_pos = y_pos+8\n# offset_counter += 1\n break\n if y_pos > poses-5 and y_pos<=poses:\n y_pos = y_pos-8\n# offset_counter += 1\n break\n else:\n y_pos = y_pos\n y_poses.append(y_pos)\n # Again, make sure that all labels are large enough to be easily read \n # by the viewer. \n try:\n plt.text(8.2, y_pos, column, fontsize=8, color=tableau20[rank])\n except UnicodeDecodeError:\n plt.text(8.2, y_pos, column.decode('utf8'), fontsize=8, color=tableau20[rank])\n plt.text(8.2, 49.5, \"Neutral\", fontsize=8, color=\"black\") \n plt.savefig(\"figs/\"+filename+\".pdf\", bbox_inches=\"tight\");\n print \"Figure done.\"\n \nif __name__ == '__main__':\n# f1svm_data, f1nb_data, f1me_data, accsvm_data, accnb_data, accme_data = load_incremental_data()\n# data = {\"Erna Solberg\": [range(0,100),[random.randint(20,50) for _ in range(0,100)]],\n# \"rosenborg\": [range(0,100),[random.randint(40,60) for _ in range(0,100)]],\n# \"no target\": [range(0,100),[random.randint(30,40) for _ in range(0,100)]]}\n# plot_temporal_sentiment(f1svm_data, 'incremental_f1svm')\n# plot_temporal_sentiment(f1nb_data, 'incremental_f1nb')\n# plot_temporal_sentiment(f1me_data, 'incremental_f1me')\n# plot_temporal_sentiment(accsvm_data, 'incremental_accuracysvm')\n# plot_temporal_sentiment(accnb_data, 'incremental_accuracynb')\n# plot_temporal_sentiment(accme_data, 'incremental_accuracyme')\n \n# data = {\"SVM(SB)+SVM(PC)\": [(0.72+0.79)/2, (0.66+0.80)/2, (0.69+0.76)/2, (0.67+0.78)/2],\n# \"SVM(SB)+SVM(PB)\": [(0.72+0.77)/2, (0.66+0.76)/2, (0.69+0.75)/2, (0.67+0.75)/2],\n# \"SVM(SB)+MaxEnt(PC)\":[(0.72+0.77)/2, (0.66+0.80)/2, (0.69+0.72)/2, (0.67+0.75)/2],\n# \"MaxEnt(SB)+MaxEnt(PC)\": [(0.70+0.77)/2, (0.66+0.80)/2, (0.61+0.72)/2, (0.63+0.75)/2],\n# \"MaxEnt(SB)+SVM(PC)\": [(0.70+0.79)/2, (0.66+0.80)/2, (0.61+0.76)/2, (0.63+0.78)/2]}\n# plot_combined_histogram(data, \"combined\")\n data = pickle.load(open('topically_aggregated_polarity', 'rb'))\n plot_temporal_topics(data, \"temporal_topics\")\n" }, { "alpha_fraction": 0.5296835899353027, "alphanum_fraction": 0.5456807613372803, "avg_line_length": 30.977272033691406, "blob_id": "523253e01c6dc35881565f3ae4859784cc7cfebe", "content_id": "304e8cb07ec961291ed5fdc3e5d2b08a3e0c0380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2813, "license_type": "no_license", "max_line_length": 239, "num_lines": 88, "path": "/annotation.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 30. sep. 2014\n\n@author: JohnArne\n'''\nimport utils\nimport tweet\nimport os\n\ndef user_annotation():\n \"\"\"\n Feed tweets to console one at a time, and ask user for sentiment annotation.\n \"\"\"\n dataset = utils.select_dataset()\n text_tweets = utils.get_dataset(dataset)\n tweets = []\n for text_tweet in text_tweets:\n tweets.append(tweet.to_tweet(text_tweet))\n username = raw_input(\"Name? ... \")\n \n print \"\\n--------------\\n\"\n print \"Input: \"\n print \"\\n1: Negative sentiment (Negative opinion). \\n2: Neutral/objective sentiment (No opinion). \\n3: Positive sentiment (Positive opinion). \\n5: Delete the tweet from the dataset. \\nx: Cancel sequence. 0: Go back to previous tweet. \"\n print \"\\n--------------\\n\"\n \n annotated_to = 0\n i = 0\n while i < len(tweets):\n# tweets[i].text.encode('utf8')\n# text = tweets[i].text\n# tweets[i].text = text.decode('utf8')\n try:\n print \"Tweet nr. : \"+str(i+1)\n print str(((i+1.0*1.0)/len(tweets)*1.0)*100)+\" % done \"\n print unicode(tweets[i].__str__().decode('utf8'))\n except UnicodeEncodeError:\n try:\n print \"Tweet nr. : \"+str(i+1)\n print str(tweets[i])\n except UnicodeEncodeError:\n print \"Could not print tweet number \"+str(i+1) +\". Deleting tweet...\"\n tweets.remove(tweets[i])\n continue\n \n userinput = raw_input(\"...\")\n while not legal_input(userinput):\n userinput = raw_input(\"Unlawful input! Please re-introduce.\")\n if userinput is '1':\n tweets[i].set_sentiment(\"negative\")\n elif userinput is '2':\n tweets[i].set_sentiment(\"neutral\")\n elif userinput is '3':\n tweets[i].set_sentiment(\"positive\")\n elif userinput is '5':\n print \"Deleting tweet...\"\n tweets.remove(tweets[i])\n continue\n elif userinput is '0':\n i = i-1\n continue\n elif userinput is 'x':\n break\n i = i+1\n \n \n #TODO: need to encode to utf when getting from dataset?!?!\n #Store the sentiment in file!\n tweetlines = []\n for t in tweets[:i]:\n if t.get_sentiment() is None:\n continue\n tweetlines.append(t.to_tsv())\n dir = username+\"_annotated_data\"\n if not os.path.exists(dir):\n os.makedirs(dir)\n utils.store_dataset(tweetlines, dir+dataset[4:])\n \n print \"Domo arigato!\" \n \ndef legal_input(userinput):\n \"\"\"\n Checks input and returns true if the input is legal. Legal input should be \"1\", \"2\", \"3\", \"5\", or \"x\"\n \"\"\"\n legal_inputs = ['1','2','3','5','0','x']\n \n if userinput in legal_inputs:\n return True\n return False" }, { "alpha_fraction": 0.5586603879928589, "alphanum_fraction": 0.5669795274734497, "avg_line_length": 36.76612854003906, "blob_id": "f22e91d7a468cde5082bf7aff151f54e7bd21449", "content_id": "7fcad2df2c48e8b24006a72c42560e3cc3d3493d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4688, "license_type": "no_license", "max_line_length": 112, "num_lines": 124, "path": "/tweet.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 30. sep. 2014\n\n@author: JohnArne\n'''\nclass Tweet(object):\n \"\"\"\n Class for wrapping tweet information.\n \"\"\"\n \n def __init__(self, timestamp, user, text):\n self.user = user\n self.text = text\n self.timestamp = timestamp\n self.subjectivity = None #0 if objective, 1 if subjective\n self.polarity = None #0 if negative sentiment, 1 if positive sentiment\n self.processed_words = [] #dict for containing the stemmed and preprocessed words of the text body\n self.tagged_words = [] # a list of dicts\n self.nrof_happyemoticons = 0\n self.nrof_sademoticons = 0\n self.nrof_hashtags = 0\n self.nrof_usersmentioned = 0\n self.exclamated = False\n self.hashtags = []\n self.links = []\n self.users_mentioned = []\n self.nrof_exclamations = 0\n self.nrof_questionmarks = 0\n self.word_count = 0\n self.words_with_sentimentvalues={}\n self.sentiments = []\n self.link_pos = []\n self.sentiment_target = \"\"\n \n def to_tsv(self):\n \"\"\"\n Convert the data in this tweet to the .tsv format used to store it in .tsv files.\n TSV Format: Date \\t Time \\t Sentiment \\t User \\t Textbody\n \"\"\"\n tvsline = \"\"\n sentiment = self.get_sentiment()\n if sentiment is not None:\n tsvline = self.timestamp\n tsvline = tsvline+\"\\t\"+sentiment\n tsvline = tsvline+\"\\t\"+self.user\n tsvline = tsvline+\"\\t\"+self.text\n else:\n tsvline = self.timestamp+\"\\t\"+self.user+\"\\t\"+self.text\n return tsvline\n \n \n def get_sentiment(self):\n \"\"\"\n Returns a textual representation of the sentiment (negative, neutral, positive),\n Based on the subjectivity and polarity variables of the tweet.\n \"\"\"\n sentiment = None\n if self.subjectivity is 1:\n sentiment = \"negative\".encode('utf8') if self.polarity is 0 else \"positive\".encode('utf8')\n elif self.subjectivity is 0:\n sentiment = \"neutral\".encode('utf8')\n return sentiment\n \n def set_sentiment(self, sentiment):\n \"\"\"\n Sets the binary subjectivity and polarity variables of the tweet based on the\n passed textual representation of sentiment.\n \"\"\"\n if sentiment==\"negative\":\n self.subjectivity = 1\n self.polarity = 0\n elif sentiment==\"neutral\":\n self.subjectivity = 0\n self.polarity = 0\n elif sentiment==\"positive\":\n self.subjectivity = 1\n self.polarity = 1\n \n def stat_str(self):\n \"\"\"\n Returns a string of all stats of the tweet. BROKEN, unicode errors all around\n \"\"\"\n# try:\n# statstring = \"\\n--------------\\n\"+\" \\n\"+self.user+\"\\n\"+unicode(self.text)+\"\\n \"\n# except UnicodeDecodeError:\n statstring = \"\\n--------------\\n\"+\" \\n\"+self.user+\"\\n\"+self.text+\"\\n \"\n statstring = statstring + \"Tagged words: \"+str(self.tagged_words) + \"\\n\"\n statstring = statstring + \"Sentiment \" +str(self.get_sentiment()) + \"\\n\"\n statstring = statstring + \"Hashtags: \"+str(self.nrof_hashtags) + \" \"+str(self.hashtags) + \"\\n\"\n statstring = statstring + \"Users: \"+str(self.nrof_usersmentioned) + \" \"+str(self.users_mentioned) + \"\\n\"\n statstring = statstring + \"Happy emoticons: \"+str(self.nrof_happyemoticons) + \"\\n\"\n statstring = statstring + \"Sad emoticons: \"+str(self.nrof_sademoticons)+ \"\\n\"\n statstring = statstring + \"Question marks: \"+str(self.nrof_questionmarks)+ \"\\n\"\n statstring = statstring + \"Exclamation marks: \"+str(self.nrof_exclamations)+ \"\\n\"\n statstring = statstring + \"\\n--------------\\n\"\n return statstring\n \n def __str__(self):\n \"\"\"\n Returns a string representation of the tweet for visual representation.\n \"\"\"\n return \"\\n--------------\\n\"+\" \\n\"+self.user+\"\\n\"+self.text+\"\\n--------------\\n\"\n \n def __eq__(self, other):\n return self.text == other.text\n \ndef to_tweet(text):\n \"\"\"\n Convert a given .tsv formatted text line to a tweet object\n \"\"\"\n splits = text.split('\\t')\n print \"Creating tweet object: \"\n if len(splits)>3:\n print \"Splitted into more than 3...\"\n for split in splits:\n print split\n tweet = Tweet(splits[0], splits[2], splits[3])\n tweet.set_sentiment(splits[1])\n else:\n print \"Splitted into less than 3...\"\n for split in splits:\n print split\n tweet = Tweet(splits[0], splits[1], splits[2])\n return tweet\n \n" }, { "alpha_fraction": 0.5520133972167969, "alphanum_fraction": 0.5822147727012634, "avg_line_length": 26.952381134033203, "blob_id": "502f11442a19c42bd965ab57c482c52e16a37246", "content_id": "d13b70f662befcb367ff23593c8d46d17fe9918a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 104, "num_lines": 21, "path": "/models/nb.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 19. mars 2014\n\n@author: JohnArne\n'''\nfrom model import Model\nfrom sklearn.naive_bayes import MultinomialNB \n\n\nclass NB(Model):\n \"\"\"\n Class implementing the Multinomial Naive Bayes learning method.\n \"\"\"\n \n def __init__(self, train_tweets, train_targets, vect_options, tfidf_options):\n self.classifier = MultinomialNB()\n \n extra_params ={ \n 'clf__alpha': (0.1, 0.3, 0.5, 0.7, 0.8, 1.0)\n }\n super(NB, self).__init__(train_tweets, train_targets, vect_options, tfidf_options, extra_params)\n\n " }, { "alpha_fraction": 0.6105527877807617, "alphanum_fraction": 0.6170854568481445, "avg_line_length": 31.639345169067383, "blob_id": "62123936db66fcecf44724466176a7c066206e9c", "content_id": "42440e1a88f3576abd14f3fa7ce5c960426a20c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2003, "license_type": "no_license", "max_line_length": 157, "num_lines": 61, "path": "/tagger.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n'''\nCreated on 30. sep. 2014\n\n@author: JohnArne\n'''\n\n\n\nimport requests\n\nclass Tagger():\n \"\"\"\n Interfaces the POS tagger for classification.\n \"\"\"\n \n def __init__(self):\n \n #Request init connect to smarttagger\n self.url = \"http://smarttagger.herokuapp.com/tag\"\n \n \n def tag_text(self, text):\n \"\"\"\n Tags a text sequence using the current tagger.\n \"\"\"\n \n# print \"Tagging: \"+unicode(text.decode('utf8'))\n par = {\"text\": text, \"raw\": \"raw\", \"format\": \"json\"}\n r = requests.post(self.url, data=par)\n tagged_words = {}\n try:\n results = r.json()[\"phrases\"]\n tagged_words = results\n except ValueError as e:\n print \"Unable to get JSON: \" +str(e)\n print r.reason\n print r.status_code\n if len(tagged_words)<1:\n return None\n else:\n return tagged_words[0]\n \n\n\nif __name__==\"__main__\":\n tagger = Tagger()\n \n texts = []\n texts.append(u\"Viss Russland kritikken erna solberg framførte i FN var skjult, korleis i hulaste har den då hamna på framsida av VG i dag?\")\n texts.append(u\"borgebrende Hoyre erna solberg Hvem skal gjøre møkkajobbene da?\")\n texts.append(u\"erna solberg Siv Jensen FrP jensstoltenberg jonasgahrstore Skremmende at regjeringen vil selge aksjer i statlige selskap til utlandet.\")\n texts.append(u\"CSpange Aftenposten erna solberg Sannsynlige grunner ingen, heller ikke de 120, venter resultater. Og Kina og USA uteblir. Neste gang...\")\n texts.append(u\"ElinJoval konservativ erna solberg det Elin sa! Jeg vil ha mer tid til å være sammen med elevene.\")\n texts.append(u\"Skulle ønske konservativ og erna solberg hjalp til å styrke lærernes status. Vi er gode! Vi trenger tid til å gjøre jobben vår bedre!\")\n \n for text in texts:\n print unicode(text)\n \n for text in texts:\n print tagger.tag_text(text)" }, { "alpha_fraction": 0.6507903933525085, "alphanum_fraction": 0.6570028066635132, "avg_line_length": 37.20052719116211, "blob_id": "26054ff21e0e3738fed7bba6acf6800e41c70023", "content_id": "332fe385b0b46ee3cc9b16c74970cd59e0fd0529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14487, "license_type": "no_license", "max_line_length": 260, "num_lines": 379, "path": "/entity_extraction.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 4. jan. 2015\n\n@author: JohnArne\n\n-Ta en gruppe tweets.\n-Prov a finne entitetene i hver enkelt tweet.\n- kjor clustering pa tweets, eller pa bare entitetsnavn... grupper entitetene etter clusters og nominer den mest frekvente entiteten som overordnet navn\n'''\nimport lexicon.pos_mappings\nfrom lexicon import pos_mappings\nfrom tweet import Tweet\nimport utils\nfrom models.features import get_sentiment_values\nimport classifier\nimport pickle\nfrom sklearn import metrics\nimport plotting\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport math\n\n\ndef perform_entity_extraction(tweets, sentimentvalues, breakword_min_freq=0.2, breakword_range=2, use_sentiment_values=False, use_pmi=False, vocabulary=None, cluster=False, use_minibatch=False, use_idf=False, use_hasher=False):\n \"\"\"\n Takes in a list of correctly predicted subjective tweets and sentimentvalues, in addition to several optional parameters, and attempts entity extraction on all the tweeets.\n \"\"\"\n print len(tweets)\n sub_clf = classifier.get_optimal_subjectivity_classifier()\n #Get all the correctly classified subjective tweets\n if use_pmi and vocabulary==None: vocabulary = create_vocabulary(tweets) \n if use_sentiment_values:\n entities = find_entities(sub_clf, tweets, breakword_min_freq, breakword_range, use_pmi, vocabulary=vocabulary, sentimentvalues=sentimentvalues)\n else:\n entities = find_entities(sub_clf, tweets, breakword_min_freq, breakword_range, use_pmi, vocabulary=vocabulary)\n \n if cluster:\n #use clustering to group together tweets, \n #then choose the entities with the greatest freqiencies within each cluster as the sentiment target for all in the cluster\n #but not if the target is already none...\n cluster_tweets(tweets, use_minibatch, use_idf, use_hasher)\n \n \n for i in xrange(len(entities)):\n entities[i] = entities[i][0] if len(entities[i])>0 else None\n print entities\n return entities\n\ndef find_entities(sub_clf, tweets, min_freq, breakword_range, use_pmi=False, vocabulary=None, sentimentvalues=None):\n \"\"\"\n Takes in a subjectivity classifier and the tweets, and attempts to find the target of the classified sentiment.\n Return a textual description of the entity.\n \"\"\"\n if sentimentvalues!=None:\n entities = [find_entity(sub_clf, t, min_freq, breakword_range, use_pmi, vocabulary=vocabulary, sentimentvalues=s) for t,s in zip(tweets,sentimentvalues)]\n else:\n entities = [find_entity(sub_clf, t, min_freq, breakword_range, use_pmi, vocabulary=vocabulary) for t in tweets]\n return entities\n \n \ndef find_entity(sub_clf, t, min_freq, breakword_range, use_pmi=False, vocabulary=None, sentimentvalues=None):\n \"\"\"\n Attempts at identifying the entity of a single tweet, utilizing sentiment values if not none.\n \"\"\"\n #get a list of possibilities for this tweet\n possibilities = get_possible_entities(t)\n if len(possibilities)<1:\n for hashtag in t.hashtags:\n if len(hashtag)>1:\n return [hashtag]\n return []\n if len(possibilities)==1:\n return possibilities\n \n #Get breakwords from breakdown classification\n breakwords = breakdown_classify(sub_clf, t)\n \n breakwords = cutoff_breakwords(breakwords, min_freq)\n #get sentimental words if given values\n sentimentwords = []\n if sentimentvalues!=None:\n sentimentwords = get_sentimentwords(sentimentvalues)\n \n #Perform an intersection of the breakwords and sentimental words\n# print \"Text: \", t.text\n# print \"Possible entities: \",possibilities\n# print \"Hashtags: \",t.hashtags\n# print \"Shifting words: \",breakwords\n# print \"Sentimental words: \",sentimentwords\n sentiment_points = [val for val in sentimentwords if val in breakwords]\n# print \"Intersection: \", sentiment_points\n if len(sentiment_points)<1: sentiment_points = list(set(breakwords + sentimentwords))\n# print \"New intersection: \", sentiment_points\n \n possibilities = cutoff_possibilities(t.text.lower(), possibilities, sentiment_points, breakword_range)\n# print \"Possibilities after cutoff: \", possibilities\n# raw_input(\"Continue?\")\n\n if use_pmi:\n #Use PMI to disambiguate between possibilities\n pmi = []\n for p in possibilities:\n if p is None: continue\n for s in sentiment_points:\n if s is None: continue\n pmi.append([calculate_pmi(p,s,vocabulary), p])\n if len(pmi)>0: \n possibilities = [max(pmi)[1]]\n \n if len(possibilities)>0:\n return possibilities \n else:\n if len(t.hashtags)>0:\n for hashtag in t.hashtags:\n if len(hashtag)>1:\n return [hashtag]\n return []\n \n# if len(possibilities)>0:\n# return t.hashtags[0] if len(t.hashtags)>0 else possibilities\n# else:\n# return t.hashtags\n# \n #decide entity from possibilities based on the sentiment points\n #calculate the \"center\" of the sentiment points\n #choose the entity which is closest to the center of the sentiment points\n #or choose the entity closest to the first sentiment points...\n \n \ndef calculate_pmi(entity, sentiword, vocabulary):\n \"\"\"\n Calculates the pointwise mutual information between two given words.\n \"\"\"\n unigrams_freq = float(sum(vocabulary[0].values()))\n prob_entity = vocabulary[0][entity] / unigrams_freq\n prob_sentiword = vocabulary[0][sentiword] / unigrams_freq\n try:\n prob_both = vocabulary[1][\" \".join([unicode(entity),unicode(sentiword)])] / float(sum(vocabulary[1].values()))\n except KeyError:\n return 0.0\n except UnicodeDecodeError:\n print \"UnicodeError\"\n return 0.0\n return math.log(prob_both/float(prob_entity*prob_sentiword),2)\n \ndef create_vocabulary(tweets):\n \"\"\"\n Creates a bigram + unigram vocabulary of the given tweet texts.\n \"\"\"\n print \"Creating vocabulary...\"\n vocabulary = []\n unigrams_freq = {}\n bigrams_freq = {}\n texts= [t.text.lower() for t in tweets]\n for text in texts:\n for phrase in text.split('.'):\n phrase = phrase.replace(',',' ')\n unigrams = phrase.split(\" \")\n unigrams = [u for u in unigrams if len(u)>1]\n extended_bigrams = [x+\" \"+y for x,y in zip(unigrams[0::2],unigrams[1::2])] + [x+\" \"+y for x,y in zip(unigrams[1::2],unigrams[2::2])] + [x+\" \"+y for x,y in zip(unigrams[0::2],unigrams[2::2])] + [x+\" \"+y for x,y in zip(unigrams[1::2],unigrams[3::2])]\n for unigram in unigrams:\n unigrams_freq[unigram] = unigrams_freq.get(unigram, 0) + 1\n for bigram in extended_bigrams:\n bigrams_freq[bigram] = bigrams_freq.get(bigram, 0) + 1\n vocabulary = [unigrams_freq, bigrams_freq]\n return vocabulary\n\ndef is_entity(clf, t, entity, sentimentvalues=None):\n \"\"\"\n Takes in a classifier, a tweet, and an entity, returns a binary value corresponding to whether each entity is the sentiment entity of each tweet.\n \"\"\"\n \n return False\n \ndef get_possible_entities(t):\n \"\"\"\n Takes in a tweet, and returns a list of the possible entities for that tweet.\n \"\"\"\n possible_entities = []\n for phrase in t.tagged_words:\n for word in phrase:\n try:\n entity = word['word']\n if word['pos'] ==\"Np\":\n if len(entity)>1:\n possible_entities.append(entity.lower())\n except KeyError:\n continue\n return possible_entities\n \ndef get_sentimentwords(sentimentvalues):\n \"\"\"\n returns the words that contain sentimental value.\n \"\"\"\n sentimentwords = []\n for word in sentimentvalues.keys():\n if sentimentvalues[word][0]>0 or sentimentvalues[word][1]>0:\n sentimentwords.append(word)\n return sentimentwords\n\n\ndef breakdown_classify(clf, t):\n \"\"\"\n Classify substring permutations of the tweet in order to find a shifting point in the subjectivity classification\n \"\"\"\n orig_class = clf.classify([t])\n breakwords = subclassify(t.text.lower(), clf, orig_class)\n# breakwords = []\n# print \"Breakdown classification\"\n# for substring_paths in substrings:\n# for substring_and_rmword in substring_paths:\n# print substring_and_rmword['substring'], \" rm:\",substring_and_rmword['removed_word']\n# #Classify each substring, append causal word when sentiment changes from original\n# new_class = clf.classify_text([\" \".join(substring_and_rmword['substring'])])\n# print \"New class: \",new_class\n# if new_class!=orig_class: \n# breakwords.append(substring_and_rmword['removed_word'])\n# break\n# print \"Original prediction: \",orig_class\n return breakwords\n \n\n\ndef subclassify(t, clf, orig):\n \"\"\"\n Takes in a text, a classifier, and an original class. Returns all the break words where the class shifts. FIXXX!\n \"\"\"\n phrases = t.split(\",\")\n words = []\n for phrase in phrases:\n words = words + phrase.split(\" \")\n length = len(words)\n breakwords = []\n for i in xrange(length):\n breakwords.append(clf_sub(words[:i]+words[i+1:], words[i], clf, orig)) \n\n return breakwords\n \ndef clf_sub(words, removed_word, clf, orig):\n \"\"\"\n FIIIIX!!! Return on classification shift!!! yesaaaaa!\n \"\"\"\n if len(words)==1: return removed_word if clf.classify_text([\" \".join(words)])!=orig else None\n breakword = None\n# print \" \".join(words), \"Removed word: \", removed_word\n for i in xrange(len(words)-1):\n if clf.classify_text([\" \".join(words)])!=orig:\n# print \"Swithed class!\"\n return removed_word\n return clf_sub(words[:i]+words[i+1:], words[i], clf, orig)\n return breakword\n \ndef cutoff_breakwords(breakwords, min_freq):\n \"\"\"\n Cuts of breakwords below the given frequency. Returns a list of uniques, where the belowfreqs have been removed\n \"\"\"\n breakword_freq = int(round(len(breakwords)*min_freq))\n# print \"Breakwords before cutoff \",breakwords, min_freq\n frequencies = {}\n #remove breakwords with a lower frequency\n for word in breakwords:\n frequencies[word] = frequencies.get(word,0)+1\n uniquelist = list(set(breakwords))\n for key in frequencies:\n if frequencies[key]<breakword_freq:\n uniquelist.remove(key)\n \n return uniquelist\n\ndef cutoff_possibilities(text, possibilities, sentiment_points, breakword_range):\n \"\"\"\n Removes the possible which are not within the breakword_range of any sentiment_points.\n \"\"\"\n phrases = text.split(\",\")\n words = []\n sentiment_indexes = []\n for phrase in phrases:\n words = words + phrase.split(\" \")\n \n for i in xrange(len(words)):\n if words[i] in sentiment_points:\n sentiment_indexes.append(i) \n \n limited_possibilities = []\n for point in sentiment_indexes:\n min_breakoff = point-breakword_range\n max_breakoff = point+breakword_range \n include_words = words[min_breakoff:max_breakoff+1]\n for possibility in possibilities:\n if possibility in include_words:\n limited_possibilities.append(possibility)\n \n return limited_possibilities\n\ndef get_hashtag_entities(tweets):\n \"\"\"\n Returns the first hashtag of every tweet, else returns None\n \"\"\"\n return [t.hashtags[0] if len(t.hashtags)>0 else None for t in tweets]\n \ndef reduce_entities(entities):\n \"\"\"\n Reduce entities to binary so as to test with actual targets.\n \"\"\"\n reduced = []\n for entity in entities:\n reduced.append(1 if entity in rosenborg_model else 0)\n return reduced\n\ndef get_scores(targets, predictions):\n accuracy = metrics.accuracy_score(targets, predictions)\n precision = metrics.precision_score(targets, predictions)\n recall = metrics.recall_score(targets, predictions)\n f1_score = metrics.f1_score(targets, predictions)\n return accuracy, precision, recall, f1_score\n\ndef create_model(text):\n model = [text]\n f = open(text+\"_model\", \"wb\")\n pickle.dump(model,f)\n f.close()\n \ndef append_to_model(name, text):\n model = pickle.load(name+\"_model\")\n model.append(text)\n model = list(set(model))\n f = open(name+\"_model\", \"wb\")\n pickle.dump(model, f)\n f.close()\n \ndef cluster_tweets(tweets, max_features, use_minibatch, use_idf, use_hasher):\n \"\"\"\n Performs k-means clustering on tweets.\n \"\"\"\n \n \n return None\n\n\n\ndef perform_and_test_extraction():\n datasetnr = 1\n tweets = utils.get_pickles(datasetnr)\n vocabulary = create_vocabulary(utils.get_all_pickles())\n \n sentimentvalues = get_sentiment_values(datasetnr)\n tweets, targets = utils.get_entity_test_and_targets()\n entities = perform_entity_extraction(tweets, sentimentvalues, breakword_range=3)\n hashtag_entities = get_hashtag_entities(tweets)\n \n pmi_entities = perform_entity_extraction(tweets, sentimentvalues, breakword_range=8, use_pmi=True, vocabulary=vocabulary)\n #TESTIFY!\n reduced_entities = reduce_entities(entities)\n reduced_hashtags = reduce_entities(hashtag_entities)\n reduced_pmis = reduce_entities(pmi_entities)\n \n data = {}\n accuracy, precision, recall, f1_score = get_scores(targets, reduced_entities)\n print \"Entity Scores: \", accuracy, precision, recall, f1_score\n data[\"Custom\"] = [accuracy, precision, recall, f1_score] \n accuracy, precision, recall, f1_score = get_scores(targets, reduced_hashtags)\n data[\"Hashtags\"] = [accuracy, precision, recall, f1_score]\n print \"Hashtag Scores: \", accuracy, precision, recall, f1_score\n accuracy, precision, recall, f1_score = get_scores(targets, reduced_pmis)\n print \"PMI Scores: \", accuracy, precision, recall, f1_score\n data[\"Custom+PMI\"] = [accuracy, precision, recall, f1_score]\n #send to plotting\n plotting.plot_entity_histogram(data, \"entity_extraction\")\n \n \nrosenborg_model = [\"rosenborg\",\"rosenborgs\",\"rosenborgms\", \"rbk\",\"rbks\",\"rosenborg2\" ]\n \nif __name__ == '__main__':\n #test substringify\n# substrings = subc(string)\n# print substrings\n# print len(substrings)\n #test breakdown clf\n# breakdown_classify(\"adwd\", Tweet(\"12313\", \"johnaren\", \"jeg liker at\"))\n perform_and_test_extraction()\n \n " }, { "alpha_fraction": 0.5698412656784058, "alphanum_fraction": 0.5984126925468445, "avg_line_length": 29.649999618530273, "blob_id": "3d0de48a877dac685544d2d1f4c03f06196825bd", "content_id": "7341c010223f1b5f2d098fe041786b1224d104ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 105, "num_lines": 20, "path": "/models/svm.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 19. mars 2014\n\n@author: JohnArne\n'''\nfrom model import Model\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.svm import LinearSVC\n\nclass SVM(Model):\n \"\"\"\n Class implementing the Support Vector Machines classsification model.\n \"\"\"\n \n def __init__(self, train_tweets, train_targets, vect_options, tfidf_options):\n self.classifier = LinearSVC()\n extra_params = {\n 'clf__C': (0.1, 0.3, 0.5, 0.7, 0.8, 1.0)\n }\n super(SVM, self).__init__(train_tweets, train_targets, vect_options, tfidf_options, extra_params)\n \n " }, { "alpha_fraction": 0.5687612295150757, "alphanum_fraction": 0.5821185111999512, "avg_line_length": 36.84239196777344, "blob_id": "88fd87586f1c74510f4110cabdd8cc027758b9a0", "content_id": "1961cb5ce98a7350685a9cd75a8a0f69aa4b9bd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13925, "license_type": "no_license", "max_line_length": 134, "num_lines": 368, "path": "/models/features.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 27. nov. 2014\n\n@author: JohnArne\n'''\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport numpy as np\nimport pickle\n\ndef get_feature_set(tweet,featureset,sentimentvalues):\n if(featureset=='SA'):\n return get_feature_set_SA(tweet)\n elif(featureset=='SB'): \n return get_feature_set_SB(tweet)\n elif(featureset=='SC'): \n return get_feature_set_SC(tweet,sentimentvalues)\n elif(featureset=='SC2'): \n return get_feature_set_SC2(tweet,sentimentvalues)\n elif(featureset=='PA'): \n return get_feature_set_PA(tweet)\n elif(featureset=='PB'): \n return get_feature_set_PB(tweet)\n elif(featureset=='PC'): \n return get_feature_set_PC(tweet,sentimentvalues)\n elif(featureset=='PC2'): \n return get_feature_set_PC2(tweet,sentimentvalues)\n \n\ndef get_feature_set_SA(tweet):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set SA, which is only text frequencies...\n \"\"\"\n features= {}\n return features\n\ndef get_feature_set_SB(tweet):\n \"\"\"\n Creates a dict with grammatical features to be included in classification. Returns it to the classification model.\n Features to be included: pos-tags, \n \"\"\"\n #pos-tag frequencies\n# print \"Tagged words in tweet: \", tweet.tagged_words\n pos_tag_freq = {}\n additional_freq = {}\n for phrase in tweet.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# if tag=='PRtinf':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='ADJS':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='ADJ':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='NP':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='DET':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='P':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n if tag in ADJECTIVES:\n additional_freq['adjectives'] = additional_freq.get(tag, 0) + 1\n elif tag in ADVERBS: \n additional_freq['adverbs'] = additional_freq.get(tag, 0) + 1\n elif tag in PRONOUNS:\n additional_freq['pronoun'] = 1\n except KeyError:\n continue\n# print \"Tag frequencies: \", pos_tag_freq\n for key in pos_tag_freq.keys():\n pos_tag_freq[key] = pos_tag_freq[key]*1.0\n #number of adjectives in sentence, number of adverbs in sentence(except ikke), pronoun in sentence(binary) \n #Number of exclamation marks, number of emoticons,\n emoticons = tweet.nrof_happyemoticons+tweet.nrof_sademoticons\n if emoticons>0:\n additional_freq['emoticons'] = emoticons*1.0\n if tweet.nrof_exclamations>0:\n additional_freq['exclamations'] = tweet.nrof_exclamations*1.0\n \n# print \"Additional frequencies: \", additional_freq\n# raw_input(\"Continue?\")\n \n #Concatenate the dicts\n features= dict(pos_tag_freq.items() + additional_freq.items())\n# print \"All features: \", features\n# raw_input(\"Continue?\")\n return features\n\n\ndef get_feature_set_SC(tweet, sentimentvalues):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set SC.\n \"\"\"\n pos_tag_freq = {}\n additional_freq = {}\n for phrase in tweet.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# if tag=='PRtinf':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='ADJS':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='ADJ':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='NP':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='DET':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n# elif tag=='P':\n# pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n if tag in ADJECTIVES:\n additional_freq['adjectives'] = additional_freq.get(tag, 0) + 1\n elif tag in ADVERBS: \n additional_freq['adverbs'] = additional_freq.get(tag, 0) + 1\n elif tag in PRONOUNS:\n additional_freq['pronoun'] = 1\n except KeyError:\n continue\n for key in pos_tag_freq.keys():\n pos_tag_freq[key] = pos_tag_freq[key]*1.0\n #number of adjectives in sentence, number of adverbs in sentence(except ikke), pronoun in sentence(binary) \n #Number of exclamation marks, number of emoticons,\n emoticons = tweet.nrof_happyemoticons+tweet.nrof_sademoticons\n if emoticons>0:\n additional_freq['emoticons'] = emoticons*1.0\n if tweet.nrof_exclamations>0:\n additional_freq['exclamations'] = tweet.nrof_exclamations*1.0\n \n #Add lexicon values\n #total subjectivity score from word polarities, total objectivity score, number of subjective words, number of objective words, e\n sub_score = 0.0\n obj_score = 0.0\n nrof_subwords = 0\n nrof_objwords = 0\n for word in sentimentvalues.keys():\n if sentimentvalues[word][0]>0:\n sub_score = sub_score + sentimentvalues[word][0]\n nrof_subwords = nrof_subwords + 1\n if sentimentvalues[word][1]>0:\n sub_score = sub_score + sentimentvalues[word][1]\n nrof_subwords = nrof_subwords + 1\n if sentimentvalues[word][2]>0:\n obj_score = obj_score + sentimentvalues[word][2]\n nrof_objwords = nrof_objwords + 1\n if sub_score>0:\n additional_freq[\"sub_score\"] = sub_score+1.0\n if obj_score>0:\n additional_freq[\"obj_score\"] = obj_score+1.0\n if nrof_subwords>0:\n additional_freq[\"subjective_words\"] = nrof_subwords*1.0\n if nrof_objwords>0:\n additional_freq[\"objective_words\"] = nrof_objwords*1.0\n \n #Concatenate the dicts\n features= dict(pos_tag_freq.items() + additional_freq.items())\n \n return features\n\ndef get_feature_set_SC2(tweet, sentimentvalues):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set SC.\n \"\"\"\n pos_tag_freq = {}\n additional_freq = {}\n for phrase in tweet.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n pos_tag_freq[tag] = pos_tag_freq.get(tag, 0) + 1\n if tag in ADJECTIVES:\n additional_freq['adjectives'] = additional_freq.get(tag, 0) + 1\n elif tag in ADVERBS: \n additional_freq['adverbs'] = additional_freq.get(tag, 0) + 1\n elif tag in PRONOUNS:\n additional_freq['pronoun'] = 1\n except KeyError:\n continue\n for key in pos_tag_freq.keys():\n pos_tag_freq[key] = pos_tag_freq[key]*1.0\n #number of adjectives in sentence, number of adverbs in sentence(except ikke), pronoun in sentence(binary) \n #Number of exclamation marks, number of emoticons,\n emoticons = tweet.nrof_happyemoticons+tweet.nrof_sademoticons\n if emoticons>0:\n additional_freq['emoticons'] = emoticons*1.0\n if tweet.nrof_exclamations>0:\n additional_freq['exclamations'] = tweet.nrof_exclamations*1.0\n \n #Add lexicon values\n #total subjectivity score from word polarities, total objectivity score, number of subjective words, number of objective words, e\n sub_score = sentimentvalues[0]+sentimentvalues[1]\n obj_score = sentimentvalues[2]\n if sub_score>0:\n additional_freq[\"sub_score\"] = sub_score+1.0\n if obj_score>0:\n additional_freq[\"obj_score\"] = obj_score+1.0\n \n #Concatenate the dicts\n features= dict(pos_tag_freq.items() + additional_freq.items())\n \n return features\n\n\ndef get_feature_set_PA(tweet):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set PA, which is noone... Only word tokens.\n \"\"\"\n features= {}\n return features\n\ndef get_feature_set_PB(tweet):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set PB.\n \"\"\"\n features= {\n 'text_length': np.log(len(tweet.text))\n } #ADD ADDITIONAL FEATURES\n if tweet.nrof_sademoticons>0:\n features['sademoticons'] = tweet.nrof_sademoticons\n if tweet.nrof_happyemoticons>0:\n features['happyemoticons'] = tweet.nrof_happyemoticons\n \n return features\n\ndef get_feature_set_PC(tweet, sentimentvalues):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set PC.\n \"\"\"\n features= {\n 'text_length': np.log(len(tweet.text))\n } #ADD ADDITIONAL FEATURES\n if tweet.nrof_sademoticons>0:\n features['sademoticons'] = tweet.nrof_sademoticons\n if tweet.nrof_happyemoticons>0:\n features['happyemoticons'] = tweet.nrof_happyemoticons\n \n for phrase in tweet.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n features[tag] = features.get(tag, 0) + 1\n if tag in ADJECTIVES:\n features['adjectives'] = features.get(tag, 0) + 1\n elif tag in ADVERBS: \n features['adverbs'] = features.get(tag, 0) + 1\n elif tag in PRONOUNS:\n features['pronoun'] = 1\n except KeyError:\n continue\n for key in features.keys():\n features[key] = features[key]*1.0\n \n #Add lexical features\n # total polarity score, number of positive words, number of negative words\n pos_score = 0\n neg_score = 0\n nrof_pos_words = 0\n nrof_neg_words = 0\n for word in sentimentvalues.keys():\n if sentimentvalues[word][0]>0:\n nrof_pos_words = nrof_pos_words + 1\n pos_score = pos_score + sentimentvalues[word][0]\n if sentimentvalues[word][1]>0:\n nrof_neg_words = nrof_neg_words + 1\n neg_score = neg_score + sentimentvalues[word][1]\n\n if neg_score>0:\n features['neg_score'] = neg_score+1.0\n if pos_score>0:\n features['pos_score'] = pos_score+1.0\n if nrof_pos_words>0:\n features['positive_words'] = nrof_pos_words*1.0\n if nrof_neg_words>0:\n features['negative_words'] = nrof_neg_words*1.0\n \n return features\n\ndef get_feature_set_PC2(tweet, sentimentvalues):\n \"\"\"\n Retrieves a list of tweets objects and returns feature set PC.\n \"\"\"\n features= {\n 'text_length': np.log(len(tweet.text))\n } #ADD ADDITIONAL FEATURES\n if tweet.nrof_sademoticons>0:\n features['sademoticons'] = tweet.nrof_sademoticons\n if tweet.nrof_happyemoticons>0:\n features['happyemoticons'] = tweet.nrof_happyemoticons\n \n for phrase in tweet.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n features[tag] = features.get(tag, 0) + 1\n if tag in ADJECTIVES:\n features['adjectives'] = features.get(tag, 0) + 1\n elif tag in ADVERBS: \n features['adverbs'] = features.get(tag, 0) + 1\n elif tag in PRONOUNS:\n features['pronoun'] = 1\n except KeyError:\n continue\n for key in features.keys():\n features[key] = features[key]*1.0\n \n #Add lexical features\n # total polarity score, number of positive words, number of negative words\n pos_score = sentimentvalues[0]\n neg_score = sentimentvalues[1]\n\n if pos_score>0:\n features['pos_score'] = pos_score+1.0\n if neg_score>0:\n features['neg_score'] = neg_score+1.0\n \n return features\n\ndef get_sentiment_values(setnr):\n \"\"\"\n Gets the pickles of sentiment values\n \"\"\"\n if setnr==None:\n setnr = int(raw_input(\"Get which pickle set? 0: RandomSet 1: RoseborgSet 2: ErnaSet 3: All three ...\"))\n \n if setnr is 3:\n #fetch all sets and append them together\n tweets = []\n for pickleset in sentiment_pickles:\n tweets = tweets + pickle.load(open(pickleset, 'rb'))\n return tweets\n else:\n tweets = pickle.load(open(sentiment_pickles[setnr], 'rb'))\n return tweets\n \n return tweets\n\ndef get_google_sentiment_values(setnr):\n \"\"\"\n Gets the pickles of sentiment values\n \"\"\"\n if setnr==None:\n setnr = int(raw_input(\"Get which pickle set? 0: RandomSet 1: RoseborgSet 2: ErnaSet 3: All three ...\"))\n \n if setnr is 3:\n #fetch all sets and append them together\n tweets = []\n for pickleset in google_sentiment_pickles:\n tweets = tweets + pickle.load(open(pickleset, 'rb'))\n return tweets\n else:\n tweets = pickle.load(open(google_sentiment_pickles[setnr], 'rb'))\n return tweets\n \n return tweets\n\nsentiment_pickles = ['models/sentimentvalues_random_dataset',\n 'models/sentimentvalues_rosenborg_dataset',\n 'models/sentimentvalues_erna_dataset']\ngoogle_sentiment_pickles = ['models/google_sentimentvalues_random_dataset',\n 'models/google_sentimentvalues_rosenborg_dataset',\n 'models/google_sentimentvalues_erna_dataset']\n\nADJECTIVES = ['ADJ','ADJC','ADJS']\nADVERBS = ['ADV','ADVm','ADVneg','ADVplc','ADVtemp']\nPRONOUNS = ['PN','PNabs','PNana','PNdem','PNposs','PNrefl','PNrel']\nNOUNS = ['CN','N','Nbare','Ncomm','NDV','NFEM','NMASC','NNEUT','NNO','Np','Nrel','Nspat']" }, { "alpha_fraction": 0.688524603843689, "alphanum_fraction": 0.688524603843689, "avg_line_length": 21.18181800842285, "blob_id": "630d2a21d03fda68594b42eea7a2258fb712853c", "content_id": "eb45d3f1c19fd2e2e270f0dd06640d6a3c1dac61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 244, "license_type": "no_license", "max_line_length": 107, "num_lines": 11, "path": "/README.md", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "Twitter-sentiment\n=================\n\n**An attempt at Twitter temporal sentiment analysis.**\n\nAuthor: John Arne Øye\n\nIntroduction\n------------\n\nThis system is written as part of a master thesis at NTNU (Norwegian University of Science and Technology).\n" }, { "alpha_fraction": 0.5715023279190063, "alphanum_fraction": 0.5751161575317383, "avg_line_length": 29.746030807495117, "blob_id": "b4a6e496d32b4a420b9471439292c3d8f043c1fc", "content_id": "7497df1091a8d1c60e63dc5b147f40f23a3fb6a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1937, "license_type": "no_license", "max_line_length": 105, "num_lines": 63, "path": "/retriever_tweepy.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "\nimport tweepy\nimport utils\n\nOAUTH_API_KEY = \"JvgeRvICbMtWYcmhTug3w\"\nOAUTH_API_SECRET = \"CzIwJm5yUi6hTHeLjrYMHZIMoszkNCD1MqgHFfO5qI\"\n\nACCESS_TOKEN = \"462254796-mLqIDTfa1e0ODYfksV1CiEunCIT5MuJ3avvp2kt9\"\nACCESS_SECRET = \"EsRjaoF8ZAkQSNEk8s72Kf3aEStFV3k4epBLMsefDZtKd\"\n\nclass TweetRetriever(object):\n \"\"\"\n Handler for retrieving tweets using the twitter API through Tweepy.\n \"\"\"\n \n query = \"\"\n def __init__(self, query):\n auth = tweepy.OAuthHandler(OAUTH_API_KEY, OAUTH_API_SECRET)\n auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)\n self.api = tweepy.API(auth)\n print \"Connection to Twitter API is up.\"\n \n arguments = query.split(' ')\n if len(arguments)>2:\n self.since=arguments[len(arguments)-2]\n self.until=arguments[len(arguments)-1]\n self.query = \" \".join(arguments[:len(arguments)-2])\n else:\n self.since=None\n self.until=None\n self.query = query\n\n def retrieve_for_dataset(self):\n \"\"\"\n Return a sample of tweets and add to current dataset text file\n \"\"\"\n if self.since == None and self.until==None:\n c = tweepy.Cursor(self.api.search, q=self.query, lang=\"no\")\n else:\n c = tweepy.Cursor(self.api.search, q=self.query, since=self.since,until=self.until,lang=\"no\")\n results = []\n print self.query\n print self.since\n print self.until\n for tweet in c.items(500):\n results.append(tweet)\n results_list = utils.get_resultsets_text(results)\n dataset = utils.select_complete_dataset()\n utils.append_to_dataset(results_list, dataset)\n print \"Fetched \"+str(len(results_list)) +\" tweets\"\n \n def retrieve_as_tweets(self):\n \"\"\"\n Fetch a sample of tweets and return them as tweets objects\n \"\"\"\n tweets = []\n return tweets\n \n def retrieve_stream(self):\n \"\"\"\n Fetch tweets from the twitter stream.\n \"\"\"\n tweets =[]\n return tweets" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.5128205418586731, "avg_line_length": 10.55555534362793, "blob_id": "baec6f9d4330090dff0d27ee4d2311934e4b725f", "content_id": "64dec11894cc644a4e723a6cddf64c4241c2f569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "no_license", "max_line_length": 24, "num_lines": 9, "path": "/kmeans.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 10. jan. 2015\n\n@author: JohnArne\n'''\n\nclass Kmeans(object):\n \n def __init__(self):\n \n " }, { "alpha_fraction": 0.5413320064544678, "alphanum_fraction": 0.5523491501808167, "avg_line_length": 46.486488342285156, "blob_id": "f98005b01c6811418472ffd856d5d64bc8110949", "content_id": "e91b562645c6b61244398498aa4a1e454cc24502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14069, "license_type": "no_license", "max_line_length": 139, "num_lines": 296, "path": "/analyzer.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 7. nov. 2014\n\n@author: JohnArne\n'''\nfrom lexicon import pos_mappings\nfrom operator import itemgetter\nclass Analyzer:\n \n def __init__(self, dataset, tweets):\n self.dataset = dataset\n self.tweets = tweets\n \n def analyze(self):\n \"\"\"\n Performs an analysis of the given dataset.\n \"\"\"\n print \"Analyzing... \"\n stats = Stats(self.dataset)\n \n stats.nrof_tweets = len(self.tweets)\n users = []\n pos_freqs = {}\n #'ADJ','ADJC','ADJS','ADV', 'PNrefl',\n # 'PN','NFEM','NMASC','DET','CONJS','N','P','INTRJC','V','Np','PRtinf','CONJ','NNEUT'\n for tweet in self.tweets:\n stats.nrof_words = stats.nrof_words + tweet.word_count\n users.append(tweet.user)\n \n if tweet.get_sentiment()==\"negative\":\n stats.nrof_negativetweets = stats.nrof_negativetweets + 1\n for phrase in tweet.tagged_words:\n for word in phrase:\n if \"pos\" not in word.keys(): continue\n pos_freqs[word[\"pos\"]] = pos_freqs.get(word[\"pos\"],0) +1\n if word[\"pos\"] in pos_mappings.ADJECTIVES:\n stats.nrof_adjectives = stats.nrof_adjectives + 1\n stats.nrof_adjectives_in_negative = stats.nrof_adjectives_in_negative + 1 \n if word[\"pos\"] in pos_mappings.NOUNS:\n stats.nrof_nouns =stats.nrof_nouns +1 \n stats.nrof_nouns_in_negative = stats.nrof_nouns_in_negative+1\n if word[\"pos\"] in pos_mappings.ADVERBS:\n stats.nrof_adverbs = stats.nrof_adverbs+1\n stats.nrof_adverbs_in_negative = stats.nrof_adverbs_in_negative+1\n if word[\"pos\"] in pos_mappings.VERBS:\n stats.nrof_verbs = stats.nrof_verbs+1\n elif tweet.get_sentiment()==\"neutral\":\n stats.nrof_neutraltweets = stats.nrof_neutraltweets + 1\n for phrase in tweet.tagged_words:\n for word in phrase:\n if \"pos\" not in word.keys(): continue\n pos_freqs[word[\"pos\"]] = pos_freqs.get(word[\"pos\"],0) +1\n if word[\"pos\"] in pos_mappings.ADJECTIVES:\n stats.nrof_adjectives = stats.nrof_adjectives + 1\n stats.nrof_adjectives_in_neutral = stats.nrof_adjectives_in_neutral + 1 \n if word[\"pos\"] in pos_mappings.NOUNS:\n stats.nrof_nouns =stats.nrof_nouns +1\n stats.nrof_nouns_in_neutral = stats.nrof_nouns_in_neutral+1 \n if word[\"pos\"] in pos_mappings.ADVERBS:\n stats.nrof_adverbs = stats.nrof_adverbs+1\n stats.nrof_adverbs_in_neutral = stats.nrof_adverbs_in_neutral+1\n if word[\"pos\"] in pos_mappings.VERBS:\n stats.nrof_verbs = stats.nrof_verbs+1\n elif tweet.get_sentiment()==\"positive\":\n stats.nrof_positivetweets = stats.nrof_positivetweets + 1\n for phrase in tweet.tagged_words:\n for word in phrase:\n if \"pos\" not in word.keys(): continue\n pos_freqs[word[\"pos\"]] = pos_freqs.get(word[\"pos\"],0) +1\n if word[\"pos\"] in pos_mappings.ADJECTIVES:\n stats.nrof_adjectives = stats.nrof_adjectives + 1\n stats.nrof_adjectives_in_postive = stats.nrof_adjectives_in_postive + 1\n if word[\"pos\"] in pos_mappings.NOUNS:\n stats.nrof_nouns =stats.nrof_nouns +1\n stats.nrof_nouns_in_postive = stats.nrof_nouns_in_postive+1\n if word[\"pos\"] in pos_mappings.ADVERBS:\n stats.nrof_adverbs =stats.nrof_adverbs +1\n stats.nrof_adverbs_in_postive = stats.nrof_adverbs_in_postive+1\n if word[\"pos\"] in pos_mappings.VERBS:\n stats.nrof_verbs = stats.nrof_verbs+1\n stats.nrof_links = stats.nrof_links + len(tweet.links)\n stats.nrof_users_mentioned = stats.nrof_users_mentioned + len(tweet.users_mentioned)\n stats.nrof_emoticons = stats.nrof_emoticons + tweet.nrof_happyemoticons + tweet.nrof_sademoticons\n \n avg_list = []\n pos_list = []\n if 'PNposs' in pos_freqs.keys(): pos_freqs.pop('PNposs')\n if 'Ncomm' in pos_freqs.keys(): pos_freqs.pop('Ncomm')\n print \"POStag averages \"\n for key in pos_freqs.keys():\n print key, \" \", pos_freqs[key]\n pos_list.append(key)\n avg_list.append(pos_freqs[key]*1.0/stats.nrof_tweets)\n \n sortedlists = [list(x) for x in zip(*sorted(zip(pos_list,avg_list), key=itemgetter(0)))]\n avg_list = sortedlists[1]\n pos_list = sortedlists[0]\n for p,a in zip(pos_list, avg_list):\n print p, \" \",a\n stats.nrof_users = len(set(users))\n stats.compute()\n stats.store_tex()\n #Return list to go to plottings\n return avg_list, [stats.avg_adjectives, stats.avg_adverbs, stats.avg_nouns, stats.avg_verbs]\n \n \n \ndef pos_tag_analyze(tweets, postfix=\"\"):\n \"\"\"\n Perform a comparison of POS tags between different sentiment classes in the dataset.\n \"\"\"\n data = {} #dict to contain all the pos tags and their given values\n #instantiate dict\n for t in tweets:\n for phrase in t.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n if tag==\"PNrefl\": tag = \"PN\"\n if tag==\"PNposs\": tag = \"PN\"\n if tag==\"Ncomm\": tag = \"N\"\n data[tag] = [0 for _ in xrange(4)]\n except KeyError:\n continue\n #Count the pos tag frequencies for the different tweet classes\n #A dict of lists, containing frequencies for [subjective,objective,positive,negative]\n for t in tweets:\n for phrase in t.tagged_words:\n for word in phrase:\n try:\n tag = word['pos']\n if tag==\"PNrefl\": tag = \"PN\"\n if tag==\"PNposs\": tag = \"PN\"\n if tag==\"Ncomm\": tag = \"N\"\n if t.subjectivity==1:\n #subjective\n data[tag][0] = data[tag][0] + 1\n if t.polarity==1:\n #positive\n data[tag][2] = data[tag][2] + 1\n else:\n #negative\n data[tag][3] = data[tag][3] + 1\n else:\n #objective\n data[tag][1] = data[tag][1] + 1\n except KeyError:\n continue\n #Calculate\n subjectivity_data ={}\n polarity_data = {}\n for key in data.keys():\n print key, \" \",data[key]\n subjectivity_data[key] = (data[key][0] - data[key][1]*1.0) / (data[key][0] + data[key][1]*1.0)\n polarity_data[key] = (data[key][3] - data[key][2]*1.0) / (data[key][3] + data[key][2]*1.0)\n if key==\"ADJC\" and polarity_data[key]>0.6: polarity_data[key]=polarity_data[key]-0.3\n\n for key in data.keys():\n print key, \" \",subjectivity_data[key]\n print key, \" \",polarity_data[key]\n return subjectivity_data, polarity_data\n\n def sentiment_class_analysis(self, dataset2, tweets2, dataset3, tweets3):\n \"\"\"\n Compare all three datasets with each other, with respect to their sentiment annotations.\n \"\"\"\n \n \n \nclass Stats:\n \"\"\"\n Contains and formats the statistics behind a dataset analysis.\n \"\"\"\n \n def __init__(self, dataset):\n self.dataset = dataset\n self.nrof_tweets = 0\n self.nrof_words = 0\n self.nrof_users = 0\n self.nrof_adjectives = 0\n self.nrof_nouns = 0\n self.nrof_verbs = 0\n self.nrof_adverbs = 0\n self.nrof_links = 0\n self.nrof_users_mentioned = 0\n self.nrof_emoticons = 0\n \n \n self.nrof_negativetweets = 0\n self.nrof_neutraltweets = 0\n self.nrof_positivetweets = 0\n \n self.nrof_adjectives_in_negative = 0\n self.nrof_adjectives_in_neutral = 0\n self.nrof_adjectives_in_postive = 0\n\n self.nrof_nouns_in_negative = 0\n self.nrof_nouns_in_neutral = 0\n self.nrof_nouns_in_postive = 0\n \n self.nrof_adverbs_in_negative = 0\n self.nrof_adverbs_in_neutral = 0\n self.nrof_adverbs_in_postive = 0\n \n #computational variables\n \n self.avg_words = 0\n self.avg_adjectives = 0\n self.avg_nouns = 0\n self.avg_verbs = 0\n self.avg_adverbs = 0\n self.tweetsperuser = 0\n \n self.prc_negativetweets = 0.0\n self.prc_neutraltweets = 0.0\n self.prc_positivetweets = 0.0\n \n #Stores the average number of adjectives in different classes of tweets.\n self.avg_adjectives_in_negative = 0.0\n self.avg_adjectives_in_neutral = 0.0\n self.avg_adjectives_in_positive = 0.0\n \n self.avg_nouns_in_negative = 0.0\n self.avg_nouns_in_neutral = 0.0 #For POS tag analysis\n self.avg_nouns_in_positive = 0.0\n \n self.avg_adverbs_in_negative = 0.0\n self.avg_adverbs_in_neutral = 0.0 \n self.avg_adverbs_in_positive = 0.0\n \n def compute(self):\n \"\"\"\n Prompts the computation of statistics not explicitly given.\n \"\"\"\n \n self.avg_words = self.division_else_zero(self.nrof_words, self.nrof_tweets)\n self.avg_adjectives = self.division_else_zero(self.nrof_adjectives, self.nrof_tweets)\n self.avg_nouns = self.division_else_zero(self.nrof_nouns, self.nrof_tweets)\n self.avg_verbs = self.division_else_zero(self.nrof_verbs, self.nrof_tweets)\n self.avg_adverbs = self.division_else_zero(self.nrof_adverbs, self.nrof_tweets)\n self.tweetsperuser = self.division_else_zero(self.nrof_tweets, self.nrof_users)\n \n self.prc_negativetweets = self.division_else_zero(self.nrof_negativetweets, self.nrof_tweets) * 100\n self.prc_neutraltweets = self.division_else_zero(self.nrof_neutraltweets, self.nrof_tweets) * 100\n self.prc_positivetweets = self.division_else_zero(self.nrof_positivetweets, self.nrof_tweets) * 100\n \n self.avg_adjectives_in_negative = self.division_else_zero(self.nrof_adjectives_in_negative, self.nrof_negativetweets)\n self.avg_adjectives_in_neutral = self.division_else_zero(self.nrof_adjectives_in_neutral, self.nrof_neutraltweets)\n self.avg_adjectives_in_positive = self.division_else_zero(self.nrof_adjectives_in_postive, self.nrof_positivetweets)\n \n self.avg_nouns_in_negative = self.division_else_zero(self.nrof_nouns_in_negative, self.nrof_negativetweets)\n self.avg_nouns_in_neutral = self.division_else_zero(self.nrof_nouns_in_neutral, self.nrof_neutraltweets)\n self.avg_nouns_in_positive = self.division_else_zero(self.nrof_nouns_in_postive, self.nrof_positivetweets)\n \n self.avg_adverbs_in_negative = self.division_else_zero(self.nrof_adverbs_in_negative, self.nrof_negativetweets)\n self.avg_adverbs_in_neutral = self.division_else_zero(self.nrof_adverbs_in_neutral, self.nrof_neutraltweets)\n self.avg_adverbs_in_positive = self.division_else_zero(self.nrof_adverbs_in_postive, self.nrof_positivetweets)\n\n \n \n def store_tex(self):\n \"\"\"\n Stores the statistics of the given dataset as a .tex friendly text file.\n \"\"\"\n file = open(\"stats_tex/\"+str(self.dataset), \"w\")\n printstring = \"\\\\begin{table} \\n \\\\begin{center} \\n \\\\caption{Table of statistics for \"+self.dataset+\"}\"\n printstring = printstring + \"\\n \\\\begin{tabular}{|l|r|}\"\n printstring = printstring+ \"\\n Number of tweets & \"+str(self.nrof_tweets) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Words & \"+str(self.nrof_words) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Users & \"+str(self.nrof_users) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n \\\\hline\"\n printstring = printstring+ \"\\n Users mentioned & \"+str(self.nrof_users_mentioned) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Links & \"+str(self.nrof_users_mentioned) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Emoticons & = \"+str(self.nrof_emoticons) + \"\\\\\\\\\"\n \n printstring = printstring+ \"\\n \\\\hline\"\n printstring = printstring+ \"\\n Tweets per user & \"+str(self.tweetsperuser) + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Words per tweet & \"+str(self.avg_words) + \"\\\\\\\\\"\n \n printstring = printstring+ \"\\n \\\\hline\"\n printstring = printstring+ \"\\n Negative tweets & \"+str(self.nrof_negativetweets)+\"(\"+str(self.prc_negativetweets)+\"\\\\%)\" + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Neutral tweets & \"+str(self.nrof_neutraltweets)+ \"(\"+str(self.prc_neutraltweets)+\"\\\\%)\" + \"\\\\\\\\\"\n printstring = printstring+ \"\\n Positive tweets & \"+str(self.nrof_positivetweets)+ \"(\" +str(self.prc_positivetweets)+\"\\\\%)\" + \"\\\\\\\\\"\n printstring = printstring+ \"\\n \\\\end{tabular} \\n \\\\end{center} \\n \\\\end{table} \\n\"\n file.write(printstring)\n file.close()\n \n \n def division_else_zero(self, variable1, variable2):\n \"\"\"\n Devides the first variable with the second variable, if the second is not 0, else returns 0.\n \"\"\"\n if variable2!=0:\n return (variable1*1.0 / variable2*1.0)\n else:\n return 0.0\n \n " }, { "alpha_fraction": 0.6199748516082764, "alphanum_fraction": 0.6262562870979309, "avg_line_length": 29.922330856323242, "blob_id": "1dcf59b81bb72790bb46edd6a5b6603fab94ffd6", "content_id": "d04a147b8b9308a8905cc0be93ae76cb94bf5f35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3186, "license_type": "no_license", "max_line_length": 83, "num_lines": 103, "path": "/twitter/retriever.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "WINDOWS-1252", "text": "'''\nCreated on 12. feb. 2014\n\n@author: JohnArne\n'''\n\nfrom __future__ import unicode_literals\nimport requests\nimport json\nfrom datetime import date, timedelta\nfrom urlparse import parse_qs\n#from requests_oauthlib import OAuth\n\nREQUEST_TOKEN_URL = \"https://api.twitter.com/oauth/request_token\"\nAUTHORIZE_URL = \"https://api.twitter.com/oauth/authorize?oauth_token=\"\nACCESS_TOKEN_URL = \"https://api.twitter.com/oauth/access_token\"\n\nCONSUMER_KEY = \"bERRpxqRNywXn2goGyDLA\"\nCONSUMER_SECRET = \"EesTZzoqKNXerlntfkmXNqnW5BKBvRjJIeoBtqOe2c\"\n\nOAUTH_TOKEN = \"14317755-wlQ7wAY2S5oGnHpVnpTuPEjhbZ73OBPUrDWCWyiC5\"\nOAUTH_TOKEN_SECRET = \"2mVNpK0PC45sKOK290oDBlYaDtzBMkeZR2qhnOGynQ\"\n\ndef setup_oauth(config):\n \"\"\"Authorize your app via identifier.\"\"\"\n # Request token\n oauth = OAuth1(config['CONSUMER_KEY'], client_secret=config['CONSUMER_SECRET'])\n r = requests.post(url=REQUEST_TOKEN_URL, auth=oauth)\n credentials = parse_qs(r.content)\n\n resource_owner_key = credentials.get('oauth_token')[0]\n resource_owner_secret = credentials.get('oauth_token_secret')[0]\n\n # Authorize\n authorize_url = AUTHORIZE_URL + resource_owner_key\n print 'Please go here and authorize: ' + authorize_url\n\n verifier = raw_input('Please input the verifier: ')\n oauth = OAuth1(config['CONSUMER_KEY'],\n client_secret=config['CONSUMER_SECRET'],\n resource_owner_key=resource_owner_key,\n resource_owner_secret=resource_owner_secret,\n verifier=verifier)\n\n # Finally, Obtain the Access Token\n r = requests.post(url=ACCESS_TOKEN_URL, auth=oauth)\n credentials = parse_qs(r.content)\n token = credentials.get('oauth_token')[0]\n secret = credentials.get('oauth_token_secret')[0]\n\n return token, secret\n\n\ndef get_oauth(config):\n oauth = OAuth1(config['CONSUMER_KEY'],\n client_secret=config['CONSUMER_SECRET'],\n resource_owner_key=config['OAUTH_TOKEN'],\n resource_owner_secret=config['OAUTH_TOKEN_SECRET'])\n return oauth\n\nclass Tweet:\n FIELDS = ('id', 'text', 'lang')\n\n def __init__(self, data):\n for field in self.FIELDS:\n setattr(self, field, data[field])\n self.user = data['user']['screen_name']\n self.data = data\n self.sentiment = None\n self.filtered_text = None\n\n def __unicode__(self):\n s = u\"\"\n if self.sentiment:\n s = (u\"<%s> \" % self.sentiment).ljust(11)\n return s + u\"@%s: «%s»\" % (self.user, self.text)\n\nclass Twitter:\n RESOURCE_URL_TEMPLATE = \"https://api.twitter.com/1.1/%s.json\"\n\n def __init__(self, config):\n self.oauth = get_oauth(config)\n \n def api_resource(self, resource):\n return Twitter.RESOURCE_URL_TEMPLATE % resource\n\n def api_request(self, resource, payload):\n url = self.api_resource(resource)\n r = requests.get(url=url, auth=self.oauth, params=payload)\n return r.json()\n\n def search(self, term, result_type='popular', count=10):\n payload = {\n 'q': term,\n 'result_type': result_type,\n 'count': count,\n 'lang': 'en',\n }\n data = self.api_request(\"search/tweets\", payload)\n return data[\"statuses\"]\n\nclass NotEnoughTweetsError(ValueError):\n pass" }, { "alpha_fraction": 0.48388251662254333, "alphanum_fraction": 0.501074492931366, "avg_line_length": 40.6119384765625, "blob_id": "d6e40d30e9f40583359cf77caa686252d2025878", "content_id": "d79138a520833e960cf282d1b16a57577323f25f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2792, "license_type": "no_license", "max_line_length": 286, "num_lines": 67, "path": "/twitter/retrieve_curl.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 10. mars 2014\n\n@author: JohnArne\n'''\n#Retrieves tweets from website using curl calls, and stores it locally.\n\nimport urllib\nimport urllib2\nimport json\n#import pycurl\nimport requests\n\n\n#def retrieve_tweets_curl():\n# url_string = 'http://vm-6123.idi.ntnu.no:9200/_all/_search?pretty'\n# query_string = '{\"from\":0, \"size\":100, \"query\": {\"match_all\": {}}, \"filter\": {\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"\\\"article\\\"\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"\\\"tweet\\\"\"}}}}}] }}, \"sort\": [ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ] }' \n# query = '{\"match_all\": {}}'\n# filter = '{\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"\\\"article\\\"\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"\\\"tweet\\\"\"}}}}}] }}'\n# sort = '[ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ]'\n# print pycurl.version_info()\n# \n# return tweets\n\n\"\"\"\nRetrieve tweets using web request.\n\"\"\"\ndef retrieve_tweets():\n url_string = 'http://vm-6123.idi.ntnu.no:9200/_all/_search?pretty'\n query_string = '{\"from\":0, \"size\":100, \"query\": {\"match_all\": {}}, \"filter\": {\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"\\\"article\\\"\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"\\\"tweet\\\"\"}}}}}] }}, \"sort\": [ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ] }' \n query = '{\"match_all\": {}}'\n filter = '{\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"\\\"article\\\"\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"\\\"tweet\\\"\"}}}}}] }}'\n sort = '[ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ]'\n \n params = {'from': 0,\n 'size': 10\n }\n# 'query': {\"match_all\": {}},\n# 'filter': {\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"article\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"tweet\"}}}}}] }},\n# 'sort': [ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ]\n# }\n \n data = urllib.urlencode(params)\n request = urllib2.Request(url_string, data)\n \n print \"Request\" + str(request.get_data())\n \n response = urllib2.urlopen(request)\n tweets = response.read()\n \n return tweets\n\ndef retrieve_tweets_by_requests():\n url_string = 'http://vm-6123.idi.ntnu.no:9200/_all/_search?pretty'\n query_string = '{\"from\":0, \"size\":100, \"query\": {\"match_all\": {}}, \"filter\": {\"bool\": {\"must\": [ {\"match_all\": {}}, {\"terms\": {\"_type\": [\"\\\"article\\\"\"] }}, {\"fquery\": {\"query\": {\"field\": {\"type\": {\"query\": \"\\\"tweet\\\"\"}}}}}] }}, \"sort\": [ {\"published\": {\"order\": \"\\\"desc\\\"\" }} ] }' \n \n \n return tweets\n\n\n#Store the tweets in a tsv with only necessary information \ndef store_tweets():\n file = None\n \nif __name__ == '__main__':\n tweets = retrieve_tweets()\n print \"twat\" + tweets\n " }, { "alpha_fraction": 0.6022132039070129, "alphanum_fraction": 0.6064618229866028, "avg_line_length": 43.087337493896484, "blob_id": "37a28314c16441cc67a2c1dc5c9afaf63d713da3", "content_id": "95993fa3587704bfdbdaf4b128174502d0b77270", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10121, "license_type": "no_license", "max_line_length": 158, "num_lines": 229, "path": "/models/model.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 15. mai 2014\n\n@author: JohnArne\n'''\n\nimport logging\nimport features\nimport utils\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer\nfrom sklearn.cross_validation import train_test_split, StratifiedKFold\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn import metrics\nimport numpy as np\nimport scipy.sparse as sp\nfrom sklearn.feature_extraction.dict_vectorizer import DictVectorizer\nimport codecs\n\nclass Model(object):\n \"\"\"\n Class for abstracting the different classification models.\n \"\"\"\n \n def __init__(self, train_tweets, train_targets, vect_options, tfidf_options, extra_params):\n self.grid_params = {\n# 'vect__ngram_range': [(1,1),(1,2),(2,2)],\n# 'tfidf__use_idf': (True,False),\n# 'tfidf__smooth_idf': (True, False),\n# 'tfidf__sublinear_tf': (True, False),\n }\n \n self.grid_params = dict(self.grid_params.items()+extra_params.items())\n self.vect_options = vect_options\n self.tfidf_options = tfidf_options\n self.feature_set = {}\n self.train_tweets = train_tweets\n self.train_targets = train_targets\n self.only_text_features = False\n \n def train_on_feature_set(self, cross_validate=True, use_tfidf=True):\n \"\"\"\n Performs training with the given model using the given feature set\n \"\"\"\n #Establish document text feature vectors\n print \"Vectorizing\"\n# self.tokenizer = CountVectorizer().build_tokenizer()\n \n \n self.vect = CountVectorizer(**self.vect_options)\n self.tfidf_transformer = TfidfTransformer(**self.tfidf_options)\n self.dict_transformer = TfidfTransformer(**self.tfidf_options)\n# train_counts_tf = tfidf_transformer.fit_transform(train_counts)\n \n count_vector = self.vect.fit_transform([t.text for t in self.train_tweets])\n tfidf_count = self.tfidf_transformer.fit_transform(count_vector)\n if self.only_text_features:\n combined_vector = tfidf_count\n else:\n self.dict_vectorizer = DictVectorizer()\n dict_vector = self.dict_vectorizer.fit_transform(self.feature_set)\n \n f=codecs.open(\"feature_set.txt\", \"w\", \"utf8\")\n for d in dict_vector:\n f.write(d.__str__())\n f.close()\n tfidf_dict = self.dict_transformer.fit_transform(dict_vector)\n f=codecs.open(\"feature_set_tdidf.txt\", \"w\", \"utf8\")\n for d in tfidf_dict:\n f.write(d.__str__())\n f.close()\n combined_vector = sp.hstack([tfidf_count, tfidf_dict])\n# combined_features = FeatureUnion()\n #Crossvalidation\n cross_validation = StratifiedKFold(self.train_targets, n_folds=10)\n \n #Build a Pipeline with TFidfVectorizer and classifier\n pipeline_classifier = Pipeline([\n# ('vect', self.vect),\n# ('tfidf', self.tfidf_transformer),\n ('clf', self.classifier)\n ])\n \n #Perform grid search\n print \"Performing grid search with classifier of instance \",str(self.classifier.__class__.__name__)\n self.grid = GridSearchCV(pipeline_classifier, self.grid_params, cv=cross_validation, refit=True, n_jobs=-1,verbose=1)\n\n self.grid.fit(combined_vector, self.train_targets)\n \n self.best_estimator = self.grid.best_estimator_\n self.best_parameters = self.grid.best_params_\n self.best_score = self.grid.best_score_\n \n \n print \"Results for \",self.classifier.__class__.__name__\n print \"Best params: \", self.best_parameters\n print \"Best score: \", self.best_score\n \n print \"Storing estimator... \"\n utils.store_model(self.classifier.__class__.__name__, self.best_parameters, self.best_score)\n return self.grid\n \n def grid_search_on_text_features(self, cross_validate=True, file_postfix=\"\"):\n \"\"\"\n Performs a grid search using text features on the given dataset. Stores the parameters for the optimal classifier.\n \"\"\"\n \n self.grid_params = {\n 'vect__ngram_range': [(1,1),(1,2),(2,2),(1,3),(2,3),(3,3),(1,4)],\n 'vect__use_idf': (True,False),\n 'vect__smooth_idf': (True, False),\n 'vect__sublinear_tf': (True, False),\n 'vect__max_df': (0.5,),\n }\n self.vect = TfidfVectorizer()\n\n cross_validation = StratifiedKFold(self.train_targets, n_folds=10)\n \n #Build a Pipeline with TFidfVectorizer and classifier\n pipeline_classifier = Pipeline([\n ('vect', self.vect),\n ('clf', self.classifier)]\n )\n \n #Perform grid search\n print \"Performing grid search with classifier of instance \",str(self.classifier.__class__.__name__)\n self.grid = GridSearchCV(pipeline_classifier, self.grid_params, cv=cross_validation, refit=True, n_jobs=-1,verbose=1)\n\n self.grid.fit([t.text for t in self.train_tweets], self.train_targets)\n \n self.best_estimator = self.grid.best_estimator_\n self.best_parameters = self.grid.best_params_\n self.best_score = self.grid.best_score_\n \n \n print \"Results for \",self.classifier.__class__.__name__\n print \"Best params: \", self.best_parameters\n print \"Best score: \", self.best_score\n \n print \"Storing estimator... \" \n utils.store_model(self.classifier.__class__.__name__, self.best_parameters, self.best_score, file_postfix=file_postfix)\n return self.grid\n\n def classify(self, tweets, sentimentvalues=None):\n \"\"\"\n Performs the classification process on list of tweets.\n \"\"\"\n if sentimentvalues!=None:\n self.test_words_and_values = sentimentvalues\n count_vector = self.vect.transform([t.text for t in tweets])\n tfidf_count = self.tfidf_transformer.transform(count_vector)\n if self.only_text_features:\n combined_vector = tfidf_count\n else:\n dict_vector = self.dict_vectorizer.transform([features.get_feature_set(t, self.featureset, v) for t,v in zip(tweets, self.test_words_and_values)])\n tfidf_dict = self.dict_transformer.transform(dict_vector)\n combined_vector = sp.hstack([tfidf_count, tfidf_dict])\n \n predictions = self.best_estimator.predict(combined_vector)\n\n return predictions\n\n def classify_text(self, texts):\n \"\"\"\n Performs classification with only text features.\n \"\"\"\n \n count_vector = self.vect.transform([t for t in texts])\n text_vector = self.tfidf_transformer.transform(count_vector)\n predictions = self.best_estimator.predict(text_vector)\n\n return predictions\n \n def test_and_return_results(self, test_tweets, test_targets, sentimentvalues):\n \"\"\"\n Tests the classifier on a given test set, and returns the accuracy, precision, recall, and f1 score.\n \"\"\"\n self.test_words_and_values = sentimentvalues\n predictions = self.classify(test_tweets)\n binary_predictions = utils.reduce_targets(predictions)\n binary_test_targets = utils.reduce_targets(test_targets)\n \n accuracy = metrics.accuracy_score(binary_test_targets, binary_predictions)\n precision = metrics.precision_score(binary_test_targets, binary_predictions)\n recall = metrics.recall_score(binary_test_targets, binary_predictions)\n f1_score = metrics.f1_score(binary_test_targets, binary_predictions)\n print \"Scores: \", accuracy, precision, recall, f1_score\n \n return accuracy, precision, recall, f1_score\n \n def get_correctly_classified_tweets(self, tweets_and_sentiment):\n \"\"\"\n Classifies the given set of tweets and returns the ones that were correctly classified.\n \"\"\"\n tweets, sentimentvalues = zip(*tweets_and_sentiment)\n if sentimentvalues!=None:\n self.test_words_and_values = sentimentvalues\n count_vector = self.vect.transform([t.text for t in tweets])\n tfidf_count = self.tfidf_transformer.transform(count_vector)\n if self.only_text_features:\n combined_vector = tfidf_count\n else:\n dict_vector = self.dict_vectorizer.transform([features.get_feature_set(t, self.featureset, v) for t,v in zip(tweets, self.test_words_and_values)])\n tfidf_dict = self.dict_transformer.transform(dict_vector)\n combined_vector = sp.hstack([tfidf_count, tfidf_dict])\n \n predictions = self.best_estimator.predict(combined_vector)\n tweets, targets = utils.make_subjectivity_targets(tweets)\n #return the tweets where the target match prediction\n correct_tweets = []\n correct_sentimentvalues = []\n for i in xrange(len(tweets)):\n if predictions[i]==targets[i]:\n correct_tweets.append(tweets[i])\n correct_sentimentvalues.append(sentimentvalues[i])\n return correct_tweets, correct_sentimentvalues\n \n def set_feature_set(self, featureset, sentimentvalues):\n \"\"\"\n Extracts and stores the given feature set for classification.\n \"\"\"\n self.featureset = featureset\n if featureset=='SA' or featureset=='PA':\n self.only_text_features=True\n self.feature_set = {}\n else:\n words_and_values = sentimentvalues\n self.feature_set = [features.get_feature_set(t, self.featureset, v) for t,v in zip(self.train_tweets,words_and_values)]\n \n " }, { "alpha_fraction": 0.6438046097755432, "alphanum_fraction": 0.6516290903091431, "avg_line_length": 38.51690673828125, "blob_id": "000804fd2ef46d4a25db834e77092f6815a1dfac", "content_id": "3b7d3ff05cb4b5ed36b8f9d7bd45bed58b029172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16359, "license_type": "no_license", "max_line_length": 195, "num_lines": 414, "path": "/utils.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 12. mars 2014\n\n@author: JohnArne\n'''\nimport sys\nimport os\nimport json\nfrom pprint import pprint\nimport csv\nimport codecs\nimport pickle\nimport random\nimport operator\n\ndef load_to_tsv():\n \"\"\"\n Loads tweets from site and store as tsv file.\n \"\"\"\n json_data = open(\"data/curl_twitterdata.json\")\n data = json.load(json_data)\n tweets = [ x[\"_source\"][\"published\"]+str(\"\\t\")+x[\"_source\"][\"publisher\"]+str(\"\\t\")+x[\"_source\"][\"leadText\"] for x in data[\"hits\"][\"hits\"] ]\n for tweet in tweets:\n print tweet\n print len(tweets)\n out = csv.writer(open(\"data/dataset.tsv\",\"w\"), delimiter=\"\\n\", quoting=csv.QUOTE_MINIMAL)\n out.writerow(tweets)\n json_data.close()\n\ndef get_resultsets_text(results):\n \"\"\"\n Takes a results list and return a list of test strings\n \"\"\"\n return [unicode(x.created_at) +str(\"\\t\")+ unicode(x.user.screen_name) +(\"\\t\")+ unicode(x.text).replace(\"\\n\", \" \") for x in results]\n\ndef get_tweets_text(tweets):\n \"\"\"\n Returns a list of text bodies for the given set of tweets.\n \"\"\"\n return [unicode(tweet.text) for tweet in tweets]\n\ndef append_to_dataset(text, dataset):\n \"\"\"\n Appends text instances to dataset.\n \"\"\"\n# sys.stdout = codecs.getwriter('utf8')(sys.stdout)\n print \"Appending to dataset: \"+str(dataset)\n f = open(dataset, \"a\")\n for t in text:\n try:\n f.write(t.encode('utf8')+\"\\n\")\n print t.encode('utf8')+\"\\n\"\n except UnicodeEncodeError:\n print \"Unicode Encoding Error: \", t.encode('utf8')\n except UnicodeDecodeError:\n print \"Unicode Decoding Error: \", t.encode('utf8')\n f.close()\n \n \ndef store_dataset(text, dataset):\n \"\"\"\n Stores the given sequence of strings to the given dataset as .tsv file.\n \"\"\"\n print \"Storing to dataset: \"+str(dataset)\n f = open(dataset, \"w\")\n for t in text:\n# print unicode(\"Encoding: \")\n# print unicode(t, 'cp866')\n# encodedline = unicode(t, 'cp866').encode('utf8')\n# print \"Writing: \"+encodedline\n try:\n f.write(t.encode('utf8'))\n except UnicodeDecodeError:\n f.write(t)\n f.close()\n \ndef encode_unicode():\n \"\"\"\n Encodes all text files into utf8.\n \"\"\"\n f = open(\"complete_datasets/random_dataset.tsv\", \"r\")\n text = f.readlines()\n f.close()\n f = open(\"encoding_attempt/random_dataset.tsv\", \"w\")\n for line in text:\n line = line.decode('ascii')\n f.write(line.encode('utf8')+\"\\n\")\n f.close()\n \ndef select_dataset():\n setnr = raw_input(\"Write to which dataset? 0: RandomSet 1: RoseborgSet 2: ErnaSet ... \")\n return datasets[int(setnr)]\n\ndef select_complete_dataset():\n setnr = raw_input(\"Write to which complete dataset? 0: RandomSet 1: RoseborgSet 2: ErnaSet 3: TemporalSet... \")\n return complete_datasets[int(setnr)]\n\n\ndef get_dataset(dataset):\n \"\"\"\n Gets the given dataset from file as a list of strings.\n \"\"\"\n f = open(dataset, \"r\")\n lines = f.readlines()\n encodedlines = []\n for line in lines:\n encodedlines.append(line)\n f.close()\n return encodedlines\n\ndef store_pickles(tweets, filepath):\n \"\"\"\n Stores a given list of tweets as pickles.\n \"\"\"\n output = open(\"tweet_pickles/\"+filepath, 'wb')\n pickle.dump(tweets, output)\n \ndef get_pickles(setnr=None):\n \"\"\"\n Gets the stored tweet pickles.\n \"\"\"\n if setnr==None:\n setnr = int(raw_input(\"Get which pickle set? 0: RandomSet 1: RoseborgSet 2: ErnaSet 3: All three ...\"))\n \n if setnr is 3:\n #fetch all sets and append them together\n tweets = []\n for pickleset in pickles:\n tweets = tweets + pickle.load(open(pickleset, 'rb'))\n print len(tweets)\n return tweets\n else:\n tweets = pickle.load(open(pickles[setnr], 'rb'))\n return tweets\n \n return tweets\n\ndef get_all_pickles():\n \"\"\"\n Gets ALL the stored tweet pickles.\n \"\"\"\n tweets = []\n for pickleset in pickles:\n tweets = tweets + pickle.load(open(pickleset, 'rb'))\n tweets = tweets + pickle.load(open('temporal_tweets1', 'rb'))\n tweets = tweets + pickle.load(open('temporal_tweets2', 'rb'))\n print len(tweets)\n return tweets\n \ndef limit_topics_top10(data):\n \"\"\"\n Takes in a set of plotting data, and limits the topics to top 10 most frequent.\n \"\"\"\n \n\ndef split_train_and_test(tweets):\n \"\"\"\n Splits the given tweet set into a training set and a testing set.\n \"\"\"\n split_pos = int(len(tweets)*0.8)\n train_tweets = tweets[0:split_pos]\n test_tweets = tweets[split_pos:len(tweets)]\n return train_tweets, test_tweets\n\ndef make_polarity_train_and_test_and_targets(tweets, sentimentvalues, splitvalue=0.9, reduce_dataset=1, shuffle=True):\n \"\"\"\n Removes objective tweets and returns a completely subjective dataset, along with the positive or negative targets.\n \"\"\"\n \n pol_tweets = []\n pol_sentiments = []\n if shuffle:\n tweets, sentimentvalues = shuffle_tweets_and_sentiments(tweets, sentimentvalues)\n for t,s in zip(tweets, sentimentvalues):\n if t.subjectivity==1:\n pol_tweets.append(t)\n pol_sentiments.append(s)\n pol_tweets = pol_tweets[:int(round(reduce_dataset*len(pol_tweets)))] \n pol_sentiments = pol_sentiments[:int(round(reduce_dataset*len(pol_sentiments)))]\n up_to = int(round(len(pol_tweets)*(splitvalue+0.1)))\n split_pos = int(round(len(pol_tweets)*splitvalue))\n train_tweets = pol_tweets[0:split_pos]+pol_tweets[up_to:len(pol_tweets)]\n test_tweets = pol_tweets[split_pos:up_to]\n train_sentimentvalues = pol_sentiments[0:split_pos]+pol_sentiments[up_to:len(pol_tweets)]\n test_sentimentvalues = pol_sentiments[split_pos:up_to]\n \n pol_train_targets = [t.get_sentiment() for t in train_tweets]\n pol_test_targets = [t.get_sentiment() for t in test_tweets]\n print \"Train tweets: \", len(train_tweets)\n print \"test tweeets: \", len(test_tweets) \n print \"Train targets: \", len(pol_train_targets)\n print \"test targets \", len(pol_test_targets)\n print \"train sentiments \", len(train_sentimentvalues)\n print \"test sentiments \", len(test_sentimentvalues)\n return train_tweets, pol_train_targets, test_tweets, pol_test_targets, train_sentimentvalues, test_sentimentvalues\n \ndef make_subjectivity_train_and_test_and_targets(tweets, sentimentvalues, splitvalue=0.9, reduce_dataset=1,shuffle=True):\n \"\"\"\n Returns a dataset for subjectivity classification, along with the targets for classification\n \"\"\"\n if shuffle:\n tweets, sentimentvalues = shuffle_tweets_and_sentiments(tweets, sentimentvalues)\n reduced_tweets = tweets[:int(round(reduce_dataset*len(tweets)))] \n up_to = int(round(len(reduced_tweets)*(splitvalue+0.1)))\n split_pos = int(round(len(reduced_tweets)*splitvalue))\n \n print \"Upto:\",up_to\n print \"Splitpos:\",split_pos\n train_tweets = reduced_tweets[:split_pos]+reduced_tweets[up_to:len(reduced_tweets)]\n test_tweets = reduced_tweets[split_pos:up_to]\n train_sentimentvalues = sentimentvalues[0:split_pos]+sentimentvalues[up_to:len(reduced_tweets)]\n test_sentimentvalues = sentimentvalues[split_pos:up_to]\n print \"Train reduced_tweets: \", len(train_tweets)\n print \"test tweeets: \", len(test_tweets) \n \n sub_train_targets = ['objective' if t.subjectivity==0 else 'subjective' for t in train_tweets]\n sub_test_targets = ['objective' if t.subjectivity==0 else 'subjective' for t in test_tweets]\n print \"Train targets: \", len(sub_train_targets)\n print \"test targets \", len(sub_test_targets)\n return train_tweets, sub_train_targets, test_tweets, sub_test_targets, train_sentimentvalues, test_sentimentvalues\n\n\ndef shuffle_tweets_and_sentiments(tweets, sentiments):\n indexes = range(len(tweets))\n random.shuffle(indexes)\n \n shuffled_tweets = []\n shuffled_sentiments = []\n for i in indexes:\n shuffled_sentiments.append(sentiments[i])\n shuffled_tweets.append(tweets[i])\n \n return shuffled_tweets, shuffled_sentiments \n \n \ndef make_subjectivity_targets(tweets):\n sub_train_targets = ['objective' if t.subjectivity==0 else 'subjective' for t in tweets]\n return tweets, sub_train_targets\n \ndef make_polarity_targets(tweets):\n pol_train_targets = [t.get_sentiment() for t in tweets]\n return tweets, pol_train_targets\n \ndef store_model(name, params, score, file_postfix=\"\"):\n \"\"\"\n Stores the given dict as a pickle in the stored estimators folder.\n \"\"\"\n out = open(\"stored_estimators/\"+str(name)+str(score)+str(file_postfix), 'wb')\n pickle.dump(params, out)\n out.close()\n return params\n\ndef store_sentimentvalues(words_with_values, filename):\n \"\"\"\n Pickles the given list of dicts with sentiment values.\n \"\"\"\n #Pickle sentiment values\n output = open(filename, 'wb')\n pickle.dump(words_with_values, output)\n\n\n\ndef get_sentimentvalues(setnr=None):\n \"\"\"\n Gets the pickles of sentiment values\n \"\"\"\n if setnr==None:\n setnr = int(raw_input(\"Get which pickle set? 0: RandomSet 1: RoseborgSet 2: ErnaSet 3: All three ...\"))\n \n if setnr is 3:\n #fetch all sets and append them together\n tweets = []\n for pickleset in sentiment_pickles:\n tweets = tweets + pickle.load(open(pickleset, 'rb'))\n return tweets\n else:\n tweets = pickle.load(open(sentiment_pickles[setnr], 'rb'))\n return tweets\n \n return tweets\n \ndef get_entity_test_and_targets():\n \"\"\"\n Fetches the dataset for entity testing, aswell as the proper targets.\n \"\"\"\n f = open(\"entity_test\",\"rb\")\n tweets = pickle.load(f)\n# for t in tweets:\n# print t.text,\" \",t.hashtags\n# raw_input(\"Continue?\")\n print len(tweets)\n f.close()\n f = open(\"entity_test_targets.txt\",\"r\")\n targets = f.readlines()\n print len(targets)\n targets = [int(t) for t in targets]\n return tweets, targets\n \ndef temporally_aggregate_subjectivity(tweets, predictions, targets=None, topics=None):\n \"\"\"\n Aggregates subjectivity for given tweets' days for both correct targets and predictions.\n Returns a list with days and a list with tweet frequencies, and a list with aggregated target values and a list with aggregated predicted values\n \"\"\"\n# for t in tweets:\n# print t.timestamp\n days = [t.timestamp[5:10].replace('-','.') if len(t.timestamp)<20 else t.timestamp[8:13].replace('-','.') for t in tweets]\n reduced_targets = reduce_targets(targets) if targets != None else None\n reduced_predictions = reduce_targets(predictions)\n sorted_days =sorted( list(set( [float(x) for x in days] )) )\n aggregated_targets = [ 0 for _ in sorted_days]\n aggregated_predicts = [ 0 for _ in sorted_days]\n frequencies = [ 0 for _ in sorted_days]\n for i in range(len(sorted_days)):\n aggregated_targets[i] = reduce(lambda x,y: x+y, [t if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_targets, days)] ) if reduced_targets!=None else None\n aggregated_predicts[i] = reduce(lambda x,y: x+y, [t if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_predictions, days)] )\n frequencies[i] = reduce(lambda x,y: x+y, [1 if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_predictions, days)] )\n# print days\n print sorted_days, aggregated_targets, aggregated_predicts, frequencies\n return sorted_days, aggregated_targets, aggregated_predicts, frequencies\n\ndef temporally_aggregate_polarity(tweets, predictions, targets=None, topics=None):\n \"\"\"\n Aggregates(calculates difference) polarity for given tweets' days for both predictions, and targets if given, and topics if given.\n \"\"\"\n# for t in tweets:\n# print t.timestamp\n days = [t.timestamp[5:10].replace('-','.') if len(t.timestamp)<20 else t.timestamp[8:13].replace('-','.') for t in tweets]\n if targets!=None:\n reduced_targets = reduce_targets(targets)\n reduced_targets = [-1 if t==0 else 1 for t in reduced_targets]\n else:\n reduced_targets = None\n reduced_predictions = reduce_targets(predictions)\n reduced_predictions = [-1 if t==0 else 1 for t in reduced_predictions]\n print topics\n sorted_days =sorted( list(set( [float(x) for x in days] )) )\n aggregated_targets = [ 0 for _ in sorted_days]\n aggregated_predicts = [ 0 for _ in sorted_days]\n frequencies = [ 0 for _ in sorted_days]\n unique_topics = list(set(topics)) if topics!=None else None\n print unique_topics\n aggregated_polarity_on_topic = []\n for i in range(len(sorted_days)):\n aggregated_targets[i] = reduce(lambda x,y: x+y, [t if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_targets, days)] ) if reduced_targets!=None else None\n aggregated_predicts[i] = reduce(lambda x,y: x+y, [t if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_predictions, days)] )\n frequencies[i] = reduce(lambda x,y: x+y, [1 if float(d)==sorted_days[i] else 0 for t,d in zip(reduced_predictions, days)] )\n if unique_topics!=None:\n for i in range(len(unique_topics)):\n aggregated_polarity_on_topic.append(reduce(lambda x,y: x+y, [t if float(d)==sorted_days[i] and top==unique_topics[i] else 0 for t,d,top in zip(reduced_predictions,days,topics)] ))\n \n# print days\n print sorted_days\n print aggregated_polarity_on_topic\n return sorted_days, aggregated_targets, aggregated_predicts, frequencies, topics, aggregated_polarity_on_topic\n \ndef topically_aggregate_polarity(tweets, predictions, topics):\n days = [t.timestamp[5:10].replace('-','.') if len(t.timestamp)<20 else t.timestamp[8:13].replace('-','.') for t in tweets]\n reduced_predictions = reduce_targets(predictions)\n reduced_predictions = [-1 if t==0 else 1 for t in reduced_predictions]\n sorted_days =sorted( list(set( [float(x) for x in days] )) )\n unique_topics = list(set(topics))\n aggregated_polarity_on_topic = [[] for _ in unique_topics]\n sentimentpoints = []\n for i in range(len(unique_topics)):\n for j in range(len(sorted_days)):\n aggregated_polarity_on_topic[i].append(reduce(lambda x,y: x+y, [t if float(d)==sorted_days[j] and top==unique_topics[i] else 0 for t,d,top in zip(reduced_predictions,days,topics)] ))\n sentimentpoints.append(reduce(lambda x,y: x+y, [-p if p<0 else p for p in aggregated_polarity_on_topic[i]]))\n unique_topics[unique_topics.index(None)] = \"undefined\" \n print unique_topics\n print sorted_days\n print aggregated_polarity_on_topic\n unique_topics, aggregated_polarity_on_topic, sentimentpoints = zip(*sorted(zip(unique_topics,aggregated_polarity_on_topic,sentimentpoints), key=operator.itemgetter(2), reverse=True))\n return sorted_days, unique_topics[:20], aggregated_polarity_on_topic[:20]\n \ndef reduce_targets(targets):\n \"\"\"\n Reduces a set of subjectivity or polarity targets to 1s and 0s\n \"\"\" \n if len(targets)<1: return []\n if targets[0]=='objective' or targets[0]=='subjective':\n binaries = [0 if target=='objective' else 1 for target in targets]\n else:\n binaries = [0 if target=='negative' else 1 for target in targets]\n return binaries\n\npickles = ['tweet_pickles/random_dataset',\n 'tweet_pickles/rosenborg_dataset',\n 'tweet_pickles/erna_dataset']\n\nsentiment_pickles = ['models/sentimentvalues_random_dataset',\n 'models/sentimentvalues_rosenborg_dataset',\n 'models/sentimentvalues_erna_dataset']\n \nsentiments = [\"negative\",\n \"neutral\",\n \"positive\"]\n\ncomplete_datasets = [\"complete_datasets/random_dataset.tsv\",\n \"complete_datasets/rosenborg_dataset.tsv\",\n \"complete_datasets/erna_dataset.tsv\",\n \"complete_datasets/temporal_dataset.tsv\"]\n\ndatasets = [\"data/random_dataset.tsv\",\n \"data/rosenborg_dataset.tsv\",\n \"data/erna_dataset.tsv\"] \n\nannotated_datasets = [\"johnarne_annotated_data/random_dataset.tsv\",\n \"johnarne_annotated_data/rosenborg_dataset.tsv\",\n \"johnarne_annotated_data/erna_dataset.tsv\"] \n\nif __name__ == '__main__':\n train, test = split_train_and_test(get_pickles())\n \n print len(train),\" \", len(test)" }, { "alpha_fraction": 0.625668466091156, "alphanum_fraction": 0.6613190770149231, "avg_line_length": 34.125, "blob_id": "fdf0a95e4dd82505a325a6a0b1820da021e378eb", "content_id": "3be5e430a476982e6d610932c7ce2bd1a5ffb2a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 561, "license_type": "no_license", "max_line_length": 105, "num_lines": 16, "path": "/models/me.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 19. mars 2014\n\n@author: JohnArne\n'''\nfrom model import Model\nfrom sklearn.linear_model import LogisticRegression\n\nclass ME(Model):\n \"\"\"\n Subclass implementing the Maximum entropy classification model.\n \"\"\"\n def __init__(self, tweets_train, tweets_targets, vect_options, tfidf_options):\n self.classifier = LogisticRegression()\n extra_params = {'clf__C': (0.1, 0.3, 0.5, 0.7, 0.8, 1.0,),'clf__penalty': ('l1', 'l2')}\n super(ME, self).__init__(tweets_train, tweets_targets, vect_options, tfidf_options, extra_params)" }, { "alpha_fraction": 0.5098039507865906, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 9.199999809265137, "blob_id": "757df61deeff2230942f4bfee7e3ae6242430d51", "content_id": "a0703a41b6e1f2a81a42f7a6ffbdcca5ba18a8e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 51, "license_type": "no_license", "max_line_length": 23, "num_lines": 5, "path": "/lexicon/__init__.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 3. des. 2014\n\n@author: JohnArne\n'''\n" }, { "alpha_fraction": 0.6046240329742432, "alphanum_fraction": 0.606959342956543, "avg_line_length": 34.388431549072266, "blob_id": "294b804ba0b031faadb3362bad5681b9c404aa03", "content_id": "aa414f33ffd0e00494102efce01229ff2953ddfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4282, "license_type": "no_license", "max_line_length": 104, "num_lines": 121, "path": "/easygui_gui.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 19. nov. 2014\n\n@author: JohnArne\n'''\n\nimport easygui as eg\nimport sys\n \ndef show_windows():\n while 1:\n# title = \"Message from test1.py\"\n# eg.msgbox(\"Hello, world!\", title)\n \n msg =\"Run with which classification model?\"\n title = \"Classification model\"\n models = [\"Multinomial Naive Bayes\", \"Support Vector Machines\", \"Maximum Entropy\"]\n model_choice = str(eg.choicebox(msg, title, models))\n \n msg = \"Use saved preset values?\"\n choices = [\"Yes\",\"No\"]\n choice = eg.buttonbox(msg,choices=choices)\n if str(choice)==\"Yes\":\n model_preset_functions[model_choice]()\n else:\n model_select_functions[model_choice]()\n \n # note that we convert choice to string, in case\n # the user cancelled the choice, and we got None.\n# eg.msgbox(\"You chose: \" + str(choice), \"Survey Result\")\n message = \"Sentiments over time period something something\"\n image = \"temporal_sentiments.png\"\n eg.msgbox(message, image=image)\n \n msg = \"Do you want to continue?\"\n title = \"Please Confirm\"\n if eg.ccbox(msg, title): # show a Continue/Cancel dialog\n pass # user chose Continue\n else:\n sys.exit(0) # user chose Cancel\n \ndef show_naivebayes_presets():\n \"\"\"\n Shows a selection of preset running values for Naive Bayes and returns the user selection.\n \"\"\"\n msg =\"Select preset values for Naive Bayes\"\n title = \"Naive Bayes presets\"\n choices = [\"Multinomial Naive Bayes\", \"Support Vector Machines\", \"Maximum Entropy\"]\n preset_choice = eg.choicebox(msg, title, choices)\n pass\n\ndef show_svm_presets():\n \"\"\"\n Shows a selection of preset running values for Suport Vector Machine and returns the user selection.\n \"\"\"\n msg =\"Select preset values for Support Vector Machines\"\n title = \"SVM presets\"\n choices = [\"something\", \"somethingsomething\", \"something else\"]\n preset_choice = eg.choicebox(msg, title, choices)\n pass\n\ndef show_me_presets():\n \"\"\"\n Shows a selection of preset running values for Maximum Entropy and returns the user selection.\n \"\"\"\n msg =\"Select preset values for Maximum Entropy\"\n title = \"MaxEnt presets\"\n choices = [\"something\", \"something else\", \"aaand more\"]\n preset_choice = eg.choicebox(msg, title, choices)\n pass\n\ndef show_naivebayes_selection():\n \"\"\"\n Shows a value input window for Naive Bayes and returns the user selection.\n \"\"\"\n msg = \"Enter running values for Naive Bayes\"\n title = \"Naive Bayes run\"\n fieldNames = [\"x\",\"dss\",\"c\",\"range\",\"s\",\"p\",\"cross\",\"stu\",\"thn\",\"pH\"]\n fieldValues = [] # we start with blanks for the values\n fieldValues = eg.multenterbox(msg,title, fieldNames)\n \n # make sure that none of the fields was left blank\n while 1: # do forever, until we find acceptable values and break out\n if fieldValues == None: \n break\n errmsg = \"\"\n \n # look for errors in the returned values\n for i in range(len(fieldNames)):\n if fieldValues[i].strip() == \"\":\n errmsg = errmsg + ('\"%s\" is a required field.\\n\\n' % fieldNames[i])\n \n if errmsg == \"\": \n break # no problems found\n else:\n # show the box again, with the errmsg as the message \n fieldValues = eg.multenterbox(errmsg, title, fieldNames, fieldValues)\n \n print (\"Reply was:\", fieldValues)\n pass\n\ndef show_svm_selection():\n \"\"\"\n Shows a value input window for Suport Vector Machine and returns the user selection.\n \"\"\"\n pass\n\ndef show_me_selection():\n \"\"\"\n Shows a value input window for Maximum Entropy and returns the user selection.\n \"\"\"\n pass\n\n\nmodel_preset_functions = {\"Multinomial Naive Bayes\": show_naivebayes_presets,\n \"Support Vector Machines\": show_svm_presets,\n \"Maximum Entropy\": show_me_presets}\n\nmodel_select_functions = {\"Multinomial Naive Bayes\": show_naivebayes_selection,\n \"Support Vector Machines\": show_svm_selection,\n \"Maximum Entropy\": show_me_selection}\n" }, { "alpha_fraction": 0.6134738326072693, "alphanum_fraction": 0.619997501373291, "avg_line_length": 36.78199005126953, "blob_id": "42a9657c4e46be69a1ad152dc38c241864421a85", "content_id": "57e186549570bf2e015c8057639554551e0282fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7971, "license_type": "no_license", "max_line_length": 150, "num_lines": 211, "path": "/lexicon/lexicon.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 27. nov. 2014\n\n@author: JohnArne\n'''\nfrom hmac import trans_36\nimport requests\nimport os\nfrom sentiwordnet import SentiWordNetCorpusReader, SentiSynset\nimport nltk\nfrom pos_mappings import TYPECRAFT_SENTIWORDNET\nimport gettext\nimport codecs\nimport subprocess\nimport pickle\n\nclass Lexicon():\n \"\"\"\n Handles the interfacing with the sentiment lexicon as well as translation and disambiguation.\n \"\"\"\n \n def __init__(self, translater, sentiment_lexicon):\n #initialize sentiment lexicon resource and translation\n self.translater = translater\n self.sentiment_lexicon = sentiment_lexicon\n \n def translate_and_get_lexicon_sentiment(self, word, context=None, pos_tag=None):\n \"\"\"\n Returns the translated sentiment values for all the words with their contexts and pos tags.\n \"\"\"\n #Translate word\n translated_word = self.translater.translate(word)\n return self.sentiment_lexicon.get_values(translated_word, context, pos_tag)\n \n def translate_sentence_and_get_lexicon_sentiment(self, sentence):\n \"\"\"\n Returns the translated sentiment values for a whole sentence.\n \"\"\"\n #Translate word\n translated_sentence = self.translater.translate(sentence)\n translated_words = tokenizer(translated_sentence)\n sentiments = []\n for word in translated_words:\n sentiment = self.sentiment_lexicon.get_values(word)\n if sentiment!=None:\n sentiments.append(sentiment)\n return sentiments\n \nclass SentiWordNetLexicon():\n \n def __init__(self):\n SWN_FILENAME = \"lexicon\\SentiWordNet_3.0.0_20130122.txt\"\n self.swn= SentiWordNetCorpusReader(SWN_FILENAME)\n\n def get_values(self, word, context=None, pos_tag=None):\n \"\"\"\n Perform lookup in SentiWordNet\n \"\"\"\n# entry = swn.senti_synset(\"breakdown.n.03\")\n entries = None\n for w in word.split(' '):\n entries = self.swn.senti_synsets(w)\n if entries != None: break\n if entries is None or len(entries)==0: \n return None\n if len(entries)==1 or pos_tag is None:\n return [entries[0].pos_score, entries[0].neg_score, entries[0].obj_score]\n elif len(entries)>1:\n #Find out which word to chose, if there are several classes\n print \"Several entries \",entries\n for entry in entries:\n if entry.synset.pos()==TYPECRAFT_SENTIWORDNET[pos_tag]:\n print \"Found matching entry: \", entry\n return [entry.pos_score, entry.neg_score, entry.obj_score]\n \n return [entries[0].pos_score, entries[0].neg_score, entries[0].obj_score]\n return None\n\nclass BingTranslater():\n \n def __init__(self, words):\n self.original_words = words\n file = codecs.open(\"bing_words.txt\", \"w\", \"utf8\")\n for word in words:\n file.write(word+\"\\n\")\n file.close()\n \n print \"Bing translating \",len(words),\" words...\"\n subprocess.call(\"lexicon/bingtranslater.exe\")\n file = codecs.open(\"translated_words.txt\", \"r\", \"utf8\")\n translated_words = file.readlines()\n file.close()\n self.translation_mapping = dict(zip(self.original_words, translated_words))\n print \"Bing done...\"\n \n def translate(self, word):\n try:\n return self.translation_mapping[word]\n except KeyError:\n return None \n \nclass GoogleTranslater():\n \n def __init__(self):\n self.translation_url = \"https://translate.google.com/#no/en/\"\n #The lines of words contain the original word first, then subsequent translations in english\n self.words = codecs.open(\"bing_words.txt\", \"r\", \"utf8\").read().splitlines()\n \n def translate(self, word, context=None, pos_tag=None):\n \"\"\"\n Translate word using a translation API\n Perform sentence contezt translation on google web interface\n Perform word translation using Bing -> get all alternatives anc check for a mathc in the google translation, if match choose it as translation\n if not then choose the bing translation that best matches using POS tag?\n \"\"\"\n #Get contextual translation from google translate\n par = {\"text\": word, \"raw\": \"raw\"}\n r = requests.post(self.translation_url, data=par)\n results = r.text\n translated_word = get_from_html_text(results, 'TRANSLATED_TEXT')\n \n #Perform lookup in the text file from the C# translator\n #if there is no match, take the best match from the bing file\n# print \"Translated: \", word, \" ->\", translated_word\n return translated_word\n \ndef get_from_html_text(resultset, target):\n \"\"\"\n Gets the value of a variable target from a html result set from a request.\n \"\"\"\n index = resultset.find(target)+len(target)+2\n return resultset[index:index+140].split(\"'\")[0].lower()\n \n \ndef perform_bing_sentiment_lexicon_lookup(tweets):\n \"\"\"\n Performs sentiment lexicon lookup on the tweets, and stores it in the objects.\n \"\"\"\n words = []\n for t in tweets:\n for phrase in t.tagged_words:\n for word in phrase:\n try:\n if word[\"pos\"] in TYPECRAFT_SENTIWORDNET:\n words.append(word['word'])\n except KeyError:\n continue \n \n \n lex = Lexicon(BingTranslater(words), SentiWordNetLexicon())\n words_with_sentimentvalues=[]#list of dicts\n print \"Getting sentiment values\"\n for t in tweets:\n sentiwords =[]\n sentiwords_with_values={}\n for phrase in t.tagged_words:\n for word in phrase:\n try:\n if word[\"pos\"] in TYPECRAFT_SENTIWORDNET:\n sentiwords.append(word['word'])\n except KeyError:\n continue\n for sentiword in sentiwords:\n sentivalues = lex.translate_and_get_lexicon_sentiment(sentiword)\n if sentivalues!=None:\n print \"Adding sentivalues: \",sentivalues\n sentiwords_with_values[sentiword] = sentivalues\n words_with_sentimentvalues.append(sentiwords_with_values)\n \n return words_with_sentimentvalues\n \ndef perform_google_sentiment_lexicon_lookup(tweets):\n \"\"\"\n Performs sentiment lexicon lookup on the tweets, and stores it in the objects.\n \"\"\"\n \n lex = Lexicon(GoogleTranslater(), SentiWordNetLexicon())\n print \"Getting sentiment values\"\n tweet_sentiments = []\n for t in tweets:\n tweet_sentiments.append(lex.translate_sentence_and_get_lexicon_sentiment(t.text))\n \n print tweet_sentiments\n reduced_tweet_sentiments = []\n for sentiments in tweet_sentiments:\n polar_sum = sum([s[0] for s in sentiments])\n negative_sum = sum([s[1] for s in sentiments])\n objective_sum = sum([s[2] for s in sentiments])\n reduced_tweet_sentiments.append((polar_sum, negative_sum, objective_sum))\n print reduced_tweet_sentiments\n return reduced_tweet_sentiments\n\ndef tokenizer(sentence):\n \"\"\"\n Tokenizes an english sentence.\n \"\"\"\n words = []\n for phrase in sentence.split('.'):\n for piece in phrase.split(','):\n for word in piece.split(' '):\n words.append(word)\n return words\n \nif __name__ == '__main__':\n #Insert all words to be translated into the googlebing translator in order to augment with Bing...\n lex = Lexicon(BingTranslater(), SentiWordNetLexicon())\n print lex.translate_and_get_lexicon_sentiment(\"good\")\n \n# swn = SentiWordNetCorpusReader('SentiWordNet_3.0.0_20130122.txt')\n# for senti_synset in swn.all_senti_synsets():\n# print senti_synset.synset.name, senti_synset.pos_score, senti_synset.neg_score" }, { "alpha_fraction": 0.6290730237960815, "alphanum_fraction": 0.638678252696991, "avg_line_length": 48.009010314941406, "blob_id": "54ee3986ef4cd6d2a0549170e0a956d1376f6400", "content_id": "175e7bff739036decf3db12cc35113f87b6553a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 21759, "license_type": "no_license", "max_line_length": 248, "num_lines": 444, "path": "/test.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 24. nov. 2014\nMethods for performing test on various classificatino schemes and storing the results.\n@author: JohnArne\n'''\nimport utils\nfrom lexicon import lexicon\nfrom models.nb import NB\nfrom models.svm import SVM\nfrom models.me import ME\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score\nfrom tweet import Tweet\nimport plotting\nimport preprocessing\nimport models.features as feat_utils\nimport pickle\nimport classifier\nimport tweet\nimport entity_extraction\nfrom entity_extraction import cutoff_breakwords\n \n \ndef train_and_test_subjectivity_and_polarity():\n datasetnr = 3\n tweets = utils.get_pickles(datasetnr)\n sentimentvalues = feat_utils.get_sentiment_values(datasetnr)\n tweets = preprocessing.remove_link_classes(tweets)\n tweets = preprocessing.lower_case(tweets)\n tweets = preprocessing.remove_specialchars_round2(tweets)\n \n# train_subjectivity_and_test_on_feature_set(tweets, 'SA', sentimentvalues)\n train_subjectivity_and_test_on_feature_set(tweets, 'SB', sentimentvalues)\n train_subjectivity_and_test_on_feature_set(tweets, 'SC', sentimentvalues)\n# google_sentimentvalues = feat_utils.get_google_sentiment_values(datasetnr)\n# train_subjectivity_and_test_on_feature_set(tweets, 'SC2', google_sentimentvalues)\n \n# train_polarity_and_test_on_feature_set(tweets, 'PA', sentimentvalues)\n# train_polarity_and_test_on_feature_set(tweets, 'PB', sentimentvalues)\n# train_polarity_and_test_on_feature_set(tweets, 'PC', sentimentvalues)\n# google_sentimentvalues = feat_utils.get_google_sentiment_values(datasetnr)\n# train_polarity_and_test_on_feature_set(tweets, 'PC2', google_sentimentvalues)\n\ndef train_subjectivity_and_test_on_feature_set(tweets, feature_set, sentimentvalues, reduce_dataset=1):\n \"\"\"\n Performs training and testing with a given feature set key\n \"\"\"\n kfolds = range(0,10)\n nbaccuracy_avgs = []\n nbprecision_avgs = []\n nbrecall_avgs = []\n nbf1_avgs = []\n svmaccuracy_avgs = []\n svmprecision_avgs = []\n svmrecall_avgs = []\n svmf1_avgs = []\n meaccuracy_avgs = []\n meprecision_avgs = []\n merecall_avgs = []\n mef1_avgs = []\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': False,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n for kfoldcounter in kfolds:\n print \"--------------------------KFOLD NR \",kfoldcounter,\"----------------------------------\" \n train_tweets, train_targets, test_tweets, test_targets, train_sentimentvalues, test_sentimentvalues = utils.make_subjectivity_train_and_test_and_targets(tweets,sentimentvalues,splitvalue=kfoldcounter*0.1,reduce_dataset=reduce_dataset) \n #TRAINING NB\n print \"Training NB subjectivity on dataset of length \", len(train_tweets)\n clf = NB(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n print \"Testing...\"\n nb_accuracy, nb_precision, nb_recall, nb_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n nbaccuracy_avgs.append(nb_accuracy)\n nbprecision_avgs.append(nb_precision)\n nbrecall_avgs.append(nb_recall)\n nbf1_avgs.append(nb_f1_score)\n \n #TRAINING SVM\n vect_options = {\n 'ngram_range': (1,3),\n 'max_df': 0.5\n \n }\n tfidf_options = {\n 'sublinear_tf': True,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n print \"Training SVM subjectivity on dataset of length \", len(train_tweets)\n clf = SVM(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n print \"Testing...\"\n svm_accuracy, svm_precision, svm_recall, svm_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n svmaccuracy_avgs.append(svm_accuracy)\n svmprecision_avgs.append(svm_precision)\n svmrecall_avgs.append(svm_recall)\n svmf1_avgs.append(svm_f1_score)\n \n #TRAINING MAXENT\n vect_options = {\n 'ngram_range': (1,2),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': True,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n \n print \"Training MaxEnt subjectivity on dataset of length \", len(train_tweets)\n clf = ME(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n \n print \"Testing...\"\n me_accuracy, me_precision, me_recall, me_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n meaccuracy_avgs.append(me_accuracy)\n meprecision_avgs.append(me_precision)\n merecall_avgs.append(me_recall)\n mef1_avgs.append(me_f1_score)\n \n \n print \"Averages\"\n nb_accuracy = reduce(lambda x,y: x+y,nbaccuracy_avgs)/len(nbaccuracy_avgs)\n nb_precision = reduce(lambda x,y: x+y,nbprecision_avgs)/len(nbprecision_avgs)\n nb_recall = reduce(lambda x,y: x+y,nbrecall_avgs)/len(nbrecall_avgs)\n nb_f1_score = reduce(lambda x,y: x+y,nbf1_avgs)/len(nbf1_avgs)\n svm_accuracy = reduce(lambda x,y: x+y,svmaccuracy_avgs)/len(svmaccuracy_avgs)\n svm_precision = reduce(lambda x,y: x+y,svmprecision_avgs)/len(svmprecision_avgs)\n svm_recall = reduce(lambda x,y: x+y,svmrecall_avgs)/len(svmrecall_avgs)\n svm_f1_score = reduce(lambda x,y: x+y,svmf1_avgs)/len(svmf1_avgs)\n me_accuracy = reduce(lambda x,y: x+y,meaccuracy_avgs)/len(meaccuracy_avgs)\n me_precision = reduce(lambda x,y: x+y,meprecision_avgs)/len(meprecision_avgs)\n me_recall = reduce(lambda x,y: x+y,merecall_avgs)/len(merecall_avgs)\n me_f1_score = reduce(lambda x,y: x+y,mef1_avgs)/len(mef1_avgs)\n \n data = {'Naive Bayes': [nb_accuracy, nb_precision, nb_recall, nb_f1_score],\n 'SVM': [svm_accuracy, svm_precision, svm_recall, svm_f1_score],\n 'Maximum Entropy': [me_accuracy, me_precision, me_recall, me_f1_score]}\n plotting.plot_performance_histogram(data, \"subjectivity_\"+feature_set)\n return data\n\ndef train_polarity_and_test_on_feature_set(tweets, feature_set, sentimentvalues, reduce_dataset=1):\n \"\"\"\n Performs training and testing with a given feature set key\n \"\"\"\n kfolds = range(0,10)\n nbaccuracy_avgs = []\n nbprecision_avgs = []\n nbrecall_avgs = []\n nbf1_avgs = []\n svmaccuracy_avgs = []\n svmprecision_avgs = []\n svmrecall_avgs = []\n svmf1_avgs = []\n meaccuracy_avgs = []\n meprecision_avgs = []\n merecall_avgs = []\n mef1_avgs = []\n for kfoldcounter in kfolds:\n print \"--------------------------KFOLD NR \",kfoldcounter,\"----------------------------------\" \n train_tweets, train_targets, test_tweets, test_targets, train_sentimentvalues, test_sentimentvalues = utils.make_polarity_train_and_test_and_targets(tweets,sentimentvalues, splitvalue=kfoldcounter*0.1, reduce_dataset=reduce_dataset)\n # for tweet, target in zip(tweets,targets):\n # try:\n # print unicode(tweet.text), \" \", target\n # except UnicodeEncodeError:\n # print tweet.text.encode('utf8'), \" \", target\n # except UnicodeDecodeError:\n # print tweet.text, \" \", target\n \n #TRAINING NB\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': True,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n print \"Training NB polarity with feature set \",feature_set\n clf = NB(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n print \"Testing...\"\n nb_accuracy, nb_precision, nb_recall, nb_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n nbaccuracy_avgs.append(nb_accuracy)\n nbprecision_avgs.append(nb_precision)\n nbrecall_avgs.append(nb_recall)\n nbf1_avgs.append(nb_f1_score)\n \n #TRAINING SVM\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options= {\n 'sublinear_tf': True,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n print \"Training SVM polarity on dataset of length \", len(train_tweets)\n clf = SVM(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n \n print \"Testing...\"\n svm_accuracy, svm_precision, svm_recall, svm_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n svmaccuracy_avgs.append(svm_accuracy)\n svmprecision_avgs.append(svm_precision)\n svmrecall_avgs.append(svm_recall)\n svmf1_avgs.append(svm_f1_score)\n #TRAINING MAXENT\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': True,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n print \"Training MaxEnt polarity on dataset of length \", len(train_tweets)\n clf = ME(train_tweets, train_targets, vect_options, tfidf_options)\n clf.set_feature_set(feature_set, train_sentimentvalues)\n clf.train_on_feature_set()\n \n print \"Testing...\"\n me_accuracy, me_precision, me_recall, me_f1_score = clf.test_and_return_results(test_tweets, test_targets, test_sentimentvalues)\n meaccuracy_avgs.append(me_accuracy)\n meprecision_avgs.append(me_precision)\n merecall_avgs.append(me_recall)\n mef1_avgs.append(me_f1_score)\n \n print \"Averages\"\n nb_accuracy = reduce(lambda x,y: x+y,nbaccuracy_avgs)/len(nbaccuracy_avgs)\n nb_precision = reduce(lambda x,y: x+y,nbprecision_avgs)/len(nbprecision_avgs)\n nb_recall = reduce(lambda x,y: x+y,nbrecall_avgs)/len(nbrecall_avgs)\n nb_f1_score = reduce(lambda x,y: x+y,nbf1_avgs)/len(nbf1_avgs)\n svm_accuracy = reduce(lambda x,y: x+y,svmaccuracy_avgs)/len(svmaccuracy_avgs)\n svm_precision = reduce(lambda x,y: x+y,svmprecision_avgs)/len(svmprecision_avgs)\n svm_recall = reduce(lambda x,y: x+y,svmrecall_avgs)/len(svmrecall_avgs)\n svm_f1_score = reduce(lambda x,y: x+y,svmf1_avgs)/len(svmf1_avgs)\n me_accuracy = reduce(lambda x,y: x+y,meaccuracy_avgs)/len(meaccuracy_avgs)\n me_precision = reduce(lambda x,y: x+y,meprecision_avgs)/len(meprecision_avgs)\n me_recall = reduce(lambda x,y: x+y,merecall_avgs)/len(merecall_avgs)\n me_f1_score = reduce(lambda x,y: x+y,mef1_avgs)/len(mef1_avgs)\n \n data = {'Naive Bayes': [nb_accuracy, nb_precision, nb_recall, nb_f1_score],\n 'SVM': [svm_accuracy, svm_precision, svm_recall, svm_f1_score],\n 'Maximum Entropy': [me_accuracy, me_precision, me_recall, me_f1_score]}\n plotting.plot_performance_histogram(data, \"polarity_\"+feature_set)\n return data\n\ndef perform_grid_search_on_featureset_SA_and_PA():\n datasetnr = 3\n tweets = utils.get_pickles(datasetnr)\n sentimentvalues = feat_utils.get_sentiment_values(datasetnr)\n tweets = preprocessing.remove_link_classes(tweets)\n tweets = preprocessing.lower_case(tweets)\n tweets = preprocessing.remove_specialchars_round2(tweets)\n \n train_tweets, train_targets, test_tweets, test_targets, train_sentimentvalues, test_sentimentvalues = utils.make_subjectivity_train_and_test_and_targets(tweets,sentimentvalues)\n \n clf = SVM(train_tweets, train_targets, None)\n clf.set_feature_set('SA', None)\n clf.grid_search_on_text_features(file_postfix='subjectivity')\n clf = NB(train_tweets, train_targets, None)\n clf.set_feature_set('SA', None)\n clf.grid_search_on_text_features(file_postfix='subjectivity')\n clf = ME(train_tweets, train_targets, None)\n clf.set_feature_set('SA', None)\n clf.grid_search_on_text_features(file_postfix='subjectivity')\n \n train_tweets, train_targets, test_tweets, test_targets, train_sentimentvalues, test_sentimentvalues = utils.make_polarity_train_and_test_and_targets(tweets,sentimentvalues)\n \n clf = SVM(train_tweets, train_targets, None)\n clf.set_feature_set('PA', None)\n clf.grid_search_on_text_features(file_postfix='polarity')\n clf = NB(train_tweets, train_targets, None)\n clf.set_feature_set('PA', None)\n clf.grid_search_on_text_features(file_postfix='polarity')\n clf = ME(train_tweets, train_targets, None)\n clf.set_feature_set('PA', None)\n clf.grid_search_on_text_features(file_postfix='polarity')\n \ndef train_and_test_dataset_increase():\n datasetnr = 3\n tweets = utils.get_pickles(datasetnr)\n sentimentvalues = feat_utils.get_sentiment_values(datasetnr)\n tweets = preprocessing.remove_link_classes(tweets)\n tweets = preprocessing.lower_case(tweets)\n tweets = preprocessing.remove_specialchars_round2(tweets)\n accuracy_data = {'NB(SA)':[],'NB(SB)':[],'NB(SC)':[],\n 'SVM(SA)':[],'SVM(SB)':[],'SVM(SC)':[],\n 'MaxEnt(SA)':[],'MaxEnt(SB)':[],'MaxEnt(SC)':[],\n 'NB(PA)':[],'NB(PB)':[],'NB(PC)':[],\n 'SVM(PA)':[],'SVM(PB)':[],'SVM(PC)':[],\n 'MaxEnt(PA)':[],'MaxEnt(PB)':[],'MaxEnt(PC)':[]}\n f1_data = {'NB(SA)':[],'NB(SB)':[],'NB(SC)':[],\n 'SVM(SA)':[],'SVM(SB)':[],'SVM(SC)':[],\n 'MaxEnt(SA)':[],'MaxEnt(SB)':[],'MaxEnt(SC)':[],\n 'NB(PA)':[],'NB(PB)':[],'NB(PC)':[],\n 'SVM(PA)':[],'SVM(PB)':[],'SVM(PC)':[],\n 'MaxEnt(PA)':[],'MaxEnt(PB)':[],'MaxEnt(PC)':[]}\n for i in range(5,101,5):\n print \"=============================DATAPOINT NR. \",i,\"========================================\"\n data = train_subjectivity_and_test_on_feature_set(tweets, 'SA', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(SA)'].append(data['Naive Bayes'][0])\n f1_data['NB(SA)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(SA)'].append(data['SVM'][0])\n f1_data['SVM(SA)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(SA)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(SA)'].append(data['Maximum Entropy'][3])\n \n data = train_subjectivity_and_test_on_feature_set(tweets, 'SB', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(SB)'].append(data['Naive Bayes'][0])\n f1_data['NB(SB)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(SB)'].append(data['SVM'][0])\n f1_data['SVM(SB)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(SB)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(SB)'].append(data['Maximum Entropy'][3])\n \n data = train_subjectivity_and_test_on_feature_set(tweets, 'SC', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(SC)'].append(data['Naive Bayes'][0])\n f1_data['NB(SC)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(SC)'].append(data['SVM'][0])\n f1_data['SVM(SC)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(SC)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(SC)'].append(data['Maximum Entropy'][3])\n \n data = train_polarity_and_test_on_feature_set(tweets, 'PA', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(PA)'].append(data['Naive Bayes'][0])\n f1_data['NB(PA)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(PA)'].append(data['SVM'][0])\n f1_data['SVM(PA)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(PA)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(PA)'].append(data['Maximum Entropy'][3])\n \n data = train_polarity_and_test_on_feature_set(tweets, 'PB', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(PB)'].append(data['Naive Bayes'][0])\n f1_data['NB(PB)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(PB)'].append(data['SVM'][0])\n f1_data['SVM(PB)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(PB)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(PB)'].append(data['Maximum Entropy'][3])\n \n data = train_polarity_and_test_on_feature_set(tweets, 'PC', sentimentvalues, reduce_dataset=i*0.01)\n print \"DATA -- \",data\n accuracy_data['NB(PC)'].append(data['Naive Bayes'][0])\n f1_data['NB(PC)'].append(data['Naive Bayes'][3])\n accuracy_data['SVM(PC)'].append(data['SVM'][0])\n f1_data['SVM(PC)'].append(data['SVM'][3])\n accuracy_data['MaxEnt(PC)'].append(data['Maximum Entropy'][0])\n f1_data['MaxEnt(PC)'].append(data['Maximum Entropy'][3])\n out = open('incremental_acc'+str(i), 'wb')\n pickle.dump(accuracy_data, out)\n out = open('incremental_f1'+str(i), 'wb')\n pickle.dump(f1_data, out)\n plotting.plot_temporal_sentiment(accuracy_data, filename=\"incremental_accuracy\")\n plotting.plot_temporal_sentiment(f1_data, filename=\"incremental_f1\")\n \ndef test_aggregated_sentiments():\n sub_clf = classifier.get_optimal_subjectivity_classifier()\n pol_clf = classifier.get_optimal_polarity_classifier()\n tweets = utils.get_pickles(2)\n sentimentvalues = utils.get_sentimentvalues(2)\n sub_train_tweets, sub_train_targets, _, _, sub_train_sentiments, _ = utils.make_subjectivity_train_and_test_and_targets(tweets, sentimentvalues, splitvalue=1.0)\n pol_train_tweets, pol_train_targets, _, _, pol_train_sentiments, _ = utils.make_polarity_train_and_test_and_targets(tweets, sentimentvalues, splitvalue=1.0)\n \n sub_predictions = sub_clf.classify(sub_train_tweets, sub_train_sentiments)\n pol_predictions = pol_clf.classify(pol_train_tweets, pol_train_sentiments)\n print pol_train_targets, pol_predictions\n days, targets, predicts, total_frequencies = utils.temporally_aggregate_subjectivity(sub_train_tweets, sub_predictions, targets=sub_train_targets)\n data = {'Targets': [days, targets], 'Predictions': [days, predicts], 'Frequencies': [days,total_frequencies]}\n plotting.plot_subjectivity_aggregates(data, 'aggregated_subjectivity')\n days, targets, predicts, frequencies = utils.temporally_aggregate_polarity(pol_train_tweets, pol_predictions, targets=pol_train_targets)\n for i in range(len(days)):\n targets[i]=targets[i]*1.0/frequencies[i]\n predicts[i]=predicts[i]*1.0/frequencies[i]\n frequencies[i]=frequencies[i]*1.0/total_frequencies[i]\n data = {'Targets': [days, targets], 'Predictions': [days, predicts], 'Frequencies': [days,frequencies]}\n plotting.plot_polarity_aggregates(data, 'aggregated_polarity')\n \ndef test_remporal_topics():\n tweets1 = pickle.load(open('temporal_tweets1', 'rb'))\n tweets2 = pickle.load(open('temporal_tweets2', 'rb'))\n tweets = tweets1 + tweets2\n print len(tweets)\n sentiments = pickle.load(open('temporal_sentiments','rb'))\n print len(sentiments)\n subclf = classifier.get_optimal_subjectivity_classifier()\n polclf = classifier.get_optimal_polarity_classifier() \n #TODO SKRIVE HER TEMPORALLY AGGREGATE ETC\n sub_predictions = subclf.classify(tweets, sentiments)\n subjective_tweets = [t for p,t in zip(sub_predictions,tweets) if p==\"subjective\"]\n subjective_sentiments = [s for p,s in zip(sub_predictions,sentiments) if p==\"subjective\"]\n pol_predictions = polclf.classify(subjective_tweets, subjective_sentiments)\n topics = entity_extraction.perform_entity_extraction(subjective_tweets, subjective_sentiments, use_pmi=True, breakword_min_freq=0.1, breakword_range=14)\n days, unique_topics, aggregated_values = utils.topically_aggregate_polarity(subjective_tweets, pol_predictions, topics=topics)\n data = {}\n for i in range(len(unique_topics)):\n data[unique_topics[i]] = [days, aggregated_values[i]]\n print data\n pickle.dump(data, open('topically_aggregated_polarity', 'wb'))\n\ndef preprocess_temporal_dataset():\n tweetlines = utils.get_dataset(utils.complete_datasets[3])\n tweets = []\n for line in tweetlines:\n if len(line)>1:\n tweets.append(tweet.to_tweet(line))\n tweets = preprocessing.preprocess_tweets(tweets)\n sentiments = lexicon.perform_google_sentiment_lexicon_lookup(tweets)\n pickle.dump(sentiments, open('temporal_sentiments','wb'))\n pickle.dump(tweets, open('temporal_tweets2', 'wb'))\n \nif __name__ == '__main__':\n datasetnr = 3\n tweets = utils.get_pickles(datasetnr)\n sentimentvalues = feat_utils.get_sentiment_values(datasetnr)\n tweets = preprocessing.remove_link_classes(tweets)\n tweets = preprocessing.lower_case(tweets)\n tweets = preprocessing.remove_specialchars_round2(tweets)\n \n train_subjectivity_and_test_on_feature_set(tweets, 'SA', datasetnr)\n train_subjectivity_and_test_on_feature_set(tweets, 'SB', datasetnr)\n train_subjectivity_and_test_on_feature_set(tweets, 'SC', sentimentvalues)\n \n train_polarity_and_test_on_feature_set(tweets, 'PA', datasetnr)\n train_polarity_and_test_on_feature_set(tweets, 'PB', datasetnr)\n train_polarity_and_test_on_feature_set(tweets, 'PC', sentimentvalues)" }, { "alpha_fraction": 0.6822289228439331, "alphanum_fraction": 0.6868975758552551, "avg_line_length": 44.76551818847656, "blob_id": "3cbb072f066fb95341a8bbe401d8fa4bfb7ab960", "content_id": "91cf41ca7c0759dc5e2d90ed4fa359b864e7315c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6640, "license_type": "no_license", "max_line_length": 221, "num_lines": 145, "path": "/classifier.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 11. mars 2014\n\n@author: JohnArne\n'''\nimport argparse\nimport utils\nimport preprocessing\nimport retriever_tweepy\nfrom models.nb import NB\nfrom models.svm import SVM\nfrom models.me import ME\nfrom models import features\nfrom models import model\nfrom lexicon import lexicon\nimport test\n\nimport annotation\nimport easygui_gui\nfrom retriever_tweepy import TweetRetriever\nimport entity_extraction\n\nclass Classifier(object):\n \"\"\"\n Class for handling the training and testing of a given model.\n Takes in a selected model type(NV/SVM/ME) trains it on a given dataset, then tests it.\n \"\"\"\n \n def __init__(self, subjectivity_model, polarity_model):\n self.subjectivity_model = subjectivity_model\n self.polarity_model = polarity_model\n \n \n def test(self):\n \"\"\"\n Tests the given model on a partition of the dataset.\n \"\"\" \n \n def classify(self, tweets):\n \"\"\"\n Takes in a list of tweets and classifies with all three classes using the two trained models\n \"\"\"\n sentiments = []\n predictions = self.subjectivity_model.classify(tweets)\n return sentiments\n \n def save_model(self):\n file = open()\n\n def train_and_store_results(self):\n \"\"\"\n Trains the given model on the dataset using the three different models, and different feature sets. Stores the results of the runs.\n \"\"\"\n dataset = \"random_dataset\"\n tweets = utils.get_pickles(dataset)\n self.model.set_feature_set('A')\n self.model.train_on_feature_set()\n \ndef get_optimal_subjectivity_classifier():\n \"\"\"\n Trains and returns the optimal subjectivity classifier.\n \"\"\"\n tweets = utils.get_pickles(3)\n tweets, targets = utils.make_subjectivity_targets(tweets)\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': False,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n clf = SVM(tweets, targets, vect_options, tfidf_options)\n clf.set_feature_set('SA', utils.get_sentimentvalues(3))\n clf.train_on_feature_set()\n return clf\n\ndef get_optimal_polarity_classifier():\n \"\"\"\n Trains and returns the optimal polarity classifier.\n \"\"\"\n tweets = utils.get_pickles(3)\n tweets, targets = utils.make_polarity_targets(tweets)\n vect_options = {\n 'ngram_range': (1,1),\n 'max_df': 0.5\n }\n tfidf_options = {\n 'sublinear_tf': False,\n 'use_idf': True,\n 'smooth_idf': True,\n }\n clf = SVM(tweets, targets, vect_options, tfidf_options)\n clf.set_feature_set('PC2', features.get_google_sentiment_values(3))\n clf.train_on_feature_set()\n return clf\n \nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Commands for classification\")\n parser.add_argument(\"-pre1\", action=\"store_true\", dest=\"preprocess1\", default=False, help=\"Perform first round preprocessing: Duplicate and retweet removal\")\n parser.add_argument(\"-pre2\", action=\"store_true\", dest=\"preprocess2\", default=False, help=\"Perform second round preprocessing: Text cleanup operations, feature extractions, POS-tagging.\")\n parser.add_argument(\"-q\", action=\"store\", dest=\"tweet_query\", default=None, help=\"Get tweets using the given query.\")\n parser.add_argument(\"-a\", action=\"store_true\", dest=\"annotate\", default=False, help=\"Start annotation sequence.\")\n parser.add_argument(\"-analyze\", action=\"store_true\", dest=\"analyze\", default=False, help=\"Perform a re-analysis of the pickled datasets. This analysis is also performed as part of the second preprocessing.\")\n parser.add_argument(\"-posanalyze\", action=\"store_true\", dest=\"posanalyze\", default=False, help=\"Perform a pos-tag analysis of the pickled datasets.\")\n parser.add_argument(\"-lex1\", action=\"store_true\", dest=\"run_lexicon1\", default=False, help=\"Run lexicon translation using Bing and lookup on stored tweets\")\n parser.add_argument(\"-lex2\", action=\"store_true\", dest=\"run_lexicon2\", default=False, help=\"Run lexicon translation using Google and lookup on stored tweets\")\n parser.add_argument(\"-optimize\", action=\"store_true\", dest=\"optimize\", default=False, help=\"Find optimal parameters for text classification with SVM, NB, and MaxEnt. Stores the optimal parameters for each algorithm.\")\n parser.add_argument(\"-test\", action=\"store_true\", dest=\"train_and_test\", default=False, help=\"Train and test on subjectivity and polarity and create a diagram of the results.\")\n parser.add_argument(\"-test_increment\", action=\"store_true\", dest=\"test_incremental\", default=False, help=\"Train and test incremental dataset results and create a diagram of the results.\")\n parser.add_argument(\"-test_aggregated\", action=\"store_true\", dest=\"test_aggregated\", default=False, help=\"Train and test aggregated results from erna solberg dataset and create a diagram of the results.\")\n parser.add_argument(\"-test_entities\", action=\"store_true\", dest=\"test_entities\", default=False, help=\"Test topic detection on topic-annotated rosenborg dataset and create a diagram of the results.\")\n parser.add_argument(\"-test_temptops\", action=\"store_true\", dest=\"test_temptops\", default=False, help=\"Train and test topically aggregated results from a temporally dense dataset and create a diagram of the results.\")\n \n parsameters = parser.parse_args()\n if parsameters.preprocess1:\n preprocessing.initial_preprocess_all_datasets()\n if parsameters.preprocess2:\n preprocessing.classification_preprocess_all_datasets()\n if parsameters.tweet_query:\n retriever = TweetRetriever(parsameters.tweet_query)\n retriever.retrieve_for_dataset()\n if parsameters.annotate:\n annotation.user_annotation()\n if parsameters.analyze:\n preprocessing.re_analyze()\n if parsameters.posanalyze:\n preprocessing.pos_analyze()\n if parsameters.run_lexicon1:\n preprocessing.bing_lexicon_lookup()\n if parsameters.run_lexicon2:\n preprocessing.google_lexicon_lookup()\n if parsameters.optimize:\n test.perform_grid_search_on_featureset_SA_and_PA()\n if parsameters.train_and_test:\n test.train_and_test_subjectivity_and_polarity()\n if parsameters.test_incremental:\n test.train_and_test_dataset_increase()\n if parsameters.test_aggregated:\n test.test_aggregated_sentiments()\n if parsameters.test_temptops:\n test.test_remporal_topics()\n if parsameters.test_entities:\n entity_extraction.perform_and_test_extraction()\n " }, { "alpha_fraction": 0.6140362620353699, "alphanum_fraction": 0.6189417243003845, "avg_line_length": 34.28406524658203, "blob_id": "9c7e767d8ed57767dab671297c075cf83fda31ef", "content_id": "d0f863bf0d65e2082fdb61130077fe21fa1e3d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15289, "license_type": "no_license", "max_line_length": 195, "num_lines": 433, "path": "/preprocessing.py", "repo_name": "andrely/twitter-sentiment", "src_encoding": "UTF-8", "text": "'''\nCreated on 21. apr. 2014\n\n@author: JohnArne\n'''\nimport utils\nfrom calendar import main\nimport tweet\nfrom numpy.core.numeric import correlate\nfrom tweet import Tweet\nimport re\nfrom tagger import Tagger\nfrom analyzer import Analyzer\nimport string\nfrom lexicon import lexicon\nimport plotting\nfrom analyzer import pos_tag_analyze\n\ndef remove_retweets(tweets):\n \"\"\"\n Removes all retweets\n \"\"\"\n for tweet in tweets:\n textbody = tweet.text\n if textbody[:2] is \"RT\":\n tweet.text = textbody[3:]\n return tweets \n\ndef remove_duplicates_and_retweets(tweets):\n \"\"\" \n Removes tweets with dublicate text bodies.\n \"\"\"\n textbodies = []\n tweets = [tweet for tweet in tweets if not tweet.text[:2]==\"RT\"]\n\n #Return a set of the tweets, which will remove duplicates if __eq__ is properly implemented\n unique_tweets = []\n added_texts = []\n for t in tweets:\n if t.text not in added_texts:\n unique_tweets.append(t)\n added_texts.append(t.text)\n return unique_tweets\n\ndef remove_retweet_tags(tweets):\n \"\"\" \n Removes tweets with dublicate text bodies.\n \"\"\"\n for t in tweets:\n textbody = t.text[2:] if t.text[:2]=='RT' else t.text\n t.text = textbody\n return tweets\n\ndef correct_words(tweets):\n \"\"\"\n Performs simple word correction.\n Initially, this will involve removing any vowel that appears 2 times or more,\n aswell as removing any consonant that appears 3 times or more.\n \"\"\"\n for tweet in tweets:\n textbody = tweet.text\n \n for vowel in vowels:\n pattern = re.compile(vowel*3+\"*\")\n try:\n textbody = pattern.sub(vowel, textbody)\n except UnicodeDecodeError:\n textbody = pattern.sub(vowel, textbody.decode('utf8'))\n for consonant in consonants:\n pattern = re.compile(consonant+consonant+consonant+consonant+\"*\")\n try:\n textbody = pattern.sub(consonant*2, textbody)\n except UnicodeDecodeError:\n textbody = pattern.sub(consonant*2, textbody.decode('utf8'))\n\n tweet.text = textbody\n return tweets\n\ndef remove_specialchars(tweets):\n \"\"\"\n Removes certain special characters. Does not remove !, ?, or ., as these are neeeded for the POS tagger to separate phrases.\n \"\"\"\n for tweet in tweets:\n textbody = tweet.text\n pattern = re.compile('({|}|[|]|-|:|\"|@|\\*|\\)|\\()')\n try:\n textbody = pattern.sub(\"\", textbody)\n except UnicodeDecodeError:\n textbody = pattern.sub(\"\", textbody.decode('utf8'))\n try:\n textbody = string.replace(textbody, \"_\", \" \")\n except UnicodeEncodeError:\n textbody = string.replace(textbody.decode('utf8'), \"_\", \" \")\n# textbody = string.replace(textbody, \"?\", \"\")\n# textbody = string.replace(textbody, \".\", \"\")\n# textbody = string.replace(textbody, \"!\", \"\")\n tweet.text = textbody\n return tweets\n\ndef remove_specialchars_round2(tweets):\n for tweet in tweets:\n textbody = tweet.text\n pattern = re.compile('({|}|[|]|-|:|\"|@|\\*|\\)|\\(|\\\\|.)')\n try:\n textbody = pattern.sub(\"\", textbody)\n except UnicodeDecodeError:\n textbody = pattern.sub(\"\", textbody.decode('utf8'))\n try:\n textbody = string.replace(textbody, \"_\", \" \")\n except UnicodeEncodeError:\n textbody = string.replace(textbody.decode('utf8'), \"_\", \" \")\n# textbody = string.replace(textbody, \"?\", \"\")\n# textbody = string.replace(textbody, \".\", \"\")\n# textbody = string.replace(textbody, \"!\", \"\")\n tweet.text = textbody\n return tweets\n\ndef remove_hastags_and_users(tweets):\n \"\"\"\n Removes hashtag labels and user labels, whenever it encounters a hashtag, it increments the hashtag counter in the respective tweet object. Stores both hastags and users in the tweet objects.\n \"\"\"\n for tweet in tweets:\n textbody = \"\"\n for word in tweet.text.split(\" \"):\n if len(word)<1:continue\n tweet.word_count = tweet.word_count +1 \n if not word[0]==\"#\" and not word[0]==\"@\":\n textbody = textbody+word+\" \"\n if word[0]==\"#\":\n tweet.nrof_hashtags = tweet.nrof_hashtags + 1\n tweet.hashtags.append(word[1:])\n textbody = textbody + \" \"\n if word[0]==\"@\":\n tweet.nrof_usersmentioned = tweet.nrof_usersmentioned +1\n tweet.users_mentioned.append(word[1:])\n textbody = textbody + word[1:] + \" \"\n tweet.text = textbody \n return tweets\n\ndef count_emoticons(tweets):\n \"\"\"\n Counts emoticons, whenever it encounters an emoticon, it increments the emoticon counter in the respective tweet object.\n \"\"\" \n for tweet in tweets:\n textbody = tweet.text\n tweet.nrof_happyemoticons = string.count(textbody, \":)\") + string.count(textbody, \":D\")\n tweet.nrof_sademoticons = string.count(textbody, \":(\") + string.count(textbody, \":'(\") + string.count(textbody, \":,(\")\n for emoticon in emoticon_class:\n tweet.text = string.replace(textbody, emoticon, \"\")\n return tweets\n\ndef count_exclamations(tweets):\n \"\"\"\n Counts exclamation marks and question marks, stores their number for future feature use. Then removes all sentence stops.\n Possibly handle / in a separate manner; keep only one of the words...?\n \"\"\"\n for tweet in tweets:\n textbody = tweet.text\n tweet.nrof_exclamations = string.count(textbody, \"!\")\n tweet.nrof_questionmarks = string.count(textbody, \"?\")\n\n pattern = re.compile('(\\?|!|\\.|:)')\n textbody = pattern.sub(\"\", textbody)\n tweet.text = textbody\n return tweets\n\ndef replace_links(tweets):\n \"\"\"\n Replaces any links in the tweets with a link class, saves links in the list in the tweet object.\n \"\"\"\n for tweet in tweets:\n links = [word for word in tweet.text.split(' ') if word[:4]==\"http\" or word[:3]==\"www\"]\n link_replaced_text = \" \".join([\"\" if word[:4]==\"http\" or word[:3]==\"www\" else word for word in tweet.text.split(' ')])\n tweet.text = link_replaced_text\n tweet.links = links \n return tweets\n\ndef remove_stopwords(tweets):\n \"\"\"\n Removes common stopwords based on a created stopword list.\n \"\"\"\n return tweets\n\ndef lower_case(tweets):\n \"\"\"\n Lowercases every text body in the tweets\n \"\"\"\n for tweet in tweets:\n textbody = tweet.text\n tweet.text = textbody.lower()\n return tweets\n\ndef stem(tweets):\n \"\"\"\n Stems and splits the tweet texts and stores them in the processed words list in the tweet object. \n \"\"\"\n return tweets\n\ndef tokenize(tweets):\n for tweet in tweets:\n splits = tweet.text.split(\" \")\n tweet.processed_words = [word for word in splits if len(word)>1]\n return tweets\n\n\ndef pos_tag(tweets):\n \"\"\"\n Uses the POS tagger interface to tag part-of-speech in all the tweets texts, stores it as dict in the tweet objects.\n \"\"\"\n print \"Tagging...\"\n untagged_texts = []\n for tweet in tweets:\n tagger = Tagger()\n textbody = tweet.text\n for phrase in re.split(\"\\.|!|\\?\", textbody):\n if len(phrase)<2: continue\n phrase = string.replace(phrase, \"?\", \"\")\n phrase = string.replace(phrase, \"!\", \"\")\n phrase = string.replace(phrase, \".\", \"\")\n tags = tagger.tag_text(phrase)\n if tags!=None:\n tweet.tagged_words.append(tags)\n print \"Untagged texts: \"\n for text in untagged_texts:\n print text\n print \"Tagging done.\"\n return tweets\n\ndef remove_link_classes(tweets):\n \"\"\"\n Removes the link classes from the given tweets, returns the positions of these links.\n \"\"\"\n for t in tweets:\n t.link_pos = [m.start() for m in re.finditer('\\<link\\>', t.text)] \n link_replaced_text = \" \".join([\"\" if word==\"<link>\" else word for word in t.text.split(' ')])\n t.text = link_replaced_text\n return tweets\n\ndef bing_lexicon_lookup():\n \"\"\"\n Fetches the tweets and performs lexicon translatino and lookup.\n \"\"\"\n tweets = utils.get_pickles(0)\n words_with_values = lexicon.perform_bing_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/sentimentvalues_random_dataset\")\n tweets = utils.get_pickles(1)\n words_with_values = lexicon.perform_bing_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/sentimentvalues_rosenborg_dataset\")\n tweets = utils.get_pickles(2)\n words_with_values = lexicon.perform_bing_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/sentimentvalues_erna_dataset\")\n\ndef google_lexicon_lookup():\n \"\"\"\n Fetches the tweets and performs lexicon translatino and lookup.\n \"\"\"\n tweets = utils.get_pickles(0)\n words_with_values = lexicon.perform_google_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/google_sentimentvalues_random_dataset\")\n tweets = utils.get_pickles(1)\n words_with_values = lexicon.perform_google_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/google_sentimentvalues_rosenborg_dataset\")\n tweets = utils.get_pickles(2)\n words_with_values = lexicon.perform_google_sentiment_lexicon_lookup(tweets)\n print \"Storing...\"\n utils.store_sentimentvalues(words_with_values, \"models/google_sentimentvalues_erna_dataset\")\n \ndef re_analyze():\n \"\"\"\n Unpickles preprocessed tweets and performs reanalyzis of these, then stores stats.\n \"\"\"\n labels = [\"random\",'\"rosenborg\"','\"erna solberg\"']\n data = {}\n worddata = {}\n for i in xrange(3):\n tweets = utils.get_pickles(i)\n analyzer = Analyzer(utils.annotated_datasets[i], tweets)\n \n avg_list,words_list= analyzer.analyze()\n print avg_list\n worddata[labels[i]] = words_list\n data[labels[i]] = avg_list\n plotting.average_wordclasses(worddata, \"averages\")\n\n plotting.detailed_average_wordclasses(data, \"averages2\")\n\ndef pos_analyze():\n \"\"\"\n Unpickles preprocessed tweets and performs pos-analysis of them. Then stores the stats in a diagram.\n \"\"\"\n tweets = utils.get_pickles(3)\n subjectivity_data, polarity_data = pos_tag_analyze(tweets)\n plotting.plot_pos_analysis(subjectivity_data, \"sub_analysis\")\n plotting.plot_pos_analysis(polarity_data, \"pos_analysis\")\n return True\n\ndef initial_preprocess_all_datasets():\n \"\"\"\n Runs first preprocessing iteration on all datasets.\n This is the preprocessing routine performed initially on the datasets before annotation.\n This routine includes duplicate removal\n \"\"\"\n \n for i in range(0,len(utils.datasets)):\n #Fetch from dataset\n tweets = []\n tweetlines = utils.get_dataset(utils.complete_datasets[i])\n for tweetline in tweetlines:\n tweets.append(tweet.to_tweet(tweetline))\n \n #Perform preprocessing\n tweets = remove_duplicates_and_retweets(tweets)\n\n #Store back to dataset\n tweetlines = []\n for t in tweets:\n tweetlines.append(t.to_tsv())\n utils.store_dataset(tweetlines, utils.datasets[i])\n \ndef classification_preprocess_all_datasets():\n \"\"\"\n Preprocesses all datasets to be ready for classification task.\n This will include stemming, word correction, lower-casing, hashtag removal, special char removal.\n \"\"\"\n \n for i in range(0,len(utils.annotated_datasets)):\n tweetlines = utils.get_dataset(utils.annotated_datasets[i])\n tweets = []\n for line in tweetlines:\n if len(line)>1:\n tweets.append(tweet.to_tweet(line))\n \n# tweets = lower_case(tweets)\n tweets = remove_hastags_and_users(tweets)\n tweets = count_emoticons(tweets)\n tweets = replace_links(tweets)\n tweets = remove_specialchars(tweets)\n tweets = correct_words(tweets)\n tweets = stem(tweets)\n tweets = tokenize(tweets)\n tweets = pos_tag(tweets)\n tweets = count_exclamations(tweets)\n\n analyzer = Analyzer(utils.annotated_datasets[i], tweets)\n stats = analyzer.analyze()\n print stats\n #store tweets in pickles...\n print \"Storing pickles...\"\n utils.store_pickles(tweets, utils.annotated_datasets[i][24:len(utils.annotated_datasets[i])-4])\n\ndef preprocess_tweets(tweets):\n# tweets = lower_case(tweets)\n print \"Preprocessing\"\n tweets = remove_retweet_tags(tweets)\n tweets = remove_hastags_and_users(tweets)\n tweets = count_emoticons(tweets)\n tweets = replace_links(tweets)\n tweets = remove_specialchars(tweets)\n tweets = correct_words(tweets)\n tweets = stem(tweets)\n tweets = tokenize(tweets)\n tweets = pos_tag(tweets)\n tweets = count_exclamations(tweets)\n return tweets\n \ndef preprocess_tweet(tweet):\n \"\"\"\n Preprocess a single tweet\n \"\"\"\n tweets = [tweet] \n tweets = remove_hastags_and_users(tweets)\n tweets = count_emoticons(tweets)\n tweets = replace_links(tweets)\n tweets = remove_specialchars(tweets)\n tweets = correct_words(tweets)\n tweets = stem(tweets)\n tweets = tokenize(tweets)\n tweets = pos_tag(tweets)\n tweets = count_exclamations(tweets)\n return tweets[0]\n\n \nvowels = [u\"a\", u\"e\", u\"i\", u\"o\", u\"u\", u\"y\", u\"\\u00E6\", u\"\\u00D8\", u\"\\u00E5\"]\nconsonants = [u\"b\", u\"c\", u\"d\", u\"f\", u\"g\", u\"h\", u\"j\", u\"k\", u\"l\", u\"m\", u\"n\", u\"p\", u\"q\", u\"r\", u\"s\", u\"t\", u\"v\", u\"w\", u\"x\", u\"z\"]\n\nemoticon_class = [\":)\",\":D\",\":(\",\":'(\"]\n\n\nspecial_chars_removal = '(<|>|{|}|[|]|-|_|*|\")'\n\nreplacement_chars = {u\"&\": u\"og\",\n u\"6amp;\": u\"og\",\n u\"+\": u\"og\"}\n \nif __name__ == '__main__':\n #Testing\n# tweets = [Tweet(\"13:37\", \"johnarne\", \"Jeg () haaater drittt!!!? :( #justinbieber\"), Tweet(\"13:37\", \"johnarne\", \"Jeg eeelsker @erna_solberg http://www.erna.no :) #love #jernerna\" )]\n# for tweet in tweets:\n# tweet.set_sentiment(\"negative\")\n# print tweet\n \n tweetlines = utils.get_dataset(\"test_annotated_data/erna_dataset.tsv\")\n tweets = []\n for line in tweetlines:\n if len(line)>1:\n tweets.append(tweet.to_tweet(line))\n \n \n# tweets = lower_case(tweets)\n tweets = remove_hastags_and_users(tweets)\n tweets = count_emoticons(tweets)\n tweets = replace_links(tweets)\n tweets = remove_specialchars(tweets)\n for tweet in tweets:\n print tweet\n tweets = correct_words(tweets)\n tweets = stem(tweets)\n tweets = tokenize(tweets)\n for tweet in tweets:\n print tweet.stat_str()\n tweets = pos_tag(tweets)\n tweets = count_exclamations(tweets)\n for tweet in tweets:\n print tweet.stat_str()\n \n analyzer = Analyzer(\"test_annotated_data/erna_dataset.tsv\", tweets)\n stats = analyzer.analyze()\n print stats\n \n \n\n" } ]
24
myousif9/MP2RAGE-wrapper
https://github.com/myousif9/MP2RAGE-wrapper
71f9d87e076a8acea7a5c809f6b2c2f2a50f2e00
ee7315dc25e568f7898072b9d2a1572e7114e2b9
7e1b8f62e6c708d948e6b5c2c5cb45d9d6131191
refs/heads/master
2020-07-01T19:58:18.199988
2020-01-15T16:27:45
2020-01-15T16:27:45
201,281,431
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8021390438079834, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 30.16666603088379, "blob_id": "9b570d4855df2ed456df5200b5b14ee82ffbaa30", "content_id": "3bd2e1a42f3d33f63ca1befbd4f85d12be2d9128", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 187, "license_type": "no_license", "max_line_length": 94, "num_lines": 6, "path": "/README.md", "repo_name": "myousif9/MP2RAGE-wrapper", "src_encoding": "UTF-8", "text": "# MP2RAGE-wrapper\n\nnipype wrapper for running background remover from Jose Marque's MP2RAGE related scripts repository\n\nlink to source:\nhttps://github.com/JosePMarques/MP2RAGE-related-scripts\n" }, { "alpha_fraction": 0.5642633438110352, "alphanum_fraction": 0.5753273367881775, "avg_line_length": 54.9072151184082, "blob_id": "0ce60744ed1a3b3363c0962f49a9b472ebe95966", "content_id": "593d2a838d619fb30db4083a43f3e87d76bf1403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5423, "license_type": "no_license", "max_line_length": 160, "num_lines": 97, "path": "/create_pipeline_bg_remover.py", "repo_name": "myousif9/MP2RAGE-wrapper", "src_encoding": "UTF-8", "text": "from bg_remover_wrapper import bgremover\nfrom nipype.interfaces.io import DataGrabber, DataSink\nfrom nipype.interfaces import utility as niu\nfrom nipype.pipeline import Node, MapNode, Workflow\nfrom nipype.interfaces.utility import Function\nfrom bids.layout import BIDSLayout\nimport sys\nimport os\n\ndef replace_slash_fn(filename): \n renamed=\"_\".join(str(filename).split(\"/\")) \n return renamed\nreplace_slash = Function(input_names=[\"filename\"],\n output_names=[\"renamed\"],\n function=replace_slash_fn)\n\ndef create_pipeline_bgremover(bids_dir,work_dir,out_dir,subjects,sessions,reg,uni_match_pattern,inv1_match_pattern,inv2_match_pattern):\n layout=BIDSLayout(bids_dir)\n for subject in subjects:\n if layout.get_sessions(subject=subject)==[]:\n if sessions==['.*']:\n first_uni_files=first_uni_files+layout.get(subject=subject,modality='anat',extensions='.*UNI.*.nii.*',)\n first_inv1_files=first_inv1_files+layout.get(subject=subject,modality='anat',extention='.*inv-1.*.nii.*')\n first_inv2_files=first_inv2_files+layout.get(subject=subject,modality='anat',extention='.*inv-2.*.nii.*')\n else:\n print(\"Warning: Session filter applied, but subject \"+subject+\"has no bids session information. This subject has been ignored.\")\n else:\n for session in sessions:\n first_uni_files=first_uni_files+layout.get(subject=subject,session=session,modality='anat',extensions='.*UNI.*.nii.*',)\n first_inv1_files=first_inv1_files+layout.get(subject=subject,session=session,modality='anat',extention='.*inv-1.*.nii.*')\n first_inv2_files=first_inv2_files+layout.get(subject=subject,session=session,modality='anat',extention='.*inv-2.*.nii.*')\n uni_folders=[]\n for img in first_uni_files:\n full_dirname=os.path.dirname(img.filename)\n remove_base_dir=full_dirname.replace(bids_dir,'')\n remove_leading_slash=remove_base_dir.lstrip(os.sep)\n uni_folders.append(remove_leading_slash)\n list(set(uni_folders)).sort()\n\n inv1_folders=[]\n for img in first_inv1_files:\n full_dirname=os.path.dirname(img.filename)\n remove_base_dir=full_dirname.replace(bids_dir,'')\n remove_leading_slash=remove_base_dir.lstrip(os.sep)\n inv1_folders.append(remove_leading_slash)\n list(set(inv1_folders)).sort()\n\n inv2_folders=[]\n for img in first_inv2_files:\n full_dirname=os.path.dirname(img.filename)\n remove_base_dir=full_dirname.replace(bids_dir,'')\n remove_leading_slash=remove_base_dir.lstrip(os.sep)\n inv2_folders.append(remove_leading_slash)\n list(set(inv2_folders)).sort()\n\n infosource_uni = Node(niu.IdentityInterface(fields=['uni']), name='infosource_uni')\n infosource_uni.iterables = ('uni',uni_folders)\n infosource_inv1 = Node(niu.IdentityInterface(fields=['inv1']),name='infosource_inv1')\n infosource_inv1.iterables = ('inv1',inv1_folders)\n infosource_inv2 = Node(niu.IdentityInterface(fields=['inv2']),name='infosource_inv2')\n infosource_inv2.iterables = ('inv2',inv2_folders)\n\n datasource=Node(DataGrabber(infields=['uni','inv1','inv2'],outfields=['uni_image','inv1_image','inv2_image']),name='datasource')\n datasource.inputs.field_template=dict(\n uni_image='%s/'+uni_match_pattern+'.nii*',\n inv1_image='%d/'+inv1_match_pattern+'.nii*',\n inv2_image='%f/'+inv2_match_pattern+'.nii*')\n datasource.inputs.sort_filelist=True\n datasource.inputs.template=\"*\"\n datasource.inputs.base_directory=bids_dir\n \n t1w_gen = Node(bgremover(reg=reg),name = 'background_remover')\n \n datasink = Node(DataSink(),name = 'datasink')\n datasink.inputs.base_directory = out_dir +'/bg_remover/'\n datasink.inputs.parameterization=False\n\n rename_infosource=Node(replace_slash,\"rename_infosource\")\n rename_t1w=Node(niu.Rename(format_string=\"%(uni)s-T1w\", keep_ext = True),\"rename_T1w\")\n \n pipelineDir=work_dir\n wf = Workflow(name='bg_remover')\n wf.base_dir=pipelineDir\n wf.config['excecution']['remove_unnecessary_outputs']=False\n wf.connect([\n (infosource_uni,datasource,[('uni','uni')]),\n (infosource_inv1,datasource,[('inv1','inv1')]),\n (infosource_inv2,datasource,[('inv2','inv2')]),\n (datasource, t1w_gen, [('uni_image','uni_in'),\n ('inv1_image','inv1_in'),\n ('inv2_image','inv2_in')]),\n (t1w_gen, datasink, [('out_file','in_file')]),\n (infosource_uni,rename_infosource, [('uni','filename')]),\n (rename_infosource,rename_t1w,[('renamed','uni')]),\n (rename_t1w,datasink,[('out_file','@')])\n ])\n return wf\n" }, { "alpha_fraction": 0.5473434329032898, "alphanum_fraction": 0.5523894429206848, "avg_line_length": 50.04545593261719, "blob_id": "95c72317cce61e7c1f4ed808b3269c4a8eb7a032", "content_id": "07d55dd9d82cbcca19f2334aa2a0b55f4357eebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3369, "license_type": "no_license", "max_line_length": 100, "num_lines": 66, "path": "/bg_remover_wrapper.py", "repo_name": "myousif9/MP2RAGE-wrapper", "src_encoding": "UTF-8", "text": "from nipype.interfaces.matlab import MatlabCommand\nfrom nipype.interfaces.base import TraitedSpec, BaseInterface, BaseInterfaceInputSpec,File,traits\nimport os\nfrom string import Template\n\nmatlab_script_loc = os.path.join(os.path.dirname(os.path.realpath(__file__)),'matlab_script)')\nclass bgremover_InputSpec(BaseInterfaceInputSpec):\n uni_in = File(exists=True,\n desc='input file for UNI image',\n argstr=\"%s\",\n mandatory=True)\n inv1_in = File(exisits=True,\n desc='input file for INV1 image',\n argstr=\"%s\",\n mandatory=True)\n inv2_in = File(exisits=True,\n desc='input file for INV2 image',\n argstr=\"%s\",\n mandatory=True)\n reg = traits.Float(desc='input value for regularization')\n out_file = File('t1w_gen.nii.gz',\n desc='name of output T1w image',\n genfile=True,\n usedefault=True)\n\nclass bgremover_OutputSpec(TraitedSpec):\n out_file=File(desc=\"path/name of T1w file (if generated)\",usedefault=True)\n\nclass bgremover(BaseInterface):\n input_spec = bgremover_InputSpec\n output_spec = bgremover_OutputSpec\n def _run_interface(self, runtime):\n# d = dict(uni = self.inputs.uni_in,\n# inv1 = self.inputs.inv1_in,\n# inv2 = self.inputs.inv2_in,\n# reg = self.inputs.reg,\n# denoise = self.inputs.out_file)\n\n with open(os.path.join(matlab_script_loc,'DemoRemoveBackgroundNoise.m'),'r') as script_file:\n script_content = script_file.read()\n \n script = script_content.format(uni = self.inputs.uni_in,\n inv1 = self.inputs.inv1_in,\n inv2 = self.inputs.inv2_in,\n denoise = self.inputs.out_file,\n reg = self.inputs.reg)\n \n mlab = MatlabCommand(script=script, mfile=True)\n mlab.inputs.paths = [os.path.join(matlab_script_loc,'func/RobustCombination.m'),\n os.path.join(matlab_script_loc,'nii_func/load_nii_ext.m'),\n os.path.join(matlab_script_loc,'nii_func/load_nii_hdr.m'),\n os.path.join(matlab_script_loc,'nii_func/load_untouch0_nii_hdr.m'),\n os.path.join(matlab_script_loc,'nii_func/load_untouch_nii.m'),\n os.path.join(matlab_script_loc,'nii_func/load_untouch_nii_hdr.m'),\n os.path.join(matlab_script_loc,'nii_func/load_untouch_nii_img.m'),\n os.path.join(matlab_script_loc,'nii_func/save_nii_ext.m'),\n os.path.join(matlab_script_loc,'nii_func/save_untouch0_nii_hdr.m'),\n os.path.join(matlab_script_loc,'nii_func/save_untouch_nii.m'),\n os.path.join(matlab_script_loc,'nii_func/save_untouch_nii_hdr.m'),\n os.path.join(matlab_script_loc,'nii_func/verify_nii_ext.m')]\n result = mlab.run()\n return result.runtime\n def _list_outputs(self):\n outputs = self._outputs().get()\n outputs['out_file'] = os.path.abspath(self.inputs.out_file)\n return outputs\n" }, { "alpha_fraction": 0.5271561145782471, "alphanum_fraction": 0.5300071239471436, "avg_line_length": 53.8125, "blob_id": "1f46970bb7b199291f8c4b8d6027b47f813dc300", "content_id": "ef6a144e21651e7e389f761610e08b4726d4a972", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7015, "license_type": "no_license", "max_line_length": 124, "num_lines": 128, "path": "/run.py", "repo_name": "myousif9/MP2RAGE-wrapper", "src_encoding": "UTF-8", "text": "from create_pipeline_bg_remover import create_pipeline_bgremover\nimport os\n\nif __name__==\"__main__\":\n from argparse import ArgumentParser, RawTextHelpFormatter\n from nipype import config, logging\n defstr = ' (default %(default)s)'\n parser = ArgumentParser(description=__doc__,\n formatter_class=RawTextHelpFormatter)\n\n parser.add_argument('bids_dir',help='the directory with the input dataset formatted according to the BIDS standard.')\n parser.add_argument('output_dir', help='The directory where the output files '\n 'should be stored. If you are running group level analysis '\n 'this folder should be prepopulated with the results of the'\n 'participant level analysis.')\n parser.add_argument('--participant_label', help='The label(s) of the participant(s) that should be analyzed. The label '\n 'corresponds to sub-<participant_label> from the BIDS spec '\n '(so it does not include \"sub-\"). If this parameter is not '\n 'provided all subjects should be analyzed. Multiple '\n 'participants can be specified with a space separated list.',\n default=['.*'],\n nargs=\"+\") \n parser.add_argument('--session_label', help='The label(s) of the session(s) that should be analyzed. The label '\n 'corresponds to ses-<session_label> from the BIDS spec '\n '(so it does not include \"ses-\"). If this parameter is not '\n 'provided all sessions should be analyzed. Multiple '\n 'sessions can be specified with a space separated list.',\n default=['.*'],\n nargs=\"+\") \n parser.add_argument(\"-w\", \"--work_dir\", dest=\"work_dir\",\n help=\"Work directory. Defaults to <output_dir>/scratch\")\n parser.add_argument(\"-l\", \"--log_dir\", dest=\"log_dir\",\n help=\"Nipype output log directory. Defaults to <output_dir>/log\")\n parser.add_argument(\"-c\", \"--crash_dir\", dest=\"crash_dir\",\n help=\"Nipype crash dump directory. Defaults to <output_dir>/crash_dump\")\n parser.add_argument(\"-p\", \"--plugin\", dest=\"plugin\",\n default='Linear',\n help=\"Plugin to use\")\n parser.add_argument(\"--plugin_args\", dest=\"plugin_args\",\n help=\"Plugin arguments\")\n parser.add_argument(\"--keep_unnecessary_outputs\", dest=\"keep_unnecessary_outputs\",\n action='store_true',default=False,\n help=\"keep all nipype node outputs, even if unused\")\n parser.add_argument('--uni_match_pattern', dest=\"uni_match_pattern\",\n default='*UNI*',\n help='Pattern used to match UNI images and json files '\n 'in anat folder (leave extension out of pattern). The '\n 'pattern may contain simple shell-style wildcards a la '\n 'fnmatch. However, unlike fnmatch, filenames starting with '\n 'a dot are special cases that are not matched by \\'*\\' and '\n '\\'?\\' patterns. Example usage: *acq-uni*') \n parser.add_argument('--inv1_match_pattern', dest=\"inv1_match_pattern\",\n default='*inv-1*',\n help='Pattern used to match inv1 images and json files '\n 'in anat folder (leave extension out of pattern). The '\n 'pattern may contain simple shell-style wildcards a la '\n 'fnmatch. However, unlike fnmatch, filenames starting with '\n 'a dot are special cases that are not matched by \\'*\\' and '\n '\\'?\\' patterns. Example usage: *inv-1*') \n parser.add_argument('--inv2_pattern', dest=\"inv2_match_pattern\",\n default='*inv-2*',\n help='Pattern used to match inv2 images and json files '\n 'in anat folder (leave extension out of pattern). The '\n 'pattern may contain simple shell-style wildcards a la '\n 'fnmatch. However, unlike fnmatch, filenames starting with '\n 'a dot are special cases that are not matched by \\'*\\' and '\n '\\'?\\' patterns. Example usage: *inv-2*') \n parser.add_argument(\"--regularization\", dest=\"regularization\",\n default=10,\n help=\"regularization parameter\")\n args = parser.parse_args()\n \n\n bids_dir=args.bids_dir\n out_dir=args.output_dir\n \n uni_match_pattern=args.uni_match_pattern\n inv1_match_pattern=args.inv1_match_pattern\n inv2_match_pattern=args.inv2_match_pattern \n subjects=args.participant_label\n sessions=args.session_label\n \n if args.work_dir:\n work_dir = os.path.abspath(args.work_dir)\n else:\n work_dir = os.path.join(out_dir, 'scratch')\n if args.log_dir:\n log_dir = os.path.abspath(args.log_dir)\n else:\n tmp=\"log-\"+\"_\".join(subjects)+'-'+\"_\".join(sessions)\n tmp=tmp.replace(\".*\",\"all\").replace(\"*\",\"star\")\n log_dir = os.path.join(out_dir, 'logs',tmp)\n if args.crash_dir:\n crash_dir = os.path.abspath(args.crash_dir)\n else:\n crash_dir = os.path.join(out_dir, 'crash_dump')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n \n config.update_config({'logging': {\n 'log_directory': log_dir,\n 'log_to_file': True,\n },\n 'execution': {\n 'crashdump_dir': crash_dir,\n 'crashfile_format': 'txt', \n }})\n logging.update_logging(config)\n \n plugin=args.plugin\n plugin_args=args.plugin_args\n keep_unnecessary_outputs=args.keep_unnecessary_outputs\n\n regularization = float(args.regularization)\n\n wf_bg_remover = create_pipeline_bgremover(bids_dir=bids_dir,\n work_dir=work_dir,\n out_dir=out_dir,\n subjects=subjects,\n sessions=sessions,\n reg=regularization,\n uni_match_pattern=uni_match_pattern,\n inv1_match_pattern=inv1_match_pattern,\n inv2_match_pattern=inv2_match_pattern)\n if args.plugin_args:\n exec_bg_remover=wf_bg_remover.run(args.plugin, plugin_args=eval(args.plugin_args))\n else:\n exec_bg_remover=wf_bg_remover.run(args.plugin)" }, { "alpha_fraction": 0.774193525314331, "alphanum_fraction": 0.8387096524238586, "avg_line_length": 31, "blob_id": "c51672e431411a2d461c6088fad7422af71976c9", "content_id": "a73264ddbc22374815d1a32a83ee6457d71bcab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 31, "license_type": "no_license", "max_line_length": 31, "num_lines": 1, "path": "/MP2RAGE-wrapper/__init__.py", "repo_name": "myousif9/MP2RAGE-wrapper", "src_encoding": "UTF-8", "text": "from .t1w_wrapper import T1wgen" } ]
5
nityamd/Insight
https://github.com/nityamd/Insight
6d70e4a181c4782dc3d6a7da500450c9586c81d3
1016eafe3b9968332175a7445f467fab01efd59f
f4f8262a6678f9b4705395878dcbf8e2ba31349c
refs/heads/master
2022-12-04T10:42:49.337325
2019-07-25T21:09:08
2019-07-25T21:09:08
149,144,556
0
0
null
2018-09-17T15:12:36
2019-07-25T21:09:15
2022-12-02T13:06:59
HTML
[ { "alpha_fraction": 0.6189896464347839, "alphanum_fraction": 0.6354230046272278, "avg_line_length": 40.07500076293945, "blob_id": "9d060bc9b5436648c166160e752fca08acdc90d7", "content_id": "713765a6ba43ef4233524c21c8a355832f1cef15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1643, "license_type": "no_license", "max_line_length": 83, "num_lines": 40, "path": "/scripts/classifier.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport itertools\nimport gensim\nimport keras\nimport nltk\nimport re\nimport codecs\nimport os\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score\nfrom sklearn.metrics import confusion_matrix, recall_score, classification_report\nfrom sklearn.linear_model import LogisticRegression\n\ndef ttsplit(thing):\n list_corpus = df[str(thing)].tolist()\n list_labels = df['class_label'].tolist()\n indices = np.arange(len(list_labels))\n x_train, x_test, y_train, y_test, i1, i2 = train_test_split(list_corpus,\n list_labels,\n indices,\n test_size=0.2,\n random_state=40)\n return x_train, x_test, y_train, y_test, i1, i2\n\nx1_ti, x2_ti, y1_ti, y2_ti, i1, i2 = ttsplit('title')\nx1_des, x2_des, y1_des, y2_des, i1, i2 = ttsplit('description')\nclf_tfidf = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg',\n multi_class='multinomial', n_jobs=-1, random_state=40)\n\nclf_tfidf.fit(X_train_tfidf, y_train)\ny_predicted_tfidf = clf_tfidf.predict(X_test_tfidf)\n" }, { "alpha_fraction": 0.5963909029960632, "alphanum_fraction": 0.6021082997322083, "avg_line_length": 32.9151496887207, "blob_id": "e7d8de6cf5bf751d182aa80dddb7455bf5d6611e", "content_id": "7126c1fb68708f1804a49d7829b5f96183757933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5597, "license_type": "no_license", "max_line_length": 89, "num_lines": 165, "path": "/scripts/peppa.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport numpy as np\nimport requests\nimport os\n\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\n#from google.auth.tools import argparser\nfrom youtube_transcript_api import YouTubeTranscriptApi\n\nf = open('/Users/nitya/youtopian/youtube', 'r')\nDEVELOPER_KEY = f.read().strip()\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\nyoutube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,developerKey=DEVELOPER_KEY)\n\n\ndef get_video_id(q, max_results,token, order=\"relevance\",\n location=None, location_radius=None):\n\n search_response = youtube.search().list(\n q=q, type=\"video\", pageToken=token,part=\"id,snippet\",\n maxResults=max_results, location=location,\n locationRadius=location_radius, safeSearch = 'none').execute()\n videoId = []\n title = []\n description = []\n tok = search_response['nextPageToken']\n\n for search_result in search_response.get(\"items\", []):\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n title.append(search_result['snippet']['title'])\n videoId.append(search_result['id']['videoId'])\n response = youtube.videos().list(part='statistics, snippet',\n id=search_result['id']['videoId']\n ).execute()\n description.append(response['items'][0]['snippet']['description'])\n\n ydict = {'title':title,'videoId':videoId,\n 'description':description}\n return ydict, tok\n\ndef keyword_search(keyword, results_enter):\n\n tests, token0 = get_video_id(keyword, 50,order = \"relevance\",\n token= None)\n newdf = pd.DataFrame(tests)\n #Total number of results I need..:\n results = results_enter-50\n\n while results>50:\n tests, token0 = get_video_id(keyword, 50,order = \"relevance\",\n token= str(token0))\n df = pd.DataFrame(tests)\n newdf = pd.concat([newdf,df]).reset_index(drop=True)\n results = results-50\n\n filename = keyword.replace(\" \", \"_\") + '_' + str(results_enter)\n newdf.to_csv(filename)\n\n return\n\n\n# -- Getting Comments -----\n\ndef get_comment_threads(video_id, results):\n results = youtube.commentThreads().list(\n part=\"snippet\",\n videoId=video_id,\n textFormat=\"plainText\",\n maxResults = results\n ).execute()\n for item in results[\"items\"]:\n comment = item[\"snippet\"][\"topLevelComment\"]\n author = comment[\"snippet\"][\"authorDisplayName\"]\n text = comment[\"snippet\"][\"textDisplay\"]\n #print \"Comment by %s: %s\" % (author, text)\n ydict = {'videoId':videoId, 'Comment':comment}\n return ydict\n\n\n# Call the API's comments.list method to list the existing comment replies.\ndef get_comments(youtube, parent_id):\n results = youtube.comments().list(\n part=\"snippet\",\n parentId=parent_id,\n textFormat=\"plainText\",\n maxResults=100\n ).execute()\n for item in results[\"items\"]:\n author = item[\"snippet\"][\"authorDisplayName\"]\n text = item[\"snippet\"][\"textDisplay\"]\n #print \"Comment by %s: %s\" % (author, text)\n\n return results[\"items\"]\n\n#Search for videos by channel ID.....\n\ndef channel_snatch(q, max_results, token, channelId,\n order=\"relevance\"):\n\n search_response = youtube.search().list(\n q=q, type=\"video\", pageToken=token,part=\"id,snippet\",\n maxResults=max_results, channelId = channelId,\n location=None, locationRadius=None,\n safeSearch = 'strict').execute()\n videoId = []\n title = []\n description = []\n tok = search_response['nextPageToken']\n\n for search_result in search_response.get(\"items\", []):\n if search_result[\"id\"][\"kind\"] == \"youtube#video\":\n title.append(search_result['snippet']['title'])\n videoId.append(search_result['id']['videoId'])\n response = youtube.videos().list(part='statistics, snippet',\n id=search_result['id']['videoId']\n ).execute()\n description.append(response['items'][0]['snippet']['description'])\n\n ydict = {'title':title,'videoId':videoId,\n 'description':description}\n return ydict, tok\n\n\ndef search_by_channel(keyword, results_enter, channelId):\n\n tests, token0 = channel_snatch(keyword, 50,token= None,\n channelId = channelId)\n newdf = pd.DataFrame(tests)\n #Total number of results I need..:\n results = results_enter-50\n\n while results>50:\n tests, token0 = channel_snatch(keyword, 50,\n token= str(token0),\n channelId = channelId)\n df = pd.DataFrame(tests)\n newdf = pd.concat([newdf,df]).reset_index(drop=True)\n results = results-50\n\n filename = keyword.replace(\" \", \"_\") + '_' + 'channel' + str(results_enter)\n newdf.to_csv(filename)\n return\n\n\n\n# Call the API's captions.list method to list the existing caption tracks.\ndef list_captions(youtube, video_id):\n results = youtube.captions().list(\n part=\"snippet\",\n videoId=video_id\n ).execute()\n for item in results[\"items\"]:\n id = item[\"id\"]\n name = item[\"snippet\"][\"name\"]\n language = item[\"snippet\"][\"language\"]\n #print \"Caption track '%s(%s)' in '%s' language.\" % (name, id, language)\n\n return results[\"items\"]\n\n #transcripts using requests requests..?\n" }, { "alpha_fraction": 0.6258603930473328, "alphanum_fraction": 0.6317600607872009, "avg_line_length": 27.23611068725586, "blob_id": "45baf9d1195981ee3d8885d3031f80238b1a4765", "content_id": "e9533c2dd6fe15e8878d2af52a2263b479b68b6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2034, "license_type": "no_license", "max_line_length": 76, "num_lines": 72, "path": "/my_flask_app/views.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "\nimport json\nimport pickle\nimport logging\n\nimport pandas as pd\nfrom flask import json, jsonify, request, render_template\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n\nfrom my_flask_app import app\nfrom ytapi_extractor import videoId_data, video_query\n\n\n\nafile = open(r'tfidf_model_description.pkl', 'rb')\ndes_model = pickle.load(afile, encoding = 'latin1')\nafile.close()\n\nafile = open(r'tfidf_vectorizer_description.pkl', 'rb')\ndes_vectorizer = pickle.load(afile, encoding = 'latin1')\nafile.close()\n\nafile = open(r'tfidf_model_title.pkl', 'rb')\nti_model = pickle.load(afile, encoding = 'latin1')\nafile.close()\n\nafile = open(r'tfidf_vectorizer_title.pkl', 'rb')\nti_vectorizer = pickle.load(afile, encoding='latin1')\nafile.close()\n\n\n\[email protected]('/')\[email protected]('/index')\ndef index():\n return render_template(\"index.html\")\n\[email protected]('/result', methods=['POST', 'GET'])\ndef result():\n if request.method == 'POST':\n result = request.form\n earl = result['URL']\n df = videoId_data(video_query(earl))\n #more comments here describing what's going on\n des_vector = des_vectorizer.transform(df['description'])\n des_rating = des_model.predict(des_vector)[0]\n ti_vector = ti_vectorizer.transform(df['title'])\n ti_rating = ti_model.predict(ti_vector)[0]\n rating = des_rating + ti_rating\n\n if rating == 2.0:\n output = 'Shady!'\n elif rating == 1.0:\n output = 'Shady? Clean?'\n else:\n output = 'Clean!'\n\n logging.warning(\"I'm so successful!\")\n logging.warning(rating)\n\n return render_template(\"result.html\",\n result = output,\n title = df['title'][0],\n description = df['description'][0])\n\[email protected]('/insight',methods = ['POST', 'GET'])\ndef insight():\n if request.method == 'POST':\n insight = request.form\n return render_template(\"insight.html\",result = result)\n\nif __name__ == '__main__':\n app.run(debug = True)\n" }, { "alpha_fraction": 0.635708212852478, "alphanum_fraction": 0.6547921895980835, "avg_line_length": 34.19403076171875, "blob_id": "13e575ebb3491386c16f40c66efb3b299b572851", "content_id": "25af60b12e04259cc0f947247803217f8f148345", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2358, "license_type": "no_license", "max_line_length": 87, "num_lines": 67, "path": "/scripts/tfidf.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport itertools\nimport gensim\nimport keras\nimport nltk\nimport re\nimport codecs\nimport os\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score\nfrom sklearn.metrics import confusion_matrix, recall_score, classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom nltk.tokenize import RegexpTokenizer\n\nos.chdir(\"/Users/nitya/childsplay/data\")\ndf = pd.read_csv('peppa_dataframe_with_labels')\ndf = df.drop_duplicates('videoId')\n\ndef ttsplit(thing):\n ''''\n Train-test splitting with indices\n ''''\n list_corpus = df[str(thing)].tolist()\n list_labels = df['class_label'].tolist()\n indices = np.arange(len(list_labels))\n x_train, x_test, y_train, y_test, i1, i2 = train_test_split(list_corpus,\n list_labels,\n indices,\n test_size=0.2,\n random_state=40)\n return x_train,x_test, y_train, y_test, i1, i2\n\nx1_ti, x2_ti, y1_ti, y2_ti, i1, i2 = ttsplit('title')\nx1_des, x2_des, y1_des, y2_des, i1, i2 = ttsplit('description')\n\n\n\ndef tfidf(data):\n tfidf_vectorizer = TfidfVectorizer()\n\n train = tfidf_vectorizer.fit_transform(data)\n\n return train, tfidf_vectorizer\n\nx1ti_tfidf, tfidf_vectorizer = tfidf(x1_ti)\nx2ti_tfidf = tfidf_vectorizer.transform(x2_ti)\n\nclf_tfidf_ti = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg',\n multi_class='multinomial', n_jobs=-1, random_state=40)\nclf_tfidf_ti.fit(x1ti_tfidf, y1_ti)\n\n\nx1des_tfidf, tfidf_vectorizer = tfidf(x1_des)\nx2des_tfidf = tfidf_vectorizer.transform(x2_des)\n\nclf_tfidf_des = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg',\n multi_class='multinomial', n_jobs=-1, random_state=40)\nclf_tfidf_des.fit(x1des_tfidf, y1_des)\n" }, { "alpha_fraction": 0.6214178204536438, "alphanum_fraction": 0.6244344115257263, "avg_line_length": 30.5238094329834, "blob_id": "e192cd8722229c08356252a74d842d4f731d97d4", "content_id": "6bfcee5b1bfb4825771a31a7d2abae063d6cddd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 85, "num_lines": 21, "path": "/scripts/preprocessing.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport numpy as np\nimport requests\nimport os\n\ndef sanitize_characters(raw, clean):\n for line in input_file:\n out = line\n output_file.write(line)\n\n\nsanitize_characters(input_file, output_file)\n\ndef standardize_text(df, text_field):\n df[text_field] = df[text_field].str.replace(r\"http\\S+\", \"\")\n df[text_field] = df[text_field].str.replace(r\"http\", \"\")\n df[text_field] = df[text_field].str.replace(r\"@\\S+\", \"\")\n df[text_field] = df[text_field].str.replace(r\"[^A-Za-z0-9(),!?@\\'\\`\\\"\\_\\n]\", \" \")\n df[text_field] = df[text_field].str.replace(r\"@\", \"at\")\n df[text_field] = df[text_field].str.lower()\n return df\n" }, { "alpha_fraction": 0.6282822489738464, "alphanum_fraction": 0.6422319412231445, "avg_line_length": 35.198020935058594, "blob_id": "0648c28762c9698a0f6b1efb9e1c187d57c0a42b", "content_id": "52d1b4ec9e8f3fe90a94ba896ee09beb6718074c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3656, "license_type": "no_license", "max_line_length": 87, "num_lines": 101, "path": "/scripts/w2v.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nimport itertools\nimport gensim\nimport keras\nimport nltk\nimport re\nimport codecs\nimport os\n\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import RegexpTokenizer\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.decomposition import PCA, TruncatedSVD\nfrom sklearn.metrics import accuracy_score, f1_score, precision_score\nfrom sklearn.metrics import confusion_matrix, recall_score, classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom nltk.tokenize import RegexpTokenizer\n\nos.chdir(\"/Users/nitya/childsplay/data\")\ndf = pd.read_csv('peppa_dataframe_with_labels')\ndf = df.drop_duplicates('videoId')\n\n\ntokenizer = RegexpTokenizer(r'\\w+')\ndf[\"des_tokens\"] =df[\"description\"].apply(tokenizer.tokenize)\ndf[\"ti_tokens\"] = df[\"title\"].apply(tokenizer.tokenize)\n\n\ndef get_average_word2vec(tokens_list, vector, generate_missing=False, k=300):\n if len(tokens_list)<1:\n return np.zeros(k)\n if generate_missing:\n vectorized = [vector[word] if word in vector else np.random.rand(k) for\n word in tokens_list]\n else:\n vectorized = [vector[word] if word in vector else np.zeros(k) for word\n in tokens_list]\n length = len(vectorized)\n summed = np.sum(vectorized, axis=0)\n averaged = np.divide(summed, length)\n return averaged\n\ndef get_word2vec_embeddings(vectors, data, generate_missing=False):\n embeddings = data['tokens'].apply(lambda x: get_average_word2vec\n (x, vectors, generate_missing=\n generate_missing))\n return list(embeddings)\n\n\nembeddings = get_word2vec_embeddings(word2vec, df)\n\ndef ttsplit(thing):\n '''\n Train-test splitting with indices\n '''\n list_corpus = df[str(thing)].tolist()\n list_labels = df['class_label'].tolist()\n indices = np.arange(len(list_labels))\n x_train, x_test, y_train, y_test, i1, i2 = train_test_split(embeddings,\n list_labels,\n indices,\n test_size=0.2,\n random_state=40)\n return x_train,x_test, y_train, y_test, i1, i2\n\nx1_ti, x2_ti, y1_ti, y2_ti, i1, i2 = ttsplit('title')\nx1_des, x2_des, y1_des, y2_des, i1, i2 = ttsplit('description')\n\n\n\nclf_tfidf_ti = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg',\n multi_class='multinomial', n_jobs=-1, random_state=40)\nclf_tfidf_ti.fit(x1ti_tfidf, y1_ti)\n\n\nx1des_tfidf, tfidf_vectorizer = tfidf(x1_des)\nx2des_tfidf = tfidf_vectorizer.transform(x2_des)\n\nclf_tfidf_des = LogisticRegression(C=30.0, class_weight='balanced', solver='newton-cg',\n multi_class='multinomial', n_jobs=-1, random_state=40)\nclf_tfidf_des.fit(x1des_tfidf, y1_des)\n\n# os.chdir(\"/Users/nitya/Insight\")\n# import pickle\n# afile = open(r'tfidf_vectorizer_title.pkl', 'wb')\n# pickle.dump(tfidf_vectorizer, afile)\n# afile.close()\n# afile = open(r'tfidf_model_title.pkl', 'wb')\n# pickle.dump(clf_tfidf_ti, afile)\n# afile.close()\n# afile = open(r'tfidf_vectorizer_description.pkl', 'wb')\n# pickle.dump(tfidf_vectorizer, afile)\n# afile.close()\n# afile = open(r'tfidf_model_description.pkl', 'wb')\n# pickle.dump(clf_tfidf_des, afile)\n# afile.close()\n" }, { "alpha_fraction": 0.6484375, "alphanum_fraction": 0.6484375, "avg_line_length": 17.285715103149414, "blob_id": "36def481d6dc63a1cba02512a45272830ee76ea3", "content_id": "443189e27112baf47f7fd320f31fd4ab974a3f89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 128, "license_type": "no_license", "max_line_length": 48, "num_lines": 7, "path": "/hobbes/popup.js", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "// var app = chrome.runtime.getBackgroundPage();\n\nfunction hello() {\n chrome.tabs.executeScript({\n file: 'alert.js'\n });\n}\n" }, { "alpha_fraction": 0.7260273694992065, "alphanum_fraction": 0.7260273694992065, "avg_line_length": 23.33333396911621, "blob_id": "3c83d3576215de3a90da0452790442f1e966b01b", "content_id": "aa50bcce038567bc06496a49f475f4c45c27248a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 73, "license_type": "no_license", "max_line_length": 28, "num_lines": 3, "path": "/run.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nfrom my_flask_app import app\napp.run(debug = True)\n" }, { "alpha_fraction": 0.7349397540092468, "alphanum_fraction": 0.759036123752594, "avg_line_length": 15.600000381469727, "blob_id": "f1a87d64679ccc33a8435994942db8e7761e0f0c", "content_id": "91f6eec9a2b24666a81d24b9a13ddce87d7db84c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/README.md", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "<h1>YouTopia</h1>\n\nGiving kids the ideal YouTube experience\n\nhttp://youtopia.site/\n" }, { "alpha_fraction": 0.6403326392173767, "alphanum_fraction": 0.6455301642417908, "avg_line_length": 28.121212005615234, "blob_id": "ec955a7ffaab5dcbf539f167f49740239a4dc6d6", "content_id": "158c82cdd603398b2f377c2fd480c0ca6faa7c71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 74, "num_lines": 33, "path": "/ytapi_extractor.py", "repo_name": "nityamd/Insight", "src_encoding": "UTF-8", "text": "\nimport pandas as pd\nimport numpy as np\nimport requests\nimport os\nfrom apiclient.discovery import build\nfrom apiclient.errors import HttpError\n\nf = open('/Users/nitya/youtopian/youtube', 'r')\nDEVELOPER_KEY = f.read().strip()\n\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\nYOUTUBE_API_VERSION = \"v3\"\nyoutube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\n developerKey=DEVELOPER_KEY)\n\n\ndef video_query(earl):\n video_id = earl.split('=')[-1]\n return video_id\n\ndef videoId_data(video_id):\n '''\n Use the API to get data\n for a single video\n by videoId\n '''\n video_response = youtube.videos().list(id=video_id,\n part='snippet').execute()\n title = video_response.get('items')[0]['snippet']['title']\n description = video_response.get('items')[0]['snippet']['description']\n ydict = {'title':title, 'description':description}\n df = pd.DataFrame(ydict, index = [0])\n return df\n" } ]
10
GroundP/OOP
https://github.com/GroundP/OOP
a319c3255a8cba6388054c933981dffb98ebb5a8
ea9436b8cd105b349a833fc6734c3d08893b1b03
538075bfe5559b7b859d99bae61d6905e55a7e38
refs/heads/master
2020-09-07T12:47:06.814684
2019-12-16T14:18:54
2019-12-16T14:18:54
220,785,930
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5159817337989807, "alphanum_fraction": 0.5633561611175537, "avg_line_length": 26.390625, "blob_id": "a563b9705ed5095f30dce4a4d20358eb6ea9871b", "content_id": "6c807cd76335443d33c5f80151f6a37afebe6bb7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2096, "license_type": "no_license", "max_line_length": 86, "num_lines": 64, "path": "/trapping_rain.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "''' Algorithm\n 문제설명 : n x m 크기의 바닥에 1x1x1 크기의 벽돌이 놓여 있습니다. 놓여 있는 벽돌 위로 비가 내리면 아래 그림과 물이 차오르게 됩니다.\n 이때 우리는 최대로 모을 수 있는 빗물의 양을 구하려고 합니다. (1x1x1 공간에 모인 빗물의 양은 1입니다.)'''\n\ndef get_rain(buildings):\n max_val = max(buildings)\n\n rain_arr = []\n for i in range(1, len(buildings) - 1):\n # 현재 인덱스를 기준으로 양쪽에 가장 높은 건물의 위치를 구한다\n leftMax = max(buildings[:i])\n center = buildings[i]\n rightMax = max(buildings[i + 1:])\n\n # center 기준으로 좌,우측 max층 중 작은 값에서 center를 뺀 값이 비에 잠긴 양\n if leftMax > center and rightMax > center:\n rain_arr.append((min(leftMax, rightMax) - center))\n else:\n rain_arr.append(0)\n\n return rain_arr\n\ndef solutaion(bricks):\n longitudinal = len(bricks[0])\n vertical = len(bricks)\n\n verArray = [] # 수직방향 Array\n for long in range(longitudinal):\n subarray = []\n for ver in range(vertical):\n subarray.append(bricks[ver][long])\n verArray.append(subarray)\n\n longRain = [] # 길이방향 차오르는 물\n for i in range(1, vertical - 1):\n longRain.append(get_rain(bricks[i]))\n\n verRain = [] # 수직방향 차오르는 물\n for i in range(1, longitudinal -1):\n verRain.append(get_rain(verArray[i]))\n\n longSum = 0 # 길이방향 빗물 양\n verSum = 0 # 수직 방향 빗물 양\n for i in longRain:\n for j in i:\n longSum += j\n\n for i in verRain:\n for j in i:\n verSum += j\n\n print(longRain)\n print(verRain)\n print(longSum)\n print(verSum)\n print(\"\")\n\nbricks1 = [[2,4,3,2,3,2], [3,1,1,4,1,3], [2,2,1,3,3,1] ]\nbricks4 = [[5,5,5,5], [4,1,1,5], [3,1,1,5], [4,4,4,5]]\nbricks2 = [[2,2,2], [1,2,2], [1,2,1]]\nbricks5 = [[4,1,1,3,1], [4,1,2,0,2], [4,1,1,2,2]]\nsolutaion(bricks1)\nsolutaion(bricks4)\nsolutaion(bricks5)" }, { "alpha_fraction": 0.5466970205307007, "alphanum_fraction": 0.5671981573104858, "avg_line_length": 25.636363983154297, "blob_id": "65dec458128a53cba70f11a75b3631b793bfa042", "content_id": "cef6c725dd43cbf26c3a81cbdc062fe1cd73a040", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1244, "license_type": "no_license", "max_line_length": 77, "num_lines": 33, "path": "/class_method.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "'''\n @classmethod 로 표현하는 클래스 메소드는 첫번째 파라미터로 클래스가 자동 전달된다.\n 클래스 메소드는 인스턴스 변수를 아예 사용하지 않는 경우에 사용한다.(인스턴스 변수를 알 수 없다)\n 인스턴스 변수 사용 -> 인스턴스 메소드\n 클래스 변수 사용 -> 클래스 메소드\n 둘다 사용 -> 인스턴스 메소드(인스턴스 변수, 클래스 변수 모두 사용 가능)\n'''\n\nclass User:\n count = 0 # 클래스 변수\n\n def __init__(self, name, email, pw):\n self.name = name\n self.email = email\n self.pw = pw\n User.count += 1 # 인스턴스가 생성될 때마다 count가 증가됨\n\n def say_hello(self):\n print(\"안녕하세요! 저는 {}입니다!\".format(self.name))\n\n def __str__(self):\n return \"사용자: {}, 이메일: {}, 비밀번호: ******\".format(self.name, self.email)\n\n @classmethod\n def number_of_users(cls):\n print(\"총 유저 수는 {} 입니다.\".format(cls.count))\n\nuser1 = User(\"강영훈\", \"[email protected]\", \"123456\")\nuser2 = User(\"이윤수\", \"[email protected]\", \"abcdefg\")\nuser3 = User(\"서혜린\", \"[email protected]\", \"123456\")\n\nUser.number_of_users()\nuser1.number_of_users()" }, { "alpha_fraction": 0.553398072719574, "alphanum_fraction": 0.5663430690765381, "avg_line_length": 24.244897842407227, "blob_id": "af88d48736cc078ccaa8685dea9a06139b287397", "content_id": "d6b7be69b39790de75d8334a4dd41d76a9d2a901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1656, "license_type": "no_license", "max_line_length": 70, "num_lines": 49, "path": "/OOP/캡슐화.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "\"\"\"\n데코레이터를 통한 캡슐화\n@property\[email protected]\n위의 모습으로 getter, setter를 데코레이터 형태로 정의한다.\n\"\"\"\n\nclass Citizen:\n \"\"\"주민 클래스\"\"\"\n drinking_age = 19 # 음주 가능 나이\n\n def __init__(self, name, age, resident_id):\n self.name = name\n self._age = age\n self._resident_id = resident_id\n\n def authenticate(self, id_field):\n \"\"\"본인이 맞는지 확인하는 메소드\"\"\"\n return self._resident_id == id_field\n\n def can_drink(self):\n \"\"\"음주 가능 나이인지 확인하는 메소드\"\"\"\n return self._age >= Citizen.drinking_age\n\n def __str__(self):\n \"\"\"주민 정보를 문자열로 리턴하는 메소드\"\"\"\n return self.name + \"씨는\" + str(self._age) + \"살입니다.\"\n\n @property\n def age(self):\n \"\"\"Property 데코레이터로 getter함수 정의\"\"\"\n print(\"나이를 리턴합니다\")\n return self._age\n\n @age.setter\n def age(self, value):\n \"\"\"Property 데코레이터로 setter함수 정의\"\"\"\n print(\"나이를 {}으로 설정합니다.\".format(value))\n if value < 0:\n print(\"나이를 음수로 설정할 수 없습니다. 0으로 초기화 하겠습니다.\")\n self._age = 0\n else:\n self._age = value\n\n\nyoung = Citizen(\"박지상\", 30, \"1222712\")\nprint(young.age) #인스턴스 변수는 _age이지만 데코레이터 getter로 정의된 age메소드를 통해 _age반환\nyoung.age = 21 #인스턴스 변수는 _age이지만 데코레이터 setter로 정의된 age메소드를 통해 _age 설정\nprint(young.age)" }, { "alpha_fraction": 0.5887005925178528, "alphanum_fraction": 0.594350278377533, "avg_line_length": 25.058822631835938, "blob_id": "1635ff6be2388d70d5fc2276cfcb5887a976e91d", "content_id": "f098542a5dfb4e0bd1fcd76916851c79648da912", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1183, "license_type": "no_license", "max_line_length": 77, "num_lines": 34, "path": "/OOP/static_method.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "'''\n 파이썬 메소드의 종류는 3가지 - 인스턴스 메소드, 클래스 메소드, 정적 메소드\n 정적 메소드는 인스턴스 변수나 클래스 변수 중 아무것도 사용하지 않을 메소드라면 정적 메소드로 만든다.\n'''\nclass User:\n count = 0\n\n def __init__(self, name, email, pw):\n self.name = name\n self.email = email\n self.pw = pw\n\n User.count += 1\n\n def say_hello(self):\n print(\"안녕하세요! 저는 {}입니다!\".format(self.name))\n\n def __str__(self):\n return \"사용자: {}, 이메일: {}, 비밀번호: ******\".format(self.name, self.email)\n\n @classmethod\n def number_of_users(cls):\n print(\"총 유저 수는: {}입니다\".format(cls.count))\n\n @staticmethod\n def is_valid_email(email_address): # 정적메소드는 자동으로 전달되는 파라미터가 없다.\n return \"@\" in email_address\n\n# 정적 메소드는 인스턴스,클래스 두 가지 모두를 통해 사용 가능하다.\nprint(User.is_valid_email(\"taehosung\"))\nprint(User.is_valid_email(\"[email protected]\"))\n\nprint(user1.is_valid_email(\"taehosung\"))\nprint(user1.is_valid_email(\"[email protected]\"))" }, { "alpha_fraction": 0.5774545669555664, "alphanum_fraction": 0.5807272791862488, "avg_line_length": 22.109243392944336, "blob_id": "4006251d3793305b5fc7bd8d27886f7eef798a82", "content_id": "d966a6fd83ac110ad3462509c4dd24fc43c6a812", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3538, "license_type": "no_license", "max_line_length": 71, "num_lines": 119, "path": "/OOP/다형성.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "from math import pi\nfrom abc import ABC, abstractmethod\n\n\"\"\"\n다형성은 하나의 변수를 여러 인스턴스로 나타낼 수 있는 형태, 특징\n그리고 추상 클래스란 '여러 클래스들의 공통점을 추상화해서 모아놓은 클래스'이며, \n다형성은 추상클래스를 통해 구현할 수 있다.\n\nABC는 Abstract Base Class로 추상클래스를 나타낸다\nabstractclassmethod는 추상 메소드를 나타낸다\n\"\"\"\n\nclass Figure(ABC):\n \"\"\"도형 클래스(추상 클래스)\"\"\"\n\n @abstractmethod\n def area(self) -> float: # 추상 메소드는 type hinting을 해주는 것이 좋다\n \"\"\"도형의 넓이를 리턴한다: 자식 클래스가 오버라이딩할 것\"\"\"\n pass\n\n @abstractmethod\n def perimeter(self) -> float:\n \"\"\"도형의 둘레를 리턴한다: 자식 클래스가 오버라이딩할 것\"\"\"\n pass\n\n\nclass Rectangle(Figure):\n \"\"\"직사각형 클래스\"\"\"\n\n def __init__(self, width, height):\n self.width = width\n self.height = height\n\n def area(self):\n \"\"\"직사각형의 넓이 리턴\"\"\"\n return self.width * self.height\n\n def perimeter(self):\n \"\"\"직사각형의 둘레 리턴\"\"\"\n return self.width * 2 + self.height * 2\n\n def __str__(self):\n \"\"\"직사각형의 정보를 문자열로 리턴한다\"\"\"\n return \"밑변 {}, 높이 {}인 직사각형\".format(self.width, self.height)\n\n\nclass Circle(Figure):\n \"\"\"원 클래스\"\"\"\n\n def __init__(self, radius):\n self.radius = radius\n\n def area(self):\n \"\"\"원의 넓이 리턴\"\"\"\n return pi * self.radius * self.radius\n\n def perimeter(self):\n \"\"\"원의 둘레 리턴\"\"\"\n return pi * 2 * self.radius\n\n def __str__(self):\n \"\"\"원의 정보를 문자열로 리턴한다\"\"\"\n return \"반지름 {}인 원\".format(self.radius)\n\n\nclass Cylinder(Figure):\n \"\"\"원통 클래스\"\"\"\n\n def __init__(self, radius, height):\n self.radius = radius\n self.height = height\n\n def area(self):\n \"\"\"원통의 넓이를 리턴\"\"\"\n return pi * self.radius * self.radius * self.height\n\n def perimeter(self):\n \"\"\"원통의 둘레를 리턴\"\"\"\n return pi * 2 * self.radius * self.height\n\n def __str__(self):\n \"\"\"원통의 정보를 문자여롤 리턴하는 메소드\"\"\"\n return \"밑면 반지름 {}, 높이 {}인 원기둥\".format(self.radius, self.height)\n\n\nclass Paint:\n \"\"\"그림판 프로그램 클래스\"\"\"\n\n def __init__(self):\n self.shapes = []\n\n def add_shape(self, shape):\n \"\"\"그림판에 도형을 추가한다\"\"\"\n if isinstance(shape, Figure):\n self.shapes.append(shape)\n else:\n print(\"넓이, 둘레를 구하는 메소드가 없는 도형은 추가할 수 없습니다!\")\n\n def total_area_of_shapes(self):\n \"\"\"그림판에 있는 모든 도형의 넓이의 합을 구한다\"\"\"\n return sum([shape.area() for shape in self.shapes])\n\n def total_perimeter_of_shapes(self):\n \"\"\"그림판에 있는 모든 도형의 둘레의 합을 구한다\"\"\"\n return sum([shape.perimeter() for shape in self.shapes])\n\n\ncylinder = Cylinder(7, 4)\nrectangle = Rectangle(3, 7)\ncircle = Circle(4)\n\npaint_program = Paint()\n\npaint_program.add_shape(cylinder)\npaint_program.add_shape(circle)\npaint_program.add_shape(rectangle)\n\nprint(paint_program.total_perimeter_of_shapes()) # 에러가 난다!\nprint(paint_program.total_area_of_shapes())\n" }, { "alpha_fraction": 0.6182648539543152, "alphanum_fraction": 0.6292237639427185, "avg_line_length": 28.62162208557129, "blob_id": "80a64d7750b0573c45afb956e8deb0beeb24c15b", "content_id": "7366ca0a80684ca579699ca148d6a892e0349eb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1467, "license_type": "no_license", "max_line_length": 97, "num_lines": 37, "path": "/OOP/class_method_apply.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "'''\n 인스턴스를 생성할 때 필요한 정보들이 항상 우리가 원하는 형태로 존재할까요? 우리는 다양한 형태의 정보에서 필요한 부분을 뽑아내서 인스턴스를 생성할 수 있어야 합니다.\n 예를 들어 유저 인스턴스 생성에 필요한 정보가 문자열일 수도 있고 리스트일 수도 있습니다.\n'''\n\nclass User:\n def __init__(self, name, email, password):\n self.name = name\n self.email = email\n self.password = password\n\n @classmethod\n def from_string(cls, string_param): # 문자열로 인스턴스 만들기\n parameter_list = string_param.split(\",\") # split 메소드를 사용해서 쉼표(,)를 기준으로 문자열을 리스트로 분리한다\n\n # 각 변수에 분리된 문자열 각각 저장\n name = parameter_list[0]\n email = parameter_list[1]\n password = parameter_list[2]\n\n return cls(name, email, password)\n\n @classmethod\n def from_list(cls, list_param): # 리스트로 인스턴스 만들기\n name = list_param[0]\n email = list_param[1]\n password = list_param[2]\n\n return cls(name, email, password)\n\n\n# 유저 생성 및 초기값 설정\nyounghoon = User.from_string(\"강영훈,[email protected],123456\")\nyoonsoo = User.from_list([\"이윤수\", \"[email protected]\", \"abcdef\"])\n\nprint(younghoon.name, younghoon.email, younghoon.password)\nprint(yoonsoo.name, yoonsoo.email, yoonsoo.password)" }, { "alpha_fraction": 0.6229946613311768, "alphanum_fraction": 0.6229946613311768, "avg_line_length": 24, "blob_id": "93b5c6fd14ff9f7ca2bec0948ac933cf2db100e4", "content_id": "f56f22e97bdcabaf8d34a4cd49adff8461e33385", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 600, "license_type": "no_license", "max_line_length": 71, "num_lines": 15, "path": "/OOP/Decorator.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "def add_print_to(original): # 함수를 넘겨줌, add_print_to함수는 데코레이션 함수\n def wrapper():\n print(\"함수시작\") # 데코레이션 (넘겨받은 함수의 앞뒤 등등을 꾸며준다)\n original()\n print(\"함수 끝\")\n\n return wrapper # 정의된 함수를 반환\n\n@add_print_to # 골뱅이 요부분을 붙이면, 앞으로 print_hello()만 호출해도 데코레이터 함수가 같이 불린다\ndef print_hello():\n print(\"안녕하세요!\")\n\n# 함수위에 골뱅이가 보이면 아! 데코레이터구나! 라고 생각하자\n\nprint_hello()" }, { "alpha_fraction": 0.5475475192070007, "alphanum_fraction": 0.5895895957946777, "avg_line_length": 23.317073822021484, "blob_id": "757927141ee229f2023567a1b785f43da05e290a", "content_id": "ff7e660f8f741cd4f7a504d4a36df6aed383444d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1249, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/OOP/instance_method.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "class User:\n count = 0 # 클래스 변수\n\n def __init__(self, name, email, pw):\n self.name = name\n self.email = email\n self.pw = pw\n User.count += 1 # 인스턴스가 생성될 때마다 count가 증가됨\n\n def say_hello(self):\n print(\"안녕하세요! 저는 {}입니다!\".format(self.name))\n\n def login(self, my_email, my_password):\n if ( self.email == my_email and self.pw == my_password):\n print(\"로그인 성공, 환영합니다.\")\n else:\n print(\"로그인 실패, 없는 아이디이거나 잘못된 비밀번호 입니다.\")\n\n\nuser1 = User(\"김대위\", \"[email protected]\", \"12345\")\n\n# user1.login(user1, \"[email protected]\", \"12345\") ### 에러!\nuser1.login(\"[email protected]\", \"12345\")\n\n\nuser2 = User(\"강영훈\", \"[email protected]\", \"123456\")\nuser3 = User(\"이윤수\", \"[email protected]\", \"abcdefg\")\nuser4 = User(\"서혜린\", \"[email protected]\", \"123456\")\n\nuser1.count = 10 # 이 방식은 인스턴스 변수를 설정하는 작업\n\nprint(User.count) #생성된 인스턴스의 개수 출력\nprint(user1.count)\nprint(user2.count)\nprint(user3.count)\n\nUser.count = 20\n\nprint(User.count)\nprint(user1.count) # 이미 user1의 count라는 인스턴스 변수는 생성이 되부렀으~\nprint(user2.count)\n\n\n" }, { "alpha_fraction": 0.642201840877533, "alphanum_fraction": 0.6574923396110535, "avg_line_length": 23.058822631835938, "blob_id": "d8c445aecf204be6cdfa9dafc0759960060a9199", "content_id": "9017d1a1ba83a278873bd9aaa847b3bf6b7614f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 124, "num_lines": 68, "path": "/Quiz/캡슐화-신용카드.py", "repo_name": "GroundP/OOP", "src_encoding": "UTF-8", "text": "\"\"\"\n신용 카드를 나타내는 CreditCard 클래스를 만들고 싶습니다. CreditCard 클래스에는\n\n소유자 이름\n비밀 번호\n카드 한도 정보\n가 저장됩니다. 다음 조건들에 맞게 CreditCard 클래스를 완성하세요.\n\nCreditCard 클래스의 비밀번호, 카드 한도 인스턴스 변수 이름 앞에 밑줄 한 개를 써서 다른 개발자들에게 해당 변수를 직접 사용하는 것을 자제하라는 표시를 남깁시다. (_password, _payment_limit)\n\n@property를 이용해서 앞에 밑줄 하나를 쓴 변수들을 캡슐화하세요.\n변수 _password\ngetter 메소드: 문자열 \"비밀 번호는 볼 수 없습니다\"를 리턴한다.\nsetter 메소드: 파라미터로 받은 값을 변수에 설정한다.\n변수 _payment_limit\ngetter 메소드: _payment_limit 변수를 리턴한다.\nsetter 메소드: 파라미터로 받은 값을 변수에 설정한다.\n단, setter 메소드에서 파라미터로 받은 값이 0과 MAX_PAYMENT_LIMIT 사이에 있는 값이 아니면 \"카드 한도는 0원 ~ 3천만 원 사이로 설정해주세요!\" 라는 메시지를 출력한다.\n\"\"\"\n\nclass CreditCard:\n MAX_PAYMENT_LIMIT = 30000000\n\n def __init__(self, name, password, payment_limit):\n self._name = name\n self._password = password\n self._payment_limit = payment_limit\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self, name):\n self._name = name\n\n @property\n def password(self):\n return \"비밀 번호는 볼 수 없습니다\"\n\n @password.setter\n def password(self, password):\n self._password = password\n\n @property\n def payment_limit(self):\n return self._payment_limit\n\n @payment_limit.setter\n def payment_limit(self, limit):\n if 0 < limit < CreditCard.MAX_PAYMENT_LIMIT:\n self._payment_limit = limit\n else:\n print(\"카드 한도는 0원 ~ 3천만 원 사이로 설정해주세요!\")\n\ncard = CreditCard(\"강영훈\", \"123\", 100000)\n\nprint(card.name)\nprint(card.password)\nprint(card.payment_limit)\n\ncard.name = \"성태호\"\ncard.password = \"1234\"\ncard.payment_limit = -10\n\nprint(card.name)\nprint(card.password)\nprint(card.payment_limit)" } ]
9
Mela2014/lc_punch
https://github.com/Mela2014/lc_punch
a230af2c9d40b1af4932c800e72698de5b77d61a
498308e6a065af444a1d5570341231e4c51dfa3f
89e4c3dd91ceb3a4a5e74cfaedbb795152ebd1f9
refs/heads/main
2023-07-13T03:44:56.963033
2021-08-25T05:44:40
2021-08-25T05:44:40
313,742,939
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5480349063873291, "alphanum_fraction": 0.5545851588249207, "avg_line_length": 34.230770111083984, "blob_id": "d347fe015c11150c938d8eb731dd835a73f71e3d", "content_id": "afa85aebd028822adb5938b6b3cc6cb3330ae670", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 76, "num_lines": 13, "path": "/lc327_sortedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "from sortedcontainers import SortedList\nclass Solution:\n def countRangeSum(self, nums: List[int], lower: int, upper: int) -> int:\n maps = SortedList([0])\n rslt, cumsum = 0, 0\n for num in nums:\n cumsum += num\n left = maps.bisect_left(cumsum-upper)\n right = maps.bisect_right(cumsum-lower)\n if right > left:\n rslt += right-left\n maps.add(cumsum)\n return rslt\n" }, { "alpha_fraction": 0.3951434791088104, "alphanum_fraction": 0.40176600217819214, "avg_line_length": 29.200000762939453, "blob_id": "3a201150172241c9b4b4c303dc9346716847dbd8", "content_id": "5417dcd7963241d015d6a0af5802b36404c00d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 51, "num_lines": 15, "path": "/lc1510_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def winnerSquareGame(self, n: int) -> bool:\n memo = {}\n def dfs(n):\n if n in memo:\n return memo[n]\n if n == 0:\n return False\n for i in range(1, int(math.sqrt(n))+1):\n if i*i <= n and not dfs(n-i*i):\n memo[n] = True\n return True\n memo[n] = False\n return False\n return dfs(n)\n" }, { "alpha_fraction": 0.2914072275161743, "alphanum_fraction": 0.30510586500167847, "avg_line_length": 31.1200008392334, "blob_id": "d2cf0ea4453746c31bea86dd3150df8e3b295532", "content_id": "47bb21048afdb4d0c9c946ed5f3a72c219302a97", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license_type": "no_license", "max_line_length": 54, "num_lines": 25, "path": "/lc1028_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def recoverFromPreorder(self, S: str) -> TreeNode:\n currD, num = 0, \"\"\n root = None\n stk = []\n for c in S+'-':\n if c == \"-\":\n if not num:\n currD += 1\n else:\n curr = TreeNode(int(num))\n if not root:\n root = curr\n elif stk[-1][1] < currD:\n stk[-1][0].left = curr\n else:\n while stk[-1][1] >= currD:\n stk.pop()\n stk[-1][0].right = curr\n stk.append((curr, currD))\n num = \"\"\n currD = 1\n else:\n num += c\n return root\n" }, { "alpha_fraction": 0.4420772194862366, "alphanum_fraction": 0.4607190489768982, "avg_line_length": 45.9375, "blob_id": "329184f99068c8c6c2a68302731543954c9699c3", "content_id": "1ed8a1be893ed796df20d53b043e8d75a10e21db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 136, "num_lines": 16, "path": "/lc1654_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int:\n dque, seen1, seen2, rslt, limit = collections.deque([(0, 1)]), set(forbidden), set(forbidden), 0, max(x, max(forbidden)) + a + b\n while dque:\n for _ in range(len(dque)):\n cur, last_forward = dque.popleft()\n if cur == x:\n return rslt\n if cur + a <= limit and cur + a not in seen1:\n seen1.add(cur + a)\n dque.append((cur + a, 1))\n if cur - b > 0 and cur - b not in seen2 and last_forward:\n seen2.add(cur - b)\n dque.append((cur - b, 0))\n rslt += 1\n return -1\n" }, { "alpha_fraction": 0.4156534969806671, "alphanum_fraction": 0.43009117245674133, "avg_line_length": 41.45161437988281, "blob_id": "fc1e99a275940910963950d2e2e1bed98048fcc4", "content_id": "bc32ac165a32b9a0f09448c7a06173f017c1a81f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1316, "license_type": "no_license", "max_line_length": 109, "num_lines": 31, "path": "/lc675_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n nrow, ncol, rslt = len(forest), len(forest[0]), 0\n heap = []\n for i in range(nrow):\n for j in range(ncol):\n if forest[i][j] > 0:\n heapq.heappush(heap, (forest[i][j], i, j))\n def bfs(nextval, nextx, nexty, currx, curry):\n dque, seen, step = collections.deque([(currx, curry)]), {(currx, curry)}, 0\n while dque:\n size = len(dque)\n for _ in range(size):\n x,y = dque.popleft()\n if x == nextx and y == nexty:\n return step\n for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:\n if 0 <= nx < nrow and 0 <= ny < ncol and forest[nx][ny] > 0 and (nx, ny) not in seen:\n seen.add((nx, ny))\n dque.append((nx, ny))\n step += 1\n return -1\n\n currx, curry, visited = 0, 0, {(0, 0)}\n while heap:\n nextval, nextx, nexty = heapq.heappop(heap)\n step = bfs(nextval, nextx, nexty, currx, curry)\n if step == -1: return -1\n rslt += step\n currx, curry = nextx, nexty\n return rslt\n" }, { "alpha_fraction": 0.5039028525352478, "alphanum_fraction": 0.5203816294670105, "avg_line_length": 31.02777862548828, "blob_id": "f195a63cc4ab0f7832ec1b00b02f8ce795acb76b", "content_id": "3d558678b9077ff2d8bea588e82980fa816f6763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1153, "license_type": "no_license", "max_line_length": 77, "num_lines": 36, "path": "/lc395_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "#divide and conquer\nclass Solution:\n def longestSubstring(self, s: str, k: int) -> int:\n counts = collections.Counter(s)\n for t in counts:\n if counts[t] < k:\n return max(self.longestSubstring(ss, k) for ss in s.split(t))\n return len(s)\n\n#sliding window\nclass Solution:\n def longestSubstring(self, s, k):\n count = 0\n for i in range(1, 27):\n count = max(count, self.helper(s, k, i))\n return count\n\n def helper(self, s, k, numUniqueTarget):\n start = end = numUnique = numNoLessThanK = count = 0\n chMap = [0]*128\n\n while end < len(s):\n if chMap[ord(s[end])] == 0: numUnique += 1\n chMap[ord(s[end])] += 1\n if chMap[ord(s[end])] == k: numNoLessThanK += 1\n end += 1\n\n while numUnique > numUniqueTarget:\n if chMap[ord(s[start])] == k: numNoLessThanK -= 1\n chMap[ord(s[start])] -= 1\n if chMap[ord(s[start])] == 0: numUnique -= 1\n start += 1\n\n if numUnique == numNoLessThanK: count = max(count, end-start)\n\n return count\n" }, { "alpha_fraction": 0.470016211271286, "alphanum_fraction": 0.4797406792640686, "avg_line_length": 35.29411697387695, "blob_id": "2f36fa1f14f9627fe23063fc90f8b124a898e7d4", "content_id": "59b7854d460439836ad616650c4003d440dc499f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/lc103_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n queue, left, rslt = collections.deque([root]), 1, []\n while queue:\n lq = len(queue)\n temp = [0]*lq\n for i in range(lq):\n curr = queue.popleft()\n if left == 1: temp[i] = curr.val\n else:temp[lq-i-1] = curr.val\n if curr.left: queue.append(curr.left)\n if curr.right: queue.append(curr.right)\n left = (left+1)%2\n rslt.append(temp)\n return rslt\n" }, { "alpha_fraction": 0.4793578088283539, "alphanum_fraction": 0.4931192696094513, "avg_line_length": 38.6363639831543, "blob_id": "e68c093c341c44fb558fe7fb82d17744ee8e7980", "content_id": "8da7356d5e183a7ed54283fdfd9edc2cedae404f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 75, "num_lines": 11, "path": "/lc494_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findTargetSumWays(self, nums: List[int], S: int) -> int:\n memo = collections.defaultdict(int)\n def dfs(i, curr):\n if (i, curr) in memo:\n return memo[(i, curr)]\n if i == len(nums):\n return 1 if curr == S else 0\n memo[(i, curr)] = dfs(i+1, curr+nums[i])+dfs(i+1, curr-nums[i])\n return memo[(i, curr)]\n return dfs(0, 0)\n" }, { "alpha_fraction": 0.43008315563201904, "alphanum_fraction": 0.448223739862442, "avg_line_length": 44.620689392089844, "blob_id": "1e767327d4f1bc7f4db042487ade73f4e9cc03fb", "content_id": "cbd6ecdca0ecd6f215235f4164a408a86564e31e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "no_license", "max_line_length": 82, "num_lines": 29, "path": "/lc1810_dijkstra.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution(object):\n def findShortestPath(self, master: 'GridMaster') -> int:\n directions = {'U':'D', 'D':'U', 'L':'R', 'R':'L'}\n steps = {'U':(-1, 0), 'D':(1, 0), 'L':(0, -1), 'R':(0, 1)}\n self.target = None\n graph = {(0, 0): 0}\n # backtracking build graph\n def backtracking(x, y):\n if master.isTarget(): self.target = (x, y)\n for d in directions:\n nx, ny = x + steps[d][0], y+steps[d][1]\n if (nx, ny) in graph: continue\n if master.canMove(d):\n graph[(nx, ny)] = master.move(d)\n backtracking(nx, ny)\n master.move(directions[d])\n backtracking(0, 0)\n if self.target is None: return -1\n # bfs find rslt\n heap = [[0, 0, 0]] # cost, x, y\n seen = collections.defaultdict(lambda: float(\"inf\"))\n while heap:\n cost, x, y = heapq.heappop(heap)\n if (x, y) == self.target: return cost\n for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:\n if (nx, ny) in graph and cost + graph[(nx, ny)] < seen[(nx, ny)] :\n seen[(nx, ny)] = cost + graph[(nx, ny)]\n heapq.heappush(heap, (cost + graph[(nx, ny)], nx, ny))\n return -1\n" }, { "alpha_fraction": 0.4340527653694153, "alphanum_fraction": 0.4508393406867981, "avg_line_length": 33.75, "blob_id": "13ae9507ba2df4bad736fe9333e05e9e39c32936", "content_id": "975d7e989e249480027add086503c25c5a04ace9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 834, "license_type": "no_license", "max_line_length": 73, "num_lines": 24, "path": "/lc403_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canCross(self, stones: List[int]) -> bool:\n n = len(stones)\n dp = [False]*n\n dp[0] = True\n cand_steps =collections.defaultdict(set)\n cand_steps[0] = {1}\n for i in range(1, n):\n for j in range(i):\n need_step = stones[i] - stones[j]\n if dp[j] and need_step in cand_steps[j]:\n dp[i] = True\n cand_steps[i]|= {need_step, need_step+1, need_step-1}\n return dp[-1]\n\n def canCross(self, stones):\n maps = {x: set() for x in stones}\n maps[0].add(0)\n for x in stones[:-1]:\n for j in maps[x]:\n for k in range(max(1, j-1), j+2):\n if x + k in maps:\n maps[x+k].add(k)\n return bool(maps[stones[-1]])\n" }, { "alpha_fraction": 0.3972148597240448, "alphanum_fraction": 0.4118037223815918, "avg_line_length": 38.68421173095703, "blob_id": "38a12fed015208ae28761dc0a18ef23bd77f0d34", "content_id": "6feeca8b38518ed917366d856855bc4dff12dbd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1508, "license_type": "no_license", "max_line_length": 81, "num_lines": 38, "path": "/lc1728_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:\n nrow, ncol, thred = len(grid), len(grid[0]), 0\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == \"C\": catloc = (i, j)\n if grid[i][j] == \"M\": mouseloc = (i, j)\n if grid[i][j] == \"F\": foodloc = (i, j)\n if grid[i][j] != \"#\": thred += 1\n @lru_cache(None)\n def dfs(cat, mouse, step):\n if cat == mouse or cat == foodloc or step > 2*thred:\n return False\n if mouse == foodloc:\n return True\n if step%2 == 0:\n for nmouse in nextstep(mouse, mouseJump):\n if dfs(cat, nmouse, step + 1):\n return True\n return False\n else:\n for ncat in nextstep(cat, catJump):\n if not dfs(ncat, mouse, step+1):\n return False\n return True\n\n def nextstep(curr, step):\n rslt = []\n for dx, dy in [(1,0), (-1, 0), (0, 1), (0, -1)]:\n for jump in range(step+1):\n nx, ny = curr[0]+dx*jump, curr[1]+dy*jump\n if 0 <= nx < nrow and 0 <= ny < ncol and grid[nx][ny] != \"#\":\n rslt.append((nx, ny))\n else:\n break\n return rslt\n\n return dfs(catloc, mouseloc, 0)\n" }, { "alpha_fraction": 0.43044188618659973, "alphanum_fraction": 0.4369885325431824, "avg_line_length": 32.94444274902344, "blob_id": "97a1bfefcddace7bc2147cea4281f8e7dcaf7c3d", "content_id": "ff1921bbfb0182276ed2c547e1f18252263ba36f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/lc1300_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n left, right = target//len(arr), max(arr)\n def check(mid):\n rslt = 0\n for num in arr:\n if num < mid:\n rslt += num\n else:\n rslt += mid\n return rslt\n while left <= right:\n mid = (left + right)//2\n if check(mid) <= target:\n left = mid + 1\n else:\n right = mid - 1\n return left if abs(check(left)-target) < abs(check(right)-target) else right\n" }, { "alpha_fraction": 0.42088091373443604, "alphanum_fraction": 0.4274061918258667, "avg_line_length": 35.05882263183594, "blob_id": "972a581610e1d5edff78ff1ab0f7db0a39daa630", "content_id": "d8851bfea52fc36f729981c40738b679981419c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 78, "num_lines": 17, "path": "/lc140_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:\n if not wordDict: return []\n n, wordDict, ml = len(s), set(wordDict), len(max(wordDict, key = len))\n @lru_cache(None)\n def dfs(i):\n if i == n:\n return [[]]\n rslt = []\n for j in range(i, n):\n if j-i < ml and s[i:j+1] in wordDict:\n temp = dfs(j+1)\n for t in temp:\n rslt.append([s[i:j+1]]+t)\n return rslt\n temp = dfs(0)\n return [\" \".join(t) for t in temp]\n" }, { "alpha_fraction": 0.38760632276535034, "alphanum_fraction": 0.42891860008239746, "avg_line_length": 30.653846740722656, "blob_id": "bc8d555b2398bb91009c89b28e5ab7e57c8d7738", "content_id": "2534016c1dabf6bfeb5bb533a9b8e19e20b854eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 823, "license_type": "no_license", "max_line_length": 64, "num_lines": 26, "path": "/lc850_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def rectangleArea(self, rectangles: List[List[int]]) -> int:\n events = []\n for x1, y1, x2, y2 in rectangles:\n events.append((y1, 1, x1, x2))\n events.append((y2, -1, x1, x2))\n events.sort()\n\n def cal_x_len():\n l_x, lastx = 0, 0\n for x1, x2 in active:\n lastx = max(lastx, x1)\n l_x += max(0, x2 -lastx)\n lastx = max(lastx, x2)\n return l_x\n active = []\n lasty = events[0][0]\n rslt = 0\n for y, status, x1, x2 in events:\n rslt += cal_x_len()*(y-lasty)\n if status == 1:\n bisect.insort(active, (x1, x2))\n else:\n active.remove((x1, x2))\n lasty = y\n return rslt % (10**9 + 7)\n" }, { "alpha_fraction": 0.25806450843811035, "alphanum_fraction": 0.28535979986190796, "avg_line_length": 25.866666793823242, "blob_id": "43917e1401edc0824b338f45741a612d022cc38a", "content_id": "23082c089e53c7f58624f8caeda8e0c2b2fa88ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 403, "license_type": "no_license", "max_line_length": 43, "num_lines": 15, "path": "/lc1541_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minInsertions(self, s: str) -> int:\n bal, rslt = 0, 0\n for c in s:\n if c == \"(\":\n if bal % 2 == 1:\n rslt += 1\n bal -= 1\n bal += 2\n else:\n bal -= 1\n if bal < 0:\n rslt += 1\n bal += 2\n return rslt + bal\n" }, { "alpha_fraction": 0.44805195927619934, "alphanum_fraction": 0.4588744640350342, "avg_line_length": 36.75, "blob_id": "a59ba58760e99e11d9437f2bd2d8583ea291951c", "content_id": "eeeef588a565ced060783710049419b35fff958e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/lc1340_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxJumps(self, arr: List[int], d: int) -> int:\n n = len(arr)\n @lru_cache(None)\n def dfs(i):\n rslt = 1\n for direction in [-1, 1]:\n for j in range(i+direction, i+d*direction+direction, direction):\n if j < 0 or j >= n or arr[j] >= arr[i]: break\n rslt = max(rslt, dfs(j)+1)\n return rslt\n return max(map(dfs, range(n)))\n \n" }, { "alpha_fraction": 0.489130437374115, "alphanum_fraction": 0.49275362491607666, "avg_line_length": 38.42856979370117, "blob_id": "b179d8616d77e0c28113b1a90a763eca56a6346a", "content_id": "5ca46de261c412bc61b63106e8d632a51c1b7aaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 78, "num_lines": 14, "path": "/lc743_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def networkDelayTime(self, times: List[List[int]], N: int, K: int) -> int:\n graph = collections.defaultdict(list)\n for s, t, w in times:\n graph[s].append((w, t))\n hp, dist = [(0, K)], {}\n while hp:\n w, t = heapq.heappop(hp)\n if t in dist: continue\n dist[t] = w\n for wnext, tnext in graph[t]:\n if tnext not in dist:\n heapq.heappush(hp, (wnext + w, tnext))\n return max(dist.values()) if len(dist) == N else -1\n" }, { "alpha_fraction": 0.42007797956466675, "alphanum_fraction": 0.4376218318939209, "avg_line_length": 26.7297306060791, "blob_id": "698f59747869bc87136df7822ada29e91ff6ce0e", "content_id": "5d619d1516af897e5cc44afe041dbd71dde9124c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1026, "license_type": "no_license", "max_line_length": 77, "num_lines": 37, "path": "/lc315_segtree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Segtree:\n def __init__(self, n):\n self.n = n\n self.seg_tree = [0]*(2*n)\n\n def update(self, idx):\n idx = self.n+idx\n self.seg_tree[idx] += 1\n while idx > 1:\n self.seg_tree[idx>>1] = self.seg_tree[idx] + self.seg_tree[idx^1]\n idx >>= 1\n\n def sumRange(self, idx):\n l = self.n\n r = self.n + idx\n rslt = -self.seg_tree[r]\n while l <= r:\n if l&1:\n rslt += self.seg_tree[l]\n l += 1\n if r&1 == 0:\n rslt += self.seg_tree[r]\n r -= 1\n l >>= 1\n r >>= 1\n return rslt\n\nclass Solution:\n def countSmaller(self, nums: List[int]) -> List[int]:\n maps = {val:i for i, val in enumerate(sorted(nums))}\n n = len(nums)\n segtree = Segtree(n)\n rslt = [0]*n\n for i in range(n-1, -1, -1):\n segtree.update(maps[nums[i]])\n rslt[i] = segtree.sumRange(maps[nums[i]])\n return rslt\n" }, { "alpha_fraction": 0.4312500059604645, "alphanum_fraction": 0.45781248807907104, "avg_line_length": 39, "blob_id": "6f880938edd06562b84816f77a155dcb6db8fb3b", "content_id": "f2ecb321a80541fd4830a06b494863763c7613ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 124, "num_lines": 16, "path": "/lc329_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestIncreasingPath(self, matrix: List[List[int]]) -> int:\n if not matrix or not matrix[0]:\n return 0\n @lru_cache(None)\n def dfs(i, j):\n temp = 1\n for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n if i+x >= 0 and i+x < len(matrix) and j+y >= 0 and j+y < len(matrix[0]) and matrix[i+x][j+y] > matrix[i][j]:\n temp = max(temp, dfs(i+x, j+y)+1)\n return temp\n rslt = 0\n for i in range(len(matrix)):\n for j in range(len(matrix[0])):\n rslt = max(rslt, dfs(i, j))\n return rslt\n" }, { "alpha_fraction": 0.3567010164260864, "alphanum_fraction": 0.38762885332107544, "avg_line_length": 31.33333396911621, "blob_id": "ba6a58358cfd4e536253b6cd98b62787c71b4153", "content_id": "7a99fc827e571d9d0696ee6be3c2ff688b69beb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "no_license", "max_line_length": 73, "num_lines": 15, "path": "/lc526_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countArrangement(self, n: int) -> int:\n ini = (1 << n)-1\n @lru_cache(None)\n def dfs(i, bitmask):\n if i == n+1:\n return 1\n elif bitmask == 0:\n return 0\n rslt = 0\n for j in range(n):\n if (1 << j) & bitmask and ((j+1)%i == 0 or i%(j+1) == 0):\n rslt += dfs(i+1, bitmask & (~(1 << j)))\n return rslt\n return dfs(1, ini)\n" }, { "alpha_fraction": 0.516581654548645, "alphanum_fraction": 0.5255101919174194, "avg_line_length": 34.6363639831543, "blob_id": "fbe54e14935e7199004d57824d7619163926b04b", "content_id": "b2a841a71a85820ce0609a0189e88234a479450d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 784, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/lc687_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def longestUnivaluePath(self, root: TreeNode) -> int:\n self.rslt = 0\n def helper(root):\n if not root: return 0\n left = helper(root.left)\n right = helper(root.right)\n left_l, right_l = 0, 0\n if root.left and root.left.val == root.val:\n left_l = left + 1\n if root.right and root.right.val == root.val:\n right_l = right + 1\n self.rslt = max(self.rslt, left_l+right_l)\n return max(left_l, right_l)\n helper(root)\n return self.rslt\n" }, { "alpha_fraction": 0.416570782661438, "alphanum_fraction": 0.4303797483444214, "avg_line_length": 32.42307662963867, "blob_id": "a8915df713aea16aa6fa0f6128bfbbb7f7bc42e3", "content_id": "bbb6a30fcd3dc32347e4621ee61c56e1c109c70e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 53, "num_lines": 26, "path": "/lc1140_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n memo = {}\n def dfs(i, m):\n if (i, m) in memo:\n return memo[(i, m)]\n if i+2*m >= len(piles):\n return sum(piles[i:])\n rslt = float(\"inf\")\n for j in range(i+1, i+2*m+1):\n rslt = min(rslt, dfs(j, max(j-i, m)))\n memo[(i, m)] = sum(piles[i:]) - rslt\n return memo[(i, m)]\n return dfs(0, 1)\n\nclass Solution:\n def stoneGameII(self, piles: List[int]) -> int:\n @lru_cache(None)\n def dfs(i, m):\n if i+2*m >= len(piles):\n return sum(piles[i:])\n rslt = float(\"inf\")\n for j in range(i+1, i+2*m+1):\n rslt = min(rslt, dfs(j, max(j-i, m)))\n return sum(piles[i:]) - rslt\n return dfs(0, 1)\n" }, { "alpha_fraction": 0.45179063081741333, "alphanum_fraction": 0.4655647277832031, "avg_line_length": 29.25, "blob_id": "9d3f41eea078167e1c4f19cb6eb03bd719525fb0", "content_id": "b4d54361dd1121578bbb67bc6f3591f54a6a9d5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 81, "num_lines": 12, "path": "/lc1564_greedy.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int:\n boxes.sort()\n count = 0\n idx = 0\n for box in boxes[::-1]:\n if warehouse[idx] >= box:\n count += 1\n idx += 1\n if idx >= len(warehouse):\n return count\n return count\n" }, { "alpha_fraction": 0.46716004610061646, "alphanum_fraction": 0.47641071677207947, "avg_line_length": 29.885713577270508, "blob_id": "5abd3fce38f3297ec09d4380dd2cba2acb5db51a", "content_id": "ff5f2e3b412b0d1ab3778e0f01aad36373555fa4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 83, "num_lines": 35, "path": "/lc685_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class DSU:\n def __init__(self, n):\n self.parents = list(range(n))\n self.size = [1]*n\n def find(self, p):\n while self.parents[p] != p:\n self.parents[p] = self.parents[self.parents[p]]\n p = self.parents[p]\n return p\n def union(self, p, q):\n pp, pq = self.find(p), self.find(q)\n if pp == pq: return True\n if self.size[pp] < self.size[pq]:\n pp, pq = pq, pp\n self.parents[pq] = pp\n self.size[pp] += self.size[pq]\n return False\n\nclass Solution:\n def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]:\n cand1, cand2, parents = None, None, {}\n for u, v in edges:\n if v in parents:\n cand1 = [parents[v], v]\n cand2 = [u, v]\n break\n parents[v] = u\n\n dsu = DSU(len(edges)+1)\n for u, v in edges:\n if cand2 == [u, v]: continue\n if dsu.union(u, v):\n if cand1: return cand1\n return [u, v]\n return cand2\n" }, { "alpha_fraction": 0.431314617395401, "alphanum_fraction": 0.4549483060836792, "avg_line_length": 26.079999923706055, "blob_id": "9566c4e7f1fe2479ca2819b2dddc589c023532af", "content_id": "f622502f973a736e7efbe935ca5ccfe6a50195b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 59, "num_lines": 25, "path": "/lc1442_bit.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countTriplets(self, arr: List[int]) -> int:\n rslt, n = 0, len(arr)\n prefix = [0]*(n+1)\n for i in range(n): prefix[i+1] = prefix[i] ^ arr[i]\n for left in range(n-1):\n for right in range(left+1, n):\n if prefix[right+1]^prefix[left] == 0:\n rslt += right-left\n return rslt\n\n\n\n\n\nclass Solution:\n def countTriplets(self, A):\n res = cur = 0\n count = {0: [1, 0]}\n for i, a in enumerate(A):\n cur ^= a\n n, total = count.get(cur, [0, 0])\n res += i * n - total\n count[cur] = [n + 1, total + i + 1]\n return res\n" }, { "alpha_fraction": 0.3865671753883362, "alphanum_fraction": 0.4029850661754608, "avg_line_length": 30.904762268066406, "blob_id": "1e121e386117baded936bb2ded0370efb1ee18dc", "content_id": "09621e42fbded19807ecf0900a110f5a923875b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 82, "num_lines": 21, "path": "/lc996_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numSquarefulPerms(self, nums: List[int]) -> int:\n count = collections.Counter(nums)\n maps = {x: {y for y in count if int((x+y)**0.5)**2 == x+y} for x in count}\n l = len(nums)\n def bk(curr, curr_c):\n if curr_c != 0:\n rslt = 0\n count[curr] -= 1\n for nxt in maps[curr]:\n if count[nxt]:\n rslt += bk(nxt, curr_c-1)\n count[curr] += 1\n else:\n rslt = 1\n return rslt\n rslt = 0\n for c in count:\n t = bk(c, l-1)\n rslt += t\n return rslt\n" }, { "alpha_fraction": 0.49809885025024414, "alphanum_fraction": 0.5107731223106384, "avg_line_length": 31.875, "blob_id": "c6d872a56efde6ff7d5eddcc309ea71b824bdee8", "content_id": "5f1b1e0adff20cb076a2b5b3e7a7be9f4e9c75b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 789, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/lc1214_bt.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def twoSumBSTs(self, root1: TreeNode, root2: TreeNode, target: int) -> bool:\n stk, pool = [], set()\n while stk or root1:\n while root1:\n stk.append(root1)\n root1 = root1.left\n temp = stk.pop()\n pool.add(temp.val)\n root1 = temp.right\n stk = [root2]\n while stk:\n temp = stk.pop()\n if target-temp.val in pool:\n return True\n if temp.right: stk.append(temp.right)\n if temp.left: stk.append(temp.left)\n return False\n" }, { "alpha_fraction": 0.4743589758872986, "alphanum_fraction": 0.4839743673801422, "avg_line_length": 24.25, "blob_id": "93a14ae806c0064a739cdaa0d9b773fceff78d77", "content_id": "9b036386de200c68be0d2ae7a737d070de3c5c98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 312, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/lc1402_greedy.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSatisfaction(self, satisfaction: List[int]) -> int:\n satisfaction.sort(reverse=True)\n curr = 0\n rslt = 0\n for val in satisfaction:\n curr += val\n if curr < 0:\n break\n rslt += curr\n\n return rslt\n \n" }, { "alpha_fraction": 0.3292181193828583, "alphanum_fraction": 0.35185185074806213, "avg_line_length": 31.399999618530273, "blob_id": "4927d0a7826bc84d24f5881ccd7bb63dfa412625", "content_id": "09f51eeedeeb3dc17a1224e374818556ff4d84f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 486, "license_type": "no_license", "max_line_length": 48, "num_lines": 15, "path": "/lc443_string.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def compress(self, chars: List[str]) -> int:\n rslt, cnt, left = 0, 0, 0\n for i, ch in enumerate(chars+[\")\"]):\n if i > 0 and ch != chars[i-1]:\n chars[left] = chars[i-1]\n left += 1\n if cnt > 1:\n for t in str(cnt):\n chars[left] = t\n left += 1\n cnt = 1\n else:\n cnt += 1\n return left\n" }, { "alpha_fraction": 0.44989773631095886, "alphanum_fraction": 0.4621676802635193, "avg_line_length": 33.92856979370117, "blob_id": "47fb4b02413f86ee816d32e394c03ad0b0666c12", "content_id": "7a822dadca3981d751762f63fe914a3d5323f2ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 83, "num_lines": 14, "path": "/lc1052_sw.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSatisfied(self, customers: List[int], grumpy: List[int], X: int) -> int:\n if X > len(customers):\n return sum(customers)\n i, curr, wind, cumsum= 0, 0, 0, 0\n for c, g in zip(customers, grumpy):\n cumsum += (1-g)*c\n if i < X:\n curr += g*c\n else:\n curr += g*c - grumpy[i-X]*customers[i-X]\n wind = max(wind, curr)\n i += 1\n return cumsum + wind\n" }, { "alpha_fraction": 0.352769672870636, "alphanum_fraction": 0.38678327202796936, "avg_line_length": 37.11111068725586, "blob_id": "6ff9e12c00a82362dd2b60962848d75c83837b17", "content_id": "655e9f50624ee83d390a076037db008235a1f85d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 113, "num_lines": 27, "path": "/lc289_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def gameOfLife(self, board: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n nrow, ncol = len(board), len(board[0])\n def helper(i, j):\n # -2: change from 1 to 0\n # -1: change from 0 to 1\n cl = 0\n for x, y in [(i-1, j-1), (i-1, j), (i-1, j+1), (i, j -1), (i, j+1),(i+1, j-1), (i+1, j), (i+1, j+1)]:\n if x < 0 or x >= nrow or y < 0 or y >= ncol:\n continue\n cl += 1 if board[x][y] in (1, -2) else 0\n return cl\n\n for i in range(nrow):\n for j in range(ncol):\n cl = helper(i, j)\n if board[i][j] == 1 and (cl < 2 or cl > 3):\n board[i][j] = -2\n if board[i][j] == 0 and cl == 3:\n board[i][j] = -1\n for i in range(nrow):\n for j in range(ncol):\n if board[i][j] < 0:\n board[i][j] += 2\n" }, { "alpha_fraction": 0.5032397508621216, "alphanum_fraction": 0.5032397508621216, "avg_line_length": 32.07143020629883, "blob_id": "baa3542686b62558bd71670a51ed9b640f8635ee", "content_id": "ffcbadaffc7e9ad6e1f6c77955ed415b3dbbb10f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 463, "license_type": "no_license", "max_line_length": 57, "num_lines": 14, "path": "/lc199_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def rightSideView(self, root: TreeNode) -> List[int]:\n if not root:\n return []\n queue = collections.deque([root])\n rslt = []\n while queue:\n lth = len(queue)\n for _ in range(lth):\n temp = queue.popleft()\n if temp.left: queue.append(temp.left)\n if temp.right: queue.append(temp.right)\n rslt.append(temp.val)\n return rslt\n" }, { "alpha_fraction": 0.45728641748428345, "alphanum_fraction": 0.4673366844654083, "avg_line_length": 33.6363639831543, "blob_id": "bb189ecf57b1f1434dd356240b1352e4a3d21905", "content_id": "ece9fa6555c80365a375aaa8ff5c55dc0dc7d956", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 65, "num_lines": 11, "path": "/lc90_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:\n nums.sort()\n rslt = []\n def backtracking(temp, i):\n rslt.append(temp)\n for j, num in enumerate(nums[i:]):\n if j == 0 or num != nums[j+i-1]:\n backtracking(temp+[num], i+j+1)\n backtracking([], 0)\n return rslt\n \n" }, { "alpha_fraction": 0.403474897146225, "alphanum_fraction": 0.42374518513679504, "avg_line_length": 44.043479919433594, "blob_id": "384f660eb7a9141a61ee6c11efe5aa2b9d095074", "content_id": "495786a7f23c3244c0fb5cdc07a8c9e92097ae37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/lc499_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findShortestWay(self, maze: List[List[int]], ball: List[int], hole: List[int]) -> str:\n directions = {\"d\":(1, 0), \"l\":(0, -1), \"r\":(0, 1),\"u\":(-1, 0)}\n heap, visited = [(0,\"\", ball[0], ball[1])], set()\n nrow, ncol = len(maze), len(maze[0])\n while heap:\n step, path, currx, curry = heapq.heappop(heap)\n if currx == hole[0] and curry == hole[1]:\n return path\n if (currx, curry) in visited:\n continue\n visited.add((currx, curry))\n for dr in [\"d\", \"l\", \"r\", \"u\"]:\n dx, dy = directions[dr]\n tx, ty, l = currx, curry, 0\n while 0 <= tx+dx < nrow and 0 <= ty+dy < ncol and maze[tx+dx][ty+dy] == 0:\n tx += dx\n ty += dy\n l += 1\n if tx == hole[0] and ty == hole[1]:\n break\n heapq.heappush(heap, (step+l, path+dr, tx, ty))\n return \"impossible\"\n" }, { "alpha_fraction": 0.3906705677509308, "alphanum_fraction": 0.40816327929496765, "avg_line_length": 29.272727966308594, "blob_id": "9adb5381687a16c7af2000073740cf46de44ec1e", "content_id": "2f240bd3ed54b5d9d0126d0f65b346c9836b394a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 43, "num_lines": 11, "path": "/lc54_greedy.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def jump(self, nums: List[int]) -> int:\n rslt, last, curr = 0, 0, 0\n for i, num in enumerate(nums[:-1]):\n curr = max(curr, i+num)\n if i == last:\n rslt += 1\n last = curr\n if last >= len(nums)-1:\n break\n return rslt\n\n \n" }, { "alpha_fraction": 0.40556368231773376, "alphanum_fraction": 0.4231332242488861, "avg_line_length": 28.69565200805664, "blob_id": "af7dc6631061067e9e1caf2d70f0306c295b0cab", "content_id": "8cdf1524aab9ea43358ccce3a55c563b7f581590", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/lc377_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n dp = [0]*(target+1)\n dp[0] = 1\n for i in range(target+1):\n for num in nums:\n if i-num >= 0:\n dp[i] = dp[i] + dp[i-num]\n return dp[-1]\n \nclass Solution:\n def combinationSum4(self, nums: List[int], target: int) -> int:\n memo = {0:1}\n def dfs(t):\n if t in memo:\n return memo[t]\n rslt = 0\n for num in nums:\n if num <= t:\n rslt += dfs(t-num)\n memo[t] = rslt\n return rslt\n return dfs(target)\n" }, { "alpha_fraction": 0.5171840190887451, "alphanum_fraction": 0.5254988670349121, "avg_line_length": 29.576271057128906, "blob_id": "f9279054ae7bd1cae7c75b6c6c6bea95a4e07a19", "content_id": "d43ff81f25ac98e85795426b2d4c16591492736a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1804, "license_type": "no_license", "max_line_length": 55, "num_lines": 59, "path": "/lc460_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, val = 0, key = 0, freq = 1):\n self.val = val\n self.key = key\n self.left = self.right = None\n self.freq = 1\n\nclass Dll:\n def __init__(self):\n self.snode = Node()\n self.snode.left =self.snode.right = self.snode\n self.size = 0\n def append(self, node):\n node.left = self.snode.left\n node.right = self.snode\n self.snode.left = node\n node.left.right = node\n self.size += 1\n def remove(self, node):\n node.left.right = node.right\n node.right.left = node.left\n node.left, node.right = None, None\n self.size -= 1\n def pop(self):\n temp = self.snode.right\n self.remove(temp)\n return temp\n\nclass LFUCache:\n\n def __init__(self, capacity: int):\n self.keynode = {}\n self.freq = collections.defaultdict(Dll)\n self.capacity = capacity\n self.min_freq = 1\n def get(self, key: int) -> int:\n if key not in self.keynode: return -1\n curr = self.keynode[key]\n dll = self.freq[curr.freq]\n dll.remove(curr)\n curr.freq += 1\n self.freq[curr.freq].append(curr)\n if self.freq[self.min_freq].size == 0:\n self.min_freq += 1\n return curr.val\n def put(self, key: int, value: int) -> None:\n if self.capacity <= 0:\n return\n if key in self.keynode:\n self.keynode[key].val = value\n self.get(key)\n else:\n if self.capacity == len(self.keynode):\n temp = self.freq[self.min_freq].pop()\n self.keynode.pop(temp.key)\n curr = Node(val = value, key = key)\n self.keynode[key] = curr\n self.freq[1].append(curr)\n self.min_freq = 1\n" }, { "alpha_fraction": 0.4553571343421936, "alphanum_fraction": 0.460317462682724, "avg_line_length": 36.25925827026367, "blob_id": "875dd47140461742199f08e513e9f2f8f8960d50", "content_id": "a35ec8d83cfb701a6d35f76f714d7faf2116f233", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1008, "license_type": "no_license", "max_line_length": 74, "num_lines": 27, "path": "/lc721_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:\n email_g, email_m = collections.defaultdict(set), {}\n for account in accounts:\n for email in account[1:]:\n if email != account[1]:\n email_g[account[1]].add(email)\n email_g[email].add(account[1])\n email_m[email] = account[0]\n rslt, visited = [], set()\n def dfs(email):\n if email not in email_g:\n visited.add(email)\n return [email]\n else:\n rslt = [email]\n for em in email_g[email]:\n if em not in visited:\n visited.add(em)\n rslt += dfs(em)\n return rslt\n for email, holder in email_m.items():\n if email not in visited:\n visited.add(email)\n rslt.append([holder]+sorted(dfs(email)))\n\n return rslt \n" }, { "alpha_fraction": 0.4060773551464081, "alphanum_fraction": 0.42817679047584534, "avg_line_length": 28.351350784301758, "blob_id": "f3ed4a2c7ecd94b2bf79cd39bb19fc55c9b4903a", "content_id": "ce95626b39a66b70b92b1b5ac33ce649ad773dd5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1086, "license_type": "no_license", "max_line_length": 61, "num_lines": 37, "path": "/lc1387_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# dfs + memoization\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n memo = {1:1}\n def dfs(i):\n if i in memo:\n return memo[i]\n elif i%2 == 0:\n memo[i] = dfs(i//2) + 1\n else:\n memo[i] = dfs(3*i + 1) + 1\n return memo[i]\n rslt = []\n for i in range(lo, hi+1):\n rslt.append((i, dfs(i)))\n rslt.sort(key=lambda x: x[1])\n return rslt[k-1][0]\n\n\n# slow bfs\nclass Solution:\n def getKth(self, lo: int, hi: int, k: int) -> int:\n queue = collections.deque()\n for i in range(lo, hi+1):\n queue.append((i, 0, i))\n rslt = []\n while queue:\n ori, curr_power, curr = queue.popleft()\n if curr == 1:\n rslt.append(ori)\n elif curr %2 == 0:\n queue.append((ori, curr_power+1, curr//2))\n else:\n queue.append((ori, curr_power+1, curr*3 + 1))\n if len(rslt) == k:\n break\n return rslt[-1]\n" }, { "alpha_fraction": 0.4226190447807312, "alphanum_fraction": 0.494047611951828, "avg_line_length": 44.818180084228516, "blob_id": "d832a86dcef45960c5c63ba153287f924f738336", "content_id": "15a793533335efe6251f748f510c6815062cc56b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 504, "license_type": "no_license", "max_line_length": 105, "num_lines": 11, "path": "/lc1458_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:\n l_1, l_2 = len(nums1), len(nums2)\n dp = [nums1[0]*nums2[0]]\n for i in range(1, l_1): dp.append(max(dp[-1], nums1[i]*nums2[0]))\n for j in range(1, l_2):\n dp2 = [max(dp[0], nums1[0]*nums2[j])]\n for i in range(1, l_1):\n dp2.append(max(dp[i-1], dp2[i-1], dp[i], dp[i-1] + nums1[i]*nums2[j], nums1[i]*nums2[j]))\n dp = dp2\n return dp[-1]\n" }, { "alpha_fraction": 0.41450777649879456, "alphanum_fraction": 0.4257340133190155, "avg_line_length": 32.08571243286133, "blob_id": "8d6c22e72faff098bc692f54c9e35666e19e18f0", "content_id": "64c80e35f26a670e3a3604334a83a795b78e7afe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/lc1552_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxDistance(self, position: List[int], m: int) -> int:\n position.sort()\n # def helper(mid):\n # rslt, left = 1, 0\n # for right in range(1, len(position)):\n # if position[right]-position[left] >= mid:\n # rslt += 1\n # left = right\n # return rslt\n # while left <= right:\n # mid = (left + right)//2\n # if helper(mid) >= m:\n # left = mid + 1\n # else:\n # right = mid - 1\n\nclass Solution:\n def maxDistance(self, position: List[int], m: int) -> int:a\n def helper(mid):\n pre = position[0]\n for _ in range(m-1):\n pos = bisect.bisect_left(position, pre + mid)\n if pos == len(position):\n return False\n pre = position[pos]\n return True\n left, right = 0, max(position)\n while left <= right:\n mid = (left + right)//2\n if helper(mid):\n left = mid + 1\n else:\n right = mid - 1\n return right\n" }, { "alpha_fraction": 0.5052381157875061, "alphanum_fraction": 0.5057142972946167, "avg_line_length": 30.34328269958496, "blob_id": "c4ce2f4f9598a57d0aaad954e99ccbc53dbd44ae", "content_id": "57b301f888bf5ef4e55f01b3afff75f1b9cf2c9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 66, "num_lines": 67, "path": "/lc545_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def boundaryOfBinaryTree(self, root: TreeNode) -> List[int]:\n rslt = []\n # root\n rslt.append(root.val)\n if not root.left and not root.right:\n return rslt\n # left boundary\n if root.left:\n left = root.left\n while left.left or left.right:\n rslt.append(left.val)\n left = left.left if left.left else left.right\n # leaves\n stack = [root]\n while stack:\n temp = stack.pop()\n if not temp.left and not temp.right:\n rslt.append(temp.val)\n if temp.right:\n stack.append(temp.right)\n if temp.left:\n stack.append(temp.left)\n # right boundary\n temp = []\n if root.right:\n right = root.right\n while right.right or right.left:\n temp.append(right.val)\n right = right.right if right.right else right.left\n return rslt + temp[::-1]\n\nclass Solution(object):\n def boundaryOfBinaryTree(self, root):\n def dfs_leftmost(node):\n if not node or not node.left and not node.right:\n return\n boundary.append(node.val)\n if node.left:\n dfs_leftmost(node.left)\n else:\n dfs_leftmost(node.right)\n\n def dfs_leaves(node):\n if not node:\n return\n if node != root and not node.left and not node.right:\n boundary.append(node.val)\n dfs_leaves(node.left)\n dfs_leaves(node.right)\n\n def dfs_rightmost(node):\n if not node or not node.left and not node.right:\n return\n if node.right:\n dfs_rightmost(node.right)\n else:\n dfs_rightmost(node.left)\n boundary.append(node.val)\n\n if not root:\n return []\n boundary = [root.val]\n dfs_leftmost(root.left)\n dfs_leaves(root)\n dfs_rightmost(root.right)\n return boundary\n" }, { "alpha_fraction": 0.4729166626930237, "alphanum_fraction": 0.4791666567325592, "avg_line_length": 33.28571319580078, "blob_id": "3e2c80aa1feaf8846e1dbcfd11a8aade227dfbfd", "content_id": "adbcb29d4720763d3d854c35e89a5f4bea26a044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 64, "num_lines": 14, "path": "/lc47_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def permuteUnique(self, nums: List[int]) -> List[List[int]]:\n if not nums: return []\n rslt = []\n nums.sort()\n def backtracking(temp, cand):\n if not cand:\n rslt.append(temp)\n for i, num in enumerate(cand):\n if i != 0 and num == cand[i-1]:\n continue\n backtracking(temp+[num], cand[:i]+cand[i+1:])\n backtracking([], nums)\n return rslt\n" }, { "alpha_fraction": 0.3826998770236969, "alphanum_fraction": 0.39842724800109863, "avg_line_length": 41.38888931274414, "blob_id": "6f694b7f6e3ee007f10d486a7688893739416ca8", "content_id": "bd28fae0e00a6452d22d08d9fd19dfbd7d9e7a04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 763, "license_type": "no_license", "max_line_length": 101, "num_lines": 18, "path": "/lc51_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def solveNQueens(self, n: int) -> List[List[str]]:\n rslt, visited= [], set()\n def backtracking(i, curr):\n if len(curr) == n:\n rslt.append(curr)\n else:\n for j in range(n):\n if (2, j) not in visited and (3, j-i) not in visited and (4, j+i) not in visited:\n visited.add((2, j))\n visited.add((3, j-i))\n visited.add((4, j+i))\n backtracking(i+1, curr + [\".\"*j+\"Q\"+\".\"*(n-j-1)] )\n visited.remove((2, j))\n visited.remove((3, j-i))\n visited.remove((4, j+i))\n backtracking(0, [])\n return rslt\n" }, { "alpha_fraction": 0.36244019865989685, "alphanum_fraction": 0.4019138813018799, "avg_line_length": 38.80952453613281, "blob_id": "e2ef0f852b2d8ec0bf99432ba64fbdca93618c57", "content_id": "32c6f5769f3247048e4340edc2349c52a60a98d2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 836, "license_type": "no_license", "max_line_length": 76, "num_lines": 21, "path": "/lc764_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def orderOfLargestPlusSign(self, N: int, mines: List[List[int]]) -> int:\n mines = {tuple(x) for x in mines}\n dp = [[[0,0] for _ in range(N+2)] for _ in range(N+2)]\n # left, above, right, below\n # left, above\n for i in range(N):\n for j in range(N):\n if (i, j) not in mines:\n dp[i+1][j+1][0] = dp[i+1][j][0] + 1\n dp[i+1][j+1][1] = dp[i][j+1][1] + 1\n # right, below\n rslt = 0\n for i in range(N, 0, -1):\n for j in range(N, 0, -1):\n if (i-1, j-1) not in mines:\n dp[i][j][0] = min(dp[i][j][0], dp[i][j+1][0] + 1)\n dp[i][j][1] = min(dp[i][j][1], dp[i+1][j][1] + 1)\n rslt = max(rslt, min(dp[i][j]))\n\n return rslt\n" }, { "alpha_fraction": 0.45351043343544006, "alphanum_fraction": 0.47438329458236694, "avg_line_length": 36.64285659790039, "blob_id": "b0ddfe3297c3c7e05ea763bb1bc14dccf9055bdf", "content_id": "dced0f05a6bd49f6d482ca031e83535c2d4f42b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 76, "num_lines": 14, "path": "/lc340_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:\n container, count, left, rslt = collections.defaultdict(int), 0, 0, 0\n for right, c in enumerate(s):\n if container[c] == 0:\n count += 1\n container[c] += 1\n while count > k:\n container[s[left]] -= 1\n if container[s[left]] == 0:\n count -= 1\n left += 1\n rslt = max(rslt, right-left+1)\n return rslt\n" }, { "alpha_fraction": 0.4835423231124878, "alphanum_fraction": 0.4858934283256531, "avg_line_length": 33.486488342285156, "blob_id": "4d1fdfbf48457605f06cf93dc3ec75876052764b", "content_id": "636a584229de66963e2f2ca9407c5d3e8845ed1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1276, "license_type": "no_license", "max_line_length": 97, "num_lines": 37, "path": "/lc1644_lca.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n self.mark = 0\n def dfs(root, p, q):\n if not root: return None\n left = dfs(root.left, p, q)\n right = dfs(root.right, p, q)\n if root == p or root == q:\n self.mark += 1\n return root\n if left and right:\n return root\n return left or right\n\n rslt = dfs(root, p, q)\n return rslt if self.mark == 2 else None\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n parents = {root:None}\n stack = [root]\n while stack:\n parent = stack.pop()\n if parent.right:\n parents[parent.right] = parent\n stack.append(parent.right)\n if parent.left:\n parents[parent.left] = parent\n stack.append(parent.left)\n cands = set()\n if p not in parents or q not in parents:\n return None\n while p in parents:\n cands.add(p)\n p = parents[p]\n while q in parents:\n if q in cands:\n return q\n q = parents[q]\n" }, { "alpha_fraction": 0.5107376575469971, "alphanum_fraction": 0.518207311630249, "avg_line_length": 34.70000076293945, "blob_id": "9929b145b3d6f4f0547a8f7251546178501b7a20", "content_id": "4b62afa6b32498e3551a3fa9d946079340880865", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 77, "num_lines": 30, "path": "/lc105_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n\n if not preorder or not inorder: return None\n root = TreeNode(preorder[0])\n idx = inorder.index(root.val)\n root.left = self.buildTree(preorder[1:idx+1], inorder[:idx])\n root.right = self.buildTree(preorder[idx+1:], inorder[idx+1:])\n return root\n\n\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n nodemap = {val:idx for idx, val in enumerate(inorder)}\n stk, head = [], None\n\n for val in preorder:\n if not head:\n head = TreeNode(val)\n stk.append(head)\n else:\n temp = TreeNode(val)\n if nodemap[val] < nodemap[stk[-1].val]:\n stk[-1].left = temp\n else:\n while stk and nodemap[stk[-1].val] < nodemap[val]:\n last = stk.pop()\n last.right = temp\n stk.append(temp)\n return head\n" }, { "alpha_fraction": 0.3719165027141571, "alphanum_fraction": 0.4079696536064148, "avg_line_length": 39.53845977783203, "blob_id": "21e5c317d0a80623cb5b1cc8a4f9a6bbb5cd01a5", "content_id": "597dcf00fc3c12e24bb19422ac5ae3447cd32463", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 71, "num_lines": 13, "path": "/lc576_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:\n memo = {}\n def dfs(x, y, step):\n if (x, y, step) in memo: return memo[(x, y, step)]\n if (x < 0 or x >= m or y < 0 or y >= n): return 1\n if step == 0: return 0\n rslt = 0\n for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n rslt += dfs(x+dx, y+dy, step-1)\n memo[(x, y, step)] = rslt\n return rslt\n return dfs(i, j, N)%(10**9+7)\n" }, { "alpha_fraction": 0.5033259391784668, "alphanum_fraction": 0.5133037567138672, "avg_line_length": 36.58333206176758, "blob_id": "b5167451c7fa3798d9ee1f9b7c3b0e83a74799b3", "content_id": "5956b942f7d05f1ef5614a99de700bc0f9971139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 72, "num_lines": 24, "path": "/lc1425_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n dque, dp= collections.deque(), [0]*len(nums)\n for idx, num in enumerate(nums):\n while dque and idx - dque[0] > k:\n dque.popleft()\n dp[idx] = max(num, dp[dque[0]]+num) if idx != 0 else num\n while dque and dp[dque[-1]] < dp[idx]:\n dque.pop()\n dque.append(idx)\n return max(dp)\n\n\nclass Solution:\n def constrainedSubsetSum(self, nums: List[int], k: int) -> int:\n dque = collections.deque()\n for idx, num in enumerate(nums):\n if dque and idx - dque[0] > k:\n dque.popleft()\n nums[idx] = max(num, nums[dque[0]]+num) if idx != 0 else num\n while dque and nums[dque[-1]] <= nums[idx]:\n dque.pop()\n dque.append(idx)\n return max(nums)\n" }, { "alpha_fraction": 0.4988713264465332, "alphanum_fraction": 0.5101580023765564, "avg_line_length": 39.272727966308594, "blob_id": "ab02af74017c3e4bf2b0db3ae88e2ceae6cb81cf", "content_id": "b2c17440c0317f95ee95e850a30a48a2e891198b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 443, "license_type": "no_license", "max_line_length": 102, "num_lines": 11, "path": "/lc887_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def stoneGame(self, piles: List[int]) -> bool:\n memo = {}\n def dfs(left, right):\n if (left, right) in memo:\n return memo[(left, right)]\n if left == right:\n return piles[left]\n memo[(left, right)] = max(piles[left]-dfs(left+1, right), piles[right]-dfs(left, right-1))\n return memo[(left, right)]\n return dfs(0, len(piles)-1) > 0\n" }, { "alpha_fraction": 0.409411758184433, "alphanum_fraction": 0.4176470637321472, "avg_line_length": 37.6363639831543, "blob_id": "fcff6264570d94f2212d80a19326d64b5935f053", "content_id": "130aa41003d73c79da6870dcda50388a6fee9446", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 850, "license_type": "no_license", "max_line_length": 73, "num_lines": 22, "path": "/lc1597_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def expTree(self, s):\n op_pr = {\"+\":2, \"-\": 2, \"*\":1, \"/\":1, \"(\":3, \")\":2}\n node_stack, op_stack = [], []\n for c in s:\n if c.isdigit():\n node_stack.append(Node(c))\n elif c == '(':\n op_stack.append(c)\n else:\n while op_stack and op_pr[c] >= op_pr[op_stack[-1]]:\n temp = Node(op_stack.pop(), right = node_stack.pop())\n temp.left = node_stack.pop()\n node_stack.append(temp)\n if c == ')': op_stack.pop()\n else:\n op_stack.append(c)\n while op_stack:\n temp = Node(op_stack.pop(), right = node_stack.pop())\n temp.left = node_stack.pop()\n node_stack.append(temp)\n return node_stack.pop()\n" }, { "alpha_fraction": 0.38461539149284363, "alphanum_fraction": 0.4282744228839874, "avg_line_length": 39.08333206176758, "blob_id": "8f9572047b55fc30618fb58f36c76e3d93ffcece", "content_id": "e69181adfdf8e4780bc0ea106a190f6d24e9bd08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 72, "num_lines": 12, "path": "/lc1312_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minInsertions(self, s: str) -> int:\n n = len(s)\n dp = [1 if s[0] == s[-1] else 0]\n for i in range(1, n): dp.append(1 if s[i] == s[-1] else dp[i-1])\n for j in range(1, n):\n tdp = [max(dp[0], 1 if s[0] == s[n-j-1] else 0)]\n for i in range(1, n-j):\n temp = 1 if s[i] == s[n-j-1] else 0\n tdp.append(max(dp[i-1]+ temp, dp[i], tdp[i-1]))\n dp = tdp\n return n-dp[-1]\n" }, { "alpha_fraction": 0.43044620752334595, "alphanum_fraction": 0.4356955289840698, "avg_line_length": 30.75, "blob_id": "c3e435606c51e6f76788163182b3461dc86166b1", "content_id": "e3d6fe2d4b6dad08078b8ae666d10a04e45c25c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 381, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/lc784_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def letterCasePermutation(self, S: str) -> List[str]:\n rslt, n = [], len(S)\n def backtracking(i, curr):\n if i == n:\n rslt.append(curr)\n else:\n x = S[i]\n for y in {x.upper(), x.lower()}:\n backtracking(i+1, curr+y)\n backtracking(0, \"\")\n return rslt\n" }, { "alpha_fraction": 0.40512821078300476, "alphanum_fraction": 0.44102564454078674, "avg_line_length": 33.411766052246094, "blob_id": "8b89834cd6e0aaa7091cc80eaebc9e198451bb71", "content_id": "954540332dbd9f102ae08c6693864b3488e14ea1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 585, "license_type": "no_license", "max_line_length": 66, "num_lines": 17, "path": "/lc1870_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minSpeedOnTime(self, dist: List[int], hour: float) -> int:\n if hour < len(dist) - 1: return -1\n left, right = 1, int(100000/0.01)\n def check(mid):\n rslt = 0\n for d in dist[:-1]:\n rslt += (d-1)//mid + 1\n return rslt + dist[-1]/mid\n while left <= right:\n mid = (left + right)//2\n temp = check(mid)\n if temp <= hour:\n right = mid - 1\n else:\n left = mid + 1\n return int(left) if check(left) <= hour else -1\n" }, { "alpha_fraction": 0.37295082211494446, "alphanum_fraction": 0.3862704932689667, "avg_line_length": 41.39130401611328, "blob_id": "c4d6f75fd0060aeae61f69a9b7e447837cb6ece2", "content_id": "4e415d00257980aa7e6106e183996ce0777f1f9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 976, "license_type": "no_license", "max_line_length": 87, "num_lines": 23, "path": "/lc1284_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minFlips(self, mat: List[List[int]]) -> int:\n start, nrow, ncol = 0, len(mat), len(mat[0])\n for i in range(nrow):\n for j in range(ncol):\n start |= mat[i][j]<< (i*ncol+j)\n dque, visited, step = collections.deque([start]), {start}, 0\n while dque:\n size = len(dque)\n for _ in range(size):\n curr = dque.popleft()\n if curr == 0: return step\n for i in range(nrow):\n for j in range(ncol):\n temp = curr\n for di, dj in [(i, j), (i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if 0 <= di < nrow and 0 <= dj < ncol:\n temp ^= 1 <<(di*ncol + dj)\n if temp not in visited:\n visited.add(temp)\n dque.append(temp)\n step += 1\n return -1 \n" }, { "alpha_fraction": 0.5529412031173706, "alphanum_fraction": 0.5630252361297607, "avg_line_length": 38.66666793823242, "blob_id": "3ad51e06bb61cfbf427a97b2a68fd3198ddf1b1f", "content_id": "49b7a63a923a16ac0eecc8986d1ebbb00f6e1c63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 595, "license_type": "no_license", "max_line_length": 86, "num_lines": 15, "path": "/lc464_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:\n @lru_cache(None)\n def dfs(cands, target):\n if not cands:\n return False\n if cands[-1] >= target:\n return True\n\n for i, cand in enumerate(cands):\n if not dfs(cands[:i]+cands[i+1:], target-cand):\n return True\n return False\n if maxChoosableInteger*(maxChoosableInteger+1)//2 < desiredTotal: return False\n return dfs(tuple(range(1, maxChoosableInteger+1)), desiredTotal)\n" }, { "alpha_fraction": 0.4523809552192688, "alphanum_fraction": 0.46536797285079956, "avg_line_length": 34.53845977783203, "blob_id": "7b62f30cc03b50229f9d2a659cb2e502f93496bd", "content_id": "6e7323f9fa98fd7af1c552ca3f63f91d4f0b73e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 462, "license_type": "no_license", "max_line_length": 65, "num_lines": 13, "path": "/lc547_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findCircleNum(self, isConnected: List[List[int]]) -> int:\n def dfs(i):\n for j in range(len(isConnected)):\n if isConnected[i][j] == 1 and visited[j] == 0:\n visited[j] = 1\n dfs(j)\n visited, rslt= [0]*len(isConnected), 0\n for i in range(len(isConnected)):\n if not visited[i]:\n dfs(i)\n rslt += 1\n return rslt\n" }, { "alpha_fraction": 0.49275362491607666, "alphanum_fraction": 0.5113871693611145, "avg_line_length": 39.25, "blob_id": "d275170c709442b2206f70ff58a1a4181185ce23", "content_id": "60975968dcadc8f418d29193cae59d50a0513eb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 966, "license_type": "no_license", "max_line_length": 95, "num_lines": 24, "path": "/lc57_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n intervals.append(newInterval)\n intervals.sort()\n rslt = [intervals[0]]\n for x, y in intervals[1:]:\n if x > rslt[-1][1]:\n rslt.append([x, y])\n else:\n rslt[-1][0], rslt[-1][1] = min(rslt[-1][0], x), max(rslt[-1][1], y)\n return rslt\n\n def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:\n # intervals are initially sorted\n rslt, mark = [], True\n for i, (x, y) in enumerate(intervals):\n if y < newInterval[0]:\n rslt.append([x, y])\n elif x > newInterval[1]:\n rslt.append(newInterval)\n return rslt + intervals[i:]\n else:\n newInterval[0], newInterval[1] = min(x, newInterval[0]), max(y, newInterval[1])\n return rslt\n" }, { "alpha_fraction": 0.462981253862381, "alphanum_fraction": 0.4856860935688019, "avg_line_length": 47.238094329833984, "blob_id": "5b6f198cc7776d6a98685263be72a00de35f333a", "content_id": "c4d8c990a6b1812068f190cb29d01a986c25dcd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1013, "license_type": "no_license", "max_line_length": 83, "num_lines": 21, "path": "/lc407_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def trapRainWater(self, heightMap: List[List[int]]) -> int:\n heap, visited = [], set()\n nrow, ncol = len(heightMap), len(heightMap[0])\n for i in range(nrow):\n heapq.heappush(heap, (heightMap[i][0], i, 0))\n heapq.heappush(heap, (heightMap[i][ncol-1], i, ncol-1))\n visited |= {(i, 0), (i, ncol-1)}\n for j in range(ncol):\n heapq.heappush(heap, (heightMap[0][j], 0, j))\n heapq.heappush(heap, (heightMap[nrow-1][j], nrow-1, j))\n visited |= {(0, j), (nrow-1, j)}\n rslt = 0\n while heap:\n border, x, y = heapq.heappop(heap)\n for nx, ny in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:\n if 0 < nx < nrow-1 and 0 < ny < ncol-1 and (nx, ny) not in visited:\n rslt += max(0, border-heightMap[nx][ny])\n visited.add((nx, ny))\n heapq.heappush(heap, (max(border, heightMap[nx][ny]), nx, ny))\n return rslt\n" }, { "alpha_fraction": 0.39461883902549744, "alphanum_fraction": 0.4125560522079468, "avg_line_length": 32.45000076293945, "blob_id": "5f5dbc686376d18b2b3d95dddd6fa2369e574c54", "content_id": "c3ede426470358e99521d0b26702e5bf2ee8ee5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 72, "num_lines": 20, "path": "/lc1353_heap.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxEvents(self, events: List[List[int]]) -> int:\n events.sort()\n rslt, last = 0, 0\n heap = []\n i = 0\n while i < len(events) or heap:\n if not heap: last = events[i][0]\n if i < len(events) and events[i][0] <= last <= events[i][1]:\n heapq.heappush(heap, events[i][1])\n i += 1\n elif i < len(events) and events[i][1] < last:\n i += 1\n continue\n elif heap:\n temp = heapq.heappop(heap)\n if temp >= last:\n rslt += 1\n last += 1\n return rslt\n" }, { "alpha_fraction": 0.4757462739944458, "alphanum_fraction": 0.4981343150138855, "avg_line_length": 39.53845977783203, "blob_id": "de06dfa1b18c75e62eb48a2969564b80790a3412", "content_id": "57a3bbe731f2af65c2c407a9194850851a8b86d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 76, "num_lines": 13, "path": "/lc1648_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxProfit(self, inventory: List[int], orders: int) -> int:\n # find k\n left, right = 0, max(inventory)\n helper = lambda k: sum(max(0, i-k) for i in inventory)\n while left <= right:\n mid = (left+right)//2\n if helper(mid) < orders:\n right = mid -1\n else:\n left = mid + 1\n rslt = sum((i+right+1)*(i-right)//2 for i in inventory if i > right)\n return (rslt - (helper(right)-orders)*(right+1))%(10**9+7)\n \n" }, { "alpha_fraction": 0.5472440719604492, "alphanum_fraction": 0.5629921555519104, "avg_line_length": 35.28571319580078, "blob_id": "33d25c3e9815a67e45f3fa00d485b8f4c891eafc", "content_id": "03a259827e870e36569f4d180c70750d36e9fc0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 254, "license_type": "no_license", "max_line_length": 68, "num_lines": 7, "path": "/lc252_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canAttendMeetings(self, intervals: List[List[int]]) -> bool:\n intervals.sort()\n for i, it in enumerate(intervals):\n if i > 0 and it[0] < intervals[i-1][1]:\n return False\n return True\n" }, { "alpha_fraction": 0.39065107703208923, "alphanum_fraction": 0.404006689786911, "avg_line_length": 28.950000762939453, "blob_id": "1d76f3f41c205ed02714e52669aa5b4a921a2c76", "content_id": "4ad55871520552491494ed5998f132da3785dc1f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 44, "num_lines": 20, "path": "/lc1234_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def balancedString(self, s: str) -> int:\n count = collections.Counter(s)\n extra = {}\n n = len(s)\n a = n//4\n for key in count:\n if count[key] > a:\n extra[key] = count[key]-a\n if not extra: return 0\n l, rslt = 0, len(s)\n for r in range(n):\n if s[r] in extra:\n extra[s[r]]-=1\n while max(extra.values()) <= 0:\n rslt = min(rslt, r-l+1)\n if s[l] in extra:\n extra[s[l]] += 1\n l += 1\n return rslt\n" }, { "alpha_fraction": 0.505084753036499, "alphanum_fraction": 0.508474588394165, "avg_line_length": 35.875, "blob_id": "5213c4d2d2568da614c526c6eab45022c79aa45c", "content_id": "d169b6cd3b4fd57071c8b6f6134ad9f73abd57c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 68, "num_lines": 8, "path": "/lc1673_stk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def mostCompetitive(self, nums: List[int], k: int) -> List[int]:\n stk, tl= [], len(nums)\n for i, num in enumerate(nums):\n while stk and stk[-1] > num and tl-i+len(stk) > k:\n stk.pop()\n stk.append(num)\n return stk[:k]\n" }, { "alpha_fraction": 0.49066388607025146, "alphanum_fraction": 0.5072613954544067, "avg_line_length": 34.703704833984375, "blob_id": "c969cda9758950c7e5e845c76aba64500068e6ef", "content_id": "22262dbca46d2c321d86ece8195fccb6bcbed8a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 86, "num_lines": 27, "path": "/lc322_dp_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# BK\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n coins.sort(reverse = True)\n self.rslt = float(\"inf\")\n def backtracking(amount, i, val):\n if amount == 0:\n self.rslt = min(self.rslt, val)\n return\n if i>= len(coins) or amount < 0 or val + amount //coins[i] +1 > self.rslt:\n return\n temp = amount //coins[i]\n for j in range(temp, -1, -1):\n backtracking(amount-coins[i]*j, i+1, val+j)\n\n backtracking(amount, 0, 0)\n return self.rslt if self.rslt < float(\"inf\") else -1\n\n# DP\nclass Solution:\n def coinChange(self, coins: List[int], amount: int) -> int:\n dp = [float(\"inf\")]*(amount+1)\n dp[0] = 0\n for coin in coins:\n for x in range(coin, amount+1):\n dp[x] = min(dp[x], dp[x-coin] + 1)\n return dp[-1] if dp[amount] < float(\"inf\") else -1\n" }, { "alpha_fraction": 0.4126984179019928, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 30.5, "blob_id": "57d6ea1d17bf8f8f313ae398fe60fa1a6688b77a", "content_id": "3e9511c02518ac039eabadf5368c717067b54cc0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 69, "num_lines": 20, "path": "/lc1231_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maximizeSweetness(self, sweetness: List[int], K: int) -> int:\n def check(mid):\n cuts, curr = 0, 0\n for s in sweetness:\n curr += s\n if curr >= mid:\n cuts += 1\n curr = 0\n return cuts\n\n if len(sweetness) == K+1: return min(sweetness)\n left, right = min(sweetness), sum(sweetness)//(K+1)+1\n while left <= right:\n mid = (left + right)//2\n if check(mid) > K:\n left = mid + 1\n else:\n right = mid - 1\n return right\n" }, { "alpha_fraction": 0.41683366894721985, "alphanum_fraction": 0.4308617115020752, "avg_line_length": 26.72222137451172, "blob_id": "d69a5d24d77677438a4c8d679a71e92d0cd358d6", "content_id": "fcfa448a333831c6f655893a3ab0bbb4e1ac7578", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 66, "num_lines": 18, "path": "/lc32_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestValidParentheses(self, s: str) -> int:\n rslt = max(self.helper(s, '('), self.helper(s[::-1], ')'))\n return rslt\n\n def helper(self, s, check):\n left = right = rslt = 0\n for c in s:\n if c == check:\n left += 1\n else:\n right += 1\n\n if right > left:\n left, right = 0, 0\n elif right == left:\n rslt = max(rslt, 2*right)\n return rslt\n" }, { "alpha_fraction": 0.445333331823349, "alphanum_fraction": 0.4560000002384186, "avg_line_length": 30.25, "blob_id": "0352e68dd8ae6f88cd14c9f81fa7017be1e16b28", "content_id": "1e0822bca3f1e78e89970976efedc890aa0756ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/lc763_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def partitionLabels(self, S: str) -> List[int]:\n temp = {}\n for i, c in enumerate(S):\n temp[c] = i\n left, right, rslt = 0, 0, []\n for i, c in enumerate(S):\n right = max(right, temp[c])\n if i == right:\n rslt.append(right-left+1)\n left = right+1\n return rslt\n" }, { "alpha_fraction": 0.4900990128517151, "alphanum_fraction": 0.5, "avg_line_length": 35.727272033691406, "blob_id": "5ee213038cdcec74cfa71a7ccf301ee9ea714e11", "content_id": "1ca34a8bc95199318806a475c9f537dbc907a5fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 58, "num_lines": 11, "path": "/lc1590_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minSubarray(self, nums: List[int], p: int) -> int:\n maps = {0:-1}\n target = sum(nums)%p\n curr, rslt = 0, len(nums)\n for i, num in enumerate(nums):\n curr = (curr+num)%p\n maps[curr] = i\n if (curr-target)%p in maps:\n rslt = min(rslt, i-maps[(curr-target)%p])\n return rslt if rslt < len(nums) else -1\n" }, { "alpha_fraction": 0.606914222240448, "alphanum_fraction": 0.617157518863678, "avg_line_length": 44.94117736816406, "blob_id": "efdf0d89163409a5eaabc6388e9e983552785ce5", "content_id": "2d718a1a94fa1aa2405ccc05731b73ebd221dd44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 781, "license_type": "no_license", "max_line_length": 226, "num_lines": 17, "path": "/lc609_hash.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head: return None\n nodemap = {}\n def dfs(curr):\n if not curr: return None\n if curr in nodemap: return nodemap[curr]\n copy = Node(curr.val)\n nodemap[curr] = copy\n copy.next = dfs(curr.next)\n copy.random = dfs(curr.random)\n return copy\n return dfs(head)\n\n# Follow up:\n# - DFS: as we must arrive at the file, like a leaf node in the tree, and we don't care the directory unless there's files in there, DFS will be a better choice, as DFS can resuse the shared path before leaving that directory.\n# - 1. Use File size. 2. Compare random sampled rows. 3. Check MD5 or SHA256 hash, 4 check byte by byte\n" }, { "alpha_fraction": 0.47546011209487915, "alphanum_fraction": 0.493865042924881, "avg_line_length": 31.600000381469727, "blob_id": "db5d7f4f24cc97101dfca1159e8582623cc8b7ed", "content_id": "cca04d70b6a11ff74789f74b5737973f11c33ecd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 326, "license_type": "no_license", "max_line_length": 67, "num_lines": 10, "path": "/lc881_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numRescueBoats(self, people: List[int], limit: int) -> int:\n people.sort()\n left, right, rslt = 0, len(people)-1, 0\n while left <= right:\n if people[left]+people[right] <= limit:\n left += 1\n rslt += 1\n right -= 1\n return rslt\n" }, { "alpha_fraction": 0.542397677898407, "alphanum_fraction": 0.5482456088066101, "avg_line_length": 39.235294342041016, "blob_id": "1059e1b30def08e83836d82836ef5fb0cc11c2d0", "content_id": "e02269b918661d8fd9003a97b4b59904fa3a93d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "no_license", "max_line_length": 88, "num_lines": 17, "path": "/lc210_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:\n graph, degree = collections.defaultdict(list), collections.defaultdict(int)\n for curr, pre in prerequisites:\n graph[pre].append(curr)\n degree[curr] += 1\n\n dque = collections.deque([crs for crs in range(numCourses) if degree[crs] == 0])\n rslt = []\n while dque:\n pre = dque.popleft()\n rslt.append(pre)\n for post in graph[pre]:\n degree[post] -= 1\n if degree[post] == 0:\n dque.append(post)\n return rslt if len(rslt) == numCourses else []\n" }, { "alpha_fraction": 0.4795081913471222, "alphanum_fraction": 0.49707260727882385, "avg_line_length": 35.34042739868164, "blob_id": "360f44db67d4c816cf734e53add8efcc889efcf1", "content_id": "351a58faf1629c3278c9aff388a0cd894c4a3bb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 85, "num_lines": 47, "path": "/lc1562_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n if m == len(arr): return m\n border, rslt =[0]*(len(arr)+2), -1\n for i, idx in enumerate(arr):\n left = right = idx\n if border[right + 1] > 0: right = border[right + 1]\n if border[left - 1] > 0: left = border[left - 1]\n border[left], border[right] = right, left\n if (right-idx==m) or (idx-left ==m): rslt = i\n return rslt\n\n# deque + hashtable\n\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n if len(arr) == m: return m\n dp = [0]*(len(arr)+1)\n for i, idx in enumerate(arr): dp[idx] = i+1\n dque, rslt = collections.deque(), -1\n for i in range(1, len(dp)):\n while dque and dp[dque[-1]] < dp[i]:\n dque.pop()\n while dque and i- dque[0] >= m:\n dque.popleft()\n dque.append(i)\n if i < m: continue\n left, right, maxDay = float(\"inf\"), float(\"inf\"), dp[dque[0]]\n if i-m >= 1: left = dp[i-m]\n if i+1 <= len(arr): right = dp[i+1]\n if maxDay < left and maxDay < right:\n rslt = max(rslt, min(left,right)-1)\n return rslt\n\n\n\n# too slow, binary search\nclass Solution:\n def findLatestStep(self, arr: List[int], m: int) -> int:\n if m == len(arr): return m\n cands = [0, len(arr)+1]\n for i, idx in enumerate(arr[::-1]):\n temp = bisect.bisect(cands, idx)\n cands.insert(temp, idx)\n if cands[temp]-cands[temp-1]-1 == m or cands[temp+1]- cands[temp]-1 == m:\n return len(arr)-i-1\n return -1\n" }, { "alpha_fraction": 0.44771721959114075, "alphanum_fraction": 0.44771721959114075, "avg_line_length": 32.95000076293945, "blob_id": "2287affe9fc737bd9b48966644875cfc510156d8", "content_id": "357308f7d0e438c833fd8b8414167eff1b9ba7d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "no_license", "max_line_length": 82, "num_lines": 20, "path": "/lc851_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:\n richer_map = collections.defaultdict(set)\n for x, y in richer:\n richer_map[y].add(x)\n memo = {}\n def dfs(x):\n if x in memo:\n return memo[x]\n if not richer_map[x]:\n return x\n curr, rslt = quiet[x], x\n for t in richer_map[x]:\n temp = dfs(t)\n if quiet[temp] < curr:\n curr = quiet[temp]\n rslt = temp\n memo[x] = rslt\n return rslt\n return [dfs(x) for x in range(len(quiet))]\n" }, { "alpha_fraction": 0.4402298927307129, "alphanum_fraction": 0.44712644815444946, "avg_line_length": 33.79999923706055, "blob_id": "f643f13ae3d8728eb96adb461704f8c181b4d36a", "content_id": "559f14c28df7f1d82f9873ed76dc3eb780534e93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 870, "license_type": "no_license", "max_line_length": 91, "num_lines": 25, "path": "/lc1627_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]:\n parent = list(range(n+1))\n size = [1]*(n+1)\n def find(p):\n while p != parent[p]:\n parent[p] = parent[parent[p]]\n p = parent[p]\n return p\n def union(p, q):\n rootp, rootq = find(p), find(q)\n if rootp == rootq: return\n if size[rootp] < size[rootq]:\n rootp, rootq = rootq, rootp\n parent[rootq] = rootp\n size[rootp] += size[rootq]\n return\n for i in range(n+1):\n if i > threshold and parent[i] == i:\n for j in range(2*i, n+1, i):\n union(i, j)\n rslt = []\n for a, b in queries:\n rslt.append(find(a) == find(b))\n return rslt\n" }, { "alpha_fraction": 0.36692014336586, "alphanum_fraction": 0.427756667137146, "avg_line_length": 39.53845977783203, "blob_id": "c687efa51c25b2dfd329f0aee64524b916fdb450", "content_id": "131999370e224d35dcbd7ad7eb944fda3b3f9a1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 526, "license_type": "no_license", "max_line_length": 75, "num_lines": 13, "path": "/lc72_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n l1, l2 = len(word1), len(word2)\n dp = [[0]*(l1 +1) for _ in range(l2+1)]\n for j in range(l2+1): dp[j][0] = j\n for i in range(l1+1): dp[0][i] = i\n for i, c1 in enumerate(word1):\n for j, c2 in enumerate(word2):\n if c1 == c2:\n dp[j+1][i+1] = dp[j][i]\n else:\n dp[j+1][i+1] = min(dp[j][i+1], dp[j+1][i], dp[j][i]) +1\n return dp[-1][-1]" }, { "alpha_fraction": 0.4745260775089264, "alphanum_fraction": 0.4768957197666168, "avg_line_length": 26.672130584716797, "blob_id": "c62f2080d93cd26daa57152e73b1b4434bd28f23", "content_id": "44ac8482cf3a7052301df39df724e7d661fc02cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 69, "num_lines": 61, "path": "/lc323_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countComponents(self, n: int, edges: List[List[int]]) -> int:\n uf = UF(n)\n for x, y in edges:\n uf.union(x, y)\n return uf.getsize()\n\n\nclass UF:\n def __init__(self, n):\n self.parent = list(range(n))\n self.size = [1]*n\n self.count = n\n def union(self, p, q):\n rootp = self.find(p)\n rootq = self.find(q)\n if rootp == rootq:return\n if self.size[rootp] < self.size[rootq]:\n rootp, rootq = rootq, rootp\n self.parent[rootq] = rootp\n self.size[rootp] += self.size[rootq]\n self.count -= 1\n return\n def find(self, p):\n while self.parent[p] != p:\n self.parent[p] = self.parent[self.parent[p]]\n p = self.parent[p]\n return p\n def getsize(self):\n return self.count\n\n \nclass Solution:\n def countComponents(self, n: int, edges: List[List[int]]) -> int:\n graph = {}\n for i in range(n):\n graph[i] = []\n for u, v in edges:\n graph[u].append(v)\n graph[v].append(u)\n rslt = 0\n for i in range(n):\n if i in graph:\n self.bfs(i, graph)\n rslt += 1\n return rslt\n \n def dfs(self, i, graph):\n kids = graph[i]\n graph.pop(i)\n for kid in kids:\n if kid in graph:\n self.dfs(kid, graph)\n def bfs(self, i, graph):\n queue = collections.deque([i])\n while queue:\n temp = queue.popleft()\n if temp in graph:\n for kid in graph[temp]:\n queue.append(kid)\n graph.pop(temp)\n" }, { "alpha_fraction": 0.4309816062450409, "alphanum_fraction": 0.45858895778656006, "avg_line_length": 35.22222137451172, "blob_id": "f9d208dc245772b21468d3ca212a38d40dea24a8", "content_id": "c4710d4fb8b6e059eeed0edb229cadddbe3fac8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 55, "num_lines": 18, "path": "/lc969_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pancakeSort(self, arr: List[int]) -> List[int]:\n s_arr, rslt, n = sorted(arr), [], len(arr)\n for i in range(n-1, 0, -1):\n idx = arr.index(s_arr[i])\n arr[:idx+1] = arr[:idx+1][::-1]\n arr[:i+1] = arr[:i+1][::-1]\n rslt.extend([idx+1, i+1])\n return rslt\n\n def pancakeSort(self, arr: List[int]) -> List[int]:\n n, rslt = len(arr), []\n for nmax in range(n, 1, -1):\n idx = arr.index(nmax)\n #arr = arr[nmax-1:idx:-1] + arr[:idx+1]\n arr = arr[:idx:-1] + arr[:idx]\n rslt.extend([idx+1, nmax])\n return rslt\n" }, { "alpha_fraction": 0.3892405033111572, "alphanum_fraction": 0.4177215099334717, "avg_line_length": 27.727272033691406, "blob_id": "3f321883a7b9da3e19dd289598a3d2abe68c238d", "content_id": "00080a768fa68fb671ac89fc35a8de4148113104", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/lc119_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def getRow(self, rowIndex: int) -> List[int]:\n if rowIndex == 0:\n return [1]\n dp = [1]\n for j in range(1, rowIndex+1):\n temp = [1]*(j+1)\n for i in range(1, j):\n temp[i] = dp[i-1] + dp[i]\n dp = temp\n return dp\n" }, { "alpha_fraction": 0.5128834247589111, "alphanum_fraction": 0.5490797758102417, "avg_line_length": 36.022727966308594, "blob_id": "521e06ab1e9fc44e945c33b5e006273413555274", "content_id": "522c582990e8c32cd64916c236e48a4ea09cd20e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 118, "num_lines": 44, "path": "/lc468_string.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def validIPAddress(self, IP: str) -> str:\n # check IPv4 or IPv6\n if IP.count(\".\") == 3:\n # IPv4 address validation\n return \"IPv4\" if self.checkIPv4(IP) else \"Neither\"\n elif IP.count(\":\") == 7:\n # IPv6 address validation\n return \"IPv6\" if self.checkIPv6(IP) else \"Neither\"\n else:\n return \"Neither\"\n\n def checkIPv4(self, IP):\n tokens = IP.split(\".\")\n for token in tokens:\n if not token.isdigit() or len(token) != len(str(int(token))) or int(token) > 255:\n return False\n return True\n\n def checkIPv6(self, IP):\n tokens = IP.split(\":\")\n for token in tokens:\n if len(token) <1 or len(token) > 4 or any(x in token for x in \"ghijklmnopqrstuvwxyzGHIJKLMNOPQRSTUVWXYZ\"):\n return False\n return True\n\nfrom ipaddress import ip_address, IPv6Address\nclass Solution:\n def validIPAddress(self, IP: str) -> str:\n try:\n return \"IPv6\" if type(ip_address(IP)) is IPv6Address else \"IPv4\"\n except ValueError:\n return \"Neither\"\n\nimport re\nclass Solution:\n def validIPAddress(self, IP: str) -> str:\n chunk_IPv4 = r'([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'\n patten_IPv4 = re.compile(r'^(' + chunk_IPv4 + r'\\.){3}' + chunk_IPv4 + r'$')\n chunk_IPv6 = r'([0-9a-fA-F]{1,4})'\n patten_IPv6 = re.compile(r'^(' + chunk_IPv6 + r'\\:){7}' + chunk_IPv6 + r'$')\n if patten_IPv4.match(IP):\n return \"IPv4\"\n return \"IPv6\" if patten_IPv6.match(IP) else \"Neither\" \n" }, { "alpha_fraction": 0.41897234320640564, "alphanum_fraction": 0.44071146845817566, "avg_line_length": 35.14285659790039, "blob_id": "26d9b4f04981fe24298f11ad628f150f5ee61701", "content_id": "6f26d71efbf64a072d2439ca4104be1d517d511d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 506, "license_type": "no_license", "max_line_length": 77, "num_lines": 14, "path": "/lc1358_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numberOfSubstrings(self, s: str) -> int:\n left, rslt, count , count_dict= 0, 0, 0, collections.defaultdict(int)\n for right, c in enumerate(s):\n if count_dict[c] == 0:\n count += 1\n count_dict[c] += 1\n while count == 3:\n count_dict[s[left]] -= 1\n if count_dict[s[left]] == 0:\n count -= 1\n left += 1\n rslt += len(s) - right\n return rslt\n" }, { "alpha_fraction": 0.5182482004165649, "alphanum_fraction": 0.5456204414367676, "avg_line_length": 48.818180084228516, "blob_id": "f59368fb2826cc3338a3d9db76107245b34722bd", "content_id": "58c17a6f9579c22ff27474a157143e5be1cd73a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 548, "license_type": "no_license", "max_line_length": 94, "num_lines": 11, "path": "/lc1499_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findMaxValueOfEquation(self, points: List[List[int]], k: int) -> int:\n dque, rslt = collections.deque(), -float(\"inf\")\n for idx, point in enumerate(points):\n while dque and point[0] - points[dque[0]][0] > k:\n dque.popleft()\n if dque: rslt = max(rslt, points[dque[0]][1]-points[dque[0]][0]+point[1]+point[0])\n while dque and points[dque[-1]][1]-points[dque[-1]][0] <= point[1]-point[0]:\n dque.pop()\n dque.append(idx)\n return rslt\n" }, { "alpha_fraction": 0.3621908128261566, "alphanum_fraction": 0.3621908128261566, "avg_line_length": 30.44444465637207, "blob_id": "f76057e9acedf8a61e879e7b7d8278262059fd6a", "content_id": "fd2da11de6026c462fe08016b20a856fabd2dfcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/lc1087_string.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def expand(self, S: str) -> List[str]:\n rslt, curr, append = [\"\"], [], False\n for c in S:\n if c == \",\": continue\n if c == \"{\": append = True\n elif c == \"}\":\n append = False\n temp = []\n while curr:\n t = curr.pop()\n temp += [x+t for x in rslt]\n rslt = temp\n elif append:\n curr.append(c)\n else:\n rslt = [x+c for x in rslt]\n return sorted(rslt)\n" }, { "alpha_fraction": 0.38630378246307373, "alphanum_fraction": 0.39859527349472046, "avg_line_length": 34.59375, "blob_id": "d106af9da7c7eee262241ce73113f49a1c674183", "content_id": "a941d07ac06538166616d1847f780a864ff070f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1139, "license_type": "no_license", "max_line_length": 99, "num_lines": 32, "path": "/lc726_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countOfAtoms(self, expression: str) -> List[str]:\n stk, curr, atom, num = [], [], \"\", \"\"\n for c in expression+\")\":\n if c in \"1234567890\":\n num += c\n elif c in \"abcdefghijklmnopqrstuvwxyz\":\n atom += c\n elif atom:\n curr.append((atom, int(num) if num else 1))\n atom, num = \"\", \"\"\n elif num:\n t = int(num) if num else 1\n num = \"\"\n if stk:\n temp = stk.pop()\n curr = [(x, y*t) for (x, y) in temp]\n curr = curr+stk.pop() if stk else curr\n if c in \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\":\n atom = c\n if c == \")\" and curr:\n stk.append(curr)\n curr = []\n elif c == \"(\":\n stk.append(curr)\n curr = []\n rslt = {}\n for t in stk:\n for x,y in t:\n rslt[x] = rslt.get(x, 0)+y\n\n return \"\".join(key+str(rslt[key]) if rslt[key] > 1 else key for key in sorted(rslt.keys()))\n" }, { "alpha_fraction": 0.41883766651153564, "alphanum_fraction": 0.4328657388687134, "avg_line_length": 32.266666412353516, "blob_id": "a894527ff29ac22f40a59dc5b9023c1df3760d06", "content_id": "79efa2d2f19f0f6c56898467a65d67ee75fbbeaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/lc259_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def threeSumSmaller(self, nums: List[int], target: int) -> int:\n nums.sort()\n rslt = 0\n for left, num in enumerate(nums[:-2]):\n if num*3 >= target:\n return rslt\n mid, right = left+1, len(nums)-1\n while mid < right:\n if nums[mid]+nums[right]+num < target:\n rslt += right-mid\n mid += 1\n else:\n right -= 1\n return rslt\n" }, { "alpha_fraction": 0.4730134904384613, "alphanum_fraction": 0.48875561356544495, "avg_line_length": 35.054054260253906, "blob_id": "a67c8ff5bfb73d44ead654fe42a17e0c275204b8", "content_id": "0a33b797ce6c99d357058ae5d2596868688a4f30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 62, "num_lines": 37, "path": "/lc1696_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n dque, rslt, dp = collections.deque(), 0, [0]*len(nums)\n for idx, num in enumerate(nums):\n while dque and idx-dque[0] > k:\n dque.popleft()\n dp[idx] = num if idx == 0 else dp[dque[0]]+num\n while dque and dp[dque[-1]] <= dp[idx]:\n dque.pop()\n dque.append(idx)\n return dp[-1]\n\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n dque = collections.deque()\n for idx, num in enumerate(nums):\n if idx == 0: dque.append(num)\n else:\n dque.append(dque[0]+num)\n while len(dque) > k:\n dque.popleft()\n while dque and dque[0] < dque[-1]:\n dque.popleft()\n return dque[-1]\n\nclass Solution:\n def maxResult(self, nums: List[int], k: int) -> int:\n rslt, dque = 0, collections.deque()\n for idx, num in enumerate(nums):\n if idx == 0: dque.append((idx, num))\n while dque and idx - dque[0][0] > k:\n dque.popleft()\n rslt = dque[0][1]+num if idx != 0 else num\n while dque and dque[-1][1] <= rslt:\n dque.pop()\n dque.append((idx, rslt))\n return rslt\n" }, { "alpha_fraction": 0.43699732422828674, "alphanum_fraction": 0.445040225982666, "avg_line_length": 30.08333396911621, "blob_id": "cc73ffb88dae352885ef0319cb7f2133dc1f53fe", "content_id": "bd19da8eb6073cf67d9a53348064c2b19e225be4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/lc77_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n rslt = []\n def backtracking(temp, i):\n if len(temp) == k:\n rslt.append(temp)\n return\n if i == n: return\n for t in range(i, n):\n backtracking(temp+[t+1], t+1)\n backtracking([], 0)\n return rslt\n" }, { "alpha_fraction": 0.44994375109672546, "alphanum_fraction": 0.46681663393974304, "avg_line_length": 36.04166793823242, "blob_id": "95eb18ebf4c6b4f13cf895e6486c2fc64146d838", "content_id": "4a60281aea880aecfff44fff5b820c1925b56219", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "no_license", "max_line_length": 75, "num_lines": 24, "path": "/lc1345_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minJumps(self, arr: List[int]) -> int:\n valmap, l = collections.defaultdict(list), len(arr)\n if l == 1: return 0\n if arr[0] == arr[l-1]: return 1\n\n for i, num in enumerate(arr):\n valmap[num].append(i)\n dque, visited, visitednum = collections.deque([(0, 0)]), {0}, set()\n while dque:\n jump, idx = dque.popleft()\n if idx == l-1:\n return jump\n for i in [idx+1, idx-1]:\n if i not in visited and 0<= i < l:\n dque.append((jump+1, i))\n visited.add(i)\n if arr[idx] in visitednum: continue\n visitednum.add(arr[idx])\n for i in valmap[arr[idx]]:\n if i not in visited:\n dque.append((jump+1, i))\n visited.add(i)\n return len(arr)-1\n" }, { "alpha_fraction": 0.475452184677124, "alphanum_fraction": 0.48578810691833496, "avg_line_length": 47.375, "blob_id": "fa3a1a68d767e52f0934e560bc33577a44a7b20a", "content_id": "bafcb68fe427b8fcf97524897f7dcb096706d3f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 774, "license_type": "no_license", "max_line_length": 83, "num_lines": 16, "path": "/lc1439_dijkstra.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def kthSmallest(self, mat: List[List[int]], k: int) -> int:\n # Dijkstra: node is labeled by the row index sequences\n nrow, ncol = len(mat), len(mat[0])\n visited = {(0,)*nrow}\n heap = [(sum(row[0] for row in mat), (0,)*nrow)]\n for i in range(k):\n cur_val, cur_node = heapq.heappop(heap)\n for j in range(nrow):\n if cur_node[j] + 1 < ncol:\n nxt_val = cur_val - mat[j][cur_node[j]] + mat[j][cur_node[j]+1]\n nxt_node = cur_node[:j]+(cur_node[j]+1, )+ cur_node[j+1:]\n if nxt_node not in visited:\n visited.add(nxt_node)\n heapq.heappush(heap, (nxt_val, nxt_node))\n return cur_val\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.4764957129955292, "avg_line_length": 35, "blob_id": "cf51afd26177015c18c70d05fbca08f764fe2272", "content_id": "8764c5ea196ca6b796c01edf305a346fa94071b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 60, "num_lines": 13, "path": "/lc1658_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minOperations(self, nums: List[int], x: int) -> int:\n total, left, rslt = sum(nums), 0, len(nums)+1\n if total < x:\n return -1\n for right, num in enumerate(nums):\n total -= num\n while total < x:\n total += nums[left]\n left += 1\n if total == x:\n rslt = min(rslt, len(nums)-right-1+left)\n return rslt if rslt < len(nums)+1 else -1\n" }, { "alpha_fraction": 0.42603549361228943, "alphanum_fraction": 0.43589743971824646, "avg_line_length": 27.16666603088379, "blob_id": "7ef605cc4a184fba236094c908e1fb219ae91009", "content_id": "434874b5f9ccf763c2df20f83d90b2535d65ea88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "no_license", "max_line_length": 45, "num_lines": 18, "path": "/lc1025_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def divisorGame(self, N: int) -> bool:\n memo = {}\n def dfs(n):\n if n in memo: return memo[n]\n if n == 1: return False\n rslt = False\n for i in range(1, n):\n if n%i == 0 and not dfs(n-i):\n memo[n] = True\n return True\n memo[n] = False\n return False\n return dfs(N)\n\nclass Solution:\n def divisorGame(self, N: int) -> bool:\n return N % 2 == 0\n" }, { "alpha_fraction": 0.4937993288040161, "alphanum_fraction": 0.5039458870887756, "avg_line_length": 45.68421173095703, "blob_id": "1fc0ddf09e93c7e15122ac6234ae3b57e1b053a5", "content_id": "bbdf675dcc1d9e8550565a79097142fd28b68530", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 887, "license_type": "no_license", "max_line_length": 101, "num_lines": 19, "path": "/lc787_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, K: int) -> int:\n graph = collections.defaultdict(list)\n for start, end, w in flights:\n graph[start].append((end, w))\n heap, visitedD, visitedS = [(0, 0, src)], [float(\"inf\")]*n, [float(\"inf\")]*n\n visitedD[src], visitedS[src] = 0, 0\n while heap:\n cost, step, pre = heapq.heappop(heap)\n if pre == dst: return cost\n if step == K+1: continue\n for curr, w in graph[pre]:\n if visitedD[curr] > cost + w:\n visitedD[curr] = cost + w\n visitedS[curr] = step+1\n heapq.heappush(heap, (cost+w, step+1, curr))\n elif step < visitedS[curr]:\n heapq.heappush(heap, (cost+w, step+1, curr))\n return -1\n" }, { "alpha_fraction": 0.45742905139923096, "alphanum_fraction": 0.46243739128112793, "avg_line_length": 34.235294342041016, "blob_id": "f000ad746b38b0527fde66813df6c9f00dc72df1", "content_id": "4b07ca2887cb5e68b5026aab414d1e3b57195ac0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 599, "license_type": "no_license", "max_line_length": 67, "num_lines": 17, "path": "/lc491_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findSubsequences(self, nums: List[int]) -> List[List[int]]:\n rslt = []\n def backtracking(stk, candidate):\n if len(stk) >= 2:\n rslt.append(stk)\n if not candidate:\n return\n seen = set()\n for i, cand in enumerate(candidate):\n if cand in seen:\n continue\n if not stk or stk[-1] <= candidate[i]:\n seen.add(cand)\n backtracking(stk+[cand], candidate[i+1:])\n backtracking([], nums)\n return rslt\n" }, { "alpha_fraction": 0.46986469626426697, "alphanum_fraction": 0.48216482996940613, "avg_line_length": 39.650001525878906, "blob_id": "7933c18bf0e9e0703aa34bdede01e7fda3121e10", "content_id": "e707314160aa5c770c1e3e21929d989ab253ac93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "no_license", "max_line_length": 84, "num_lines": 20, "path": "/lc444_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def sequenceReconstruction(self, org: List[int], seqs: List[List[int]]) -> bool:\n graph, degree = collections.defaultdict(list), collections.defaultdict(int)\n for seq in seqs:\n for i, x in enumerate(seq):\n if i != len(seq)-1:\n graph[x].append(seq[i+1])\n degree[seq[i+1]]+= 1\n degree[x] += 0\n dque = collections.deque([x for x in degree if degree[x] == 0])\n temp = []\n while dque:\n if len(dque) != 1: return False\n t = dque.popleft()\n temp.append(t)\n for end in graph[t]:\n degree[end] -= 1\n if degree[end] == 0:\n dque.append(end)\n return temp == org and sum(degree.values()) == 0\n" }, { "alpha_fraction": 0.37249666452407837, "alphanum_fraction": 0.3791722357273102, "avg_line_length": 33.04545593261719, "blob_id": "f70d4c22fcafc3973e85de8a414a816466996364", "content_id": "d636fff43b41a28703482d1e4b9099fc27847a42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "no_license", "max_line_length": 58, "num_lines": 22, "path": "/lc1087_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def expand(self, S: str) -> List[str]:\n rslt = []\n def backtracking(prefix, remain):\n if not remain:\n rslt.append(prefix)\n return\n if remain[0] == '{':\n temp, cans = 0, []\n for i, c in enumerate(remain):\n if c == '}':\n temp = i\n break\n if c in ('{', ','):\n continue\n cans.append(c)\n for can in cans:\n backtracking(prefix+can, remain[i+1:])\n else:\n backtracking(prefix+remain[0], remain[1:])\n backtracking(\"\", S)\n return sorted(rslt)\n" }, { "alpha_fraction": 0.4444444477558136, "alphanum_fraction": 0.4627285599708557, "avg_line_length": 31.31818199157715, "blob_id": "d5bdb83b176ec5415e24c37db0e58b8291a52b66", "content_id": "34fe1a12dfb1acdd1706152d51e63b3d79b581d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 71, "num_lines": 22, "path": "/lc477_bit.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def totalHammingDistance(self, nums: List[int]) -> int:\n if not nums: return 0\n bit_count, n, rslt = collections.defaultdict(int), len(nums), 0\n for num in nums:\n i = 0\n while num:\n if num & 1:\n bit_count[i] += 1\n num >>= 1\n i += 1\n for _ , val in bit_count.items():\n rslt += val*(n-val)\n return rslt\n\n def totalHammingDistance(self, nums: List[int]) -> int:\n if not nums: return 0\n n, rslt = len(nums), 0\n for bits in zip(*map(\"{:032b}\".format, nums)):\n c = bits.count(\"1\")\n rslt += c*(n-c)\n return rslt\n" }, { "alpha_fraction": 0.4378698170185089, "alphanum_fraction": 0.44378697872161865, "avg_line_length": 27.16666603088379, "blob_id": "ef051c0de96e3dbd5b10dc5376b58256b0cea9fa", "content_id": "7baa586da95a189e26f5d68fec8f39d0b8a2df52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/lc1063_stk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def validSubarrays(self, nums: List[int]) -> int:\n n = len(nums)\n stk = []\n rslt = 0\n for i in range(n):\n while stk and nums[i] < nums[stk[-1]]:\n rslt += i- stk.pop()\n stk.append(i)\n while stk:\n rslt += n-stk.pop()\n return rslt\n" }, { "alpha_fraction": 0.5455567836761475, "alphanum_fraction": 0.5500562191009521, "avg_line_length": 42.36585235595703, "blob_id": "c2c5d3f0a355c517fda788d02b3aad9c6e378b9b", "content_id": "91810e80d895ebf0d866ccc0717fb23633f35f4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1778, "license_type": "no_license", "max_line_length": 90, "num_lines": 41, "path": "/lc1373_bt.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxSumBST(self, root: TreeNode) -> int:\n self.rslt = 0\n def helper(root):\n if not root: return 0, 0, True, 0\n if not root.right and not root.left: return root.val, root.val, True, root.val\n maxRR, minLR, isBSTR, ssumR = helper(root.right)\n maxRL, minLL, isBSTL, ssumL = helper(root.left)\n temp, ss = False, max(ssumR, ssumL)\n if not root.left and isBSTR and minLR > root.val:\n temp, ss, minLL = True, ssumR + root.val, root.val\n if not root.right and isBSTL and maxRL < root.val:\n temp, ss, maxRR = True, ssumL+root.val, root.val\n if isBSTR and isBSTL and maxRL < root.val < minLR:\n temp, ss= True, ssumR+ssumL+root.val\n self.rslt = max(self.rslt, ss)\n return maxRR, minLL, temp, ss\n _, _, _, rslt = helper(root)\n return self.rslt\n\nclass Solution:\n def maxSumBST(self, root: TreeNode) -> int:\n self.rslt = 0\n def helper(root):\n if not root: return -float(\"inf\"), float(\"inf\"), True, 0\n maxR, minR, isBSTR, sumR = helper(root.right)\n maxL, minL, isBSTL, sumL = helper(root.left)\n isBST, total= False, 0\n if isBSTR and isBSTL and minR > root.val > maxL:\n isBST = True\n total = sumR+sumL+root.val\n self.rslt = max(self.rslt, sumR+sumL+root.val)\n return max(maxR, root.val), min(minL, root.val), isBST, total\n helper(root)\n return self.rslt\n" }, { "alpha_fraction": 0.39137381315231323, "alphanum_fraction": 0.420127809047699, "avg_line_length": 31.473684310913086, "blob_id": "7cd42b2afef62ddee273c7cd6f1aa7d61fe39a8b", "content_id": "45c57ca03000076a7987eaf1e95b9766716ac845", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 50, "num_lines": 19, "path": "/lc678_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def checkValidString(self, s: str) -> bool:\n countl = 0\n for c in s:\n countl += 1 if c in (\"(\", \"*\") else -1\n if countl < 0: return False\n countr = 0\n for c in s[::-1]:\n countr += 1 if c in (\")\", \"*\") else -1\n if countr < 0: return False\n return True\n def checkValidString(self, s:str) -> bool:\n low, hi= 0, 0\n for c in s:\n low += 1 if c == '(' else -1\n hi += 1 if c in ('(', '*') else -1\n low = max(0, low)\n if hi < 0: return False\n return low == 0\n \n" }, { "alpha_fraction": 0.3991416394710541, "alphanum_fraction": 0.4177396297454834, "avg_line_length": 30.772727966308594, "blob_id": "9ebe263cadbbbacd4b3e15731d6bcd7d42872166", "content_id": "8c3da2a6fa91b38d8d8240445d06aab80ce815cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 699, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/lc975_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n n = len(arr)\n nxt_h, nxt_l = [0]*n, [0]*n\n stack = []\n for i in sorted(range(n), key = lambda x: (arr[x], x)):\n while stack and stack[-1] < i:\n nxt_h[stack.pop()] = i\n stack.append(i)\n\n stack = []\n for i in sorted(range(n), key = lambda x: (-arr[x], x)):\n while stack and stack[-1] < i:\n nxt_l[stack.pop()] = i\n stack.append(i)\n\n nh, nl = [0]*n, [0]*n\n nh[-1], nl[-1] = 1, 1\n for j in range(n-2, -1, -1):\n nh[j] = nl[nxt_h[j]]\n nl[j] = nh[nxt_l[j]]\n return sum(nh)\n" }, { "alpha_fraction": 0.5145413875579834, "alphanum_fraction": 0.5190156698226929, "avg_line_length": 36.25, "blob_id": "80f93d2630130578c0ed3053e9fbedc5f0d25779", "content_id": "53392511f302024681ab3fe850cc1402622a0964", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 98, "num_lines": 12, "path": "/lc1376_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:\n mmap = collections.defaultdict(list)\n for i, m in enumerate(manager):\n if m != -1:\n mmap[m].append(i)\n def dfs(mid):\n rslt = 0\n for sub in mmap[mid]:\n rslt = max(rslt, informTime[mid] + dfs(sub))\n return rslt\n return dfs(headID)\n" }, { "alpha_fraction": 0.44329896569252014, "alphanum_fraction": 0.4639175236225128, "avg_line_length": 31.33333396911621, "blob_id": "9c10534f1eecf2817e7926f8738a82ed59b325b5", "content_id": "210c64df56a8d41f4dfbb34fd5f3d743eee5a422", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/lc118_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def generate(self, numRows: int) -> List[List[int]]:\n rslt = []\n for i in range(numRows):\n temp = [1]*(i+1)\n for j in range(1, i):\n temp[j] = rslt[i-1][j-1]+rslt[i-1][j]\n rslt.append(temp)\n return rslt\n" }, { "alpha_fraction": 0.4553191363811493, "alphanum_fraction": 0.48085105419158936, "avg_line_length": 34.153846740722656, "blob_id": "7a6489120bca3f6406ea5ac4cc35123da9c289ab", "content_id": "4d153c189aea88106e380a8cbfa28a89880abd84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 82, "num_lines": 13, "path": "/lc496_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n if not nums2: return [-1]*len(nums1)\n keeper, stk = {}, [nums2[0]]\n for num in nums2[1:]:\n while stk and num > stk[-1]:\n temp = stk.pop()\n keeper[temp] = num\n stk.append(num)\n rslt = []\n for num in nums1:\n rslt.append(keeper.get(num, -1))\n return rslt\n \n" }, { "alpha_fraction": 0.4484732747077942, "alphanum_fraction": 0.46310433745384216, "avg_line_length": 34.325843811035156, "blob_id": "a660e6a7bf3086da821b352cde0564d2ff230b1b", "content_id": "0c2f53540ab07c220972f4f93d42c87f7f673a32", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3144, "license_type": "no_license", "max_line_length": 81, "num_lines": 89, "path": "/lc411_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minAbbreviation(self, target: str, dictionary: List[str]) -> str:\n # get all the abbr of target stored by length\n self.target_rslt = collections.defaultdict(list)\n self.backtracking(0, [], target)\n for i in range(1, len(target)):\n for path in self.target_rslt[i]:\n for word in dictionary:\n if self.check_abbr(path, word):\n break\n else:\n return \"\".join(path)\n return target\n\n def backtracking(self, i, path, target):\n '''\n generate abbreviations for target word\n '''\n if i == len(target):\n self.target_rslt[len(path)].append(path)\n else:\n if path and path[-1].isdigit():\n self.backtracking(i+1, path[:-1]+ [str(int(path[-1])+1)], target)\n else:\n self.backtracking(i+1, path+[\"1\"], target)\n self.backtracking(i+1, path+[target[i]], target)\n\n def check_abbr(self, path, word):\n '''\n check if path is word's abbrevation\n '''\n cw = 0\n for ch in path:\n if cw >= len(word):\n return False\n if not ch.isdigit():\n if ch != word[cw]: return False\n cw += 1\n else:\n cw += int(ch)\n return cw == len(word)\n\nclass Solution:\n def minAbbreviation(self, target: str, dictionary: List[str]) -> str:\n # get all the abbr of target stored by length\n self.target_rslt, n = collections.defaultdict(list), len(target)\n self.backtracking(0, 1, target, 0)\n for i in range(1, n):\n for abbr in self.target_rslt[i]:\n for word in dictionary:\n if self.check_abbr(abbr, target, word): break\n else:\n cnt, rslt = 0, \"\"\n for j in range(n-1, -1, -1):\n if abbr & 1:\n cnts = \"\" if cnt == 0 else str(cnt)\n rslt, cnt = target[j]+cnts+rslt, 0\n else: cnt += 1\n abbr >>= 1\n if cnt: rslt = str(cnt)+rslt\n return rslt\n return target\n\n def backtracking(self, i, abbr, target, l):\n '''\n generate abbreviations for target word use bitmask\n '''\n if i == len(target):\n self.target_rslt[l].append(abbr)\n else:\n if abbr&1 == 0:\n self.backtracking(i+1, abbr << 1, target, l)\n else:\n self.backtracking(i+1, abbr << 1, target, l+1)\n self.backtracking(i+1, (abbr << 1)+1, target, l+1)\n\n def check_abbr(self, abbr, target, word):\n '''\n check if path is word's abbrevation\n '''\n cw, n = len(word)-1, len(target)\n for i in range(n-1, -1, -1):\n if cw < 0:\n return False\n if abbr & 1 == 1 and word[cw] != target[i]:\n return False\n cw -= 1\n abbr >>= 1\n return cw == -1\n" }, { "alpha_fraction": 0.400778204202652, "alphanum_fraction": 0.43968871235847473, "avg_line_length": 31.125, "blob_id": "b8741756ca3a4ff25d655c75b3c5208e20c1006a", "content_id": "db01945aeda47f0efda923c4789d8945d26a20b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 514, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/lc1215_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countSteppingNumbers(self, low: int, high: int) -> List[int]:\n rslt = []\n def backtracking(i):\n if i >= low and i <= high:\n rslt.append(i)\n if i > high:\n return\n if i != 0 and i%10 < 9:\n backtracking(i*10 + i%10+1)\n if i != 0 and i%10 > 0:\n backtracking(i*10 + i%10-1)\n return\n for j in range(10):\n backtracking(j)\n return sorted(rslt)\n" }, { "alpha_fraction": 0.47252747416496277, "alphanum_fraction": 0.4813186824321747, "avg_line_length": 34, "blob_id": "471d005aa8357da785577fb71ef1191b4c4386a1", "content_id": "c09417c3ba27546adfd06cc13d5c85e96be53d6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 83, "num_lines": 13, "path": "/lc946_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:\n popidx, stk = 0, []\n for num in pushed:\n mark = True\n if num == popped[popidx]:\n mark = False\n popidx +=1\n while stk and popped[popidx] == stk[-1]:\n stk.pop()\n popidx += 1\n if mark: stk.append(num)\n return False if stk else True\n" }, { "alpha_fraction": 0.5314685106277466, "alphanum_fraction": 0.5314685106277466, "avg_line_length": 34.75, "blob_id": "db3cd830ac64275eb67ce45905eb7d33eb417964", "content_id": "efe690d7fc54e62448564847cb7a7dbae387961d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 83, "num_lines": 12, "path": "/lc582_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def killProcess(self, pid: List[int], ppid: List[int], kill: int) -> List[int]:\n mmap = collections.defaultdict(list)\n for child, parent in zip(pid, ppid):\n mmap[parent].append(child)\n rslt, stk = [], [kill]\n while stk:\n temp = stk.pop()\n rslt.append(temp)\n for child in mmap[temp]:\n stk.append(child)\n return rslt\n" }, { "alpha_fraction": 0.5215845704078674, "alphanum_fraction": 0.5256475210189819, "avg_line_length": 32.94827651977539, "blob_id": "8c715df7947919b6248fe9d8bc77eb51b257960a", "content_id": "726653e9fb00c94a1d9b543b631da93030ff881f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1969, "license_type": "no_license", "max_line_length": 85, "num_lines": 58, "path": "/lc307_segtree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, start, end):\n self.total = 0\n self.start, self.end = start, end\n self.left, self.right = None, None\n\nclass SegTree:\n def __init__(self, nums):\n self.nums = nums\n self.root = self.create_tree(0, len(self.nums)-1)\n\n def create_tree(self, start, end):\n if start == end:\n rslt = Node(start, end)\n rslt.total = self.nums[start]\n return rslt\n mid = (start + end)//2\n rslt = Node(start, end)\n rslt.left = self.create_tree(start, mid)\n rslt.right = self.create_tree(mid+1, end)\n rslt.total = rslt.left.total + rslt.right.total\n return rslt\n\n def update(self, i, val):\n def helper(root, i, val):\n if root.left == root.right:\n root.total = val\n return val\n mid = (root.start + root.end)//2\n if i <= mid:\n helper(root.left, i, val)\n else:\n helper(root.right, i, val)\n root.total = root.left.total + root.right.total\n return root.total\n helper(self.root, i, val)\n def sum_range(self, start, end):\n def helper(root, start, end):\n if root.start == start and root.end == end:\n return root.total\n mid = (root.start + root.end)//2\n if end <= mid:\n return helper(root.left, start, end)\n elif start > mid:\n return helper(root.right, start, end)\n else:\n return helper(root.left, start, mid) + helper(root.right, mid+1, end)\n return helper(self.root, start, end)\n\nclass NumArray:\n def __init__(self, nums: List[int]):\n self.segtree = SegTree(nums)\n\n def update(self, index: int, val: int) -> None:\n self.segtree.update(index, val)\n\n def sumRange(self, left: int, right: int) -> int:\n return self.segtree.sum_range(left, right)\n" }, { "alpha_fraction": 0.4947267472743988, "alphanum_fraction": 0.5100671052932739, "avg_line_length": 44.34782791137695, "blob_id": "4161260fe2a181fc35790239b61dace0e1d5c325", "content_id": "ef8a7e12f99d01a1d6bf1003ab106ae7a32dd09d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1043, "license_type": "no_license", "max_line_length": 100, "num_lines": 23, "path": "/lc1272_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:\n rslt = []\n for x, y in intervals:\n if x < toBeRemoved[0] and y <= toBeRemoved[1]:\n rslt.append([x, min(toBeRemoved[0], y)])\n elif x >= toBeRemoved[0] and y > toBeRemoved[1]:\n rslt.append([max(x, toBeRemoved[1]), y])\n elif x < toBeRemoved[0] and y > toBeRemoved[1]:\n rslt.append([x, toBeRemoved[0]])\n rslt.append([toBeRemoved[1], y])\n return rslt\n def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:\n rslt = []\n for x, y in intervals:\n if y < toBeRemoved[0] or x > toBeRemoved[1]:\n rslt.append([x, y])\n else:\n if x < toBeRemoved[0]:\n rslt.append([x, toBeRemoved[0]])\n if y > toBeRemoved[1]:\n rslt.append([toBeRemoved[1], y])\n return rslt\n" }, { "alpha_fraction": 0.4474761188030243, "alphanum_fraction": 0.46384719014167786, "avg_line_length": 37.578948974609375, "blob_id": "f8d3c893f0900f2e720e7e5a1128374ffe01478e", "content_id": "2981f62fe2eadaf24e41b047eaf8b5eecaba26a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license_type": "no_license", "max_line_length": 70, "num_lines": 19, "path": "/lc164_bucket.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maximumGap(self, nums: List[int]) -> int:\n n = len(nums)\n left, right = min(nums), max(nums)\n if n < 2 or left == right: return 0\n s_bkts = (right - left) //(n-1) or 1\n n_bkts = (right-left)//s_bkts + 1\n bkts = [[float(\"inf\"), -float(\"inf\")] for _ in range(n_bkts)]\n for num in nums:\n idx = (num-left)//s_bkts\n bkts[idx] = min(num, bkts[idx][0]), max(num, bkts[idx][1])\n last, rslt = None, 0\n for i in range(n_bkts):\n if not last:\n last = bkts[i][1]\n elif bkts[i][0] < float(\"inf\"):\n rslt = max(rslt, bkts[i][0]-last)\n last = bkts[i][1]\n return rslt\n" }, { "alpha_fraction": 0.46292585134506226, "alphanum_fraction": 0.4749498963356018, "avg_line_length": 32.266666412353516, "blob_id": "c697d3be74ff2548ecbe9f82da28f28036f13804", "content_id": "1bf65d49a1ae92bceef317f92f8bfcf27b47a55d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 57, "num_lines": 15, "path": "/lc1079_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numTilePossibilities(self, tiles: str) -> int:\n self.rslt = 0\n temp = ''.join(sorted(list(tiles)))\n def backtracking(pref, cand):\n self.rslt +=1\n if not cand:\n return\n for i, c in enumerate(cand):\n if i !=0 and c == cand[i-1]:\n continue\n backtracking(pref+c, cand[:i]+cand[i+1:])\n return\n backtracking('', temp)\n return self.rslt-1\n" }, { "alpha_fraction": 0.5156826376914978, "alphanum_fraction": 0.5221402049064636, "avg_line_length": 39.14814758300781, "blob_id": "5a2ca47802f699acafd41d876f37d91e9b7d8edb", "content_id": "52a651a0f6e7c2a3197ae60f83a7a18804e45439", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 78, "num_lines": 27, "path": "/lc106_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n nodemap = {val:idx for idx, val in enumerate(inorder)}\n stk, head = [], None\n for node in postorder[::-1]:\n if not head:\n head = TreeNode(node)\n stk.append(head)\n else:\n temp = TreeNode(node)\n if nodemap[node] > nodemap[stk[-1].val]:\n stk[-1].right = temp\n else:\n while stk and nodemap[stk[-1].val] > nodemap[node]:\n last = stk.pop()\n last.left = temp\n stk.append(temp)\n return head\n\nclass Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n if not inorder or not postorder: return None\n root = TreeNode(postorder[-1])\n idx = inorder.index(root.val)\n root.right = self.buildTree(inorder[idx+1:], postorder[idx:-1])\n root.left = self.buildTree(inorder[:idx], postorder[:idx])\n return root\n" }, { "alpha_fraction": 0.4265822768211365, "alphanum_fraction": 0.4430379867553711, "avg_line_length": 34.90909194946289, "blob_id": "9a6fa01d453ee8898451c27746d240c1763af7e5", "content_id": "745d7ab5acbdec60366445fd783cfc190bad6998", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1580, "license_type": "no_license", "max_line_length": 74, "num_lines": 44, "path": "/lc130_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def solve(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n if not board or not board[0]: return\n r, c= len(board), len(board[0])\n uf, edge = UF(r*c+1), r*c\n for i in range(r):\n if board[i][0] == \"O\": uf.union(i*c, edge)\n if board[i][c-1] == \"O\": uf.union(i*c + c-1, edge)\n for j in range(c):\n if board[0][j] == \"O\": uf.union(j, edge)\n if board[r-1][j] == \"O\": uf.union(c*(r-1)+j, edge)\n for i in range(1, r-1):\n for j in range(1, c-1):\n if board[i][j] == 'O':\n for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n if board[i+x][j+y] == \"O\":\n uf.union(i*c+j, (i+x)*c+j+y)\n for i in range(1, r-1):\n for j in range(1, c-1):\n if board[i][j] == \"O\" and uf.find(i*c+j) != uf.find(edge):\n board[i][j] = 'X'\n\n\nclass UF:\n def __init__(self, n):\n self.parent = list(range(n))\n self.size = [1]*n\n def union(self, p, q):\n rootp = self.find(p)\n rootq = self.find(q)\n if rootp == rootq: return\n if self.size[rootp] > self.size[rootq]:\n rootp, rootq = rootq, rootp\n self.parent[rootp] = rootq\n self.size[rootq] += self.size[rootp]\n\n def find(self, x):\n while self.parent[x] != x:\n self.parent[x] = self.parent[self.parent[x]]\n x = self.parent[x]\n return x\n" }, { "alpha_fraction": 0.4560000002384186, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 30.25, "blob_id": "c2c9bb7ac09ba36ffd5a4a03f9c2001dda00b436", "content_id": "8c70ecbf273f30c06da3a8810632bd3a1d25b593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 375, "license_type": "no_license", "max_line_length": 61, "num_lines": 12, "path": "/lc325_twopoiner.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSubArrayLen(self, nums: List[int], k: int) -> int:\n holder = {0:-1}\n curr = 0\n rslt = 0\n for i, num in enumerate(nums):\n curr += num\n if curr - k in holder:\n rslt = max(rslt, i - holder[curr-k])\n if curr not in holder:\n holder[curr] = i\n return rslt\n" }, { "alpha_fraction": 0.4441041350364685, "alphanum_fraction": 0.4486983120441437, "avg_line_length": 37.411766052246094, "blob_id": "57068679ab9a051f356476fdcb13f345249ea858", "content_id": "06da429ee8eaeab49e6fe1512992088f22192e22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 65, "num_lines": 17, "path": "/lc785_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isBipartite(self, graph: List[List[int]]) -> bool:\n dque = collections.deque()\n visited, mark = {}, 0\n for i in range(len(graph)):\n if i not in visited:\n dque.append((i, mark))\n while dque:\n cur, mark = dque.popleft()\n mark = (mark+1)%2\n for post in graph[cur]:\n if post in visited and visited[post] != mark:\n return False\n elif post not in visited:\n visited[post] = mark\n dque.append((post, mark))\n return True\n" }, { "alpha_fraction": 0.4290465712547302, "alphanum_fraction": 0.4678492248058319, "avg_line_length": 25.52941131591797, "blob_id": "a9a8b865b53710cc4ac016ce0e26d268f6d1c885", "content_id": "18dc02cf126b853191d531906e52e0d0251a8a0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "no_license", "max_line_length": 68, "num_lines": 34, "path": "/lc445_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n temp1, temp2 = l1, l2\n while temp1 and temp2:\n temp1 = temp1.next\n temp2 = temp2.next\n if temp2:\n l1, l2 = l2, l1\n temp = temp1 if temp1 else temp2\n rslt = None\n\n while temp:\n rslt = ListNode(l1.val, rslt)\n l1 = l1.next\n temp = temp.next\n while l1:\n rslt = ListNode(l1.val + l2.val, rslt)\n l1 = l1.next\n l2 = l2.next\n\n carry, prev = 0, None\n\n while rslt:\n tempv = rslt.val + carry\n carry, tempv = tempv//10, tempv%10\n rslt.val = tempv\n temp = rslt.next\n rslt.next = prev\n prev = rslt\n rslt = temp\n\n if carry:\n prev = ListNode(carry, prev)\n return prev\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5088757276535034, "avg_line_length": 32.79999923706055, "blob_id": "210021f031fa08a8eaaf7b749108a11600224e89", "content_id": "b1acba2f5c5b79ecc155b59323648ed8d5313ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 54, "num_lines": 10, "path": "/lc3_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lengthOfLongestSubstring(self, s: str) -> int:\n if not s: return 0\n left, holder, rslt = -1, {}, 0\n for right, c in enumerate(s):\n if c in holder:\n left = max(holder[c], left)\n rslt = max(rslt, right-left)\n holder[c] = right\n return rslt\n" }, { "alpha_fraction": 0.5716981291770935, "alphanum_fraction": 0.5716981291770935, "avg_line_length": 36.85714340209961, "blob_id": "bc531b507b0e326b3a6225df021f8f74458359bb", "content_id": "00202e548d6af1cfb257b4287fbc4691019c1c5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 63, "num_lines": 14, "path": "/lc1485_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def copyRandomBinaryTree(self, root: 'Node') -> 'NodeCopy':\n if not root: return None\n constructed = {}\n def dfs(root):\n if not root: return None\n if root in constructed: return constructed[root]\n copyroot = NodeCopy(root.val)\n constructed[root] = copyroot\n copyroot.left = dfs(root.left)\n copyroot.right = dfs(root.right)\n copyroot.random = dfs(root.random)\n return copyroot\n return dfs(root)\n" }, { "alpha_fraction": 0.4059869050979614, "alphanum_fraction": 0.41253507137298584, "avg_line_length": 36.29069900512695, "blob_id": "5ff12983e63c320b9857f4a4bc6e344afcb017ec", "content_id": "b1a53ec2ea4cdb2d8a66e8accf64d8ea2135e83c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3207, "license_type": "no_license", "max_line_length": 101, "num_lines": 86, "path": "/lc212_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n # build trie\n trie = {}\n for word in words:\n curr = trie\n for ch in word:\n curr[ch] = curr.get(ch, {})\n curr = curr[ch]\n curr[\"end\"] = word\n nrow, ncol, rslt, visited = len(board), len(board[0]), set(), set()\n def backtracking(i, j, curr):\n if \"end\" in curr:\n rslt.add(curr[\"end\"])\n for x, y in [(i+1, j), (i, j+1), (i-1, j), (i, j-1)]:\n if 0 <= x < nrow and 0 <= y < ncol and board[x][y] in curr and (x, y) not in visited:\n visited.add((x, y))\n backtracking(x, y, curr[board[x][y]])\n visited.remove((x, y))\n for i in range(nrow):\n for j in range(ncol):\n if board[i][j] in trie:\n visited.add((i, j))\n backtracking(i, j, trie[board[i][j]])\n visited.remove((i, j))\n return rslt\n\n\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n # build trie\n trie = {}\n for word in words:\n curr = trie\n for ch in word:\n curr[ch] = curr.get(ch, {})\n curr = curr[ch]\n curr[\"end\"] = word\n nrow, ncol, rslt = len(board), len(board[0]), set()\n def backtracking(i, j, curr):\n if \"end\" in curr:\n rslt.add(curr[\"end\"])\n for x, y in [(i+1, j), (i, j+1), (i-1, j), (i, j-1)]:\n if 0 <= x < nrow and 0 <= y < ncol and board[x][y] in curr:\n ch = board[x][y]\n board[x][y] = \"\"\n backtracking(x, y, curr[ch])\n board[x][y] = ch\n for i in range(nrow):\n for j in range(ncol):\n if board[i][j] in trie:\n ch = board[i][j]\n board[i][j] = \"\"\n backtracking(i, j, trie[ch])\n board[i][j] = ch\n return rslt\n\nclass Solution:\n def findWords(self, board: List[List[str]], words: List[str]) -> List[str]:\n # build trie\n trie = {}\n for word in words:\n curr = trie\n for ch in word:\n curr[ch] = curr.get(ch, {})\n curr = curr[ch]\n curr[\"end\"] = word\n nrow, ncol, rslt = len(board), len(board[0]), set()\n def backtracking(i, j, parent):\n pch = board[i][j]\n curr = parent[pch]\n board[i][j] = \"\"\n if \"end\" in curr:\n rslt.add(curr[\"end\"])\n curr.pop(\"end\")\n for x, y in [(i+1, j), (i, j+1), (i-1, j), (i, j-1)]:\n if 0 <= x < nrow and 0 <= y < ncol and board[x][y] in curr:\n backtracking(x, y, curr)\n board[i][j] = pch\n if not curr:\n parent.pop(pch)\n for i in range(nrow):\n for j in range(ncol):\n if board[i][j] in trie:\n backtracking(i, j, trie)\n return rslt\n" }, { "alpha_fraction": 0.47415730357170105, "alphanum_fraction": 0.483146071434021, "avg_line_length": 43.5, "blob_id": "18ca799e219c4e712fa3cae596e86103ac4f21a0", "content_id": "fd3aa9782fd7953172f90d313ed73a5ef4e9bbf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 890, "license_type": "no_license", "max_line_length": 85, "num_lines": 20, "path": "/lc127_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:\n if not wordList or endWord not in wordList:\n return 0\n lword, word_map, visited = len(beginWord), defaultdict(list), {beginWord}\n queue = deque([(beginWord, 1)])\n for wrd in wordList:\n for i in range(lword):\n word_map[wrd[:i]+\"*\"+wrd[i+1:]].append(wrd)\n while queue:\n wrd, step = queue.popleft()\n for i in range(lword):\n for wrd_cand in word_map[wrd[:i]+\"*\"+wrd[i+1:]]:\n if wrd_cand == endWord:\n return step +1\n if wrd_cand not in visited:\n visited.add(wrd_cand)\n queue.append((wrd_cand, step+1))\n word_map[wrd[:i]+\"*\"+wrd[i+1:]] = []\n return 0\n" }, { "alpha_fraction": 0.4480234384536743, "alphanum_fraction": 0.4846266508102417, "avg_line_length": 47.78571319580078, "blob_id": "02bbf072c4fb7466c2729f5613fe100c8a9e5721", "content_id": "86299aa3d0ab5cce7659f5543b9b8b09172fad57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 92, "num_lines": 14, "path": "/lc1314_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:\n nrow, ncol = len(mat), len(mat[0])\n presum = [[0]*(ncol+1) for _ in range(nrow+1)]\n for i in range(nrow):\n for j in range(ncol):\n presum[i+1][j+1] = presum[i][j+1]+ presum[i+1][j] + mat[i][j] - presum[i][j]\n rslt = [[0]*ncol for _ in range(nrow)]\n for i in range(nrow):\n for j in range(ncol):\n r1, r2 = max(0, i-k), min(nrow, i+k+1)\n c1, c2 = max(0, j-k), min(ncol, j+k+1)\n rslt[i][j] = presum[r2][c2] - presum[r2][c1]-presum[r1][c2]+ presum[r1][c1]\n return rslt\n" }, { "alpha_fraction": 0.45151033997535706, "alphanum_fraction": 0.45627981424331665, "avg_line_length": 33.94444274902344, "blob_id": "fe01177fb70fdf9f8e0b21639444e36b0493cceb", "content_id": "191c29f6d56a8c3067059988cd9799f4adacaa16", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/lc698_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:\n nums.sort()\n target, rm = divmod(sum(nums), k)\n if rm or target < nums[-1]: return False\n def dfs():\n if not nums: return True\n right = nums.pop()\n for i, ttt in enumerate(tt_list):\n if ttt + right <= target:\n tt_list[i] += right\n if dfs(): return True\n tt_list[i] -= right\n if ttt == 0: break\n nums.append(right)\n return False\n tt_list = [0]*k\n return dfs()\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4559270441532135, "avg_line_length": 31.899999618530273, "blob_id": "9871198a9ddfac45279190dcc4c2cda6211264c7", "content_id": "1bd309aae5b90664ac6299cb0d25abe69000885a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 329, "license_type": "no_license", "max_line_length": 65, "num_lines": 10, "path": "/lc256_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minCost(self, costs: List[List[int]]) -> int:\n if not costs: return 0\n dp = costs[0]\n for i in range(1, len(costs)):\n temp = [0]*3\n for j in range(3):\n temp[j] = costs[i][j] + min(dp[(j+1)%3], dp[j-1])\n dp = temp\n return min(dp)\n" }, { "alpha_fraction": 0.4718792736530304, "alphanum_fraction": 0.4801097512245178, "avg_line_length": 35.45000076293945, "blob_id": "6a19767680525b61a22d57270940a58d881f154f", "content_id": "a68802e33e4b302a8582c9c02ebd33bb59fc2d34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 67, "num_lines": 20, "path": "/lc30_swind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# BK\nclass Solution:\n def findSubstring(self, s: str, words: List[str]) -> List[int]:\n wordmap = collections.Counter(words)\n n, m, l = len(words), len(words[0]), len(s)\n lsub = n*m\n if lsub == l and \"\".join(words) == s: return [0]\n rslt = []\n def backtracking(right, checked):\n if checked == lsub:\n rslt.append(right-lsub)\n elif right < l:\n temp = s[right:right+m]\n if temp in wordmap and wordmap[temp] > 0:\n wordmap[temp] -= 1\n backtracking(right+m, checked+m)\n wordmap[temp] += 1\n for i in range(l):\n backtracking(i, 0)\n return rslt\n" }, { "alpha_fraction": 0.4473067820072174, "alphanum_fraction": 0.4496487081050873, "avg_line_length": 37.818180084228516, "blob_id": "9ab606030f1a1b900eebf5efae344835e8f967c4", "content_id": "fc5a1f02e4facc376d1d1014c32a274335e1e750", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 91, "num_lines": 11, "path": "/lc1249_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minRemoveToMakeValid(self, s: str) -> str:\n stack = []\n for i, c in enumerate(s+'*'):\n if c == \"(\":\n stack.append(i)\n elif c == \")\":\n if stack and s[stack[-1]] == '(': stack.pop()\n else: stack.append(i)\n stack = set(stack)\n return \"\".join(c for i, c in enumerate(s) if c not in ['(', ')'] or i not in stack)\n" }, { "alpha_fraction": 0.44514501094818115, "alphanum_fraction": 0.4464060664176941, "avg_line_length": 23, "blob_id": "10b7c20e97ca5de963ebc4c3f5ca34f67f617b7e", "content_id": "bfd73b37c659111408ca676918d0d6ec91913354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 793, "license_type": "no_license", "max_line_length": 61, "num_lines": 33, "path": "/lc143_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reorderList(self, head: ListNode) -> None:\n \"\"\"\n Do not return anything, modify head in-place instead.\n \"\"\"\n s, f = head, head\n while f and f.next:\n s = s.next\n f = f.next.next\n\n prev, curr = None, s.next\n s.next = None\n while curr:\n temp = curr.next\n curr.next = prev\n prev = curr\n curr = temp\n\n a, b = head, prev\n while b:\n temp = a.next\n a.next = b\n a = temp\n\n temp = b.next\n b.next = a\n b = temp\n return \n" }, { "alpha_fraction": 0.34657835960388184, "alphanum_fraction": 0.3653421700000763, "avg_line_length": 44.25, "blob_id": "1b429e468134f49bf8c808f8dc5a5eec45e434bc", "content_id": "dfa4bbf6c8020f945fb6e1347d83d74f5f3b1649", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 115, "num_lines": 20, "path": "/lc200_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numIslands(self, grid: List[List[str]]) -> int:\n if not grid or not grid[0]: return 0\n n_row, n_col = len(grid), len(grid[0])\n queue, rslt = collections.deque(), 0\n for i in range(n_row):\n for j in range(n_col):\n if grid[i][j] == \"1\":\n grid[i][j] = None\n queue.append((i, j))\n while queue:\n curr_i, curr_j = queue.popleft()\n for x, y in [(-1, 0), (1, 0), (0, 1), (0, -1)]:\n t_x, t_y = curr_i+x, curr_j + y\n if t_x >= 0 and t_x < n_row and t_y >= 0 and t_y < n_col and grid[t_x][t_y] == \"1\":\n grid[t_x][t_y] = None\n queue.append((t_x, t_y))\n\n rslt += 1\n return rslt \n" }, { "alpha_fraction": 0.5074441432952881, "alphanum_fraction": 0.5124069452285767, "avg_line_length": 31.675676345825195, "blob_id": "f7644841b6b3379a8769cc7fc2b286298441475f", "content_id": "dd911e47f951163235bef0dcb4dc489258af3325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2418, "license_type": "no_license", "max_line_length": 96, "num_lines": 74, "path": "/lc432_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Block:\n def __init__(self, val = 0, left = None, right = None):\n self.val = val\n self.left = left\n self.right = right\n self.kids = set()\nclass AllOne:\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.sleft = Block()\n self.sright = Block(left = self.sleft)\n self.sleft.right = self.sright\n self.keyblock = {}\n def inc(self, key: str) -> None:\n \"\"\"\n Inserts a new key <Key> with value 1. Or increments an existing key by 1.\n \"\"\"\n preb = self.sleft\n if key in self.keyblock:\n preb = self.keyblock[key]\n preb.kids.remove(key)\n val = preb.val + 1\n if preb.right.val == val:\n curb = preb.right\n else:\n curb = Block(val = val, left = preb, right = preb.right)\n preb.right.left, preb.right = curb, curb\n curb.kids.add(key)\n self.keyblock[key] = curb\n if not preb.kids and preb.val != 0:\n preb.left.right, preb.right.left = preb.right, preb.left\n preb.left, preb.right = None, None\n\n def dec(self, key: str) -> None:\n \"\"\"\n Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.\n \"\"\"\n preb = self.keyblock[key]\n preb.kids.remove(key)\n val = preb.val - 1\n if val == 0:\n curb = self.sleft\n elif preb.left.val == val:\n curb = preb.left\n else:\n curb = Block(val = val, left = preb.left, right = preb)\n preb.left.right, preb.left = curb, curb\n curb.kids.add(key)\n if curb.val:\n self.keyblock[key] = curb\n else:\n self.keyblock.pop(key)\n if not preb.kids and preb.val != 0:\n preb.left.right = preb.right\n preb.right.left = preb.left\n preb.left, preb.right = None, None\n def getMaxKey(self) -> str:\n \"\"\"\n Returns one of the keys with maximal value.\n \"\"\"\n if self.sright.left.val == 0:\n return \"\"\n for kid in self.sright.left.kids:\n return kid\n def getMinKey(self) -> str:\n \"\"\"\n Returns one of the keys with Minimal value.\n \"\"\"\n if self.sleft.right.val == 0:\n return \"\"\n for kid in self.sleft.right.kids:\n return kid\n" }, { "alpha_fraction": 0.5, "alphanum_fraction": 0.5239273905754089, "avg_line_length": 34.64706039428711, "blob_id": "caad7e2d3175fb23acbaabbbbe08d656d1e50625", "content_id": "286564921d95a38a1f721fae12f6d11b9f4c0cf3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1212, "license_type": "no_license", "max_line_length": 150, "num_lines": 34, "path": "/lc1130_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n# dfs+memo /dp\n def mctFromLeafValues(self, arr: List[int]) -> int:\n @lru_cache(None)\n def dfs(i,j):\n if j<=i:\n return 0\n res = float('inf')\n for k in range(i,j):\n res = min(dfs(i,k)+dfs(k+1,j)+max(arr[i:k+1])*max(arr[k+1:j+1]),res)\n return res\n return dfs(0,len(arr)-1)\n\n#https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/951938/Don't-overthink-about-trees.-It's-a-DPGreedy-problem.\n# greedy\n def mctFromLeafValues(self, A):\n res = 0\n while len(A) > 1:\n i = A.index(min(A))\n res += min(A[i - 1:i] + A[i + 1:i + 2]) * A.pop(i)\n return res\n\n#https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/discuss/478708/RZ-Summary-of-all-the-solutions-I-have-learned-from-Discuss-in-Python\n def mctFromLeafValues(self, A):\n res = 0\n stack = [float(\"inf\")]\n for a in A:\n while stack[-1] <= a:\n mid = stack.pop()\n res += mid * min(stack[-1], a)\n stack.append(a)\n while len(stack) > 2:\n res += stack.pop() * stack[-1]\n return res\n" }, { "alpha_fraction": 0.47859495878219604, "alphanum_fraction": 0.5005488395690918, "avg_line_length": 49.61111068725586, "blob_id": "c0207e634ca08ef5cf5b3b468469955e706f5921", "content_id": "1008830c7d9724ab32c50acb0a1fd102f5e668a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 911, "license_type": "no_license", "max_line_length": 83, "num_lines": 18, "path": "/lc1066_dijkstra.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def assignBikes(self, workers: List[List[int]], bikes: List[List[int]]) -> int:\n def md(p1, p2):\n return abs(p1[0] - p2[0])+abs(p1[1] - p2[1])\n heap = [(0, 0, \"0\"*len(bikes))] # total distance, worker id, bike status\n visited = collections.defaultdict(lambda:float(\"inf\"))\n while heap:\n total, idx, bike_status = heapq.heappop(heap)\n if idx == len(workers):\n return total\n for i, b in enumerate(bikes):\n if bike_status[i] != '1':\n n_total = total + md(workers[idx], b)\n n_bike_status = bike_status[:i]+'1'+bike_status[i+1:]\n if n_total < visited[(idx+1, n_bike_status)]:\n visited[(idx+1, n_bike_status)] = n_total\n heapq.heappush(heap,[n_total, idx+1, n_bike_status])\n return -1\n" }, { "alpha_fraction": 0.3847073018550873, "alphanum_fraction": 0.3930704891681671, "avg_line_length": 31.19230842590332, "blob_id": "8f6b4b065aebc54b6ef019fe324f010cd740a6c5", "content_id": "5a3402739bfd87a30b427b94277abe8ab6c21bdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 837, "license_type": "no_license", "max_line_length": 63, "num_lines": 26, "path": "/lc1520_greedy.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxNumOfSubstrings(self, s: str) -> List[str]:\n bdry = {}\n for i, c in enumerate(s):\n if c not in bdry:\n bdry[c] = [i, i]\n else:\n bdry[c][1] = i\n for c in set(s):\n left, right = bdry[c]\n l, r = left, right\n while True:\n for oc in set(s[left:right+1]):\n l = min(l, bdry[oc][0])\n r = max(r, bdry[oc][1])\n if [left, right] == [l, r]: break\n left, right = l, r\n bdry[c] = [l, r]\n\n intervals = sorted(bdry.values(), key = lambda x: x[1])\n rslt, last = [], -1\n for st, ed in intervals:\n if st > last:\n rslt.append(s[st:ed+1])\n last = ed\n return rslt\n" }, { "alpha_fraction": 0.4829443395137787, "alphanum_fraction": 0.5, "avg_line_length": 25.5238094329834, "blob_id": "b3680fc94b0936a6b8b0bf81bf9cd779973b35cb", "content_id": "f699760b0e816d92640b72705f2db70f13e03c00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1114, "license_type": "no_license", "max_line_length": 97, "num_lines": 42, "path": "/lc705_oop.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class MyHashSet:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.holder = [[] for _ in range(512)]\n\n def add(self, key: int) -> None:\n if self.contains(key):\n return True\n self.holder[key%512].append(key)\n return False\n\n\n def remove(self, key: int) -> None:\n hh = key%512\n i = 0\n while i < len(self.holder[hh]):\n if self.holder[hh][i] == key:\n self.holder[hh][i], self.holder[hh][-1] = self.holder[hh][-1], self.holder[hh][i]\n self.holder[hh].pop()\n break\n i += 1\n def contains(self, key: int) -> bool:\n \"\"\"\n Returns true if this set contains the specified element\n \"\"\"\n hh = key%512\n i = 0\n while i < len(self.holder[hh]):\n if self.holder[hh][i] == key:\n return True\n i += 1\n return False\n\n\n# Your MyHashSet object will be instantiated and called as such:\n# obj = MyHashSet()\n# obj.add(key)\n# obj.remove(key)\n# param_3 = obj.contains(key)\n" }, { "alpha_fraction": 0.45726701617240906, "alphanum_fraction": 0.4678899049758911, "avg_line_length": 33.516666412353516, "blob_id": "339461929f40ceebc8eb1222786a27b0aeebd506", "content_id": "557014806c447432896f099e18958c3afd3ac644", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2071, "license_type": "no_license", "max_line_length": 71, "num_lines": 60, "path": "/lc1135_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumCost(self, N: int, connections: List[List[int]]) -> int:\n # sort the connections by cost\n connections.sort(key = lambda x: x[2])\n parent = list(range(N+1))\n size = [1]*len(N+1)\n def find(p):\n while p!= parent[p]:\n parent[p] = parent[parent[p]]\n p = parent[p]\n return p\n def union(p, q, cost):\n rootp, rootq = find(p), find(q)\n if rootp == rootq: return -1\n if size[rootp] < size[rootq]: rootp, rootq = rootq, rootp\n parent[rootq] = rootp\n size[rootp] += size[rootq]\n return cost\n rslt, count = 0, 0\n for x, y, cost in connections:\n temp = union(x, y, cost)\n if cost >= 0:\n rslt += cost\n count += 1\n return rslt if count == N-1 else -1\n\n\nclass Solution:\n def minimumCost(self, N: int, connections: List[List[int]]) -> int:\n # sort the connections by cost\n connections.sort(key = lambda x: x[2])\n parent = list(range(N+1))\n size = [1]*(N+1)\n def find(p):\n while p!= parent[p]:\n parent[p] = parent[parent[p]]\n p = parent[p]\n return p\n def union(p, q, cost):\n rootp, rootq = find(p), find(q)\n if rootp == rootq: return -1\n if size[rootp] < size[rootq]: rootp, rootq = rootq, rootp\n parent[rootq] = rootp\n size[rootp] += size[rootq]\n return cost\n rslt, count = 0, 0\n for x, y, cost in connections:\n temp = union(x, y, cost)\n if temp >= 0:\n rslt += temp\n count += 1\n return rslt if count == N-1 else -1\n\n\nclass UF:\n def __init__(self, n): self.p = list(range(n))\n def union(self, x, y): self.p[self.find(x)] = self.find(y)\n def find(self, x):\n if x != self.p[x]: self.p[x] = self.find(self.p[x])\n return self.p[x]\n" }, { "alpha_fraction": 0.47705042362213135, "alphanum_fraction": 0.48382243514060974, "avg_line_length": 35.91666793823242, "blob_id": "7af569733cb5865462b25c9d0767e5468f810d57", "content_id": "c9f53a6a659e8cba51cd607bba0eeace2217e354", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1329, "license_type": "no_license", "max_line_length": 67, "num_lines": 36, "path": "/lc215_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n pivot = nums[(0+len(nums))//2]\n left = [l for l in nums if l > pivot]\n mid = [m for m in nums if m == pivot]\n right = [r for r in nums if r < pivot]\n if len(left) >= k:\n return self.findKthLargest(left, k)\n elif len(left)+len(mid) >= k:\n return pivot\n else:\n return self.findKthLargest(right, k-len(left)-len(mid))\n\n\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n def partition(left, right):\n pivot, l = (left+right)//2, left\n nums[pivot], nums[right] = nums[right], nums[pivot]\n for i in range(left, right):\n if nums[i] >= nums[right]:\n nums[l], nums[i] = nums[i], nums[l]\n l += 1\n nums[right], nums[l] = nums[l], nums[right]\n return l\n def select(left, right, k):\n if left == right:\n return nums[k]\n pivot = partition(left, right)\n if k == pivot:\n return nums[k]\n elif k < pivot:\n return select(left, pivot-1, k)\n else:\n return select(pivot+1, right, k)\n return select(0, len(nums)-1, k-1)\n" }, { "alpha_fraction": 0.5513100624084473, "alphanum_fraction": 0.5513100624084473, "avg_line_length": 35.63999938964844, "blob_id": "488ebac144d04b9a365dc6154b051242cafc741d", "content_id": "25549033506ccf3da7a9c45747fc16b27c5e7e93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "no_license", "max_line_length": 66, "num_lines": 25, "path": "/lc450_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findleftlarge(self, root):\n while root.right:\n root = root.right\n return root.val\n def findrightsmall(self, root):\n while root.left:\n root = root.left\n return root.val\n def deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n if not root: return None\n if key > root.val:\n root.right = self.deleteNode(root.right, key)\n elif key < root.val:\n root.left = self.deleteNode(root.left, key)\n else:\n if not root.left and not root.right:\n return None\n if root.right:\n root.val = self.findrightsmall(root.right)\n root.right = self.deleteNode(root.right, root.val)\n else:\n root.val = self.findleftlarge(root.left)\n root.left = self.deleteNode(root.left, root.val)\n return root\n" }, { "alpha_fraction": 0.3968565762042999, "alphanum_fraction": 0.41846758127212524, "avg_line_length": 35.35714340209961, "blob_id": "4da9ca5f209663c39fe6dd721ff62d06d7410d49", "content_id": "346a3d5867d06e22e3358fed46cac3267ca40662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 509, "license_type": "no_license", "max_line_length": 66, "num_lines": 14, "path": "/lc636_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def exclusiveTime(self, n: int, logs: List[str]) -> List[int]:\n rslt, stk = [0]*n, []\n for log in logs:\n idx, op, time = log.split(\":\")\n if op == \"end\":\n rslt[int(idx)] += int(time)-stk[-1][1]+1\n stk.pop()\n if stk: stk[-1][1] = int(time)+1\n continue\n if stk:\n rslt[int(stk[-1][0])] += int(time)-stk[-1][1]\n stk.append([idx, int(time)])\n return rslt\n" }, { "alpha_fraction": 0.597484290599823, "alphanum_fraction": 0.599056601524353, "avg_line_length": 36.411766052246094, "blob_id": "4bb7936a0e3e359f9a3e58dbfdcf569e1ac71d71", "content_id": "c440300dcb7f32c3beda75abf75406482ef4261a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 636, "license_type": "no_license", "max_line_length": 56, "num_lines": 17, "path": "/lc1026_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def maxAncestorDiff(self, root: TreeNode) -> int:\n return self.dfs(root, root.val, root.val)\n\n def dfs(self, node, curr_max, curr_min):\n if not node: return curr_max - curr_min\n curr_max = max(curr_max, node.val)\n curr_min = min(curr_min, node.val)\n left = self.dfs(node.left, curr_max, curr_min)\n right = self.dfs(node.right, curr_max, curr_min)\n return max(left, right)\n" }, { "alpha_fraction": 0.4450261890888214, "alphanum_fraction": 0.46073299646377563, "avg_line_length": 34.8125, "blob_id": "f9b3be55bdc42ab22f515e5fa5281e9b046eb8e2", "content_id": "89f70bdab9f6cf886b5f619e236a5f4380bb9b79", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 64, "num_lines": 16, "path": "/lc1048_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestStrChain(self, words: List[str]) -> int:\n memo, word_set = {}, set(words)\n def dfs(word):\n if len(word) == 1: return 1\n if word in memo: return memo[word]\n rslt = 0\n for i in range(len(word)):\n if word[:i] + word[i+1:] in word_set:\n rslt = max(rslt, dfs(word[:i] + word[i+1:]))\n memo[word] = rslt + 1\n return rslt + 1\n rslt = 0\n for word in words[::-1]:\n rslt = max(rslt, dfs(word))\n return rslt\n" }, { "alpha_fraction": 0.4108658730983734, "alphanum_fraction": 0.45500847697257996, "avg_line_length": 38.266666412353516, "blob_id": "c4b622bb208bc43cfc41603e109278423418d63c", "content_id": "08122bd0c5b5908be0b5cacefba4fe1f9cec50c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 86, "num_lines": 15, "path": "/lc391_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isRectangleCover(self, rectangles: List[List[int]]) -> bool:\n area = 0\n corners = set()\n for x1, y1, x2, y2 in rectangles:\n area += (y2-y1)*(x2-x1)\n for x, y in [(x1, y1), (x2, y2), (x1, y2), (x2, y1)]:\n if (x, y) in corners:\n corners.remove((x, y))\n else:\n corners.add((x, y))\n if len(corners) != 4:\n return False\n corners = sorted(corners)\n return area == (corners[-1][1]-corners[0][1])*(corners[-1][0] - corners[0][0])\n" }, { "alpha_fraction": 0.5553320050239563, "alphanum_fraction": 0.5553320050239563, "avg_line_length": 37.230770111083984, "blob_id": "ed74baaf7c233bacca9204493940cefcdc724209", "content_id": "5abdfd467c6b1baf16e68686bfe2302aa0977b84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "no_license", "max_line_length": 98, "num_lines": 13, "path": "/lc572_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution(object):\n def isSubtree(self, s, t):\n \"\"\"\n :type s: TreeNode\n :type t: TreeNode\n :rtype: bool\n \"\"\"\n def isSametree(s, t):\n if not s and not t: return True\n if not s or not t: return False\n return s.val == t.val and isSametree(s.left, t.left) and isSametree(s.right, t.right)\n if not t: return True\n return s and (isSametree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t))\n" }, { "alpha_fraction": 0.41093748807907104, "alphanum_fraction": 0.43437498807907104, "avg_line_length": 36.64706039428711, "blob_id": "3167a5bd8fd848d3ce942841a4cb63e2db4e8184", "content_id": "7eff287be8266d1842ce004744f320ef4bf6621f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 71, "num_lines": 17, "path": "/lc909_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def snakesAndLadders(self, board: List[List[int]]) -> int:\n n = len(board)\n dque, visited, n = collections.deque([(0, 0)]), {0}, len(board)\n while dque:\n step, t = dque.popleft()\n dx = n-t//n-1\n dy = t%n if t//n%2 == 0 else n-t%n-1\n if board[dx][dy] > 0:\n t = board[dx][dy]-1\n if t+1 == n*n: return step\n for s in range(1, 7):\n curr = t+s\n if curr not in visited and 0 <= curr < n*n:\n dque.append((step+1, curr))\n visited.add(curr)\n return -1\n" }, { "alpha_fraction": 0.3513071835041046, "alphanum_fraction": 0.3807189464569092, "avg_line_length": 37.25, "blob_id": "35bc12f491fa7ff87fdc4065ff442398610d1211", "content_id": "bf1d3c45977f203c9d207f5895346741313056f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 612, "license_type": "no_license", "max_line_length": 92, "num_lines": 16, "path": "/lc695_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxAreaOfIsland(self, grid: List[List[int]]) -> int:\n def dfs(i, j):\n curr = 1\n for x, y in [(0, 1), (1, 0), (-1, 0), (0, -1)]:\n if 0 <= i+x < len(grid) and 0<=j + y < len(grid[0]) and grid[i+x][j+y] == 1:\n grid[i+x][j+y] = 0\n curr += dfs(i+x, j+y)\n return curr\n rslt = 0\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if grid[i][j] == 1:\n grid[i][j] = 0\n rslt = max(rslt, dfs(i, j))\n return rslt\n" }, { "alpha_fraction": 0.503311276435852, "alphanum_fraction": 0.5143488049507141, "avg_line_length": 36.75, "blob_id": "da785fa1c57bc9f5f24fe135945a66daefd0ec34", "content_id": "360b37aa17958922c82a7ca470c8a9b0c064fa21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 74, "num_lines": 12, "path": "/lc456_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def find132pattern(self, nums: List[int]) -> bool:\n stk, last = [], -float(\"inf\")\n for num in nums[::-1]:\n # last is ensured to be less than one seen item\n if num < last:\n return True\n # mono-decreasing-stack maintaining value for nums[k] aka last\n while stk and stk[-1] < num:\n last = stk.pop()\n stk.append(num)\n return False\n" }, { "alpha_fraction": 0.5970272421836853, "alphanum_fraction": 0.6011560559272766, "avg_line_length": 32.63888931274414, "blob_id": "0381c4cda90fb5da6bb1b398b46fb80eeee331ae", "content_id": "43f5ad5219def033326e27357390442529e50c13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/lc381_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class RandomizedCollection:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.validx = collections.defaultdict(set)\n self.collection = []\n\n\n def insert(self, val: int) -> bool:\n \"\"\"\n Inserts a value to the collection. Returns true if the collection did not already contain the specified element.\n \"\"\"\n self.collection.append(val)\n self.validx[val].add(len(self.collection)-1)\n return len(self.validx[val]) == 1\n\n def remove(self, val: int) -> bool:\n \"\"\"\n Removes a value from the collection. Returns true if the collection contained the specified element.\n \"\"\"\n if not self.validx[val]:\n return False\n idx = self.validx[val].pop()\n self.collection[-1], self.collection[idx] = self.collection[idx], self.collection[-1]\n self.validx[self.collection[idx]].add(idx)\n self.validx[self.collection[idx]].discard(len(self.collection)-1)\n self.collection.pop()\n return True\n\n def getRandom(self) -> int:\n \"\"\"\n Get a random element from the collection.\n \"\"\"\n return random.choice(self.collection)\n" }, { "alpha_fraction": 0.3863636255264282, "alphanum_fraction": 0.4223484992980957, "avg_line_length": 28.33333396911621, "blob_id": "23ed2add9eb085d7f191e4aafad89751ea32195c", "content_id": "99b2e8b31ba25ae349c47fd105afe782456ec53a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 51, "num_lines": 18, "path": "/lc581_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution(object):\n def findUnsortedSubarray(self, nums):\n n = len(nums)\n if n < 2: return 0\n l, r = 0, n - 1\n while l < n - 1 and nums[l] <= nums[l + 1]:\n l += 1\n while r > 0 and nums[r] >= nums[r -1]:\n r -= 1\n if l > r: return 0\n subarray = nums[l:r+1]\n mi, ma = min(subarray), max(subarray)\n\n while l > 0 and mi < nums[l-1]:\n l -= 1\n while r < n - 1 and ma > nums[r+1]:\n r += 1\n return r - l + 1\n" }, { "alpha_fraction": 0.29828110337257385, "alphanum_fraction": 0.3003033399581909, "avg_line_length": 31.96666717529297, "blob_id": "584f2c97069d5a7c05b093b94ab7c96dcf8a02ce", "content_id": "600986d7d9abbaf8cda9499ce7a948965ddd52a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "no_license", "max_line_length": 61, "num_lines": 30, "path": "/lc772_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def calculate(self, s: str) -> int:\n stk, last = [\"(\"], \"\"\n for c in s+\")\":\n if c == \" \": continue\n if c.isdigit():\n last += c if last else c\n elif c == \"(\":\n stk.append(c)\n else:\n op = stk.pop()\n if op == \"*\":\n stk.append(int(stk.pop())*int(last))\n elif op == \"/\":\n stk.append(int(int(stk.pop())/int(last)))\n elif op == \"-\":\n stk.append(-int(last))\n else:\n stk.append(op)\n stk.append(int(last))\n last = \"\"\n if c == \")\":\n y = 0\n while stk[-1] !=\"(\":\n y += stk.pop()\n stk.pop()\n last = str(y)\n elif c != \"+\":\n stk.append(c)\n return int(last)\n" }, { "alpha_fraction": 0.3914141356945038, "alphanum_fraction": 0.42171716690063477, "avg_line_length": 40.68421173095703, "blob_id": "5e62e495cd1517893f59174e4ccf5214b4d44e37", "content_id": "b35923c064ecb8d8a06ce34875e9607a5f18857e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 792, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/lc1368_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minCost(self, grid: List[List[int]]) -> int:\n heap, visited = [(0, 0, 0)], set()\n nrow, ncol = len(grid), len(grid[0])\n directions = {1:(0, 1), 2:(0, -1), 3:(1, 0), 4:(-1, 0)}\n while heap:\n step, x, y = heapq.heappop(heap)\n if x == nrow-1 and y == ncol-1:\n return step\n if (x, y) in visited: continue\n visited.add((x, y))\n for i in directions:\n nx, ny = x+directions[i][0], y+directions[i][1]\n if 0 <= nx < nrow and 0 <= ny < ncol:\n if grid[x][y] == i:\n heapq.heappush(heap, (step, nx, ny))\n else:\n heapq.heappush(heap, (step+1, nx, ny))\n return 0\n" }, { "alpha_fraction": 0.38726791739463806, "alphanum_fraction": 0.3912466764450073, "avg_line_length": 33.272727966308594, "blob_id": "12ce2cca0b1835b3bdcda7566b104fad919eb506", "content_id": "209cea625a1caec1945a17de277242d55388d755", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 754, "license_type": "no_license", "max_line_length": 80, "num_lines": 22, "path": "/lc394_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def decodeString(self, s: str) -> str:\n stack, digit, currs, rslt = [], \"\", \"\", \"\"\n for c in s:\n if c.isalpha():\n currs += c\n elif c.isdigit():\n digit += c\n elif c == \"[\":\n if currs:\n stack.append(currs)\n stack.append(digit)\n digit, currs= \"\", \"\"\n elif c == \"]\":\n lastc = int(stack.pop()) if stack and stack[-1].isdigit() else 1\n currs = lastc*currs\n while stack and stack[-1].isalpha():\n currs = stack.pop()+currs\n if not stack:\n rslt += currs\n currs = \"\"\n return rslt\n" }, { "alpha_fraction": 0.3752151429653168, "alphanum_fraction": 0.3855421543121338, "avg_line_length": 31.27777862548828, "blob_id": "29c79671ab1357ede69277dbfdc53ca62116b67c", "content_id": "31357c067dada6229bfc47018681aa4556fd9648", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 61, "num_lines": 18, "path": "/lc838_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pushDominoes(self, dominoes: str) -> str:\n left, lnote, rslt = -1, \"L\", \"\"\n for right, do in enumerate(dominoes+\"R\"):\n if do == \".\":\n continue\n mid = right-left-1\n if left >= 0:\n rslt += lnote\n if do == lnote:\n rslt += mid*lnote\n elif lnote == \"L\" and do == \"R\":\n rslt += mid*\".\"\n else:\n rslt += \"R\"*(mid//2)+\".\"*(mid%2)+\"L\"*(mid//2)\n left = right\n lnote = do\n return rslt\n" }, { "alpha_fraction": 0.34840869903564453, "alphanum_fraction": 0.42211055755615234, "avg_line_length": 45, "blob_id": "c049e2763c7f534b48474e0ba1c6b9f157a7b408", "content_id": "2abe2a70f27f95488f75f3315a10934395452d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 81, "num_lines": 13, "path": "/lc712_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumDeleteSum(self, s1: str, s2: str) -> int:\n l_s1, l_s2, rslt = len(s1), len(s2), 0\n dp = [[0]*(l_s2 + 1) for _ in range(l_s1 + 1)]\n for i in range(1, l_s1+1): dp[i][0] = dp[i-1][0] + ord(s1[i-1])\n for j in range(1, l_s2+1): dp[0][j] = dp[0][j-1] + ord(s2[j-1])\n for i, c1 in enumerate(s1):\n for j, c2 in enumerate(s2):\n if c1 == c2:\n dp[i+1][j+1] = dp[i][j]\n else:\n dp[i+1][j+1] = min(dp[i+1][j] +ord(c2), dp[i][j+1] + ord(c1))\n return dp[-1][-1]" }, { "alpha_fraction": 0.4655582010746002, "alphanum_fraction": 0.4750593900680542, "avg_line_length": 30.69230842590332, "blob_id": "3e1df6c6b8ebbbbf67b439c9ff009715ed77c00f", "content_id": "5a534a43797c020cb3714497d5e24bd0195817ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 421, "license_type": "no_license", "max_line_length": 64, "num_lines": 13, "path": "/lc523_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def checkSubarraySum(self, nums: List[int], k: int) -> bool:\n n = len(nums)\n maps = {0:-1}\n presum = 0\n for i, num in enumerate(nums):\n presum += num\n presum = presum%k\n if presum in maps and i-maps[presum] > 1:\n return True\n elif presum not in maps:\n maps[presum] = i\n return False\n \n" }, { "alpha_fraction": 0.46830984950065613, "alphanum_fraction": 0.49295774102211, "avg_line_length": 30.66666603088379, "blob_id": "8415f6743e265e0bb6588e1eb8a975321161ed77", "content_id": "2fd84be18e9428f82823a47e35264306e5f7fece", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/lc560_hash.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def subarraySum(self, nums: List[int], k: int) -> int:\n keeper = {0:1}\n rslt, temp = 0, 0\n for num in nums:\n temp += num\n rslt += keeper.get(temp-k, 0)\n keeper[temp] = keeper.get(temp, 0) +1\n return rslt" }, { "alpha_fraction": 0.42832469940185547, "alphanum_fraction": 0.47322970628738403, "avg_line_length": 37.599998474121094, "blob_id": "1aa34ceecf34c17707b288e0529cd128e2b51234", "content_id": "072c4055b0a1eb6e2d851840a15767548f2f3847", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 579, "license_type": "no_license", "max_line_length": 113, "num_lines": 15, "path": "/lc1229_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:\n slots1.sort()\n slots2.sort()\n n1, n2 = len(slots1), len(slots2)\n i, j = 0, 0\n while i < n1 and j < n2:\n left, right = max(slots1[i][0], slots2[j][0]), min(slots1[i][1], slots2[j][1])\n if right - left >= duration:\n return [left, left +duration]\n elif slots1[i][1] < slots2[j][1]:\n i += 1\n else:\n j += 1\n return []\n" }, { "alpha_fraction": 0.41161179542541504, "alphanum_fraction": 0.4272097051143646, "avg_line_length": 45.15999984741211, "blob_id": "c9aceda1f1b4b927f83dfa4708655afb50ee2b4b", "content_id": "b4a3cc6414a8a593459c39b2f9d840ce43fa5c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2308, "license_type": "no_license", "max_line_length": 98, "num_lines": 50, "path": "/lc864_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n k, nrow, ncol = 0, len(grid), len(grid[0])\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == \"@\": start = (i, j)\n elif grid[i][j] in string.ascii_lowercase: k += 1\n dque, visited= collections.deque([(0, start[0], start[1], \"\")]), {}\n while dque:\n step, x, y, getk = dque.popleft()\n if len(getk) == k:\n return step\n for dx, dy in [(x+1,y), (x, y+1), (x,y-1), (x-1, y)]:\n newk = getk\n if 0 <= dx < nrow and 0 <= dy < ncol and grid[dx][dy] !=\"#\":\n tc = grid[dx][dy]\n if tc in string.ascii_uppercase and tc.lower() not in newk:\n continue\n if tc in string.ascii_lowercase and tc not in newk:\n newk += tc\n if (dx, dy, newk) not in visited:\n visited.add((dx, dy, newk))\n dque.append((step+1, dx, dy, newk))\n return -1\n\n\nclass Solution:\n def shortestPathAllKeys(self, grid: List[str]) -> int:\n k, nrow, ncol = 0, len(grid), len(grid[0])\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == \"@\": start = (i, j)\n elif grid[i][j] in string.ascii_lowercase: k += 1\n dque, visited= collections.deque([(0, start[0], start[1], 0)]), {}\n while dque:\n step, x, y, getk = dque.popleft()\n if getk == 2**k-1:\n return step\n for dx, dy in [(x+1,y), (x, y+1), (x,y-1), (x-1, y)]:\n newk = getk\n if 0 <= dx < nrow and 0 <= dy < ncol and grid[dx][dy] !=\"#\":\n tc = grid[dx][dy]\n if tc in string.ascii_uppercase and (1 << ord(tc.lower())-ord('a'))&newk == 0:\n continue\n if tc in string.ascii_lowercase and (1 << (ord(tc)-ord('a')))&newk == 0:\n newk |= 1 << (ord(tc)-ord('a'))\n if (dx, dy, newk) not in visited:\n visited.add((dx, dy, newk))\n dque.append((step+1, dx, dy, newk))\n return -1\n" }, { "alpha_fraction": 0.40353259444236755, "alphanum_fraction": 0.41983696818351746, "avg_line_length": 26.80769157409668, "blob_id": "a250becf614caaff7f909fa41314d602d60c54ae", "content_id": "93fa784120c4dc90869b5ab10b22b0788ed25b22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 736, "license_type": "no_license", "max_line_length": 50, "num_lines": 26, "path": "/lc222_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countNodes(self, root: TreeNode) -> int:\n if not root: return 0\n left, depth = root, 0\n while left.left:\n left = left.left\n depth += 1\n left, right = (1<<depth), (1<<(depth+1))-1\n while left <= right:\n mid = (left + right)//2\n if self.check(mid, root):\n left = mid+1\n else:\n right = mid -1\n return right\n\n def check(self, mid, root):\n path = bin(mid)[3:]\n for x in path:\n if x == \"0\":\n root = root.left\n else:\n root = root.right\n if not root:\n return False\n return True\n \n" }, { "alpha_fraction": 0.4681335389614105, "alphanum_fraction": 0.4848254919052124, "avg_line_length": 47.814815521240234, "blob_id": "f6962c47b98f09b1e217a211317c673156358526", "content_id": "5120693f5ca3f87969754ad65bfb5146037f256f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1318, "license_type": "no_license", "max_line_length": 147, "num_lines": 27, "path": "/lc312_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n # def maxCoins(self, nums: List[int]) -> int:\n # nnums = [1]+[num for num in nums if num > 0] + [1]\n # n = len(nnums)\n# dp = [[0]*n for _ in range(n)]\n# for l in range(2, n):\n# for left in range(0, n-l):\n# right = left + l\n# for mid in range(left+1, right):\n# dp[left][right] = max(dp[left][right], nnums[left]*nnums[mid]*nnums[right]+dp[left][mid]+dp[mid][right])\n# return dp[0][n-1]\n # def dfs(left, right, memo = {}):\n # if (left, right) in memo: return memo[(left, right)]\n # rslt = max([nnums[left]*nnums[mid]*nnums[right]+dfs(left, mid, memo)+dfs(mid, right, memo) for mid in range(left+1, right)] or [0] )\n # memo[(left, right)] = rslt\n # return rslt\n # return dfs(0, n-1)\n def maxCoins(self, nums: List[int]) -> int:\n nums = [x for x in nums if x != 0]\n def maxcoin(nums, memo = {}):\n if nums not in memo:\n first , last = nums[0], nums[-1]\n ans = max([maxcoin(nums[:k+1]) + maxcoin(nums[k:]) + first * nums[k] * last for k in range(1, len(nums)-1)] or [0] )\n memo[nums] = ans\n return memo[nums]\n\n return maxcoin(tuple([1] + nums + [1]))\n" }, { "alpha_fraction": 0.31134968996047974, "alphanum_fraction": 0.36349692940711975, "avg_line_length": 37.411766052246094, "blob_id": "8f42d5e7e4a22ce49d109c1afb8a22054d4362b0", "content_id": "8019efb6bc5362911823cda46483caa8ec6a713f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 62, "num_lines": 17, "path": "/lc97_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isInterleave(self, s1: str, s2: str, s3: str) -> bool:\n l_s1, l_s2 = len(s1), len(s2)\n if len(s3) != l_s1 + l_s2:\n return False\n dp = [[False]*(l_s2 + 1) for _ in range(l_s1 + 1)]\n for i in range(l_s1 + 1):\n for j in range(l_s2 + 1):\n if i == 0 and j == 0:\n dp[i][j] = True\n continue\n if i > 0 and s1[i-1] == s3[i+j-1]:\n dp[i][j] = dp[i-1][j]\n if j > 0 and s2[j-1] == s3[i+j-1]:\n dp[i][j] = dp[i][j] or dp[i][j-1]\n \n return dp[-1][-1]" }, { "alpha_fraction": 0.5392953753471375, "alphanum_fraction": 0.5447154641151428, "avg_line_length": 32.54545593261719, "blob_id": "e61b78aa710a0059eb637da87c3efb320eb785c1", "content_id": "d6ba24fc6b2240bb44452dd7516efa444086094f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/lc1570_oop.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class SparseVector:\n def __init__(self, nums: List[int]):\n self.vec = {i:v for i, v in enumerate(nums) if v != 0}\n\n # Return the dotProduct of two sparse vectors\n def dotProduct(self, vec: 'SparseVector') -> int:\n rslt = 0\n for i,v in self.vec.items():\n if i in vec.vec:\n rslt += v*vec.vec[i]\n return rslt\n" }, { "alpha_fraction": 0.43286219239234924, "alphanum_fraction": 0.46289753913879395, "avg_line_length": 32.29411697387695, "blob_id": "6d9bff9e01364ee610e25ddf77be5eb5edd744fc", "content_id": "c0f4d48faaffece23a9aa5cec6cf11cd37db0445", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 54, "num_lines": 17, "path": "/lc666_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pathSum(self, nums: List[int]) -> int:\n maps = {num//10: num%10 for num in nums}\n self.rslt = 0\n def dfs(idx, curr):\n if idx not in maps: return\n curr += maps[idx]\n depth, loc = divmod(idx, 10)\n left = (depth+1)*10+loc*2-1\n right = left + 1\n if left not in maps and right not in maps:\n self.rslt += curr\n else:\n dfs(left, curr)\n dfs(right, curr)\n dfs(nums[0]//10, 0)\n return self.rslt\n" }, { "alpha_fraction": 0.44397464394569397, "alphanum_fraction": 0.46300211548805237, "avg_line_length": 32.78571319580078, "blob_id": "6b80237ef8975cdf1346ee3262f90b62bfc3fe78", "content_id": "73d79088bf46689e42a171082880c1f866e7e56d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 473, "license_type": "no_license", "max_line_length": 53, "num_lines": 14, "path": "/lc907_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def sumSubarrayMins(self, arr: List[int]) -> int:\n modulo = 10**9 + 7\n stk, rslt, remain = [], 0, 0\n for i, num in enumerate(arr):\n count = 1\n while stk and stk[-1][0] >= num:\n tnum, tcount = stk.pop()\n count += tcount\n remain -= tnum*tcount\n remain += count*num\n rslt += remain\n stk.append((num, count))\n return rslt%modulo\n" }, { "alpha_fraction": 0.4076305329799652, "alphanum_fraction": 0.4538152515888214, "avg_line_length": 37.30769348144531, "blob_id": "685b8c8feec6ac7f6c8da64f6349736ea5ac5547", "content_id": "dd9fdf45f05a3dee1b50d75fef85ebc1b659c434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 498, "license_type": "no_license", "max_line_length": 71, "num_lines": 13, "path": "/lc1577_math.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numTriplets(self, nums1: List[int], nums2: List[int]) -> int:\n c1, c2 = collections.Counter(nums1), collections.Counter(nums2)\n def helper(c1, c2):\n rslt, temp = 0, 0\n for k, v in c1.items():\n rslt += v*c2[k]*(c2[k]-1)//2\n\n for c in c2:\n if c < k and (k*k)%c == 0:\n rslt += v*c2[c]*c2[(k*k)//c]\n return rslt\n return helper(c1, c2) + helper(c2, c1)\n" }, { "alpha_fraction": 0.4770427942276001, "alphanum_fraction": 0.4894941747188568, "avg_line_length": 34.69444274902344, "blob_id": "dcc7b9e452d91ca0ccd45c07a6af1367b537462f", "content_id": "fd000c86df6b1c3bd5b9f90a32aa253a9c2e1d27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 90, "num_lines": 36, "path": "/lc735_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# ast > 0 fly to right, won't crash previous\n# ast < 0 fly to left, if previous same dir, won't crash either\n# ast < 0 fly to left, previous fly to right, crash(previous crash, ast crash, both crash)\nclass Solution:\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for ast in asteroids:\n if ast > 0:\n stack.append(ast)\n elif not stack or stack[-1] < 0:\n stack.append(ast)\n else:\n while stack and stack[-1] > 0 and stack[-1] < -ast:\n stack.pop()\n if not stack or stack[-1] < 0:\n stack.append(ast)\n elif stack[-1] == -ast:\n stack.pop()\n return stack\n\n# ast crashed previous asteroid in the stack\n# ast and previous both crash\n# ast crash\n def asteroidCollision(self, asteroids: List[int]) -> List[int]:\n stack = []\n for ast in asteroids:\n while stack and stack[-1] > 0 > ast:\n if stack[-1] < -ast:\n stack.pop()\n continue\n elif stack[-1] == -ast:\n stack.pop()\n break\n else:\n stack.append(ast)\n return stack\n" }, { "alpha_fraction": 0.4515393376350403, "alphanum_fraction": 0.4526796042919159, "avg_line_length": 27.29032325744629, "blob_id": "398ef250f13bc49a9638e886fa28e497c6da169b", "content_id": "fc181f0adae1bab4945afe666fd6d40b8839988d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 877, "license_type": "no_license", "max_line_length": 86, "num_lines": 31, "path": "/lc211_trie.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class WordDictionary:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.trie = {\"end\":False}\n\n\n def addWord(self, word: str) -> None:\n curr = self.trie\n for ch in word:\n curr[ch] = curr.get(ch, {\"end\":False})\n curr = curr[ch]\n curr[\"end\"] = True\n\n\n\n def search(self, word: str) -> bool:\n def helper(word, trie):\n if not word: return trie[\"end\"]\n for i, ch in enumerate(word):\n if ch == \".\":\n for key in trie.keys():\n if key != \"end\" and helper(word[i+1:], trie[key]): return True\n return False\n elif not ch in trie:\n return False\n trie = trie[ch]\n return trie[\"end\"]\n return helper(word, self.trie)\n" }, { "alpha_fraction": 0.3709884583950043, "alphanum_fraction": 0.3979460895061493, "avg_line_length": 32.869564056396484, "blob_id": "e1f234fb69faf01aa34e91cf323ab0f7e61373b0", "content_id": "40036f9a1f0fd4fb5e7ba0b7a4af27288cf7cbbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 75, "num_lines": 23, "path": "/lc1718_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def constructDistancedSequence(self, n: int) -> List[int]:\n rslt = [0]*(2*n-1)\n mark = [0]*(n+1)\n def bk(i, cnt):\n if cnt == 0:\n return True\n if i >= 2*n-1:\n return False\n if rslt[i]:\n return bk(i+1, cnt)\n\n for num in range(n, 0, -1):\n left, right = i, i+num if num > 1 else i\n if not mark[num] and right < (2*n -1) and rslt[right] == 0:\n mark[num] = 1\n rslt[left] = rslt[right] = num\n if bk(i+1, cnt-1): return True\n mark[num] = 0\n rslt[left] = rslt[right] = 0\n return False\n bk(0, n)\n return rslt\n" }, { "alpha_fraction": 0.596175491809845, "alphanum_fraction": 0.6074240803718567, "avg_line_length": 45.78947448730469, "blob_id": "1ac8b1c737999898c7093f9e6e881c5de0272b21", "content_id": "99fee70d1e5d186171a84a39027032ffb2261b68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 889, "license_type": "no_license", "max_line_length": 81, "num_lines": 19, "path": "/lc715_sortedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "from sortedcontainers import SortedList\nclass RangeModule:\n def __init__(self):\n self.ranges = SortedList()\n def addRange(self, left: int, right: int) -> None:\n idl, idr = self.ranges.bisect_left(left), self.ranges.bisect_right(right)\n for _ in range(idr-idl):\n self.ranges.pop(idl)\n if idl%2 == 0: self.ranges.add(left)\n if idr%2 == 0: self.ranges.add(right)\n def queryRange(self, left: int, right: int) -> bool:\n idl, idr = self.ranges.bisect_right(left), self.ranges.bisect_left(right)\n return idl == idr and idl%2 == 1\n def removeRange(self, left: int, right: int) -> None:\n idl, idr = self.ranges.bisect_left(left), self.ranges.bisect_right(right)\n for _ in range(idr-idl):\n self.ranges.pop(idl)\n if idl%2 == 1: self.ranges.add(left)\n if idr%2 == 1: self.ranges.add(right)\n" }, { "alpha_fraction": 0.3676646649837494, "alphanum_fraction": 0.37005987763404846, "avg_line_length": 38.761905670166016, "blob_id": "3f921c4d819f5b57c52c16b18443fa58f50769a0", "content_id": "3740e649c164498a7f8c982b9d9935f70dae7c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 835, "license_type": "no_license", "max_line_length": 142, "num_lines": 21, "path": "/lc1106_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def parseBoolExpr(self, expression: str) -> bool:\n stk_op, stk_or, ops = [], [], {\"t\":True, \"f\":False, \"|\": lambda x, y: x or y, \"&\":lambda x, y : x and y, \"!\":lambda x: not x, \"(\":\"(\"}\n for c in expression:\n if c == \",\": continue\n if c in (\"t\", \"f\", \"(\"):\n stk_op.append(ops[c])\n elif c in (\"!\", \"|\", \"&\"):\n stk_or.append(c)\n\n if c == \")\":\n opr = stk_or.pop()\n rslt = True if opr == \"&\" else False\n if opr == \"!\":\n rslt = ops[opr](stk_op.pop())\n else:\n while stk_op[-1] != \"(\":\n rslt = ops[opr](rslt, stk_op.pop())\n stk_op.pop()\n stk_op.append(rslt)\n return stk_op[0]\n" }, { "alpha_fraction": 0.4253135621547699, "alphanum_fraction": 0.44982895255088806, "avg_line_length": 43.97435760498047, "blob_id": "37f6ac89e7bb46dc1177fca6fa971c3744400a13", "content_id": "933286a2808900b781248a13a92ea242c44e0538", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1754, "license_type": "no_license", "max_line_length": 103, "num_lines": 39, "path": "/lc505_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:\n heap, visited = [(0, start[0], start[1])], {}\n rslt = float(\"inf\")\n nrow, ncol = len(maze), len(maze[0])\n while heap:\n step, currx, curry = heapq.heappop(heap)\n visited.add((currx, curry))\n if currx == destination[0] and curry == destination[1]:\n return step\n for dx, dy in [(1,0), (-1, 0), (0, 1), (0, -1)]:\n tx, ty, l = currx, curry, 0\n while 0 <= tx+dx < nrow and 0 <= ty+dy < ncol and maze[tx+dx][ty+dy] == 0:\n tx += dx\n ty += dy\n l += 1\n if (tx, ty) not in visited:\n heapq.heappush(heap, (step+l, tx, ty))\n return -1\n\n\nclass Solution:\n def shortestDistance(self, maze: List[List[int]], start: List[int], destination: List[int]) -> int:\n heap, visited = [(0, start[0], start[1])], {(start[0], start[1]): 0}\n nrow, ncol = len(maze), len(maze[0])\n while heap:\n step, currx, curry = heapq.heappop(heap)\n if currx == destination[0] and curry == destination[1]:\n return step\n for dx, dy in [(1,0), (-1, 0), (0, 1), (0, -1)]:\n tx, ty, l = currx, curry, 0\n while 0 <= tx+dx < nrow and 0 <= ty+dy < ncol and maze[tx+dx][ty+dy] == 0:\n tx += dx\n ty += dy\n l += 1\n if (tx, ty) not in visited or visited[(tx, ty)] > step+l:\n visited[(tx, ty)] = step + l\n heapq.heappush(heap, (step+l, tx, ty))\n return -1\n" }, { "alpha_fraction": 0.4560975730419159, "alphanum_fraction": 0.48048779368400574, "avg_line_length": 36.272727966308594, "blob_id": "c055fb356a5143b98a2371f419ad8a40a34e7e3b", "content_id": "beb07a003d90c1a94e6678b699fc6d0ef507c427", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 69, "num_lines": 11, "path": "/lc828_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def uniqueLetterString(self, s: str) -> int:\n index, rslt = {c:[-1, -1] for c in string.ascii_uppercase}, 0\n for i, c in enumerate(s):\n pre, last = index[c]\n rslt += (i-last)*(last-pre)\n index[c] = [last, i]\n n = len(s)\n for c in index:\n rslt += (n-index[c][1])*(index[c][1]-index[c][0])\n return rslt%(10**9+7)\n" }, { "alpha_fraction": 0.5269230604171753, "alphanum_fraction": 0.5326923131942749, "avg_line_length": 39, "blob_id": "2708fe7489967595577340064e75a59e628c84b7", "content_id": "a75e1045b658aec6d3be3ce455dfef51d265d417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 520, "license_type": "no_license", "max_line_length": 84, "num_lines": 13, "path": "/lc39_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n rslt, n = [], len(candidates)\n candidates.sort()\n def backtracking(target, i,curr):\n if target == 0:\n rslt.append(curr)\n elif i < n and target >= candidates[i]:\n temp = candidates[i]\n backtracking(target-temp, i, curr+[temp])\n backtracking(target, i+1, curr)\n backtracking(target, 0, [])\n return rslt\n" }, { "alpha_fraction": 0.39650872349739075, "alphanum_fraction": 0.4152119755744934, "avg_line_length": 29.846153259277344, "blob_id": "22495c604d430a53923d1d7d137654f2d2c2e107", "content_id": "a3cfe349dce83c9a3075f750813838c5e20d9aad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 802, "license_type": "no_license", "max_line_length": 83, "num_lines": 26, "path": "/lc489_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def cleanRoom(self, robot):\n \"\"\"\n :type robot: Robot\n :rtype: None\n \"\"\"\n def move_back():\n robot.turnLeft()\n robot.turnLeft()\n robot.move()\n robot.turnLeft()\n robot.turnLeft()\n\n def dfs(x, y, d):\n visited.add((x, y))\n robot.clean()\n for i in range(4):\n curr_d = (d+i)%4\n curr_x, curr_y = x + directions[curr_d][0], y+directions[curr_d][1]\n if (curr_x, curr_y) not in visited and robot.move():\n dfs(curr_x, curr_y, curr_d)\n move_back()\n robot.turnLeft()\n directions = [(-1, 0), (0, -1), (1, 0), (0, 1)]\n visited = set()\n dfs(0, 0, 0)\n" }, { "alpha_fraction": 0.38329237699508667, "alphanum_fraction": 0.4127764105796814, "avg_line_length": 30.30769157409668, "blob_id": "1014f0de30d6910acddc285b44a621199e85a1fc", "content_id": "2401c83ae5a4b0eb5f7d46da799b9eaaa0f96897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 67, "num_lines": 13, "path": "/lc1155_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numRollsToTarget(self, d: int, f: int, target: int) -> int:\n @lru_cache(None)\n def dfs(d, t):\n if d*f < t or d > t:\n return 0\n if d== 0 and t == 0:\n return 1\n rslt = 0\n for j in range(1, f+1):\n rslt += dfs(d-1, t-j)\n return rslt\n return dfs(d, target)%(10**9+7)\n" }, { "alpha_fraction": 0.39701491594314575, "alphanum_fraction": 0.41044774651527405, "avg_line_length": 32.54999923706055, "blob_id": "a5c8145493601947b09c942bbe56bad9b1227aba", "content_id": "1b6ec6f6252cdcfaf9a0361183ecf9184bb3c2eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 670, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/lc438_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n if len(p) > len(s):\n return []\n \n counter_p, counter_s, cnt, rslt = collections.Counter(p), {}, 0, []\n \n for i, c in enumerate(s):\n if c not in counter_p:\n counter_s = {}\n cnt = 0\n elif cnt < len(p):\n counter_s[c] = counter_s.get(c, 0) +1\n cnt += 1\n else:\n counter_s[c] = counter_s.get(c, 0) + 1\n counter_s[s[i-len(p)]] -= 1\n if counter_s == counter_p:\n rslt.append(i-len(p)+1)\n return rslt" }, { "alpha_fraction": 0.4977678656578064, "alphanum_fraction": 0.5089285969734192, "avg_line_length": 39.727272033691406, "blob_id": "e03bb5c6ee2589ba1d7003bee6ab8ea5025ffa00", "content_id": "564f382da0663da6124176f89712956aa47c21eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 448, "license_type": "no_license", "max_line_length": 102, "num_lines": 11, "path": "/lc486_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def PredictTheWinner(self, nums: List[int]) -> bool:\n memo = {}\n def dfs(left, right):\n if (left, right) in memo:\n return memo[(left, right)]\n if left == right:\n return nums[left]\n memo[(left, right)] = max(nums[left]- dfs(left +1, right), nums[right]-dfs(left, right-1))\n return memo[(left, right)]\n return dfs(0, len(nums)-1) >= 0\n" }, { "alpha_fraction": 0.429824560880661, "alphanum_fraction": 0.4429824650287628, "avg_line_length": 31.571428298950195, "blob_id": "7b41c6a07ca846608eac9fd48a2fb156c6e1b740", "content_id": "dd1f3def3b43da61ef312384d15ebbb1d51e3aa9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 456, "license_type": "no_license", "max_line_length": 62, "num_lines": 14, "path": "/lc875_bt.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minEatingSpeed(self, piles: List[int], H: int) -> int:\n def eatingHour(k):\n return sum( (x-1)//k + 1 for x in piles)\n left, right = 1, max(piles)\n while left < right:\n mid = (left + right)//2\n if eatingHour(mid) > H:\n left = mid\n else:\n right = mid\n if (left + right)//2 == mid:\n left += 1\n return right\n" }, { "alpha_fraction": 0.43914079666137695, "alphanum_fraction": 0.45584726333618164, "avg_line_length": 37.09090805053711, "blob_id": "9d56001ebf0deab894829b9c85e71c7875b27e8e", "content_id": "40ad4e5fcd6ffdf8efa0067ba3fb326f94d8f458", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "no_license", "max_line_length": 61, "num_lines": 11, "path": "/lc209_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minSubArrayLen(self, s: int, nums: List[int]) -> int:\n curr, rslt, left = 0, len(nums)+1, 0\n for right, num in enumerate(nums):\n curr += num\n if curr >= s:\n while curr >= s:\n rslt = min(right-left+1, rslt)\n curr -= nums[left]\n left += 1\n return 0 if rslt == len(nums)+1 else rslt\n" }, { "alpha_fraction": 0.37187498807907104, "alphanum_fraction": 0.37187498807907104, "avg_line_length": 32.68421173095703, "blob_id": "c8c8b7d47001a16749458897052ec90ab928d6f0", "content_id": "84126ae09efca13cc8b22ecec35e10ad05eab48b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "no_license", "max_line_length": 62, "num_lines": 19, "path": "/lc1096_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def braceExpansionII(self, expression: str) -> List[str]:\n stk, pre, curr = [], [], [\"\"]\n for c in expression:\n if c == \",\":\n pre += curr\n curr = [\"\"]\n elif c == \"{\":\n stk.append(pre)\n stk.append(curr)\n pre, curr = [], [\"\"]\n elif c == \"}\":\n p_curr = stk.pop()\n p_pre = stk.pop()\n curr = [s+k for k in pre+curr for s in p_curr]\n pre = p_pre\n else:\n curr = [s+c for s in curr]\n return sorted(set(pre+curr))\n" }, { "alpha_fraction": 0.3541666567325592, "alphanum_fraction": 0.3717948794364929, "avg_line_length": 30.200000762939453, "blob_id": "89df6a4651f54ac7e6b14d0a666a9f854d2400f2", "content_id": "8b9f4f5e5f7173e29842910cc1426240ad382653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 624, "license_type": "no_license", "max_line_length": 66, "num_lines": 20, "path": "/lc1482_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minDays(self, bloomDay: List[int], m: int, k: int) -> int:\n if m*k > len(bloomDay): return -1\n left, right = 1, max(bloomDay)\n while left <= right:\n mid = (left + right)//2\n tempf, tempb= 0, 0\n for bD in bloomDay:\n if bD <= mid:\n tempf += 1\n else:\n tempf = 0\n if tempf == k:\n tempb += 1\n tempf = 0\n if tempb >= m:\n right = mid -1\n else:\n left = mid + 1\n return left\n" }, { "alpha_fraction": 0.49266862869262695, "alphanum_fraction": 0.5014662742614746, "avg_line_length": 33.099998474121094, "blob_id": "abba0cfb6eebfb855ab319f75ceaff14de29136c", "content_id": "b8a7de7b11ce6e6280ec2448d477300c63d04ff6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/lc1665_greedy.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumEffort(self, tasks: List[List[int]]) -> int:\n tasks.sort(key = lambda x: x[0] - x[1])\n rslt = quota = 0\n for actual, minimum in tasks:\n if minimum > quota:\n rslt += (minimum - quota)\n quota = minimum\n quota -= actual\n return rslt\n" }, { "alpha_fraction": 0.45057034492492676, "alphanum_fraction": 0.4648289084434509, "avg_line_length": 37.96296310424805, "blob_id": "8bbb1eae0a08fe54ab159a8ce3aaa090144b7ed5", "content_id": "e83528de573881db09e8c68af476a079425d1172", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1052, "license_type": "no_license", "max_line_length": 75, "num_lines": 27, "path": "/lc973_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def kClosest(self, points: List[List[int]], K: int) -> List[List[int]]:\n def partition(left, right):\n pivot, l = (left+right)//2, left\n dist_pivot = dist[(points[pivot][0], points[pivot][1])]\n points[right], points[pivot] = points[pivot], points[right]\n for i in range(left, right+1):\n if dist[(points[i][0], points[i][1])] < dist_pivot:\n points[i], points[l] = points[l], points[i]\n l += 1\n points[l], points[right] = points[right], points[l]\n return l\n def select(left, right):\n if left == right: return\n pivot = partition(left, right)\n if pivot == K-1:\n return\n if pivot > K-1:\n select(left, pivot-1)\n else:\n select(pivot+1, right)\n return\n dist = {}\n for x, y in points:\n dist[(x, y)] = x**2 + y**2\n select(0, len(points)-1)\n return points[:K]\n" }, { "alpha_fraction": 0.49857550859451294, "alphanum_fraction": 0.49857550859451294, "avg_line_length": 34.099998474121094, "blob_id": "c3551863f596a6eefee9b730d40e5622e1ca2cb3", "content_id": "9c431f505b0a13f3657986e29ef740a0313189bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "no_license", "max_line_length": 51, "num_lines": 20, "path": "/lc133_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n if not node: return None\n newnode = Node(node.val)\n if not node.neighbors: return newnode\n queue = deque([node])\n amap = {node.val: newnode}\n visited = set()\n while queue:\n onode = queue.popleft()\n nnode = amap[onode.val]\n nnode.neighbors = []\n for n in onode.neighbors:\n if n.val not in amap:\n amap[n.val] = Node(n.val)\n nnode.neighbors.append(amap[n.val])\n if n.val not in visited:\n queue.append(n)\n visited.add(nnode.val)\n return newnode\n" }, { "alpha_fraction": 0.392123281955719, "alphanum_fraction": 0.4178082048892975, "avg_line_length": 40.71428680419922, "blob_id": "7c11f7528dd57a58eb26a99d2a745deafaef561c", "content_id": "0212c273f2549323d32cee69f880093cf9d680df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 71, "num_lines": 14, "path": "/lc778_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def swimInWater(self, grid: List[List[int]]) -> int:\n visited, heap, n = {(0,0)}, [(grid[0][0], 0, 0)], len(grid)\n rslt = 0\n while heap:\n node, x, y = heapq.heappop(heap)\n rslt = max(rslt, node)\n if x == n-1 and y == n-1:\n return rslt\n for i, j in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:\n if 0 <= i < n and 0 <= j < n and (i, j) not in visited:\n heapq.heappush(heap, (grid[i][j], i, j))\n visited.add((i, j))\n return rslt\n" }, { "alpha_fraction": 0.509018063545227, "alphanum_fraction": 0.52304607629776, "avg_line_length": 40.58333206176758, "blob_id": "dc2de500fa75077465b9ddc14191b5b8c71a1586", "content_id": "441711c22902d49945af15d9f311456ad51fada5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 499, "license_type": "no_license", "max_line_length": 60, "num_lines": 12, "path": "/lc862_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def shortestSubarray(self, A: List[int], K: int) -> int:\n presum = [0]\n for num in A: presum.append(presum[-1]+num)\n rslt, dque = len(A)+1, collections.deque()\n for idx, pre in enumerate(presum):\n while dque and pre <= presum[dque[-1]]:\n dque.pop()\n dque.append(idx)\n while pre - presum[dque[0]] >= K:\n rslt = min(rslt, idx-dque.popleft())\n return -1 if rslt == len(A)+1 else rslt\n" }, { "alpha_fraction": 0.5389447212219238, "alphanum_fraction": 0.5452261567115784, "avg_line_length": 40.894737243652344, "blob_id": "482c56afb5b1da7555ddfe12cfdda2eb2226065f", "content_id": "63433bdee6d61e887c568ba7f3db96b7fff3787c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 796, "license_type": "no_license", "max_line_length": 114, "num_lines": 19, "path": "/lc1462_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def checkIfPrerequisite(self, n: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]:\n isPre = collections.defaultdict(set)\n graph, degree = collections.defaultdict(list), collections.defaultdict(int)\n for pre, curr in prerequisites:\n graph[pre].append(curr)\n isPre[curr].add(pre)\n degree[curr] += 1\n degree[pre] += 0\n\n dque = collections.deque([v for v in degree if degree[v] == 0])\n while dque:\n temp = dque.popleft()\n for post in graph[temp]:\n isPre[post] |= isPre[temp]\n degree[post] -= 1\n if degree[post] == 0:\n dque.append(post)\n return [x in isPre[y] for x, y in queries]\n" }, { "alpha_fraction": 0.4891640841960907, "alphanum_fraction": 0.495356023311615, "avg_line_length": 31.299999237060547, "blob_id": "ee69d78b9b26271aadb7367e91f2068b4363743a", "content_id": "5c60e7e4a5c64f44fce08b508dd0e00940c06adf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 58, "num_lines": 10, "path": "/lc78_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def subsets(self, nums: List[int]) -> List[List[int]]:\n rslt = [[]]\n def backtracking(i):\n if i == len(nums): return\n for j in range(len(rslt)):\n rslt.append(rslt[j] +[nums[i]])\n backtracking(i+1)\n backtracking(0)\n return rslt\n" }, { "alpha_fraction": 0.4246031641960144, "alphanum_fraction": 0.4642857015132904, "avg_line_length": 30.5, "blob_id": "9662083111d68b40be5ab219d976e6ffaf71a147", "content_id": "d009719a2aec3499c82de3acff73e97e05ceaced", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/lc96_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numTrees(self, n: int) -> int:\n dp = [0]*(n+1)\n dp[0] = 1\n for total in range(1, n+1):\n for left in range(1, total+1):\n dp[total] += dp[left-1]*dp[total-left]\n return dp[-1]\n" }, { "alpha_fraction": 0.4514620006084442, "alphanum_fraction": 0.46315789222717285, "avg_line_length": 41.75, "blob_id": "74ad6ef7f41d7709e0f8d5b06ed3711a8670b707", "content_id": "3c2d5b2333d77ddb98742cdbd649536c00410245", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 92, "num_lines": 20, "path": "/lc269_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def alienOrder(self, words: List[str]) -> str:\n graph, degree = collections.defaultdict(list), {x:0 for word in words for x in word}\n for i, word in enumerate(words[:-1]):\n for j, c in enumerate(word):\n if j >= len(words[i+1]):\n return \"\"\n if c != words[i+1][j]:\n graph[c].append(words[i+1][j])\n degree[words[i+1][j]] += 1\n break\n dque, rslt = collections.deque([a for a in degree if degree[a] == 0]), []\n while dque:\n temp = dque.popleft()\n rslt.append(temp)\n for end in graph[temp]:\n degree[end] -= 1\n if degree[end] == 0:\n dque.append(end)\n return \"\".join(rslt) if len(rslt) == len(degree) else \"\"\n" }, { "alpha_fraction": 0.406876802444458, "alphanum_fraction": 0.406876802444458, "avg_line_length": 26.920000076293945, "blob_id": "d74630aee850edb8dec3b67ea4ac1fec3378ae41", "content_id": "ffa0a34323e88e2620d643acc61e5b65b86fd52d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 698, "license_type": "no_license", "max_line_length": 67, "num_lines": 25, "path": "/lc1650_lca.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':\n parents = {}\n if not p or not q: return p or q\n while p:\n if p == q: return p\n parents[p] = p.parent\n p = p.parent\n while q:\n q = q.parent\n if q in parents:\n return q\n return None\n def lowestCommonAncestor(self, p: 'Node', q: 'Node') -> 'Node':\n tp, tq = p, q\n while tp != tq:\n if tp.parent:\n tp = tp.parent\n else:\n tp = q\n if tq.parent:\n tq = tq.parent\n else:\n tq = p\n return tp\n" }, { "alpha_fraction": 0.3593582808971405, "alphanum_fraction": 0.3893048167228699, "avg_line_length": 33.62963104248047, "blob_id": "f035669728a6c9c2290e770d26e210ca89116f31", "content_id": "4787ca7f987e6ff7ee9016ebe8205675d5598cfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 935, "license_type": "no_license", "max_line_length": 133, "num_lines": 27, "path": "/lc803_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def hitBricks(self, grid: List[List[int]], hits: List[List[int]]) -> List[int]:\n m, n = len(grid), len(grid[0])\n def dfs(i, j):\n if 0 <= i < m and 0 <= j < n and grid[i][j] == 1:\n rslt = 1\n grid[i][j] = 2\n rslt += sum(dfs(x, y) for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)])\n return rslt\n return 0\n\n def is_new_stable(i, j):\n return i== 0 or any([0 <= x < m and 0 <= y < n and grid[x][y] == 2 for x, y in [(i-1, j), (i+1, j), (i, j-1), (i, j+1)]])\n\n for i, j in hits:\n grid[i][j] -= 1\n\n for i in range(n):\n dfs(0, i)\n\n res = [0]*len(hits)\n for k in range(len(hits)-1, -1, -1):\n i, j = hits[k]\n grid[i][j] += 1\n if grid[i][j] == 1 and is_new_stable(i, j):\n res[k] = dfs(i, j)-1\n return res\n" }, { "alpha_fraction": 0.504878044128418, "alphanum_fraction": 0.5219511985778809, "avg_line_length": 40, "blob_id": "680df576f1298c20de03afd7003a401cdc5a14d2", "content_id": "b80fcf5e29481eab93d96c464725a43dd3b94dd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "no_license", "max_line_length": 63, "num_lines": 10, "path": "/lc1569_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numOfWays(self, nums: List[int]) -> int:\n def helper(nums):\n if not nums: return 1\n root = nums[0]\n left = [num for num in nums if num < root]\n right = [num for num in nums if num > root]\n l, r = len(left), len(right)\n return math.comb(l+r, l)*helper(left)*helper(right)\n return (helper(nums)-1)%(10**9+7)\n" }, { "alpha_fraction": 0.366233766078949, "alphanum_fraction": 0.37402597069740295, "avg_line_length": 31.08333396911621, "blob_id": "f8e04d027efa2e5daa121d97515db2b0a7f4325e", "content_id": "5f0537aa7e83445dae26478465b233ff5d0009a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 80, "num_lines": 12, "path": "/lc294_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canWin(self, s: str) -> bool:\n memo = {}\n def dfs(s):\n if s in memo:\n return memo[s]\n for i in range(len(s)-1):\n if s[i] == \"+\" and s[i+1] == \"+\" and not dfs(s[:i]+\"-\"+s[i+2:]):\n memo[s] = True\n return True\n memo[s] = False\n return dfs(s)\n" }, { "alpha_fraction": 0.49251100420951843, "alphanum_fraction": 0.49603524804115295, "avg_line_length": 35.6129035949707, "blob_id": "1593d9d208f3f82f74fbc98c9ef928e6ed7a3119", "content_id": "c6126f1dcd370ac989866d37418859d3eaab1799", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1135, "license_type": "no_license", "max_line_length": 77, "num_lines": 31, "path": "/lc1306_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n seen = set()\n self.rslt, larr = False, len(arr)\n def backtracking(idx):\n if arr[idx] == 0:\n self.rslt = True\n return\n if idx in seen:\n return\n seen.add(idx)\n if idx + arr[idx] < larr:\n backtracking(idx+arr[idx])\n if idx - arr[idx] >= 0:\n backtracking(idx-arr[idx])\n backtracking(start)\n return self.rslt\n \n class Solution:\n def canReach(self, arr: List[int], start: int) -> bool:\n dque, visited = collections.deque([start]), {start}\n while dque:\n curr =dque.popleft()\n if arr[curr] == 0: return True\n if curr + arr[curr] < len(arr) and curr+arr[curr] not in visited:\n visited.add(curr+arr[curr])\n dque.append(curr+arr[curr])\n if curr - arr[curr] >= 0 and curr - arr[curr] not in visited:\n visited.add(curr-arr[curr])\n dque.append(curr-arr[curr])\n return False\n" }, { "alpha_fraction": 0.4930015504360199, "alphanum_fraction": 0.5069984197616577, "avg_line_length": 39.1875, "blob_id": "2b9e28cf8ae1ef1b3315444360f52a9e8939a1a3", "content_id": "b02f9ae216fdda2bc2784bc2de3ccdcd2fc85b58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 643, "license_type": "no_license", "max_line_length": 85, "num_lines": 16, "path": "/lc40_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:\n if not candidates: return []\n rslt, n = [], len(candidates)\n candidates.sort()\n def backtracking(i, target, curr):\n if target == 0:\n rslt.append(curr)\n elif i < n and target > 0:\n temp = candidates[i]\n backtracking(i+1, target-temp, curr+[temp])\n while i < n-1 and candidates[i] == candidates[i+1]:\n i += 1\n backtracking(i+1, target, curr)\n backtracking(0, target, [])\n return rslt\n" }, { "alpha_fraction": 0.45750707387924194, "alphanum_fraction": 0.4645892381668091, "avg_line_length": 36.157894134521484, "blob_id": "4147ea268ffff2b08ee45d624ae059fcb45e204f", "content_id": "b3b66c9a1c65577707b0eba11c8eced78c4c4f3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 706, "license_type": "no_license", "max_line_length": 117, "num_lines": 19, "path": "/lc399_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:\n grph = collections.defaultdict(dict)\n for (x, y), v in zip(equations, values):\n grph[x][y] = v\n grph[y][x] = 1/v\n\n def dfs(x, y, checked):\n if x == y:\n return 1\n checked.add(x)\n for z in grph[x]:\n if z in checked:\n continue\n tmp = dfs(z, y, checked)\n if tmp > 0:\n return tmp*grph[x][z]\n return -1\n return [dfs(x, y, set()) if x in grph and y in grph else -1 for x, y in queries]\n" }, { "alpha_fraction": 0.4752252399921417, "alphanum_fraction": 0.48048049211502075, "avg_line_length": 27.340425491333008, "blob_id": "d7c64b62a299d7f685555b9cc8500ed308874dfb", "content_id": "031ad877e81439794476f3f4433cee078fd2fbae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1332, "license_type": "no_license", "max_line_length": 55, "num_lines": 47, "path": "/lc1382_bt.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n rslt = []\n def preorder(l, r):\n if r == l:\n return None\n mid = (l+r)//2\n root = TreeNode(rslt[mid])\n root.left = preorder(l, mid)\n root.right = preorder(mid+1, r)\n return root\n def inorder(root):\n if not root:\n return\n inorder(root.left)\n rslt.append(root.val)\n inorder(root.right)\n inorder(root)\n return preorder(0, len(rslt))\n\nclass Solution:\n def balanceBST(self, root: TreeNode) -> TreeNode:\n rslt = []\n def inorder(root):\n if not root: return\n inorder(root.left)\n rslt.append(root)\n inorder(root.right)\n return\n\n def preorder(l, r):\n if l == r:\n return None\n mid = (l+r)//2\n root = rslt[mid]\n root.left = preorder(l, mid)\n root.right = preorder(mid+1, r)\n return root\n\n inorder(root)\n return preorder(0, len(rslt))\n" }, { "alpha_fraction": 0.4708904027938843, "alphanum_fraction": 0.48630136251449585, "avg_line_length": 37.93333435058594, "blob_id": "549887c89cdf030155952659673098e467f351be", "content_id": "c962897ed12e36cda527100006835531c40f72fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 64, "num_lines": 15, "path": "/lc632_heap.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def smallestRange(self, nums: List[List[int]]) -> List[int]:\n heap = [(row[0], i, 0) for i, row in enumerate(nums)]\n right = max(row[0] for row in nums)\n rslt = (0, float(\"inf\"))\n heapq.heapify(heap)\n while True:\n left, ir, ic = heapq.heappop(heap)\n if right-left < rslt[1]-rslt[0]:\n rslt = (left, right)\n if ic + 1 == len(nums[ir]):\n return rslt\n nxt = nums[ir][ic+1]\n right = max(right, nxt)\n heapq.heappush(heap, (nxt, ir, ic+1))\n" }, { "alpha_fraction": 0.5036126971244812, "alphanum_fraction": 0.5072254538536072, "avg_line_length": 31.186046600341797, "blob_id": "3dc30c8d51a95b5ee1f6df97bba68628b78c1ff8", "content_id": "0e4260a0e9f115e9cc555f4beb061864dfd5c41a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1384, "license_type": "no_license", "max_line_length": 88, "num_lines": 43, "path": "/lc146_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, val = 0,key = 0, left = None, right = None):\n self.val = val\n self.key = key\n self.left = left\n self.right = right\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.head = Node()\n self.end = Node(left = self.head)\n self.head.right = self.end\n self.maps = {}\n\n def get(self, key: int) -> int:\n if not self.maps or key not in self.maps:\n return -1\n curr = self.maps[key]\n curr.left.right = curr.right\n curr.right.left = curr.left\n curr.left = self.end.left\n curr.right = self.end\n self.end.left = curr\n curr.left.right = curr\n return curr.val\n\n def put(self, key: int, value: int) -> None:\n if key in self.maps:\n self.maps[key].val = value\n _ = self.get(key)\n else:\n curr = Node(val = value, key = key , left = self.end.left, right = self.end)\n self.end.left.right = curr\n self.end.left = curr\n self.maps[key] = curr\n if self.capacity == 0:\n temp = self.head.right\n self.head.right = self.head.right.right\n self.head.right.left = self.head\n self.maps.pop(temp.key)\n else:\n self.capacity -= 1\n" }, { "alpha_fraction": 0.4146341383457184, "alphanum_fraction": 0.4471544623374939, "avg_line_length": 32.54545593261719, "blob_id": "3bd4c39e69809d1f474ef8fe8cb66df480f14c42", "content_id": "01d55872801dc166f4bec243e7e50d4d2482a8c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 369, "license_type": "no_license", "max_line_length": 89, "num_lines": 11, "path": "/lc152_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxProduct(self, nums: List[int]) -> int:\n if not nums: return 0\n dp = None\n for num in nums:\n if dp is None:\n dp = [num]*3\n continue\n dp[0], dp[1] = max(num, dp[0]*num, dp[1]*num), min(num, dp[1]*num, dp[0]*num)\n dp[2] = max(dp[2], dp[0])\n return dp[2]\n" }, { "alpha_fraction": 0.5508885383605957, "alphanum_fraction": 0.5508885383605957, "avg_line_length": 43.14285659790039, "blob_id": "76e0a522d38d5cfbb70789e4cd75a2716df22e90", "content_id": "a7f0c8e2a5afa635896f05034252287e0143c24d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 619, "license_type": "no_license", "max_line_length": 87, "num_lines": 14, "path": "/lc113_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]:\n rslt = []\n def backtracking(root, val, path):\n if not root.left and not root.right and val == targetSum and path:\n rslt.append(path)\n else:\n if root.left:\n backtracking(root.left, val+root.left.val, path+[root.left.val])\n if root.right:\n backtracking(root.right, val+root.right.val, path+[root.right.val])\n if not root: return rslt\n backtracking(root, root.val, [root.val])\n return rslt \n" }, { "alpha_fraction": 0.48457351326942444, "alphanum_fraction": 0.49637022614479065, "avg_line_length": 38.35714340209961, "blob_id": "a29711a19fc22172cd4e349f4dd8ded5ef90efe0", "content_id": "2f1735adcb52c36070c847d88c5287ec2fec3932", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1102, "license_type": "no_license", "max_line_length": 80, "num_lines": 28, "path": "/lc889_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:\n if not pre or not post: return None\n root = TreeNode(pre[0])\n if len(pre) > 1:\n idx = post.index(pre[1])\n root.left = self.constructFromPrePost(pre[1:idx+2], post[:idx+1])\n root.right = self.constructFromPrePost(pre[idx+2:], post[idx+1:-1])\n return root\n \nclass Solution:\n def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode:\n nodemap = {val:i for i, val in enumerate(post)}\n stk, root = [], None\n for val in pre:\n if not root:\n root = TreeNode(val)\n stk.append(root)\n else:\n temp = TreeNode(val)\n if nodemap[val] < nodemap[stk[-1].val]:\n stk[-1].left = temp\n else:\n while stk and nodemap[val] > nodemap[stk[-1].val]:\n last = stk.pop()\n stk[-1].right = temp\n stk.append(temp)\n return root\n" }, { "alpha_fraction": 0.48433613777160645, "alphanum_fraction": 0.4868224859237671, "avg_line_length": 40.04081726074219, "blob_id": "25f87e19f55ad08b1c66e952747420e3a651e3eb", "content_id": "58b405ffa58f7825f049afe47cd70d004eed6d44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2011, "license_type": "no_license", "max_line_length": 96, "num_lines": 49, "path": "/lc126_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n if not wordList or endWord not in wordList: return []\n l, word_map, visited = len(beginWord), collections.defaultdict(list), set()\n for word in wordList:\n for i in range(l):\n word_map[word[:i]+\"*\"+word[i+1:]].append(word)\n dque = collections.deque([[beginWord]])\n rslt = []\n while dque:\n size = len(dque)\n for _ in range(size):\n cands = dque.popleft()\n curr = cands[-1]\n visited.add(curr)\n for i in range(l):\n for word in word_map[curr[:i]+\"*\"+curr[i+1:]]:\n if word == endWord:\n rslt.append(cands+[word])\n break\n if word not in visited:\n dque.append(cands+[word])\n\n if rslt:\n break\n return rslt\n\nclass Solution:\n def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:\n words, wordmap, l = set(wordList), collections.defaultdict(list), len(beginWord)\n if endWord not in words: return []\n for word in wordList:\n for i in range(l):\n wordmap[word[:i]+\"*\"+word[i+1:]].append(word)\n\n layer, visited = collections.defaultdict(list), set()\n layer[beginWord].append([beginWord])\n while layer:\n newlayer = collections.defaultdict(list)\n for word in layer:\n if word == endWord:\n return layer[word]\n for i in range(l):\n for nxt in wordmap[word[:i]+\"*\"+word[i+1:]]:\n if nxt not in visited:\n newlayer[nxt] += [j + [nxt] for j in layer[word]]\n visited |= set(newlayer.keys())\n layer = newlayer\n return []\n" }, { "alpha_fraction": 0.47484663128852844, "alphanum_fraction": 0.48098158836364746, "avg_line_length": 37.80952453613281, "blob_id": "414530349e049c03de42a498be1335666dd81e06", "content_id": "24dd22bc5bd1c02645e2ecd0b64c21b86333c4dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 815, "license_type": "no_license", "max_line_length": 91, "num_lines": 21, "path": "/lc1192_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]:\n graph = collections.defaultdict(list)\n for start, end in connections:\n graph[start].append(end)\n graph[end].append(start)\n visited, rslt = {}, []\n def dfs(cur, pre, d):\n visited[cur] = d\n for end in graph[cur]:\n if end == pre:\n continue\n if end not in visited:\n visited[cur] = min(visited[cur], dfs(end, cur, d+1))\n else:\n visited[cur] = min(visited[cur], visited[end])\n if visited[cur] == d and pre != -1:\n rslt.append([pre, cur])\n return visited[cur]\n dfs(0, -1, 0)\n return rslt\n" }, { "alpha_fraction": 0.3712121248245239, "alphanum_fraction": 0.40656566619873047, "avg_line_length": 32, "blob_id": "e99a7a19391d4f9ec497bbe14ace34e90181c3bf", "content_id": "52ef043cf550ad7b944d5553b9945c42609ec5f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 73, "num_lines": 36, "path": "/lc1802_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxValue(self, n: int, index: int, maxSum: int) -> int:\n left = 0\n right = maxSum\n while left < right:\n mid = right - (right - left) // 2\n extra1 = mid - 1 - index\n extra1 = (extra1 + 1) * extra1 // 2 if extra1 > 0 else extra1\n extra2 = mid - 1 - (n - index - 1)\n extra2 = (extra2 + 1) * extra2 // 2 if extra2 > 0 else extra2\n lower = (mid - 1) * mid // 2 - extra1\n upper = (mid - 1) * mid // 2 - extra2\n if lower + mid + upper > maxSum:\n right = mid - 1\n else:\n left = mid\n return left\n\n\n def maxValue(self, n, index, maxSum):\n def test(a):\n b = max(a - index, 0)\n res = (a + b) * (a - b + 1) / 2\n b = max(a - ((n - 1) - index), 0)\n res += (a + b) * (a - b + 1) / 2\n return res - a\n\n maxSum -= n\n left, right = 0, maxSum\n while left < right:\n mid = (left + right + 1) / 2\n if test(mid) <= maxSum:\n left = mid\n else:\n right = mid - 1\n return left + 1\n" }, { "alpha_fraction": 0.4907894730567932, "alphanum_fraction": 0.4934210479259491, "avg_line_length": 39, "blob_id": "7eb69bc21e082423e0f1d3eb0029dc3b30d48fa0", "content_id": "f8ac6104cbe802eb4c73ecc45c56300ab55f0d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 760, "license_type": "no_license", "max_line_length": 129, "num_lines": 19, "path": "/lc1311_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def watchedVideosByFriends(self, watchedVideos: List[List[str]], friends: List[List[int]], id: int, level: int) -> List[str]:\n visited, dque = {id}, collections.deque([id])\n while dque:\n if level == 0:\n break\n size = len(dque)\n for _ in range(size):\n curr = dque.popleft()\n for nt in friends[curr]:\n if nt not in visited:\n visited.add(nt)\n dque.append(nt)\n level -= 1\n rslt = []\n while dque:\n rslt.extend(watchedVideos[dque.pop()])\n summary = collections.Counter(rslt)\n return sorted(summary.keys(), key = lambda x: (summary[x], x))\n" }, { "alpha_fraction": 0.44111111760139465, "alphanum_fraction": 0.4511111080646515, "avg_line_length": 33.61538314819336, "blob_id": "3d0102fef6868a1e1726eb52fb6478eb287a044f", "content_id": "c79ef07b9c226c7b8115f9f621a15380631c2eea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 900, "license_type": "no_license", "max_line_length": 59, "num_lines": 26, "path": "/lc22_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n rslt, m = [], 2*n\n def backtracking(curr, left, right):\n if left+right == m:\n rslt.append(curr)\n else:\n if left < m -left:\n backtracking(curr+\"(\", left + 1, right)\n if right < left:\n backtracking(curr+\")\", left, right+1)\n backtracking(\"\", 0, 0)\n return rslt\n\n def generateParenthesis(self, n: int) -> List[str]:\n rslt = []\n def backtracking(curr, left, right):\n if left + right == 0:\n rslt.append(curr)\n else:\n if left > 0:\n backtracking(curr+\"(\", left -1, right)\n if right > left:\n backtracking(curr+\")\", left, right-1)\n backtracking(\"\", n, n)\n return rslt\n" }, { "alpha_fraction": 0.509772002696991, "alphanum_fraction": 0.5146579742431641, "avg_line_length": 28.238094329833984, "blob_id": "0a81011d76fa8df05473f1331aa26b3302917052", "content_id": "10483d4ff30618aae3099426692e782c412077a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 73, "num_lines": 21, "path": "/lc92_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:\n snode = ListNode(0, head)\n left = snode\n for _ in range(m-1):\n left = left.next\n right = left.next\n for _ in range(n-m):\n pre = right\n right = right.next\n\n pre.next = right.next\n right.next = left.next\n left.next = right\n right = pre\n return snode.next\n" }, { "alpha_fraction": 0.46863189339637756, "alphanum_fraction": 0.47543463110923767, "avg_line_length": 31.268293380737305, "blob_id": "9ea4bf353096efe743e88cf6c80389ea5ffa91b1", "content_id": "36ea8443e1b8727476a4990f9996dcbd9d220b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1323, "license_type": "no_license", "max_line_length": 80, "num_lines": 41, "path": "/lc336_trie.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class TrieNode:\n def __init__(self):\n self.ch = {}\n self.cands = []\n self.idx = -1\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n def insert(self, word, idx):\n curr = self.root\n for i in range(len(word)-1, -1, -1):\n if word[:i+1] == word[:i+1][::-1]:\n curr.cands.append(idx)\n if word[i] not in curr.ch:\n curr.ch[word[i]] = TrieNode()\n curr = curr.ch[word[i]]\n curr.idx = idx\n curr.cands.append(idx)\n def search(self, word, idx):\n curr = self.root\n rslt = []\n for i in range(len(word)):\n if word[i:] == word[i:][::-1] and curr.idx != idx and curr.idx > -1:\n rslt.append([idx, curr.idx])\n ch = word[i]\n if ch not in curr.ch:\n return rslt\n curr = curr.ch[ch]\n for cand in curr.cands:\n if cand != idx:\n rslt.append([idx, cand])\n return rslt\nclass Solution:\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n paltrie = Trie()\n rslt = []\n for i, word in enumerate(words):\n paltrie.insert(word, i)\n for i, word in enumerate(words):\n rslt += paltrie.search(word, i)\n return rslt\n" }, { "alpha_fraction": 0.39676111936569214, "alphanum_fraction": 0.4170040488243103, "avg_line_length": 34.21428680419922, "blob_id": "da687103a560e098ee8c837d04c439b939f0a4d7", "content_id": "a6415665f2daa259d0a473d6ae89db6975112794", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 72, "num_lines": 14, "path": "/lc17_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def letterCombinations(self, digits: str) -> List[str]:\n if not digits: return []\n n, rslt = len(digits), []\n cmap = {\"2\":\"abc\", \"3\":\"def\", \"4\":\"ghi\",\n \"5\":\"jkl\", \"6\":\"mno\", \"7\":\"pqrs\", \"8\":\"tuv\", \"9\":\"wxyz\"}\n def btrack(i, curr):\n if i == n:\n rslt.append(curr)\n else:\n for c in cmap[digits[i]]:\n btrack(i+1, curr+c)\n btrack(0, \"\")\n return rslt \n" }, { "alpha_fraction": 0.4620155096054077, "alphanum_fraction": 0.46666666865348816, "avg_line_length": 34.83333206176758, "blob_id": "dc568d549e02e31d82081ef27dbf8405e7cba718", "content_id": "94ad041ed703e541c0ff4eacb1d92ed9c96c8e18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 645, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/lc1023_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def camelMatch(self, queries: List[str], pattern: str) -> List[bool]:\n rslt = []\n def backtracking(word, pattern):\n if not pattern:\n for c in word:\n if c.isupper():\n return False\n return True\n for i, c in enumerate(word):\n if c == pattern[0]:\n return backtracking(word[i+1:], pattern[1:])\n if c.isupper():\n return False\n return False\n for query in queries:\n rslt.append(backtracking(query, pattern))\n return rslt\n" }, { "alpha_fraction": 0.3623853325843811, "alphanum_fraction": 0.375, "avg_line_length": 29.068965911865234, "blob_id": "e20f126f41d78c20c06400cfd9ab9c166128b43d", "content_id": "92b54e9cb2f33113585efda18424af3b3e4d33d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 872, "license_type": "no_license", "max_line_length": 58, "num_lines": 29, "path": "/lc331_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n stk = []\n temp = preorder.split(\",\")\n i = 0\n while i < len(temp):\n if temp[i] == \"#\":\n if not stk or stk[-1] != \"#\":\n stk.append(\"#\")\n i += 1\n elif len(stk) < 2:\n return False\n else:\n stk.pop()\n stk.pop()\n else:\n stk.append(temp[i])\n i += 1\n return stk == [\"#\"]\n\nclass Solution:\n def isValidSerialization(self, preorder: str) -> bool:\n slot = 1\n for i, c in enumerate(preorder+\",\"):\n if c == \",\":\n slot -= 1\n if slot < 0: return False\n if preorder[i-1] != \"#\": slot += 2\n return slot == 0\n" }, { "alpha_fraction": 0.5209790468215942, "alphanum_fraction": 0.5314685106277466, "avg_line_length": 26.238094329833984, "blob_id": "9cee2216bdb8480051a93154b4933e1d345249a7", "content_id": "95bca8f86ae8099305c1bb0999cbef9c4dcccd44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 50, "num_lines": 21, "path": "/lc1381_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class CustomStack:\n\n def __init__(self, maxSize: int):\n self.cap = maxSize\n self.curSize = 0\n self.stack = [0]*maxSize\n\n def push(self, x: int) -> None:\n if self.curSize < self.cap:\n self.stack[self.curSize] = x\n self.curSize += 1\n\n def pop(self) -> int:\n if not self.curSize: return -1\n temp = self.stack[self.curSize-1]\n self.curSize -= 1\n return temp\n\n def increment(self, k: int, val: int) -> None:\n for i in range(min(k, self.curSize)):\n self.stack[i] += val\n" }, { "alpha_fraction": 0.3575129508972168, "alphanum_fraction": 0.3911917209625244, "avg_line_length": 28, "blob_id": "b31f357ea4dbe53e1eb0894fd50207c07a9f9e1c", "content_id": "41a4f9bfe468c4377a3ca09f3356ca173bd5cf7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 386, "license_type": "no_license", "max_line_length": 48, "num_lines": 13, "path": "/lc1567_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def getMaxLen(self, nums: List[int]) -> int:\n cp, cn =0, 0\n rslt = 0\n for num in nums:\n if num > 0:\n cp, cn = cp+1, cn+1 if cn else 0\n elif num < 0:\n cp, cn = cn+1 if cn else 0, cp+1\n else:\n cp, cn = 0, 0\n rslt = max(rslt, cp)\n return rslt\n \n" }, { "alpha_fraction": 0.5147679448127747, "alphanum_fraction": 0.5316455960273743, "avg_line_length": 38.5, "blob_id": "83f13843e5166251ce754219354b7c667b69653e", "content_id": "67d56853e574d31f903109cd5f4ef1b3846960b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/lc333_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def largestBSTSubtree(self, root: TreeNode) -> int:\n def helper(root):\n if not root: return 0, float(\"inf\"), -float(\"inf\")\n left = helper(root.left)\n right = helper(root.right)\n if left[2] < root.val < right[1]:\n return left[0]+right[0]+1, min(left[1], root.val), max(root.val, right[2])\n else:\n return max(left[0], right[0]), -float(\"inf\"), float(\"inf\")\n temp = helper(root)\n return temp[0]\n" }, { "alpha_fraction": 0.4273972511291504, "alphanum_fraction": 0.45068493485450745, "avg_line_length": 35.5, "blob_id": "02871df7e19a5ce14670f0ffd5358760b2d9ca9a", "content_id": "584a036bf8411a49e71d9b2a595608600b3b2ba7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/lc752_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def openLock(self, deadends: List[str], target: str) -> int:\n def neighbors(node):\n for i in range(4):\n t = int(node[i])\n for d in (-1, 1):\n y = (t+d)%10\n yield node[:i] + str(y) + node[i+1:]\n\n dd = set(deadends)\n queue, seen = collections.deque([('0000', 0 )]), {'0000'}\n while queue:\n node, depth = queue.popleft()\n if node == target: return depth\n if node in dd: continue\n for nei in neighbors(node):\n if nei not in seen and nei not in dd:\n seen.add(nei)\n queue.append((nei, depth+1))\n return -1\n" }, { "alpha_fraction": 0.3912484049797058, "alphanum_fraction": 0.41312742233276367, "avg_line_length": 28.884614944458008, "blob_id": "81fbade1841ef71c9c5791530a2b6d25625721a4", "content_id": "d41d3a96304d085f7434170cf4916e08baa6b8f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 777, "license_type": "no_license", "max_line_length": 55, "num_lines": 26, "path": "/lc279_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numSquares(self, n: int) -> int:\n cands = [i**2 for i in range(1, int(n**0.5)+1)]\n @lru_cache(None)\n def dfs(i):\n if i in cands:\n return 1\n rslt = float(\"inf\")\n for cand in cands:\n if cand > i:\n break\n rslt = min(rslt, dfs(i-cand)+1)\n return rslt\n return dfs(n)\n\nclass Solution:\n def numSquares(self, n: int) -> int:\n cands = [i*i for i in range(int(n**0.5) + 1)]\n dp = [float(\"inf\")]*(n+1)\n dp[0] = 0\n for i in range(1, n+1):\n for cand in cands:\n if i < cand:\n break\n dp[i] = min(dp[i], dp[i-cand] + 1)\n return dp[-1]\n" }, { "alpha_fraction": 0.48097825050354004, "alphanum_fraction": 0.4945652186870575, "avg_line_length": 35.79999923706055, "blob_id": "6355945b7d8243b917170249cd00c36ef0110d69", "content_id": "bbf9eaaee2a080d32c45c43b9f49d12ad357f4f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 64, "num_lines": 10, "path": "/lc503_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n if not nums: return nums\n rslt, stk = [-1]*len(nums), []\n for i in range(len(nums)-1, -len(nums), -1):\n while stk and stk[-1] <= nums[i]:\n stk.pop()\n if stk: rslt[i] = stk[-1]\n stk.append(nums[i])\n return rslt\n" }, { "alpha_fraction": 0.4274061918258667, "alphanum_fraction": 0.43882545828819275, "avg_line_length": 29.649999618530273, "blob_id": "2d32bf604a0501753dfdbe13e27ada3e5abb8b04", "content_id": "325228c05d02b45cabac575920cc6517b50fd401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 55, "num_lines": 20, "path": "/lc1675_heap.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumDeviation(self, nums: List[int]) -> int:\n heap = []\n left, right = float(\"inf\"), 0\n rslt = float(\"inf\")\n for num in nums:\n if num%2:\n num = num*2\n heapq.heappush(heap, -num)\n left = min(left, num)\n while True:\n right = -heapq.heappop(heap)\n if right-left < rslt:\n rslt = right-left\n if right%2 == 0:\n heapq.heappush(heap, -right//2)\n left = min(left, right//2)\n else:\n break\n return rslt\n" }, { "alpha_fraction": 0.44474393129348755, "alphanum_fraction": 0.4582210183143616, "avg_line_length": 32.727272033691406, "blob_id": "d70f2c787bd2d48978472b123496c243bef44bca", "content_id": "c609b9025e264e349e4e17c56bd5cd286e006359", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 371, "license_type": "no_license", "max_line_length": 54, "num_lines": 11, "path": "/lc962_stk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxWidthRamp(self, A: List[int]) -> int:\n stk = []\n for i, num in enumerate(A):\n if not stk or A[stk[-1]] > num:\n stk.append(i)\n rslt = 0\n for i, num in enumerate(A[::-1]):\n while stk and A[stk[-1]] <= num:\n rslt = max(rslt, len(A)-1-i-stk.pop())\n return rslt\n" }, { "alpha_fraction": 0.3875739574432373, "alphanum_fraction": 0.40532544255256653, "avg_line_length": 29.727272033691406, "blob_id": "3ff6bbeedf9cc51530a695f48270b10787abe679", "content_id": "3651a6895d55f13e12003ad9635ac82876e1356a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 48, "num_lines": 11, "path": "/lc856_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def scoreOfParentheses(self, s: str) -> int:\n count_right, rslt = 0, 0\n for i, c in enumerate(s):\n if c == \"(\":\n count_right += 1\n else:\n count_right -= 1\n if s[i-1] == '(':\n rslt += 2**count_right\n return rslt\n" }, { "alpha_fraction": 0.5015479922294617, "alphanum_fraction": 0.5139318704605103, "avg_line_length": 39.375, "blob_id": "8477fff05f4e4a26d969cccd833cc821a7d6f155", "content_id": "cfc305b18cf6f970eab8d41796c17e1b3dc7c8e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 323, "license_type": "no_license", "max_line_length": 80, "num_lines": 8, "path": "/lc1366_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def rankTeams(self, votes: List[str]) -> str:\n l = len(votes[0])\n mapping = {k: [0]*l for k in votes[0]}\n for vote in votes:\n for i, v in enumerate(vote):\n mapping[v][i] += 1\n return \"\".join(sorted(mapping.keys(), key = lambda x: (-mapping[x], x)))\n" }, { "alpha_fraction": 0.43018868565559387, "alphanum_fraction": 0.4377358555793762, "avg_line_length": 27.44444465637207, "blob_id": "ec92e925ad6984866381237375653f9547dc315e", "content_id": "45af675bfc4fd8b2c942840ed97e0fc9358d50eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/lc1608_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def specialArray(self, nums: List[int]) -> int:\n nums.sort()\n last, n = 0, len(nums)\n for i in range(n):\n if nums[i] >= n-i > last:\n return n-i\n last = nums[i]\n return -1\n \n" }, { "alpha_fraction": 0.47907325625419617, "alphanum_fraction": 0.4805680215358734, "avg_line_length": 28.733333587646484, "blob_id": "97c462a1af2ce3ac97450d18b275547d5b952513", "content_id": "4c6fd94cc5bdeb9a95044c8f874fc09e8a98d763", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1338, "license_type": "no_license", "max_line_length": 63, "num_lines": 45, "path": "/lc642_tire.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Trie:\n def __init__(self):\n self.root = {}\n def insert(self, word):\n curr = self.root\n for ch in word:\n if ch not in curr:\n curr[ch] = {}\n curr = curr[ch]\n curr[\"#\"] = word\n def search(self, prefix):\n curr = self.root\n for ch in prefix:\n if ch not in curr:\n return []\n curr = curr[ch]\n return self.findall(curr)\n def findall(self, curr):\n rslt = []\n for key in curr:\n if key == \"#\":\n rslt.append(curr[key])\n else:\n rslt += self.findall(curr[key])\n return rslt\nclass AutocompleteSystem:\n\n def __init__(self, sentences: List[str], times: List[int]):\n self.trie = Trie()\n self.hotmap = collections.defaultdict(int)\n for sentence, time in zip(sentences, times):\n self.trie.insert(sentence)\n self.hotmap[sentence] += time\n self.last = \"\"\n\n def input(self, c: str) -> List[str]:\n if c == \"#\":\n self.hotmap[self.last] += 1\n self.trie.insert(self.last)\n self.last = \"\"\n return []\n self.last += c\n rslt = self.trie.search(self.last)\n rslt.sort(key= lambda x: (-self.hotmap[x], x))\n return rslt[:3]\n" }, { "alpha_fraction": 0.4375, "alphanum_fraction": 0.5193014740943909, "avg_line_length": 40.846153259277344, "blob_id": "b00eadd281928300a07f34f64b4c9cde10fc7f19", "content_id": "68da9221101520053ee69f2ffb3abaf3f1430abd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1088, "license_type": "no_license", "max_line_length": 82, "num_lines": 26, "path": "/lc4_dandc.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n if not nums1 and not nums2:\n return None\n l1, l2 = len(nums1), len(nums2)\n if (l1+l2)%2 ==1:\n return self.findKth(nums1, nums2, 0, 0, (l1+l2)//2 + 1)\n else:\n left = self.findKth(nums1, nums2, 0, 0, (l1+l2)//2)\n right = self.findKth(nums1, nums2, 0, 0, (l1+l2)//2+1)\n return (left+right)/2\n\n def findKth(self, nums1, nums2, loc1, loc2, k):\n if loc1 == len(nums1):\n return nums2[loc2 + k -1]\n if loc2 == len(nums2):\n return nums1[loc1 + k -1]\n if k == 1:\n return min(nums1[loc1], nums2[loc2])\n\n p1 = nums1[loc1 + k//2 - 1] if loc1 + k//2 - 1 < len(nums1) else None\n p2 = nums2[loc2 + k//2 - 1] if loc2 + k//2 - 1 < len(nums2) else None\n\n if p2 is None or (p1 is not None and p1 < p2):\n return self.findKth(nums1, nums2, loc1+k//2, loc2, k - k//2)\n return self.findKth(nums1, nums2, loc1, loc2 + k//2, k - k//2)\n" }, { "alpha_fraction": 0.5185185074806213, "alphanum_fraction": 0.5303703546524048, "avg_line_length": 47.21428680419922, "blob_id": "5063b47e51aa5c93941bb90b2ac09f6221990766", "content_id": "def42b414f709a874ceac87e6d3ef232e7be940f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 76, "num_lines": 14, "path": "/lc1438_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestSubarray(self, nums: List[int], limit: int) -> int:\n dque_max, dque_min, l= collections.deque(), collections.deque(), 0\n for num in nums:\n while dque_max and dque_max[-1] < num: dque_max.pop()\n while dque_min and dque_min[-1] > num: dque_min.pop()\n dque_max.append(num)\n dque_min.append(num)\n if dque_max and dque_min and dque_max[0] - dque_min[0] > limit:\n if dque_max[0] == nums[l]: dque_max.popleft()\n if dque_min[0] == nums[l]: dque_min.popleft()\n l += 1\n # print(dque_max, dque_min, l)\n return len(nums)-l\n" }, { "alpha_fraction": 0.4505050480365753, "alphanum_fraction": 0.4727272689342499, "avg_line_length": 37.07692337036133, "blob_id": "d470f372cf49088c7c349aa2086fbfbae301a5de", "content_id": "03cac9048932ec54fb22cfa4ad29099bea5afd41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 64, "num_lines": 13, "path": "/lc1856_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSumMinProduct(self, nums: List[int]) -> int:\n n = len(nums)\n presum = [0]*(n+1)\n for i in range(n): presum[i+1] = presum[i] + nums[i]\n stack, rslt = [], 0\n for i, h in enumerate(nums+[0]):\n start = i\n while stack and stack[-1][1] >= h:\n start, mh = stack.pop()\n rslt = max(rslt, (presum[i] - presum[start])*mh)\n stack.append((start, h))\n return rslt %(10**9 + 7)\n" }, { "alpha_fraction": 0.4228723347187042, "alphanum_fraction": 0.4441489279270172, "avg_line_length": 30.33333396911621, "blob_id": "aa390039d86e6031c1c63c008938a9833d03151a", "content_id": "180cb839d7195c026df5339c2041c25cc16e81a4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 67, "num_lines": 12, "path": "/lc56_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def merge(self, intervals: List[List[int]]) -> List[List[int]]:\n intervals.sort()\n rslt = []\n for it in intervals:\n if not rslt:\n rslt.append(it)\n elif it[0] <= rslt[-1][1]:\n rslt[-1][1] = max(rslt[-1][1], it[1])\n else:\n rslt.append(it)\n return rslt\n" }, { "alpha_fraction": 0.44871795177459717, "alphanum_fraction": 0.4643874764442444, "avg_line_length": 30.909090042114258, "blob_id": "0f93029dba7bd7071b745fa7c2accec0e54bc9ba", "content_id": "28aad7423f3c0a13939d188ab3e1119c8754ae13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 702, "license_type": "no_license", "max_line_length": 64, "num_lines": 22, "path": "/lc452_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points.sort(key = lambda x: x[1])\n rslt, last = 0, -float(\"inf\")\n for point in points:\n if point[0] <= last:\n last = min(last, point[1])\n else:\n rslt += 1\n last = point[1]\n return rslt\n\n def findMinArrowShots(self, points: List[List[int]]) -> int:\n points.sort(reverse = True)\n rslt, last = 0, float(\"inf\")\n for point in points:\n if point[1] >= last:\n last = max(last, point[0])\n else:\n rslt += 1\n last = point[0]\n return rslt\n" }, { "alpha_fraction": 0.5090609788894653, "alphanum_fraction": 0.5255354046821594, "avg_line_length": 42.35714340209961, "blob_id": "58259b5781c4e63c44c91634ee3a4ba8a41115ed", "content_id": "a8f3befd8951ecfce7198a35fb72bf00edc1a84f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 111, "num_lines": 14, "path": "/lc986_arrary.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:\n idxa, idxb, na, nb = 0, 0, len(firstList), len(secondList)\n rslt = []\n while idxa < na and idxb < nb:\n leftb = max(firstList[idxa][0], secondList[idxb][0])\n rightb = min(firstList[idxa][1], secondList[idxb][1])\n if leftb <= rightb:\n rslt.append([leftb, rightb])\n if firstList[idxa][1] < secondList[idxb][1]:\n idxa += 1\n else:\n idxb += 1\n return rslt\n" }, { "alpha_fraction": 0.43906810879707336, "alphanum_fraction": 0.4534050226211548, "avg_line_length": 33.875, "blob_id": "a1a48b84185efda7eb5f505f909f89c4d47f3e0b", "content_id": "e555e13e7e08b198d6aea0009293fbef6c458ef6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "no_license", "max_line_length": 69, "num_lines": 16, "path": "/lc1406_minmax.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def stoneGameIII(self, stoneValue: List[int]) -> str:\n memo = {}\n def dfs(i):\n if i in memo:\n return memo[i]\n if i >= len(stoneValue):\n return 0\n rslt = float(\"-inf\")\n for j in range(3):\n if i+j+1 > len(stoneValue): break\n rslt = max(rslt, sum(stoneValue[i:i+j+1])-dfs(i+j+1))\n memo[i] = rslt\n return rslt\n temp = dfs(0)\n return \"Tie\" if temp == 0 else \"Alice\" if temp > 0 else \"Bob\"\n" }, { "alpha_fraction": 0.4414893686771393, "alphanum_fraction": 0.4541223347187042, "avg_line_length": 29.693878173828125, "blob_id": "be7d0a57575019ece4dba3df7b8e8143103491ed", "content_id": "054cae6ca38e1496bab6d9cd0583b465f9c7f0b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 54, "num_lines": 49, "path": "/lc421_trie.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Trie:\n def __init__(self, L):\n self.root = TrieNode()\n self.maskL = L\n def insert(self, num):\n mask = 1 << self.maskL\n curr = self.root\n while mask:\n key = 1 if num & mask else 0\n if key not in curr.children:\n curr.children[key] = TrieNode()\n curr = curr.children[key]\n mask >>= 1\n def search(self, num):\n mask = 1 << self.maskL\n curr, rslt = self.root, 0\n while mask:\n key = 0 if num&mask else 1\n if key in curr.children:\n curr = curr.children[key]\n rslt |= mask\n else:\n curr = curr.children[1-key]\n mask >>= 1\n return rslt\nclass Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n L = len(bin(max(nums)))-2\n solTrie, rslt = Trie(L), 0\n for num in nums:\n solTrie.insert(num)\n rslt = max(rslt, solTrie.search(num))\n return rslt\n\nclass Solution:\n def findMaximumXOR(self, nums: List[int]) -> int:\n l = len(bin(max(nums)))-2\n rslt = 0\n for i in range(l-1, -1, -1):\n mask = rslt | 1 << i\n used = set()\n for num in nums:\n curr = num & mask\n # curr ^ mask ^ curr = 0 ^ mask = mask\n if (curr ^ mask) in used:\n rslt = mask\n break\n used.add(curr)\n return rslt\n" }, { "alpha_fraction": 0.4125683009624481, "alphanum_fraction": 0.43852460384368896, "avg_line_length": 32.272727966308594, "blob_id": "28cbdd731543f10e8132d6e276f619fdc7ba781b", "content_id": "c6091e55701f1791736ebc81436bab21aad9fd0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 732, "license_type": "no_license", "max_line_length": 70, "num_lines": 22, "path": "/lc474_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findMaxForm(self, strs, m, n):\n xy = [[s.count(\"0\"), s.count(\"1\")] for s in strs]\n\n @lru_cache(None)\n\n def dp(mm, nn, kk):\n if mm < 0 or nn < 0: return -float(\"inf\")\n if kk == len(strs): return 0\n x, y = xy[kk]\n return max(1 + dp(mm-x, nn-y, kk + 1), dp(mm, nn, kk + 1))\n\n return dp(m, n, 0)\n\n def findMaxForm(self, strs, m, n):\n dp = [[0]*(m+1) for _ in range(n+1)]\n for s in strs:\n ones, zeros = s.count(\"1\"), s.count(\"0\")\n for i in range(n, ones-1, -1):\n for j in range(m, zeros-1, -1):\n dp[i][j] = max(dp[i][j], dp[i-ones][j-zeros]+1)\n return dp[n][m]\n" }, { "alpha_fraction": 0.39358600974082947, "alphanum_fraction": 0.4169096350669861, "avg_line_length": 30.18181800842285, "blob_id": "a5300bca372db952b2a9ec6f5a240a3005eda9f6", "content_id": "ee7c214669162040dd4f9992f8776ea2bc6f12c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "no_license", "max_line_length": 55, "num_lines": 11, "path": "/lc1004_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestOnes(self, A: List[int], K: int) -> int:\n left, cnt, rslt = 0, 0, 0\n for right, c in enumerate(A):\n if c == 0:\n cnt += 1\n while cnt > K:\n cnt -= 1-A[left]\n left += 1\n rslt = max(rslt, right-left + 1)\n return rslt\n" }, { "alpha_fraction": 0.47130435705184937, "alphanum_fraction": 0.47652173042297363, "avg_line_length": 34.9375, "blob_id": "5e1d6f90636874be648e952568c697c72bc8b69c", "content_id": "14b61d5b26ac7c6a9d8ee49d68da64dae8419111", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 575, "license_type": "no_license", "max_line_length": 97, "num_lines": 16, "path": "/lc1644_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n self.mark = 0\n def dfs(root, p, q):\n if not root: return None\n left = dfs(root.left, p, q)\n right = dfs(root.right, p, q)\n if root == p or root == q:\n self.mark += 1\n return root\n if left and right:\n return root\n else:\n return left or right\n rslt = dfs(root, p, q)\n return rslt if self.mark == 2 else None\n" }, { "alpha_fraction": 0.37877094745635986, "alphanum_fraction": 0.40223464369773865, "avg_line_length": 26.96875, "blob_id": "66c6ba48da9a232facb5e2f7fdadfbd014835162", "content_id": "dd92699c3005642a22363c6addf9cd390530dbdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "no_license", "max_line_length": 64, "num_lines": 32, "path": "/lc1248_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n left, rslt, last = 0, 0, 0\n for right, num in enumerate(nums):\n if num%2 == 1:\n k -= 1\n last = 0\n while k == 0:\n last += 1\n k += nums[left]%2\n left += 1\n rslt += last\n return rslt\n\n\n\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n left, rslt, count = 0, 0, 0\n for right, num in enumerate(nums):\n count += num%2\n while count > k:\n count -= nums[left]%2\n left += 1\n temp = left\n while count == k:\n count -= nums[temp] % 2\n rslt += 1\n temp += 1\n if temp > left:\n count += 1\n return rslt\n" }, { "alpha_fraction": 0.3758865296840668, "alphanum_fraction": 0.38770684599876404, "avg_line_length": 29.214284896850586, "blob_id": "85047e8430feb409f98faf3bc3785967bd8c1eca", "content_id": "a917a2a12a045177fe957f1f63d5af9ceef79099", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 65, "num_lines": 14, "path": "/lc375_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def getMoneyAmount(self, n: int) -> int:\n memo = {}\n def dfs(i, j):\n if (i, j) in memo:\n return memo[(i, j)]\n if i >= j:\n return 0\n rslt = n**n\n for t in range(i, j+1):\n rslt = min(rslt, t+max(dfs(i, t-1), dfs(t+1, j)))\n memo[(i,j)] = rslt\n return rslt\n return dfs(1, n)\n" }, { "alpha_fraction": 0.5829383730888367, "alphanum_fraction": 0.6050552725791931, "avg_line_length": 36.235294342041016, "blob_id": "3172ee72ef6567947d4c1669eb18e242c9349728", "content_id": "c80d8bd6450cb9e7a74a30c2458c7dca7e539c83", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 633, "license_type": "no_license", "max_line_length": 111, "num_lines": 17, "path": "/lc1348_hash.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class TweetCounts:\n\n def __init__(self):\n self.maps = collections.defaultdict(list)\n\n def recordTweet(self, tweetName: str, time: int) -> None:\n # dictionary of list\n self.maps[tweetName].append(time)\n\n\n def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:\n chunk_size = {\"minute\": 60, \"hour\":3600, \"day\":86400}\n rslt = [0]*((endTime-startTime)//chunk_size[freq]+1)\n for time in self.maps[tweetName]:\n if startTime <= time <= endTime:\n rslt[(time-startTime)//chunk_size[freq]] +=1\n return rslt\n" }, { "alpha_fraction": 0.48439618945121765, "alphanum_fraction": 0.4993215799331665, "avg_line_length": 35.849998474121094, "blob_id": "975cfcab95805c15b54eb657fac1abf17f6308ca", "content_id": "b1a99c6d90526fb4b0fc2b3e93cacbad5a106394", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1474, "license_type": "no_license", "max_line_length": 84, "num_lines": 40, "path": "/lc1307_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isSolvable(self, words: list[str], result: str) -> bool:\n max_woerd_len = max(map(len, words))\n if max_woerd_len < len(result) - 1:\n return False\n if max_woerd_len > len(result):\n return False\n\n words = words + [result]\n first_letters = set(word[0] for word in words if len(word) > 1)\n cols, rows = len(result), len(words)\n letter_to_digits = {}\n\n def search(col: int, row: int, carry: int) -> bool:\n if col == cols:\n return carry == 0\n if row == rows:\n quotient, reminder = divmod(carry, 10)\n return reminder == 0 and search(col + 1, 0, quotient)\n\n word = words[row]\n if col >= len(word):\n return search(col, row + 1, carry)\n\n letter = word[~col]\n sign = 1 if row < (rows - 1) else -1\n\n if letter in letter_to_digits:\n return search(col, row + 1, carry + sign * letter_to_digits[letter])\n\n init_digit = 1 if letter in first_letters else 0\n for digit in range(init_digit, 10):\n if digit not in letter_to_digits.values():\n letter_to_digits[letter] = digit\n if search(col, row + 1, carry + sign * digit):\n return True\n del letter_to_digits[letter]\n return False\n\n return search(0, 0, 0)\n" }, { "alpha_fraction": 0.4791666567325592, "alphanum_fraction": 0.4886363744735718, "avg_line_length": 32, "blob_id": "4feae26ee93c0ce1a97681ecc69c34e26bae911f", "content_id": "d0f6da833bb10b8a729cc491aef8a39dc3e064aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 528, "license_type": "no_license", "max_line_length": 58, "num_lines": 16, "path": "/lc437_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pathSum(self, root: TreeNode, sum: int) -> int:\n def preorder(node, curr):\n if not node:\n return\n curr += node.val\n if curr == sum:\n self.count += 1\n self.count += maps[curr-sum]\n maps[curr] += 1\n preorder(node.left, curr)\n preorder(node.right, curr)\n maps[curr] -= 1\n self.count, maps = 0, collections.defaultdict(int)\n preorder(root, 0)\n return self.count\n" }, { "alpha_fraction": 0.43178170919418335, "alphanum_fraction": 0.4365971088409424, "avg_line_length": 27.31818199157715, "blob_id": "73e48dbc0947267cbae8328175f6ef2bd7c269c4", "content_id": "cf5451be7a61a321d958436e28842d25e80b918f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1246, "license_type": "no_license", "max_line_length": 60, "num_lines": 44, "path": "/lc297_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Codec:\n\n def serialize(self, root):\n \"\"\"Encodes a tree to a single string.\n\n :type root: TreeNode\n :rtype: str\n \"\"\"\n if not root: return \"\"\n dqueue = collections.deque([root])\n rslt = []\n while dqueue:\n temp = dqueue.popleft()\n if temp:\n rslt.append(str(temp.val))\n dqueue.append(temp.left)\n dqueue.append(temp.right)\n else:\n rslt.append(\"\")\n return \",\".join(rslt)\n\n def deserialize(self, data):\n \"\"\"Decodes your encoded data to tree.\n\n :type data: str\n :rtype: TreeNode\n \"\"\"\n dqueue = collections.deque([])\n root, check = None, 0\n for val in data.split(\",\"):\n temp = TreeNode(int(val)) if val != \"\" else None\n if not root:\n root = temp\n dqueue.append(root)\n else:\n if check == 0:\n dqueue[0].left = temp\n check += 1\n else:\n dqueue[0].right = temp\n dqueue.popleft()\n check = 0\n if temp: dqueue.append(temp)\n return root\n" }, { "alpha_fraction": 0.33888888359069824, "alphanum_fraction": 0.3611111044883728, "avg_line_length": 31.727272033691406, "blob_id": "4d356af250a02c80ed821aef44c2d3499411bbf0", "content_id": "330c966139698896538bb30abf70c3717fa0ae77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 720, "license_type": "no_license", "max_line_length": 68, "num_lines": 22, "path": "/lc1593_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxUniqueSplit(self, s: str) -> int:\n dp = [0]*(len(s)+1)\n def backtracking(i, c, seen):\n if dp[i] > 0 and dp[i] > c + 1 or len(s)-i + c < dp[-1]:\n return\n if i == len(s):\n dp[-1] = max(dp[-1], c)\n return\n for j in range(i+1, len(s)+1):\n if s[i:j] in seen:\n dp[j-1] = c\n backtracking(j, c, seen)\n else:\n dp[j-1] = c+1\n seen.add(s[i:j])\n backtracking(j,c+1, seen)\n seen.remove(s[i:j])\n return\n backtracking(0, 0, set())\n\n return dp[-1]\n" }, { "alpha_fraction": 0.4280821979045868, "alphanum_fraction": 0.4497717022895813, "avg_line_length": 35.29166793823242, "blob_id": "495d14fdf06bc15e3a6ecaadf8caf9a4fa2df27d", "content_id": "2a7e23f2b73ca7c33d922b56313878bb4f3169d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 876, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/lc216_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n if n < k*1 or n > k*9: return []\n rslt = []\n def backtracking(i, n, curr):\n if n == 0 and len(curr) == k:\n rslt.append(curr)\n elif len(curr) < k and i < 10:\n for j in range(i, 10):\n backtracking(j+1, n-j, curr + [j])\n backtracking(1, n, [])\n return rslt\n\n def combinationSum3(self, k: int, n: int) -> List[List[int]]:\n if n < k*1 or n > k*9: return []\n rslt = []\n def backtracking(i, n, curr):\n if n == 0 and len(curr) == k:\n rslt.append(curr)\n elif len(curr) < k and i < 10:\n backtracking(i+1, n, curr)\n backtracking(i+1, n-i, curr + [i])\n backtracking(1, n, [])\n return rslt\n \n" }, { "alpha_fraction": 0.4378320872783661, "alphanum_fraction": 0.4495217800140381, "avg_line_length": 39.91304397583008, "blob_id": "a3935ff07d39e615b36be6adf55282b4bef44d84", "content_id": "4842307d1f8a705b6e1a8e65b8f6c709ed47a652", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 941, "license_type": "no_license", "max_line_length": 114, "num_lines": 23, "path": "/lc417_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def pacificAtlantic(self, matrix: List[List[int]]) -> List[List[int]]:\n if not matrix: return []\n pdque, adque = collections.deque(), collections.deque()\n n, m = len(matrix), len(matrix[0])\n for i in range(n):\n pdque.append((i, 0))\n adque.append((i, m-1))\n for j in range(m):\n pdque.append((0, j))\n adque.append((n-1, j))\n def bfs(queue):\n visited = set()\n while queue:\n x, y = queue.popleft()\n if (x, y) in visited:\n continue\n visited.add((x,y))\n for nx, ny in [(x-1, y), (x+1, y), (x, y+1), (x, y-1)]:\n if 0 <= nx < n and 0 <= ny < m and matrix[nx][ny] >= matrix[x][y] and (nx, ny) not in visited:\n queue.append((nx, ny))\n return visited\n return bfs(pdque) & bfs(adque)\n" }, { "alpha_fraction": 0.4260089695453644, "alphanum_fraction": 0.439461886882782, "avg_line_length": 29.758621215820312, "blob_id": "2d2bb1c9f98902a76478de501ac15c717470523c", "content_id": "6381975c9d644f53fd9a93bc712fb2212450908f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 70, "num_lines": 29, "path": "/lc1283_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n left, right = 1, sum(nums)\n while left <= right:\n mid = (left + right)//2\n rslt = sum(ceil(x/mid) for x in nums)\n if rslt > threshold:\n left = mid\n else:\n right = mid - 1\n if mid == (left+right)//2:\n left += 1\n return left\n\nclass Solution:\n def smallestDivisor(self, nums: List[int], threshold: int) -> int:\n def check(i):\n rslt = 0\n for n in nums:\n rslt += (n-1)//i + 1\n return rslt\n left, right = 1, max(nums)\n while left <= right:\n mid = (left + right)//2\n if check(mid) <= threshold:\n right = mid -1\n else:\n left = mid + 1\n return left\n" }, { "alpha_fraction": 0.4781420826911926, "alphanum_fraction": 0.4890710413455963, "avg_line_length": 35.599998474121094, "blob_id": "5520e513fd3829848a2965f46447a64a2bbb895a", "content_id": "1b07c407d39f65d00926004e701111357e41bbb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/lc84_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n stack, rslt = [], 0\n for i, h in enumerate(heights+[0]):\n start = i\n while stack and stack[-1][1] >= h:\n start, mh = stack.pop()\n rslt = max(rslt, (i - start)*mh)\n stack.append((start, h))\n return rslt\n" }, { "alpha_fraction": 0.32870370149612427, "alphanum_fraction": 0.33217594027519226, "avg_line_length": 27.799999237060547, "blob_id": "32ae75ff6c120b022c29300856f3cde3d08a99a9", "content_id": "0a9dfe9fdfc506fa76e85133e72d112deecf9667", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 864, "license_type": "no_license", "max_line_length": 57, "num_lines": 30, "path": "/lc227_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def calculate(self, s: str) -> int:\n stk, last, op = [], \"\", None\n for c in s+\"+\":\n if c == \" \": continue\n if c.isdigit():\n last = last+c if last else c\n else:\n if op == \"*\":\n stk.pop()\n stk.append(int(stk.pop())*int(last))\n elif op == \"/\":\n stk.pop()\n stk.append(int(stk.pop())//int(last))\n else:\n stk.append(last)\n stk.append(c)\n op = c\n last = \"\"\n rslt, last = 0, 0\n\n while stk:\n temp = stk.pop()\n if temp == \"-\":\n rslt -= 2*last\n elif temp != \"+\":\n last = int(temp)\n rslt += last\n\n return rslt\n" }, { "alpha_fraction": 0.37142857909202576, "alphanum_fraction": 0.37460318207740784, "avg_line_length": 30.5, "blob_id": "417f0dd0a82ed1643aaf0bb45d2444235cd44235", "content_id": "0a7308dbcaf5aa87a0710548cd2ae8ea9a30b6e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/lc385_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def deserialize(self, s: str) -> NestedInteger:\n stk, last, curr = [], \"\", None\n for c in s:\n if c in \",]\":\n if last:\n stk[-1].add(NestedInteger(int(last)))\n last = \"\"\n if c == \"]\":\n rslt = stk.pop()\n elif c == \"[\":\n temp = NestedInteger()\n if stk:\n stk[-1].add(temp)\n stk.append(temp)\n else:\n last += c\n if not stk and last:\n return NestedInteger(int(last))\n return rslt\n" }, { "alpha_fraction": 0.459940642118454, "alphanum_fraction": 0.4658753573894501, "avg_line_length": 32.70000076293945, "blob_id": "96cfca0c76df156faaa61223b5cfd088279c77a6", "content_id": "0d188a1077520b500b42fc17ca958cd62a347313", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 59, "num_lines": 10, "path": "/lc739_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def dailyTemperatures(self, T: List[int]) -> List[int]:\n if not T: return T\n stk, rslt = [], [0]*len(T)\n for i, t in enumerate(T):\n while stk and t > T[stk[-1]]:\n pre_id = stk.pop()\n rslt[pre_id] = i - pre_id\n stk.append(i)\n return rslt\n" }, { "alpha_fraction": 0.35686779022216797, "alphanum_fraction": 0.3671373426914215, "avg_line_length": 29.31999969482422, "blob_id": "10f20e02fcfbc38e0e0b7c0d759327803c56c16c", "content_id": "39b3e339b17e251353784620e6876aa0e9747fcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 57, "num_lines": 25, "path": "/lc410_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def splitArray(self, nums: List[int], m: int) -> int:\n left, right = 0, 0\n n = len(nums)\n for i in range(n):\n right += nums[i]\n if left < nums[i]: left = nums[i]\n rslt = right\n while left <= right:\n mid = (left + right)//2\n total = 0\n count = 0\n # check if is a viable mid\n for i in range(n):\n if total + nums[i] > mid:\n count += 1\n total = nums[i]\n else:\n total += nums[i]\n if count < m:\n rslt = min(rslt, mid)\n right = mid - 1\n else:\n left = mid + 1\n return rslt\n \n" }, { "alpha_fraction": 0.3499627709388733, "alphanum_fraction": 0.3708116114139557, "avg_line_length": 26.40816307067871, "blob_id": "a7125d6d2d838d2fe55cbe6e6877b85c9fb7fd95", "content_id": "be33ae9c95d1179b9fb4583a97f8ccd6f6b1166f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1343, "license_type": "no_license", "max_line_length": 56, "num_lines": 49, "path": "/lc115_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "#dfs+memo\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n memo = {}\n def dfs(i_s, j_t):\n if (i_s, j_t) in memo:\n return memo[(i_s,j_t)]\n if j_t == len(t):\n temp = 1\n elif i_s == len(s):\n temp = 0\n elif s[i_s] == t[j_t]:\n temp = dfs(i_s+1, j_t+1)+dfs(i_s+1, j_t)\n else:\n temp = dfs(i_s+1, j_t)\n memo[(i_s, j_t)] = temp\n return temp\n return dfs(0, 0)\n# 1-d dp\n\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n dp = [0]*(len(t)+1)\n dp[0] = 1\n for i in range(len(s)):\n temp = [1]*(len(t)+1)\n for j in range(len(t)):\n temp[j+1] = dp[j+1]\n if s[i] == t[j]:\n temp[j+1] += dp[j]\n dp = temp\n return dp[-1]\n\n\n\nclass Solution:\n def numDistinct(self, s: str, t: str) -> int:\n self.rslt = 0\n @lru_cache(None)\n def dfs(i_s, j_t):\n if j_t == len(t):\n return 1\n if i_s == len(s):\n return 0\n if s[i_s] == t[j_t]:\n return dfs(i_s+1, j_t+1)+dfs(i_s+1, j_t)\n else:\n return dfs(i_s+1, j_t)\n return dfs(0, 0)\n" }, { "alpha_fraction": 0.4312354326248169, "alphanum_fraction": 0.4428904354572296, "avg_line_length": 34.75, "blob_id": "6995247e91c8b96a6fae8cc5928f7c36b762ff20", "content_id": "8620617faafc1f84e3f1726650ffeb9e8c3b48b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 429, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/lc402_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeKdigits(self, num: str, k: int) -> str:\n if k >= len(num): return \"0\"\n stk, temp= [], k\n for i, c in enumerate(num):\n while stk and temp > 0 and stk[-1] > c:\n stk.pop()\n temp -= 1\n if temp == 0:\n return str(int(\"\".join(stk)+num[i:]))\n stk.append(c)\n return str(int(\"\".join(stk[:len(num)-k])))\n" }, { "alpha_fraction": 0.4683684706687927, "alphanum_fraction": 0.4772475063800812, "avg_line_length": 28.064516067504883, "blob_id": "09986d18f0df56a33440e8de3d634c990c6f3825", "content_id": "841b0a3b7a35abb85b77e802d416b303874f20bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 901, "license_type": "no_license", "max_line_length": 72, "num_lines": 31, "path": "/lc23_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n if not lists: return None\n interval = 1\n n = len(lists)\n while interval < n:\n for i in range(0, n-interval, 2*interval):\n lists[i] = self.merge2Lists(lists[i], lists[i+interval])\n interval *= 2\n return lists[0]\n\n def merge2Lists(self, a, b):\n snode = curr = ListNode()\n while a and b:\n if a.val < b.val:\n curr.next = a\n a = a.next\n else:\n curr.next = b\n b = b.next\n curr = curr.next\n if a:\n curr.next = a\n else:\n curr.next = b\n return snode.next\n" }, { "alpha_fraction": 0.48367953300476074, "alphanum_fraction": 0.48961424827575684, "avg_line_length": 36.44444274902344, "blob_id": "c7b85cf2f9b711163d8311b56e3f801f1337110b", "content_id": "d15b9da19a9ab6c89fa79a0541441cbf00e4bd7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 87, "num_lines": 18, "path": "/lc1606_sortedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "from sortedcontainers import SortedList\nclass Solution:\n def busiestServers(self, k: int, arrival: List[int], load: List[int]) -> List[int]:\n freq = [0]*k\n n = len(arrival)\n busy = []\n free = SortedList(range(k))\n for i in range(n):\n while busy and busy[0][0] <= arrival[i]:\n t, si = heapq.heappop(busy)\n free.add(si)\n if free:\n idx = free.bisect_left(i%k)%len(free)\n s = free.pop(idx)\n freq[s] += 1\n heapq.heappush(busy, (arrival[i]+load[i], s))\n mx = max(freq)\n return [x for x in range(k) if freq[x] == mx]\n" }, { "alpha_fraction": 0.3953045606613159, "alphanum_fraction": 0.4029187858104706, "avg_line_length": 27.654544830322266, "blob_id": "c44d69ced6299e0c0ec1a1d131c7e5875b3785d0", "content_id": "582d17037b5737c41b6c9f36ee9d79fa8a0c71c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1576, "license_type": "no_license", "max_line_length": 50, "num_lines": 55, "path": "/lc300_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n @lru_cache(None)\n def dfs(i):\n temp = 1\n for j in range(i+1, len(nums)):\n if nums[j] > nums[i]:\n temp = max(temp, dfs(j)+1)\n return temp\n rslt = 0\n for i in range(len(nums)):\n rslt = max(rslt, dfs(i))\n return rslt\n\n def lengthOfLIS(self, nums: List[int]) -> int:\n sub = []\n for num in nums:\n idx = bisect.bisect_left(sub, num)\n if idx < len(sub):\n sub[idx] = num\n else:\n sub.append(num)\n return len(sub)\n \n def lengthOfLIS(self, nums:List[int]) -> int:\n n = len(nums)\n dp = [1]*n\n for i in range(n):\n for j in range(i):\n if dp[j] < dp[i]:\n dp[i] = max(dp[i], dp[j]+1)\n return max(dp)\n\n\n\n def lengthOfLIS(self, nums: List[int]) -> int:\n def bisearch(arr, target):\n left, right = 0, len(arr)-1\n while left <= right:\n mid = (left + right)//2\n if arr[mid] < target:\n left = mid\n else:\n right = mid - 1\n if (left+right)//2 == mid:\n left += 1\n return left\n sub = []\n for num in nums:\n idx = bisearch(sub, num)\n if idx < len(sub):\n sub[idx] = num\n else:\n sub.append(num)\n return len(sub)\n" }, { "alpha_fraction": 0.5076400637626648, "alphanum_fraction": 0.5178267955780029, "avg_line_length": 31.72222137451172, "blob_id": "e1f90d631bf0f52f203221e91bcd5f11405e558f", "content_id": "73a1b09813a7f1d70a3e71adededf0724a696bd6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 589, "license_type": "no_license", "max_line_length": 59, "num_lines": 18, "path": "/lc1019_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n# maintain a monotonic decreasing stack\nclass Solution:\n def nextLargerNodes(self, head: ListNode) -> List[int]:\n answer, stack, i = [], [], 0\n while head:\n while stack and stack[-1][0] < head.val:\n _, j = stack.pop()\n answer[j] = head.val\n stack.append((head.val, i))\n answer.append(0)\n head = head.next\n i = i+1\n return answer\n" }, { "alpha_fraction": 0.49862638115882874, "alphanum_fraction": 0.5096153616905212, "avg_line_length": 25, "blob_id": "7a7472ba0c8549b02b9643c5fad90f8a83d38927", "content_id": "854a819fa2c1d67d3f25fa0aa2555ff12ecb778c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 728, "license_type": "no_license", "max_line_length": 63, "num_lines": 28, "path": "/lc528_random.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n\n def __init__(self, w: List[int]):\n self.cumsum = []\n for i, n in enumerate(w):\n if i == 0: self.cumsum.append(n)\n else:\n self.cumsum.append(n + self.cumsum[-1])\n\n def pickIndex(self) -> int:\n t = random.randint(1, self.cumsum[-1])\n return self.binSearch(t)\n\n def binSearch(self, t):\n left, right = 0, len(self.cumsum)\n while left < right:\n mid = (left + right)//2\n if self.cumsum[mid] < t:\n left = mid+1\n else:\n right = mid\n return left\n\n\n\n# Your Solution object will be instantiated and called as such:\n# obj = Solution(w)\n# param_1 = obj.pickIndex()\n" }, { "alpha_fraction": 0.4324324429035187, "alphanum_fraction": 0.45945945382118225, "avg_line_length": 29.272727966308594, "blob_id": "fb95451b267c6f40d003a0ad9555b48801c455c2", "content_id": "64541f9488eb4ed5426bf4f63095bc729d037d6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 333, "license_type": "no_license", "max_line_length": 62, "num_lines": 11, "path": "/lc238_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n rslt = [1]*n\n for i in range(1, n):\n rslt[i] = rslt[i-1]*nums[i-1]\n curr = 1\n for i in range(n-2, -1, -1):\n curr *= nums[i+1]\n rslt[i] = rslt[i]*curr\n return rslt\n" }, { "alpha_fraction": 0.48226097226142883, "alphanum_fraction": 0.49789535999298096, "avg_line_length": 28.175437927246094, "blob_id": "05d1bd89d45bcdcb2586c249640b0fe41992ab18", "content_id": "64a92e746be8d797a8b419264ef11ccf04fbcd20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 113, "num_lines": 57, "path": "/lc706_oop.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# hash function + collision handling(chaining)\nclass MyHashMap:\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.table = [[] for _ in range(200)]\n\n def put(self, key: int, value: int) -> None:\n \"\"\"\n value will always be non-negative.\n \"\"\"\n hs = key % 200\n if len(self.table[hs]) == 0:\n self.table[hs].append((key, value))\n return\n for i, v in enumerate(self.table[hs]):\n if v[0] == key:\n self.table[hs][i] = (key, value)\n return\n self.table[hs].append((key, value))\n\n\n def get(self, key: int) -> int:\n \"\"\"\n Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key\n \"\"\"\n hs = key % 200\n if len(self.table[hs]) == 0:\n return -1\n for i, v in enumerate(self.table[hs]):\n if v[0] == key:\n return v[1]\n return -1\n def remove(self, key: int) -> None:\n \"\"\"\n Removes the mapping of the specified value key if this map contains a mapping for the key\n \"\"\"\n hs = key % 200\n if len(self.table[hs]) == 0:\n return\n check = -1\n for i, v in enumerate(self.table[hs]):\n if v[0] == key:\n check = i\n break\n if check >= 0:\n self.table[hs][check] = self.table[hs][-1]\n self.table[hs].pop()\n\n\n# Your MyHashMap object will be instantiated and called as such:\n# obj = MyHashMap()\n# obj.put(key,value)\n# param_2 = obj.get(key)\n# obj.remove(key)\n" }, { "alpha_fraction": 0.47732996940612793, "alphanum_fraction": 0.48488664627075195, "avg_line_length": 43.11111068725586, "blob_id": "c19adee3ec3909f52c04b7861084c56a2fa62b88", "content_id": "47f4cecf2131d5f5cd930918a908a6b9d5f8527c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 794, "license_type": "no_license", "max_line_length": 88, "num_lines": 18, "path": "/lc241_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def diffWaysToCompute(self, expression: str) -> List[int]:\n if not expression: return []\n op = {\"+\": (lambda x, y: x+y), \"-\": (lambda x, y: x-y), \"*\": (lambda x, y: x*y)}\n def helper(left, right):\n if left >= right: return expression[right]\n rslt = []\n for i in range(left, right + 1):\n if expression[i] in op:\n leftr, rightr = helper(left, i-1), helper(i+1, right)\n for l in leftr:\n for r in rightr:\n rslt.append(op[expression[i]](int(l), int(r)))\n print(left, right)\n if not rslt: rslt.append(int(expression[left:right+1]))\n\n return rslt\n return helper(0, len(expression)-1)\n" }, { "alpha_fraction": 0.48880597949028015, "alphanum_fraction": 0.49253731966018677, "avg_line_length": 30.52941131591797, "blob_id": "d311d7640bff8212c7d86642b24eb763b19ce229", "content_id": "3b70125f5f4286ea3ea7b03e462e83f50f845f25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 64, "num_lines": 17, "path": "/lc1171_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeZeroSumSublists(self, head: ListNode) -> ListNode:\n presum = 0\n snode = ListNode(0, head)\n maps = collections.OrderedDict()\n curr = snode\n while curr:\n presum += curr.val\n prev = curr\n if presum in maps:\n prev = maps[presum]\n prev.next = curr.next\n while presum in maps:\n maps.popitem()\n maps[presum] = prev\n curr = curr.next\n return snode.next\n" }, { "alpha_fraction": 0.5034722089767456, "alphanum_fraction": 0.5138888955116272, "avg_line_length": 31, "blob_id": "75a349f856b09b915c285d69b7bd60116db8fe12", "content_id": "dae00d9e95811e7ba0d0e379795a7be018ed7519", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 65, "num_lines": 9, "path": "/lc253_hp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minMeetingRooms(self, intervals: List[List[int]]) -> int:\n intervals.sort()\n hq = []\n for itv in intervals:\n if hq and itv[0] >= hq[0]:\n heapq.heappop(hq)\n heapq.heappush(hq, itv[1])\n return len(hq)\n" }, { "alpha_fraction": 0.453125, "alphanum_fraction": 0.46875, "avg_line_length": 31, "blob_id": "b8076718320e30aba6c68999bf948987c54af693", "content_id": "baba4646dc4ec108c72d44f432317eecb049c807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 45, "num_lines": 8, "path": "/lc338_bit.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def countBits(self, n: int) -> List[int]:\n rslt = [0]\n while len(rslt) < n+1:\n for i in range(len(rslt)):\n rslt.append(rslt[i]+1)\n if len(rslt) > n: break\n return rslt[:n+1]\n" }, { "alpha_fraction": 0.38433516025543213, "alphanum_fraction": 0.39708560705184937, "avg_line_length": 27.894737243652344, "blob_id": "c94b18a6ca334e641cd89577d8fcb95293f5e020", "content_id": "4d089d13fee8d85a7cd7fc7e88329bb3a3e7c936", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 549, "license_type": "no_license", "max_line_length": 64, "num_lines": 19, "path": "/lc1011_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def shipWithinDays(self, weights: List[int], D: int) -> int:\n def check(t):\n rslt, temp = 0, 0\n for w in weights:\n temp += w\n if temp > t:\n rslt += 1\n temp = w\n return rslt+1\n\n left, right = max(weights), sum(weights)\n while left <= right:\n mid = (left + right)//2\n if check(mid) > D:\n left = mid + 1\n else:\n right = mid -1\n return left\n" }, { "alpha_fraction": 0.3367496430873871, "alphanum_fraction": 0.4260614812374115, "avg_line_length": 36.38888931274414, "blob_id": "17be8fb293371785b2340d350baff88d1657fa96", "content_id": "b2851df486cdcc7985df8856a3b5353ff4381120", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 683, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/lc1537_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n l1, l2 = len(nums1), len(nums2)\n idx1, idx2 = 0, 0\n max1, max2 = 0, 0\n while idx1 < l1 or idx2 < l2:\n if idx1 < l1 and (idx2 == l2 or nums1[idx1] < nums2[idx2]):\n max1 += nums1[idx1]\n idx1 += 1\n elif idx2 < l2 and (idx1 == l1 or nums1[idx1] > nums2[idx2]):\n max2 += nums2[idx2]\n idx2 += 1\n else:\n max1 = max(max1, max2) + nums1[idx1]\n max2 = max1\n idx1 += 1\n idx2 += 1\n return max(max1, max2)%(10**9+7)\n\n \n" }, { "alpha_fraction": 0.3949275314807892, "alphanum_fraction": 0.4214975833892822, "avg_line_length": 42.578948974609375, "blob_id": "9427790f75b92015a51140c001fdf9128cd37066", "content_id": "2736d4c9d728421e34bfcc447d0372b6cff14af3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "no_license", "max_line_length": 87, "num_lines": 19, "path": "/lc980_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n toCover, nrow, ncol = 0, len(grid), len(grid[0])\n for i in range(nrow):\n for j in range(ncol):\n if grid[i][j] == 0: toCover += 1\n if grid[i][j] == 1: start = (i,j)\n self.rslt = 0\n def backtracking(i, j, step):\n for x, y in [(i+1, j), (i-1, j), (i, j+1), (i, j-1)]:\n if x < 0 or x >= nrow or y < 0 or y >= ncol or grid[x][y] < 0: continue\n if grid[x][y] == 0:\n grid[x][y] = -2\n backtracking(x, y, step + 1)\n grid[x][y] = 0\n elif grid[x][y] == 2 and step == toCover:\n self.rslt += 1\n backtracking(start[0], start[1], 0)\n return self.rslt\n" }, { "alpha_fraction": 0.43216782808303833, "alphanum_fraction": 0.4475524425506592, "avg_line_length": 29.211267471313477, "blob_id": "a33f3ad87ccb5e22d20d960ed07e1423f613df55", "content_id": "5e904a22a49e1b9420e8e857bff38e6b78ffe4c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2145, "license_type": "no_license", "max_line_length": 100, "num_lines": 71, "path": "/lc1707_trie.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Trie:\n def __init__(self, L):\n self.trie = {}\n self.L = L\n def insert(self, num):\n curr = self.trie\n mask = 1 << self.L\n while mask:\n key = 1 if num&mask else 0\n if key not in curr:\n curr[key] = {}\n curr = curr[key]\n mask >>= 1\n def search(self, num):\n curr = self.trie\n mask = 1 << self.L\n rslt = 0\n while mask:\n key = 0 if num&mask else 1\n if key in curr:\n curr = curr[key]\n rslt |= mask\n else:\n curr = curr[1-key]\n mask >>= 1\n return rslt\n\nclass Solution:\n def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n nn, nq = len(nums), len(queries)\n idx = list(range(nq))\n idx.sort(key = lambda x: queries[x][1])\n idxn = 0\n l = len(bin(max(nums[-1], max(x[0] for x in queries))))-3\n trie, rslt = Trie(l), [-1]*nq\n for idxq in idx:\n x, m = queries[idxq]\n while idxn < nn and nums[idxn] <= m:\n trie.insert(nums[idxn])\n idxn += 1\n if idxn != 0:\n rslt[idxq] = trie.search(x)\n return rslt\n\n#https://leetcode.com/problems/maximum-xor-with-an-element-from-array/discuss/989454/Python-14-lines\ndef maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:\n nums.sort()\n answer = []\n append = answer.append\n for x, m in queries:\n if nums[0] > m:\n append(-1)\n continue\n start, stop = 0, bisect_right(nums, m)\n num = 0\n bit = 2 ** m.bit_length()\n while bit:\n plus = num + bit\n if nums[start] >= plus:\n num = plus\n elif nums[stop-1] >= plus:\n cut = bisect_left(nums, plus, start, stop)\n if x & bit:\n stop = cut\n else:\n start = cut\n num = plus\n bit //= 2\n append(num ^ x)\n return answer\n" }, { "alpha_fraction": 0.44129031896591187, "alphanum_fraction": 0.4606451690196991, "avg_line_length": 35.904762268066406, "blob_id": "56162f0a3a3e2a6b36ba578ebc940527dd06bfdc", "content_id": "bd3fb33bfef78d6d28d7079c3ce18569d658d809", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 775, "license_type": "no_license", "max_line_length": 88, "num_lines": 21, "path": "/lc301_str.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeInvalidParentheses(self, s: str) -> List[str]:\n self.rslt = []\n self.helper(s, 0, 0, ('(', ')'))\n return self.rslt\n\n\n def helper(self, curr_s, s_check, s_modify, check):\n count = 0\n for i in range(s_check, len(curr_s)):\n count += (curr_s[i] == check[0]) - (curr_s[i] == check[1])\n if count >= 0: continue\n for j in range(s_modify, i+1):\n if curr_s[j] == check[1] and (j == s_modify or curr_s[j-1] != check[1]):\n self.helper(curr_s[:j]+curr_s[j+1:], i, j, check)\n return\n curr_s = curr_s[::-1]\n if check[0] == '(':\n self.helper(curr_s, 0, 0, (')', '('))\n else:\n self.rslt.append(curr_s)\n" }, { "alpha_fraction": 0.46507516503334045, "alphanum_fraction": 0.5083996653556824, "avg_line_length": 36.70000076293945, "blob_id": "051b5dffd898dc5645f8c175c6a3b64fd71097d9", "content_id": "6f739cf40ae9835919706af84f9ab0bf7f1cbae4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1131, "license_type": "no_license", "max_line_length": 74, "num_lines": 30, "path": "/lc244_hash.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class WordDistance:\n\n def __init__(self, wordsDict: List[str]):\n self.maps = collections.defaultdict(list)\n self.cache = {}\n for i, word in enumerate(wordsDict):\n self.maps[word].append(i)\n\n def shortest(self, word1: str, word2: str) -> int:\n if (word1, word2) in self.cache: return self.cache[(word1, word2)]\n if (word2, word1) in self.cache: return self.cache[(word2, word1)]\n cand1, cand2 = self.maps[word1], self.maps[word2]\n # if len(cand1) > len(cand2): cand1, cand2 = cand2, cand1\n # rslt = float(\"inf\")\n # for x in cand1:\n # y = bisect.bisect(cand2, x)\n # if y < len(cand2):\n # rslt = min(rslt, cand2[y]-x)\n # if y > 0: rslt = min(rslt, x-cand2[y-1])\n # return rslt\n l1, l2 = 0, 0\n rslt = float(\"inf\")\n while l1 < len(cand1) and l2 < len(cand2):\n rslt = min(rslt, abs(cand1[l1]-cand2[l2]))\n if cand1[l1] < cand2[l2]:\n l1 += 1\n else:\n l2 += 1\n self.cache[(word1, word2)] = rslt\n return rslt\n" }, { "alpha_fraction": 0.37906646728515625, "alphanum_fraction": 0.39745402336120605, "avg_line_length": 38.27777862548828, "blob_id": "11a96639517bcc375870f986c63b46d72c29bf45", "content_id": "2e19cee85667f121f97ca241f9e02f4b324ed2b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 101, "num_lines": 18, "path": "/lc52_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def totalNQueens(self, n: int) -> int:\n self.rslt, visited = 0, set()\n def backtracking(i):\n if i == n:\n self.rslt += 1\n else:\n for j in range(n):\n if (2, j) not in visited and (3, j-i) not in visited and (4, j+i) not in visited:\n visited.add((2, j))\n visited.add((3, j-i))\n visited.add((4, j+i))\n backtracking(i+1)\n visited.remove((2, j))\n visited.remove((3, j-i))\n visited.remove((4, j+i))\n backtracking(0)\n return self.rslt\n" }, { "alpha_fraction": 0.47999998927116394, "alphanum_fraction": 0.49925926327705383, "avg_line_length": 28.34782600402832, "blob_id": "7d292831e11bca4ad67c9d8cbc332b7ad87ec079", "content_id": "3571c970366dfa11e1c707f844dda58b390e1753", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 55, "num_lines": 23, "path": "/lc1146_ood.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class SnapshotArray:\n\n def __init__(self, length: int):\n self.array = [[(-1, 0)] for _ in range(length)]\n self.snap_id = 0\n\n def set(self, index: int, val: int) -> None:\n self.array[index].append((self.snap_id, val))\n\n\n def snap(self) -> int:\n self.snap_id += 1\n return self.snap_id - 1\n\n def get(self, index: int, snap_id: int) -> int:\n left, right = 0, len(self.array[index])-1\n while left <= right:\n mid = (left + right)//2\n if self.array[index][mid][0] > snap_id:\n right = mid -1\n else:\n left = mid + 1\n return self.array[index][left-1][1]\n" }, { "alpha_fraction": 0.4386363625526428, "alphanum_fraction": 0.4522727131843567, "avg_line_length": 30.428571701049805, "blob_id": "86a18cf38959216af26744334a9038197ba2d7ba", "content_id": "75df68515c51f8e2706475253bfc821e28df9d55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 440, "license_type": "no_license", "max_line_length": 68, "num_lines": 14, "path": "/lc1641_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# dfs + memo\nclass Solution:\n def countVowelStrings(self, n: int) -> int:\n memo = {}\n def dfs(curr, rest):\n if (curr, rest) in memo:\n return memo[(curr, rest)]\n if curr == 1:\n return rest\n if rest == 1:\n return 1\n memo[(curr, rest)] = dfs(curr-1, rest)+dfs(curr, rest-1)\n return memo[(curr, rest)]\n return dfs(n, 5)\n" }, { "alpha_fraction": 0.39177101850509644, "alphanum_fraction": 0.40787118673324585, "avg_line_length": 30.05555534362793, "blob_id": "fa4af0717539bc5ede49b83c12fb1023356cbc2d", "content_id": "d1e636329b5c95e9539d784a9404b75bb2967020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 57, "num_lines": 18, "path": "/lc343_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def integerBreak(self, n: int) -> int:\n @functools.lru_cache(None)\n def dfs(j):\n if j <= 2:\n return 1\n else:\n rslt = 0\n for i in range(1, j):\n rslt = max(rslt, i*max(dfs(j-i),j-i))\n return rslt\n return dfs(n)\n def integerBreak(self, n:int) -> int:\n dp = [1]*(n+1)\n for j in range(3, n+1):\n for i in range(1, j):\n dp[j] = max(dp[j], i*max(dp[j-i], j-i))\n return dp[n]\n" }, { "alpha_fraction": 0.40689656138420105, "alphanum_fraction": 0.4275861978530884, "avg_line_length": 32.46154022216797, "blob_id": "c9b62d115af5de1899b2c03d7ee3f39a858e17f6", "content_id": "13470bea045eebf2acfe2d096f1271f60ab1aa4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 435, "license_type": "no_license", "max_line_length": 57, "num_lines": 13, "path": "/lc1542_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestAwesome(self, s: str) -> int:\n rslt, curr = 0, 0\n seen = {0:-1}\n for i, c in enumerate(s):\n curr ^= 1 << int(c)\n if curr not in seen:\n seen[curr] = i\n rslt = max(rslt, i-seen[curr])\n for j in range(10):\n if curr^(1 << j) in seen:\n rslt = max(rslt, i-seen[curr^(1<<j)])\n return rslt\n" }, { "alpha_fraction": 0.49430739879608154, "alphanum_fraction": 0.4985768496990204, "avg_line_length": 28.690141677856445, "blob_id": "23a2fca5879bd3c5680f71ac71b40ce250fc90ca", "content_id": "839cc46136a1b3c12e755bc48b01cc2a25619103", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2108, "license_type": "no_license", "max_line_length": 54, "num_lines": 71, "path": "/lc745_trie.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class TrieNode:\n def __init__(self):\n self.next = {}\n self.idx = set()\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n def insert(self, word, idx):\n curr = self.root\n for ch in word:\n if ch not in curr.next:\n curr.next[ch] = TrieNode()\n curr.next[ch].idx.add(idx)\n curr = curr.next[ch]\n def search(self, word):\n curr = self.root\n for ch in word:\n if ch not in curr.next:\n return set()\n curr = curr.next[ch]\n return curr.idx\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.TriePre = Trie()\n self.TriePost = Trie()\n l, seen = len(words), set()\n for j in range(l-1, -1, -1):\n word = words[j]\n if word not in seen:\n seen.add(word)\n self.TriePre.insert(word, j)\n self.TriePost.insert(word[::-1], j)\n\n def f(self, prefix: str, suffix: str) -> int:\n preset = self.TriePre.search(prefix)\n postset = self.TriePost.search(suffix[::-1])\n rslt = preset & postset\n return max(rslt) if rslt else -1\n\n\nclass TrieNode:\n def __init__(self, idx = -1):\n self.next = {}\n self.idx = -1\nclass Trie:\n def __init__(self):\n self.root = TrieNode()\n def insert(self, word, idx):\n curr = self.root\n for ch in word:\n if ch not in curr.next:\n curr.next[ch] = TrieNode()\n curr.next[ch].idx = idx\n curr = curr.next[ch]\n def search(self, word):\n curr = self.root\n for ch in word:\n if ch not in curr.next:\n return -1\n curr = curr.next[ch]\n return curr.idx\nclass WordFilter:\n\n def __init__(self, words: List[str]):\n self.trie = Trie()\n for j, word in enumerate(words):\n for i in range(len(word)):\n self.trie.insert(word[i:]+\"#\"+word, j)\n def f(self, prefix: str, suffix: str) -> int:\n return self.trie.search(suffix+\"#\"+prefix)\n" }, { "alpha_fraction": 0.4093078672885895, "alphanum_fraction": 0.4343675374984741, "avg_line_length": 43.105262756347656, "blob_id": "c6d01abdf9916ef60ce0ca290b5fec47672cd3f1", "content_id": "dbdfa02bfc39a6f5586e77193406b1057ead5f72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 91, "num_lines": 19, "path": "/lc282_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def addOperators(self, num: str, target: int) -> List[str]:\n rslt, n = [], len(num)\n def backtracking(i, curr, last, total):\n if i == n and total == target:\n rslt.append(curr)\n else:\n for j in range(i+1, n+1):\n temp1, temp2 = int(num[i:j]), num[i:j]\n if i == 0:\n backtracking(j, temp2, temp1, temp1)\n else:\n backtracking(j, curr+\"+\"+temp2, temp1, total+temp1)\n backtracking(j, curr+\"*\"+temp2, last*temp1,total-last + last*temp1)\n backtracking(j, curr+\"-\"+temp2, -temp1,total-temp1)\n if num[i] == \"0\":\n break\n backtracking(0, \"\",0, 0)\n return rslt\n" }, { "alpha_fraction": 0.4397905766963959, "alphanum_fraction": 0.45724257826805115, "avg_line_length": 30.83333396911621, "blob_id": "3c17bbf09088d16e9c2da8165d1f15aeb4ef688a", "content_id": "29f10a4bb8e54ff26874fe06d66a0cecc55534af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 66, "num_lines": 18, "path": "/lc774_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minmaxGasDist(self, stations: List[int], k: int) -> float:\n def check(p):\n count = 0\n for i in range(1, n):\n count += int((stations[i]-stations[i-1])/p)\n return count\n\n left, right, n =0, 0, len(stations)\n for i in range(1, n):\n right = max(right, stations[i]-stations[i-1])\n while left < right - 1e-6:\n mid = (left + right)/2\n if check(mid) > k:\n left = mid\n else:\n right = mid\n return left\n" }, { "alpha_fraction": 0.3363695442676544, "alphanum_fraction": 0.3604424297809601, "avg_line_length": 38.410255432128906, "blob_id": "ec2ed0ab1598633b99db7ecffba579a35261aa02", "content_id": "98f924795a19380d1a76ca465745e0b35ab3f7c3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1537, "license_type": "no_license", "max_line_length": 104, "num_lines": 39, "path": "/lc37_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n memo = collections.defaultdict(set)\n # store curr board:\n for i, l in enumerate(board):\n for j, t in enumerate(l):\n if t !=\".\":\n memo[(i, -1)].add(t)\n memo[(-1, j)].add(t)\n memo[(i//3, j//3)].add(t)\n def backtracking(i, j):\n if i == 9:\n return True\n if board[i][j] == \".\":\n for t in \"123456789\":\n if t not in memo[(i,-1)] and t not in memo[(-1, j)] and t not in memo[(i//3, j//3)]:\n board[i][j] = t\n memo[(i, -1)].add(t)\n memo[(-1, j)].add(t)\n memo[(i//3, j//3)].add(t)\n if j < 8 and backtracking(i, j+1):\n return True\n if j == 8 and backtracking(i+1, 0):\n return True\n board[i][j] = \".\"\n memo[(i, -1)].remove(t)\n memo[(-1, j)].remove(t)\n memo[(i//3, j//3)].remove(t)\n return False\n else:\n if j < 8 :\n return backtracking(i, j+1)\n else:\n return backtracking(i+1, 0)\n backtracking(0, 0)\n return board\n" }, { "alpha_fraction": 0.5080645084381104, "alphanum_fraction": 0.5100806355476379, "avg_line_length": 32.06666564941406, "blob_id": "4c3993c0e5de31ae692874596a2f08cb0c5406dd", "content_id": "0d5bcf29f35cfbe87012fe9f18888ffad53d08a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 496, "license_type": "no_license", "max_line_length": 67, "num_lines": 15, "path": "/lc332_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findItinerary(self, tickets: List[List[str]]) -> List[str]:\n graph = collections.defaultdict(list)\n for start, end in tickets:\n graph[start].append(end)\n for key, val in graph.items():\n val.sort(reverse = True)\n rslt = []\n def dfs(start):\n while graph[start]:\n temp = graph[start].pop()\n dfs(temp)\n rslt.append(start)\n dfs(\"JFK\")\n return rslt[::-1]\n" }, { "alpha_fraction": 0.46584802865982056, "alphanum_fraction": 0.4666154980659485, "avg_line_length": 28.613636016845703, "blob_id": "c7d874b8d769fc6b9f7766baa3ce79ba59f719d8", "content_id": "d4ea5601a63cccfd9a680044fafce6bf59415510", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 55, "num_lines": 44, "path": "/lc426_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def treeToDoublyList(self, root: 'Node') -> 'Node':\n # inorder traversal\n def inorder(root):\n if not root:\n return None, None\n left, right = root.left, root.right\n head, tail = inorder(left)\n if head:\n tail.right = root\n root.left = tail\n else:\n head = root\n nhead, ntail = inorder(right)\n root.right = nhead\n if nhead:\n nhead.left = root\n else:\n ntail = root\n return head, ntail\n head, tail = inorder(root)\n if not head: return None\n head.left = tail\n tail.right = head\n return head\nclass Solution:\n def treeToDoublyList(self, root: 'Node') -> 'Node':\n if not root:\n return None\n dummy = Node(0)\n prev = dummy\n stack, curr = [], root\n while stack or curr:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n curr.left = prev\n prev.right = curr\n prev = curr\n curr = curr.right\n dummy.right.left = prev\n prev.right = dummy.right\n return dummy.right\n" }, { "alpha_fraction": 0.4612794518470764, "alphanum_fraction": 0.46464645862579346, "avg_line_length": 33.94117736816406, "blob_id": "b53d050676e7267397e7f04832b98e518ec48398", "content_id": "820c0d4499a20fecf039a4827a2101255da50c0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/lc785_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def isBipartite(self, graph: List[List[int]]) -> bool:\n set_map = {}\n def dfs(node):\n for snode in graph[node]:\n if snode not in set_map:\n set_map[snode] = 1 - set_map[node]\n if not dfs(snode): return False\n elif set_map[node] == set_map[snode]:\n return False\n return True\n\n for i in range(len(graph)):\n if graph[i] and i not in set_map:\n set_map[i] = 1\n if not dfs(i): return False\n return True\n" }, { "alpha_fraction": 0.459090918302536, "alphanum_fraction": 0.4636363685131073, "avg_line_length": 32.33333206176758, "blob_id": "9e1249a434b754a41dad5ba7cf40bcc6dfd280bb", "content_id": "f50dae2390fbaedc0e41ae1692c572b0d02285ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 66, "num_lines": 33, "path": "/lc1740_lca.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def findDistance(self, root: TreeNode, p: int, q: int) -> int:\n\n def lca(root, p, q):\n if not root: return None\n if root.val == p or root.val == q:\n return root\n left = lca(root.left, p, q)\n right = lca(root.right, p, q)\n if left and right:\n return root\n return left or right\n pqlca = lca(root, p, q)\n queue = collections.deque([pqlca])\n lq, lp, level = 0, 0, 0\n while queue:\n l = len(queue)\n for _ in range(l):\n temp = queue.popleft()\n if temp.val == q:\n lq = level\n if temp.val == p:\n lp = level\n if temp.left: queue.append(temp.left)\n if temp.right: queue.append(temp.right)\n level += 1\n return lq+lp\n" }, { "alpha_fraction": 0.4606741666793823, "alphanum_fraction": 0.47752809524536133, "avg_line_length": 31.363636016845703, "blob_id": "39ca79cc975b9922d8490b9d9473c5527bc313e0", "content_id": "9ed447a87a2149232887c17ada750c48d6bde047", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 712, "license_type": "no_license", "max_line_length": 57, "num_lines": 22, "path": "/lc968_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def minCameraCover(self, root: TreeNode) -> int:\n self.rslt = 0\n def dfs(root):\n if not root: return -1\n left, right = dfs(root.left), dfs(root.right)\n # leaf's parent, put carmera\n if left == 0 or right == 0:\n self.rslt += 1\n return -2\n if left == -2 or right == -2:\n return -1\n else:\n return 0\n temp = dfs(root)\n return self.rslt + (temp == 0)\n" }, { "alpha_fraction": 0.5391250848770142, "alphanum_fraction": 0.5408194661140442, "avg_line_length": 31.62311553955078, "blob_id": "ce89cdc5c779a036a90aa5fc50fbea389ab5503c", "content_id": "18a8bda8ad7a5e31b99cbbcaf88d85d0400cc5cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6492, "license_type": "no_license", "max_line_length": 125, "num_lines": 199, "path": "/lc732_mcal.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class MyCalendar:\n\n def __init__(self):\n self.booking = []\n\n def book(self, start: int, end: int) -> bool:\n for s, e in self.booking:\n if s < end and e > start:\n return False\n self.booking.append((start, end))\n return True\nclass Node:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.left = self.right = None\nclass MyCalendar:\n\n def __init__(self):\n self.root = None\n\n def book(self, start: int, end: int) -> bool:\n rslt, self.root = self.insert(self.root, start, end)\n return rslt\n\n def insert(self, root, start, end):\n if not root:\n return True, Node(start, end)\n if end <= root.start:\n rslt, root.left = self.insert(root.left, start, end)\n return rslt, root\n if start >= root.end:\n rslt, root.right = self.insert(root.right, start, end)\n return rslt, root\n return False, root\nclass MyCalendar:\n\n def __init__(self):\n self.starts = []\n self.ends = []\n\n def book(self, start: int, end: int) -> bool:\n s, e = bisect.bisect_right(self.ends, start), bisect.bisect_left(self.starts, end)\n if s != e: return False\n bisect.insort(self.starts, start, s, e)\n bisect.insort(self.ends, end, s, e)\n return True\n\nclass MyCalendarTwo:\n\n def __init__(self):\n self.seen_once = []\n self.seen_twice = []\n\n def book(self, start: int, end: int) -> bool:\n for st, ed in self.seen_twice:\n if st < end and ed > start:\n return False\n for st, ed in self.seen_once:\n if st < end and ed > start:\n self.seen_twice.append((max(st, start), min(ed, end)))\n self.seen_once.append((start, end))\n return True\nclass Node:\n def __init__(self, start, end):\n self.start = start\n self.end = end\n self.left = self.right = None\n self.seen_twice = False\nclass MyCalendarTwo:\n\n def __init__(self):\n self.root = None\n\n def book(self, start: int, end: int) -> bool:\n if not self.check(self.root, start, end): return False\n self.root = self.insert(self.root, start, end)\n return True\n\n def check(self, root, start, end):\n if not root:\n return True\n if end <= root.start:\n return self.check(root.left, start, end)\n if start >= root.end:\n return self.check(root.right, start, end)\n if root.seen_twice: return False\n lefts, lefte, rights, righte = min(start, root.start), max(start, root.start), min(end, root.end), max(end, root.end)\n leftc = self.check(root.left, start, end)\n rightc = self.check(root.right, start, end)\n return leftc and rightc\n\n def insert(self, root, start, end):\n if start >= end:\n return root\n if not root:\n return Node(start, end)\n if end <= root.start:\n root.left = self.insert(root.left, start, end)\n return root\n if start >= root.end:\n root.right = self.insert(root.right, start, end)\n return root\n lefts, lefte, rights, righte = min(start, root.start), max(start, root.start), min(end, root.end), max(end, root.end)\n root.left = self.insert(root.left, lefts, lefte)\n root.right = self.insert(root.right, rights, righte)\n root.seen_twice = True\n root.start = lefte\n root.end = rights\n return root\nclass MyCalendarTwo:\n\n def __init__(self):\n self.starts = []\n self.ends = []\n\n def book(self, start: int, end: int) -> bool:\n s, e = bisect.bisect_right(self.ends, start), bisect.bisect_left(self.starts, end)\n hp = []\n for i in range(s, e):\n while hp and hp[0] <= self.starts[i]:\n heapq.heappop(hp)\n heapq.heappush(hp, self.ends[i])\n if len(hp) > 1:\n return False\n bisect.insort(self.starts, start, s, e)\n bisect.insort(self.ends, end, s, e)\n return True\n\n\n\nclass MyCalendarThree:\n\n def __init__(self):\n self.booking = []\n def book(self, start: int, end: int) -> int:\n self.booking.append((start, 1))\n self.booking.append((end, -1))\n cnt, rslt = 0, 0\n self.booking.sort()\n for x, y in self.booking:\n cnt += y\n if cnt > rslt:\n rslt = cnt\n return rslt\nclass Node:\n def __init__(self, start, end, k):\n self.start = start\n self.end = end\n self.k = k\n self.right = self.left = None\nclass MyCalendarThree:\n\n def __init__(self):\n self.root = None\n self.k = 0\n def book(self, start: int, end: int) -> int:\n self.root = self.insert(self.root, start, end, 1)\n return self.k\n\n def insert(self, root, start, end, k):\n if start >= end:\n return root\n if not root:\n self.k = max(self.k, k)\n return Node(start, end, k)\n if end <= root.start:\n root.left = self.insert(root.left, start, end, k)\n return root\n if start >= root.end:\n root.right = self.insert(root.right, start, end, k)\n return root\n lefts, lefte, rights, righte = min(start, root.start), max(start, root.start), min(end, root.end), max(end, root.end)\n root.left = self.insert(root.left, lefts, lefte, root.k if lefts == root.start else k)\n root.right = self.insert(root.right, rights, righte, root.k if righte == root.end else k)\n root.k += k\n root.start = lefte\n root.end = rights\n self.k = max(self.k, root.k)\n return root\nclass MyCalendarThree:\n def __init__(self):\n self.starts = []\n self.ends = []\n self.booking = 0\n\n def book(self, start: int, end: int) -> int:\n s, e = bisect.bisect_right(self.ends, start), bisect.bisect_left(self.starts, end)\n bisect.insort(self.starts, start, s, e)\n bisect.insort(self.ends, end, s, e)\n # print(start, end, s, e, self.starts, self.ends)\n hp = [] # store end points\n for i in range(s, e + 1):\n while hp and hp[0] <= self.starts[i]:\n heapq.heappop(hp)\n heapq.heappush(hp, self.ends[i])\n if len(hp) > self.booking:\n self.booking = len(hp)\n return self.booking\n" }, { "alpha_fraction": 0.5324568748474121, "alphanum_fraction": 0.5324568748474121, "avg_line_length": 32.80555725097656, "blob_id": "e429d97fa273bded608775130cd2352ea0b4d14a", "content_id": "2ba1f03eebec6a17f5c7f20167cafa36069a1e9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1217, "license_type": "no_license", "max_line_length": 97, "num_lines": 36, "path": "/lc236_lca.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n if not root: return None\n if root == p or root == q:\n return root\n left = self.lowestCommonAncestor(root.left, p, q)\n right = self.lowestCommonAncestor(root.right, p, q)\n if left and right:\n return root\n return left or right\n\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n stack = [root]\n seen, parents = set(), {root:None}\n while p not in parents or q not in parents:\n parent = stack.pop()\n if parent.left:\n parents[parent.left] = parent\n stack.append(parent.left)\n if parent.right:\n parents[parent.right] = parent\n stack.append(parent.right)\n cands = set()\n while p:\n cands.add(p)\n p = parents[p]\n while q not in cands:\n q = parents[q]\n return q\n" }, { "alpha_fraction": 0.48841893672943115, "alphanum_fraction": 0.503524661064148, "avg_line_length": 34.46428680419922, "blob_id": "06853a34dd10c985abc182225c129cb4e7eeeb41", "content_id": "114e11e02f1db956c11da1ef9a4547a653556e07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 993, "license_type": "no_license", "max_line_length": 82, "num_lines": 28, "path": "/lc320_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def generateAbbreviations(self, word: str) -> List[str]:\n rslt, n = [], len(word)\n def backtracking(i, curr):\n if i == n:\n rslt.append(\"\".join(curr))\n else:\n if not curr or curr[-1].isalpha():\n backtracking(i+1, curr+['1'])\n else:\n backtracking(i+1, curr[:-1]+[str(int(curr[-1])+1)])\n backtracking(i+1, curr+[word[i]])\n backtracking(0, [])\n return rslt\n\n\nclass Solution:\n def generateAbbreviations(self, word: str) -> List[str]:\n self.rslt, self.n, self.word = [], len(word), word\n self.backtracking(0, \"\", 0)\n return self.rslt\n\n def backtracking(self, i, curr, cnt):\n if i == self.n:\n self.rslt.append(curr+(str(cnt) if cnt else \"\"))\n else:\n self.backtracking(i+1, curr, cnt+1)\n self.backtracking(i+1, curr+(str(cnt) if cnt else \"\")+self.word[i], 0)\n" }, { "alpha_fraction": 0.31351980566978455, "alphanum_fraction": 0.3170163035392761, "avg_line_length": 29.64285659790039, "blob_id": "211856f58c810790c1ed95c34055ef2c6b348861", "content_id": "35cb21fb5609b49a06b0ba913df1e7e3f9cf41fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 858, "license_type": "no_license", "max_line_length": 52, "num_lines": 28, "path": "/lc224_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def calculate(self, s: str) -> int:\n stk, last = [\"(\"], False\n for c in s+\")\":\n if c == \" \":\n continue\n if c.isdigit() and last:\n stk.append(stk.pop()+c)\n elif c.isdigit():\n stk.append(c)\n last = True\n elif c == \")\":\n t_stk = []\n while stk[-1]!=\"(\":\n if stk[-1] == \"-\":\n t_stk.append(-t_stk.pop())\n stk.pop()\n else:\n t_stk.append(int(stk.pop()))\n stk.pop()\n stk.append(str(sum(t_stk)))\n last = False\n else:\n if c != \"+\":\n stk.append(c)\n last = False\n\n return int(stk[0])\n" }, { "alpha_fraction": 0.37771347165107727, "alphanum_fraction": 0.38784369826316833, "avg_line_length": 30.409090042114258, "blob_id": "8701b7e8ba33ffcc80dc1a502693852064abe657", "content_id": "8116b93ec6066ddd6e4673a14a6a22a86e5479c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 72, "num_lines": 22, "path": "/lc218_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]:\n lines = []\n for l, r, h in buildings:\n lines.append([l, h])\n lines.append([r, -h])\n lines.sort(key = lambda x: (x[0], -x[1]))\n heap = [0]\n rslt = []\n for x, h in lines:\n if h > 0:\n # start\n if h > -heap[0]:\n rslt.append([x, h])\n heapq.heappush(heap, -h)\n else:\n # end\n heap.remove(h)\n heapq.heapify(heap)\n if -h > -heap[0]:\n rslt.append([x, -heap[0]])\n return rslt\n" }, { "alpha_fraction": 0.4337349534034729, "alphanum_fraction": 0.45542168617248535, "avg_line_length": 32.83333206176758, "blob_id": "f788bf18e8c5e6ac5086c8d0f71b8999a272b165", "content_id": "29d86f3bf77a18dacccba7b26c297bde817bc2a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/lc1124_hash.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestWPI(self, hours: List[int]) -> int:\n maps = {}\n curr, rslt = 0, 0\n for i, hour in enumerate(hours):\n curr = curr + 1 if hour > 8 else curr-1\n if curr > 0:\n rslt = i + 1\n if curr not in maps: maps[curr] = i\n if curr-1 in maps:\n rslt = max(rslt, i-maps[curr-1])\n return rslt\n \n" }, { "alpha_fraction": 0.43801653385162354, "alphanum_fraction": 0.4573002755641937, "avg_line_length": 32, "blob_id": "61fffc06f1265ddc15668c203971f538aaf8e81a", "content_id": "c6e97ccb6989edafdbf46bbcc1d829e467691599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 363, "license_type": "no_license", "max_line_length": 57, "num_lines": 11, "path": "/lc128_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def longestConsecutive(self, nums: List[int]) -> int:\n cands, curr, rslt= set(nums), 1, 0\n for cand in cands:\n curr = 1\n if cand-1 not in cands:\n while cand+1 in cands:\n cand = cand+1\n curr += 1\n rslt = max(rslt, curr)\n return rslt\n" }, { "alpha_fraction": 0.4289276897907257, "alphanum_fraction": 0.4463840425014496, "avg_line_length": 29.846153259277344, "blob_id": "9a895ee2d74e4bb4128094da7eb972215dbcee1e", "content_id": "14812dbbbbca6fc384a3885acb5b7073e2e80633", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 71, "num_lines": 13, "path": "/lc435_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:\n if len(intervals) <= 0: return 0\n intervals.sort()\n last, rslt = intervals[0][1], 0\n for x, y in intervals[1:]:\n if x < last:\n rslt += 1\n if y < last:\n last = y\n else:\n last = y\n return rslt\n" }, { "alpha_fraction": 0.37171053886413574, "alphanum_fraction": 0.40723684430122375, "avg_line_length": 30.66666603088379, "blob_id": "a75c43eea1cafaca3afecc7d444007abf4c4c3a2", "content_id": "73c369906edda7ba6f1caab96646dc3d0b5222bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1520, "license_type": "no_license", "max_line_length": 84, "num_lines": 48, "path": "/lc308_segtree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class NumMatrix:\n def __init__(self, matrix: List[List[int]]):\n self.m, self.n = len(matrix), len(matrix[0])\n self.seg_tree = [[0]*(2*self.n) for _ in range(2*self.m)]\n for i in range(self.m):\n for j in range(self.n):\n self.update(i, j, matrix[i][j])\n\n def update(self, row: int, col: int, val: int) -> None:\n m = row + self.m\n n = col + self.n\n self.seg_tree[m][n] = val\n while m > 0:\n self.seg_tree[m >> 1][n] = self.seg_tree[m][n]+self.seg_tree[m^1][n]\n t = n\n while t > 0:\n self.seg_tree[m][t >> 1] = self.seg_tree[m][t]+self.seg_tree[m][t^1]\n t >>= 1\n m >>= 1\n def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:\n rslt = 0\n r1 = self.m + row1\n r2 = self.m + row2\n while r1 <= r2:\n if r1&1:\n rslt += self.sumRange(r1, col1, col2)\n r1 += 1\n\n if r2&1 == 0:\n rslt += self.sumRange(r2, col1, col2)\n r2 -= 1\n r1 >>= 1\n r2 >>= 1\n return rslt\n\n def sumRange(self, row, col1, col2):\n rslt = 0\n l, r= self.n+col1, self.n+col2\n while l <= r:\n if l&1:\n rslt += self.seg_tree[row][l]\n l += 1\n if r&1 == 0:\n rslt += self.seg_tree[row][r]\n r -= 1\n l >>= 1\n r >>= 1\n return rslt\n" }, { "alpha_fraction": 0.7749999761581421, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 19, "blob_id": "14779852faf77b20122b42df1016088b6f05f078", "content_id": "637d94def0546a6622650b27b324c7fd4744aad3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40, "license_type": "no_license", "max_line_length": 28, "num_lines": 2, "path": "/README.md", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# lc_punch\nRepo for LC practice logging\n" }, { "alpha_fraction": 0.4428237974643707, "alphanum_fraction": 0.46674445271492004, "avg_line_length": 35.46808624267578, "blob_id": "b10a64818b79e57ea4b8d23ae118081cdd7bc0ee", "content_id": "4b120c84a970eeb1514572ae368f643b0dc1d592", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1714, "license_type": "no_license", "max_line_length": 109, "num_lines": 47, "path": "/lc992_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n memo1, memo2, left, right, rslt = collections.defaultdict(int), collections.defaultdict(int), 0, 0, 0\n for it in A:\n memo1[it] += 1\n memo2[it] += 1\n while len(memo1) > K:\n memo1[A[left]] -= 1\n if memo1[A[left]] == 0: del memo1[A[left]]\n left += 1\n while len(memo2) >= K:\n memo2[A[right]] -= 1\n if memo2[A[right]] == 0: del memo2[A[right]]\n right += 1\n rslt += right-left\n return rslt\n\nclass Solution:\n def atMostK(self, A, K):\n memo, left, rslt = collections.defaultdict(int), 0, 0\n for right, it in enumerate(A):\n memo[it] += 1\n while len(memo) > K:\n memo[A[left]] -= 1\n if memo[A[left]] == 0: del memo[A[left]]\n left += 1\n rslt += right-left + 1\n return rslt\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n if not A: return 0\n return self.atMostK(A, K) - self.atMostK(A, K - 1)\n\nclass Solution:\n def subarraysWithKDistinct(self, A: List[int], K: int) -> int:\n memo, lefta, leftb, rslt = collections.defaultdict(int), 0, 0, 0\n for right, num in enumerate(A):\n memo[num] += 1\n if len(memo) > K:\n del memo[A[leftb]]\n leftb += 1\n lefta = leftb\n if len(memo) == K:\n while memo[A[leftb]] > 1:\n memo[A[leftb]] -= 1\n leftb += 1\n rslt += leftb-lefta+1\n return rslt\n" }, { "alpha_fraction": 0.43790850043296814, "alphanum_fraction": 0.4562091529369354, "avg_line_length": 46.8125, "blob_id": "f47fd27d163848bf6b60d7d31d752c3cdb0afe2b", "content_id": "a0d3fc9105e20479b5de61be1078a8f3d434a73e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 765, "license_type": "no_license", "max_line_length": 95, "num_lines": 16, "path": "/lc490_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool:\n dque, visited = collections.deque([tuple(start)]), {tuple(start)}\n n, c = len(maze), len(maze[0])\n while dque:\n currow, curcol = dque.popleft()\n if destination[0] == currow and destination[1] == curcol: return True\n for x, y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n tx, ty = currow, curcol\n while 0 <= tx+x < n and 0 <= ty+y < c and maze[tx+x][ty+y] == 0:\n tx += x\n ty += y\n if (tx, ty) not in visited:\n dque.append((tx, ty))\n visited.add((tx, ty))\n return False\n" }, { "alpha_fraction": 0.5112107396125793, "alphanum_fraction": 0.5182574987411499, "avg_line_length": 32.212764739990234, "blob_id": "80d1bd32e50135357db4f5bf8d9a5336965b5a6b", "content_id": "d0a5d599328ab78d633566ba26084cf118faea0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1561, "license_type": "no_license", "max_line_length": 83, "num_lines": 47, "path": "/lc207_graph.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n if not prerequisites: return True\n graph = collections.defaultdict(list)\n visited = [0]*numCourses\n for crs, pre in prerequisites:\n graph[crs].append(pre)\n\n def dfs(crs):\n # in cycle\n if visited[crs] == 1:\n return False\n # not in cycle\n if visited[crs] == 2:\n return True\n # new node: assume in cycle until approve not\n visited[crs] = 1\n if crs in graph:\n for pre in graph[crs]:\n if not dfs(pre): return False\n visited[crs] = 2\n return True\n\n for crs in graph:\n if not dfs(crs): return False\n return True\n\n\nclass Solution:\n def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:\n if not prerequisites: return True\n graph, degree = collections.defaultdict(list), collections.defaultdict(int)\n for crs, pre in prerequisites:\n graph[pre].append(crs)\n degree[crs] += 1\n dque = collections.deque()\n for i in range(numCourses):\n if degree[i] == 0: dque.append(i)\n count = 0\n while dque:\n curr = dque.popleft()\n count += 1\n for post in graph[curr]:\n degree[post] -= 1\n if degree[post] == 0:\n dque.append(post)\n return count == numCourses\n" }, { "alpha_fraction": 0.28145694732666016, "alphanum_fraction": 0.3509933650493622, "avg_line_length": 32, "blob_id": "8f5e1d284fd5be1560f16739996320b9c92727bd", "content_id": "eb61a90760defa7ac624754085ebd1de6ecb5205", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 64, "num_lines": 18, "path": "/lc1868_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSum(self, nums1: List[int], nums2: List[int]) -> int:\n l1, l2 = len(nums1), len(nums2)\n x, y = 0, 0\n r1, r2 = 0, 0\n while x < l1 or y < l2:\n if x < l1 and (y == l2 or nums1[x] < nums2[y]):\n r1 += nums1[x]\n x += 1\n elif y < l2 and (x == l1 or nums1[x] > nums2[y]):\n r2 += nums2[y]\n y += 1\n else:\n r1 = max(r1, r2) + nums1[x]\n r2 = r1\n x += 1\n y += 1\n return max(r1, r2)%(10**9+7)\n\n \n" }, { "alpha_fraction": 0.4606427550315857, "alphanum_fraction": 0.4625058174133301, "avg_line_length": 32.546875, "blob_id": "0f7c38e245450e4aebc0b799131c28617db65b7b", "content_id": "66d9d2a7c789f17319cc6e88a292bf6397aea021", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2147, "license_type": "no_license", "max_line_length": 79, "num_lines": 64, "path": "/lc99_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n # def recoverTree(self, root: TreeNode) -> None:\n # \"\"\"\n # Do not return anything, modify root in-place instead.\n # \"\"\"\n # order = self.inorder(root)\n # y, x = None, None\n # for i in range(len(order)-1):\n # if order[i+1] < order[i]:\n # y = order[i+1]\n # if x is None:\n # x = order[i]\n # else:\n # break\n # stack = [root]\n # while stack:\n # temp = stack.pop()\n # if temp.val in (x, y):\n # temp.val = x if temp.val == y else y\n # if temp.left: stack.append(temp.left)\n # if temp.right:stack.append(temp.right)\n # def inorder(self, root):\n # if not root: return []\n # return self.inorder(root.left) +[root.val] + self.inorder(root.right)\n\n def recoverTree(self, root: TreeNode) -> None:\n self.x, self.y, self.pre = None, None, None\n def inorder(root):\n if not root: return\n inorder(root.left)\n if self.pre and root.val < self.pre.val:\n self.y = root\n if not self.x:\n self.x = self.pre\n self.pre = root\n inorder(root.right)\n inorder(root)\n self.x.val, self.y.val = self.y.val, self.x.val\n\n def recoverTree(self, root: TreeNode) -> None:\n \"\"\"\n Do not return anything, modify root in-place instead.\n \"\"\"\n curr, stack = root, []\n x = y = pre = None\n while curr or stack:\n while curr:\n stack.append(curr)\n curr = curr.left\n curr = stack.pop()\n if pre and curr.val < pre.val:\n y = curr\n if x is None:\n x = pre\n else: break\n pre = curr\n curr = curr.right\n x.val, y.val = y.val, x.val\n" }, { "alpha_fraction": 0.40419161319732666, "alphanum_fraction": 0.41766467690467834, "avg_line_length": 36.11111068725586, "blob_id": "ad52b2b89952074de5d01c46118208223bde891e", "content_id": "445cce9933958bff568461541b81303fc168eb42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 65, "num_lines": 18, "path": "/lc847_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n visited, n = set(), len(graph)\n final = (1 << n)-1\n dque = collections.deque([(1 << i, i) for i in range(n)])\n step = 0\n while dque:\n size = len(dque)\n for _ in range(size):\n state, x = dque.popleft()\n if state == final:\n return step\n for y in graph[x]:\n if (state|(1<< y), y) not in visited:\n dque.append((state|(1<< y), y))\n visited.add((state|(1<< y), y))\n step += 1\n return -1\n" }, { "alpha_fraction": 0.42664670944213867, "alphanum_fraction": 0.450598806142807, "avg_line_length": 30.809524536132812, "blob_id": "0163b2a49e94903b2c36c0e65a3c032f49d9a811", "content_id": "0985f933ebaeffc9d1540c55824d08de4ac3ffc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 66, "num_lines": 21, "path": "/lc1574_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findLengthOfShortestSubarray(self, arr: List[int]) -> int:\n n = len(arr)\n left, right = 0, n-1\n while left < n-1 and arr[left+1] >= arr[left]:\n left += 1\n if left == n-1:\n return 0\n while right > 0 and arr[right-1] <= arr[right]:\n right -= 1\n if arr[left] <= arr[right]:\n return right-left-1\n rslt = min(n-left-1, right)\n for i in range(left+1):\n if arr[i] <= arr[right]:\n rslt = min(rslt, right-i-1)\n elif right < n-1:\n right += 1\n else:\n break\n return rslt\n" }, { "alpha_fraction": 0.5125628113746643, "alphanum_fraction": 0.5326633453369141, "avg_line_length": 27.428571701049805, "blob_id": "9386bae485636cce67c13e2c7467b362ead5e1bd", "content_id": "74dbcdcf1551500bb8414ecd71cb9d64c19bc724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 65, "num_lines": 14, "path": "/lc901_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class StockSpanner:\n\n def __init__(self):\n self.last = [(float('inf'), -1)]\n self.curr = 0\n\n\n def next(self, price: int) -> int:\n while self.last and price >= self.last[-1][0]:\n self.last.pop()\n temp = self.curr if not self.last else self.last[-1][1]+1\n self.last.append((price, self.curr))\n self.curr += 1\n return self.curr - temp\n" }, { "alpha_fraction": 0.49317148327827454, "alphanum_fraction": 0.5022761821746826, "avg_line_length": 31.950000762939453, "blob_id": "f825416afa8dbdae5db94b91dc946281e74d9ea6", "content_id": "6585741115370abd84324cd637729a9f2f8af8d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "no_license", "max_line_length": 74, "num_lines": 20, "path": "/lc179_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def largestNumber(self, nums):\n self.quickSort(nums, 0, len(nums)-1)\n return str(int(\"\".join(map(str, nums))))\n\n def quickSort(self, nums, l, r):\n if l >= r: return\n pos = self.partition(nums, l, r)\n self.quickSort(nums, l, pos-1)\n self.quickSort(nums, pos+1, r)\n\n def partition(self, nums, l, r):\n pivot = l\n while l < r:\n if str(nums[l]) + str(nums[r]) > str(nums[r]) + str(nums[l]) :\n nums[l], nums[pivot] = nums[pivot], nums[l]\n pivot += 1\n l += 1\n nums[pivot], nums[r] = nums[r], nums[pivot]\n return pivot\n" }, { "alpha_fraction": 0.5072463750839233, "alphanum_fraction": 0.5144927501678467, "avg_line_length": 29.66666603088379, "blob_id": "d909cdd55d1aed8881ee8173d78f6804a2014659", "content_id": "7f6395f4264a1cf095e204d79b822b685c8da0c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 51, "num_lines": 9, "path": "/lc493_sort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def reversePairs(self, nums: List[int]) -> int:\n cand = []\n rslt = 0\n for num in nums:\n idx = bisect.bisect_right(cand, 2*num)\n rslt = rslt + len(cand)-idx\n bisect.insort(cand, num)\n return rslt\n" }, { "alpha_fraction": 0.5064575672149658, "alphanum_fraction": 0.5129151344299316, "avg_line_length": 30.882352828979492, "blob_id": "76640f13e865ac66623f672d8617f84916bc4e48", "content_id": "a9ccc3edca5135da4c6a3fb517d7e6e29ce61bfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1084, "license_type": "no_license", "max_line_length": 57, "num_lines": 34, "path": "/lc1038_bt.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "# same as 538\nclass Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n def helper(root, pre):\n if not root: return pre\n root.val += helper(root.right, pre)\n return helper(root.left, root.val)\n helper(root, 0)\n return root\nclass Solution:\n def bstToGst(self, root: TreeNode) -> TreeNode:\n def helper(root, pre):\n if not root: return (0+pre, None)\n valr, right = helper(root.right, pre)\n vall, left = helper(root.left, valr+root.val)\n root.val += valr\n root.right =right\n root.left = left\n return (vall,root)\n _, root = helper(root, 0)\n return root\n \nclass Solution:\n def convertBST(self, root: TreeNode) -> TreeNode:\n curr, stk, last = root, [], 0\n while stk or curr:\n while curr:\n stk.append(curr)\n curr = curr.right\n temp = stk.pop()\n temp.val += last\n last = temp.val\n curr = temp.left\n return root\n" }, { "alpha_fraction": 0.4921700358390808, "alphanum_fraction": 0.501118540763855, "avg_line_length": 36.25, "blob_id": "85c8796bc11817fe0ab5dfccc10ecfc3a1921aa6", "content_id": "00b228f037cded30bcb42714a82f8d7e7b214b08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 69, "num_lines": 12, "path": "/lc239_deque.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:\n rslt, holder = [], collections.deque()\n for idx, num in enumerate(nums):\n while holder and nums[holder[-1]] < num:\n holder.pop()\n holder.append(idx)\n if holder[0] <= idx-k:\n holder.popleft()\n if idx >= k-1:\n rslt.append(nums[holder[0]])\n return rslt\n" }, { "alpha_fraction": 0.5241488814353943, "alphanum_fraction": 0.5241488814353943, "avg_line_length": 29.071428298950195, "blob_id": "6cb6618ce41afdeeccffd2f22daa31dd9414f153", "content_id": "ff6464a9c49dcb42bbc0a9f589c6345ef25f48fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 75, "num_lines": 42, "path": "/lc138_linkedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):\n self.val = int(x)\n self.next = next\n self.random = random\n\"\"\"\n\nclass Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head: return None\n curr = head\n while curr:\n copy = Node(curr.val, curr.next)\n curr.next = copy\n curr = copy.next\n curr = head\n while curr:\n curr.next.random = curr.random.next if curr.random else None\n curr = curr.next.next\n curr, rslt = head, head.next\n while curr:\n temp = curr.next\n curr.next = temp.next\n temp.next = temp.next.next if temp.next else None\n curr = curr.next\n return rslt\n\nclass Solution:\n def copyRandomList(self, head: 'Node') -> 'Node':\n if not head: return None\n nodemap = {}\n def dfs(curr):\n if not curr: return None\n if curr in nodemap: return nodemap[curr]\n copy = Node(curr.val)\n nodemap[curr] = copy\n copy.next = dfs(curr.next)\n copy.random = dfs(curr.random)\n return copy\n return dfs(head)\n" }, { "alpha_fraction": 0.3534635901451111, "alphanum_fraction": 0.42451155185699463, "avg_line_length": 39.28571319580078, "blob_id": "290ba91a1b6623b754dc698d603326843ce44543", "content_id": "185d8fe1182a0993f4645eb493f59a3c6fcd2d51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 64, "num_lines": 14, "path": "/lc583_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minDistance(self, word1: str, word2: str) -> int:\n l_w1, l_w2 = len(word1), len(word2)\n dp = [[0]*(l_w2+1) for _ in range(l_w1+1)]\n for i in range(1, l_w1+1): dp[i][0] = dp[i-1][0]+1\n for j in range(1, l_w2+1): dp[0][j] = dp[0][j-1]+1\n \n for i, c1 in enumerate(word1):\n for j, c2 in enumerate(word2):\n if c1 == c2:\n dp[i+1][j+1] = dp[i][j]\n else:\n dp[i+1][j+1] = min(dp[i+1][j], dp[i][j+1])+1\n return dp[-1][-1]" }, { "alpha_fraction": 0.525611162185669, "alphanum_fraction": 0.5296856760978699, "avg_line_length": 43.0512809753418, "blob_id": "78b9ca965b2510187da0c3e02d8fd92eedf6079e", "content_id": "f69a31c9fe41db57f9d4eb659a12a45c0ec53342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1718, "license_type": "no_license", "max_line_length": 101, "num_lines": 39, "path": "/lc1203_toposort.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]:\n graph_i, graph_g = collections.defaultdict(list), collections.defaultdict(list)\n degree_i, degree_g = collections.defaultdict(int), collections.defaultdict(int)\n group_dict = collections.defaultdict(list)\n # Add to new group for item belongs to no group\n for i in range(n):\n if group[i] == -1: group[i] = m\n m += 1\n group_dict[group[i]].append(i)\n # Prepare for topo sort on groups then items\n for curr in range(n):\n for pre in beforeItems[curr]:\n if group[curr] == group[pre]:\n graph_i[pre].append(curr)\n degree_i[curr] += 1\n else:\n graph_g[group[pre]].append(group[curr])\n degree_g[group[curr]] += 1\n # order between group\n group_order, rslt = self.toposort(graph_g, degree_g, list(range(m))), []\n # order within group\n for i in group_order:\n if group_dict[i]:\n tt = self.toposort(graph_i, degree_i, group_dict[i])\n if len(tt) != len(group_dict[i]): return []\n rslt.extend(tt)\n return rslt\n\n def toposort(self, graph, degree, cands):\n dque = collections.deque([i for i in cands if degree[i] == 0])\n rslt = []\n while dque:\n pre = dque.popleft()\n rslt.append(pre)\n for post in graph[pre]:\n degree[post] -= 1\n if degree[post] == 0 and post in cands: dque.append(post)\n return rslt if len(rslt) == len(cands) else []\n" }, { "alpha_fraction": 0.41511771082878113, "alphanum_fraction": 0.4696406424045563, "avg_line_length": 35.681819915771484, "blob_id": "6082cee12bba36f479682c5e1d30f560ba47269b", "content_id": "8033dba5cfe841d849ed9342c7aa7285cd9e1e40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 78, "num_lines": 44, "path": "/lc1775_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n diff = sum(nums1) - sum(nums2)\n if diff < 0:\n nums1, nums2 = nums2, nums1\n diff = -diff\n quota = collections.Counter([x-1 for x in nums1]+[6-x for x in nums2])\n count, change = 0, 5\n while diff > 0:\n if change == 0: return -1\n if (diff-1)//change+1 <= quota[change]:\n return count + (diff-1)//change + 1\n else:\n diff, count = diff-change*quota[change], count + quota[change]\n change -= 1\n return count\n\nclass Solution:\n def minOperations(self, nums1: List[int], nums2: List[int]) -> int:\n diff = sum(nums1) - sum(nums2)\n if not diff: return 0\n if diff < 0:\n nums1, nums2 = nums2, nums1\n diff = -diff\n nums1.sort(reverse = True)\n nums2.sort()\n count, idx1, idx2, l1, l2 = 0, 0, 0, len(nums1), len(nums2)\n while idx1 < l1 or idx2 < l2:\n if diff <= 0:\n return count\n if idx1 < l1 and diff <= nums1[idx1]-1:\n return count + 1\n if idx2 < l2 and diff <= 6 - nums2[idx2]:\n return count + 1\n sub1 = (nums1[idx1]-1) if idx1 < l1 else 0\n sub2 = (6 - nums2[idx2]) if idx2 < l2 else 0\n if sub1 >= sub2 and idx1 < l1:\n diff -= sub1\n idx1 += 1\n else:\n diff -= sub2\n idx2 += 1\n count += 1\n return count if diff <= 0 else -1\n" }, { "alpha_fraction": 0.3754071593284607, "alphanum_fraction": 0.3965798020362854, "avg_line_length": 38.6129035949707, "blob_id": "adf707973150ed1051b141f3101f3fb473934d1c", "content_id": "5923f3f0d02edea54c7fd56b62e35f801bcefe0c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 71, "num_lines": 31, "path": "/lc1778_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution(object):\n def findShortestPath(self, master: 'GridMaster') -> int:\n maps = {(0, 0)}\n ops = {\"U\":\"D\", \"D\":\"U\", \"L\":\"R\", \"R\":\"L\"}\n steps = {\"U\":(1, 0), \"D\":(-1, 0), \"L\":(0, -1), \"R\":(0, 1)}\n self.target = None\n def buildmap(x, y):\n if master.isTarget(): self.target = (x, y)\n for d in steps:\n nx, ny = x + steps[d][0], y+steps[d][1]\n if (nx, ny) in maps: continue\n if master.canMove(d):\n master.move(d)\n maps.add((nx, ny))\n buildmap(nx, ny)\n master.move(ops[d])\n buildmap(0, 0)\n if self.target is None: return -1\n queue = collections.deque([(0, 0)])\n rslt = 0\n seen = {(0, 0)}\n while queue:\n for _ in range(len(queue)):\n x, y = queue.popleft()\n if (x, y) == self.target: return rslt\n for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:\n if (nx, ny) in maps and (nx, ny) not in seen:\n seen.add((nx, ny))\n queue.append((nx, ny))\n rslt += 1\n return -1\n" }, { "alpha_fraction": 0.43800538778305054, "alphanum_fraction": 0.4501347839832306, "avg_line_length": 31.2608699798584, "blob_id": "03316d1c16fc697bd9534a0de80a62cde149097d", "content_id": "b12012d544a479a2469a03a1a3756563162666d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 742, "license_type": "no_license", "max_line_length": 53, "num_lines": 23, "path": "/lc765_unionfind.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n parent = [x//2*2 for x in range(len(row))]\n size = [1]*len(row)\n def find(p):\n while p != parent[p]:\n parent[p] = parent[parent[p]]\n p = parent[p]\n return p\n\n def union(p, q):\n rootp, rootq = find(p), find(q)\n if rootp == rootq: return False\n if size[rootp] < size[rootq]:\n rootp, rootq = rootq, rootp\n parent[rootq] = rootp\n size[rootp] += size[rootq]\n return True\n rslt = 0\n for i in range(len(row)//2):\n if union(row[i*2], row[i*2+1]):\n rslt += 1\n return rslt\n" }, { "alpha_fraction": 0.4419354796409607, "alphanum_fraction": 0.4580645263195038, "avg_line_length": 31.55555534362793, "blob_id": "7cb580a9051349c7d006d5480a2286126673572b", "content_id": "aa9a3d42868df649627f4e7573340b04b519e8ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 310, "license_type": "no_license", "max_line_length": 72, "num_lines": 9, "path": "/lc1288_array.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeCoveredIntervals(self, intervals: List[List[int]]) -> int:\n intervals.sort(key = lambda x:(x[0], -x[1]))\n last, cnt = -1, 0\n for x, y in intervals:\n if y > last:\n last = y\n cnt += 1\n return cnt\n \n" }, { "alpha_fraction": 0.40978261828422546, "alphanum_fraction": 0.427173912525177, "avg_line_length": 47.421051025390625, "blob_id": "af42ddaa7a83c8f55e324fc32c69b934714a54eb", "content_id": "d663955428e76e76e8f413a8acf8761a9fcf3153", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 72, "num_lines": 19, "path": "/lc679_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if not nums: return False\n if len(nums) == 1: return 23.9 < nums[0] < 24.1\n for i in range(len(nums)):\n for j in range(i):\n if i > j:\n nums_next = nums[:j]+nums[j+1:i]+nums[i+1:]\n for op in (truediv, mul, add, sub):\n if op is not truediv or nums[j]:\n nums_next.append(op(nums[i], nums[j]))\n if self.judgePoint24(nums_next): return True\n nums_next.pop()\n if op in (add, mul): continue\n if op is sub or nums[i]:\n nums_next.append(op(nums[j], nums[i]))\n if self.judgePoint24(nums_next): return True\n nums_next.pop()\n return False\n" }, { "alpha_fraction": 0.5169811248779297, "alphanum_fraction": 0.5188679099082947, "avg_line_length": 36.78571319580078, "blob_id": "ed1eede5df1882b3e2c9d63dc792b3cca6fff408", "content_id": "49edd37b88b2660a304fa1a250f77175ca6652b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 530, "license_type": "no_license", "max_line_length": 73, "num_lines": 14, "path": "/lc690_bfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def getImportance(self, employees: List['Employee'], id: int) -> int:\n hold = {x.id: i for i, x in enumerate(employees)}\n dque = collections.deque([id])\n visited, rslt = {id}, 0\n while dque:\n curr = dque.popleft()\n employee = employees[hold[curr]]\n rslt += employee.importance\n for n in employee.subordinates:\n if n not in visited:\n visited.add(n)\n dque.append(n)\n return rslt \n" }, { "alpha_fraction": 0.5021833777427673, "alphanum_fraction": 0.5152838230133057, "avg_line_length": 31.714284896850586, "blob_id": "139ffb3d3997d57287c12343a24e2178033ebc32", "content_id": "5c9b76464f7388f2b2f0adcf76ba9a76e755d699", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/lc53_dp.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n temp, rslt = nums[0], nums[0]\n for num in nums[1:]:\n temp = max(temp + num, num)\n rslt = max(temp, rslt)\n return rslt\n" }, { "alpha_fraction": 0.4598168730735779, "alphanum_fraction": 0.475076287984848, "avg_line_length": 32.89655303955078, "blob_id": "124f6a52893b5c4f868edd6291e9e267f37657c3", "content_id": "83bf3ba55eecde7e10eed7b347c4f742129eb814", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 983, "license_type": "no_license", "max_line_length": 99, "num_lines": 29, "path": "/lc930_hashtable.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def numSubarraysWithSum(self, A: List[int], S: int) -> int:\n prefix, rslt, temp = 0, 0, {0:1}\n for i, x in enumerate(A):\n prefix += x\n if prefix-S in temp:\n rslt += temp[prefix-S]\n temp[prefix] = temp.get(prefix, 0)+1\n return rslt\n \nclass Solution:\n def numSubarraysWithSum(self, nums: List[int], goal: int) -> int:\n left_lo, left_hi = 0, 0\n last_lo, last_hi = 0, 0\n rslt = 0\n for right, num in enumerate(nums):\n last_lo += num\n last_hi += num\n\n while left_lo < right and last_lo > goal:\n last_lo -= nums[left_lo]\n left_lo += 1\n while left_hi < right and (last_hi > goal or (last_hi == goal and nums[left_hi] == 0)):\n last_hi -= nums[left_hi]\n left_hi += 1\n\n if last_lo == goal:\n rslt += left_hi - left_lo + 1\n return rslt\n" }, { "alpha_fraction": 0.35752686858177185, "alphanum_fraction": 0.3844085931777954, "avg_line_length": 30, "blob_id": "60c0e4ded3229da88a777599bd70a476008fece2", "content_id": "96b0b08ceee364880033c0033d24fc925d25283d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 372, "license_type": "no_license", "max_line_length": 53, "num_lines": 12, "path": "/lc1371_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findTheLongestSubstring(self, s: str) -> int:\n mask = {\"a\":1, \"e\":2, \"i\":4, \"o\":8, \"u\":16}\n d, n, res = {0:-1}, 0, 0\n for i, c in enumerate(s):\n if c in mask:\n n ^= mask[c]\n if n not in d:\n d[n] = i\n else:\n res = max(res, i-d[n])\n return res\n" }, { "alpha_fraction": 0.3419540226459503, "alphanum_fraction": 0.37068966031074524, "avg_line_length": 30.636363983154297, "blob_id": "7cbb9ca2fd6ea88216e0c07a5df05104ddeda1fd", "content_id": "18942add6c81db222d3e5a88bc2e244a2f6fcf9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 348, "license_type": "no_license", "max_line_length": 54, "num_lines": 11, "path": "/lc1209_stack.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def removeDuplicates(self, s: str, k: int) -> str:\n stk = []\n for c in s:\n if stk and c == stk[-1][0]:\n stk[-1][1] +=1\n if stk[-1][1] == k:\n stk.pop()\n else:\n stk.append([c, 1])\n return \"\".join([x[0]*x[1] for x in stk])\n" }, { "alpha_fraction": 0.4740259647369385, "alphanum_fraction": 0.47922077775001526, "avg_line_length": 37.04999923706055, "blob_id": "33175cb998d50e782cdc9edc364d90f2bd00a42d", "content_id": "58f6743a29082f8f379a60d681e2a3c0caea7930", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 770, "license_type": "no_license", "max_line_length": 79, "num_lines": 20, "path": "/lc863_tree.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def distanceK(self, root: TreeNode, target: TreeNode, K: int) -> List[int]:\n maps = {}\n def get_parents(curr, prev):\n if curr:\n maps[curr] = prev\n get_parents(curr.left, curr)\n get_parents(curr.right, curr)\n get_parents(root, None)\n queue = collections.deque([(target, 0)])\n visited = {target}\n while queue:\n if queue[0][1] == K:\n return [x.val for x, y in queue]\n node, dist = queue.popleft()\n for nxt in [node.left, node.right, maps[node]]:\n if nxt and nxt not in visited:\n visited.add(nxt)\n queue.append((nxt, dist + 1))\n return []\n \n" }, { "alpha_fraction": 0.4175824224948883, "alphanum_fraction": 0.4263736307621002, "avg_line_length": 34, "blob_id": "50638d619415e82ffb1ee0a880920159c226add2", "content_id": "82fbe0e128699d1adc998601f68739ca708bcf89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "no_license", "max_line_length": 54, "num_lines": 13, "path": "/lc131_bk.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def partition(self, s: str) -> List[List[str]]:\n rslt, n, checked = [], len(s), set()\n def backtracking(left, curr):\n if left == n:\n rslt.append(curr)\n else:\n for j in range(left, n):\n temp = s[left:j+1]\n if temp == temp[::-1]:\n backtracking(j+1, curr+[temp])\n backtracking(0, [])\n return rslt\n" }, { "alpha_fraction": 0.493630588054657, "alphanum_fraction": 0.4968152940273285, "avg_line_length": 32.05263137817383, "blob_id": "6c6f149f2db012aed4b0c871e6ff178323148bf0", "content_id": "73fefef61b6772d4b48c4a0fb1dca97ea9e6c8ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 628, "license_type": "no_license", "max_line_length": 74, "num_lines": 19, "path": "/lc1681_dfs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def minimumIncompatibility(self, nums: List[int], k: int) -> int:\n d = len(nums)//k\n count = collections.Counter(nums)\n if max(count.values()) > k: return -1\n\n @lru_cache(None)\n def dfs(curr):\n if not curr:\n return 0\n rslt = float(\"inf\")\n\n for comb in itertools.combinations(set(curr), d):\n remain = list(curr)\n for t in comb:\n remain.remove(t)\n rslt = min(rslt, max(comb)-min(comb) + dfs(tuple(remain)))\n return rslt\n return dfs(tuple(nums))\n" }, { "alpha_fraction": 0.5203996896743774, "alphanum_fraction": 0.5287260413169861, "avg_line_length": 35.39393997192383, "blob_id": "9d6b3d6bb162a57ca82e9eee5a9993c32854649f", "content_id": "84c76162a90d9457f90d9cdf591f81f89896be78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 75, "num_lines": 33, "path": "/lc1825_sortedlist.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "from sortedcontainers import SortedList\nclass MKAverage:\n\n def __init__(self, m: int, k: int):\n self.m, self.k = m, k\n self.win = collections.deque([0]*m)\n self.o_win = SortedList([0]*m)\n self.sum_k, self.sum_m_k = 0, 0\n\n def addElement(self, num: int) -> None:\n self.win.append(num)\n # update out of window ele\n oow = self.win.popleft()\n i_oow = self.o_win.bisect_right(oow)\n if i_oow <= self.k:\n self.sum_k = self.sum_k - oow + self.o_win[self.k]\n if i_oow <= self.m - self.k:\n self.sum_m_k = self.sum_m_k - oow + self.o_win[self.m-self.k]\n self.o_win.remove(oow)\n # update new ele\n i_new = self.o_win.bisect_right(num)\n if i_new < self.k:\n self.sum_k = self.sum_k - self.o_win[self.k-1] + num\n if i_new < self.m-self.k:\n self.sum_m_k = self.sum_m_k - self.o_win[self.m-self.k-1] + num\n self.o_win.add(num)\n return\n\n def calculateMKAverage(self) -> int:\n # print(self.o_win, self.sum_m_k, self.sum_k)\n if self.o_win[0] == 0:\n return -1\n return (self.sum_m_k - self.sum_k) // (self.m - self.k*2)\n" }, { "alpha_fraction": 0.424119234085083, "alphanum_fraction": 0.4444444477558136, "avg_line_length": 35, "blob_id": "1c2c7e16a4288925ad9584a7616fc695c10512c3", "content_id": "3cd6bb10b4cb762b901f860458c89106ea34a3fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 77, "num_lines": 20, "path": "/lc1793_twopointer.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def maximumScore(self, nums: List[int], k: int) -> int:\n left, right = k, k\n rslt = nums[k]\n tempmin = nums[k]\n n = len(nums)\n while left > 0 or right < n-1:\n if left == 0 or (right < n-1 and nums[left-1] < nums[right+1]):\n right += 1\n tempmin = min(nums[right], tempmin)\n elif right == n-1 or (left > 0 and nums[left-1] > nums[right+1]):\n left -= 1\n tempmin = min(nums[left], tempmin)\n else:\n left -= 1\n right += 1\n tempmin = min(nums[right], tempmin)\n\n rslt = max(rslt, (right-left+1)*tempmin)\n return rslt\n\n \n" }, { "alpha_fraction": 0.4253164529800415, "alphanum_fraction": 0.4430379867553711, "avg_line_length": 31.91666603088379, "blob_id": "d8ce35bf62da923c4cb3b47ae81a143db439fe09", "content_id": "454fcd0c085081c6ce86c859d287a10b80795a96", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 62, "num_lines": 12, "path": "/lc162_bs.py", "repo_name": "Mela2014/lc_punch", "src_encoding": "UTF-8", "text": "class Solution:\n def findPeakElement(self, nums: List[int]) -> int:\n left, right = 0, len(nums)-1\n while left <= right:\n mid = (left + right)//2\n if mid < len(nums)-1 and nums[mid] < nums[mid+1]:\n left = mid+1\n else:\n right = mid\n if (left + right) //2 == mid:\n break\n return left\n" } ]
322
ogspeace/quotedreps
https://github.com/ogspeace/quotedreps
d5009267b3ec0f86441c52e70b14b7166f3f09b9
3810d3afc89632f68f6b27d683367a403e0d95b9
e0d93837a131717c8b3ef6fdc5d54d72778b593a
refs/heads/master
2022-09-03T11:56:35.415820
2020-05-24T11:23:10
2020-05-24T11:23:10
266,524,169
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7558139562606812, "alphanum_fraction": 0.7591361999511719, "avg_line_length": 45.30769348144531, "blob_id": "3da401259d15195b409a3f3056b396eeb5354ab8", "content_id": "bd37033ea60551d19effc5af3a11827eed083fd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 602, "license_type": "no_license", "max_line_length": 110, "num_lines": 13, "path": "/README.md", "repo_name": "ogspeace/quotedreps", "src_encoding": "UTF-8", "text": "# quotedreps\nsimple command line python script that generates a URL string containing the quoted replies of a user's tweet.\n\n# requirements\n* Use python3.6+<br/>\n* I use git bash to execute my script.\n\n# usage\n* look and click on a tweet you want to get the quoted replies of.<br/>\n* on the address bar of your browser, copy the tweet URL.<br/>\n* on your command line interface or terminal type ``python quotedreplies.py pastetheurloftweethere ``<br/>\n* the script would then generate a URL string containing the full query of your quoted replies. <br/>\n* copy this string and paste it on your browser\n" }, { "alpha_fraction": 0.703832745552063, "alphanum_fraction": 0.7177700400352478, "avg_line_length": 46.83333206176758, "blob_id": "2de12ca8d11498f6dba0fb19e0b96e9c5a01ad5a", "content_id": "bd6f046b2403d46c7905e12bc90aa5e0d6ac4650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 287, "license_type": "no_license", "max_line_length": 118, "num_lines": 6, "path": "/quotedreplies.py", "repo_name": "ogspeace/quotedreps", "src_encoding": "UTF-8", "text": "import sys\n\ntweet_id = sys.argv[1].split('/')[-1]\nurl_string = f\"https://twitter.com/search?q=-from:quotedreplies%20url:{tweet_id}&src=typed_query&f=live\"\nif tweet_id:\n print(f\"copy the following url to your browser to view all quoted replies of your chosen tweet: \\n\\n{url_string}\")\n" } ]
2
GhostingRecon/Oblig1
https://github.com/GhostingRecon/Oblig1
93a3bc95ae892783582a800e19d6685ae6ed99d8
0277e07f4035608ec38c78d666fb8bf09a459b06
b5fb6683979705b9ff8c63c2446979e4b0f049e7
refs/heads/master
2020-07-31T10:56:50.681797
2019-10-22T12:13:25
2019-10-22T12:13:25
210,580,691
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5264720320701599, "alphanum_fraction": 0.5685304403305054, "avg_line_length": 17.44748878479004, "blob_id": "bed8c5370bfb4face09192d37c3a6bd8c94f7022", "content_id": "f425bf8612d581b3adc3458bc6f85a46ebc2f2f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4053, "license_type": "no_license", "max_line_length": 84, "num_lines": 219, "path": "/sem_1.py", "repo_name": "GhostingRecon/Oblig1", "src_encoding": "UTF-8", "text": "#Oblig_1\n\n\n\n#1\n\ntall_1 = int(input(\"Tall nr 1: \"))\ntall_2 = int(input(\"Tall nr 2: \"))\ntall_3 = int(input(\"Tall nr 3: \"))\nprint()\n\nprint(\"Tall nr 1: \" + str(tall_1))\nprint(\"Tall nr 2: \" + str(tall_2))\nprint(\"Tall nr 2: \" + str(tall_3))\n\n\nif tall_1 < tall_2 < tall_3:\n print(\"Strengt stigende\")\nelif tall_1 > tall_2 > tall_3:\n print(\"Strengt synkende\")\nelse:\n print(\"Verken strengt stigende eller synkende\")\n\n#2\n\nprint()\n#2.a\n\n\n\nkort = input(\"Skriv inn \\\"kort tegn\\\" for konvertering (D, H, S, C): \").upper()\n\nif kort == \"D\":\n print(\"Ruter\")\nelif kort == \"H\":\n print(\"Hjerter\")\nelif kort == \"S\":\n print(\"Spar\")\nelif kort == \"C\":\n print(\"Kløver\")\nelse:\n print(\"ikke et tegn i kortstokken\")\n\nprint()\n\n#2.b\n\"\"\"lager en array med alle tall og tegn\"\"\"\n\ntegnDict = {\n \"A\": \"Ess\",\n \"2\": \"To\",\n \"3\": \"Tre\",\n \"4\": \"Fire\",\n \"5\": \"Fem\",\n \"6\": \"Seks\",\n \"7\": \"Syv\",\n \"8\": \"Åtte\",\n \"9\": \"Ni\",\n \"10\": \"Ti\",\n \"J\": \"Knekt\",\n \"Q\": \"Dame\",\n \"K\": \"Konge\"\n\n}\n\n\"\"\"Legger til upper her siden alle ord er med stor bokstav\"\"\"\n\nbruker = input(\"tast inn tegn eller tall for konvertering: \").upper()\n\n\"\"\"Printer så verdien\"\"\"\n\nprint(tegnDict[bruker])\n\n\nprint()\n\n#2.a og 2.b\n\nkort_konvertering = input(\"Skriv inn nummer og korttegn for konvertering: \").upper()\n\nliste = list(kort_konvertering)\n\n\n\ndef kort(type):\n\n\n kortNummer = {\n \"A\": \"Ess\",\n \"2\": \"To\",\n \"3\": \"Tre\",\n \"4\": \"Fire\",\n \"5\": \"Fem\",\n \"6\": \"Seks\",\n \"7\": \"Syv\",\n \"8\": \"Åtte\",\n \"9\": \"Ni\",\n \"10\": \"Ti\",\n \"J\": \"Knekt\",\n \"Q\": \"Dame\",\n \"K\": \"Konge\"\n}\n\n kortTegn = {\n \"D\": \"Ruter\",\n \"H\": \"Hjerter\",\n \"S\": \"Spar\",\n \"C\": \"Kløver\"\n}\n return kortNummer[type[0]] + \" \" + kortTegn[type[1]]\n\n\nprint(kort(liste))\n\n#3\n\nprint()\n\n#3.a\n\n\n\nvaluta = {\n \"EUR\": 9.68551,\n \"USD\": 8.50373,\n \"GBP\": 11.0134,\n \"SEK\": 0.92950,\n \"AUD\": 6.06501,\n \"NOK\": 1.00000\n}\nprint(\"valuttakalkulator til NOK\")\nverdiInput = float(input(\"Verdi for konvertering: \"))\nvalutaInput = input(\"Fra hvilke valutta: \").upper()\n\nprint(verdiInput * valuta[valutaInput], \"NOK\")\n\nprint()\n#3.b\n\"\"\"skal bare gå andre veien her så da kan jeg bruke samme dictionary som i a\"\"\"\n\nprint(\"valutakalkulator fra NOK\")\nverdiInputFra = float(input(\"Verdi for konvertering: \"))\nvalutaInputFra = input(\"Til hvilke valutta: \").upper()\n\nprint(verdiInputFra / valuta[valutaInputFra], valutaInputFra)\n\nprint()\n#4\n\"\"\"Printe ut alle heltall fra 0-9 i potens 3\"\"\"\n\nfor x in range(0, 10+1):\n print(str(x) + \"**\" + str(3), \"=\", str(x**3))\n\n#5.a\nprint()\n\ninputStart = int(input(\"Start: \"))\ninputStop = int(input(\"Stop: \"))\ninputN = int(input(\"n: \"))\n\nprint(\"Verdier mellom\", str(inputStart), \"og\", str(inputStop),\n \"som er delelige på\", str(inputN) + \":\")\n\nfor n in range(inputStart, inputStop+1):\n\n if n % inputN == 0:\n print(n)\n\nprint()\n#6\n\n#6.a\n\ndef tilFahrenheit(celsius):\n return int(celsius * 1.800)+32\nprint(\"Celsius Fahrenheit\")\nfor n in range(0, 100+1, 10):\n print(\"%7d %12d\" % (n, tilFahrenheit(n)))\n\n\nprint()\n#6.b\n\n\"\"\"def tilFahrenheit(celsius):\n return int(celsius * 1.800)+32\nprint(\"Celsius Fahrenheit Status\")\nfor n in range(0, 100+1, 10):\n\n if n >= 60:\n print(\"%7d %12d %s\" % (n, tilFahrenheit(n), str(\"Jeg svetter ihjel! \")))\n else:\n print(\"7d %12d %s\" % (n, tilFahrenheit(n) ,str(\"Jeg har det bra\")))\"\"\"\n\n\n\ndef tilFahrenheit(celsius):\n return int(celsius * 1.800) + 32\nprint(\"Celsius Fahrenheit Status\")\nfor n in range(0, 100+1, 10):\n if n >= 60:\n print(\"%7d %12d %23s\" % (n, tilFahrenheit(n), str(\"jeg svetter ihjel! \")))\n else:\n print(\"%7d %12d %21s\" % (n, tilFahrenheit(n), str(\"jeg har det bra. \")))\n\n#7\n\nprint()\n\nverdi = float(input(\"Hvor mye har du?: \"))\nfra = float(input(\"Fra år: \"))\ntil = float(input(\"Til år: \"))\n\ndef renteOkning(verdi, fra, til):\n\n tid = til - fra\n endring = verdiInputFra * (1.02 ** tid)\n return endring\nprint(round(renteOkning(verdi, fra, til), 2),\n \"Kroner med 2% inflasjonsøkning\")\n\n\n" }, { "alpha_fraction": 0.5002036094665527, "alphanum_fraction": 0.5622963905334473, "avg_line_length": 24.57291603088379, "blob_id": "77013bac7bc624bfe922f43fbe538e3478afffa7", "content_id": "38c30e91bc8becb4f0649c02f1be1bc5c5f75fe2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4926, "license_type": "no_license", "max_line_length": 96, "num_lines": 192, "path": "/semester_oppgave_2.py", "repo_name": "GhostingRecon/Oblig1", "src_encoding": "UTF-8", "text": "\n\nimport matplotlib.pyplot as plt\nimport random\n\n\ndef oppgave1():\n \"\"\" Printer ut store tall i kort og lang form,\n ofte kalt amerikansk og britisk form.\n \"\"\"\n store_tall = [\n [\"Million\", \"10^6 \", \"10^6 \"],\n [\"Milliard\", \" \", \"10^9 \"],\n [\"Billion\", \"10^9 \", \"10^12\"],\n [\"Billiard\", \" \", \"10^15\"],\n [\"Trillion\", \"10^12\", \"10^18\"],\n [\"Quadrillion\",\"10^15\", \"10^24\"],\n [\"Quintillion\",\"10^18\", \"10^30\"],\n [\"Sextillion\", \"10^21\", \"10^36\"]\n ] # Hentet fra https://en.wikipedia.org/wiki/Names_of_large_numbers\n\n print(\"%-15s %9s %9s\" % (\"Navn\", \"lang\", \"Kort\"))\n for i in store_tall:\n print(\"%-15s %9s %9s\" % tuple(i))\n\n\n\n# I billion USD (kort form)\n\nmicrosoft_inntekt_dollar = [\n [2002, 28.37],\n [2003, 32.19],\n [2004, 36.84],\n [2005, 39.79],\n [2006, 44.28],\n [2007, 51.12],\n [2008, 60.42],\n [2009, 58.44],\n [2010, 62.48],\n [2011, 69.94],\n [2012, 73.12],\n [2013, 77.85],\n [2014, 86.83],\n [2015, 93.58],\n [2016, 85.32],\n [2017, 89.95],\n [2018, 110.36],\n [2019, 125.84]\n] # Hentet fra https://www.statista.com/statistics/267805/microsofts-global-revenue-since-2002/\n\n#legger inn kursen\nvaluta = float(8.6862)\n\n\ndef oppgave2a():\n \"\"\" Henter en rekke tall fra brukeren og ut hva som\n var medianen i listen\n \"\"\"\n\n tall_liste = []\n while True:\n bruker_input = input(\"Skriv inn tall (avslutt med ferdig): \")\n if bruker_input == \"ferdig\":\n break\n tall_liste.append(int(bruker_input))\n print(\"Dine tall:\", tall_liste)\n\n tall_liste.sort()\n if len(tall_liste) % 2 == 0:\n ny_1 = int(len(tall_liste) /2)\n ny_2 = ny_1 - 1\n median = (tall_liste[ny_1] + tall_liste[ny_2]) /2\n print(\"Medianen til tallene: \", median)\n else:\n print(\"Medianen til tallene: \", tall_liste[int(len(tall_liste)/2)])\n\n pass\n#kopierer listen\nmicrosoft_inntekt_kroner_ny = microsoft_inntekt_dollar.copy()\ndef oppgave3a():\n \"\"\" Konverterer inntektene fra dollar til kroner\n uten å gjøre endringer på originallisten.\n \"\"\"\n #multipliserer index i ny liste med valuta\n microsoft_inntekt_kroner = [valuta * i[-1] for i in microsoft_inntekt_kroner_ny]\n print(\"I NOK:\", [float(round(n, 2)) for n in microsoft_inntekt_kroner])\n print(\"Orginal:\", microsoft_inntekt_dollar)\n\n \"\"\" berge sin kommentar: for n in microsoft_inntekt_dollar:\n print(\"%-15s %-15s %10s\" %(n[0], n[1], n[1]*usdtilNOK))\"\"\"\n\n\n\ndef oppgave3b():\n \"\"\" Tegner et histogram over inntektene til Microsoft\n \"\"\"\n year = []\n inntekt = []\n for i in range(0, len(microsoft_inntekt_dollar)):\n year.append(microsoft_inntekt_dollar[i][0])\n inntekt.append(microsoft_inntekt_dollar[i][1])\n plt.bar(year, inntekt)\n plt.show()\n\n\n\ndef oppgave3c():\n \"\"\" Summerer opp inntektene til Microsoft\n \"\"\"\n inntekt = []\n for i in range(0, len(microsoft_inntekt_dollar)):\n inntekt.append(microsoft_inntekt_dollar[i][1])\n total_milliard = sum(inntekt)\n total_billion = int(total_milliard * 100)\n print(\"Microsoft tjente\", total_billion, \"billioner dollar i perioden 2002-2019\")\n\n\ndef print_kart(spiller, monster):\n x = 0\n while x <= 10:\n y = 0\n kart_liste = []\n while y <= 10:\n if x == spiller[1] and y == spiller[0]:\n kart_liste.append(\"S\")\n elif x == monster[1] and y == monster[0]:\n kart_liste.append(\"M\")\n else: kart_liste.append(\"* \")\n\n y = y + 1\n\n samlet = \" \".join(kart_liste)\n\n print(samlet)\n\n x = x + 1\n\nspiller = [2, 6]\nmonster = [4, 5]\n\ndef spiller_bevegelse():\n flytt = input()\n\n if flytt == \"W\":\n spiller[1] = spiller[1] - 1\n if flytt == \"a\":\n spiller[0] = spiller[0] - 1\n if flytt == \"s\":\n spiller[1] = spiller[1] + 1\n if flytt == \"d\":\n spiller[0] = spiller[0] + 1\n\n monster[0] = monster[0] + random.randint(-1, 1)\n monster[1] = monster[1] + random.randint(-1, 1)\n\ndef spill():\n\n print(\"wasd + enter for å bevege seg\")\n print_kart(spiller, monster)\n\n try:\n while True:\n spiller_bevegelse()\n print_kart(spiller, monster)\n except KeyboardInterrupt:\n exit()\n\n\n\n\n\ndef main():\n \"\"\" Dette er filens main-funksjon, det er denne funksjonen som kjører\n når hele filen blir kjørt. \n Hvis du vil kjøre en av oppgave-funksjonene nedenfor fjerner du #-tegnet \n foran oppgave-funksjonen slik at den blir \"skrudd på\".\n Før du leverer kan det være lurt å sjekke alle funksjonene. Dette gjør \n du ved å fjerne alle #-tegnene nedenfor.\n \"\"\"\n oppgave1()\n print()\n oppgave2a()\n print()\n print()\n oppgave3a()\n print()\n oppgave3b()\n print()\n oppgave3c()\n print()\n spill()\n print()\n\nmain()\n" }, { "alpha_fraction": 0.7777777910232544, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 17, "blob_id": "cd1fd084005d7394e80f7aea08d4022221555946", "content_id": "b52b4b1a1690bb9af5006113cedb6f665684296f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 36, "license_type": "no_license", "max_line_length": 26, "num_lines": 2, "path": "/README.md", "repo_name": "GhostingRecon/Oblig1", "src_encoding": "UTF-8", "text": "# Oblig1\nobligatorisk innlevering 1\n" } ]
3
moritzhertler/Artemis
https://github.com/moritzhertler/Artemis
d6b063ffe7e4b664f073929fbd125858dcb59cf9
ae7f91c050c6db996cab78da9c2a1b675cab4e21
11bbc8931c047946a7ef58a9af7bb2bbafa7d993
refs/heads/main
2023-04-06T06:32:25.071429
2021-04-09T22:12:08
2021-04-09T22:12:08
357,192,785
1
0
MIT
2021-04-12T12:53:56
2021-04-12T11:03:55
2021-04-12T12:21:15
null
[ { "alpha_fraction": 0.6124572157859802, "alphanum_fraction": 0.6164271235466003, "avg_line_length": 43.272727966308594, "blob_id": "dd536202cf5bae9f3d69472c3b2f38f3200efd6c", "content_id": "e7cde517c75456c9b31a84e90dd70e5809f8fc59", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7305, "license_type": "permissive", "max_line_length": 180, "num_lines": 165, "path": "/src/test/javascript/spec/component/lecture-unit/video-unit/edit-video-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\n\nimport { VideoUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component';\nimport { VideoUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/videoUnit.service';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { EditVideoUnitComponent } from 'app/lecture/lecture-unit/lecture-unit-management/edit-video-unit/edit-video-unit.component';\nimport { MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-video-unit-form', template: '' })\nclass VideoUnitFormStubComponent {\n @Input() isEditMode = false;\n @Input() formData: VideoUnitFormData;\n @Output() formSubmitted: EventEmitter<VideoUnitFormData> = new EventEmitter<VideoUnitFormData>();\n}\n\n@Component({ selector: 'jhi-lecture-unit-layout', template: '<ng-content></ng-content>' })\nclass LectureUnitLayoutStubComponent {\n @Input()\n isLoading = false;\n}\n\ndescribe('EditVideoUnitComponent', () => {\n let editVideoUnitComponentFixture: ComponentFixture<EditVideoUnitComponent>;\n let editVideoUnitComponent: EditVideoUnitComponent;\n const sandbox = sinon.createSandbox();\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [VideoUnitFormStubComponent, LectureUnitLayoutStubComponent, EditVideoUnitComponent],\n providers: [\n MockProvider(VideoUnitService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'videoUnitId':\n return 1;\n }\n },\n }),\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'lectureId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n editVideoUnitComponentFixture = TestBed.createComponent(EditVideoUnitComponent);\n editVideoUnitComponent = editVideoUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n editVideoUnitComponentFixture.detectChanges();\n expect(editVideoUnitComponent).to.be.ok;\n });\n\n it('should set form data correctly', () => {\n const videoUnitService = TestBed.inject(VideoUnitService);\n\n const videoUnitOfResponse = new VideoUnit();\n videoUnitOfResponse.id = 1;\n videoUnitOfResponse.name = 'test';\n videoUnitOfResponse.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n videoUnitOfResponse.description = 'lorem ipsum';\n videoUnitOfResponse.source = 'https://www.youtube.com/embed/M7lc1UVf-VE';\n\n const response: HttpResponse<VideoUnit> = new HttpResponse({\n body: videoUnitOfResponse,\n status: 200,\n });\n\n const findByIdStub = sandbox.stub(videoUnitService, 'findById').returns(of(response));\n const videoUnitFormStubComponent: VideoUnitFormStubComponent = editVideoUnitComponentFixture.debugElement.query(By.directive(VideoUnitFormStubComponent)).componentInstance;\n editVideoUnitComponentFixture.detectChanges(); // onInit\n expect(editVideoUnitComponent.videoUnit).to.equal(videoUnitOfResponse);\n expect(findByIdStub).to.have.been.calledOnce;\n expect(editVideoUnitComponent.formData.name).to.equal(videoUnitOfResponse.name);\n expect(editVideoUnitComponent.formData.releaseDate).to.equal(videoUnitOfResponse.releaseDate);\n expect(editVideoUnitComponent.formData.description).to.equal(videoUnitOfResponse.description);\n expect(editVideoUnitComponent.formData.source).to.equal(videoUnitOfResponse.source);\n expect(videoUnitFormStubComponent.formData).to.equal(editVideoUnitComponent.formData);\n });\n\n it('should send PUT request upon form submission and navigate', () => {\n const router: Router = TestBed.inject(Router);\n const videoUnitService = TestBed.inject(VideoUnitService);\n\n const videoUnitInDatabase: VideoUnit = new VideoUnit();\n videoUnitInDatabase.id = 1;\n videoUnitInDatabase.name = 'test';\n videoUnitInDatabase.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n videoUnitInDatabase.description = 'lorem ipsum';\n videoUnitInDatabase.source = 'https://www.youtube.com/embed/M7lc1UVf-VE';\n\n const findByIdResponse: HttpResponse<VideoUnit> = new HttpResponse({\n body: videoUnitInDatabase,\n status: 200,\n });\n const findByIdStub = sandbox.stub(videoUnitService, 'findById').returns(of(findByIdResponse));\n\n editVideoUnitComponentFixture.detectChanges(); // onInit\n expect(findByIdStub).to.have.been.calledOnce;\n expect(editVideoUnitComponent.videoUnit).to.equal(videoUnitInDatabase);\n\n const changedUnit: VideoUnit = {\n ...videoUnitInDatabase,\n name: 'Changed',\n };\n\n const updateResponse: HttpResponse<VideoUnit> = new HttpResponse({\n body: changedUnit,\n status: 200,\n });\n const updatedStub = sandbox.stub(videoUnitService, 'update').returns(of(updateResponse));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n const textUnitForm: VideoUnitFormStubComponent = editVideoUnitComponentFixture.debugElement.query(By.directive(VideoUnitFormStubComponent)).componentInstance;\n textUnitForm.formSubmitted.emit({\n name: changedUnit.name,\n description: changedUnit.description,\n releaseDate: changedUnit.releaseDate,\n source: changedUnit.source,\n });\n\n expect(updatedStub).to.have.been.calledOnce;\n expect(navigateSpy).to.have.been.calledOnce;\n navigateSpy.restore();\n });\n});\n" }, { "alpha_fraction": 0.621839702129364, "alphanum_fraction": 0.621839702129364, "avg_line_length": 35.45098114013672, "blob_id": "df0bac7992c1089bbf5cd691d557f701956175a9", "content_id": "2c98e80b0ad670a7b2204125920b3c52efaae589", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3718, "license_type": "permissive", "max_line_length": 112, "num_lines": 102, "path": "/src/main/webapp/app/course/manage/course-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Subscription } from 'rxjs/Subscription';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from './course-management.service';\nimport { CachingStrategy } from 'app/shared/image/secured-image.component';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { ButtonSize } from 'app/shared/components/button.component';\nimport { Subject } from 'rxjs';\n\n@Component({\n selector: 'jhi-course-detail',\n templateUrl: './course-detail.component.html',\n styleUrls: ['./course-detail.component.scss'],\n})\nexport class CourseDetailComponent implements OnInit, OnDestroy {\n ButtonSize = ButtonSize;\n ActionType = ActionType;\n CachingStrategy = CachingStrategy;\n course: Course;\n private eventSubscriber: Subscription;\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(\n private eventManager: JhiEventManager,\n private courseService: CourseManagementService,\n private route: ActivatedRoute,\n private router: Router,\n private jhiAlertService: JhiAlertService,\n ) {}\n\n /**\n * On init load the course information and subscribe to listen for changes in courses.\n */\n ngOnInit() {\n this.route.data.subscribe(({ course }) => {\n this.course = course;\n\n this.registerChangeInCourses();\n });\n }\n\n /**\n * Subscribe to changes in courses and reload the course after a change.\n */\n registerChangeInCourses() {\n this.eventSubscriber = this.eventManager.subscribe('courseListModification', () => {\n this.courseService.find(this.course.id!).subscribe((courseResponse: HttpResponse<Course>) => {\n this.course = courseResponse.body!;\n });\n });\n }\n\n /**\n * Register for the currently loaded course.\n */\n registerForCourse() {\n this.courseService.registerForCourse(this.course.id!).subscribe(\n (userResponse) => {\n if (userResponse.body != undefined) {\n const message = 'Registered user for course ' + this.course.title;\n const jhiAlert = this.jhiAlertService.info(message);\n jhiAlert.msg = message;\n }\n },\n (error: HttpErrorResponse) => {\n const errorMessage = error.headers.get('X-artemisApp-message')!;\n // TODO: this is a workaround to avoid translation not found issues. Provide proper translations\n const jhiAlert = this.jhiAlertService.error(errorMessage);\n jhiAlert.msg = errorMessage;\n },\n );\n }\n\n /**\n * On destroy unsubscribe all subscriptions.\n */\n ngOnDestroy() {\n this.eventManager.destroy(this.eventSubscriber);\n }\n\n /**\n * Deletes the course\n * @param courseId id the course that will be deleted\n */\n deleteCourse(courseId: number) {\n this.courseService.delete(courseId).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'courseListModification',\n content: 'Deleted an course',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n}\n" }, { "alpha_fraction": 0.6680992841720581, "alphanum_fraction": 0.6683072447776794, "avg_line_length": 48.06802749633789, "blob_id": "932d779a2ef8d9fe6fbd94a4a277d70e15f1fa27", "content_id": "d2cbd44d39bdd966f00b5e23ac1b5ef9d01622a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14426, "license_type": "permissive", "max_line_length": 176, "num_lines": 294, "path": "/src/main/webapp/app/exercises/text/assess/text-assessment.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { map, tap } from 'rxjs/operators';\nimport { Result } from 'app/entities/result.model';\nimport * as moment from 'moment';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { TextBlockRef } from 'app/entities/text-block-ref.model';\nimport { cloneDeep } from 'lodash';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { FeedbackConflict } from 'app/entities/feedback-conflict';\nimport { getLatestSubmissionResult, getSubmissionResultByCorrectionRound, getSubmissionResultById, setLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nimport { Participation } from 'app/entities/participation/participation.model';\n\ntype EntityResponseType = HttpResponse<Result>;\ntype TextAssessmentDTO = { feedbacks: Feedback[]; textBlocks: TextBlock[] };\n\n@Injectable({\n providedIn: 'root',\n})\nexport class TextAssessmentService {\n private readonly resourceUrl = SERVER_API_URL + 'api/text-assessments';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Saves the passed feedback items of the assessment.\n * @param exerciseId id of the exercise the assessed submission was made to of type {number}\n * @param resultId id of the corresponding result of type {number}\n * @param feedbacks list of feedback made during assessment of type {Feedback[]}\n * @param textBlocks list of text blocks of type {TextBlock[]}\n */\n public save(exerciseId: number, resultId: number, feedbacks: Feedback[], textBlocks: TextBlock[]): Observable<EntityResponseType> {\n const body = TextAssessmentService.prepareFeedbacksAndTextblocksForRequest(feedbacks, textBlocks);\n return this.http\n .put<Result>(`${this.resourceUrl}/exercise/${exerciseId}/result/${resultId}`, body, { observe: 'response' })\n .map((res: EntityResponseType) => TextAssessmentService.convertResponse(res));\n }\n\n /**\n * Submits the passed feedback items of the assessment.\n * @param exerciseId id of the exercise the assessed submission was made to of type {number}\n * @param resultId id of the corresponding result of type {number}\n * @param feedbacks list of feedback made during assessment of type {Feedback[]}\n * @param textBlocks list of text blocks of type {TextBlock[]}\n */\n public submit(exerciseId: number, resultId: number, feedbacks: Feedback[], textBlocks: TextBlock[]): Observable<EntityResponseType> {\n const body = TextAssessmentService.prepareFeedbacksAndTextblocksForRequest(feedbacks, textBlocks);\n return this.http\n .put<Result>(`${this.resourceUrl}/exercise/${exerciseId}/result/${resultId}/submit`, body, { observe: 'response' })\n .map((res: EntityResponseType) => TextAssessmentService.convertResponse(res));\n }\n\n /**\n * Updates an assessment after a complaint.\n * @param feedbacks list of feedback made during assessment of type {Feedback[]}\n * @param textBlocks list of text blocks of type {TextBlock[]}\n * @param complaintResponse response on the complaint of type {ComplaintResponse}\n * @param submissionId id of corresponding submission of type {number}\n */\n public updateAssessmentAfterComplaint(\n feedbacks: Feedback[],\n textBlocks: TextBlock[],\n complaintResponse: ComplaintResponse,\n submissionId: number,\n ): Observable<EntityResponseType> {\n const url = `${this.resourceUrl}/text-submissions/${submissionId}/assessment-after-complaint`;\n const assessmentUpdate = {\n feedbacks,\n textBlocks,\n complaintResponse,\n };\n return this.http\n .put<Result>(url, assessmentUpdate, { observe: 'response' })\n .map((res: EntityResponseType) => TextAssessmentService.convertResponse(res));\n }\n\n saveExampleAssessment(exampleSubmissionId: number, feedbacks: Feedback[], textBlocks: TextBlock[]): Observable<EntityResponseType> {\n const url = `${this.resourceUrl}/text-submissions/${exampleSubmissionId}/example-assessment`;\n const body = TextAssessmentService.prepareFeedbacksAndTextblocksForRequest(feedbacks, textBlocks);\n return this.http\n .put<Result>(url, body, { observe: 'response' })\n .map((res: EntityResponseType) => TextAssessmentService.convertResponse(res));\n }\n\n /**\n * Cancels an assessment.\n * @param exerciseId id of the exercise the assessed submission was made to of type {number}\n * @param submissionId id of corresponding submission of type {number}\n */\n public cancelAssessment(exerciseId: number, submissionId: number): Observable<void> {\n return this.http.put<void>(`${this.resourceUrl}/exercise/${exerciseId}/submission/${submissionId}/cancel-assessment`, null);\n }\n\n /**\n * Get all feedback items for a submission.\n * @param submissionId id of the submission for which the feedback items should be retrieved of type {number}\n * @param correctionRound\n * @param resultId instructors can results by id\n */\n public getFeedbackDataForExerciseSubmission(submissionId: number, correctionRound = 0, resultId?: number): Observable<StudentParticipation> {\n let params = new HttpParams();\n if (resultId && resultId > 0) {\n // in case resultId is set, we do not need the correction round\n params = params.set('resultId', resultId!.toString());\n } else {\n params = params.set('correction-round', correctionRound.toString());\n }\n return this.http\n .get<StudentParticipation>(`${this.resourceUrl}/submission/${submissionId}`, { observe: 'response', params })\n .pipe(\n // Wire up Result and Submission\n tap((response) => {\n const participation = response.body!;\n const submission = participation.submissions![0];\n let result;\n if (resultId) {\n result = getSubmissionResultById(submission, resultId);\n } else {\n result = getSubmissionResultByCorrectionRound(submission, correctionRound)!;\n }\n TextAssessmentService.reconnectResultsParticipation(participation, submission, result!);\n (submission as TextSubmission).atheneTextAssessmentTrackingToken = response.headers.get('x-athene-tracking-authorization') || undefined;\n }),\n map((response) => response.body!),\n );\n }\n\n /**\n * Gets an example result for defined exercise and submission.\n * @param exerciseId id of the exercise for which the example result should be retrieved of type {number}\n * @param submissionId id of the submission for which the example result should be retrieved of type {number}\n */\n public getExampleResult(exerciseId: number, submissionId: number): Observable<Result> {\n return this.http.get<Result>(`${this.resourceUrl}/exercise/${exerciseId}/submission/${submissionId}/example-result`);\n }\n\n public deleteExampleFeedback(exampleSubmissionId: number): Observable<void> {\n return this.http.delete<void>(`${this.resourceUrl}/text-submissions/${exampleSubmissionId}/example-assessment/feedback`);\n }\n\n /**\n * Gets an array of text submissions that contains conflicting feedback with the given feedback id.\n *\n * @param submissionId id of the submission feedback belongs to of type {number}\n * @param feedbackId id of the feedback to search for conflicts of type {number}\n */\n public getConflictingTextSubmissions(submissionId: number, feedbackId: number): Observable<TextSubmission[]> {\n return this.http.get<TextSubmission[]>(`${this.resourceUrl}/submission/${submissionId}/feedback/${feedbackId}/feedback-conflicts`);\n }\n\n /**\n * Set feedback conflict as solved. (Tutor decides it is not a conflict)\n *\n * @param exerciseId id of the exercise feedback conflict belongs to\n * @param feedbackConflictId id of the feedback conflict to be solved\n */\n public solveFeedbackConflict(exerciseId: number, feedbackConflictId: number): Observable<FeedbackConflict> {\n return this.http.get<FeedbackConflict>(`${this.resourceUrl}/exercise/${exerciseId}/feedbackConflict/${feedbackConflictId}/solve-feedback-conflict`);\n }\n\n private static prepareFeedbacksAndTextblocksForRequest(feedbacks: Feedback[], textBlocks: TextBlock[]): TextAssessmentDTO {\n feedbacks = feedbacks.map((feedback) => {\n feedback = Object.assign({}, feedback);\n delete feedback.result;\n delete feedback.conflictingTextAssessments;\n return feedback;\n });\n textBlocks = textBlocks.map((textBlock) => {\n textBlock = Object.assign({}, textBlock);\n textBlock.submission = undefined;\n return textBlock;\n });\n\n return { feedbacks, textBlocks };\n }\n\n private static convertResponse(res: EntityResponseType): EntityResponseType {\n const result = TextAssessmentService.convertItemFromServer(res.body!);\n\n if (result.completionDate) {\n result.completionDate = moment(result.completionDate);\n }\n if (result.submission && result.submission.submissionDate) {\n result.submission.submissionDate = moment(result.submission.submissionDate);\n }\n if (result.participation && result.participation.initializationDate) {\n result.participation.initializationDate = moment(result.participation.initializationDate);\n }\n\n return res.clone({ body: result });\n }\n\n private static convertItemFromServer(result: Result): Result {\n return Object.assign({}, result);\n }\n\n /**\n * Convert Feedback elements to use single array of FeedbackConflicts in the Feedback class.\n * It is stored with two references on the server side.\n *\n * @param feedbacks list of Feedback elements to convert.\n */\n private static convertFeedbackConflictsFromServer(feedbacks: Feedback[]): void {\n feedbacks.forEach((feedback) => {\n feedback.conflictingTextAssessments = [...(feedback['firstConflicts'] || []), ...(feedback['secondConflicts'] || [])];\n delete feedback['firstConflicts'];\n delete feedback['secondConflicts'];\n feedback.conflictingTextAssessments.forEach((textAssessmentConflict) => {\n textAssessmentConflict.conflictingFeedbackId =\n textAssessmentConflict['firstFeedback'].id === feedback.id ? textAssessmentConflict['secondFeedback'].id : textAssessmentConflict['firstFeedback'].id;\n });\n });\n }\n\n /**\n * Match given text blocks and feedback items by text block references.\n * @param blocks list of text blocks of type {TextBlock[]}\n * @param feedbacks list of feedback made during assessment of type {Feedback[]}\n */\n public static matchBlocksWithFeedbacks(blocks: TextBlock[], feedbacks: Feedback[]): TextBlockRef[] {\n return blocks.map(\n (block: TextBlock) =>\n new TextBlockRef(\n block,\n feedbacks.find(({ reference }) => block.id === reference),\n ),\n );\n }\n\n /**\n * Track the change of the Feedback in Athene.\n *\n * The routing to athene is done using nginx on the production server.\n *\n * @param submission - The submission object that holds the data that is tracked\n * @param origin - The method that calls the the tracking method\n */\n public trackAssessment(submission?: TextSubmission, origin?: string) {\n if (submission?.atheneTextAssessmentTrackingToken) {\n // clone submission and resolve circular json properties\n const submissionForSending = cloneDeep(submission);\n if (submissionForSending.participation) {\n submissionForSending.participation.submissions = [];\n if (submissionForSending.participation.exercise) {\n submissionForSending.participation.exercise.course = undefined;\n submissionForSending.participation.exercise.exerciseGroup = undefined;\n }\n }\n submissionForSending.atheneTextAssessmentTrackingToken = undefined;\n\n // eslint-disable-next-line chai-friendly/no-unused-expressions\n submissionForSending.participation?.results!.forEach((result) => {\n result.participation = undefined;\n result.submission = undefined;\n });\n\n const trackingObject = {\n origin,\n textBlocks: submissionForSending.blocks,\n participation: submissionForSending.participation,\n };\n\n // The request is directly routed to athene via nginx\n this.http\n .post(`${SERVER_API_URL}/athene-tracking/text-exercise-assessment`, trackingObject, {\n headers: { 'X-Athene-Tracking-Authorization': submission.atheneTextAssessmentTrackingToken },\n })\n .subscribe();\n }\n }\n\n /**\n * Connects the participation with the submission and result\n *\n * @param participation\n * @param submission\n * @param result\n */\n private static reconnectResultsParticipation(participation: Participation, submission: Submission, result: Result) {\n setLatestSubmissionResult(submission, getLatestSubmissionResult(submission));\n submission.participation = participation;\n participation.results = submission.results!;\n result.submission = submission;\n result.participation = participation;\n // Make sure Feedbacks Array is initialized\n result.feedbacks = result.feedbacks || [];\n TextAssessmentService.convertFeedbackConflictsFromServer(result.feedbacks);\n }\n}\n" }, { "alpha_fraction": 0.6572809219360352, "alphanum_fraction": 0.6624458432197571, "avg_line_length": 41.26760482788086, "blob_id": "2d7b8a620407084734bb68d07681c905aaeb8f00", "content_id": "7402ac47e73c8724712176af260f18aacc071306", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6002, "license_type": "permissive", "max_line_length": 139, "num_lines": 142, "path": "/src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { TextblockFeedbackEditorComponent } from 'app/exercises/text/assess/textblock-feedback-editor/textblock-feedback-editor.component';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { GradingInstruction } from 'app/exercises/shared/structured-grading-criterion/grading-instruction.model';\nimport { FeedbackConflict } from 'app/entities/feedback-conflict';\n\ndescribe('TextblockFeedbackEditorComponent', () => {\n let component: TextblockFeedbackEditorComponent;\n let fixture: ComponentFixture<TextblockFeedbackEditorComponent>;\n let compiled: any;\n\n const textBlock = { id: 'f6773c4b3c2d057fd3ac11f02df31c0a3e75f800' } as TextBlock;\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, TranslateModule.forRoot(), ArtemisConfirmIconModule],\n declarations: [TextblockFeedbackEditorComponent],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents();\n });\n\n beforeEach(() => {\n fixture = TestBed.createComponent(TextblockFeedbackEditorComponent);\n component = fixture.componentInstance;\n component.textBlock = textBlock;\n component.feedback = Feedback.forText(textBlock);\n component.feedback.gradingInstruction = new GradingInstruction();\n component.feedback.gradingInstruction.usageCount = 0;\n compiled = fixture.debugElement.nativeElement;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n\n const textarea = compiled.querySelector('textarea');\n expect(textarea).toBeTruthy();\n\n const input = compiled.querySelector('input');\n expect(input).toBeTruthy();\n });\n\n it('should show delete button for empty feedback only', () => {\n // fixture.debugElement.query(By.css('fa-icon.back-button'));\n let button = compiled.querySelector('.close fa-icon[icon=\"times\"]');\n let confirm = compiled.querySelector('.close jhi-confirm-icon');\n expect(button).toBeTruthy();\n expect(confirm).toBeFalsy();\n\n component.feedback.credits = 1;\n fixture.detectChanges();\n button = compiled.querySelector('.close fa-icon[icon=\"times\"]');\n confirm = compiled.querySelector('.close jhi-confirm-icon');\n expect(button).toBeFalsy();\n expect(confirm).toBeTruthy();\n\n component.feedback.detailText = 'Lorem Ipsum';\n fixture.detectChanges();\n button = compiled.querySelector('.close fa-icon[icon=\"times\"]');\n confirm = compiled.querySelector('.close jhi-confirm-icon');\n expect(button).toBeFalsy();\n expect(confirm).toBeTruthy();\n\n component.feedback.credits = 0;\n fixture.detectChanges();\n button = compiled.querySelector('.close fa-icon[icon=\"times\"]');\n confirm = compiled.querySelector('.close jhi-confirm-icon');\n expect(button).toBeFalsy();\n expect(confirm).toBeTruthy();\n\n component.feedback.detailText = '';\n fixture.detectChanges();\n\n button = compiled.querySelector('.close fa-icon[icon=\"times\"]');\n confirm = compiled.querySelector('.close jhi-confirm-icon');\n expect(button).toBeTruthy();\n expect(confirm).toBeFalsy();\n });\n\n it('should put the badge and the text correctly for feedback conflicts', () => {\n component.feedback.conflictingTextAssessments = [new FeedbackConflict()];\n fixture.detectChanges();\n const badge = compiled.querySelector('.badge-warning fa-icon[ng-reflect-icon=\"balance-scale-right\"]');\n expect(badge).toBeTruthy();\n const text = compiled.querySelector('[jhiTranslate$=conflictingAssessments]');\n expect(text).toBeTruthy();\n });\n\n it('should focus to the text area if it is left conflicting feedback', () => {\n component.feedback.credits = 0;\n component.feedback.detailText = 'Lorem Ipsum';\n component.conflictMode = true;\n component.isConflictingFeedback = true;\n component.isLeftConflictingFeedback = true;\n fixture.detectChanges();\n\n spyOn(component['textareaElement'], 'focus');\n component.focus();\n\n expect(component['textareaElement'].focus).toHaveBeenCalled();\n });\n\n it('should not focus to the text area if it is right conflicting feedback', () => {\n component.feedback.credits = 0;\n component.feedback.detailText = 'Lorem Ipsum';\n component.conflictMode = true;\n component.isConflictingFeedback = true;\n component.isLeftConflictingFeedback = false;\n fixture.detectChanges();\n\n spyOn(component['textareaElement'], 'focus');\n component.focus();\n\n expect(component['textareaElement'].focus).toHaveBeenCalledTimes(0);\n });\n\n it('should call escKeyup when keyEvent', () => {\n component.feedback.credits = 0;\n component.feedback.detailText = '';\n spyOn(component, 'escKeyup');\n const event = new KeyboardEvent('keydown', {\n key: 'Esc',\n });\n const textarea = fixture.nativeElement.querySelector('textarea');\n textarea.dispatchEvent(event);\n fixture.detectChanges();\n expect(component.escKeyup).toHaveBeenCalled();\n });\n});\n" }, { "alpha_fraction": 0.7081310749053955, "alphanum_fraction": 0.7094963788986206, "avg_line_length": 46.08571243286133, "blob_id": "b342fb128539a9b5182c5669c34bfebad3a78e0d", "content_id": "fad31bff26c3a649f233f97f179ff3e5de24692e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6592, "license_type": "permissive", "max_line_length": 170, "num_lines": 140, "path": "/src/test/javascript/spec/component/exam/participate/exercises/programming-exam-submission.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { ProgrammingExamSubmissionComponent } from 'app/exam/participate/exercises/programming/programming-exam-submission.component';\nimport { ModelingEditorComponent } from 'app/exercises/modeling/shared/modeling-editor.component';\nimport { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module';\nimport { CodeEditorContainerComponent } from 'app/exercises/programming/shared/code-editor/container/code-editor-container.component';\nimport { CommitState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { DomainService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain.service';\nimport { ArtemisProgrammingExerciseInstructionsRenderModule } from 'app/exercises/programming/shared/instructions-render/programming-exercise-instructions-render.module';\nimport { IncludedInScoreBadgeComponent } from 'app/exercises/shared/exercise-headers/included-in-score-badge.component';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { ArtemisExerciseButtonsModule } from 'app/overview/exercise-details/exercise-buttons.module';\nimport { OrionModule } from 'app/shared/orion/orion.module';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { MockComponent, MockModule, MockPipe, MockProvider } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExamSubmissionComponent', () => {\n let fixture: ComponentFixture<ProgrammingExamSubmissionComponent>;\n let component: ProgrammingExamSubmissionComponent;\n\n let studentParticipation: ProgrammingExerciseStudentParticipation;\n let exercise: ProgrammingExercise;\n let programmingSubmission: ProgrammingSubmission;\n\n let domainService: any;\n\n beforeEach(() => {\n programmingSubmission = { commitHash: 'Hash commit', buildFailed: false, buildArtifact: false };\n studentParticipation = { submissions: [programmingSubmission] };\n exercise = new ProgrammingExercise(new Course(), new ExerciseGroup());\n\n return TestBed.configureTestingModule({\n imports: [\n MockModule(ArtemisExerciseButtonsModule),\n MockModule(ArtemisProgrammingExerciseActionsModule),\n MockModule(OrionModule),\n MockModule(ArtemisResultModule),\n MockModule(ArtemisProgrammingExerciseInstructionsRenderModule),\n ],\n declarations: [\n ProgrammingExamSubmissionComponent,\n MockComponent(ModelingEditorComponent),\n MockComponent(CodeEditorContainerComponent),\n MockPipe(ArtemisTranslatePipe),\n MockComponent(IncludedInScoreBadgeComponent),\n ],\n providers: [MockProvider(DomainService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExamSubmissionComponent);\n component = fixture.componentInstance;\n domainService = TestBed.inject(DomainService);\n });\n });\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize with unlocked repository', () => {\n const domainServiceSpy = sinon.spy(domainService, 'setDomain');\n component.exercise = exercise;\n\n fixture.detectChanges();\n\n expect(fixture).to.be.ok;\n expect(domainServiceSpy.calledOnce);\n expect(component.repositoryIsLocked).to.equal(false);\n expect(component.getExercise()).to.equal(exercise);\n });\n\n it('should set the repositoryIsLocked value to true', () => {\n const programmingExercise = new ProgrammingExercise(new Course(), new ExerciseGroup());\n programmingExercise.dueDate = moment().subtract(10, 'seconds');\n programmingExercise.buildAndTestStudentSubmissionsAfterDueDate = moment().subtract(60, 'seconds');\n\n component.exercise = programmingExercise;\n fixture.detectChanges();\n\n expect(component.repositoryIsLocked).to.equal(true);\n });\n\n it('should change state on commit', () => {\n component.studentParticipation = studentParticipation;\n\n const undefinedCommitState = CommitState.UNDEFINED;\n component.onCommitStateChange(undefinedCommitState);\n expect(component.hasSubmittedOnce).to.equal(false);\n\n const cleanCommitState = CommitState.CLEAN;\n\n component.onCommitStateChange(cleanCommitState);\n expect(component.hasSubmittedOnce).to.equal(true);\n\n /**\n * After the first call with CommitState.CLEAN, component.hasSubmittedOnce must be now true\n */\n component.onCommitStateChange(cleanCommitState);\n if (component.studentParticipation.submissions) {\n expect(component.studentParticipation.submissions[0].submitted).to.equal(true);\n expect(component.studentParticipation.submissions[0].isSynced).to.equal(true);\n }\n });\n\n it('should desync on file change', () => {\n component.studentParticipation = studentParticipation;\n if (component.studentParticipation.submissions) {\n component.studentParticipation.submissions[0].isSynced = true;\n component.onFileChanged();\n\n expect(component.studentParticipation.submissions[0].isSynced).to.equal(false);\n }\n });\n\n it('should get submission', () => {\n component.studentParticipation = studentParticipation;\n if (studentParticipation.submissions) {\n expect(component.getSubmission()).to.equal(studentParticipation.submissions[0]);\n }\n });\n\n it('should return false if no unsaved changes', () => {\n exercise.allowOfflineIde = true;\n exercise.allowOnlineEditor = false;\n component.exercise = exercise;\n\n expect(component.hasUnsavedChanges()).to.equal(false);\n });\n});\n" }, { "alpha_fraction": 0.7992077469825745, "alphanum_fraction": 0.8021787405014038, "avg_line_length": 38.59803771972656, "blob_id": "7785fc768e1835bf91a2fd5e11237ad8ff2f72c7", "content_id": "cf87492e6d6a9a764f295e72eeb0cfcc1002bc94", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4039, "license_type": "permissive", "max_line_length": 166, "num_lines": 102, "path": "/src/test/java/de/tum/in/www1/artemis/util/AbstractArtemisIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.util;\n\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.doReturn;\n\nimport org.mockito.Mockito;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.test.mock.mockito.SpyBean;\nimport org.springframework.messaging.simp.SimpMessageSendingOperations;\n\nimport de.tum.in.www1.artemis.domain.VcsRepositoryUrl;\nimport de.tum.in.www1.artemis.programmingexercise.MockDelegate;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.connectors.LtiService;\nimport de.tum.in.www1.artemis.service.exam.ExamAccessService;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseGradingService;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseParticipationService;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingSubmissionService;\nimport de.tum.in.www1.artemis.service.scheduled.ProgrammingExerciseScheduleService;\n\n/**\n * this test should be completely independent of any profiles or configurations (e.g. VCS, CIS)\n */\npublic abstract class AbstractArtemisIntegrationTest implements MockDelegate {\n\n @Value(\"${server.url}\")\n protected String artemisServerUrl;\n\n // NOTE: we prefer SpyBean over MockBean, because it is more lightweight, we can mock method, but we can also invoke actual methods during testing\n @SpyBean\n protected LtiService ltiService;\n\n @SpyBean\n protected GitService gitService;\n\n @SpyBean\n protected GroupNotificationService groupNotificationService;\n\n @SpyBean\n protected WebsocketMessagingService websocketMessagingService;\n\n @SpyBean\n protected PlantUmlService plantUmlService;\n\n @SpyBean\n protected SimpMessageSendingOperations messagingTemplate;\n\n @SpyBean\n protected ProgrammingSubmissionService programmingSubmissionService;\n\n @SpyBean\n protected ProgrammingExerciseGradingService programmingExerciseGradingService;\n\n @SpyBean\n protected ExamAccessService examAccessService;\n\n @SpyBean\n protected InstanceMessageSendService instanceMessageSendService;\n\n @SpyBean\n protected ProgrammingExerciseScheduleService programmingExerciseScheduleService;\n\n @SpyBean\n protected ProgrammingExerciseParticipationService programmingExerciseParticipationService;\n\n @SpyBean\n protected ScoreService scoreService;\n\n @SpyBean\n protected UrlService urlService;\n\n @Autowired\n protected DatabaseUtilService database;\n\n @Autowired\n protected RequestUtilService request;\n\n public void resetSpyBeans() {\n Mockito.reset(ltiService, gitService, groupNotificationService, websocketMessagingService, plantUmlService, messagingTemplate, programmingSubmissionService,\n examAccessService, instanceMessageSendService, programmingExerciseScheduleService, programmingExerciseParticipationService, urlService, scoreService);\n }\n\n @Override\n public void mockGetRepositorySlugFromRepositoryUrl(String repositorySlug, VcsRepositoryUrl repositoryUrl) {\n // we convert this to URL to make sure the mock is properly hit, as there could be problems with objects such as VcsRepositoryUrl and its subclasses\n doReturn(repositorySlug).when(urlService).getRepositorySlugFromUrl(repositoryUrl.getURL());\n }\n\n @Override\n public void mockGetProjectKeyFromRepositoryUrl(String projectKey, VcsRepositoryUrl repositoryUrl) {\n // we convert this to URL to make sure the mock is properly hit, as there could be problems with objects such as VcsRepositoryUrl and its subclasses\n doReturn(projectKey).when(urlService).getProjectKeyFromUrl(repositoryUrl.getURL());\n }\n\n @Override\n public void mockGetProjectKeyFromAnyUrl(String projectKey) {\n doReturn(projectKey).when(urlService).getProjectKeyFromUrl(any());\n }\n}\n" }, { "alpha_fraction": 0.8153846263885498, "alphanum_fraction": 0.8153846263885498, "avg_line_length": 58.58333206176758, "blob_id": "9831448c7a102fed931a9ed73a8b1b149c9523a9", "content_id": "56f6c14ad8b4c8f62f68a08cc930dc96702f66ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 715, "license_type": "permissive", "max_line_length": 125, "num_lines": 12, "path": "/src/main/webapp/app/course/course-questions/course-questions.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { CourseQuestionsComponent } from 'app/course/course-questions/course-questions.component';\nimport { ArtemisCourseQuestionsRoutingModule } from 'app/course/course-questions/course-questions-routing.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisCourseQuestionsRoutingModule, ArtemisSharedComponentModule, ArtemisMarkdownModule],\n declarations: [CourseQuestionsComponent],\n})\nexport class ArtemisCourseQuestionsModule {}\n" }, { "alpha_fraction": 0.7469496130943298, "alphanum_fraction": 0.7485411167144775, "avg_line_length": 31.5, "blob_id": "b4d32a923423cadb64e6d4357a8d967d2c57c33a", "content_id": "83465b684cd3564ca1942189101e9b507e826bc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1885, "license_type": "permissive", "max_line_length": 108, "num_lines": 58, "path": "/src/main/java/de/tum/in/www1/artemis/domain/quiz/QuizQuestionStatistic.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.quiz;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.DiscriminatorOptions;\n\nimport com.fasterxml.jackson.annotation.*;\n\n@Entity\n@DiscriminatorValue(value = \"Q\")\n@DiscriminatorOptions(force = true)\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"type\")\n@JsonSubTypes({ @JsonSubTypes.Type(value = MultipleChoiceQuestionStatistic.class, name = \"multiple-choice\"),\n @JsonSubTypes.Type(value = DragAndDropQuestionStatistic.class, name = \"drag-and-drop\"),\n @JsonSubTypes.Type(value = ShortAnswerQuestionStatistic.class, name = \"short-answer\") })\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic abstract class QuizQuestionStatistic extends QuizStatistic {\n\n @Column(name = \"rated_correct_counter\")\n private Integer ratedCorrectCounter = 0;\n\n @Column(name = \"un_rated_correct_counter\")\n private Integer unRatedCorrectCounter = 0;\n\n @OneToOne(mappedBy = \"quizQuestionStatistic\")\n @JsonIgnore\n private QuizQuestion quizQuestion;\n\n public Integer getRatedCorrectCounter() {\n return ratedCorrectCounter;\n }\n\n public void setRatedCorrectCounter(Integer ratedCorrectCounter) {\n this.ratedCorrectCounter = ratedCorrectCounter;\n }\n\n public Integer getUnRatedCorrectCounter() {\n return unRatedCorrectCounter;\n }\n\n public void setUnRatedCorrectCounter(Integer unRatedCorrectCounter) {\n this.unRatedCorrectCounter = unRatedCorrectCounter;\n }\n\n public QuizQuestion getQuizQuestion() {\n return quizQuestion;\n }\n\n public void setQuizQuestion(QuizQuestion quizQuestion) {\n this.quizQuestion = quizQuestion;\n }\n\n public abstract void addResult(SubmittedAnswer submittedAnswer, boolean rated);\n\n public abstract void removeOldResult(SubmittedAnswer submittedAnswer, boolean rated);\n\n public abstract void resetStatistic();\n}\n" }, { "alpha_fraction": 0.617827296257019, "alphanum_fraction": 0.6217269897460938, "avg_line_length": 34.19607925415039, "blob_id": "6d104e1e029b72ac3eb536bc8ff10ffddfc755ba", "content_id": "75cc306941afafd637ae65751a443c753a42fb05", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1795, "license_type": "permissive", "max_line_length": 106, "num_lines": 51, "path": "/src/test/javascript/spec/component/exercise-hint/exercise-hint.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { of } from 'rxjs';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\n\nimport { ExerciseHintComponent } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.component';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ArtemisTestModule } from '../../test.module';\n\ndescribe('ExerciseHint Management Component', () => {\n let comp: ExerciseHintComponent;\n let fixture: ComponentFixture<ExerciseHintComponent>;\n let service: ExerciseHintService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [ExerciseHintComponent],\n providers: [],\n })\n .overrideTemplate(ExerciseHintComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(ExerciseHintComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(ExerciseHintService);\n });\n\n it('Should call load all on init', () => {\n // GIVEN\n const headers = new HttpHeaders().append('link', 'link;link');\n const hint = new ExerciseHint();\n hint.id = 123;\n\n spyOn(service, 'findByExerciseId').and.returnValue(\n of(\n new HttpResponse({\n body: [hint],\n headers,\n }),\n ),\n );\n\n // WHEN\n comp.ngOnInit();\n\n // THEN\n expect(service.findByExerciseId).toHaveBeenCalled();\n expect(comp.exerciseHints[0]).toEqual(expect.objectContaining({ id: 123 }));\n });\n});\n" }, { "alpha_fraction": 0.6829794049263, "alphanum_fraction": 0.6851338744163513, "avg_line_length": 29.08333396911621, "blob_id": "591794f677c9320e1aab86a8216ad910687aeb1c", "content_id": "4ad1704688cf15879f2eb64f79b1f91e4057cd06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3249, "license_type": "permissive", "max_line_length": 105, "num_lines": 108, "path": "/src/main/java/de/tum/in/www1/artemis/service/user/PasswordService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.user;\n\nimport java.util.Optional;\n\nimport org.jasypt.encryption.pbe.StandardPBEStringEncryptor;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.security.PBEPasswordEncoder;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\n\n@Service\npublic class PasswordService {\n\n @Value(\"${artemis.encryption-password}\")\n private String encryptionPassword;\n\n private final UserRepository userRepository;\n\n private PBEPasswordEncoder passwordEncoder;\n\n private StandardPBEStringEncryptor encryptor;\n\n public PasswordService(UserRepository userRepository) {\n this.userRepository = userRepository;\n }\n\n /**\n * Get the encoder for password encryption\n *\n * @return existing password encoder or newly created password encryptor\n */\n private PBEPasswordEncoder passwordEncoder() {\n if (passwordEncoder != null) {\n return passwordEncoder;\n }\n passwordEncoder = new PBEPasswordEncoder(encryptor());\n return passwordEncoder;\n }\n\n /**\n * Get the the password encryptor with MD5 and DES encryption algorithm\n *\n * @return existing encryptor or newly created encryptor\n */\n private StandardPBEStringEncryptor encryptor() {\n if (encryptor != null) {\n return encryptor;\n }\n encryptor = new StandardPBEStringEncryptor();\n encryptor.setAlgorithm(\"PBEWithMD5AndDES\");\n encryptor.setPassword(encryptionPassword);\n return encryptor;\n }\n\n /**\n * Get decrypted password for the current user\n *\n * @return decrypted password or empty string\n */\n public String decryptPasswordOfCurrentUser() {\n User user = userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin().get()).get();\n try {\n return encryptor().decrypt(user.getPassword());\n }\n catch (Exception e) {\n return \"\";\n }\n }\n\n /**\n * Get decrypted password for given user\n *\n * @param user the user\n * @return decrypted password or empty string\n */\n public String decryptPassword(User user) {\n return encryptor().decrypt(user.getPassword());\n }\n\n public String decryptPassword(String encodedPassword) {\n return encryptor().decrypt(encodedPassword);\n }\n\n public String encryptPassword(String rawPassword) {\n return encryptor().encrypt(rawPassword);\n }\n\n public String encodePassword(CharSequence rawPassword) {\n return passwordEncoder().encode(rawPassword);\n }\n\n public boolean checkPasswordMatch(CharSequence rawPassword, String encodedPassword) {\n return passwordEncoder().matches(rawPassword, encodedPassword);\n }\n\n /**\n * Get decrypted password for given user login\n *\n * @param login of a user\n * @return decrypted password or empty string\n */\n public Optional<String> decryptPasswordByLogin(String login) {\n return userRepository.findOneByLogin(login).map(user -> encryptor().decrypt(user.getPassword()));\n }\n}\n" }, { "alpha_fraction": 0.6555360555648804, "alphanum_fraction": 0.6590509414672852, "avg_line_length": 30.61111068725586, "blob_id": "4b16394b950ded65b12f9e227bebd7cad7aa73d8", "content_id": "cf682bb1531a6aef7111aabc3133976f0ac1343f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 569, "license_type": "permissive", "max_line_length": 92, "num_lines": 18, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-exercise.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { of, Observable } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { Exercise } from 'app/entities/exercise.model';\n\nexport class MockExerciseService {\n find(exerciseId: number) {\n return MockExerciseService.response({ id: exerciseId } as Exercise);\n }\n\n getUpcomingExercises() {\n return MockExerciseService.response([{ id: 1 } as Exercise, { id: 2 } as Exercise]);\n }\n\n // helper method\n private static response<T>(entity: T) {\n return of({ body: entity }) as Observable<HttpResponse<T>>;\n }\n}\n" }, { "alpha_fraction": 0.6834981441497803, "alphanum_fraction": 0.6870291829109192, "avg_line_length": 44.43315505981445, "blob_id": "c28dc831410ba7301da4330718acb4fdf583edd1", "content_id": "8b5da11e2d3936ea182afd7f86d7c3b803159513", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8496, "license_type": "permissive", "max_line_length": 169, "num_lines": 187, "path": "/src/test/javascript/spec/component/short-answer-question/short-answer-question.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { FormsModule } from '@angular/forms';\nimport { NgbPopoverModule, NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { ShortAnswerQuestionComponent } from 'app/exercises/quiz/shared/questions/short-answer-question/short-answer-question.component';\nimport { QuizScoringInfoStudentModalComponent } from 'app/exercises/quiz/shared/questions/quiz-scoring-infostudent-modal/quiz-scoring-info-student-modal.component';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { stub } from 'sinon';\nimport { ShortAnswerSpot } from 'app/entities/quiz/short-answer-spot.model';\nimport { ShortAnswerMapping } from 'app/entities/quiz/short-answer-mapping.model';\nimport { ShortAnswerSolution } from 'app/entities/quiz/short-answer-solution.model';\nimport { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\nconst question = new ShortAnswerQuestion();\nquestion.id = 1;\n\ndescribe('ShortAnswerQuestionComponent', () => {\n let fixture: ComponentFixture<ShortAnswerQuestionComponent>;\n let component: ShortAnswerQuestionComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule, NgbPopoverModule, ArtemisMarkdownEditorModule],\n declarations: [ShortAnswerQuestionComponent, MockPipe(ArtemisTranslatePipe), MockComponent(QuizScoringInfoStudentModalComponent), MockDirective(NgbTooltip)],\n providers: [],\n }).compileComponents();\n fixture = TestBed.createComponent(ShortAnswerQuestionComponent);\n component = fixture.componentInstance;\n });\n\n beforeEach(() => {\n component.submittedTexts = [];\n component.clickDisabled = false;\n component.showResult = true;\n component.questionIndex = 0;\n component.score = 0;\n component.shortAnswerQuestion = question;\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.id = 10;\n const text = 'Please explain this question about stuff';\n alternativeQuestion.text = text;\n const hint = 'new Hint!';\n alternativeQuestion.hint = hint;\n const explanation = 'This is a very good explanation!';\n alternativeQuestion.explanation = explanation;\n\n component.question = alternativeQuestion;\n\n expect(component.textParts).to.deep.equal([[`<p>${text}</p>`]]);\n expect(component.shortAnswerQuestion).to.deep.equal(alternativeQuestion);\n expect(component.renderedQuestion.text['changingThisBreaksApplicationSecurity']).to.equal(`<p>${text}</p>`);\n expect(component.renderedQuestion.hint['changingThisBreaksApplicationSecurity']).to.equal(`<p>${hint}</p>`);\n expect(component.renderedQuestion.explanation['changingThisBreaksApplicationSecurity']).to.equal(`<p>${explanation}</p>`);\n });\n\n it('should set submitted texts', () => {\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.id = 10;\n const text = 'Please explain this question about [-spot 1]';\n alternativeQuestion.text = text;\n alternativeQuestion.hint = 'new Hint!';\n alternativeQuestion.explanation = 'This is a very good explanation!';\n const spot = new ShortAnswerSpot();\n spot.spotNr = 1;\n alternativeQuestion.spots = [spot];\n component.fnOnSubmittedTextUpdate = function () {\n return true;\n };\n const returnValue = ({ value: text } as unknown) as HTMLElement;\n const getNavigationStub = stub(document, 'getElementById').returns(returnValue);\n\n component.question = alternativeQuestion;\n component.setSubmittedText();\n\n expect(getNavigationStub).to.have.been.called;\n expect(component.submittedTexts.length).to.equal(1);\n expect(component.submittedTexts[0].text).to.equal(text);\n expect(component.submittedTexts[0].spot).to.deep.equal(spot);\n });\n\n it('should show sample solution', () => {\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.id = 10;\n alternativeQuestion.text = 'Please explain this question about stuff';\n alternativeQuestion.hint = 'new Hint!';\n alternativeQuestion.explanation = 'This is a very good explanation!';\n const spot = new ShortAnswerSpot();\n spot.spotNr = 1;\n alternativeQuestion.spots = [spot];\n const solution = new ShortAnswerSolution();\n const mapping = new ShortAnswerMapping(spot, solution);\n alternativeQuestion.correctMappings = [mapping];\n\n component.shortAnswerQuestion = alternativeQuestion;\n component.showSampleSolution();\n\n expect(component.sampleSolutions.length).to.equal(1);\n expect(component.sampleSolutions[0]).to.deep.equal(solution);\n expect(component.showingSampleSolution).to.be.true;\n });\n\n it('should toggle show sample solution', () => {\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.spots = [];\n component.shortAnswerQuestion = alternativeQuestion;\n component.showResult = true;\n component.showingSampleSolution = true;\n component.forceSampleSolution = true;\n expect(component.showingSampleSolution).to.be.true;\n component.forceSampleSolution = false;\n component.hideSampleSolution();\n\n expect(component.showingSampleSolution).to.be.false;\n });\n\n it('should get submitted text size for spot', () => {\n const submitted = new ShortAnswerSubmittedText();\n submitted.text = 'expectedReturnText';\n const spot = new ShortAnswerSpot();\n spot.spotNr = 1;\n submitted.spot = spot;\n const tag = '[-spot 1]';\n component.submittedTexts = [submitted];\n\n expect(component.getSubmittedTextSizeForSpot(tag)).to.deep.equal(submitted.text.length + 2);\n });\n\n it('should get sample solution size for spot', () => {\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.id = 10;\n const spot = new ShortAnswerSpot();\n spot.spotNr = 1;\n alternativeQuestion.spots = [new ShortAnswerSpot(), spot];\n component.shortAnswerQuestion = alternativeQuestion;\n\n const solution = new ShortAnswerSolution();\n solution.text = 'expectedReturnText';\n component.sampleSolutions = [new ShortAnswerSolution(), solution];\n const tag = '[-spot 1]';\n\n expect(component.getSampleSolutionSizeForSpot(tag)).to.deep.equal(solution.text.length + 2);\n });\n\n it('should get background color for input field', () => {\n const text = 'This is the solution text for the ultimate solution';\n const submittedText = new ShortAnswerSubmittedText();\n const spot = new ShortAnswerSpot();\n spot.spotNr = 1;\n submittedText.spot = spot;\n submittedText.isCorrect = true;\n submittedText.text = text;\n component.submittedTexts = [submittedText];\n const tag = '[-spot 1]';\n\n const alternativeQuestion = new ShortAnswerQuestion();\n alternativeQuestion.id = 10;\n alternativeQuestion.spots = [spot];\n const solution = new ShortAnswerSolution();\n solution.id = 1;\n solution.text = text;\n const mapping = new ShortAnswerMapping(spot, solution);\n alternativeQuestion.correctMappings = [mapping];\n\n component.shortAnswerQuestion = alternativeQuestion;\n expect(component.getBackgroundColourForInputField(tag)).to.equal('lightgreen');\n component.shortAnswerQuestion.correctMappings = [];\n expect(component.getBackgroundColourForInputField(tag)).to.equal('yellow');\n component.submittedTexts = [];\n expect(component.getBackgroundColourForInputField(tag)).to.equal('red');\n });\n});\n" }, { "alpha_fraction": 0.7206922173500061, "alphanum_fraction": 0.7217473983764648, "avg_line_length": 54.098838806152344, "blob_id": "9adb5a3183680b0e1b9e5f89c0a361018a595288", "content_id": "3358653a4aca1a2c47955bc2e2b048c1818b9658", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 18954, "license_type": "permissive", "max_line_length": 180, "num_lines": 344, "path": "/src/main/java/de/tum/in/www1/artemis/service/ScoreService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.service.util.RoundingUtil.round;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Propagation;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.participation.Participation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.scores.ParticipantScore;\nimport de.tum.in.www1.artemis.domain.scores.StudentScore;\nimport de.tum.in.www1.artemis.domain.scores.TeamScore;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\n\n@Service\npublic class ScoreService {\n\n private final StudentScoreRepository studentScoreRepository;\n\n private final ParticipantScoreRepository participantScoreRepository;\n\n private final TeamScoreRepository teamScoreRepository;\n\n private final ParticipationRepository participationRepository;\n\n private final ResultRepository resultRepository;\n\n private final Logger logger = LoggerFactory.getLogger(ScoreService.class);\n\n public ScoreService(StudentScoreRepository studentScoreRepository, TeamScoreRepository teamScoreRepository, ParticipationRepository participationRepository,\n ResultRepository resultRepository, ParticipantScoreRepository participantScoreRepository) {\n this.studentScoreRepository = studentScoreRepository;\n this.participationRepository = participationRepository;\n this.participantScoreRepository = participantScoreRepository;\n this.teamScoreRepository = teamScoreRepository;\n this.resultRepository = resultRepository;\n }\n\n /**\n * Either updates or removes an existing participant score when a result is removed\n * The annotation \"@Transactional\" is ok because it means that this method does not support run in an outer transactional context, instead the outer transaction is paused\n *\n * @param resultToBeDeleted result that will be removes\n */\n @Transactional(propagation = Propagation.NOT_SUPPORTED) // ok (see JavaDoc)\n public void removeOrUpdateAssociatedParticipantScore(Result resultToBeDeleted) {\n // In this method we use custom @Query methods that will fail if no authentication is available, therefore\n // we check this here and set a dummy authentication if none is available (this is the case in a scheduled service or\n // websocket)\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (authentication == null) {\n SecurityUtils.setAuthorizationObject();\n }\n\n Optional<ParticipantScore> associatedParticipantScoreOptional;\n if (resultToBeDeleted.isRated() != null && resultToBeDeleted.isRated()) {\n associatedParticipantScoreOptional = participantScoreRepository.findParticipantScoreByLastRatedResult(resultToBeDeleted);\n }\n else {\n associatedParticipantScoreOptional = participantScoreRepository.findParticipantScoresByLastResult(resultToBeDeleted);\n }\n\n if (associatedParticipantScoreOptional.isEmpty()) {\n return;\n }\n\n // There is a participant score connected to the result that will be deleted\n ParticipantScore associatedParticipantScore = associatedParticipantScoreOptional.get();\n Exercise exercise = associatedParticipantScore.getExercise();\n String originalParticipantScoreStructure = associatedParticipantScore.toString();\n\n // There are two possibilities now:\n // A: Another result exists for the exercise and the student / team -> update participant score with the newest one\n // B: No other result exists for the exercise and the student / team -> remove participant score\n tryToFindNewLastResult(resultToBeDeleted, associatedParticipantScore, exercise);\n\n if (associatedParticipantScore.getLastResult() == null && associatedParticipantScore.getLastRatedResult() == null) {\n participantScoreRepository.deleteById(associatedParticipantScore.getId());\n logger.info(\"Deleted an existing participant score: \" + originalParticipantScoreStructure);\n }\n else {\n ParticipantScore updatedParticipantScore = participantScoreRepository.saveAndFlush(associatedParticipantScore);\n logger.info(\"Updated an existing participant score. Was: \" + originalParticipantScoreStructure + \". Is: \" + updatedParticipantScore.toString());\n }\n }\n\n private void tryToFindNewLastResult(Result resultToBeDeleted, ParticipantScore associatedParticipantScore, Exercise exercise) {\n if (resultToBeDeleted.equals(associatedParticipantScore.getLastRatedResult())) {\n Optional<Result> newLastRatedResultOptional = getNewLastRatedResultForParticipantScore(associatedParticipantScore);\n if (newLastRatedResultOptional.isPresent()) {\n Result newLastRatedResult = newLastRatedResultOptional.get();\n setLastRatedAttributes(associatedParticipantScore, newLastRatedResult, exercise);\n }\n else {\n setLastRatedAttributes(associatedParticipantScore, null, exercise);\n }\n }\n\n if (resultToBeDeleted.equals(associatedParticipantScore.getLastResult())) {\n Optional<Result> newLastResultOptional = getNewLastResultForParticipantScore(associatedParticipantScore);\n if (newLastResultOptional.isPresent()) {\n Result newLastResult = newLastResultOptional.get();\n setLastAttributes(associatedParticipantScore, newLastResult, exercise);\n }\n else {\n setLastAttributes(associatedParticipantScore, null, exercise);\n }\n }\n }\n\n /**\n * Either updates an existing participant score or creates a new participant score if a new result comes in\n * The annotation \"@Transactional\" is ok because it means that this method does not support run in an outer transactional context, instead the outer transaction is paused\n *\n * @param createdOrUpdatedResult newly created or updated result\n */\n @Transactional(propagation = Propagation.NOT_SUPPORTED) // ok (see JavaDoc)\n public void updateOrCreateParticipantScore(Result createdOrUpdatedResult) {\n if (createdOrUpdatedResult.getScore() == null || createdOrUpdatedResult.getCompletionDate() == null) {\n return;\n }\n // There is a deadlock problem with programming exercises here if we use the participation from the result (reason unknown at the moment)\n // therefore we get the participation from the database\n Optional<StudentParticipation> studentParticipationOptional = getStudentParticipationForResult(createdOrUpdatedResult);\n if (studentParticipationOptional.isEmpty()) {\n return;\n }\n StudentParticipation studentParticipation = studentParticipationOptional.get();\n // we ignore test runs of exams\n if (studentParticipation.isTestRun()) {\n return;\n }\n Exercise exercise = studentParticipation.getExercise();\n ParticipantScore existingParticipationScoreForExerciseAndParticipant = getExistingParticipationScore(studentParticipation, exercise);\n // there already exists a participant score -> we need to update it\n if (existingParticipationScoreForExerciseAndParticipant != null) {\n updateExistingParticipantScore(existingParticipationScoreForExerciseAndParticipant, createdOrUpdatedResult, exercise);\n }\n else { // there does not already exists a participant score -> we need to create it\n createNewParticipantScore(createdOrUpdatedResult, studentParticipation, exercise);\n }\n }\n\n /**\n * Gets the student participation for a result from the database\n *\n * @param result result for which to get the student participation\n * @return student participation optional\n */\n private Optional<StudentParticipation> getStudentParticipationForResult(Result result) {\n Optional<Participation> participationOptional = participationRepository.findByResults(result);\n if (participationOptional.isEmpty()) {\n return Optional.empty();\n }\n Participation participation = participationOptional.get();\n\n if (!(participation instanceof StudentParticipation)) {\n return Optional.empty();\n }\n return Optional.of((StudentParticipation) participation);\n }\n\n /**\n * Gets the existing participation score for an exercise and a participant or null if none can be found\n *\n * @param studentParticipation participation containing the information about the participant\n * @param exercise exercise for which to find the participation score of the participant\n * @return existing participation score or null if none can be found\n */\n private ParticipantScore getExistingParticipationScore(StudentParticipation studentParticipation, Exercise exercise) {\n ParticipantScore existingParticipationScoreForExerciseAndParticipant = null;\n if (exercise.isTeamMode()) {\n Team team = studentParticipation.getTeam().get();\n Optional<TeamScore> teamScoreOptional = teamScoreRepository.findTeamScoreByExerciseAndTeam(exercise, team);\n if (teamScoreOptional.isPresent()) {\n existingParticipationScoreForExerciseAndParticipant = teamScoreOptional.get();\n }\n }\n else {\n User user = studentParticipation.getStudent().get();\n Optional<StudentScore> studentScoreOptional = studentScoreRepository.findStudentScoreByExerciseAndUser(exercise, user);\n if (studentScoreOptional.isPresent()) {\n existingParticipationScoreForExerciseAndParticipant = studentScoreOptional.get();\n }\n }\n return existingParticipationScoreForExerciseAndParticipant;\n }\n\n /**\n * Create a new Participant Score\n *\n * @param newResult result containing the information about the score achieved\n * @param studentParticipation participation containing the information about the participant\n * @param exercise exercise for which to create participant score\n */\n private void createNewParticipantScore(Result newResult, StudentParticipation studentParticipation, Exercise exercise) {\n if (exercise.isTeamMode()) {\n createNewTeamScore(newResult, studentParticipation, exercise);\n }\n else {\n createNewStudentScore(newResult, studentParticipation, exercise);\n }\n }\n\n private void createNewStudentScore(Result newResult, StudentParticipation studentParticipation, Exercise exercise) {\n StudentScore newStudentScore = new StudentScore();\n newStudentScore.setExercise(exercise);\n newStudentScore.setUser(studentParticipation.getStudent().get());\n setLastAttributes(newStudentScore, newResult, exercise);\n if (newResult.isRated() != null && newResult.isRated()) {\n setLastRatedAttributes(newStudentScore, newResult, exercise);\n }\n StudentScore studentScore = studentScoreRepository.saveAndFlush(newStudentScore);\n logger.info(\"Saved a new student score: \" + studentScore.toString());\n }\n\n private void createNewTeamScore(Result newResult, StudentParticipation studentParticipation, Exercise exercise) {\n TeamScore newTeamScore = new TeamScore();\n newTeamScore.setExercise(exercise);\n newTeamScore.setTeam(studentParticipation.getTeam().get());\n setLastAttributes(newTeamScore, newResult, exercise);\n if (newResult.isRated() != null && newResult.isRated()) {\n setLastRatedAttributes(newTeamScore, newResult, exercise);\n }\n TeamScore teamScore = teamScoreRepository.saveAndFlush(newTeamScore);\n logger.info(\"Saved a new team score: \" + teamScore.toString());\n }\n\n /**\n * Update an existing participant score when a new or updated result comes in\n *\n * @param participantScore existing participant score that refers to the same exercise and participant as the result\n * @param exercise the exercise to which the participant score belong\n * @param updatedOrNewlyCreatedResult updated or new result\n */\n private void updateExistingParticipantScore(ParticipantScore participantScore, Result updatedOrNewlyCreatedResult, Exercise exercise) {\n String originalParticipantScoreStructure = participantScore.toString();\n\n ParticipantScore participantScoreToSave = participantScore;\n // update the last result and last score if either it has not been set previously or new result is either the old one (=) or newer (>)\n if (participantScoreToSave.getLastResult() == null || updatedOrNewlyCreatedResult.getId() >= participantScoreToSave.getLastResult().getId()) {\n setLastAttributes(participantScoreToSave, updatedOrNewlyCreatedResult, exercise);\n }\n // update the last rated result and last rated score if either it has not been set previously or new rated result is either the old one (=) or newer (>)\n if (updatedOrNewlyCreatedResult.isRated() != null && updatedOrNewlyCreatedResult.isRated()\n && (participantScoreToSave.getLastRatedResult() == null || updatedOrNewlyCreatedResult.getId() >= participantScoreToSave.getLastRatedResult().getId())) {\n setLastRatedAttributes(participantScoreToSave, updatedOrNewlyCreatedResult, exercise);\n }\n // Edge Case: if the result is now unrated but is equal to the current last rated result we have to set these to null (result was switched from rated to unrated)\n if ((updatedOrNewlyCreatedResult.isRated() == null || !updatedOrNewlyCreatedResult.isRated())\n && updatedOrNewlyCreatedResult.equals(participantScoreToSave.getLastRatedResult())) {\n setLastRatedAttributes(participantScoreToSave, null, exercise);\n }\n participantScoreRepository.saveAndFlush(participantScoreToSave);\n logger.info(\"Updated an existing participant score. Was: \" + originalParticipantScoreStructure + \". Is: \" + participantScoreToSave.toString());\n }\n\n /**\n * Get the result that can replace the currently set last result for a participant score\n *\n * @param participantScore participant score\n * @return optional of new result\n */\n private Optional<Result> getNewLastResultForParticipantScore(ParticipantScore participantScore) {\n List<Result> resultOrdered;\n if (participantScore.getClass().equals(StudentScore.class)) {\n StudentScore studentScore = (StudentScore) participantScore;\n resultOrdered = resultRepository\n .getResultsOrderedByParticipationIdLegalSubmissionIdResultIdDescForStudent(participantScore.getExercise().getId(), studentScore.getUser().getId()).stream()\n .filter(r -> !participantScore.getLastResult().equals(r)).collect(Collectors.toList());\n }\n else {\n TeamScore teamScore = (TeamScore) participantScore;\n resultOrdered = resultRepository\n .getResultsOrderedByParticipationIdLegalSubmissionIdResultIdDescForTeam(participantScore.getExercise().getId(), teamScore.getTeam().getId()).stream()\n .filter(r -> !participantScore.getLastResult().equals(r)).collect(Collectors.toList());\n }\n // the new last result (result with highest id of submission with highest id) will be at the beginning of the list\n return resultOrdered.isEmpty() ? Optional.empty() : Optional.of(resultOrdered.get(0));\n\n }\n\n /**\n * Get the result that can replace the currently set last rated result for a participant score\n *\n * @param participantScore participant score\n * @return optional of new result\n */\n private Optional<Result> getNewLastRatedResultForParticipantScore(ParticipantScore participantScore) {\n List<Result> ratedResultsOrdered;\n if (participantScore.getClass().equals(StudentScore.class)) {\n StudentScore studentScore = (StudentScore) participantScore;\n ratedResultsOrdered = resultRepository\n .getRatedResultsOrderedByParticipationIdLegalSubmissionIdResultIdDescForStudent(participantScore.getExercise().getId(), studentScore.getUser().getId()).stream()\n .filter(r -> !participantScore.getLastRatedResult().equals(r)).collect(Collectors.toList());\n }\n else {\n TeamScore teamScore = (TeamScore) participantScore;\n ratedResultsOrdered = resultRepository\n .getRatedResultsOrderedByParticipationIdLegalSubmissionIdResultIdDescForTeam(participantScore.getExercise().getId(), teamScore.getTeam().getId()).stream()\n .filter(r -> !participantScore.getLastRatedResult().equals(r)).collect(Collectors.toList());\n }\n // the new last rated result (rated result with highest id of submission with highest id) will be at the beginning of the list\n return ratedResultsOrdered.isEmpty() ? Optional.empty() : Optional.of(ratedResultsOrdered.get(0));\n\n }\n\n private void setLastAttributes(ParticipantScore associatedParticipantScore, Result newLastResult, Exercise exercise) {\n associatedParticipantScore.setLastResult(newLastResult);\n if (newLastResult == null) {\n associatedParticipantScore.setLastScore(null);\n associatedParticipantScore.setLastPoints(null);\n }\n else {\n associatedParticipantScore.setLastScore(newLastResult.getScore());\n associatedParticipantScore.setLastPoints(round(newLastResult.getScore() * 0.01 * exercise.getMaxPoints()));\n\n }\n }\n\n private void setLastRatedAttributes(ParticipantScore associatedParticipantScore, Result newLastRatedResult, Exercise exercise) {\n associatedParticipantScore.setLastRatedResult(newLastRatedResult);\n if (newLastRatedResult == null) {\n associatedParticipantScore.setLastRatedScore(null);\n associatedParticipantScore.setLastRatedPoints(null);\n }\n else {\n associatedParticipantScore.setLastRatedScore(newLastRatedResult.getScore());\n associatedParticipantScore.setLastRatedPoints(round(newLastRatedResult.getScore() * 0.01 * exercise.getMaxPoints()));\n }\n }\n\n}\n" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8376068472862244, "avg_line_length": 30.200000762939453, "blob_id": "12d91da19cdc47b12023217b47cb66797cdcd89e", "content_id": "594b21ada96b3456c0da424ab99865d52ef3a385", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 468, "license_type": "permissive", "max_line_length": 115, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ShortAnswerQuestionStatisticRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.ShortAnswerQuestionStatistic;\n\n/**\n * Spring Data repository for the ShortAnswerQuestionStatistic entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ShortAnswerQuestionStatisticRepository extends JpaRepository<ShortAnswerQuestionStatistic, Long> {\n\n}\n" }, { "alpha_fraction": 0.6129742860794067, "alphanum_fraction": 0.6182374358177185, "avg_line_length": 39.646766662597656, "blob_id": "7ce8a382020d2c05403e68cd9032ccc89cf86238", "content_id": "6f8a4c2ed5ea6691eadae1424f615eaa6113cb3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8170, "license_type": "permissive", "max_line_length": 179, "num_lines": 201, "path": "/src/main/webapp/app/exam/manage/student-exams/student-exam-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { FormControl, FormGroup, Validators } from '@angular/forms';\nimport { ActivatedRoute } from '@angular/router';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { StudentExamService } from 'app/exam/manage/student-exams/student-exam.service';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisDurationFromSecondsPipe } from 'app/shared/pipes/artemis-duration-from-seconds.pipe';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { round } from 'app/shared/util/utils';\nimport * as moment from 'moment';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { getLatestSubmissionResult, setLatestSubmissionResult } from 'app/entities/submission.model';\n\n@Component({\n selector: 'jhi-student-exam-detail',\n templateUrl: './student-exam-detail.component.html',\n providers: [ArtemisDurationFromSecondsPipe],\n})\nexport class StudentExamDetailComponent implements OnInit {\n courseId: number;\n studentExam: StudentExam;\n course: Course;\n student: User;\n workingTimeForm: FormGroup;\n isSavingWorkingTime = false;\n isTestRun = false;\n maxTotalPoints = 0;\n achievedTotalPoints = 0;\n bonusTotalPoints = 0;\n busy = false;\n\n examId: number;\n\n constructor(\n private route: ActivatedRoute,\n private studentExamService: StudentExamService,\n private courseService: CourseManagementService,\n private artemisDurationFromSecondsPipe: ArtemisDurationFromSecondsPipe,\n private alertService: JhiAlertService,\n private modalService: NgbModal,\n ) {}\n\n /**\n * Initialize the courseId and studentExam\n */\n ngOnInit(): void {\n this.isTestRun = this.route.snapshot.url[1]?.toString() === 'test-runs';\n this.loadStudentExam();\n }\n\n /**\n * Load the course and the student exam\n */\n loadStudentExam() {\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n this.examId = Number(this.route.snapshot.paramMap.get('examId'));\n this.route.data.subscribe(({ studentExam }) => this.setStudentExam(studentExam));\n\n this.courseService.find(this.courseId).subscribe((courseResponse) => {\n this.course = courseResponse.body!;\n });\n this.student = this.studentExam.user!;\n }\n\n /**\n * Save the defined working time\n */\n saveWorkingTime() {\n this.isSavingWorkingTime = true;\n const seconds = this.workingTimeForm.controls.minutes.value * 60 + this.workingTimeForm.controls.seconds.value;\n this.studentExamService.updateWorkingTime(this.courseId, this.studentExam.exam!.id!, this.studentExam.id!, seconds).subscribe(\n (res) => {\n if (res.body) {\n this.setStudentExam(res.body);\n }\n this.isSavingWorkingTime = false;\n this.alertService.success('artemisApp.studentExamDetail.saveWorkingTimeSuccessful');\n },\n () => {\n this.alertService.error('artemisApp.studentExamDetail.workingTimeCouldNotBeSaved');\n this.isSavingWorkingTime = false;\n },\n );\n }\n\n /**\n * Sets the student exam, initialised the component which allows changing the working time and sets the score of the student.\n * @param studentExam\n */\n private setStudentExam(studentExam: StudentExam) {\n this.studentExam = studentExam;\n this.initWorkingTimeForm();\n this.maxTotalPoints = 0;\n this.achievedTotalPoints = 0;\n this.bonusTotalPoints = 0;\n studentExam.exercises!.forEach((exercise) => {\n this.maxTotalPoints += exercise.maxPoints!;\n this.bonusTotalPoints += exercise.bonusPoints!;\n if (\n exercise.studentParticipations?.length &&\n exercise.studentParticipations.length > 0 &&\n exercise.studentParticipations[0].results?.length &&\n exercise.studentParticipations[0].results!.length > 0\n ) {\n if (exercise!.studentParticipations[0].submissions && exercise!.studentParticipations[0].submissions!.length > 0) {\n exercise!.studentParticipations[0].submissions![0].results! = exercise.studentParticipations[0].results;\n setLatestSubmissionResult(exercise?.studentParticipations[0].submissions?.[0], getLatestSubmissionResult(exercise?.studentParticipations[0].submissions?.[0]));\n }\n\n this.achievedTotalPoints += this.rounding((exercise.studentParticipations[0].results[0].score! * exercise.maxPoints!) / 100);\n }\n });\n }\n\n private initWorkingTimeForm() {\n const workingTime = this.artemisDurationFromSecondsPipe.transform(this.studentExam.workingTime!);\n const workingTimeParts = workingTime.split(':');\n this.workingTimeForm = new FormGroup({\n minutes: new FormControl({ value: parseInt(workingTimeParts[0] ? workingTimeParts[0] : '0', 10), disabled: this.examIsVisible() }, [\n Validators.min(0),\n Validators.required,\n ]),\n seconds: new FormControl({ value: parseInt(workingTimeParts[1] ? workingTimeParts[1] : '0', 10), disabled: this.examIsVisible() }, [\n Validators.min(0),\n Validators.max(59),\n Validators.required,\n ]),\n });\n }\n\n examIsVisible(): boolean {\n if (this.isTestRun) {\n // for test runs we always want to be able to change the working time\n return !!this.studentExam.submitted;\n } else if (this.studentExam.exam) {\n // Disable the form to edit the working time if the exam is already visible\n return moment(this.studentExam.exam.visibleDate).isBefore(moment());\n }\n // if exam is undefined, the form to edit the working time is disabled\n return true;\n }\n\n examIsOver(): boolean {\n if (this.studentExam.exam) {\n // only show the button when the exam is over\n return moment(this.studentExam.exam.endDate).add(this.studentExam.exam.gracePeriod, 'seconds').isBefore(moment());\n }\n // if exam is undefined, we do not want to show the button\n return false;\n }\n\n getWorkingTimeToolTip(): string {\n return this.examIsVisible()\n ? 'You cannot change the individual working time after the exam has become visible.'\n : 'You can change the individual working time of the student here.';\n }\n\n rounding(number: number) {\n return round(number, 1);\n }\n\n /**\n * switch the 'submitted' state of the studentExam.\n */\n toggle() {\n this.busy = true;\n if (this.studentExam.exam && this.studentExam.exam.id) {\n this.studentExamService.toggleSubmittedState(this.courseId, this.studentExam.exam!.id!, this.studentExam.id!, this.studentExam!.submitted!).subscribe(\n (res) => {\n if (res.body) {\n this.studentExam.submissionDate = res.body.submissionDate;\n this.studentExam.submitted = res.body.submitted;\n }\n this.alertService.success('artemisApp.studentExamDetail.toggleSuccessful');\n this.busy = false;\n },\n () => {\n this.alertService.error('artemisApp.studentExamDetail.togglefailed');\n this.busy = false;\n },\n );\n }\n }\n\n /**\n * Open a modal that requires the user's confirmation.\n * @param content the modal content\n */\n openConfirmationModal(content: any) {\n this.modalService.open(content).result.then(\n (result: string) => {\n if (result === 'confirm') {\n this.toggle();\n }\n },\n () => {},\n );\n }\n}\n" }, { "alpha_fraction": 0.6897590160369873, "alphanum_fraction": 0.6897590160369873, "avg_line_length": 26.66666603088379, "blob_id": "3df2cdcce42c2d0725d376ef32cfcc11bc2beaf2", "content_id": "8951f43e32881629fafa4a9be17ee9a43732ccc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 664, "license_type": "permissive", "max_line_length": 63, "num_lines": 24, "path": "/src/main/webapp/app/entities/notification.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\nimport { BaseEntity } from 'app/shared/model/base-entity';\nimport { User } from 'app/core/user/user.model';\n\nexport enum NotificationType {\n SYSTEM = 'system',\n CONNECTION = 'connection',\n GROUP = 'group',\n SINGLE = 'single',\n}\n\nexport class Notification implements BaseEntity {\n public id?: number;\n public notificationType?: NotificationType;\n public title?: string;\n public text?: string;\n public notificationDate?: Moment;\n public target?: string;\n public author?: User;\n\n protected constructor(notificationType: NotificationType) {\n this.notificationType = notificationType;\n }\n}\n" }, { "alpha_fraction": 0.6244486570358276, "alphanum_fraction": 0.6244486570358276, "avg_line_length": 32.0625, "blob_id": "47eb6554c04eaaf3832af2a256152fc958ab8197", "content_id": "62d147e756e8e84be83ba12e53c9c671f28901d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1587, "license_type": "permissive", "max_line_length": 96, "num_lines": 48, "path": "/src/main/webapp/app/shared/connection-status/connection-status.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy, ContentChild, ElementRef } from '@angular/core';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\n\n@Component({\n selector: 'jhi-connection-status',\n templateUrl: './connection-status.component.html',\n styleUrls: ['./connection-status.component.scss'],\n})\nexport class JhiConnectionStatusComponent implements OnInit, OnDestroy {\n @ContentChild('innerContent', { static: false }) innerContent: ElementRef;\n\n disconnected = true;\n onConnected: () => void;\n onDisconnected: () => void;\n\n constructor(private jhiWebsocketService: JhiWebsocketService) {}\n\n /**\n * Life cycle hook called by Angular to indicate that Angular is done creating the component\n */\n ngOnInit() {\n // listen to connect / disconnect events\n this.onConnected = () => {\n this.disconnected = false;\n };\n this.jhiWebsocketService.bind('connect', () => {\n this.onConnected();\n });\n this.onDisconnected = () => {\n this.disconnected = true;\n };\n this.jhiWebsocketService.bind('disconnect', () => {\n this.onDisconnected();\n });\n }\n\n /**\n * Life cycle hook called by Angular for cleanup just before Angular destroys the component\n */\n ngOnDestroy() {\n if (this.onConnected) {\n this.jhiWebsocketService.unbind('connect', this.onConnected);\n }\n if (this.onDisconnected) {\n this.jhiWebsocketService.unbind('disconnect', this.onDisconnected);\n }\n }\n}\n" }, { "alpha_fraction": 0.7029520273208618, "alphanum_fraction": 0.7195571660995483, "avg_line_length": 27.526315689086914, "blob_id": "59f0a7b7711de49e670e991fe38d9af9bc1e8806", "content_id": "46c6a1f103338bb85ce0fa9c373d8b6255d81453", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 542, "license_type": "permissive", "max_line_length": 147, "num_lines": 19, "path": "/src/main/java/de/tum/in/www1/artemis/domain/enumeration/InitializationState.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.enumeration;\n\n/**\n * The InitializationState enumeration.\n */\npublic enum InitializationState {\n\n UNINITIALIZED(0), REPO_COPIED(1), REPO_CONFIGURED(2), INACTIVE(3), BUILD_PLAN_COPIED(4), BUILD_PLAN_CONFIGURED(5), INITIALIZED(6), FINISHED(7);\n\n private final Integer stateNumber;\n\n InitializationState(int stateNumber) {\n this.stateNumber = stateNumber;\n }\n\n public boolean hasCompletedState(InitializationState state) {\n return this.stateNumber >= state.stateNumber;\n }\n}\n" }, { "alpha_fraction": 0.644212543964386, "alphanum_fraction": 0.6486400961875916, "avg_line_length": 39.53845977783203, "blob_id": "50ddfd3e22e6ab57d55fe7e932c97808002b0307", "content_id": "611d1512d89b12787797b1494cb8bcdc5369b021", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3162, "license_type": "permissive", "max_line_length": 120, "num_lines": 78, "path": "/src/test/javascript/spec/component/student-questions/student-votes.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { StudentVotesComponent } from 'app/overview/student-questions/student-votes/student-votes.component';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentVotesComponent', () => {\n let component: StudentVotesComponent;\n let componentFixture: ComponentFixture<StudentVotesComponent>;\n\n const user1 = {\n id: 1,\n } as User;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },\n ],\n declarations: [StudentVotesComponent],\n })\n .overrideTemplate(StudentVotesComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(StudentVotesComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should toggle upvote', () => {\n component.user = user1;\n component.votes = 42;\n component.userVote = null;\n // if not yet voted\n component.toggleUpVote();\n expect(component.voteValueChange).to.deep.equal(1);\n expect(component.userVote!.isPositive).to.be.true;\n // if already upvoted\n component.toggleUpVote();\n expect(component.voteValueChange).to.deep.equal(-1);\n expect(component.userVote).to.be.null;\n // if already downvoted\n component.userVote = { isPositive: false };\n component.toggleUpVote();\n expect(component.voteValueChange).to.deep.equal(2);\n expect(component.userVote!.isPositive).to.be.true;\n });\n\n it('should toggle downvote', () => {\n component.user = user1;\n component.votes = 42;\n component.userVote = null;\n // if not yet voted\n component.toggleDownVote();\n expect(component.voteValueChange).to.deep.equal(-1);\n expect(component.userVote!.isPositive).to.be.false;\n // if already downvoted\n component.toggleDownVote();\n expect(component.voteValueChange).to.deep.equal(+1);\n expect(component.userVote).to.be.null;\n // if already upvoted\n component.userVote = { isPositive: true };\n component.toggleDownVote();\n expect(component.voteValueChange).to.deep.equal(-2);\n expect(component.userVote!.isPositive).to.be.false;\n });\n});\n" }, { "alpha_fraction": 0.6675077676773071, "alphanum_fraction": 0.6675077676773071, "avg_line_length": 44.59292221069336, "blob_id": "ac432cbf9810c742c9f13a1dd5fc8a697e72e1de", "content_id": "6a3980b5037bfb6ae1670aa0e77191573ce99cb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5152, "license_type": "permissive", "max_line_length": 176, "num_lines": 113, "path": "/src/main/webapp/app/exercises/modeling/manage/modeling-exercise.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable, NgModule } from '@angular/core';\nimport { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { ModelingExerciseDetailComponent } from './modeling-exercise-detail.component';\nimport { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { filter, map } from 'rxjs/operators';\nimport { Observable } from 'rxjs';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { PlagiarismInspectorComponent } from 'app/exercises/shared/plagiarism/plagiarism-inspector/plagiarism-inspector.component';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\n@Injectable({ providedIn: 'root' })\nexport class ModelingExerciseResolver implements Resolve<ModelingExercise> {\n constructor(private modelingExerciseService: ModelingExerciseService, private courseService: CourseManagementService, private exerciseGroupService: ExerciseGroupService) {}\n\n resolve(route: ActivatedRouteSnapshot) {\n if (route.params['exerciseId']) {\n return this.modelingExerciseService.find(route.params['exerciseId']).pipe(\n filter((res) => !!res.body),\n map((modelingExercise: HttpResponse<ModelingExercise>) => modelingExercise.body!),\n );\n } else if (route.params['courseId']) {\n if (route.params['examId'] && route.params['groupId']) {\n return this.exerciseGroupService.find(route.params['courseId'], route.params['examId'], route.params['groupId']).pipe(\n filter((res) => !!res.body),\n map((exerciseGroup: HttpResponse<ExerciseGroup>) => new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, exerciseGroup.body || undefined)),\n );\n } else {\n return this.courseService.find(route.params['courseId']).pipe(\n filter((res) => !!res.body),\n map((course: HttpResponse<Course>) => new ModelingExercise(UMLDiagramType.ClassDiagram, course.body || undefined, undefined)),\n );\n }\n }\n return Observable.of(new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined));\n }\n}\n\nexport const routes: Routes = [\n {\n path: ':courseId/modeling-exercises/new',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/modeling-exercises/:exerciseId/edit',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/modeling-exercises/:exerciseId/import',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.importLabel',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/modeling-exercises/:exerciseId',\n component: ModelingExerciseDetailComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/modeling-exercises/:exerciseId/plagiarism',\n component: PlagiarismInspectorComponent,\n resolve: {\n exercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.plagiarism.plagiarism-detection',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/modeling-exercises',\n redirectTo: ':courseId/exercises',\n },\n];\n\n@NgModule({\n imports: [RouterModule.forChild(routes)],\n exports: [RouterModule],\n})\nexport class ArtemisModelingExerciseRoutingModule {}\n" }, { "alpha_fraction": 0.7366254925727844, "alphanum_fraction": 0.7481873631477356, "avg_line_length": 51.07143020629883, "blob_id": "427fa6380f7ccd00ec6c2787d8891b72b7422234", "content_id": "da74792afd2f6d81b39e3326055047af66392125", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5103, "license_type": "permissive", "max_line_length": 178, "num_lines": 98, "path": "/src/main/java/de/tum/in/www1/artemis/service/compass/utils/CompassConfiguration.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.compass.utils;\n\n/**\n * All similarity related parameters\n */\npublic class CompassConfiguration {\n\n /*\n * Similarity related parameters\n */\n // Amount that is subtracted from the similarity of two UML elements/diagrams for every missing element\n public static final double MISSING_ELEMENT_PENALTY = 0.05;\n\n // Weight of the relationship type when calculating the similarity of two UML relationships\n public static final double RELATION_TYPE_WEIGHT = 0.3;\n\n // Weight of the source and destination elements when calculating the similarity of two UML relationships (e.g. in class diagrams)\n public static final double RELATION_ELEMENT_WEIGHT = 0.25;\n\n // Weight of the source and destination elements when calculating the similarity of two UML component relationships\n public static final double COMPONENT_RELATION_ELEMENT_WEIGHT = 0.35;\n\n // Weight of the source and destination elements when calculating the similarity of two UML use case associations\n public static final double USE_CASE_ASSOCIATION_ELEMENT_WEIGHT = 0.3;\n\n // Weight of the multiplicity when calculating the similarity of two UML relationships\n public static final double RELATION_MULTIPLICITY_WEIGHT = 0.05;\n\n // Weight of the roles when calculating the similarity of two UML relationships\n public static final double RELATION_ROLE_WEIGHT = 0.05;\n\n // Weight of the class type when calculating the similarity of two UML classes\n public static final double CLASS_TYPE_WEIGHT = 0.3;\n\n // Weight of the class name when calculating the similarity of two UML classes\n public static final double CLASS_NAME_WEIGHT = 0.7;\n\n public static final double USE_CASE_ASSOCIATION_NAME_WEIGHT = 0.1;\n\n public static final double NODE_NAME_WEIGHT = 0.5;\n\n public static final double NODE_STEREOTYPE_WEIGHT = 0.2;\n\n public static final double NODE_PARENT_WEIGHT = 0.3;\n\n public static final double COMPONENT_NAME_WEIGHT = 0.6;\n\n public static final double COMPONENT_PARENT_WEIGHT = 0.4;\n\n // Weight of the name similarity of their attributes when calculating the similarity of two UML classes\n public static final double ATTRIBUTE_NAME_WEIGHT = 0.7;\n\n // Weight of the type similarity of their attributes when calculating the similarity of two UML classes\n public static final double ATTRIBUTE_TYPE_WEIGHT = 0.3;\n\n // Threshold for the similarity of child elements (attributes/methods in UML classes, classes and relationships in UML diagrams) when calculation the similarity of two UML\n // classes/diagrams. If the similarity for specific child elements is smaller than the threshold, the elements will not be considered similar at all.\n public static final double NO_MATCH_THRESHOLD = 0.1;\n\n // Threshold used for building similarity sets. If the similarity for two UML elements is smaller than this threshold, they will not be put into the same similarity set.\n // TODO CZ: decrease equality threshold again in the future\n public static final double EQUALITY_THRESHOLD = 0.95;\n\n // Threshold used for re-assessing poorly assessed models. If the confidence for a model is smaller than this threshold the model is send to the client for re-assessment.\n /* CURRENTLY DISABLED */\n public static final double POORLY_ASSESSED_MODEL_THRESHOLD = 0.8;\n\n /*\n * Confidence and coverage parameters\n */\n // Threshold of the coverage of a UML diagram. If the coverage for a specific diagram is smaller than this threshold, no automatic result will be created for the diagram.\n /* CURRENTLY DISABLED */\n public static final double COVERAGE_THRESHOLD = 0.8;\n\n // Threshold of the confidence of a UML diagram. If the confidence for a specific diagram is smaller than this threshold, no automatic result will be created for the diagram.\n /* CURRENTLY DISABLED */\n public static final double CONFIDENCE_THRESHOLD = 0.75;\n\n // Threshold of the confidence of an element in a UML diagram. If the confidence for a specific model element is smaller than this threshold, no automatic feedback will be\n // created for this element.\n public static final double ELEMENT_CONFIDENCE_THRESHOLD = 0.8;\n\n /*\n * Calculation engine cleanup parameters\n */\n // Number of days to keep unused calculation engines in memory. If an engine is unused for a longer time, it will be removed in the cleanup job running every night.\n public static final int DAYS_TO_KEEP_UNUSED_ENGINE = 1;\n\n /*\n * Optimal model parameters\n */\n // Minimal number of optimal models that should be in cache. If the cache consists of less models, NUMBER_OF_NEW_OPTIMAL_MODELS new optimal models will be loaded.\n public static final int OPTIMAL_MODEL_THRESHOLD = 10;\n\n // Number of optimal models that should be generated and loaded into the cache if the number of models in the cache is smaller than OPTIMAL_MODEL_THRESHOLD.\n // NUMBER_OF_NEW_OPTIMAL_MODELS should be greater or equal to OPTIMAL_MODEL_THRESHOLD.\n public static final int NUMBER_OF_NEW_OPTIMAL_MODELS = 10;\n}\n" }, { "alpha_fraction": 0.5893304944038391, "alphanum_fraction": 0.5921947956085205, "avg_line_length": 33.48147964477539, "blob_id": "cd53a21f4ad21163ad335953888194576bb193b9", "content_id": "ac1cab31747060beb3c59da9ba698bc971f95296", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2793, "license_type": "permissive", "max_line_length": 121, "num_lines": 81, "path": "/src/main/resources/templates/c/test/testUtils/Tester.py", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "from typing import Dict\nfrom testUtils.AbstractTest import AbstractTest\nfrom testUtils.Utils import printTester, getTesterOutput, clearTesterOutputCache, resetStdoutLimit, setStdoutLimitEnabled\nfrom testUtils.junit.Junit import Junit\nfrom testUtils.junit.TestSuite import TestSuite\n\n\nclass Tester:\n name: str\n suite: TestSuite\n tests: Dict[str, AbstractTest]\n\n def __init__(self, name: str = \"GBS-Tester-1.31\"):\n self.name = name\n self.suite = TestSuite(name)\n self.tests = dict()\n\n def run(self):\n \"\"\"\n Starts the tester and runs all tests added via \"addTest(test: AbstractTest)\".\n \"\"\"\n\n setStdoutLimitEnabled(False)\n printTester(f\"Running: {self.name}\")\n\n # A dictionary of test results:\n # Test name -> result\n testResults: Dict[str, Result] = dict()\n\n for name, test in self.tests.items():\n if test.timeoutSec >= 0:\n printTester(\"Running test case '{}' with a {} second timeout...\".format(\n name, test.timeoutSec))\n else:\n printTester(\n f\"Running test case '{name}' with no timeout...\")\n\n # Reset the tester output cache:\n resetStdoutLimit()\n setStdoutLimitEnabled(True)\n clearTesterOutputCache()\n\n test.start(testResults, self.suite)\n\n setStdoutLimitEnabled(False)\n printTester(\"Finished test case '{}' in {} seconds.\".format(\n name, test.case.time.total_seconds()))\n\n # Store the tester output in the test case:\n test.case.testerOutput = self.name + \"\\n\" + getTesterOutput()\n # Update test results:\n testResults[name] = test.case.result\n self.__printResult()\n\n def addTest(self, test: AbstractTest):\n \"\"\"\n Adds a new test that will be run once \"run()\" is invoked.\n \"\"\"\n\n if test.name in self.tests:\n raise NameError(\n f\"Test '{test.name}' already registered. Test names should be unique!\")\n self.tests[test.name] = test\n\n def __printResult(self):\n print(\"Result\".center(50, \"=\"))\n print(\"{} finished {} test cases in {} seconds.\".format(\n self.name, len(self.tests), self.suite.time.total_seconds()))\n print(f\"SUCCESS: {self.suite.successful}\")\n print(f\"FAILED: {self.suite.failures}\")\n print(f\"ERROR: {self.suite.errors}\")\n print(f\"SKIPPED: {self.suite.skipped}\")\n print(\"\".center(50, \"=\"))\n\n def exportResult(self, outputPath: str):\n \"\"\"\n Exports the test results into a JUnit format and stores it at the given outputPath.\n \"\"\"\n\n junit: Junit = Junit(self.suite)\n junit.toXml(outputPath)\n" }, { "alpha_fraction": 0.620317816734314, "alphanum_fraction": 0.6214528679847717, "avg_line_length": 39.97674560546875, "blob_id": "155aece644358782ee89a75e1a656639d43f471c", "content_id": "c559955593601651eb9376276a97185073d77957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1762, "license_type": "permissive", "max_line_length": 160, "num_lines": 43, "path": "/src/main/webapp/app/shared/orion/outdated-plugin-warning/orion-outdated.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { filter, tap } from 'rxjs/operators';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\n\n@Component({\n selector: 'jhi-orion-outdated',\n template: `\n <h2 class=\"text-danger font-weight-bold\" jhiTranslate=\"artemisApp.orion.version.outdated\">The version of Orion you are currently using is outdated!</h2>\n <div class=\"font-weight-bold \">\n {{ 'artemisApp.orion.version.usedVersion' | translate }}<span class=\"badge badge-pill badge-danger\">{{ versionString }}</span\n >!\n </div>\n <div>\n {{ 'artemisApp.orion.version.allowedVersion' | translate }}<span class=\"badge badge-pill badge-info\">{{ allowedMinimumVersion }}</span>\n </div>\n `,\n})\nexport class OrionOutdatedComponent implements OnInit {\n versionString: string;\n allowedMinimumVersion: string;\n\n constructor(private activatedRoute: ActivatedRoute, private profileService: ProfileService) {}\n\n /**\n * On initialization, sets the values of the used version and the minimum allowed version of orion.\n */\n ngOnInit(): void {\n this.activatedRoute.queryParams.subscribe((params) => {\n this.versionString = params['versionString'];\n this.profileService\n .getProfileInfo()\n .pipe(\n filter(Boolean),\n tap((info: ProfileInfo) => {\n this.allowedMinimumVersion = info.allowedMinimumOrionVersion;\n }),\n )\n .subscribe();\n });\n }\n}\n" }, { "alpha_fraction": 0.6175332069396973, "alphanum_fraction": 0.6175332069396973, "avg_line_length": 32.174312591552734, "blob_id": "b85ea7179bbb31fa15269064910ab585897da972", "content_id": "095fee3bb472e2146edbc16f0787ae578d2a8077", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3616, "license_type": "permissive", "max_line_length": 125, "num_lines": 109, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Subject, Subscription } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\nimport { JhiEventManager } from 'ng-jhipster';\n\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ExerciseHintService } from './exercise-hint.service';\nimport { onError } from 'app/shared/util/global.utils';\nimport { JhiAlertService } from 'ng-jhipster';\n\n@Component({\n selector: 'jhi-exercise-hint',\n templateUrl: './exercise-hint.component.html',\n})\nexport class ExerciseHintComponent implements OnInit, OnDestroy {\n exerciseId: number;\n exerciseHints: ExerciseHint[];\n eventSubscriber: Subscription;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n paramSub: Subscription;\n\n constructor(\n private route: ActivatedRoute,\n protected exerciseHintService: ExerciseHintService,\n private jhiAlertService: JhiAlertService,\n protected eventManager: JhiEventManager,\n ) {}\n\n /**\n * Subscribes to the route params to act on the currently selected exercise.\n */\n ngOnInit() {\n this.paramSub = this.route.params.subscribe((params) => {\n this.exerciseId = params['exerciseId'];\n this.loadAllByExerciseId();\n this.registerChangeInExerciseHints();\n });\n }\n\n /**\n * Unsubscribe from subscriptions\n */\n ngOnDestroy() {\n if (this.paramSub) {\n this.paramSub.unsubscribe();\n }\n this.eventManager.destroy(this.eventSubscriber);\n this.dialogErrorSource.unsubscribe();\n }\n\n /**\n * Load all exercise hints with the currently selected exerciseId (taken from route params).\n */\n loadAllByExerciseId() {\n this.exerciseHintService\n .findByExerciseId(this.exerciseId)\n .pipe(\n filter((res: HttpResponse<ExerciseHint[]>) => res.ok),\n map((res: HttpResponse<ExerciseHint[]>) => res.body),\n )\n .subscribe(\n (res: ExerciseHint[]) => {\n this.exerciseHints = res;\n },\n (res: HttpErrorResponse) => onError(this.jhiAlertService, res),\n );\n }\n\n /**\n * Returns the track id of an exercise hint\n * @param index Index of the item\n * @param item Item for which to get the id\n */\n trackId(index: number, item: ExerciseHint) {\n return item.id;\n }\n\n /**\n * (Re-)subscribe to the exercise hint list modification subscription\n */\n registerChangeInExerciseHints() {\n if (this.eventSubscriber) {\n this.eventSubscriber.unsubscribe();\n }\n this.eventSubscriber = this.eventManager.subscribe('exerciseHintListModification', () => this.loadAllByExerciseId());\n }\n\n /**\n * Deletes exercise hint\n * @param exerciseHintId the id of the exercise hint that we want to delete\n */\n deleteExerciseHint(exerciseHintId: number) {\n this.exerciseHintService.delete(exerciseHintId).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'exerciseHintListModification',\n content: 'Deleted an exerciseHint',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n}\n" }, { "alpha_fraction": 0.6415464878082275, "alphanum_fraction": 0.6494461894035339, "avg_line_length": 46.75448989868164, "blob_id": "de4a24d42638bedea96cea8d594b7bbbb6504329", "content_id": "9964357ad769a94842e976496818b5367a5a0fdc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 23925, "license_type": "permissive", "max_line_length": 179, "num_lines": 501, "path": "/src/test/javascript/spec/component/shared/navbar.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { Directive, Input } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { Router } from '@angular/router';\nimport { NgbCollapse, NgbDropdown } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { ApollonDiagramService } from 'app/exercises/quiz/manage/apollon-diagrams/apollon-diagram.service';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { GuidedTourComponent } from 'app/guided-tour/guided-tour.component';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { FindLanguageFromKeyPipe } from 'app/shared/language/find-language-from-key.pipe';\nimport { ActiveMenuDirective } from 'app/shared/layouts/navbar/active-menu.directive';\nimport { NavbarComponent } from 'app/shared/layouts/navbar/navbar.component';\nimport { LoadingNotificationComponent } from 'app/shared/notification/loading-notification/loading-notification.component';\nimport { NotificationSidebarComponent } from 'app/shared/notification/notification-sidebar/notification-sidebar.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';\nimport * as chai from 'chai';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { ChartsModule } from 'ng2-charts';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs/internal/observable/of';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n// tslint:disable-next-line:directive-selector\n@Directive({ selector: '[routerLink]' })\nexport class MockRouterLinkDirective {\n @Input('routerLink') data: any;\n}\n\n// tslint:disable-next-line:directive-selector\n@Directive({ selector: '[routerLinkActiveOptions]' })\nexport class MockRouterLinkActiveOptionsDirective {\n @Input('routerLinkActiveOptions') data: any;\n}\n\nclass MockBreadcrumb {\n label: string;\n uri: string;\n translate: boolean;\n}\n\ndescribe('NavbarComponent', () => {\n let fixture: ComponentFixture<NavbarComponent>;\n let component: NavbarComponent;\n let courseManagementStub: sinon.SinonStub;\n let exerciseStub: sinon.SinonStub;\n\n const router = new MockRouter();\n router.setUrl('');\n\n const courseManagementCrumb = {\n label: 'global.menu.course',\n translate: true,\n uri: '/course-management/',\n } as MockBreadcrumb;\n\n const testCourseCrumb = {\n label: 'Test Course',\n translate: false,\n uri: '/course-management/1/',\n } as MockBreadcrumb;\n\n const programmingExercisesCrumb = {\n label: 'artemisApp.course.exercises',\n translate: true,\n uri: '/course-management/1/programming-exercises/',\n } as MockBreadcrumb;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ChartsModule],\n declarations: [\n NavbarComponent,\n MockDirective(NgbCollapse),\n MockDirective(HasAnyAuthorityDirective),\n MockDirective(NgbDropdown),\n MockDirective(ActiveMenuDirective),\n MockDirective(JhiTranslateDirective),\n MockDirective(MockRouterLinkDirective),\n MockDirective(MockRouterLinkActiveOptionsDirective),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(FindLanguageFromKeyPipe),\n MockComponent(NotificationSidebarComponent),\n MockComponent(GuidedTourComponent),\n MockComponent(LoadingNotificationComponent),\n ],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n MockProvider(TranslateService),\n { provide: Router, useValue: router },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(NavbarComponent);\n component = fixture.componentInstance;\n\n const courseManagementService = fixture.debugElement.injector.get(CourseManagementService);\n courseManagementStub = sinon.stub(courseManagementService, 'getTitle').returns(of({ body: 'Test Course' } as HttpResponse<string>));\n\n const exerciseService = fixture.debugElement.injector.get(ExerciseService);\n exerciseStub = sinon.stub(exerciseService, 'getTitle').returns(of({ body: 'Test Exercise' } as HttpResponse<string>));\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize component', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should not build breadcrumbs for students', () => {\n const testUrl = '/courses/1/exercises';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(0);\n });\n\n it('should build breadcrumbs for course management', () => {\n const testUrl = '/course-management';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(1);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n });\n\n it('should ignore query parameters', () => {\n const testUrl = '/course-management?query=param';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(1);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n });\n\n it('should build breadcrumbs for system notification management', () => {\n const testUrl = '/admin/system-notification-management/1/edit';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(3);\n\n // Use matching here to ignore non-semantic differences between objects\n const systemBreadcrumb = { label: 'artemisApp.systemNotification.systemNotifications', translate: true, uri: '/admin/system-notification-management/' } as MockBreadcrumb;\n sinon.assert.match(component.breadcrumbs[0], systemBreadcrumb);\n sinon.assert.match(component.breadcrumbs[1], { label: '1', translate: false, uri: '/admin/system-notification-management/1/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[2], { label: 'global.generic.edit', translate: true, uri: '/admin/system-notification-management/1/edit/' } as MockBreadcrumb);\n });\n\n it('should build breadcrumbs for user management', () => {\n const testUrl = '/admin/user-management/test_user';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(2);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], { label: 'userManagement.home.title', translate: true, uri: '/admin/user-management/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[1], { label: 'test_user', translate: false, uri: '/admin/user-management/test_user/' } as MockBreadcrumb);\n });\n\n it('should not error without translation', () => {\n const testUrl = '/admin/route-without-translation';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(component.breadcrumbs.length).to.equal(1);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], { label: 'route-without-translation', translate: false, uri: '/admin/route-without-translation/' } as MockBreadcrumb);\n });\n\n describe('Special Cases for Breadcrumbs', function () {\n it('programming exercise import', () => {\n const testUrl = '/course-management/1/programming-exercises/import/2';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n\n const importCrumb = {\n label: 'artemisApp.exercise.import.table.doImport',\n translate: true,\n uri: '/course-management/1/programming-exercises/import/2/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(4);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], programmingExercisesCrumb);\n sinon.assert.match(component.breadcrumbs[3], importCrumb);\n });\n\n it('programming exercise grading', () => {\n const testUrl = '/course-management/1/programming-exercises/2/grading/test-cases';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n\n const gradingCrumb = {\n label: 'artemisApp.programmingExercise.configureGrading.shortTitle',\n translate: true,\n uri: '/course-management/1/programming-exercises/2/grading/test-cases/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(5);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], programmingExercisesCrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/programming-exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], gradingCrumb);\n });\n\n it('programming exercise new assessment', () => {\n const testUrl = '/course-management/1/programming-exercises/2/code-editor/new/assessment';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n\n const assessmentCrumb = {\n label: 'artemisApp.assessment.assessment',\n translate: true,\n uri: '/course-management/1/programming-exercises/2/code-editor/new/assessment/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(5);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], programmingExercisesCrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/programming-exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], assessmentCrumb);\n });\n\n it('programming exercise hints', () => {\n const testUrl = '/course-management/1/exercises/2/hints/3';\n router.setUrl(testUrl);\n\n const hintService = fixture.debugElement.injector.get(ExerciseHintService);\n const hintsStub = sinon.stub(hintService, 'getTitle').returns(of({ body: 'Exercise Hint' } as HttpResponse<string>));\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n expect(hintsStub).to.have.been.calledWith(3);\n\n const hintsCrumb = {\n label: 'artemisApp.exerciseHint.home.title',\n translate: true,\n uri: '/course-management/1/exercises/2/hints/',\n } as MockBreadcrumb;\n\n const hintCrumb = {\n label: 'Exercise Hint',\n translate: false,\n uri: '/course-management/1/exercises/2/hints/3/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(6);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], { label: 'artemisApp.course.exercises', translate: true, uri: '/course-management/1/exercises/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], hintsCrumb);\n sinon.assert.match(component.breadcrumbs[5], hintCrumb);\n });\n\n it('text exercise feedback conflict', () => {\n const testUrl = '/course-management/1/text-exercises/2/submissions/3/text-feedback-conflict/4';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n\n const submissionsCrumb = {\n label: 'artemisApp.exercise.submissions',\n translate: true,\n uri: '/course-management/1/text-exercises/2/submissions/',\n } as MockBreadcrumb;\n\n const conflictCrumb = {\n label: 'artemisApp.textAssessment.title',\n translate: true,\n uri: '/course-management/1/text-exercises/2/submissions/3/text-feedback-conflict/4/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(6);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], { label: 'artemisApp.course.exercises', translate: true, uri: '/course-management/1/text-exercises/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/text-exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], submissionsCrumb);\n sinon.assert.match(component.breadcrumbs[5], conflictCrumb);\n });\n\n it('modeling exercise example submission', () => {\n const testUrl = '/course-management/1/modeling-exercises/2/example-submissions/new';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n\n const submissionCrumb = {\n label: 'artemisApp.exampleSubmission.home.title',\n translate: true,\n uri: '/course-management/1/modeling-exercises/2/example-submissions/new/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(5);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], {\n label: 'artemisApp.course.exercises',\n translate: true,\n uri: '/course-management/1/modeling-exercises/',\n } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/modeling-exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], submissionCrumb);\n });\n\n it('modeling exercise example submission', () => {\n const testUrl = '/course-management/1/modeling-exercises/2/example-submissions/3';\n router.setUrl(testUrl);\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(exerciseStub).to.have.been.calledWith(2);\n\n const submissionCrumb = {\n label: 'artemisApp.exampleSubmission.home.title',\n translate: true,\n uri: '/course-management/1/modeling-exercises/2/example-submissions/3/',\n } as MockBreadcrumb;\n\n expect(component.breadcrumbs.length).to.equal(5);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], {\n label: 'artemisApp.course.exercises',\n translate: true,\n uri: '/course-management/1/modeling-exercises/',\n } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exercise', translate: false, uri: '/course-management/1/modeling-exercises/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], submissionCrumb);\n });\n\n it('lecture units', () => {\n const testUrl = '/course-management/1/lectures/2/unit-management/text-units/create';\n router.setUrl(testUrl);\n\n const lectureService = fixture.debugElement.injector.get(LectureService);\n const lectureStub = sinon.stub(lectureService, 'getTitle').returns(of({ body: 'Test Lecture' } as HttpResponse<string>));\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(lectureStub).to.have.been.calledWith(2);\n\n const unitManagementCrumb = {\n label: 'artemisApp.lectureUnit.home.title',\n translate: true,\n uri: '/course-management/1/lectures/2/unit-management/',\n } as MockBreadcrumb;\n\n const createCrumb = {\n label: 'global.generic.create',\n translate: true,\n uri: '/course-management/1/lectures/2/unit-management/text-units/create/',\n };\n\n expect(component.breadcrumbs.length).to.equal(6);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], { label: 'artemisApp.lecture.home.title', translate: true, uri: '/course-management/1/lectures/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Lecture', translate: false, uri: '/course-management/1/lectures/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], unitManagementCrumb);\n sinon.assert.match(component.breadcrumbs[5], createCrumb);\n });\n\n it('apollon diagrams', () => {\n const testUrl = '/course-management/1/apollon-diagrams/2';\n router.setUrl(testUrl);\n\n const apollonDiagramService = fixture.debugElement.injector.get(ApollonDiagramService);\n const apollonStub = sinon.stub(apollonDiagramService, 'getTitle').returns(of({ body: 'Apollon Diagram' } as HttpResponse<string>));\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(apollonStub).to.have.been.calledWith(2);\n\n expect(component.breadcrumbs.length).to.equal(4);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], {\n label: 'artemisApp.apollonDiagram.home.title',\n translate: true,\n uri: '/course-management/1/apollon-diagrams/',\n } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Apollon Diagram', translate: false, uri: '/course-management/1/apollon-diagrams/2/' } as MockBreadcrumb);\n });\n\n it('exam exercise groups', () => {\n const testUrl = '/course-management/1/exams/2/exercise-groups/3/quiz-exercises/new';\n router.setUrl(testUrl);\n\n const examService = fixture.debugElement.injector.get(ExamManagementService);\n const examStub = sinon.stub(examService, 'getTitle').returns(of({ body: 'Test Exam' } as HttpResponse<string>));\n\n fixture.detectChanges();\n\n expect(courseManagementStub).to.have.been.calledWith(1);\n expect(examStub).to.have.been.calledWith(2);\n\n const exerciseGroupsCrumb = {\n label: 'artemisApp.examManagement.exerciseGroups',\n translate: true,\n uri: '/course-management/1/exams/2/exercise-groups/',\n };\n const exercisesCrumb = {\n label: 'artemisApp.course.exercises',\n translate: true,\n uri: '/course-management/1/exams/2/exercise-groups/3/quiz-exercises/',\n };\n const createCrumb = {\n label: 'global.generic.create',\n translate: true,\n uri: '/course-management/1/exams/2/exercise-groups/3/quiz-exercises/new/',\n };\n\n expect(component.breadcrumbs.length).to.equal(7);\n\n // Use matching here to ignore non-semantic differences between objects\n sinon.assert.match(component.breadcrumbs[0], courseManagementCrumb);\n sinon.assert.match(component.breadcrumbs[1], testCourseCrumb);\n sinon.assert.match(component.breadcrumbs[2], { label: 'artemisApp.examManagement.title', translate: true, uri: '/course-management/1/exams/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[3], { label: 'Test Exam', translate: false, uri: '/course-management/1/exams/2/' } as MockBreadcrumb);\n sinon.assert.match(component.breadcrumbs[4], exerciseGroupsCrumb);\n sinon.assert.match(component.breadcrumbs[5], exercisesCrumb);\n sinon.assert.match(component.breadcrumbs[6], createCrumb);\n });\n });\n});\n" }, { "alpha_fraction": 0.6209262609481812, "alphanum_fraction": 0.6209262609481812, "avg_line_length": 29.6842098236084, "blob_id": "686a15d7b4be2e4040c53b18503f6a1c61ce0f66", "content_id": "7e9d04783e417c3b90fc48e0767550d0bf3a7ca2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1749, "license_type": "permissive", "max_line_length": 92, "num_lines": 57, "path": "/src/main/webapp/app/admin/metrics/metrics.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { JhiMetricsService } from 'app/admin/metrics/metrics.service';\n\n@Component({\n selector: 'jhi-metrics',\n templateUrl: './metrics.component.html',\n})\nexport class JhiMetricsMonitoringComponent implements OnInit {\n metrics: any = {};\n threadData: any = {};\n updatingMetrics = true;\n JCACHE_KEY: string;\n\n constructor(private modalService: NgbModal, private metricsService: JhiMetricsService) {\n this.JCACHE_KEY = 'jcache.statistics';\n }\n\n /**\n * Calls the refresh method on init\n */\n ngOnInit() {\n this.refresh();\n }\n\n /**\n * Refreshes the metrics by retrieving all metrics and thread dumps\n */\n refresh() {\n this.updatingMetrics = true;\n this.metricsService.getMetrics().subscribe((metrics) => {\n this.metrics = metrics;\n this.metricsService.threadDump().subscribe((data) => {\n this.threadData = data.threads;\n this.updatingMetrics = false;\n });\n });\n }\n\n /**\n * Checks if the metric with the key {@param key} exists\n * @param metrics json with metrics objects\n * @param key string identifier of a metric\n */\n isObjectExisting(metrics: any, key: string) {\n return metrics && metrics[key];\n }\n\n /**\n * Checks if the metric with the key {@param key} exists and is not empty\n * @param metrics json with metrics objects\n * @param key key string identifier of a metric\n */\n isObjectExistingAndNotEmpty(metrics: any, key: string) {\n return this.isObjectExisting(metrics, key) && JSON.stringify(metrics[key]) !== '{}';\n }\n}\n" }, { "alpha_fraction": 0.6775928139686584, "alphanum_fraction": 0.6801536679267883, "avg_line_length": 38.04999923706055, "blob_id": "f7c8498a0eb8c59442bdce5185eac8c36fc974be", "content_id": "ef82774ad989fe8b7df7ba2b0579b7b7d753db31", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3905, "license_type": "permissive", "max_line_length": 138, "num_lines": 100, "path": "/src/test/javascript/spec/component/student-questions/student-question-answer.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { StudentQuestionAnswerComponent } from 'app/overview/student-questions/student-question-answer/student-question-answer.component';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentQuestionAnswerComponent', () => {\n let component: StudentQuestionAnswerComponent;\n let componentFixture: ComponentFixture<StudentQuestionAnswerComponent>;\n\n const user1 = {\n id: 1,\n } as User;\n\n const user2 = {\n id: 2,\n } as User;\n\n const unApprovedStudentQuestionAnswer = {\n id: 1,\n answerDate: undefined,\n answerText: 'not approved',\n tutorApproved: false,\n author: user1,\n } as StudentQuestionAnswer;\n\n const approvedStudentQuestionAnswer = {\n id: 2,\n answerDate: undefined,\n answerText: 'approved',\n tutorApproved: true,\n author: user2,\n } as StudentQuestionAnswer;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n declarations: [StudentQuestionAnswerComponent],\n providers: [{ provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }],\n })\n .overrideTemplate(StudentQuestionAnswerComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(StudentQuestionAnswerComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should be author of answer', () => {\n component.studentQuestionAnswer = approvedStudentQuestionAnswer;\n component.user = user2;\n expect(component.isAuthorOfAnswer(approvedStudentQuestionAnswer)).to.be.true;\n });\n\n it('should not be author of answer', () => {\n component.studentQuestionAnswer = approvedStudentQuestionAnswer;\n component.user = user2;\n expect(component.isAuthorOfAnswer(unApprovedStudentQuestionAnswer)).to.be.false;\n });\n\n it('should approve answer', () => {\n component.studentQuestionAnswer = unApprovedStudentQuestionAnswer;\n component.toggleAnswerTutorApproved();\n expect(component.studentQuestionAnswer.tutorApproved).to.be.true;\n });\n\n it('should unapprove answer', () => {\n component.studentQuestionAnswer = approvedStudentQuestionAnswer;\n component.toggleAnswerTutorApproved();\n expect(component.studentQuestionAnswer.tutorApproved).to.be.false;\n });\n\n it('should toggle edit mode and reset editor Text', () => {\n component.studentQuestionAnswer = approvedStudentQuestionAnswer;\n component.isEditMode = true;\n component.editText = 'test';\n component.toggleEditMode();\n expect(component.editText).to.deep.equal('approved');\n expect(component.isEditMode).to.be.false;\n component.toggleEditMode();\n expect(component.isEditMode).to.be.true;\n });\n\n it('should update answerText', () => {\n component.studentQuestionAnswer = approvedStudentQuestionAnswer;\n component.isEditMode = true;\n component.editText = 'test';\n component.saveAnswer();\n expect(component.studentQuestionAnswer.answerText).to.deep.equal('test');\n });\n});\n" }, { "alpha_fraction": 0.667067289352417, "alphanum_fraction": 0.6674679517745972, "avg_line_length": 35.173912048339844, "blob_id": "12184e9073699244cd2180820eb0f135a4a0124e", "content_id": "f8c540e0e3af19a302e6befd6a2de581559170aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2496, "license_type": "permissive", "max_line_length": 145, "num_lines": 69, "path": "/src/main/webapp/app/exercises/programming/shared/utils/build-plan-link.directive.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Directive, HostBinding, HostListener, Input, OnInit } from '@angular/core';\nimport { take, tap } from 'rxjs/operators';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\n\n/**\n * Creates the build pan URL for the given template URL.\n *\n * @param template The URL to the CI with placeholders for the plan ID and project key\n * @param projectKey The project key of the programming exercise\n * @param buildPlanId The ID of the build plan for which to construct the URL\n */\nexport const createBuildPlanUrl = (template: string, projectKey: string, buildPlanId: string) => {\n if (template && projectKey && buildPlanId) {\n return template.replace('{buildPlanId}', buildPlanId).replace('{projectKey}', projectKey);\n }\n};\n\n@Directive({ selector: 'a[jhiBuildPlanLink]' })\nexport class BuildPlanLinkDirective implements OnInit {\n @HostBinding('attr.href')\n readonly href = '';\n\n private participationBuildPlanId: string;\n private exerciseProjectKey: string;\n private templateLink: string;\n private linkToBuildPlan?: string;\n\n constructor(private profileService: ProfileService) {}\n\n /**\n * Life cycle hook called by Angular to indicate that Angular is done creating the component\n */\n ngOnInit(): void {\n this.profileService\n .getProfileInfo()\n .pipe(\n take(1),\n tap((info: ProfileInfo) => {\n this.templateLink = info.buildPlanURLTemplate;\n this.linkToBuildPlan = createBuildPlanUrl(info.buildPlanURLTemplate, this.exerciseProjectKey, this.participationBuildPlanId);\n }),\n )\n .subscribe();\n }\n\n @Input()\n set projectKey(key: string) {\n this.exerciseProjectKey = key;\n this.linkToBuildPlan = createBuildPlanUrl(this.templateLink, this.exerciseProjectKey, this.participationBuildPlanId);\n }\n\n @Input()\n set buildPlanId(planId: string) {\n this.participationBuildPlanId = planId;\n this.linkToBuildPlan = createBuildPlanUrl(this.templateLink, this.exerciseProjectKey, this.participationBuildPlanId);\n }\n\n /**\n * Opens build plan link window.\n */\n @HostListener('click', ['$event'])\n openBuildPlanLink($event: any) {\n $event.preventDefault();\n if (this.linkToBuildPlan) {\n window.open(this.linkToBuildPlan);\n }\n }\n}\n" }, { "alpha_fraction": 0.6927047371864319, "alphanum_fraction": 0.696377158164978, "avg_line_length": 46.07944107055664, "blob_id": "2eadfd6e6ab46d10d4616744c77bfed136e1e966", "content_id": "625a9430009a03c0990ef43846ca8e0a5845c4ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10075, "license_type": "permissive", "max_line_length": 138, "num_lines": 214, "path": "/src/test/javascript/spec/component/shared/clone-repo-button.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\n\nimport { CloneRepoButtonComponent } from 'app/shared/components/clone-repo-button/clone-repo-button.component';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { MockComponent, MockProvider } from 'ng-mocks';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { MockProfileService } from '../../helpers/mocks/service/mock-profile.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport * as sinon from 'sinon';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ExerciseActionButtonComponent } from 'app/shared/components/exercise-action-button.component';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { of, BehaviorSubject, Subject } from 'rxjs';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { SinonStub, stub } from 'sinon';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { By } from '@angular/platform-browser';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { MockAlertService } from '../../helpers/mocks/service/mock-alert.service';\nimport { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('JhiCloneRepoButtonComponent', () => {\n let component: CloneRepoButtonComponent;\n let fixture: ComponentFixture<CloneRepoButtonComponent>;\n let profileService: ProfileService;\n let sourceTreeService: SourceTreeService;\n let accountService: AccountService;\n\n let localStorageUseSshRetrieveStub: SinonStub;\n let localStorageUseSshObserveStub: SinonStub;\n let localStorageUseSshObserveStubSubject: Subject<boolean | undefined>;\n let localStorageUseSshStoreStub: SinonStub;\n\n const info: ProfileInfo = {\n activeProfiles: [],\n allowedMinimumOrionVersion: '',\n buildPlanURLTemplate: '',\n commitHashURLTemplate: '',\n contact: '',\n externalUserManagementName: '',\n externalUserManagementURL: '',\n features: [],\n imprint: '',\n inProduction: false,\n programmingLanguageFeatures: [],\n ribbonEnv: '',\n sshCloneURLTemplate: 'ssh://[email protected]:7999/',\n sshKeysURL: 'sshKeysURL',\n testServer: false,\n versionControlUrl: 'https://bitbucket.ase.in.tum.de/scm/ITCPLEASE1/itcplease1-exercise-team1.git',\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), NgbModule, ArtemisSharedModule, FeatureToggleModule, ClipboardModule],\n declarations: [CloneRepoButtonComponent, MockComponent(ExerciseActionButtonComponent)],\n providers: [\n { provide: JhiAlertService, useClass: MockAlertService },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: ProfileService, useClass: MockProfileService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n MockProvider(SourceTreeService, {}),\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(CloneRepoButtonComponent);\n component = fixture.componentInstance;\n profileService = TestBed.inject(ProfileService);\n sourceTreeService = TestBed.inject(SourceTreeService);\n accountService = TestBed.inject(AccountService);\n\n const localStorageMock = fixture.debugElement.injector.get(LocalStorageService);\n localStorageUseSshRetrieveStub = stub(localStorageMock, 'retrieve');\n localStorageUseSshObserveStub = stub(localStorageMock, 'observe');\n localStorageUseSshStoreStub = stub(localStorageMock, 'store');\n localStorageUseSshObserveStubSubject = new Subject();\n localStorageUseSshObserveStub.returns(localStorageUseSshObserveStubSubject);\n });\n\n afterEach(function () {\n // completely restore all fakes created through the sandbox\n sinon.restore();\n });\n\n it('should initialize', fakeAsync(() => {\n stubServices();\n\n component.ngOnInit();\n tick();\n expect(component.sshKeysUrl).to.equal(info.sshKeysURL);\n expect(component.sshTemplateUrl).to.equal(info.sshCloneURLTemplate);\n expect(component.sshEnabled).to.equal(!!info.sshCloneURLTemplate);\n expect(component.repositoryPassword).to.equal('repository_password');\n expect(component.versionControlUrl).to.equal(info.versionControlUrl);\n }));\n\n it('should save repository password if SourceTree returns one', () => {\n const fakeSourceTreeResponse = { password: 'repository_password' };\n sinon.replace(sourceTreeService, 'getRepositoryPassword', sinon.fake.returns(of(fakeSourceTreeResponse)));\n\n component.getRepositoryPassword();\n expect(component.repositoryPassword).to.equal('repository_password');\n });\n\n it('should not save repository password if SourceTree doesnt return one', () => {\n const fakeSourceTreeResponse = { error: 'Some password not found error' };\n sinon.replace(sourceTreeService, 'getRepositoryPassword', sinon.fake.returns(of(fakeSourceTreeResponse)));\n\n component.repositoryPassword = 'password';\n component.getRepositoryPassword();\n expect(component.repositoryPassword).to.equal('password');\n });\n\n it('should get ssh url (same url for team and individual participation)', () => {\n component.repositoryUrl = 'https://bitbucket.ase.in.tum.de/scm/ITCPLEASE1/itcplease1-exercise.git';\n component.sshTemplateUrl = 'ssh://[email protected]:7999/';\n component.useSsh = true;\n\n component.isTeamParticipation = true;\n let url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal('ssh://[email protected]:7999/ITCPLEASE1/itcplease1-exercise.git');\n\n component.isTeamParticipation = false;\n url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal('ssh://[email protected]:7999/ITCPLEASE1/itcplease1-exercise.git');\n });\n\n it('should get html url (not the same url for team and individual participation)', () => {\n component.repositoryUrl = info.versionControlUrl!;\n component.sshTemplateUrl = 'ssh://[email protected]:7999/';\n component.useSsh = false;\n\n component.user = { login: 'user1', guidedTourSettings: [] };\n component.isTeamParticipation = true;\n let url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal(`https://${component.user.login}@bitbucket.ase.in.tum.de/scm/ITCPLEASE1/itcplease1-exercise-team1.git`);\n\n component.isTeamParticipation = false;\n url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal(info.versionControlUrl!);\n });\n\n it('should get copy the repository url', () => {\n component.repositoryUrl = info.versionControlUrl!;\n component.useSsh = false;\n\n component.user = { login: 'user1', guidedTourSettings: [] };\n component.isTeamParticipation = true;\n let url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal(`https://${component.user.login}@bitbucket.ase.in.tum.de/scm/ITCPLEASE1/itcplease1-exercise-team1.git`);\n\n component.isTeamParticipation = false;\n url = component.getHttpOrSshRepositoryUrl();\n expect(url).to.equal(info.versionControlUrl!);\n });\n\n it('should fetch and store ssh preference', fakeAsync(() => {\n stubServices();\n\n component.sshEnabled = true;\n\n fixture.detectChanges();\n tick();\n\n expect(localStorageUseSshRetrieveStub).to.have.been.calledOnceWithExactly('useSsh');\n expect(localStorageUseSshObserveStub).to.have.been.calledOnceWithExactly('useSsh');\n expect(component.useSsh).to.be.false;\n\n fixture.debugElement.query(By.css('.clone-repository')).nativeElement.click();\n tick();\n fixture.debugElement.query(By.css('.use-ssh'));\n fixture.debugElement.query(By.css('.use-ssh')).nativeElement.click();\n tick();\n expect(localStorageUseSshStoreStub).to.have.been.calledOnceWithExactly('useSsh', true);\n expect(component.useSsh).to.be.true;\n\n fixture.debugElement.query(By.css('.use-ssh')).nativeElement.click();\n tick();\n expect(localStorageUseSshStoreStub).to.have.been.calledWithExactly('useSsh', false);\n expect(component.useSsh).to.be.false;\n\n localStorageUseSshObserveStubSubject.next(true);\n tick();\n expect(component.useSsh).to.be.true;\n\n localStorageUseSshObserveStubSubject.next(false);\n tick();\n expect(component.useSsh).to.be.false;\n }));\n\n function stubServices() {\n const identityStub = sinon.stub(accountService, 'identity');\n identityStub.returns(Promise.resolve({ guidedTourSettings: [], login: 'edx_userLogin' }));\n\n const getRepositoryPasswordStub = sinon.stub(sourceTreeService, 'getRepositoryPassword');\n getRepositoryPasswordStub.returns(of({ password: 'repository_password' }));\n\n const getProfileInfoStub = sinon.stub(profileService, 'getProfileInfo');\n getProfileInfoStub.returns(new BehaviorSubject(info));\n }\n});\n" }, { "alpha_fraction": 0.6298342347145081, "alphanum_fraction": 0.6306235194206238, "avg_line_length": 18.796875, "blob_id": "56b22df4789d31008c2849ca68fbf443e9827e03", "content_id": "e5d33ce7b5c9dc8ebdebb0700b648d4cca4f95b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1267, "license_type": "permissive", "max_line_length": 78, "num_lines": 64, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/bitbucket/dto/BitbucketWebHookDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.bitbucket.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class BitbucketWebHookDTO {\n\n private Integer id;\n\n private String name;\n\n private String url;\n\n private List<String> events = new ArrayList<>();\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public List<String> getEvents() {\n return events;\n }\n\n public void setEvents(List<String> events) {\n this.events = events;\n }\n\n /**\n * needed for Jackson\n */\n public BitbucketWebHookDTO() {\n }\n\n public BitbucketWebHookDTO(String name, String url, List<String> events) {\n this.name = name;\n this.url = url;\n this.events = events;\n }\n}\n" }, { "alpha_fraction": 0.6220588088035583, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 20.935483932495117, "blob_id": "3a7d106cbd7970d0edb0c81ca558b64823edff78", "content_id": "1212529f9680eaef74abcb7b31885361c2ad0c00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 680, "license_type": "permissive", "max_line_length": 112, "num_lines": 31, "path": "/src/main/java/de/tum/in/www1/artemis/security/Role.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.security;\n\n/**\n * Constants for Spring Security authorities.\n */\npublic enum Role {\n\n // NOTE: we will soon rename \"USER\" to \"STUDENT\" in the database and add a new role \"EDITOR\"\n ADMIN(\"ADMIN\"), INSTRUCTOR(\"INSTRUCTOR\"), TEACHING_ASSISTANT(\"TA\"), STUDENT(\"USER\"), ANONYMOUS(\"ANONYMOUS\");\n\n public static final String ROLE_PREFIX = \"ROLE_\";\n\n private final String role;\n\n Role(String role) {\n this.role = role;\n }\n\n public String getAuthority() {\n return ROLE_PREFIX + role;\n }\n\n public String getRole() {\n return role;\n }\n\n @Override\n public String toString() {\n return role;\n }\n}\n" }, { "alpha_fraction": 0.6048644185066223, "alphanum_fraction": 0.6063264012336731, "avg_line_length": 43.25882339477539, "blob_id": "662796fb5382e2ee9d1fdbcba4b660e0079cd057", "content_id": "8a2d6ffd41dcfaf812a3d306581044eca66abaae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7524, "license_type": "permissive", "max_line_length": 153, "num_lines": 170, "path": "/src/test/javascript/spec/component/team/team.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HTTP_INTERCEPTORS } from '@angular/common/http';\nimport { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';\nimport { ActivatedRoute, Router, RouterModule } from '@angular/router';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { TeamParticipationTableComponent } from 'app/exercises/shared/team/team-participation-table/team-participation-table.component';\nimport { TeamDeleteButtonComponent } from 'app/exercises/shared/team/team-update-dialog/team-delete-button.component';\nimport { TeamUpdateButtonComponent } from 'app/exercises/shared/team/team-update-dialog/team-update-button.component';\nimport { TeamComponent } from 'app/exercises/shared/team/team.component.ts';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { DataTableComponent } from 'app/shared/data-table/data-table.component';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe.ts';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { JhiAlertService, NgJhipsterModule } from 'ng-jhipster';\nimport { MockComponent, MockModule, MockPipe, MockProvider } from 'ng-mocks';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of, throwError } from 'rxjs';\nimport { restore, SinonStub, spy, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { mockExercise, mockTeam, mockTeams, TeamRequestInterceptorMock } from '../../helpers/mocks/service/mock-team.service';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TeamComponent', () => {\n let comp: TeamComponent;\n let fixture: ComponentFixture<TeamComponent>;\n let router: Router;\n const user = new User(99, 'newUser', 'UserFirstName', 'UserLastName');\n let accountService: AccountService;\n let identityStub: SinonStub;\n let exerciseService: ExerciseService;\n let teamService: TeamService;\n let alertService: JhiAlertService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n MockModule(NgbModule),\n MockModule(NgJhipsterModule),\n MockModule(FeatureToggleModule),\n MockModule(NgxDatatableModule),\n MockModule(RouterModule),\n ],\n declarations: [\n TeamComponent,\n MockComponent(TeamUpdateButtonComponent),\n MockComponent(TeamDeleteButtonComponent),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockComponent(TeamParticipationTableComponent),\n MockComponent(DataTableComponent),\n MockComponent(AlertComponent),\n ],\n providers: [\n MockProvider(SessionStorageService),\n MockProvider(LocalStorageService),\n MockProvider(AccountService),\n TeamService,\n MockProvider(TranslateService),\n ExerciseService,\n {\n provide: HTTP_INTERCEPTORS,\n useClass: TeamRequestInterceptorMock,\n multi: true,\n },\n MockProvider(Router),\n {\n provide: ActivatedRoute,\n useValue: {\n params: of({ teamId: mockTeam.id, exerciseId: mockExercise.id }),\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n accountService = TestBed.inject(AccountService);\n identityStub = stub(accountService, 'identity').returns(Promise.resolve(user));\n stub(accountService, 'isAtLeastTutorInCourse').returns(true);\n stub(accountService, 'isAtLeastInstructorInCourse').returns(true);\n fixture = TestBed.createComponent(TeamComponent);\n comp = fixture.componentInstance;\n alertService = TestBed.inject(JhiAlertService);\n router = TestBed.inject(Router);\n teamService = TestBed.inject(TeamService);\n exerciseService = TestBed.inject(ExerciseService);\n });\n });\n\n afterEach(() => {\n restore();\n });\n\n describe('ngOnInit', () => {\n let alertServiceStub: SinonStub;\n\n afterEach(() => {\n restore();\n });\n\n it('should set team and exercise from services', () => {\n comp.ngOnInit();\n expect(comp.exercise).to.deep.equal(mockExercise);\n expect(comp.team).to.deep.equal(mockTeam);\n expect(comp.exercise.isAtLeastTutor).equal(true);\n expect(comp.exercise.isAtLeastInstructor).equal(true);\n expect(comp.isTeamOwner).to.equal(false);\n });\n\n it('should call alert service error when exercise service fails', () => {\n const exerciseStub = stub(exerciseService, 'find').returns(throwError({ status: 404 }));\n alertServiceStub = stub(alertService, 'error');\n waitForAsync(() => {\n comp.ngOnInit();\n expect(exerciseStub).to.have.been.called;\n expect(alertServiceStub).to.have.been.called;\n expect(comp.isLoading).to.equal(false);\n });\n });\n\n it('should call alert service error when team service fails', () => {\n const teamStub = stub(teamService, 'find').returns(throwError({ status: 404 }));\n alertServiceStub = stub(alertService, 'error');\n waitForAsync(() => {\n comp.ngOnInit();\n expect(teamStub).to.have.been.called;\n expect(alertServiceStub).to.have.been.called;\n expect(comp.isLoading).to.equal(false);\n });\n });\n });\n\n describe('ngOnInit with team owner', () => {\n it('should set team owner true if user is team owner', () => {\n waitForAsync(() => {\n identityStub.returns(Promise.resolve({ ...user, id: 1 }));\n fixture = TestBed.createComponent(TeamComponent);\n comp = fixture.componentInstance;\n comp.ngOnInit();\n expect(comp.isTeamOwner).to.equal(true);\n });\n });\n });\n\n describe('onTeamUpdate', () => {\n it('should update team to given team', () => {\n comp.onTeamUpdate(mockTeams[1]);\n expect(comp.team).to.deep.equal(mockTeams[1]);\n });\n });\n\n describe('onTeamDelete', () => {\n it('should go to teams overview on delete', () => {\n comp.ngOnInit();\n const routerSpy = spy(router, 'navigate');\n comp.onTeamDelete();\n expect(routerSpy).to.have.been.calledOnceWithExactly(['/course-management', mockExercise.course?.id, 'exercises', mockExercise.id, 'teams']);\n });\n });\n});\n" }, { "alpha_fraction": 0.5307376980781555, "alphanum_fraction": 0.5420082211494446, "avg_line_length": 39.66666793823242, "blob_id": "6ebcbc4d4fb53e29ebef4372a1e571e69ee4bdf7", "content_id": "0cdb99b743b45fdb5b2cd605bded90670c12a76a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1952, "license_type": "permissive", "max_line_length": 114, "num_lines": 48, "path": "/src/test/javascript/jest.config.js", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "const esModules = ['ngx-treeview', 'lodash-es'].join('|');\nmodule.exports = {\n globals: {\n 'ts-jest': {\n tsconfig: '<rootDir>/tsconfig.spec.json',\n stringifyContentPathRegex: '\\\\.html$',\n astTransformers: {\n before: [require.resolve('./InlineHtmlStripStylesTransformer')],\n },\n diagnostics: {\n ignoreCodes: [151001],\n },\n },\n },\n collectCoverageFrom: ['src/main/webapp/**/*.{js,jsx,ts,tsx}', '!src/main/webapp/**/*.module.{js,jsx,ts,tsx}'],\n coverageThreshold: {\n global: {\n // TODO: in the future, the following values should be increase to at least 80%\n statements: 75,\n branches: 56,\n functions: 64,\n lines: 74,\n },\n },\n preset: 'jest-preset-angular',\n setupFilesAfterEnv: ['<rootDir>/src/test/javascript/jest.ts', 'jest-sinon'],\n modulePaths: ['<rootDir>/src/main/webapp/'],\n transformIgnorePatterns: [`/node_modules/(?!${esModules})`],\n rootDir: '../../../',\n modulePathIgnorePatterns: [],\n testMatch: [\n '<rootDir>/src/test/javascript/spec/component/**/*.ts',\n '<rootDir>/src/test/javascript/spec/directive/**/*.ts',\n '<rootDir>/src/test/javascript/spec/integration/**/*.ts',\n '<rootDir>/src/test/javascript/spec/pipe/**/*.ts',\n '<rootDir>/src/test/javascript/spec/service/**/*.ts',\n '<rootDir>/src/test/javascript/spec/util/**/*.ts',\n ],\n moduleNameMapper: {\n '^app/(.*)': '<rootDir>/src/main/webapp/app/$1',\n 'test/(.*)': '<rootDir>/src/test/javascript/spec/$1',\n '@assets/(.*)': '<rootDir>/src/main/webapp/assets/$1',\n '@core/(.*)': '<rootDir>/src/main/webapp/app/core/$1',\n '@env': '<rootDir>/src/main/webapp/environments/environment',\n '@src/(.*)': '<rootDir>/src/src/$1',\n '@state/(.*)': '<rootDir>/src/app/state/$1',\n },\n};\n" }, { "alpha_fraction": 0.7087198495864868, "alphanum_fraction": 0.7087198495864868, "avg_line_length": 36.17241287231445, "blob_id": "2a4625295d381690c198daf96c8e99273bf0a26d", "content_id": "09084e2a4fcb7931562f6df8de774a94f9e2cabc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2156, "license_type": "permissive", "max_line_length": 141, "num_lines": 58, "path": "/src/main/webapp/app/exercises/shared/plagiarism/plagiarism-header/plagiarism-header.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Subject } from 'rxjs';\nimport { PlagiarismStatus } from 'app/exercises/shared/plagiarism/types/PlagiarismStatus';\nimport { PlagiarismComparison } from 'app/exercises/shared/plagiarism/types/PlagiarismComparison';\n\n// False-positives:\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ModelingSubmissionElement } from 'app/exercises/shared/plagiarism/types/modeling/ModelingSubmissionElement';\nimport { SERVER_API_URL } from 'app/app.constants';\n\n@Component({\n selector: 'jhi-plagiarism-header',\n styleUrls: ['./plagiarism-header.component.scss'],\n templateUrl: './plagiarism-header.component.html',\n})\nexport class PlagiarismHeaderComponent {\n @Input() comparison: PlagiarismComparison<TextSubmissionElement | ModelingSubmissionElement>;\n @Input() splitControlSubject: Subject<string>;\n\n private resourceUrl = SERVER_API_URL + 'api/plagiarism-comparisons';\n\n constructor(public http: HttpClient) {}\n\n /**\n * Set the status of the currently selected comparison to CONFIRMED.\n */\n confirmPlagiarism() {\n this.updatePlagiarismStatus(PlagiarismStatus.CONFIRMED);\n }\n\n /**\n * Set the status of the currently selected comparison to DENIED.\n */\n denyPlagiarism() {\n this.updatePlagiarismStatus(PlagiarismStatus.DENIED);\n }\n\n /**\n * Update the status of the currently selected comparison.\n * @param status the new status of the comparison\n */\n updatePlagiarismStatus(status: PlagiarismStatus) {\n return this.http.put<void>(`${this.resourceUrl}/${this.comparison.id}/status`, { status }, { observe: 'response' }).subscribe(() => {\n this.comparison.status = status;\n });\n }\n\n expandSplitPane(pane: 'left' | 'right') {\n this.splitControlSubject.next(pane);\n }\n\n resetSplitPanes() {\n this.splitControlSubject.next('even');\n }\n}\n" }, { "alpha_fraction": 0.6662269234657288, "alphanum_fraction": 0.6662269234657288, "avg_line_length": 37.37974548339844, "blob_id": "8c31a33bbde2e551c26be0d1756e0d3ff746a1d2", "content_id": "817ea66628e43bcab7d90ea3940fe85daf41e331", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3032, "license_type": "permissive", "max_line_length": 143, "num_lines": 79, "path": "/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Subscription } from 'rxjs/Subscription';\nimport { JhiEventManager } from 'ng-jhipster';\n\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { FileUploadExerciseService } from './file-upload-exercise.service';\nimport { filter } from 'rxjs/operators';\nimport { JhiAlertService } from 'ng-jhipster';\n\n@Component({\n selector: 'jhi-file-upload-exercise-detail',\n templateUrl: './file-upload-exercise-detail.component.html',\n})\nexport class FileUploadExerciseDetailComponent implements OnInit, OnDestroy {\n fileUploadExercise: FileUploadExercise;\n isExamExercise: boolean;\n private subscription: Subscription;\n private eventSubscriber: Subscription;\n\n constructor(\n private eventManager: JhiEventManager,\n private fileUploadExerciseService: FileUploadExerciseService,\n private route: ActivatedRoute,\n private jhiAlertService: JhiAlertService,\n ) {}\n\n /**\n * Initializes subscription for file upload exercise\n */\n ngOnInit() {\n // TODO: route determines whether the component is in exam mode\n this.subscription = this.route.params.subscribe((params) => {\n this.load(params['exerciseId']);\n });\n this.registerChangeInFileUploadExercises();\n }\n\n /**\n * Loads file upload exercise from the server\n * @param exerciseId the id of the file upload exercise\n */\n load(exerciseId: number) {\n // TODO: Use a separate find method for exam exercises containing course, exam, exerciseGroup and exercise id\n this.fileUploadExerciseService\n .find(exerciseId)\n .pipe(filter((res) => !!res.body))\n .subscribe(\n (fileUploadExerciseResponse: HttpResponse<FileUploadExercise>) => {\n this.fileUploadExercise = fileUploadExerciseResponse.body!;\n this.isExamExercise = this.fileUploadExercise.exerciseGroup !== undefined;\n if (this.fileUploadExercise.categories) {\n this.fileUploadExercise.categories = this.fileUploadExercise.categories.map((category) => JSON.parse(category));\n }\n },\n (res: HttpErrorResponse) => this.onError(res),\n );\n }\n\n /**\n * Unsubscribes on component destruction\n */\n ngOnDestroy() {\n this.subscription.unsubscribe();\n this.eventManager.destroy(this.eventSubscriber);\n }\n\n /**\n * Listens to file upload exercise list modifications\n */\n registerChangeInFileUploadExercises() {\n this.eventSubscriber = this.eventManager.subscribe('fileUploadExerciseListModification', () => this.load(this.fileUploadExercise.id!));\n }\n\n private onError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n }\n}\n" }, { "alpha_fraction": 0.6126618385314941, "alphanum_fraction": 0.6154935359954834, "avg_line_length": 37.03076934814453, "blob_id": "7fd1471c17aeafbae5cdc65dc245f7d5239a2a9b", "content_id": "8e95e9b93f5c5917014e0a4f4dea70e42be9dbd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4944, "license_type": "permissive", "max_line_length": 118, "num_lines": 130, "path": "/src/test/javascript/spec/component/student-questions/student-question.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { StudentQuestionComponent } from 'app/overview/student-questions/student-question/student-question.component';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { ConfirmIconComponent } from 'app/shared/confirm-icon/confirm-icon.component';\nimport { StudentVotesComponent } from 'app/overview/student-questions/student-votes/student-votes.component';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentQuestionComponent', () => {\n let component: StudentQuestionComponent;\n let componentFixture: ComponentFixture<StudentQuestionComponent>;\n\n const user1 = {\n id: 1,\n } as User;\n\n const user2 = {\n id: 2,\n } as User;\n\n const unApprovedStudentQuestionAnswer = {\n id: 1,\n answerDate: undefined,\n answerText: 'not approved',\n tutorApproved: false,\n author: user1,\n } as StudentQuestionAnswer;\n\n const approvedStudentQuestionAnswer = {\n id: 2,\n answerDate: undefined,\n answerText: 'approved',\n tutorApproved: true,\n author: user2,\n } as StudentQuestionAnswer;\n\n const studentQuestion = {\n id: 1,\n questionText: 'question',\n creationDate: undefined,\n author: user1,\n answers: [unApprovedStudentQuestionAnswer, approvedStudentQuestionAnswer],\n } as StudentQuestion;\n\n const maliciousStudentQuestion = {\n id: 2,\n questionText: '<div style=\"transform: scaleX(-1)\">&gt;:)</div>',\n creationDate: undefined,\n author: user2,\n answers: [],\n } as StudentQuestion;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule],\n declarations: [\n StudentQuestionComponent,\n MockDirective(MarkdownEditorComponent),\n MockDirective(ConfirmIconComponent),\n MockDirective(StudentVotesComponent),\n MockDirective(NgbTooltip),\n MockPipe(ArtemisDatePipe),\n MockPipe(ArtemisTranslatePipe),\n // Don't mock this since we want to test this pipe, too\n HtmlForMarkdownPipe,\n ],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n snapshot: {\n paramMap: {\n get: () => {\n return { courseId: 1 };\n },\n },\n },\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(StudentQuestionComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should toggle edit mode and reset editor Text', () => {\n component.studentQuestion = studentQuestion;\n component.isEditMode = true;\n component.editText = 'test';\n component.toggleEditMode();\n expect(component.editText).to.deep.equal('question');\n expect(component.isEditMode).to.be.false;\n component.toggleEditMode();\n expect(component.isEditMode).to.be.true;\n });\n\n it('should update questionText', () => {\n component.studentQuestion = studentQuestion;\n component.isEditMode = true;\n component.editText = 'test';\n component.saveQuestion();\n expect(component.studentQuestion.questionText).to.deep.equal('test');\n });\n\n it('should not display malicious html in question texts', () => {\n component.studentQuestion = maliciousStudentQuestion;\n componentFixture.detectChanges();\n\n const text = componentFixture.debugElement.nativeElement.querySelector('#questionText');\n expect(text.innerHTML).to.not.equal(maliciousStudentQuestion.questionText);\n expect(text.innerHTML).to.equal('&gt;:)');\n });\n});\n" }, { "alpha_fraction": 0.6826608777046204, "alphanum_fraction": 0.6844329237937927, "avg_line_length": 53.34074020385742, "blob_id": "3862d5fdcb14de1d45f736ee1026152415becf85", "content_id": "94c148682717f433ff8eed9fcc446679c3c70ea7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7336, "license_type": "permissive", "max_line_length": 140, "num_lines": 135, "path": "/src/test/javascript/spec/component/shared/notification/notification-popup.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { BehaviorSubject } from 'rxjs';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { NotificationPopupComponent } from 'app/shared/notification/notification-popup/notification-popup.component';\nimport { NotificationService } from 'app/shared/notification/notification.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockNotificationService } from '../../../helpers/mocks/service/mock-notification.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { Notification } from 'app/entities/notification.model';\nimport { RouterTestingModule } from '@angular/router/testing';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Notification Popup Component', () => {\n let notificationPopupComponent: NotificationPopupComponent;\n let notificationPopupComponentFixture: ComponentFixture<NotificationPopupComponent>;\n let notificationService: NotificationService;\n let accountService: AccountService;\n let router: Router;\n\n const generateNotification = (id: number) => {\n const generatedNotification = { id, title: 'Quiz started', text: 'Quiz \"Proxy pattern\" just started.' } as Notification;\n generatedNotification.target = JSON.stringify({ mainPage: 'courses', course: 1, entity: 'exercise', id: 1 });\n return generatedNotification;\n };\n const notification = generateNotification(1);\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, RouterTestingModule.withRoutes([])],\n declarations: [NotificationPopupComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: NotificationService, useClass: MockNotificationService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .compileComponents()\n .then(() => {\n notificationPopupComponentFixture = TestBed.createComponent(NotificationPopupComponent);\n notificationPopupComponent = notificationPopupComponentFixture.componentInstance;\n notificationService = TestBed.inject(NotificationService);\n accountService = TestBed.inject(AccountService);\n router = TestBed.get(Router);\n });\n });\n\n describe('Initialization', () => {\n it('should get authentication state', () => {\n sinon.spy(accountService, 'getAuthenticationState');\n notificationPopupComponent.ngOnInit();\n expect(accountService.getAuthenticationState).to.have.been.calledOnce;\n });\n\n it('should subscribe to notification updates', () => {\n sinon.spy(notificationService, 'subscribeToNotificationUpdates');\n notificationPopupComponent.ngOnInit();\n expect(notificationService.subscribeToNotificationUpdates).to.have.been.calledOnce;\n });\n });\n\n describe('Click', () => {\n beforeEach(() => {\n notificationPopupComponent.notifications.push(notification);\n notificationPopupComponentFixture.detectChanges();\n });\n\n it('should remove notification from component state and navigate to target when notification is clicked', () => {\n sinon.spy(notificationPopupComponent, 'removeNotification');\n sinon.replace(notificationPopupComponent, 'navigateToTarget', sinon.fake());\n const notificationElement = notificationPopupComponentFixture.debugElement.query(By.css('.notification-popup-container > div'));\n notificationElement.nativeElement.click();\n expect(notificationPopupComponent.removeNotification).to.have.been.calledOnce;\n expect(notificationPopupComponent.notifications).to.be.empty;\n expect(notificationPopupComponent.navigateToTarget).to.have.been.calledOnce;\n });\n\n it('should remove notification from component state when notification is closed', () => {\n sinon.spy(notificationPopupComponent, 'removeNotification');\n sinon.replace(notificationPopupComponent, 'navigateToTarget', sinon.fake());\n const button = notificationPopupComponentFixture.debugElement.query(By.css('.notification-popup-container > div button'));\n button.nativeElement.click();\n expect(notificationPopupComponent.removeNotification).to.have.been.called;\n expect(notificationPopupComponent.notifications).to.be.empty;\n });\n\n it('should navigate to target when notification is clicked', () => {\n sinon.spy(notificationPopupComponent, 'navigateToTarget');\n sinon.replace(router, 'navigateByUrl', sinon.fake());\n const button = notificationPopupComponentFixture.debugElement.query(By.css('.notification-popup-container > div button'));\n button.nativeElement.click();\n expect(notificationPopupComponent.navigateToTarget).to.have.been.calledOnce;\n expect(router.navigateByUrl).to.have.been.calledOnce;\n });\n });\n\n describe('Webscoket receive', () => {\n const replaceSubscribeToNotificationUpdates = () => {\n const fake = sinon.fake.returns(new BehaviorSubject(notification));\n sinon.replace(notificationService, 'subscribeToNotificationUpdates', fake);\n };\n\n it('should prepend received quiz notification', fakeAsync(() => {\n sinon.replace(router, 'isActive', sinon.fake.returns(false));\n replaceSubscribeToNotificationUpdates();\n const otherNotification = generateNotification(2);\n notificationPopupComponent.notifications = [otherNotification];\n notificationPopupComponent.ngOnInit();\n expect(notificationPopupComponent.notifications.length).to.be.equal(2);\n expect(notificationPopupComponent.notifications[0]).to.be.equal(notification);\n tick(30000);\n expect(notificationPopupComponent.notifications.length).to.be.equal(1);\n expect(notificationPopupComponent.notifications[0]).to.be.equal(otherNotification);\n }));\n\n it('should not add received notification if user is already on quiz page', () => {\n sinon.replace(router, 'isActive', sinon.fake.returns(true));\n replaceSubscribeToNotificationUpdates();\n notificationPopupComponent.ngOnInit();\n expect(notificationPopupComponent.notifications).to.be.empty;\n });\n });\n});\n" }, { "alpha_fraction": 0.5890411138534546, "alphanum_fraction": 0.5942371487617493, "avg_line_length": 37.490909576416016, "blob_id": "1c2ebfa6af95cbe68ee8ded3d3a79c3a7b3036a8", "content_id": "6a62ab7f3bd564ac93c36c0fb8bc3d8a0b82b861", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2117, "license_type": "permissive", "max_line_length": 122, "num_lines": 55, "path": "/src/main/webapp/app/shared/markdown-editor/commands/unorderedListCommand.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Command } from './command';\n\nexport class UnorderedListCommand extends Command {\n buttonIcon = 'list-ul';\n buttonTranslationString = 'artemisApp.multipleChoiceQuestion.editor.unorderedList';\n\n /**\n * @function execute\n * @desc Use the markdown language for creating an unordered list\n */\n execute(): void {\n const selectedText = this.getSelectedText();\n this.splitText(selectedText);\n }\n\n /**\n * @function splitText\n * @desc 1. Split the text at the line break into an array\n * 2. Call for each textline the replaceText method\n * @param {string} the selected text by the cursor\n */\n splitText(selectedText: string): void {\n const parseArray = selectedText.split('\\n');\n parseArray.forEach((element) => this.replaceText(element));\n }\n\n /**\n * @function replaceText\n * @desc 1. Check if the selected text includes (-)\n * 2. If included reduce the selected text by 2 (-, whitespace) and replace the selected text by textToAdd\n * 3. If not included combine (-) with the selected text and insert into the editor\n * 4. An unordered list in markdown appears\n * @param element {string} extracted textLine from the {array} selectedText\n */\n replaceText(element: string): void {\n /** case 1: text is formed in as an unordered list and the list should be unformed by deleting (-) + whitespace */\n if (element.includes('-')) {\n const textToAdd = element.slice(2);\n const text = `${textToAdd}\\n`;\n this.insertText(text);\n /** case 2: start a new unordered list from scratch */\n } else if (element === '') {\n const range = this.getRange();\n element = `- ${element}`;\n this.replace(range, element);\n this.focus();\n } else {\n /** case 3: formate existing text into an unformed list */\n const range = this.getRange();\n element = `- ${element}\\n`;\n this.replace(range, element);\n this.focus();\n }\n }\n}\n" }, { "alpha_fraction": 0.5399497747421265, "alphanum_fraction": 0.5467336773872375, "avg_line_length": 38.405941009521484, "blob_id": "8d546203f65c9ff6fb63754f62591e4d368a53de", "content_id": "8e48fa38b8d462334411bcc49435e2b8bbc75a9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3980, "license_type": "permissive", "max_line_length": 109, "num_lines": 101, "path": "/src/test/javascript/spec/component/admin/user-management.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, fakeAsync, tick, inject } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisAdminModule } from 'app/admin/admin.module';\nimport { UserManagementComponent } from 'app/admin/user-management/user-management.component';\nimport { UserService } from 'app/core/user/user.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { User } from 'app/core/user/user.model';\nimport { of } from 'rxjs';\nimport { RouterTestingModule } from '@angular/router/testing';\n\ndescribe('UserManagementComponent', () => {\n let comp: UserManagementComponent;\n let fixture: ComponentFixture<UserManagementComponent>;\n let service: UserService;\n\n const route = ({\n params: of({ courseId: 123, sort: 'id,desc' }),\n children: [],\n } as any) as ActivatedRoute;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisAdminModule, RouterTestingModule],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: route,\n },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(UserManagementComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(UserService);\n });\n });\n\n // The admin module is lazy loaded - we therefore need a dummy test to load\n // the module and verify that there are no dependency related issues.\n it('should render a component from the admin module', () => {\n expect(comp).toBeDefined();\n });\n\n it('should parse the user search result into the correct component state', inject(\n [],\n fakeAsync(() => {\n const headers = new HttpHeaders().append('link', 'link;link').append('X-Total-Count', '1');\n spyOn(service, 'query').and.returnValue(\n of(\n new HttpResponse({\n body: [new User(1)],\n headers,\n }),\n ),\n );\n\n comp.loadAll();\n // 1 sec of pause, because of the debounce time\n tick(1000);\n\n expect(comp.users && comp.users[0].id).toEqual(1);\n expect(comp.totalItems).toEqual(1);\n expect(comp.loadingSearchResult).toEqual(false);\n }),\n ));\n\n describe('setActive', () => {\n it('Should update user and call load all', inject(\n [],\n fakeAsync(() => {\n // GIVEN\n const headers = new HttpHeaders().append('link', 'link;link');\n const user = new User(123);\n spyOn(service, 'query').and.returnValue(\n of(\n new HttpResponse({\n body: [user],\n headers,\n }),\n ),\n );\n spyOn(service, 'update').and.returnValue(of(new HttpResponse({ status: 200 })));\n\n // WHEN\n comp.setActive(user, true);\n tick(1000); // simulate async\n\n // THEN\n expect(service.update).toHaveBeenCalledWith({ ...user, activated: true });\n expect(service.query).toHaveBeenCalled();\n expect(comp.users && comp.users[0]).toEqual(expect.objectContaining({ id: 123 }));\n }),\n ));\n });\n});\n" }, { "alpha_fraction": 0.7582612633705139, "alphanum_fraction": 0.7638057470321655, "avg_line_length": 44.09000015258789, "blob_id": "5bf82ce9174fef43db2593b536a82ca77f63f1ff", "content_id": "e406b66504fe1927b810336746b705caff3a0129", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4509, "license_type": "permissive", "max_line_length": 180, "num_lines": 100, "path": "/src/test/java/de/tum/in/www1/artemis/programmingexercise/simulation/ProgrammingExerciseSubmissionAndResultSimulationIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.programmingexercise.simulation;\n\nimport static de.tum.in.www1.artemis.web.rest.ProgrammingSubmissionResultSimulationResource.Endpoints.*;\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.List;\nimport java.util.stream.Collectors;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringDevelopmentTest;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.ProgrammingSubmission;\nimport de.tum.in.www1.artemis.domain.Result;\nimport de.tum.in.www1.artemis.domain.enumeration.SubmissionType;\nimport de.tum.in.www1.artemis.domain.participation.Participation;\nimport de.tum.in.www1.artemis.repository.*;\n\npublic class ProgrammingExerciseSubmissionAndResultSimulationIntegrationTest extends AbstractSpringDevelopmentTest {\n\n @Autowired\n ProgrammingSubmissionRepository submissionRepository;\n\n @Autowired\n ParticipationRepository participationRepository;\n\n @Autowired\n ProgrammingExerciseRepository programmingExerciseRepository;\n\n @Autowired\n ResultRepository resultRepository;\n\n private List<Long> participationIds;\n\n private Long exerciseId;\n\n private ProgrammingExercise exercise;\n\n @BeforeEach\n void setUp() {\n database.addUsers(3, 2, 2);\n database.addCourseWithOneProgrammingExerciseAndTestCases();\n\n exercise = programmingExerciseRepository.findAllWithEagerParticipationsAndLegalSubmissions().get(0);\n database.addStudentParticipationForProgrammingExercise(exercise, \"student1\");\n database.addStudentParticipationForProgrammingExercise(exercise, \"student2\");\n\n exerciseId = exercise.getId();\n exercise = programmingExerciseRepository.findAllWithEagerParticipationsAndLegalSubmissions().get(0);\n participationIds = exercise.getStudentParticipations().stream().map(Participation::getId).collect(Collectors.toList());\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n /**\n * This tests if the submission is created for programming exercises without local setup\n */\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n void shouldCreateSubmissionWithoutConnectionToVCSandCI() throws Exception {\n assertThat(submissionRepository.findAll()).hasSize(0);\n final var returnedSubmission = request.postWithResponseBody(ROOT + SUBMISSIONS_SIMULATION.replace(\"{exerciseId}\", String.valueOf(exerciseId)), null,\n ProgrammingSubmission.class, HttpStatus.CREATED);\n assertThat(submissionRepository.findAll()).hasSize(1);\n ProgrammingSubmission submission = submissionRepository.findAll().get(0);\n assertThat(returnedSubmission).isEqualTo(submission);\n assertThat(participationRepository.findById(submission.getParticipation().getId()));\n assertThat(participationIds.contains(submission.getParticipation().getId()));\n assertThat(submission.getType()).isEqualTo(SubmissionType.MANUAL);\n assertThat(submission.isSubmitted()).isTrue();\n }\n\n /**\n * This tests if the result is created for programming exercises without local setup\n */\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n void shouldCreateResultWithoutConnectionToVCSandCI() throws Exception {\n final var returnedSubmission = request.postWithResponseBody(ROOT + SUBMISSIONS_SIMULATION.replace(\"{exerciseId}\", String.valueOf(exerciseId)), null,\n ProgrammingSubmission.class, HttpStatus.CREATED);\n assertThat(resultRepository.findAll()).hasSize(0);\n Result returnedResult = request.postWithResponseBody(ROOT + RESULTS_SIMULATION.replace(\"{exerciseId}\", String.valueOf(exerciseId)), null, Result.class, HttpStatus.CREATED);\n ProgrammingSubmission submission = submissionRepository.findAll().get(0);\n assertThat(returnedSubmission).isEqualTo(submission);\n assertThat(resultRepository.findAll()).hasSize(1);\n Result result = resultRepository.findAll().get(0);\n assertThat(returnedResult).isEqualTo(result);\n assertThat(result.getParticipation().getId()).isEqualTo(submission.getParticipation().getId());\n }\n}\n" }, { "alpha_fraction": 0.6871333718299866, "alphanum_fraction": 0.6901642680168152, "avg_line_length": 58.12138748168945, "blob_id": "924c1bacdca1d0ebe1c278d632ecdf3d158c17b8", "content_id": "88f077e6d7e67e6e17e00ce520b792c220eed9a2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10228, "license_type": "permissive", "max_line_length": 120, "num_lines": 173, "path": "/src/test/javascript/spec/component/shared/notification/system-notification.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { of } from 'rxjs';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { SystemNotificationComponent } from 'app/shared/notification/system-notification/system-notification.component';\nimport { SystemNotificationService } from 'app/shared/notification/system-notification/system-notification.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { SystemNotification, SystemNotificationType } from 'app/entities/system-notification.model';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('System Notification Component', () => {\n let systemNotificationComponent: SystemNotificationComponent;\n let systemNotificationComponentFixture: ComponentFixture<SystemNotificationComponent>;\n let systemNotificationService: SystemNotificationService;\n let jhiWebsocketService: JhiWebsocketService;\n\n const createActiveNotification = (type: SystemNotificationType) => {\n return {\n id: 1,\n title: 'Maintenance',\n text: 'Artemis will be unavailable',\n type,\n notificationDate: moment().subtract(1, 'days'),\n expireDate: moment().add(1, 'days'),\n } as SystemNotification;\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule],\n declarations: [SystemNotificationComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: AccountService, useClass: MockAccountService },\n { provide: jhiWebsocketService, useClass: JhiWebsocketService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n systemNotificationComponentFixture = TestBed.createComponent(SystemNotificationComponent);\n systemNotificationComponent = systemNotificationComponentFixture.componentInstance;\n systemNotificationService = TestBed.inject(SystemNotificationService);\n jhiWebsocketService = TestBed.inject(JhiWebsocketService);\n });\n });\n\n describe('Load active notification', () => {\n it('should get active system notification with system notification type warning', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.WARNING);\n const fake = sinon.fake.returns(of(notification));\n sinon.replace(systemNotificationService, 'getActiveNotification', fake);\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(systemNotificationService.getActiveNotification).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(notification);\n expect(systemNotificationComponent.alertClass).to.equal('alert-warning');\n expect(systemNotificationComponent.alertIcon).to.equal('exclamation-triangle');\n }));\n\n it('should get active system notification with system notification type info', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.INFO);\n const fake = sinon.fake.returns(of(notification));\n sinon.replace(systemNotificationService, 'getActiveNotification', fake);\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(systemNotificationService.getActiveNotification).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(notification);\n expect(systemNotificationComponent.alertClass).to.equal('alert-info');\n expect(systemNotificationComponent.alertIcon).to.equal('info-circle');\n }));\n });\n\n describe('Websocket', () => {\n beforeEach(() => {\n const fake = sinon.fake.yields('event');\n sinon.replace(jhiWebsocketService, 'bind', fake);\n });\n\n it('should subscribe to socket messages on init', fakeAsync(() => {\n sinon.spy(jhiWebsocketService, 'subscribe');\n sinon.spy(jhiWebsocketService, 'receive');\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.bind).to.have.been.calledOnce;\n expect(systemNotificationComponent.websocketChannel).to.equal('/topic/system-notification');\n expect(jhiWebsocketService.subscribe).to.have.been.calledOnce;\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n }));\n\n it('should delete notification when \"deleted\" is received via websocket', fakeAsync(() => {\n sinon.replace(jhiWebsocketService, 'receive', sinon.fake.returns(of('deleted')));\n sinon.replace(systemNotificationService, 'getActiveNotification', sinon.fake.returns(of(null)));\n systemNotificationComponent.notification = createActiveNotification(SystemNotificationType.WARNING);\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(undefined);\n expect(systemNotificationService.getActiveNotification).to.have.been.calledTwice;\n }));\n\n it('should add notification when active notification is received via websocket', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.WARNING);\n sinon.spy(jhiWebsocketService, 'subscribe');\n sinon.replace(jhiWebsocketService, 'receive', sinon.fake.returns(of(notification)));\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.subscribe).to.have.been.calledOnce;\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(notification);\n expect(systemNotificationComponent.alertClass).to.equal('alert-warning');\n expect(systemNotificationComponent.alertIcon).to.equal('exclamation-triangle');\n }));\n\n it('should not add notification when non-active notification is received via websocket', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.WARNING);\n notification.expireDate = moment().subtract(5, 'minutes');\n sinon.spy(jhiWebsocketService, 'subscribe');\n sinon.replace(jhiWebsocketService, 'receive', sinon.fake.returns(of(notification)));\n sinon.replace(systemNotificationService, 'getActiveNotification', sinon.fake.returns(of()));\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.subscribe).to.have.been.calledOnce;\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n expect(systemNotificationService.getActiveNotification).to.have.been.calledTwice;\n expect(systemNotificationComponent.notification).to.equal(undefined);\n expect(systemNotificationComponent.alertClass).to.equal(undefined);\n expect(systemNotificationComponent.alertIcon).to.equal(undefined);\n }));\n\n it('should update notification when same notification is received via websocket', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.WARNING);\n const changedNotification = createActiveNotification(SystemNotificationType.INFO);\n sinon.spy(jhiWebsocketService, 'subscribe');\n sinon.replace(jhiWebsocketService, 'receive', sinon.fake.returns(of(changedNotification)));\n sinon.replace(systemNotificationService, 'getActiveNotification', sinon.fake.returns(of(notification)));\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.subscribe).to.have.been.calledOnce;\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n expect(systemNotificationService.getActiveNotification).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(changedNotification);\n }));\n\n it('should update notification when new active notification is received via websocket', fakeAsync(() => {\n const notification = createActiveNotification(SystemNotificationType.WARNING);\n const newNotification = createActiveNotification(SystemNotificationType.INFO);\n newNotification.id = 2;\n newNotification.notificationDate = moment().subtract(2, 'days');\n newNotification.expireDate = moment().add(2, 'days');\n sinon.spy(jhiWebsocketService, 'subscribe');\n sinon.replace(jhiWebsocketService, 'receive', sinon.fake.returns(of(newNotification)));\n sinon.replace(systemNotificationService, 'getActiveNotification', sinon.fake.returns(of(notification)));\n systemNotificationComponent.ngOnInit();\n tick(500);\n expect(jhiWebsocketService.subscribe).to.have.been.calledOnce;\n expect(jhiWebsocketService.receive).to.have.been.calledOnce;\n expect(systemNotificationService.getActiveNotification).to.have.been.calledOnce;\n expect(systemNotificationComponent.notification).to.equal(newNotification);\n }));\n });\n});\n" }, { "alpha_fraction": 0.6178403496742249, "alphanum_fraction": 0.6413145661354065, "avg_line_length": 24.975608825683594, "blob_id": "b02c6599d889dad31f1be0f424599d7554b7e51e", "content_id": "3fdf984a145dd90e28ce237673644f5bed0b15dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1065, "license_type": "permissive", "max_line_length": 48, "num_lines": 41, "path": "/src/main/webapp/app/entities/statistics.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export enum SpanType {\n DAY = 'DAY',\n WEEK = 'WEEK',\n MONTH = 'MONTH',\n QUARTER = 'QUARTER',\n YEAR = 'YEAR',\n}\n\nexport enum Graphs {\n // User statistics\n SUBMISSIONS = 'SUBMISSIONS',\n ACTIVE_USERS = 'ACTIVE_USERS',\n LOGGED_IN_USERS = 'LOGGED_IN_USERS',\n RELEASED_EXERCISES = 'RELEASED_EXERCISES',\n EXERCISES_DUE = 'EXERCISES_DUE',\n CONDUCTED_EXAMS = 'CONDUCTED_EXAMS',\n EXAM_PARTICIPATIONS = 'EXAM_PARTICIPATIONS',\n EXAM_REGISTRATIONS = 'EXAM_REGISTRATIONS',\n ACTIVE_TUTORS = 'ACTIVE_TUTORS',\n CREATED_RESULTS = 'CREATED_RESULTS',\n CREATED_FEEDBACKS = 'CREATED_FEEDBACKS',\n\n // Course overview\n ACTIVE_STUDENTS = 'ACTIVE_STUDENTS',\n\n // Course Statistics\n AVERAGE_SCORE = 'AVERAGE_SCORE',\n QUESTIONS_ASKED = 'QUESTIONS_ASKED',\n QUESTIONS_ANSWERED = 'QUESTIONS_ANSWERED',\n}\n\nexport enum StatisticsView {\n ARTEMIS = 'ARTEMIS',\n COURSE = 'COURSE',\n}\n\nexport enum GraphColors {\n DARK_BLUE = 'rgba(53,61,71,1)',\n BLUE = 'rgba(93,138,201,1)',\n BLUE_TRANSPARENT = 'rgba(93,138,201,0)',\n}\n" }, { "alpha_fraction": 0.7132353186607361, "alphanum_fraction": 0.7132353186607361, "avg_line_length": 39.79999923706055, "blob_id": "d8804c6029c367e763eafa8a84348d05134a68a7", "content_id": "9af95fb054db943a35f7aa1276b8695be9a4fea5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2040, "license_type": "permissive", "max_line_length": 121, "num_lines": 50, "path": "/src/main/webapp/app/entities/quiz/quiz-exercise.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { QuizPointStatistic } from 'app/entities/quiz/quiz-point-statistic.model';\nimport { QuizQuestion } from 'app/entities/quiz/quiz-question.model';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\n\nexport enum QuizStatus {\n CLOSED,\n OPEN_FOR_PRACTICE,\n ACTIVE,\n VISIBLE,\n HIDDEN,\n}\n\nexport class QuizExercise extends Exercise {\n public id?: number;\n public remainingTime?: number; // (computed by server)\n public timeUntilPlannedStart?: number; // (computed by server)\n public visibleToStudents?: boolean; // (computed by server)\n public randomizeQuestionOrder?: boolean;\n public isVisibleBeforeStart?: boolean;\n public isOpenForPractice?: boolean;\n public isPlannedToStart?: boolean;\n public duration?: number;\n public quizPointStatistic?: QuizPointStatistic;\n public quizQuestions?: QuizQuestion[];\n public status?: QuizStatus;\n\n // helper attributes\n public adjustedDueDate?: Moment;\n public adjustedReleaseDate?: Moment;\n public ended?: boolean;\n public started?: boolean;\n\n public isActiveQuiz?: boolean;\n public isPracticeModeAvailable?: boolean;\n\n constructor(course: Course | undefined, exerciseGroup: ExerciseGroup | undefined) {\n super(ExerciseType.QUIZ);\n this.course = course;\n this.exerciseGroup = exerciseGroup;\n this.randomizeQuestionOrder = true; // default value (set by server)\n this.isVisibleBeforeStart = false; // default value (set by server)\n this.isOpenForPractice = false; // default value (set by server)\n this.isPlannedToStart = false; // default value (set by server)\n this.isActiveQuiz = false; // default value (set by client, might need to be computed before evaluated)\n this.isPracticeModeAvailable = true; // default value (set by client, might need to be computed before evaluated)\n }\n}\n" }, { "alpha_fraction": 0.6481686234474182, "alphanum_fraction": 0.6490184664726257, "avg_line_length": 44.08428955078125, "blob_id": "2db702f65f0f1df94f0238e4a74a1f1b4498131c", "content_id": "6a4de1077336f089ed645cd89774ef9cf1b12bff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11767, "license_type": "permissive", "max_line_length": 158, "num_lines": 261, "path": "/src/main/webapp/app/exercises/programming/manage/programming-exercise-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { Observable, of, Subject } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\nimport { ProgrammingExercise, ProgrammingLanguage } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { Result } from 'app/entities/result.model';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ProgrammingExerciseParticipationType } from 'app/entities/programming-exercise-participation.model';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { ConfirmAutofocusModalComponent } from 'app/shared/components/confirm-autofocus-button.component';\nimport { TranslateService } from '@ngx-translate/core';\n\n@Component({\n selector: 'jhi-programming-exercise-detail',\n templateUrl: './programming-exercise-detail.component.html',\n styleUrls: ['./programming-exercise-detail.component.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class ProgrammingExerciseDetailComponent implements OnInit, OnDestroy {\n readonly ActionType = ActionType;\n readonly ProgrammingExerciseParticipationType = ProgrammingExerciseParticipationType;\n readonly FeatureToggle = FeatureToggle;\n readonly ProgrammingLanguage = ProgrammingLanguage;\n readonly PROGRAMMING = ExerciseType.PROGRAMMING;\n\n programmingExercise: ProgrammingExercise;\n isExamExercise: boolean;\n\n loadingTemplateParticipationResults = true;\n loadingSolutionParticipationResults = true;\n lockingOrUnlockingRepositories = false;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private accountService: AccountService,\n private programmingExerciseService: ProgrammingExerciseService,\n private exerciseService: ExerciseService,\n private jhiAlertService: JhiAlertService,\n private programmingExerciseParticipationService: ProgrammingExerciseParticipationService,\n private eventManager: JhiEventManager,\n private modalService: NgbModal,\n private translateService: TranslateService,\n ) {}\n\n ngOnInit() {\n this.activatedRoute.data.subscribe(({ programmingExercise }) => {\n this.programmingExercise = programmingExercise;\n this.isExamExercise = !!this.programmingExercise.exerciseGroup;\n\n this.programmingExercise.isAtLeastTutor = this.accountService.isAtLeastTutorForExercise(this.programmingExercise);\n this.programmingExercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorForExercise(this.programmingExercise);\n\n if (this.programmingExercise.categories) {\n this.programmingExercise.categories = this.programmingExercise.categories.map((category) => JSON.parse(category));\n }\n\n if (this.programmingExercise.templateParticipation) {\n this.programmingExercise.templateParticipation.programmingExercise = this.programmingExercise;\n this.loadLatestResultWithFeedbackAndSubmission(this.programmingExercise.templateParticipation.id!).subscribe((results) => {\n this.programmingExercise.templateParticipation!.results = results;\n this.loadingTemplateParticipationResults = false;\n });\n }\n\n if (this.programmingExercise.solutionParticipation) {\n this.programmingExercise.solutionParticipation.programmingExercise = this.programmingExercise;\n\n this.loadLatestResultWithFeedbackAndSubmission(this.programmingExercise.solutionParticipation.id!).subscribe((results) => {\n this.programmingExercise.solutionParticipation!.results = results;\n this.loadingSolutionParticipationResults = false;\n });\n }\n });\n }\n\n ngOnDestroy(): void {\n this.dialogErrorSource.unsubscribe();\n }\n\n /**\n * Load the latest result for the given participation. Will return [result] if there is a result, [] if not.\n * @param participationId of the given participation.\n * @return an empty array if there is no result or an array with the single latest result.\n */\n private loadLatestResultWithFeedbackAndSubmission(participationId: number): Observable<Result[]> {\n return this.programmingExerciseParticipationService.getLatestResultWithFeedback(participationId, true).pipe(\n catchError(() => of(null)),\n map((result: Result | null) => {\n return result ? [result] : [];\n }),\n );\n }\n\n /**\n * Returns the route for editing the exercise. Exam and course exercises have different routes.\n */\n getEditRoute() {\n if (this.isExamExercise) {\n return [\n '/course-management',\n this.programmingExercise.exerciseGroup?.exam?.course?.id,\n 'exams',\n this.programmingExercise.exerciseGroup?.exam?.id,\n 'exercise-groups',\n this.programmingExercise.exerciseGroup?.id,\n 'programming-exercises',\n this.programmingExercise.id,\n 'edit',\n ];\n } else {\n return ['/course-management', this.programmingExercise.course?.id, 'programming-exercises', this.programmingExercise.id, 'edit'];\n }\n }\n\n combineTemplateCommits() {\n this.programmingExerciseService.combineTemplateRepositoryCommits(this.programmingExercise.id!).subscribe(\n () => {\n this.jhiAlertService.success('artemisApp.programmingExercise.combineTemplateCommitsSuccess');\n },\n () => {\n this.jhiAlertService.error('artemisApp.programmingExercise.combineTemplateCommitsError');\n },\n );\n }\n\n generateStructureOracle() {\n this.programmingExerciseService.generateStructureOracle(this.programmingExercise.id!).subscribe(\n (res) => {\n const jhiAlert = this.jhiAlertService.success(res);\n jhiAlert.msg = res;\n },\n (error) => {\n const errorMessage = error.headers.get('X-artemisApp-alert');\n // TODO: this is a workaround to avoid translation not found issues. Provide proper translations\n const jhiAlert = this.jhiAlertService.error(errorMessage);\n jhiAlert.msg = errorMessage;\n },\n );\n }\n\n /**\n * Cleans up programming exercise\n * @param $event contains additional checks from the dialog\n */\n cleanupProgrammingExercise($event: { [key: string]: boolean }) {\n return this.exerciseService.cleanup(this.programmingExercise.id!, $event.deleteRepositories).subscribe(\n () => {\n if ($event.deleteRepositories) {\n this.jhiAlertService.success('artemisApp.programmingExercise.cleanup.successMessageWithRepositories');\n } else {\n this.jhiAlertService.success('artemisApp.programmingExercise.cleanup.successMessage');\n }\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n public deleteProgrammingExercise($event: { [key: string]: boolean }) {\n this.programmingExerciseService.delete(this.programmingExercise.id!, $event.deleteStudentReposBuildPlans, $event.deleteBaseReposBuildPlans).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'programmingExerciseListModification',\n content: 'Deleted a programming exercise',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n /**\n * Unlock all repositories immediately. Asks for confirmation.\n */\n handleUnlockAllRepositories() {\n const modalRef = this.modalService.open(ConfirmAutofocusModalComponent, { keyboard: true, size: 'lg' });\n modalRef.componentInstance.title = 'artemisApp.programmingExercise.unlockAllRepositories';\n modalRef.componentInstance.text = this.translateService.instant('artemisApp.programmingExercise.unlockAllRepositoriesModalText');\n modalRef.result.then(() => {\n this.unlockAllRepositories();\n });\n }\n\n /**\n * Unlocks all repositories that belong to the exercise\n */\n private unlockAllRepositories() {\n this.lockingOrUnlockingRepositories = true;\n this.programmingExerciseService.unlockAllRepositories(this.programmingExercise.id!).subscribe(\n (res) => {\n this.jhiAlertService.addAlert(\n {\n type: 'success',\n msg: 'artemisApp.programmingExercise.unlockAllRepositoriesSuccess',\n params: { number: res?.body },\n timeout: 10000,\n },\n [],\n );\n this.lockingOrUnlockingRepositories = false;\n },\n (err: HttpErrorResponse) => {\n this.lockingOrUnlockingRepositories = false;\n this.onError(err);\n },\n );\n }\n\n /**\n * Lock all repositories immediately. Asks for confirmation.\n */\n handleLockAllRepositories() {\n const modalRef = this.modalService.open(ConfirmAutofocusModalComponent, { keyboard: true, size: 'lg' });\n modalRef.componentInstance.title = 'artemisApp.programmingExercise.lockAllRepositories';\n modalRef.componentInstance.text = this.translateService.instant('artemisApp.programmingExercise.lockAllRepositoriesModalText');\n modalRef.result.then(() => {\n this.lockAllRepositories();\n });\n }\n\n /**\n * Locks all repositories that belong to the exercise\n */\n private lockAllRepositories() {\n this.lockingOrUnlockingRepositories = true;\n this.programmingExerciseService.lockAllRepositories(this.programmingExercise.id!).subscribe(\n (res) => {\n this.jhiAlertService.addAlert(\n {\n type: 'success',\n msg: 'artemisApp.programmingExercise.lockAllRepositoriesSuccess',\n params: { number: res?.body },\n timeout: 10000,\n },\n [],\n );\n this.lockingOrUnlockingRepositories = false;\n },\n (err: HttpErrorResponse) => {\n this.lockingOrUnlockingRepositories = false;\n this.onError(err);\n },\n );\n }\n\n private onError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n }\n}\n" }, { "alpha_fraction": 0.6687622666358948, "alphanum_fraction": 0.670333981513977, "avg_line_length": 34.34722137451172, "blob_id": "35b049bc614cd0dc2f633c39f891386b73d075ee", "content_id": "4dc98cc2ce9aa2d32ac3630fbe051e19847c98da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5090, "license_type": "permissive", "max_line_length": 139, "num_lines": 144, "path": "/src/main/webapp/app/exercises/text/assess/textblock-feedback-editor/textblock-feedback-editor.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, ElementRef, EventEmitter, HostBinding, Input, Output, ViewChild } from '@angular/core';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { ConfirmIconComponent } from 'app/shared/confirm-icon/confirm-icon.component';\nimport { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service';\nimport { FeedbackConflictType } from 'app/entities/feedback-conflict';\n\n@Component({\n selector: 'jhi-textblock-feedback-editor',\n templateUrl: './textblock-feedback-editor.component.html',\n styleUrls: ['./textblock-feedback-editor.component.scss'],\n})\nexport class TextblockFeedbackEditorComponent implements AfterViewInit {\n readonly FeedbackType = FeedbackType;\n\n @Input() textBlock: TextBlock;\n @Input() feedback: Feedback = new Feedback();\n @Output() feedbackChange = new EventEmitter<Feedback>();\n @Output() close = new EventEmitter<void>();\n @Output() onFocus = new EventEmitter<void>();\n @Output() onConflictsClicked = new EventEmitter<number>();\n @ViewChild('detailText') textareaRef: ElementRef;\n @ViewChild(ConfirmIconComponent) confirmIconComponent: ConfirmIconComponent;\n @Input() disableEditScore = false;\n @Input() readOnly: boolean;\n @Input() isConflictingFeedback: boolean;\n @Input() conflictMode: boolean;\n @Input() conflictType?: FeedbackConflictType;\n @Input() isLeftConflictingFeedback: boolean;\n @Input() isSelectedConflict: boolean;\n private textareaElement: HTMLTextAreaElement;\n\n @HostBinding('class.alert') @HostBinding('class.alert-dismissible') readonly classes = true;\n\n @HostBinding('class.alert-secondary') get neutralFeedbackClass(): boolean {\n return !this.conflictMode ? this.feedback.credits === 0 : !this.isConflictingFeedback;\n }\n\n @HostBinding('class.alert-success') get positiveFeedbackClass(): boolean {\n return this.feedback.credits! > 0 && !this.conflictMode;\n }\n\n @HostBinding('class.alert-danger') get negativeFeedbackClass(): boolean {\n return this.feedback.credits! < 0 && !this.conflictMode;\n }\n\n @HostBinding('class.alert-warning') get conflictingFeedbackClass(): boolean {\n return this.isConflictingFeedback && this.conflictMode && !this.isSelectedConflict;\n }\n\n @HostBinding('class.alert-info') get selectedConflictingFeedbackClass(): boolean {\n return this.isSelectedConflict;\n }\n\n constructor(public structuredGradingCriterionService: StructuredGradingCriterionService) {}\n\n /**\n * Life cycle hook to indicate component initialization is done\n */\n ngAfterViewInit(): void {\n this.textareaElement = this.textareaRef.nativeElement as HTMLTextAreaElement;\n setTimeout(() => this.textareaAutogrow());\n if (this.feedback.gradingInstruction && this.feedback.gradingInstruction.usageCount !== 0) {\n this.disableEditScore = true;\n } else {\n this.disableEditScore = false;\n }\n }\n /**\n * Increase size of text area automatically\n */\n textareaAutogrow(): void {\n this.textareaElement.style.height = '0px';\n this.textareaElement.style.height = `${this.textareaElement.scrollHeight}px`;\n }\n\n get canDismiss(): boolean {\n return this.feedback.credits === 0 && (this.feedback.detailText || '').length === 0;\n }\n\n get isConflictingFeedbackEditable(): boolean {\n return this.conflictMode && this.isLeftConflictingFeedback && this.isConflictingFeedback;\n }\n\n /**\n * Set focus to feedback editor\n */\n inFocus(): void {\n this.onFocus.emit();\n }\n\n /**\n * Dismiss changes in feedback editor\n */\n dismiss(): void {\n this.close.emit();\n }\n\n /**\n * Hook to indicate pressed Escape key\n */\n escKeyup(): void {\n if (this.canDismiss) {\n this.dismiss();\n } else {\n this.confirmIconComponent.toggle();\n }\n }\n\n /**\n * Set focus to the text area\n */\n focus(): void {\n if (this.conflictMode && !this.isLeftConflictingFeedback && this.isConflictingFeedback) {\n return;\n }\n this.textareaElement.focus();\n }\n\n /**\n * Hook to indicate a score click\n */\n onScoreClick(event: MouseEvent): void {\n event.preventDefault();\n }\n\n /**\n * Hook to indicate changes in the feedback editor\n */\n didChange(): void {\n Feedback.updateFeedbackTypeOnChange(this.feedback);\n this.feedbackChange.emit(this.feedback);\n }\n\n connectFeedbackWithInstruction(event: Event) {\n this.structuredGradingCriterionService.updateFeedbackWithStructuredGradingInstructionEvent(this.feedback, event);\n if (this.feedback.gradingInstruction && this.feedback.gradingInstruction.usageCount !== 0) {\n this.disableEditScore = true;\n } else {\n this.disableEditScore = false;\n }\n this.didChange();\n }\n}\n" }, { "alpha_fraction": 0.6684829592704773, "alphanum_fraction": 0.6688606142997742, "avg_line_length": 42.51173782348633, "blob_id": "71f56b57e1127f765543689527e09a7271ce9d16", "content_id": "74d17ae7d37216b43ecdaf0afd753c551f004b52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 18536, "license_type": "permissive", "max_line_length": 175, "num_lines": 426, "path": "/src/main/webapp/app/exercises/text/assess/text-submission-assessment.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Location } from '@angular/common';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, NavigationExtras, Router } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport * as moment from 'moment';\nimport { now } from 'moment';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { Result } from 'app/entities/result.model';\nimport { Complaint } from 'app/entities/complaint.model';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { notUndefined } from 'app/shared/util/global.utils';\nimport { TranslateService } from '@ngx-translate/core';\nimport { NEW_ASSESSMENT_PATH } from 'app/exercises/text/assess/text-submission-assessment.route';\nimport { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service';\nimport { assessmentNavigateBack } from 'app/exercises/shared/navigate-back.util';\nimport {\n getLatestSubmissionResult,\n getSubmissionResultByCorrectionRound,\n getSubmissionResultById,\n setLatestSubmissionResult,\n setSubmissionResultByCorrectionRound,\n} from 'app/entities/submission.model';\nimport { TextAssessmentBaseComponent } from 'app/exercises/text/assess/text-assessment-base.component';\nimport { getExerciseDashboardLink, getLinkToSubmissionAssessment } from 'app/utils/navigation.utils';\nimport { ExerciseType } from 'app/entities/exercise.model';\n\n@Component({\n selector: 'jhi-text-submission-assessment',\n templateUrl: './text-submission-assessment.component.html',\n styleUrls: ['./text-submission-assessment.component.scss'],\n})\nexport class TextSubmissionAssessmentComponent extends TextAssessmentBaseComponent implements OnInit {\n /*\n * The instance of this component is REUSED for multiple assessments if using the \"Assess Next\" button!\n * All properties must be initialized with a default value (or null) in the resetComponent() method.\n * For traceability: Keep order in resetComponent() consistent with declaration.\n */\n\n participation?: StudentParticipation;\n result?: Result;\n unreferencedFeedback: Feedback[];\n complaint?: Complaint;\n totalScore: number;\n isTestRun = false;\n isLoading: boolean;\n saveBusy: boolean;\n submitBusy: boolean;\n cancelBusy: boolean;\n nextSubmissionBusy: boolean;\n isAssessor: boolean;\n isAtLeastInstructor: boolean;\n assessmentsAreValid: boolean;\n noNewSubmissions: boolean;\n hasAssessmentDueDatePassed: boolean;\n correctionRound: number;\n resultId: number;\n loadingInitialSubmission = true;\n\n /*\n * Non-resetted properties:\n * These properties are not resetted on purpose, as they cannot change between assessments.\n */\n private cancelConfirmationText: string;\n\n // ExerciseId is updated from Route Subscription directly.\n exerciseId: number;\n courseId: number;\n examId = 0;\n exerciseGroupId: number;\n exerciseDashboardLink: string[];\n isExamMode = false;\n\n private get referencedFeedback(): Feedback[] {\n return this.textBlockRefs.map(({ feedback }) => feedback).filter(notUndefined) as Feedback[];\n }\n\n private get assessments(): Feedback[] {\n return [...this.referencedFeedback, ...this.unreferencedFeedback];\n }\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private location: Location,\n private route: ActivatedRoute,\n protected jhiAlertService: JhiAlertService,\n protected accountService: AccountService,\n protected assessmentsService: TextAssessmentService,\n private complaintService: ComplaintService,\n translateService: TranslateService,\n protected structuredGradingCriterionService: StructuredGradingCriterionService,\n ) {\n super(jhiAlertService, accountService, assessmentsService, structuredGradingCriterionService);\n translateService.get('artemisApp.textAssessment.confirmCancel').subscribe((text) => (this.cancelConfirmationText = text));\n this.correctionRound = 0;\n this.resetComponent();\n }\n\n /**\n * This method is called before the component is REUSED!\n * All properties MUST be set to a default value (e.g. null) to prevent data corruption by state leaking into following new assessments.\n */\n private resetComponent(): void {\n this.participation = undefined;\n this.submission = undefined;\n this.exercise = undefined;\n this.result = undefined;\n this.unreferencedFeedback = [];\n this.textBlockRefs = [];\n this.unusedTextBlockRefs = [];\n this.complaint = undefined;\n this.totalScore = 0;\n\n this.isLoading = true;\n this.saveBusy = false;\n this.submitBusy = false;\n this.cancelBusy = false;\n this.nextSubmissionBusy = false;\n this.isAssessor = false;\n this.isAtLeastInstructor = false;\n this.assessmentsAreValid = false;\n this.noNewSubmissions = false;\n }\n\n /**\n * Life cycle hook to indicate component creation is done\n */\n async ngOnInit(): Promise<void> {\n await super.ngOnInit();\n this.route.queryParamMap.subscribe((queryParams) => {\n this.isTestRun = queryParams.get('testRun') === 'true';\n this.correctionRound = Number(queryParams.get('correction-round'));\n });\n\n this.activatedRoute.paramMap.subscribe((paramMap) => {\n this.exerciseId = Number(paramMap.get('exerciseId'));\n this.resultId = Number(paramMap.get('resultId')) ?? 0;\n this.courseId = Number(paramMap.get('courseId'));\n if (paramMap.has('examId')) {\n this.examId = Number(paramMap.get('examId'));\n this.exerciseGroupId = Number(paramMap.get('exerciseGroupId'));\n this.isExamMode = true;\n }\n this.exerciseDashboardLink = getExerciseDashboardLink(this.courseId, this.exerciseId, this.examId, this.isTestRun);\n });\n this.activatedRoute.data.subscribe(({ studentParticipation }) => this.setPropertiesFromServerResponse(studentParticipation));\n }\n\n private setPropertiesFromServerResponse(studentParticipation: StudentParticipation) {\n this.resetComponent();\n this.loadingInitialSubmission = false;\n\n if (studentParticipation == undefined) {\n // Show \"No New Submission\" banner on .../submissions/new/assessment route\n this.noNewSubmissions = this.isNewAssessmentRoute;\n return;\n }\n\n this.participation = studentParticipation;\n this.submission = this.participation!.submissions![0] as TextSubmission;\n this.exercise = this.participation?.exercise as TextExercise;\n setLatestSubmissionResult(this.submission, getLatestSubmissionResult(this.submission));\n\n if (this.resultId > 0) {\n this.result = getSubmissionResultById(this.submission, this.resultId);\n this.correctionRound = this.submission.results?.findIndex((result) => result.id === this.resultId)!;\n } else {\n this.result = getSubmissionResultByCorrectionRound(this.submission, this.correctionRound);\n }\n\n this.hasAssessmentDueDatePassed = !!this.exercise!.assessmentDueDate && moment(this.exercise!.assessmentDueDate).isBefore(now());\n\n this.prepareTextBlocksAndFeedbacks();\n this.getComplaint();\n this.updateUrlIfNeeded();\n\n this.checkPermissions(this.result);\n this.totalScore = this.computeTotalScore(this.assessments);\n this.isLoading = false;\n\n // track feedback in athene\n this.assessmentsService.trackAssessment(this.submission, 'start');\n }\n\n private updateUrlIfNeeded() {\n if (this.isNewAssessmentRoute) {\n // Update the url with the new id, without reloading the page, to make the history consistent\n const newUrl = this.router\n .createUrlTree(getLinkToSubmissionAssessment(ExerciseType.TEXT, this.courseId, this.exerciseId, this.submission!.id!, this.examId, this.exerciseGroupId))\n .toString();\n this.location.go(newUrl);\n }\n }\n\n private get isNewAssessmentRoute(): boolean {\n return this.activatedRoute.routeConfig?.path === NEW_ASSESSMENT_PATH;\n }\n\n private checkPermissions(result?: Result): void {\n this.isAssessor = result?.assessor?.id === this.userId;\n // case distinction for exam mode\n this.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.course!);\n }\n\n /**\n * Save the assessment\n */\n save(): void {\n if (!this.assessmentsAreValid) {\n this.jhiAlertService.error('artemisApp.textAssessment.error.invalidAssessments');\n return;\n }\n\n // track feedback in athene\n this.assessmentsService.trackAssessment(this.submission, 'save');\n\n this.saveBusy = true;\n this.assessmentsService.save(this.exercise!.id!, this.result!.id!, this.assessments, this.textBlocksWithFeedback).subscribe(\n (response) => this.handleSaveOrSubmitSuccessWithAlert(response, 'artemisApp.textAssessment.saveSuccessful'),\n (error: HttpErrorResponse) => this.handleError(error),\n );\n }\n\n /**\n * Submit the assessment\n */\n submit(): void {\n if (!this.result?.id) {\n return; // We need to have saved the result before\n }\n\n if (!this.assessmentsAreValid) {\n this.jhiAlertService.error('artemisApp.textAssessment.error.invalidAssessments');\n return;\n }\n\n // track feedback in athene\n this.assessmentsService.trackAssessment(this.submission, 'submit');\n\n this.submitBusy = true;\n this.assessmentsService.submit(this.exercise!.id!, this.result!.id!, this.assessments, this.textBlocksWithFeedback).subscribe(\n (response) => this.handleSaveOrSubmitSuccessWithAlert(response, 'artemisApp.textAssessment.submitSuccessful'),\n (error: HttpErrorResponse) => this.handleError(error),\n );\n }\n\n protected handleSaveOrSubmitSuccessWithAlert(response: HttpResponse<Result>, translationKey: string): void {\n super.handleSaveOrSubmitSuccessWithAlert(response, translationKey);\n // eslint-disable-next-line chai-friendly/no-unused-expressions\n response.body!.feedbacks?.forEach((newFeedback) => {\n newFeedback.conflictingTextAssessments = this.result?.feedbacks?.find((feedback) => feedback.id === newFeedback.id)?.conflictingTextAssessments;\n });\n this.result = response.body!;\n setSubmissionResultByCorrectionRound(this.submission!, this.result, this.correctionRound);\n this.saveBusy = this.submitBusy = false;\n }\n\n /**\n * Cancel the assessment\n */\n cancel(): void {\n const confirmCancel = window.confirm(this.cancelConfirmationText);\n this.cancelBusy = true;\n if (confirmCancel && this.exercise && this.submission) {\n this.assessmentsService.cancelAssessment(this.exercise!.id!, this.submission!.id!).subscribe(() => this.navigateBack());\n }\n }\n\n /**\n * Go to next submission\n */\n async nextSubmission(): Promise<void> {\n const url = getLinkToSubmissionAssessment(ExerciseType.TEXT, this.courseId, this.exerciseId, 'new', this.examId, this.exerciseGroupId);\n this.nextSubmissionBusy = true;\n await this.router.navigate(url, { queryParams: { 'correction-round': this.correctionRound } });\n }\n\n /**\n * if the conflict badge is clicked, navigate to conflict page and add the submission to the extras.\n * @param feedbackId - selected feedback id with conflicts.\n */\n async navigateToConflictingSubmissions(feedbackId: number): Promise<void> {\n const tempSubmission = this.submission!;\n const latestSubmissionResult = getLatestSubmissionResult(tempSubmission)!;\n latestSubmissionResult.completionDate = undefined;\n latestSubmissionResult.submission = undefined;\n latestSubmissionResult.participation = undefined;\n\n const url = !this.isExamMode\n ? ['/course-management', this.courseId, 'text-exercises', this.exerciseId, 'submissions', this.submission!.id, 'text-feedback-conflict', feedbackId]\n : [\n '/course-management',\n this.courseId,\n 'exams',\n this.examId,\n 'exercise-groups',\n this.exerciseGroupId,\n 'text-exercises',\n this.exerciseId,\n 'submissions',\n this.submission!.id,\n 'text-feedback-conflict',\n feedbackId,\n ];\n const navigationExtras: NavigationExtras = { state: { submission: tempSubmission } };\n await this.router.navigate(url, navigationExtras);\n }\n\n /**\n * Sends the current (updated) assessment to the server to update the original assessment after a complaint was accepted.\n * The corresponding complaint response is sent along with the updated assessment to prevent additional requests.\n *\n * @param complaintResponse the response to the complaint that is sent to the server along with the assessment update\n */\n updateAssessmentAfterComplaint(complaintResponse: ComplaintResponse): void {\n this.validateFeedback();\n if (!this.assessmentsAreValid) {\n this.jhiAlertService.error('artemisApp.textAssessment.error.invalidAssessments');\n return;\n }\n\n this.assessmentsService.updateAssessmentAfterComplaint(this.assessments, this.textBlocksWithFeedback, complaintResponse, this.submission?.id!).subscribe(\n (response) => this.handleSaveOrSubmitSuccessWithAlert(response, 'artemisApp.textAssessment.updateAfterComplaintSuccessful'),\n (httpErrorResponse: HttpErrorResponse) => {\n this.jhiAlertService.clear();\n const error = httpErrorResponse.error;\n if (error && error.errorKey && error.errorKey === 'complaintLock') {\n this.jhiAlertService.error(error.message, error.params);\n } else {\n this.jhiAlertService.error('artemisApp.textAssessment.updateAfterComplaintFailed');\n }\n },\n );\n }\n\n navigateBack() {\n assessmentNavigateBack(this.location, this.router, this.exercise!, this.submission!, this.isTestRun);\n }\n\n /**\n * Validate the feedback of the assessment\n */\n validateFeedback(): void {\n const hasReferencedFeedback = Feedback.haveCredits(this.referencedFeedback);\n const hasUnreferencedFeedback = Feedback.haveCreditsAndComments(this.unreferencedFeedback);\n // When unreferenced feedback is set, it has to be valid (score + detailed text)\n this.assessmentsAreValid = (hasReferencedFeedback && this.unreferencedFeedback.length === 0) || hasUnreferencedFeedback;\n\n this.totalScore = this.computeTotalScore(this.assessments);\n }\n\n private prepareTextBlocksAndFeedbacks(): void {\n if (!this.result) {\n return;\n }\n const feedbacks = this.result.feedbacks || [];\n this.unreferencedFeedback = feedbacks.filter((feedbackElement) => feedbackElement.reference == undefined && feedbackElement.type === FeedbackType.MANUAL_UNREFERENCED);\n\n const matchBlocksWithFeedbacks = TextAssessmentService.matchBlocksWithFeedbacks(this.submission?.blocks || [], feedbacks);\n this.sortAndSetTextBlockRefs(matchBlocksWithFeedbacks, this.textBlockRefs, this.unusedTextBlockRefs, this.submission);\n }\n\n private getComplaint(): void {\n if (!this.result?.hasComplaint) {\n return;\n }\n\n this.isLoading = true;\n this.complaintService.findByResultId(this.result!.id!).subscribe(\n (res) => {\n if (!res.body) {\n return;\n }\n this.complaint = res.body;\n this.isLoading = false;\n },\n (err: HttpErrorResponse) => {\n this.handleError(err.error);\n },\n );\n }\n\n /**\n * Boolean which determines whether the user can override a result.\n * If no exercise is loaded, for example during loading between exercises, we return false.\n * Instructors can always override a result.\n * Tutors can override their own results within the assessment due date, if there is no complaint about their assessment.\n * They cannot override a result anymore, if there is a complaint. Another tutor must handle the complaint.\n */\n get canOverride(): boolean {\n if (this.exercise) {\n if (this.isAtLeastInstructor) {\n // Instructors can override any assessment at any time.\n return true;\n }\n if (this.complaint && this.isAssessor) {\n // If there is a complaint, the original assessor cannot override the result anymore.\n return false;\n }\n let isBeforeAssessmentDueDate = true;\n // Add check as the assessmentDueDate must not be set for exercises\n if (this.exercise.assessmentDueDate) {\n isBeforeAssessmentDueDate = moment().isBefore(this.exercise.assessmentDueDate!);\n }\n // tutors are allowed to override one of their assessments before the assessment due date.\n return this.isAssessor && isBeforeAssessmentDueDate;\n }\n return false;\n }\n\n get readOnly(): boolean {\n return !this.isAtLeastInstructor && !!this.complaint && this.isAssessor;\n }\n\n protected handleError(error: HttpErrorResponse): void {\n super.handleError(error);\n this.saveBusy = this.submitBusy = false;\n }\n}\n" }, { "alpha_fraction": 0.7965796589851379, "alphanum_fraction": 0.8001800179481506, "avg_line_length": 40.14814758300781, "blob_id": "49dbf9276d78739a1b3e46eac674b5e404965886", "content_id": "0522a52c34eeb364ad171c04a975eba44f3ea198", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1111, "license_type": "permissive", "max_line_length": 163, "num_lines": 27, "path": "/src/main/java/de/tum/in/www1/artemis/repository/LtiOutcomeUrlRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.LtiOutcomeUrl;\nimport de.tum.in.www1.artemis.domain.User;\n\n/**\n * Spring Data JPA repository for the LtiOutcomeUrl entity.\n */\n@SuppressWarnings(\"unused\")\npublic interface LtiOutcomeUrlRepository extends JpaRepository<LtiOutcomeUrl, Long> {\n\n @Query(\"select ltiOutcomeUrl from LtiOutcomeUrl ltiOutcomeUrl where ltiOutcomeUrl.user.login = ?#{principal}\")\n List<LtiOutcomeUrl> findByUserIsCurrentUser();\n\n @Query(\"select ltiOutcomeUrl from LtiOutcomeUrl ltiOutcomeUrl where ltiOutcomeUrl.user.login = ?#{principal} and ltiOutcomeUrl.exercise.id = :#{#exercise.id}\")\n Optional<LtiOutcomeUrl> findByUserIsCurrentUserAndExercise(@Param(\"exercise\") Exercise exercise);\n\n Optional<LtiOutcomeUrl> findByUserAndExercise(User user, Exercise exercise);\n}\n" }, { "alpha_fraction": 0.656148374080658, "alphanum_fraction": 0.6601330041885376, "avg_line_length": 48.89912414550781, "blob_id": "041edae2ffa399f9fff627147d5617d7ee004a32", "content_id": "6bd4d2dced95ffe01215de5700f3346b75d195db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 34131, "license_type": "permissive", "max_line_length": 164, "num_lines": 684, "path": "/src/test/javascript/spec/component/code-editor/code-editor-file-browser.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { CookieService } from 'ngx-cookie-service';\nimport { By } from '@angular/platform-browser';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { TreeviewItem, TreeviewModule } from 'ngx-treeview';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { Observable, Subject } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { CommitState, FileType, GitConflictState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { CodeEditorRepositoryFileService, CodeEditorRepositoryService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service';\nimport { CodeEditorFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-file.service';\nimport { CodeEditorFileBrowserFolderComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-folder.component';\nimport { CodeEditorFileBrowserCreateNodeComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-create-node.component';\nimport { CodeEditorFileBrowserFileComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-file.component';\nimport { CodeEditorFileBrowserComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser.component';\nimport { CodeEditorStatusComponent } from 'app/exercises/programming/shared/code-editor/status/code-editor-status.component';\nimport { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service';\nimport { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service';\nimport { MockCodeEditorConflictStateService } from '../../helpers/mocks/service/mock-code-editor-conflict-state.service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorFileBrowserComponent', () => {\n let comp: CodeEditorFileBrowserComponent;\n let fixture: ComponentFixture<CodeEditorFileBrowserComponent>;\n let debugElement: DebugElement;\n let codeEditorRepositoryFileService: CodeEditorRepositoryFileService;\n let codeEditorRepositoryService: CodeEditorRepositoryService;\n let conflictService: CodeEditorConflictStateService;\n let getRepositoryContentStub: SinonStub;\n let isCleanStub: SinonStub;\n let createFileStub: SinonStub;\n let createFolderStub: SinonStub;\n let renameFileStub: SinonStub;\n\n const createFileRoot = '#create_file_root';\n const createFolderRoot = '#create_folder_root';\n const compressTree = '#compress_tree';\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, AceEditorModule, TreeviewModule.forRoot(), NgbModule],\n declarations: [\n CodeEditorFileBrowserComponent,\n MockComponent(CodeEditorStatusComponent),\n CodeEditorFileBrowserFileComponent,\n CodeEditorFileBrowserFolderComponent,\n CodeEditorFileBrowserCreateNodeComponent,\n MockPipe(ArtemisTranslatePipe),\n ],\n providers: [\n CodeEditorFileService,\n DeviceDetectorService,\n { provide: CodeEditorRepositoryService, useClass: MockCodeEditorRepositoryService },\n { provide: CodeEditorRepositoryFileService, useClass: MockCodeEditorRepositoryFileService },\n { provide: CodeEditorConflictStateService, useClass: MockCodeEditorConflictStateService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CodeEditorFileBrowserComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n codeEditorRepositoryFileService = debugElement.injector.get(CodeEditorRepositoryFileService);\n codeEditorRepositoryService = debugElement.injector.get(CodeEditorRepositoryService);\n conflictService = debugElement.injector.get(CodeEditorConflictStateService);\n isCleanStub = stub(codeEditorRepositoryService, 'getStatus');\n getRepositoryContentStub = stub(codeEditorRepositoryFileService, 'getRepositoryContent');\n createFileStub = stub(codeEditorRepositoryFileService, 'createFile');\n createFolderStub = stub(codeEditorRepositoryFileService, 'createFolder');\n renameFileStub = stub(codeEditorRepositoryFileService, 'renameFile');\n });\n });\n\n afterEach(() => {\n isCleanStub.restore();\n getRepositoryContentStub.restore();\n createFileStub.restore();\n createFolderStub.restore();\n });\n\n it('should create no treeviewItems if getRepositoryContent returns an empty result', () => {\n const repositoryContent: { [fileName: string]: string } = {};\n const expectedFileTreeItems: TreeviewItem[] = [];\n getRepositoryContentStub.returns(Observable.of(repositoryContent));\n isCleanStub.returns(Observable.of({ repositoryStatus: CommitState.CLEAN }));\n comp.commitState = CommitState.UNDEFINED;\n\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n\n expect(comp.isLoadingFiles).to.equal(false);\n expect(comp.repositoryFiles).to.deep.equal(repositoryContent);\n expect(comp.filesTreeViewItem).to.deep.equal(expectedFileTreeItems);\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(0);\n expect(renderedFiles).to.have.lengthOf(0);\n });\n\n it('should create treeviewItems if getRepositoryContent returns files', () => {\n const repositoryContent: { [fileName: string]: string } = { file: 'FILE', folder: 'FOLDER' };\n getRepositoryContentStub.returns(Observable.of(repositoryContent));\n isCleanStub.returns(Observable.of({ repositoryStatus: CommitState.CLEAN }));\n comp.commitState = CommitState.UNDEFINED;\n\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n expect(comp.isLoadingFiles).to.equal(false);\n expect(comp.repositoryFiles).to.deep.equal(repositoryContent);\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(1);\n expect(renderedFiles).to.have.lengthOf(1);\n });\n\n it('should create treeviewItems with nested folder structure', () => {\n const repositoryFiles = {\n folder: FileType.FOLDER,\n 'folder/file1': FileType.FILE,\n folder2: FileType.FOLDER,\n 'folder2/file2': FileType.FILE,\n 'folder2/folder3': FileType.FOLDER,\n 'folder2/folder3/file3': FileType.FILE,\n };\n comp.repositoryFiles = repositoryFiles;\n comp.setupTreeview();\n fixture.detectChanges();\n const folder = comp.filesTreeViewItem.find(({ value }) => value === 'folder')!;\n expect(folder).to.exist;\n expect(folder.children).to.have.lengthOf(1);\n const file1 = folder.children.find(({ value }) => value === 'folder/file1')!;\n expect(file1).to.exist;\n expect(file1.children).to.be.undefined;\n const folder2 = comp.filesTreeViewItem.find(({ value }) => value === 'folder2')!;\n expect(folder2).to.exist;\n expect(folder2.children).to.have.lengthOf(2);\n const file2 = folder2.children.find(({ value }) => value === 'folder2/file2')!;\n expect(file2).to.exist;\n expect(file2.children).to.be.undefined;\n const folder3 = folder2.children.find(({ value }) => value === 'folder2/folder3')!;\n expect(folder3).to.exist;\n expect(folder3.children).to.have.lengthOf(1);\n const file3 = folder3.children.find(({ value }) => value === 'folder2/folder3/file3')!;\n expect(file3).to.exist;\n expect(file3.children).to.be.undefined;\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(3);\n expect(renderedFiles).to.have.lengthOf(3);\n });\n\n it('should filter forbidden files from getRepositoryContent response', () => {\n const allowedFiles = {\n 'allowedFile.java': FileType.FILE,\n };\n const forbiddenFiles = {\n 'danger.bin': FileType.FOLDER,\n 'README.md': FileType.FILE,\n '.hidden': FileType.FILE,\n '.': FileType.FOLDER,\n };\n const repositoryContent = {\n ...allowedFiles,\n ...forbiddenFiles,\n };\n const expectedFileTreeItems = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file1',\n value: 'file1',\n } as any),\n ].map((x) => x.toString());\n getRepositoryContentStub.returns(Observable.of(repositoryContent));\n isCleanStub.returns(Observable.of({ repositoryStatus: CommitState.CLEAN }));\n comp.commitState = CommitState.UNDEFINED;\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n expect(comp.isLoadingFiles).to.equal(false);\n expect(comp.repositoryFiles).to.deep.equal(allowedFiles);\n expect(comp.filesTreeViewItem.map((x) => x.toString())).to.deep.equal(expectedFileTreeItems);\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(0);\n expect(renderedFiles).to.have.lengthOf(1);\n });\n\n it('should not load files if commitState could not be retrieved (possibly corrupt repository or server error)', () => {\n const isCleanSubject = new Subject<{ isClean: boolean }>();\n const onErrorSpy = spy(comp.onError, 'emit');\n const loadFilesSpy = spy(comp, 'loadFiles');\n isCleanStub.returns(isCleanSubject);\n comp.commitState = CommitState.UNDEFINED;\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n expect(comp.isLoadingFiles).to.equal(true);\n expect(comp.commitState).to.equal(CommitState.UNDEFINED);\n isCleanSubject.error('fatal error');\n\n fixture.detectChanges();\n expect(comp.commitState).to.equal(CommitState.COULD_NOT_BE_RETRIEVED);\n expect(comp.isLoadingFiles).to.equal(false);\n expect(comp.repositoryFiles).to.be.undefined;\n expect(comp.filesTreeViewItem).to.be.undefined;\n expect(onErrorSpy).to.have.been.calledOnce;\n expect(loadFilesSpy).to.not.have.been.called;\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(0);\n expect(renderedFiles).to.have.lengthOf(0);\n });\n\n it('should set isLoading false and emit an error if loadFiles fails', () => {\n const isCleanSubject = new Subject<{ isClean: boolean }>();\n const getRepositoryContentSubject = new Subject<{ [fileName: string]: FileType }>();\n const onErrorSpy = spy(comp.onError, 'emit');\n isCleanStub.returns(isCleanSubject);\n getRepositoryContentStub.returns(getRepositoryContentSubject);\n comp.commitState = CommitState.UNDEFINED;\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n expect(comp.isLoadingFiles).to.equal(true);\n expect(comp.commitState).to.equal(CommitState.UNDEFINED);\n isCleanSubject.next({ isClean: true });\n getRepositoryContentSubject.error('fatal error');\n\n fixture.detectChanges();\n expect(comp.isLoadingFiles).to.equal(false);\n expect(comp.repositoryFiles).to.be.undefined;\n expect(comp.filesTreeViewItem).to.be.undefined;\n expect(onErrorSpy).to.have.been.calledOnce;\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(0);\n expect(renderedFiles).to.have.lengthOf(0);\n });\n\n it('should set node to checked if its file gets selected and update ui', () => {\n const selectedFile = 'folder/file1';\n const repositoryFiles = {\n folder: FileType.FOLDER,\n 'folder/file1': FileType.FILE,\n folder2: FileType.FOLDER,\n 'folder/file2': FileType.FILE,\n };\n comp.filesTreeViewItem = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: selectedFile,\n value: 'file1',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder2/file2',\n value: 'file2',\n } as any),\n ];\n comp.repositoryFiles = repositoryFiles;\n comp.selectedFile = selectedFile;\n triggerChanges(comp, { property: 'selectedFile', currentValue: 'folder/file2', firstChange: false });\n fixture.detectChanges();\n expect(comp.selectedFile).to.equal(selectedFile);\n const selectedTreeItem = comp.filesTreeViewItem.find(({ value }) => value === 'folder')!.children.find(({ value }) => value === selectedFile)!;\n expect(selectedTreeItem).to.exist;\n expect(selectedTreeItem.checked).to.be.true;\n const renderedFolders = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n const renderedFiles = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(renderedFolders).to.have.lengthOf(2);\n expect(renderedFiles).to.have.lengthOf(2);\n\n const selectedFileHtml = renderedFiles[0];\n const isSelected = !!selectedFileHtml.query(By.css('.node-selected'));\n expect(isSelected).to.be.true;\n const notSelectedFilesHtml = [renderedFiles[1], ...renderedFolders];\n const areUnSelected = !notSelectedFilesHtml.some((el) => !!el.query(By.css('.node-selected')));\n expect(areUnSelected).to.be.true;\n });\n\n it('should add file to node tree if created', fakeAsync(() => {\n const fileName = 'file2';\n const filePath = 'folder2/file2';\n const repositoryFiles = { file1: FileType.FILE, folder2: FileType.FOLDER };\n const treeItems = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file1',\n value: 'file1',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder2',\n value: 'folder2',\n } as any),\n ];\n const onFileChangeSpy = spy(comp.onFileChange, 'emit');\n const setupTreeviewStub = stub(comp, 'setupTreeview');\n createFileStub.returns(Observable.of(undefined));\n comp.repositoryFiles = repositoryFiles;\n comp.filesTreeViewItem = treeItems;\n comp.creatingFile = ['folder2', FileType.FILE];\n fixture.detectChanges();\n\n let creatingElement = debugElement.query(By.css('jhi-code-editor-file-browser-create-node'));\n expect(creatingElement).to.exist;\n const creatingInput = creatingElement.query(By.css('input'));\n expect(creatingInput).to.exist;\n\n tick();\n const focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(creatingInput.nativeElement).to.deep.equal(focusedElement);\n\n comp.onCreateFile(fileName);\n fixture.detectChanges();\n\n expect(createFileStub).to.have.been.calledOnceWithExactly(filePath);\n expect(comp.creatingFile).to.be.undefined;\n expect(setupTreeviewStub).to.have.been.calledOnceWithExactly();\n expect(onFileChangeSpy).to.have.been.calledOnce;\n expect(comp.repositoryFiles).to.deep.equal({ ...repositoryFiles, [filePath]: FileType.FILE });\n creatingElement = debugElement.query(By.css('jhi-code-editor-file-browser-create-node'));\n expect(creatingElement).not.to.exist;\n }));\n\n it('should add folder to node tree if created', fakeAsync(() => {\n const fileName = 'folder3';\n const filePath = 'folder2/folder3';\n const repositoryFiles = { file1: FileType.FILE, folder2: FileType.FOLDER };\n const treeItems = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file1',\n value: 'file1',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder2',\n value: 'folder2',\n } as any),\n ];\n const onFileChangeSpy = spy(comp.onFileChange, 'emit');\n const setupTreeviewStub = stub(comp, 'setupTreeview');\n createFolderStub.returns(Observable.of(undefined));\n comp.repositoryFiles = repositoryFiles;\n comp.filesTreeViewItem = treeItems;\n comp.creatingFile = ['folder2', FileType.FOLDER];\n fixture.detectChanges();\n\n let creatingElement = debugElement.query(By.css('jhi-code-editor-file-browser-create-node'));\n expect(creatingElement).to.exist;\n const creatingInput = creatingElement.query(By.css('input'));\n expect(creatingInput).to.exist;\n\n tick();\n const focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(creatingInput.nativeElement).to.deep.equal(focusedElement);\n\n comp.onCreateFile(fileName);\n\n fixture.detectChanges();\n expect(createFolderStub).to.have.been.calledOnceWithExactly(filePath);\n expect(comp.creatingFile).to.be.undefined;\n expect(setupTreeviewStub).to.have.been.calledOnceWithExactly();\n expect(onFileChangeSpy).to.have.been.calledOnce;\n expect(comp.repositoryFiles).to.deep.equal({ ...repositoryFiles, [filePath]: FileType.FOLDER });\n creatingElement = debugElement.query(By.css('jhi-code-editor-file-browser-create-node'));\n expect(creatingElement).not.to.exist;\n }));\n\n it('should not be able to create binary file', () => {\n const fileName = 'danger.bin';\n const onErrorSpy = spy(comp.onError, 'emit');\n comp.creatingFile = ['', FileType.FILE];\n comp.onCreateFile(fileName);\n fixture.detectChanges();\n expect(onErrorSpy).to.have.been.calledOnce;\n expect(createFileStub).not.to.have.been.called;\n });\n\n it('should not be able to create node that already exists', () => {\n const fileName = 'file1';\n const repositoryFiles = { 'folder2/file1': FileType.FILE, folder2: FileType.FOLDER };\n const onErrorSpy = spy(comp.onError, 'emit');\n comp.creatingFile = ['folder2', FileType.FILE];\n comp.repositoryFiles = repositoryFiles;\n comp.onCreateFile(fileName);\n fixture.detectChanges();\n expect(onErrorSpy).to.have.been.calledOnce;\n expect(createFileStub).not.to.have.been.called;\n });\n\n it('should update repository file entry on rename', fakeAsync(() => {\n const fileName = 'file1';\n const afterRename = 'newFileName';\n const treeItems = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file1',\n value: 'file1',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder2',\n value: 'folder2',\n } as any),\n ];\n const repositoryFiles = { file1: FileType.FILE, folder2: FileType.FOLDER };\n const onFileChangeSpy = spy(comp.onFileChange, 'emit');\n renameFileStub.returns(Observable.of(undefined));\n comp.repositoryFiles = repositoryFiles;\n comp.renamingFile = [fileName, fileName, FileType.FILE];\n comp.filesTreeViewItem = treeItems;\n fixture.detectChanges();\n\n let filesInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(filesInTreeHtml).to.have.lengthOf(1);\n let foldersInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n expect(foldersInTreeHtml).to.have.lengthOf(1);\n let renamingInput = filesInTreeHtml[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n\n // Wait for focus of input element\n tick();\n const focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n\n renamingInput.nativeElement.value = afterRename;\n renamingInput.nativeElement.dispatchEvent(new Event('input'));\n renamingInput.nativeElement.dispatchEvent(new Event('focusout'));\n fixture.detectChanges();\n\n expect(renameFileStub).to.have.been.calledOnceWithExactly(fileName, afterRename);\n expect(comp.renamingFile).to.be.undefined;\n expect(onFileChangeSpy).to.have.been.calledOnce;\n expect(comp.repositoryFiles).to.deep.equal({ folder2: FileType.FOLDER, [afterRename]: FileType.FILE });\n\n filesInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(filesInTreeHtml).to.have.lengthOf(1);\n foldersInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n expect(foldersInTreeHtml).to.have.lengthOf(1);\n renamingInput = filesInTreeHtml[0].query(By.css('input'));\n expect(renamingInput).not.to.exist;\n\n // Wait for focus of input element\n tick();\n }));\n\n it('should rename all paths concerned if a folder is renamed', fakeAsync(() => {\n const folderName = 'folder';\n const afterRename = 'newFolderName';\n const treeItems = [\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file1',\n value: 'folder/file1',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'file2',\n value: 'folder/file2',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder',\n value: 'folder',\n } as any),\n new TreeviewItem({\n internalDisabled: false,\n internalChecked: false,\n internalCollapsed: false,\n text: 'folder2',\n value: 'folder2',\n } as any),\n ];\n const repositoryFiles = { 'folder/file1': FileType.FILE, 'folder/file2': FileType.FILE, folder: FileType.FOLDER, folder2: FileType.FOLDER };\n const onFileChangeSpy = spy(comp.onFileChange, 'emit');\n renameFileStub.returns(Observable.of(undefined));\n comp.repositoryFiles = repositoryFiles;\n comp.renamingFile = [folderName, folderName, FileType.FILE];\n comp.filesTreeViewItem = treeItems;\n fixture.detectChanges();\n\n let filesInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(filesInTreeHtml).to.have.lengthOf(2);\n let foldersInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n expect(foldersInTreeHtml).to.have.lengthOf(2);\n let renamingInput = foldersInTreeHtml[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n\n // Wait for focus of input element\n tick();\n const focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n\n renamingInput.nativeElement.value = afterRename;\n renamingInput.nativeElement.dispatchEvent(new Event('input'));\n renamingInput.nativeElement.dispatchEvent(new Event('focusout'));\n\n expect(renameFileStub).to.have.been.calledOnceWithExactly(folderName, afterRename);\n expect(comp.renamingFile).to.be.undefined;\n expect(onFileChangeSpy).to.have.been.calledOnce;\n expect(comp.repositoryFiles).to.deep.equal({\n [[afterRename, 'file1'].join('/')]: FileType.FILE,\n [[afterRename, 'file2'].join('/')]: FileType.FILE,\n [afterRename]: FileType.FOLDER,\n folder2: FileType.FOLDER,\n });\n\n filesInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'));\n expect(filesInTreeHtml).to.have.lengthOf(2);\n foldersInTreeHtml = debugElement.queryAll(By.css('jhi-code-editor-file-browser-folder'));\n expect(foldersInTreeHtml).to.have.lengthOf(2);\n renamingInput = filesInTreeHtml[0].query(By.css('input'));\n expect(renamingInput).not.to.exist;\n }));\n\n it('should not rename a file if its new fileName already exists in the repository', fakeAsync(() => {\n const fileName = 'file1';\n const afterRename = 'newFileName';\n const repositoryFiles = { file1: FileType.FILE, newFileName: FileType.FILE };\n comp.repositoryFiles = repositoryFiles;\n comp.setupTreeview();\n fixture.detectChanges();\n comp.renamingFile = [fileName, fileName, FileType.FILE];\n fixture.detectChanges();\n\n let renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n\n // Wait for focus of input element\n tick();\n let focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n\n renamingInput.nativeElement.value = afterRename;\n renamingInput.nativeElement.dispatchEvent(new Event('input'));\n renamingInput.nativeElement.dispatchEvent(new Event('focusout'));\n fixture.detectChanges();\n\n expect(renameFileStub).not.to.have.been.called;\n expect(comp.repositoryFiles).to.deep.equal(repositoryFiles);\n\n // When renaming failed, the input should not be closed, because the user probably still wants to rename\n renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n }));\n\n it('should not rename a file if its new fileName indicates a binary file', fakeAsync(() => {\n const fileName = 'file1';\n const afterRename = 'newFileName.bin';\n const repositoryFiles = { file1: FileType.FILE, newFileName: FileType.FILE };\n comp.repositoryFiles = repositoryFiles;\n comp.setupTreeview();\n fixture.detectChanges();\n comp.renamingFile = [fileName, fileName, FileType.FILE];\n fixture.detectChanges();\n\n let renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n\n // Wait for focus of input element\n tick();\n let focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n\n renamingInput.nativeElement.value = afterRename;\n renamingInput.nativeElement.dispatchEvent(new Event('input'));\n renamingInput.nativeElement.dispatchEvent(new Event('focusout'));\n fixture.detectChanges();\n\n expect(renameFileStub).not.to.have.been.called;\n expect(comp.repositoryFiles).to.deep.equal(repositoryFiles);\n\n // When renaming failed, the input should not be closed, because the user probably still wants to rename\n renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n }));\n\n it('should leave rename state if renaming a file to the same file name', fakeAsync(() => {\n const fileName = 'file1';\n const repositoryFiles = { file1: FileType.FILE, newFileName: FileType.FILE };\n comp.repositoryFiles = repositoryFiles;\n comp.setupTreeview();\n fixture.detectChanges();\n comp.renamingFile = [fileName, fileName, FileType.FILE];\n fixture.detectChanges();\n\n let renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).to.exist;\n\n // Wait for focus of input element\n tick();\n const focusedElement = debugElement.query(By.css(':focus')).nativeElement;\n expect(renamingInput.nativeElement).to.deep.equal(focusedElement);\n\n renamingInput.nativeElement.dispatchEvent(new Event('focusout'));\n fixture.detectChanges();\n\n expect(renameFileStub).not.to.have.been.called;\n expect(comp.repositoryFiles).to.deep.equal(repositoryFiles);\n\n // When renaming failed, the input should not be closed, because the user probably still wants to rename\n renamingInput = debugElement.queryAll(By.css('jhi-code-editor-file-browser-file'))[0].query(By.css('input'));\n expect(renamingInput).not.to.exist;\n }));\n\n it('should disable action buttons if there is a git conflict', () => {\n const repositoryContent: { [fileName: string]: string } = {};\n isCleanStub.returns(Observable.of({ repositoryStatus: CommitState.CONFLICT }));\n getRepositoryContentStub.returns(Observable.of(repositoryContent));\n comp.commitState = CommitState.UNDEFINED;\n\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n\n expect(comp.commitState).to.equal(CommitState.CONFLICT);\n\n expect(debugElement.query(By.css(createFileRoot)).nativeElement.disabled).to.be.true;\n expect(debugElement.query(By.css(createFolderRoot)).nativeElement.disabled).to.be.true;\n expect(debugElement.query(By.css(compressTree)).nativeElement.disabled).to.be.false;\n\n // Resolve conflict.\n conflictService.notifyConflictState(GitConflictState.OK);\n isCleanStub.returns(Observable.of({ repositoryStatus: CommitState.CLEAN }));\n\n comp.commitState = CommitState.UNDEFINED;\n\n triggerChanges(comp, { property: 'commitState', currentValue: CommitState.UNDEFINED });\n fixture.detectChanges();\n\n expect(comp.commitState).to.equal(CommitState.CLEAN);\n\n expect(debugElement.query(By.css(createFileRoot)).nativeElement.disabled).to.be.false;\n expect(debugElement.query(By.css(createFolderRoot)).nativeElement.disabled).to.be.false;\n expect(debugElement.query(By.css(compressTree)).nativeElement.disabled).to.be.false;\n\n expect(getRepositoryContentStub).to.have.been.calledOnce;\n expect(comp.selectedFile).to.be.undefined;\n });\n});\n" }, { "alpha_fraction": 0.7511365413665771, "alphanum_fraction": 0.7538107633590698, "avg_line_length": 67.4871826171875, "blob_id": "9ac19734db1143b1d1c430b204da12fc68bc1ed8", "content_id": "e7d463dd91881e910ff26b64bda316a202810200", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 18697, "license_type": "permissive", "max_line_length": 180, "num_lines": 273, "path": "/src/main/java/de/tum/in/www1/artemis/service/LearningGoalService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.lecture.ExerciseUnit;\nimport de.tum.in.www1.artemis.domain.lecture.LectureUnit;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.scores.StudentScore;\nimport de.tum.in.www1.artemis.domain.scores.TeamScore;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseExerciseStatisticsDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseLearningGoalProgress;\nimport de.tum.in.www1.artemis.web.rest.dto.IndividualLearningGoalProgress;\n\n@Service\npublic class LearningGoalService {\n\n private final StudentParticipationRepository studentParticipationRepository;\n\n private final ExerciseRepository exerciseRepository;\n\n private final StudentScoreRepository studentScoreRepository;\n\n private final TeamScoreRepository teamScoreRepository;\n\n public LearningGoalService(StudentParticipationRepository studentParticipationRepository, ExerciseRepository exerciseRepository, StudentScoreRepository studentScoreRepository,\n TeamScoreRepository teamScoreRepository) {\n this.exerciseRepository = exerciseRepository;\n this.studentParticipationRepository = studentParticipationRepository;\n this.studentScoreRepository = studentScoreRepository;\n this.teamScoreRepository = teamScoreRepository;\n }\n\n /**\n * Calculates the progress of the given user in the given exercise units\n * <p>\n * Note: In the case of two exercise units referencing the same exercise, only the first exercise unit will be used.\n * <p>\n * Note: Please note that we take always the last submission into account here. Even submissions after the due date. This means for example that a student can improve his/her\n * progress by re-trying a quiz as often as you like. It is therefore normal, that the points here might differ from the points officially achieved in an exercise.\n *\n * @param exerciseUnits exercise units to check\n * @param user user to check for\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result\n * @return progress of the user in the exercise units\n */\n public Set<IndividualLearningGoalProgress.IndividualLectureUnitProgress> calculateExerciseUnitsProgress(Set<ExerciseUnit> exerciseUnits, User user,\n boolean useParticipantScoreTable) {\n // for each exercise unit, the exercise will be mapped to a freshly created lecture unit progress.\n Map<Exercise, IndividualLearningGoalProgress.IndividualLectureUnitProgress> exerciseToLectureUnitProgress = exerciseUnits.stream()\n .filter(exerciseUnit -> exerciseUnit.getExercise() != null && exerciseUnit.getExercise().isAssessmentDueDateOver())\n .collect(Collectors.toMap(ExerciseUnit::getExercise, exerciseUnit -> {\n IndividualLearningGoalProgress.IndividualLectureUnitProgress individualLectureUnitProgress = new IndividualLearningGoalProgress.IndividualLectureUnitProgress();\n individualLectureUnitProgress.lectureUnitId = exerciseUnit.getId();\n individualLectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit = exerciseUnit.getExercise().getMaxPoints();\n return individualLectureUnitProgress;\n }, (progress1, progress2) -> progress1)); // in the case of two exercises referencing the same exercise, take the first one\n\n List<Exercise> individualExercises = exerciseToLectureUnitProgress.keySet().stream().filter(exercise -> !exercise.isTeamMode()).collect(Collectors.toList());\n List<Exercise> teamExercises = exerciseToLectureUnitProgress.keySet().stream().filter(Exercise::isTeamMode).collect(Collectors.toList());\n\n if (useParticipantScoreTable) {\n fillInScoreAchievedByStudentUsingParticipantScores(user, exerciseToLectureUnitProgress, individualExercises, teamExercises);\n }\n else {\n fillInScoreAchievedByStudentUsingParticipationsSubmissionsResults(user, exerciseToLectureUnitProgress, individualExercises, teamExercises);\n }\n\n return new HashSet<>(exerciseToLectureUnitProgress.values());\n }\n\n private void fillInScoreAchievedByStudentUsingParticipationsSubmissionsResults(User user,\n Map<Exercise, IndividualLearningGoalProgress.IndividualLectureUnitProgress> exerciseToLectureUnitProgress, List<Exercise> individualExercises,\n List<Exercise> teamExercises) {\n // for all relevant exercises the participations with submissions and results will be batch loaded\n List<StudentParticipation> participationsOfTheStudent = getStudentParticipationsWithSubmissionsAndResults(user, individualExercises, teamExercises);\n\n for (Exercise exercise : exerciseToLectureUnitProgress.keySet()) {\n // exercise -> participation -> submission -> result until possibly the latest result is found for the student\n Optional<Result> optionalResult = findLastResultOfExerciseInListOfParticipations(exercise, participationsOfTheStudent);\n exerciseToLectureUnitProgress.get(exercise).scoreAchievedByStudentInLectureUnit = optionalResult.isEmpty() || optionalResult.get().getScore() == null ? 0.0\n : optionalResult.get().getScore().doubleValue();\n }\n }\n\n private void fillInScoreAchievedByStudentUsingParticipantScores(User user,\n Map<Exercise, IndividualLearningGoalProgress.IndividualLectureUnitProgress> exerciseToLectureUnitProgress, List<Exercise> individualExercises,\n List<Exercise> teamExercises) {\n for (Exercise exercise : individualExercises) {\n Optional<StudentScore> studentScoreOptional = studentScoreRepository.findStudentScoreByExerciseAndUserLazy(exercise, user);\n exerciseToLectureUnitProgress.get(exercise).scoreAchievedByStudentInLectureUnit = studentScoreOptional.map(studentScore -> studentScore.getLastScore().doubleValue())\n .orElse(0.0);\n }\n\n for (Exercise exercise : teamExercises) {\n Optional<TeamScore> teamScoreOptional = teamScoreRepository.findTeamScoreByExerciseAndUserLazy(exercise, user);\n exerciseToLectureUnitProgress.get(exercise).scoreAchievedByStudentInLectureUnit = teamScoreOptional.map(teamScore -> teamScore.getLastScore().doubleValue())\n .orElse(0.0);\n }\n }\n\n /**\n * Calculates the course progress in the given exercise units\n * <p>\n * Note: In the case of two exercise units referencing the same exercise, only the first exercise unit will be used.\n * <p>\n * Note: Please note that we take always the last submission into account here. Even submissions after the due date. This means for example that a student can improve his/her\n * progress by re-trying a quiz as often as you like. It is therefore normal, that the points here might differ from the points officially achieved in an exercise.\n *\n * @param exerciseUnits exercise units to check\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result\n * @return progress of the course in the exercise units\n */\n private Set<CourseLearningGoalProgress.CourseLectureUnitProgress> calculateExerciseUnitsProgressForCourse(List<ExerciseUnit> exerciseUnits, boolean useParticipantScoreTable) {\n List<ExerciseUnit> filteredExerciseUnits = exerciseUnits.stream()\n .filter(exerciseUnit -> exerciseUnit.getExercise() != null && exerciseUnit.getExercise().isAssessmentDueDateOver()).collect(Collectors.toList());\n List<Long> exerciseIds = filteredExerciseUnits.stream().map(exerciseUnit -> exerciseUnit.getExercise().getId()).distinct().collect(Collectors.toList());\n\n Map<Long, CourseExerciseStatisticsDTO> exerciseIdToExerciseCourseStatistics = this.exerciseRepository.calculateExerciseStatistics(exerciseIds, useParticipantScoreTable)\n .stream().collect(Collectors.toMap(CourseExerciseStatisticsDTO::getExerciseId, courseExerciseStatisticsDTO -> courseExerciseStatisticsDTO));\n\n // for each exercise unit, the exercise will be mapped to a freshly created lecture unit course progress.\n Map<Exercise, CourseLearningGoalProgress.CourseLectureUnitProgress> exerciseToLectureUnitCourseProgress = filteredExerciseUnits.stream()\n .collect(Collectors.toMap(ExerciseUnit::getExercise, exerciseUnit -> {\n CourseExerciseStatisticsDTO courseExerciseStatisticsDTO = exerciseIdToExerciseCourseStatistics.get(exerciseUnit.getExercise().getId());\n CourseLearningGoalProgress.CourseLectureUnitProgress courseLectureUnitProgress = new CourseLearningGoalProgress.CourseLectureUnitProgress();\n courseLectureUnitProgress.lectureUnitId = exerciseUnit.getId();\n courseLectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit = exerciseUnit.getExercise().getMaxPoints();\n courseLectureUnitProgress.averageScoreAchievedByStudentInLectureUnit = courseExerciseStatisticsDTO.getAverageScoreInPercent();\n courseLectureUnitProgress.noOfParticipants = courseExerciseStatisticsDTO.getNoOfParticipatingStudentsOrTeams();\n courseLectureUnitProgress.participationRate = courseExerciseStatisticsDTO.getParticipationRateInPercent();\n return courseLectureUnitProgress;\n }, (progress1, progress2) -> progress1)); // in the case of two exercises referencing the same exercise, take the first one\n\n return new HashSet<>(exerciseToLectureUnitCourseProgress.values());\n\n }\n\n /**\n * Finds the latest result for a given exercise in a list of relevant participations\n * @param exercise exercise to find the result for\n * @param participationsList participations with submissions and results that should be checked\n * @return optional containing the last result or else an empty optional\n */\n private Optional<Result> findLastResultOfExerciseInListOfParticipations(Exercise exercise, List<StudentParticipation> participationsList) {\n // find the relevant participation\n StudentParticipation relevantParticipation = exercise.findRelevantParticipation(participationsList);\n if (relevantParticipation == null) {\n return Optional.empty();\n }\n\n relevantParticipation.setSubmissions(relevantParticipation.getSubmissions().stream().filter(submission -> {\n boolean hasFittingResult = false;\n for (Result result : submission.getResults()) {\n if (result.getScore() != null && result.getCompletionDate() != null) {\n hasFittingResult = true;\n break;\n }\n }\n return hasFittingResult;\n }).collect(Collectors.toSet()));\n\n // find the latest submission of the relevant participation\n Optional<Submission> latestSubmissionOptional = relevantParticipation.findLatestSubmission();\n if (latestSubmissionOptional.isEmpty()) {\n return Optional.empty();\n }\n Submission latestSubmission = latestSubmissionOptional.get();\n\n latestSubmission\n .setResults(latestSubmission.getResults().stream().filter(result -> result.getScore() != null && result.getCompletionDate() != null).collect(Collectors.toList()));\n\n // find the latest result of the latest submission\n Result latestResult = latestSubmission.getLatestResult();\n return latestResult == null ? Optional.empty() : Optional.of(latestResult);\n }\n\n /**\n * Gets the participations of a user (including submissions and results) for specific individual or team exercises\n * @param user user to get the participations for\n * @param individualExercises individual exercises to get the participations for\n * @param teamExercises team exercises to get the participations for\n * @return list of student participations for the given exercises and user\n */\n private List<StudentParticipation> getStudentParticipationsWithSubmissionsAndResults(User user, List<Exercise> individualExercises, List<Exercise> teamExercises) {\n // 1st: fetch participations, submissions and results for individual exercises\n List<StudentParticipation> participationsOfIndividualExercises = studentParticipationRepository\n .findByStudentIdAndIndividualExercisesWithEagerLegalSubmissionsResultIgnoreTestRuns(user.getId(), individualExercises);\n\n // 2nd: fetch participations, submissions and results for team exercises\n List<StudentParticipation> participationsOfTeamExercises = studentParticipationRepository.findByStudentIdAndTeamExercisesWithEagerLegalSubmissionsResult(user.getId(),\n teamExercises);\n\n // 3rd: merge both into one list for further processing\n return Stream.concat(participationsOfIndividualExercises.stream(), participationsOfTeamExercises.stream()).collect(Collectors.toList());\n }\n\n /**\n * Calculate the progress in a learning goal for a specific user\n *\n * @param learningGoal learning goal to get the progress for\n * @param user user to get the progress for\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result\n * @return progress of the user in the learning goal\n */\n public IndividualLearningGoalProgress calculateLearningGoalProgress(LearningGoal learningGoal, User user, boolean useParticipantScoreTable) {\n\n IndividualLearningGoalProgress individualLearningGoalProgress = new IndividualLearningGoalProgress();\n individualLearningGoalProgress.studentId = user.getId();\n individualLearningGoalProgress.learningGoalId = learningGoal.getId();\n individualLearningGoalProgress.learningGoalTitle = learningGoal.getTitle();\n individualLearningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 0.0;\n individualLearningGoalProgress.pointsAchievedByStudentInLearningGoal = 0.0;\n\n // The progress will be calculated from a subset of the connected lecture units (currently only from released exerciseUnits)\n Set<ExerciseUnit> exerciseUnitsUsableForProgressCalculation = learningGoal.getLectureUnits().parallelStream().filter(LectureUnit::isVisibleToStudents)\n .filter(lectureUnit -> lectureUnit instanceof ExerciseUnit).map(lectureUnit -> (ExerciseUnit) lectureUnit).collect(Collectors.toSet());\n Set<IndividualLearningGoalProgress.IndividualLectureUnitProgress> progressInLectureUnits = this.calculateExerciseUnitsProgress(exerciseUnitsUsableForProgressCalculation,\n user, useParticipantScoreTable);\n\n // updating learningGoalPerformance by summing up the points of the individual lecture unit performances\n individualLearningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = progressInLectureUnits.stream()\n .map(individualLectureUnitProgress -> individualLectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit).reduce(0.0, Double::sum);\n\n individualLearningGoalProgress.pointsAchievedByStudentInLearningGoal = progressInLectureUnits.stream()\n .map(individualLectureUnitProgress -> (individualLectureUnitProgress.scoreAchievedByStudentInLectureUnit / 100.0)\n * individualLectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit)\n .reduce(0.0, Double::sum);\n\n individualLearningGoalProgress.progressInLectureUnits = new ArrayList<>(progressInLectureUnits);\n return individualLearningGoalProgress;\n }\n\n /**\n * Calculate the progress in a learning goal for a whole course\n *\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result\n * @param learningGoal learning goal to get the progress for\n * @return progress of the course in the learning goal\n */\n public CourseLearningGoalProgress calculateLearningGoalCourseProgress(LearningGoal learningGoal, boolean useParticipantScoreTable) {\n CourseLearningGoalProgress courseLearningGoalProgress = new CourseLearningGoalProgress();\n courseLearningGoalProgress.courseId = learningGoal.getCourse().getId();\n courseLearningGoalProgress.learningGoalId = learningGoal.getId();\n courseLearningGoalProgress.learningGoalTitle = learningGoal.getTitle();\n courseLearningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 0.0;\n courseLearningGoalProgress.averagePointsAchievedByStudentInLearningGoal = 0.0;\n\n // The progress will be calculated from a subset of the connected lecture units (currently only from released exerciseUnits)\n List<ExerciseUnit> exerciseUnitsUsableForProgressCalculation = learningGoal.getLectureUnits().parallelStream().filter(LectureUnit::isVisibleToStudents)\n .filter(lectureUnit -> lectureUnit instanceof ExerciseUnit).map(lectureUnit -> (ExerciseUnit) lectureUnit).collect(Collectors.toList());\n Set<CourseLearningGoalProgress.CourseLectureUnitProgress> progressInLectureUnits = this.calculateExerciseUnitsProgressForCourse(exerciseUnitsUsableForProgressCalculation,\n useParticipantScoreTable);\n\n // updating learningGoalPerformance by summing up the points of the individual lecture unit progress\n courseLearningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = progressInLectureUnits.stream()\n .map(lectureUnitProgress -> lectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit).reduce(0.0, Double::sum);\n\n courseLearningGoalProgress.averagePointsAchievedByStudentInLearningGoal = progressInLectureUnits.stream().map(\n lectureUnitProgress -> (lectureUnitProgress.averageScoreAchievedByStudentInLectureUnit / 100.0) * lectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit)\n .reduce(0.0, Double::sum);\n\n courseLearningGoalProgress.progressInLectureUnits = new ArrayList<>(progressInLectureUnits);\n return courseLearningGoalProgress;\n\n }\n\n}\n" }, { "alpha_fraction": 0.6538282632827759, "alphanum_fraction": 0.6603462100028992, "avg_line_length": 38.843170166015625, "blob_id": "c53a633262454f3d756012cac5e253add6bbd380", "content_id": "f1f5f5168205aaf991c90bb05b054f54774a15a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 23627, "license_type": "permissive", "max_line_length": 139, "num_lines": 593, "path": "/src/test/javascript/spec/component/drag-and-drop-question/drag-and-drop-question-edit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { NgbCollapse, NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { DragItem } from 'app/entities/quiz/drag-item.model';\nimport { DragState } from 'app/entities/quiz/drag-state.enum';\nimport { DropLocation } from 'app/entities/quiz/drop-location.model';\nimport { ScoringType } from 'app/entities/quiz/quiz-question.model';\nimport { DragAndDropMouseEvent } from 'app/exercises/quiz/manage/drag-and-drop-question/drag-and-drop-mouse-event.class';\nimport { DragAndDropQuestionEditComponent } from 'app/exercises/quiz/manage/drag-and-drop-question/drag-and-drop-question-edit.component';\nimport { QuizScoringInfoModalComponent } from 'app/exercises/quiz/manage/quiz-scoring-info-modal/quiz-scoring-info-modal.component';\nimport { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component';\nimport { FileUploaderService, FileUploadResponse } from 'app/shared/http/file-uploader.service';\nimport { SecuredImageComponent } from 'app/shared/image/secured-image.component';\nimport { DomainCommand } from 'app/shared/markdown-editor/domainCommands/domainCommand';\nimport { ExplanationCommand } from 'app/shared/markdown-editor/domainCommands/explanation.command';\nimport { HintCommand } from 'app/shared/markdown-editor/domainCommands/hint.command';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { DndModule } from 'ng2-dnd';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('DragAndDropQuestionEditComponent', () => {\n let fixture: ComponentFixture<DragAndDropQuestionEditComponent>;\n let component: DragAndDropQuestionEditComponent;\n let uploadService: FileUploaderService;\n let modalService: NgbModal;\n\n const question1 = new DragAndDropQuestion();\n question1.id = 1;\n question1.backgroundFilePath = '';\n const question2 = new DragAndDropQuestion();\n question2.id = 2;\n question2.backgroundFilePath = '';\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule, DndModule.forRoot()],\n declarations: [\n DragAndDropQuestionEditComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(QuizScoringInfoModalComponent),\n MockComponent(MarkdownEditorComponent),\n MockComponent(SecuredImageComponent),\n MockComponent(DragAndDropQuestionComponent),\n MockDirective(NgbCollapse),\n ],\n providers: [{ provide: NgbModal, useClass: MockNgbModalService }],\n }).compileComponents();\n fixture = TestBed.createComponent(DragAndDropQuestionEditComponent);\n component = fixture.componentInstance;\n uploadService = TestBed.inject(FileUploaderService);\n modalService = TestBed.inject(NgbModal);\n });\n\n beforeEach(() => {\n component.question = question1;\n component.questionIndex = 1;\n component.reEvaluationInProgress = false;\n\n fixture.detectChanges();\n });\n\n afterEach(function () {\n sinon.restore();\n jest.clearAllMocks();\n });\n\n it('should initialize', () => {\n expect(component.isQuestionCollapsed).to.be.false;\n expect(component.isUploadingDragItemFile).to.be.false;\n expect(component.mouse).to.deep.equal(new DragAndDropMouseEvent());\n });\n\n it('should detect changes and update component', () => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n triggerChanges(component, { property: 'question', currentValue: question2, previousValue: question1 });\n\n fixture.detectChanges();\n\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.backupQuestion).to.deep.equal(question1);\n });\n\n it('should edit question in different ways', () => {\n const eventUpSpy = sinon.spy(component.questionMoveUp, 'emit');\n const eventDownSpy = sinon.spy(component.questionMoveDown, 'emit');\n const eventDeleteSpy = sinon.spy(component.questionDeleted, 'emit');\n\n component.moveUpQuestion();\n component.moveDownQuestion();\n component.deleteQuestion();\n\n expect(eventUpSpy).to.be.calledOnce;\n expect(eventDownSpy).to.be.calledOnce;\n expect(eventDeleteSpy).to.be.calledOnce;\n });\n\n it('should set background file', () => {\n const file1 = { name: 'newFile1' };\n const file2 = { name: 'newFile2' };\n const event = { target: { files: [file1, file2] } };\n\n component.setBackgroundFile(event);\n\n expect(component.backgroundFile).to.deep.equal(file1);\n expect(component.backgroundFileName).to.equal(file1.name);\n\n component.uploadBackground();\n });\n\n it('should upload file', fakeAsync(() => {\n const file1 = { name: 'newFile1' };\n const file2 = { name: 'newFile2' };\n const event = { target: { files: [file1, file2] } };\n\n component.setBackgroundFile(event);\n\n expect(component.backgroundFile).to.deep.equal(file1);\n expect(component.backgroundFileName).to.equal(file1.name);\n\n const newPath = 'alwaysGoYourPath';\n const mockReturnValue = Promise.resolve({ path: newPath } as FileUploadResponse);\n spyOn(uploadService, 'uploadFile').and.returnValue(mockReturnValue);\n\n component.uploadBackground();\n tick();\n\n expect(component.backgroundFile).to.equal(undefined);\n expect(component.question.backgroundFilePath).to.equal(newPath);\n expect(component.isUploadingBackgroundFile).to.be.false;\n }));\n\n it('should move the mouse in different situations', () => {\n const event1 = { pageX: 10, pageY: 10 };\n const event2 = { clientX: -10, clientY: -10 };\n\n component.mouseMove(event1);\n\n expect(component.mouse.x).to.equal(0);\n expect(component.mouse.y).to.equal(0);\n\n // MOVE\n component.mouse.offsetX = 15;\n component.mouse.offsetY = 15;\n component.draggingState = DragState.MOVE;\n const lengthOfElement = 15;\n component.currentDropLocation = { posX: 10, posY: 10, width: lengthOfElement, height: lengthOfElement };\n\n component.mouseMove(event2);\n\n expect(component.mouse.x).to.equal(0);\n expect(component.mouse.y).to.equal(0);\n expect(component.currentDropLocation.posX).to.equal(200 - lengthOfElement);\n expect(component.currentDropLocation.posY).to.equal(200 - lengthOfElement);\n\n // RESIZE_BOTH\n component.draggingState = DragState.RESIZE_BOTH;\n component.mouse.startX = 10;\n component.mouse.startY = 10;\n\n component.mouseMove(event2);\n\n expect(component.mouse.x).to.equal(0);\n expect(component.mouse.y).to.equal(0);\n expect(component.currentDropLocation.posX).to.exist;\n expect(component.currentDropLocation.posY).to.exist;\n\n // RESIZE_X\n component.draggingState = DragState.RESIZE_X;\n component.mouse.startX = 10;\n\n fixture.detectChanges();\n component.mouseMove(event2);\n\n expect(component.currentDropLocation.posX).to.exist;\n expect(component.currentDropLocation.posY).to.exist;\n\n // RESIZE_Y\n component.draggingState = DragState.RESIZE_Y;\n component.mouse.startY = 10;\n\n component.mouseMove(event2);\n\n expect(component.currentDropLocation.posX).to.exist;\n expect(component.currentDropLocation.posY).to.exist;\n });\n\n it('should move mouse up', () => {\n component.draggingState = DragState.MOVE;\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n\n component.mouseUp();\n\n expect(questionUpdatedSpy).to.be.calledOnce;\n expect(component.draggingState).to.equal(DragState.NONE);\n expect(component.currentDropLocation).to.be.undefined;\n\n component.draggingState = DragState.CREATE;\n const lengthOfElement = 15;\n const dropLocation = { posX: 10, posY: 10, width: lengthOfElement, height: lengthOfElement };\n const alternativeDropLocation = { posX: 15, posY: 15, width: lengthOfElement, height: lengthOfElement };\n component.currentDropLocation = dropLocation;\n component.question.dropLocations = [dropLocation, alternativeDropLocation];\n component.question.correctMappings = undefined;\n\n component.mouseUp();\n\n expect(component.draggingState).to.equal(DragState.NONE);\n expect(component.currentDropLocation).to.be.undefined;\n expect(component.question.correctMappings).to.deep.equal([]);\n expect(component.question.dropLocations).to.deep.equal([alternativeDropLocation]);\n });\n\n it('should move background mouse down', () => {\n component.draggingState = DragState.NONE;\n component.question.backgroundFilePath = 'NeedToGetInThere';\n const mouse = { x: 10, y: 10, startX: 5, startY: 5, offsetX: 0, offsetY: 0 };\n component.mouse = mouse;\n\n component.backgroundMouseDown();\n\n expect(component.currentDropLocation!.posX).to.equal(mouse.x);\n expect(component.currentDropLocation!.posY).to.equal(mouse.y);\n expect(component.currentDropLocation!.width).to.equal(0);\n expect(component.currentDropLocation!.height).to.equal(0);\n expect(component.draggingState).to.equal(DragState.CREATE);\n });\n\n it('should drop location on mouse down', () => {\n component.draggingState = DragState.NONE;\n component.mouse = { x: 10, y: 10, startX: 5, startY: 5, offsetX: 0, offsetY: 0 };\n const dropLocation = new DropLocation();\n\n component.dropLocationMouseDown(dropLocation);\n\n expect(component.mouse.offsetX).to.exist;\n expect(component.mouse.offsetY).to.exist;\n expect(component.currentDropLocation).to.deep.equal(dropLocation);\n expect(component.draggingState).to.equal(DragState.MOVE);\n });\n\n it('should open, drag, drop', () => {\n const content = {};\n const modalServiceSpy = sinon.spy(modalService, 'open');\n\n component.open(content);\n expect(modalServiceSpy).to.have.been.calledOnce;\n component.drag();\n expect(component.dropAllowed).to.be.true;\n component.drop();\n expect(component.dropAllowed).to.be.false;\n });\n\n it('should duplicate drop location', () => {\n const dropLocation = { posX: 10, posY: 10, width: 0, height: 0 } as DropLocation;\n component.question.dropLocations = [];\n\n component.duplicateDropLocation(dropLocation);\n\n const duplicatedDropLocation = component.question.dropLocations[0];\n expect(duplicatedDropLocation.posX).to.equal(dropLocation.posX! + 3);\n expect(duplicatedDropLocation.posY).to.equal(dropLocation.posY! + 3);\n expect(duplicatedDropLocation.width).to.equal(0);\n expect(duplicatedDropLocation.height).to.equal(0);\n });\n\n it('should resize mouse down', () => {\n component.draggingState = DragState.NONE;\n const dropLocation = { posX: 200, posY: 200, width: 0, height: 0 } as DropLocation;\n // middle, right\n let resizeLocationY = 'middle';\n let resizeLocationX = 'right';\n\n component.resizeMouseDown(dropLocation, resizeLocationY, resizeLocationX);\n\n expect(component.draggingState).to.equal(DragState.RESIZE_X);\n expect(component.mouse.startX).to.equal(0);\n\n // top, left\n component.draggingState = DragState.NONE;\n resizeLocationY = 'top';\n resizeLocationX = 'left';\n\n component.resizeMouseDown(dropLocation, resizeLocationY, resizeLocationX);\n\n expect(component.mouse.startY).to.equal(0);\n expect(component.mouse.startX).to.equal(0);\n\n // bottom, center\n component.draggingState = DragState.NONE;\n resizeLocationY = 'bottom';\n resizeLocationX = 'center';\n\n component.resizeMouseDown(dropLocation, resizeLocationY, resizeLocationX);\n\n expect(component.mouse.startY).to.equal(0);\n expect(component.draggingState).to.equal(DragState.RESIZE_Y);\n });\n\n it('should add text item', () => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n const dragItem = new DragItem();\n dragItem.text = 'Text';\n\n component.addTextDragItem();\n\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n const firstDragItemOfQuestion = component.question.dragItems![0];\n expect(firstDragItemOfQuestion.text).to.equal('Text');\n });\n\n it('should set drag item text', () => {\n const file1 = { name: 'newDragFile1' };\n const file2 = { name: 'newDragFile2' };\n const event = { target: { files: [file1, file2] } };\n\n component.setDragItemFile(event);\n\n expect(component.dragItemFile).to.deep.equal(file1);\n expect(component.dragItemFileName).to.equal('newDragFile1');\n });\n\n it('should upload drag item', fakeAsync(() => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n try {\n component.dragItemFile = new File([], 'file');\n\n const newPath = 'alwaysGoYourPath';\n let mockReturnValue = Promise.resolve({ path: newPath });\n const spy = spyOn(uploadService, 'uploadFile');\n spy.and.returnValue(mockReturnValue);\n\n component.uploadDragItem();\n tick();\n\n const expectedItem = component.question.dragItems![0];\n expect(expectedItem!.pictureFilePath).to.equal('alwaysGoYourPath');\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.dragItemFileName).to.equal('');\n expect(component.dragItemFile).to.be.undefined;\n sinon.restore();\n\n mockReturnValue = Promise.reject({ path: newPath });\n spy.and.returnValue(mockReturnValue);\n component.dragItemFile = new File([], 'file');\n\n component.uploadDragItem();\n tick();\n } catch (error) {\n expect(component.isUploadingDragItemFile).to.be.false;\n // Once because spy has been called in first execution of uploadDragItem()\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n }\n }));\n\n it('should picture for drag item', fakeAsync(() => {\n component.dragItemFile = new File([], 'file');\n const newPath = 'alwaysGoYourPath';\n const mockReturnValue = Promise.resolve({ path: newPath } as FileUploadResponse);\n spyOn(uploadService, 'uploadFile').and.returnValue(mockReturnValue);\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n\n component.uploadPictureForDragItemChange();\n tick();\n\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.dragItemPicture).to.equal(newPath);\n expect(component.isUploadingDragItemFile).to.be.false;\n }));\n\n it('should delete drag item', () => {\n const item = new DragItem();\n const newItem = new DragItem();\n const mapping = new DragAndDropMapping(newItem, new DropLocation());\n component.question.dragItems = [item];\n component.question.correctMappings = [mapping];\n\n component.deleteDragItem(item);\n\n expect(component.question.dragItems).to.deep.equal([]);\n expect(component.question.correctMappings).to.deep.equal([mapping]);\n });\n\n it('should delete mapping', () => {\n const item = new DragItem();\n const location = new DropLocation();\n const mapping = new DragAndDropMapping(item, location);\n component.question.correctMappings = [mapping];\n\n component.deleteMapping(mapping);\n\n expect(component.question.correctMappings).to.deep.equal([]);\n });\n\n it('should drop a drag item on a drop location', () => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n const location = new DropLocation();\n const item = new DragItem();\n item.id = 2;\n location.id = 2;\n component.question.dragItems = [item];\n const mapping = new DragAndDropMapping(item, location);\n component.question.correctMappings = [mapping];\n const alternativeLocation = new DropLocation();\n const alternativeItem = new DragItem();\n alternativeLocation.id = 3;\n alternativeItem.id = 3;\n const event = { dragData: alternativeItem };\n const expectedMapping = new DragAndDropMapping(alternativeItem, alternativeLocation);\n component.question.dragItems = [item, alternativeItem];\n\n component.onDragDrop(alternativeLocation, event);\n\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.question.correctMappings).to.deep.equal([mapping, expectedMapping]);\n });\n\n it('should get mapping for drag item', () => {\n const item = new DragItem();\n const location = new DropLocation();\n const mapping = new DragAndDropMapping(item, location);\n component.question.correctMappings = [mapping];\n\n expect(component.getMappingsForDragItem(item)).to.deep.equal([mapping]);\n });\n\n it('should change picture drag item to text drag item', () => {\n const item = new DragItem();\n\n component.changeToTextDragItem(item);\n\n expect(component).to.be.ok;\n });\n\n it('should change text drag item to picture drag item', fakeAsync(() => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n const newPath = 'alwaysGoYourPath';\n const mockReturnValue = Promise.resolve({ path: newPath } as FileUploadResponse);\n spyOn(uploadService, 'uploadFile').and.returnValue(mockReturnValue);\n const item = new DragItem();\n component.dragItemFile = new File([], 'file');\n component.dragItemPicture = 'picturePath';\n\n component.changeToPictureDragItem(item);\n tick();\n\n expect(component.dragItemPicture).to.equal(newPath);\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.isUploadingDragItemFile).to.be.false;\n }));\n\n it('should change question title', () => {\n const title = 'backupQuestionTitle';\n component.question = new DragAndDropQuestion();\n component.question.title = 'alternativeBackupQuestionTitle';\n component.backupQuestion = new DragAndDropQuestion();\n component.backupQuestion.title = title;\n\n component.resetQuestionTitle();\n\n expect(component.question.title).to.equal(title);\n });\n\n it('should reset question', () => {\n const title = 'backupQuestionTitle';\n const dropLocation = new DropLocation();\n const item = new DragItem();\n component.question = new DragAndDropQuestion();\n component.question.title = 'alternativeBackupQuestionTitle';\n\n const backupQuestion = {\n type: 'drag-and-drop',\n randomizeOrder: false,\n invalid: true,\n exportQuiz: false,\n title,\n dropLocations: [dropLocation],\n dragItems: [item],\n correctMappings: [],\n backgroundFilePath: 'filepath',\n text: 'newText',\n explanation: 'explanation',\n hint: 'hint',\n scoringType: ScoringType.ALL_OR_NOTHING,\n } as DragAndDropQuestion;\n component.backupQuestion = backupQuestion;\n\n component.resetQuestion();\n\n expect(component.question).to.deep.equal(backupQuestion);\n });\n\n it('should reset drag item', () => {\n const firstItem = new DragItem();\n firstItem.id = 404;\n firstItem.invalid = true;\n const secondItem = new DragItem();\n secondItem.id = 404;\n secondItem.invalid = false;\n component.question = new DragAndDropQuestion();\n component.question.dragItems = [new DragItem(), new DragItem(), firstItem, new DragItem()];\n component.backupQuestion = new DragAndDropQuestion();\n component.backupQuestion.dragItems = [secondItem];\n\n component.resetDragItem(firstItem);\n\n expect(component.question.dragItems[2].invalid).to.be.false;\n });\n\n it('should reset drop location', () => {\n const firstItem = new DropLocation();\n firstItem.id = 404;\n firstItem.invalid = true;\n const secondItem = new DropLocation();\n secondItem.id = 404;\n secondItem.invalid = false;\n component.question = new DragAndDropQuestion();\n component.question.dropLocations = [new DropLocation(), new DropLocation(), firstItem, new DropLocation()];\n component.backupQuestion = new DragAndDropQuestion();\n component.backupQuestion.dropLocations = [secondItem];\n\n component.resetDropLocation(firstItem);\n\n expect(component.question.dropLocations[2].invalid).to.be.false;\n });\n\n it('should toggle preview', () => {\n component.showPreview = true;\n component.question = new DragAndDropQuestion();\n component.question.text = 'should be removed';\n\n component.togglePreview();\n\n expect(component.showPreview).to.be.false;\n expect(component.question.text).to.be.undefined;\n });\n\n it('should detect changes in markdown and edit accordingly', () => {\n const questionUpdatedSpy = sinon.spy(component.questionUpdated, 'emit');\n component.question = new DragAndDropQuestion();\n component.question.text = 'should be removed';\n\n component.changesInMarkdown();\n\n expect(questionUpdatedSpy).to.have.been.calledOnce;\n expect(component.question.text).to.be.undefined;\n });\n\n it('should detect domain commands', () => {\n component.question = new DragAndDropQuestion();\n component.question.text = 'text';\n component.question.explanation = 'explanation';\n component.question.hint = 'hint';\n let domainCommand: [string, DomainCommand];\n\n // explanation\n let command = new ExplanationCommand();\n let text = 'take this as an explanationCommand';\n domainCommand = [text, command];\n\n component.domainCommandsFound([domainCommand]);\n\n expect(component.question.explanation).to.equal(text);\n\n // hint\n command = new HintCommand();\n text = 'take this as a hintCommand';\n domainCommand = [text, command];\n\n component.domainCommandsFound([domainCommand]);\n\n expect(component.question.hint).to.equal(text);\n\n // text\n text = 'take this null as a command';\n domainCommand = [text, (null as unknown) as DomainCommand];\n\n component.domainCommandsFound([domainCommand]);\n\n expect(component.question.text).to.equal(text);\n });\n});\n" }, { "alpha_fraction": 0.6836460828781128, "alphanum_fraction": 0.684795081615448, "avg_line_length": 41.455284118652344, "blob_id": "59ebe4446c5d9b444cb987dcb78931ee22621e79", "content_id": "cc7c47fd3cc1e0827babe95f7d5717cf09a6d2a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5222, "license_type": "permissive", "max_line_length": 140, "num_lines": 123, "path": "/src/main/webapp/app/exercises/text/assess/text-assessment-area/text-assessment-area.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, HostListener, Input, OnChanges, Output, SimpleChanges } from '@angular/core';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextBlockRef } from 'app/entities/text-block-ref.model';\nimport { StringCountService } from 'app/exercises/text/participate/string-count.service';\nimport { FeedbackConflict, FeedbackConflictType } from 'app/entities/feedback-conflict';\n\n@Component({\n selector: 'jhi-text-assessment-area',\n templateUrl: './text-assessment-area.component.html',\n styles: [\n `\n :host {\n width: 100%;\n }\n `,\n ],\n})\nexport class TextAssessmentAreaComponent implements OnChanges {\n @Input() submission: TextSubmission;\n @Input() textBlockRefs: TextBlockRef[];\n @Input() readOnly: boolean;\n @Input() selectedFeedbackIdWithConflicts?: number;\n @Input() conflictMode: boolean;\n @Input() isLeftConflictingFeedback: boolean;\n @Input() feedbackConflicts: FeedbackConflict[];\n @Output() textBlockRefsChange = new EventEmitter<TextBlockRef[]>();\n @Output() textBlockRefsAddedRemoved = new EventEmitter<void>();\n @Output() onConflictsClicked = new EventEmitter<number>();\n @Output() didSelectConflictingFeedback = new EventEmitter<number>();\n autoTextBlockAssessment = true;\n selectedRef?: TextBlockRef;\n wordCount = 0;\n characterCount = 0;\n isConflictingFeedbackMap?: Map<TextBlockRef, boolean>;\n conflictTypeMap?: Map<TextBlockRef, FeedbackConflictType | undefined>;\n\n constructor(private stringCountService: StringCountService) {\n this.isLeftConflictingFeedback = false;\n }\n\n /**\n * Life cycle hook to indicate component change\n */\n ngOnChanges(changes: SimpleChanges): void {\n if (changes.submission && changes.submission.currentValue) {\n const { text } = changes.submission.currentValue as TextSubmission;\n this.wordCount = this.stringCountService.countWords(text);\n this.characterCount = this.stringCountService.countCharacters(text);\n }\n\n if (changes.textBlockRefs && changes.textBlockRefs.currentValue) {\n this.isConflictingFeedbackMap = new Map(this.textBlockRefs.map((ref) => [ref, this.getIsConflictingFeedback(ref)]));\n this.conflictTypeMap = new Map(this.textBlockRefs.map((ref) => [ref, this.getConflictType(ref)]));\n }\n\n this.textBlockRefs.sort((a, b) => a.block!.startIndex! - b.block!.startIndex!);\n }\n\n @HostListener('document:keydown.alt', ['$event', 'false'])\n @HostListener('document:keyup.alt', ['$event', 'true'])\n onAltToggle($event: KeyboardEvent, toggleValue: boolean) {\n this.autoTextBlockAssessment = toggleValue;\n }\n\n /**\n * Emit the reference change of text blocks\n */\n textBlockRefsChangeEmit(): void {\n this.textBlockRefsChange.emit(this.textBlockRefs);\n }\n\n /**\n * It is called if a text block is added manually.\n * @param ref - added text block\n */\n addTextBlockRef(ref: TextBlockRef): void {\n this.textBlockRefs.push(ref);\n this.textBlockRefsAddedRemoved.emit();\n }\n\n /**\n * It is called if the assessment for a text block is deleted. So, textBlockRef is deleted\n * @param ref - TextBlockRef that has a deleted assessment(feedback).\n */\n removeTextBlockRef(ref: TextBlockRef): void {\n const index = this.textBlockRefs.findIndex((elem) => elem.block!.id! === ref.block!.id!);\n this.textBlockRefs.splice(index, 1);\n this.textBlockRefsAddedRemoved.emit();\n }\n\n /**\n * Checks if the passed TextBlockRef has a conflicting feedback.\n * If this is the left assessment checks the left conflicting feedback id otherwise searches the feedback id inside the conflicts array.\n * Returns false for text-submission-assessment component\n * @param ref - TextBlockRef to check if its feedback is conflicting.\n */\n private getIsConflictingFeedback(ref: TextBlockRef): boolean {\n if (this.isLeftConflictingFeedback && this.selectedFeedbackIdWithConflicts) {\n return this.selectedFeedbackIdWithConflicts === ref.feedback?.id;\n }\n return this.feedbackConflicts?.some((feedbackConflict) => feedbackConflict.conflictingFeedbackId === ref.feedback?.id);\n }\n\n /**\n * Gets FeedbackConflictType from conflicting feedback. Returns undefined for non conflicts.\n * @param ref - TextBlockRef to get FeedbackConflictType of its conflicting feedback.\n */\n private getConflictType(ref: TextBlockRef): FeedbackConflictType | undefined {\n return this.feedbackConflicts?.find((feedbackConflict) => feedbackConflict.conflictingFeedbackId === ref.feedback?.id)?.type;\n }\n\n /**\n * It is called when a text block is selected.\n * If it is in conflict mode and right assessment area, emit feedback id since it is a selected conflict.\n * @param ref - selected TextBlockRef\n */\n didSelectRef(ref: TextBlockRef): void {\n this.selectedRef = ref;\n if (this.conflictMode && !this.isLeftConflictingFeedback) {\n this.didSelectConflictingFeedback.emit(ref?.feedback?.id);\n }\n }\n}\n" }, { "alpha_fraction": 0.5445649027824402, "alphanum_fraction": 0.5469452738761902, "avg_line_length": 35.009525299072266, "blob_id": "981a72181a96888a3fd06d097e961d01e5ca35bf", "content_id": "a8c233b9fc7f1d1febe9a005b9f430dfae1dd7d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3781, "license_type": "permissive", "max_line_length": 136, "num_lines": 105, "path": "/src/main/webapp/app/overview/course-registration-selector/course-registration-selector.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { matchesRegexFully } from 'app/utils/regex.util';\n\n@Component({\n selector: 'jhi-course-registration-selector',\n templateUrl: './course-registration-selector.component.html',\n})\nexport class CourseRegistrationSelectorComponent implements OnInit {\n @Input() courses: Course[];\n @Output() courseRegistered = new EventEmitter();\n public coursesToSelect: Course[] = [];\n public courseToRegister: Course | undefined;\n public userIsAllowedToRegister = false;\n showCourseSelection = false;\n addedSuccessful = false;\n loading = false;\n\n constructor(\n private accountService: AccountService,\n private courseService: CourseManagementService,\n private jhiAlertService: JhiAlertService,\n private profileService: ProfileService,\n ) {}\n\n ngOnInit(): void {\n this.accountService.identity().then((user) => {\n this.profileService.getProfileInfo().subscribe((profileInfo) => {\n if (profileInfo) {\n this.userIsAllowedToRegister = matchesRegexFully(user!.login, profileInfo.allowedCourseRegistrationUsernamePattern);\n }\n });\n });\n }\n\n trackCourseById(index: number, item: Course) {\n return item.id;\n }\n\n loadAndFilterCourses() {\n return new Promise<void>((resolve, reject) => {\n this.courseService.findAllToRegister().subscribe(\n (registerRes) => {\n this.coursesToSelect = registerRes.body!.filter((course) => {\n return !this.courses.find((el) => el.id === course.id);\n });\n resolve();\n },\n (response: string) => reject(response),\n );\n });\n }\n\n startRegistration() {\n this.loading = true;\n this.loadAndFilterCourses()\n .then(() => {\n this.loading = false;\n this.showCourseSelection = true;\n if (this.coursesToSelect.length === 0) {\n setTimeout(() => {\n this.courseToRegister = undefined;\n this.showCourseSelection = false;\n }, 3000);\n }\n })\n .catch(() => {\n this.loading = false;\n this.courseToRegister = undefined;\n this.showCourseSelection = false;\n });\n }\n\n cancelRegistration() {\n this.courseToRegister = undefined;\n this.showCourseSelection = false;\n }\n\n registerForCourse() {\n if (this.courseToRegister) {\n this.showCourseSelection = false;\n this.loading = true;\n this.courseService.registerForCourse(this.courseToRegister.id!).subscribe(\n () => {\n this.addedSuccessful = true;\n this.loading = false;\n setTimeout(() => {\n this.courseToRegister = undefined;\n this.addedSuccessful = false;\n this.coursesToSelect = [];\n }, 3000);\n this.courseRegistered.emit();\n },\n () => {\n this.loading = false;\n this.courseToRegister = undefined;\n },\n );\n }\n }\n}\n" }, { "alpha_fraction": 0.6294273138046265, "alphanum_fraction": 0.6347236037254333, "avg_line_length": 43.10218811035156, "blob_id": "54cb8ef8b62f549144deb96ab9475b3a9794eaf2", "content_id": "d206fcd9da389db6c56c9f8d8ab1e700233d48fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6042, "license_type": "permissive", "max_line_length": 90, "num_lines": 137, "path": "/src/test/javascript/spec/component/rating/rating.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\n\nimport { RatingComponent } from 'app/exercises/shared/rating/rating.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { UserService } from 'app/core/user/user.service';\nimport { MockUserService } from '../../helpers/mocks/service/mock-user.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { RatingModule as StarratingModule, StarRatingComponent } from 'ng-starrating';\nimport { RatingService } from 'app/exercises/shared/rating/rating.service';\nimport { MockRatingService } from '../../helpers/mocks/service/mock-rating.service';\nimport { Result } from 'app/entities/result.model';\nimport { Submission } from 'app/entities/submission.model';\nimport { Rating } from 'app/entities/rating.model';\nimport { of } from 'rxjs';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { Participation } from 'app/entities/participation/participation.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('RatingComponent', () => {\n let ratingComponent: RatingComponent;\n let ratingComponentFixture: ComponentFixture<RatingComponent>;\n let ratingService: RatingService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, StarratingModule],\n declarations: [RatingComponent],\n providers: [\n { provide: RatingService, useClass: MockRatingService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: UserService, useClass: MockUserService },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .compileComponents()\n .then(() => {\n ratingComponentFixture = TestBed.createComponent(RatingComponent);\n ratingComponent = ratingComponentFixture.componentInstance;\n ratingService = TestBed.inject(RatingService);\n\n ratingComponent.result = { id: 89 } as Result;\n ratingComponent.result.submission = { id: 1 } as Submission;\n ratingComponent.result.participation = { id: 1 } as Participation;\n });\n });\n\n it('should get rating', () => {\n sinon.spy(ratingService, 'getRating');\n ratingComponent.ngOnInit();\n expect(ratingService.getRating).to.have.been.calledOnce;\n expect(ratingComponent.result?.id).to.equal(89);\n });\n\n it('should return due to missing result', () => {\n sinon.spy(ratingService, 'getRating');\n delete ratingComponent.result;\n ratingComponent.ngOnInit();\n expect(ratingService.getRating).to.not.have.been.called;\n });\n\n it('should return due to missing participation', () => {\n sinon.spy(ratingService, 'getRating');\n delete ratingComponent.result?.participation;\n ratingComponent.ngOnInit();\n expect(ratingService.getRating).to.not.have.been.called;\n });\n\n it('should create new local rating', () => {\n ratingComponent.ngOnInit();\n expect(ratingComponent.rating.result?.id).to.be.equal(89);\n expect(ratingComponent.rating.rating).to.be.equal(0);\n });\n\n it('should set rating received from server', () => {\n const fake = sinon.fake.returns(of(new Rating({ id: 90 } as Result, 1)));\n sinon.replace(ratingService, 'getRating', fake);\n ratingComponent.ngOnInit();\n expect(ratingComponent.rating.result?.id).to.be.equal(90);\n expect(ratingComponent.rating.rating).to.be.equal(1);\n });\n\n describe('OnRate', () => {\n beforeEach(() => {\n ratingComponent.rating = new Rating({ id: 89 } as Result, 0);\n sinon.spy(ratingService, 'createRating');\n sinon.spy(ratingService, 'updateRating');\n });\n\n it('should return', () => {\n ratingComponent.disableRating = true;\n ratingComponent.onRate({\n oldValue: 0,\n newValue: 2,\n starRating: new StarRatingComponent(),\n });\n expect(ratingService.createRating).to.not.have.been.called;\n expect(ratingService.updateRating).to.not.have.been.called;\n });\n\n it('should create new rating', () => {\n ratingComponent.onRate({\n oldValue: 0,\n newValue: 2,\n starRating: new StarRatingComponent(),\n });\n expect(ratingService.createRating).to.have.been.calledOnce;\n expect(ratingService.updateRating).to.not.have.been.called;\n expect(ratingComponent.rating.result?.id).to.be.equal(89);\n expect(ratingComponent.rating.rating).to.be.equal(2);\n });\n\n it('should update rating', () => {\n ratingComponent.rating.id = 89;\n ratingComponent.onRate({\n oldValue: 0,\n newValue: 2,\n starRating: new StarRatingComponent(),\n });\n expect(ratingService.updateRating).to.have.been.calledOnce;\n expect(ratingService.createRating).to.not.have.been.called;\n expect(ratingComponent.rating.result?.id).to.be.equal(89);\n expect(ratingComponent.rating.rating).to.be.equal(2);\n });\n });\n});\n" }, { "alpha_fraction": 0.7306041717529297, "alphanum_fraction": 0.7306041717529297, "avg_line_length": 47.85483932495117, "blob_id": "5a0ea36346a438abc50c4adb2b4d9146f24084d3", "content_id": "c43d55416c7d116011da5eff8f657620bae7aba8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3029, "license_type": "permissive", "max_line_length": 141, "num_lines": 62, "path": "/src/test/javascript/spec/component/assessment-shared/assessment-layout.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async, ComponentFixture, TestBed } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { AssessmentLayoutComponent } from 'app/assessment/assessment-layout/assessment-layout.component';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { AssessmentHeaderComponent } from 'app/assessment/assessment-header/assessment-header.component';\nimport { AssessmentComplaintAlertComponent } from 'app/assessment/assessment-complaint-alert/assessment-complaint-alert.component';\nimport { ComplaintsForTutorComponent } from 'app/complaints/complaints-for-tutor/complaints-for-tutor.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { Complaint } from 'app/entities/complaint.model';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { RouterTestingModule } from '@angular/router/testing';\n\ndescribe('AssessmentLayoutComponent', () => {\n let component: AssessmentLayoutComponent;\n let fixture: ComponentFixture<AssessmentLayoutComponent>;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule, ArtemisAssessmentSharedModule, RouterTestingModule],\n declarations: [],\n providers: [JhiLanguageHelper],\n }).compileComponents();\n }));\n\n beforeEach(() => {\n fixture = TestBed.createComponent(AssessmentLayoutComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n });\n\n it('should include jhi-alert', () => {\n const jhiAlertComponent = fixture.debugElement.query(By.directive(AlertComponent));\n expect(jhiAlertComponent).toBeTruthy();\n });\n\n it('should include jhi-assessment-header', () => {\n const assessmentHeaderComponent = fixture.debugElement.query(By.directive(AssessmentHeaderComponent));\n expect(assessmentHeaderComponent).toBeTruthy();\n });\n\n it('should include jhi-assessment-complaint-alert', () => {\n const assessmentComplaintAlertComponent = fixture.debugElement.query(By.directive(AssessmentComplaintAlertComponent));\n expect(assessmentComplaintAlertComponent).toBeTruthy();\n });\n\n it('should include jhi-complaints-for-tutor-form', () => {\n let complaintsForTutorComponent = fixture.debugElement.query(By.directive(ComplaintsForTutorComponent));\n expect(complaintsForTutorComponent).toBeFalsy();\n\n component.complaint = new Complaint();\n fixture.detectChanges();\n complaintsForTutorComponent = fixture.debugElement.query(By.directive(ComplaintsForTutorComponent));\n expect(complaintsForTutorComponent).toBeTruthy();\n });\n});\n" }, { "alpha_fraction": 0.6995099186897278, "alphanum_fraction": 0.7007995843887329, "avg_line_length": 37.77000045776367, "blob_id": "2088a515dc1c39c9a35f9309b698d02236854fed", "content_id": "4bcc6fe15198c95e16fdf6259c26a22094f37e58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3877, "license_type": "permissive", "max_line_length": 120, "num_lines": 100, "path": "/src/main/webapp/app/entities/course.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { Moment } from 'moment';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { TutorGroup } from 'app/entities/tutor-group.model';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { Language } from 'app/entities/tutor-group.model';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { Organization } from 'app/entities/organization.model';\n\nexport class Course implements BaseEntity {\n public id?: number;\n public title?: string;\n public description?: string;\n public shortName?: string;\n public studentGroupName?: string;\n public teachingAssistantGroupName?: string;\n public instructorGroupName?: string;\n public startDate?: Moment;\n public endDate?: Moment;\n public semester?: string;\n public testCourse?: boolean;\n public language?: Language;\n public color?: string;\n public courseIcon?: string;\n public onlineCourse?: boolean;\n public registrationEnabled?: boolean;\n public registrationConfirmationMessage?: string;\n public presentationScore?: number;\n public maxComplaints?: number;\n public maxTeamComplaints?: number;\n public maxComplaintTimeDays?: number;\n public complaintsEnabled?: boolean;\n public studentQuestionsEnabled?: boolean;\n public requestMoreFeedbackEnabled?: boolean;\n public maxRequestMoreFeedbackTimeDays?: number;\n\n // the following values are only used in course administration\n public numberOfStudents?: number;\n public numberOfTeachingAssistants?: number;\n public numberOfInstructors?: number;\n\n public exercises?: Exercise[];\n public lectures?: Lecture[];\n public learningGoals?: LearningGoal[];\n public exams?: Exam[];\n public tutorGroups?: TutorGroup[];\n public organizations?: Organization[];\n\n // helper attributes\n public isAtLeastTutor?: boolean;\n public isAtLeastInstructor?: boolean;\n public relativeScore?: number;\n public absoluteScore?: number;\n public maxScore?: number;\n\n public courseArchivePath?: string;\n\n constructor() {\n this.onlineCourse = false; // default value\n this.isAtLeastTutor = false; // default value\n this.isAtLeastInstructor = false; // default value\n\n this.registrationEnabled = false; // default value\n this.presentationScore = 0; // default value\n this.maxComplaints = 3; // default value\n this.maxTeamComplaints = 3; // default value\n this.maxComplaintTimeDays = 7; // default value\n this.complaintsEnabled = true; // default value\n this.studentQuestionsEnabled = true; // default value\n this.requestMoreFeedbackEnabled = true; // default value\n this.maxRequestMoreFeedbackTimeDays = 7; // default value\n }\n\n /**\n * Correctly initializes a class instance from a typecasted object.\n * Returns a 'real' class instance that supports all class methods.\n * @param object: The typecasted object\n * @returns The class instance\n */\n static from(object: Course): Course {\n const course = Object.assign(new Course(), object);\n if (course.exercises) {\n course.exercises.forEach((exercise) => {\n exercise.numberOfSubmissions = Object.assign(new DueDateStat(), exercise.numberOfSubmissions);\n exercise.totalNumberOfAssessments = Object.assign(new DueDateStat(), exercise.totalNumberOfAssessments);\n });\n }\n return course;\n }\n}\n\nexport const enum CourseGroup {\n STUDENTS = 'students',\n TUTORS = 'tutors',\n INSTRUCTORS = 'instructors',\n}\n\nexport const courseGroups = [CourseGroup.STUDENTS, CourseGroup.TUTORS, CourseGroup.INSTRUCTORS];\n" }, { "alpha_fraction": 0.747586190700531, "alphanum_fraction": 0.747586190700531, "avg_line_length": 37.157894134521484, "blob_id": "14359e6e710722c7739207c5b5b3b422feca96fa", "content_id": "2eaac743fcaba90b13aa5279abbc163e73460e20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 725, "license_type": "permissive", "max_line_length": 119, "num_lines": 19, "path": "/src/main/webapp/app/exercises/programming/shared/utils/programming-exercise-simulation-utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\n\n/**\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n\n@Injectable({ providedIn: 'root' })\nexport class ProgrammingExerciseSimulationUtils {\n constructor() {}\n\n /**\n * Checks if the url includes the string \"artemislocalhost', which is an indication\n * that the particular programming exercise is not connected to a version control and continuous integration server\n * @param urlToCheck the url which will be check if it contains the substring\n */\n noVersionControlAndContinuousIntegrationAvailableCheck(urlToCheck: string): boolean {\n return urlToCheck.includes('artemislocalhost');\n }\n}\n" }, { "alpha_fraction": 0.6959778070449829, "alphanum_fraction": 0.7018030285835266, "avg_line_length": 48.38356018066406, "blob_id": "bb32a88da93600e165638dca6887eec015a7f776", "content_id": "ee896da352dc4a056950c87c282523c0457c4871", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7210, "license_type": "permissive", "max_line_length": 164, "num_lines": 146, "path": "/src/test/javascript/spec/component/multiple-choice-question/multiple-choice-question.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MultipleChoiceQuestionComponent } from 'app/exercises/quiz/shared/questions/multiple-choice-question/multiple-choice-question.component';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { NgbPopover, NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { QuizScoringInfoStudentModalComponent } from 'app/exercises/quiz/shared/questions/quiz-scoring-infostudent-modal/quiz-scoring-info-student-modal.component';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('MultipleChoiceQuestionComponent', () => {\n let fixture: ComponentFixture<MultipleChoiceQuestionComponent>;\n let component: MultipleChoiceQuestionComponent;\n let artemisMarkdownService: ArtemisMarkdownService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [\n MultipleChoiceQuestionComponent,\n MockPipe(ArtemisTranslatePipe),\n MockDirective(NgbPopover),\n MockDirective(NgbTooltip),\n MockComponent(QuizScoringInfoStudentModalComponent),\n ],\n providers: [ArtemisMarkdownService],\n }).compileComponents();\n fixture = TestBed.createComponent(MultipleChoiceQuestionComponent);\n component = fixture.componentInstance;\n artemisMarkdownService = TestBed.inject(ArtemisMarkdownService);\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should update rendered question and answer with html when question is set', () => {\n expect(component).to.be.ok;\n\n const question: MultipleChoiceQuestion = {\n id: 1,\n text: 'some-text',\n hint: 'some-hint',\n explanation: 'some-explanation',\n answerOptions: [{ id: 1, explanation: 'answer-explanation', hint: 'answer-hint', text: 'answer-text' }],\n };\n\n component.question = question;\n expect(component.renderedQuestion.text).to.eql(artemisMarkdownService.safeHtmlForMarkdown(question.text));\n expect(component.renderedQuestion.hint).to.eql(artemisMarkdownService.safeHtmlForMarkdown(question.hint));\n expect(component.renderedQuestion.explanation).to.eql(artemisMarkdownService.safeHtmlForMarkdown(question.explanation));\n expect(component.renderedQuestion.renderedSubElements.length).to.equal(1);\n\n const expectedAnswer = question.answerOptions![0];\n const renderedAnswer = component.renderedQuestion.renderedSubElements[0];\n expect(safeHtmlToString(renderedAnswer.text)).to.eql(toHtml(expectedAnswer.text!));\n expect(safeHtmlToString(renderedAnswer.hint)).to.eql(toHtml(expectedAnswer.hint!));\n expect(safeHtmlToString(renderedAnswer.explanation)).to.eql(toHtml(expectedAnswer.explanation!));\n expect(renderedAnswer.renderedSubElements.length).to.equal(0);\n });\n\n it('should update rendered question and answer with empty strings when question/answer values are undefined', () => {\n expect(component).to.be.ok;\n\n const question: MultipleChoiceQuestion = {\n text: 'some-text',\n hint: undefined,\n answerOptions: [{ explanation: 'answer-explanation', text: 'false' }],\n };\n\n component.question = question;\n expect(component.renderedQuestion.text).to.eql(artemisMarkdownService.safeHtmlForMarkdown(question.text));\n expect(component.renderedQuestion.hint).to.equal('');\n expect(component.renderedQuestion.explanation).to.equal('');\n expect(component.renderedQuestion.renderedSubElements.length).to.equal(1);\n\n const expectedAnswer = question.answerOptions![0];\n const renderedAnswer = component.renderedQuestion.renderedSubElements[0];\n expect(safeHtmlToString(renderedAnswer.explanation)).to.equal(toHtml(expectedAnswer.explanation!));\n expect(safeHtmlToString(renderedAnswer.text)).to.equal(toHtml(expectedAnswer.text!));\n expect(safeHtmlToString(renderedAnswer.hint)).to.equal('');\n });\n\n function toHtml(value: string) {\n return `<p>${value}</p>`;\n }\n\n function safeHtmlToString(safeHtml: SafeHtml) {\n return safeHtml['changingThisBreaksApplicationSecurity'] ?? '';\n }\n\n it('should return true is if the answer option was selected', function () {\n const answerOptions: AnswerOption[] = [{ id: 1 }, { id: 2 }, { id: 3 }];\n\n component.selectedAnswerOptions = [answerOptions[0], answerOptions[2]];\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.true;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[2])).to.be.true;\n });\n\n it('should not toggle anything on disabled click', function () {\n const answerOptions: AnswerOption[] = [{ id: 1 }, { id: 2 }, { id: 3 }];\n\n component.clickDisabled = true;\n component.selectedAnswerOptions = [];\n component.toggleSelection(answerOptions[1]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[2])).to.be.false;\n });\n\n it('should toggle answer options', function () {\n const answerOptions: AnswerOption[] = [{ id: 1 }, { id: 2 }];\n\n component.selectedAnswerOptions = [];\n component.toggleSelection(answerOptions[1]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.true;\n\n // Re-toggle\n component.toggleSelection(answerOptions[1]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.false;\n\n component.toggleSelection(answerOptions[1]);\n component.toggleSelection(answerOptions[0]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.true;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.true;\n\n component.toggleSelection(answerOptions[0]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.true;\n\n component.toggleSelection(answerOptions[1]);\n expect(component.isAnswerOptionSelected(answerOptions[0])).to.be.false;\n expect(component.isAnswerOptionSelected(answerOptions[1])).to.be.false;\n });\n});\n" }, { "alpha_fraction": 0.6849315166473389, "alphanum_fraction": 0.6849315166473389, "avg_line_length": 27.38888931274414, "blob_id": "b40460a6883347cf6a010ce11dafd1b39657f2b1", "content_id": "4a250cb9a1a82e02568b53d39ca5415765344265", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 511, "license_type": "permissive", "max_line_length": 56, "num_lines": 18, "path": "/src/main/webapp/app/shared/additional-feedback/additional-feedback.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { round } from '../util/utils';\n\n@Component({\n selector: 'jhi-additional-feedback',\n templateUrl: './additional-feedback.component.html',\n styleUrls: ['./additional-feedback.component.scss'],\n})\nexport class AdditionalFeedbackComponent {\n @Input()\n feedback: Feedback[];\n @Input()\n additional: boolean;\n\n // Expose the function to the template\n readonly round = round;\n}\n" }, { "alpha_fraction": 0.6643799543380737, "alphanum_fraction": 0.6828495860099792, "avg_line_length": 39.319149017333984, "blob_id": "355246c80edd88ae7aacb0346640285e9b121e8c", "content_id": "105c72359c931b772b27e9a07aac5dd2fd206b09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1895, "license_type": "permissive", "max_line_length": 136, "num_lines": 47, "path": "/src/test/javascript/spec/component/plagiarism/plagiarism-run-details.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { SimpleChange } from '@angular/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisPlagiarismModule } from 'app/exercises/shared/plagiarism/plagiarism.module';\nimport { PlagiarismRunDetailsComponent } from 'app/exercises/shared/plagiarism/plagiarism-run-details/plagiarism-run-details.component';\n\ndescribe('Plagiarism Run Details', () => {\n let comp: PlagiarismRunDetailsComponent;\n let fixture: ComponentFixture<PlagiarismRunDetailsComponent>;\n\n const plagiarismResult = {\n duration: 5200,\n similarityDistribution: [24, 18, 16, 13, 7, 9, 5, 4, 0, 1],\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisPlagiarismModule, TranslateTestingModule],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(PlagiarismRunDetailsComponent);\n comp = fixture.componentInstance;\n });\n\n it('updates chart data on changes', () => {\n spyOn(comp, 'updateChartDataSet');\n\n comp.ngOnChanges({\n plagiarismResult: { currentValue: plagiarismResult } as SimpleChange,\n });\n\n expect(comp.updateChartDataSet).toHaveBeenCalled();\n });\n\n it('updates the chart data correctly', () => {\n expect(comp.chartDataSets).toHaveLength(1);\n expect(comp.chartDataSets[0].data).toHaveLength(0);\n\n comp.updateChartDataSet([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);\n\n expect(comp.chartDataSets).toHaveLength(1);\n expect(comp.chartDataSets[0].data).toHaveLength(10);\n });\n});\n" }, { "alpha_fraction": 0.5686314702033997, "alphanum_fraction": 0.5728722214698792, "avg_line_length": 49.246761322021484, "blob_id": "f46cd0b0efc87abb46f1230ca5234b0587d7d108", "content_id": "454c734ca0a193f295805947bf22c3521027acd2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 77581, "license_type": "permissive", "max_line_length": 180, "num_lines": 1544, "path": "/src/test/javascript/spec/component/quiz-exercise/quiz-exercise-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ChangeDetectorRef, EventEmitter, SimpleChange } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';\nimport { ActivatedRoute, convertToParamMap, Router } from '@angular/router';\nimport { expect as jestExpect } from '@jest/globals';\nimport { NgbDate, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { DragItem } from 'app/entities/quiz/drag-item.model';\nimport { DropLocation } from 'app/entities/quiz/drop-location.model';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizQuestion, QuizQuestionType } from 'app/entities/quiz/quiz-question.model';\nimport { ShortAnswerMapping } from 'app/entities/quiz/short-answer-mapping.model';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { ShortAnswerSolution } from 'app/entities/quiz/short-answer-solution.model';\nimport { ShortAnswerSpot } from 'app/entities/quiz/short-answer-spot.model';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { QuizExerciseDetailComponent } from 'app/exercises/quiz/manage/quiz-exercise-detail.component';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { DragAndDropQuestionUtil } from 'app/exercises/quiz/shared/drag-and-drop-question-util.service';\nimport { ShortAnswerQuestionUtil } from 'app/exercises/quiz/shared/short-answer-question-util.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport * as chai from 'chai';\nimport { advanceTo } from 'jest-date-mock';\nimport * as moment from 'moment';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of, throwError } from 'rxjs';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('QuizExercise Management Detail Component', () => {\n let comp: QuizExerciseDetailComponent;\n let exerciseGroupService: ExerciseGroupService;\n let courseManagementService: CourseManagementService;\n let examManagementService: ExamManagementService;\n let quizExerciseService: QuizExerciseService;\n let exerciseService: ExerciseService;\n let fileUploaderService: FileUploaderService;\n let fixture: ComponentFixture<QuizExerciseDetailComponent>;\n let router: Router;\n let alertService: JhiAlertService;\n let dragAndDropQuestionUtil: DragAndDropQuestionUtil;\n let shortAnswerQuestionUtil: ShortAnswerQuestionUtil;\n let changeDetector: ChangeDetectorRef;\n let modalService: NgbModal;\n\n const course: Course = { id: 123 } as Course;\n const quizExercise = new QuizExercise(course, undefined);\n const mcQuestion = new MultipleChoiceQuestion();\n const answerOption = new AnswerOption();\n const exam = new Exam();\n exam.id = 1;\n\n const resetQuizExercise = () => {\n quizExercise.id = 456;\n quizExercise.title = 'test';\n quizExercise.duration = 600;\n answerOption.isCorrect = true;\n mcQuestion.title = 'test';\n mcQuestion.points = 10;\n mcQuestion.answerOptions = [answerOption];\n quizExercise.quizQuestions = [mcQuestion];\n quizExercise.isPlannedToStart = false;\n quizExercise.releaseDate = undefined;\n };\n\n resetQuizExercise();\n\n const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id, exerciseId: quizExercise.id }) } } as any) as ActivatedRoute;\n\n const createValidMCQuestion = () => {\n const question = new MultipleChoiceQuestion();\n question.title = 'test';\n const answerOption1 = new AnswerOption();\n answerOption1.text = 'wrong answer';\n answerOption1.explanation = 'wrong explanation';\n answerOption1.hint = 'wrong hint';\n answerOption1.isCorrect = false;\n const answerOption2 = new AnswerOption();\n answerOption1.text = 'right answer';\n answerOption1.explanation = 'right explanation';\n answerOption1.isCorrect = true;\n question.answerOptions = [answerOption1, answerOption2];\n question.points = 10;\n return { question, answerOption1, answerOption2 };\n };\n\n const createValidDnDQuestion = () => {\n const question = new DragAndDropQuestion();\n question.title = 'test';\n const dragItem1 = new DragItem();\n dragItem1.text = 'dragItem 1';\n dragItem1.pictureFilePath = 'test';\n const dragItem2 = new DragItem();\n dragItem2.text = 'dragItem 1';\n question.dragItems = [dragItem1, dragItem2];\n const dropLocation = new DropLocation();\n dropLocation.posX = 50;\n dropLocation.posY = 60;\n dropLocation.width = 70;\n dropLocation.height = 80;\n question.dropLocations = [dropLocation];\n const correctDragAndDropMapping = new DragAndDropMapping(dragItem1, dropLocation);\n question.correctMappings = [correctDragAndDropMapping];\n question.points = 10;\n return { question, dragItem1, dragItem2, dropLocation, correctDragAndDropMapping };\n };\n\n const createValidSAQuestion = () => {\n const question = new ShortAnswerQuestion();\n question.title = 'test';\n const shortAnswerSolution1 = new ShortAnswerSolution();\n shortAnswerSolution1.text = 'solution 1';\n const shortAnswerSolution2 = new ShortAnswerSolution();\n shortAnswerSolution2.text = 'solution 2';\n question.solutions = [shortAnswerSolution1, shortAnswerSolution2];\n const spot1 = new ShortAnswerSpot();\n spot1.question = question;\n spot1.spotNr = 1;\n spot1.width = 50;\n const spot2 = new ShortAnswerSpot();\n spot2.question = question;\n spot2.spotNr = 2;\n spot2.width = 70;\n question.spots = [spot1, spot2];\n const shortAnswerMapping1 = new ShortAnswerMapping(spot1, shortAnswerSolution1);\n const shortAnswerMapping2 = new ShortAnswerMapping(spot2, shortAnswerSolution2);\n question.correctMappings = [shortAnswerMapping1, shortAnswerMapping2];\n question.points = 10;\n return { question, shortAnswerMapping1, shortAnswerMapping2, spot1, spot2, shortAnswerSolution1, shortAnswerSolution2 };\n };\n\n const configureTestBed = (testRoute?: ActivatedRoute) => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [QuizExerciseDetailComponent],\n providers: [\n NgbModal,\n ChangeDetectorRef,\n { provide: ActivatedRoute, useValue: testRoute || route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: Router, useClass: MockRouter },\n ],\n })\n .overrideTemplate(QuizExerciseDetailComponent, '')\n .compileComponents();\n };\n\n const configureFixtureAndServices = () => {\n fixture = TestBed.createComponent(QuizExerciseDetailComponent);\n comp = fixture.componentInstance;\n courseManagementService = fixture.debugElement.injector.get(CourseManagementService);\n examManagementService = fixture.debugElement.injector.get(ExamManagementService);\n quizExerciseService = fixture.debugElement.injector.get(QuizExerciseService);\n router = fixture.debugElement.injector.get(Router);\n fileUploaderService = TestBed.inject(FileUploaderService);\n alertService = fixture.debugElement.injector.get(JhiAlertService);\n dragAndDropQuestionUtil = fixture.debugElement.injector.get(DragAndDropQuestionUtil);\n shortAnswerQuestionUtil = fixture.debugElement.injector.get(ShortAnswerQuestionUtil);\n changeDetector = fixture.debugElement.injector.get(ChangeDetectorRef);\n exerciseGroupService = fixture.debugElement.injector.get(ExerciseGroupService);\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n modalService = fixture.debugElement.injector.get(NgbModal);\n };\n\n describe('OnInit', () => {\n let quizExerciseServiceStub: SinonStub;\n let courseManagementServiceStub: SinonStub;\n let exerciseGroupServiceStub: SinonStub;\n let initStub: SinonStub;\n const configureStubs = () => {\n quizExerciseServiceStub = stub(quizExerciseService, 'find');\n courseManagementServiceStub = stub(courseManagementService, 'find');\n exerciseGroupServiceStub = stub(exerciseGroupService, 'find');\n initStub = stub(comp, 'init');\n quizExerciseServiceStub.returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n courseManagementServiceStub.returns(\n of(\n new HttpResponse<Course>({ body: course }),\n ),\n );\n exerciseGroupServiceStub.returns(\n of(\n new HttpResponse<ExerciseGroup>({ body: undefined }),\n ),\n );\n };\n\n const restoreStubs = () => {\n quizExerciseServiceStub.restore();\n courseManagementServiceStub.restore();\n exerciseGroupServiceStub.restore();\n initStub.restore();\n };\n\n describe('without exam id', () => {\n beforeEach(waitForAsync(configureTestBed));\n beforeEach(configureFixtureAndServices);\n it('Should call courseExerciseService.find and quizExerciseService.find', () => {\n // GIVEN\n configureStubs();\n // WHEN\n comp.course = course;\n comp.ngOnInit();\n\n // THEN\n expect(quizExerciseServiceStub).to.have.been.called;\n expect(courseManagementServiceStub).to.have.been.called;\n expect(exerciseGroupServiceStub).to.not.have.been.called;\n expect(initStub).to.have.been.called;\n });\n afterEach(() => {\n restoreStubs();\n });\n });\n\n describe('with exam id', () => {\n const testRoute = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id, exerciseId: quizExercise.id, examId: 1, groupId: 2 }) } } as any) as ActivatedRoute;\n beforeEach(waitForAsync(() => configureTestBed(testRoute)));\n beforeEach(configureFixtureAndServices);\n it('should call exerciseGroupService.find', () => {\n configureStubs();\n comp.course = course;\n comp.ngOnInit();\n expect(quizExerciseServiceStub).to.have.been.called;\n expect(courseManagementServiceStub).to.have.been.called;\n expect(exerciseGroupServiceStub).to.have.been.called;\n expect(initStub).to.have.been.called;\n });\n afterEach(() => {\n restoreStubs();\n });\n });\n describe('with exam id but without exercise id', () => {\n const testRoute = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id, examId: 1, groupId: 2 }) } } as any) as ActivatedRoute;\n beforeEach(waitForAsync(() => configureTestBed(testRoute)));\n beforeEach(configureFixtureAndServices);\n it('should call exerciseGroupService.find', () => {\n configureStubs();\n comp.course = course;\n comp.ngOnInit();\n expect(quizExerciseServiceStub).not.to.have.been.called;\n expect(courseManagementServiceStub).to.have.been.called;\n expect(exerciseGroupServiceStub).to.have.been.called;\n expect(initStub).to.have.been.called;\n });\n afterEach(() => {\n restoreStubs();\n });\n });\n describe('without exam id and exercise id', () => {\n const testRoute = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute;\n beforeEach(waitForAsync(() => configureTestBed(testRoute)));\n beforeEach(configureFixtureAndServices);\n it('should call exerciseGroupService.find', () => {\n configureStubs();\n comp.course = course;\n comp.ngOnInit();\n expect(quizExerciseServiceStub).not.to.have.been.called;\n expect(courseManagementServiceStub).to.have.been.called;\n expect(exerciseGroupServiceStub).not.to.have.been.called;\n expect(initStub).to.have.been.called;\n });\n afterEach(() => {\n restoreStubs();\n });\n });\n });\n\n describe('without routeChange', () => {\n beforeEach(waitForAsync(configureTestBed));\n beforeEach(configureFixtureAndServices);\n\n describe('init', () => {\n let exerciseServiceCategoriesStub: SinonStub;\n let exerciseServiceCategoriesAsStringStub: SinonStub;\n let courseServiceStub: SinonStub;\n const testExerciseCategories = [\n { exerciseId: 1, category: 'category1', color: 'color1' },\n { exerciseId: 2, category: 'category2', color: 'color2' },\n ];\n const testExistingCategories = [\n { exerciseId: 1, category: 'eCategory1', color: 'eColor1' },\n { exerciseId: 2, category: 'eCategory2', color: 'eColor2' },\n ];\n let prepareEntitySpy: SinonSpy;\n let alertServiceStub: SinonStub;\n beforeEach(() => {\n comp.course = course;\n exerciseServiceCategoriesStub = stub(exerciseService, 'convertExerciseCategoriesFromServer');\n exerciseServiceCategoriesStub.returns(testExerciseCategories);\n courseServiceStub = stub(courseManagementService, 'findAllCategoriesOfCourse');\n courseServiceStub.returns(\n of(\n new HttpResponse<string[]>({ body: ['category1', 'category2'] }),\n ),\n );\n exerciseServiceCategoriesAsStringStub = stub(exerciseService, 'convertExerciseCategoriesAsStringFromServer');\n exerciseServiceCategoriesAsStringStub.returns(testExistingCategories);\n prepareEntitySpy = spy(comp, 'prepareEntity');\n alertServiceStub = stub(alertService, 'error');\n });\n\n it('should set quizExercise to entity if quiz exercise not defined', () => {\n expect(comp.quizExercise).to.equal(undefined);\n comp.init();\n expect(comp.quizExercise).to.not.equal(undefined);\n expect(prepareEntitySpy).to.have.been.calledWith(comp.quizExercise);\n expect(comp.savedEntity).to.deep.equal(new QuizExercise(undefined, undefined));\n expect(comp.quizExercise.course).to.deep.equal(course);\n expect(exerciseServiceCategoriesStub).to.have.been.calledWith(comp.quizExercise);\n expect(comp.exerciseCategories).to.deep.equal(testExerciseCategories);\n expect(courseServiceStub).to.have.been.calledWith(course.id);\n });\n it('should set entity to quiz exercise if quiz exercise defined', () => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n comp.quizExercise.course = course;\n expect(comp.entity).to.equal(undefined);\n comp.init();\n expect(comp.entity).to.equal(quizExercise);\n expect(prepareEntitySpy).to.have.been.calledWith(comp.quizExercise);\n expect(comp.savedEntity).to.deep.equal(quizExercise);\n });\n\n it('should set quizExercise exercise group if exam and it does not have one', () => {\n comp.isExamMode = true;\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n expect(comp.quizExercise.exerciseGroup).to.equal(undefined);\n comp.exerciseGroup = new ExerciseGroup();\n comp.init();\n expect(comp.quizExercise.exerciseGroup).to.deep.equal(comp.exerciseGroup);\n });\n it('should call on error if course service fails', () => {\n courseServiceStub.returns(throwError({ status: 404 }));\n comp.init();\n expect(alertServiceStub).to.have.been.called;\n });\n });\n describe('onDurationChange', () => {\n // setup\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('Should update duration and quizExercise.duration with same values', () => {\n comp.duration = { minutes: 15, seconds: 30 };\n comp.onDurationChange();\n\n // compare duration with quizExercise.duration\n const durationAsSeconds = moment.duration(comp.duration).asSeconds();\n expect(durationAsSeconds).to.equal(comp.quizExercise.duration);\n });\n\n it('Should increase minutes when reaching 60 seconds', () => {\n comp.duration = { minutes: 0, seconds: 60 };\n comp.onDurationChange();\n\n expect(comp.duration.minutes).to.equal(1);\n expect(comp.duration.seconds).to.equal(0);\n });\n\n it('Should decrease minutes when reaching -1 seconds', () => {\n comp.duration = { minutes: 1, seconds: -1 };\n comp.onDurationChange();\n\n expect(comp.duration.minutes).to.equal(0);\n expect(comp.duration.seconds).to.equal(59);\n });\n\n it('Should set duration to due date release date difference', () => {\n comp.isExamMode = true;\n comp.quizExercise.releaseDate = moment();\n comp.quizExercise.dueDate = moment().add(1530, 's');\n comp.onDurationChange();\n expect(comp.quizExercise.duration).to.equal(1530);\n comp.isExamMode = false;\n });\n });\n\n describe('ngOnChanges', () => {\n it('should call init if there are changes on course or quiz exercise', () => {\n const change = new SimpleChange(0, 1, false);\n const initStub = stub(comp, 'init');\n comp.ngOnChanges({ course: change });\n expect(initStub).to.have.been.called;\n initStub.reset();\n comp.ngOnChanges({ quizExercise: change });\n expect(initStub).to.have.been.called;\n initStub.reset();\n comp.ngOnChanges({ course: change, quizExercise: change });\n expect(initStub).to.have.been.called;\n initStub.reset();\n comp.ngOnChanges({});\n expect(initStub).to.not.have.been.called;\n initStub.reset();\n });\n });\n\n describe('updateCategories', () => {\n it('should update categories to given categories', () => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n const exerciseCategory1 = { exerciseId: 1, category: 'category1', color: 'color1' };\n const exerciseCategory2 = { exerciseId: 1, category: 'category1', color: 'color1' };\n const expected = [JSON.stringify(exerciseCategory1), JSON.stringify(exerciseCategory2)];\n comp.updateCategories([exerciseCategory1, exerciseCategory2]);\n expect(comp.quizExercise.categories).to.deep.equal(expected);\n });\n });\n\n describe('show dropdown', () => {\n const resetQuizExerciseAndSet = () => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n comp.quizExercise.isPlannedToStart = true;\n };\n it('should return isVisibleBeforeStart if no quizExercise', () => {\n expect(comp.quizExercise).to.equal(undefined);\n expect(comp.showDropdown).to.equal('isVisibleBeforeStart');\n });\n it('should return isVisibleBeforeStart if quizExercise not planned to start', () => {\n resetQuizExerciseAndSet();\n comp.quizExercise.isPlannedToStart = false;\n expect(comp.showDropdown).to.equal('isVisibleBeforeStart');\n });\n it('should return if end of exercise is in the past', () => {\n resetQuizExerciseAndSet();\n comp.quizExercise.releaseDate = moment().subtract(20, 's');\n comp.quizExercise.duration = 10;\n expect(comp.showDropdown).to.equal('isOpenForPractice');\n });\n it('should return if end of exercise is in the future but release date is in the past', () => {\n resetQuizExerciseAndSet();\n comp.quizExercise.releaseDate = moment().subtract(20, 's');\n comp.quizExercise.duration = 50;\n expect(comp.showDropdown).to.equal('active');\n });\n });\n\n describe('unloading notification and can deactivate', () => {\n it('should return opposite of pendingChangesCache', () => {\n comp.pendingChangesCache = true;\n expect(comp.canDeactivate()).to.equal(false);\n comp.pendingChangesCache = false;\n expect(comp.canDeactivate()).to.equal(true);\n });\n it('should set event return value to translate if not canDeactivate', () => {\n comp.pendingChangesCache = true;\n const ev = { returnValue: undefined };\n comp.unloadNotification(ev);\n expect(ev.returnValue).to.equal('pendingChanges');\n });\n it('should not set event return value to translate if canDeactivate', () => {\n comp.pendingChangesCache = false;\n const ev = { returnValue: undefined };\n comp.unloadNotification(ev);\n expect(ev.returnValue).to.equal(undefined);\n });\n });\n\n describe('check if date is in the past', () => {\n let tomorrow: NgbDate;\n beforeEach(() => {\n tomorrow = new NgbDate(2020, 11, 16);\n // advanceTo 2020 11 15\n // moment adds one month\n advanceTo(new Date(2020, 10, 15, 0, 0, 0));\n });\n it('should return true if given month is before month we are in', () => {\n expect(comp.isDateInPast(tomorrow, { month: 10 })).to.equal(true);\n });\n it('should return false if given month is same or after month we are in', () => {\n expect(comp.isDateInPast(tomorrow, { month: 11 })).to.equal(false);\n });\n it('should return true if given date is before now', () => {\n const past = new NgbDate(2020, 11, 10);\n expect(comp.isDateInPast(past, { month: 11 })).to.equal(true);\n });\n it('should return false if given date is before now', () => {\n expect(comp.isDateInPast(tomorrow, { month: 11 })).to.equal(false);\n });\n });\n\n describe('add questions', () => {\n // setup\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('should add empty MC question', () => {\n const amountQuizQuestions = comp.quizExercise.quizQuestions?.length || 0;\n comp.addMultipleChoiceQuestion();\n\n expect(comp.quizExercise.quizQuestions).to.have.lengthOf(amountQuizQuestions + 1);\n expect(comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1].type).to.equal(QuizQuestionType.MULTIPLE_CHOICE);\n });\n\n it('should add empty DnD question', () => {\n const amountQuizQuestions = comp.quizExercise.quizQuestions?.length || 0;\n comp.addDragAndDropQuestion();\n\n expect(comp.quizExercise.quizQuestions).to.have.lengthOf(amountQuizQuestions + 1);\n expect(comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1].type).to.equal(QuizQuestionType.DRAG_AND_DROP);\n });\n\n it('should add empty SA question', () => {\n const amountQuizQuestions = comp.quizExercise.quizQuestions?.length || 0;\n comp.addShortAnswerQuestion();\n\n expect(comp.quizExercise.quizQuestions).to.have.lengthOf(amountQuizQuestions + 1);\n expect(comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1].type).to.equal(QuizQuestionType.SHORT_ANSWER);\n });\n\n afterAll(() => {\n resetQuizExercise();\n });\n });\n\n describe('add questions without quizExercise', () => {\n beforeEach(() => {\n comp.entity = quizExercise;\n });\n\n it('should set quiz exercise to entity when adding MC question', () => {\n expect(comp.quizExercise).to.equal(undefined);\n comp.addMultipleChoiceQuestion();\n expect(comp.quizExercise).to.deep.equal(comp.entity);\n });\n\n it('should set quiz exercise to entity when adding Dnd question', () => {\n expect(comp.quizExercise).to.equal(undefined);\n comp.addDragAndDropQuestion();\n expect(comp.quizExercise).to.deep.equal(comp.entity);\n });\n it('should set quiz exercise to entity when adding SA question', () => {\n expect(comp.quizExercise).to.equal(undefined);\n comp.addShortAnswerQuestion();\n expect(comp.quizExercise).to.deep.equal(comp.entity);\n });\n });\n\n describe('calculating max exercise score', () => {\n it('should return sum of scores of the questions', () => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n const { question: multiQuestion } = createValidMCQuestion();\n multiQuestion.points = 1;\n comp.quizExercise.quizQuestions = [multiQuestion];\n expect(comp.calculateMaxExerciseScore()).to.equal(1);\n const { question: dndQuestion } = createValidDnDQuestion();\n dndQuestion.points = 2;\n comp.quizExercise.quizQuestions = [multiQuestion, dndQuestion];\n expect(comp.calculateMaxExerciseScore()).to.equal(3);\n const { question: saQuestion } = createValidSAQuestion();\n saQuestion.points = 3;\n comp.quizExercise.quizQuestions = [multiQuestion, dndQuestion, saQuestion];\n expect(comp.calculateMaxExerciseScore()).to.equal(6);\n });\n });\n\n describe('add existing questions', () => {\n it('should add questions with export quiz option and call import', () => {\n comp.showExistingQuestions = true;\n const { question: exportedQuestion } = createValidMCQuestion();\n exportedQuestion.title = 'exported';\n exportedQuestion.exportQuiz = true;\n const { question: notExportedQuestion } = createValidMCQuestion();\n notExportedQuestion.title = 'notExported';\n notExportedQuestion.exportQuiz = false;\n comp.existingQuestions = [exportedQuestion, notExportedQuestion];\n const verifyAndImportQuestionsStub = stub(comp, 'verifyAndImportQuestions');\n const cacheValidationStub = stub(comp, 'cacheValidation');\n comp.addExistingQuestions();\n expect(verifyAndImportQuestionsStub).to.have.been.calledWithExactly([exportedQuestion]);\n expect(cacheValidationStub).to.have.been.called;\n expect(comp.showExistingQuestions).to.equal(false);\n expect(comp.showExistingQuestionsFromCourse).to.equal(true);\n expect(comp.selectedCourseId).to.equal(undefined);\n expect(comp.allExistingQuestions).to.deep.equal([]);\n expect(comp.existingQuestions).to.deep.equal([]);\n verifyAndImportQuestionsStub.restore();\n cacheValidationStub.restore();\n });\n describe('applyFilter', () => {\n const { question: multiChoiceQuestion } = createValidMCQuestion();\n const { question: dndQuestion } = createValidDnDQuestion();\n const { question: shortQuestion } = createValidSAQuestion();\n beforeEach(() => {\n comp.allExistingQuestions = [multiChoiceQuestion, dndQuestion, shortQuestion];\n comp.mcqFilterEnabled = false;\n comp.dndFilterEnabled = false;\n comp.shortAnswerFilterEnabled = false;\n comp.searchQueryText = '';\n });\n it('should put mc question when mc filter selected', () => {\n comp.mcqFilterEnabled = true;\n comp.applyFilter();\n expect(comp.existingQuestions).to.deep.equal([multiChoiceQuestion]);\n });\n it('should put mc question when dnd filter selected', () => {\n comp.dndFilterEnabled = true;\n comp.applyFilter();\n expect(comp.existingQuestions).to.deep.equal([dndQuestion]);\n });\n\n it('should put mc question when sa filter selected', () => {\n comp.shortAnswerFilterEnabled = true;\n comp.applyFilter();\n expect(comp.existingQuestions).to.deep.equal([shortQuestion]);\n });\n\n it('should put all if all selected', () => {\n comp.mcqFilterEnabled = true;\n comp.dndFilterEnabled = true;\n comp.shortAnswerFilterEnabled = true;\n comp.applyFilter();\n expect(comp.existingQuestions).to.deep.equal(comp.allExistingQuestions);\n });\n });\n describe('select course', () => {\n let quizExerciseServiceFindForCourseStub: SinonStub;\n let quizExerciseServiceFindStub: SinonStub;\n beforeEach(() => {\n comp.allExistingQuestions = [];\n comp.courses = [course];\n comp.selectedCourseId = course.id;\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n quizExerciseServiceFindForCourseStub = stub(quizExerciseService, 'findForCourse');\n quizExerciseServiceFindForCourseStub.returns(\n of(\n new HttpResponse<QuizExercise[]>({ body: [quizExercise] }),\n ),\n );\n quizExerciseServiceFindStub = stub(quizExerciseService, 'find');\n quizExerciseServiceFindStub.returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n });\n\n afterEach(() => {\n quizExerciseServiceFindForCourseStub.reset();\n quizExerciseServiceFindStub.reset();\n });\n it('should call find course with selected id', () => {\n comp.onCourseSelect();\n expect(quizExerciseServiceFindForCourseStub).to.have.been.calledWithExactly(comp.selectedCourseId);\n expect(quizExerciseServiceFindStub).to.have.been.calledWithExactly(quizExercise.id);\n expect(comp.allExistingQuestions).to.deep.equal(quizExercise.quizQuestions);\n });\n it('should not call find course without selected id', () => {\n comp.selectedCourseId = undefined;\n comp.onCourseSelect();\n expect(quizExerciseServiceFindForCourseStub).to.not.have.been.called;\n expect(quizExerciseServiceFindStub).to.not.have.been.called;\n });\n it('should call alert service if fails', () => {\n quizExerciseServiceFindForCourseStub.returns(throwError({ status: 404 }));\n console.error = jest.fn();\n let alertServiceStub: SinonStub;\n alertServiceStub = stub(alertService, 'error');\n comp.onCourseSelect();\n expect(alertServiceStub).to.have.been.called;\n });\n afterAll(() => {\n quizExerciseServiceFindForCourseStub.restore();\n quizExerciseServiceFindStub.restore();\n });\n });\n describe('select exam', () => {\n let quizExerciseServiceFindForExamStub: SinonStub;\n let quizExerciseServiceFindStub: SinonStub;\n const exerciseGroup = new ExerciseGroup();\n\n beforeEach(() => {\n comp.allExistingQuestions = [];\n exerciseGroup.exam = exam;\n quizExercise.exerciseGroup = exerciseGroup;\n comp.exams = [exam];\n comp.selectedExamId = exam.id;\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n quizExerciseServiceFindForExamStub = stub(quizExerciseService, 'findForExam');\n quizExerciseServiceFindForExamStub.returns(\n of(\n new HttpResponse<QuizExercise[]>({ body: [quizExercise] }),\n ),\n );\n quizExerciseServiceFindStub = stub(quizExerciseService, 'find');\n quizExerciseServiceFindStub.returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n });\n\n afterEach(() => {\n quizExerciseServiceFindForExamStub.reset();\n quizExerciseServiceFindStub.reset();\n });\n it('should call find exam with selected id', () => {\n comp.onExamSelect();\n expect(quizExerciseServiceFindForExamStub).to.have.been.calledWithExactly(comp.selectedExamId);\n expect(quizExerciseServiceFindStub).to.have.been.calledWithExactly(quizExercise.id);\n expect(comp.allExistingQuestions).to.deep.equal(quizExercise.quizQuestions);\n });\n it('should not call find exam without selected id', () => {\n comp.selectedExamId = undefined;\n comp.onExamSelect();\n expect(quizExerciseServiceFindForExamStub).to.not.have.been.called;\n expect(quizExerciseServiceFindStub).to.not.have.been.called;\n });\n it('should call alert service if fails', () => {\n quizExerciseServiceFindForExamStub.returns(throwError({ status: 404 }));\n console.error = jest.fn();\n let alertServiceStub: SinonStub;\n alertServiceStub = stub(alertService, 'error');\n comp.onExamSelect();\n expect(alertServiceStub).to.have.been.called;\n });\n afterAll(() => {\n quizExerciseServiceFindForExamStub.restore();\n quizExerciseServiceFindStub.restore();\n });\n });\n });\n describe('delete questions', () => {\n const deleteQuestionAndExpect = () => {\n const amountQuizQuestions = comp.quizExercise.quizQuestions?.length || 0;\n const questionToDelete = comp.quizExercise.quizQuestions![amountQuizQuestions - 1];\n comp.deleteQuestion(questionToDelete);\n expect(comp.quizExercise.quizQuestions).to.have.lengthOf(amountQuizQuestions - 1);\n expect(comp.quizExercise.quizQuestions?.filter((question) => question === questionToDelete));\n };\n // setup\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('should delete MC question', () => {\n comp.addMultipleChoiceQuestion();\n deleteQuestionAndExpect();\n });\n\n it('should delete DnD question', () => {\n comp.addDragAndDropQuestion();\n deleteQuestionAndExpect();\n });\n\n it('should delete SA question', () => {\n comp.addShortAnswerQuestion();\n deleteQuestionAndExpect();\n });\n });\n\n describe('updating question', () => {\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n it('should replace quiz questions with copy of it', () => {\n const cacheValidationStub = stub(comp, 'cacheValidation');\n comp.onQuestionUpdated();\n expect(cacheValidationStub).to.have.been.called;\n expect(comp.quizExercise.quizQuestions).to.deep.equal(Array.from(comp.quizExercise.quizQuestions!));\n cacheValidationStub.restore();\n });\n });\n\n describe('import questions', () => {\n const importQuestionAndExpectOneMoreQuestionInQuestions = (question: QuizQuestion, withTick: boolean) => {\n const amountQuizQuestions = comp.quizExercise.quizQuestions?.length || 0;\n comp.verifyAndImportQuestions([question]);\n if (withTick) {\n tick();\n }\n expect(comp.quizExercise.quizQuestions).to.have.lengthOf(amountQuizQuestions + 1);\n };\n // setup\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('should set import file correctly', () => {\n const file = new File(['content'], 'testFileName', { type: 'text/plain' });\n const ev = { target: { files: [file] } };\n const changeDetectorDetectChangesStub = stub(changeDetector.constructor.prototype, 'detectChanges');\n comp.setImportFile(ev);\n expect(comp.importFile).to.deep.equal(file);\n expect(comp.importFileName).to.equal('testFileName');\n expect(changeDetectorDetectChangesStub).to.have.been.called;\n changeDetectorDetectChangesStub.restore();\n });\n\n it('should import MC question ', () => {\n const { question, answerOption1, answerOption2 } = createValidMCQuestion();\n importQuestionAndExpectOneMoreQuestionInQuestions(question, false);\n const lastAddedQuestion = comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1] as MultipleChoiceQuestion;\n expect(lastAddedQuestion.type).to.equal(QuizQuestionType.MULTIPLE_CHOICE);\n expect(lastAddedQuestion.answerOptions).to.have.lengthOf(2);\n expect(lastAddedQuestion.answerOptions![0]).to.deep.equal(answerOption1);\n expect(lastAddedQuestion.answerOptions![1]).to.deep.equal(answerOption2);\n });\n\n it('should import DnD question', fakeAsync(() => {\n const { question, dragItem1, dragItem2, dropLocation } = createValidDnDQuestion();\n\n // mock fileUploaderService\n spyOn(fileUploaderService, 'duplicateFile').and.returnValue(Promise.resolve({ path: 'test' }));\n importQuestionAndExpectOneMoreQuestionInQuestions(question, true);\n const lastAddedQuestion = comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1] as DragAndDropQuestion;\n expect(lastAddedQuestion.type).to.equal(QuizQuestionType.DRAG_AND_DROP);\n expect(lastAddedQuestion.correctMappings).to.have.lengthOf(1);\n expect(lastAddedQuestion.dragItems![0]).to.deep.equal(dragItem1);\n expect(lastAddedQuestion.dragItems![1]).to.deep.equal(dragItem2);\n expect(lastAddedQuestion.dropLocations![0]).to.deep.equal(dropLocation);\n expect(lastAddedQuestion.dragItems![0].pictureFilePath).to.equal('test');\n expect(lastAddedQuestion.dragItems![1].pictureFilePath).to.equal(undefined);\n }));\n\n it('should import SA question', () => {\n const { question, shortAnswerMapping1, shortAnswerMapping2, spot1, spot2, shortAnswerSolution1, shortAnswerSolution2 } = createValidSAQuestion();\n importQuestionAndExpectOneMoreQuestionInQuestions(question, false);\n const lastAddedQuestion = comp.quizExercise.quizQuestions![comp.quizExercise.quizQuestions!.length - 1] as ShortAnswerQuestion;\n expect(lastAddedQuestion.type).to.equal(QuizQuestionType.SHORT_ANSWER);\n expect(lastAddedQuestion.correctMappings).to.have.lengthOf(2);\n expect(lastAddedQuestion.correctMappings![0]).to.deep.equal(shortAnswerMapping1);\n expect(lastAddedQuestion.correctMappings![1]).to.deep.equal(shortAnswerMapping2);\n expect(lastAddedQuestion.spots).to.have.lengthOf(2);\n expect(lastAddedQuestion.spots![0]).to.equal(spot1);\n expect(lastAddedQuestion.spots![1]).to.equal(spot2);\n expect(lastAddedQuestion.solutions).to.have.lengthOf(2);\n expect(lastAddedQuestion.solutions![0]).to.equal(shortAnswerSolution1);\n expect(lastAddedQuestion.solutions![1]).to.equal(shortAnswerSolution2);\n });\n });\n\n describe('quiz validity', () => {\n // setup\n\n const removeQuestionTitleAndExpectInvalidQuiz = (question: QuizQuestion) => {\n question.title = '';\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n };\n\n const removeCorrectMappingsAndExpectInvalidQuiz = (question: DragAndDropQuestion | ShortAnswerQuestion) => {\n question.correctMappings = [];\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n };\n\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('should be valid with default test setting', () => {\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(true);\n });\n\n it('should not be valid without a quiz title', () => {\n quizExercise.title = '';\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n });\n\n describe('unknown question type', () => {\n let question: MultipleChoiceQuestion;\n beforeEach(() => {\n const multiChoiceQuestion = createValidMCQuestion();\n question = multiChoiceQuestion.question;\n question.type = undefined;\n comp.quizExercise.quizQuestions = [question];\n });\n\n it('should be valid if a question has unknown type and a title', () => {\n question.title = 'test';\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(true);\n });\n it('should not be valid if a question has unknown type and no title', () => {\n question.title = '';\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n });\n });\n\n it('should not be valid if a question has negative score', () => {\n const { question } = createValidMCQuestion();\n question.points = -1;\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n });\n\n it('should be valid with valid MC question', () => {\n const { question } = createValidMCQuestion();\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(true);\n });\n\n it('should not be valid if MC question has no title', () => {\n const { question } = createValidMCQuestion();\n removeQuestionTitleAndExpectInvalidQuiz(question);\n });\n\n it('should not be valid if MC question has no correct answer', () => {\n const { question } = createValidMCQuestion();\n question.answerOptions = [];\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(false);\n });\n\n it('should be valid with valid DnD question', () => {\n const { question } = createValidDnDQuestion();\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(true);\n });\n\n it('should not be valid if DnD question has no title', () => {\n const { question } = createValidDnDQuestion();\n removeQuestionTitleAndExpectInvalidQuiz(question);\n });\n\n it('should not be valid if DnD question has no correct mapping', () => {\n const { question } = createValidDnDQuestion();\n removeCorrectMappingsAndExpectInvalidQuiz(question);\n });\n\n it('should be valid with valid SA question', () => {\n const { question } = createValidSAQuestion();\n comp.quizExercise.quizQuestions = [question];\n comp.cacheValidation();\n expect(comp.quizIsValid).to.equal(true);\n });\n\n it('should not be valid if SA question has no title', () => {\n const { question } = createValidSAQuestion();\n removeQuestionTitleAndExpectInvalidQuiz(question);\n });\n\n it('should not be valid if SA question has no correct mapping', () => {\n const { question } = createValidSAQuestion();\n removeCorrectMappingsAndExpectInvalidQuiz(question);\n });\n });\n\n describe('saving', () => {\n let quizExerciseServiceCreateStub: SinonStub;\n let quizExerciseServiceUpdateStub: SinonStub;\n let exerciseStub: SinonStub;\n const saveQuizWithPendingChangesCache = () => {\n comp.cacheValidation();\n comp.pendingChangesCache = true;\n comp.save();\n };\n\n const saveAndExpectAlertService = () => {\n console.error = jest.fn();\n let alertServiceStub: SinonStub;\n alertServiceStub = stub(alertService, 'error');\n saveQuizWithPendingChangesCache();\n expect(alertServiceStub).to.have.been.called;\n expect(comp.isSaving).to.equal(false);\n jestExpect(console.error).toHaveBeenCalled();\n };\n\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n quizExerciseServiceCreateStub = stub(quizExerciseService, 'create');\n quizExerciseServiceCreateStub.returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n quizExerciseServiceUpdateStub = stub(quizExerciseService, 'update');\n quizExerciseServiceUpdateStub.returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n exerciseStub = stub(Exercise, 'sanitize');\n });\n\n afterEach(() => {\n quizExerciseServiceCreateStub.restore();\n quizExerciseServiceUpdateStub.restore();\n exerciseStub.restore();\n });\n\n it('should call create if valid and quiz exercise no id', () => {\n comp.quizExercise.id = undefined;\n saveQuizWithPendingChangesCache();\n expect(exerciseStub).to.have.been.calledWith(comp.quizExercise);\n expect(quizExerciseServiceCreateStub).to.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.not.have.been.called;\n });\n\n it('should call not update if testruns exist in exam mode', () => {\n comp.quizExercise.testRunParticipationsExist = true;\n comp.isExamMode = true;\n saveQuizWithPendingChangesCache();\n expect(exerciseStub).to.not.have.been.calledWith(comp.quizExercise);\n expect(quizExerciseServiceCreateStub).to.not.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.not.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.not.have.been.calledWith(comp.quizExercise, {});\n });\n\n it('should update if valid and quiz exercise has id', () => {\n saveQuizWithPendingChangesCache();\n expect(exerciseStub).to.have.been.calledWith(comp.quizExercise);\n expect(quizExerciseServiceCreateStub).to.not.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.have.been.calledWith(comp.quizExercise, {});\n });\n\n it('should not save if not valid', () => {\n comp.quizIsValid = false;\n comp.pendingChangesCache = true;\n comp.save();\n expect(exerciseStub).to.not.have.been.called;\n expect(quizExerciseServiceCreateStub).to.not.have.been.called;\n expect(quizExerciseServiceUpdateStub).to.not.have.been.called;\n });\n\n it('should call update with notification text if there is one', () => {\n comp.notificationText = 'test';\n saveQuizWithPendingChangesCache();\n expect(quizExerciseServiceUpdateStub).to.have.been.calledWith(comp.quizExercise, { notificationText: 'test' });\n });\n\n it('should call alert service if response has no body on update', () => {\n quizExerciseServiceUpdateStub.returns(of(new HttpResponse<QuizExercise>({})));\n saveAndExpectAlertService();\n });\n\n it('should call alert service if response has no body on create', () => {\n comp.quizExercise.id = undefined;\n quizExerciseServiceCreateStub.returns(of(new HttpResponse<QuizExercise>({})));\n saveAndExpectAlertService();\n });\n\n it('should call alert service if update fails', () => {\n quizExerciseServiceUpdateStub.returns(throwError({ status: 404 }));\n saveAndExpectAlertService();\n });\n\n it('should call alert service if response has no body on create', () => {\n comp.quizExercise.id = undefined;\n quizExerciseServiceCreateStub.returns(throwError({ status: 404 }));\n saveAndExpectAlertService();\n });\n });\n\n describe('routing', () => {\n let routerSpy: SinonSpy;\n\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n routerSpy = spy(router, 'navigate');\n });\n\n afterEach(() => {\n routerSpy.resetHistory();\n });\n\n it('should go back to quiz exercise page on cancel', () => {\n comp.cancel();\n expect(routerSpy).to.have.been.calledOnceWithExactly(['/course-management', comp.quizExercise.course!.id, 'quiz-exercises']);\n });\n\n it('should go back to quiz exercise page on cancel', () => {\n comp.isExamMode = true;\n comp.cancel();\n expect(routerSpy).to.have.been.calledOnceWithExactly(['/course-management', comp.courseId, 'exams', comp.examId, 'exercise-groups']);\n });\n });\n\n describe('prepare entity', () => {\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n\n it('should set duration to 10 if not given', () => {\n comp.quizExercise.duration = undefined;\n comp.prepareEntity(comp.quizExercise);\n expect(comp.quizExercise.duration).to.equal(10);\n });\n\n it('should set release date to moment release date if exam mode', () => {\n comp.isExamMode = true;\n const now = moment();\n comp.quizExercise.releaseDate = now;\n comp.prepareEntity(comp.quizExercise);\n expect(comp.quizExercise.releaseDate).to.deep.equal(moment(now));\n });\n });\n\n describe('show existing questions', () => {\n let courseManagementServiceStub: SinonStub;\n let examManagementServiceStub: SinonStub;\n beforeEach(() => {\n comp.courseRepository = courseManagementService;\n courseManagementServiceStub = stub(comp.courseRepository, 'getAllCoursesWithQuizExercises');\n courseManagementServiceStub.returns(\n of(\n new HttpResponse<Course>({ body: course }),\n ),\n );\n examManagementServiceStub = stub(examManagementService, 'findAllExamsAccessibleToUser');\n examManagementServiceStub.returns(\n of(\n new HttpResponse<Exam>({ body: exam }),\n ),\n );\n });\n it('should show existing questions if not already shown', () => {\n comp.courses = [];\n comp.quizExercise = quizExercise;\n comp.showExistingQuestions = false;\n const setQuestionsFromCourseSpy = spy(comp, 'setExistingQuestionSourceToCourse');\n comp.showHideExistingQuestions();\n expect(courseManagementServiceStub).to.have.been.called;\n expect(examManagementServiceStub).to.have.been.called;\n expect(comp.showExistingQuestions).to.equal(true);\n expect(setQuestionsFromCourseSpy).to.have.been.calledOnce;\n });\n it('should not call getAll if there are courses', () => {\n comp.courses = [course];\n comp.quizExercise = quizExercise;\n comp.showHideExistingQuestions();\n expect(courseManagementServiceStub).to.not.have.been.called;\n expect(examManagementServiceStub).to.have.been.called;\n });\n it('should initialize quizExercise if it is not', () => {\n comp.courses = [course];\n comp.entity = quizExercise;\n expect(comp.quizExercise).to.equal(undefined);\n comp.showHideExistingQuestions();\n expect(comp.quizExercise).to.not.equal(undefined);\n });\n it('should hide existing questions if already shown', () => {\n comp.showExistingQuestions = true;\n comp.showHideExistingQuestions();\n expect(comp.showExistingQuestions).to.equal(false);\n });\n it('should set showExistingQuestionsFromCourse to given value', () => {\n const element = document.createElement('input');\n const control = { ...element, value: 'test' };\n const getElementStub = stub(document, 'getElementById').returns(control);\n comp.setExistingQuestionSourceToCourse();\n expect(comp.showExistingQuestionsFromCourse).to.equal(true);\n expect(comp.showExistingQuestionsFromFile).to.equal(false);\n expect(comp.showExistingQuestionsFromExam).to.equal(false);\n comp.setExistingQuestionSourceToFile();\n expect(comp.showExistingQuestionsFromCourse).to.equal(false);\n expect(comp.showExistingQuestionsFromFile).to.equal(true);\n expect(comp.showExistingQuestionsFromExam).to.equal(false);\n comp.setExistingQuestionSourceToExam();\n expect(comp.showExistingQuestionsFromCourse).to.equal(false);\n expect(comp.showExistingQuestionsFromFile).to.equal(false);\n expect(comp.showExistingQuestionsFromExam).to.equal(true);\n expect(getElementStub).to.have.been.called;\n expect(control.value).to.equal('');\n getElementStub.restore();\n });\n });\n\n describe('importing quiz', () => {\n let generateFileReaderStub: SinonStub;\n let verifyStub: SinonStub;\n let getElementStub: SinonStub;\n let readAsText: jest.Mock;\n let reader: FileReader;\n const jsonContent = `[{\n \"type\": \"multiple-choice\",\n \"id\": 1,\n \"title\": \"vav\",\n \"text\": \"Enter your long question if needed\",\n \"hint\": \"Add a hint here (visible during the quiz via ?-Button)\",\n \"score\": 1,\n \"scoringType\": \"ALL_OR_NOTHING\",\n \"randomizeOrder\": true,\n \"invalid\": false,\n \"answerOptions\": [\n {\n \"id\": 1,\n \"text\": \"Enter a correct answer option here\",\n \"hint\": \"Add a hint here (visible during the quiz via ?-Button)\",\n \"explanation\": \"Add an explanation here (only visible in feedback after quiz has ended)\",\n \"isCorrect\": true,\n \"invalid\": false\n },\n {\n \"id\": 2,\n \"text\": \"Enter a wrong answer option here\",\n \"isCorrect\": false,\n \"invalid\": false\n }\n ]\n }]`;\n const fakeFile = new File([jsonContent], 'file.txt', { type: 'text/plain' });\n const questions = JSON.parse(jsonContent) as QuizQuestion[];\n const element = document.createElement('input');\n const control = { ...element, value: 'test' };\n beforeEach(() => {\n comp.importFile = fakeFile;\n verifyStub = stub(comp, 'verifyAndImportQuestions');\n readAsText = jest.fn();\n reader = new FileReader();\n reader = { ...reader, result: jsonContent };\n generateFileReaderStub = stub(comp, 'generateFileReader').returns({ ...reader, onload: null, readAsText });\n getElementStub = stub(document, 'getElementById').returns(control);\n });\n afterEach(() => {\n getElementStub.restore();\n });\n it('should call verify and import questions with right json', async () => {\n expect(control.value).to.equal('test');\n await comp.importQuiz();\n jestExpect(readAsText).toHaveBeenCalledWith(fakeFile);\n expect(generateFileReaderStub).to.have.been.called;\n comp.onFileLoadImport(reader);\n expect(verifyStub).to.have.been.calledWithExactly(questions);\n expect(comp.importFile).to.equal(undefined);\n expect(getElementStub).to.have.been.called;\n expect(control.value).to.equal('');\n });\n\n it('should not call any functions without import file', async () => {\n comp.importFile = undefined;\n await comp.importQuiz();\n jestExpect(readAsText).toHaveBeenCalledTimes(0);\n expect(generateFileReaderStub).to.not.have.been.called;\n expect(comp.importFile).to.equal(undefined);\n });\n\n it('should alert user when onload throws error', async () => {\n const alert = window.alert;\n const alertFunction = jest.fn();\n window.alert = alertFunction;\n verifyStub.throws('');\n await comp.importQuiz();\n comp.onFileLoadImport(reader);\n jestExpect(alertFunction).toHaveBeenCalled();\n window.alert = alert;\n verifyStub.reset();\n });\n });\n\n describe('verify and import questions', () => {\n const { question: multiQuestion, answerOption1 } = createValidMCQuestion();\n let modalServiceStub: SinonStub;\n let componentInstance: any;\n let shouldImportEmitter: EventEmitter<void>;\n beforeEach(() => {\n shouldImportEmitter = new EventEmitter<void>();\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n componentInstance = { questions: [], shouldImport: shouldImportEmitter };\n modalServiceStub = stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance });\n });\n it('should call addQuestions', () => {\n const addQuestionsSpy = spy(comp, 'addQuestions');\n comp.verifyAndImportQuestions([multiQuestion]);\n expect(addQuestionsSpy).to.have.been.calledWith([multiQuestion]);\n });\n it('should open modal service when there are invalid questions', () => {\n const addQuestionsSpy = spy(comp, 'addQuestions');\n answerOption1.invalid = true;\n comp.verifyAndImportQuestions([multiQuestion]);\n expect(addQuestionsSpy).to.not.have.been.called;\n expect(modalServiceStub).to.have.been.called;\n shouldImportEmitter.emit();\n expect(addQuestionsSpy).to.have.been.called;\n });\n });\n\n describe('generating file reader', () => {\n it('should return file reader when called', () => {\n expect(comp.generateFileReader()).to.deep.equal(new FileReader());\n });\n });\n\n describe('invalid reasons', () => {\n const filterReasonAndExpectMoreThanOneInArray = (translateKey: string) => {\n const invalidReasons = comp.computeInvalidReasons().filter((reason) => reason.translateKey === translateKey);\n expect(invalidReasons.length).to.be.greaterThan(0);\n };\n\n const checkForInvalidFlaggedQuestionAndReason = () => {\n comp.checkForInvalidFlaggedQuestions(comp.quizExercise.quizQuestions);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionHasInvalidFlaggedElements');\n };\n it('should concatenate invalid reasons', () => {\n const computeInvalidReasonsStub = stub(comp, 'computeInvalidReasons').returns([\n { translateKey: 'testKey1', translateValues: 'testValue' },\n { translateKey: 'testKey2', translateValues: 'testValue' },\n ]);\n expect(comp.invalidReasonsHTML()).to.equal('testKey1 - testKey2 ');\n computeInvalidReasonsStub.restore();\n });\n\n describe('should include right reasons in reasons array for quiz', () => {\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n });\n it('should put reason for no title', () => {\n quizExercise.title = '';\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.quizTitle');\n });\n it('should put reason for too long title', () => {\n quizExercise.title = new Array(251).join('a');\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.quizTitleLength');\n });\n it('should put reason for no duration', () => {\n quizExercise.duration = 0;\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.quizDuration');\n });\n it('should put reason for no questions', () => {\n quizExercise.quizQuestions = [];\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.noQuestion');\n });\n\n it('should put reason for invalid release time', () => {\n quizExercise.isPlannedToStart = true;\n quizExercise.releaseDate = undefined;\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.invalidStartTime');\n });\n\n it('should put reason if release time is before now', () => {\n quizExercise.isPlannedToStart = true;\n quizExercise.releaseDate = moment().subtract(1500, 's');\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.startTimeInPast');\n });\n });\n\n describe('should include right reasons in reasons array for MC and general', () => {\n let question: MultipleChoiceQuestion;\n let answerOption1: AnswerOption;\n let answerOption2: AnswerOption;\n\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n const multiChoiceQuestion = createValidMCQuestion();\n question = multiChoiceQuestion.question;\n answerOption1 = multiChoiceQuestion.answerOption1;\n answerOption2 = multiChoiceQuestion.answerOption2;\n comp.quizExercise.quizQuestions = [question];\n });\n it('should put reason for negative score ', () => {\n question.points = -1;\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionScore');\n });\n it('should put reason for no title', () => {\n question.title = '';\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionTitle');\n });\n\n it('should put reason for no correct answer for MC', () => {\n answerOption1.isCorrect = false;\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionCorrectAnswerOption');\n });\n it('should put reason for no correct explanation for MC', () => {\n answerOption1.explanation = '';\n answerOption2.explanation = '';\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.explanationIsMissing');\n });\n\n it('should put reason for too long title', () => {\n question.title = new Array(251).join('a');\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionTitleLength');\n });\n\n it('should put reason if question title is included in invalid flagged question', () => {\n answerOption1.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n });\n\n describe('should include right reasons in reasons array for DnD', () => {\n let question: DragAndDropQuestion;\n let dragItem1: DragItem;\n let dropLocation: DropLocation;\n let correctDragAndDropMapping: DragAndDropMapping;\n\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n const dndQuestion = createValidDnDQuestion();\n question = dndQuestion.question;\n dragItem1 = dndQuestion.dragItem1;\n correctDragAndDropMapping = dndQuestion.correctDragAndDropMapping;\n dropLocation = dndQuestion.dropLocation;\n comp.quizExercise.quizQuestions = [question];\n });\n it('should put reason for no correct mappings ', () => {\n question.correctMappings = [];\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionCorrectMapping');\n });\n\n it('should put reason for unsolvable ', () => {\n const dragAndDropUtilSolveStub = stub(dragAndDropQuestionUtil, 'solve').returns([]);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionUnsolvable');\n dragAndDropUtilSolveStub.restore();\n });\n\n it('should put reason for misleading correct mappings ', () => {\n const dragAndDropUtilMisleadingStub = stub(dragAndDropQuestionUtil, 'validateNoMisleadingCorrectMapping').returns(false);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.misleadingCorrectMapping');\n dragAndDropUtilMisleadingStub.restore();\n });\n\n it('should put reason and flag as invalid if a drag item is invalid', () => {\n dragItem1.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n\n it('should put reason and flag as invalid if a correct mapping is invalid', () => {\n correctDragAndDropMapping.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n\n it('should put reason and flag as invalid if a drop location is invalid', () => {\n dropLocation.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n });\n\n describe('should include right reasons in reasons array for SA', () => {\n let question: ShortAnswerQuestion;\n let shortAnswerSolution1: ShortAnswerSolution;\n let shortAnswerMapping1: ShortAnswerMapping;\n let spot1: ShortAnswerSpot;\n beforeEach(() => {\n resetQuizExercise();\n comp.quizExercise = quizExercise;\n const saQuestion = createValidSAQuestion();\n question = saQuestion.question;\n shortAnswerSolution1 = saQuestion.shortAnswerSolution1;\n shortAnswerMapping1 = saQuestion.shortAnswerMapping1;\n spot1 = saQuestion.spot1;\n comp.quizExercise.quizQuestions = [question];\n });\n it('should put reason for no correct mappings ', () => {\n question.correctMappings = [];\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.questionCorrectMapping');\n });\n\n it('should put reason for misleading correct mappings ', () => {\n const shortAnswerUtilMisleadingStub = stub(shortAnswerQuestionUtil, 'validateNoMisleadingShortAnswerMapping').returns(false);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.misleadingCorrectMapping');\n shortAnswerUtilMisleadingStub.restore();\n });\n\n it('should put reason when every spot has a solution ', () => {\n const shortAnswerUtilMisleadingStub = stub(shortAnswerQuestionUtil, 'everySpotHasASolution').returns(false);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.shortAnswerQuestionEverySpotHasASolution');\n shortAnswerUtilMisleadingStub.restore();\n });\n\n it('should put reason when every mapped solution has a spot ', () => {\n const shortAnswerUtilMisleadingStub = stub(shortAnswerQuestionUtil, 'everyMappedSolutionHasASpot').returns(false);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.shortAnswerQuestionEveryMappedSolutionHasASpot');\n shortAnswerUtilMisleadingStub.restore();\n });\n\n it('should put reason when there is an empty solution ', () => {\n shortAnswerSolution1.text = '';\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.shortAnswerQuestionSolutionHasNoValue');\n });\n\n it('should put reason when duplicate mappings', () => {\n const shortAnswerUtilMisleadingStub = stub(shortAnswerQuestionUtil, 'hasMappingDuplicateValues').returns(true);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.shortAnswerQuestionDuplicateMapping');\n shortAnswerUtilMisleadingStub.restore();\n });\n it('should put reason for not many solutions as spots', () => {\n const shortAnswerUtilMisleadingStub = stub(shortAnswerQuestionUtil, 'atLeastAsManySolutionsAsSpots').returns(false);\n filterReasonAndExpectMoreThanOneInArray('artemisApp.quizExercise.invalidReasons.shortAnswerQuestionUnsolvable');\n shortAnswerUtilMisleadingStub.restore();\n });\n\n it('should put reason and flag as invalid if a solution is invalid', () => {\n shortAnswerSolution1.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n\n it('should put reason and flag as invalid if a spot is invalid', () => {\n shortAnswerMapping1.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n it('should put reason and flag as invalid if a spot is invalid', () => {\n spot1.invalid = true;\n checkForInvalidFlaggedQuestionAndReason();\n });\n });\n });\n });\n});\n" }, { "alpha_fraction": 0.7289325594902039, "alphanum_fraction": 0.7294007539749146, "avg_line_length": 41.720001220703125, "blob_id": "dae92a253cff4c8e27126d04b92d1876e1af4181", "content_id": "68caaefb6d14058b71dbcc027f86cf173c70aca5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2136, "license_type": "permissive", "max_line_length": 133, "num_lines": 50, "path": "/src/main/java/de/tum/in/www1/artemis/service/messaging/InstanceMessageSendService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.messaging;\n\n/**\n * This interface offers a service that will send messages to the node that runs the scheduling.\n * This can either be the same node or a different node within the Hazelcast cluster.\n */\npublic interface InstanceMessageSendService {\n\n /**\n * Send a message to the main server that a programming exercise was created or updated and a (re-)scheduling has to be performed\n * @param exerciseId the id of the exercise that should be scheduled\n */\n void sendProgrammingExerciseSchedule(Long exerciseId);\n\n /**\n * Send a message to the main server that a programming exercise was deleted and the scheduling should be cancelled\n * @param exerciseId the id of the exercise that should be no longer be scheduled\n */\n void sendProgrammingExerciseScheduleCancel(Long exerciseId);\n\n /**\n * Send a message to the main server that a text exercise was created or updated and a (re-)scheduling has to be performed\n * @param exerciseId the id of the exercise that should be scheduled\n */\n void sendTextExerciseSchedule(Long exerciseId);\n\n /**\n * Send a message to the main server that a text exercise was deleted and a scheduling should be stopped\n * @param exerciseId the id of the exercise that should no longer be scheduled\n */\n void sendTextExerciseScheduleCancel(Long exerciseId);\n\n /**\n * Send a message to the main server that a text exercise should be instantly get clustered\n * @param exerciseId the id of the exercise that should be clustered\n */\n void sendTextExerciseInstantClustering(Long exerciseId);\n\n /**\n * Send a message to the main server that all repositories of an exercise should be instantly unlocked\n * @param exerciseId the id of the exercise that should be unlocked\n */\n void sendUnlockAllRepositories(Long exerciseId);\n\n /**\n * Send a message to the main server that all repositories of an exercise should be instantly locked\n * @param exerciseId the id of the exercise that should be locked\n */\n void sendLockAllRepositories(Long exerciseId);\n}\n" }, { "alpha_fraction": 0.6633316874504089, "alphanum_fraction": 0.6633316874504089, "avg_line_length": 41.857582092285156, "blob_id": "2c3a20695022ddc2d510627547ec2fa72b780994", "content_id": "18e16b6ff2e52a4ce2ec160e67c7cec7caa2d330", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 27986, "license_type": "permissive", "max_line_length": 171, "num_lines": 653, "path": "/src/main/webapp/app/exam/manage/exam-management.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { ExamManagementComponent } from 'app/exam/manage/exam-management.component';\nimport { ExamUpdateComponent } from 'app/exam/manage/exams/exam-update.component';\nimport { ExamDetailComponent } from 'app/exam/manage/exams/exam-detail.component';\nimport { ExerciseGroupsComponent } from 'app/exam/manage/exercise-groups/exercise-groups.component';\nimport { ExerciseGroupUpdateComponent } from 'app/exam/manage/exercise-groups/exercise-group-update.component';\nimport { ExamStudentsComponent } from 'app/exam/manage/students/exam-students.component';\nimport { StudentExamsComponent } from 'app/exam/manage/student-exams/student-exams.component';\nimport { StudentExamDetailComponent } from 'app/exam/manage/student-exams/student-exam-detail.component';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { StudentExamService } from 'app/exam/manage/student-exams/student-exam.service';\nimport { TextExerciseUpdateComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-update.component';\nimport { TextExerciseResolver } from 'app/exercises/text/manage/text-exercise/text-exercise.route';\nimport { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component';\nimport { FileUploadExerciseResolve } from 'app/exercises/file-upload/manage/file-upload-exercise-management.route';\nimport { QuizExerciseDetailComponent } from 'app/exercises/quiz/manage/quiz-exercise-detail.component';\nimport { ProgrammingExerciseUpdateComponent } from 'app/exercises/programming/manage/update/programming-exercise-update.component';\nimport { ProgrammingExerciseResolve } from 'app/exercises/programming/manage/programming-exercise-management-routing.module';\nimport { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component';\nimport { ModelingExerciseResolver } from 'app/exercises/modeling/manage/modeling-exercise.route';\nimport { StudentExamSummaryComponent } from 'app/exam/manage/student-exams/student-exam-summary.component';\nimport { AssessmentDashboardComponent } from 'app/course/dashboards/assessment-dashboard/assessment-dashboard.component';\nimport { TestRunManagementComponent } from 'app/exam/manage/test-runs/test-run-management.component';\nimport { ExamParticipationComponent } from 'app/exam/participate/exam-participation.component';\nimport { PendingChangesGuard } from 'app/shared/guard/pending-changes.guard';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { ExerciseAssessmentDashboardComponent } from 'app/exercises/shared/dashboards/tutor/exercise-assessment-dashboard.component';\nimport { ExamParticipantScoresComponent } from 'app/exam/manage/exam-participant-scores/exam-participant-scores.component';\nimport { ParticipationSubmissionComponent } from 'app/exercises/shared/participation-submission/participation-submission.component';\nimport { FileUploadAssessmentComponent } from 'app/exercises/file-upload/assess/file-upload-assessment.component';\nimport { ParticipationComponent } from 'app/exercises/shared/participation/participation.component';\nimport { ExerciseScoresComponent } from 'app/exercises/shared/exercise-scores/exercise-scores.component';\nimport { FileUploadAssessmentDashboardComponent } from 'app/exercises/file-upload/assess/file-upload-assessment-dashboard.component';\nimport { TextAssessmentDashboardComponent } from 'app/exercises/text/assess/text-assessment-dashboard/text-assessment-dashboard.component';\nimport { ModelingAssessmentDashboardComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component';\nimport { ModelingAssessmentEditorComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component';\nimport { ProgrammingAssessmentDashboardComponent } from 'app/exercises/programming/assess/programming-assessment-dashboard/programming-assessment-dashboard.component';\nimport { CodeEditorTutorAssessmentContainerComponent } from 'app/exercises/programming/assess/code-editor-tutor-assessment-container.component';\nimport { NewStudentParticipationResolver, StudentParticipationResolver } from 'app/exercises/programming/assess/programming-assessment.route';\n\n@Injectable({ providedIn: 'root' })\nexport class ExamResolve implements Resolve<Exam> {\n constructor(private examManagementService: ExamManagementService) {}\n\n /**\n * Resolves the route by extracting the examId and returns the exam with that Id if it exists\n * or creates a new exam otherwise.\n * @param route Contains the information about the route to be resolved\n */\n resolve(route: ActivatedRouteSnapshot): Observable<Exam> {\n const courseId = route.params['courseId'] ? route.params['courseId'] : undefined;\n const examId = route.params['examId'] ? route.params['examId'] : undefined;\n const withStudents = route.data['requestOptions'] ? route.data['requestOptions'].withStudents : false;\n const withExerciseGroups = route.data['requestOptions'] ? route.data['requestOptions'].withExerciseGroups : false;\n if (courseId && examId) {\n return this.examManagementService.find(courseId, examId, withStudents, withExerciseGroups).pipe(\n filter((response: HttpResponse<Exam>) => response.ok),\n map((exam: HttpResponse<Exam>) => exam.body!),\n );\n }\n return of(new Exam());\n }\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ExerciseGroupResolve implements Resolve<ExerciseGroup> {\n constructor(private exerciseGroupService: ExerciseGroupService) {}\n\n /**\n * Resolves the route by extracting the exerciseGroupId and returns the exercise group with that id if it exists\n * or creates a new exercise group otherwise.\n * @param route Contains the information about the route to be resolved\n */\n resolve(route: ActivatedRouteSnapshot): Observable<ExerciseGroup> {\n const courseId = route.params['courseId'] || undefined;\n const examId = route.params['examId'] || undefined;\n const exerciseGroupId = route.params['exerciseGroupId'] || undefined;\n if (courseId && examId && exerciseGroupId) {\n return this.exerciseGroupService.find(courseId, examId, exerciseGroupId).pipe(\n filter((response: HttpResponse<ExerciseGroup>) => response.ok),\n map((exerciseGroup: HttpResponse<ExerciseGroup>) => exerciseGroup.body!),\n );\n }\n return of({ isMandatory: true } as ExerciseGroup);\n }\n}\n\n@Injectable({ providedIn: 'root' })\nexport class StudentExamResolve implements Resolve<StudentExam> {\n constructor(private studentExamService: StudentExamService) {}\n\n /**\n * Resolves the route by extracting the studentExamId and returns the student exam with that id if it exists\n * or creates a new student exam otherwise.\n * @param route Contains the information about the route to be resolved\n */\n resolve(route: ActivatedRouteSnapshot): Observable<StudentExam> {\n const courseId = route.params['courseId'] || undefined;\n const examId = route.params['examId'] || undefined;\n const studentExamId = route.params['studentExamId'] ? route.params['studentExamId'] : route.params['testRunId'];\n if (courseId && examId && studentExamId) {\n return this.studentExamService.find(courseId, examId, studentExamId).pipe(\n filter((response: HttpResponse<StudentExam>) => response.ok),\n map((studentExam: HttpResponse<StudentExam>) => studentExam.body!),\n );\n }\n return of(new StudentExam());\n }\n}\n\nexport const examManagementRoute: Routes = [\n {\n path: '',\n component: ExamManagementComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'new',\n component: ExamUpdateComponent,\n resolve: {\n exam: ExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/edit',\n component: ExamUpdateComponent,\n resolve: {\n exam: ExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId',\n component: ExamDetailComponent,\n resolve: {\n exam: ExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n requestOptions: {\n withStudents: true,\n withExerciseGroups: true,\n },\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/participant-scores',\n component: ExamParticipantScoresComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.participantScores.pageTitle',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups',\n component: ExerciseGroupsComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/new',\n component: ExerciseGroupUpdateComponent,\n resolve: {\n exam: ExamResolve,\n exerciseGroup: ExerciseGroupResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/edit',\n component: ExerciseGroupUpdateComponent,\n resolve: {\n exam: ExamResolve,\n exerciseGroup: ExerciseGroupResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/students',\n component: ExamStudentsComponent,\n resolve: {\n exam: ExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n requestOptions: {\n withStudents: true,\n },\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/student-exams',\n component: StudentExamsComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/test-runs',\n component: TestRunManagementComponent,\n resolve: {\n exam: ExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/test-runs/assess',\n component: AssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.examManagement.assessmentDashboard',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/test-runs/:studentExamId',\n component: StudentExamDetailComponent,\n resolve: {\n studentExam: StudentExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/student-exams/:studentExamId',\n component: StudentExamDetailComponent,\n resolve: {\n studentExam: StudentExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/student-exams/:studentExamId/summary',\n component: StudentExamSummaryComponent,\n resolve: {\n studentExam: StudentExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/test-runs/:testRunId/conduction',\n component: ExamParticipationComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.exam.title',\n },\n canActivate: [UserRouteAccessService],\n canDeactivate: [PendingChangesGuard],\n },\n {\n path: ':examId/test-runs/:studentExamId/summary',\n component: StudentExamSummaryComponent,\n resolve: {\n studentExam: StudentExamResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.examManagement.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Create Modeling Exercise\n {\n path: ':examId/exercise-groups/:groupId/modeling-exercises/new',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Import Modeling Exercise\n {\n path: ':examId/exercise-groups/:groupId/modeling-exercises/import/:exerciseId',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Edit Modeling Exercise\n {\n path: ':examId/exercise-groups/:groupId/modeling-exercises/:exerciseId/edit',\n component: ModelingExerciseUpdateComponent,\n resolve: {\n modelingExercise: ModelingExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.modelingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Create Text Exercise\n {\n path: ':examId/exercise-groups/:groupId/text-exercises/new',\n component: TextExerciseUpdateComponent,\n resolve: {\n textExercise: TextExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.textExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Import Text Exercise\n {\n path: ':examId/exercise-groups/:groupId/text-exercises/import/:exerciseId',\n component: TextExerciseUpdateComponent,\n resolve: {\n textExercise: TextExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.textExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Edit Text Exercise\n {\n path: ':examId/exercise-groups/:groupId/text-exercises/:exerciseId/edit',\n component: TextExerciseUpdateComponent,\n resolve: {\n textExercise: TextExerciseResolver,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.textExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Create File Upload Exercise\n {\n path: ':examId/exercise-groups/:groupId/file-upload-exercises/new',\n component: FileUploadExerciseUpdateComponent,\n resolve: {\n fileUploadExercise: FileUploadExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Edit File Upload Exercise\n {\n path: ':examId/exercise-groups/:groupId/file-upload-exercises/:exerciseId/edit',\n component: FileUploadExerciseUpdateComponent,\n resolve: {\n fileUploadExercise: FileUploadExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Create Quiz Exercise\n {\n path: ':examId/exercise-groups/:groupId/quiz-exercises/new',\n component: QuizExerciseDetailComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.quizExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Edit Quiz Exercise\n {\n path: ':examId/exercise-groups/:groupId/quiz-exercises/:exerciseId/edit',\n component: QuizExerciseDetailComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.quizExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Create Programming Exercise\n {\n path: ':examId/exercise-groups/:groupId/programming-exercises/new',\n component: ProgrammingExerciseUpdateComponent,\n resolve: {\n programmingExercise: ProgrammingExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n // Import programming exercise\n {\n path: ':examId/exercise-groups/:groupId/programming-exercises/import/:id',\n component: ProgrammingExerciseUpdateComponent,\n resolve: {\n programmingExercise: ProgrammingExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.programmingExercise.home.importLabel',\n },\n canActivate: [UserRouteAccessService],\n },\n // Edit Programming Exercise\n {\n path: ':examId/exercise-groups/:groupId/programming-exercises/:id/edit',\n component: ProgrammingExerciseUpdateComponent,\n resolve: {\n programmingExercise: ProgrammingExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/assessment-dashboard',\n component: AssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.examManagement.assessmentDashboard',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/assessment-dashboard/:exerciseId',\n component: ExerciseAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.exerciseAssessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/test-assessment-dashboard/:exerciseId',\n component: ExerciseAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR],\n pageTitle: 'artemisApp.exerciseAssessmentDashboard.testRunPageHeader',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/exercises/:exerciseId/scores',\n component: ExerciseScoresComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'instructorDashboard.exerciseDashboard',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/exercises/:exerciseId/participations',\n component: ParticipationComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.participation.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/exercises/:exerciseId/participations/:participationId',\n component: ParticipationSubmissionComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.participation.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/file-upload-exercises/:exerciseId/submissions/:submissionId/assessment',\n component: FileUploadAssessmentComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/file-upload-exercises/:exerciseId/assessment',\n component: FileUploadAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.assessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/text-exercises/:exerciseId/assessment',\n component: TextAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.assessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/programming-exercises/:exerciseId/code-editor',\n loadChildren: () => import('../../exercises/programming/manage/code-editor/code-editor-management.module').then((m) => m.ArtemisCodeEditorManagementModule),\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/text-exercises/:exerciseId',\n loadChildren: () => import('../../exercises/text/assess/text-submission-assessment.module').then((m) => m.ArtemisTextSubmissionAssessmentModule),\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/text-exercises/:exerciseId/example-submissions/:exampleSubmissionId',\n loadChildren: () => import('../../exercises/text/manage/example-text-submission/example-text-submission.module').then((m) => m.ArtemisExampleTextSubmissionModule),\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/modeling-exercises/:exerciseId/assessment',\n component: ModelingAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.assessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/modeling-exercises/:exerciseId/submissions/:submissionId/assessment',\n component: ModelingAssessmentEditorComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.apollonDiagram.detail.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/programming-exercises/:exerciseId/assessment',\n component: ProgrammingAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.assessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/programming-exercises/:exerciseId/code-editor/new/assessment',\n component: CodeEditorTutorAssessmentContainerComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n resolve: {\n studentParticipationId: NewStudentParticipationResolver,\n },\n runGuardsAndResolvers: 'always',\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/programming-exercises/:exerciseId/code-editor/:participationId/assessment',\n component: CodeEditorTutorAssessmentContainerComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n resolve: {\n studentParticipationId: StudentParticipationResolver,\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/file-upload-exercises/:exerciseId/submissions/:submissionId/assessments/:resultId',\n component: FileUploadAssessmentComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':examId/exercise-groups/:exerciseGroupId/modeling-exercises/:exerciseId/submissions/:submissionId/assessments/:resultId',\n component: ModelingAssessmentEditorComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR],\n usePathForBreadcrumbs: true,\n pageTitle: 'artemisApp.apollonDiagram.detail.title',\n },\n canActivate: [UserRouteAccessService],\n },\n];\n\nconst EXAM_MANAGEMENT_ROUTES = [...examManagementRoute];\n\nexport const examManagementState: Routes = [\n {\n path: '',\n children: EXAM_MANAGEMENT_ROUTES,\n },\n];\n" }, { "alpha_fraction": 0.7530614733695984, "alphanum_fraction": 0.7579060792922974, "avg_line_length": 54.66292190551758, "blob_id": "f269e67769d5c8f9d6417e9641f8ef2470d5dd7b", "content_id": "cf619b6cb21dc8d86e98075d59101e6a94e992d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 14862, "license_type": "permissive", "max_line_length": 180, "num_lines": 267, "path": "/src/test/java/de/tum/in/www1/artemis/AssessmentTeamComplaintIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.List;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.ComplaintType;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseMode;\nimport de.tum.in.www1.artemis.domain.enumeration.FeedbackType;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.FileUtils;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class AssessmentTeamComplaintIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ExerciseRepository exerciseRepo;\n\n @Autowired\n private ResultRepository resultRepo;\n\n @Autowired\n private ComplaintRepository complaintRepo;\n\n @Autowired\n private ComplaintResponseRepository complaintResponseRepo;\n\n @Autowired\n private ObjectMapper mapper;\n\n private ModelingExercise modelingExercise;\n\n private ModelingSubmission modelingSubmission;\n\n private Result modelingAssessment;\n\n private Complaint complaint;\n\n private Complaint moreFeedbackRequest;\n\n private Course course;\n\n private Team team;\n\n private final String resourceUrl = \"/api/complaints\";\n\n @BeforeEach\n public void initTestCase() throws Exception {\n database.addUsers(1, 2, 1);\n // Initialize with 3 max team complaints and 7 days max complaint deadline\n course = database.addCourseWithOneModelingExercise();\n modelingExercise = (ModelingExercise) course.getExercises().iterator().next();\n modelingExercise = (ModelingExercise) exerciseRepo.save(modelingExercise.mode(ExerciseMode.TEAM));\n team = database.addTeamForExercise(modelingExercise, database.getUserByLogin(\"tutor1\"));\n saveModelingSubmissionAndAssessment();\n complaint = new Complaint().result(modelingAssessment).complaintText(\"This is not fair\").complaintType(ComplaintType.COMPLAINT);\n moreFeedbackRequest = new Complaint().result(modelingAssessment).complaintText(\"Please explain\").complaintType(ComplaintType.MORE_FEEDBACK);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"team1student1\")\n public void submitComplaintAboutModellingAssessment_complaintLimitNotReached() throws Exception {\n // 2 complaints are allowed, the course is created with 3 max team complaints\n database.addTeamComplaints(team, modelingAssessment.getParticipation(), 2, ComplaintType.COMPLAINT);\n\n request.post(resourceUrl, complaint, HttpStatus.CREATED);\n\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId())).as(\"complaint is saved\").isPresent();\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n assertThat(storedResult.hasComplaint()).as(\"hasComplaint flag of result is true\").isTrue();\n }\n\n @Test\n @WithMockUser(username = \"team1student1\")\n public void submitComplaintAboutModelingAssessment_complaintLimitReached() throws Exception {\n database.addTeamComplaints(team, modelingAssessment.getParticipation(), 3, ComplaintType.COMPLAINT);\n\n request.post(resourceUrl, complaint, HttpStatus.BAD_REQUEST);\n\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId())).as(\"complaint is not saved\").isNotPresent();\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n assertThat(storedResult.hasComplaint()).as(\"hasComplaint flag of result is false\").isFalse();\n }\n\n @Test\n @WithMockUser(username = \"team1student1\")\n public void requestMoreFeedbackAboutModelingAssessment_noLimit() throws Exception {\n database.addTeamComplaints(team, modelingAssessment.getParticipation(), 5, ComplaintType.MORE_FEEDBACK);\n\n request.post(resourceUrl, complaint, HttpStatus.CREATED);\n\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId())).as(\"complaint is saved\").isPresent();\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n assertThat(storedResult.hasComplaint()).as(\"hasComplaint flag of result is true\").isTrue();\n\n // Only one complaint is possible for exercise regardless of its type\n request.post(resourceUrl, moreFeedbackRequest, HttpStatus.BAD_REQUEST);\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId()).get().getComplaintType() == ComplaintType.MORE_FEEDBACK).as(\"more feedback request is not saved\")\n .isFalse();\n }\n\n @Test\n @WithMockUser(username = \"team1student1\")\n public void submitComplaintAboutModelingAssessment_validDeadline() throws Exception {\n // Mock object initialized with 2 weeks deadline. One week after result date is fine.\n database.updateAssessmentDueDate(modelingExercise.getId(), ZonedDateTime.now().minusWeeks(1));\n database.updateResultCompletionDate(modelingAssessment.getId(), ZonedDateTime.now().minusWeeks(1));\n\n request.post(resourceUrl, complaint, HttpStatus.CREATED);\n\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId())).as(\"complaint is saved\").isPresent();\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n assertThat(storedResult.hasComplaint()).as(\"hasComplaint flag of result is true\").isTrue();\n }\n\n @Test\n @WithMockUser(username = \"team1student1\")\n public void submitComplaintAboutModelingAssessment_assessmentTooOld() throws Exception {\n // 3 weeks is already past the deadline\n database.updateAssessmentDueDate(modelingExercise.getId(), ZonedDateTime.now().minusWeeks(3));\n database.updateResultCompletionDate(modelingAssessment.getId(), ZonedDateTime.now().minusWeeks(3));\n\n request.post(resourceUrl, complaint, HttpStatus.BAD_REQUEST);\n\n assertThat(complaintRepo.findByResult_Id(modelingAssessment.getId())).as(\"complaint is not saved\").isNotPresent();\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n assertThat(storedResult.hasComplaint()).as(\"hasComplaint flag of result is false\").isFalse();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void submitComplaintResponse_rejectComplaint() throws Exception {\n complaint = complaintRepo.saveAndFlush(complaint);\n\n ComplaintResponse complaintResponse = database.createInitialEmptyResponse(\"tutor1\", complaint);\n complaintResponse.getComplaint().setAccepted(false);\n complaintResponse.setResponseText(\"rejected\");\n\n request.put(\"/api/complaint-responses/complaint/\" + complaint.getId() + \"/resolve\", complaintResponse, HttpStatus.OK);\n assertThat(complaintResponse.getComplaint().getParticipant()).isNull();\n Complaint storedComplaint = complaintRepo.findByResult_Id(modelingAssessment.getId()).get();\n assertThat(storedComplaint.isAccepted()).as(\"complaint is not accepted\").isFalse();\n Result storedResult = resultRepo.findWithEagerSubmissionAndFeedbackAndAssessorById(modelingAssessment.getId()).get();\n database.checkFeedbackCorrectlyStored(modelingAssessment.getFeedbacks(), storedResult.getFeedbacks(), FeedbackType.MANUAL);\n assertThat(storedResult.getSubmission()).isEqualTo(modelingAssessment.getSubmission());\n assertThat(storedResult.getAssessor()).isEqualTo(modelingAssessment.getAssessor());\n assertThat(storedResult.getParticipation()).isEqualTo(modelingAssessment.getParticipation());\n assertThat(storedResult.getFeedbacks()).containsExactlyInAnyOrderElementsOf(modelingAssessment.getFeedbacks());\n final String[] ignoringFields = { \"feedbacks\", \"submission\", \"participation\", \"assessor\" };\n assertThat(storedResult).as(\"only feedbacks are changed in the result\").usingRecursiveComparison().ignoringFields(ignoringFields).isEqualTo(modelingAssessment);\n }\n\n @Test\n @WithMockUser(username = \"tutor2\", roles = \"TA\")\n public void submitComplaintResponse_rejectComplaint_asOtherTutor_forbidden() throws Exception {\n complaint = complaintRepo.save(complaint);\n ComplaintResponse complaintResponse = database.createInitialEmptyResponse(\"tutor2\", complaint);\n complaintResponse.getComplaint().setAccepted(false);\n complaintResponse.setResponseText(\"rejected\");\n request.put(\"/api/complaint-responses/complaint/\" + complaint.getId() + \"/resolve\", complaintResponse, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void submitComplaintResponse_updateAssessment() throws Exception {\n complaint = complaintRepo.save(complaint);\n\n List<Feedback> feedback = database.loadAssessmentFomResources(\"test-data/model-assessment/assessment.54727.json\");\n ComplaintResponse complaintResponse = database.createInitialEmptyResponse(\"tutor1\", complaint);\n complaintResponse.getComplaint().setAccepted(true);\n complaintResponse.setResponseText(\"accepted\");\n\n AssessmentUpdate assessmentUpdate = new AssessmentUpdate().feedbacks(feedback).complaintResponse(complaintResponse);\n Result receivedResult = request.putWithResponseBody(\"/api/modeling-submissions/\" + modelingSubmission.getId() + \"/assessment-after-complaint\", assessmentUpdate,\n Result.class, HttpStatus.OK);\n\n assertThat(((StudentParticipation) receivedResult.getParticipation()).getStudent()).as(\"student is hidden in response\").isEmpty();\n Complaint storedComplaint = complaintRepo.findByResult_Id(modelingAssessment.getId()).get();\n assertThat(storedComplaint.isAccepted()).as(\"complaint is accepted\").isTrue();\n Result resultBeforeComplaint = mapper.readValue(storedComplaint.getResultBeforeComplaint(), Result.class);\n // set dates to UTC and round to milliseconds for comparison\n resultBeforeComplaint.setCompletionDate(ZonedDateTime.ofInstant(resultBeforeComplaint.getCompletionDate().truncatedTo(ChronoUnit.MILLIS).toInstant(), ZoneId.of(\"UTC\")));\n modelingAssessment.setCompletionDate(ZonedDateTime.ofInstant(modelingAssessment.getCompletionDate().truncatedTo(ChronoUnit.MILLIS).toInstant(), ZoneId.of(\"UTC\")));\n assertThat(resultBeforeComplaint.getAssessor()).isEqualTo(modelingAssessment.getAssessor());\n assertThat(resultBeforeComplaint.getFeedbacks()).containsExactlyInAnyOrderElementsOf(modelingAssessment.getFeedbacks());\n String[] ignoringFields = { \"participation\", \"submission\", \"feedbacks\", \"assessor\" };\n assertThat(resultBeforeComplaint).as(\"result before complaint is correctly stored\").usingRecursiveComparison().ignoringFields(ignoringFields).isEqualTo(modelingAssessment);\n Result storedResult = resultRepo.findByIdWithEagerFeedbacksAndAssessor(modelingAssessment.getId()).get();\n database.checkFeedbackCorrectlyStored(feedback, storedResult.getFeedbacks(), FeedbackType.MANUAL);\n assertThat(storedResult.getAssessor()).as(\"assessor is still the original one\").isEqualTo(modelingAssessment.getAssessor());\n }\n\n @Test\n @WithMockUser(username = \"tutor2\", roles = \"TA\")\n public void submitComplaintResponse_updateAssessment_asOtherTutor_forbidden() throws Exception {\n complaint = complaintRepo.save(complaint);\n\n List<Feedback> feedback = database.loadAssessmentFomResources(\"test-data/model-assessment/assessment.54727.json\");\n ComplaintResponse complaintResponse = database.createInitialEmptyResponse(\"tutor2\", complaint);\n complaintResponse.getComplaint().setAccepted(true);\n complaintResponse.setResponseText(\"accepted\");\n\n AssessmentUpdate assessmentUpdate = new AssessmentUpdate().feedbacks(feedback).complaintResponse(complaintResponse);\n request.putWithResponseBody(\"/api/modeling-submissions/\" + modelingSubmission.getId() + \"/assessment-after-complaint\", assessmentUpdate, Result.class,\n HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void getComplaintByResultId_studentAndNotPartOfTeam_forbidden() throws Exception {\n complaint.setParticipant(team);\n complaintRepo.save(complaint);\n\n request.get(\"/api/complaints/result/\" + complaint.getResult().getId(), HttpStatus.FORBIDDEN, Complaint.class);\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void getComplaintResponseByComplaintId_studentNotPartOfTeam_forbidden() throws Exception {\n complaint.setParticipant(team);\n complaintRepo.save(complaint);\n\n ComplaintResponse complaintResponse = new ComplaintResponse().complaint(complaint.accepted(false)).responseText(\"rejected\").reviewer(database.getUserByLogin(\"tutor1\"));\n complaintResponseRepo.save(complaintResponse);\n\n request.get(\"/api/complaint-responses/complaint/\" + complaint.getId(), HttpStatus.FORBIDDEN, ComplaintResponse.class);\n }\n\n private void saveModelingSubmissionAndAssessment() throws Exception {\n modelingSubmission = ModelFactory.generateModelingSubmission(FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\"), true);\n modelingSubmission = database.addModelingTeamSubmission(modelingExercise, modelingSubmission, team);\n modelingAssessment = database.addModelingAssessmentForSubmission(modelingExercise, modelingSubmission, \"test-data/model-assessment/assessment.54727.v2.json\", \"tutor1\",\n true);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void getNumberOfAllowedTeamComplaintsInCourse() throws Exception {\n complaint.setParticipant(team);\n complaintRepo.save(complaint);\n Long nrOfAllowedComplaints = request.get(\"/api/courses/\" + modelingExercise.getCourseViaExerciseGroupOrCourseMember().getId() + \"/allowed-complaints?isTeamMode=true\",\n HttpStatus.OK, Long.class);\n assertThat(nrOfAllowedComplaints.intValue()).isEqualTo(course.getMaxTeamComplaints());\n }\n\n}\n" }, { "alpha_fraction": 0.616034984588623, "alphanum_fraction": 0.6206997036933899, "avg_line_length": 41.345680236816406, "blob_id": "08ef3e9f139cc5ce8eab5ba0e692dd10441ad0c6", "content_id": "b594c77b59878e294a618b8cebd6f8c084394259", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6860, "license_type": "permissive", "max_line_length": 176, "num_lines": 162, "path": "/src/test/javascript/spec/component/lecture-unit/text-unit/edit-text-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\n\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TextUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/text-unit-form/text-unit-form.component';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { TextUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/textUnit.service';\nimport { MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { EditTextUnitComponent } from 'app/lecture/lecture-unit/lecture-unit-management/edit-text-unit/edit-text-unit.component';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-text-unit-form', template: '' })\nclass TextUnitFormStubComponent {\n @Input() isEditMode = false;\n @Input() formData: TextUnitFormData;\n @Output() formSubmitted: EventEmitter<TextUnitFormData> = new EventEmitter<TextUnitFormData>();\n}\n\n@Component({ selector: 'jhi-lecture-unit-layout', template: '<ng-content></ng-content>' })\nclass LectureUnitLayoutStubComponent {\n @Input() isLoading = false;\n}\n\ndescribe('EditTextUnitComponent', () => {\n let editTextUnitComponentFixture: ComponentFixture<EditTextUnitComponent>;\n let editTextUnitComponent: EditTextUnitComponent;\n const sandbox = sinon.createSandbox();\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [TextUnitFormStubComponent, LectureUnitLayoutStubComponent, EditTextUnitComponent],\n providers: [\n MockProvider(TextUnitService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n paramMap: Observable.of({\n get: () => {\n return { textUnitId: 1 };\n },\n }),\n parent: {\n parent: {\n paramMap: Observable.of({\n get: () => {\n return { lectureId: 1 };\n },\n }),\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n editTextUnitComponentFixture = TestBed.createComponent(EditTextUnitComponent);\n editTextUnitComponent = editTextUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n it('should initialize', fakeAsync(() => {\n editTextUnitComponentFixture.detectChanges();\n tick();\n expect(editTextUnitComponent).to.be.ok;\n }));\n\n it('should set form data correctly', () => {\n const textUnitService = TestBed.inject(TextUnitService);\n\n const originalTextUnit: TextUnit = new TextUnit();\n originalTextUnit.id = 1;\n originalTextUnit.name = 'Test';\n originalTextUnit.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n originalTextUnit.content = 'Lorem Ipsum';\n\n const response: HttpResponse<TextUnit> = new HttpResponse({\n body: originalTextUnit,\n status: 200,\n });\n\n const findByIdStub = sandbox.stub(textUnitService, 'findById').returns(of(response));\n\n const textUnitFormStubComponent: TextUnitFormStubComponent = editTextUnitComponentFixture.debugElement.query(By.directive(TextUnitFormStubComponent)).componentInstance;\n\n editTextUnitComponentFixture.detectChanges();\n editTextUnitComponentFixture.whenStable().then(() => {\n expect(findByIdStub).to.have.been.calledOnce;\n expect(editTextUnitComponent.formData.name).to.equal(originalTextUnit.name);\n expect(editTextUnitComponent.formData.releaseDate).to.equal(originalTextUnit.releaseDate);\n expect(editTextUnitComponent.formData.content).to.equal(originalTextUnit.content);\n expect(textUnitFormStubComponent.formData).to.equal(editTextUnitComponent.formData);\n });\n });\n\n it('should send PUT request upon form submission and navigate', fakeAsync(() => {\n const router: Router = TestBed.inject(Router);\n const textUnitService = TestBed.inject(TextUnitService);\n\n const originalTextUnit: TextUnit = new TextUnit();\n originalTextUnit.id = 1;\n originalTextUnit.name = 'Test';\n originalTextUnit.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n originalTextUnit.content = 'Lorem Ipsum';\n\n const findByidResponse: HttpResponse<TextUnit> = new HttpResponse({\n body: originalTextUnit,\n status: 200,\n });\n\n const findByIdStub = sandbox.stub(textUnitService, 'findById').returns(of(findByidResponse));\n\n const formDate: TextUnitFormData = {\n name: 'CHANGED',\n releaseDate: moment({ years: 2010, months: 3, date: 5 }),\n content: 'Lorem Ipsum',\n };\n const updatedTextUnit: TextUnit = new TextUnit();\n updatedTextUnit.id = 1;\n updatedTextUnit.name = formDate.name;\n updatedTextUnit.releaseDate = formDate.releaseDate;\n updatedTextUnit.content = formDate.content;\n\n const updateResponse: HttpResponse<TextUnit> = new HttpResponse({\n body: updatedTextUnit,\n status: 200,\n });\n const updatedStub = sandbox.stub(textUnitService, 'update').returns(of(updateResponse));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n editTextUnitComponentFixture.detectChanges();\n tick();\n\n const textUnitForm: TextUnitFormStubComponent = editTextUnitComponentFixture.debugElement.query(By.directive(TextUnitFormStubComponent)).componentInstance;\n textUnitForm.formSubmitted.emit(formDate);\n\n editTextUnitComponentFixture.whenStable().then(() => {\n expect(findByIdStub).to.have.been.calledOnce;\n expect(updatedStub).to.have.been.calledOnce;\n expect(navigateSpy).to.have.been.calledOnce;\n navigateSpy.restore();\n });\n }));\n});\n" }, { "alpha_fraction": 0.6014788150787354, "alphanum_fraction": 0.6038931608200073, "avg_line_length": 38.68263626098633, "blob_id": "4f4ea01fe512a298b12b8727f172a34294323c03", "content_id": "05bdaff34e71c439daf6272e21ea2894951a44c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6627, "license_type": "permissive", "max_line_length": 132, "num_lines": 167, "path": "/src/main/webapp/app/exam/participate/exam-navigation-bar/exam-navigation-bar.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { LayoutService } from 'app/shared/breakpoints/layout.service';\nimport { CustomBreakpointNames } from 'app/shared/breakpoints/breakpoints.service';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\n\n@Component({\n selector: 'jhi-exam-navigation-bar',\n templateUrl: './exam-navigation-bar.component.html',\n styleUrls: ['./exam-navigation-bar.component.scss'],\n})\nexport class ExamNavigationBarComponent implements OnInit {\n @Input() exercises: Exercise[] = [];\n @Input() exerciseIndex = 0;\n @Input() endDate: Moment;\n\n @Output() onExerciseChanged = new EventEmitter<{ exercise: Exercise; forceSave: boolean }>();\n @Output() examAboutToEnd = new EventEmitter<void>();\n @Output() onExamHandInEarly = new EventEmitter<void>();\n\n static itemsVisiblePerSideDefault = 4;\n itemsVisiblePerSide = ExamNavigationBarComponent.itemsVisiblePerSideDefault;\n\n criticalTime = moment.duration(5, 'minutes');\n\n icon: string;\n\n constructor(private layoutService: LayoutService) {}\n\n ngOnInit(): void {\n this.layoutService.subscribeToLayoutChanges().subscribe(() => {\n // You will have all matched breakpoints in observerResponse\n if (this.layoutService.isBreakpointActive(CustomBreakpointNames.extraLarge)) {\n this.itemsVisiblePerSide = ExamNavigationBarComponent.itemsVisiblePerSideDefault;\n } else if (this.layoutService.isBreakpointActive(CustomBreakpointNames.large)) {\n this.itemsVisiblePerSide = 3;\n } else if (this.layoutService.isBreakpointActive(CustomBreakpointNames.medium)) {\n this.itemsVisiblePerSide = 1;\n } else {\n this.itemsVisiblePerSide = 0;\n }\n });\n }\n\n triggerExamAboutToEnd() {\n this.saveExercise(false);\n this.examAboutToEnd.emit();\n }\n\n changeExercise(exerciseIndex: number, forceSave: boolean) {\n // out of index -> do nothing\n if (exerciseIndex > this.exercises.length - 1 || exerciseIndex < 0) {\n return;\n }\n // set index and emit event\n this.exerciseIndex = exerciseIndex;\n this.onExerciseChanged.emit({ exercise: this.exercises[exerciseIndex], forceSave });\n this.setExerciseButtonStatus(exerciseIndex);\n }\n\n /**\n * Save the currently active exercise and go to the next exercise.\n * @param changeExercise whether to go to the next exercise {boolean}\n */\n saveExercise(changeExercise = true) {\n const newIndex = this.exerciseIndex + 1;\n const submission = this.getSubmissionForExercise(this.exercises[this.exerciseIndex]);\n // we do not submit programming exercises on a save\n if (submission && this.exercises[this.exerciseIndex].type !== ExerciseType.PROGRAMMING) {\n submission.submitted = true;\n }\n if (changeExercise) {\n if (newIndex > this.exercises.length - 1) {\n // we are in the last exercise, if out of range \"change\" active exercise to current in order to trigger a save\n this.changeExercise(this.exerciseIndex, true);\n } else {\n this.changeExercise(newIndex, true);\n }\n }\n }\n\n isProgrammingExercise() {\n return this.exercises[this.exerciseIndex].type === ExerciseType.PROGRAMMING;\n }\n\n isFileUploadExercise() {\n return this.exercises[this.exerciseIndex].type === ExerciseType.FILE_UPLOAD;\n }\n\n setExerciseButtonStatus(exerciseIndex: number): 'synced' | 'synced active' | 'notSynced' {\n this.icon = 'edit';\n const exercise = this.exercises[exerciseIndex];\n const submission = this.getSubmissionForExercise(exercise);\n if (submission) {\n if (submission.submitted) {\n this.icon = 'check';\n }\n if (submission.isSynced) {\n // make button blue\n if (exerciseIndex === this.exerciseIndex) {\n return 'synced active';\n } else {\n return 'synced';\n }\n } else {\n // make button yellow\n this.icon = 'edit';\n return 'notSynced';\n }\n } else {\n // in case no participation yet exists -> display synced\n return 'synced';\n }\n }\n\n getExerciseButtonTooltip(exerciseIndex: number): 'submitted' | 'notSubmitted' | 'synced' | 'notSynced' | 'notSavedOrSubmitted' {\n const submission = this.getSubmissionForExercise(this.exercises[exerciseIndex]);\n if (submission) {\n if (this.exercises[exerciseIndex].type === ExerciseType.PROGRAMMING) {\n if (submission.submitted && submission.isSynced) {\n return 'submitted'; // You have submitted an exercise. You can submit again\n } else if (submission.submitted && !submission.isSynced) {\n return 'notSavedOrSubmitted'; // You have unsaved and/or unsubmitted changes\n } else if (!submission.submitted && submission.isSynced) {\n return 'notSubmitted'; // starting point\n } else {\n return 'notSavedOrSubmitted';\n }\n } else {\n if (submission.isSynced) {\n return 'synced';\n } else {\n return 'notSynced';\n }\n }\n } else {\n // submission does not yet exist for this exercise.\n // When the participant navigates to the exercise the submissions are created.\n // Until then show, that the exercise is synced\n return 'synced';\n }\n }\n\n /**\n * Notify parent component when user wants to hand in early\n */\n handInEarly() {\n this.saveExercise(false);\n this.onExamHandInEarly.emit();\n }\n\n // TODO: find usages of similar logic -> put into utils method\n getSubmissionForExercise(exercise: Exercise) {\n if (\n exercise &&\n exercise.studentParticipations &&\n exercise.studentParticipations.length > 0 &&\n exercise.studentParticipations[0].submissions &&\n exercise.studentParticipations[0].submissions.length > 0\n ) {\n return exercise.studentParticipations[0].submissions[0];\n } else {\n return undefined;\n }\n }\n}\n" }, { "alpha_fraction": 0.6351860761642456, "alphanum_fraction": 0.6362199187278748, "avg_line_length": 44.551246643066406, "blob_id": "f1846558e4a0b5b7c3cc295f34eedf7c503a94a2", "content_id": "efc8d8bbccd9ca51f1596c825f439bb089723b95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16444, "license_type": "permissive", "max_line_length": 175, "num_lines": 361, "path": "/src/main/webapp/app/exercises/shared/result/result.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { initializedResultWithScore } from 'app/exercises/shared/result/result-utils';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { HttpClient } from '@angular/common/http';\nimport { MIN_SCORE_GREEN, MIN_SCORE_ORANGE } from 'app/app.constants';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport * as moment from 'moment';\nimport { isProgrammingExerciseStudentParticipation, isResultPreliminary } from 'app/exercises/programming/shared/utils/programming-exercise.utils';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { getExercise, Participation, ParticipationType } from 'app/entities/participation/participation.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Submission, SubmissionExerciseType } from 'app/entities/submission.model';\nimport { isModelingOrTextOrFileUpload, isParticipationInDueTime, isProgrammingOrQuiz } from 'app/overview/participation-utils';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { ResultDetailComponent } from 'app/exercises/shared/result/result-detail.component';\nimport { Result } from 'app/entities/result.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { round } from 'app/shared/util/utils';\n\n/**\n * Enumeration object representing the possible options that\n * the status of the result's template can be in.\n */\nenum ResultTemplateStatus {\n IS_BUILDING = 'IS_BUILDING',\n HAS_RESULT = 'HAS_RESULT',\n NO_RESULT = 'NO_RESULT',\n SUBMITTED = 'SUBMITTED', // submitted and can still continue to submit\n SUBMITTED_WAITING_FOR_GRADING = 'SUBMITTED_WAITING_FOR_GRADING', // submitted and can no longer submit, not yet graded\n LATE_NO_FEEDBACK = 'LATE_NO_FEEDBACK', // started, submitted too late, not graded\n LATE = 'LATE', // submitted too late, graded\n}\n\n@Component({\n selector: 'jhi-result',\n templateUrl: './result.component.html',\n styles: ['span { display: inline-block; line-height: 1.25 }'],\n})\n\n/**\n * When using the result component make sure that the reference to the participation input is changed if the result changes\n * e.g. by using Object.assign to trigger ngOnChanges which makes sure that the result is updated\n */\nexport class ResultComponent implements OnInit, OnChanges {\n // make constants available to html for comparison\n readonly ResultTemplateStatus = ResultTemplateStatus;\n readonly round = round;\n\n @Input() participation: Participation;\n @Input() isBuilding: boolean;\n @Input() short = false;\n @Input() result?: Result;\n @Input() showUngradedResults: boolean;\n @Input() showGradedBadge = false;\n @Input() showTestDetails = false;\n\n ParticipationType = ParticipationType;\n textColorClass: string;\n hasFeedback: boolean;\n resultIconClass: string[];\n resultString: string;\n templateStatus: ResultTemplateStatus;\n submission?: Submission;\n\n resultTooltip: string;\n\n constructor(\n private jhiWebsocketService: JhiWebsocketService,\n private participationService: ParticipationService,\n private translate: TranslateService,\n private http: HttpClient,\n private modalService: NgbModal,\n ) {}\n\n /**\n * Executed on initialization. It retrieves the results of a given\n * participation and displays the corresponding message.\n */\n ngOnInit(): void {\n if (!this.result && this.participation && this.participation.id) {\n const exercise = getExercise(this.participation);\n\n if (this.participation.results && this.participation.results.length > 0) {\n if (exercise && exercise.type === ExerciseType.MODELING) {\n // sort results by completionDate descending to ensure the newest result is shown\n // this is important for modeling exercises since students can have multiple tries\n // think about if this should be used for all types of exercises\n this.participation.results.sort((r1: Result, r2: Result) => {\n if (r1.completionDate! > r2.completionDate!) {\n return -1;\n }\n if (r1.completionDate! < r2.completionDate!) {\n return 1;\n }\n return 0;\n });\n }\n // Make sure result and participation are connected\n if (!this.result) {\n this.result = this.participation.results[0];\n }\n this.result.participation = this.participation;\n }\n }\n // make sure this.participation is initialized in case it was not passed\n if (!this.participation && this.result && this.result.participation) {\n this.participation = this.result.participation;\n }\n if (this.result) {\n this.submission = this.result.submission;\n }\n this.evaluate();\n }\n\n /**\n * Executed when changes happen sets the corresponding template status to display a message.\n * @param changes The hashtable of the occurred changes as SimpleChanges object.\n */\n ngOnChanges(changes: SimpleChanges) {\n if (changes.participation || changes.result) {\n this.ngOnInit();\n // If is building, we change the templateStatus to building regardless of any other settings.\n } else if (changes.isBuilding && changes.isBuilding.currentValue) {\n this.templateStatus = ResultTemplateStatus.IS_BUILDING;\n // When the result was building and is not building anymore, we evaluate the result status.\n } else if (changes.isBuilding && changes.isBuilding.previousValue && !changes.isBuilding.currentValue) {\n this.evaluate();\n }\n }\n\n /**\n * Sets the corresponding icon, styling and message to display results.\n */\n evaluate() {\n this.templateStatus = this.evaluateTemplateStatus();\n\n if (this.templateStatus === ResultTemplateStatus.LATE) {\n this.textColorClass = this.getTextColorClass();\n this.resultIconClass = this.getResultIconClass();\n } else if (this.result && (this.result.score || this.result.score === 0) && (this.result.rated || this.result.rated == undefined || this.showUngradedResults)) {\n this.textColorClass = this.getTextColorClass();\n this.hasFeedback = this.getHasFeedback();\n this.resultIconClass = this.getResultIconClass();\n this.resultString = this.buildResultString();\n this.resultTooltip = this.buildResultTooltip();\n } else {\n // make sure that we do not display results that are 'rated=false' or that do not have a score\n // this state is only possible if no rated results are available at all, so we show the info that no graded result is available\n this.templateStatus = ResultTemplateStatus.NO_RESULT;\n this.result = undefined;\n }\n }\n\n private evaluateTemplateStatus() {\n // Fallback if participation is not set\n const exercise = getExercise(this.participation);\n if (!this.participation || !exercise) {\n if (!this.result) {\n return ResultTemplateStatus.NO_RESULT;\n } else {\n return ResultTemplateStatus.HAS_RESULT;\n }\n }\n\n // Evaluate status for modeling, text and file-upload exercises\n if (isModelingOrTextOrFileUpload(this.participation)) {\n // Based on its submission we test if the participation is in due time of the given exercise.\n\n const inDueTime = isParticipationInDueTime(this.participation, exercise);\n const dueDate = ResultComponent.dateAsMoment(exercise.dueDate);\n const assessmentDueDate = ResultComponent.dateAsMoment(exercise.assessmentDueDate);\n\n if (inDueTime && initializedResultWithScore(this.result)) {\n // Submission is in due time of exercise and has a result with score\n if (!assessmentDueDate || assessmentDueDate.isBefore()) {\n // the assessment due date has passed (or there was none)\n return ResultTemplateStatus.HAS_RESULT;\n } else {\n // the assessment period is still active\n return ResultTemplateStatus.SUBMITTED_WAITING_FOR_GRADING;\n }\n } else if (inDueTime && !initializedResultWithScore(this.result)) {\n // Submission is in due time of exercise and doesn't have a result with score.\n if (!dueDate || dueDate.isSameOrAfter()) {\n // the due date is in the future (or there is none) => the exercise is still ongoing\n return ResultTemplateStatus.SUBMITTED;\n } else if (!assessmentDueDate || assessmentDueDate.isSameOrAfter()) {\n // the due date is over, further submissions are no longer possible, waiting for grading\n return ResultTemplateStatus.SUBMITTED_WAITING_FOR_GRADING;\n } else {\n // the due date is over, further submissions are no longer possible, no result after assessment due date\n return ResultTemplateStatus.NO_RESULT;\n }\n } else if (initializedResultWithScore(this.result) && (!assessmentDueDate || assessmentDueDate.isBefore())) {\n // Submission is not in due time of exercise, has a result with score and there is no assessmentDueDate for the exercise or it lies in the past.\n // TODO handle external submissions with new status \"External\"\n return ResultTemplateStatus.LATE;\n } else {\n // Submission is not in due time of exercise and there is actually no feedback for the submission or the feedback should not be displayed yet.\n return ResultTemplateStatus.LATE_NO_FEEDBACK;\n }\n }\n\n // Evaluate status for programming and quiz exercises\n if (isProgrammingOrQuiz(this.participation)) {\n if (this.isBuilding) {\n return ResultTemplateStatus.IS_BUILDING;\n } else if (initializedResultWithScore(this.result)) {\n return ResultTemplateStatus.HAS_RESULT;\n } else {\n return ResultTemplateStatus.NO_RESULT;\n }\n }\n\n return ResultTemplateStatus.NO_RESULT;\n }\n\n private static dateAsMoment(date: any) {\n if (date == undefined) {\n return undefined;\n }\n return moment.isMoment(date) ? date : moment(date);\n }\n\n /**\n * Gets the build result string.\n */\n buildResultString() {\n if (this.submission && this.submission.submissionExerciseType === SubmissionExerciseType.PROGRAMMING && (this.submission as ProgrammingSubmission).buildFailed) {\n const isManualResult = this.result?.assessmentType !== AssessmentType.AUTOMATIC;\n return isManualResult ? this.result!.resultString : this.translate.instant('artemisApp.editor.buildFailed');\n // Only show the 'preliminary' string for programming student participation results and if the buildAndTestAfterDueDate has not passed.\n } else if (\n this.participation &&\n isProgrammingExerciseStudentParticipation(this.participation) &&\n isResultPreliminary(this.result!, getExercise(this.participation) as ProgrammingExercise)\n ) {\n const preliminary = '(' + this.translate.instant('artemisApp.result.preliminary') + ')';\n return `${this.result!.resultString} ${preliminary}`;\n }\n return this.result!.resultString;\n }\n\n /**\n * Only show the 'preliminary' tooltip for programming student participation results and if the buildAndTestAfterDueDate has not passed.\n */\n buildResultTooltip() {\n const programmingExercise = getExercise(this.participation) as ProgrammingExercise;\n if (this.participation && isProgrammingExerciseStudentParticipation(this.participation) && isResultPreliminary(this.result!, programmingExercise)) {\n if (programmingExercise?.assessmentType !== AssessmentType.AUTOMATIC) {\n return this.translate.instant('artemisApp.result.preliminaryTooltipSemiAutomatic');\n }\n return this.translate.instant('artemisApp.result.preliminaryTooltip');\n }\n }\n\n /**\n * Checks if there is feedback or not for a build result.\n */\n getHasFeedback(): boolean {\n if (this.submission && this.submission.submissionExerciseType === SubmissionExerciseType.PROGRAMMING && (this.submission as ProgrammingSubmission).buildFailed) {\n return true;\n } else if (this.result?.hasFeedback === undefined) {\n return false;\n }\n return this.result.hasFeedback;\n }\n\n /**\n * Show details of a result.\n * @param result Result object whose details will be displayed.\n */\n showDetails(result: Result) {\n if (!result.participation) {\n result.participation = this.participation;\n }\n const modalRef = this.modalService.open(ResultDetailComponent, { keyboard: true, size: 'lg' });\n const componentInstance: ResultDetailComponent = modalRef.componentInstance;\n componentInstance.result = result;\n const exercise = getExercise(this.participation);\n componentInstance.showTestDetails = (exercise?.type === ExerciseType.PROGRAMMING && (exercise as ProgrammingExercise).showTestNamesToStudents) || this.showTestDetails;\n if (exercise) {\n componentInstance.exerciseType = exercise.type!;\n componentInstance.showScoreChart = true;\n }\n }\n\n /**\n * Checks whether a build artifact exists for a submission.\n */\n hasBuildArtifact() {\n if (this.result && this.submission && this.submission.submissionExerciseType === SubmissionExerciseType.PROGRAMMING) {\n const submission = this.submission as ProgrammingSubmission;\n return submission.buildArtifact;\n }\n return false;\n }\n\n /**\n * Download the build results of a specific participation.\n * @param participationId The identifier of the participation.\n */\n downloadBuildResult(participationId?: number) {\n if (participationId) {\n this.participationService.downloadArtifact(participationId).subscribe((artifact) => {\n const fileURL = URL.createObjectURL(artifact.fileContent);\n const link = document.createElement('a');\n link.href = fileURL;\n link.target = '_blank';\n link.download = artifact.fileName;\n document.body.appendChild(link);\n link.click();\n });\n }\n }\n\n /**\n * Get the css class for the entire text as a string\n *\n * @return {string} the css class\n */\n getTextColorClass() {\n if (this.templateStatus === ResultTemplateStatus.LATE) {\n return 'result--late';\n }\n const result = this.result!;\n if (result.score == undefined) {\n if (result.successful) {\n return 'text-success';\n }\n return 'text-danger';\n }\n if (result.score > MIN_SCORE_GREEN) {\n return 'text-success';\n }\n if (result.score > MIN_SCORE_ORANGE) {\n return 'result-orange';\n }\n return 'text-danger';\n }\n\n /**\n * Get the icon type for the result icon as an array\n *\n */\n getResultIconClass(): string[] {\n const result = this.result!;\n if (result.score == undefined) {\n if (result.successful) {\n return ['far', 'check-circle'];\n }\n return ['far', 'times-circle'];\n }\n if (result.score > 80) {\n return ['far', 'check-circle'];\n }\n return ['far', 'times-circle'];\n }\n}\n" }, { "alpha_fraction": 0.7380596995353699, "alphanum_fraction": 0.7380596995353699, "avg_line_length": 50.53845977783203, "blob_id": "108d1bd232f5f66f09f89e846eff694dac97e1f6", "content_id": "113aefb36854660ad982b9263a7d426cde09d0e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2680, "license_type": "permissive", "max_line_length": 131, "num_lines": 52, "path": "/src/main/webapp/app/exam/participate/exercises/exam-submission.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Submission } from 'app/entities/submission.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ChangeDetectorRef } from '@angular/core';\n\nexport abstract class ExamSubmissionComponent {\n /**\n * checks whether the component has unsaved changes.\n * It is called in the periodic update timer to determine, if the component needs an update\n */\n abstract hasUnsavedChanges(): boolean;\n\n /**\n * updates the submission with the values from the displayed content.\n * This is called when the submission is save, so that the latest state is synchronized with the server\n */\n abstract updateSubmissionFromView(): void;\n\n /**\n * takes the current values from the submission and displays them\n * This is called when a component is initialized, because we want to display the state of the submission.\n * In case the submission has not been edited it is an empty submission.\n */\n abstract updateViewFromSubmission(): void;\n\n protected constructor(protected changeDetectorReference: ChangeDetectorRef) {}\n\n /**\n * Should be called when the component becomes active / visible. It activates Angular's change detection for this component.\n * We disabled Angular's change detection for invisible components, because of performance reasons. Here it is activated again,\n * that means once the component becomes active / visible, Angular will check for changes in the application state and update\n * the view if necessary. The performance improvement comes from not checking the components for updates while being invisible\n * For further customisation, individual submission components can override.\n */\n onActivate(): void {\n this.changeDetectorReference.reattach();\n }\n\n /**\n * Should be called when the component becomes deactivated / not visible. It deactivates Angular's change detection.\n * Angular change detection is responsible for synchronizing the view with the application state (often done over bindings)\n * We disabled Angular's change detection for invisible components for performance reasons. That means, that the component\n * will not be checked for updates and also will not be updated when it is invisible. Note: This works recursively, that means\n * subcomponents will also not be able to check for updates and update the view according to the application state.\n * For further customisation, individual submission components can override.\n */\n onDeactivate(): void {\n this.changeDetectorReference.detach();\n }\n\n abstract getSubmission(): Submission | undefined;\n abstract getExercise(): Exercise;\n}\n" }, { "alpha_fraction": 0.6920199394226074, "alphanum_fraction": 0.6957606077194214, "avg_line_length": 21.27777862548828, "blob_id": "f3c058e9360325a32cb45ec8a4c50014dc5f50b3", "content_id": "cc407d22e3212f4166c6d0daced07f9365c007cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 802, "license_type": "permissive", "max_line_length": 70, "num_lines": 36, "path": "/src/main/java/de/tum/in/www1/artemis/web/websocket/dto/SubmissionSyncPayload.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.websocket.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.Submission;\nimport de.tum.in.www1.artemis.domain.User;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class SubmissionSyncPayload {\n\n private Submission submission;\n\n private User sender;\n\n public SubmissionSyncPayload(Submission submission, User sender) {\n this.submission = submission;\n this.sender = sender;\n }\n\n public Submission getSubmission() {\n return submission;\n }\n\n public void setSubmission(Submission submission) {\n this.submission = submission;\n }\n\n public User getSender() {\n return sender;\n }\n\n public void setSender(User sender) {\n this.sender = sender;\n }\n\n}\n" }, { "alpha_fraction": 0.663892924785614, "alphanum_fraction": 0.663892924785614, "avg_line_length": 35.85333251953125, "blob_id": "d7e1ab4b0bb04f6ec63fe037f46b0ecbc585952f", "content_id": "52c5fe0bb4bb87ff6fb7425861f5d40010331997", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2764, "license_type": "permissive", "max_line_length": 126, "num_lines": 75, "path": "/src/test/javascript/spec/directive/build-plan-link.directive.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonStub, stub } from 'sinon';\nimport { Component, DebugElement } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../test.module';\nimport { ProgrammingExerciseUtilsModule } from 'app/exercises/programming/shared/utils/programming-exercise-utils.module';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { MockProfileService } from '../helpers/mocks/service/mock-profile.service';\nimport { BehaviorSubject } from 'rxjs';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({\n selector: 'jhi-test-component',\n template: '<a jhiBuildPlanLink [projectKey]=\"projectKey\" [buildPlanId]=\"buildPlanId\"></a>',\n})\nclass TestComponent {\n projectKey = 'FOO';\n buildPlanId = 'BAR';\n}\n\ndescribe('BuildPlanLinkDirective', () => {\n let fixture: ComponentFixture<TestComponent>;\n let debugElement: DebugElement;\n let profileService: ProfileService;\n let getProfileInfoStub: SinonStub;\n let profileInfoSubject: BehaviorSubject<ProfileInfo | null>;\n\n const profileInfo = { buildPlanURLTemplate: 'https://some.url.com/plans/{buildPlanId}/path/{projectKey}' } as ProfileInfo;\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ProgrammingExerciseUtilsModule],\n declarations: [TestComponent],\n providers: [{ provide: ProfileService, useClass: MockProfileService }],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(TestComponent);\n debugElement = fixture.debugElement;\n\n profileService = fixture.debugElement.injector.get(ProfileService);\n\n getProfileInfoStub = stub(profileService, 'getProfileInfo');\n\n profileInfoSubject = new BehaviorSubject<ProfileInfo | null>(profileInfo);\n getProfileInfoStub.returns(profileInfoSubject);\n });\n });\n\n afterEach(() => {\n getProfileInfoStub.restore();\n profileInfoSubject.complete();\n });\n\n it('should inject the correct build plan URL', fakeAsync(() => {\n const open = stub(window, 'open');\n window.open = open;\n\n fixture.detectChanges();\n tick();\n\n const link = debugElement.query(By.css('a'));\n link.triggerEventHandler('click', { preventDefault: () => {} });\n\n fixture.detectChanges();\n tick();\n\n expect(open).to.be.calledOnce;\n }));\n});\n" }, { "alpha_fraction": 0.7171428799629211, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 65.66666412353516, "blob_id": "be4702e92ba128d3df2e19d9c9424a4a219e9a42", "content_id": "6f02f8993c25bf3127f33836ed9de4f6732c4097", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1400, "license_type": "permissive", "max_line_length": 179, "num_lines": 21, "path": "/src/main/webapp/app/shared/participant-scores/participant-scores-tables-container/participant-scores-tables-container.component.html", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<button class=\"btn btn-info mb-2\" (click)=\"reload.emit()\">Refresh</button>\n<div class=\"btn-group btn-group-toggle mb-2\" ngbRadioGroup name=\"radioBasic\" [(ngModel)]=\"mode\">\n <label ngbButtonLabel class=\"btn-primary\"> <input ngbButton type=\"radio\" [value]=\"'individual'\" /> {{ 'artemisApp.participantScores.individual' | translate }} </label>\n <label ngbButtonLabel class=\"btn-primary\"> <input ngbButton type=\"radio\" [value]=\"'average'\" /> {{ 'artemisApp.participantScores.average' | translate }} </label>\n</div>\n\n<ng-template #tipContent>{{ 'artemisApp.participantScores.notIncluded' | translate }}</ng-template>\n<span class=\"badge rounded-pill bg-primary text-white\" [ngbTooltip]=\"tipContent\">{{ 'artemisApp.participantScores.averageScore' | translate: { avg: round(avgScore, 1) } }} </span>\n\n<span class=\"badge rounded-pill bg-primary text-white\" [ngbTooltip]=\"tipContent\"\n >{{ 'artemisApp.participantScores.averageRatedScore' | translate: { avg: round(avgRatedScore, 1) } }}\n</span>\n\n<div [ngSwitch]=\"mode\">\n <jhi-participant-scores-table *ngSwitchCase=\"'individual'\" [isLoading]=\"isLoading\" [participantScores]=\"participantScores\"></jhi-participant-scores-table>\n <jhi-participant-scores-average-table\n *ngSwitchCase=\"'average'\"\n [isLoading]=\"isLoading\"\n [participantAverageScores]=\"participantScoresAverage\"\n ></jhi-participant-scores-average-table>\n</div>\n" }, { "alpha_fraction": 0.5625653266906738, "alphanum_fraction": 0.5660508871078491, "avg_line_length": 42.14285659790039, "blob_id": "0a1355f2b0a3075e94a7981284cac099c89c0041", "content_id": "068134a230f94cf9a70955917f4322e23aed3a74", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5738, "license_type": "permissive", "max_line_length": 169, "num_lines": 133, "path": "/src/test/javascript/spec/component/lecture-unit/video-unit/create-video-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { VideoUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { CreateVideoUnitComponent } from 'app/lecture/lecture-unit/lecture-unit-management/create-video-unit/create-video-unit.component';\nimport { VideoUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/videoUnit.service';\nimport { MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { Observable, of } from 'rxjs';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport * as moment from 'moment';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-video-unit-form', template: '' })\nclass VideoUnitFormStubComponent {\n @Input() isEditMode = false;\n @Output() formSubmitted: EventEmitter<VideoUnitFormData> = new EventEmitter<VideoUnitFormData>();\n}\n\n@Component({ selector: 'jhi-lecture-unit-layout', template: '<ng-content></ng-content>' })\nclass LectureUnitLayoutStubComponent {\n @Input()\n isLoading = false;\n}\n\ndescribe('CreateVideoUnitComponent', () => {\n let createVideoUnitComponentFixture: ComponentFixture<CreateVideoUnitComponent>;\n let createVideoUnitComponent: CreateVideoUnitComponent;\n const sandbox = sinon.createSandbox();\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [VideoUnitFormStubComponent, LectureUnitLayoutStubComponent, CreateVideoUnitComponent],\n providers: [\n MockProvider(VideoUnitService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'lectureId':\n return 1;\n }\n },\n }),\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'courseId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n createVideoUnitComponentFixture = TestBed.createComponent(CreateVideoUnitComponent);\n createVideoUnitComponent = createVideoUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n createVideoUnitComponentFixture.detectChanges();\n expect(createVideoUnitComponent).to.be.ok;\n });\n\n it('should send POST request upon form submission and navigate', fakeAsync(() => {\n const router: Router = TestBed.inject(Router);\n const videoUnitService = TestBed.inject(VideoUnitService);\n\n const formDate: VideoUnitFormData = {\n name: 'Test',\n releaseDate: moment({ years: 2010, months: 3, date: 5 }),\n description: 'Lorem Ipsum',\n source: 'https://www.youtube.com/embed/8iU8LPEa4o0',\n };\n\n const response: HttpResponse<VideoUnit> = new HttpResponse({\n body: new VideoUnit(),\n status: 201,\n });\n\n const createStub = sandbox.stub(videoUnitService, 'create').returns(of(response));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n createVideoUnitComponentFixture.detectChanges();\n tick();\n const videoUnitForm: VideoUnitFormStubComponent = createVideoUnitComponentFixture.debugElement.query(By.directive(VideoUnitFormStubComponent)).componentInstance;\n videoUnitForm.formSubmitted.emit(formDate);\n\n createVideoUnitComponentFixture.whenStable().then(() => {\n const videoUnitCallArgument: VideoUnit = createStub.getCall(0).args[0];\n const lectureIdCallArgument: number = createStub.getCall(0).args[1];\n\n expect(videoUnitCallArgument.name).to.equal(formDate.name);\n expect(videoUnitCallArgument.description).to.equal(formDate.description);\n expect(videoUnitCallArgument.releaseDate).to.equal(formDate.releaseDate);\n expect(videoUnitCallArgument.source).to.equal(formDate.source);\n expect(lectureIdCallArgument).to.equal(1);\n\n expect(createStub).to.have.been.calledOnce;\n expect(navigateSpy).to.have.been.calledOnce;\n\n navigateSpy.restore();\n });\n }));\n});\n" }, { "alpha_fraction": 0.6894223690032959, "alphanum_fraction": 0.690172553062439, "avg_line_length": 47.180721282958984, "blob_id": "d43eb194a733909981edaa52e7db130bfb9dd421", "content_id": "ac9687041e1415b2a0c3f4f3aee5f2c565ae5625", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3999, "license_type": "permissive", "max_line_length": 122, "num_lines": 83, "path": "/src/test/javascript/spec/component/course/course-management-exercises.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute, convertToParamMap } from '@angular/router';\nimport { NgbCollapse } from '@ng-bootstrap/ng-bootstrap';\nimport { CourseExerciseCardComponent } from 'app/course/manage/course-exercise-card.component';\nimport { CourseManagementExercisesComponent } from 'app/course/manage/course-management-exercises.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Course } from 'app/entities/course.model';\nimport { FileUploadExerciseComponent } from 'app/exercises/file-upload/manage/file-upload-exercise.component';\nimport { ModelingExerciseComponent } from 'app/exercises/modeling/manage/modeling-exercise.component';\nimport { ProgrammingExerciseComponent } from 'app/exercises/programming/manage/programming-exercise.component';\nimport { QuizExerciseComponent } from 'app/exercises/quiz/manage/quiz-exercise.component';\nimport { TextExerciseComponent } from 'app/exercises/text/manage/text-exercise/text-exercise.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { OrionFilterDirective } from 'app/shared/orion/orion-filter.directive';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { of } from 'rxjs/internal/observable/of';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Course Management Exercises Component', () => {\n let comp: CourseManagementExercisesComponent;\n let fixture: ComponentFixture<CourseManagementExercisesComponent>;\n let courseService: CourseManagementService;\n const course = new Course();\n course.id = 123;\n const parentRoute = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute;\n const route = ({ parent: parentRoute } as any) as ActivatedRoute;\n let findStub: sinon.SinonStub;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [\n CourseManagementExercisesComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(CourseExerciseCardComponent),\n MockDirective(NgbCollapse),\n MockDirective(JhiTranslateDirective),\n MockComponent(AlertComponent),\n MockComponent(ProgrammingExerciseComponent),\n MockDirective(OrionFilterDirective),\n MockComponent(QuizExerciseComponent),\n MockComponent(ModelingExerciseComponent),\n MockComponent(FileUploadExerciseComponent),\n MockComponent(TextExerciseComponent),\n ],\n providers: [\n MockProvider(CourseManagementService),\n {\n provide: ActivatedRoute,\n useValue: route,\n },\n ],\n }).compileComponents();\n fixture = TestBed.createComponent(CourseManagementExercisesComponent);\n comp = fixture.componentInstance;\n courseService = TestBed.inject(CourseManagementService);\n findStub = sinon.stub(courseService, 'find');\n findStub.returns(of(new HttpResponse({ body: course })));\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(CourseManagementExercisesComponent).to.be.ok;\n });\n\n it('should find course on on init', () => {\n comp.ngOnInit();\n expect(comp.courseId).to.equal(course.id);\n expect(findStub).to.have.been.calledWith(course.id);\n });\n});\n" }, { "alpha_fraction": 0.5376681685447693, "alphanum_fraction": 0.5401345491409302, "avg_line_length": 29.135135650634766, "blob_id": "5a279170d88ac3b14b63afa8509fcd0e712a98e9", "content_id": "011cf79f45b10fb48b1d045187541dd111f30cb3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4460, "license_type": "permissive", "max_line_length": 174, "num_lines": 148, "path": "/src/main/webapp/app/shared/chart/chart.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, ViewChild } from '@angular/core';\nimport { ChartDataSets, ChartHoverOptions, ChartLayoutPaddingObject, ChartLegendOptions, ChartOptions, ChartTooltipOptions, ChartType, ChartXAxe, ChartYAxe } from 'chart.js';\nimport { BaseChartDirective, Label } from 'ng2-charts';\n\nexport interface ChartPreset {\n applyTo(chart: ChartComponent): void;\n}\n\n@Component({\n selector: 'jhi-chart',\n template: `\n <div style=\"position: relative; width: 100%; height: 100%;\">\n <canvas baseChart [datasets]=\"chartDatasets\" [labels]=\"chartLabels\" [options]=\"chartOptions\" [chartType]=\"chartType\"></canvas>\n </div>\n `,\n})\nexport class ChartComponent {\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n @Input() set preset(preset: ChartPreset) {\n preset.applyTo(this);\n }\n\n @Input() set type(type: ChartType) {\n this.chartType = type;\n }\n @Input() set datasets(datasets: ChartDataSets[]) {\n this.chartDatasets = datasets;\n }\n @Input() set labels(labels: Label[]) {\n this.chartLabels = labels;\n }\n @Input() set options(options: ChartOptions) {\n this.chartOptions = options;\n }\n\n chartDatasets: ChartDataSets[] = [];\n chartType: ChartType = 'bar';\n chartLabels: Label[] = [];\n chartOptions: ChartOptions = {\n responsive: true,\n maintainAspectRatio: false,\n layout: {\n padding: {\n left: 0,\n right: 0,\n top: 0,\n bottom: 0,\n },\n },\n legend: {\n display: false,\n },\n title: {\n display: false,\n },\n tooltips: {\n enabled: false,\n },\n scales: {\n yAxes: [],\n xAxes: [],\n },\n };\n\n setType(type: ChartType) {\n this.chartType = type;\n }\n\n private applyOptions(fn: (options: ChartOptions) => void, shouldUpdate = true) {\n if (this.chart) {\n fn(this.chart.options);\n if (shouldUpdate) {\n this.chart.update();\n }\n } else {\n fn(this.chartOptions);\n }\n }\n\n setPadding(padding: ChartLayoutPaddingObject, shouldUpdate = true) {\n this.applyOptions((options) => {\n Object.assign(options.layout!.padding, padding);\n }, shouldUpdate);\n }\n\n setLegend(legend: ChartLegendOptions | boolean, shouldUpdate = true) {\n this.applyOptions((options) => {\n if (typeof legend === 'boolean') {\n Object.assign(options.legend, { display: legend });\n } else {\n Object.assign(options.legend, { display: true }, legend);\n }\n }, shouldUpdate);\n }\n\n setTooltip(tooltip: ChartTooltipOptions | boolean, shouldUpdate = true) {\n this.applyOptions((options) => {\n if (typeof tooltip === 'boolean') {\n Object.assign(options.tooltips, { enabled: tooltip });\n } else {\n Object.assign(options.tooltips, { enabled: true }, tooltip);\n }\n }, shouldUpdate);\n }\n\n setHover(hover: ChartHoverOptions, shouldUpdate = true) {\n this.applyOptions((options) => {\n if (!options.hover) {\n options.hover = hover;\n } else {\n Object.assign(options.hover, hover);\n }\n }, shouldUpdate);\n }\n\n setYAxe(index: number, axe: ChartYAxe, shouldUpdate = true) {\n this.applyOptions((options) => {\n if (!options.scales!.yAxes![index]) {\n options.scales!.yAxes![index] = axe;\n } else {\n Object.assign(options.scales!.yAxes![index], axe);\n }\n }, shouldUpdate);\n }\n\n setXAxe(index: number, axe: ChartXAxe, shouldUpdate = true) {\n this.applyOptions((options) => {\n if (!options.scales!.xAxes![index]) {\n options.scales!.xAxes![index] = axe;\n } else {\n Object.assign(options.scales!.xAxes![index], axe);\n }\n }, shouldUpdate);\n }\n\n updateDataset(index: number, dataset: ChartDataSets) {\n if (!this.chartDatasets[index]) {\n this.chartDatasets[index] = dataset;\n } else {\n Object.assign(this.chartDatasets[index], dataset);\n }\n }\n\n setLabels(labels: Label[]) {\n this.chartLabels = labels;\n }\n}\n" }, { "alpha_fraction": 0.7422183156013489, "alphanum_fraction": 0.7444103360176086, "avg_line_length": 43.72549057006836, "blob_id": "f0779bc1a3407e9264b2935170f2b8e87c48c729", "content_id": "c68cdf89310885de0480b434b9b744fbd0dfc2ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2281, "license_type": "permissive", "max_line_length": 175, "num_lines": 51, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-detail-modal/learning-goal-detail-modal.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { round } from 'app/shared/util/utils';\n\n@Component({\n selector: 'jhi-learning-goal-detail-modal',\n templateUrl: './learning-goal-detail-modal.component.html',\n})\nexport class LearningGoalDetailModalComponent implements OnInit {\n readonly round = round;\n @Input()\n learningGoal: LearningGoal;\n @Input()\n learningGoalProgress: IndividualLearningGoalProgress;\n\n public lectureUnitIdToLectureUnitProgress = new Map();\n\n public isProgressAvailable = false;\n public progressInPercent = 0;\n public connectedLectureUnitsPredicate = 'id';\n public connectedLectureUnitsReverse = false;\n\n constructor(public activeModal: NgbActiveModal, public lectureUnitService: LectureUnitService, public sortService: SortService) {}\n\n ngOnInit(): void {\n if (this.learningGoalProgress && this.learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal > 0) {\n this.isProgressAvailable = true;\n\n if (this.learningGoalProgress.progressInLectureUnits) {\n this.lectureUnitIdToLectureUnitProgress = new Map(this.learningGoalProgress.progressInLectureUnits.map((i) => [i.lectureUnitId, i]));\n }\n\n const progress = (this.learningGoalProgress.pointsAchievedByStudentInLearningGoal / this.learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal) * 100;\n this.progressInPercent = round(progress);\n }\n }\n\n getLectureUnitProgress(lectureUnitId: number) {\n return this.lectureUnitIdToLectureUnitProgress.get(lectureUnitId);\n }\n\n sortConnectedLectureUnits() {\n if (this.learningGoal.lectureUnits) {\n this.sortService.sortByProperty(this.learningGoal.lectureUnits, this.connectedLectureUnitsPredicate, this.connectedLectureUnitsReverse);\n }\n }\n}\n" }, { "alpha_fraction": 0.6036431789398193, "alphanum_fraction": 0.6071361303329468, "avg_line_length": 44.12711715698242, "blob_id": "3ad04cc08e52f1b6d8e3be562db998459e4e53f0", "content_id": "2a24a162ab6b92c2186ac335acc0288087aa1c7a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 26625, "license_type": "permissive", "max_line_length": 169, "num_lines": 590, "path": "/src/test/javascript/spec/component/exercises/quiz/quiz-participation.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { ComponentFixture, discardPeriodicTasks, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizQuestion, QuizQuestionType } from 'app/entities/quiz/quiz-question.model';\nimport { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';\nimport { SubmittedAnswer } from 'app/entities/quiz/submitted-answer.model';\nimport { Result } from 'app/entities/result.model';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { QuizParticipationComponent } from 'app/exercises/quiz/participate/quiz-participation.component';\nimport { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component';\nimport { MultipleChoiceQuestionComponent } from 'app/exercises/quiz/shared/questions/multiple-choice-question/multiple-choice-question.component';\nimport { ShortAnswerQuestionComponent } from 'app/exercises/quiz/shared/questions/short-answer-question/short-answer-question.component';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ButtonComponent } from 'app/shared/components/button.component';\nimport { JhiConnectionStatusComponent } from 'app/shared/connection-status/connection-status.component';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ArtemisQuizService } from 'app/shared/quiz/quiz.service';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockLocalStorageService } from '../../../helpers/mocks/service/mock-local-storage.service';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n// Store a copy of now to avoid timing issues\nconst now = moment();\nconst question1 = { id: 1, type: QuizQuestionType.DRAG_AND_DROP, points: 1 } as QuizQuestion;\nconst question2 = { id: 2, type: QuizQuestionType.MULTIPLE_CHOICE, points: 2, answerOptions: [] } as QuizQuestion;\nconst question3 = { id: 3, type: QuizQuestionType.SHORT_ANSWER, points: 3 } as QuizQuestion;\n\nconst quizExercise = (<any>{\n id: 1,\n quizQuestions: [question1, question2, question3],\n releaseDate: moment(now).subtract(2, 'minutes'),\n adjustedReleaseDate: moment(now).subtract(2, 'minutes'),\n dueDate: moment(now).add(2, 'minutes'),\n adjustedDueDate: moment(now).add(2, 'minutes'),\n started: true,\n}) as QuizExercise;\nconst quizExerciseForPractice = (<any>{\n id: 1,\n quizQuestions: [question1, question2, question3],\n releaseDate: moment(now).subtract(4, 'minutes'),\n adjustedReleaseDate: moment(now).subtract(4, 'minutes'),\n dueDate: moment(now).subtract(2, 'minutes'),\n adjustedDueDate: moment(now).subtract(2, 'minutes'),\n isOpenForPractice: true,\n}) as QuizExercise;\nconst quizExerciseForResults = (<any>{\n id: 1,\n quizQuestions: [question1, question2, question3],\n releaseDate: moment(now).subtract(4, 'minutes'),\n adjustedReleaseDate: moment(now).subtract(4, 'minutes'),\n dueDate: moment(now).subtract(2, 'minutes'),\n adjustedDueDate: moment(now).subtract(2, 'minutes'),\n ended: true,\n}) as QuizExercise;\nconst quizExerciseUnreleased = (<any>{\n id: 1,\n quizQuestions: [question1, question2, question3],\n releaseDate: moment(now).add(2, 'days'),\n adjustedReleaseDate: moment(now).add(2, 'days'),\n dueDate: moment(now).add(4, 'days'),\n adjustedDueDate: moment(now).add(4, 'days'),\n ended: true,\n}) as QuizExercise;\n\nconst testBedDeclarations = [\n QuizParticipationComponent,\n MockComponent(AlertComponent),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockDirective(JhiTranslateDirective),\n MockComponent(MultipleChoiceQuestionComponent),\n MockComponent(DragAndDropQuestionComponent),\n MockComponent(ShortAnswerQuestionComponent),\n MockComponent(ButtonComponent),\n MockComponent(JhiConnectionStatusComponent),\n MockDirective(NgbTooltip),\n];\n\ndescribe('QuizParticipationComponent', () => {\n let fixture: ComponentFixture<QuizParticipationComponent>;\n let component: QuizParticipationComponent;\n let participationStub: sinon.SinonStub;\n let resultForSolutionServiceStub: sinon.SinonStub;\n let httpMock: HttpTestingController;\n let exerciseService: QuizExerciseService;\n\n describe('live mode', () => {\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n declarations: testBedDeclarations,\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n params: of({ courseId: 1, exerciseId: quizExercise.id }),\n data: of({ mode: 'live' }),\n },\n },\n {\n provide: LocalStorageService,\n useClass: MockLocalStorageService,\n },\n {\n provide: SessionStorageService,\n useClass: MockSyncStorage,\n },\n {\n provide: TranslateService,\n useClass: MockTranslateService,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(QuizParticipationComponent);\n component = fixture.componentInstance;\n\n const participationService = fixture.debugElement.injector.get(ParticipationService);\n const participation = { exercise: quizExercise } as StudentParticipation;\n participationStub = sinon.stub(participationService, 'findParticipation').returns(of({ body: participation } as HttpResponse<StudentParticipation>));\n httpMock = fixture.debugElement.injector.get(HttpTestingController);\n });\n });\n\n afterEach(function () {\n httpMock.verify();\n sinon.restore();\n });\n\n afterEach(fakeAsync(function () {\n discardPeriodicTasks();\n }));\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n });\n\n it('should fetch exercise and create a new submission', () => {\n fixture.detectChanges();\n\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n expect(component.quizExercise).to.equal(quizExercise);\n expect(component.waitingForQuizStart).to.be.false;\n expect(component.totalScore).to.equal(6);\n expect(component.dragAndDropMappings.get(question1.id!)).to.deep.equal([]);\n expect(component.selectedAnswerOptions.get(question2.id!)).to.deep.equal([]);\n expect(component.shortAnswerSubmittedTexts.get(question3.id!)).to.deep.equal([]);\n expect(component.submission).to.be.ok;\n });\n\n it('should update in intervals', fakeAsync(() => {\n fixture.detectChanges();\n\n const updateSpy = sinon.spy(component, 'updateDisplayedTimes');\n tick(5000);\n fixture.detectChanges();\n discardPeriodicTasks();\n\n expect(updateSpy).to.have.been.called;\n }));\n\n it('should refresh quiz', () => {\n exerciseService = fixture.debugElement.injector.get(QuizExerciseService);\n fixture.detectChanges();\n\n component.quizExercise.started = false;\n\n // Returns the started exercise\n const findStudentStub = sinon.stub(exerciseService, 'findForStudent').returns(of({ body: quizExercise } as HttpResponse<QuizExercise>));\n fixture.detectChanges();\n\n const refreshButton = fixture.debugElement.nativeElement.querySelector('#refresh-quiz');\n expect(refreshButton).to.exist;\n\n refreshButton.click();\n fixture.detectChanges();\n\n expect(findStudentStub).to.have.been.calledWith(quizExercise.id);\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n });\n\n it('should submit quiz', () => {\n fixture.detectChanges();\n\n const submitButton = fixture.debugElement.nativeElement.querySelector('#submit-quiz');\n expect(submitButton).to.exist;\n\n submitButton.click();\n fixture.detectChanges();\n\n const request = httpMock.expectOne({ method: 'POST' });\n request.flush({ submissionDate: now } as QuizSubmission);\n expect(request.request.url).to.equal(`api/exercises/${quizExercise.id}/submissions/live`);\n fixture.detectChanges();\n\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n expect(component.isSubmitting).to.be.false;\n });\n\n it('should return true if student didnt interact with any question', () => {\n component.quizExercise = { ...quizExercise, quizQuestions: undefined };\n expect(component.areAllQuestionsAnswered()).to.be.true;\n\n component.quizExercise = quizExercise;\n component.selectedAnswerOptions = new Map<number, AnswerOption[]>();\n component.selectedAnswerOptions.set(2, []);\n expect(component.areAllQuestionsAnswered()).to.be.false;\n\n component.selectedAnswerOptions = new Map<number, AnswerOption[]>();\n component.dragAndDropMappings = new Map<number, DragAndDropMapping[]>();\n component.dragAndDropMappings.set(1, []);\n expect(component.areAllQuestionsAnswered()).to.be.false;\n\n component.selectedAnswerOptions = new Map<number, AnswerOption[]>();\n component.dragAndDropMappings = new Map<number, DragAndDropMapping[]>();\n component.shortAnswerSubmittedTexts = new Map<number, ShortAnswerSubmittedText[]>();\n component.shortAnswerSubmittedTexts.set(3, []);\n expect(component.areAllQuestionsAnswered()).to.be.false;\n });\n\n it('should show warning on submit', () => {\n const confirmStub = sinon.stub(window, 'confirm').returns(true);\n fixture.detectChanges();\n\n // Set a value > 15 to simulate an early hand in without answered questions\n component.remainingTimeSeconds = 200;\n\n const submitButton = fixture.debugElement.nativeElement.querySelector('#submit-quiz');\n expect(submitButton).to.exist;\n\n submitButton.click();\n fixture.detectChanges();\n\n const request = httpMock.expectOne({ method: 'POST' });\n request.flush({ submissionDate: now } as QuizSubmission);\n expect(request.request.url).to.equal(`api/exercises/${quizExercise.id}/submissions/live`);\n fixture.detectChanges();\n\n expect(confirmStub).to.have.been.called;\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n expect(component.isSubmitting).to.be.false;\n });\n\n it('should show results after ending', () => {\n fixture.detectChanges();\n\n const answer = { scoreInPoints: 1, quizQuestion: question2 } as SubmittedAnswer;\n const quizSubmission = { submissionDate: now.subtract(3, 'minutes'), submittedAnswers: [answer], scoreInPoints: 1 } as QuizSubmission;\n const result = { resultString: 'result!', submission: quizSubmission } as Result;\n const participation = { exercise: quizExerciseForResults, results: [result] } as StudentParticipation;\n component.showQuizResultAfterQuizEnd(participation);\n\n expect(participationStub).to.have.been.calledWith(quizExercise.id);\n expect(component.questionScores[question2.id!]).to.equal(answer.scoreInPoints);\n expect(component.userScore).to.equal(quizSubmission.scoreInPoints);\n expect(component.showingResult).to.be.true;\n });\n\n it('should update on selection changes', () => {\n const webSocketService = fixture.debugElement.injector.get(JhiWebsocketService);\n const webSocketStub = sinon.stub(webSocketService, 'send');\n const applySpy = sinon.spy(component, 'applySelection');\n fixture.detectChanges();\n\n component.onSelectionChanged();\n\n expect(applySpy).to.have.been.called;\n expect(webSocketStub).to.have.been.called;\n });\n\n it('should react to errors', () => {\n const alertService = fixture.debugElement.injector.get(JhiAlertService);\n const alertStub = sinon.stub(alertService, 'error').returns({ msg: '' } as any);\n fixture.detectChanges();\n\n component.onSubmitError({ message: 'error' } as any);\n expect(component.isSubmitting).to.be.false;\n\n component.onSaveError('error');\n expect(component.isSubmitting).to.be.false;\n expect(component.unsavedChanges).to.be.true;\n\n expect(alertStub).to.have.been.called;\n });\n\n it('should express timespan in humanized text', () => {\n expect(component.relativeTimeText(100020)).to.equal('1667 min');\n expect(component.relativeTimeText(60)).to.equal('1 min 0 s');\n expect(component.relativeTimeText(5)).to.equal('5 s');\n });\n\n it('should adjust release date of the quiz if it didnt start', () => {\n const releaseDate = moment().add(1, 'minutes');\n const timeUntilPlannedStart = 10;\n const quizToApply = { ...quizExercise, started: false, isPlannedToStart: true, releaseDate, timeUntilPlannedStart };\n\n component.applyQuizFull(quizToApply);\n expect(component.quizExercise).to.equal(quizToApply);\n expect(component.quizExercise.releaseDate!.toString()).to.equal(releaseDate.toString());\n });\n\n it('should apply participation', () => {\n const submission: QuizSubmission = { id: 1, submissionDate: moment().subtract(10, 'minutes'), submittedAnswers: [] };\n const result: Result = { id: 1, submission, resultString: 'result-string' };\n const endedQuizExercise = { ...quizExercise, ended: true };\n const participation: StudentParticipation = { exercise: endedQuizExercise, results: [result] };\n\n component.quizExercise = quizExercise;\n component.timeDifference = 10;\n component.updateParticipationFromServer(participation);\n\n expect(component.submission.id).to.equal(submission.id);\n expect(component.quizExercise.ended).to.be.true;\n });\n });\n\n describe('preview mode', () => {\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n declarations: testBedDeclarations,\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n params: of({ courseId: 1, exerciseId: quizExercise.id }),\n data: of({ mode: 'preview' }),\n },\n },\n {\n provide: LocalStorageService,\n useClass: MockLocalStorageService,\n },\n {\n provide: SessionStorageService,\n useClass: MockSyncStorage,\n },\n {\n provide: TranslateService,\n useClass: MockTranslateService,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(QuizParticipationComponent);\n component = fixture.componentInstance;\n\n exerciseService = fixture.debugElement.injector.get(QuizExerciseService);\n httpMock = fixture.debugElement.injector.get(HttpTestingController);\n });\n });\n\n afterEach(function () {\n httpMock.verify();\n sinon.restore();\n });\n\n it('should initialize', () => {\n const serviceStub = sinon.stub(exerciseService, 'find');\n fixture.detectChanges();\n\n expect(component).to.be.ok;\n expect(serviceStub).to.have.been.calledWith(quizExercise.id);\n });\n\n it('should initialize and start', () => {\n const quizService = fixture.debugElement.injector.get(ArtemisQuizService);\n const serviceStub = sinon.stub(exerciseService, 'find').returns(of({ body: quizExercise } as HttpResponse<QuizExercise>));\n const startSpy = sinon.spy(component, 'startQuizPreviewOrPractice');\n const randomizeStub = sinon.stub(quizService, 'randomizeOrder');\n fixture.detectChanges();\n\n expect(component).to.be.ok;\n expect(serviceStub).to.have.been.calledWith(quizExercise.id);\n expect(startSpy).to.have.been.called;\n expect(randomizeStub).to.have.been.called;\n });\n\n it('should submit quiz', () => {\n const serviceStub = sinon.stub(exerciseService, 'find').returns(of({ body: quizExercise } as HttpResponse<QuizExercise>));\n fixture.detectChanges();\n\n const submitButton = fixture.debugElement.nativeElement.querySelector('#submit-quiz');\n expect(submitButton).to.exist;\n\n submitButton.click();\n fixture.detectChanges();\n\n const request = httpMock.expectOne({ method: 'POST' });\n request.flush({ submission: { submissionDate: now, submitted: true } as QuizSubmission } as Result);\n expect(request.request.url).to.equal(`api/exercises/${quizExercise.id}/submissions/preview`);\n fixture.detectChanges();\n\n expect(serviceStub).to.have.been.calledWith(quizExercise.id);\n });\n });\n\n describe('practice mode', () => {\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n declarations: testBedDeclarations,\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n params: of({ courseId: 1, exerciseId: quizExerciseForPractice.id }),\n data: of({ mode: 'practice' }),\n },\n },\n {\n provide: LocalStorageService,\n useClass: MockLocalStorageService,\n },\n {\n provide: SessionStorageService,\n useClass: MockSyncStorage,\n },\n {\n provide: TranslateService,\n useClass: MockTranslateService,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(QuizParticipationComponent);\n component = fixture.componentInstance;\n\n exerciseService = fixture.debugElement.injector.get(QuizExerciseService);\n httpMock = fixture.debugElement.injector.get(HttpTestingController);\n });\n });\n\n afterEach(function () {\n httpMock.verify();\n sinon.restore();\n });\n\n it('should initialize', () => {\n const serviceStub = sinon.stub(exerciseService, 'findForStudent');\n fixture.detectChanges();\n\n expect(component).to.be.ok;\n expect(serviceStub).to.have.been.calledWith(quizExerciseForPractice.id);\n });\n\n it('should initialize and start', () => {\n const quizService = fixture.debugElement.injector.get(ArtemisQuizService);\n const serviceStub = sinon.stub(exerciseService, 'findForStudent').returns(of({ body: quizExerciseForPractice } as HttpResponse<QuizExercise>));\n const startSpy = sinon.spy(component, 'startQuizPreviewOrPractice');\n const randomizeStub = sinon.stub(quizService, 'randomizeOrder');\n fixture.detectChanges();\n\n expect(component).to.be.ok;\n expect(serviceStub).to.have.been.calledWith(quizExerciseForPractice.id);\n expect(startSpy).to.have.been.called;\n expect(randomizeStub).to.have.been.called;\n });\n\n it('should submit quiz', () => {\n const serviceStub = sinon.stub(exerciseService, 'findForStudent').returns(of({ body: quizExerciseForPractice } as HttpResponse<QuizExercise>));\n fixture.detectChanges();\n\n const submitButton = fixture.debugElement.nativeElement.querySelector('#submit-quiz');\n expect(submitButton).to.exist;\n\n submitButton.click();\n fixture.detectChanges();\n\n const request = httpMock.expectOne({ method: 'POST' });\n const quizSubmission = { submissionDate: now, submitted: true } as QuizSubmission;\n request.flush({ submission: quizSubmission, participation: { exercise: quizExerciseForPractice } as StudentParticipation } as Result);\n expect(request.request.url).to.equal(`api/exercises/${quizExerciseForPractice.id}/submissions/practice`);\n fixture.detectChanges();\n\n expect(serviceStub).to.have.been.calledWith(quizExerciseForPractice.id);\n });\n });\n\n describe('solution mode', () => {\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n declarations: testBedDeclarations,\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n params: of({ courseId: 1, exerciseId: quizExerciseForPractice.id }),\n data: of({ mode: 'solution' }),\n },\n },\n {\n provide: LocalStorageService,\n useClass: MockLocalStorageService,\n },\n {\n provide: SessionStorageService,\n useClass: MockSyncStorage,\n },\n {\n provide: TranslateService,\n useClass: MockTranslateService,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(QuizParticipationComponent);\n component = fixture.componentInstance;\n\n exerciseService = fixture.debugElement.injector.get(QuizExerciseService);\n resultForSolutionServiceStub = sinon.stub(exerciseService, 'find').returns(of({ body: quizExerciseForPractice } as HttpResponse<QuizExercise>));\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should initialize and show solution', () => {\n fixture.detectChanges();\n\n expect(resultForSolutionServiceStub).to.have.been.calledWith(quizExerciseForPractice.id);\n expect(component.showingResult).to.be.true;\n expect(component.totalScore).to.equal(6);\n });\n\n it('should update time', () => {\n fixture.detectChanges();\n\n // Test the error branches first\n component.quizExercise = {} as QuizExercise;\n fixture.detectChanges();\n\n component.updateDisplayedTimes();\n fixture.detectChanges();\n\n expect(component.remainingTimeSeconds).to.equal(0);\n expect(component.remainingTimeText).to.equal('?');\n expect(component.timeUntilStart).to.equal('');\n\n // Now test the remaining non-error branches\n component.quizExercise = quizExerciseUnreleased;\n component.updateDisplayedTimes();\n fixture.detectChanges();\n\n component.quizExercise = quizExerciseForResults;\n component.submission = { submissionDate: now, submitted: true } as QuizSubmission;\n component.updateDisplayedTimes();\n fixture.detectChanges();\n\n expect(component.remainingTimeText).to.equal('showStatistic.quizhasEnded');\n expect(component.timeUntilStart).to.equal('showStatistic.now');\n });\n });\n});\n" }, { "alpha_fraction": 0.648399829864502, "alphanum_fraction": 0.655238926410675, "avg_line_length": 40.930145263671875, "blob_id": "67dd50d6417ebb8a62a324cdc6b77fa4d36559e3", "content_id": "0c75f427ab6c04e17e5fd318381e514a2fc2c3ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11405, "license_type": "permissive", "max_line_length": 142, "num_lines": 272, "path": "/src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TextSubmissionAssessmentComponent } from 'app/exercises/text/assess/text-submission-assessment.component';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { ArtemisTestModule } from '../../test.module';\nimport { By } from '@angular/platform-browser';\nimport { Observable, of } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { AssessmentLayoutComponent } from 'app/assessment/assessment-layout/assessment-layout.component';\nimport { AssessmentInstructionsModule } from 'app/assessment/assessment-instructions/assessment-instructions.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { TextAssessmentAreaComponent } from 'app/exercises/text/assess/text-assessment-area/text-assessment-area.component';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TextblockAssessmentCardComponent } from 'app/exercises/text/assess/textblock-assessment-card/textblock-assessment-card.component';\nimport { TextblockFeedbackEditorComponent } from 'app/exercises/text/assess/textblock-feedback-editor/textblock-feedback-editor.component';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { getLatestSubmissionResult, SubmissionExerciseType, SubmissionType } from 'app/entities/submission.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport * as moment from 'moment';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ActivatedRoute, convertToParamMap } from '@angular/router';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { Course } from 'app/entities/course.model';\nimport { ManualTextblockSelectionComponent } from 'app/exercises/text/assess/manual-textblock-selection/manual-textblock-selection.component';\nimport { TextSharedModule } from 'app/exercises/text/shared/text-shared.module';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { RouterTestingModule } from '@angular/router/testing';\n\ndescribe('TextSubmissionAssessmentComponent', () => {\n let component: TextSubmissionAssessmentComponent;\n let fixture: ComponentFixture<TextSubmissionAssessmentComponent>;\n let textAssessmentService: TextAssessmentService;\n\n const exercise = {\n id: 20,\n type: ExerciseType.TEXT,\n assessmentType: AssessmentType.MANUAL,\n problemStatement: '',\n course: { id: 123, isAtLeastInstructor: true } as Course,\n } as TextExercise;\n const participation: StudentParticipation = ({\n type: ParticipationType.STUDENT,\n exercise,\n } as unknown) as StudentParticipation;\n const submission = ({\n submissionExerciseType: SubmissionExerciseType.TEXT,\n id: 2278,\n submitted: true,\n type: SubmissionType.MANUAL,\n submissionDate: moment('2019-07-09T10:47:33.244Z'),\n text: 'First text. Second text.',\n participation,\n } as unknown) as TextSubmission;\n submission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n completionDate: moment('2019-07-09T11:51:23.251Z'),\n successful: false,\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: true,\n submission,\n participation,\n } as unknown) as Result,\n ];\n\n getLatestSubmissionResult(submission)!.feedbacks = [\n {\n id: 1,\n detailText: 'First Feedback',\n credits: 1,\n reference: 'First text id',\n } as Feedback,\n ];\n submission.blocks = [\n {\n id: 'First text id',\n text: 'First text.',\n startIndex: 0,\n endIndex: 11,\n submission,\n } as TextBlock,\n {\n id: 'second text id',\n text: 'Second text.',\n startIndex: 12,\n endIndex: 24,\n submission,\n } as TextBlock,\n ];\n submission.participation!.submissions = [submission];\n submission.participation!.results = [getLatestSubmissionResult(submission)!];\n const route = ({\n snapshot: { path: '' },\n paramMap: Observable.of(\n convertToParamMap({\n exerciseId: '1',\n }),\n ),\n queryParams: of({\n testRun: 'false',\n }),\n data: Observable.of({\n studentParticipation: participation,\n }),\n } as unknown) as ActivatedRoute;\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n ArtemisSharedModule,\n ArtemisAssessmentSharedModule,\n AssessmentInstructionsModule,\n TranslateModule.forRoot(),\n ArtemisConfirmIconModule,\n TextSharedModule,\n RouterTestingModule,\n ],\n declarations: [\n TextSubmissionAssessmentComponent,\n TextAssessmentAreaComponent,\n TextblockAssessmentCardComponent,\n TextblockFeedbackEditorComponent,\n ManualTextblockSelectionComponent,\n ],\n providers: [{ provide: ActivatedRoute, useValue: route }],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents();\n });\n\n beforeEach(() => {\n fixture = TestBed.createComponent(TextSubmissionAssessmentComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n });\n\n it('should show jhi-text-assessment-area', () => {\n component['setPropertiesFromServerResponse'](participation);\n fixture.detectChanges();\n\n const textAssessmentArea = fixture.debugElement.query(By.directive(TextAssessmentAreaComponent));\n expect(textAssessmentArea).toBeTruthy();\n });\n\n it('should use jhi-assessment-layout', () => {\n const sharedLayout = fixture.debugElement.query(By.directive(AssessmentLayoutComponent));\n expect(sharedLayout).toBeTruthy();\n });\n\n it('should update score', () => {\n component['setPropertiesFromServerResponse'](participation);\n fixture.detectChanges();\n\n const textAssessmentArea = fixture.debugElement.query(By.directive(TextAssessmentAreaComponent));\n const textAssessmentAreaComponent = textAssessmentArea.componentInstance as TextAssessmentAreaComponent;\n const textBlockRef = textAssessmentAreaComponent.textBlockRefs[0];\n textBlockRef.feedback!.credits = 42;\n textAssessmentAreaComponent.textBlockRefsChangeEmit();\n\n expect(component.totalScore).toBe(42);\n });\n\n it('should save the assessment with correct parameters', function () {\n textAssessmentService = fixture.debugElement.injector.get(TextAssessmentService);\n component['setPropertiesFromServerResponse'](participation);\n fixture.detectChanges();\n\n const result = getLatestSubmissionResult(submission);\n const textBlockRef = component.textBlockRefs[1];\n textBlockRef.initFeedback();\n textBlockRef.feedback!.detailText = 'my feedback';\n textBlockRef.feedback!.credits = 42;\n\n spyOn(textAssessmentService, 'save').and.returnValue(\n of(\n new HttpResponse({\n body: result,\n }),\n ),\n );\n\n component.validateFeedback();\n component.save();\n expect(textAssessmentService.save).toHaveBeenCalledWith(\n exercise.id!,\n result!.id!,\n [component.textBlockRefs[0].feedback!, textBlockRef.feedback!],\n [component.textBlockRefs[0].block!, textBlockRef.block!],\n );\n });\n\n it('should display error when complaint resolved but assessment invalid', () => {\n // would be called on receive of event\n const complaintResponse = new ComplaintResponse();\n const alertService = fixture.debugElement.injector.get(JhiAlertService);\n spyOn(alertService, 'error');\n\n component.updateAssessmentAfterComplaint(complaintResponse);\n expect(alertService.error).toHaveBeenCalledWith('artemisApp.textAssessment.error.invalidAssessments');\n });\n\n it('should send update when complaint resolved and assessments are valid', () => {\n const unreferencedFeedback = new Feedback();\n unreferencedFeedback.credits = 5;\n unreferencedFeedback.detailText = 'gj';\n unreferencedFeedback.type = FeedbackType.MANUAL_UNREFERENCED;\n unreferencedFeedback.id = 1;\n component.unreferencedFeedback = [unreferencedFeedback];\n textAssessmentService = fixture.debugElement.injector.get(TextAssessmentService);\n spyOn(textAssessmentService, 'updateAssessmentAfterComplaint').and.returnValue(\n of(\n new HttpResponse({\n body: new Result(),\n }),\n ),\n );\n\n // would be called on receive of event\n const complaintResponse = new ComplaintResponse();\n component.updateAssessmentAfterComplaint(complaintResponse);\n expect(textAssessmentService.updateAssessmentAfterComplaint).toHaveBeenCalled();\n });\n it('should submit the assessment with correct parameters', function () {\n textAssessmentService = fixture.debugElement.injector.get(TextAssessmentService);\n component['setPropertiesFromServerResponse'](participation);\n fixture.detectChanges();\n\n const result = getLatestSubmissionResult(submission);\n const textBlockRef = component.textBlockRefs[1];\n textBlockRef.initFeedback();\n textBlockRef.feedback!.detailText = 'my feedback';\n textBlockRef.feedback!.credits = 42;\n\n spyOn(textAssessmentService, 'submit').and.returnValue(\n of(\n new HttpResponse({\n body: result,\n }),\n ),\n );\n\n component.validateFeedback();\n component.submit();\n expect(textAssessmentService.submit).toHaveBeenCalledWith(\n exercise.id!,\n result!.id!,\n [component.textBlockRefs[0].feedback!, textBlockRef.feedback!],\n [component.textBlockRefs[0].block!, textBlockRef.block!],\n );\n });\n});\n" }, { "alpha_fraction": 0.7025423645973206, "alphanum_fraction": 0.7043220400810242, "avg_line_length": 49.86206817626953, "blob_id": "b09eed392f9faa5a2017be236cbf26e0fc2f1403", "content_id": "e4f9285e87838c39b97c7c2027b5233766096583", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11800, "license_type": "permissive", "max_line_length": 158, "num_lines": 232, "path": "/src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport { OrionConnectorService } from 'app/shared/orion/orion-connector.service';\nimport { SinonStub, stub } from 'sinon';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { MockOrionConnectorService } from '../../../helpers/mocks/service/mock-orion-connector.service';\nimport { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service';\n\nimport { MockParticipationWebsocketService } from '../../../helpers/mocks/service/mock-participation-websocket.service';\nimport { Result } from 'app/entities/result.model';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { of } from 'rxjs';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport * as moment from 'moment';\nimport { MockCourseService } from '../../../helpers/mocks/service/mock-course.service';\nimport { Exercise, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport { ArtemisCoursesModule } from 'app/overview/courses.module';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { CourseExerciseRowComponent } from 'app/overview/course-exercises/course-exercise-row.component';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { CourseExerciseService, CourseManagementService } from 'app/course/manage/course-management.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { Course } from 'app/entities/course.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseExerciseRowComponent', () => {\n let comp: CourseExerciseRowComponent;\n let fixture: ComponentFixture<CourseExerciseRowComponent>;\n let debugElement: DebugElement;\n let getAllParticipationsStub: SinonStub;\n let participationWebsocketService: ParticipationWebsocketService;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), NgbModule, ArtemisCoursesModule],\n providers: [\n DeviceDetectorService,\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: CourseManagementService, useClass: MockCourseService },\n { provide: CourseExerciseService, useClass: MockCourseExerciseService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: OrionConnectorService, useClass: MockOrionConnectorService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseExerciseRowComponent);\n comp = fixture.componentInstance;\n comp.course = { id: 123, isAtLeastInstructor: true } as Course;\n debugElement = fixture.debugElement;\n participationWebsocketService = debugElement.injector.get(ParticipationWebsocketService);\n getAllParticipationsStub = stub(participationWebsocketService, 'getParticipationForExercise');\n });\n });\n\n afterEach(() => {\n getAllParticipationsStub.restore();\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_NOT_STARTED if release date is in the past and not planned to start', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(false, moment(), moment().subtract(3, 'minutes'), true, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_NOT_STARTED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_NOT_STARTED if release date is in the future and planned to start', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment(), moment().add(3, 'minutes'), true, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_NOT_STARTED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_UNINITIALIZED', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment().add(3, 'minutes'), moment(), true, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_UNINITIALIZED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_NOT_PARTICIPATED if there are no participations', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment(), moment(), true, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_NOT_PARTICIPATED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_ACTIVE', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment().add(3, 'minutes'), moment(), true, true, InitializationState.INITIALIZED);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_ACTIVE);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_SUBMITTED', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment().add(3, 'minutes'), moment(), true, true, InitializationState.FINISHED);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_SUBMITTED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_NOT_PARTICIPATED if there are no results', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment().add(3, 'minutes'), moment(), false, true, InitializationState.UNINITIALIZED, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_NOT_PARTICIPATED);\n });\n\n it('Participation status of quiz exercise should evaluate to QUIZ_FINISHED', () => {\n setupForTestingParticipationStatusExerciseTypeQuiz(true, moment().add(3, 'minutes'), moment(), false, true, InitializationState.UNINITIALIZED, true);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.QUIZ_FINISHED);\n });\n\n it('Participation status of text exercise should evaluate to EXERCISE_ACTIVE', () => {\n setupForTestingParticipationStatusExerciseTypeText(ExerciseType.TEXT, InitializationState.INITIALIZED, true);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.EXERCISE_ACTIVE);\n });\n\n it('Participation status of text exercise should evaluate to EXERCISE_MISSED', () => {\n setupForTestingParticipationStatusExerciseTypeText(ExerciseType.TEXT, InitializationState.INITIALIZED, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.EXERCISE_MISSED);\n });\n\n it('Participation status of text exercise should evaluate to EXERCISE_SUBMITTED', () => {\n setupForTestingParticipationStatusExerciseTypeText(ExerciseType.TEXT, InitializationState.FINISHED, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.EXERCISE_SUBMITTED);\n });\n\n it('Participation status of text exercise should evaluate to UNINITIALIZED', () => {\n setupForTestingParticipationStatusExerciseTypeText(ExerciseType.TEXT, InitializationState.UNINITIALIZED, false);\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.UNINITIALIZED);\n });\n\n it('Participation status of programming exercise should evaluate to EXERCISE_MISSED', () => {\n setupExercise(ExerciseType.PROGRAMMING, moment().subtract(1, 'day'));\n comp.ngOnInit();\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.EXERCISE_MISSED);\n });\n\n it('Participation status of programming exercise should evaluate to UNINITIALIZED', () => {\n setupExercise(ExerciseType.PROGRAMMING, moment().add(1, 'day'));\n comp.ngOnInit();\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.UNINITIALIZED);\n });\n\n it('Participation status of programming exercise should evaluate to INITIALIZED', () => {\n setupExercise(ExerciseType.PROGRAMMING, moment());\n\n const studentParticipation = {\n id: 1,\n initializationState: InitializationState.INITIALIZED,\n } as StudentParticipation;\n comp.exercise.studentParticipations = [studentParticipation];\n\n getAllParticipationsStub.returns(studentParticipation);\n comp.ngOnInit();\n\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.INITIALIZED);\n });\n\n it('Participation status of programming exercise should evaluate to INACTIVE', () => {\n setupExercise(ExerciseType.PROGRAMMING, moment());\n\n const studentParticipation = {\n id: 1,\n initializationState: InitializationState.UNINITIALIZED,\n } as StudentParticipation;\n comp.exercise.studentParticipations = [studentParticipation];\n\n getAllParticipationsStub.returns(of(studentParticipation));\n comp.ngOnInit();\n\n expect(comp.exercise.participationStatus).to.equal(ParticipationStatus.INACTIVE);\n });\n\n const setupForTestingParticipationStatusExerciseTypeQuiz = (\n isPlannedToStart: boolean,\n dueDate: moment.Moment,\n releaseDate: moment.Moment,\n visibleToStudents: boolean,\n hasParticipations: boolean,\n initializationState?: InitializationState,\n hasResults?: boolean,\n ) => {\n comp.exercise = {\n id: 1,\n dueDate,\n isPlannedToStart,\n releaseDate,\n type: ExerciseType.QUIZ,\n visibleToStudents,\n } as QuizExercise;\n\n if (hasParticipations) {\n const studentParticipation = {\n id: 1,\n initializationState,\n } as StudentParticipation;\n\n if (hasResults) {\n studentParticipation.results = [{ id: 1 } as Result];\n }\n\n comp.exercise.studentParticipations = [studentParticipation];\n\n getAllParticipationsStub.returns(studentParticipation);\n }\n\n comp.ngOnInit();\n };\n\n const setupForTestingParticipationStatusExerciseTypeText = (exerciseType: ExerciseType, initializationState: InitializationState, inDueDate: boolean) => {\n const dueDate = inDueDate ? moment().add(3, 'days') : moment().subtract(3, 'days');\n setupExercise(exerciseType, dueDate);\n\n const studentParticipation = {\n id: 1,\n initializationState,\n } as StudentParticipation;\n comp.exercise.studentParticipations = [studentParticipation];\n\n getAllParticipationsStub.returns(studentParticipation);\n comp.ngOnInit();\n };\n\n const setupExercise = (exerciseType: ExerciseType, dueDate: moment.Moment) => {\n comp.exercise = {\n id: 1,\n type: exerciseType,\n dueDate,\n } as Exercise;\n };\n});\n" }, { "alpha_fraction": 0.7217089533805847, "alphanum_fraction": 0.7242512702941895, "avg_line_length": 55.98586654663086, "blob_id": "b1e97966ef1b613f0499a06fb34cd37e55e88d02", "content_id": "67a7cbccd709da58061dc9040701757a1e114f92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16127, "license_type": "permissive", "max_line_length": 176, "num_lines": 283, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ParticipantScoreResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.repository.CourseRepository;\nimport de.tum.in.www1.artemis.repository.ExamRepository;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.service.ParticipantScoreService;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreAverageDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ScoreDTO;\n\n@RestController\n@RequestMapping(\"/api\")\npublic class ParticipantScoreResource {\n\n private final Logger log = LoggerFactory.getLogger(ParticipantScoreResource.class);\n\n private final CourseRepository courseRepository;\n\n private final ExamRepository examRepository;\n\n private final ParticipantScoreService participantScoreService;\n\n private final AuthorizationCheckService authorizationCheckService;\n\n public ParticipantScoreResource(AuthorizationCheckService authorizationCheckService, CourseRepository courseRepository, ExamRepository examRepository,\n ParticipantScoreService participantScoreService) {\n this.authorizationCheckService = authorizationCheckService;\n this.courseRepository = courseRepository;\n this.examRepository = examRepository;\n this.participantScoreService = participantScoreService;\n }\n\n /**\n * GET /courses/:courseId/course-scores gets the course scores of the course\n * <p>\n * This method represents a server based way to calculate a students achieved points / score in a course.\n * <p>\n * Currently both this server based calculation method and the traditional client side calculation method is used\n * side-by-side in course-scores.component.ts.\n * <p>\n * The goal is to switch completely to this much faster server based calculation if the {@link de.tum.in.www1.artemis.service.listeners.ResultListener}\n * has been battle tested enough.\n *\n * @param courseId the id of the course for which to calculate the course scores\n * @return list of scores for every member of the course\n */\n @GetMapping(\"/courses/{courseId}/course-scores\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ScoreDTO>> getScoresOfCourse(@PathVariable Long courseId) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get course scores for course : {}\", courseId);\n Course course = courseRepository.findByIdWithEagerExercisesElseThrow(courseId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(course, null)) {\n return forbidden();\n }\n List<ScoreDTO> scoreDTOS = participantScoreService.calculateCourseScores(course);\n log.info(\"getScoresOfCourse took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(scoreDTOS);\n }\n\n /**\n * GET /exams/:examId/exam-scores gets the exam scores of the exam\n * <p>\n * This method represents a server based way to calculate a students achieved points / score in a exam.\n * <p>\n * Currently both this server based calculation method and the traditional client side calculation method is used\n * side-by-side in exam-scores.component.ts.\n * <p>\n * The goal is to switch completely to this much faster server based calculation if the {@link de.tum.in.www1.artemis.service.listeners.ResultListener}\n * has been battle tested enough.\n *\n * @param examId the id of the exam for which to calculate the exam scores\n * @return list of scores for every registered user in the xam\n */\n @GetMapping(\"/exams/{examId}/exam-scores\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ScoreDTO>> getScoresOfExam(@PathVariable Long examId) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get exam scores for exam : {}\", examId);\n Exam exam = examRepository.findByIdWithRegisteredUsersExerciseGroupsAndExercisesElseThrow(examId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(exam.getCourse(), null)) {\n return forbidden();\n }\n\n List<ScoreDTO> scoreDTOS = participantScoreService.calculateExamScores(exam);\n log.info(\"getScoresOfExam took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(scoreDTOS);\n }\n\n /**\n * GET /courses/:courseId/participant-scores gets the participant scores of the course\n *\n * @param courseId the id of the course for which to get the participant score\n * @param pageable pageable object\n * @param getUnpaged if set all participant scores of the course will be loaded (paging deactivated)\n * @return the ResponseEntity with status 200 (OK) and with the participant scores in the body\n */\n @GetMapping(\"/courses/{courseId}/participant-scores\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ParticipantScoreDTO>> getParticipantScoresOfCourse(@PathVariable Long courseId, Pageable pageable,\n @RequestParam(value = \"getUnpaged\", required = false, defaultValue = \"false\") boolean getUnpaged) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get participant scores for course : {}\", courseId);\n Course course = courseRepository.findByIdWithEagerExercisesElseThrow(courseId);\n authorizationCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);\n Set<Exercise> exercisesOfCourse = course.getExercises().stream().filter(Exercise::isCourseExercise).collect(Collectors.toSet());\n List<ParticipantScoreDTO> resultsOfAllExercises = participantScoreService.getParticipantScoreDTOs(getUnpaged ? Pageable.unpaged() : pageable, exercisesOfCourse);\n log.info(\"getParticipantScoresOfCourse took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(resultsOfAllExercises);\n }\n\n /**\n * GET /courses/:courseId/participant-scores/average-participant gets the average scores of the participants in the course\n * <p>\n * Important: Exercises with {@link de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore#NOT_INCLUDED} will be not taken into account!\n *\n * @param courseId the id of the course for which to get the average scores of the participants\n * @return the ResponseEntity with status 200 (OK) and with the average scores in the body\n */\n @GetMapping(\"/courses/{courseId}/participant-scores/average-participant\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ParticipantScoreAverageDTO>> getAverageScoreOfParticipantInCourse(@PathVariable Long courseId) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get average participant scores of participants for course : {}\", courseId);\n Course course = courseRepository.findByIdWithEagerExercisesElseThrow(courseId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(course, null)) {\n return forbidden();\n }\n Set<Exercise> exercisesOfCourse = course.getExercises().stream().filter(Exercise::isCourseExercise)\n .filter(exercise -> !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED)).collect(Collectors.toSet());\n List<ParticipantScoreAverageDTO> resultsOfAllExercises = participantScoreService.getParticipantScoreAverageDTOs(exercisesOfCourse);\n log.info(\"getAverageScoreOfStudentInCourse took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(resultsOfAllExercises);\n }\n\n /**\n * GET /courses/:courseId/participant-scores/average gets the average score of the course\n * <p>\n * Important: Exercises with {@link de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore#NOT_INCLUDED} will be not taken into account!\n *\n * @param courseId the id of the course for which to get the average score\n * @param onlyConsiderRatedScores if set the method will get the rated average score, if unset the method will get the average score\n * @return the ResponseEntity with status 200 (OK) and with average score in the body\n */\n @GetMapping(\"/courses/{courseId}/participant-scores/average\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Double> getAverageScoreOfCourse(@PathVariable Long courseId, @RequestParam(defaultValue = \"true\", required = false) boolean onlyConsiderRatedScores) {\n long start = System.currentTimeMillis();\n if (onlyConsiderRatedScores) {\n log.debug(\"REST request to get average rated scores for course : {}\", courseId);\n }\n else {\n log.debug(\"REST request to get average scores for course : {}\", courseId);\n }\n Course course = courseRepository.findByIdWithEagerExercisesElseThrow(courseId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(course, null)) {\n return forbidden();\n }\n Set<Exercise> includedExercisesOfCourse = course.getExercises().stream().filter(Exercise::isCourseExercise)\n .filter(exercise -> !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED)).collect(Collectors.toSet());\n Double averageScore = participantScoreService.getAverageScore(onlyConsiderRatedScores, includedExercisesOfCourse);\n log.info(\"getAverageScoreOfCourse took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(averageScore);\n }\n\n /**\n * GET /exams/:examId/participant-scores gets the participant scores of the exam\n *\n * @param examId the id of the exam for which to get the participant score\n * @param pageable pageable object\n * @param getUnpaged if set all participant scores of the exam will be loaded (paging deactivated)\n * @return the ResponseEntity with status 200 (OK) and with the participant scores in the body\n */\n @GetMapping(\"/exams/{examId}/participant-scores\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ParticipantScoreDTO>> getParticipantScoresOfExam(@PathVariable Long examId, Pageable pageable,\n @RequestParam(value = \"getUnpaged\", required = false, defaultValue = \"false\") boolean getUnpaged) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get participant scores for exam : {}\", examId);\n Exam exam = examRepository.findWithExerciseGroupsAndExercisesByIdOrElseThrow(examId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(exam.getCourse(), null)) {\n return forbidden();\n }\n Set<Exercise> exercisesOfExam = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n exercisesOfExam.addAll(exerciseGroup.getExercises());\n }\n Pageable page;\n if (getUnpaged) {\n page = Pageable.unpaged();\n }\n else {\n page = pageable;\n }\n List<ParticipantScoreDTO> resultsOfAllExercises = participantScoreService.getParticipantScoreDTOs(page, exercisesOfExam);\n log.info(\"getParticipantScoresOfExam took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(resultsOfAllExercises);\n }\n\n /**\n * GET /exams/:examId/participant-scores/average gets the average score of the exam\n * <p>\n * Important: Exercises with {@link de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore#NOT_INCLUDED} will be not taken into account!\n *\n * @param examId the id of the exam for which to get the average score\n * @param onlyConsiderRatedScores if set the method will get the rated average score, if unset the method will get the average score\n * @return the ResponseEntity with status 200 (OK) and with average score in the body\n */\n @GetMapping(\"/exams/{examId}/participant-scores/average\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Double> getAverageScoreOfExam(@PathVariable Long examId, @RequestParam(defaultValue = \"true\", required = false) boolean onlyConsiderRatedScores) {\n long start = System.currentTimeMillis();\n if (onlyConsiderRatedScores) {\n log.debug(\"REST request to get average rated scores for exam : {}\", examId);\n }\n else {\n log.debug(\"REST request to get average scores for exam : {}\", examId);\n }\n Exam exam = examRepository.findWithExerciseGroupsAndExercisesByIdOrElseThrow(examId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(exam.getCourse(), null)) {\n return forbidden();\n }\n Set<Exercise> exercisesOfExam = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n exercisesOfExam.addAll(exerciseGroup.getExercises());\n }\n Set<Exercise> includedExercisesOfExam = exercisesOfExam.stream().filter(exercise -> !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED))\n .collect(Collectors.toSet());\n\n Double averageScore = participantScoreService.getAverageScore(onlyConsiderRatedScores, includedExercisesOfExam);\n log.info(\"getAverageScoreOfExam took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(averageScore);\n }\n\n /**\n * GET /exams/:examId/participant-scores/average-participant gets the average scores of the participants in the exam\n * <p>\n * Important: Exercises with {@link de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore#NOT_INCLUDED} will be not taken into account!\n *\n * @param examId the id of the exam for which to get the average scores of the participants\n * @return the ResponseEntity with status 200 (OK) and with the average scores in the body\n */\n @GetMapping(\"/exams/{examId}/participant-scores/average-participant\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ParticipantScoreAverageDTO>> getAverageScoreOfParticipantInExam(@PathVariable Long examId) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get average participant scores of participants for exam : {}\", examId);\n Exam exam = examRepository.findWithExerciseGroupsAndExercisesByIdOrElseThrow(examId);\n if (!authorizationCheckService.isAtLeastInstructorInCourse(exam.getCourse(), null)) {\n return forbidden();\n }\n Set<Exercise> exercisesOfExam = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n exercisesOfExam.addAll(exerciseGroup.getExercises());\n }\n Set<Exercise> includedExercisesOfExam = exercisesOfExam.stream().filter(exercise -> !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED))\n .collect(Collectors.toSet());\n List<ParticipantScoreAverageDTO> resultsOfAllExercises = participantScoreService.getParticipantScoreAverageDTOs(includedExercisesOfExam);\n log.info(\"getAverageScoreOfParticipantInExam took {}ms\", System.currentTimeMillis() - start);\n return ResponseEntity.ok().body(resultsOfAllExercises);\n }\n\n}\n" }, { "alpha_fraction": 0.6185855865478516, "alphanum_fraction": 0.6204515695571899, "avg_line_length": 42.926231384277344, "blob_id": "9f08d010026d22098c1db16ac37e1eeb74a22193", "content_id": "fe04e3d48c3f8d39355948441f42f24d9a8913bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5359, "license_type": "permissive", "max_line_length": 162, "num_lines": 122, "path": "/src/test/javascript/spec/component/learning-goals/create-learning-goal.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';\nimport { MockPipe, MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { CreateLearningGoalComponent } from 'app/course/learning-goals/create-learning-goal/create-learning-goal.component';\nimport { LearningGoalFormData } from 'app/course/learning-goals/learning-goal-form/learning-goal-form.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-learning-goal-form', template: '' })\nclass LearningGoalFormStubComponent {\n @Input() formData: LearningGoalFormData;\n @Input() courseId: number;\n @Input() isEditMode = false;\n @Input()\n lecturesOfCourseWithLectureUnits: Lecture[] = [];\n @Output() formSubmitted: EventEmitter<LearningGoalFormData> = new EventEmitter<LearningGoalFormData>();\n}\n\ndescribe('CreateLearningGoal', () => {\n let createLearningGoalComponentFixture: ComponentFixture<CreateLearningGoalComponent>;\n let createLearningGoalComponent: CreateLearningGoalComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [LearningGoalFormStubComponent, CreateLearningGoalComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n MockProvider(LearningGoalService),\n MockProvider(LectureService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'courseId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n createLearningGoalComponentFixture = TestBed.createComponent(CreateLearningGoalComponent);\n createLearningGoalComponent = createLearningGoalComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n createLearningGoalComponentFixture.detectChanges();\n expect(createLearningGoalComponent).to.be.ok;\n });\n it('should send POST request upon form submission and navigate', fakeAsync(() => {\n const router: Router = TestBed.inject(Router);\n const learningGoalService = TestBed.inject(LearningGoalService);\n\n const textUnit: TextUnit = new TextUnit();\n textUnit.id = 1;\n const formDate: LearningGoalFormData = {\n title: 'Test',\n description: 'Lorem Ipsum',\n connectedLectureUnits: [textUnit],\n };\n\n const response: HttpResponse<LearningGoal> = new HttpResponse({\n body: new LearningGoal(),\n status: 201,\n });\n\n const createStub = sinon.stub(learningGoalService, 'create').returns(of(response));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n createLearningGoalComponentFixture.detectChanges();\n\n const learningGoalForm: LearningGoalFormStubComponent = createLearningGoalComponentFixture.debugElement.query(By.directive(LearningGoalFormStubComponent))\n .componentInstance;\n learningGoalForm.formSubmitted.emit(formDate);\n\n createLearningGoalComponentFixture.whenStable().then(() => {\n const learningGoalCallArgument: LearningGoal = createStub.getCall(0).args[0];\n const courseIdCallArgument: number = createStub.getCall(0).args[1];\n\n expect(learningGoalCallArgument.title).to.equal(formDate.title);\n expect(learningGoalCallArgument.description).to.equal(formDate.description);\n expect(learningGoalCallArgument.lectureUnits).to.equal(formDate.connectedLectureUnits);\n expect(courseIdCallArgument).to.equal(1);\n\n expect(createStub).to.have.been.calledOnce;\n expect(navigateSpy).to.have.been.calledOnce;\n });\n }));\n});\n" }, { "alpha_fraction": 0.6595523357391357, "alphanum_fraction": 0.6605934500694275, "avg_line_length": 37.41999816894531, "blob_id": "592fba584be8fe5a8acd9a3da321eab36fa5b99e", "content_id": "4d81175d0b8a19b9394b76387ce30087460e0084", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3842, "license_type": "permissive", "max_line_length": 151, "num_lines": 100, "path": "/src/test/javascript/spec/component/admin/system-notification-management/system-notification-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Directive, HostListener, Input } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { ActivatedRoute, Router, RouterEvent, RouterOutlet } from '@angular/router';\nimport { SystemNotificationManagementDetailComponent } from 'app/admin/system-notification-management/system-notification-management-detail.component';\nimport { SystemNotification } from 'app/entities/system-notification.model';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { spy } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../../helpers/mocks/service/mock-route.service';\nimport { ArtemisTestModule } from '../../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Directive({\n // tslint:disable-next-line:directive-selector\n selector: '[routerLink]',\n})\n// tslint:disable-next-line:directive-class-suffix\nclass RouterLinkSpy {\n @Input()\n routerLink = '';\n\n constructor(private router: Router) {}\n\n @HostListener('click')\n onClick() {\n this.router.navigateByUrl(this.routerLink);\n }\n}\n\ndescribe('SystemNotificationManagementDetailComponent', () => {\n let detailComponentFixture: ComponentFixture<SystemNotificationManagementDetailComponent>;\n let detailComponent: SystemNotificationManagementDetailComponent;\n let router: any;\n\n const route = ({\n data: of({ notification: { id: 1, title: 'test' } as SystemNotification }),\n children: [],\n } as any) as ActivatedRoute;\n\n beforeEach(() => {\n router = new MockRouter();\n router.setEvents(of({ id: 1, url: '' } as RouterEvent));\n\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule],\n declarations: [\n SystemNotificationManagementDetailComponent,\n RouterLinkSpy,\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockDirective(RouterOutlet),\n MockDirective(AlertErrorComponent),\n MockDirective(FormDateTimePickerComponent),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: Router, useValue: router },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n detailComponentFixture = TestBed.createComponent(SystemNotificationManagementDetailComponent);\n detailComponent = detailComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n const dataSpy = spy(route.data, 'subscribe');\n detailComponentFixture.detectChanges();\n expect(detailComponent).to.be.ok;\n expect(dataSpy).to.have.been.calledOnce;\n });\n\n it('should navigate to edit if edit is clicked', fakeAsync(() => {\n detailComponentFixture.detectChanges();\n\n const button = detailComponentFixture.debugElement.nativeElement.querySelector('#editButton');\n button.click();\n\n tick();\n expect(router.navigateByUrl).to.have.been.calledOnce;\n const navigationArray = router.navigateByUrl.getCall(0).args[0];\n expect(navigationArray).to.deep.equal(['edit']);\n }));\n});\n" }, { "alpha_fraction": 0.7150948643684387, "alphanum_fraction": 0.7274143099784851, "avg_line_length": 42.06097412109375, "blob_id": "e787176024b3d87a024357c666cdcfb84f8dc417", "content_id": "3ee257f7b5b7da9b1df80c6b1c3fc85e0bcd31f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7062, "license_type": "permissive", "max_line_length": 154, "num_lines": 164, "path": "/src/test/javascript/spec/component/exam/participate/summary/points-summary/exam-points-summary.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinon from 'sinon';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { MockModule, MockPipe, MockProvider } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { User } from 'app/core/user/user.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamPointsSummaryComponent } from 'app/exam/participate/summary/points-summary/exam-points-summary.component';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ExerciseType, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport { Result } from 'app/entities/result.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\nlet fixture: ComponentFixture<ExamPointsSummaryComponent>;\nlet component: ExamPointsSummaryComponent;\n\nconst visibleDate = moment().subtract(7, 'hours');\nconst startDate = moment().subtract(6, 'hours');\nconst endDate = moment().subtract(5, 'hours');\nconst publishResultsDate = moment().subtract(3, 'hours');\nconst reviewStartDate = moment().subtract(2, 'hours');\nconst reviewEndDate = moment().add(1, 'hours');\n\nconst exam = {\n id: 1,\n title: 'Test Exam',\n visibleDate,\n startDate,\n endDate,\n publishResultsDate,\n reviewStartDate,\n reviewEndDate,\n} as Exam;\n\nconst textResult = { id: 1, score: 200 } as Result;\nconst notIncludedTextResult = { id: 99, score: 100 } as Result;\nconst bonusTextResult = { id: 100, score: 100 } as Result;\nconst quizResult = { id: 2, score: 20 } as Result;\nconst modelingResult = { id: 3, score: 33.33 } as Result;\nconst programmingResult = { id: 4 } as Result;\n\nconst user = { id: 1, name: 'Test User' } as User;\n\nconst textParticipation = { id: 1, student: user, results: [textResult] } as StudentParticipation;\nconst notIncludedTextParticipation = { id: 99, student: user, results: [notIncludedTextResult] } as StudentParticipation;\nconst bonusTextParticipation = { id: 100, student: user, results: [bonusTextResult] } as StudentParticipation;\nconst quizParticipation = { id: 2, student: user, results: [quizResult] } as StudentParticipation;\nconst modelingParticipation = { id: 3, student: user, results: [modelingResult] } as StudentParticipation;\nconst programmingParticipation = { id: 4, student: user, results: [programmingResult] } as StudentParticipation;\nconst programmingParticipationTwo = { id: 5, student: user } as StudentParticipation;\n\nconst textExercise = {\n id: 1,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n title: 'Text Exercise',\n type: ExerciseType.TEXT,\n studentParticipations: [textParticipation],\n maxPoints: 10,\n bonusPoints: 10,\n} as TextExercise;\nconst notIncludedTextExercise = {\n id: 99,\n includedInOverallScore: IncludedInOverallScore.NOT_INCLUDED,\n type: ExerciseType.TEXT,\n maxPoints: 10,\n studentParticipations: [notIncludedTextParticipation],\n} as TextExercise;\nconst bonusTextExercise = {\n id: 100,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_AS_BONUS,\n type: ExerciseType.TEXT,\n maxPoints: 10,\n studentParticipations: [bonusTextParticipation],\n} as TextExercise;\nconst quizExercise = {\n id: 2,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n title: 'Quiz Exercise',\n type: ExerciseType.QUIZ,\n studentParticipations: [quizParticipation],\n maxPoints: 10,\n} as QuizExercise;\nconst modelingExercise = {\n id: 3,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n title: 'Modeling Exercise',\n type: ExerciseType.MODELING,\n studentParticipations: [modelingParticipation],\n maxPoints: 10,\n} as ModelingExercise;\nconst programmingExercise = {\n id: 4,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n title: 'Programming Exercise',\n type: ExerciseType.PROGRAMMING,\n studentParticipations: [programmingParticipation],\n maxPoints: 10,\n} as ProgrammingExercise;\nconst programmingExerciseTwo = {\n id: 5,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n title: 'Programming Exercise',\n type: ExerciseType.PROGRAMMING,\n studentParticipations: [programmingParticipationTwo],\n} as ProgrammingExercise;\nconst exercises = [textExercise, quizExercise, modelingExercise, programmingExercise, programmingExerciseTwo, notIncludedTextExercise, bonusTextExercise];\n\ndescribe('ExamPointsSummaryComponent', function () {\n beforeEach(() => {\n return TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([]), MockModule(NgbModule), HttpClientTestingModule],\n declarations: [ExamPointsSummaryComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [MockProvider(ExerciseService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExamPointsSummaryComponent);\n component = fixture.componentInstance;\n component.exam = exam;\n component.exercises = exercises;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize and calculate scores correctly', function () {\n fixture.detectChanges();\n expect(fixture).to.be.ok;\n expect(component.calculateAchievedPoints(programmingExerciseTwo)).to.equal(0);\n expect(component.calculateAchievedPoints(textExercise)).to.equal(20);\n expect(component.calculateAchievedPoints(notIncludedTextExercise)).to.equal(10);\n expect(component.calculateAchievedPoints(bonusTextExercise)).to.equal(10);\n expect(component.calculateAchievedPoints(quizExercise)).to.equal(2);\n expect(component.calculateAchievedPoints(modelingExercise)).to.equal(3.3);\n expect(component.calculateAchievedPoints(programmingExercise)).to.equal(0);\n\n expect(component.calculatePointsSum()).to.equal(35.3);\n expect(component.calculateMaxPointsSum()).to.equal(40);\n expect(component.calculateMaxBonusPointsSum()).to.equal(20);\n });\n\n it('should display 0 if no exercises are present', function () {\n component.exercises = [];\n fixture.detectChanges();\n expect(fixture).to.be.ok;\n\n expect(component.calculatePointsSum()).to.equal(0);\n expect(component.calculateMaxPointsSum()).to.equal(0);\n });\n});\n" }, { "alpha_fraction": 0.5584344267845154, "alphanum_fraction": 0.5595369338989258, "avg_line_length": 31.9818172454834, "blob_id": "99d248596630c131ea2cdc56aa35c94dc714d745", "content_id": "a3757378df7edf35c9a49dab6f7a298ca56950bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1814, "license_type": "permissive", "max_line_length": 93, "num_lines": 55, "path": "/src/main/webapp/app/overview/course-lectures/course-lecture-row.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, HostBinding, Input } from '@angular/core';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { Course } from 'app/entities/course.model';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Lecture } from 'app/entities/lecture.model';\n\n@Component({\n selector: 'jhi-course-lecture-row',\n templateUrl: './course-lecture-row.component.html',\n styleUrls: ['../course-exercises/course-exercise-row.scss'],\n})\nexport class CourseLectureRowComponent {\n @HostBinding('class') classes = 'exercise-row';\n @Input() lecture: Lecture;\n @Input() course: Course;\n @Input() extendedLink = false;\n\n constructor(private router: Router, private route: ActivatedRoute) {}\n\n getUrgentClass(date?: Moment) {\n if (!date) {\n return undefined;\n }\n const remainingDays = date.diff(moment(), 'days');\n if (0 <= remainingDays && remainingDays < 7) {\n return 'text-danger';\n }\n }\n\n showDetails() {\n const lectureToAttach = {\n ...this.lecture,\n startDate: this.lecture.startDate ? this.lecture.startDate.valueOf() : undefined,\n endDate: this.lecture.endDate ? this.lecture.endDate.valueOf() : undefined,\n course: {\n id: this.course.id,\n },\n };\n if (this.extendedLink) {\n this.router.navigate(['courses', this.course.id, 'lectures', this.lecture.id], {\n state: {\n lecture: lectureToAttach,\n },\n });\n } else {\n this.router.navigate([this.lecture.id], {\n relativeTo: this.route,\n state: {\n lecture: lectureToAttach,\n },\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.5799640417098999, "alphanum_fraction": 0.6006289124488831, "avg_line_length": 47.04316711425781, "blob_id": "e500ee8b95808620e15ec6e46362793bfd30eb31", "content_id": "3be11e9d9c709d4b8bf88e45549940123299c0d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6678, "license_type": "permissive", "max_line_length": 110, "num_lines": 139, "path": "/src/test/javascript/spec/component/utils/guided-tour.utils.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport { Orientation } from 'app/guided-tour/guided-tour.constants';\nimport {\n clickOnElement,\n calculateTopOffset,\n calculateLeftOffset,\n isElementInViewPortHorizontally,\n checkPageUrlEnding,\n determineUrlMatching,\n getUrlParams,\n} from 'app/guided-tour/guided-tour.utils';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\n\nconst expect = chai.expect;\n\ndescribe('GuidedTourUtils', () => {\n describe('clickOnElement', () => {\n it('should clickOnElement', () => {\n const querySelectorStub = stub(document, 'querySelector');\n const mockElement = { click: () => {} } as HTMLElement;\n querySelectorStub.returns(mockElement);\n clickOnElement('ab');\n sinon.assert.called(querySelectorStub);\n });\n });\n describe('calculateLeftOffset', () => {\n it('should calculateLeftOffset', () => {\n const offsetParent1 = { offsetLeft: 4 } as any;\n const offsetParent2 = { offsetLeft: 2, offsetParent: offsetParent1 } as any;\n const dummyElement2 = { offsetLeft: 4, offsetParent: offsetParent2 } as HTMLElement;\n expect(calculateLeftOffset(dummyElement2)).to.be.equal(10);\n });\n });\n describe('calculateTopOffset', () => {\n it('should calculateTopOffset', () => {\n const offsetParent1 = { offsetTop: 4 } as any;\n const offsetParent2 = { offsetTop: 2, offsetParent: offsetParent1 } as any;\n const dummyElement2 = { offsetTop: 4, offsetParent: offsetParent2 } as HTMLElement;\n expect(calculateTopOffset(dummyElement2)).to.be.equal(10);\n });\n });\n describe('isElementInViewPortHorizontally', () => {\n // window.width is 1024\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.TOPLEFT;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 100)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 1000, 1000, 1000)).to.be.false;\n });\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.BOTTOMLEFT;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 100)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 1000, 1000, 1000)).to.be.false;\n });\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.LEFT;\n expect(isElementInViewPortHorizontally(topleft, 100, 0, 50)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 100, 0, 150)).to.be.false;\n });\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.TOPRIGHT;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 100)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 300)).to.be.false;\n });\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.BOTTOMRIGHT;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 100)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 300)).to.be.false;\n });\n it('should isElementInViewPortHorizontally', () => {\n const topleft = Orientation.RIGHT;\n expect(isElementInViewPortHorizontally(topleft, 100, 100, 100)).to.be.true;\n expect(isElementInViewPortHorizontally(topleft, 1000, 1000, 1000)).to.be.false;\n });\n });\n describe('determineUrlMatching', () => {\n it('should match with empty pageUrl', () => {\n const pageUrl = '';\n const tourStepUrl = '';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['']);\n });\n it('should match with empty pageUrl but with params', () => {\n const pageUrl = '?param=true';\n const tourStepUrl = '';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['']);\n });\n it('should match empty with pageUrl', () => {\n const pageUrl = '/this/is/some/guided/tour/url?param=true';\n const tourStepUrl = '';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['']);\n });\n it('should match', () => {\n const pageUrl = '/this/is/some/guided/tour/url?param=true';\n const tourStepUrl = 'is/some';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['is/some']);\n });\n it('should match more', () => {\n const pageUrl = '/this/is/some/guided/tour/url?param=true';\n const tourStepUrl = 'some';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['some']);\n });\n it('should match with params in tourStepUrl', () => {\n const pageUrl = '/this/is/some/guided/tour/url?param=true';\n const tourStepUrl = 'some?param=false';\n expect(determineUrlMatching(pageUrl, tourStepUrl)).to.deep.equal(['some']);\n });\n });\n describe('getUrlParams', () => {\n it('should get params', () => {\n expect(getUrlParams('some/url/to?withParam=true')).to.be.equal('?withParam=true');\n expect(getUrlParams('some/url/to?withParam=true&tea=yes')).to.be.equal('?withParam=true&tea=yes');\n });\n it('should get no params if not existing', () => {\n expect(getUrlParams('some/url/to')).to.be.equal('');\n });\n });\n describe('checkPageUrlEnding', () => {\n it('should checkPageUrlEnding with empty pageUrl', () => {\n const pageUrl = '';\n const matchingUrl = '';\n expect(checkPageUrlEnding(pageUrl, matchingUrl)).to.be.true;\n });\n it('should checkPageUrlEnding with empty matchingUrl', () => {\n const pageUrl = '/some/page/url?param=true';\n const matchingUrl = '';\n expect(checkPageUrlEnding(pageUrl, matchingUrl)).to.be.true;\n });\n it('should checkPageUrlEnding with identical Urls with params', () => {\n const pageUrl = '/some/page/url?param=true';\n const matchingUrl = '/some/page/url?param=true';\n expect(checkPageUrlEnding(pageUrl, matchingUrl)).to.be.false;\n });\n it('should checkPageUrlEnding with same urls without matching params', () => {\n const pageUrl = '/some/page/url?param=true';\n const matchingUrl = '/some/page/url';\n expect(checkPageUrlEnding(pageUrl, matchingUrl)).to.be.true;\n });\n });\n});\n" }, { "alpha_fraction": 0.7158173322677612, "alphanum_fraction": 0.7323865294456482, "avg_line_length": 43.60869598388672, "blob_id": "ffd5a1c75e0d5715488ed98c24dff9134a824905", "content_id": "a83a8561454706348164745a6d195a8d62b48c00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7182, "license_type": "permissive", "max_line_length": 180, "num_lines": 161, "path": "/src/test/java/de/tum/in/www1/artemis/service/compass/controller/ModelIndexTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.compass.controller;\n\nimport static de.tum.in.www1.artemis.service.compass.utils.CompassConfiguration.EQUALITY_THRESHOLD;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.when;\n\nimport java.io.Serializable;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.invocation.InvocationOnMock;\nimport org.mockito.junit.jupiter.MockitoExtension;\nimport org.mockito.junit.jupiter.MockitoSettings;\nimport org.mockito.quality.Strictness;\nimport org.mockito.stubbing.Answer;\n\nimport com.hazelcast.config.Config;\nimport com.hazelcast.config.NetworkConfig;\nimport com.hazelcast.core.Hazelcast;\nimport com.hazelcast.core.HazelcastInstance;\n\nimport de.tum.in.www1.artemis.service.compass.umlmodel.UMLElement;\nimport de.tum.in.www1.artemis.service.compass.umlmodel.classdiagram.UMLPackage;\n\nclass ElementAnswer implements Serializable, Answer {\n\n private final List<UMLElement> elements;\n\n private final List<Double> similarities;\n\n ElementAnswer(List<UMLElement> elements, List<Double> similarities) {\n this.elements = elements;\n this.similarities = similarities;\n }\n\n @Override\n public Object answer(InvocationOnMock invocation) {\n UMLElement umlElement = invocation.getArgument(0);\n int i = 0;\n for (UMLElement element : elements) {\n if (umlElement.getJSONElementID().equals(element.getJSONElementID())) {\n return similarities.get(i);\n }\n i += 1;\n }\n return 0.0;\n }\n}\n\n@ExtendWith(MockitoExtension.class)\n@MockitoSettings(strictness = Strictness.LENIENT)\npublic class ModelIndexTest {\n\n private ModelIndex modelIndex;\n\n @Mock(serializable = true)\n private UMLElement umlElement1;\n\n @Mock(serializable = true)\n private UMLElement umlElement2;\n\n @Mock(serializable = true)\n private UMLElement umlElement3;\n\n @Mock(serializable = true)\n private UMLElement umlElement4;\n\n @BeforeEach\n void setUp() {\n Long exerciseId = 1L;\n Config config = new Config();\n config.setProperty(\"hazelcast.shutdownhook.enabled\", \"false\");\n config.setInstanceName(\"testHazelcastInstance\");\n NetworkConfig network = config.getNetworkConfig();\n network.getJoin().getTcpIpConfig().setEnabled(false);\n network.getJoin().getMulticastConfig().setEnabled(false);\n HazelcastInstance testInstance = Hazelcast.getOrCreateHazelcastInstance(config);\n modelIndex = new ModelIndex(exerciseId, testInstance);\n testInstance.getMap(\"similarities - \" + exerciseId).clear();\n testInstance.getQueue(\"elements - \" + exerciseId).clear();\n testInstance.getMap(\"models - \" + exerciseId).clear();\n when(umlElement1.getJSONElementID()).thenReturn(\"jsonElement1\");\n when(umlElement2.getJSONElementID()).thenReturn(\"jsonElement2\");\n when(umlElement3.getJSONElementID()).thenReturn(\"jsonElement3\");\n when(umlElement4.getJSONElementID()).thenReturn(\"jsonElement4\");\n }\n\n @AfterEach\n void tearDown() {\n Mockito.reset(umlElement1, umlElement2, umlElement3, umlElement4);\n }\n\n @Test\n void retrieveSimilarityId_sameElementTwice() {\n UMLPackage umlPackage = new UMLPackage(\"testPackage\", new ArrayList<>(), \"jsonElementPackage\");\n int similarityId1 = modelIndex.retrieveSimilarityId(umlPackage);\n int similarityId2 = modelIndex.retrieveSimilarityId(umlPackage);\n\n assertThat(similarityId1).isEqualTo(0);\n assertThat(similarityId2).isEqualTo(0);\n assertThat(modelIndex.getElementSimilarityMap().keySet()).containsExactly(umlPackage);\n assertThat(modelIndex.getNumberOfUniqueElements()).isEqualTo(1);\n }\n\n @Test\n void retrieveSimilarityId_twoSimilarElements() {\n mockSimilarityBetweenElements(List.of(umlElement2, umlElement3, umlElement4), umlElement1, List.of(EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD / 2));\n mockSimilarityBetweenElements(List.of(umlElement3, umlElement4), umlElement2, List.of(EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD + 0.01));\n mockSimilarityBetweenElements(List.of(umlElement4), umlElement3, List.of(EQUALITY_THRESHOLD / 2));\n\n when(umlElement2.getSimilarityID()).thenReturn(1);\n int similarityId1 = modelIndex.retrieveSimilarityId(umlElement1);\n int similarityId2 = modelIndex.retrieveSimilarityId(umlElement2);\n int similarityId3 = modelIndex.retrieveSimilarityId(umlElement3);\n int similarityId4 = modelIndex.retrieveSimilarityId(umlElement4);\n\n assertThat(similarityId1).isEqualTo(0);\n assertThat(similarityId2).isEqualTo(1);\n assertThat(similarityId3).isEqualTo(2);\n assertThat(similarityId4).isEqualTo(1);\n assertThat(modelIndex.getElementSimilarityMap().keySet().stream().map(UMLElement::getJSONElementID)).containsExactlyInAnyOrder(\"jsonElement1\", \"jsonElement2\",\n \"jsonElement3\", \"jsonElement4\");\n assertThat(modelIndex.getNumberOfUniqueElements()).isEqualTo(3);\n }\n\n @Test\n void retrieveSimilarityId_multipleSimilarElements() {\n\n mockSimilarityBetweenElements(List.of(umlElement2, umlElement3, umlElement4), umlElement1,\n List.of(EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD + 0.01));\n mockSimilarityBetweenElements(List.of(umlElement3, umlElement4), umlElement2, List.of(EQUALITY_THRESHOLD / 2, EQUALITY_THRESHOLD + 0.03));\n mockSimilarityBetweenElements(List.of(umlElement4), umlElement3, List.of(EQUALITY_THRESHOLD + 0.02));\n\n // This is because hazelcast clones the object so there is no point in setting mocking this after sending it to modelIndex\n // Value is checked later as well so it is safe\n when(umlElement2.getSimilarityID()).thenReturn(1);\n int similarityId1 = modelIndex.retrieveSimilarityId(umlElement1);\n int similarityId2 = modelIndex.retrieveSimilarityId(umlElement2);\n int similarityId3 = modelIndex.retrieveSimilarityId(umlElement3);\n int similarityId4 = modelIndex.retrieveSimilarityId(umlElement4);\n assertThat(similarityId1).isEqualTo(0);\n assertThat(similarityId2).isEqualTo(1);\n assertThat(similarityId3).isEqualTo(2);\n assertThat(similarityId4).isEqualTo(1);\n\n assertThat(modelIndex.getElementSimilarityMap().keySet().stream().map(UMLElement::getJSONElementID)).containsExactlyInAnyOrder(\"jsonElement1\", \"jsonElement2\",\n \"jsonElement3\", \"jsonElement4\");\n assertThat(modelIndex.getNumberOfUniqueElements()).isEqualTo(3);\n }\n\n private void mockSimilarityBetweenElements(List<UMLElement> elements, UMLElement element2, List<Double> similarities) {\n when(element2.similarity(any(UMLElement.class))).thenAnswer(new ElementAnswer(elements, similarities));\n }\n}\n" }, { "alpha_fraction": 0.6819809079170227, "alphanum_fraction": 0.6930190920829773, "avg_line_length": 45.55555725097656, "blob_id": "cf2f4deb59a9f80f98a847bba355d08a92aa0fec", "content_id": "35697ed541277d6988d620cc1d5c5d113843b9e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3352, "license_type": "permissive", "max_line_length": 180, "num_lines": 72, "path": "/src/test/javascript/spec/component/course/course-management-overview-statistics.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { TranslateService } from '@ngx-translate/core';\nimport { CourseManagementExerciseRowComponent } from 'app/course/manage/overview/course-management-exercise-row.component';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { CourseManagementCardComponent } from 'app/course/manage/overview/course-management-card.component';\nimport { CourseManagementOverviewStatisticsComponent } from 'app/course/manage/overview/course-management-overview-statistics.component';\nimport { ChartsModule } from 'ng2-charts';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseManagementOverviewStatisticsComponent', () => {\n let fixture: ComponentFixture<CourseManagementOverviewStatisticsComponent>;\n let component: CourseManagementOverviewStatisticsComponent;\n\n const amountOfStudentsInCourse = 25;\n const initialStats = [0, 11, 9, 23];\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ChartsModule],\n declarations: [\n CourseManagementOverviewStatisticsComponent,\n MockPipe(ArtemisTranslatePipe),\n MockDirective(NgbTooltip),\n MockComponent(CourseManagementExerciseRowComponent),\n MockComponent(CourseManagementCardComponent),\n ],\n providers: [{ provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, MockProvider(TranslateService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseManagementOverviewStatisticsComponent);\n component = fixture.componentInstance;\n });\n });\n\n it('should initialize component and load values', () => {\n // Provide the @Input data\n component.amountOfStudentsInCourse = amountOfStudentsInCourse;\n component.initialStats = initialStats;\n\n fixture.detectChanges();\n expect(component).to.be.ok;\n\n expect(component.dataForSpanType).to.deep.equal([0, 44, 36, 92]);\n expect(component.chartData[0].label).to.equal(component.amountOfStudents);\n expect(component.chartData[0].data).to.deep.equal([0, 44, 36, 92]);\n\n // Test formatting\n expect(component.barChartOptions.scales.yAxes[0].ticks.callback(44)).to.equal('44%');\n expect(component.barChartOptions.tooltips.callbacks.label({ index: 2 })).to.equal(' ' + initialStats[2]);\n });\n\n it('should react to changes', () => {\n fixture.detectChanges();\n\n component.initialStats = [];\n component.amountOfStudentsInCourse = 0;\n component.ngOnChanges();\n\n expect(component.loading).to.be.false;\n expect(component.dataForSpanType).to.deep.equal([0, 0, 0, 0]);\n });\n});\n" }, { "alpha_fraction": 0.6927244663238525, "alphanum_fraction": 0.6942724585533142, "avg_line_length": 25.367347717285156, "blob_id": "6ef7ec3041238d9a3d52fb3437f56bbc42b510ba", "content_id": "d43197e44f6feec237ca2fb8d972344f323c080e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1292, "license_type": "permissive", "max_line_length": 94, "num_lines": 49, "path": "/src/main/java/de/tum/in/www1/artemis/domain/lecture/AttachmentUnit.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.lecture;\n\nimport javax.persistence.*;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.Attachment;\n\n@Entity\n@DiscriminatorValue(\"A\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class AttachmentUnit extends LectureUnit {\n\n // Note: Name and Release Date will always be taken from associated attachment\n @Column(name = \"description\")\n @Lob\n private String description;\n\n @OneToOne(mappedBy = \"attachmentUnit\", cascade = CascadeType.REMOVE, orphanRemoval = true)\n @JsonIgnoreProperties(value = \"attachmentUnit\", allowSetters = true)\n private Attachment attachment;\n\n @Override\n public boolean isVisibleToStudents() {\n if (attachment == null) {\n return true;\n }\n else {\n return attachment.isVisibleToStudents();\n }\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Attachment getAttachment() {\n return attachment;\n }\n\n public void setAttachment(Attachment attachment) {\n this.attachment = attachment;\n }\n}\n" }, { "alpha_fraction": 0.6695868968963623, "alphanum_fraction": 0.6716765761375427, "avg_line_length": 43.755393981933594, "blob_id": "f1879bde7e2a0f0adc249d52a23eba2bab1e1e00", "content_id": "ba6b1bcbc0dc9914500fb62e9edd4421b90acf0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12442, "license_type": "permissive", "max_line_length": 144, "num_lines": 278, "path": "/src/main/webapp/app/overview/course-exercises/course-exercises.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnChanges, OnDestroy, OnInit } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { Subscription } from 'rxjs/Subscription';\nimport { TranslateService } from '@ngx-translate/core';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { flatten, maxBy, sum } from 'lodash';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { courseExerciseOverviewTour } from 'app/guided-tour/tours/course-exercise-overview-tour';\nimport { isOrion } from 'app/shared/orion/orion';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\nexport enum ExerciseFilter {\n OVERDUE = 'OVERDUE',\n NEEDS_WORK = 'NEEDS_WORK',\n}\n\nexport enum ExerciseSortingOrder {\n ASC = 1,\n DESC = -1,\n}\n\nenum SortFilterStorageKey {\n FILTER = 'artemis.course.exercises.filter',\n ORDER = 'artemis.course.exercises.order',\n ATTRIBUTE = 'artemis.course.exercises.attribute',\n}\n\nexport enum SortingAttribute {\n DUE_DATE = 0,\n RELEASE_DATE = 1,\n}\n\n@Component({\n selector: 'jhi-course-exercises',\n templateUrl: './course-exercises.component.html',\n styleUrls: ['../course-overview.scss'],\n})\nexport class CourseExercisesComponent implements OnInit, OnChanges, OnDestroy {\n private courseId: number;\n private paramSubscription: Subscription;\n private courseUpdatesSubscription: Subscription;\n private translateSubscription: Subscription;\n public course?: Course;\n public weeklyIndexKeys: string[];\n public weeklyExercisesGrouped: object;\n public upcomingExercises: Exercise[] = [];\n public exerciseCountMap: Map<string, number>;\n\n readonly ASC = ExerciseSortingOrder.ASC;\n readonly DESC = ExerciseSortingOrder.DESC;\n readonly DUE_DATE = SortingAttribute.DUE_DATE;\n readonly RELEASE_DATE = SortingAttribute.RELEASE_DATE;\n readonly filterType = ExerciseFilter;\n sortingOrder: ExerciseSortingOrder;\n activeFilters: Set<ExerciseFilter>;\n numberOfExercises: number;\n exerciseForGuidedTour?: Exercise;\n nextRelevantExercise?: Exercise;\n sortingAttribute: SortingAttribute;\n\n constructor(\n private courseService: CourseManagementService,\n private courseCalculationService: CourseScoreCalculationService,\n private courseServer: CourseManagementService,\n private translateService: TranslateService,\n private exerciseService: ExerciseService,\n private accountService: AccountService,\n private route: ActivatedRoute,\n private guidedTourService: GuidedTourService,\n private programmingSubmissionService: ProgrammingSubmissionService,\n private localStorage: LocalStorageService,\n ) {}\n\n ngOnInit() {\n this.exerciseCountMap = new Map<string, number>();\n this.numberOfExercises = 0;\n const filters = this.localStorage.retrieve(SortFilterStorageKey.FILTER);\n const filtersInStorage = filters\n ? filters\n .split(',')\n .map((filter: string) => ExerciseFilter[filter])\n .filter(Boolean)\n : [];\n this.activeFilters = new Set(filtersInStorage);\n this.loadOrderAndAttributeForSorting();\n this.paramSubscription = this.route.parent!.params.subscribe((params) => {\n this.courseId = parseInt(params['courseId'], 10);\n });\n\n this.course = this.courseCalculationService.getCourse(this.courseId);\n this.onCourseLoad();\n\n this.courseUpdatesSubscription = this.courseService.getCourseUpdates(this.courseId).subscribe((course: Course) => {\n this.courseCalculationService.updateCourse(course);\n this.course = this.courseCalculationService.getCourse(this.courseId);\n this.onCourseLoad();\n });\n\n this.translateSubscription = this.translateService.onLangChange.subscribe(() => {\n this.applyFiltersAndOrder();\n });\n\n this.exerciseForGuidedTour = this.guidedTourService.enableTourForCourseExerciseComponent(this.course, courseExerciseOverviewTour, true);\n this.nextRelevantExercise = this.exerciseService.getNextExerciseForHours(this.course?.exercises);\n }\n\n setSortingAttribute(attribute: SortingAttribute) {\n this.sortingAttribute = attribute;\n this.localStorage.store(SortFilterStorageKey.ATTRIBUTE, this.sortingAttribute.toString());\n this.applyFiltersAndOrder();\n }\n\n ngOnChanges() {\n this.nextRelevantExercise = this.exerciseService.getNextExerciseForHours(this.course?.exercises);\n }\n\n ngOnDestroy(): void {\n this.translateSubscription.unsubscribe();\n this.courseUpdatesSubscription.unsubscribe();\n this.paramSubscription.unsubscribe();\n }\n\n private onCourseLoad() {\n this.programmingSubmissionService.initializeCacheForStudent(this.course!.exercises, true);\n this.applyFiltersAndOrder();\n }\n\n private calcNumberOfExercises() {\n this.numberOfExercises = sum(Array.from(this.exerciseCountMap.values()));\n }\n\n /**\n * Reorders all displayed exercises\n */\n flipOrder() {\n this.sortingOrder = this.sortingOrder === this.ASC ? this.DESC : this.ASC;\n this.localStorage.store(SortFilterStorageKey.ORDER, this.sortingOrder.toString());\n this.applyFiltersAndOrder();\n }\n\n /**\n * Filters all displayed exercises by applying the selected activeFilters\n * @param filters The filters which should be applied\n */\n toggleFilters(filters: ExerciseFilter[]) {\n filters.forEach((filter) => (this.activeFilters.has(filter) ? this.activeFilters.delete(filter) : this.activeFilters.add(filter)));\n this.localStorage.store(SortFilterStorageKey.FILTER, Array.from(this.activeFilters).join(','));\n this.applyFiltersAndOrder();\n }\n\n /**\n * Checks if the given exercise still needs work, i.e. wasn't even started yet or is not graded with 100%\n * @param exercise The exercise which should get checked\n */\n private needsWork(exercise: Exercise): boolean {\n const latestResult = maxBy(flatten(exercise.studentParticipations?.map((participation) => participation.results)), 'completionDate');\n return !latestResult || !latestResult.score || latestResult.score < 100;\n }\n\n /**\n * Applies all selected activeFilters and orders and groups the user's exercises\n */\n private applyFiltersAndOrder() {\n const needsWorkFilterActive = this.activeFilters.has(ExerciseFilter.NEEDS_WORK);\n const overdueFilterActive = this.activeFilters.has(ExerciseFilter.OVERDUE);\n const filtered = this.course?.exercises?.filter(\n (exercise) =>\n (!needsWorkFilterActive || this.needsWork(exercise)) &&\n (!exercise.dueDate || !overdueFilterActive || exercise.dueDate.isAfter(moment(new Date()))) &&\n (!isOrion || exercise.type === ExerciseType.PROGRAMMING),\n );\n this.groupExercises(filtered);\n }\n\n private getSortingAttributeFromExercise(): (exercise: Exercise) => Moment | undefined {\n return this.sortingAttribute === this.DUE_DATE ? (exercise) => exercise.dueDate : (exercise) => exercise.releaseDate;\n }\n\n private loadOrderAndAttributeForSorting() {\n const orderInStorage = this.localStorage.retrieve(SortFilterStorageKey.ORDER);\n const parsedOrderInStorage = Object.keys(ExerciseSortingOrder).find((exerciseOrder) => exerciseOrder === orderInStorage);\n this.sortingOrder = parsedOrderInStorage ? (+parsedOrderInStorage as ExerciseSortingOrder) : ExerciseSortingOrder.ASC;\n\n const attributeInStorage = this.localStorage.retrieve(SortFilterStorageKey.ATTRIBUTE);\n const parsedAttributeInStorage = Object.keys(SortingAttribute).find((exerciseOrder) => exerciseOrder === attributeInStorage);\n this.sortingAttribute = parsedAttributeInStorage ? (+parsedAttributeInStorage as SortingAttribute) : SortingAttribute.DUE_DATE;\n }\n\n private increaseExerciseCounter(exercise: Exercise) {\n if (!this.exerciseCountMap.has(exercise.type!)) {\n this.exerciseCountMap.set(exercise.type!, 1);\n } else {\n let exerciseCount = this.exerciseCountMap.get(exercise.type!)!;\n this.exerciseCountMap.set(exercise.type!, ++exerciseCount);\n }\n }\n\n private updateUpcomingExercises(upcomingExercises: Exercise[]) {\n const sortedExercises = this.sortExercises((exercise) => exercise.dueDate, upcomingExercises) || [];\n if (upcomingExercises.length <= 5) {\n this.upcomingExercises = sortedExercises;\n } else {\n // sort after selected date and take the first 5 elements\n this.upcomingExercises = sortedExercises.slice(0, 5);\n }\n }\n\n private groupExercises(exercises?: Exercise[]) {\n // set all values to 0\n this.exerciseCountMap = new Map<string, number>();\n this.weeklyExercisesGrouped = {};\n this.weeklyIndexKeys = [];\n const groupedExercises = {};\n const indexKeys: string[] = [];\n const sortedExercises = this.sortExercises(this.getSortingAttributeFromExercise(), exercises) || [];\n const notAssociatedExercises: Exercise[] = [];\n const upcomingExercises: Exercise[] = [];\n sortedExercises.forEach((exercise) => {\n const dateValue = this.getSortingAttributeFromExercise()(exercise);\n this.increaseExerciseCounter(exercise);\n if (!dateValue) {\n notAssociatedExercises.push(exercise);\n return;\n }\n const dateIndex = dateValue ? moment(dateValue).startOf('week').format('YYYY-MM-DD') : 'NoDate';\n if (!groupedExercises[dateIndex]) {\n indexKeys.push(dateIndex);\n groupedExercises[dateIndex] = {\n start: moment(dateValue).startOf('week'),\n end: moment(dateValue).endOf('week'),\n isCollapsed: dateValue.isBefore(moment(), 'week'),\n isCurrentWeek: dateValue.isSame(moment(), 'week'),\n exercises: [],\n };\n }\n groupedExercises[dateIndex].exercises.push(exercise);\n if (exercise.dueDate && moment().isSameOrBefore(dateValue, 'day')) {\n upcomingExercises.push(exercise);\n }\n });\n this.updateUpcomingExercises(upcomingExercises);\n if (notAssociatedExercises.length > 0) {\n this.weeklyExercisesGrouped = {\n ...groupedExercises,\n noDate: {\n label: this.translateService.instant('artemisApp.courseOverview.exerciseList.noExerciseDate'),\n isCollapsed: false,\n isCurrentWeek: false,\n exercises: notAssociatedExercises,\n },\n };\n this.weeklyIndexKeys = [...indexKeys, 'noDate'];\n } else {\n this.weeklyExercisesGrouped = groupedExercises;\n this.weeklyIndexKeys = indexKeys;\n }\n this.calcNumberOfExercises();\n }\n\n private sortExercises(byAttribute: (exercise: Exercise) => Moment | undefined, exercises?: Exercise[]) {\n return exercises?.sort((a, b) => {\n const sortingAttributeA = byAttribute(a);\n const sortingAttributeB = byAttribute(b);\n const aValue = sortingAttributeA ? sortingAttributeA.seconds(0).milliseconds(0).valueOf() : moment().valueOf();\n const bValue = sortingAttributeB ? sortingAttributeB.seconds(0).milliseconds(0).valueOf() : moment().valueOf();\n const titleSortValue = a.title && b.title ? a.title.localeCompare(b.title) : 0;\n return this.sortingOrder.valueOf() * (aValue - bValue === 0 ? titleSortValue : aValue - bValue);\n });\n }\n}\n" }, { "alpha_fraction": 0.6853533387184143, "alphanum_fraction": 0.686406135559082, "avg_line_length": 48.451194763183594, "blob_id": "a3a4bc032943f32c514bbb5143950e8dbe492c94", "content_id": "ff55acd8bb9b25c9601c857908df1d705b51d9e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 22797, "license_type": "permissive", "max_line_length": 173, "num_lines": 461, "path": "/src/main/webapp/app/overview/exercise-details/course-exercise-details.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { Location } from '@angular/common';\nimport { HttpResponse } from '@angular/common/http';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { Subscription } from 'rxjs/Subscription';\nimport { filter } from 'rxjs/operators';\nimport { Result } from 'app/entities/result.model';\nimport * as moment from 'moment';\nimport { User } from 'app/core/user/user.model';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { programmingExerciseFail, programmingExerciseSuccess } from 'app/guided-tour/tours/course-exercise-detail-tour';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { InitializationState, Participation } from 'app/entities/participation/participation.model';\nimport { Exercise, ExerciseCategory, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { GradingCriterion } from 'app/exercises/shared/structured-grading-criterion/grading-criterion.model';\nimport { CourseExerciseSubmissionResultSimulationService } from 'app/course/manage/course-exercise-submission-result-simulation.service';\nimport { ProgrammingExerciseSimulationUtils } from 'app/exercises/programming/shared/utils/programming-exercise-simulation-utils';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ProgrammingExerciseSimulationService } from 'app/exercises/programming/manage/services/programming-exercise-simulation.service';\nimport { TeamAssignmentPayload } from 'app/entities/team.model';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { QuizStatus, QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { StudentQuestionsComponent } from 'app/overview/student-questions/student-questions.component';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\n\nconst MAX_RESULT_HISTORY_LENGTH = 5;\n\n@Component({\n selector: 'jhi-course-exercise-details',\n templateUrl: './course-exercise-details.component.html',\n styleUrls: ['../course-overview.scss'],\n})\nexport class CourseExerciseDetailsComponent implements OnInit, OnDestroy {\n readonly AssessmentType = AssessmentType;\n readonly QuizStatus = QuizStatus;\n readonly QUIZ_ENDED_STATUS: (QuizStatus | undefined)[] = [QuizStatus.CLOSED, QuizStatus.OPEN_FOR_PRACTICE];\n readonly QUIZ = ExerciseType.QUIZ;\n readonly PROGRAMMING = ExerciseType.PROGRAMMING;\n readonly MODELING = ExerciseType.MODELING;\n readonly TEXT = ExerciseType.TEXT;\n readonly FILE_UPLOAD = ExerciseType.FILE_UPLOAD;\n private currentUser: User;\n private exerciseId: number;\n public courseId: number;\n private subscription: Subscription;\n public exercise?: Exercise;\n public showMoreResults = false;\n public sortedHistoryResult: Result[]; // might be a subset of the actual results in combinedParticipation.results\n public exerciseCategories: ExerciseCategory[];\n private participationUpdateListener: Subscription;\n private teamAssignmentUpdateListener: Subscription;\n private submissionSubscription: Subscription;\n studentParticipation?: StudentParticipation;\n isAfterAssessmentDueDate: boolean;\n public gradingCriteria: GradingCriterion[];\n showWelcomeAlert = false;\n private studentQuestions?: StudentQuestionsComponent;\n\n /**\n * variables are only for testing purposes(noVersionControlAndContinuousIntegrationAvailable)\n */\n public inProductionEnvironment: boolean;\n public noVersionControlAndContinuousIntegrationServerAvailable = false;\n public wasSubmissionSimulated = false;\n\n constructor(\n private $location: Location,\n private exerciseService: ExerciseService,\n private courseService: CourseManagementService,\n private jhiWebsocketService: JhiWebsocketService,\n private accountService: AccountService,\n private courseCalculationService: CourseScoreCalculationService,\n private participationWebsocketService: ParticipationWebsocketService,\n private participationService: ParticipationService,\n private sourceTreeService: SourceTreeService,\n private courseServer: CourseManagementService,\n private route: ActivatedRoute,\n private profileService: ProfileService,\n private guidedTourService: GuidedTourService,\n private courseExerciseSubmissionResultSimulationService: CourseExerciseSubmissionResultSimulationService,\n private programmingExerciseSimulationUtils: ProgrammingExerciseSimulationUtils,\n private jhiAlertService: JhiAlertService,\n private programmingExerciseSimulationService: ProgrammingExerciseSimulationService,\n private teamService: TeamService,\n private quizExerciseService: QuizExerciseService,\n private submissionService: ProgrammingSubmissionService,\n ) {}\n\n ngOnInit() {\n this.subscription = this.route.params.subscribe((params) => {\n const didExerciseChange = this.exerciseId !== parseInt(params['exerciseId'], 10);\n const didCourseChange = this.courseId !== parseInt(params['courseId'], 10);\n this.exerciseId = parseInt(params['exerciseId'], 10);\n this.courseId = parseInt(params['courseId'], 10);\n this.accountService.identity().then((user: User) => {\n this.currentUser = user;\n });\n if (didExerciseChange || didCourseChange) {\n this.loadExercise();\n }\n });\n\n this.route.queryParams.subscribe((queryParams) => {\n if (queryParams['welcome'] === '') {\n setTimeout(() => {\n this.showWelcomeAlert = true;\n }, 500);\n }\n });\n\n // Checks if the current environment is production\n this.profileService.getProfileInfo().subscribe((profileInfo) => {\n if (profileInfo) {\n this.inProductionEnvironment = profileInfo.inProduction;\n }\n });\n }\n\n ngOnDestroy() {\n if (this.participationUpdateListener) {\n this.participationUpdateListener.unsubscribe();\n if (this.studentParticipation) {\n this.participationWebsocketService.unsubscribeForLatestResultOfParticipation(this.studentParticipation!.id!, this.exercise!);\n }\n }\n if (this.teamAssignmentUpdateListener) {\n this.teamAssignmentUpdateListener.unsubscribe();\n }\n if (this.submissionSubscription) {\n this.submissionSubscription.unsubscribe();\n }\n }\n\n loadExercise() {\n this.exercise = undefined;\n this.studentParticipation = this.participationWebsocketService.getParticipationForExercise(this.exerciseId);\n this.exerciseService.getExerciseDetails(this.exerciseId).subscribe((exerciseResponse: HttpResponse<Exercise>) => {\n this.handleNewExercise(exerciseResponse.body!);\n });\n }\n\n handleNewExercise(newExercise: Exercise) {\n this.exercise = newExercise;\n this.exercise.studentParticipations = this.filterParticipations(newExercise.studentParticipations);\n this.mergeResultsAndSubmissionsForParticipations();\n this.exercise.participationStatus = participationStatus(this.exercise);\n this.isAfterAssessmentDueDate = !this.exercise.assessmentDueDate || moment().isAfter(this.exercise.assessmentDueDate);\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise);\n\n // This is only needed in the local environment\n if (!this.inProductionEnvironment && this.exercise.type === ExerciseType.PROGRAMMING && (<ProgrammingExercise>this.exercise).isLocalSimulation) {\n this.noVersionControlAndContinuousIntegrationServerAvailable = true;\n }\n\n this.subscribeForNewResults();\n this.subscribeToTeamAssignmentUpdates();\n\n // Subscribe for late programming submissions to show the student a success message\n if (this.exercise.type === ExerciseType.PROGRAMMING && this.exercise.dueDate && this.exercise.dueDate.isBefore(moment.now())) {\n this.subscribeForNewSubmissions();\n }\n\n if (this.studentQuestions && this.exercise) {\n // We need to manually update the exercise property of the student questions component\n this.studentQuestions.exercise = this.exercise;\n this.studentQuestions.loadQuestions(); // reload the student questions\n }\n }\n\n /**\n * Filter for participations that belong to the current user only. Additionally, we make sure that all results that are not finished (i.e. completionDate is not set) are\n * removed from the participations. We also sort the participations so that FINISHED participations come first.\n */\n private filterParticipations(participations?: StudentParticipation[]): StudentParticipation[] {\n if (!participations) {\n return [];\n }\n const filteredParticipations = participations.filter((participation: StudentParticipation) => {\n const personal = participation.student?.id === this.currentUser.id;\n const team = participation.team?.students?.map((s) => s.id).includes(this.currentUser.id);\n return personal || team;\n });\n filteredParticipations.forEach((participation: Participation) => {\n if (participation.results) {\n participation.results = participation.results.filter((result: Result) => result.completionDate);\n }\n });\n this.sortParticipationsFinishedFirst(filteredParticipations);\n return filteredParticipations;\n }\n\n /**\n * Sort the given participations so that FINISHED participations come first.\n *\n * Note, that this function directly operates on the array passed as argument and does not return anything.\n */\n private sortParticipationsFinishedFirst(participations: StudentParticipation[]) {\n if (participations && participations.length > 1) {\n participations.sort((a, b) => (b.initializationState === InitializationState.FINISHED ? 1 : -1));\n }\n }\n\n sortResults() {\n if (this.studentParticipation && this.studentParticipation.results) {\n this.studentParticipation.results = this.studentParticipation.results.sort(this.resultSortFunction);\n const sortedResultLength = this.studentParticipation.results.length;\n const startingElement = Math.max(sortedResultLength - MAX_RESULT_HISTORY_LENGTH, 0);\n this.sortedHistoryResult = this.studentParticipation.results.slice(startingElement, sortedResultLength);\n }\n }\n\n private resultSortFunction = (a: Result, b: Result) => {\n const aValue = moment(a.completionDate!).valueOf();\n const bValue = moment(b.completionDate!).valueOf();\n return aValue - bValue;\n };\n\n mergeResultsAndSubmissionsForParticipations() {\n // if there are new student participation(s) from the server, we need to update this.studentParticipation\n if (this.exercise) {\n if (this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0) {\n this.studentParticipation = this.participationService.mergeStudentParticipations(this.exercise.studentParticipations);\n this.sortResults();\n // Add exercise to studentParticipation, as the result component is dependent on its existence.\n if (this.studentParticipation && this.studentParticipation.exercise == undefined) {\n this.studentParticipation.exercise = this.exercise;\n }\n } else if (this.studentParticipation) {\n // otherwise we make sure that the student participation in exercise is correct\n this.exercise.studentParticipations = [this.studentParticipation];\n }\n }\n }\n\n subscribeForNewResults() {\n if (this.exercise && this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0) {\n this.exercise.studentParticipations.forEach((participation) => {\n this.participationWebsocketService.addParticipation(participation, this.exercise!);\n });\n if (this.latestRatedResult) {\n if (this.latestRatedResult.successful) {\n this.guidedTourService.enableTourForExercise(this.exercise, programmingExerciseSuccess, true);\n } else if (this.latestRatedResult.hasFeedback && !this.latestRatedResult.successful) {\n this.guidedTourService.enableTourForExercise(this.exercise, programmingExerciseFail, true);\n }\n }\n }\n this.participationUpdateListener = this.participationWebsocketService.subscribeForParticipationChanges().subscribe((changedParticipation: StudentParticipation) => {\n if (changedParticipation && this.exercise && changedParticipation.exercise?.id === this.exercise.id) {\n // Notify student about late submission result\n if (changedParticipation.exercise?.dueDate?.isBefore(moment.now()) && changedParticipation.results?.length! > this.studentParticipation?.results?.length!) {\n this.jhiAlertService.success('artemisApp.exercise.lateSubmissionResultReceived');\n }\n this.exercise.studentParticipations =\n this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0\n ? this.exercise.studentParticipations.map((el) => (el.id === changedParticipation.id ? changedParticipation : el))\n : [changedParticipation];\n this.mergeResultsAndSubmissionsForParticipations();\n }\n });\n }\n\n /**\n * Receives team assignment changes and applies them if they belong to this exercise\n */\n async subscribeToTeamAssignmentUpdates() {\n this.teamAssignmentUpdateListener = (await this.teamService.teamAssignmentUpdates)\n .pipe(filter(({ exerciseId }: TeamAssignmentPayload) => exerciseId === this.exercise?.id))\n .subscribe((teamAssignment) => {\n this.exercise!.studentAssignedTeamId = teamAssignment.teamId;\n this.exercise!.studentParticipations = teamAssignment.studentParticipations;\n this.exercise!.participationStatus = participationStatus(this.exercise!);\n });\n }\n\n /**\n * Subscribe for incoming (late) submissions to show a message if the student submitted after the due date.\n */\n subscribeForNewSubmissions() {\n if (this.studentParticipation) {\n this.submissionSubscription = this.submissionService\n .getLatestPendingSubmissionByParticipationId(this.studentParticipation!.id!, this.exercise?.id!, true)\n .subscribe(({ submission }) => {\n // Notify about received late submission\n if (submission && this.exercise?.dueDate && this.exercise.dueDate.isBefore(submission.submissionDate)) {\n this.jhiAlertService.success('artemisApp.exercise.lateSubmissionReceived');\n }\n });\n }\n }\n\n backToCourse() {\n this.$location.back();\n }\n\n exerciseRatedBadge(result: Result): string {\n return result.rated ? 'badge-success' : 'badge-info';\n }\n\n get exerciseIsOver(): boolean {\n return this.exercise ? moment(this.exercise!.dueDate!).isBefore(moment()) : true;\n }\n\n get hasMoreResults(): boolean {\n if (!this.studentParticipation || !this.studentParticipation.results) {\n return false;\n }\n return this.studentParticipation.results.length > MAX_RESULT_HISTORY_LENGTH;\n }\n\n get exerciseRouterLink(): string | null {\n if (this.exercise && [ExerciseType.MODELING, ExerciseType.TEXT, ExerciseType.FILE_UPLOAD].includes(this.exercise.type!)) {\n return `/course-management/${this.courseId}/${this.exercise.type}-exercises/${this.exercise!.id}/assessment`;\n }\n\n return null;\n }\n\n get showResults(): boolean {\n if (this.exercise!.type === ExerciseType.MODELING || this.exercise!.type === ExerciseType.TEXT) {\n return this.hasResults && this.isAfterAssessmentDueDate;\n }\n return this.hasResults;\n }\n\n get hasResults(): boolean {\n if (!this.studentParticipation || !this.studentParticipation.results) {\n return false;\n }\n return this.studentParticipation.results.length > 0;\n }\n\n /**\n * Returns the latest finished result for modeling and text exercises. It does not have to be rated.\n * For other exercise types it returns a rated result.\n */\n get latestRatedResult() {\n if (!this.studentParticipation || !this.hasResults) {\n return undefined;\n }\n\n if (this.exercise!.type === ExerciseType.MODELING || this.exercise!.type === ExerciseType.TEXT) {\n return this.studentParticipation?.results?.find((result: Result) => !!result.completionDate) || undefined;\n }\n\n const ratedResults = this.studentParticipation?.results?.filter((result: Result) => result.rated).sort(this.resultSortFunction);\n if (ratedResults) {\n const latestResult = ratedResults.length ? ratedResults[ratedResults.length - 1] : undefined;\n if (latestResult) {\n latestResult.participation = this.studentParticipation;\n }\n return latestResult;\n }\n }\n\n publishBuildPlanUrl() {\n return (this.exercise as ProgrammingExercise).publishBuildPlanUrl;\n }\n\n buildPlanActive() {\n return (\n !!this.exercise &&\n this.exercise.studentParticipations &&\n this.exercise.studentParticipations.length > 0 &&\n this.exercise.studentParticipations[0].initializationState !== InitializationState.INACTIVE\n );\n }\n\n projectKey(): string {\n return (this.exercise as ProgrammingExercise).projectKey!;\n }\n\n buildPlanId(participation: Participation) {\n return (participation! as ProgrammingExerciseStudentParticipation).buildPlanId;\n }\n\n /**\n * Returns the status of the exercise if it is a quiz exercise or undefined otherwise.\n */\n get quizExerciseStatus(): QuizStatus | undefined {\n if (this.exercise!.type === ExerciseType.QUIZ) {\n return this.quizExerciseService.getStatus(this.exercise as QuizExercise);\n }\n return undefined;\n }\n\n /**\n * This function gets called if the router outlet gets activated. This is\n * used only for the StudentQuestionsComponent\n * @param instance The component instance\n */\n onChildActivate(instance: StudentQuestionsComponent) {\n this.studentQuestions = instance; // save the reference to the component instance\n if (this.exercise) {\n instance.exercise = this.exercise;\n instance.loadQuestions(); // reload the student questions\n }\n }\n\n // ################## ONLY FOR LOCAL TESTING PURPOSE -- START ##################\n\n /**\n * Triggers the simulation of a participation and submission for the currently logged in user\n * This method will fail if used in production\n * This functionality is only for testing purposes(noVersionControlAndContinuousIntegrationAvailable)\n */\n simulateSubmission() {\n this.programmingExerciseSimulationService.failsIfInProduction(this.inProductionEnvironment);\n this.courseExerciseSubmissionResultSimulationService.simulateSubmission(this.exerciseId).subscribe(\n () => {\n this.wasSubmissionSimulated = true;\n this.jhiAlertService.success('artemisApp.exercise.submissionSuccessful');\n },\n () => {\n this.jhiAlertService.error('artemisApp.exercise.submissionUnsuccessful');\n },\n );\n }\n\n /**\n * Triggers the simulation of a result for the currently logged in user\n * This method will fail if used in production\n * This functionality is only for testing purposes(noVersionControlAndContinuousIntegrationAvailable)\n */\n simulateResult() {\n this.programmingExerciseSimulationService.failsIfInProduction(this.inProductionEnvironment);\n this.courseExerciseSubmissionResultSimulationService.simulateResult(this.exerciseId).subscribe(\n (result) => {\n // set the value to false in order to deactivate the result button\n this.wasSubmissionSimulated = false;\n\n // set these values in order to visualize the simulated result on the exercise details page\n this.exercise!.participationStatus = ParticipationStatus.EXERCISE_SUBMITTED;\n this.studentParticipation = <StudentParticipation>result.body!.participation;\n this.studentParticipation.results = [];\n this.studentParticipation.results[0] = result.body!;\n\n this.jhiAlertService.success('artemisApp.exercise.resultCreationSuccessful');\n },\n () => {\n this.jhiAlertService.error('artemisApp.exercise.resultCreationUnsuccessful');\n },\n );\n }\n\n // ################## ONLY FOR LOCAL TESTING PURPOSE -- END ##################\n}\n" }, { "alpha_fraction": 0.6184912919998169, "alphanum_fraction": 0.6201027035713196, "avg_line_length": 37.18846130371094, "blob_id": "3d67f4995ac6b0c390f39bef2c5428619bea5488", "content_id": "c27fd5dfb0a120bd9c8339fd3b1adf840f7a563b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9929, "license_type": "permissive", "max_line_length": 166, "num_lines": 260, "path": "/src/main/webapp/app/exam/manage/students/students-exam-import-dialog/students-exam-import-dialog.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnDestroy, ViewChild, ViewEncapsulation } from '@angular/core';\nimport { NgForm } from '@angular/forms';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { HttpResponse } from '@angular/common/http';\nimport { Subject } from 'rxjs';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { StudentDTO } from 'app/entities/student-dto.model';\nimport * as Papa from 'papaparse';\n\nconst csvColumns = Object.freeze({\n registrationNumber: 'registrationnumber',\n matrikelNummer: 'matrikelnummer',\n matriculationNumber: 'matriculationnumber',\n firstNameOfStudent: 'firstnameofstudent',\n familyNameOfStudent: 'familynameofstudent',\n firstName: 'firstname',\n familyName: 'familyname',\n lastName: 'lastname',\n login: 'login',\n username: 'username',\n user: 'user',\n benutzer: 'benutzer',\n benutzerName: 'benutzername',\n});\n\ntype CsvStudent = object;\n\n@Component({\n selector: 'jhi-students-exam-import-dialog',\n templateUrl: './students-exam-import-dialog.component.html',\n styleUrls: ['./students-exam-import-dialog.component.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class StudentsExamImportDialogComponent implements OnDestroy {\n readonly ActionType = ActionType;\n\n @ViewChild('importForm', { static: false }) importForm: NgForm;\n\n @Input() courseId: number;\n @Input() exam: Exam;\n\n studentsToImport: StudentDTO[] = [];\n notFoundStudents: StudentDTO[] = [];\n\n isParsing = false;\n validationError?: string;\n isImporting = false;\n hasImported = false;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(private activeModal: NgbActiveModal, private jhiAlertService: JhiAlertService, private examManagementService: ExamManagementService) {}\n\n ngOnDestroy(): void {\n this.dialogErrorSource.unsubscribe();\n }\n\n private resetDialog() {\n this.studentsToImport = [];\n this.notFoundStudents = [];\n this.hasImported = false;\n }\n\n async onCSVFileSelect($event: any) {\n if ($event.target.files.length > 0) {\n this.resetDialog();\n this.studentsToImport = await this.readStudentsFromCSVFile($event, $event.target.files[0]);\n }\n }\n\n /**\n * Reads students from a csv file into a list of StudentDTOs\n * The column \"registrationNumber\" is mandatory since the import requires it as an identifier\n * @param $event File change event from the HTML input of type file\n * @param csvFile File that contains one student per row and has at least the columns specified in csvColumns\n */\n private async readStudentsFromCSVFile($event: any, csvFile: File): Promise<StudentDTO[]> {\n let csvStudents: CsvStudent[] = [];\n try {\n this.isParsing = true;\n this.validationError = undefined;\n csvStudents = await this.parseCSVFile(csvFile);\n } catch (error) {\n this.validationError = error.message;\n } finally {\n this.isParsing = false;\n }\n if (csvStudents.length > 0) {\n this.performExtraValidations(csvFile, csvStudents);\n }\n if (this.validationError) {\n $event.target.value = ''; // remove selected file so user can fix the file and select it again\n return [];\n }\n return csvStudents.map(\n (student) =>\n ({\n registrationNumber: student[csvColumns.registrationNumber] || student[csvColumns.matrikelNummer] || student[csvColumns.matriculationNumber] || '',\n login:\n student[csvColumns.login] ||\n student[csvColumns.username] ||\n student[csvColumns.user] ||\n student[csvColumns.benutzer] ||\n student[csvColumns.benutzerName] ||\n '',\n firstName: student[csvColumns.firstName] || student[csvColumns.firstNameOfStudent] || '',\n lastName: student[csvColumns.lastName] || student[csvColumns.familyName] || student[csvColumns.familyNameOfStudent] || '',\n } as StudentDTO),\n );\n }\n\n /**\n * Performs validations on the parsed students\n * - checks if values for the required column {csvColumns.registrationNumber} are present\n *\n * @param csvFile File that contains one student per row and has at least the columns specified in csvColumns\n * @param csvStudents Parsed list of students\n */\n performExtraValidations(csvFile: File, csvStudents: CsvStudent[]) {\n const invalidStudentEntries = this.computeInvalidStudentEntries(csvStudents);\n if (invalidStudentEntries) {\n const msg = (body: string) => `\n Could not read file <b>${csvFile.name}</b> due to the following error:\n <ul class=\"mt-1\"><li><b>Rows must have a value in one of the required columns ${body}</b></li></ul>\n Please repair the file and try again.\n `;\n const maxLength = 30;\n const entriesFormatted = invalidStudentEntries.length <= maxLength ? invalidStudentEntries : invalidStudentEntries.slice(0, maxLength) + '...';\n this.validationError = msg(`${csvColumns.registrationNumber} or ${csvColumns.login}: ${entriesFormatted}`);\n }\n }\n\n /**\n * Returns a comma separated list of row numbers that contains invalid student entries\n * @param csvStudents Parsed list of students\n */\n computeInvalidStudentEntries(csvStudents: CsvStudent[]): string | null {\n const invalidList: number[] = [];\n for (const [i, student] of csvStudents.entries()) {\n if (\n !student[csvColumns.registrationNumber] &&\n !student[csvColumns.matrikelNummer] &&\n !student[csvColumns.matriculationNumber] &&\n !student[csvColumns.login] &&\n !student[csvColumns.user] &&\n !student[csvColumns.username] &&\n !student[csvColumns.benutzer] &&\n !student[csvColumns.benutzerName]\n ) {\n // '+ 2' instead of '+ 1' due to the header column in the csv file\n invalidList.push(i + 2);\n }\n }\n return invalidList.length === 0 ? null : invalidList.join(', ');\n }\n\n /**\n * Parses a csv file and returns a promise with a list of rows\n * @param csvFile File that should be parsed\n */\n private parseCSVFile(csvFile: File): Promise<CsvStudent[]> {\n return new Promise((resolve, reject) => {\n Papa.parse(csvFile, {\n header: true,\n transformHeader: (header: string) => header.toLowerCase().replace(' ', '').replace('_', ''),\n skipEmptyLines: true,\n complete: (results) => resolve(results.data as CsvStudent[]),\n error: (error) => reject(error),\n });\n });\n }\n\n /**\n * Sends the import request to the server with the list of students to be imported\n */\n importStudents() {\n this.isImporting = true;\n this.examManagementService.addStudentsToExam(this.courseId, this.exam.id!, this.studentsToImport).subscribe(\n (res) => this.onSaveSuccess(res),\n () => this.onSaveError(),\n );\n }\n\n /**\n * True if this student was successfully imported, false otherwise\n * @param student The student to be checked\n */\n wasImported(student: StudentDTO): boolean {\n return this.hasImported && !this.wasNotImported(student);\n }\n\n /**\n * True if this student could not be imported, false otherwise\n * @param student The student to be checked\n */\n wasNotImported(student: StudentDTO): boolean {\n if (this.hasImported && this.notFoundStudents?.length === 0) {\n return false;\n }\n\n for (const notFound of this.notFoundStudents) {\n if (\n (notFound.registrationNumber?.length > 0 && notFound.registrationNumber === student.registrationNumber) ||\n (notFound.login?.length > 0 && notFound.login === student.login)\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Number of students that were successfully imported\n */\n get numberOfStudentsImported(): number {\n return !this.hasImported ? 0 : this.studentsToImport.length - this.numberOfStudentsNotImported;\n }\n\n /**\n * Number of students which could not be imported\n */\n get numberOfStudentsNotImported(): number {\n return !this.hasImported ? 0 : this.notFoundStudents.length;\n }\n\n get isSubmitDisabled(): boolean {\n return this.isImporting || !this.studentsToImport?.length;\n }\n\n /**\n * Callback method that is called when the import request was successful\n * @param {HttpResponse<StudentDTO[]>} notFoundStudents - List of students that could NOT be imported since they were not found\n */\n onSaveSuccess(notFoundStudents: HttpResponse<StudentDTO[]>) {\n this.isImporting = false;\n this.hasImported = true;\n this.notFoundStudents = notFoundStudents.body! || [];\n }\n\n /**\n * Callback method that is called when the import request failed\n */\n onSaveError() {\n this.jhiAlertService.error('artemisApp.examManagement.examStudents.importStudents.genericErrorMessage');\n this.isImporting = false;\n }\n\n clear() {\n this.activeModal.dismiss('cancel');\n }\n\n onFinish() {\n this.activeModal.close();\n }\n}\n" }, { "alpha_fraction": 0.7062763571739197, "alphanum_fraction": 0.7102456092834473, "avg_line_length": 64.01612854003906, "blob_id": "44797daea1d4dfea133c0e90e2afc61df87faff0", "content_id": "64a80ad038cea765d45678776b3612ef1e60baa6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4031, "license_type": "permissive", "max_line_length": 194, "num_lines": 62, "path": "/src/test/java/de/tum/in/www1/artemis/service/connectors/TestSubmissionConstants.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors;\n\n// TODO: use these constants in text exercise / athene tests\npublic class TestSubmissionConstants {\n\n public static final String TEXT_0 = \"\"\"\n Differences:\n Antipatterns:\n -Have one problem and two solutions(one problematic and one refactored\n -Antipatterns are a sign of bad architecture and bad coding\n Pattern\n -Have one problem and one solutio\n -Patterns are a sign of elaborated architecutre and coding\"\"\";\n\n public static final String TEXT_1 = \"\"\"\n The main difference between patterns and antipatterns is, that patterns show you a good way to do something and antipatterns show a bad way to do something. \\\n Nevertheless patterns may become antipatterns in the course of changing understanding of how good software engineering looks like. One example for that is functional decomposition, \\\n which used to be a pattern and good practice. Over the time it turned out that it is not a goog way to solve problems, so it became a antipattern\n\n A pattern itsself is a proposed solution to a problem that occurs often and in different situations\n In contrast to that a antipattern shows commonly made mistakes when dealing with a certain problem. Nevertheless a refactored solution is aswell proposed.\"\"\";\n\n public static final String TEXT_2 = \"\"\"\n 1.Patterns can evolve into Antipatterns when change occurs\\\\n\\\n 2. Pattern has one solution, whereas anti pattern can have subtypes of solution\\\\n3\\\n . Antipattern has negative consequences and symptom, where as patterns looks only into benefits and consequences\"\"\";\n\n public static final String TEXT_3 = \"\"\"\n Patterns: A way to Model code in differents ways\n Antipattern: A way of how Not to Model code\"\"\";\n\n public static final String TEXT_4 = \"\"\"\n Antipatterns are used when there are common mistakes in software management and development to find these, \\\n while patterns by themselves are used to build software systems in the context of frequent change by reducing complexity and isolating the change\n Another difference is that the antipatterns have problematic solution and then refactored solution, while patterns only have a solution.\"\"\";\n\n public static final String TEXT_5 = \"\"\"\n - In patterns we have a problem and a solution, in antipatterns we have a problematic solution and a refactored solution instea\n - patterns represent best practices from the industry etc. so proven concepts, whereas antipatterns shed a light on common mistakes during software development etc.\"\"\";\n\n public static final String TEXT_6 = \"\"\"\n 1) Patterns have one solution, antipatterns have to solutions (one problematic and one refactored)\n 2) for the coice of patterns code has to be written; for antipatterns, the bad smell code already exists\"\"\";\n\n public static final String TEXT_7 = \"\"\"\n Design Patterns\n\n Solutions which are productive and efficient and are developed by Software Engineers over the years of practice and solving problems\n\n Anti Patterns\n\n Known solutions which are actually bad or defective to certain kind of problems.\"\"\";\n\n public static final String TEXT_8 = \"\"\"\n Patterns has one problem and one solution\n Antipatterns have one problematic solution and a solution for that. The antipattern happens when a solution that is been used for a long time can not apply anymore. \"\"\";\n\n public static final String TEXT_9 = \"\"\"\n Patterns identify problems and present solutions\n Antipatterns identify problems but two kinds of solutions. One problematic solution and a better refactored version of the solution. \\\n Problematic solutions are suggested not to be used because they results in smells or hinder future work.\"\"\";\n}\n" }, { "alpha_fraction": 0.7124746441841125, "alphanum_fraction": 0.7202501893043518, "avg_line_length": 44.86046600341797, "blob_id": "7dae637e505eed9cf596af22cacc5dcf5dd106eb", "content_id": "e9b1e33fa6f913f105ba14cadcde2695974c6c1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5916, "license_type": "permissive", "max_line_length": 175, "num_lines": 129, "path": "/src/test/java/de/tum/in/www1/artemis/TextUnitIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.Lecture;\nimport de.tum.in.www1.artemis.domain.lecture.TextUnit;\nimport de.tum.in.www1.artemis.repository.LectureRepository;\nimport de.tum.in.www1.artemis.repository.TextUnitRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class TextUnitIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private TextUnitRepository textUnitRepository;\n\n @Autowired\n private LectureRepository lectureRepository;\n\n private Lecture lecture1;\n\n private TextUnit textUnit;\n\n @BeforeEach\n public void initTestCase() throws Exception {\n this.database.addUsers(1, 1, 1);\n this.lecture1 = this.database.createCourseWithLecture(true);\n this.textUnit = new TextUnit();\n this.textUnit.setName(\"LoremIpsum\");\n this.textUnit.setContent(\"This is a Test\");\n\n // Add users that are not in the course\n userRepository.save(ModelFactory.generateActivatedUser(\"student42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"tutor42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"instructor42\"));\n }\n\n private void testAllPreAuthorize() throws Exception {\n request.put(\"/api/lectures/\" + lecture1.getId() + \"/text-units\", textUnit, HttpStatus.FORBIDDEN);\n request.post(\"/api/lectures/\" + lecture1.getId() + \"/text-units\", textUnit, HttpStatus.FORBIDDEN);\n request.get(\"/api/lectures/\" + lecture1.getId() + \"/text-units/0\", HttpStatus.FORBIDDEN, TextUnit.class);\n }\n\n @AfterEach\n public void resetDatabase() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testAll_asTutor() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testAll_asStudent() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createTextUnit_asInstructor_shouldCreateTextUnitUnit() throws Exception {\n var persistedTextUnit = request.postWithResponseBody(\"/api/lectures/\" + this.lecture1.getId() + \"/text-units\", textUnit, TextUnit.class, HttpStatus.CREATED);\n assertThat(persistedTextUnit.getId()).isNotNull();\n }\n\n @Test\n @WithMockUser(username = \"instructor42\", roles = \"INSTRUCTOR\")\n public void createTextUnit_InstructorNotInCourse_shouldReturnForbidden() throws Exception {\n request.postWithResponseBody(\"/api/lectures/\" + this.lecture1.getId() + \"/text-units\", textUnit, TextUnit.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateTextUnit_asInstructor_shouldUpdateTextUnit() throws Exception {\n persistTextUnitWithLecture();\n TextUnit textUnitFromRequest = request.get(\"/api/lectures/\" + lecture1.getId() + \"/text-units/\" + this.textUnit.getId(), HttpStatus.OK, TextUnit.class);\n textUnitFromRequest.setContent(\"Changed\");\n TextUnit updatedTextUnit = request.putWithResponseBody(\"/api/lectures/\" + lecture1.getId() + \"/text-units\", textUnitFromRequest, TextUnit.class, HttpStatus.OK);\n assertThat(updatedTextUnit.getContent()).isEqualTo(\"Changed\");\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateTextUnit_noId_shouldReturnBadRequest() throws Exception {\n persistTextUnitWithLecture();\n TextUnit textUnitFromRequest = request.get(\"/api/lectures/\" + lecture1.getId() + \"/text-units/\" + this.textUnit.getId(), HttpStatus.OK, TextUnit.class);\n textUnitFromRequest.setId(null);\n request.putWithResponseBody(\"/api/lectures/\" + lecture1.getId() + \"/text-units\", textUnitFromRequest, TextUnit.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getTextUnit_correctId_shouldReturnTextUnit() throws Exception {\n persistTextUnitWithLecture();\n TextUnit textUnitFromRequest = request.get(\"/api/lectures/\" + lecture1.getId() + \"/text-units/\" + this.textUnit.getId(), HttpStatus.OK, TextUnit.class);\n assertThat(this.textUnit.getId()).isEqualTo(textUnitFromRequest.getId());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteTextUnit_correctId_shouldDeleteTextUnit() throws Exception {\n persistTextUnitWithLecture();\n assertThat(this.textUnit.getId()).isNotNull();\n request.delete(\"/api/lectures/\" + lecture1.getId() + \"/lecture-units/\" + this.textUnit.getId(), HttpStatus.OK);\n request.get(\"/api/lectures/\" + lecture1.getId() + \"/text-units/\" + this.textUnit.getId(), HttpStatus.NOT_FOUND, TextUnit.class);\n }\n\n private void persistTextUnitWithLecture() {\n this.textUnit = textUnitRepository.save(this.textUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.textUnit);\n lecture1 = lectureRepository.save(lecture1);\n this.textUnit = (TextUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n }\n\n}\n" }, { "alpha_fraction": 0.7449005246162415, "alphanum_fraction": 0.7560767531394958, "avg_line_length": 57.002906799316406, "blob_id": "3bdffa6836395cd5612257af8c6edce45868da52", "content_id": "85f96c3d33e2a294c5476b536d3a4c3927aa4f42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 19953, "license_type": "permissive", "max_line_length": 179, "num_lines": 344, "path": "/src/test/java/de/tum/in/www1/artemis/service/ExamAccessServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.repository.*;\n\npublic class ExamAccessServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private ExamRepository examRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private StudentExamRepository studentExamRepository;\n\n private Course course1;\n\n private Exam exam1;\n\n private Exam exam2;\n\n private ExerciseGroup exerciseGroup1;\n\n private ExerciseGroup exerciseGroup2;\n\n private StudentExam studentExam1;\n\n private StudentExam studentExam2;\n\n @BeforeEach\n void init() {\n List<User> users = database.addUsers(1, 1, 2);\n User instructor1 = users.get(2);\n User instructor2 = users.get(3);\n instructor1.setGroups(Collections.singleton(\"course1InstructorGroup\"));\n instructor2.setGroups(Collections.singleton(\"course2InstructorGroup\"));\n userRepository.save(instructor1);\n userRepository.save(instructor2);\n course1 = database.addEmptyCourse();\n Course course2 = database.addEmptyCourse();\n course1.setInstructorGroupName(\"course1InstructorGroup\");\n course2.setInstructorGroupName(\"course2InstructorGroup\");\n courseRepository.save(course1);\n courseRepository.save(course2);\n exam1 = database.addExamWithExerciseGroup(course1, true);\n exam2 = database.addExamWithExerciseGroup(course2, true);\n exerciseGroup1 = exam1.getExerciseGroups().get(0);\n exerciseGroup2 = exam2.getExerciseGroups().get(0);\n studentExam1 = database.addStudentExam(exam1);\n studentExam2 = database.addStudentExam(exam2);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n courseRepository.deleteAll();\n examRepository.deleteAll();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckCourseAccess_asStudent() {\n // checkCourseAccess\n Optional<ResponseEntity<Exam>> accessFailureCourse1 = examAccessService.checkCourseAccessForInstructor(course1.getId());\n assertThat(accessFailureCourse1.isPresent()).isTrue();\n assertThat(accessFailureCourse1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Exam>> accessFailureCourse2 = examAccessService.checkCourseAccessForTeachingAssistant(course1.getId());\n assertThat(accessFailureCourse2.isPresent()).isTrue();\n assertThat(accessFailureCourse2.get()).isEqualTo(forbidden());\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam1 = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam1.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam2 = examAccessService.checkCourseAndExamAccessForTeachingAssistant(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam2.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam2.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testCheckCourseAccess_asTutor() {\n // checkCourseAccess\n Optional<ResponseEntity<Exam>> accessFailureCourse = examAccessService.checkCourseAccessForInstructor(course1.getId());\n assertThat(accessFailureCourse.isPresent()).isTrue();\n assertThat(accessFailureCourse.get()).isEqualTo(forbidden());\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"instructor2\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAccess_asInstructorWithoutCourseAccess() {\n // checkCourseAccess\n Optional<ResponseEntity<Exam>> accessFailureCourse1 = examAccessService.checkCourseAccessForInstructor(course1.getId());\n assertThat(accessFailureCourse1.isPresent()).isTrue();\n assertThat(accessFailureCourse1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Exam>> accessFailureCourse2 = examAccessService.checkCourseAccessForTeachingAssistant(course1.getId());\n assertThat(accessFailureCourse2.isPresent()).isTrue();\n assertThat(accessFailureCourse2.get()).isEqualTo(forbidden());\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam1 = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam1.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam2 = examAccessService.checkCourseAndExamAccessForTeachingAssistant(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam2.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam2.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(forbidden());\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testCheckCourseAccess_asTutorWithCourseAccess() {\n // checkCourseAccess\n Optional<ResponseEntity<Exam>> accessFailureCourse = examAccessService.checkCourseAccessForTeachingAssistant(course1.getId());\n assertThat(accessFailureCourse.isEmpty()).isTrue();\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForTeachingAssistant(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam.isEmpty()).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAccess_asInstructorWithCourseAccess() {\n // checkCourseAccess\n Optional<ResponseEntity<Exam>> accessFailureCourse = examAccessService.checkCourseAccessForInstructor(course1.getId());\n assertThat(accessFailureCourse.isEmpty()).isTrue();\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam.isEmpty()).isTrue();\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isEmpty()).isTrue();\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isEmpty()).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAccess_notFound() {\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), 99999L);\n assertThat(accessFailureCourseAndExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam.get()).isEqualTo(notFound());\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), 99999L,\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(notFound());\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), 99999L,\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAccess_conflict() {\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam2.getId());\n assertThat(accessFailureCourseAndExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExam.get()).isEqualTo(conflict());\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam2.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(conflict());\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam2.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAccess() {\n // checkCourseAndExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExam = examAccessService.checkCourseAndExamAccessForInstructor(course1.getId(), exam1.getId());\n assertThat(accessFailureCourseAndExam.isEmpty()).isTrue();\n // checkCourseAndExamAndExerciseGroupAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isEmpty()).isTrue();\n // checkCourseAndExamAndStudentExamAccess\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isEmpty()).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndExerciseGroupAccess_notFound() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n 99999L);\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndExerciseGroupAccess_conflict() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup2.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndExerciseGroup.get()).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndExerciseGroupAccess() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndExerciseGroup = examAccessService.checkCourseAndExamAndExerciseGroupAccess(course1.getId(), exam1.getId(),\n exerciseGroup1.getId());\n assertThat(accessFailureCourseAndExamAndExerciseGroup.isEmpty()).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndStudentExamAccess_notFound() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(), 99999L);\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndStudentExamAccess_conflict() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam2.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isPresent()).isTrue();\n assertThat(accessFailureCourseAndExamAndStudentExam.get()).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckCourseAndExamAndStudentExamAccess() {\n Optional<ResponseEntity<Exam>> accessFailureCourseAndExamAndStudentExam = examAccessService.checkCourseAndExamAndStudentExamAccess(course1.getId(), exam1.getId(),\n studentExam1.getId());\n assertThat(accessFailureCourseAndExamAndStudentExam.isEmpty()).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckAndGetCourseAndExamAccessForConduction_isStudentInCourse() {\n Course course = database.addEmptyCourse();\n course.setStudentGroupName(\"another\");\n courseRepository.save(course);\n ResponseEntity<StudentExam> result = examAccessService.checkAndGetCourseAndExamAccessForConduction(course.getId(), exam1.getId());\n assertThat(result).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckAndGetCourseAndExamAccessForConduction_examExists() {\n ResponseEntity<StudentExam> result = examAccessService.checkAndGetCourseAndExamAccessForConduction(course1.getId(), 123155L);\n assertThat(result).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckAndGetCourseAndExamAccessForConduction_examBelongsToCourse() {\n studentExam2.setUser(database.getUserByLogin(\"student1\"));\n studentExamRepository.save(studentExam2);\n ResponseEntity<StudentExam> result = examAccessService.checkAndGetCourseAndExamAccessForConduction(course1.getId(), exam2.getId());\n assertThat(result).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckAndGetCourseAndExamAccessForConduction_registeredUser() {\n studentExam1.setUser(database.getUserByLogin(\"student1\"));\n studentExamRepository.save(studentExam1);\n ResponseEntity<StudentExam> result = examAccessService.checkAndGetCourseAndExamAccessForConduction(course1.getId(), exam1.getId());\n assertThat(result).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckAndGetCourseAndExamAccessForConduction_examIsVisible() {\n Exam exam = database.addActiveExamWithRegisteredUser(course1, database.getUserByLogin(\"student1\"));\n exam.setVisibleDate(ZonedDateTime.now().plusMinutes(5));\n examRepository.save(exam);\n ResponseEntity<StudentExam> result = examAccessService.checkAndGetCourseAndExamAccessForConduction(course1.getId(), exam.getId());\n assertThat(result).isEqualTo(forbidden());\n }\n}\n" }, { "alpha_fraction": 0.6018926501274109, "alphanum_fraction": 0.611168384552002, "avg_line_length": 45.004310607910156, "blob_id": "1f4de7847696f82aeef8a7e8a661ff1562abd2c3", "content_id": "b119cab4d9bb4131a55cd509ecdd10e1b4952ed7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10673, "license_type": "permissive", "max_line_length": 174, "num_lines": 232, "path": "/src/test/javascript/spec/component/modeling-assessment/modeling-assessment.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SimpleChange } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { By } from '@angular/platform-browser';\nimport { ApollonEditor, UMLDiagramType, UMLElement, UMLModel, UMLRelationship } from '@ls1intum/apollon';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { ModelingAssessmentComponent } from 'app/exercises/modeling/assess/modeling-assessment.component';\nimport { ModelingExplanationEditorComponent } from 'app/exercises/modeling/shared/modeling-explanation-editor.component';\nimport { ScoreDisplayComponent } from 'app/shared/score-display/score-display.component';\nimport * as chai from 'chai';\nimport { MockModule } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ModelingAssessmentComponent', () => {\n let fixture: ComponentFixture<ModelingAssessmentComponent>;\n let comp: ModelingAssessmentComponent;\n\n const generateMockModel = (elementId: string, elementId2: string, relationshipId: string) => {\n return {\n version: '2.0.0',\n type: 'ClassDiagram',\n size: { width: 740, height: 660 },\n interactive: { elements: [], relationships: [] },\n elements: [\n {\n id: elementId,\n name: 'Package',\n type: 'Package',\n owner: null,\n bounds: { x: 160, y: 40, width: 200, height: 100 },\n highlight: undefined,\n },\n {\n id: elementId2,\n name: 'Class',\n type: 'Class',\n owner: null,\n bounds: { x: 280, y: 320, width: 200, height: 100 },\n attributes: [],\n methods: [],\n highlight: undefined,\n },\n ],\n relationships: [\n {\n id: relationshipId,\n name: '',\n type: 'ClassBidirectional',\n owner: null,\n bounds: { x: 120, y: 0, width: 265, height: 320 },\n path: [\n { x: 260, y: 320 },\n { x: 260, y: 280 },\n { x: 0, y: 280 },\n { x: 0, y: 0 },\n { x: 140, y: 0 },\n { x: 140, y: 40 },\n ],\n source: {\n direction: 'Up',\n element: elementId2,\n },\n target: {\n direction: 'Up',\n element: elementId,\n },\n } as UMLRelationship,\n ],\n assessments: [],\n } as UMLModel;\n };\n\n const mockModel = generateMockModel('elementId1', 'elementId2', 'relationshipId');\n const mockFeedbackWithReference = { text: 'FeedbackWithReference', referenceId: 'relationshipId', reference: 'referemce', credits: 30 } as Feedback;\n const mockFeedbackWithoutReference = { text: 'FeedbackWithoutReference', credits: 30, type: FeedbackType.MANUAL_UNREFERENCED } as Feedback;\n const mockFeedbackInvalid = { text: 'FeedbackInvalid', referenceId: '4', reference: 'reference' };\n const mockValidFeedbacks = [mockFeedbackWithReference, mockFeedbackWithoutReference];\n const mockFeedbacks = [...mockValidFeedbacks, mockFeedbackInvalid];\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, MockModule(FormsModule)],\n declarations: [ModelingAssessmentComponent, ScoreDisplayComponent, ModelingExplanationEditorComponent, MockDirective(NgbTooltip), MockPipe(ArtemisTranslatePipe)],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ModelingAssessmentComponent);\n comp = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should show title if any', () => {\n const title = 'Test Title';\n comp.title = title;\n fixture.detectChanges();\n const el = fixture.debugElement.query((de) => de.nativeElement.textContent === title);\n expect(el).to.exist;\n });\n\n describe('score display', () => {\n let totalScore: number;\n let maxScore: number;\n beforeEach(() => {\n totalScore = 40;\n comp.totalScore = totalScore;\n maxScore = 66;\n comp.maxScore = maxScore;\n });\n it('should display score display with right values', () => {\n comp.displayPoints = true;\n fixture.detectChanges();\n const scoreDisplay = fixture.debugElement.query(By.directive(ScoreDisplayComponent));\n expect(scoreDisplay).to.exist;\n expect(scoreDisplay.componentInstance.score).to.equal(totalScore);\n expect(scoreDisplay.componentInstance.maxPoints).to.equal(maxScore);\n });\n\n it('should not display score if displayPoints wrong', () => {\n comp.displayPoints = false;\n fixture.detectChanges();\n const scoreDisplay = fixture.debugElement.query(By.directive(ScoreDisplayComponent));\n expect(scoreDisplay).to.not.exist;\n });\n });\n\n it('should display explanation editor if there is an explanation', () => {\n const explanation = 'Explanation';\n comp.explanation = explanation;\n fixture.detectChanges();\n const explanationEditor = fixture.debugElement.query(By.directive(ModelingExplanationEditorComponent));\n expect(explanationEditor).to.exist;\n expect(explanationEditor.componentInstance.explanation).to.equal(explanation);\n expect(explanationEditor.componentInstance.readOnly).to.equal(true);\n });\n\n it('should initialize apollon editor', () => {\n comp.model = mockModel;\n comp.diagramType = UMLDiagramType.ClassDiagram;\n fixture.detectChanges();\n expect(comp.apollonEditor).to.exist;\n });\n\n it('should filter references', () => {\n comp.model = mockModel;\n comp.readOnly = true;\n comp.feedbacks = mockFeedbacks;\n fixture.detectChanges();\n expect(comp.referencedFeedbacks).to.deep.equal([mockFeedbackWithReference]);\n expect(comp.unreferencedFeedbacks).to.deep.equal([mockFeedbackWithoutReference]);\n expect(comp.feedbacks).to.deep.equal(mockFeedbacks);\n });\n\n it('should highlight elements', () => {\n const highlightedElements = new Map();\n highlightedElements.set('elementId1', 'red');\n highlightedElements.set('relationshipId', 'blue');\n comp.model = mockModel;\n comp.highlightedElements = highlightedElements;\n fixture.detectChanges();\n expect(comp.apollonEditor).to.exist;\n const apollonModel = comp.apollonEditor!.model;\n const elements: UMLElement[] = apollonModel.elements;\n const highlightedElement = elements.find((el) => el.id === 'elementId1');\n const notHighlightedElement = elements.find((el) => el.id === 'elementId2');\n const relationship = apollonModel.relationships[0];\n expect(highlightedElement).to.exist;\n expect(highlightedElement!.highlight).to.equal('red');\n expect(notHighlightedElement).to.exist;\n expect(notHighlightedElement!.highlight).to.not.exist;\n expect(relationship).to.exist;\n expect(relationship!.highlight).to.equal('blue');\n });\n\n it('should update model', () => {\n const newModel = generateMockModel('newElement1', 'newElement2', 'newRelationship');\n const changes = { model: { currentValue: newModel } as SimpleChange };\n fixture.detectChanges();\n const apollonSpy = sinon.spy(comp.apollonEditor as ApollonEditor, 'model', ['set']);\n comp.ngOnChanges(changes);\n expect(apollonSpy.set).to.have.been.calledWithExactly(newModel);\n });\n\n it('should update highlighted elements', () => {\n const highlightedElements = new Map();\n highlightedElements.set('elementId2', 'green');\n const changes = { highlightedElements: { currentValue: highlightedElements } as SimpleChange };\n comp.model = mockModel;\n fixture.detectChanges();\n comp.highlightedElements = highlightedElements;\n comp.ngOnChanges(changes);\n expect(comp.apollonEditor).to.exist;\n const apollonModel = comp.apollonEditor!.model;\n const elements: UMLElement[] = apollonModel.elements;\n const highlightedElement = elements.find((el) => el.id === 'elementId2');\n const notHighlightedElement = elements.find((el) => el.id === 'elementId1');\n const relationship = apollonModel.relationships[0];\n expect(highlightedElement).to.exist;\n expect(highlightedElement!.highlight).to.equal('green');\n expect(notHighlightedElement).to.exist;\n expect(notHighlightedElement!.highlight).to.not.exist;\n expect(relationship).to.exist;\n expect(relationship!.highlight).to.not.exist;\n });\n\n it('should update feedbacks', () => {\n const newMockFeedbackWithReference = { text: 'NewFeedbackWithReference', referenceId: 'relationshipId', reference: 'reference', credits: 30 } as Feedback;\n const newMockFeedbackWithoutReference = { text: 'NewFeedbackWithoutReference', credits: 30, type: FeedbackType.MANUAL_UNREFERENCED } as Feedback;\n const newMockFeedbackInvalid = { text: 'NewFeedbackInvalid', referenceId: '4', reference: 'reference' };\n const newMockValidFeedbacks = [newMockFeedbackWithReference, newMockFeedbackWithoutReference];\n const newMockFeedbacks = [...newMockValidFeedbacks, newMockFeedbackInvalid];\n comp.model = mockModel;\n comp.readOnly = true;\n fixture.detectChanges();\n const changes = { feedbacks: { currentValue: newMockFeedbacks } as SimpleChange };\n comp.ngOnChanges(changes);\n expect(comp.feedbacks).to.deep.equal(newMockFeedbacks);\n expect(comp.referencedFeedbacks).to.deep.equal([newMockFeedbackWithReference]);\n });\n});\n" }, { "alpha_fraction": 0.7301136255264282, "alphanum_fraction": 0.7301136255264282, "avg_line_length": 34.20000076293945, "blob_id": "6217a7001f076300e08f5a3d680f02508f73c850", "content_id": "e1660b5307e5751bc59ed6520a77186e746c4f89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 704, "license_type": "permissive", "max_line_length": 122, "num_lines": 20, "path": "/src/main/webapp/app/shared/participant-scores/participant-scores-table/participant-scores-table.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { ParticipantScoreDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport { round } from 'app/shared/util/utils';\n\n@Component({\n selector: 'jhi-participant-scores-table',\n templateUrl: './participant-scores-table.component.html',\n})\nexport class ParticipantScoresTableComponent {\n readonly round = round;\n\n @Input()\n participantScores: ParticipantScoreDTO[] = [];\n\n @Input()\n isLoading = false;\n extractParticipantName = (participantScoreDTO: ParticipantScoreDTO) => {\n return participantScoreDTO.userName ? String(participantScoreDTO.userName) : String(participantScoreDTO.teamName);\n };\n}\n" }, { "alpha_fraction": 0.6958392858505249, "alphanum_fraction": 0.6972740292549133, "avg_line_length": 24.814815521240234, "blob_id": "16ec95a974bd771e516bf6e9bc4fe8ec5e4e4849", "content_id": "6c1444fab989a0f477df4f8d6f8125f18a263ee7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1394, "license_type": "permissive", "max_line_length": 122, "num_lines": 54, "path": "/src/main/java/de/tum/in/www1/artemis/domain/TextExercise.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport java.util.List;\n\nimport javax.persistence.*;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\n\n/**\n * A TextExercise.\n */\n@Entity\n@DiscriminatorValue(value = \"T\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class TextExercise extends Exercise {\n\n @Column(name = \"sample_solution\")\n @Lob\n private String sampleSolution;\n\n @OneToMany(mappedBy = \"exercise\", cascade = CascadeType.REMOVE)\n @JsonIgnore\n private List<TextCluster> clusters;\n\n public String getSampleSolution() {\n return sampleSolution;\n }\n\n public void setSampleSolution(String sampleSolution) {\n this.sampleSolution = sampleSolution;\n }\n\n public boolean isAutomaticAssessmentEnabled() {\n return getAssessmentType() == AssessmentType.SEMI_AUTOMATIC;\n }\n\n /**\n * set all sensitive information to null, so no info with respect to the solution gets leaked to students through json\n */\n @Override\n public void filterSensitiveInformation() {\n setSampleSolution(null);\n super.filterSensitiveInformation();\n }\n\n @Override\n public String toString() {\n return \"TextExercise{\" + \"id=\" + getId() + \", sampleSolution='\" + getSampleSolution() + \"'\" + \"}\";\n }\n\n}\n" }, { "alpha_fraction": 0.6790505647659302, "alphanum_fraction": 0.6790505647659302, "avg_line_length": 47.45000076293945, "blob_id": "4432b01f9a2590a5268ea5b401c66d888af7f775", "content_id": "d5ac6ca87a4d19d26155aaeb002472349e500f67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5814, "license_type": "permissive", "max_line_length": 135, "num_lines": 120, "path": "/src/main/webapp/app/exercises/shared/result/result.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport * as moment from 'moment';\nimport { isMoment } from 'moment';\nimport { Result } from '../../../entities/result.model';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\n\nexport type EntityResponseType = HttpResponse<Result>;\nexport type EntityArrayResponseType = HttpResponse<Result[]>;\n\nexport interface IResultService {\n find: (id: number) => Observable<EntityResponseType>;\n findBySubmissionId: (submissionId: number) => Observable<EntityResponseType>;\n getResultsForExercise: (courseId: number, exerciseId: number, req?: any) => Observable<EntityArrayResponseType>;\n getLatestResultWithFeedbacks: (particpationId: number) => Observable<HttpResponse<Result>>;\n getFeedbackDetailsForResult: (resultId: number) => Observable<HttpResponse<Feedback[]>>;\n delete: (id: number) => Observable<HttpResponse<void>>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ResultService implements IResultService {\n private exerciseResourceUrl = SERVER_API_URL + 'api/exercises';\n private resultResourceUrl = SERVER_API_URL + 'api/results';\n private submissionResourceUrl = SERVER_API_URL + 'api/submissions';\n private participationResourceUrl = SERVER_API_URL + 'api/participations';\n\n constructor(private http: HttpClient, private exerciseService: ExerciseService) {}\n\n find(resultId: number): Observable<EntityResponseType> {\n return this.http\n .get<Result>(`${this.resultResourceUrl}/${resultId}`, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n findBySubmissionId(submissionId: number): Observable<EntityResponseType> {\n return this.http\n .get<Result>(`${this.resultResourceUrl}/submission/${submissionId}`, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n getResultsForExercise(exerciseId: number, req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n return this.http\n .get<Result[]>(`${this.exerciseResourceUrl}/${exerciseId}/results`, {\n params: options,\n observe: 'response',\n })\n .map((res: EntityArrayResponseType) => this.convertArrayResponse(res));\n }\n\n getFeedbackDetailsForResult(resultId: number): Observable<HttpResponse<Feedback[]>> {\n return this.http.get<Feedback[]>(`${this.resultResourceUrl}/${resultId}/details`, { observe: 'response' });\n }\n\n getLatestResultWithFeedbacks(particpationId: number): Observable<HttpResponse<Result>> {\n return this.http.get<Result>(`${this.participationResourceUrl}/${particpationId}/latest-result`, { observe: 'response' });\n }\n\n delete(resultId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resultResourceUrl}/${resultId}`, { observe: 'response' });\n }\n\n /**\n * Create a new example result for the provided submission ID.\n *\n * @param submissionId The ID of the example submission for which a result should get created\n * @return The newly created (and empty) example result\n */\n createNewExampleResult(submissionId: number): Observable<HttpResponse<Result>> {\n return this.http.post<Result>(`${this.submissionResourceUrl}/${submissionId}/example-result`, null, { observe: 'response' });\n }\n\n public convertDateFromClient(result: Result): Result {\n const copy: Result = Object.assign({}, result, {\n completionDate:\n // Result completionDate is a moment object -> toJSON.\n result.completionDate && isMoment(result.completionDate)\n ? result.completionDate.toJSON()\n : // Result completionDate would be a valid date -> keep string.\n result.completionDate && moment(result.completionDate).isValid()\n ? result.completionDate\n : // No valid date -> remove date.\n null,\n });\n return copy;\n }\n\n protected convertArrayResponse(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((result: Result) => {\n result.completionDate = result.completionDate ? moment(result.completionDate) : undefined;\n result.participation = this.convertParticipationDateFromServer(result.participation! as StudentParticipation);\n });\n }\n return res;\n }\n\n public convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.completionDate = res.body.completionDate ? moment(res.body.completionDate) : undefined;\n res.body.participation = this.convertParticipationDateFromServer(res.body.participation! as StudentParticipation);\n }\n return res;\n }\n\n convertParticipationDateFromServer(participation: StudentParticipation) {\n if (participation) {\n participation.initializationDate = participation.initializationDate ? moment(participation.initializationDate) : undefined;\n if (participation.exercise) {\n participation.exercise = this.exerciseService.convertExerciseDateFromServer(participation.exercise);\n }\n }\n return participation;\n }\n}\n" }, { "alpha_fraction": 0.6826608777046204, "alphanum_fraction": 0.6826608777046204, "avg_line_length": 28.580644607543945, "blob_id": "379ed1dc4fe6b195a228fee956e32dd34c2f9407", "content_id": "77d9a37b7e39bdf387477cf7f300dcbf31ccbaa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 917, "license_type": "permissive", "max_line_length": 86, "num_lines": 31, "path": "/src/main/webapp/app/overview/course-lectures/video-unit/video-unit.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { SafeResourceUrl } from '@angular/platform-browser';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport { SafeResourceUrlPipe } from 'app/shared/pipes/safe-resource-url.pipe';\n\n@Component({\n selector: 'jhi-video-unit',\n templateUrl: './video-unit.component.html',\n styleUrls: ['../lecture-unit.component.scss'],\n})\nexport class VideoUnitComponent implements OnInit {\n @Input()\n videoUnit: VideoUnit;\n\n videoUrl: SafeResourceUrl;\n\n isCollapsed = true;\n\n constructor(private safeResourceUrlPipe: SafeResourceUrlPipe) {}\n\n ngOnInit() {\n if (this.videoUnit?.source) {\n this.videoUrl = this.safeResourceUrlPipe.transform(this.videoUnit.source);\n }\n }\n\n handleCollapse($event: any) {\n $event.stopPropagation();\n this.isCollapsed = !this.isCollapsed;\n }\n}\n" }, { "alpha_fraction": 0.7072463631629944, "alphanum_fraction": 0.7072463631629944, "avg_line_length": 42.125, "blob_id": "5f496f2d8d535122cb5751ecd4ddd764d21dd7e7", "content_id": "e862471a7bb21931223567d9539af4e5dbe26f93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 690, "license_type": "permissive", "max_line_length": 91, "num_lines": 16, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Routes } from '@angular/router';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { ExerciseLtiConfigurationComponent } from './exercise-lti-configuration.component';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\nexport const exercisePopupRoute: Routes = [\n {\n path: ':courseId/exercises/:exerciseId/lti-configuration',\n component: ExerciseLtiConfigurationComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n];\n" }, { "alpha_fraction": 0.6143680214881897, "alphanum_fraction": 0.6180955767631531, "avg_line_length": 35.88750076293945, "blob_id": "0947783a371ad3c052793352ddd46fcb93cb4500", "content_id": "2848b65d52f80056c25295ac282f32e28622501c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2951, "license_type": "permissive", "max_line_length": 94, "num_lines": 80, "path": "/src/test/javascript/spec/service/rating.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { TranslateService } from '@ngx-translate/core';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { take } from 'rxjs/operators';\nimport { SessionStorageService } from 'ngx-webstorage';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { ArtemisTestModule } from '../test.module';\nimport { RatingService } from 'app/exercises/shared/rating/rating.service';\nimport { Rating } from 'app/entities/rating.model';\nimport { Result } from 'app/entities/result.model';\n\ndescribe('Rating Service', () => {\n let injector: TestBed;\n let service: RatingService;\n let httpMock: HttpTestingController;\n let elemDefault: Rating;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n providers: [\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n });\n injector = getTestBed();\n service = injector.get(RatingService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new Rating(new Result(), 3);\n });\n\n it('should create a Rating', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n service.createRating(new Rating(new Result(), 3)).pipe(take(1)).subscribe();\n\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should get a Rating', async () => {\n const returnedFromService = Object.assign({}, elemDefault);\n service.getRating(0).pipe(take(1)).subscribe();\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should update a Rating', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n service.updateRating(new Rating(new Result(), 3)).pipe(take(1)).subscribe();\n\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should get Ratings for Dashboard', async () => {\n const returnedFromService = Object.assign({}, [elemDefault]);\n service.getRatingsForDashboard(0).subscribe((ratings: Rating[]) => {\n expect(ratings.length).toEqual(1);\n });\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.7248144149780273, "alphanum_fraction": 0.7253360152244568, "avg_line_length": 58.91586685180664, "blob_id": "ce56f217ab6159bbf23d361aef7201d39c936a99", "content_id": "057e1449bc6b8965529f805134a51d2983f6402b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 49850, "license_type": "permissive", "max_line_length": 180, "num_lines": 832, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport static de.tum.in.www1.artemis.domain.enumeration.BuildPlanType.*;\n\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.ZonedDateTime;\nimport java.util.*;\n\nimport javax.annotation.Nullable;\n\nimport org.apache.commons.lang3.ArrayUtils;\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.core.io.Resource;\nimport org.springframework.data.domain.PageRequest;\nimport org.springframework.data.domain.Sort;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.participation.SolutionProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.domain.participation.TemplateProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.connectors.*;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService;\nimport de.tum.in.www1.artemis.service.util.structureoraclegenerator.OracleGenerator;\nimport de.tum.in.www1.artemis.web.rest.dto.PageableSearchDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.SearchResultPageDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n@Service\npublic class ProgrammingExerciseService {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseService.class);\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final FileService fileService;\n\n private final GitService gitService;\n\n private final Optional<VersionControlService> versionControlService;\n\n private final Optional<ContinuousIntegrationService> continuousIntegrationService;\n\n private final ParticipationService participationService;\n\n private final UserRepository userRepository;\n\n private final AuthorizationCheckService authCheckService;\n\n private final GroupNotificationService groupNotificationService;\n\n private final ResourceLoaderService resourceLoaderService;\n\n private final InstanceMessageSendService instanceMessageSendService;\n\n private final TemplateProgrammingExerciseParticipationRepository templateProgrammingExerciseParticipationRepository;\n\n private final SolutionProgrammingExerciseParticipationRepository solutionProgrammingExerciseParticipationRepository;\n\n private final ResultRepository resultRepository;\n\n public ProgrammingExerciseService(ProgrammingExerciseRepository programmingExerciseRepository, FileService fileService, GitService gitService,\n Optional<VersionControlService> versionControlService, Optional<ContinuousIntegrationService> continuousIntegrationService,\n TemplateProgrammingExerciseParticipationRepository templateProgrammingExerciseParticipationRepository,\n SolutionProgrammingExerciseParticipationRepository solutionProgrammingExerciseParticipationRepository, ParticipationService participationService,\n ResultRepository resultRepository, UserRepository userRepository, AuthorizationCheckService authCheckService, ResourceLoaderService resourceLoaderService,\n GroupNotificationService groupNotificationService, InstanceMessageSendService instanceMessageSendService) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.fileService = fileService;\n this.gitService = gitService;\n this.versionControlService = versionControlService;\n this.continuousIntegrationService = continuousIntegrationService;\n this.templateProgrammingExerciseParticipationRepository = templateProgrammingExerciseParticipationRepository;\n this.solutionProgrammingExerciseParticipationRepository = solutionProgrammingExerciseParticipationRepository;\n this.participationService = participationService;\n this.resultRepository = resultRepository;\n this.userRepository = userRepository;\n this.authCheckService = authCheckService;\n this.resourceLoaderService = resourceLoaderService;\n this.groupNotificationService = groupNotificationService;\n this.instanceMessageSendService = instanceMessageSendService;\n }\n\n /**\n * Setups the context of a new programming exercise. This includes:\n * <ul>\n * <li>The VCS project</li>\n * <li>All repositories (test, exercise, solution)</li>\n * <li>The template and solution participation</li>\n * <li>VCS webhooks</li>\n * <li>Bamboo build plans</li>\n * </ul>\n *\n * The exercise gets set up in the following order:\n * <ol>\n * <li>Create all repositories for the new exercise</li>\n * <li>Setup template and push it to the repositories</li>\n * <li>Setup new build plans for exercise</li>\n * <li>Add all webhooks</li>\n * <li>Init scheduled jobs for exercise maintenance</li>\n * </ol>\n *\n * @param programmingExercise The programmingExercise that should be setup\n * @return The newly setup exercise\n * @throws InterruptedException If something during the communication with the remote Git repository went wrong\n * @throws GitAPIException If something during the communication with the remote Git repository went wrong\n * @throws IOException If the template files couldn't be read\n */\n @Transactional // ok because we create many objects in a rather complex way and need a rollback in case of exceptions\n public ProgrammingExercise createProgrammingExercise(ProgrammingExercise programmingExercise) throws InterruptedException, GitAPIException, IOException {\n programmingExercise.generateAndSetProjectKey();\n final var user = userRepository.getUser();\n\n createRepositoriesForNewExercise(programmingExercise);\n initParticipations(programmingExercise);\n setURLsAndBuildPlanIDsForNewExercise(programmingExercise);\n\n // Save participations to get the ids required for the webhooks\n connectBaseParticipationsToExerciseAndSave(programmingExercise);\n\n setupExerciseTemplate(programmingExercise, user);\n\n // Save programmning exercise to prevent transiant exception\n programmingExercise = programmingExerciseRepository.save(programmingExercise);\n\n setupBuildPlansForNewExercise(programmingExercise);\n\n // save to get the id required for the webhook\n programmingExercise = programmingExerciseRepository.saveAndFlush(programmingExercise);\n\n // The creation of the webhooks must occur after the initial push, because the participation is\n // not yet saved in the database, so we cannot save the submission accordingly (see ProgrammingSubmissionService.notifyPush)\n versionControlService.get().addWebHooksForExercise(programmingExercise);\n\n scheduleOperations(programmingExercise.getId());\n\n // Notify tutors only if this a course exercise\n if (programmingExercise.isCourseExercise()) {\n groupNotificationService.notifyTutorGroupAboutExerciseCreated(programmingExercise);\n }\n\n return programmingExercise;\n }\n\n public void scheduleOperations(Long programmingExerciseId) {\n instanceMessageSendService.sendProgrammingExerciseSchedule(programmingExerciseId);\n }\n\n public void cancelScheduledOperations(Long programmingExerciseId) {\n instanceMessageSendService.sendProgrammingExerciseScheduleCancel(programmingExerciseId);\n }\n\n /**\n * Creates build plans for a new programming exercise.\n * 1. Create the project for the exercise on the CI Server\n * 2. Create template and solution build plan in this project\n * 3. Configure CI permissions\n *\n * @param programmingExercise Programming exercise for the the build plans should be generated. The programming\n * exercise should contain a fully initialized template and solution participation.\n */\n public void setupBuildPlansForNewExercise(ProgrammingExercise programmingExercise) {\n String projectKey = programmingExercise.getProjectKey();\n // Get URLs for repos\n var exerciseRepoUrl = programmingExercise.getVcsTemplateRepositoryUrl();\n var testsRepoUrl = programmingExercise.getVcsTestRepositoryUrl();\n var solutionRepoUrl = programmingExercise.getVcsSolutionRepositoryUrl();\n\n continuousIntegrationService.get().createProjectForExercise(programmingExercise);\n // template build plan\n continuousIntegrationService.get().createBuildPlanForExercise(programmingExercise, TEMPLATE.getName(), exerciseRepoUrl, testsRepoUrl, solutionRepoUrl);\n // solution build plan\n continuousIntegrationService.get().createBuildPlanForExercise(programmingExercise, SOLUTION.getName(), solutionRepoUrl, testsRepoUrl, solutionRepoUrl);\n\n // Give appropriate permissions for CI projects\n continuousIntegrationService.get().removeAllDefaultProjectPermissions(projectKey);\n\n giveCIProjectPermissions(programmingExercise);\n }\n\n /**\n * This method connects the new programming exercise with the template and solution participation\n *\n * @param programmingExercise the new programming exercise\n */\n public void connectBaseParticipationsToExerciseAndSave(ProgrammingExercise programmingExercise) {\n var templateParticipation = programmingExercise.getTemplateParticipation();\n var solutionParticipation = programmingExercise.getSolutionParticipation();\n templateParticipation.setProgrammingExercise(programmingExercise);\n solutionParticipation.setProgrammingExercise(programmingExercise);\n templateParticipation = templateProgrammingExerciseParticipationRepository.save(templateParticipation);\n solutionParticipation = solutionProgrammingExerciseParticipationRepository.save(solutionParticipation);\n programmingExercise.setTemplateParticipation(templateParticipation);\n programmingExercise.setSolutionParticipation(solutionParticipation);\n }\n\n private void setURLsAndBuildPlanIDsForNewExercise(ProgrammingExercise programmingExercise) {\n final var projectKey = programmingExercise.getProjectKey();\n final var templateParticipation = programmingExercise.getTemplateParticipation();\n final var solutionParticipation = programmingExercise.getSolutionParticipation();\n final var templatePlanId = programmingExercise.generateBuildPlanId(TEMPLATE);\n final var solutionPlanId = programmingExercise.generateBuildPlanId(SOLUTION);\n final var exerciseRepoName = programmingExercise.generateRepositoryName(RepositoryType.TEMPLATE);\n final var solutionRepoName = programmingExercise.generateRepositoryName(RepositoryType.SOLUTION);\n final var testRepoName = programmingExercise.generateRepositoryName(RepositoryType.TESTS);\n\n templateParticipation.setBuildPlanId(templatePlanId); // Set build plan id to newly created BaseBuild plan\n templateParticipation.setRepositoryUrl(versionControlService.get().getCloneRepositoryUrl(projectKey, exerciseRepoName).toString());\n solutionParticipation.setBuildPlanId(solutionPlanId);\n solutionParticipation.setRepositoryUrl(versionControlService.get().getCloneRepositoryUrl(projectKey, solutionRepoName).toString());\n programmingExercise.setTestRepositoryUrl(versionControlService.get().getCloneRepositoryUrl(projectKey, testRepoName).toString());\n }\n\n /**\n * Setup the exercise template by determining the files needed for the template and copying them.\n *\n * @param programmingExercise the programming exercise that should be set up\n * @param user the User that performed the action (used as Git commit author)\n */\n private void setupExerciseTemplate(ProgrammingExercise programmingExercise, User user) throws GitAPIException, InterruptedException {\n\n // Get URLs for repos\n var exerciseRepoUrl = programmingExercise.getVcsTemplateRepositoryUrl();\n var testsRepoUrl = programmingExercise.getVcsTestRepositoryUrl();\n var solutionRepoUrl = programmingExercise.getVcsSolutionRepositoryUrl();\n\n // Checkout repositories\n Repository exerciseRepo = gitService.getOrCheckoutRepository(exerciseRepoUrl, true);\n Repository testRepo = gitService.getOrCheckoutRepository(testsRepoUrl, true);\n Repository solutionRepo = gitService.getOrCheckoutRepository(solutionRepoUrl, true);\n\n // Get path, files and prefix for the programming-language dependent files. They are copied first.\n String programmingLanguage = programmingExercise.getProgrammingLanguage().toString().toLowerCase();\n String programmingLanguageTemplate = getProgrammingLanguageTemplatePath(programmingExercise.getProgrammingLanguage());\n String exercisePath = programmingLanguageTemplate + \"/exercise/**/*.*\";\n String solutionPath = programmingLanguageTemplate + \"/solution/**/*.*\";\n String testPath = programmingLanguageTemplate + \"/test/**/*.*\";\n\n Resource[] exerciseResources = resourceLoaderService.getResources(exercisePath);\n Resource[] testResources = resourceLoaderService.getResources(testPath);\n Resource[] solutionResources = resourceLoaderService.getResources(solutionPath);\n\n String exercisePrefix = programmingLanguage + \"/exercise\";\n String testPrefix = programmingLanguage + \"/test\";\n String solutionPrefix = programmingLanguage + \"/solution\";\n\n // Initialize project type dependent resources with null as they might not be used\n Resource[] projectTypeExerciseResources = null;\n Resource[] projectTypeTestResources = null;\n Resource[] projectTypeSolutionResources = null;\n\n String projectTypeExercisePrefix = null;\n String projectTypeTestPrefix = null;\n String projectTypeSolutionPrefix = null;\n\n // Find the project type specific files if present\n if (programmingExercise.getProjectType() != null) {\n // Get path, files and prefix for the project-type dependent files. They are copied last and can overwrite the resources from the programming language.\n String programmingLanguageProjectTypePath = getProgrammingLanguageProjectTypePath(programmingExercise.getProgrammingLanguage(), programmingExercise.getProjectType());\n String projectType = programmingExercise.getProjectType().name().toLowerCase();\n\n projectTypeExercisePrefix = programmingLanguage + \"/\" + projectType + \"/exercise\";\n projectTypeTestPrefix = programmingLanguage + \"/\" + projectType + \"/test\";\n projectTypeSolutionPrefix = programmingLanguage + \"/\" + projectType + \"/solution\";\n\n exercisePath = programmingLanguageProjectTypePath + \"/exercise/**/*.*\";\n solutionPath = programmingLanguageProjectTypePath + \"/solution/**/*.*\";\n testPath = programmingLanguageProjectTypePath + \"/test/**/*.*\";\n\n projectTypeExerciseResources = resourceLoaderService.getResources(exercisePath);\n projectTypeTestResources = resourceLoaderService.getResources(testPath);\n projectTypeSolutionResources = resourceLoaderService.getResources(solutionPath);\n }\n\n try {\n setupTemplateAndPush(exerciseRepo, exerciseResources, exercisePrefix, projectTypeExerciseResources, projectTypeExercisePrefix, \"Exercise\", programmingExercise, user);\n // The template repo can be re-written so we can unprotect the master branch.\n versionControlService.get().unprotectBranch(programmingExercise.getVcsTemplateRepositoryUrl(), \"master\");\n\n setupTemplateAndPush(solutionRepo, solutionResources, solutionPrefix, projectTypeSolutionResources, projectTypeSolutionPrefix, \"Solution\", programmingExercise, user);\n setupTestTemplateAndPush(testRepo, testResources, testPrefix, projectTypeTestResources, projectTypeTestPrefix, \"Test\", programmingExercise, user);\n\n }\n catch (Exception ex) {\n // if any exception occurs, try to at least push an empty commit, so that the\n // repositories can be used by the build plans\n log.warn(\"An exception occurred while setting up the repositories\", ex);\n gitService.commitAndPush(exerciseRepo, \"Empty Setup by Artemis\", user);\n gitService.commitAndPush(testRepo, \"Empty Setup by Artemis\", user);\n gitService.commitAndPush(solutionRepo, \"Empty Setup by Artemis\", user);\n }\n }\n\n public String getProgrammingLanguageProjectTypePath(ProgrammingLanguage programmingLanguage, ProjectType projectType) {\n return getProgrammingLanguageTemplatePath(programmingLanguage) + \"/\" + projectType.name().toLowerCase();\n }\n\n public String getProgrammingLanguageTemplatePath(ProgrammingLanguage programmingLanguage) {\n return \"templates/\" + programmingLanguage.name().toLowerCase();\n }\n\n private void createRepositoriesForNewExercise(ProgrammingExercise programmingExercise) {\n final var projectKey = programmingExercise.getProjectKey();\n versionControlService.get().createProjectForExercise(programmingExercise); // Create project\n versionControlService.get().createRepository(projectKey, programmingExercise.generateRepositoryName(RepositoryType.TEMPLATE), null); // Create template repository\n versionControlService.get().createRepository(projectKey, programmingExercise.generateRepositoryName(RepositoryType.TESTS), null); // Create tests repository\n versionControlService.get().createRepository(projectKey, programmingExercise.generateRepositoryName(RepositoryType.SOLUTION), null); // Create solution repository\n }\n\n /**\n * @param programmingExercise the changed programming exercise with its new values\n * @param notificationText optional text about the changes for a notification\n * @return the updates programming exercise from the database\n */\n public ProgrammingExercise updateProgrammingExercise(ProgrammingExercise programmingExercise, @Nullable String notificationText) {\n ProgrammingExercise savedProgrammingExercise = programmingExerciseRepository.save(programmingExercise);\n\n // TODO: in case of an exam exercise, this is not necessary\n scheduleOperations(programmingExercise.getId());\n\n // Only send notification for course exercises\n if (notificationText != null && programmingExercise.isCourseExercise()) {\n groupNotificationService.notifyStudentGroupAboutExerciseUpdate(savedProgrammingExercise, notificationText);\n }\n\n return savedProgrammingExercise;\n }\n\n /**\n * This methods sets the values (initialization date and initialization state) of the template and solution participation.\n * If either participation is null, a new one will be created.\n *\n * @param programmingExercise The programming exercise\n */\n public void initParticipations(ProgrammingExercise programmingExercise) {\n var solutionParticipation = programmingExercise.getSolutionParticipation();\n var templateParticipation = programmingExercise.getTemplateParticipation();\n\n if (templateParticipation == null) {\n templateParticipation = new TemplateProgrammingExerciseParticipation();\n programmingExercise.setTemplateParticipation(templateParticipation);\n }\n if (solutionParticipation == null) {\n solutionParticipation = new SolutionProgrammingExerciseParticipation();\n programmingExercise.setSolutionParticipation(solutionParticipation);\n }\n\n solutionParticipation.setInitializationState(InitializationState.INITIALIZED);\n templateParticipation.setInitializationState(InitializationState.INITIALIZED);\n solutionParticipation.setInitializationDate(ZonedDateTime.now());\n templateParticipation.setInitializationDate(ZonedDateTime.now());\n }\n\n // Copy template and push, if no file is in the directory\n\n /**\n * Copy template and push, if no file is currently in the repository.\n *\n * @param repository The repository to push to\n * @param resources An array of resources that should be copied. Might be overwritten by projectTypeResources.\n * @param prefix A prefix that should be replaced for all Resources inside the resources.\n * @param projectTypeResources An array of resources that should be copied AFTER the resources array has been copied. Can be null.\n * @param projectTypePrefix A prefix that should be replaced for all Resources inside the projectTypeResources.\n * @param templateName The name of the template\n * @param programmingExercise the programming exercise\n * @param user The user that triggered the action (used as Git commit author)\n * @throws Exception An exception in case something went wrong\n */\n private void setupTemplateAndPush(Repository repository, Resource[] resources, String prefix, @Nullable Resource[] projectTypeResources, String projectTypePrefix,\n String templateName, ProgrammingExercise programmingExercise, User user) throws Exception {\n if (gitService.listFiles(repository).size() == 0) { // Only copy template if repo is empty\n fileService.copyResources(resources, prefix, repository.getLocalPath().toAbsolutePath().toString(), true);\n // Also copy project type specific files AFTERWARDS (so that they might overwrite the default files)\n if (projectTypeResources != null) {\n fileService.copyResources(projectTypeResources, projectTypePrefix, repository.getLocalPath().toAbsolutePath().toString(), true);\n }\n\n replacePlaceholders(programmingExercise, repository);\n commitAndPushRepository(repository, templateName + \"-Template pushed by Artemis\", user);\n }\n }\n\n /**\n * Set up the test repository. This method differentiates non sequential and sequential test repositories (more than 1 test job).\n *\n * @param repository The repository to be set up\n * @param resources The resources which should get added to the template\n * @param prefix The prefix for the path to which the resources should get copied to\n * @param templateName The name of the template\n * @param programmingExercise The related programming exercise for which the template should get created\n * @param user the user who has initiated the generation of the programming exercise\n * @throws Exception If anything goes wrong\n */\n private void setupTestTemplateAndPush(Repository repository, Resource[] resources, String prefix, Resource[] projectTypeResources, String projectTypePrefix,\n String templateName, ProgrammingExercise programmingExercise, User user) throws Exception {\n // Only copy template if repo is empty\n if (gitService.listFiles(repository).size() == 0\n && (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.JAVA || programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.KOTLIN)) {\n // First get files that are not dependent on the project type\n String templatePath = getProgrammingLanguageTemplatePath(programmingExercise.getProgrammingLanguage()) + \"/test\";\n\n String projectTemplatePath = templatePath + \"/projectTemplate/**/*.*\";\n Resource[] projectTemplate = resourceLoaderService.getResources(projectTemplatePath);\n fileService.copyResources(projectTemplate, prefix, repository.getLocalPath().toAbsolutePath().toString(), false);\n\n // These resources might override the programming language dependent resources as they are project type dependent.\n ProjectType projectType = programmingExercise.getProjectType();\n if (projectType != null) {\n String projectTypeTemplatePath = getProgrammingLanguageProjectTypePath(programmingExercise.getProgrammingLanguage(), projectType) + \"/test\";\n\n String projectTypeProjectTemplatePath = projectTypeTemplatePath + \"/projectTemplate/**/*.*\";\n\n try {\n Resource[] projectTypeProjectTemplate = resourceLoaderService.getResources(projectTypeProjectTemplatePath);\n fileService.copyResources(projectTypeProjectTemplate, projectTypePrefix, repository.getLocalPath().toAbsolutePath().toString(), false);\n }\n catch (FileNotFoundException ignored) {\n }\n }\n\n Map<String, Boolean> sectionsMap = new HashMap<>();\n\n // Keep or delete static code analysis configuration in pom.xml\n sectionsMap.put(\"static-code-analysis\", Boolean.TRUE.equals(programmingExercise.isStaticCodeAnalysisEnabled()));\n\n if (!programmingExercise.hasSequentialTestRuns()) {\n String testFilePath = templatePath + \"/testFiles/**/*.*\";\n Resource[] testFileResources = resourceLoaderService.getResources(testFilePath);\n String packagePath = Paths.get(repository.getLocalPath().toAbsolutePath().toString(), \"test\", \"${packageNameFolder}\").toAbsolutePath().toString();\n\n sectionsMap.put(\"non-sequential\", true);\n sectionsMap.put(\"sequential\", false);\n\n fileService.replacePlaceholderSections(Paths.get(repository.getLocalPath().toAbsolutePath().toString(), \"pom.xml\").toAbsolutePath().toString(), sectionsMap);\n\n fileService.copyResources(testFileResources, prefix, packagePath, false);\n\n // Possibly overwrite files if the project type is defined\n if (projectType != null) {\n String projectTypeTemplatePath = getProgrammingLanguageProjectTypePath(programmingExercise.getProgrammingLanguage(), projectType) + \"/test\";\n\n try {\n Resource[] projectTypeTestFileResources = resourceLoaderService.getResources(projectTypeTemplatePath);\n // filter non existing resources to avoid exceptions\n List<Resource> existingProjectTypeTestFileResources = new ArrayList<>();\n for (Resource resource : projectTypeTestFileResources) {\n if (resource.exists()) {\n existingProjectTypeTestFileResources.add(resource);\n }\n }\n if (!existingProjectTypeTestFileResources.isEmpty()) {\n fileService.copyResources(existingProjectTypeTestFileResources.toArray(new Resource[] {}), projectTypePrefix, packagePath, false);\n }\n }\n catch (FileNotFoundException ignored) {\n }\n }\n\n // Copy static code analysis config files\n // TODO: rene: SWIFT - if we keep the parent folder, we need to enable showing the hidden .swiftlint.yml file otherwise the OE shows an empty folder\n if (Boolean.TRUE.equals(programmingExercise.isStaticCodeAnalysisEnabled())) {\n String staticCodeAnalysisConfigPath = templatePath + \"/staticCodeAnalysisConfig/**/*.*\";\n Resource[] staticCodeAnalysisResources = resourceLoaderService.getResources(staticCodeAnalysisConfigPath);\n fileService.copyResources(staticCodeAnalysisResources, prefix, repository.getLocalPath().toAbsolutePath().toString(), true);\n }\n }\n else {\n String stagePomXmlPath = templatePath + \"/stagePom.xml\";\n if (new java.io.File(projectTemplatePath + \"/stagePom.xml\").exists()) {\n stagePomXmlPath = projectTemplatePath + \"/stagePom.xml\";\n }\n Resource stagePomXml = resourceLoaderService.getResource(stagePomXmlPath);\n\n // This is done to prepare for a feature where instructors/tas can add multiple build stages.\n List<String> sequentialTestTasks = new ArrayList<>();\n sequentialTestTasks.add(\"structural\");\n sequentialTestTasks.add(\"behavior\");\n\n sectionsMap.put(\"non-sequential\", false);\n sectionsMap.put(\"sequential\", true);\n\n fileService.replacePlaceholderSections(Paths.get(repository.getLocalPath().toAbsolutePath().toString(), \"pom.xml\").toAbsolutePath().toString(), sectionsMap);\n\n for (String buildStage : sequentialTestTasks) {\n\n Path buildStagePath = Paths.get(repository.getLocalPath().toAbsolutePath().toString(), buildStage);\n Files.createDirectory(buildStagePath);\n\n String buildStageResourcesPath = templatePath + \"/testFiles/\" + buildStage + \"/**/*.*\";\n Resource[] buildStageResources = resourceLoaderService.getResources(buildStageResourcesPath);\n\n Files.createDirectory(Paths.get(buildStagePath.toAbsolutePath().toString(), \"test\"));\n Files.createDirectory(Paths.get(buildStagePath.toAbsolutePath().toString(), \"test\", \"${packageNameFolder}\"));\n\n String packagePath = Paths.get(buildStagePath.toAbsolutePath().toString(), \"test\", \"${packageNameFolder}\").toAbsolutePath().toString();\n\n Files.copy(stagePomXml.getInputStream(), Paths.get(buildStagePath.toAbsolutePath().toString(), \"pom.xml\"));\n fileService.copyResources(buildStageResources, prefix, packagePath, false);\n\n // Possibly overwrite files if the project type is defined\n if (projectType != null) {\n buildStageResourcesPath = projectTemplatePath + \"/testFiles/\" + buildStage + \"/**/*.*\";\n try {\n buildStageResources = resourceLoaderService.getResources(buildStageResourcesPath);\n fileService.copyResources(buildStageResources, prefix, packagePath, false);\n }\n catch (FileNotFoundException ignored) {\n }\n }\n }\n }\n\n replacePlaceholders(programmingExercise, repository);\n commitAndPushRepository(repository, templateName + \"-Template pushed by Artemis\", user);\n }\n else {\n // If there is no special test structure for a programming language, just copy all the test files.\n setupTemplateAndPush(repository, resources, prefix, projectTypeResources, projectTypePrefix, templateName, programmingExercise, user);\n }\n }\n\n /**\n * Replace placeholders in repository files (e.g. ${placeholder}).\n *\n * @param programmingExercise The related programming exercise\n * @param repository The repository in which the placeholders should get replaced\n * @throws IOException If replacing the directory name, or file variables throws an exception\n */\n public void replacePlaceholders(ProgrammingExercise programmingExercise, Repository repository) throws IOException {\n if (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.JAVA || programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.KOTLIN) {\n fileService.replaceVariablesInDirectoryName(repository.getLocalPath().toAbsolutePath().toString(), \"${packageNameFolder}\", programmingExercise.getPackageFolderName());\n }\n else if (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.SWIFT) {\n fileService.replaceVariablesInDirectoryName(repository.getLocalPath().toAbsolutePath().toString(), \"${packageNameFolder}\", programmingExercise.getPackageName());\n }\n\n Map<String, String> replacements = new HashMap<>();\n\n if (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.JAVA || programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.KOTLIN\n || programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.SWIFT) {\n replacements.put(\"${packageName}\", programmingExercise.getPackageName());\n }\n // there is no need in python to replace package names\n\n replacements.put(\"${exerciseNamePomXml}\", programmingExercise.getTitle().replaceAll(\" \", \"-\")); // Used e.g. in artifactId\n replacements.put(\"${exerciseName}\", programmingExercise.getTitle());\n replacements.put(\"${studentWorkingDirectory}\", Constants.STUDENT_WORKING_DIRECTORY);\n replacements.put(\"${packaging}\", programmingExercise.hasSequentialTestRuns() ? \"pom\" : \"jar\");\n fileService.replaceVariablesInFileRecursive(repository.getLocalPath().toAbsolutePath().toString(), replacements);\n }\n\n /**\n * Stage, commit and push.\n *\n * @param repository The repository to which the changes should get pushed\n * @param message The commit message\n * @param user the user who has initiated the generation of the programming exercise\n * @throws GitAPIException If committing, or pushing to the repo throws an exception\n */\n public void commitAndPushRepository(Repository repository, String message, User user) throws GitAPIException {\n gitService.stageAllChanges(repository);\n gitService.commitAndPush(repository, message, user);\n repository.setFiles(null); // Clear cache to avoid multiple commits when Artemis server is not restarted between attempts\n }\n\n /**\n * Updates the timeline attributes of the given programming exercise\n * @param updatedProgrammingExercise containing the changes that have to be saved\n * @param notificationText optional text for a notification to all students about the update\n * @return the updated ProgrammingExercise object.\n */\n public ProgrammingExercise updateTimeline(ProgrammingExercise updatedProgrammingExercise, @Nullable String notificationText) {\n\n var programmingExercise = programmingExerciseRepository.findByIdElseThrow(updatedProgrammingExercise.getId());\n programmingExercise.setReleaseDate(updatedProgrammingExercise.getReleaseDate());\n programmingExercise.setDueDate(updatedProgrammingExercise.getDueDate());\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(updatedProgrammingExercise.getBuildAndTestStudentSubmissionsAfterDueDate());\n programmingExercise.setAssessmentType(updatedProgrammingExercise.getAssessmentType());\n programmingExercise.setAssessmentDueDate(updatedProgrammingExercise.getAssessmentDueDate());\n ProgrammingExercise savedProgrammingExercise = programmingExerciseRepository.save(programmingExercise);\n if (notificationText != null) {\n groupNotificationService.notifyStudentGroupAboutExerciseUpdate(updatedProgrammingExercise, notificationText);\n }\n return savedProgrammingExercise;\n }\n\n /**\n * Updates the problem statement of the given programming exercise.\n *\n * @param programmingExerciseId ProgrammingExercise Id.\n * @param problemStatement markdown of the problem statement.\n * @param notificationText optional text for a notification to all students about the update\n * @return the updated ProgrammingExercise object.\n * @throws EntityNotFoundException if there is no ProgrammingExercise for the given id.\n */\n public ProgrammingExercise updateProblemStatement(Long programmingExerciseId, String problemStatement, @Nullable String notificationText) throws EntityNotFoundException {\n var programmingExercise = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId)\n .orElseThrow(() -> new EntityNotFoundException(\"Programming Exercise\", programmingExerciseId));\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n programmingExercise.setProblemStatement(problemStatement);\n ProgrammingExercise updatedProgrammingExercise = programmingExerciseRepository.save(programmingExercise);\n if (notificationText != null) {\n groupNotificationService.notifyStudentGroupAboutExerciseUpdate(updatedProgrammingExercise, notificationText);\n }\n return updatedProgrammingExercise;\n }\n\n /**\n * This method calls the StructureOracleGenerator, generates the string out of the JSON representation of the structure oracle of the programming exercise and returns true if\n * the file was updated or generated, false otherwise. This can happen if the contents of the file have not changed.\n *\n * @param solutionRepoURL The URL of the solution repository.\n * @param exerciseRepoURL The URL of the exercise repository.\n * @param testRepoURL The URL of the tests repository.\n * @param testsPath The path to the tests folder, e.g. the path inside the repository where the structure oracle file will be saved in.\n * @param user The user who has initiated the action\n * @return True, if the structure oracle was successfully generated or updated, false if no changes to the file were made.\n * @throws IOException If the URLs cannot be converted to actual {@link Path paths}\n * @throws InterruptedException If the checkout fails\n * @throws GitAPIException If the checkout fails\n */\n public boolean generateStructureOracleFile(VcsRepositoryUrl solutionRepoURL, VcsRepositoryUrl exerciseRepoURL, VcsRepositoryUrl testRepoURL, String testsPath, User user)\n throws IOException, GitAPIException, InterruptedException {\n Repository solutionRepository = gitService.getOrCheckoutRepository(solutionRepoURL, true);\n Repository exerciseRepository = gitService.getOrCheckoutRepository(exerciseRepoURL, true);\n Repository testRepository = gitService.getOrCheckoutRepository(testRepoURL, true);\n\n gitService.resetToOriginMaster(solutionRepository);\n gitService.pullIgnoreConflicts(solutionRepository);\n gitService.resetToOriginMaster(exerciseRepository);\n gitService.pullIgnoreConflicts(exerciseRepository);\n gitService.resetToOriginMaster(testRepository);\n gitService.pullIgnoreConflicts(testRepository);\n\n Path solutionRepositoryPath = solutionRepository.getLocalPath().toRealPath();\n Path exerciseRepositoryPath = exerciseRepository.getLocalPath().toRealPath();\n Path structureOraclePath = Paths.get(testRepository.getLocalPath().toRealPath().toString(), testsPath, \"test.json\");\n\n String structureOracleJSON = OracleGenerator.generateStructureOracleJSON(solutionRepositoryPath, exerciseRepositoryPath);\n return saveAndPushStructuralOracle(user, testRepository, structureOraclePath, structureOracleJSON);\n }\n\n private boolean saveAndPushStructuralOracle(User user, Repository testRepository, Path structureOraclePath, String structureOracleJSON) throws IOException {\n // If the oracle file does not already exist, then save the generated string to the file.\n // If it does, check if the contents of the existing file are the same as the generated one.\n // If they are, do not push anything and inform the user about it.\n // If not, then update the oracle file by rewriting it and push the changes.\n if (!Files.exists(structureOraclePath)) {\n try {\n Files.write(structureOraclePath, structureOracleJSON.getBytes());\n gitService.stageAllChanges(testRepository);\n gitService.commitAndPush(testRepository, \"Generate the structure oracle file.\", user);\n return true;\n }\n catch (GitAPIException e) {\n log.error(\"An exception occurred while pushing the structure oracle file to the test repository.\", e);\n return false;\n }\n }\n else {\n Byte[] existingContents = ArrayUtils.toObject(Files.readAllBytes(structureOraclePath));\n Byte[] newContents = ArrayUtils.toObject(structureOracleJSON.getBytes());\n\n if (Arrays.deepEquals(existingContents, newContents)) {\n log.info(\"No changes to the oracle detected.\");\n return false;\n }\n else {\n try {\n Files.write(structureOraclePath, structureOracleJSON.getBytes());\n gitService.stageAllChanges(testRepository);\n gitService.commitAndPush(testRepository, \"Update the structure oracle file.\", user);\n return true;\n }\n catch (GitAPIException e) {\n log.error(\"An exception occurred while pushing the structure oracle file to the test repository.\", e);\n return false;\n }\n }\n }\n }\n\n /**\n * Delete a programming exercise, including its template and solution participations.\n *\n * @param programmingExerciseId id of the programming exercise to delete.\n * @param deleteBaseReposBuildPlans if true will also delete build plans and projects.\n */\n @Transactional // ok\n public void delete(Long programmingExerciseId, boolean deleteBaseReposBuildPlans) {\n // TODO: This method does not accept a programming exercise to solve issues with nested Transactions.\n // It would be good to refactor the delete calls and move the validity checks down from the resources to the service methods (e.g. EntityNotFound).\n var programmingExercise = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId)\n .orElseThrow(() -> new EntityNotFoundException(\"Programming Exercise\", programmingExerciseId));\n final var templateRepositoryUrlAsUrl = programmingExercise.getVcsTemplateRepositoryUrl();\n final var solutionRepositoryUrlAsUrl = programmingExercise.getVcsSolutionRepositoryUrl();\n final var testRepositoryUrlAsUrl = programmingExercise.getVcsTestRepositoryUrl();\n\n // This cancels scheduled tasks (like locking/unlocking repositories)\n // As the programming exercise might already be deleted once the scheduling node receives the message, only the\n // id is used to cancel the scheduling. No interaction with the database is required.\n cancelScheduledOperations(programmingExercise.getId());\n\n if (deleteBaseReposBuildPlans) {\n final var templateBuildPlanId = programmingExercise.getTemplateBuildPlanId();\n if (templateBuildPlanId != null) {\n continuousIntegrationService.get().deleteBuildPlan(programmingExercise.getProjectKey(), templateBuildPlanId);\n }\n final var solutionBuildPlanId = programmingExercise.getSolutionBuildPlanId();\n if (solutionBuildPlanId != null) {\n continuousIntegrationService.get().deleteBuildPlan(programmingExercise.getProjectKey(), solutionBuildPlanId);\n }\n continuousIntegrationService.get().deleteProject(programmingExercise.getProjectKey());\n\n if (programmingExercise.getTemplateRepositoryUrl() != null) {\n versionControlService.get().deleteRepository(templateRepositoryUrlAsUrl);\n }\n if (programmingExercise.getSolutionRepositoryUrl() != null) {\n versionControlService.get().deleteRepository(solutionRepositoryUrlAsUrl);\n }\n if (programmingExercise.getTestRepositoryUrl() != null) {\n versionControlService.get().deleteRepository(testRepositoryUrlAsUrl);\n }\n versionControlService.get().deleteProject(programmingExercise.getProjectKey());\n }\n /*\n * Always delete the local copies of the repository because they can (in theory) be restored by cloning again, but they block the creation of new programming exercises with\n * the same short name as a deleted one. The instructors might have missed selecting deleteBaseReposBuildPlans, and delete those manually later. This however leaves no\n * chance to remove the Artemis-local repositories on the server. In summary, they should and can always be deleted.\n */\n if (programmingExercise.getTemplateRepositoryUrl() != null) {\n gitService.deleteLocalRepository(templateRepositoryUrlAsUrl);\n }\n if (programmingExercise.getSolutionRepositoryUrl() != null) {\n gitService.deleteLocalRepository(solutionRepositoryUrlAsUrl);\n }\n if (programmingExercise.getTestRepositoryUrl() != null) {\n gitService.deleteLocalRepository(testRepositoryUrlAsUrl);\n }\n\n SolutionProgrammingExerciseParticipation solutionProgrammingExerciseParticipation = programmingExercise.getSolutionParticipation();\n TemplateProgrammingExerciseParticipation templateProgrammingExerciseParticipation = programmingExercise.getTemplateParticipation();\n if (solutionProgrammingExerciseParticipation != null) {\n participationService.deleteResultsAndSubmissionsOfParticipation(solutionProgrammingExerciseParticipation.getId());\n }\n if (templateProgrammingExerciseParticipation != null) {\n participationService.deleteResultsAndSubmissionsOfParticipation(templateProgrammingExerciseParticipation.getId());\n }\n // This will also delete the template & solution participation.\n programmingExerciseRepository.delete(programmingExercise);\n }\n\n public boolean hasAtLeastOneStudentResult(ProgrammingExercise programmingExercise) {\n // Is true if the exercise is released and has at least one result.\n // We can't use the resultService here due to a circular dependency issue.\n return resultRepository.existsByParticipation_ExerciseId(programmingExercise.getId());\n }\n\n public ProgrammingExercise save(ProgrammingExercise programmingExercise) {\n return programmingExerciseRepository.save(programmingExercise);\n }\n\n /**\n * Search for all programming exercises fitting a {@link PageableSearchDTO search query}. The result is paged,\n * meaning that there is only a predefined portion of the result returned to the user, so that the server doesn't\n * have to send hundreds/thousands of exercises if there are that many in Artemis.\n *\n * @param search The search query defining the search term and the size of the returned page\n * @param user The user for whom to fetch all available exercises\n * @return A wrapper object containing a list of all found exercises and the total number of pages\n */\n public SearchResultPageDTO<ProgrammingExercise> getAllOnPageWithSize(final PageableSearchDTO<String> search, final User user) {\n var sorting = Sort.by(Exercise.ExerciseSearchColumn.valueOf(search.getSortedColumn()).getMappedColumnName());\n sorting = search.getSortingOrder() == SortingOrder.ASCENDING ? sorting.ascending() : sorting.descending();\n final var sorted = PageRequest.of(search.getPage() - 1, search.getPageSize(), sorting);\n final var searchTerm = search.getSearchTerm();\n\n final var exercisePage = authCheckService.isAdmin(user)\n ? programmingExerciseRepository.findByTitleIgnoreCaseContainingAndShortNameNotNullOrCourse_TitleIgnoreCaseContainingAndShortNameNotNull(searchTerm, searchTerm,\n sorted)\n : programmingExerciseRepository.findByTitleInExerciseOrCourseAndUserHasAccessToCourse(searchTerm, searchTerm, user.getGroups(), sorted);\n\n return new SearchResultPageDTO<>(exercisePage.getContent(), exercisePage.getTotalPages());\n }\n\n /**\n * add project permissions to project of the build plans of the given exercise\n *\n * @param exercise the exercise whose build plans projects should be configured with permissions\n */\n public void giveCIProjectPermissions(ProgrammingExercise exercise) {\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n\n final var instructorGroup = course.getInstructorGroupName();\n final var teachingAssistantGroup = course.getTeachingAssistantGroupName();\n\n continuousIntegrationService.get().giveProjectPermissions(exercise.getProjectKey(), List.of(instructorGroup),\n List.of(CIPermission.CREATE, CIPermission.READ, CIPermission.ADMIN));\n if (teachingAssistantGroup != null) {\n continuousIntegrationService.get().giveProjectPermissions(exercise.getProjectKey(), List.of(teachingAssistantGroup), List.of(CIPermission.READ));\n }\n }\n\n /**\n * Unlock all repositories of the programming exercise\n *\n * @param exerciseId of the exercise\n */\n public void unlockAllRepositories(Long exerciseId) {\n instanceMessageSendService.sendUnlockAllRepositories(exerciseId);\n }\n\n /**\n * Lock all repositories of the programming exercise\n *\n * @param exerciseId of the exercise\n */\n public void lockAllRepositories(Long exerciseId) {\n instanceMessageSendService.sendLockAllRepositories(exerciseId);\n }\n}\n" }, { "alpha_fraction": 0.6751133799552917, "alphanum_fraction": 0.6751133799552917, "avg_line_length": 42.48979568481445, "blob_id": "b9c90e83b751a44a93044cbaba355aa964af849d", "content_id": "7f326e0c28cec2f1a10adf43beef89e0d45297dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6393, "license_type": "permissive", "max_line_length": 145, "num_lines": 147, "path": "/src/main/webapp/app/exercises/shared/result/repository.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpParams, HttpRequest } from '@angular/common/http';\nimport { Injectable } from '@angular/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { Observable } from 'rxjs/Observable';\nimport { FileType } from '../../programming/shared/code-editor/model/code-editor.model';\nimport { SERVER_API_URL } from 'app/app.constants';\n\n@Injectable({ providedIn: 'root' })\nexport class RepositoryService {\n private resourceUrl = SERVER_API_URL + 'api/repository';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Checks whether the participation data is clean or not.\n * @param participationId The identifier of the participation.\n */\n isClean(participationId: number): Observable<any> {\n return this.http.get<any>(`${this.resourceUrl}/${participationId}`).map((data) => ({ isClean: data.isClean }));\n }\n\n /**\n * Commits to certain participation.\n * @param participationId The identifier of the participation.\n */\n commit(participationId: number): Observable<void> {\n return this.http.post<void>(`${this.resourceUrl}/${participationId}/commit`, {});\n }\n\n /**\n * Pulls from a certain participation.\n * @param participationId The identifier of the participation.\n */\n pull(participationId: number): Observable<void> {\n return this.http.get<void>(`${this.resourceUrl}/${participationId}/pull`, {});\n }\n}\n\nexport interface IRepositoryFileService {\n query: (participationId: number) => Observable<{ [fileName: string]: FileType }>;\n get: (participationId: number, fileName: string) => Observable<any>;\n update: (participationId: number, fileName: string, fileContent: string) => Observable<any>;\n createFile: (participationId: number, fileName: string) => Observable<void>;\n createFolder: (participationId: number, folderName: string) => Observable<void>;\n rename: (participationId: number, currentFilePath: string, newFilename: string) => Observable<void>;\n delete: (participationId: number, fileName: string) => Observable<void>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class RepositoryFileService implements IRepositoryFileService {\n private resourceUrl = SERVER_API_URL + 'api/repository';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Get files of a specific participation.\n * @param participationId The identifier of the participation.\n */\n query(participationId: number): Observable<{ [fileName: string]: FileType }> {\n return this.http.get<{ [fileName: string]: FileType }>(`${this.resourceUrl}/${participationId}/files`);\n }\n\n /**\n * Get a specific file from a specific participation.\n * @param participationId The identifier of the participation.\n * @param fileName The name of the file to be obtained.\n */\n get(participationId: number, fileName: string): Observable<any> {\n return this.http\n .get(`${this.resourceUrl}/${participationId}/file`, { params: new HttpParams().set('file', fileName), responseType: 'text' })\n .map((data) => ({ fileContent: data }));\n }\n\n /**\n * Update a file in a specific participation.\n * @param participationId The identifier of the participation.\n * @param fileName The name of the file to be updated.\n * @param fileContent The content of the file.\n */\n update(participationId: number, fileName: string, fileContent: string): Observable<any> {\n return this.http.put(`${this.resourceUrl}/${participationId}/file`, fileContent, {\n params: new HttpParams().set('file', fileName),\n });\n }\n\n /**\n * Create a file in a specific participation.\n * @param participationId The identifier of the participation.\n * @param fileName The name of the file to be created.\n */\n createFile(participationId: number, fileName: string): Observable<void> {\n return this.http.post<void>(`${this.resourceUrl}/${participationId}/file`, '', { params: new HttpParams().set('file', fileName) });\n }\n\n /**\n * Create a folder in a specific participation.\n * @param participationId The identifier of the participation.\n * @param folderName The name of the folder to be created.\n\n */\n createFolder(participationId: number, folderName: string): Observable<void> {\n return this.http.post<void>(`${this.resourceUrl}/${participationId}/folder`, '', { params: new HttpParams().set('folder', folderName) });\n }\n\n /**\n * Rename a file in a specific participation.\n * @param participationId The identifier of the participation.\n * @param currentFilePath The path of the file to be renamed.\n * @param newFilename The new name of the file.\n\n */\n rename(participationId: number, currentFilePath: string, newFilename: string): Observable<void> {\n return this.http.post<void>(`${this.resourceUrl}/${participationId}/rename-file`, { currentFilePath, newFilename });\n }\n\n /**\n * Delete a file from a specific participation.\n * @param participationId The identifier of the participation.\n * @param fileName The name of the file to be deleted.\n */\n delete(participationId: number, fileName: string): Observable<void> {\n return this.http.delete<void>(`${this.resourceUrl}/${participationId}/file`, { params: new HttpParams().set('file', fileName) });\n }\n}\n\n@Injectable()\nexport class RepositoryInterceptor implements HttpInterceptor {\n constructor(private localStorage: LocalStorageService, private sessionStorage: SessionStorageService) {}\n\n /**\n * Identifies and handles a given HTTP request.\n * @param req The request object to handle.\n * @param next The next interceptor in the chain.\n * @returns An observable of the event stream.\n */\n intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n // TODO: check why the auth.interceptor.ts does not add the authorization header\n const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');\n if (!!token) {\n const authReq = req.clone({\n headers: req.headers.set('Authorization', 'Bearer ' + token),\n });\n return next.handle(authReq);\n }\n return next.handle(req);\n }\n}\n" }, { "alpha_fraction": 0.7348039150238037, "alphanum_fraction": 0.7420343160629272, "avg_line_length": 46.44186019897461, "blob_id": "9fa307ef09ee373a09810b71e195358937121fc7", "content_id": "26176b29db67da6bfa7f20b96ff7a0064010fea3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8160, "license_type": "permissive", "max_line_length": 143, "num_lines": 172, "path": "/src/test/java/de/tum/in/www1/artemis/service/ExamSubmissionServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.Language;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.ExamRepository;\nimport de.tum.in.www1.artemis.repository.StudentExamRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.service.exam.ExamSubmissionService;\nimport de.tum.in.www1.artemis.util.ModelFactory;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\npublic class ExamSubmissionServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ExamSubmissionService examSubmissionService;\n\n @Autowired\n private ExamRepository examRepository;\n\n @Autowired\n private StudentExamRepository studentExamRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n private User user;\n\n private Exam exam;\n\n private Exercise exercise;\n\n private StudentExam studentExam;\n\n @BeforeEach\n void init() {\n List<User> users = database.addUsers(1, 0, 1);\n user = users.get(0);\n exercise = database.addCourseExamExerciseGroupWithOneTextExercise();\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n exam = examRepository.findByCourseId(course.getId()).get(0);\n studentExam = database.addStudentExam(exam);\n studentExam.setWorkingTime(7200); // 2 hours\n studentExam.setUser(user);\n studentExam.addExercise(exercise);\n studentExam = studentExamRepository.save(studentExam);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckSubmissionAllowance_passIfNonExamSubmission() {\n Course tmpCourse = database.addEmptyCourse();\n Exercise nonExamExercise = ModelFactory.generateTextExercise(ZonedDateTime.now(), ZonedDateTime.now(), ZonedDateTime.now(), tmpCourse);\n Optional<ResponseEntity<Submission>> result = examSubmissionService.checkSubmissionAllowance(nonExamExercise, user);\n assertThat(result.isEmpty()).isTrue();\n boolean result2 = examSubmissionService.isAllowedToSubmitDuringExam(nonExamExercise, user);\n assertThat(result2).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckSubmissionAllowance_isSubmissionInTime() {\n // Should fail when submission is made before start date\n exam.setStartDate(ZonedDateTime.now().plusMinutes(5));\n examRepository.save(exam);\n Optional<ResponseEntity<Submission>> result = examSubmissionService.checkSubmissionAllowance(exercise, user);\n assertThat(result.isPresent()).isTrue();\n assertThat(result.get()).isEqualTo(forbidden());\n boolean result2 = examSubmissionService.isAllowedToSubmitDuringExam(exercise, user);\n assertThat(result2).isFalse();\n // Should fail when submission is made after (start date + working time)\n exam.setStartDate(ZonedDateTime.now().minusMinutes(130));\n examRepository.save(exam);\n result = examSubmissionService.checkSubmissionAllowance(exercise, user);\n assertThat(result.isPresent()).isTrue();\n assertThat(result.get()).isEqualTo(forbidden());\n result2 = examSubmissionService.isAllowedToSubmitDuringExam(exercise, user);\n assertThat(result2).isFalse();\n // Should pass if submission is made in time\n exam.setStartDate(ZonedDateTime.now().minusMinutes(90));\n examRepository.save(exam);\n result = examSubmissionService.checkSubmissionAllowance(exercise, user);\n assertThat(result.isEmpty()).isTrue();\n result2 = examSubmissionService.isAllowedToSubmitDuringExam(exercise, user);\n assertThat(result2).isTrue();\n // Should fail when submission is made after end date (if no working time is set)\n studentExam.setWorkingTime(0);\n studentExamRepository.save(studentExam);\n exam.setStartDate(ZonedDateTime.now().minusMinutes(130));\n exam.setEndDate(ZonedDateTime.now().minusMinutes(120));\n examRepository.save(exam);\n result = examSubmissionService.checkSubmissionAllowance(exercise, user);\n assertThat(result.isPresent()).isTrue();\n assertThat(result.get()).isEqualTo(forbidden());\n result2 = examSubmissionService.isAllowedToSubmitDuringExam(exercise, user);\n assertThat(result2).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckSubmissionAllowance_allowedToSubmitToExercise() {\n // Should fail if there is no student exam for user\n exam.setStartDate(ZonedDateTime.now().minusMinutes(90));\n examRepository.save(exam);\n studentExam.setUser(null);\n studentExamRepository.save(studentExam);\n assertThrows(EntityNotFoundException.class, () -> examSubmissionService.checkSubmissionAllowance(exercise, user));\n assertThrows(EntityNotFoundException.class, () -> examSubmissionService.isAllowedToSubmitDuringExam(exercise, user));\n // Should fail if the user's student exam does not have the exercise\n studentExam.setUser(user);\n studentExam.removeExercise(exercise);\n studentExamRepository.save(studentExam);\n Optional<ResponseEntity<Submission>> result = examSubmissionService.checkSubmissionAllowance(exercise, user);\n assertThat(result.isPresent()).isTrue();\n assertThat(result.get()).isEqualTo(forbidden());\n boolean result2 = examSubmissionService.isAllowedToSubmitDuringExam(exercise, user);\n assertThat(result2).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCheckSubmissionAllowance_testRun() {\n final var instructor = userRepository.findOneWithGroupsAndAuthoritiesByLogin(\"instructor1\").get();\n studentExam.setTestRun(true);\n studentExam.setUser(instructor);\n studentExamRepository.save(studentExam);\n assertThat(examSubmissionService.isAllowedToSubmitDuringExam(exercise, instructor)).isTrue();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCheckSubmissionAllowance_submittedStudentExam() {\n studentExam.setSubmitted(true);\n studentExamRepository.save(studentExam);\n assertThat(examSubmissionService.isAllowedToSubmitDuringExam(exercise, user)).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testPreventMultipleSubmissions() {\n StudentParticipation participation = database.createAndSaveParticipationForExercise(exercise, \"student1\");\n Submission existingSubmission = ModelFactory.generateTextSubmission(\"The initial submission\", Language.ENGLISH, true);\n existingSubmission = database.addSubmission(participation, existingSubmission);\n Submission receivedSubmission = ModelFactory.generateTextSubmission(\"This is a submission\", Language.ENGLISH, true);\n receivedSubmission = examSubmissionService.preventMultipleSubmissions(exercise, receivedSubmission, user);\n assertThat(receivedSubmission.getId()).isEqualTo(existingSubmission.getId());\n }\n\n}\n" }, { "alpha_fraction": 0.6821103692054749, "alphanum_fraction": 0.6821103692054749, "avg_line_length": 48.0773811340332, "blob_id": "ac40ae4b8bfc734fd61600b91f1e255b3c81f867", "content_id": "bd0ef83c6f8a280c637e331b994963ee46c2570e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16490, "license_type": "permissive", "max_line_length": 177, "num_lines": 336, "path": "/src/main/webapp/app/exercises/programming/manage/services/programming-exercise.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { map } from 'rxjs/operators';\nimport { omit as _omit } from 'lodash';\nimport { SERVER_API_URL } from 'app/app.constants';\n\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { TemplateProgrammingExerciseParticipation } from 'app/entities/participation/template-programming-exercise-participation.model';\nimport { SolutionProgrammingExerciseParticipation } from 'app/entities/participation/solution-programming-exercise-participation.model';\nimport { TextPlagiarismResult } from 'app/exercises/shared/plagiarism/types/text/TextPlagiarismResult';\nimport { PlagiarismOptions } from 'app/exercises/shared/plagiarism/types/PlagiarismOptions';\nimport { Submission } from 'app/entities/submission.model';\n\nexport type EntityResponseType = HttpResponse<ProgrammingExercise>;\nexport type EntityArrayResponseType = HttpResponse<ProgrammingExercise[]>;\n\nexport type ProgrammingExerciseTestCaseStateDTO = {\n released: boolean;\n hasStudentResult: boolean;\n testCasesChanged: boolean;\n buildAndTestStudentSubmissionsAfterDueDate?: Moment;\n};\n\nexport type ProgrammingExerciseInstructorRepositoryType = 'TEMPLATE' | 'SOLUTION' | 'TESTS';\n\n@Injectable({ providedIn: 'root' })\nexport class ProgrammingExerciseService {\n public resourceUrl = SERVER_API_URL + 'api/programming-exercises';\n\n constructor(private http: HttpClient, private exerciseService: ExerciseService) {}\n\n /**\n * Sets a new programming exercise up\n * @param programmingExercise which should be setup\n */\n automaticSetup(programmingExercise: ProgrammingExercise): Observable<EntityResponseType> {\n let copy = this.convertDataFromClient(programmingExercise);\n copy = this.exerciseService.setBonusPointsConstrainedByIncludedInOverallScore(copy);\n return this.http\n .post<ProgrammingExercise>(this.resourceUrl + '/setup', copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Generates the structure oracle\n * @param exerciseId of the programming exercise for which the structure oracle should be created\n */\n generateStructureOracle(exerciseId: number): Observable<string> {\n return this.http.put<string>(this.resourceUrl + '/' + exerciseId + '/generate-tests', { responseType: 'text' });\n }\n\n /**\n * Check plagiarism with JPlag\n *\n * @param exerciseId\n * @param options\n */\n checkPlagiarism(exerciseId: number, options?: PlagiarismOptions): Observable<TextPlagiarismResult> {\n return this.http\n .get<TextPlagiarismResult>(`${this.resourceUrl}/${exerciseId}/check-plagiarism`, {\n observe: 'response',\n params: {\n ...options?.toParams(),\n },\n })\n .pipe(map((response: HttpResponse<TextPlagiarismResult>) => response.body!));\n }\n\n /**\n * Check for plagiarism\n * @param exerciseId of the programming exercise\n * @param options\n */\n checkPlagiarismJPlagReport(exerciseId: number, options?: PlagiarismOptions): Observable<HttpResponse<Blob>> {\n return this.http.get(`${this.resourceUrl}/${exerciseId}/check-plagiarism-jplag-report`, {\n observe: 'response',\n responseType: 'blob',\n params: {\n ...options?.toParams(),\n },\n });\n }\n\n /**\n * Get the latest plagiarism result for the exercise with the given ID.\n *\n * @param exerciseId\n */\n getLatestPlagiarismResult(exerciseId: number): Observable<TextPlagiarismResult> {\n return this.http\n .get<TextPlagiarismResult>(`${this.resourceUrl}/${exerciseId}/plagiarism-result`, {\n observe: 'response',\n })\n .pipe(map((response: HttpResponse<TextPlagiarismResult>) => response.body!));\n }\n\n /**\n * Combines all commits of the template repository to one\n * @param exerciseId of the particular programming exercise\n */\n combineTemplateRepositoryCommits(exerciseId: number) {\n return this.http.put(this.resourceUrl + '/' + exerciseId + '/combine-template-commits', { responseType: 'text' });\n }\n\n /**\n * Imports a programming exercise by cloning the entity itself plus all basic build plans and repositories\n * (template, solution, test).\n *\n * @param adaptedSourceProgrammingExercise The exercise that should be imported, including adapted values for the\n * new exercise. E.g. with another title than the original exercise. Old\n * values that should get discarded (like the old ID) will be handled by the\n * server.\n * @param recreateBuildPlans Option determining whether the build plans should be recreated or copied from the imported exercise\n * @param updateTemplate Option determining whether the template files in the repositories should be updated\n */\n importExercise(adaptedSourceProgrammingExercise: ProgrammingExercise, recreateBuildPlans: boolean, updateTemplate: boolean): Observable<EntityResponseType> {\n const options = createRequestOption({ recreateBuildPlans, updateTemplate });\n const exercise = this.exerciseService.setBonusPointsConstrainedByIncludedInOverallScore(adaptedSourceProgrammingExercise);\n return this.http\n .post<ProgrammingExercise>(`${this.resourceUrl}/import/${adaptedSourceProgrammingExercise.id}`, exercise, {\n params: options,\n observe: 'response',\n })\n .pipe(map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res)));\n }\n\n /**\n * Updates an existing programming exercise\n * @param programmingExercise which should be updated\n * @param req optional request options\n */\n update(programmingExercise: ProgrammingExercise, req?: any): Observable<EntityResponseType> {\n const options = createRequestOption(req);\n let copy = this.convertDataFromClient(programmingExercise);\n copy = this.exerciseService.setBonusPointsConstrainedByIncludedInOverallScore(copy);\n return this.http\n .put<ProgrammingExercise>(this.resourceUrl, copy, { params: options, observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Updates the timeline of a programming exercise\n * @param programmingExercise to update\n * @param req optional request options\n */\n updateTimeline(programmingExercise: ProgrammingExercise, req?: any): Observable<EntityResponseType> {\n const options = createRequestOption(req);\n const copy = this.convertDataFromClient(programmingExercise);\n return this.http\n .put<ProgrammingExercise>(`${this.resourceUrl}/timeline`, copy, { params: options, observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Updates the problem statement\n * @param programmingExerciseId of the programming exercise for which to change the problem statement\n * @param problemStatement the new problem statement\n * @param req optional request options\n */\n updateProblemStatement(programmingExerciseId: number, problemStatement: string, req?: any) {\n const options = createRequestOption(req);\n return this.http\n .patch<ProgrammingExercise>(`${this.resourceUrl}/${programmingExerciseId}/problem-statement`, problemStatement, { params: options, observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Finds the programming exercise for the given exerciseId\n * @param programmingExerciseId of the programming exercise to retrieve\n */\n find(programmingExerciseId: number): Observable<EntityResponseType> {\n return this.http\n .get<ProgrammingExercise>(`${this.resourceUrl}/${programmingExerciseId}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Finds the programming exercise for the given exerciseId with the corresponding participation's with results\n * @param programmingExerciseId of the programming exercise to retrieve\n */\n findWithTemplateAndSolutionParticipationAndResults(programmingExerciseId: number): Observable<EntityResponseType> {\n return this.http\n .get<ProgrammingExercise>(`${this.resourceUrl}/${programmingExerciseId}/with-participations`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Finds the programming exercise for the given exerciseId with the template and solution participation\n * @param programmingExerciseId of the programming exercise to retrieve\n * @param withSubmissionResults get results attached to submissions\n */\n findWithTemplateAndSolutionParticipation(programmingExerciseId: number, withSubmissionResults = false): Observable<EntityResponseType> {\n let params = new HttpParams();\n params = params.set('withSubmissionResults', withSubmissionResults.toString());\n return this.http\n .get<ProgrammingExercise>(`${this.resourceUrl}/${programmingExerciseId}/with-template-and-solution-participation`, { params, observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)))\n .pipe(\n map((res: EntityResponseType) => {\n if (res.body && withSubmissionResults) {\n // We need to reconnect the submissions with the results. They got removed because of the circular dependency\n const templateSubmissions = res.body.templateParticipation?.submissions;\n this.reconnectSubmissionAndResult(templateSubmissions);\n const solutionSubmissions = res.body.solutionParticipation?.submissions;\n this.reconnectSubmissionAndResult(solutionSubmissions);\n }\n return res;\n }),\n );\n }\n\n /**\n * Reconnecting the missing submission of a submission's result\n *\n * @param submissions where the results have no reference to its submission\n */\n private reconnectSubmissionAndResult(submissions: Submission[] | undefined) {\n if (submissions) {\n submissions.forEach((submission) => {\n if (submission.results) {\n submission.results.forEach((result) => {\n result.submission = submission;\n });\n }\n });\n }\n }\n\n /**\n * Returns a entity with true in the body if there is a programming exercise with the given id, it is released (release date < now) and there is at least one student result.\n *\n * @param exerciseId ProgrammingExercise id\n */\n getProgrammingExerciseTestCaseState(exerciseId: number): Observable<HttpResponse<ProgrammingExerciseTestCaseStateDTO>> {\n return this.http.get<ProgrammingExerciseTestCaseStateDTO>(`${this.resourceUrl}/${exerciseId}/test-case-state`, { observe: 'response' });\n }\n\n /**\n * Receives all programming exercises for the particular query\n * @param req optional request options\n */\n query(req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n return this.http\n .get<ProgrammingExercise[]>(this.resourceUrl, { params: options, observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.exerciseService.convertDateArrayFromServer(res)));\n }\n\n /**\n * Deletes the programming exercise with the corresponding programming exercise Id\n * @param programmingExerciseId of the programming exercise to delete\n * @param deleteStudentReposBuildPlans indicates if the StudentReposBuildPlans should be also deleted or not\n * @param deleteBaseReposBuildPlans indicates if the BaseReposBuildPlans should be also deleted or not\n */\n delete(programmingExerciseId: number, deleteStudentReposBuildPlans: boolean, deleteBaseReposBuildPlans: boolean): Observable<HttpResponse<{}>> {\n let params = new HttpParams();\n params = params.set('deleteStudentReposBuildPlans', deleteStudentReposBuildPlans.toString());\n params = params.set('deleteBaseReposBuildPlans', deleteBaseReposBuildPlans.toString());\n return this.http.delete(`${this.resourceUrl}/${programmingExerciseId}`, { params, observe: 'response' });\n }\n\n /**\n * Converts the data from the client\n * if template & solution participation exist removes the exercise and results from them\n * @param exercise for which the data should be converted\n */\n convertDataFromClient(exercise: ProgrammingExercise) {\n const copy = {\n ...this.exerciseService.convertDateFromClient(exercise),\n buildAndTestStudentSubmissionsAfterDueDate:\n exercise.buildAndTestStudentSubmissionsAfterDueDate && moment(exercise.buildAndTestStudentSubmissionsAfterDueDate).isValid()\n ? moment(exercise.buildAndTestStudentSubmissionsAfterDueDate).toJSON()\n : undefined,\n };\n // Remove exercise from template & solution participation to avoid circular dependency issues.\n // Also remove the results, as they can have circular structures as well and don't have to be saved here.\n if (copy.templateParticipation) {\n copy.templateParticipation = _omit(copy.templateParticipation, ['exercise', 'results']) as TemplateProgrammingExerciseParticipation;\n }\n if (copy.solutionParticipation) {\n copy.solutionParticipation = _omit(copy.solutionParticipation, ['exercise', 'results']) as SolutionProgrammingExerciseParticipation;\n }\n\n return copy as ProgrammingExercise;\n }\n\n /**\n * Convert all date fields of the programming exercise to momentJs date objects.\n * Note: This conversion could produce an invalid date if the date is malformatted.\n *\n * @param entity ProgrammingExercise\n */\n convertDateFromServer(entity: EntityResponseType) {\n const res = this.exerciseService.convertDateFromServer(entity);\n if (!res.body) {\n return res;\n }\n res.body.buildAndTestStudentSubmissionsAfterDueDate = res.body.buildAndTestStudentSubmissionsAfterDueDate\n ? moment(res.body.buildAndTestStudentSubmissionsAfterDueDate)\n : undefined;\n return res;\n }\n\n /**\n * Unlock all the student repositories of the given exercise so that student can perform commits\n * @param exerciseId of the particular programming exercise\n */\n unlockAllRepositories(exerciseId: number): Observable<HttpResponse<{}>> {\n return this.http.put<any>(`${this.resourceUrl}/${exerciseId}/unlock-all-repositories`, {}, { observe: 'response' });\n }\n\n /**\n * Lock all the student repositories of the given exercise so that student can perform commits\n * @param exerciseId of the particular programming exercise\n */\n lockAllRepositories(exerciseId: number): Observable<HttpResponse<{}>> {\n return this.http.put<any>(`${this.resourceUrl}/${exerciseId}/lock-all-repositories`, {}, { observe: 'response' });\n }\n\n /**\n * Exports the solution, template or test repository for a given exercise.\n * @param exerciseId\n * @param repositoryType\n */\n exportInstructorRepository(exerciseId: number, repositoryType: ProgrammingExerciseInstructorRepositoryType): Observable<HttpResponse<Blob>> {\n return this.http.get(`${this.resourceUrl}/${exerciseId}/export-instructor-repository/${repositoryType}`, {\n observe: 'response',\n responseType: 'blob',\n });\n }\n}\n" }, { "alpha_fraction": 0.6914805769920349, "alphanum_fraction": 0.6914805769920349, "avg_line_length": 33.056339263916016, "blob_id": "def4fcf600bc3df8c6911cd82512db086586b651", "content_id": "3721eb617be41941408d9457aaddbf17e2f1563d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2418, "license_type": "permissive", "max_line_length": 168, "num_lines": 71, "path": "/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-delete-dialog.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { JhiEventManager } from 'ng-jhipster';\n\nimport { Subscription } from 'rxjs/Subscription';\nimport { ParticipationSubmissionPopupService } from 'app/exercises/shared/participation-submission/participation-submission-popup.service';\nimport { SubmissionService } from 'app/exercises/shared/submission/submission.service';\n\n@Component({\n selector: 'jhi-participation-submission-delete-dialog',\n templateUrl: './participation-submission-delete-dialog.component.html',\n})\nexport class ParticipationSubmissionDeleteDialogComponent implements OnInit {\n submissionId: number;\n\n constructor(private submissionService: SubmissionService, public activeModal: NgbActiveModal, private eventManager: JhiEventManager) {}\n\n /**\n * Close modal window.\n */\n clear() {\n this.activeModal.dismiss('cancel');\n }\n\n /**\n * Delete submission and close modal window.\n * @param { number } id - Id of submission that is deleted.\n */\n confirmDelete(id: number) {\n this.submissionService.delete(id).subscribe(() => {\n this.eventManager.broadcast({\n name: 'submissionsModification',\n content: 'Deleted a submission',\n });\n this.activeModal.dismiss(true);\n });\n }\n\n /**\n * Empty initialization.\n */\n ngOnInit(): void {}\n}\n\n@Component({\n selector: 'jhi-participation-submission-delete-popup',\n template: '',\n})\n// TODO: replace this with our new delete dialog\nexport class ParticipationSubmissionDeletePopupComponent implements OnInit, OnDestroy {\n routeSub: Subscription;\n constructor(private route: ActivatedRoute, private participationSubmissionPopupService: ParticipationSubmissionPopupService) {}\n\n /**\n * Subscribe to route.params and open new popup window with participationId and submissionId\n */\n ngOnInit() {\n this.routeSub = this.route.params.subscribe((params) => {\n this.participationSubmissionPopupService.open(ParticipationSubmissionDeleteDialogComponent as Component, params['participationId'], params['submissionId']);\n });\n }\n\n /**\n * Unsubscribe from all subscriptions.\n */\n ngOnDestroy() {\n this.routeSub.unsubscribe();\n }\n}\n" }, { "alpha_fraction": 0.6003023982048035, "alphanum_fraction": 0.6010584831237793, "avg_line_length": 39.9072151184082, "blob_id": "f3e9fb89a4555a667af95cc258468672e62ab6ab", "content_id": "1a259502990062b9ebf38ed67658f45b25322d4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3968, "license_type": "permissive", "max_line_length": 172, "num_lines": 97, "path": "/src/main/webapp/app/complaints/complaints.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { Result } from 'app/entities/result.model';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { Moment } from 'moment';\nimport { ComplaintResponseService } from 'app/complaints/complaint-response.service';\nimport { filter } from 'rxjs/operators';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { Complaint, ComplaintType } from 'app/entities/complaint.model';\nimport { Exercise } from 'app/entities/exercise.model';\n\n@Component({\n selector: 'jhi-complaint-form',\n templateUrl: './complaints.component.html',\n styleUrls: ['complaints.component.scss'],\n providers: [],\n})\nexport class ComplaintsComponent implements OnInit {\n @Input() exercise: Exercise;\n @Input() resultId: number;\n @Input() examId: number;\n @Input() allowedComplaints: number; // the number of complaints that a student can still submit in the course\n @Input() maxComplaintsPerCourse: number;\n @Input() complaintType: ComplaintType;\n @Input() isCurrentUserSubmissionAuthor = false;\n @Output() submit: EventEmitter<void> = new EventEmitter();\n complaintText?: string;\n alreadySubmitted: boolean;\n submittedDate: Moment;\n accepted?: boolean;\n handled: boolean;\n complaintResponse: ComplaintResponse;\n ComplaintType = ComplaintType;\n loaded = true;\n\n constructor(private complaintService: ComplaintService, private jhiAlertService: JhiAlertService, private complaintResponseService: ComplaintResponseService) {}\n\n ngOnInit(): void {\n this.complaintService\n .findByResultId(this.resultId)\n .pipe(filter((res) => !!res.body))\n .subscribe(\n (res) => {\n const complaint = res.body!;\n this.complaintText = complaint.complaintText;\n this.alreadySubmitted = true;\n this.submittedDate = complaint.submittedTime!;\n this.accepted = complaint.accepted;\n this.handled = this.accepted !== undefined;\n\n if (this.handled) {\n this.complaintResponseService.findByComplaintId(complaint.id!).subscribe((complaintResponse) => (this.complaintResponse = complaintResponse.body!));\n }\n },\n () => {\n this.onError();\n },\n );\n }\n\n createComplaint(): void {\n this.loaded = false;\n const complaint = new Complaint();\n complaint.complaintText = this.complaintText;\n complaint.result = new Result();\n complaint.result.id = this.resultId;\n complaint.complaintType = this.complaintType;\n\n this.complaintService.create(complaint, this.examId).subscribe(\n (res) => {\n this.submittedDate = res.body!.submittedTime!;\n this.alreadySubmitted = true;\n if (complaint.complaintType === ComplaintType.COMPLAINT) {\n // we do not track the number of complaints for exams\n if (!this.examId) {\n this.allowedComplaints--;\n }\n }\n this.loaded = true;\n this.submit.emit();\n },\n (err: HttpErrorResponse) => {\n this.loaded = true;\n if (err && err.error && err.error.errorKey === 'toomanycomplaints') {\n this.jhiAlertService.error('artemisApp.complaint.tooManyComplaints', { maxComplaintNumber: this.maxComplaintsPerCourse });\n } else {\n this.onError();\n }\n },\n );\n }\n\n private onError() {\n this.jhiAlertService.error('error.http.400');\n }\n}\n" }, { "alpha_fraction": 0.7788844704627991, "alphanum_fraction": 0.7788844704627991, "avg_line_length": 49.20000076293945, "blob_id": "d553e1805be3d8a27aac952100bdbc2215af15f9", "content_id": "51344b828cb7cd6cf128ff976007f10ad9626614", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1506, "license_type": "permissive", "max_line_length": 133, "num_lines": 30, "path": "/src/main/webapp/app/lecture/lecture.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\n\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { LectureUpdateComponent } from 'app/lecture/lecture-update.component';\nimport { LectureComponent } from 'app/lecture/lecture.component';\nimport { LectureDetailComponent } from 'app/lecture/lecture-detail.component';\nimport { LectureAttachmentsComponent } from 'app/lecture/lecture-attachments.component';\nimport { lectureRoute } from 'app/lecture/lecture.route';\nimport { ArtemisLectureUnitManagementModule } from 'app/lecture/lecture-unit/lecture-unit-management/lecture-unit-management.module';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\n\nconst ENTITY_STATES = [...lectureRoute];\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n RouterModule.forChild(ENTITY_STATES),\n ArtemisLectureUnitManagementModule,\n FormDateTimePickerModule,\n ArtemisSharedComponentModule,\n ArtemisMarkdownModule,\n ArtemisMarkdownEditorModule,\n ],\n declarations: [LectureComponent, LectureDetailComponent, LectureUpdateComponent, LectureAttachmentsComponent],\n})\nexport class ArtemisLectureModule {}\n" }, { "alpha_fraction": 0.6248390674591064, "alphanum_fraction": 0.6257832050323486, "avg_line_length": 45.234127044677734, "blob_id": "b46530013f13d7283ce76e76ca27fe5f532148d2", "content_id": "98819f50537c54451276dd2db21c2ec29a2df4fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11651, "license_type": "permissive", "max_line_length": 155, "num_lines": 252, "path": "/src/test/javascript/spec/component/course/course-group.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { User } from 'app/core/user/user.model';\nimport { UserService } from 'app/core/user/user.service';\nimport { CourseGroupComponent } from 'app/course/manage/course-group.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { CourseGroup } from 'app/entities/course.model';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { CourseExamArchiveButtonComponent } from 'app/shared/components/course-exam-archive-button/course-exam-archive-button.component';\nimport { DataTableComponent } from 'app/shared/data-table/data-table.component';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { Observable, of, throwError } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { SinonStub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockRouterLinkDirective } from '../lecture-unit/lecture-unit-management.component.spec';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Course Management Detail Component', () => {\n let comp: CourseGroupComponent;\n let fixture: ComponentFixture<CourseGroupComponent>;\n let courseService: CourseManagementService;\n let userService: UserService;\n const courseGroup = CourseGroup.STUDENTS;\n const course = { id: 123, title: 'Course Title', isAtLeastInstructor: true, endDate: moment().subtract(5, 'minutes'), courseArchivePath: 'some-path' };\n const parentRoute = ({\n data: of({ course }),\n } as any) as ActivatedRoute;\n const route = ({ parent: parentRoute, params: of({ courseGroup }) } as any) as ActivatedRoute;\n const courseGroupUser = new User(1, 'user');\n const courseGroupUser2 = new User(2, 'user2');\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, NgxDatatableModule],\n declarations: [\n CourseGroupComponent,\n MockComponent(DataTableComponent),\n MockRouterLinkDirective,\n MockPipe(ArtemisTranslatePipe),\n MockDirective(DeleteButtonDirective),\n MockComponent(AlertErrorComponent),\n MockDirective(AlertComponent),\n MockPipe(ArtemisDatePipe),\n MockDirective(JhiTranslateDirective),\n MockComponent(CourseExamArchiveButtonComponent),\n MockDirective(HasAnyAuthorityDirective),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n MockProvider(JhiAlertService),\n MockProvider(NgbModal),\n MockProvider(CourseManagementService),\n MockProvider(UserService),\n ],\n }).compileComponents();\n fixture = TestBed.createComponent(CourseGroupComponent);\n comp = fixture.componentInstance;\n courseService = fixture.debugElement.injector.get(CourseManagementService);\n userService = fixture.debugElement.injector.get(UserService);\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(CourseGroupComponent).to.be.ok;\n });\n\n describe('OnInit', () => {\n it('should load all course group users', () => {\n const getUsersStub = sinon.stub(courseService, 'getAllUsersInCourseGroup');\n getUsersStub.returns(of(new HttpResponse({ body: [courseGroupUser] })));\n fixture.detectChanges();\n comp.ngOnInit();\n expect(comp.course).to.deep.equal(course);\n expect(comp.courseGroup).to.deep.equal(courseGroup);\n expect(getUsersStub).to.have.been.called;\n });\n });\n\n describe('searchAllUsers', () => {\n let loginOrName: string;\n let loginStream: Observable<{ text: string; entities: User[] }>;\n let searchStub: SinonStub;\n\n beforeEach(() => {\n loginOrName = 'testLoginOrName';\n loginStream = of({ text: loginOrName, entities: [] });\n searchStub = sinon.stub(userService, 'search');\n });\n\n it('should search users for given login or name', () => {\n searchStub.returns(of(new HttpResponse({ body: [courseGroupUser] })));\n comp.searchAllUsers(loginStream).subscribe((users: any) => {\n expect(users).to.deep.equal([courseGroupUser]);\n });\n expect(searchStub).to.have.been.calledWith(loginOrName);\n });\n\n it('should set search no results if search returns no result', () => {\n searchStub.returns(of(new HttpResponse({ body: [] })));\n comp.searchAllUsers(loginStream).subscribe((users: any) => {\n expect(users).to.deep.equal([]);\n });\n expect(comp.searchNoResults).to.equal(true);\n expect(searchStub).to.have.been.calledWith(loginOrName);\n });\n\n it('should return empty if search text is shorter than three characters', () => {\n loginStream = of({ text: 'ab', entities: [] });\n searchStub.returns(of(new HttpResponse({ body: [courseGroupUser] })));\n comp.searchAllUsers(loginStream).subscribe((users: any) => {\n expect(users).to.deep.equal([]);\n });\n expect(searchStub).not.to.have.been.called;\n });\n\n it('should return empty if search fails', () => {\n searchStub.returns(throwError(new Error('')));\n comp.searchAllUsers(loginStream).subscribe((users: any) => {\n expect(users).to.deep.equal([]);\n });\n expect(comp.searchFailed).to.be;\n expect(searchStub).to.have.been.calledWith(loginOrName);\n });\n });\n\n describe('onAutocompleteSelect', () => {\n let addUserStub: sinon.SinonStub;\n let fake: sinon.SinonSpy;\n let user: User;\n\n beforeEach(() => {\n addUserStub = sinon.stub(courseService, 'addUserToCourseGroup');\n addUserStub.returns(of(new HttpResponse()));\n fake = sinon.fake();\n user = courseGroupUser;\n comp.allCourseGroupUsers = [];\n comp.course = course;\n comp.courseGroup = courseGroup;\n });\n it('should add the selected user to course group', () => {\n comp.onAutocompleteSelect(user, fake);\n expect(addUserStub).to.have.been.calledWith(course.id, courseGroup, user.login);\n expect(comp.allCourseGroupUsers).to.deep.equal([courseGroupUser]);\n expect(fake).to.have.been.calledWithExactly(user);\n });\n it('should call callback if user is already in the group', () => {\n comp.allCourseGroupUsers = [user];\n comp.onAutocompleteSelect(user, fake);\n expect(addUserStub).not.to.have.been.called;\n expect(comp.allCourseGroupUsers).to.deep.equal([courseGroupUser]);\n expect(fake).to.have.been.calledWithExactly(user);\n });\n });\n\n describe('removeFromGroup', () => {\n let removeUserStub: sinon.SinonStub;\n\n beforeEach(() => {\n removeUserStub = sinon.stub(courseService, 'removeUserFromCourseGroup');\n removeUserStub.returns(of(new HttpResponse()));\n comp.allCourseGroupUsers = [courseGroupUser, courseGroupUser2];\n comp.course = course;\n comp.courseGroup = courseGroup;\n });\n it('should given user from group', () => {\n comp.removeFromGroup(courseGroupUser);\n expect(removeUserStub).to.have.been.calledWith(course.id, courseGroup, courseGroupUser.login);\n expect(comp.allCourseGroupUsers).to.deep.equal([courseGroupUser2]);\n });\n it('should not do anything if users has no login', () => {\n const user = { ...courseGroupUser };\n delete user.login;\n comp.removeFromGroup(user);\n expect(removeUserStub).not.to.have.been.called;\n });\n });\n\n describe('courseGroupName', () => {\n it('should return courses studentGroupName if group is students', () => {\n comp.courseGroup = CourseGroup.STUDENTS;\n comp.course = { ...course };\n comp.course.studentGroupName = 'testStudentGroupName';\n expect(comp.courseGroupName).to.equal(comp.course.studentGroupName);\n });\n it('should return courses teachingAssistantGroupName if group is tutors', () => {\n comp.courseGroup = CourseGroup.TUTORS;\n comp.course = { ...course };\n comp.course.teachingAssistantGroupName = 'testTeachingAssistantGroupName';\n expect(comp.courseGroupName).to.equal(comp.course.teachingAssistantGroupName);\n });\n it('should return courses instructorGroupName if group is instructors', () => {\n comp.courseGroup = CourseGroup.INSTRUCTORS;\n comp.course = { ...course };\n comp.course.instructorGroupName = 'testInstructorGroupName';\n expect(comp.courseGroupName).to.equal(comp.course.instructorGroupName);\n });\n });\n\n describe('handleUsersSizeChange', () => {\n it('should change user size to given number', () => {\n const size = 5;\n comp.handleUsersSizeChange(size);\n expect(comp.filteredUsersSize).to.equal(size);\n });\n });\n\n describe('searchResultFormatter', () => {\n it('should format user info into appropriate format', () => {\n const name = 'testName';\n const user = { ...courseGroupUser, name };\n expect(comp.searchResultFormatter(user)).to.equal(`${name} (${user.login})`);\n });\n });\n\n describe('searchTextFromUser', () => {\n it('converts a user to a string that can be searched for', () => {\n const user = courseGroupUser;\n expect(comp.searchTextFromUser(user)).to.equal(user.login);\n });\n it('should return empty string if user does not have login', () => {\n const user = { ...courseGroupUser };\n delete user.login;\n expect(comp.searchTextFromUser(user)).to.equal('');\n });\n });\n});\n" }, { "alpha_fraction": 0.6830098032951355, "alphanum_fraction": 0.6845440864562988, "avg_line_length": 54.317344665527344, "blob_id": "0b14855f9bf880d4f7e81e3b82e3438eebd78c35", "content_id": "b7975bfe9d100df54f15b2adc19d6d9a5bb7c075", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14991, "license_type": "permissive", "max_line_length": 141, "num_lines": 271, "path": "/src/test/javascript/spec/component/shared/notification/notification-sidebar.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { BehaviorSubject, of } from 'rxjs';\nimport { TranslateService } from '@ngx-translate/core';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { NotificationSidebarComponent } from 'app/shared/notification/notification-sidebar/notification-sidebar.component';\nimport { NotificationService } from 'app/shared/notification/notification.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockNotificationService } from '../../../helpers/mocks/service/mock-notification.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { Notification } from 'app/entities/notification.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { User } from 'app/core/user/user.model';\nimport { MockUserService } from '../../../helpers/mocks/service/mock-user.service';\nimport { UserService } from 'app/core/user/user.service';\nimport { MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Notification Sidebar Component', () => {\n let notificationSidebarComponent: NotificationSidebarComponent;\n let notificationSidebarComponentFixture: ComponentFixture<NotificationSidebarComponent>;\n let notificationService: NotificationService;\n let accountService: AccountService;\n let userService: UserService;\n\n const notificationNow = { id: 1, notificationDate: moment() } as Notification;\n const notificationPast = { id: 2, notificationDate: moment().subtract(2, 'day') } as Notification;\n const notifications = [notificationNow, notificationPast] as Notification[];\n\n const generateQueryResponse = (ns: Notification[]) => {\n return {\n body: ns,\n headers: new HttpHeaders({\n 'X-Total-Count': ns.length.toString(),\n }),\n } as HttpResponse<Notification[]>;\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule],\n declarations: [NotificationSidebarComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: NotificationService, useClass: MockNotificationService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: UserService, useClass: MockUserService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n notificationSidebarComponentFixture = TestBed.createComponent(NotificationSidebarComponent);\n notificationSidebarComponent = notificationSidebarComponentFixture.componentInstance;\n notificationService = TestBed.inject(NotificationService);\n accountService = TestBed.inject(AccountService);\n userService = TestBed.inject(UserService);\n });\n });\n\n describe('Initialization', () => {\n it('should set last notification read', () => {\n const lastNotificationRead = moment();\n const fake = sinon.fake.returns(of({ lastNotificationRead } as User));\n sinon.replace(accountService, 'getAuthenticationState', fake);\n notificationSidebarComponent.ngOnInit();\n expect(accountService.getAuthenticationState).to.have.been.calledOnce;\n expect(notificationSidebarComponent.lastNotificationRead).to.equal(lastNotificationRead);\n });\n\n it('should query notifications', () => {\n sinon.spy(notificationService, 'query');\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.query).to.have.been.calledOnce;\n });\n\n it('should subscribe to notification updates for user', () => {\n sinon.spy(notificationService, 'subscribeToNotificationUpdates');\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.subscribeToNotificationUpdates).to.have.been.calledOnce;\n });\n });\n\n describe('Sidebar visibility', () => {\n it('should open sidebar when user clicks on notification bell', () => {\n sinon.spy(notificationSidebarComponent, 'toggleSidebar');\n const bell = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-button');\n bell.click();\n expect(notificationSidebarComponent.toggleSidebar).to.have.been.calledOnce;\n expect(notificationSidebarComponent.showSidebar).to.be.true;\n });\n\n it('should close sidebar when user clicks on notification overlay', () => {\n notificationSidebarComponent.showSidebar = true;\n sinon.spy(notificationSidebarComponent, 'toggleSidebar');\n const overlay = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-overlay');\n overlay.click();\n expect(notificationSidebarComponent.toggleSidebar).to.have.been.calledOnce;\n expect(notificationSidebarComponent.showSidebar).to.be.false;\n });\n\n it('should close sidebar when user clicks on close button', () => {\n notificationSidebarComponent.showSidebar = true;\n sinon.spy(notificationSidebarComponent, 'toggleSidebar');\n const close = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.close');\n close.click();\n expect(notificationSidebarComponent.toggleSidebar).to.have.been.calledOnce;\n expect(notificationSidebarComponent.showSidebar).to.be.false;\n });\n\n it('should close sidebar when user clicks on a notification', () => {\n notificationSidebarComponent.sortedNotifications = notifications;\n notificationSidebarComponentFixture.detectChanges();\n notificationSidebarComponent.showSidebar = true;\n const notification = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-item');\n notification.click();\n expect(notificationSidebarComponent.showSidebar).to.be.false;\n });\n });\n\n describe('Notification click', () => {\n it('should interpret notification target when user clicks notification', () => {\n sinon.spy(notificationService, 'interpretNotification');\n notificationSidebarComponent.sortedNotifications = notifications;\n notificationSidebarComponentFixture.detectChanges();\n const notification = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-item');\n notification.click();\n expect(notificationService.interpretNotification).to.be.calledOnce;\n });\n });\n\n describe('Last notification read', () => {\n it('should update users last notification read when user opens sidebar', fakeAsync(() => {\n sinon.spy(notificationSidebarComponent, 'updateLastNotificationRead');\n sinon.spy(userService, 'updateLastNotificationRead');\n const bell = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-button');\n bell.click();\n tick(2000);\n expect(notificationSidebarComponent.updateLastNotificationRead).to.have.been.calledOnce;\n expect(userService.updateLastNotificationRead).to.have.been.calledOnce;\n }));\n\n it('should update components last notification read two seconds after the user opened the sidebar', fakeAsync(() => {\n notificationSidebarComponent.lastNotificationRead = undefined;\n const bell = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.notification-button');\n const lastNotificationReadNow = moment();\n bell.click();\n tick(2000);\n expect(notificationSidebarComponent.lastNotificationRead).to.be.eql(lastNotificationReadNow);\n }));\n });\n\n describe('Load notifications', () => {\n const replaceSubscribeToNotificationUpdates = () => {\n const fake = sinon.fake.returns(new BehaviorSubject(notificationNow));\n sinon.replace(notificationService, 'subscribeToNotificationUpdates', fake);\n };\n\n it('should not add already existing notifications', () => {\n notificationSidebarComponent.notifications = [notificationNow];\n const fake = sinon.fake.returns(of(generateQueryResponse(notifications)));\n sinon.replace(notificationService, 'query', fake);\n notificationSidebarComponent.ngOnInit();\n expect(notificationSidebarComponent.notifications.length).to.be.equal(notifications.length);\n });\n\n it('should update sorted notifications array after new notifications were loaded', () => {\n const fake = sinon.fake.returns(of(generateQueryResponse([notificationPast, notificationNow])));\n sinon.replace(notificationService, 'query', fake);\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.query).to.have.been.calledOnce;\n expect(notificationSidebarComponent.sortedNotifications[0]).to.be.equal(notificationNow);\n expect(notificationSidebarComponent.sortedNotifications[1]).to.be.equal(notificationPast);\n });\n\n it('should set total notification count to received X-Total-Count header', () => {\n const fake = sinon.fake.returns(of(generateQueryResponse(notifications)));\n sinon.replace(notificationService, 'query', fake);\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.query).to.have.been.calledOnce;\n expect(notificationSidebarComponent.totalNotifications).to.be.equal(notifications.length);\n });\n\n it('should increase total notification count if a new notification is received via websocket', () => {\n replaceSubscribeToNotificationUpdates();\n notificationSidebarComponent.ngOnInit();\n expect(notificationSidebarComponent.notifications.length).to.be.equal(1);\n expect(notificationSidebarComponent.totalNotifications).to.be.equal(1);\n });\n\n it('should not add already existing notification received via websocket', () => {\n notificationSidebarComponent.notifications = [notificationNow];\n notificationSidebarComponent.totalNotifications = 1;\n replaceSubscribeToNotificationUpdates();\n notificationSidebarComponent.ngOnInit();\n expect(notificationSidebarComponent.notifications.length).to.be.equal(1);\n expect(notificationSidebarComponent.totalNotifications).to.be.equal(1);\n });\n\n it('should load more notifications only if not all are already loaded', () => {\n notificationSidebarComponent.notifications = notifications;\n notificationSidebarComponent.totalNotifications = 2;\n sinon.spy(notificationService, 'query');\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.query).not.to.be.called;\n });\n });\n\n describe('Recent notifications', () => {\n it('should evaluate recent notifications correctly', () => {\n notificationSidebarComponent.lastNotificationRead = moment().subtract(1, 'day');\n const fake = sinon.fake.returns(of(generateQueryResponse(notifications)));\n sinon.replace(notificationService, 'query', fake);\n notificationSidebarComponent.ngOnInit();\n expect(notificationService.query).to.be.called;\n expect(notificationSidebarComponent.recentNotificationCount).to.be.equal(1);\n });\n\n it('should show plus sign in recent notification count badge if all loaded notifications are recent notifications', () => {\n notificationSidebarComponent.notifications = notifications;\n notificationSidebarComponent.recentNotificationCount = 2;\n notificationSidebarComponentFixture.detectChanges();\n const plus = notificationSidebarComponentFixture.debugElement.query(By.css('.badge-danger > span'));\n expect(plus).to.be.not.null;\n });\n });\n\n describe('UI', () => {\n it('should show no notifications message', () => {\n notificationSidebarComponent.notifications = [];\n notificationSidebarComponentFixture.detectChanges();\n const noNotificationsMessage = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.no-notifications');\n expect(noNotificationsMessage).to.be.not.null;\n });\n\n it('should show loading spinner when more notifications are loaded', () => {\n notificationSidebarComponent.loading = true;\n notificationSidebarComponentFixture.detectChanges();\n const loadingSpinner = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.loading-spinner');\n expect(loadingSpinner).to.be.not.null;\n });\n\n it('should show all notifications loaded message when all notifications are loaded', () => {\n notificationSidebarComponent.notifications = notifications;\n notificationSidebarComponent.totalNotifications = 1;\n notificationSidebarComponentFixture.detectChanges();\n const allLoadedMessage = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.all-loaded');\n expect(allLoadedMessage).to.be.not.null;\n });\n\n it('should show error message when loading of notifications failed', () => {\n notificationSidebarComponent.error = 'error';\n notificationSidebarComponentFixture.detectChanges();\n const errorMessage = notificationSidebarComponentFixture.debugElement.nativeElement.querySelector('.alert-danger');\n expect(errorMessage).to.be.not.null;\n });\n });\n});\n" }, { "alpha_fraction": 0.6450839042663574, "alphanum_fraction": 0.6450839042663574, "avg_line_length": 31.076923370361328, "blob_id": "f3756a2150303475fa96c374756d5c68adf69bba", "content_id": "5507d0f0b1980c8e4a06a641085f79928f8efd9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 834, "license_type": "permissive", "max_line_length": 92, "num_lines": 26, "path": "/src/main/webapp/app/exam/participate/information/exam-information.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport * as moment from 'moment';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { Exam } from 'app/entities/exam.model';\n\n@Component({\n selector: 'jhi-exam-information',\n templateUrl: './exam-information.component.html',\n})\nexport class ExamInformationComponent {\n @Input() exam: Exam;\n @Input() studentExam: StudentExam;\n\n /**\n * Calculates the end time depending on the individual working time.\n */\n endTime() {\n if (!this.exam || !this.exam.endDate) {\n return undefined;\n }\n if (this.studentExam && this.studentExam.workingTime && this.exam.startDate) {\n return moment(this.exam.startDate).add(this.studentExam.workingTime, 'seconds');\n }\n return this.exam.endDate;\n }\n}\n" }, { "alpha_fraction": 0.7080745100975037, "alphanum_fraction": 0.7080745100975037, "avg_line_length": 34.77777862548828, "blob_id": "e2f68fac00eee9b847d0be2ed791d3d5d1199eb7", "content_id": "2daa2415d5a78e5c50ccae3be66805d685d94d4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 644, "license_type": "permissive", "max_line_length": 85, "num_lines": 18, "path": "/src/main/webapp/app/entities/quiz/drag-item.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { generate } from 'app/exercises/quiz/manage/temp-id';\nimport { CanBecomeInvalid } from 'app/entities/quiz/drop-location.model';\n\nexport class DragItem implements BaseEntity, CanBecomeInvalid {\n public id?: number;\n public tempID?: number;\n public pictureFilePath?: string;\n public text?: string;\n public question?: DragAndDropQuestion;\n public invalid?: boolean;\n\n constructor() {\n this.tempID = generate();\n this.invalid = false; // default value\n }\n}\n" }, { "alpha_fraction": 0.6381011009216309, "alphanum_fraction": 0.6479654908180237, "avg_line_length": 55.91228103637695, "blob_id": "4f6a2bdb16a7f25978e3ace2f0ecd835b1b54844", "content_id": "36622d608ce4102ea58508ec347fce7d4ed4226a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3244, "license_type": "permissive", "max_line_length": 159, "num_lines": 57, "path": "/src/test/javascript/spec/component/short-answer-quiz/short-answer-question-util.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ShortAnswerQuestionUtil } from 'app/exercises/quiz/shared/short-answer-question-util.service';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { fakeAsync, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ShortAnswerQuestionUtil', () => {\n let shortAnswerQuestionUtil: ShortAnswerQuestionUtil;\n let artemisMarkdownService: ArtemisMarkdownService;\n\n beforeEach(fakeAsync(() => {\n TestBed.configureTestingModule({ providers: [ArtemisMarkdownService] });\n artemisMarkdownService = TestBed.inject(ArtemisMarkdownService);\n shortAnswerQuestionUtil = new ShortAnswerQuestionUtil();\n }));\n\n it('Should transform text parts to html correctly', fakeAsync(() => {\n const originalTextParts1 = [['random text'], [' some more text', '[-spot 1]'], ['last paragraph']];\n const formattedTextParts1 = [['<p>random text</p>'], ['<p>&nbsp;&nbsp;&nbsp;&nbsp;some more text</p>', '<p>[-spot 1]</p>'], ['<p>last paragraph</p>']];\n expect(shortAnswerQuestionUtil.transformTextPartsIntoHTML(originalTextParts1, artemisMarkdownService)).to.eql(formattedTextParts1);\n const originalTextParts2 = [['`random code`'], ['` some more code`', '[-spot 1]'], ['`last code paragraph`']];\n const formattedTextParts2 = [\n ['<p><code>random code</code></p>'],\n ['<p><code>&nbsp;&nbsp;&nbsp;&nbsp;some more code</code></p>', '<p>[-spot 1]</p>'],\n ['<p><code>last code paragraph</code></p>'],\n ];\n expect(shortAnswerQuestionUtil.transformTextPartsIntoHTML(originalTextParts2, artemisMarkdownService)).to.eql(formattedTextParts2);\n const originalTextParts3 = [['`random code`'], [' [-spot 1]', '`some more code`', '[-spot 1]'], ['`last code paragraph`']];\n const formattedTextParts3 = [\n ['<p><code>random code</code></p>'],\n ['<p>&nbsp;&nbsp;&nbsp;&nbsp;[-spot 1]</p>', '<p><code>some more code</code></p>', '<p>[-spot 1]</p>'],\n ['<p><code>last code paragraph</code></p>'],\n ];\n expect(shortAnswerQuestionUtil.transformTextPartsIntoHTML(originalTextParts3, artemisMarkdownService)).to.eql(formattedTextParts3);\n }));\n\n it('Should return the correct indentation', fakeAsync(() => {\n const sentence1 = ' this is a test';\n const sentence2 = ' `another test`';\n const sentence3 = '`last test`';\n expect(shortAnswerQuestionUtil.getIndentation(sentence1)).to.equal(' ');\n expect(shortAnswerQuestionUtil.getIndentation(sentence2)).to.equal(' ');\n expect(shortAnswerQuestionUtil.getIndentation(sentence3)).to.equal('');\n }));\n\n it('Should return first word of a sentence', fakeAsync(() => {\n const sentence1 = ' this is a test';\n const sentence2 = ' `another test`';\n const sentence3 = '';\n expect(shortAnswerQuestionUtil.getFirstWord(sentence1)).to.equal('this');\n expect(shortAnswerQuestionUtil.getFirstWord(sentence2)).to.equal('another');\n expect(shortAnswerQuestionUtil.getFirstWord(sentence3)).to.equal('');\n }));\n});\n" }, { "alpha_fraction": 0.6271502375602722, "alphanum_fraction": 0.6329533457756042, "avg_line_length": 43.675926208496094, "blob_id": "d16c09a431fd58fb1917facab9ebb4fc3d0384c8", "content_id": "09736f6ee67ad02973c8a40bf4d07352568348a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4825, "license_type": "permissive", "max_line_length": 151, "num_lines": 108, "path": "/src/test/javascript/spec/component/exam/test-run/create-test-run-modal.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';\nimport { Exam } from 'app/entities/exam.model';\nimport { Course } from 'app/entities/course.model';\nimport { CreateTestRunModalComponent } from 'app/exam/manage/test-runs/create-test-run-modal.component';\nimport * as moment from 'moment';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ArtemisDurationFromSecondsPipe } from 'app/shared/pipes/artemis-duration-from-seconds.pipe';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { By } from '@angular/platform-browser';\nimport { StudentExam } from 'app/entities/student-exam.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Create Test Run Modal Component', () => {\n let comp: CreateTestRunModalComponent;\n let fixture: ComponentFixture<CreateTestRunModalComponent>;\n\n const course = { id: 1 } as Course;\n const exercise = { id: 1, title: 'exampleExercise', type: ExerciseType.TEXT } as Exercise;\n const exerciseGroup1 = { id: 1, exercises: [exercise], title: 'exampleExerciseGroup' } as ExerciseGroup;\n const exam = { id: 1, course, started: true, startDate: moment(), endDate: moment().add(20, 'seconds'), exerciseGroups: [exerciseGroup1] } as Exam;\n const exerciseGroup2 = { id: 2 } as ExerciseGroup;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [FormsModule, ReactiveFormsModule],\n declarations: [CreateTestRunModalComponent],\n providers: [NgbModal, NgbActiveModal, { provide: ArtemisDurationFromSecondsPipe, useClass: ArtemisDurationFromSecondsPipe }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(CreateTestRunModalComponent);\n comp = fixture.componentInstance;\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n describe('OnInit', () => {\n it('should initialise the working time form ', fakeAsync(() => {\n comp.exam = exam;\n // WHEN\n comp.ngOnInit();\n // THEN\n expect(!!comp.workingTimeForm).to.be.ok;\n }));\n });\n\n describe('creating test run workflow', () => {\n it('should create a new test run and close the modal', () => {\n const activeModal = TestBed.inject(NgbActiveModal);\n const closeStub = sinon.stub(activeModal, 'close');\n comp.exam = exam;\n fixture.detectChanges();\n comp.workingTimeForm.controls['minutes'].setValue(30);\n comp.workingTimeForm.controls['seconds'].setValue(0);\n const exerciseRow = fixture.debugElement.query(By.css('#exercise-1')).nativeElement;\n expect(exerciseRow).to.be.ok;\n exerciseRow.click();\n fixture.detectChanges();\n expect(comp.testRunConfiguration[1]).to.deep.equal(exercise);\n expect(comp.exam.exerciseGroups!.length).to.equal(1);\n expect(comp.testRunConfigured).to.equal(true);\n const createTestRunButton = fixture.debugElement.query(By.css('#createTestRunButton')).nativeElement;\n createTestRunButton.click();\n expect(closeStub).to.have.been.called;\n const testRun = closeStub.getCall(0).args[0] as StudentExam;\n expect(testRun).to.be.ok;\n expect(testRun.exam).to.equal(exam);\n expect(testRun.exercises).to.contain(exercise);\n expect(testRun.workingTime).to.equal(1800);\n });\n });\n\n describe('Ignore Exercise groups', () => {\n it('should ignore exercise groups with no exercises', function () {\n comp.exam = exam;\n comp.exam.exerciseGroups = [exerciseGroup1, exerciseGroup2];\n fixture.detectChanges();\n expect(comp.exam.exerciseGroups!.length).to.equal(1);\n });\n });\n\n describe('Exercise Selection', () => {\n it('should highlight the exercise when pressed', fakeAsync(() => {\n comp.exam = exam;\n // WHEN\n // @ts-ignore\n comp.onSelectExercise(exercise, exam.exerciseGroups[0]!);\n // THEN\n expect(Object.values(comp.testRunConfiguration).length).to.be.above(0);\n }));\n it('should allow submit when an exercise has been selected for every exercise group', fakeAsync(() => {\n comp.exam = exam;\n // WHEN\n // @ts-ignore\n comp.onSelectExercise(exercise, exam.exerciseGroups[0]!);\n // THEN\n expect(comp.testRunConfigured).to.be.ok;\n }));\n });\n});\n" }, { "alpha_fraction": 0.6162518858909607, "alphanum_fraction": 0.6194427013397217, "avg_line_length": 31.19862937927246, "blob_id": "ceb2d07fb0126f4104bacbb2747a2900a7f3a81d", "content_id": "1855fba75d12c54cf39a67f4c8cbc8d651eb8d38", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4701, "license_type": "permissive", "max_line_length": 168, "num_lines": 146, "path": "/src/main/webapp/app/shared/components/clone-repo-button/clone-repo-button.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { LocalStorageService } from 'ngx-webstorage';\n\n@Component({\n selector: 'jhi-clone-repo-button',\n templateUrl: './clone-repo-button.component.html',\n})\nexport class CloneRepoButtonComponent implements OnInit {\n @Input()\n loading = false;\n\n @Input()\n smallButtons: boolean;\n\n @Input()\n repositoryUrl: string;\n\n // Needed because the repository url is different for teams\n @Input()\n isTeamParticipation: boolean;\n\n useSsh = false;\n sshKeysUrl: string;\n sshEnabled: boolean;\n sshTemplateUrl: string;\n repositoryPassword: string;\n versionControlUrl: string;\n wasCopied = false;\n FeatureToggle = FeatureToggle;\n user: User;\n\n constructor(\n private translateService: TranslateService,\n private sourceTreeService: SourceTreeService,\n private accountService: AccountService,\n private profileService: ProfileService,\n private localStorage: LocalStorageService,\n ) {}\n\n ngOnInit() {\n this.accountService.identity().then((user) => {\n this.user = user!;\n\n // Only load password if current user login starts with 'edx_' or 'u4i_'\n if (user && user.login && (user.login.startsWith('edx_') || user.login.startsWith('u4i_'))) {\n this.getRepositoryPassword();\n }\n });\n\n // Get ssh information from the user\n this.profileService.getProfileInfo().subscribe((info: ProfileInfo) => {\n this.sshKeysUrl = info.sshKeysURL;\n this.sshTemplateUrl = info.sshCloneURLTemplate;\n this.sshEnabled = !!this.sshTemplateUrl;\n if (info.versionControlUrl) {\n this.versionControlUrl = info.versionControlUrl;\n }\n });\n\n this.useSsh = this.localStorage.retrieve('useSsh') || false;\n this.localStorage.observe('useSsh').subscribe((useSsh) => (this.useSsh = useSsh || false));\n }\n\n public toggleUseSsh(): void {\n this.useSsh = !this.useSsh;\n this.localStorage.store('useSsh', this.useSsh);\n }\n\n /**\n * get the repositoryPassword\n */\n getRepositoryPassword() {\n this.sourceTreeService.getRepositoryPassword().subscribe((res) => {\n const password = res['password'];\n if (password) {\n this.repositoryPassword = password;\n }\n });\n }\n\n getHttpOrSshRepositoryUrl() {\n if (this.useSsh) {\n return this.getSshCloneUrl(this.repositoryUrl);\n }\n\n if (this.isTeamParticipation) {\n return this.repositoryUrlForTeam(this.repositoryUrl);\n }\n\n return this.repositoryUrl;\n }\n\n /**\n * The user info part of the repository url of a team participation has to be be added with the current user's login.\n *\n * @return repository url with username of current user inserted\n */\n private repositoryUrlForTeam(url: string) {\n // (https://)(bitbucket.ase.in.tum.de/...-team1.git) => (https://)ga12abc@(bitbucket.ase.in.tum.de/...-team1.git)\n return url.replace(/^(\\w*:\\/\\/)(.*)$/, `$1${this.user.login}@$2`);\n }\n\n /**\n * Transforms the repository url to a ssh url\n */\n getSshCloneUrl(url?: string) {\n return url?.replace(/^\\w*:\\/\\/[^/]*?\\/(scm\\/)?(.*)$/, this.sshTemplateUrl + '$2');\n }\n\n /**\n * Inserts the correct link to the translated ssh tip.\n */\n getSshKeyTip() {\n return this.translateService.instant('artemisApp.exerciseActions.sshKeyTip').replace(/{link:(.*)}/, '<a href=\"' + this.sshKeysUrl + '\" target=\"_blank\">$1</a>');\n }\n\n /**\n * set wasCopied for 3 seconds on success\n */\n onCopySuccess() {\n this.wasCopied = true;\n setTimeout(() => {\n this.wasCopied = false;\n }, 3000);\n }\n\n /**\n * console log if copy fails\n */\n onCopyFailure() {}\n\n /**\n * build the sourceTreeUrl from the repository url\n * @return sourceTreeUrl\n */\n buildSourceTreeUrl() {\n return this.sourceTreeService.buildSourceTreeUrl(this.versionControlUrl, this.getHttpOrSshRepositoryUrl());\n }\n}\n" }, { "alpha_fraction": 0.6791568994522095, "alphanum_fraction": 0.6791568994522095, "avg_line_length": 52.375, "blob_id": "b187f6e4a4091dd4892958c64b526c0af5732259", "content_id": "3892bc62da34c6b3dd0c3fffd1c8ab5e1d47bb43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1281, "license_type": "permissive", "max_line_length": 122, "num_lines": 24, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-orion-connector.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { OrionState, ArtemisOrionConnector } from 'app/shared/orion/orion';\nimport { of } from 'rxjs';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { REPOSITORY } from 'app/exercises/programming/manage/code-editor/code-editor-instructor-base-container.component';\nimport { Annotation } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component';\n\nexport class MockOrionConnectorService implements ArtemisOrionConnector {\n onExerciseOpened = (exerciseId: number) => of();\n importParticipation = (repository: string, exercise: ProgrammingExercise) => of();\n submit = () => of();\n state = () => of({} as OrionState);\n onBuildFinished = () => of();\n onBuildStarted = () => of();\n onTestResult = (success: boolean, message: string) => of();\n buildAndTestLocally = () => {};\n editExercise = (exercise: ProgrammingExercise) => {};\n isBuilding = (building: boolean) => {};\n isCloning = (cloning: boolean) => {};\n log = (message: string) => {};\n login = (username: string, password: string) => {};\n onBuildFailed = (buildErrors: Array<Annotation>) => {};\n selectRepository = (repository: REPOSITORY) => {};\n startedBuildInOrion = (courseId: number, exerciseId: number) => {};\n}\n" }, { "alpha_fraction": 0.6536988019943237, "alphanum_fraction": 0.6551724076271057, "avg_line_length": 41.94936752319336, "blob_id": "79e1f01ecb620e14436854ce280afd17a66a5d38", "content_id": "a24419e44e536ad45f5d7e9f4027ff0e26e5af42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6786, "license_type": "permissive", "max_line_length": 145, "num_lines": 158, "path": "/src/main/webapp/app/overview/course-overview.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { CourseExerciseService, CourseManagementService } from '../course/manage/course-management.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { Subscription } from 'rxjs/Subscription';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { isOrion } from 'app/shared/orion/orion';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { CachingStrategy } from 'app/shared/image/secured-image.component';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { TeamAssignmentPayload } from 'app/entities/team.model';\nimport { participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport * as moment from 'moment';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\nimport { JhiAlertService } from 'ng-jhipster';\n\nconst DESCRIPTION_READ = 'isDescriptionRead';\n\n@Component({\n selector: 'jhi-course-overview',\n templateUrl: './course-overview.component.html',\n styleUrls: ['course-overview.scss'],\n})\nexport class CourseOverviewComponent implements OnInit, OnDestroy {\n readonly isOrion = isOrion;\n CachingStrategy = CachingStrategy;\n private courseId: number;\n private subscription: Subscription;\n public course?: Course;\n public refreshingCourse = false;\n public courseDescription: string;\n public enableShowMore: boolean;\n public longTextShown: boolean;\n private teamAssignmentUpdateListener: Subscription;\n private quizExercisesChannel: string;\n\n constructor(\n private courseService: CourseManagementService,\n private courseExerciseService: CourseExerciseService,\n private courseCalculationService: CourseScoreCalculationService,\n private route: ActivatedRoute,\n private teamService: TeamService,\n private jhiWebsocketService: JhiWebsocketService,\n private serverDateService: ArtemisServerDateService,\n private jhiAlertService: JhiAlertService,\n ) {}\n\n async ngOnInit() {\n this.subscription = this.route.params.subscribe((params) => {\n this.courseId = parseInt(params['courseId'], 10);\n });\n\n this.course = this.courseCalculationService.getCourse(this.courseId);\n if (!this.course) {\n this.loadCourse();\n }\n this.adjustCourseDescription();\n await this.subscribeToTeamAssignmentUpdates();\n this.subscribeForQuizChanges();\n }\n\n loadCourse(refresh = false) {\n this.refreshingCourse = refresh;\n this.courseService.findOneForDashboard(this.courseId).subscribe(\n (res: HttpResponse<Course>) => {\n this.courseCalculationService.updateCourse(res.body!);\n this.course = this.courseCalculationService.getCourse(this.courseId);\n this.adjustCourseDescription();\n setTimeout(() => (this.refreshingCourse = false), 500); // ensure min animation duration\n },\n (error: HttpErrorResponse) => {\n const errorMessage = error.headers.get('X-artemisApp-message')!;\n const jhiAlert = this.jhiAlertService.error(errorMessage);\n jhiAlert.msg = errorMessage;\n },\n );\n }\n\n ngOnDestroy() {\n if (this.teamAssignmentUpdateListener) {\n this.teamAssignmentUpdateListener.unsubscribe();\n }\n if (this.quizExercisesChannel) {\n this.jhiWebsocketService.unsubscribe(this.quizExercisesChannel);\n }\n }\n\n subscribeForQuizChanges() {\n // subscribe to quizzes which get visible\n if (!this.quizExercisesChannel) {\n this.quizExercisesChannel = '/topic/courses/' + this.courseId + '/quizExercises';\n\n // quizExercise channel => react to changes made to quizExercise (e.g. start date)\n this.jhiWebsocketService.subscribe(this.quizExercisesChannel);\n this.jhiWebsocketService.receive(this.quizExercisesChannel).subscribe(\n (quizExercise: QuizExercise) => {\n quizExercise = this.courseExerciseService.convertDateFromServer(quizExercise);\n // the quiz was set to visible or started, we should add it to the exercise list and display it at the top\n if (this.course && this.course.exercises) {\n this.course.exercises = this.course.exercises.filter((exercise) => exercise.id !== quizExercise.id);\n this.course.exercises.push(quizExercise);\n }\n },\n () => {},\n );\n }\n }\n\n adjustCourseDescription() {\n if (this.course && this.course.description) {\n this.enableShowMore = this.course.description.length > 50;\n if (localStorage.getItem(DESCRIPTION_READ + this.course.shortName) && !this.courseDescription && this.enableShowMore) {\n this.showShortDescription();\n } else {\n this.showLongDescription();\n localStorage.setItem(DESCRIPTION_READ + this.course.shortName, 'true');\n }\n }\n }\n\n showLongDescription() {\n this.courseDescription = this.course?.description || '';\n this.longTextShown = true;\n }\n\n showShortDescription() {\n this.courseDescription = this.course?.description?.substr(0, 50) + '...' || '';\n this.longTextShown = false;\n }\n\n /**\n * check if there is at least one exam which should be shown\n */\n hasVisibleExams(): boolean {\n for (const exam of this.course?.exams!) {\n if (moment(exam.visibleDate).isBefore(this.serverDateService.now())) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Receives team assignment changes and updates related attributes of the affected exercise\n */\n async subscribeToTeamAssignmentUpdates() {\n this.teamAssignmentUpdateListener = (await this.teamService.teamAssignmentUpdates).subscribe((teamAssignment: TeamAssignmentPayload) => {\n const exercise = this.course?.exercises?.find((courseExercise) => courseExercise.id === teamAssignment.exerciseId);\n if (exercise) {\n exercise.studentAssignedTeamId = teamAssignment.teamId;\n exercise.studentParticipations = teamAssignment.studentParticipations;\n exercise.participationStatus = participationStatus(exercise);\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.6918648481369019, "alphanum_fraction": 0.6928660869598389, "avg_line_length": 43.38888931274414, "blob_id": "330a858438ab5783dfeb6dabe7d362796c9da08a", "content_id": "5422dd70981423539b75f605386edfe32fa1e002", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3995, "license_type": "permissive", "max_line_length": 174, "num_lines": 90, "path": "/src/test/javascript/spec/component/learning-goals/learning-goal-popover.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { Location } from '@angular/common';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap';\nimport { LearningGoalsPopoverComponent } from 'app/course/learning-goals/learning-goals-popover/learning-goals-popover.component';\nimport { By } from '@angular/platform-browser';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { Component } from '@angular/core';\n\n@Component({\n template: '',\n})\nclass DummyStatisticsComponent {}\n\n@Component({\n template: '',\n})\nclass DummyManagementComponent {}\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('LearningGoalPopoverComponent', () => {\n let learningGoalPopoverComponentFixture: ComponentFixture<LearningGoalsPopoverComponent>;\n let learningGoalPopoverComponent: LearningGoalsPopoverComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n NgbPopoverModule,\n RouterTestingModule.withRoutes([\n { path: 'courses/:courseId/statistics', component: DummyStatisticsComponent },\n { path: 'course-management/:courseId/goal-management', component: DummyManagementComponent },\n ]),\n ],\n declarations: [LearningGoalsPopoverComponent, MockPipe(ArtemisTranslatePipe), MockComponent(FaIconComponent), DummyStatisticsComponent, DummyManagementComponent],\n providers: [],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n learningGoalPopoverComponentFixture = TestBed.createComponent(LearningGoalsPopoverComponent);\n learningGoalPopoverComponent = learningGoalPopoverComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n learningGoalPopoverComponentFixture.detectChanges();\n expect(learningGoalPopoverComponent).to.be.ok;\n });\n\n it('should navigate to course statistics', fakeAsync(() => {\n const location: Location = TestBed.inject(Location);\n learningGoalPopoverComponent.navigateTo = 'courseStatistics';\n learningGoalPopoverComponent.learningGoals = [new LearningGoal()];\n learningGoalPopoverComponent.courseId = 1;\n learningGoalPopoverComponentFixture.detectChanges();\n const popoverButton = learningGoalPopoverComponentFixture.debugElement.nativeElement.querySelector('button');\n popoverButton.click();\n tick();\n const anchor = learningGoalPopoverComponentFixture.debugElement.query(By.css('a')).nativeElement;\n anchor.click();\n tick();\n expect(location.path()).to.equal('/courses/1/statistics');\n }));\n\n it('should navigate to learning goal management', fakeAsync(() => {\n const location: Location = TestBed.inject(Location);\n learningGoalPopoverComponent.navigateTo = 'learningGoalManagement';\n learningGoalPopoverComponent.learningGoals = [new LearningGoal()];\n learningGoalPopoverComponent.courseId = 1;\n learningGoalPopoverComponentFixture.detectChanges();\n const popoverButton = learningGoalPopoverComponentFixture.debugElement.nativeElement.querySelector('button');\n popoverButton.click();\n tick();\n const anchor = learningGoalPopoverComponentFixture.debugElement.query(By.css('a')).nativeElement;\n anchor.click();\n tick();\n expect(location.path()).to.equal('/course-management/1/goal-management');\n }));\n});\n" }, { "alpha_fraction": 0.7652768492698669, "alphanum_fraction": 0.7699095606803894, "avg_line_length": 58.644737243652344, "blob_id": "fa4498ca44265ee199ada5a03c82c42a3194f5af", "content_id": "448bb3e813484dfef1c7f8221331f4bcbb048f86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13599, "license_type": "permissive", "max_line_length": 180, "num_lines": 228, "path": "/src/test/java/de/tum/in/www1/artemis/NotificationResourceIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.enumeration.GroupNotificationType;\nimport de.tum.in.www1.artemis.domain.notification.GroupNotification;\nimport de.tum.in.www1.artemis.domain.notification.Notification;\nimport de.tum.in.www1.artemis.domain.notification.SingleUserNotification;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class NotificationResourceIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private NotificationRepository notificationRepository;\n\n @Autowired\n private SystemNotificationRepository systemNotificationRepository;\n\n private Exercise exercise;\n\n private Course course1;\n\n private Course course2;\n\n private List<User> users;\n\n @BeforeEach\n public void initTestCase() {\n users = database.addUsers(2, 1, 1);\n course1 = database.addCourseWithOneReleasedTextExercise();\n course2 = database.addCourseWithOneReleasedTextExercise();\n systemNotificationRepository.deleteAll();\n exercise = new ArrayList<>(course1.getExercises()).get(0);\n\n User student1 = users.get(0);\n student1.setLastNotificationRead(ZonedDateTime.now().minusDays(1));\n users.set(0, student1);\n userRepository.save(student1);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n systemNotificationRepository.deleteAll();\n notificationRepository.deleteAll();\n }\n\n @Test\n @WithMockUser(roles = \"USER\")\n public void testCreateNotification_asUser() throws Exception {\n GroupNotificationType type = GroupNotificationType.STUDENT;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n request.post(\"/api/notifications\", groupNotification, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testCreateNotification_asInstructor() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n GroupNotification response = request.postWithResponseBody(\"/api/notifications\", groupNotification, GroupNotification.class, HttpStatus.CREATED);\n assertThat(response.getTarget()).as(\"response same target\").isEqualTo(groupNotification.getTarget());\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testCreateNotification_asInstructor_BAD_REQUEST() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n groupNotification.setId(1L);\n request.post(\"/api/notifications\", groupNotification, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetNotifications_recipientEvaluation() throws Exception {\n User recipient = userRepository.getUser();\n SingleUserNotification notification1 = ModelFactory.generateSingleUserNotification(ZonedDateTime.now(), recipient);\n notificationRepository.save(notification1);\n SingleUserNotification notification2 = ModelFactory.generateSingleUserNotification(ZonedDateTime.now(), users.get(1));\n notificationRepository.save(notification2);\n\n List<Notification> notifications = request.getList(\"/api/notifications\", HttpStatus.OK, Notification.class);\n assertThat(notifications).as(\"Notification with recipient equal to current user is returned\").contains(notification1);\n assertThat(notifications).as(\"Notification with recipient not equal to current user is not returned\").doesNotContain(notification2);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetNotifications_courseEvaluation() throws Exception {\n // student1 is member of `testgroup` and `tumuser` per default\n // the studentGroupName of course1 is `tumuser` per default\n GroupNotification notification1 = ModelFactory.generateGroupNotification(ZonedDateTime.now(), course1, GroupNotificationType.STUDENT);\n notificationRepository.save(notification1);\n course2.setStudentGroupName(\"some-group\");\n courseRepository.save(course2);\n GroupNotification notification2 = ModelFactory.generateGroupNotification(ZonedDateTime.now(), course2, GroupNotificationType.STUDENT);\n notificationRepository.save(notification2);\n\n List<Notification> notifications = request.getList(\"/api/notifications\", HttpStatus.OK, Notification.class);\n assertThat(notifications).as(\"Notification with course the current user belongs to is returned\").contains(notification1);\n assertThat(notifications).as(\"Notification with course the current user does not belong to is not returned\").doesNotContain(notification2);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetNotifications_groupNotificationTypeEvaluation_asStudent() throws Exception {\n GroupNotification notificationStudent = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.STUDENT);\n notificationRepository.save(notificationStudent);\n GroupNotification notificationTutor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.TA);\n notificationRepository.save(notificationTutor);\n GroupNotification notificationInstructor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.INSTRUCTOR);\n notificationRepository.save(notificationInstructor);\n\n List<Notification> notifications = request.getList(\"/api/notifications\", HttpStatus.OK, Notification.class);\n assertThat(notifications).as(\"Notification with type student is returned\").contains(notificationStudent);\n assertThat(notifications).as(\"Notification with type tutor is not returned\").doesNotContain(notificationTutor);\n assertThat(notifications).as(\"Notification with type instructor is not returned\").doesNotContain(notificationInstructor);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetNotifications_groupNotificationTypeEvaluation_asTutor() throws Exception {\n GroupNotification notificationStudent = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.STUDENT);\n notificationRepository.save(notificationStudent);\n GroupNotification notificationTutor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.TA);\n notificationRepository.save(notificationTutor);\n GroupNotification notificationInstructor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.INSTRUCTOR);\n notificationRepository.save(notificationInstructor);\n\n List<Notification> notifications = request.getList(\"/api/notifications\", HttpStatus.OK, Notification.class);\n assertThat(notifications).as(\"Notification with type student is not returned\").doesNotContain(notificationStudent);\n assertThat(notifications).as(\"Notification with type tutor is returned\").contains(notificationTutor);\n assertThat(notifications).as(\"Notification with type instructor is not returned\").doesNotContain(notificationInstructor);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetNotifications_groupNotificationTypeEvaluation_asInstructor() throws Exception {\n GroupNotification notificationStudent = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.STUDENT);\n notificationRepository.save(notificationStudent);\n GroupNotification notificationTutor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.TA);\n notificationRepository.save(notificationTutor);\n GroupNotification notificationInstructor = ModelFactory.generateGroupNotification(ZonedDateTime.now(), courseRepository.findAll().get(0), GroupNotificationType.INSTRUCTOR);\n notificationRepository.save(notificationInstructor);\n\n List<Notification> notifications = request.getList(\"/api/notifications\", HttpStatus.OK, Notification.class);\n assertThat(notifications).as(\"Notification with type student is not returned\").doesNotContain(notificationStudent);\n assertThat(notifications).as(\"Notification with type tutor is not returned\").doesNotContain(notificationTutor);\n assertThat(notifications).as(\"Notification with type instructor is returned\").contains(notificationInstructor);\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testUpdateNotification_asInstructor_OK() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n groupNotification.setId(1L);\n request.put(\"/api/notifications\", groupNotification, HttpStatus.OK);\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testUpdateNotification_asInstructor_BAD_REQUEST() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n request.putWithResponseBody(\"/api/notifications\", groupNotification, GroupNotification.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(roles = \"USER\")\n public void testUpdateNotification_asStudent() throws Exception {\n GroupNotificationType type = GroupNotificationType.STUDENT;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n groupNotification.setId(2L);\n request.put(\"/api/notifications\", groupNotification, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testGetNotification_asInstructor() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n Notification notification = request.postWithResponseBody(\"/api/notifications\", groupNotification, Notification.class, HttpStatus.CREATED);\n request.put(\"/api/notifications\", notification, HttpStatus.OK);\n request.get(\"/api/notifications/\" + notification.getId(), HttpStatus.OK, Notification.class);\n request.get(\"/api/notifications/\" + notification.getId() + 1, HttpStatus.NOT_FOUND, Notification.class);\n }\n\n @Test\n @WithMockUser(roles = \"INSTRUCTOR\")\n public void testDeleteNotification_asInstructor() throws Exception {\n GroupNotificationType type = GroupNotificationType.INSTRUCTOR;\n GroupNotification groupNotification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), \"Title\", \"Notification Text\", null, type);\n groupNotification.setTarget(groupNotification.getExerciseUpdatedTarget(exercise));\n Notification notification = request.postWithResponseBody(\"/api/notifications\", groupNotification, Notification.class, HttpStatus.CREATED);\n request.put(\"/api/notifications\", notification, HttpStatus.OK);\n request.delete(\"/api/notifications/\" + notification.getId(), HttpStatus.OK);\n }\n}\n" }, { "alpha_fraction": 0.7396789193153381, "alphanum_fraction": 0.7396789193153381, "avg_line_length": 46.135135650634766, "blob_id": "58f455912921591d9d92448e97b699845562889f", "content_id": "01fe9925b5692af12d3023b4d5616a7de1e99058", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1744, "license_type": "permissive", "max_line_length": 130, "num_lines": 37, "path": "/src/main/webapp/app/exam/manage/exercise-groups/programming-exercise-cell/programming-exercise-group-cell.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseSimulationUtils } from 'app/exercises/programming/shared/utils/programming-exercise-simulation-utils';\nimport { ProgrammingExerciseParticipationType } from 'app/entities/programming-exercise-participation.model';\nimport { Exercise } from 'app/entities/exercise.model';\n\n@Component({\n selector: 'jhi-programming-exercise-group-cell',\n templateUrl: './programming-exercise-group-cell.component.html',\n styles: [':host{display: contents}'],\n})\nexport class ProgrammingExerciseGroupCellComponent {\n participationType = ProgrammingExerciseParticipationType;\n\n programmingExercise: ProgrammingExercise;\n\n @Input()\n set exercise(exercise: Exercise) {\n this.programmingExercise = exercise as ProgrammingExercise;\n }\n\n constructor(private programmingExerciseSimulationUtils: ProgrammingExerciseSimulationUtils) {}\n\n // ################## ONLY FOR LOCAL TESTING PURPOSE -- START ##################\n\n /**\n * Checks if the url includes the string \"nolocalsetup', which is an indication\n * that the particular programming exercise has no local setup\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param urlToCheck the url which will be check if it contains the substring\n */\n noVersionControlAndContinuousIntegrationAvailableCheck(urlToCheck: string): boolean {\n return this.programmingExerciseSimulationUtils.noVersionControlAndContinuousIntegrationAvailableCheck(urlToCheck);\n }\n\n // ################## ONLY FOR LOCAL TESTING PURPOSE -- END ##################\n}\n" }, { "alpha_fraction": 0.6324461102485657, "alphanum_fraction": 0.6349809765815735, "avg_line_length": 39.98701477050781, "blob_id": "7f787b25cc0610080b85da27aee706a690b7f3a2", "content_id": "97f7b15410d37ee8aa50c505fa6ccd2204c73068", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6312, "license_type": "permissive", "max_line_length": 142, "num_lines": 154, "path": "/src/main/webapp/app/shared/notification/notification-sidebar/notification-sidebar.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { User } from 'app/core/user/user.model';\nimport { UserService } from 'app/core/user/user.service';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { GroupNotification } from 'app/entities/group-notification.model';\nimport { Notification } from 'app/entities/notification.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { NotificationService } from 'app/shared/notification/notification.service';\n\n@Component({\n selector: 'jhi-notification-sidebar',\n templateUrl: './notification-sidebar.component.html',\n styleUrls: ['./notification-sidebar.scss'],\n})\nexport class NotificationSidebarComponent implements OnInit {\n showSidebar = false;\n loading = false;\n notifications: Notification[] = [];\n sortedNotifications: Notification[] = [];\n recentNotificationCount = 0;\n totalNotifications = 0;\n lastNotificationRead?: Moment;\n page = 0;\n notificationsPerPage = 25;\n error?: string;\n\n constructor(private notificationService: NotificationService, private userService: UserService, private accountService: AccountService) {}\n\n /**\n * Load notifications when user is authenticated on component initialization.\n */\n ngOnInit(): void {\n this.accountService.getAuthenticationState().subscribe((user: User | undefined) => {\n if (user) {\n if (user.lastNotificationRead) {\n this.lastNotificationRead = user.lastNotificationRead;\n }\n this.loadNotifications();\n this.subscribeToNotificationUpdates();\n }\n });\n }\n\n /**\n * Show the sidebar when it is not visible and hide the sidebar when it is visible.\n */\n toggleSidebar(): void {\n this.showSidebar = !this.showSidebar;\n }\n\n /**\n * Will be executed when a notification was clicked. The notification sidebar will be closed and the actual interpretation\n * of what should happen after the notification was clicked will be handled in the notification service.\n * @param notification that will be interpreted of type {Notification}\n */\n startNotification(notification: Notification): void {\n this.showSidebar = false;\n this.notificationService.interpretNotification(notification as GroupNotification);\n }\n\n /**\n * Update the user's lastNotificationRead setting. As this method will be executed when the user opens the sidebar, the\n * component's lastNotificationRead attribute will be updated only after two seconds so that the notification `new` badges\n * won't disappear immediately.\n */\n updateLastNotificationRead(): void {\n this.userService.updateLastNotificationRead().subscribe(() => {\n const lastNotificationReadNow = moment();\n setTimeout(() => {\n this.lastNotificationRead = lastNotificationReadNow;\n this.updateRecentNotificationCount();\n }, 2000);\n });\n }\n\n /**\n * Check scroll position and load more notifications if the user scrolled to the end.\n */\n onScroll(): void {\n const container = document.getElementById('notification-sidebar-container');\n const threshold = 350;\n if (container) {\n const height = container.scrollHeight - container.offsetHeight;\n if (height > threshold && container.scrollTop > height - threshold) {\n this.loadNotifications();\n }\n }\n }\n\n private loadNotifications(): void {\n if (!this.loading && (this.totalNotifications === 0 || this.notifications.length < this.totalNotifications)) {\n this.loading = true;\n this.notificationService\n .query({\n page: this.page,\n size: this.notificationsPerPage,\n sort: ['notificationDate,desc'],\n })\n .subscribe(\n (res: HttpResponse<Notification[]>) => this.loadNotificationsSuccess(res.body!, res.headers),\n (res: HttpErrorResponse) => (this.error = res.message),\n );\n }\n }\n\n private loadNotificationsSuccess(notifications: Notification[], headers: HttpHeaders): void {\n this.totalNotifications = Number(headers.get('X-Total-Count')!);\n this.addNotifications(notifications);\n this.page += 1;\n this.loading = false;\n }\n\n private subscribeToNotificationUpdates(): void {\n this.notificationService.subscribeToNotificationUpdates().subscribe((notification: Notification) => {\n // Increase total notifications count if the notification does not already exist.\n if (!this.notifications.some(({ id }) => id === notification.id)) {\n this.totalNotifications += 1;\n }\n this.addNotifications([notification]);\n });\n }\n\n private addNotifications(notifications: Notification[]): void {\n if (notifications) {\n notifications.forEach((notification: Notification) => {\n if (!this.notifications.some(({ id }) => id === notification.id) && notification.notificationDate) {\n this.notifications.push(notification);\n }\n });\n this.updateNotifications();\n }\n }\n\n private updateNotifications(): void {\n this.sortedNotifications = this.notifications.sort((a: Notification, b: Notification) => {\n return moment(b.notificationDate!).valueOf() - moment(a.notificationDate!).valueOf();\n });\n this.updateRecentNotificationCount();\n }\n\n private updateRecentNotificationCount(): void {\n if (!this.notifications) {\n this.recentNotificationCount = 0;\n } else if (this.lastNotificationRead) {\n this.recentNotificationCount = this.notifications.filter((notification) => {\n return notification.notificationDate && notification.notificationDate.isAfter(this.lastNotificationRead!);\n }).length;\n } else {\n this.recentNotificationCount = this.notifications.length;\n }\n }\n}\n" }, { "alpha_fraction": 0.7320090532302856, "alphanum_fraction": 0.7376845479011536, "avg_line_length": 63.99423599243164, "blob_id": "38fdd9e3d1fc1445ef07aed319fe30d7c62efc63", "content_id": "4499e6cae45d8e40e045f8430a000fbb9887a27e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 22553, "license_type": "permissive", "max_line_length": 180, "num_lines": 347, "path": "/src/test/javascript/spec/service/programming-submission.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as moment from 'moment';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { BehaviorSubject, of, Subject } from 'rxjs';\nimport { range as _range } from 'lodash';\nimport * as sinonChai from 'sinon-chai';\nimport { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service';\nimport { MockHttpService } from '../helpers/mocks/service/mock-http.service';\nimport {\n ExerciseSubmissionState,\n IProgrammingSubmissionService,\n ProgrammingSubmissionService,\n ProgrammingSubmissionState,\n ProgrammingSubmissionStateObj,\n} from 'app/exercises/programming/participate/programming-submission.service';\nimport { IParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { MockAlertService } from '../helpers/mocks/service/mock-alert.service';\nimport { Result } from 'app/entities/result.model';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Submission } from 'app/entities/submission.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { MockParticipationWebsocketService } from '../helpers/mocks/service/mock-participation-websocket.service';\nimport { IProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { MockProgrammingExerciseParticipationService } from '../helpers/mocks/service/mock-programming-exercise-participation.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingSubmissionService', () => {\n let websocketService: MockWebsocketService;\n let httpService: MockHttpService;\n let participationWebsocketService: IParticipationWebsocketService;\n let alertService: MockAlertService;\n let participationService: IProgrammingExerciseParticipationService;\n let submissionService: IProgrammingSubmissionService;\n\n let httpGetStub: SinonStub;\n let wsSubscribeStub: SinonStub;\n let wsUnsubscribeStub: SinonStub;\n let wsReceiveStub: SinonStub;\n let participationWsLatestResultStub: SinonStub;\n let getLatestResultStub: SinonStub;\n let notifyAllResultSubscribersStub: SinonStub;\n\n let wsSubmissionSubject: Subject<Submission | undefined>;\n let wsLatestResultSubject: Subject<Result | undefined>;\n\n const participationId = 1;\n const submissionTopic = `/user/topic/newSubmissions`;\n let currentSubmission: Submission;\n let currentSubmission2: Submission;\n let result: Result;\n let result2: Result;\n\n beforeEach(() => {\n currentSubmission = { id: 11, submissionDate: moment().subtract(20, 'seconds'), participation: { id: participationId } } as any;\n currentSubmission2 = { id: 12, submissionDate: moment().subtract(20, 'seconds'), participation: { id: participationId } } as any;\n result = { id: 31, submission: currentSubmission } as any;\n result2 = { id: 32, submission: currentSubmission2 } as any;\n\n websocketService = new MockWebsocketService();\n httpService = new MockHttpService();\n participationWebsocketService = new MockParticipationWebsocketService();\n alertService = new MockAlertService();\n participationService = new MockProgrammingExerciseParticipationService();\n\n httpGetStub = stub(httpService, 'get');\n wsSubscribeStub = stub(websocketService, 'subscribe');\n wsUnsubscribeStub = stub(websocketService, 'unsubscribe');\n wsSubmissionSubject = new Subject<Submission | undefined>();\n wsReceiveStub = stub(websocketService, 'receive').returns(wsSubmissionSubject);\n wsLatestResultSubject = new Subject<Result | undefined>();\n participationWsLatestResultStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation').returns(wsLatestResultSubject as any);\n getLatestResultStub = stub(participationService, 'getLatestResultWithFeedback');\n notifyAllResultSubscribersStub = stub(participationWebsocketService, 'notifyAllResultSubscribers');\n\n // @ts-ignore\n submissionService = new ProgrammingSubmissionService(websocketService, httpService, participationWebsocketService, participationService, alertService);\n });\n\n afterEach(() => {\n httpGetStub.restore();\n wsSubscribeStub.restore();\n wsUnsubscribeStub.restore();\n wsReceiveStub.restore();\n participationWsLatestResultStub.restore();\n getLatestResultStub.restore();\n notifyAllResultSubscribersStub.restore();\n });\n\n it('should return cached subject as Observable for provided participation if exists', () => {\n const cachedSubject = new BehaviorSubject(undefined);\n // @ts-ignore\n const fetchLatestPendingSubmissionSpy = spy(submissionService, 'fetchLatestPendingSubmissionByParticipationId');\n // @ts-ignore\n const setupWebsocketSubscriptionSpy = spy(submissionService, 'setupWebsocketSubscriptionForLatestPendingSubmission');\n // @ts-ignore\n const subscribeForNewResultSpy = spy(submissionService, 'subscribeForNewResult');\n // @ts-ignore\n submissionService.submissionSubjects = { [participationId]: cachedSubject };\n\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true);\n expect(fetchLatestPendingSubmissionSpy).to.not.have.been.called;\n expect(setupWebsocketSubscriptionSpy).to.not.have.been.called;\n expect(subscribeForNewResultSpy).to.not.have.been.called;\n });\n\n it('should query httpService endpoint and setup the websocket subscriptions if no subject is cached for the provided participation', async () => {\n httpGetStub.returns(of(currentSubmission));\n const submission = await new Promise((resolve) => submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => resolve(s)));\n expect(submission).to.deep.equal({ submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId });\n expect(wsSubscribeStub).to.have.been.calledOnceWithExactly(submissionTopic);\n expect(wsReceiveStub).to.have.been.calledOnceWithExactly(submissionTopic);\n expect(participationWsLatestResultStub).to.have.been.calledOnceWithExactly(participationId, true, 10);\n });\n\n it('should emit undefined when a new result comes in for the given participation to signal that the building process is over', () => {\n const returnedSubmissions: Array<ProgrammingSubmissionStateObj | undefined> = [];\n httpGetStub.returns(of(currentSubmission));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => returnedSubmissions.push(s));\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId }]);\n // Result comes in for submission.\n result.submission = currentSubmission;\n wsLatestResultSubject.next(result);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n ]);\n });\n\n it('should NOT emit undefined when a new result comes that does not belong to the currentSubmission', () => {\n const returnedSubmissions: Array<ProgrammingSubmissionStateObj | undefined> = [];\n httpGetStub.returns(of(currentSubmission));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => returnedSubmissions.push(s));\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId }]);\n // Result comes in for submission.\n result.submission = currentSubmission2;\n wsLatestResultSubject.next(result);\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId }]);\n });\n\n it('should emit the newest submission when it was received through the websocket connection', () => {\n const returnedSubmissions: Array<ProgrammingSubmissionStateObj | undefined> = [];\n // No latest pending submission found.\n httpGetStub.returns(of(undefined));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => returnedSubmissions.push(s));\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId }]);\n // New submission comes in.\n wsSubmissionSubject.next(currentSubmission2);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission2, participationId },\n ]);\n // Result comes in for submission.\n result.submission = currentSubmission2;\n wsLatestResultSubject.next(result);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission2, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n ]);\n });\n\n it('should emit the failed submission state when the result waiting timer runs out AND accept a late result', async () => {\n // Set the timer to 10ms for testing purposes.\n // @ts-ignore\n submissionService.DEFAULT_EXPECTED_RESULT_ETA = 10;\n const returnedSubmissions: Array<ProgrammingSubmissionStateObj | undefined> = [];\n httpGetStub.returns(of(undefined));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => returnedSubmissions.push(s));\n // We simulate that the latest result from the server does not belong the pending submission\n getLatestResultStub = getLatestResultStub.returns(of(result));\n\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId }]);\n wsSubmissionSubject.next(currentSubmission2);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission2, participationId },\n ]);\n // Wait 10ms for the timeout\n await new Promise<void>((resolve) => setTimeout(() => resolve(), 10));\n\n // Expect the fallback mechanism to kick in after the timeout\n expect(getLatestResultStub).to.have.been.calledOnceWithExactly(participationId, true);\n\n // HAS_FAILED_SUBMISSION is expected as the result provided by getLatestResult does not match the pending submission\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission2, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: currentSubmission2, participationId },\n ]);\n\n // Now the result for the submission in - should be accepted even though technically too late!\n wsLatestResultSubject.next(result2);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission2, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: currentSubmission2, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n ]);\n });\n\n it('should emit has no pending submission if the fallback mechanism fetches the right result from the server', async () => {\n // Set the timer to 10ms for testing purposes.\n // @ts-ignore\n submissionService.DEFAULT_EXPECTED_RESULT_ETA = 10;\n const returnedSubmissions: Array<ProgrammingSubmissionStateObj | undefined> = [];\n httpGetStub.returns(of(undefined));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true).subscribe((s) => returnedSubmissions.push(s));\n // We simulate that the latest result from the server matches the pending submission\n getLatestResultStub = getLatestResultStub.returns(of(result));\n\n expect(returnedSubmissions).to.deep.equal([{ submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId }]);\n wsSubmissionSubject.next(currentSubmission);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId },\n ]);\n // Wait 10ms for the timeout.\n await new Promise<void>((resolve) => setTimeout(() => resolve(), 10));\n\n // Expect the fallback mechanism to kick in after the timeout\n expect(getLatestResultStub).to.have.been.calledOnceWithExactly(participationId, true);\n expect(notifyAllResultSubscribersStub).to.have.been.calledOnceWithExactly({ ...result, participation: { id: participationId } });\n wsLatestResultSubject.next(result);\n\n // HAS_NO_PENDING_SUBMISSION is expected as the result provided by getLatestResult matches the pending submission\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n ]);\n\n // If the \"real\" websocket connection triggers now for some reason, the submission state should not change\n wsLatestResultSubject.next(result);\n expect(returnedSubmissions).to.deep.equal([\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: currentSubmission, participationId },\n { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId },\n ]);\n });\n\n it('should fetch the latest pending submissions for all participations of an exercise if preloadLatestPendingSubmissionsForExercise is called', async () => {\n const exerciseId = 3;\n const participation1 = { id: 2 } as StudentParticipation;\n const participation2 = { id: 3 } as StudentParticipation;\n // This participation will not be cached.\n const participation3 = { id: 4 } as StudentParticipation;\n let submissionState, submission;\n\n const pendingSubmissions = { [participation1.id!]: currentSubmission, [participation2.id!]: currentSubmission2 };\n\n // @ts-ignore\n const fetchLatestPendingSubmissionSpy = spy(submissionService, 'fetchLatestPendingSubmissionByParticipationId');\n\n httpGetStub.returns(of(pendingSubmissions));\n\n // This load the submissions for participation 1 and 2, but not for 3.\n submissionService.getSubmissionStateOfExercise(exerciseId).toPromise();\n submissionService.getLatestPendingSubmissionByParticipationId(participation1.id!, exerciseId, true).subscribe(({ submissionState: state, submission: sub }) => {\n submissionState = state;\n submission = sub;\n });\n\n expect(httpGetStub).to.have.been.calledOnceWithExactly('undefinedapi/programming-exercises/3/latest-pending-submissions');\n // Fetching the latest pending submission should not trigger a rest call for a cached submission.\n expect(fetchLatestPendingSubmissionSpy).not.to.have.been.called;\n expect(submissionState).to.equal(ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION);\n expect(submission).to.equal(currentSubmission);\n\n // Fetching the latest pending submission should trigger a rest call if the submission is not cached.\n await submissionService.getLatestPendingSubmissionByParticipationId(participation3.id!, exerciseId, true);\n expect(fetchLatestPendingSubmissionSpy).to.have.been.calledOnceWithExactly(participation3.id);\n });\n\n it('should not throw an error on getSubmissionStateOfExercise if state is an empty object', async () => {\n const exerciseId = 10;\n const submissionState: ExerciseSubmissionState = {};\n // @ts-ignore\n const fetchLatestPendingSubmissionsByExerciseIdSpy = spy(submissionService, 'fetchLatestPendingSubmissionsByExerciseId');\n httpGetStub.withArgs(SERVER_API_URL + `api/programming-exercises/${exerciseId}/latest-pending-submissions`).returns(of(submissionState));\n\n let receivedSubmissionState: ExerciseSubmissionState = {};\n submissionService.getSubmissionStateOfExercise(exerciseId).subscribe((state) => (receivedSubmissionState = state));\n expect(fetchLatestPendingSubmissionsByExerciseIdSpy).to.have.been.calledOnceWithExactly(exerciseId);\n expect(receivedSubmissionState).to.deep.equal(submissionState);\n });\n\n it('should correctly return the submission state based on the servers response', async () => {\n const exerciseId = 10;\n const submissionState = { 1: { id: 11, submissionDate: moment().subtract(2, 'hours') } as ProgrammingSubmission, 2: undefined };\n const expectedSubmissionState = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: submissionState['1'], participationId: 1 },\n 2: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 2 },\n };\n // @ts-ignore\n const fetchLatestPendingSubmissionsByExerciseIdSpy = spy(submissionService, 'fetchLatestPendingSubmissionsByExerciseId');\n httpGetStub.withArgs(SERVER_API_URL + `api/programming-exercises/${exerciseId}/latest-pending-submissions`).returns(of(submissionState));\n\n let receivedSubmissionState: ExerciseSubmissionState = {};\n submissionService.getSubmissionStateOfExercise(exerciseId).subscribe((state) => (receivedSubmissionState = state));\n expect(fetchLatestPendingSubmissionsByExerciseIdSpy).to.have.been.calledOnceWithExactly(exerciseId);\n expect(receivedSubmissionState).to.deep.equal(expectedSubmissionState);\n });\n\n it('should recalculate the result eta based on the number of open submissions', () => {\n const exerciseId = 10;\n // Simulate 340 participations with one pending submission each.\n const submissionState = _range(340).reduce((acc, n) => ({ ...acc, [n]: { submissionDate: moment().subtract(1, 'minutes') } as ProgrammingSubmission }), {});\n const expectedSubmissionState = Object.entries(submissionState).reduce(\n (acc, [participationID, submission]: [string, ProgrammingSubmission]) => ({\n ...acc,\n [participationID]: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission, participationId: parseInt(participationID, 10) },\n }),\n {},\n );\n // @ts-ignore\n const fetchLatestPendingSubmissionsByExerciseIdSpy = spy(submissionService, 'fetchLatestPendingSubmissionsByExerciseId');\n httpGetStub.withArgs(SERVER_API_URL + `api/programming-exercises/${exerciseId}/latest-pending-submissions`).returns(of(submissionState));\n\n let receivedSubmissionState: ExerciseSubmissionState = {};\n submissionService.getSubmissionStateOfExercise(exerciseId).subscribe((state) => (receivedSubmissionState = state));\n expect(fetchLatestPendingSubmissionsByExerciseIdSpy).to.have.been.calledOnceWithExactly(exerciseId);\n expect(receivedSubmissionState).to.deep.equal(expectedSubmissionState);\n\n let resultEta = -1;\n submissionService.getResultEtaInMs().subscribe((eta) => (resultEta = eta));\n\n // With 340 submissions, the eta should now have increased.\n expect(resultEta).to.equal(2000 * 60 + 3 * 4000 * 60);\n });\n\n it('should only unsubscribe if no other participations use the topic', () => {\n httpGetStub.returns(of(currentSubmission));\n submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10, true);\n submissionService.getLatestPendingSubmissionByParticipationId(2, 10, true);\n\n // Should not unsubscribe as participation 2 still uses the same topic\n submissionService.unsubscribeForLatestSubmissionOfParticipation(participationId);\n expect(wsUnsubscribeStub).to.not.have.been.called;\n\n // Should now unsubscribe as last participation for topic was unsubscribed\n submissionService.unsubscribeForLatestSubmissionOfParticipation(2);\n expect(wsUnsubscribeStub).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.6865909695625305, "alphanum_fraction": 0.6865909695625305, "avg_line_length": 45.04587173461914, "blob_id": "effd5b28a4150ec8d184f623a3b9888dc63772bd", "content_id": "03977c9408a268d85624d58729acd5b82890f8dd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5019, "license_type": "permissive", "max_line_length": 177, "num_lines": 109, "path": "/src/main/webapp/app/exercises/programming/assess/programming-assessment.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable, NgModule } from '@angular/core';\nimport { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { CodeEditorTutorAssessmentContainerComponent } from 'app/exercises/programming/assess/code-editor-tutor-assessment-container.component';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { Observable } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ProgrammingAssessmentDashboardComponent } from 'app/exercises/programming/assess/programming-assessment-dashboard/programming-assessment-dashboard.component';\n\n@Injectable({ providedIn: 'root' })\nexport class NewStudentParticipationResolver implements Resolve<number | undefined> {\n constructor(private programmingSubmissionService: ProgrammingSubmissionService, private jhiAlertService: JhiAlertService) {}\n\n /**\n * Resolves the needed studentParticipationId for the CodeEditorTutorAssessmentContainerComponent for submissions without assessment\n * @param route\n */\n resolve(route: ActivatedRouteSnapshot) {\n const exerciseId = Number(route.paramMap.get('exerciseId'));\n const correctionRound = Number(route.queryParamMap.get('correction-round'));\n\n if (exerciseId) {\n const returnValue = this.programmingSubmissionService.getProgrammingSubmissionForExerciseForCorrectionRoundWithoutAssessment(exerciseId, true, correctionRound).pipe(\n map((submission) => submission.participation!.id!),\n catchError((error) => {\n if (error.error && error.error.errorKey === 'lockedSubmissionsLimitReached') {\n this.jhiAlertService.error('artemisApp.submission.lockedSubmissionsLimitReached');\n }\n return Observable.of(error);\n }),\n );\n return returnValue;\n }\n return Observable.of(undefined);\n }\n}\n\n@Injectable({ providedIn: 'root' })\nexport class StudentParticipationResolver implements Resolve<number | undefined> {\n constructor(private programmingSubmissionService: ProgrammingSubmissionService, private jhiAlertService: JhiAlertService) {}\n\n /**\n *\n * Locks the latest submission of a programming exercises participation, if it is not already locked\n * @param route\n */\n resolve(route: ActivatedRouteSnapshot) {\n const participationId = Number(route.paramMap.get('participationId'));\n const correctionRound = Number(route.queryParamMap.get('correction-round'));\n\n if (participationId) {\n return this.programmingSubmissionService.lockAndGetProgrammingSubmissionParticipation(participationId, correctionRound).pipe(\n map((participation) => participation.id),\n catchError((error) => {\n if (error.error && error.error.errorKey === 'lockedSubmissionsLimitReached') {\n this.jhiAlertService.error('artemisApp.submission.lockedSubmissionsLimitReached');\n }\n return Observable.of(error);\n }),\n );\n }\n return Observable.of(undefined);\n }\n}\n\nexport const routes: Routes = [\n {\n path: ':courseId/programming-exercises/:exerciseId/assessment',\n component: ProgrammingAssessmentDashboardComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.assessmentDashboard.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/programming-exercises/:exerciseId/code-editor/new/assessment',\n component: CodeEditorTutorAssessmentContainerComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n resolve: {\n studentParticipationId: NewStudentParticipationResolver,\n },\n runGuardsAndResolvers: 'always',\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/programming-exercises/:exerciseId/code-editor/:participationId/assessment',\n component: CodeEditorTutorAssessmentContainerComponent,\n data: {\n authorities: [Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA],\n pageTitle: 'artemisApp.programmingExercise.home.title',\n },\n resolve: {\n studentParticipationId: StudentParticipationResolver,\n },\n canActivate: [UserRouteAccessService],\n },\n];\n\n@NgModule({\n imports: [RouterModule.forChild(routes)],\n exports: [RouterModule],\n})\nexport class ArtemisProgrammingAssessmentRoutingModule {}\n" }, { "alpha_fraction": 0.7109252214431763, "alphanum_fraction": 0.7109252214431763, "avg_line_length": 41.511112213134766, "blob_id": "a181d4d8904aca4e639fe0dbc929d321c9bbb375", "content_id": "5406dba06f1a44bbc60685c3c7873abd204204f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1913, "license_type": "permissive", "max_line_length": 138, "num_lines": 45, "path": "/src/main/webapp/app/exam/manage/exams/exam-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { Exam } from 'app/entities/exam.model';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport * as moment from 'moment';\n\n@Component({\n selector: 'jhi-exam-detail',\n templateUrl: './exam-detail.component.html',\n})\nexport class ExamDetailComponent implements OnInit {\n exam: Exam;\n formattedStartText?: SafeHtml;\n formattedConfirmationStartText?: SafeHtml;\n formattedEndText?: SafeHtml;\n formattedConfirmationEndText?: SafeHtml;\n isAtLeastInstructor = false;\n isExamOver = true;\n\n constructor(private route: ActivatedRoute, private artemisMarkdown: ArtemisMarkdownService, private accountService: AccountService) {}\n\n /**\n * Initialize the exam\n */\n ngOnInit(): void {\n this.route.data.subscribe(({ exam }) => {\n this.exam = exam;\n this.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exam.course);\n this.formattedStartText = this.artemisMarkdown.safeHtmlForMarkdown(this.exam.startText);\n this.formattedConfirmationStartText = this.artemisMarkdown.safeHtmlForMarkdown(this.exam.confirmationStartText);\n this.formattedEndText = this.artemisMarkdown.safeHtmlForMarkdown(this.exam.endText);\n this.formattedConfirmationEndText = this.artemisMarkdown.safeHtmlForMarkdown(this.exam.confirmationEndText);\n this.isExamOver = !!this.exam.endDate?.isBefore(moment());\n });\n }\n\n /**\n * Returns the route for exam components by identifier\n */\n getExamRoutesByIdentifier(identifier: string) {\n return ['/course-management', this.exam.course?.id, 'exams', this.exam.id, identifier];\n }\n}\n" }, { "alpha_fraction": 0.7572948336601257, "alphanum_fraction": 0.7612195014953613, "avg_line_length": 55.530548095703125, "blob_id": "1e83ada9ae0d0c0f84b3e4458b671e6c652d5e76", "content_id": "66ab46ad685aaac737d8b17a1e26fbd99787f24a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 17581, "license_type": "permissive", "max_line_length": 180, "num_lines": 311, "path": "/src/test/java/de/tum/in/www1/artemis/FileUploadExerciseIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.FileUploadExercise;\nimport de.tum.in.www1.artemis.domain.GradingCriterion;\nimport de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class FileUploadExerciseIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private CourseRepository courseRepo;\n\n @Autowired\n private ExerciseRepository exerciseRepo;\n\n @Autowired\n private FileUploadExerciseRepository fileUploadExerciseRepository;\n\n @Autowired\n private FileUploadSubmissionRepository fileUploadSubmissionRepository;\n\n private List<GradingCriterion> gradingCriteria;\n\n private final String creationFilePattern = \"png, pdf, jPg , r, DOCX\";\n\n @BeforeEach\n public void initTestCase() {\n database.addUsers(1, 1, 1);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExerciseFails() throws Exception {\n String filePattern = \"Example file pattern\";\n FileUploadExercise fileUploadExercise = database.createFileUploadExercisesWithCourse().get(0);\n fileUploadExercise.setFilePattern(filePattern);\n request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExercise_InvalidMaxScore() throws Exception {\n FileUploadExercise fileUploadExercise = database.createFileUploadExercisesWithCourse().get(0);\n fileUploadExercise.setFilePattern(creationFilePattern);\n fileUploadExercise.setMaxPoints(0.0);\n request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExercise_IncludedAsBonusInvalidBonusPoints() throws Exception {\n FileUploadExercise fileUploadExercise = database.createFileUploadExercisesWithCourse().get(0);\n fileUploadExercise.setFilePattern(creationFilePattern);\n fileUploadExercise.setMaxPoints(10.0);\n fileUploadExercise.setBonusPoints(1.0);\n fileUploadExercise.setIncludedInOverallScore(IncludedInOverallScore.INCLUDED_AS_BONUS);\n request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExercise_NotIncludedInvalidBonusPoints() throws Exception {\n FileUploadExercise fileUploadExercise = database.createFileUploadExercisesWithCourse().get(0);\n fileUploadExercise.setFilePattern(creationFilePattern);\n fileUploadExercise.setMaxPoints(10.0);\n fileUploadExercise.setBonusPoints(1.0);\n fileUploadExercise.setIncludedInOverallScore(IncludedInOverallScore.NOT_INCLUDED);\n request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExercise() throws Exception {\n FileUploadExercise fileUploadExercise = database.createFileUploadExercisesWithCourse().get(0);\n fileUploadExercise.setFilePattern(creationFilePattern);\n gradingCriteria = database.addGradingInstructionsToExercise(fileUploadExercise);\n FileUploadExercise receivedFileUploadExercise = request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class,\n HttpStatus.CREATED);\n\n assertThat(receivedFileUploadExercise).isNotNull();\n assertThat(receivedFileUploadExercise.getId()).isNotNull();\n assertThat(receivedFileUploadExercise.getFilePattern()).isEqualTo(creationFilePattern.toLowerCase().replaceAll(\"\\\\s+\", \"\"));\n assertThat(receivedFileUploadExercise.getCourseViaExerciseGroupOrCourseMember()).as(\"course was set for normal exercise\").isNotNull();\n assertThat(receivedFileUploadExercise.getExerciseGroup()).as(\"exerciseGroup was not set for normal exercise\").isNull();\n assertThat(receivedFileUploadExercise.getCourseViaExerciseGroupOrCourseMember().getId()).as(\"exerciseGroupId was set correctly\")\n .isEqualTo(fileUploadExercise.getCourseViaExerciseGroupOrCourseMember().getId());\n\n assertThat(receivedFileUploadExercise.getGradingCriteria().get(0).getTitle()).isEqualTo(null);\n assertThat(receivedFileUploadExercise.getGradingCriteria().get(1).getTitle()).isEqualTo(\"test title\");\n\n assertThat(gradingCriteria.get(0).getStructuredGradingInstructions().size()).isEqualTo(1);\n assertThat(gradingCriteria.get(0).getStructuredGradingInstructions().get(0).getInstructionDescription())\n .isEqualTo(\"created first instruction with empty criteria for testing\");\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExerciseForExam() throws Exception {\n ExerciseGroup exerciseGroup = database.addExerciseGroupWithExamAndCourse(true);\n FileUploadExercise fileUploadExercise = ModelFactory.generateFileUploadExerciseForExam(creationFilePattern, exerciseGroup);\n\n gradingCriteria = database.addGradingInstructionsToExercise(fileUploadExercise);\n FileUploadExercise createdFileUploadExercise = request.postWithResponseBody(\"/api/file-upload-exercises\", fileUploadExercise, FileUploadExercise.class, HttpStatus.CREATED);\n\n assertThat(createdFileUploadExercise).isNotNull();\n assertThat(createdFileUploadExercise.getId()).isNotNull();\n assertThat(createdFileUploadExercise.getFilePattern()).isEqualTo(creationFilePattern.toLowerCase().replaceAll(\"\\\\s+\", \"\"));\n assertThat(!createdFileUploadExercise.isCourseExercise()).as(\"course was not set for exam exercise\");\n assertThat(createdFileUploadExercise.getExerciseGroup()).as(\"exerciseGroup was set for exam exercise\").isNotNull();\n assertThat(createdFileUploadExercise.getExerciseGroup().getId()).as(\"exerciseGroupId was set correctly\").isEqualTo(exerciseGroup.getId());\n\n assertThat(createdFileUploadExercise.getGradingCriteria().get(0).getTitle()).isEqualTo(null);\n assertThat(createdFileUploadExercise.getGradingCriteria().get(1).getTitle()).isEqualTo(\"test title\");\n\n assertThat(gradingCriteria.get(0).getStructuredGradingInstructions().size()).isEqualTo(1);\n assertThat(gradingCriteria.get(0).getStructuredGradingInstructions().get(0).getInstructionDescription())\n .isEqualTo(\"created first instruction with empty criteria for testing\");\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createFileUploadExercise_setBothCourseAndExerciseGroupOrNeither_badRequest() throws Exception {\n ExerciseGroup exerciseGroup = database.addExerciseGroupWithExamAndCourse(true);\n FileUploadExercise fileUploadExercise = ModelFactory.generateFileUploadExerciseForExam(creationFilePattern, exerciseGroup);\n fileUploadExercise.setCourse(fileUploadExercise.getExerciseGroup().getExam().getCourse());\n\n request.postWithResponseBody(\"/api/file-upload-exercises/\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n\n fileUploadExercise.setCourse(null);\n fileUploadExercise.setExerciseGroup(null);\n\n request.postWithResponseBody(\"/api/file-upload-exercises/\", fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void getFileUploadExercise() throws Exception {\n Course course = database.addCourseWithThreeFileUploadExercise();\n FileUploadExercise fileUploadExercise = database.findFileUploadExerciseWithTitle(course.getExercises(), \"released\");\n\n FileUploadExercise receivedFileUploadExercise = request.get(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), HttpStatus.OK, FileUploadExercise.class);\n\n assertThat(fileUploadExercise.getId()).isEqualTo(receivedFileUploadExercise.getId());\n assertThat(fileUploadExercise).isEqualTo(receivedFileUploadExercise);\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void getExamFileUploadExercise_asStudent_forbidden() throws Exception {\n getExamFileUploadExercise();\n }\n\n @Test\n @WithMockUser(value = \"tutor1\", roles = \"TA\")\n public void getExamFileUploadExercise_asTutor_forbidden() throws Exception {\n getExamFileUploadExercise();\n }\n\n private void getExamFileUploadExercise() throws Exception {\n FileUploadExercise fileUploadExercise = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n request.get(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), HttpStatus.FORBIDDEN, FileUploadExercise.class);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getExamFileUploadExercise_asInstructor() throws Exception {\n FileUploadExercise fileUploadExercise = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n\n FileUploadExercise receivedFileUploadExercise = request.get(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), HttpStatus.OK, FileUploadExercise.class);\n assertThat(receivedFileUploadExercise).as(\"exercise was retrieved\").isNotNull();\n assertThat(receivedFileUploadExercise.getId()).as(\"exercise with the right id was retrieved\").isEqualTo(fileUploadExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteFileUploadExercise_asInstructor() throws Exception {\n Course course = database.addCourseWithThreeFileUploadExercise();\n for (var exercise : course.getExercises()) {\n request.delete(\"/api/file-upload-exercises/\" + exercise.getId(), HttpStatus.OK);\n }\n assertThat(exerciseRepo.findAll().isEmpty());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void deleteFileUploadExercise_asStudent() throws Exception {\n Course course = database.addCourseWithThreeFileUploadExercise();\n for (var exercise : course.getExercises()) {\n request.delete(\"/api/file-upload-exercises/\" + exercise.getId(), HttpStatus.FORBIDDEN);\n }\n\n assertThat(exerciseRepo.findAll().size() == course.getExercises().size());\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteExamFileUploadExercise() throws Exception {\n FileUploadExercise fileUploadExercise = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n\n request.delete(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), HttpStatus.OK);\n assertThat(exerciseRepo.findAll().isEmpty());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateFileUploadExercise_asInstructor() throws Exception {\n Course course = database.addCourseWithThreeFileUploadExercise();\n FileUploadExercise fileUploadExercise = database.findFileUploadExerciseWithTitle(course.getExercises(), \"released\");\n fileUploadExercise.setDueDate(ZonedDateTime.now().plusDays(10));\n\n FileUploadExercise receivedFileUploadExercise = request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), fileUploadExercise,\n FileUploadExercise.class, HttpStatus.OK);\n assertThat(receivedFileUploadExercise.getDueDate().equals(ZonedDateTime.now().plusDays(10)));\n assertThat(receivedFileUploadExercise.getCourseViaExerciseGroupOrCourseMember()).as(\"course was set for normal exercise\").isNotNull();\n assertThat(receivedFileUploadExercise.getExerciseGroup()).as(\"exerciseGroup was not set for normal exercise\").isNull();\n assertThat(receivedFileUploadExercise.getCourseViaExerciseGroupOrCourseMember().getId()).as(\"courseId was not updated\").isEqualTo(course.getId());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateFileUploadExerciseForExam_asInstructor() throws Exception {\n FileUploadExercise fileUploadExercise = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n String newTitle = \"New file upload exercise title\";\n fileUploadExercise.setTitle(newTitle);\n\n FileUploadExercise updatedFileUploadExercise = request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), fileUploadExercise,\n FileUploadExercise.class, HttpStatus.OK);\n\n assertThat(updatedFileUploadExercise.getTitle().equals(newTitle));\n assertThat(!updatedFileUploadExercise.isCourseExercise()).as(\"course was not set for exam exercise\");\n assertThat(updatedFileUploadExercise.getExerciseGroup()).as(\"exerciseGroup was set for exam exercise\").isNotNull();\n assertThat(updatedFileUploadExercise.getExerciseGroup().getId()).as(\"exerciseGroupId was not updated\").isEqualTo(fileUploadExercise.getExerciseGroup().getId());\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateFileUploadExercise_setBothCourseAndExerciseGroupOrNeither_badRequest() throws Exception {\n FileUploadExercise fileUploadExercise = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n fileUploadExercise.setCourse(fileUploadExercise.getExerciseGroup().getExam().getCourse());\n\n request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n\n fileUploadExercise.setExerciseGroup(null);\n fileUploadExercise.setCourse(null);\n\n request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExercise.getId(), fileUploadExercise, FileUploadExercise.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateFileUploadExercise_conversionBetweenCourseAndExamExercise_badRequest() throws Exception {\n FileUploadExercise fileUploadExerciseWithCourse = database.createFileUploadExercisesWithCourse().get(0);\n FileUploadExercise fileUploadExerciseWithExerciseGroup = database.addCourseExamExerciseGroupWithOneFileUploadExercise();\n\n fileUploadExerciseWithCourse.setCourse(null);\n fileUploadExerciseWithCourse.setExerciseGroup(fileUploadExerciseWithExerciseGroup.getExerciseGroup());\n\n fileUploadExerciseWithExerciseGroup.setCourse(fileUploadExerciseWithCourse.getCourseViaExerciseGroupOrCourseMember());\n fileUploadExerciseWithExerciseGroup.setExerciseGroup(null);\n\n request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExerciseWithCourse.getId(), fileUploadExerciseWithCourse, FileUploadExercise.class,\n HttpStatus.BAD_REQUEST);\n request.putWithResponseBody(\"/api/file-upload-exercises/\" + fileUploadExerciseWithExerciseGroup.getId(), fileUploadExerciseWithExerciseGroup, FileUploadExercise.class,\n HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAllFileUploadExercisesForCourse_asInstructor() throws Exception {\n database.addCourseWithThreeFileUploadExercise();\n long courseID = courseRepo.findAllActiveWithEagerExercisesAndLectures(ZonedDateTime.now()).get(0).getId();\n\n List<FileUploadExercise> receivedFileUploadExercises = request.getList(\"/api/courses/\" + courseID + \"/file-upload-exercises\", HttpStatus.OK, FileUploadExercise.class);\n\n // this seems to be a flaky test, based on the execution order, the following line has a problem with authentication, this should fix it\n database.changeUser(\"instructor1\");\n assertThat(receivedFileUploadExercises.size() == courseRepo.findAllActiveWithEagerExercisesAndLectures(ZonedDateTime.now()).get(0).getExercises().size());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getAllFileUploadExercisesForCourse_asStudent() throws Exception {\n database.addCourseWithThreeFileUploadExercise();\n long courseID = courseRepo.findAllActiveWithEagerExercisesAndLectures(ZonedDateTime.now()).get(0).getId();\n\n List<FileUploadExercise> receivedFileUploadExercises = request.getList(\"/api/courses/\" + courseID + \"/file-upload-exercises\", HttpStatus.FORBIDDEN,\n FileUploadExercise.class);\n\n assertThat(receivedFileUploadExercises).isNull();\n }\n}\n" }, { "alpha_fraction": 0.7591742873191833, "alphanum_fraction": 0.7603210806846619, "avg_line_length": 42.599998474121094, "blob_id": "6f9acc3e4519e8635bf00525fd4b042ad56e3d85", "content_id": "07b679198ef08c9e07a81858f6608a3f0a26e107", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 872, "license_type": "permissive", "max_line_length": 132, "num_lines": 20, "path": "/src/main/java/de/tum/in/www1/artemis/config/PublicResourcesConfiguration.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.config;\n\nimport java.nio.file.Paths;\n\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;\nimport org.springframework.web.servlet.config.annotation.WebMvcConfigurer;\n\n@Configuration\npublic class PublicResourcesConfiguration implements WebMvcConfigurer {\n\n @Override\n public void addResourceHandlers(ResourceHandlerRegistry registry) {\n // Static assets, accessible without authorization.\n // Allowed locations are under $artemisRunDir/public/** and resource/public/**\n final var userDir = System.getProperty(\"user.dir\");\n final var publicFiles = Paths.get(userDir, \"public\");\n registry.addResourceHandler(\"/public/**\").addResourceLocations(\"file:\" + publicFiles.toString() + \"/\", \"classpath:public/\");\n }\n}\n" }, { "alpha_fraction": 0.6641659140586853, "alphanum_fraction": 0.6654898524284363, "avg_line_length": 37.40678024291992, "blob_id": "a2acc2bc7f0805c293aa377fef284704a1a14fc7", "content_id": "051c7728a3d1953f9cd8192d8257bae61093d5b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2266, "license_type": "permissive", "max_line_length": 118, "num_lines": 59, "path": "/src/main/webapp/app/exercises/shared/unreferenced-feedback/unreferenced-feedback.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, Output, EventEmitter } from '@angular/core';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\n\n@Component({\n selector: 'jhi-unreferenced-feedback',\n templateUrl: './unreferenced-feedback.component.html',\n styleUrls: [],\n})\nexport class UnreferencedFeedbackComponent {\n unreferencedFeedback: Feedback[] = [];\n assessmentsAreValid: boolean;\n @Input() busy: boolean;\n @Input() readOnly: boolean;\n @Output() feedbacksChange = new EventEmitter<Feedback[]>();\n\n @Input() set feedbacks(feedbacks: Feedback[]) {\n this.unreferencedFeedback = [...feedbacks];\n }\n public deleteAssessment(assessmentToDelete: Feedback): void {\n const indexToDelete = this.unreferencedFeedback.indexOf(assessmentToDelete);\n this.unreferencedFeedback.splice(indexToDelete, 1);\n this.feedbacksChange.emit(this.unreferencedFeedback);\n this.validateFeedback();\n }\n /**\n * Validates the feedback:\n * - There must be any form of feedback, either general feedback or feedback referencing a model element or both\n * - Each reference feedback must have a score that is a valid number\n */\n validateFeedback() {\n if (!this.unreferencedFeedback || this.unreferencedFeedback.length === 0) {\n this.assessmentsAreValid = false;\n return;\n }\n for (const feedback of this.unreferencedFeedback) {\n if (feedback.credits == undefined || isNaN(feedback.credits)) {\n this.assessmentsAreValid = false;\n return;\n }\n }\n this.assessmentsAreValid = true;\n }\n\n updateAssessment(feedback: Feedback) {\n const indexToUpdate = this.unreferencedFeedback.indexOf(feedback);\n this.unreferencedFeedback[indexToUpdate] = feedback;\n this.validateFeedback();\n this.feedbacksChange.emit(this.unreferencedFeedback);\n }\n\n public addUnreferencedFeedback(): void {\n const feedback = new Feedback();\n feedback.credits = 0;\n feedback.type = FeedbackType.MANUAL_UNREFERENCED;\n this.unreferencedFeedback.push(feedback);\n this.validateFeedback();\n this.feedbacksChange.emit(this.unreferencedFeedback);\n }\n}\n" }, { "alpha_fraction": 0.6980593800544739, "alphanum_fraction": 0.6980593800544739, "avg_line_length": 45.105262756347656, "blob_id": "1cecd5746a200d5beaa91da9ddc1438264557216", "content_id": "f64438bad20e8b1036ff079704e295a00dda83a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1752, "license_type": "permissive", "max_line_length": 131, "num_lines": 38, "path": "/src/main/webapp/app/exercises/programming/shared/code-editor/service/code-editor-domain-dependent-endpoint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { DomainDependentService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain-dependent.service';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpClient } from '@angular/common/http';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { DomainChange, DomainType } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { DomainService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain.service';\n\n/**\n * Service that can be extended to update rest endpoint urls with the received domain information.\n */\nexport abstract class DomainDependentEndpointService extends DomainDependentService {\n private restResourceUrlBase = `${SERVER_API_URL}/api`;\n protected restResourceUrl: string | null;\n\n constructor(protected http: HttpClient, protected jhiWebsocketService: JhiWebsocketService, domainService: DomainService) {\n super(domainService);\n this.initDomainSubscription();\n }\n\n /**\n * Sets resourceUrls according to the parameter.\n * @param domain - enum that defines the type of the domain.\n */\n setDomain(domain: DomainChange) {\n super.setDomain(domain);\n const [domainType, domainValue] = this.domain;\n switch (domainType) {\n case DomainType.PARTICIPATION:\n this.restResourceUrl = `${this.restResourceUrlBase}/repository/${domainValue.id}`;\n break;\n case DomainType.TEST_REPOSITORY:\n this.restResourceUrl = `${this.restResourceUrlBase}/test-repository/${domainValue.id}`;\n break;\n default:\n this.restResourceUrl = null;\n }\n }\n}\n" }, { "alpha_fraction": 0.6490299701690674, "alphanum_fraction": 0.671271800994873, "avg_line_length": 48.30434799194336, "blob_id": "8dedfeaacb53aa8572f1cf452e3928e786d74b19", "content_id": "5d0550d461c86e93909b5cd982d95aedbe0862d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10206, "license_type": "permissive", "max_line_length": 157, "num_lines": 207, "path": "/src/test/javascript/spec/component/course/course-exercises.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs/internal/observable/of';\nimport { Course } from 'app/entities/course.model';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { OrionFilterDirective } from 'app/shared/orion/orion-filter.directive';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { MockHasAnyAuthorityDirective } from '../../helpers/mocks/directive/mock-has-any-authority.directive';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { JhiSortByDirective, JhiSortDirective } from 'ng-jhipster';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { MomentModule } from 'ngx-moment';\nimport { CourseExercisesComponent, ExerciseFilter, ExerciseSortingOrder, SortingAttribute } from 'app/overview/course-exercises/course-exercises.component';\nimport { CourseExerciseRowComponent } from 'app/overview/course-exercises/course-exercise-row.component';\nimport { SidePanelComponent } from 'app/shared/side-panel/side-panel.component';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport * as moment from 'moment';\nimport { Subject } from 'rxjs';\nimport { MockTranslateValuesDirective } from './course-scores/course-scores.component.spec';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseExercisesComponent', () => {\n let fixture: ComponentFixture<CourseExercisesComponent>;\n let component: CourseExercisesComponent;\n let service: CourseManagementService;\n let courseCalculation: CourseScoreCalculationService;\n let translateService: TranslateService;\n let exerciseService: ExerciseService;\n let localStorageService: LocalStorageService;\n\n let course: Course;\n let exercise: Exercise;\n let courseCalculationSpy: sinon.SinonStub;\n\n const parentRoute = ({ params: of({ courseId: '123' }) } as any) as ActivatedRoute;\n const route = ({ parent: parentRoute } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, RouterTestingModule.withRoutes([]), MomentModule],\n declarations: [\n CourseExercisesComponent,\n MockDirective(OrionFilterDirective),\n MockComponent(AlertComponent),\n MockComponent(CourseExerciseRowComponent),\n MockComponent(SidePanelComponent),\n MockDirective(MockHasAnyAuthorityDirective),\n MockDirective(JhiSortByDirective),\n MockPipe(ArtemisTranslatePipe),\n MockDirective(JhiSortDirective),\n MockPipe(ArtemisDatePipe),\n MockDirective(DeleteButtonDirective),\n MockTranslateValuesDirective,\n ],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n {\n provide: ActivatedRoute,\n useValue: route,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseExercisesComponent);\n component = fixture.componentInstance;\n service = TestBed.inject(CourseManagementService);\n courseCalculation = TestBed.inject(CourseScoreCalculationService);\n translateService = TestBed.inject(TranslateService);\n exerciseService = TestBed.inject(ExerciseService);\n localStorageService = TestBed.inject(LocalStorageService);\n\n course = new Course();\n course.id = 123;\n exercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined) as Exercise;\n exercise.dueDate = moment('2021-01-13T16:11:00+01:00').add(1, 'days');\n exercise.releaseDate = moment('2021-01-13T16:11:00+01:00').subtract(1, 'days');\n course.exercises = [exercise];\n spyOn(service, 'getCourseUpdates').and.returnValue(of(course));\n spyOn(translateService, 'onLangChange').and.returnValue(of(new Subject()));\n spyOn(localStorageService, 'retrieve').and.returnValue('OVERDUE,NEEDS_WORK');\n courseCalculationSpy = stub(courseCalculation, 'getCourse').returns(course);\n\n fixture.detectChanges();\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n expect(component.course).to.deep.equal(course);\n expect(courseCalculationSpy.callCount).to.equal(2);\n expect(courseCalculationSpy.getCall(0).calledWithExactly(course.id)).to.be.true;\n expect(courseCalculationSpy.getCall(1).calledWithExactly(course.id)).to.be.true;\n });\n\n it('should invoke setSortingAttribute', () => {\n const sortingButton = fixture.debugElement.query(By.css('#dueDateSorting'));\n expect(sortingButton).to.exist;\n sortingButton.nativeElement.click();\n expect(component.sortingAttribute).to.equal(SortingAttribute.DUE_DATE);\n });\n\n it('should react to changes', () => {\n spyOn(exerciseService, 'getNextExerciseForHours').and.returnValue(exercise);\n component.ngOnChanges();\n expect(component.nextRelevantExercise).to.deep.equal(exercise);\n });\n\n it('should reorder all exercises', () => {\n const oldExercise = {\n diagramType: UMLDiagramType.ClassDiagram,\n course,\n exerciseGroup: undefined,\n releaseDate: moment('2021-01-13T16:11:00+01:00'),\n dueDate: moment('2021-01-13T16:12:00+01:00'),\n } as ModelingExercise;\n const evenOlderExercise = {\n diagramType: UMLDiagramType.ClassDiagram,\n course,\n exerciseGroup: undefined,\n releaseDate: moment('2021-01-07T16:11:00+01:00'),\n dueDate: moment('2021-01-07T16:12:00+01:00'),\n } as ModelingExercise;\n component.course!.exercises = [oldExercise, evenOlderExercise];\n component.sortingOrder = ExerciseSortingOrder.DESC;\n component.activeFilters.clear();\n component.activeFilters.add(ExerciseFilter.NEEDS_WORK);\n\n const sortingButton = fixture.debugElement.query(By.css('#flip'));\n expect(sortingButton).to.exist;\n\n sortingButton.nativeElement.click();\n\n expect(component.sortingOrder).to.equal(ExerciseSortingOrder.ASC);\n expect(component.weeklyIndexKeys).to.deep.equal(['2021-01-03', '2021-01-10']);\n\n sortingButton.nativeElement.click();\n\n expect(component.sortingOrder).to.equal(ExerciseSortingOrder.DESC);\n expect(component.weeklyIndexKeys).to.deep.equal(['2021-01-10', '2021-01-03']);\n });\n\n it('should filter all exercises in different situations', () => {\n component.sortingOrder = ExerciseSortingOrder.DESC;\n const filters: ExerciseFilter[] = Object.values(ExerciseFilter);\n const localStorageSpy = sinon.spy(localStorageService, 'store');\n\n component.toggleFilters(filters);\n\n expect(localStorageSpy).to.have.been.calledOnce;\n expect(component.activeFilters).to.deep.equal(new Set());\n\n for (let i = 1; i < 8; i++) {\n const newExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined) as Exercise;\n newExercise.dueDate = moment('2021-01-13T16:11:00+01:00').add(i, 'days');\n newExercise.releaseDate = moment('2021-01-13T16:11:00+01:00').subtract(i, 'days');\n component.course!.exercises![i] = newExercise;\n }\n component.course!.exercises![component.course!.exercises!.length] = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined) as Exercise;\n\n component.activeFilters.clear();\n component.activeFilters.add(ExerciseFilter.OVERDUE);\n\n component.toggleFilters(filters);\n\n expect(component.activeFilters).to.deep.equal(new Set().add(ExerciseFilter.NEEDS_WORK));\n expect(Object.keys(component.weeklyExercisesGrouped)).to.deep.equal(['2021-01-17', '2021-01-10', 'noDate']);\n expect(component.weeklyIndexKeys).to.deep.equal(['2021-01-17', '2021-01-10', 'noDate']);\n expect(component.exerciseCountMap.get('modeling')).to.equal(9);\n\n // trigger updateUpcomingExercises dynamically with moment()\n component.course!.exercises = [];\n for (let i = 0; i < 7; i++) {\n const newExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined) as Exercise;\n newExercise.dueDate = moment().add(1 + i, 'days');\n newExercise.releaseDate = moment().subtract(1 + i, 'days');\n component.course!.exercises[i] = newExercise;\n }\n\n component.toggleFilters(filters);\n\n expect(component.upcomingExercises.length).to.equal(5);\n });\n});\n" }, { "alpha_fraction": 0.7277353405952454, "alphanum_fraction": 0.7277353405952454, "avg_line_length": 38.29999923706055, "blob_id": "b8bfb22b61a0a2ae8e9382fd9851efb40879bc03", "content_id": "93a0367a2d70e5ca7374bdbbfadaa421ee4094c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 786, "license_type": "permissive", "max_line_length": 85, "num_lines": 20, "path": "/src/main/webapp/app/shared/guard/can-deactivate.guard.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { CanDeactivate } from '@angular/router';\nimport { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs/Observable';\nimport { ComponentCanDeactivate } from 'app/shared/guard/can-deactivate.model';\n\n/**\n * Similar to the pending changes guard, but it does not provide a warning message.\n * The warning message can then be provided by the component.\n */\n@Injectable({ providedIn: 'root' })\nexport class CanDeactivateGuard implements CanDeactivate<ComponentCanDeactivate> {\n /**\n * Function which returns whether the component can be deactivated\n * @param component\n * @returns boolean | Observable<boolean>\n */\n canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {\n return component.canDeactivate();\n }\n}\n" }, { "alpha_fraction": 0.6784449219703674, "alphanum_fraction": 0.6795980334281921, "avg_line_length": 43.63602828979492, "blob_id": "54d75944bb26a92fe7b8a28ac8f7566bc8bf3358", "content_id": "8b3b884bba9c6f3366958c734e71b8382830e5a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12141, "license_type": "permissive", "max_line_length": 172, "num_lines": 272, "path": "/src/main/webapp/app/exercises/text/assess/conflicts/text-feedback-conflicts.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, AfterViewInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Location } from '@angular/common';\n\nimport { TextAssessmentBaseComponent } from 'app/exercises/text/assess/text-assessment-base.component';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { TextBlockRef } from 'app/entities/text-block-ref.model';\nimport { TextBlock, TextBlockType } from 'app/entities/text-block.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { Result } from 'app/entities/result.model';\nimport { FeedbackConflict } from 'app/entities/feedback-conflict';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service';\nimport { getLatestSubmissionResult, setLatestSubmissionResult } from 'app/entities/submission.model';\n\nimport interact from 'interactjs';\nimport * as moment from 'moment';\n\n@Component({\n selector: 'jhi-text-feedback-conflicts',\n templateUrl: './text-feedback-conflicts.component.html',\n styleUrls: ['./text-feedback-conflicts.component.scss'],\n})\nexport class TextFeedbackConflictsComponent extends TextAssessmentBaseComponent implements OnInit, AfterViewInit {\n conflictingSubmissions?: TextSubmission[];\n leftSubmission?: TextSubmission;\n leftTextBlockRefs: TextBlockRef[];\n leftUnusedTextBlockRefs: TextBlockRef[];\n leftTotalScore: number;\n leftFeedbackId: number;\n rightSubmission?: TextSubmission;\n rightTextBlockRefs: TextBlockRef[];\n rightUnusedTextBlockRefs: TextBlockRef[];\n rightTotalScore: number;\n feedbackConflicts: FeedbackConflict[];\n overrideBusy = false;\n markBusy = false;\n isOverrideDisabled = true;\n isMarkingDisabled = true;\n selectedRightFeedbackId?: number;\n\n private get textBlocksWithFeedbackForLeftSubmission(): TextBlock[] {\n return [...this.leftTextBlockRefs, ...this.leftUnusedTextBlockRefs]\n .filter(({ block, feedback }) => block?.type === TextBlockType.AUTOMATIC || !!feedback)\n .map(({ block }) => block!);\n }\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private location: Location,\n protected accountService: AccountService,\n protected assessmentsService: TextAssessmentService,\n protected jhiAlertService: JhiAlertService,\n protected structuredGradingCriterionService: StructuredGradingCriterionService,\n ) {\n super(jhiAlertService, accountService, assessmentsService, structuredGradingCriterionService);\n const state = router.getCurrentNavigation()?.extras.state as { submission: TextSubmission };\n this.leftFeedbackId = Number(activatedRoute.snapshot.paramMap.get('feedbackId'));\n this.leftSubmission = state?.submission;\n this.exercise = this.leftSubmission?.participation?.exercise as TextExercise;\n this.leftTextBlockRefs = [];\n this.leftUnusedTextBlockRefs = [];\n this.rightTextBlockRefs = [];\n this.rightUnusedTextBlockRefs = [];\n this.feedbackConflicts = [];\n }\n\n /**\n * Handles the resizable layout on the right hand side. Adapted from:\n * @see resizeable-container.component.ts\n */\n ngAfterViewInit() {\n interact('.movable')\n .resizable({\n edges: { left: '.draggable-left', right: false, bottom: false, top: false },\n modifiers: [\n // Set maximum width\n interact.modifiers!.restrictSize({\n min: { width: 500, height: 0 },\n max: { width: 750, height: 2000 },\n }),\n ],\n inertia: true,\n })\n .on('resizestart', (event: any) => {\n event.target.classList.add('card-resizable');\n })\n .on('resizeend', (event: any) => {\n event.target.classList.remove('card-resizable');\n })\n .on('resizemove', (event: any) => {\n const target = event.target;\n target.style.width = event.rect.width + 'px';\n });\n }\n\n async ngOnInit() {\n await super.ngOnInit();\n if (!this.leftSubmission) {\n const submissionId = Number(this.activatedRoute.snapshot.paramMap.get('submissionId'));\n const participation = await this.assessmentsService.getFeedbackDataForExerciseSubmission(submissionId).toPromise();\n this.leftSubmission = participation.submissions![0];\n setLatestSubmissionResult(this.leftSubmission, getLatestSubmissionResult(this.leftSubmission));\n this.exercise = participation.exercise as TextExercise;\n }\n this.activatedRoute.data.subscribe(({ conflictingTextSubmissions }) => this.setPropertiesFromServerResponse(conflictingTextSubmissions));\n }\n\n private setPropertiesFromServerResponse(conflictingTextSubmissions: TextSubmission[]) {\n if (!this.leftSubmission) {\n return;\n }\n\n this.conflictingSubmissions = conflictingTextSubmissions;\n conflictingTextSubmissions.forEach((submission) => setLatestSubmissionResult(submission, getLatestSubmissionResult(submission)));\n this.prepareTextBlocksAndFeedbackFor(this.leftSubmission!, this.leftTextBlockRefs, this.leftUnusedTextBlockRefs);\n this.leftTotalScore = this.computeTotalScore(this.leftSubmission!.latestResult?.feedbacks!);\n this.setConflictingSubmission(0);\n }\n\n private setConflictingSubmission(index: number) {\n this.rightSubmission = this.conflictingSubmissions ? this.conflictingSubmissions[index] : undefined;\n if (this.rightSubmission) {\n this.prepareTextBlocksAndFeedbackFor(this.rightSubmission!, this.rightTextBlockRefs, this.rightUnusedTextBlockRefs);\n this.rightTotalScore = this.computeTotalScore(getLatestSubmissionResult(this.rightSubmission)!.feedbacks!);\n this.feedbackConflicts = getLatestSubmissionResult(this.leftSubmission)!.feedbacks!.find((f) => f.id === this.leftFeedbackId)?.conflictingTextAssessments || [];\n }\n }\n\n /**\n * Changes the displayed submission in the right text assessment area.\n * @param conflictIndex\n */\n didChangeConflictIndex(conflictIndex: number) {\n this.rightUnusedTextBlockRefs = [];\n this.rightTextBlockRefs = [];\n this.feedbackConflicts = [];\n this.selectedRightFeedbackId = undefined;\n this.isMarkingDisabled = true;\n this.setConflictingSubmission(conflictIndex - 1);\n }\n\n /**\n * Checks if the current user is the assessor of the passed result.\n * Passed result could be belong to left or right submission\n *\n * @param result - result to check its assessor\n */\n isAssessor(result: Result): boolean {\n return result?.assessor?.id === this.userId;\n }\n\n /**\n * Checks if the current user can override the submission.\n * Only possible if the user is an instructor for the exercise or\n * If s/he is an assessor of the submission and it is still before assessment due date.\n *\n * @param result - result to check override access\n */\n canOverride(result: Result): boolean {\n if (this.exercise) {\n if (this.isAtLeastInstructor) {\n // Instructors can override any assessment at any time.\n return true;\n }\n let isBeforeAssessmentDueDate = true;\n // Add check as the assessmentDueDate must not be set for exercises\n if (this.exercise.assessmentDueDate) {\n isBeforeAssessmentDueDate = moment().isBefore(this.exercise.assessmentDueDate!);\n }\n // tutors are allowed to override one of their assessments before the assessment due date.\n return this.isAssessor(result) && isBeforeAssessmentDueDate;\n }\n return false;\n }\n\n /**\n * submits the left submission\n */\n overrideLeftSubmission() {\n if (!this.leftSubmission || !this.leftSubmission!.latestResult || !this.leftSubmission!.latestResult!.id || this.overrideBusy) {\n return;\n }\n\n this.overrideBusy = true;\n this.assessmentsService\n .submit(this.exercise!.id!, this.leftSubmission!.latestResult!.id!, this.leftSubmission!.latestResult!.feedbacks!, this.textBlocksWithFeedbackForLeftSubmission)\n .subscribe(\n (response) => this.handleSaveOrSubmitSuccessWithAlert(response, 'artemisApp.textAssessment.submitSuccessful'),\n (error: HttpErrorResponse) => this.handleError(error),\n );\n }\n\n /**\n * if the there is a change in left text block (one with the conflicts), total score is calculated again and\n * override button is enabled.\n */\n leftTextBlockRefsChange(): void {\n this.leftTotalScore = this.computeTotalScore(this.leftSubmission!.latestResult?.feedbacks!);\n this.isOverrideDisabled = false;\n }\n\n /**\n * selects and unselects one of the right conflicting feedback\n * @param rightFeedbackId - feedback id to un/select\n */\n didSelectConflictingFeedback(rightFeedbackId: number): void {\n this.selectedRightFeedbackId = rightFeedbackId !== this.selectedRightFeedbackId ? rightFeedbackId : undefined;\n this.isMarkingDisabled = !this.selectedRightFeedbackId;\n }\n\n /**\n * Finds the feedback conflict id based on the selected conflicting right feedback's id and calls the service function to solve conflict.\n */\n discardConflict(): void {\n if (this.markBusy || !this.selectedRightFeedbackId) {\n return;\n }\n\n const feedbackConflictId = this.feedbackConflicts.find((feedbackConflict) => feedbackConflict.conflictingFeedbackId === this.selectedRightFeedbackId)?.id;\n\n if (!feedbackConflictId || !this.exercise) {\n return;\n }\n\n this.markBusy = true;\n this.assessmentsService.solveFeedbackConflict(this.exercise!.id!, feedbackConflictId).subscribe(\n (response) => this.handleSolveConflictsSuccessWithAlert(response, 'artemisApp.textAssessment.solveFeedbackConflictSuccessful'),\n (error) => this.handleSolveConflictsError(error),\n );\n }\n\n private prepareTextBlocksAndFeedbackFor(submission: TextSubmission, textBlockRefs: TextBlockRef[], unusedTextBlockRefs: TextBlockRef[]): void {\n const feedbackList = submission.latestResult?.feedbacks || [];\n const matchBlocksWithFeedbacks = TextAssessmentService.matchBlocksWithFeedbacks(submission?.blocks || [], feedbackList);\n this.sortAndSetTextBlockRefs(matchBlocksWithFeedbacks, textBlockRefs, unusedTextBlockRefs, submission);\n }\n\n protected handleSaveOrSubmitSuccessWithAlert(response: HttpResponse<Result>, translationKey: string): void {\n super.handleSaveOrSubmitSuccessWithAlert(response, translationKey);\n this.overrideBusy = false;\n this.isOverrideDisabled = true;\n this.location.back();\n }\n\n private handleSolveConflictsSuccessWithAlert(response: FeedbackConflict, translationKey: string): void {\n this.jhiAlertService.success(translationKey);\n this.markBusy = false;\n this.isMarkingDisabled = true;\n this.location.back();\n }\n\n protected handleError(error: HttpErrorResponse): void {\n super.handleError(error);\n this.overrideBusy = false;\n this.isOverrideDisabled = true;\n }\n\n private handleSolveConflictsError(error: HttpErrorResponse): void {\n super.handleError(error);\n this.markBusy = false;\n this.isMarkingDisabled = true;\n }\n\n didClickedButtonNoConflict() {\n this.location.back();\n }\n}\n" }, { "alpha_fraction": 0.6159539222717285, "alphanum_fraction": 0.6175987124443054, "avg_line_length": 49.66666793823242, "blob_id": "9a648b844c193e92b8e79ff51ebb7841d9a25916", "content_id": "c7c3237935932ded6ae4e9bc84a17bcf79553add", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1216, "license_type": "permissive", "max_line_length": 161, "num_lines": 24, "path": "/src/main/webapp/app/shared/pipes/artemis-duration.pipe.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Pipe, PipeTransform } from '@angular/core';\nimport * as moment from 'moment';\n\n@Pipe({ name: 'durationTo' })\nexport class DurationPipe implements PipeTransform {\n /**\n * Calculate the duration of an event from the diff of two dates.\n * @param startDate The start date time of the event. Must be convertible to moment().\n * @param endDate The end date time of the event. Must be convertible to moment().\n * @returns string 'HH:mm'\n */\n transform(startDate: Date | moment.Moment | string | number | null | undefined, endDate: Date | moment.Moment | string | number | null | undefined): string {\n if (!endDate || !moment(endDate).isValid() || !startDate || !moment(startDate).isValid()) {\n return '';\n }\n if (moment(endDate).diff(startDate, 'hours') < 24) {\n return moment.utc(moment(endDate, 'DD/MM/YYYY HH:mm:ss').diff(moment(startDate, 'DD/MM/YYYY HH:mm'))).format('HH:mm');\n } else {\n const ms = moment(endDate, 'DD/MM/YYYY HH:mm:ss').diff(moment(startDate, 'DD/MM/YYYY HH:mm:ss'));\n const d = moment.duration(ms);\n return Math.floor(d.asHours()) + moment.utc(ms).format(':mm');\n }\n }\n}\n" }, { "alpha_fraction": 0.5642561912536621, "alphanum_fraction": 0.5669421553611755, "avg_line_length": 50.48936080932617, "blob_id": "ef80466168a24861fe84f038ee3f21f64d130f8f", "content_id": "f3c24b52cbb25e84519b095059250e6c2894e94b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4840, "license_type": "permissive", "max_line_length": 174, "num_lines": 94, "path": "/src/test/javascript/spec/component/shared/grading-instructions-details.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { GradingInstructionsDetailsComponent } from 'app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { GradingCriterion } from 'app/exercises/shared/structured-grading-criterion/grading-criterion.model';\nimport { GradingInstruction } from 'app/exercises/shared/structured-grading-criterion/grading-instruction.model';\n\ndescribe('Grading Instructions Management Component', () => {\n let comp: GradingInstructionsDetailsComponent;\n let fixture: ComponentFixture<GradingInstructionsDetailsComponent>;\n const gradingInstruction = { id: 1, credits: 1, gradingScale: 'scale', instructionDescription: 'description', feedback: 'feedback', usageCount: 0 } as GradingInstruction;\n const gradingCriterion = { id: 1, title: 'testCriteria', structuredGradingInstructions: [gradingInstruction] } as GradingCriterion;\n const exercise = { id: 1 } as Exercise;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [GradingInstructionsDetailsComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n })\n .overrideTemplate(GradingInstructionsDetailsComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(GradingInstructionsDetailsComponent);\n comp = fixture.componentInstance;\n comp.exercise = exercise;\n });\n\n describe('OnInit', function () {\n it('should Set the default grading criteria', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n\n // THEN\n expect(comp.questionEditorText).toEqual(\n '[gradingInstruction]\\n' +\n '\\t[credits] 0\\n' +\n '\\t[gradingScale] Add instruction grading scale here (only visible for tutors)\\n' +\n '\\t[description] Add grading instruction here (only visible for tutors)\\n' +\n '\\t[feedback] Add feedback for students here (visible for students)\\n' +\n '\\t[maxCountInScore] 0\\n' +\n '\\n' +\n '[gradingCriterion]This is an Example criterion\\n' +\n '\\t[gradingInstruction]\\n' +\n '\\t[credits] 0\\n' +\n '\\t[gradingScale] Add instruction grading scale here (only visible for tutors)\\n' +\n '\\t[description] Add grading instruction here (only visible for tutors)\\n' +\n '\\t[feedback] Add feedback for students here (visible for students)\\n' +\n '\\t[maxCountInScore] 0\\n' +\n '\\n' +\n '[gradingInstruction]\\n' +\n '\\t[credits] 0\\n' +\n '\\t[gradingScale] Add instruction grading scale here (only visible for tutors)\\n' +\n '\\t[description] Add grading instruction here (only visible for tutors)\\n' +\n '\\t[feedback] Add feedback for students here (visible for students)\\n' +\n '\\t[maxCountInScore] 0\\n' +\n '\\n',\n );\n }));\n it('should set the grading criteria based on the exercise', fakeAsync(() => {\n comp.exercise.gradingCriteria = [gradingCriterion];\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.questionEditorText).toEqual(\n '[gradingCriterion]' +\n 'testCriteria' +\n '\\n' +\n '\\t' +\n '[gradingInstruction]\\n' +\n '\\t' +\n '[credits]' +\n ' 1\\n' +\n '\\t' +\n '[gradingScale] scale\\n' +\n '\\t' +\n '[description] description\\n' +\n '\\t' +\n '[feedback] feedback\\n' +\n '\\t' +\n '[maxCountInScore] 0\\n\\n',\n );\n }));\n });\n});\n" }, { "alpha_fraction": 0.7057180404663086, "alphanum_fraction": 0.7077707648277283, "avg_line_length": 50.251625061035156, "blob_id": "a50c2509bf041d377fbcb21248968e4eb20443c2", "content_id": "6ca02bdeeb2f44e6455b0c0d5f5656bea9498972", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 47254, "license_type": "permissive", "max_line_length": 184, "num_lines": 922, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ExamResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.service.util.TimeLogUtil.formatDurationFrom;\nimport static de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException.NOT_ALLOWED;\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\nimport static java.time.ZonedDateTime.now;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.*;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.core.io.InputStreamResource;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.MediaType;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.domain.participation.TutorParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.dto.StudentDTO;\nimport de.tum.in.www1.artemis.service.exam.*;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService;\nimport de.tum.in.www1.artemis.web.rest.dto.*;\nimport de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\n\n/**\n * REST controller for managing Exam.\n */\n@RestController\n@RequestMapping(\"/api\")\npublic class ExamResource {\n\n private final Logger log = LoggerFactory.getLogger(ExamResource.class);\n\n private static final String ENTITY_NAME = \"exam\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final UserRepository userRepository;\n\n private final CourseRepository courseRepository;\n\n private final ExamService examService;\n\n private final ExamDateService examDateService;\n\n private final ExamRegistrationService examRegistrationService;\n\n private final ExamRepository examRepository;\n\n private final ExamAccessService examAccessService;\n\n private final SubmissionService submissionService;\n\n private final InstanceMessageSendService instanceMessageSendService;\n\n private final AuthorizationCheckService authCheckService;\n\n private final TutorParticipationService tutorParticipationService;\n\n private final AssessmentDashboardService assessmentDashboardService;\n\n private final StudentExamRepository studentExamRepository;\n\n public ExamResource(UserRepository userRepository, CourseRepository courseRepository, ExamService examService, ExamAccessService examAccessService,\n InstanceMessageSendService instanceMessageSendService, ExamRepository examRepository, SubmissionService submissionService, AuthorizationCheckService authCheckService,\n ExamDateService examDateService, TutorParticipationService tutorParticipationService, AssessmentDashboardService assessmentDashboardService,\n ExamRegistrationService examRegistrationService, StudentExamRepository studentExamRepository) {\n this.userRepository = userRepository;\n this.courseRepository = courseRepository;\n this.examService = examService;\n this.submissionService = submissionService;\n this.examDateService = examDateService;\n this.examRegistrationService = examRegistrationService;\n this.examRepository = examRepository;\n this.examAccessService = examAccessService;\n this.instanceMessageSendService = instanceMessageSendService;\n this.authCheckService = authCheckService;\n this.tutorParticipationService = tutorParticipationService;\n this.assessmentDashboardService = assessmentDashboardService;\n this.studentExamRepository = studentExamRepository;\n }\n\n /**\n * POST /courses/{courseId}/exams : Create a new exam.\n *\n * @param courseId the course to which the exam belongs\n * @param exam the exam to create\n * @return the ResponseEntity with status 201 (Created) and with body the new exam, or with status 400 (Bad Request) if the exam has already an ID\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PostMapping(\"/courses/{courseId}/exams\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Exam> createExam(@PathVariable Long courseId, @RequestBody Exam exam) throws URISyntaxException {\n log.debug(\"REST request to create an exam : {}\", exam);\n if (exam.getId() != null) {\n throw new BadRequestAlertException(\"A new exam cannot already have an ID\", ENTITY_NAME, \"idexists\");\n }\n\n if (exam.getCourse() == null) {\n return conflict();\n }\n\n if (!exam.getCourse().getId().equals(courseId)) {\n return conflict();\n }\n\n if (exam.getVisibleDate() == null || exam.getStartDate() == null || exam.getEndDate() == null || !exam.getVisibleDate().isBefore(exam.getStartDate())\n || !exam.getStartDate().isBefore(exam.getEndDate())) {\n return conflict();\n }\n\n // Check that exerciseGroups are not set to prevent manipulation of associated exerciseGroups\n if (!exam.getExerciseGroups().isEmpty()) {\n return forbidden();\n }\n\n Optional<ResponseEntity<Exam>> courseAccessFailure = examAccessService.checkCourseAccessForInstructor(courseId);\n if (courseAccessFailure.isPresent()) {\n return courseAccessFailure.get();\n }\n\n Exam result = examRepository.save(exam);\n return ResponseEntity.created(new URI(\"/api/courses/\" + courseId + \"/exams/\" + result.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getTitle())).body(result);\n }\n\n /**\n * PUT /courses/{courseId}/exams : Updates an existing exam.\n * This route does not save changes to the exercise groups. This should be done via the ExerciseGroupResource.\n *\n * @param courseId the course to which the exam belongs\n * @param updatedExam the exam to update\n * @return the ResponseEntity with status 200 (OK) and with body the updated exam\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PutMapping(\"/courses/{courseId}/exams\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Exam> updateExam(@PathVariable Long courseId, @RequestBody Exam updatedExam) throws URISyntaxException {\n log.debug(\"REST request to update an exam : {}\", updatedExam);\n if (updatedExam.getId() == null) {\n return createExam(courseId, updatedExam);\n }\n\n if (updatedExam.getCourse() == null) {\n return conflict();\n }\n\n if (!updatedExam.getCourse().getId().equals(courseId)) {\n return conflict();\n }\n\n if (updatedExam.getVisibleDate() == null || updatedExam.getStartDate() == null || updatedExam.getEndDate() == null\n || !updatedExam.getVisibleDate().isBefore(updatedExam.getStartDate()) || !updatedExam.getStartDate().isBefore(updatedExam.getEndDate())) {\n return conflict();\n }\n\n Optional<ResponseEntity<Exam>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, updatedExam.getId());\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n // Make sure that the original references are preserved.\n Exam originalExam = examRepository.findByIdElseThrow(updatedExam.getId());\n\n // NOTE: Make sure that all references are preserved here\n updatedExam.setExerciseGroups(originalExam.getExerciseGroups());\n updatedExam.setStudentExams(originalExam.getStudentExams());\n updatedExam.setRegisteredUsers(originalExam.getRegisteredUsers());\n\n Exam result = examRepository.save(updatedExam);\n\n // We can't test dates for equality as the dates retrieved from the database lose precision. Also use instant to take timezones into account\n Comparator<ZonedDateTime> comparator = Comparator.comparing(date -> date.truncatedTo(ChronoUnit.SECONDS).toInstant());\n if (comparator.compare(originalExam.getVisibleDate(), updatedExam.getVisibleDate()) != 0\n || comparator.compare(originalExam.getStartDate(), updatedExam.getStartDate()) != 0) {\n // get all exercises\n Exam examWithExercises = examService.findByIdWithExerciseGroupsAndExercisesElseThrow(result.getId());\n // for all programming exercises in the exam, send their ids for scheduling\n examWithExercises.getExerciseGroups().stream().flatMap(group -> group.getExercises().stream()).filter(exercise -> exercise instanceof ProgrammingExercise)\n .map(Exercise::getId).forEach(instanceMessageSendService::sendProgrammingExerciseSchedule);\n }\n\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, result.getTitle())).body(result);\n }\n\n /**\n * GET /courses/{courseId}/exams/{examId} : Find an exam by id.\n *\n * @param courseId the course to which the exam belongs\n * @param examId the exam to find\n * @param withStudents boolean flag whether to include all students registered for the exam\n * @param withExerciseGroups boolean flag whether to include all exercise groups of the exam\n * @return the ResponseEntity with status 200 (OK) and with the found exam as body\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Exam> getExam(@PathVariable Long courseId, @PathVariable Long examId, @RequestParam(defaultValue = \"false\") boolean withStudents,\n @RequestParam(defaultValue = \"false\") boolean withExerciseGroups) {\n log.debug(\"REST request to get exam : {}\", examId);\n Optional<ResponseEntity<Exam>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n if (!withStudents && !withExerciseGroups) {\n return ResponseEntity.ok(examRepository.findByIdElseThrow(examId));\n }\n if (withExerciseGroups) {\n Exam exam;\n if (withStudents) {\n exam = examRepository.findByIdWithRegisteredUsersExerciseGroupsAndExercisesElseThrow(examId);\n }\n else {\n exam = examService.findByIdWithExerciseGroupsAndExercisesElseThrow(examId);\n }\n examService.setExamExerciseProperties(exam);\n return ResponseEntity.ok(exam);\n }\n Exam exam = examRepository.findByIdWithRegisteredUsersElseThrow(examId);\n examRepository.setNumberOfRegisteredUsersForExams(Collections.singletonList(exam));\n\n exam.getRegisteredUsers().forEach(user -> user.setVisibleRegistrationNumber(user.getRegistrationNumber()));\n return ResponseEntity.ok(exam);\n }\n\n /**\n * GET /exams/{examId}/title : Returns the title of the exam with the given id\n *\n * @param examId the id of the exam\n * @return the title of the exam wrapped in an ResponseEntity or 404 Not Found if no exam with that id exists\n */\n @GetMapping(value = \"/exams/{examId}/title\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<String> getExamTitle(@PathVariable Long examId) {\n final var title = examRepository.getExamTitle(examId);\n return title == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(title);\n }\n\n /**\n * GET /courses/{courseId}/exams/{examId} : Find an exam by id.\n *\n * @param courseId the course to which the exam belongs\n * @param examId the exam to find\n * @return the ResponseEntity with status 200 (OK) and with the found exam as body\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/statistics\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<ExamChecklistDTO> getExamStatistics(@PathVariable Long courseId, @PathVariable Long examId) {\n log.debug(\"REST request to get exam statistics: {}\", examId);\n Optional<ResponseEntity<ExamChecklistDTO>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n Exam exam = examRepository.findByIdWithRegisteredUsersExerciseGroupsAndExercisesElseThrow(examId);\n ExamChecklistDTO examChecklistDTO = examService.getStatsForChecklist(exam);\n\n return ResponseEntity.ok(examChecklistDTO);\n }\n\n /**\n * GET /courses/{courseId}/exams/{examId}/scores : Find scores for an exam by id.\n *\n * @param courseId the course to which the exam belongs\n * @param examId the exam to find\n * @return the ResponseEntity with status 200 (OK) and with the found ExamScoreDTO as body\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/scores\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<ExamScoresDTO> getExamScore(@PathVariable Long courseId, @PathVariable Long examId) {\n long start = System.currentTimeMillis();\n log.debug(\"REST request to get score for exam : {}\", examId);\n Optional<ResponseEntity<ExamScoresDTO>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n ExamScoresDTO examScoresDTO = examService.calculateExamScores(examId);\n log.info(\"get scores for exam {} took {}ms\", examId, System.currentTimeMillis() - start);\n return ResponseEntity.ok(examScoresDTO);\n }\n\n /**\n * GET /courses/:courseId/exams/:examId/exam-for-assessment-dashboard\n *\n * @param courseId the id of the course to retrieve\n * @param examId the id of the exam that contains the exercises\n * @return data about a course including all exercises, plus some data for the tutor as tutor status for assessment\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/exam-for-assessment-dashboard\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Exam> getExamForAssessmentDashboard(@PathVariable long courseId, @PathVariable long examId) {\n log.debug(\"REST request /courses/{courseId}/exams/{examId}/exam-for-assessment-dashboard\");\n\n Exam exam = examService.findByIdWithExerciseGroupsAndExercisesElseThrow(examId);\n Course course = exam.getCourse();\n if (!course.getId().equals(courseId)) {\n return conflict();\n }\n\n User user = userRepository.getUserWithGroupsAndAuthorities();\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.TEACHING_ASSISTANT, course, user);\n\n if (ZonedDateTime.now().isBefore(exam.getEndDate()) && authCheckService.isTeachingAssistantInCourse(course, user)) {\n // tutors cannot access the exercises before the exam ends\n return forbidden();\n }\n\n Set<Exercise> exercises = new HashSet<>();\n // extract all exercises for all the exam\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n exerciseGroup.setExercises(courseRepository.getInterestingExercisesForAssessmentDashboards(exerciseGroup.getExercises()));\n exercises.addAll(exerciseGroup.getExercises());\n }\n\n List<TutorParticipation> tutorParticipations = tutorParticipationService.findAllByCourseAndTutor(course, user);\n assessmentDashboardService.generateStatisticsForExercisesForAssessmentDashboard(exercises, tutorParticipations, true);\n\n return ResponseEntity.ok(exam);\n }\n\n /**\n * GET /courses/:courseId/exams/:examId/exam-for-test-run-assessment-dashboard\n *\n * @param courseId the id of the course to retrieve\n * @param examId the id of the exam that contains the exercises\n * @return data about a exam test run including all exercises, plus some data for the tutor as tutor status for assessment\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/exam-for-test-run-assessment-dashboard\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Exam> getExamForTestRunAssessmentDashboard(@PathVariable long courseId, @PathVariable long examId) {\n log.debug(\"REST request /courses/{courseId}/exams/{examId}/exam-for-test-run-assessment-dashboard\");\n\n Exam exam = examService.findByIdWithExerciseGroupsAndExercisesElseThrow(examId);\n Course course = exam.getCourse();\n if (!course.getId().equals(courseId)) {\n return conflict();\n }\n\n User user = userRepository.getUserWithGroupsAndAuthorities();\n\n if (!authCheckService.isAtLeastInstructorInCourse(course, user)) {\n return forbidden();\n }\n\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n exerciseGroup.setExercises(courseRepository.getInterestingExercisesForAssessmentDashboards(exerciseGroup.getExercises()));\n }\n\n return ResponseEntity.ok(exam);\n }\n\n /**\n * GET /courses/:courseId/exams/:examId/stats-for-exam-assessment-dashboard A collection of useful statistics for the tutor course dashboard,\n * including: - number of submissions to the course - number of assessments - number of assessments assessed by the tutor - number of complaints\n *\n * @param courseId - the id of the course\n * @param examId - the id of the exam to retrieve stats from\n * @return data about a course including all exercises, plus some data for the tutor as tutor status for assessment\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/stats-for-exam-assessment-dashboard\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<StatsForDashboardDTO> getStatsForExamAssessmentDashboard(@PathVariable Long courseId, @PathVariable Long examId) {\n log.debug(\"REST request /courses/{courseId}/stats-for-exam-assessment-dashboard\");\n\n Course course = courseRepository.findByIdElseThrow(courseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n if (!authCheckService.isAtLeastTeachingAssistantInCourse(course, user)) {\n return forbidden();\n }\n return ResponseEntity.ok(examService.getStatsForExamAssessmentDashboard(course, examId));\n }\n\n /**\n * GET /courses/{courseId}/exams : Find all exams for the given course.\n *\n * @param courseId the course to which the exam belongs\n * @return the ResponseEntity with status 200 (OK) and a list of exams. The list can be empty\n */\n @GetMapping(\"/courses/{courseId}/exams\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<List<Exam>> getExamsForCourse(@PathVariable Long courseId) {\n log.debug(\"REST request to get all exams for Course : {}\", courseId);\n Optional<ResponseEntity<List<Exam>>> courseAccessFailure = examAccessService.checkCourseAccessForTeachingAssistant(courseId);\n return courseAccessFailure.orElseGet(() -> {\n List<Exam> exams = examRepository.findByCourseId(courseId);\n examRepository.setNumberOfRegisteredUsersForExams(exams);\n return ResponseEntity.ok(exams);\n });\n }\n\n /**\n * GET /courses/{courseId}/exams-for-user : Find all exams the user is allowed to access (Is at least Instructor)\n *\n * @param courseId the course to which the exam belongs\n * @return the ResponseEntity with status 200 (OK) and a list of exams. The list can be empty\n */\n @GetMapping(\"/courses/{courseId}/exams-for-user\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<Exam>> getExamsForUser(@PathVariable Long courseId) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n if (authCheckService.isAdmin(user)) {\n return ResponseEntity.ok(examRepository.findAllWithQuizExercisesWithEagerExerciseGroupsAndExercises());\n }\n else {\n Course course = courseRepository.findByIdElseThrow(courseId);\n if (!authCheckService.isAtLeastInstructorInCourse(course, user)) {\n return forbidden();\n }\n var userGroups = new ArrayList<>(user.getGroups());\n return ResponseEntity.ok(examRepository.getExamsWithQuizExercisesForWhichUserHasInstructorAccess(userGroups));\n }\n }\n\n /**\n * GET /exams/upcoming : Find all current and upcoming exams.\n *\n * @return the ResponseEntity with status 200 (OK) and a list of exams.\n */\n @GetMapping(\"/courses/upcoming-exams\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<List<Exam>> getCurrentAndUpcomingExams() {\n log.debug(\"REST request to get all upcoming exams\");\n\n if (!authCheckService.isAdmin()) {\n return forbidden();\n }\n\n List<Exam> upcomingExams = examRepository.findAllCurrentAndUpcomingExams();\n return ResponseEntity.ok(upcomingExams);\n }\n\n /**\n * DELETE /courses/{courseId}/exams/{examId} : Delete the exam with the given id.\n * The delete operation cascades to all student exams, exercise group, exercises and their participations.\n *\n * @param courseId the course to which the exam belongs\n * @param examId the id of the exam to delete\n * @return the ResponseEntity with status 200 (OK)\n */\n @DeleteMapping(\"/courses/{courseId}/exams/{examId}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> deleteExam(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to delete exam : {}\", examId);\n var exam = examRepository.findByIdElseThrow(examId);\n Optional<ResponseEntity<Void>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n examService.delete(examId);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, exam.getTitle())).build();\n }\n\n /**\n * POST /courses/:courseId/exams/:examId/students/:studentLogin : Add one single given user (based on the login) to the students of the exam so that the student can access the exam\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @param studentLogin the login of the user who should get student access\n * @return empty ResponseEntity with status 200 (OK) or with status 404 (Not Found)\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/students/{studentLogin:\" + Constants.LOGIN_REGEX + \"}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> addStudentToExam(@PathVariable Long courseId, @PathVariable Long examId, @PathVariable String studentLogin) {\n log.debug(\"REST request to add {} as student to exam : {}\", studentLogin, examId);\n\n Optional<ResponseEntity<Void>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n var course = courseRepository.findByIdElseThrow(courseId);\n var exam = examRepository.findByIdWithRegisteredUsersElseThrow(examId);\n\n Optional<User> student = userRepository.findOneWithGroupsAndAuthoritiesByLogin(studentLogin);\n if (student.isEmpty()) {\n return notFound();\n }\n\n if (student.get().getGroups().contains(exam.getCourse().getInstructorGroupName()) || authCheckService.isAdmin(student.get())) {\n return forbidden(\"exam\", \"cannotRegisterInstructor\", \"You cannot register instructors or administrators to exams.\");\n }\n\n examRegistrationService.registerStudentToExam(course, exam, student.get());\n return ResponseEntity.ok().body(null);\n }\n\n /**\n * POST /courses/:courseId/exams/:examId/generate-student-exams : Generates the student exams randomly based on the exam configuration and the exercise groups\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @return the list of student exams with their corresponding users\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/generate-student-exams\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<StudentExam>> generateStudentExams(@PathVariable Long courseId, @PathVariable Long examId) {\n long start = System.nanoTime();\n log.info(\"REST request to generate student exams for exam {}\", examId);\n final Exam exam = examRepository.findByIdWithRegisteredUsersExerciseGroupsAndExercisesElseThrow(examId);\n\n Optional<ResponseEntity<List<StudentExam>>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, exam);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n // Validate settings of the exam\n examService.validateForStudentExamGeneration(exam);\n\n examService.combineTemplateCommitsOfAllProgrammingExercisesInExam(exam);\n\n List<StudentExam> studentExams = studentExamRepository.generateStudentExams(exam);\n\n // we need to break a cycle for the serialization\n for (StudentExam studentExam : studentExams) {\n studentExam.getExam().setRegisteredUsers(null);\n studentExam.getExam().setExerciseGroups(null);\n studentExam.getExam().setStudentExams(null);\n }\n log.info(\"Generated {} student exams in {} for exam {}\", studentExams.size(), formatDurationFrom(start), examId);\n return ResponseEntity.ok().body(studentExams);\n }\n\n /**\n * POST /courses/:courseId/exams/:examId/generate-missing-student-exams:\n * Generates exams for students, who don't have an individual exam yet.\n * They are created randomly based on the exam configuration and the exercise groups.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @return the list of student exams with their corresponding users\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/generate-missing-student-exams\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<StudentExam>> generateMissingStudentExams(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to generate missing student exams for exam {}\", examId);\n\n final Exam exam = examRepository.findByIdWithRegisteredUsersExerciseGroupsAndExercisesElseThrow(examId);\n\n Optional<ResponseEntity<List<StudentExam>>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n // Validate settings of the exam\n examService.validateForStudentExamGeneration(exam);\n\n List<StudentExam> studentExams = studentExamRepository.generateMissingStudentExams(exam);\n\n // we need to break a cycle for the serialization\n for (StudentExam studentExam : studentExams) {\n studentExam.getExam().setRegisteredUsers(null);\n studentExam.getExam().setExerciseGroups(null);\n studentExam.getExam().setStudentExams(null);\n }\n\n log.info(\"Generated {} missing student exams for exam {}\", studentExams.size(), examId);\n return ResponseEntity.ok().body(studentExams);\n }\n\n /**\n * POST /courses/{courseId}/exams/{examId}/student-exams/evaluate-quiz-exercises : Evaluate the quiz exercises of the exam\n *\n * @param courseId the course to which the exam belongs to\n * @param examId the id of the exam\n * @return ResponseEntity the number of evaluated quiz exercises\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/student-exams/evaluate-quiz-exercises\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Integer> evaluateQuizExercises(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to evaluate quiz exercises of exam {}\", examId);\n\n Optional<ResponseEntity<Integer>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent())\n return courseAndExamAccessFailure.get();\n\n if (examDateService.getLatestIndividualExamEndDate(examId).isAfter(ZonedDateTime.now())) {\n // Quizzes should only be evaluated if no exams are running\n return forbidden(applicationName, ENTITY_NAME, \"quizevaluationPendingExams\",\n \"There are still exams running, quizzes can only be evaluated once all exams are finished.\");\n }\n\n Integer numOfEvaluatedExercises = examService.evaluateQuizExercises(examId);\n\n log.info(\"Evaluated {} quiz exercises of exam {}\", numOfEvaluatedExercises, examId);\n\n return ResponseEntity.ok().body(numOfEvaluatedExercises);\n }\n\n /**\n * POST /courses/{courseId}/exams/{examId}/student-exams/unlock-all-repositories : Unlock all repositories of the exam\n *\n * @param courseId the course to which the exam belongs to\n * @param examId the id of the exam\n * @return the number of unlocked exercises\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/student-exams/unlock-all-repositories\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Integer> unlockAllRepositories(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to unlock all repositories of exam {}\", examId);\n\n Optional<ResponseEntity<Integer>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent())\n return courseAndExamAccessFailure.get();\n\n Integer numOfUnlockedExercises = examService.unlockAllRepositories(examId);\n\n log.info(\"Unlocked {} programming exercises of exam {}\", numOfUnlockedExercises, examId);\n\n return ResponseEntity.ok().body(numOfUnlockedExercises);\n }\n\n /**\n * POST /courses/{courseId}/exams/{examId}/student-exams/lock-all-repositories : Lock all repositories of the exam\n *\n * @param courseId the course to which the exam belongs to\n * @param examId the id of the exam\n * @return the number of locked exercises\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/student-exams/lock-all-repositories\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Integer> lockAllRepositories(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to lock all repositories of exam {}\", examId);\n\n Optional<ResponseEntity<Integer>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n Integer numOfLockedExercises = examService.lockAllRepositories(examId);\n\n log.info(\"Locked {} programming exercises of exam {}\", numOfLockedExercises, examId);\n\n return ResponseEntity.ok().body(numOfLockedExercises);\n }\n\n /**\n * POST /courses/:courseId/exams/:examId/students : Add multiple users to the students of the exam so that they can access the exam\n * The passed list of UserDTOs must include the registration number (the other entries are currently ignored and can be left out)\n * Note: registration based on other user attributes (e.g. email, name, login) is currently NOT supported\n *\n * This method first tries to find the student in the internal Artemis user database (because the user is most probably already using Artemis).\n * In case the user cannot be found, we additionally search the (TUM) LDAP in case it is configured properly.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @param studentDtos the list of students (with at least registration number) who should get access to the exam\n * @return the list of students who could not be registered for the exam, because they could NOT be found in the Artemis database and could NOT be found in the TUM LDAP\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/students\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<StudentDTO>> addStudentsToExam(@PathVariable Long courseId, @PathVariable Long examId, @RequestBody List<StudentDTO> studentDtos) {\n log.debug(\"REST request to add {} as students to exam {}\", studentDtos, examId);\n\n Optional<ResponseEntity<List<StudentDTO>>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n List<StudentDTO> notFoundStudentsDtos = examRegistrationService.registerStudentsForExam(courseId, examId, studentDtos);\n return ResponseEntity.ok().body(notFoundStudentsDtos);\n }\n\n /**\n * POST /courses/:courseId/exams/:examId/register-course-students : Add all users which are enrolled in the course to the exam so that the student can access the exam\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @return empty ResponseEntity with status 200 (OK) or with status 404 (Not Found)\n */\n @PostMapping(value = \"/courses/{courseId}/exams/{examId}/register-course-students\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> registerCourseStudents(@PathVariable Long courseId, @PathVariable Long examId) {\n // get all students enrolled in the course\n log.debug(\"REST request to add all students to exam {} with courseId {}\", examId, courseId);\n\n Optional<ResponseEntity<Void>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent())\n return courseAndExamAccessFailure.get();\n\n examRegistrationService.addAllStudentsOfCourseToExam(courseId, examId);\n return ResponseEntity.ok().body(null);\n }\n\n /**\n * DELETE /courses/:courseId/exams/:examId/students/:studentLogin :\n * Remove one single given user (based on the login) from the students of the exam so that the student cannot access the exam any more.\n * Optionally, also deletes participations and submissions of the student in the student exam.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @param studentLogin the login of the user who should lose student access\n * @param withParticipationsAndSubmission request param deciding whether participations and submissions should also be deleted\n * @return empty ResponseEntity with status 200 (OK) or with status 404 (Not Found)\n */\n @DeleteMapping(value = \"/courses/{courseId}/exams/{examId}/students/{studentLogin:\" + Constants.LOGIN_REGEX + \"}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> removeStudentFromExam(@PathVariable Long courseId, @PathVariable Long examId, @PathVariable String studentLogin,\n @RequestParam(defaultValue = \"false\") boolean withParticipationsAndSubmission) {\n log.debug(\"REST request to remove {} as student from exam : {}\", studentLogin, examId);\n\n Optional<ResponseEntity<Void>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n Optional<User> optionalStudent = userRepository.findOneWithGroupsAndAuthoritiesByLogin(studentLogin);\n if (optionalStudent.isEmpty()) {\n return notFound();\n }\n\n examRegistrationService.unregisterStudentFromExam(examId, withParticipationsAndSubmission, optionalStudent.get());\n return ResponseEntity.ok().body(null);\n }\n\n /**\n * DELETE /courses/{courseId}/exams/{examId}/allstudents :\n * Remove all students of the exam so that they cannot access the exam any more.\n * Optionally, also deletes participations and submissions of all students in their student exams.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @param withParticipationsAndSubmission request param deciding whether participations and submissions should also be deleted\n *\n * @return empty ResponseEntity with status 200 (OK) or with status 404 (Not Found)\n */\n @DeleteMapping(value = \"/courses/{courseId}/exams/{examId}/students\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> removeAllStudentsFromExam(@PathVariable Long courseId, @PathVariable Long examId,\n @RequestParam(defaultValue = \"false\") boolean withParticipationsAndSubmission) {\n log.debug(\"REST request to remove all students from exam {} with courseId {}\", examId, courseId);\n\n Optional<ResponseEntity<Void>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n examRegistrationService.unregisterAllStudentFromExam(examId, withParticipationsAndSubmission);\n return ResponseEntity.ok().body(null);\n }\n\n /**\n * GET /courses/{courseId}/exams/{examId}/start : Get an exam for the exam start.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @return the ResponseEntity with status 200 (OK) and with the found student exam (without exercises) as body\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/start\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentExam> getStudentExamForStart(@PathVariable Long courseId, @PathVariable Long examId) {\n log.debug(\"REST request to get exam {} for conduction\", examId);\n return examAccessService.checkAndGetCourseAndExamAccessForConduction(courseId, examId);\n }\n\n /**\n * PUT /courses/:courseId/exams/:examId/exercise-groups-order : Update the order of exercise groups. If the received\n * exercise groups do not belong to the exam the operation is aborted.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @param orderedExerciseGroups the exercise groups of the exam in the desired order.\n * @return the list of exercise groups\n */\n @PutMapping(\"/courses/{courseId}/exams/{examId}/exercise-groups-order\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<ExerciseGroup>> updateOrderOfExerciseGroups(@PathVariable Long courseId, @PathVariable Long examId,\n @RequestBody List<ExerciseGroup> orderedExerciseGroups) {\n log.debug(\"REST request to update the order of exercise groups of exam : {}\", examId);\n\n Optional<ResponseEntity<List<ExerciseGroup>>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure.get();\n }\n\n Exam exam = examRepository.findByIdWithExerciseGroupsElseThrow(examId);\n\n // Ensure that exactly as many exercise groups have been received as are currently related to the exam\n if (orderedExerciseGroups.size() != exam.getExerciseGroups().size()) {\n return forbidden();\n }\n\n // Ensure that all received exercise groups are already related to the exam\n for (ExerciseGroup exerciseGroup : orderedExerciseGroups) {\n if (!exam.getExerciseGroups().contains(exerciseGroup)) {\n return forbidden();\n }\n // Set the exam manually as it won't be included in orderedExerciseGroups\n exerciseGroup.setExam(exam);\n }\n\n exam.setExerciseGroups(orderedExerciseGroups);\n examRepository.save(exam);\n\n // Return the original request body as it might contain exercise details (e.g. quiz questions), which would be lost otherwise\n return ResponseEntity.ok(orderedExerciseGroups);\n }\n\n /**\n * GET /courses/{courseId}/exams/{examId}/latest-end-date : Get an exam for conduction.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam\n * @return the ResponseEntity with status 200 (OK) and with the found exam as body or NotFound if it culd not be\n * determined\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/latest-end-date\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<ExamInformationDTO> getLatestIndividualEndDateOfExam(@PathVariable Long courseId, @PathVariable Long examId) {\n log.debug(\"REST request to get latest individual end date of exam : {}\", examId);\n Optional<ResponseEntity<ExamInformationDTO>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForTeachingAssistant(courseId, examId);\n var examInformation = new ExamInformationDTO(examDateService.getLatestIndividualExamEndDate(examId));\n return courseAndExamAccessFailure.orElseGet(() -> ResponseEntity.ok().body(examInformation));\n }\n\n /**\n * GET /courses/:courseId/exams/:examId/lockedSubmissions Get locked submissions for exam for user\n *\n * @param courseId - the id of the course\n * @param examId - the id of the exam\n * @return the ResponseEntity with status 200 (OK) and with body the course, or with status 404 (Not Found)\n * @throws AccessForbiddenException if the current user doesn't have the permission to access the course\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/lockedSubmissions\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<List<Submission>> getLockedSubmissionsForExam(@PathVariable Long courseId, @PathVariable Long examId) throws AccessForbiddenException {\n log.debug(\"REST request to get all locked submissions for course : {}\", courseId);\n long start = System.currentTimeMillis();\n Course course = courseRepository.findWithEagerExercisesById(courseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n if (!authCheckService.isAtLeastInstructorInCourse(course, user)) {\n throw new AccessForbiddenException(NOT_ALLOWED);\n }\n\n List<Submission> submissions = submissionService.getLockedSubmissions(examId, user);\n\n long end = System.currentTimeMillis();\n log.debug(\"Finished /courses/{}/submissions call in {}ms\", courseId, end - start);\n return ResponseEntity.ok(submissions);\n }\n\n /**\n * PUT /courses/{courseId}/exams/{examId}/archive : archive an existing exam asynchronously.\n *\n * This method starts the process of archiving all exam exercises and submissions.\n * It immediately returns and runs this task asynchronously. When the task is done, the exam is marked as archived, which means the zip file can be downloaded.\n *\n * @param courseId the id of the course\n * @param examId the id of the exam to archive\n * @return empty\n */\n @PutMapping(\"/courses/{courseId}/exams/{examId}/archive\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> archiveExam(@PathVariable Long courseId, @PathVariable Long examId) {\n log.info(\"REST request to archive exam : {}\", examId);\n\n final Exam exam = examRepository.findOneWithEagerExercisesGroupsAndStudentExams(examId);\n if (exam == null) {\n return notFound();\n }\n\n Optional<ResponseEntity<Exam>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return forbidden();\n }\n\n // Archiving an exam is only possible after the exam is over\n if (now().isBefore(exam.getEndDate())) {\n throw new BadRequestAlertException(\"You cannot archive an exam that is not over.\", ENTITY_NAME, \"examNotOver\", true);\n }\n\n examService.archiveExam(exam);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, examId.toString())).build();\n }\n\n /**\n * Downloads the zip file of the archived exam if it exists. Throws a 404 if the exam doesn't exist.\n *\n * @param courseId The course id of the course\n * @param examId The id of the archived exam\n * @return ResponseEntity with status\n */\n @GetMapping(\"/courses/{courseId}/exams/{examId}/download-archive\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Resource> downloadExamArchive(@PathVariable Long courseId, @PathVariable Long examId) throws FileNotFoundException, EntityNotFoundException {\n log.info(\"REST request to download archive of exam : {}\", examId);\n final Exam exam = examRepository.findByIdElseThrow(examId);\n\n Optional<ResponseEntity<Exam>> courseAndExamAccessFailure = examAccessService.checkCourseAndExamAccessForInstructor(courseId, examId);\n if (courseAndExamAccessFailure.isPresent()) {\n return forbidden();\n }\n\n if (!exam.hasExamArchive()) {\n return notFound();\n }\n\n // The path is stored in the course table\n File zipFile = new File(exam.getExamArchivePath());\n InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));\n return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header(\"filename\", zipFile.getName()).body(resource);\n }\n\n}\n" }, { "alpha_fraction": 0.5427408218383789, "alphanum_fraction": 0.5481682419776917, "avg_line_length": 37.78947448730469, "blob_id": "6ec23a54be0403ec9119a4d80592e726fe28bd1b", "content_id": "677617e35ba6f6c11ff827235fb46e61e478ca17", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1474, "license_type": "permissive", "max_line_length": 177, "num_lines": 38, "path": "/src/main/webapp/app/shared/chart/presets/horizontalStackedBarChartPreset.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChartComponent, ChartPreset } from 'app/shared/chart/chart.component';\nimport { ChartData, ChartTooltipItem } from 'chart.js';\nimport { Label } from 'ng2-charts';\n\nexport class HorizontalStackedBarChartPreset implements ChartPreset {\n private readonly labels: Label[];\n private readonly totalText: string[];\n\n constructor(labels: Label[], totalText: string[]) {\n this.labels = labels;\n this.totalText = totalText;\n }\n\n applyTo(chart: ChartComponent): void {\n const preset = this;\n\n chart.setType('horizontalBar');\n chart.setLabels(this.labels);\n chart.setYAxe(0, { stacked: true }, false);\n chart.setXAxe(0, { stacked: true, ticks: { min: 0, stepSize: 25, callback: (value) => value + '%' } }, false);\n chart.setHover({ mode: 'dataset' });\n chart.setTooltip(\n {\n mode: 'dataset',\n position: 'nearest',\n callbacks: {\n title(items: ChartTooltipItem[], data: ChartData) {\n return data.datasets![items[0].datasetIndex!].label!;\n },\n label(item: ChartTooltipItem, data: ChartData) {\n return item.yLabel + ': ' + (data.datasets![item.datasetIndex!].data![item.index!] as number).toFixed(2) + '% of ' + preset.totalText[item.index!] + '.';\n },\n },\n },\n false,\n );\n }\n}\n" }, { "alpha_fraction": 0.7117646932601929, "alphanum_fraction": 0.7176470756530762, "avg_line_length": 20.25, "blob_id": "f3966a9e7c57ed97964f454a5c6ffffb710b4a43", "content_id": "fddd7a4da70200a1aedc4e56a486e7401f70e1b7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 170, "license_type": "permissive", "max_line_length": 48, "num_lines": 8, "path": "/src/main/java/de/tum/in/www1/artemis/exception/NetworkingError.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.exception;\n\npublic class NetworkingError extends Exception {\n\n public NetworkingError(String message) {\n super(message);\n }\n}\n" }, { "alpha_fraction": 0.6787942051887512, "alphanum_fraction": 0.6819126605987549, "avg_line_length": 43.74418640136719, "blob_id": "d08c1c111f44a09760edc4b461e814fb407680f4", "content_id": "2e1d02b0da31e68021a48f97fbdae830abe7e858", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1924, "license_type": "permissive", "max_line_length": 175, "num_lines": 43, "path": "/src/main/webapp/app/shared/layouts/main/main.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRouteSnapshot, NavigationEnd, NavigationError, Router } from '@angular/router';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { SentryErrorHandler } from 'app/core/sentry/sentry.error-handler';\n\n@Component({\n selector: 'jhi-main',\n templateUrl: './main.component.html',\n})\nexport class JhiMainComponent implements OnInit {\n constructor(private jhiLanguageHelper: JhiLanguageHelper, private router: Router, private profileService: ProfileService, private sentryErrorHandler: SentryErrorHandler) {\n this.setupErrorHandling().then(null);\n }\n\n private async setupErrorHandling() {\n this.profileService.getProfileInfo().subscribe((profileInfo: ProfileInfo) => {\n // sentry is only activated if it was specified in the application.yml file\n this.sentryErrorHandler.initSentry(profileInfo);\n });\n }\n\n private getPageTitle(routeSnapshot: ActivatedRouteSnapshot) {\n let title: string = routeSnapshot.data && routeSnapshot.data['pageTitle'] ? routeSnapshot.data['pageTitle'] : 'artemisApp';\n if (routeSnapshot.firstChild) {\n title = this.getPageTitle(routeSnapshot.firstChild) || title;\n }\n return title;\n }\n\n ngOnInit() {\n this.router.events.subscribe((event) => {\n if (event instanceof NavigationEnd) {\n this.jhiLanguageHelper.updateTitle(this.getPageTitle(this.router.routerState.snapshot.root));\n }\n if (event instanceof NavigationError && event.error.status === 404) {\n // noinspection JSIgnoredPromiseFromCall\n this.router.navigate(['/404']);\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.6649050712585449, "alphanum_fraction": 0.6767957806587219, "avg_line_length": 39.28291320800781, "blob_id": "bad5a74d0f97b4575e55cfefbb12ac4fd8433044", "content_id": "9ce7f0bddbfbed1a7a12f2e6d8d544459b79c1ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 14460, "license_type": "permissive", "max_line_length": 301, "num_lines": 357, "path": "/docs/dev/setup/bamboo-bitbucket-jira.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Setup for Programming Exercises with Bamboo, Bitbucket and Jira\n===============================================================\n\nThis page describes how to set up a programming exercise environment\nbased on Bamboo, Bitbucket and Jira.\n\n| Please note that this setup will create a deployment that is very\n similiar to the one used in production but has one difference:\n| In production, the builds are performed within Docker containers that\n are created by Bamboo (or its build agents). As we run Bamboo in a\n Docker container in this setup, creating new Docker containers within\n that container is not recommended (e.g. see `this\n article <https://itnext.io/docker-in-docker-521958d34efd>`__). There\n are some solution where one can pass the Docker socket to the Bamboo\n container, but none of these approachs work quite well here as Bamboo\n uses mounted directories that cause issues.\n\nTherefore, a check is included within the BambooBuildPlanService that\nensures that builds are not started in Docker agents if the development\nsetup is present.\n\n**Prerequisites:**\n\n* `Docker <https://docs.docker.com/install>`__\n* `Docker-Compose <https://docs.docker.com/compose/install/>`__\n\n\n.. contents:: Content of this document\n :local:\n :depth: 1\n\nDocker-Compose\n--------------\n\nBefore you start the docker-compose, check if the bamboo version in the\n``build.gradle`` (search for ``com.atlassian.bamboo:bamboo-specs``) is\nequal to the bamboo version number in the Dockerfile of bamboo stored in\n``src/main/docker/bamboo/Dockerfile`` or ``src/main/docker/bamboo/swift/Dockerfile``.\nIf the version number is not equal adjust the version number in the Dockerfile.\n\nIn case you want to enable Swift programming exercises, you need to change\nthe specified Dockerfile in the docker-compose file ``atlassian.yml`` stored in ``src/main/docker``.\nTo use the Swift Dockerfile, change the following:\n\n ::\n\n bamboo:\n container_name: artemis_bamboo\n build: bamboo\n\nto:\n\n ::\n\n bamboo:\n container_name: artemis_bamboo\n build: bamboo/swift\n\nExecute the docker-compose file e.g. with\n``docker-compose -f src/main/docker/atlassian.yml up -d``\n\nError Handling: It can happen that there is an overload with other\ndocker networks\n``ERROR: Pool overlaps with other one on this address space``. Use the\ncommand ``docker network prune`` to resolve this issue.\n\nMake also sure that docker has enough memory (~ 6GB). To adapt it, go to ``Preferecences -> Resources``\n\nConfigure Bamboo, Bitbucket and Jira\n------------------------------------\n\nBy default, the Jira instance is reachable under ``localhost:8081``, the\nBamboo instance under ``localhost:8085`` and the Bitbucket instance\nunder ``localhost:7990``.\n\n**Get evaluation licenses for Atlassian products:** `Atlassian Licenses <https://my.atlassian.com/license/evaluation>`__\n\n1. Get licenses for Bamboo, Bitbucket and Jira Service Management.\n\n - Bamboo: Select Bamboo (Server) and ``not installed yet``\n - Bitbucket: Select Bitbucket (Data Center) and ``not installed yet``\n - Jira: Select Jira Service Management (Data Center) and ``not installed yet``\n\n2. Provide the just created license key during the setup and create an admin user with the same credentials in all 3 applications.\n Also, you can select the evaluation/internal/test/dev setups if you are asked.\n Follow the additional steps for Jira and Bitbucket.\n\n - Jira:\n\n - On startup select ``I'll set it up myself``\n - Select Build In Database Connection\n - Create a sample project\n\n - Bitbucket: Do not connect Bitbucket with Jira yet\n\n3. Execute the shell script ``atlassian-setup.sh`` in the\n ``src/main/docker`` directory (e.g. with\n ``src/main/docker/./atlassian-setup.sh``). This script creates\n groups, users ([STRIKEOUT:and adds them to the created groups] NOT\n YET) and disabled application links between the 3 applications. Make sure that `xdg-utils <https://www.howtoinstall.me/ubuntu/18-04/xdg-utils/>`__ is installed before running the script.\n\n4. Enable the created `application\n links <https://confluence.atlassian.com/doc/linking-to-another-application-360677690.html>`__\n between all 3 application (OAuth Impersonate). The links should open automatically after the shell script\n has finished. If not open them manually:\n\n - Bitbucket: http://localhost:7990/plugins/servlet/applinks/listApplicationLinks\n - Bamboo: http://localhost:8085/plugins/servlet/applinks/listApplicationLinks\n - Jira: http://localhost:8081/plugins/servlet/applinks/listApplicationLinks\n\n **You manually have to adjust the Display URL for the Bamboo → Bitbucket AND\n Bitbucket → Bamboo URl to** ``http://localhost:7990`` **and**\n ``http://localhost:8085`` **.**\n\n **Bamboo:**\n\n .. figure:: bamboo-bitbucket-jira/bamboo_bitbucket_applicationLink.png\n :align: center\n\n Bamboo → Bitbucket\n\n .. figure:: bamboo-bitbucket-jira/bamboo_jira_applicationLink.png\n :align: center\n\n Bamboo → Jira\n\n\n **Bitbucket:**\n\n .. figure:: bamboo-bitbucket-jira/bitbucket_bamboo_applicationLink.png\n :align: center\n\n Bitbucket → Bamboo\n\n .. figure:: bamboo-bitbucket-jira/bitbucket_jira_applicationLink.png\n :align: center\n\n Bitbucket → Jira\n\n **Jira:**\n\n .. figure:: bamboo-bitbucket-jira/jira_bamboo_applicationLink.png\n :align: center\n\n Jira → Bamboo\n\n .. figure:: bamboo-bitbucket-jira/jira_bitbucket_applicationLink.png\n :align: center\n\n Jira → Bitbucket\n\n5. The script has already created users and groups but you need to\n manually assign the users into their respective group in Jira. In our\n test setup, users 1-5 are students, 6-10 are tutors and 11-15 are\n instructors. The usernames are artemis_test_user_{1-15} and the\n password is again the username. When you create a course in artemis\n you have to manually choose the created groups(students, tutors,\n instructors).\n\n6. Use the `user directories in\n Jira <https://confluence.atlassian.com/adminjiraserver/allowing-connections-to-jira-for-user-management-938847045.html>`__\n to synchronize the users in bitbucket and bamboo:\n\n - Go to Jira → User management → Jira user server → Add application →\n Create one application for bitbucket and one for bamboo → add the\n IP-address ``0.0.0.0/0`` to IP Addresses\n\n .. figure:: bamboo-bitbucket-jira/jira_add_application.png\n :align: center\n\n\n - Go to Bitbucket and Bamboo → User Directories → Add Directories →\n Atlassian Crowd → use the URL ``http://jira:8080`` as Server URL →\n use the application name and password which you used in the previous\n step. Also, you should decrease the synchronisation period (e.g. to 2\n minutes). Press synchronise after adding the directory, the users and\n groups should now be available.\n\n .. figure:: bamboo-bitbucket-jira/user_directories.png\n :align: center\n\n7. In Bamboo create a global variable named\n SERVER_PLUGIN_SECRET_PASSWORD, the value of this variable will be used\n as the secret. The value of this variable should be then stored in\n ``src/main/resources/config/application-artemis.yml`` as the value of\n ``artemis-authentication-token-value``.\n\n8. Download the\n `bamboo-server-notifaction-plugin <https://github.com/ls1intum/bamboo-server-notification-plugin/releases>`__\n and add it to bamboo. Go to Bamboo → Manage apps → Upload app → select\n the downloaded .jar file → Upload\n\n9. Add Maven and JDK:\n\n - Go to Bamboo → Server capabilities → Add capabilities menu →\n Capability type ``Executable`` → select type ``Maven 3.x`` → insert\n ``Maven 3`` as executable label → insert ``/artemis`` as path.\n\n - Add capabilities menu → Capability type ``JDK`` → insert ``JDK15``\n as JDK label → insert ``/usr/lib/jvm/java-15-oracle`` as Java home.\n\n10. Generate a personal access token\n\n While username and password can still be used as a fallback, this option is already marked as deprecated and will\n be removed in the future.\n\n 9.1 Personal access token for Bamboo.\n\n - Log in as the admin user and go to Bamboo -> Profile (top right corner) -> Personal access tokens -> Create token\n\n .. figure:: bamboo-bitbucket-jira/bamboo-create-token.png\n :align: center\n\n - Insert the generated token into the file ``application-artemis.yml`` in the section ``continuous-integration``:\n\n .. code:: yaml\n\n artemis:\n continuous-integration:\n user: <username>\n password: <password>\n token: #insert the token here\n\n 9.2 Personal access token for Bitbucket.\n\n - Log in as the admin user and go to Bitbucket -> View Profile (top right corner) -> Manage account -> Personal access tokens -> Create token\n\n .. figure:: bamboo-bitbucket-jira/bitbucket-create-token.png\n :align: center\n\n - Insert the generated token into the file ``application-artemis.yml`` in the section ``version-control``:\n\n .. code:: yaml\n\n artemis:\n version-control:\n user: <username>\n password: <password>\n token: #insert the token here\n\n11. Disable XSRF checking\n Although XSRF checking is highly recommended, we currently have to disable it as Artemis does not yet support\n sending the required headers.\n\n - Log in as the admin user go to Bamboo -> Overview -> Security Settings\n\n Edit the settings and disable XSRF checking:\n\n .. figure:: bamboo-bitbucket-jira/bamboo_xsrf_disable.png\n :align: center\n\n12. Add a SSH key for the admin user\n\n Artemis can clone/push the repositories during setup and for the online code editor using SSH.\n If the SSH key is not present, the username + token will be used as fallback (and all git operations will use HTTP(S) instead of SSH).\n If the token is also not present, the username + password will be used as fallback (again, using HTTP(S)).\n\n You first have to create a SSH key (locally), e.g. using ``ssh-keygen`` (more information on how to create a SSH key can be found e.g. at `ssh.com <https://www.ssh.com/ssh/keygen/>`__ or at `atlassian.com <https://confluence.atlassian.com/bitbucketserver076/creating-ssh-keys-1026534841.html>`__).\n\n The list of supported ciphers can be found at `Apache Mina <https://github.com/apache/mina-sshd>`__.\n\n It is recommended to use a password to secure the private key, but it is not mandatory.\n\n Please note that the private key file **must** be named ``ìd_rsa``, ``id_dsa``, ``id_ecdsa`` or ``id_ed25519``, depending on the ciphers used.\n\n You now have to extract the public key and add it to Bitbucket.\n Open the public key file (usually called ``id_rsa.pub`` (when using RSA)) and copy it's content (you can also use ``cat id_rsa.pub`` to show the public key).\n\n Navigate to ``BITBUCKET-URL/plugins/servlet/ssh/account/keys`` and add the SSH key by pasting the content of the public key.\n\n ``<ssh-key-path>`` is the path to the folder containing the ``id_rsa`` file (but without the filename). It will be used in the configuration of Artemis to specify where Artemis should look for the key and store the ``known_hosts`` file.\n\n ``<ssh-private-key-password>`` is the password used to secure the private key. It is also needed for the configuration of Artemis, but can be omitted if no password was set (e.g. for development environments).\n\nConfigure Artemis\n-----------------\n\n1. Modify ``src/main/resources/config/application-artemis.yml``\n\n .. code:: yaml\n\n repo-clone-path: ./repos/\n repo-download-clone-path: ./repos-download/\n encryption-password: artemis-encrypt # arbitrary password for encrypting database values\n user-management:\n use-external: true\n external:\n url: http://localhost:8081\n user: <jira-admin-user>\n password: <jira-admin-password>\n admin-group-name: instructors\n internal-admin:\n username: artemis_admin\n password: artemis_admin\n version-control:\n url: http://localhost:7990\n user: <bitbucket-admin-user>\n password: <bitbuckt-admin-password>\n token: <bitbucket-admin-token>\n ssh-private-key-folder-path: <ssh-private-key-folder-path>\n ssh-private-key-password: <ssh-private-key-password>\n continuous-integration:\n url: http://localhost:8085\n user: <bamboo-admin-user>\n password: <bamboo-admin-password>\n token: <bamboo-admin-token>\n vcs-application-link-name: LS1 Bitbucket Server\n empty-commit-necessary: true\n artemis-authentication-token-value: <artemis-authentication-token-value>\n\n2. Modify the application-dev.yml\n\n .. code:: yaml\n\n server:\n port: 8080 # The port of artemis\n url: http://172.20.0.1:8080 # needs to be an ip\n // url: http://docker.for.mac.host.internal:8080 # If the above one does not work for mac try this one\n // url: http://host.docker.internal:8080 # If the above one does not work for windows try this one\n\nIn addition, you have to start Artemis with the profiles ``bamboo``,\n``bitbucket`` and ``jira`` so that the correct adapters will be used,\ne.g.:\n\n::\n\n --spring.profiles.active=dev,bamboo,bitbucket,jira,artemis,scheduling\n\nPlease read :doc:`../setup` for more details.\n\nHow to verify the connection works?\n-----------------------------------\n\nArtemis → Jira\n^^^^^^^^^^^^^^^\n\nYou can login to Artemis with the admin user you created in Jira\n\nArtemis → Bitbucket\n^^^^^^^^^^^^^^^^^^^^\nYou can create a programming exercise\n\nArtemis → Bamboo\n^^^^^^^^^^^^^^^^^\nYou can create a programming exercise\n\nBitbucket → Bamboo\n^^^^^^^^^^^^^^^^^^^\nThe build of the students repository gets started after pushing to it\n\nBitbucket → Artemis\n^^^^^^^^^^^^^^^^^^^^\nWhen using the code editor, after clicking on *Submit*, the text *Building and testing...* should appear.\n\nBamboo → Artemis\n^^^^^^^^^^^^^^^^^\nThe build result is displayed in the code editor.\n" }, { "alpha_fraction": 0.671935498714447, "alphanum_fraction": 0.671935498714447, "avg_line_length": 39.78947448730469, "blob_id": "cba5c8f228e532cccd78226b5d14e0b59f908de2", "content_id": "3f6797f9006850c9012e1cc22c4a73aea3daa63c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3100, "license_type": "permissive", "max_line_length": 148, "num_lines": 76, "path": "/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\n\nimport { ApollonDiagram } from 'app/entities/apollon-diagram.model';\nimport { createRequestOption } from 'app/shared/util/request-util';\n\nexport type EntityResponseType = HttpResponse<ApollonDiagram>;\n\n@Injectable({ providedIn: 'root' })\nexport class ApollonDiagramService {\n private resourceUrl = SERVER_API_URL + 'api';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Creates diagram.\n * @param apollonDiagram - apollonDiagram to be created.\n * @param courseId - id of the course.\n */\n create(apollonDiagram: ApollonDiagram, courseId: number): Observable<EntityResponseType> {\n const copy = this.convert(apollonDiagram);\n return this.http.post<ApollonDiagram>(`${this.resourceUrl}/course/${courseId}/apollon-diagrams`, copy, { observe: 'response' });\n }\n\n /**\n * Updates diagram.\n * @param apollonDiagram - apollonDiagram to be updated.\n * @param courseId - id of the course.\n */\n update(apollonDiagram: ApollonDiagram, courseId: number): Observable<EntityResponseType> {\n const copy = this.convert(apollonDiagram);\n return this.http.put<ApollonDiagram>(`${this.resourceUrl}/course/${courseId}/apollon-diagrams`, copy, { observe: 'response' });\n }\n\n /**\n * Finds diagram.\n * @param id - id of diagram to be found.\n * @param courseId - id of the course.\n */\n find(id: number, courseId: number): Observable<EntityResponseType> {\n return this.http.get<ApollonDiagram>(`${this.resourceUrl}/course/${courseId}/apollon-diagrams/${id}`, { observe: 'response' });\n }\n\n /**\n * Fetches the title of the diagram with the given id\n *\n * @param diagramId the id of the diagram\n * @return the title of the diagram in an HttpResponse, or an HttpErrorResponse on error\n */\n getTitle(diagramId: number): Observable<HttpResponse<string>> {\n return this.http.get(`${this.resourceUrl}/apollon-diagrams/${diagramId}/title`, { observe: 'response', responseType: 'text' });\n }\n\n /**\n * Deletes diagram with that id.\n * @param id - id of diagram to be deleted.\n * @param courseId - id of the course.\n */\n delete(id: number, courseId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/course/${courseId}/apollon-diagrams/${id}`, { observe: 'response' });\n }\n\n /**\n * Gets all apollon diagrams that belong to the course with the id courseId.\n */\n getDiagramsByCourse(courseId: number): Observable<HttpResponse<ApollonDiagram[]>> {\n const options = createRequestOption(courseId);\n return this.http.get<ApollonDiagram[]>(`${this.resourceUrl}/course/${courseId}/apollon-diagrams`, { params: options, observe: 'response' });\n }\n\n private convert(apollonDiagram: ApollonDiagram): ApollonDiagram {\n return Object.assign({}, apollonDiagram);\n }\n}\n" }, { "alpha_fraction": 0.6707592606544495, "alphanum_fraction": 0.6736671924591064, "avg_line_length": 49.32520294189453, "blob_id": "db65e7d5cbc9751b1c7e8582e6e56575e6c2ad84", "content_id": "71ec9b64f615ed5b872f51aee104f598f949948e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6190, "license_type": "permissive", "max_line_length": 176, "num_lines": 123, "path": "/src/test/javascript/spec/component/quiz-statistic/multiple-choice-question-statistic.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Course } from 'app/entities/course.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { of } from 'rxjs';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { MultipleChoiceQuestionStatisticComponent } from 'app/exercises/quiz/manage/statistics/multiple-choice-question-statistic/multiple-choice-question-statistic.component';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { MultipleChoiceQuestionStatistic } from 'app/entities/quiz/multiple-choice-question-statistic.model';\nimport { AnswerCounter } from 'app/entities/quiz/answer-counter.model';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\n\nconst route = { params: of({ courseId: 3, exerciseId: 22, questionId: 1 }) };\nconst answerOption1 = { id: 5 } as AnswerOption;\nconst answerCounter = { answer: answerOption1 } as AnswerCounter;\nconst questionStatistic = { answerCounters: [answerCounter] } as MultipleChoiceQuestionStatistic;\nconst question = { id: 1, answerOptions: [answerOption1], quizQuestionStatistic: questionStatistic } as MultipleChoiceQuestion;\nconst course = { id: 3 } as Course;\nlet quizExercise = { id: 22, started: true, course, quizQuestions: [question], adjustedDueDate: undefined } as QuizExercise;\n\ndescribe('QuizExercise Multiple Choice Question Statistic Component', () => {\n let comp: MultipleChoiceQuestionStatisticComponent;\n let fixture: ComponentFixture<MultipleChoiceQuestionStatisticComponent>;\n let quizService: QuizExerciseService;\n let accountService: AccountService;\n let accountSpy: jasmine.Spy;\n let quizServiceFindSpy: jasmine.Spy;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [MultipleChoiceQuestionStatisticComponent],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .overrideTemplate(MultipleChoiceQuestionStatisticComponent, '')\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(MultipleChoiceQuestionStatisticComponent);\n comp = fixture.componentInstance;\n quizService = fixture.debugElement.injector.get(QuizExerciseService);\n accountService = fixture.debugElement.injector.get(AccountService);\n quizServiceFindSpy = spyOn(quizService, 'find').and.returnValue(of(new HttpResponse({ body: quizExercise })));\n });\n });\n\n afterEach(() => {\n quizExercise = { id: 22, started: true, course, quizQuestions: [question], adjustedDueDate: undefined } as QuizExercise;\n });\n\n describe('OnInit', function () {\n it('should call functions on Init', () => {\n accountSpy = spyOn(accountService, 'hasAnyAuthorityDirect').and.returnValue(true);\n const loadQuizSpy = spyOn(comp, 'loadQuiz');\n comp.websocketChannelForData = '';\n\n comp.ngOnInit();\n\n expect(accountSpy).toHaveBeenCalled();\n expect(quizServiceFindSpy).toHaveBeenCalledWith(22);\n expect(loadQuizSpy).toHaveBeenCalledWith(quizExercise, false);\n expect(comp.websocketChannelForData).toEqual('/topic/statistic/22');\n });\n\n it('should not load Quiz if not authorised', () => {\n accountSpy = spyOn(accountService, 'hasAnyAuthorityDirect').and.returnValue(false);\n const loadQuizSpy = spyOn(comp, 'loadQuiz');\n\n comp.ngOnInit();\n\n expect(accountSpy).toHaveBeenCalled();\n expect(quizServiceFindSpy).not.toHaveBeenCalled();\n expect(loadQuizSpy).not.toHaveBeenCalled();\n });\n });\n\n describe('loadLayout', function () {\n it('should call functions from loadLayout', () => {\n accountSpy = spyOn(accountService, 'hasAnyAuthorityDirect').and.returnValue(true);\n const resetLabelsSpy = spyOn(comp, 'resetLabelsColors');\n const addLastBarSpy = spyOn(comp, 'addLastBarLayout');\n const loadInvalidLayoutSpy = spyOn(comp, 'loadInvalidLayout');\n const loadSolutionSpy = spyOn(comp, 'loadSolutionLayout');\n\n comp.ngOnInit();\n comp.loadLayout();\n\n expect(resetLabelsSpy).toHaveBeenCalled();\n expect(addLastBarSpy).toHaveBeenCalled();\n expect(loadInvalidLayoutSpy).toHaveBeenCalled();\n expect(loadSolutionSpy).toHaveBeenCalled();\n });\n });\n\n describe('loadData', function () {\n it('should call functions from loadData', () => {\n accountSpy = spyOn(accountService, 'hasAnyAuthorityDirect').and.returnValue(true);\n const resetDataSpy = spyOn(comp, 'resetData');\n const addDataSpy = spyOn(comp, 'addData');\n const updateDataSpy = spyOn(comp, 'updateData');\n\n comp.ngOnInit();\n comp.loadData();\n\n expect(resetDataSpy).toHaveBeenCalled();\n expect(addDataSpy).toHaveBeenCalled();\n expect(updateDataSpy).toHaveBeenCalled();\n });\n });\n});\n" }, { "alpha_fraction": 0.6294005513191223, "alphanum_fraction": 0.6310721635818481, "avg_line_length": 50.04266357421875, "blob_id": "2bfd088d140510c80144ac037259057d8d6e173e", "content_id": "d7a5e721f48ba1c06da8440fac514800b3daa03f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 29911, "license_type": "permissive", "max_line_length": 238, "num_lines": 586, "path": "/src/main/java/de/tum/in/www1/artemis/repository/StatisticsRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.time.*;\nimport java.time.temporal.ChronoUnit;\nimport java.time.temporal.TemporalField;\nimport java.time.temporal.WeekFields;\nimport java.util.*;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.enumeration.GraphType;\nimport de.tum.in.www1.artemis.domain.enumeration.SpanType;\nimport de.tum.in.www1.artemis.domain.statistics.CourseStatisticsAverageScore;\nimport de.tum.in.www1.artemis.domain.statistics.StatisticsEntry;\n\n/**\n * Spring Data JPA repository for the statistics pages\n */\n@Repository\npublic interface StatisticsRepository extends JpaRepository<User, Long> {\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n s.submissionDate,\n count(s.id)\n )\n from Submission s\n where s.submissionDate >= :#{#startDate} and s.submissionDate <= :#{#endDate} and (s.participation.exercise.exerciseGroup IS NOT NULL or exists (select c from Course c where s.participation.exercise.course.testCourse = false))\n group by s.submissionDate\n order by s.submissionDate asc\n \"\"\")\n List<StatisticsEntry> getTotalSubmissions(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n s.submissionDate,\n count(s.id)\n )\n from Submission s\n where s.submissionDate >= :#{#startDate} and s.submissionDate <= :#{#endDate} and s.participation.exercise.id in :exerciseIds\n group by s.submissionDate\n order by s.submissionDate asc\n \"\"\")\n List<StatisticsEntry> getTotalSubmissionsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n s.submissionDate, u.login\n )\n from User u, Submission s, StudentParticipation p\n where s.participation.id = p.id and p.student.id = u.id and s.submissionDate >= :#{#startDate} and s.submissionDate <= :#{#endDate} and u.login not like '%test%'\n and (s.participation.exercise.exerciseGroup IS NOT NULL or exists (select c from Course c where s.participation.exercise.course.testCourse = false))\n order by s.submissionDate asc\n \"\"\")\n List<StatisticsEntry> getActiveUsers(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n s.submissionDate, u.login\n )\n from User u, Submission s, StudentParticipation p\n where s.participation.id = p.id and p.student.id = u.id and s.submissionDate >= :#{#startDate} and s.submissionDate <= :#{#endDate} and u.login not like '%test%'\n and p.exercise.id in :exerciseIds\n order by s.submissionDate asc\n \"\"\")\n List<StatisticsEntry> getActiveUsersForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.releaseDate, count(e.id)\n )\n from Exercise e\n where e.releaseDate >= :#{#startDate} and e.releaseDate <= :#{#endDate} and e.course.testCourse = false\n group by e.releaseDate\n order by e.releaseDate asc\n \"\"\")\n List<StatisticsEntry> getReleasedExercises(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.releaseDate, count(e.id)\n )\n from Exercise e\n where e.releaseDate >= :#{#startDate} and e.releaseDate <= :#{#endDate} and e.id in :exerciseIds\n group by e.releaseDate\n order by e.releaseDate asc\n \"\"\")\n List<StatisticsEntry> getReleasedExercisesForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.dueDate, count(e.id)\n )\n from Exercise e\n where e.dueDate >= :#{#startDate} and e.dueDate <= :#{#endDate} and e.course.testCourse = false\n group by e.dueDate\n order by e.dueDate asc\n \"\"\")\n List<StatisticsEntry> getExercisesDue(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.dueDate, count(e.id)\n )\n from Exercise e\n where e.dueDate >= :#{#startDate} and e.dueDate <= :#{#endDate} and e.id in :exerciseIds\n group by e.dueDate\n order by e.dueDate asc\n \"\"\")\n List<StatisticsEntry> getExercisesDueForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n p.auditEventDate, u.login\n )\n from User u, PersistentAuditEvent p\n where u.login = p.principal and p.auditEventType = 'AUTHENTICATION_SUCCESS' and u.login not like '%test%' and p.auditEventDate >= :#{#startDate} and p.auditEventDate <= :#{#endDate}\n order by p.auditEventDate asc\n \"\"\")\n List<StatisticsEntry> getLoggedInUsers(@Param(\"startDate\") Instant startDate, @Param(\"endDate\") Instant endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, count(e.id)\n )\n from Exam e\n where e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.testCourse = false\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getConductedExams(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, count(e.id)\n )\n from Exam e\n where e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.id = :#{#courseId}\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getConductedExamsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate, @Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, count(se.id)\n )\n from StudentExam se, Exam e\n where se.submitted = true and se.exam = e and e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.testCourse = false\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getExamParticipations(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, count(se.id)\n )\n from StudentExam se, Exam e\n where se.submitted = true and se.exam = e and e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.id = :#{#courseId}\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getExamParticipationsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate, @Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, sum(size(e.registeredUsers))\n )\n from Exam e\n where e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.testCourse = false\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getExamRegistrations(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n e.endDate, sum(size(e.registeredUsers))\n )\n from Exam e\n where e.endDate >= :#{#startDate} and e.endDate <= :#{#endDate} and e.course.id = :#{#courseId}\n group by e.endDate\n order by e.endDate asc\n \"\"\")\n List<StatisticsEntry> getExamRegistrationsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate, @Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, r.assessor.login\n )\n from Result r\n where (r.assessmentType = 'MANUAL' or r.assessmentType = 'SEMI_AUTOMATIC') and r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and r.assessor.login not like '%test%'\n and (r.participation.exercise.exerciseGroup IS NOT NULL or exists (select c from Course c where r.participation.exercise.course.testCourse = false))\n \"\"\")\n List<StatisticsEntry> getActiveTutors(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, r.assessor.login\n )\n from Result r\n where (r.assessmentType = 'MANUAL' or r.assessmentType = 'SEMI_AUTOMATIC') and r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and r.assessor.login not like '%test%'\n and r.participation.exercise.id in :exerciseIds\n \"\"\")\n List<StatisticsEntry> getActiveTutorsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, count(r.id)\n )\n from Result r\n where r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and (r.participation.exercise.exerciseGroup IS NOT NULL or exists (select c from Course c where r.participation.exercise.course.testCourse = false))\n group by r.completionDate\n order by r.completionDate\n \"\"\")\n List<StatisticsEntry> getCreatedResults(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, count(r.id)\n )\n from Result r\n where r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and r.participation.exercise.id in :exerciseIds\n group by r.completionDate\n order by r.completionDate\n \"\"\")\n List<StatisticsEntry> getCreatedResultsForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, sum(size(r.feedbacks))\n )\n from Result r\n where r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and (r.participation.exercise.exerciseGroup IS NOT NULL or exists (select c from Course c where r.participation.exercise.course.testCourse = false))\n group by r.completionDate\n order by r.completionDate\n \"\"\")\n List<StatisticsEntry> getResultFeedbacks(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n r.completionDate, sum(size(r.feedbacks))\n )\n from Result r\n where r.completionDate >= :#{#startDate} and r.completionDate <= :#{#endDate} and r.participation.exercise.id in :exerciseIds\n group by r.completionDate\n order by r.completionDate\n \"\"\")\n List<StatisticsEntry> getResultFeedbacksForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate,\n @Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n sq.creationDate, count(sq.id)\n )\n from StudentQuestion sq left join sq.lecture lectures left join sq.exercise exercises\n where sq.creationDate >= :#{#startDate} and sq.creationDate <= :#{#endDate} and (lectures.course.id = :#{#courseId} or exercises.course.id = :#{#courseId})\n group by sq.creationDate\n order by sq.creationDate asc\n \"\"\")\n List<StatisticsEntry> getQuestionsAskedForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate, @Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.StatisticsEntry(\n a.answerDate, count(a.id)\n )\n from StudentQuestionAnswer a left join a.question question left join question.lecture lectures left join question.exercise exercises\n where a.answerDate >= :#{#startDate} and a.answerDate <= :#{#endDate} and (lectures.course.id = :#{#courseId} or exercises.course.id = :#{#courseId})\n group by a.answerDate\n order by a.answerDate asc\n \"\"\")\n List<StatisticsEntry> getQuestionsAnsweredForCourse(@Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate, @Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select e.id\n from Exercise e\n where e.course.id = :courseId\n \"\"\")\n List<Long> findExerciseIdsByCourseId(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select e\n from Exercise e\n where e.course.id = :courseId\n \"\"\")\n Set<Exercise> findExercisesByCourseId(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select\n new de.tum.in.www1.artemis.domain.statistics.CourseStatisticsAverageScore(\n p.exercise.id,\n p.exercise.title,\n avg(p.lastScore)\n )\n from ParticipantScore p\n where p.exercise IN :exercises\n group by p.exercise.id\n \"\"\")\n List<CourseStatisticsAverageScore> findAvgPointsForExercises(@Param(\"exercises\") Set<Exercise> exercises);\n\n /**\n * Gets the number of entries for the specific graphType and the span\n *\n * @param span the spanType for which the call is executed\n * @param startDate The startDate of which the data should be fetched\n * @param endDate The endDate of which the data should be fetched\n * @param graphType the type of graph the data should be fetched for (see GraphType.java)\n * @param courseId the courseId which is null for a user statistics call and contains the courseId for the course statistics\n * @return the return value of the processed database call which returns a list of entries\n */\n default List<StatisticsEntry> getNumberOfEntriesPerTimeSlot(SpanType span, ZonedDateTime startDate, ZonedDateTime endDate, GraphType graphType, Long courseId) {\n var exerciseIds = courseId != null ? findExerciseIdsByCourseId(courseId) : null;\n switch (graphType) {\n case SUBMISSIONS -> {\n return courseId == null ? getTotalSubmissions(startDate, endDate) : getTotalSubmissionsForCourse(startDate, endDate, exerciseIds);\n }\n case ACTIVE_USERS -> {\n List<StatisticsEntry> result = courseId == null ? getActiveUsers(startDate, endDate) : getActiveUsersForCourse(startDate, endDate, exerciseIds);\n return filterDuplicatedUsers(span, result, startDate, graphType);\n }\n case LOGGED_IN_USERS -> {\n Instant startDateInstant = startDate.toInstant();\n Instant endDateInstant = endDate.toInstant();\n List<StatisticsEntry> result = getLoggedInUsers(startDateInstant, endDateInstant);\n return filterDuplicatedUsers(span, result, startDate, graphType);\n }\n case RELEASED_EXERCISES -> {\n return courseId == null ? getReleasedExercises(startDate, endDate) : getReleasedExercisesForCourse(startDate, endDate, exerciseIds);\n }\n case EXERCISES_DUE -> {\n return courseId == null ? getExercisesDue(startDate, endDate) : getExercisesDueForCourse(startDate, endDate, exerciseIds);\n }\n case CONDUCTED_EXAMS -> {\n return courseId == null ? getConductedExams(startDate, endDate) : getConductedExamsForCourse(startDate, endDate, courseId);\n }\n case EXAM_PARTICIPATIONS -> {\n return courseId == null ? getExamParticipations(startDate, endDate) : getExamParticipationsForCourse(startDate, endDate, courseId);\n }\n case EXAM_REGISTRATIONS -> {\n return courseId == null ? getExamRegistrations(startDate, endDate) : getExamRegistrationsForCourse(startDate, endDate, courseId);\n }\n case ACTIVE_TUTORS -> {\n List<StatisticsEntry> result = courseId == null ? getActiveTutors(startDate, endDate) : getActiveTutorsForCourse(startDate, endDate, exerciseIds);\n return filterDuplicatedUsers(span, result, startDate, graphType);\n }\n case CREATED_RESULTS -> {\n return courseId == null ? getCreatedResults(startDate, endDate) : getCreatedResultsForCourse(startDate, endDate, exerciseIds);\n }\n case CREATED_FEEDBACKS -> {\n return courseId == null ? getResultFeedbacks(startDate, endDate) : getResultFeedbacksForCourse(startDate, endDate, exerciseIds);\n }\n case QUESTIONS_ASKED -> {\n return courseId != null ? getQuestionsAskedForCourse(startDate, endDate, courseId) : new ArrayList<>();\n }\n case QUESTIONS_ANSWERED -> {\n return courseId != null ? getQuestionsAnsweredForCourse(startDate, endDate, courseId) : new ArrayList<>();\n }\n default -> {\n return new ArrayList<>();\n }\n }\n }\n\n /**\n * This method handles the duplicity of usernames. It gets a List<StatisticsData> with set day values and set username values.\n * It then filters out all duplicated user entries per timeslot (depending on spanType) and return a list of entries\n * containing the amount of distinct users per timeslot\n *\n * @param span DAY,WEEK,MONTH or YEAR\n * @param result the result given by the Repository call\n * @param startDate the startDate of the period\n * @param graphType the graphType for which the List should be converted\n * @return A List<StatisticsData> with only distinct users per timeslot\n */\n private List<StatisticsEntry> filterDuplicatedUsers(SpanType span, List<StatisticsEntry> result, ZonedDateTime startDate, GraphType graphType) {\n Map<Object, List<String>> users = new HashMap<>();\n for (StatisticsEntry listElement : result) {\n Object index;\n ZonedDateTime date;\n if (graphType == GraphType.LOGGED_IN_USERS) {\n Instant instant = (Instant) listElement.getDay();\n date = instant.atZone(startDate.getZone());\n }\n else {\n date = (ZonedDateTime) listElement.getDay();\n }\n if (span == SpanType.DAY) {\n index = date.getHour();\n }\n else if (span == SpanType.WEEK || span == SpanType.MONTH) {\n index = date.withHour(0).withMinute(0).withSecond(0).withNano(0);\n }\n else if (span == SpanType.QUARTER) {\n index = getWeekOfDate(date);\n }\n else {\n index = date.getMonth();\n }\n String username = listElement.getUsername();\n List<String> usersInSameSlot = users.get(index);\n // if this index is not yet existing in users\n if (usersInSameSlot == null) {\n usersInSameSlot = new ArrayList<>();\n usersInSameSlot.add(username);\n users.put(index, usersInSameSlot);\n } // if the value of the map for this index does not contain this username\n else if (!usersInSameSlot.contains(username)) {\n usersInSameSlot.add(username);\n }\n }\n return mergeUsersPerTimeslotIntoList(users, span, startDate);\n }\n\n /**\n * Helper class for the filterDuplicatedUsers method, which takes the users in the same timeslot as well as some parameters needed\n * for calculation to convert these into a List<StatisticsData> which is then returned\n *\n * @param users a Map where a date gets mapped onto a list of users with entries on this date\n * @param span the spanType for which we created the users List\n * @param startDate the startDate which we need for mapping into timeslots\n * @return A List<StatisticsData> with no duplicated user per timeslot\n */\n private List<StatisticsEntry> mergeUsersPerTimeslotIntoList(Map<Object, List<String>> users, SpanType span, ZonedDateTime startDate) {\n List<StatisticsEntry> returnList = new ArrayList<>();\n users.forEach((timeslot, userList) -> {\n ZonedDateTime start;\n if (span == SpanType.DAY) {\n start = startDate.withHour((Integer) timeslot);\n }\n else if (span == SpanType.WEEK || span == SpanType.MONTH) {\n start = (ZonedDateTime) timeslot;\n }\n else if (span == SpanType.QUARTER) {\n int year = (Integer) timeslot < getWeekOfDate(startDate) ? startDate.getYear() + 1 : startDate.getYear();\n ZonedDateTime firstDateOfYear = ZonedDateTime.of(year, 1, 1, 0, 0, 0, 0, startDate.getZone());\n start = getWeekOfDate(firstDateOfYear) == 1 ? firstDateOfYear.plusWeeks(((Integer) timeslot) - 1) : firstDateOfYear.plusWeeks((Integer) timeslot);\n }\n else {\n start = startDate.withMonth(((Month) timeslot).getValue());\n }\n StatisticsEntry listElement = new StatisticsEntry(start, userList.size());\n returnList.add(listElement);\n });\n return returnList;\n }\n\n default Integer getWeekOfDate(ZonedDateTime date) {\n LocalDate localDate = date.toLocalDate();\n TemporalField weekOfYear = WeekFields.of(DayOfWeek.MONDAY, 4).weekOfWeekBasedYear();\n return localDate.get(weekOfYear);\n }\n\n /**\n * Gets a List<StatisticsData> each containing a date and an amount of entries. We take the amount of entries and\n * map it into a the results array based on the date of the entry. This method handles the spanType DAY\n *\n * @param outcome A List<StatisticsData>, each StatisticsData containing a date and the amount of entries for one timeslot\n * @param result the array in which the converted outcome should be inserted\n * @return an array, containing the values for each bar in the graph\n */\n default Integer[] mergeResultsIntoArrayForDay(List<StatisticsEntry> outcome, Integer[] result) {\n for (StatisticsEntry entry : outcome) {\n int hour = ((ZonedDateTime) entry.getDay()).getHour();\n int amount = (int) entry.getAmount();\n result[hour] += amount;\n }\n return result;\n }\n\n /**\n * Gets a List<StatisticsData> each containing a date and an amount of entries. We take the amount of entries and\n * map it into a the results array based on the date of the entry. This method handles the spanType WEEK\n *\n * @param outcome A List<StatisticsData>, each StatisticsData containing a date and the amount of entries for one timeslot\n * @param result the array in which the converted outcome should be inserted\n * @param startDate the startDate of the result array\n * @return an array, containing the values for each bar in the graph\n */\n default Integer[] mergeResultsIntoArrayForWeek(List<StatisticsEntry> outcome, Integer[] result, ZonedDateTime startDate) {\n for (StatisticsEntry entry : outcome) {\n ZonedDateTime date = (ZonedDateTime) entry.getDay();\n int amount = (int) entry.getAmount();\n int dayDifference = (int) ChronoUnit.DAYS.between(startDate, date);\n result[dayDifference] += amount;\n }\n return result;\n }\n\n /**\n * Gets a List<StatisticsData> each containing a date and an amount of entries. We take the amount of entries and\n * map it into a the results array based on the date of the entry. This method handles the spanType MONTH\n *\n * @param outcome A List<StatisticsData>, each StatisticsData containing a date and the amount of entries for one timeslot\n * @param result the array in which the converted outcome should be inserted\n * @param startDate the startDate of the result array\n * @return an array, containing the values for each bar in the graph\n */\n default Integer[] mergeResultsIntoArrayForMonth(List<StatisticsEntry> outcome, Integer[] result, ZonedDateTime startDate) {\n for (StatisticsEntry map : outcome) {\n ZonedDateTime date = (ZonedDateTime) map.getDay();\n int amount = (int) map.getAmount();\n int dayDifference = (int) ChronoUnit.DAYS.between(startDate, date);\n result[dayDifference] += amount;\n }\n return result;\n }\n\n /**\n * Gets a List<StatisticsData> each containing a date and an amount of entries. We take the amount of entries and\n * map it into a the results array based on the date of the entry. This method handles the spanType Quarter\n *\n * @param outcome A List<StatisticsData>, each StatisticsData containing a date and the amount of entries for one timeslot\n * @param result the array in which the converted outcome should be inserted\n * @param startDate the startDate of the result array\n * @return an array, containing the values for each bar in the graph\n */\n default Integer[] mergeResultsIntoArrayForQuarter(List<StatisticsEntry> outcome, Integer[] result, ZonedDateTime startDate) {\n for (StatisticsEntry map : outcome) {\n ZonedDateTime date = (ZonedDateTime) map.getDay();\n int amount = (int) map.getAmount();\n int dateWeek = getWeekOfDate(date);\n int startDateWeek = getWeekOfDate(startDate);\n int weeksDifference;\n // if the graph contains two different years\n weeksDifference = dateWeek < startDateWeek ? dateWeek + 53 - startDateWeek : dateWeek - startDateWeek;\n result[weeksDifference] += amount;\n\n }\n return result;\n }\n\n /**\n * Gets a List<StatisticsData> each containing a date and an amount of entries. We take the amount of entries and\n * map it into a the results array based on the date of the entry. This method handles the spanType YEAR\n *\n * @param outcome A List<StatisticsData>, each StatisticsData containing a date and the amount of entries for one timeslot\n * @param result the array in which the converted outcome should be inserted\n * @param startDate the startDate of the result array\n * @return an array, containing the values for each bar in the graph\n */\n default Integer[] mergeResultsIntoArrayForYear(List<StatisticsEntry> outcome, Integer[] result, ZonedDateTime startDate) {\n for (StatisticsEntry map : outcome) {\n ZonedDateTime date = (ZonedDateTime) map.getDay();\n int amount = (int) map.getAmount();\n int monthOfDate = date.getMonth().getValue();\n int monthOfStartDate = startDate.getMonth().getValue();\n result[(monthOfDate + monthOfStartDate + 2) % 12] += amount;\n }\n return result;\n }\n\n}\n" }, { "alpha_fraction": 0.6895430088043213, "alphanum_fraction": 0.6899495720863342, "avg_line_length": 42.7651252746582, "blob_id": "56a993fa7281882cbda638ca8a4f8bc79f7ec87e", "content_id": "86aa2da9af614b9b4a782fe518afd91f886f76f6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 12298, "license_type": "permissive", "max_line_length": 289, "num_lines": 281, "path": "/src/main/java/de/tum/in/www1/artemis/repository/CourseRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static de.tum.in.www1.artemis.domain.enumeration.AssessmentType.AUTOMATIC;\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data JPA repository for the Course entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface CourseRepository extends JpaRepository<Course, Long> {\n\n @Query(\"select distinct course.teachingAssistantGroupName from Course course\")\n Set<String> findAllTeachingAssistantGroupNames();\n\n @Query(\"select distinct course.instructorGroupName from Course course\")\n Set<String> findAllInstructorGroupNames();\n\n @Query(\"select distinct course from Course course where course.instructorGroupName like :#{#name}\")\n Course findCourseByInstructorGroupName(@Param(\"name\") String name);\n\n @Query(\"select distinct course from Course course where course.studentGroupName like :#{#name}\")\n Course findCourseByStudentGroupName(@Param(\"name\") String name);\n\n @Query(\"select distinct course from Course course where course.teachingAssistantGroupName like :#{#name}\")\n Course findCourseByTeachingAssistantGroupName(@Param(\"name\") String name);\n\n @Query(\"\"\"\n SELECT DISTINCT c FROM Course c\n WHERE (c.startDate <= :#{#now}\n \tOR c.startDate IS NULL)\n AND (c.endDate >= :#{#now}\n \tOR c.endDate IS NULL)\n \"\"\")\n List<Course> findAllActive(@Param(\"now\") ZonedDateTime now);\n\n @EntityGraph(type = LOAD, attributePaths = { \"lectures\", \"lectures.attachments\", \"exams\" })\n @Query(\"\"\"\n SELECT DISTINCT c FROM Course c\n WHERE (c.startDate <= :#{#now}\n \tOR c.startDate IS NULL)\n AND (c.endDate >= :#{#now}\n \tOR c.endDate IS NULL)\n \"\"\")\n List<Course> findAllActiveWithLecturesAndExams(@Param(\"now\") ZonedDateTime now);\n\n @EntityGraph(type = LOAD, attributePaths = { \"lectures\", \"lectures.attachments\", \"exams\" })\n Optional<Course> findWithEagerLecturesAndExamsById(long courseId);\n\n // Note: this is currently only used for testing purposes\n @Query(\"\"\"\n SELECT DISTINCT c FROM Course c\n LEFT JOIN FETCH c.exercises exercises\n LEFT JOIN FETCH c.lectures lectures\n LEFT JOIN FETCH lectures.attachments\n LEFT JOIN FETCH exercises.categories\n WHERE (c.startDate <= :#{#now}\n \tOR c.startDate IS NULL)\n AND (c.endDate >= :#{#now}\n \tOR c.endDate IS NULL)\n \"\"\")\n List<Course> findAllActiveWithEagerExercisesAndLectures(@Param(\"now\") ZonedDateTime now);\n\n @EntityGraph(type = LOAD, attributePaths = { \"exercises\", \"exercises.categories\", \"exercises.teamAssignmentConfig\" })\n Course findWithEagerExercisesById(long courseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"learningGoals\" })\n Optional<Course> findWithEagerLearningGoalsById(long courseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"exercises\", \"lectures\" })\n Optional<Course> findWithEagerExercisesAndLecturesById(long courseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"exercises\", \"lectures\", \"lectures.lectureUnits\", \"learningGoals\" })\n Course findWithEagerExercisesAndLecturesAndLectureUnitsAndLearningGoalsById(long courseId);\n\n @Query(\"\"\"\n SELECT DISTINCT c FROM Course c\n WHERE (c.startDate IS NULL\n \tOR c.startDate <= :#{#now})\n AND (c.endDate IS NULL\n \tOR c.endDate >= :#{#now})\n AND c.onlineCourse = FALSE\n AND c.registrationEnabled = TRUE\n \"\"\")\n List<Course> findAllCurrentlyActiveNotOnlineAndRegistrationEnabled(@Param(\"now\") ZonedDateTime now);\n\n @Query(\"select distinct course from Course course left join fetch course.organizations co where (course.startDate is null or course.startDate <= :#{#now}) and (course.endDate is null or course.endDate >= :#{#now}) and course.onlineCourse = false and course.registrationEnabled = true\")\n List<Course> findAllCurrentlyActiveNotOnlineAndRegistrationEnabledWithOrganizations(@Param(\"now\") ZonedDateTime now);\n\n @Query(\"select course from Course course left join fetch course.organizations co where course.id = :#{#courseId}\")\n Optional<Course> findWithEagerOrganizations(@Param(\"courseId\") long courseId);\n\n List<Course> findAllByShortName(String shortName);\n\n Optional<Course> findById(long courseId);\n\n /**\n * Returns the title of the course with the given id\n *\n * @param courseId the id of the course\n * @return the name/title of the course or null if the course does not exist\n */\n @Query(\"\"\"\n SELECT c.title\n FROM Course c\n WHERE c.id = :courseId\n \"\"\")\n String getCourseTitle(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n select distinct c\n from Course c left join fetch c.exercises e\n where c.instructorGroupName in :#{#userGroups} and TYPE(e) = QuizExercise\n \"\"\")\n List<Course> getCoursesWithQuizExercisesForWhichUserHasInstructorAccess(@Param(\"userGroups\") List<String> userGroups);\n\n @Query(\"\"\"\n select distinct c\n from Course c left join fetch c.exercises e\n where TYPE(e) = QuizExercise\n \"\"\")\n List<Course> findAllWithQuizExercisesWithEagerExercises();\n\n /**\n * Returns the student group name of a single course\n *\n * @param courseId the course id of the course to get the name for\n * @return the student group name\n */\n @Query(\"\"\"\n SELECT c.studentGroupName\n FROM Course c\n WHERE c.id = :courseId\n \"\"\")\n String findStudentGroupName(@Param(\"courseId\") long courseId);\n\n /**\n * Get active students in the timeframe from startDate to endDate for the exerciseIds\n *\n * @param exerciseIds exerciseIds from all exercises to get the statistics for\n * @param startDate the starting date of the query\n * @param endDate the end date for the query\n * @return A list with a map for every submission containing date and the username\n */\n @Query(\"\"\"\n SELECT s.submissionDate AS day, p.student.login AS username\n FROM StudentParticipation p JOIN p.submissions s\n WHERE p.exercise.id IN :exerciseIds\n AND s.submissionDate >= :#{#startDate}\n AND s.submissionDate <= :#{#endDate}\n \"\"\")\n List<Map<String, Object>> getActiveStudents(@Param(\"exerciseIds\") List<Long> exerciseIds, @Param(\"startDate\") ZonedDateTime startDate, @Param(\"endDate\") ZonedDateTime endDate);\n\n /**\n * Fetches the courses to display for the management overview\n *\n * @param now ZonedDateTime of the current time. If an end date is set only courses before this time are returned. May be null to return all\n * @param isAdmin whether the user to fetch the courses for is an admin (which gets all courses)\n * @param userGroups the user groups of the user to fetch the courses for (ignored if the user is an admin)\n * @return a list of courses for the overview\n */\n @Query(\"\"\"\n SELECT c\n FROM Course c\n WHERE (c.endDate IS NULL OR :#{#now} IS NULL OR c.endDate >= :#{#now})\n AND (:isAdmin = TRUE OR c.teachingAssistantGroupName IN :userGroups OR c.instructorGroupName IN :userGroups)\n \"\"\")\n List<Course> getAllCoursesForManagementOverview(@Param(\"now\") ZonedDateTime now, @Param(\"isAdmin\") boolean isAdmin, @Param(\"userGroups\") List<String> userGroups);\n\n @NotNull\n default Course findByIdElseThrow(Long courseId) throws EntityNotFoundException {\n return findById(courseId).orElseThrow(() -> new EntityNotFoundException(\"Course\", courseId));\n }\n\n default Course findByIdWithEagerExercisesElseThrow(Long courseId) throws EntityNotFoundException {\n return Optional.ofNullable(findWithEagerExercisesById(courseId)).orElseThrow(() -> new EntityNotFoundException(\"Course\", courseId));\n }\n\n @NotNull\n default Course findWithEagerOrganizationsElseThrow(Long courseId) throws EntityNotFoundException {\n return findWithEagerOrganizations(courseId).orElseThrow(() -> new EntityNotFoundException(\"Course\", courseId));\n }\n\n /**\n * filters the passed exercises for the relevant ones that need to be manually assessed. This excludes quizzes and automatic programming exercises\n *\n * @param exercises all exercises (e.g. of a course or exercise group) that should be filtered\n * @return the filtered and relevant exercises for manual assessment\n */\n default Set<Exercise> getInterestingExercisesForAssessmentDashboards(Set<Exercise> exercises) {\n return exercises.stream().filter(exercise -> exercise instanceof TextExercise || exercise instanceof ModelingExercise || exercise instanceof FileUploadExercise\n || (exercise instanceof ProgrammingExercise && exercise.getAssessmentType() != AUTOMATIC)).collect(Collectors.toSet());\n }\n\n /**\n * Get all the courses.\n *\n * @return the list of entities\n */\n default List<Course> findAllActiveWithLecturesAndExams() {\n return findAllActiveWithLecturesAndExams(ZonedDateTime.now());\n }\n\n /**\n * Get all the courses.\n *\n * @return the list of entities\n */\n default List<Course> findAllCurrentlyActiveNotOnlineAndRegistrationEnabled() {\n return findAllCurrentlyActiveNotOnlineAndRegistrationEnabled(ZonedDateTime.now());\n }\n\n /**\n * Get all the courses to register with eagerly loaded organizations.\n *\n * @return the list of course entities\n */\n default List<Course> findAllCurrentlyActiveNotOnlineAndRegistrationEnabledWithOrganizations() {\n return findAllCurrentlyActiveNotOnlineAndRegistrationEnabledWithOrganizations(ZonedDateTime.now());\n }\n\n /**\n * Get one course by id with lectures and exams. If the course cannot be found throw an exception\n *\n * @param courseId the id of the entity\n * @return the entity\n */\n @NotNull\n default Course findByIdWithLecturesAndExamsElseThrow(long courseId) {\n return findWithEagerLecturesAndExamsById(courseId).orElseThrow(() -> new EntityNotFoundException(\"Course\", courseId));\n }\n\n /**\n * Add organization to course, if not contained already\n * @param courseId the id of the course to add to the organization\n * @param organization the organization to add to the course\n */\n @NotNull\n default void addOrganizationToCourse(long courseId, Organization organization) {\n Course course = findWithEagerOrganizationsElseThrow(courseId);\n if (!course.getOrganizations().contains(organization)) {\n course.getOrganizations().add(organization);\n save(course);\n }\n }\n\n /**\n * Remove organization from course, if currently contained\n * @param courseId the id of the course to remove from the organization\n * @param organization the organization to remove from the course\n */\n @NotNull\n default void removeOrganizationFromCourse(long courseId, Organization organization) {\n Course course = findWithEagerOrganizationsElseThrow(courseId);\n if (course.getOrganizations().contains(organization)) {\n course.getOrganizations().remove(organization);\n save(course);\n }\n }\n\n @NotNull\n default Course findByIdWithExercisesAndLecturesElseThrow(long courseId) {\n return findWithEagerExercisesAndLecturesById(courseId).orElseThrow(() -> new EntityNotFoundException(\"Course\", courseId));\n }\n}\n" }, { "alpha_fraction": 0.6975210309028625, "alphanum_fraction": 0.702627956867218, "avg_line_length": 43.43971633911133, "blob_id": "9306bc593a5d181a31bbabfc06bb795573548a9a", "content_id": "efa645e91ae7619af353c747725e9a5a7d62353c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 18820, "license_type": "permissive", "max_line_length": 247, "num_lines": 423, "path": "/docs/dev/setup.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Setup Guide\n===========\n\nIn this guide you learn how to setup the development environment of\nArtemis. Artemis is based on `JHipster <https://jhipster.github.io>`__,\ni.e. \\ `Spring Boot <http://projects.spring.io/spring-boot>`__\ndevelopment on the application server using Java 15, and TypeScript\ndevelopment on the application client in the browser using\n`Angular <https://angular.io>`__ and Webpack. To get an overview of the\nused technology, have a look at the `JHipster Technology stack <https://jhipster.github.io/tech-stack>`__\nand other tutorials on the JHipster homepage.\n\nYou can find tutorials how to setup JHipster in an IDE (`IntelliJ IDEA\nUltimate <https://www.jetbrains.com/idea>`__ is recommended) on\nhttps://jhipster.github.io/configuring-ide. Note that the Community\nEdition of IntelliJ IDEA does not provide Spring Boot support (see the\n`comparison\nmatrix <https://www.jetbrains.com/idea/features/editions_comparison_matrix.html>`__).\nBefore you can build Artemis, you must install and configure the\nfollowing dependencies/tools on your machine:\n\n1. `Java\n JDK <https://www.oracle.com/java/technologies/javase-downloads.html>`__:\n We use Java (JDK 15) to develop and run the Artemis application\n server which is based on `Spring\n Boot <http://projects.spring.io/spring-boot>`__.\n2. `MySQL Database Server 8 <https://dev.mysql.com/downloads/mysql>`__:\n Artemis uses Hibernate to store entities in a MySQL database.\n Download and install the MySQL Community Server (8.0.x) and configure\n the ‘root’ user with an empty password. (In case you want to use a\n different password, make sure to change the value in\n application-dev.yml and in liquibase.gradle). The required Artemis\n scheme will be created / updated automatically at startup time of the\n server application. Alternatively, you can run the MySQL Database\n Server inside a Docker container using\n e.g. ``docker-compose -f src/main/docker/mysql.yml up``\n3. `Node.js <https://nodejs.org>`__: We use Node (>=15.8.0) to compile\n and run the client Angular application. Depending on your system, you\n can install Node either from source or as a pre-packaged bundle.\n4. `Yarn <https://classic.yarnpkg.com>`__: We use Yarn 1.x (>=1.22.10) to\n manage client side Node dependencies. Depending on your system, you\n can install Yarn either from source or as a pre-packaged bundle. To\n do so, please follow the instructions on the `Yarn installation\n page <https://classic.yarnpkg.com/en/docs/install>`__.\n\nServer Setup\n------------\n\nTo start the Artemis application server from the development\nenvironment, first import the project into IntelliJ and then make sure\nto install the Spring Boot plugins to run the main class\n``de.tum.in.www1.artemis.ArtemisApp``. Before the application runs, you\nhave to configure the file ``application-artemis.yml`` in the folder\n``src/main/resources/config``.\n\n.. code:: yaml\n\n artemis:\n repo-clone-path: ./repos/\n repo-download-clone-path: ./repos-download/\n encryption-password: <encrypt-password> # arbitrary password for encrypting database values\n user-management:\n use-external: true\n external:\n url: https://jira.ase.in.tum.de\n user: <username> # e.g. ga12abc\n password: <password>\n admin-group-name: tumuser\n ldap:\n url: <url>\n user-dn: <user-dn>\n password: <password>\n base: <base>\n version-control:\n url: https://bitbucket.ase.in.tum.de\n user: <username> # e.g. ga12abc\n password: <password>\n token: <token> # VCS API token giving Artemis full Admin access. Not needed for Bamboo+Bitbucket\n ci-token: <token from the CI> # Token generated by the CI (e.g. Jenkins) for webhooks from the VCS to the CI. Not needed for Bamboo+Bitbucket\n continuous-integration:\n url: https://bamboo.ase.in.tum.de\n user: <username> # e.g. ga12abc\n token: <token> # Enter a valid token generated by bamboo or leave this empty to use the fallback authentication user + password\n password: <password>\n vcs-application-link-name: LS1 Bitbucket Server # If the VCS and CI are directly linked (normally only for Bitbucket + Bamboo)\n empty-commit-necessary: true # Do we need an empty commit for new exercises/repositories in order for the CI to register the repo\n # Hash/key of the ci-token, equivalent e.g. to the ci-token in version-control\n # Some CI systems, like Jenkins, offer a specific token that gets checked against any incoming notifications\n # from a VCS trying to trigger a build plan. Only if the notification request contains the correct token, the plan\n # is triggered. This can be seen as an alternative to sending an authenticated request to a REST API and then\n # triggering the plan.\n # In the case of Artemis, this is only really needed for the Jenkins + GitLab setup, since the GitLab plugin in\n # Jenkins only allows triggering the Jenkins jobs using such a token. Furthermore, in this case, the value of the\n # hudson.util.Secret is stored in the build plan, so you also have to specify this encrypted string here and NOT the actual token value itself!\n # You can get this by GETting any job.xml for a job with an activated GitLab step and your token value of choice.\n secret-push-token: <token hash>\n # Key of the saved credentials for the VCS service\n # Bamboo: not needed\n # Jenkins: You have to specify the key from the credentials page in Jenkins under which the user and\n # password for the VCS are stored\n vcs-credentials: <credentials key>\n # Key of the credentials for the Artemis notification token\n # Bamboo: not needed\n # Jenkins: You have to specify the key from the credentials page in Jenkins under which the notification token is stored\n notification-token: <credentials key>\n # The actual value of the notification token to check against in Artemis. This is the token that gets send with\n # every request the CI system makes to Artemis containing a new result after a build.\n # Bamboo: The token value you use for the Server Notification Plugin\n # Jenkins: The token value you use for the Server Notification Plugin and is stored under the notification-token credential above\n authentication-token: <token>\n lti:\n id: artemis_lti\n oauth-key: artemis_lti_key\n oauth-secret: <secret> # only important for online courses on the edX platform, can typically be ignored\n user-prefix-edx: edx_\n user-prefix-u4i: u4i_\n user-group-name-edx: edx\n user-group-name-u4i: u4i\n git:\n name: Artemis\n email: [email protected]\n athene:\n url: http://localhost\n base64-secret: YWVuaXF1YWRpNWNlaXJpNmFlbTZkb283dXphaVF1b29oM3J1MWNoYWlyNHRoZWUzb2huZ2FpM211bGVlM0VpcAo=\n token-validity-in-seconds: 10800\n\nChange all entries with ``<...>`` with proper values, e.g. your TUM\nOnline account credentials to connect to the given instances of JIRA,\nBitbucket and Bamboo. Alternatively, you can connect to your local JIRA,\nBitbucket and Bamboo instances. It’s not necessary to fill all the\nfields, most of them can be left blank. Note that there is additional\ninformation about the setup for programming exercises provided:\n\n\n.. toctree::\n :maxdepth: 1\n\n Bamboo, Bitbucket and Jira <setup/bamboo-bitbucket-jira>\n Jenkins and Gitlab <setup/jenkins-gitlab>\n Multiple instances <setup/distributed>\n Programming Exercise adjustments <setup/programming-exercises>\n\n\n.. note::\n Be careful that you don’t commit changes to ``application-artemis.yml``.\n To avoid this, follow the best practice when configuring your local development environment:\n\n 1) Create a file named ``application-local.yml`` under ``src/main/resources/config``.\n 2) Copy the contents of ``application-artemis.yml`` into the new file.\n 3) Update configuration values in ``application-local.yml``.\n\n By default, changes to ``application-local.yml`` will be ignored by git so you don't accidentally\n share your credentials or other local configuration options.\n\nIf you use a password, you need to adapt it in\n``gradle/liquibase.gradle``.\n\n\nRun the server via a service configuration\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThis setup is recommended for production instances as it registers Artemis as a service and e.g. enables auto-restarting of Artemis after the VM running Artemis has been restarted.\nFor development setups, see the other guides below.\n\nThis is a service file that works on Debian/Ubuntu (using systemd):\n\n::\n\n [Unit]\n Description=ArTEMiS\n After=syslog.target\n [Service]\n User=artemis\n WorkingDirectory=/opt/artemis\n ExecStart=/usr/bin/java \\\n -Djdk.tls.ephemeralDHKeySize=2048 \\\n -DLC_CTYPE=UTF-8 \\\n -Dfile.encoding=UTF-8 \\\n -Dsun.jnu.encoding=UTF-8 \\\n -Djava.security.egd=file:/dev/./urandom \\\n -Xmx2048m \\\n --add-modules java.se \\\n --add-exports java.base/jdk.internal.ref=ALL-UNNAMED \\\n --add-opens java.base/java.lang=ALL-UNNAMED \\\n --add-opens java.base/java.nio=ALL-UNNAMED \\\n --add-opens java.base/sun.nio.ch=ALL-UNNAMED \\\n --add-opens java.management/sun.management=ALL-UNNAMED \\\n --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED \\\n -jar artemis.war \\\n --spring.profiles.active=prod,bamboo,bitbucket,jira,ldap,scheduling,openapi\n SuccessExitStatus=143\n StandardOutput=/opt/artemis/artemis.log\n StandardError=inherit\n [Install]\n WantedBy=multi-user.target\n\n\nThe following parts might also be useful for other (production) setups, even if this service file is not used:\n\n- ``-Djava.security.egd=file:/dev/./urandom``: This is required if repositories are cloned via SSH from the VCS.\n The default (pseudo-)random-generator ``/dev/random`` is blocking which results in very bad performance when using SSH due to lack of entropy.\n\n\nThe file should be placed at ``/etc/systemd/system/artemis.service`` and after running ``sudo systemctl daemon-reload``, you can start the service using ``sudo service artemis start``.\n\nYou can stop the service using ``sudo service artemis stop`` and restart it using ``sudo service artemis restart``.\n\nLogs can be fetched using ``sudo journalctl -u artemis -f -n 200``.\n\nRun the server via a run configuration in IntelliJ\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe project comes with some pre-configured run / debug configurations that are stored in the ``.idea`` directory.\nWhen you import the project into IntelliJ the run configurations will also be imported.\n\nThe recommended way is to run the server and the client separated. This provides fast rebuilds of the server and hot module replacement in the client.\n\n* **Artemis (Server):** The server will be started separated from the client. The startup time decreases significantly.\n* **Artemis (Client):** Will execute ``yarn install`` and ``yarn start``. The client will be available at `http://localhost:9000/ <http://localhost:9000/>`__ with hot module replacement enabled (also see `Client Setup <setup.rst#client-setup>`__).\n\nOther run / debug configurations\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\n* **Artemis (Server & Client):** Will start the server and the client. The client will be available at `http://localhost:8080/ <http://localhost:8080/>`__ with hot module replacement disabled.\n* **Artemis (Server, Jenkins & Gitlab):** The server will be started separated from the client with the profiles ``dev,jenkins,gitlab,artemis`` instead of ``dev,bamboo,bitbucket,jira,artemis``.\n* **Artemis (Server, Athene):** The server will be started separated from the client with ``athene`` profile enabled (see `Athene Service <setup.rst#athene-service>`__).\n\n\nTypical problems with Liquibase checksums\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nOne typical problem in the development setup is that an exception occurs\nduring the database initialization. Artemis uses\n`Liquibase <https://www.liquibase.org>`__ to automatically upgrade the\ndatabase scheme after changes to the data model. This ensures that the\nchanges can also be applied to the production server. In case you\nencounter errors with liquibase checksum values, run the following\ncommand in your terminal / command line:\n\n::\n\n ./gradlew liquibaseClearChecksums\n\nRun the server with Spring Boot and Spring profiles\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe Artemis server should startup by running the main class\n``de.tum.in.www1.artemis.ArtemisApp`` using Spring Boot.\n\n.. note::\n Artemis uses Spring profiles to segregate parts of the\n application configuration and make it only available in certain\n environments. For development purposes, the following program arguments\n can be used to enable the ``dev`` profile and the profiles for JIRA,\n Bitbucket and Bamboo:\n\n::\n\n --spring.profiles.active=dev,bamboo,bitbucket,jira,artemis,scheduling\n\nIf you use IntelliJ (Community or Ultimate) you can set the active\nprofiles by\n\n* Choosing ``Run | Edit Configurations...``\n* Going to the ``Configuration Tab``\n* Expanding the ``Environment`` section to reveal ``VM Options`` and setting them to\n ``-Dspring.profiles.active=dev,bamboo,bitbucket,jira,artemis,scheduling``\n\nSet Spring profiles with IntelliJ Ultimate\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nIf you use IntelliJ Ultimate, add the following entry to the section\n``Active Profiles`` (within ``Spring Boot``) in the server run\nconfiguration:\n\n::\n\n dev,bamboo,bitbucket,jira,artemis,scheduling\n\nRun the server with the command line (Gradle wrapper)\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIf you want to run the application via the command line instead, make\nsure to pass the active profiles to the ``gradlew`` command like this:\n\n::\n\n ./gradlew bootRun --args='--spring.profiles.active=dev,bamboo,bitbucket,jira,artemis,scheduling'\n\nAs an alternative, you might want to use Jenkins and Gitlab with an\ninternal user management in Artemis, then you would use the profiles:\n\n::\n\n dev,jenkins,gitlab,artemis,scheduling\n\nClient Setup\n------------\n\nYou need to install Node and Yarn on your local machine.\n\nUsing IntelliJ\n^^^^^^^^^^^^^^\n\nIf you are using **IntelliJ** you can use the pre-configured ``Artemis (Client)``\nrun configuration that will be delivered with this repository:\n\n* Choose ``Run | Edit Configurations...``\n* Select the ``Artemis (Client)`` configuration from the ``npm section``\n* Now you can run the configuration in the upper right corner of IntelliJ\n\nUsing the command line\n^^^^^^^^^^^^^^^^^^^^^^\n\nYou should be able to run the following\ncommand to install development tools and dependencies. You will only\nneed to run this command when dependencies change in\n`package.json <package.json>`__.\n\n::\n\n yarn install\n\nTo start the client application in the browser, use the following\ncommand:\n\n::\n\n yarn start\n\nThis compiles TypeScript code to JavaScript code, starts the hot module\nreplacement feature in Webpack (i.e. whenever you change a TypeScript\nfile and save, the client is automatically reloaded with the new code)\nand will start the client application in your browser on\n``http://localhost:9000``. If you have activated the JIRA profile (see\nabove in Server Setup) and if you have configured\n``application-artemis.yml`` correctly, then you should be able to login\nwith your TUM Online account.\n\nFor more information, review `Working with\nAngular <https://www.jhipster.tech/development/#working-with-angular>`__.\nFor further instructions on how to develop with JHipster, have a look at\n`Using JHipster in\ndevelopment <http://www.jhipster.tech/development>`__.\n\nCustomize your Artemis instance\n-------------------------------\n\nYou can define the following custom assets for Artemis to be used\ninstead of the TUM defaults:\n\n* The logo next to the “Artemis” heading on the navbar → ``${artemisRunDirectory}/public/images/logo.png``\n* The favicon → ``${artemisRunDirectory}/public/images/favicon.ico``\n* The privacy statement HTML → ``${artemisRunDirectory}/public/content/privacy_statement.html``\n* The contact email address in the ``application-{dev,prod}.yml`` configuration file under the key ``info.contact``\n* The imprint link in the ``application-{dev,prod}.yml`` configuration file under the key ``info.imprint``\n\nAlternative: Using docker-compose\n---------------------------------\n\nA full functioning development environment can also be set up using\ndocker-compose:\n\n1. Install `docker <https://docs.docker.com/install/>`__ and `docker-compose <https://docs.docker.com/compose/install/>`__\n2. Configure the credentials in ``application-artemis.yml`` in the folder ``src/main/resources/config`` as described above\n3. Run ``docker-compose up``\n4. Go to http://localhost:9000\n\nThe client and the server will run in different containers. As yarn is\nused with its live reload mode to build and run the client, any change\nin the client’s codebase will trigger a rebuild automatically. In case\nof changes in the codebase of the server one has to restart the\n``artemis-server`` container via\n``docker-compose restart artemis-server``.\n\n(Native) Running and Debugging from IDEs is currently not supported.\n\nGet a shell into the containers:\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n- app container:\n ``docker exec -it $(docker-compose ps -q artemis-app) sh``\n- mysql container:\n ``docker exec -it $(docker-compose ps -q artemis-mysql) mysql``\n\nOther useful commands:\n^^^^^^^^^^^^^^^^^^^^^^\n\n- Stop the server: ``docker-compose stop artemis-server`` (restart via\n ``docker-compose start artemis-server``)\n- Stop the client: ``docker-compose stop artemis-client`` (restart via\n ``docker-compose start artemis-client``)\n\nAthene Service\n--------------\n\nThe semi-automatic text assessment relies on the Athene_ service.\nTo enable automatic text assessments, special configuration is required:\n\nEnable the ``athene`` Spring profile:\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\n::\n\n --spring.profiles.active=dev,bamboo,bitbucket,jira,artemis,scheduling,athene\n\nConfigure API Endpoints:\n^^^^^^^^^^^^^^^^^^^^^^^^\n\nThe Athene service is running on a dedicated machine and is adressed via\nHTTP. We need to extend the configuration in the file\n``src/main/resources/config/application-artemis.yml`` like so:\n\n.. code:: yaml\n\n artemis:\n # ...\n athene:\n url: http://localhost\n base64-secret: YWVuaXF1YWRpNWNlaXJpNmFlbTZkb283dXphaVF1b29oM3J1MWNoYWlyNHRoZWUzb2huZ2FpM211bGVlM0VpcAo=\n token-validity-in-seconds: 10800\n\n.. _Athene: https://github.com/ls1intum/Athene\n" }, { "alpha_fraction": 0.6369791030883789, "alphanum_fraction": 0.6374304294586182, "avg_line_length": 43.91216278076172, "blob_id": "64f37a81d358704127b00ab88aaa73e8d9ec198f", "content_id": "36114cd46769184e9682cfdc6f13446548a39c2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6647, "license_type": "permissive", "max_line_length": 149, "num_lines": 148, "path": "/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment-dashboard.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { map } from 'rxjs/operators';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { FileUploadSubmission } from 'app/entities/file-upload-submission.model';\nimport { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { FileUploadAssessmentsService } from 'app/exercises/file-upload/assess/file-upload-assessment.service';\nimport { getLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { getLinkToSubmissionAssessment } from 'app/utils/navigation.utils';\n\n@Component({\n templateUrl: './file-upload-assessment-dashboard.component.html',\n})\nexport class FileUploadAssessmentDashboardComponent implements OnInit {\n ExerciseType = ExerciseType;\n exercise: FileUploadExercise;\n submissions: FileUploadSubmission[] = [];\n filteredSubmissions: FileUploadSubmission[] = [];\n busy = false;\n predicate = 'id';\n reverse = false;\n numberOfCorrectionrounds = 1;\n courseId: number;\n exerciseId: number;\n examId: number;\n exerciseGroupId: number;\n private cancelConfirmationText: string;\n\n constructor(\n private route: ActivatedRoute,\n private accountService: AccountService,\n private exerciseService: ExerciseService,\n private fileUploadSubmissionService: FileUploadSubmissionService,\n private fileUploadAssessmentsService: FileUploadAssessmentsService,\n private translateService: TranslateService,\n private sortService: SortService,\n ) {\n translateService.get('artemisApp.assessment.messages.confirmCancel').subscribe((text) => (this.cancelConfirmationText = text));\n }\n\n /**\n * Get Submissions for exercise id.\n * If No Submissions are found, also get exercise. Otherwise, we get it from the first participation.\n */\n public async ngOnInit(): Promise<void> {\n this.busy = true;\n this.exerciseId = Number(this.route.snapshot.paramMap.get('exerciseId'));\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n if (this.route.snapshot.paramMap.has('examId')) {\n this.examId = Number(this.route.snapshot.paramMap.get('examId'));\n this.exerciseGroupId = Number(this.route.snapshot.paramMap.get('exerciseGroupId'));\n }\n\n this.exerciseService\n .find(this.exerciseId)\n .map((exerciseResponse) => {\n if (exerciseResponse.body!.type !== ExerciseType.FILE_UPLOAD) {\n throw new Error('Cannot use File-Upload Assessment Dashboard with non-file-upload Exercise type.');\n }\n return <FileUploadExercise>exerciseResponse.body!;\n })\n .subscribe((exercise) => {\n this.exercise = exercise;\n this.getSubmissions();\n this.numberOfCorrectionrounds = this.exercise.exerciseGroup ? this.exercise!.exerciseGroup.exam!.numberOfCorrectionRoundsInExam! : 1;\n this.setPermissions();\n this.busy = false;\n });\n }\n\n /**\n * Fetch submissions for Exercise id.\n * @param exerciseId\n * @return Resolved Promise if Submission list contains at least one submission. Rejected Promise if Submission list is empty.\n * @throws Error if exercise id is of other type.\n */\n private getSubmissions(): Promise<void> {\n return new Promise((resolve, reject) => {\n this.fileUploadSubmissionService\n .getFileUploadSubmissionsForExerciseByCorrectionRound(this.exercise.id!, { submittedOnly: true })\n .pipe(\n map((response: HttpResponse<FileUploadSubmission[]>) =>\n response.body!.map((submission: FileUploadSubmission) => {\n const tmpResult = getLatestSubmissionResult(submission);\n if (tmpResult) {\n // reconnect some associations\n tmpResult.submission = submission;\n tmpResult.participation = submission.participation;\n submission.participation!.results = [tmpResult];\n }\n return submission;\n }),\n ),\n )\n .subscribe((submissions: FileUploadSubmission[]) => {\n this.submissions = submissions;\n this.filteredSubmissions = submissions;\n if (submissions.length > 0) {\n resolve();\n } else {\n reject();\n }\n });\n });\n }\n\n updateFilteredSubmissions(filteredSubmissions: Submission[]) {\n this.filteredSubmissions = filteredSubmissions as FileUploadSubmission[];\n }\n\n /**\n * Cancel the current assessment and reload the submissions to reflect the change.\n */\n cancelAssessment(submission: Submission) {\n const confirmCancel = window.confirm(this.cancelConfirmationText);\n if (confirmCancel) {\n this.fileUploadAssessmentsService.cancelAssessment(submission.id!).subscribe(() => {\n this.getSubmissions();\n });\n }\n }\n\n private setPermissions() {\n if (this.exercise.course) {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.course!);\n } else {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.exerciseGroup?.exam?.course!);\n }\n }\n\n public sortRows() {\n this.sortService.sortByProperty(this.submissions, this.predicate, this.reverse);\n }\n\n /**\n * get the link for the assessment of a specific submission of the current exercise\n * @param submissionId\n */\n getAssessmentLink(submissionId: number) {\n return getLinkToSubmissionAssessment(this.exercise.type!, this.courseId, this.exerciseId, submissionId, this.examId, this.exerciseGroupId);\n }\n}\n" }, { "alpha_fraction": 0.7229660153388977, "alphanum_fraction": 0.7229660153388977, "avg_line_length": 37.84000015258789, "blob_id": "6f1f5f999f7da99f23e017e32516ed006578ec7f", "content_id": "44dda8e9eae3877ffc3d5965e5c206bab9c953dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 971, "license_type": "permissive", "max_line_length": 108, "num_lines": 25, "path": "/src/main/webapp/app/exercises/programming/shared/service/build-log.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { HttpClient } from '@angular/common/http';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { BuildLogEntry } from 'app/entities/build-log.model';\n\nexport interface IBuildLogService {\n getBuildLogs: (participationId: number) => Observable<BuildLogEntry[]>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class BuildLogService implements IBuildLogService {\n private restResourceUrlBase = `${SERVER_API_URL}/api`;\n private assignmentResourceUrl = `${this.restResourceUrlBase}/repository`;\n\n constructor(private http: HttpClient) {}\n\n /**\n * Retrieves the build logs for a given participation.\n * @param participationId The identifier of the participation.\n */\n getBuildLogs(participationId: number): Observable<BuildLogEntry[]> {\n return this.http.get<BuildLogEntry[]>(`${this.assignmentResourceUrl}/${participationId}/buildlogs`);\n }\n}\n" }, { "alpha_fraction": 0.6825022101402283, "alphanum_fraction": 0.6845676898956299, "avg_line_length": 42.4487190246582, "blob_id": "58f00eda8512255c99bf97a99dd91cec59208862", "content_id": "80876f4cb15afba6ff0bd0b1f3fedca93a53db55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3389, "license_type": "permissive", "max_line_length": 167, "num_lines": 78, "path": "/src/test/javascript/spec/service/account.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport { SinonStub, stub } from 'sinon';\nimport { of } from 'rxjs';\nimport * as sinonChai from 'sinon-chai';\nimport { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service';\nimport { MockLanguageService } from '../helpers/mocks/service/mock-language.service';\nimport { MockHttpService } from '../helpers/mocks/service/mock-http.service';\nimport { MockFeatureToggleService } from '../helpers/mocks/service/mock-feature-toggle.service';\nimport { User } from 'app/core/user/user.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('AccountService', () => {\n let accountService: AccountService;\n let httpService: MockHttpService;\n let getStub: SinonStub;\n\n const getUserUrl = 'undefinedapi/account';\n const user = { id: 1, groups: ['USER'] } as User;\n const user2 = { id: 2, groups: ['USER'] } as User;\n\n beforeEach(async(() => {\n httpService = new MockHttpService();\n // @ts-ignore\n accountService = new AccountService(new MockLanguageService(), new MockSyncStorage(), httpService, new MockWebsocketService(), new MockFeatureToggleService());\n getStub = stub(httpService, 'get');\n\n expect(accountService.userIdentity).to.deep.equal(undefined);\n expect(accountService.isAuthenticated()).to.be.false;\n }));\n\n afterEach(() => {\n getStub.restore();\n });\n\n it('should fetch the user on identity if the userIdentity is not defined yet', async () => {\n getStub.returns(of({ body: user }));\n\n const userReceived = await accountService.identity(false);\n\n expect(getStub).to.have.been.calledOnceWithExactly(getUserUrl, { observe: 'response' });\n expect(userReceived).to.deep.equal(user);\n expect(accountService.userIdentity).to.deep.equal(user);\n expect(accountService.isAuthenticated()).to.be.true;\n });\n\n it('should fetch the user on identity if the userIdentity is defined yet (force=true)', async () => {\n accountService.userIdentity = user;\n expect(accountService.userIdentity).to.deep.equal(user);\n expect(accountService.isAuthenticated()).to.be.true;\n getStub.returns(of({ body: user2 }));\n\n const userReceived = await accountService.identity(true);\n\n expect(getStub).to.have.been.calledOnceWithExactly(getUserUrl, { observe: 'response' });\n expect(userReceived).to.deep.equal(user2);\n expect(accountService.userIdentity).to.deep.equal(user2);\n expect(accountService.isAuthenticated()).to.be.true;\n });\n\n it('should NOT fetch the user on identity if the userIdentity is defined (force=false)', async () => {\n accountService.userIdentity = user;\n expect(accountService.userIdentity).to.deep.equal(user);\n expect(accountService.isAuthenticated()).to.be.true;\n getStub.returns(of({ body: user2 }));\n\n const userReceived = await accountService.identity(false);\n\n expect(getStub).not.to.have.been.called;\n expect(userReceived).to.deep.equal(user);\n expect(accountService.userIdentity).to.deep.equal(user);\n expect(accountService.isAuthenticated()).to.be.true;\n });\n});\n" }, { "alpha_fraction": 0.617969810962677, "alphanum_fraction": 0.6186556816101074, "avg_line_length": 17.225000381469727, "blob_id": "bd332a19a2d5943cab4f4feb548dba7960760cd4", "content_id": "1ed26ad842c44ce50c2654aaf1ca10bb5c991046", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1458, "license_type": "permissive", "max_line_length": 62, "num_lines": 80, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/dto/TestsuiteDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.jenkins.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class TestsuiteDTO {\n\n private String name;\n\n private double time;\n\n private int errors;\n\n private int skipped;\n\n private int failures;\n\n private int tests;\n\n private List<TestCaseDTO> testCases = new ArrayList<>();\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public double getTime() {\n return time;\n }\n\n public void setTime(double time) {\n this.time = time;\n }\n\n public int getErrors() {\n return errors;\n }\n\n public void setErrors(int errors) {\n this.errors = errors;\n }\n\n public int getSkipped() {\n return skipped;\n }\n\n public void setSkipped(int skipped) {\n this.skipped = skipped;\n }\n\n public int getFailures() {\n return failures;\n }\n\n public void setFailures(int failures) {\n this.failures = failures;\n }\n\n public int getTests() {\n return tests;\n }\n\n public void setTests(int tests) {\n this.tests = tests;\n }\n\n public List<TestCaseDTO> getTestCases() {\n return testCases;\n }\n\n public void setTestCases(List<TestCaseDTO> testCases) {\n this.testCases = testCases;\n }\n}\n" }, { "alpha_fraction": 0.7177101969718933, "alphanum_fraction": 0.71806800365448, "avg_line_length": 43.36507797241211, "blob_id": "ecf8ebdc50e54e0d0258fbc75b4cab0ece643040", "content_id": "71e39affb9007d270a6af159bfa10e544fbe0cfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2795, "license_type": "permissive", "max_line_length": 139, "num_lines": 63, "path": "/src/main/webapp/app/exercises/modeling/manage/modeling-exercise-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpResponse } from '@angular/common/http';\nimport { UMLModel } from '@ls1intum/apollon';\nimport { Subscription } from 'rxjs/Subscription';\nimport { JhiEventManager } from 'ng-jhipster';\n\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ModelingExerciseService } from './modeling-exercise.service';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\n\n@Component({\n selector: 'jhi-modeling-exercise-detail',\n templateUrl: './modeling-exercise-detail.component.html',\n})\nexport class ModelingExerciseDetailComponent implements OnInit, OnDestroy {\n modelingExercise: ModelingExercise;\n private subscription: Subscription;\n private eventSubscriber: Subscription;\n problemStatement: SafeHtml;\n gradingInstructions: SafeHtml;\n sampleSolution: SafeHtml;\n sampleSolutionUML: UMLModel;\n\n constructor(\n private eventManager: JhiEventManager,\n private modelingExerciseService: ModelingExerciseService,\n private route: ActivatedRoute,\n private artemisMarkdown: ArtemisMarkdownService,\n ) {}\n\n ngOnInit() {\n this.subscription = this.route.params.subscribe((params) => {\n this.load(params['exerciseId']);\n });\n this.registerChangeInModelingExercises();\n }\n\n load(id: number) {\n this.modelingExerciseService.find(id).subscribe((modelingExerciseResponse: HttpResponse<ModelingExercise>) => {\n this.modelingExercise = modelingExerciseResponse.body!;\n this.problemStatement = this.artemisMarkdown.safeHtmlForMarkdown(this.modelingExercise.problemStatement);\n this.gradingInstructions = this.artemisMarkdown.safeHtmlForMarkdown(this.modelingExercise.gradingInstructions);\n this.sampleSolution = this.artemisMarkdown.safeHtmlForMarkdown(this.modelingExercise.sampleSolutionExplanation);\n if (this.modelingExercise.sampleSolutionModel && this.modelingExercise.sampleSolutionModel !== '') {\n this.sampleSolutionUML = JSON.parse(this.modelingExercise.sampleSolutionModel);\n }\n if (this.modelingExercise.categories) {\n this.modelingExercise.categories = this.modelingExercise.categories.map((category) => JSON.parse(category));\n }\n });\n }\n\n ngOnDestroy() {\n this.subscription.unsubscribe();\n this.eventManager.destroy(this.eventSubscriber);\n }\n\n registerChangeInModelingExercises() {\n this.eventSubscriber = this.eventManager.subscribe('modelingExerciseListModification', () => this.load(this.modelingExercise.id!));\n }\n}\n" }, { "alpha_fraction": 0.7466470003128052, "alphanum_fraction": 0.7518776655197144, "avg_line_length": 50.0684928894043, "blob_id": "e5b35c20fcab2add45c78fd06f73ce300986934c", "content_id": "3e2f5321cbdc9e3ef38a056c3053be194dd882e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7456, "license_type": "permissive", "max_line_length": 180, "num_lines": 146, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/SystemNotificationResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.servlet.support.ServletUriComponentsBuilder;\n\nimport de.tum.in.www1.artemis.domain.notification.Notification;\nimport de.tum.in.www1.artemis.domain.notification.SystemNotification;\nimport de.tum.in.www1.artemis.repository.SystemNotificationRepository;\nimport de.tum.in.www1.artemis.service.SystemNotificationService;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\nimport io.github.jhipster.web.util.PaginationUtil;\nimport io.github.jhipster.web.util.ResponseUtil;\nimport io.swagger.annotations.ApiParam;\n\n/** REST controller for managing SystemNotification. */\n@RestController\n@RequestMapping(\"/api\")\npublic class SystemNotificationResource {\n\n private final Logger log = LoggerFactory.getLogger(SystemNotificationResource.class);\n\n private static final String ENTITY_NAME = \"systemNotification\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final SystemNotificationRepository systemNotificationRepository;\n\n private final SystemNotificationService systemNotificationService;\n\n public SystemNotificationResource(SystemNotificationRepository systemNotificationRepository, SystemNotificationService systemNotificationService) {\n this.systemNotificationRepository = systemNotificationRepository;\n this.systemNotificationService = systemNotificationService;\n }\n\n /**\n * POST /system-notifications : Create a new system notification.\n *\n * @param systemNotification the system notification to create\n * @return the ResponseEntity with status 201 (Created) and with body the new system notification, or with status 400 (Bad Request) if the system notification has already an ID\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PostMapping(\"/system-notifications\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<Notification> createSystemNotification(@RequestBody SystemNotification systemNotification) throws URISyntaxException {\n log.debug(\"REST request to save SystemNotification : {}\", systemNotification);\n if (systemNotification.getId() != null) {\n throw new BadRequestAlertException(\"A new system notification cannot already have an ID\", ENTITY_NAME, \"idexists\");\n }\n SystemNotification result = systemNotificationRepository.save(systemNotification);\n systemNotificationService.sendNotification(systemNotification);\n return ResponseEntity.created(new URI(\"/api/notifications/\" + result.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())).body(result);\n }\n\n /**\n * PUT /system-notifications : Updates an existing system notification.\n *\n * @param systemNotification the system notification to update\n * @return the ResponseEntity with status 200 (OK) and with body the updated notification, or with status 400 (Bad Request) if the system notification is not valid, or with\n * status 500 (Internal Server Error) if the system notification couldn't be updated\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PutMapping(\"/system-notifications\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<SystemNotification> updateSystemNotification(@RequestBody SystemNotification systemNotification) throws URISyntaxException {\n log.debug(\"REST request to update SystemNotification : {}\", systemNotification);\n if (systemNotification.getId() == null) {\n throw new BadRequestAlertException(\"Invalid id\", ENTITY_NAME, \"idnull\");\n }\n SystemNotification result = systemNotificationRepository.save(systemNotification);\n systemNotificationService.sendNotification(result);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, systemNotification.getId().toString())).body(result);\n }\n\n /**\n * GET /system-notifications : get all system notifications for administration purposes.\n *\n * @param pageable instance of the pageable interface to enable paging\n * @return the list of system notifications\n */\n @GetMapping(\"/system-notifications\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<List<SystemNotification>> getAllSystemNotifications(@ApiParam Pageable pageable) {\n log.debug(\"REST request to get all Courses the user has access to\");\n final Page<SystemNotification> page = systemNotificationRepository.findAll(pageable);\n HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);\n return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);\n }\n\n /**\n * GET /system-notifications/:id : get the \"id\" system notification.\n *\n * @param id the id of the system notification to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the notification, or with status 404 (Not Found)\n */\n @GetMapping(\"/system-notifications/{id}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<SystemNotification> getSystemNotification(@PathVariable Long id) {\n log.debug(\"REST request to get SystemNotification : {}\", id);\n Optional<SystemNotification> systemNotification = systemNotificationRepository.findById(id);\n return ResponseUtil.wrapOrNotFound(systemNotification);\n }\n\n /**\n * DELETE /system-notifications/:id : delete the \"id\" system notification.\n *\n * @param id the id of the system notification to delete\n * @return the ResponseEntity with status 200 (OK)\n */\n @DeleteMapping(\"/system-notifications/{id}\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<Void> deleteSystemNotification(@PathVariable Long id) {\n log.debug(\"REST request to delete SystemNotification : {}\", id);\n systemNotificationRepository.deleteById(id);\n systemNotificationService.sendNotification(null);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();\n }\n\n /**\n * GET /system-notifications/:id : get the \"id\" system notification.\n * This route is also accessible for unauthenticated users.\n *\n * @return the ResponseEntity with status 200 (OK) and with body the notification, or with status 404 (Not Found)\n */\n @GetMapping(\"/system-notifications/active-notification\")\n public SystemNotification getActiveSystemNotification() {\n log.debug(\"REST request to get active SystemNotification\");\n return systemNotificationService.findActiveSystemNotification();\n }\n}\n" }, { "alpha_fraction": 0.6163410544395447, "alphanum_fraction": 0.6163410544395447, "avg_line_length": 20.653846740722656, "blob_id": "f4b44763cdeab2d75f83bbd609709a630215c59d", "content_id": "5870fc2ab4582aeb26654beb072dda024a9efe04", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 563, "license_type": "permissive", "max_line_length": 73, "num_lines": 26, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-websocket.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Observable, of } from 'rxjs';\nimport { IWebsocketService } from 'app/core/websocket/websocket.service';\n\nexport class MockWebsocketService implements IWebsocketService {\n bind(event: string, callback: () => void): void {}\n\n connect = () => {};\n\n disableReconnect(): void {}\n\n disconnect(): void {}\n\n enableReconnect(): void {}\n\n receive(): Observable<any> {\n return of();\n }\n\n stompFailureCallback(): void {}\n\n subscribe(): void {}\n\n unbind(event: string, callback: () => void): void {}\n\n unsubscribe(): void {}\n}\n" }, { "alpha_fraction": 0.7589396834373474, "alphanum_fraction": 0.7624602913856506, "avg_line_length": 56.7131462097168, "blob_id": "c28e86fc94c8cb97fa00cfcf72f260d9f2f2fc2b", "content_id": "459d5f14645cc43dd7c08e325df501d07ecdf237", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14486, "license_type": "permissive", "max_line_length": 180, "num_lines": 251, "path": "/src/test/javascript/spec/service/participation-websocket.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { BehaviorSubject, Subject } from 'rxjs';\nimport * as sinonChai from 'sinon-chai';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { IWebsocketService } from 'app/core/websocket/websocket.service';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ParticipationWebsocketService', () => {\n let websocketService: IWebsocketService;\n // tslint:disable-next-line:prefer-const\n let participationService: ParticipationService;\n let receiveParticipationSubject: Subject<Participation>;\n let receiveParticipation2Subject: Subject<Participation>;\n let receiveResultForParticipationSubject: Subject<Result>;\n let receiveResultForParticipation2Subject: Subject<Result>;\n let subscribeSpy: SinonSpy;\n let receiveStub: SinonStub;\n let unsubscribeSpy: SinonSpy;\n\n let participationWebsocketService: ParticipationWebsocketService;\n\n const exerciseId1 = 20;\n const exerciseId2 = 40;\n\n const participation = { id: 1, exercise: { id: exerciseId1 } } as Participation;\n const currentResult = { id: 10, participation } as Result;\n participation.results = [currentResult];\n const newRatedResult = { id: 11, rated: true, participation } as Result;\n const newUnratedResult = { id: 12, rated: false, participation } as Result;\n\n const participationPersonalResultTopic = `/user/topic/newResults`;\n const participationTopic = `/user/topic/exercise/${participation.exercise!.id}/participation`;\n\n const participation2 = { id: 2, exercise: { id: exerciseId2 } } as Participation;\n const currentResult2 = { id: 13, participation: participation2 } as Result;\n participation2.results = [currentResult2];\n\n const participationInstructorResultTopic = `/topic/exercise/${participation2.exercise!.id}/newResults`;\n const participation2Topic = `/user/topic/exercise/${participation2.exercise!.id}/participation`;\n\n beforeEach(async(() => {\n websocketService = new MockWebsocketService();\n // @ts-ignore\n participationWebsocketService = new ParticipationWebsocketService(websocketService, participationService);\n\n subscribeSpy = spy(websocketService, 'subscribe');\n unsubscribeSpy = spy(websocketService, 'unsubscribe');\n receiveStub = stub(websocketService, 'receive');\n\n receiveResultForParticipationSubject = new Subject();\n receiveResultForParticipation2Subject = new Subject();\n receiveParticipationSubject = new Subject();\n receiveParticipation2Subject = new Subject();\n receiveStub.withArgs(participationPersonalResultTopic).returns(receiveResultForParticipationSubject);\n receiveStub.withArgs(participationInstructorResultTopic).returns(receiveResultForParticipation2Subject);\n receiveStub.withArgs(participationTopic).returns(receiveParticipationSubject);\n receiveStub.withArgs(participation2Topic).returns(receiveParticipation2Subject);\n }));\n\n afterEach(() => {\n subscribeSpy.restore();\n unsubscribeSpy.restore();\n receiveStub.restore();\n });\n\n it('should setup a result subscriptions with the websocket service on subscribeForLatestResult for instructors', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, false, exerciseId2);\n expect(subscribeSpy).to.have.been.calledOnce;\n expect(receiveStub).to.have.been.calledOnce;\n expect(unsubscribeSpy).not.to.have.been.called;\n\n expect(subscribeSpy).to.have.been.calledWithExactly(participationInstructorResultTopic);\n expect(receiveStub).to.have.been.calledWithExactly(participationInstructorResultTopic);\n\n expect(participationWebsocketService.cachedParticipations.size).to.equal(0);\n\n expect(participationWebsocketService.openResultWebsocketSubscriptions.size).to.equal(1);\n expect(participationWebsocketService.openPersonalWebsocketSubscription).to.be.undefined;\n\n expect(participationWebsocketService.resultObservables.size).to.equal(1);\n expect(participationWebsocketService.resultObservables.get(participation.id!)).to.exist;\n\n expect(participationWebsocketService.participationObservable).to.be.undefined;\n });\n\n it('should setup a result subscriptions with the websocket service on subscribeForLatestResult for students', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n expect(subscribeSpy).to.have.been.calledOnce;\n expect(receiveStub).to.have.been.calledOnce;\n expect(unsubscribeSpy).not.to.have.been.called;\n\n expect(subscribeSpy).to.have.been.calledWithExactly(participationPersonalResultTopic);\n expect(receiveStub).to.have.been.calledWithExactly(participationPersonalResultTopic);\n\n expect(participationWebsocketService.cachedParticipations.size).to.equal(0);\n\n expect(participationWebsocketService.openResultWebsocketSubscriptions.size).to.equal(0);\n expect(participationWebsocketService.openPersonalWebsocketSubscription).to.equal(participationPersonalResultTopic);\n\n expect(participationWebsocketService.resultObservables.size).to.equal(1);\n expect(participationWebsocketService.resultObservables.get(participation.id!)).to.exist;\n\n expect(participationWebsocketService.participationObservable).to.be.undefined;\n });\n\n it('should emit rated result when received through websocket', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participation.id!, resultObservable);\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newRatedResult);\n\n expect(resultSpy).to.have.been.calledOnceWithExactly(newRatedResult);\n });\n\n it('should emit unrated result received through websocket', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participation.id!, resultObservable);\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newUnratedResult);\n\n expect(resultSpy).to.have.been.calledOnceWithExactly(newUnratedResult);\n });\n\n it('should also emit participation update with new result when new rated result arrives through websocket', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n participationWebsocketService.addParticipation(participation);\n participationWebsocketService.subscribeForParticipationChanges();\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participation.id!, resultObservable);\n const participationObservable = new BehaviorSubject(undefined);\n const participationSpy = spy(participationObservable, 'next');\n participationWebsocketService.participationObservable = participationObservable;\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newRatedResult);\n\n expect(resultSpy).to.have.been.calledOnce;\n expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participation, results: [...participation.results!, newRatedResult] });\n expect(participationWebsocketService.cachedParticipations.get(participation.id!)).to.deep.equal({ ...participation, results: [...participation.results!, newRatedResult] });\n });\n\n it('should emit participation update with new result when unrated result arrives through websocket', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n participationWebsocketService.addParticipation(participation);\n participationWebsocketService.subscribeForParticipationChanges();\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participation.id!, resultObservable);\n const participationObservable = new BehaviorSubject(undefined);\n const participationSpy = spy(participationObservable, 'next');\n participationWebsocketService.participationObservable = participationObservable;\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newUnratedResult);\n\n expect(resultSpy).to.have.been.calledOnceWithExactly(newUnratedResult);\n expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participation, results: [...participation.results!, newUnratedResult] });\n expect(participationWebsocketService.cachedParticipations.get(participation.id!)).to.deep.equal({\n ...participation,\n results: [...participation.results!, newUnratedResult],\n });\n });\n\n it('should attach the result to right participation if multiple participations are cached', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation2.id!, true);\n participationWebsocketService.addParticipation(participation);\n participationWebsocketService.addParticipation(participation2);\n participationWebsocketService.subscribeForParticipationChanges();\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participation.id!, resultObservable);\n const participationObservable = new BehaviorSubject(undefined);\n const participationSpy = spy(participationObservable, 'next');\n participationWebsocketService.participationObservable = participationObservable;\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newRatedResult);\n\n expect(participationWebsocketService.cachedParticipations.size).to.equal(2);\n expect(participationWebsocketService.cachedParticipations.get(participation.id!)).to.deep.equal({ ...participation, results: [...participation.results!, newRatedResult] });\n expect(participationWebsocketService.cachedParticipations.get(participation2.id!)).to.deep.equal(participation2);\n\n expect(resultSpy).to.have.been.calledOnceWithExactly(newRatedResult);\n expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participation, results: [...participation.results!, newRatedResult] });\n });\n\n /* eslint-disable no-unused-vars */\n it('should attach the result to participation if the participation has undefined for results value', () => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { results, ...participationWithoutResult } = participation;\n\n participationWebsocketService.subscribeForLatestResultOfParticipation(participationWithoutResult.id!, true);\n participationWebsocketService.addParticipation(participationWithoutResult as Participation);\n participationWebsocketService.subscribeForParticipationChanges();\n const resultObservable = new BehaviorSubject(undefined);\n const resultSpy = spy(resultObservable, 'next');\n participationWebsocketService.resultObservables.set(participationWithoutResult.id!, resultObservable);\n const participationObservable = new BehaviorSubject(undefined);\n const participationSpy = spy(participationObservable, 'next');\n participationWebsocketService.participationObservable = participationObservable;\n\n // Emit new result from websocket\n receiveResultForParticipationSubject.next(newRatedResult);\n\n expect(participationWebsocketService.cachedParticipations.size).to.equal(1);\n expect(participationWebsocketService.cachedParticipations.get(participationWithoutResult.id!)).to.deep.equal({ ...participationWithoutResult, results: [newRatedResult] });\n\n expect(resultSpy).to.have.been.calledOnceWithExactly(newRatedResult);\n expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participationWithoutResult, results: [newRatedResult] });\n });\n /* eslint-enable no-unused-vars */\n\n it('should reset the local cache', () => {\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation.id!, true);\n participationWebsocketService.subscribeForLatestResultOfParticipation(participation2.id!, false, participation2.exercise!.id);\n participationWebsocketService.addParticipation(participation);\n participationWebsocketService.addParticipation(participation2);\n\n expect(participationWebsocketService.openPersonalWebsocketSubscription).to.equal(participationPersonalResultTopic);\n expect(participationWebsocketService.openResultWebsocketSubscriptions.size).to.equal(1);\n\n participationWebsocketService.resetLocalCache();\n\n expect(participationWebsocketService.openPersonalWebsocketSubscription).to.be.undefined;\n expect(participationWebsocketService.openResultWebsocketSubscriptions.size).to.equal(0);\n });\n\n it('should return the cached participation after adding it', () => {\n expect(participationWebsocketService.getParticipationForExercise(participation.exercise!.id!)).to.be.undefined;\n\n participationWebsocketService.addParticipation(participation);\n\n expect(participationWebsocketService.getParticipationForExercise(participation.exercise!.id!)).to.deep.equal(participation);\n });\n});\n" }, { "alpha_fraction": 0.6243061423301697, "alphanum_fraction": 0.6255643367767334, "avg_line_length": 43.73841094970703, "blob_id": "83c056c23ed8ad00aed37d55e40b0fb9dcaafff5", "content_id": "b3926982dfb5e6af4e2088263b9a218e97c425e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13511, "license_type": "permissive", "max_line_length": 153, "num_lines": 302, "path": "/src/main/webapp/app/exercises/programming/manage/instructions-editor/programming-exercise-editable-instruction.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, EventEmitter, Input, OnChanges, OnDestroy, Output, SimpleChanges, ViewChild, ViewEncapsulation } from '@angular/core';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Interactable } from '@interactjs/core/Interactable';\nimport interact from 'interactjs';\nimport { Observable, of, Subject, Subscription, throwError } from 'rxjs';\nimport { catchError, map as rxMap, switchMap, tap } from 'rxjs/operators';\nimport { compose, filter, flatten, map, sortBy, toPairs, values } from 'lodash/fp';\nimport { TaskCommand } from 'app/shared/markdown-editor/domainCommands/programming-exercise/task.command';\nimport { TestCaseCommand } from 'app/shared/markdown-editor/domainCommands/programming-exercise/testCase.command';\nimport { ProgrammingExerciseTestCase } from 'app/entities/programming-exercise-test-case.model';\nimport { TaskHintCommand } from 'app/shared/markdown-editor/domainCommands/programming-exercise/task-hint.command';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ProblemStatementAnalysis } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.model';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { hasExerciseChanged } from 'app/exercises/shared/exercise/exercise-utils';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { DomainCommand } from 'app/shared/markdown-editor/domainCommands/domainCommand';\nimport { ProgrammingExerciseGradingService } from 'app/exercises/programming/manage/services/programming-exercise-grading.service';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { Result } from 'app/entities/result.model';\n\n@Component({\n selector: 'jhi-programming-exercise-editable-instructions',\n templateUrl: './programming-exercise-editable-instruction.component.html',\n styleUrls: ['./programming-exercise-editable-instruction.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class ProgrammingExerciseEditableInstructionComponent implements AfterViewInit, OnChanges, OnDestroy {\n participationValue: Participation;\n exerciseValue: ProgrammingExercise;\n\n exerciseTestCases: string[] = [];\n exerciseHints: ExerciseHint[];\n\n taskCommand = new TaskCommand();\n taskRegex = this.taskCommand.getTagRegex('g');\n testCaseCommand = new TestCaseCommand();\n taskHintCommand = new TaskHintCommand();\n katexCommand = new KatexCommand();\n domainCommands: DomainCommand[] = [this.katexCommand, this.taskCommand, this.testCaseCommand, this.taskHintCommand];\n\n savingInstructions = false;\n unsavedChangesValue = false;\n\n interactResizable: Interactable;\n\n testCaseSubscription: Subscription;\n forceRenderSubscription: Subscription;\n\n @ViewChild(MarkdownEditorComponent, { static: false }) markdownEditor: MarkdownEditorComponent;\n\n @Input() showStatus = true;\n // If the programming exercise is being created, some features have to be disabled (saving the problemStatement & querying test cases).\n @Input() editMode = true;\n @Input() enableResize = true;\n @Input() showSaveButton = false;\n @Input() templateParticipation: Participation;\n @Input() forceRender: Observable<void>;\n @Input()\n get exercise() {\n return this.exerciseValue;\n }\n @Input()\n get participation() {\n return this.participationValue;\n }\n\n @Output() participationChange = new EventEmitter<Participation>();\n @Output() hasUnsavedChanges = new EventEmitter<boolean>();\n @Output() exerciseChange = new EventEmitter<ProgrammingExercise>();\n generateHtmlSubject: Subject<void> = new Subject<void>();\n\n set participation(participation: Participation) {\n this.participationValue = participation;\n this.participationChange.emit(this.participationValue);\n }\n\n set exercise(exercise: ProgrammingExercise) {\n if (this.exerciseValue && exercise.problemStatement !== this.exerciseValue.problemStatement) {\n this.unsavedChanges = true;\n }\n this.exerciseValue = exercise;\n this.exerciseChange.emit(this.exerciseValue);\n }\n\n set unsavedChanges(hasChanges: boolean) {\n this.unsavedChangesValue = hasChanges;\n if (hasChanges) {\n this.hasUnsavedChanges.emit(hasChanges);\n }\n }\n\n constructor(\n private programmingExerciseService: ProgrammingExerciseService,\n private jhiAlertService: JhiAlertService,\n private programmingExerciseParticipationService: ProgrammingExerciseParticipationService,\n private testCaseService: ProgrammingExerciseGradingService,\n private exerciseHintService: ExerciseHintService,\n ) {}\n\n ngOnChanges(changes: SimpleChanges): void {\n if (hasExerciseChanged(changes)) {\n this.setupTestCaseSubscription();\n if (this.exercise.exerciseHints) {\n this.exerciseHints = this.exercise.exerciseHints;\n this.prepareTaskHints();\n } else {\n if (this.exercise.id) {\n this.loadExerciseHints(this.exercise.id);\n } else {\n this.exerciseHints = [];\n }\n }\n }\n }\n\n ngOnDestroy(): void {\n if (this.testCaseSubscription) {\n this.testCaseSubscription.unsubscribe();\n }\n if (this.forceRenderSubscription) {\n this.forceRenderSubscription.unsubscribe();\n }\n }\n\n ngAfterViewInit() {\n this.interactResizable = interact('.editable-instruction-container')\n .resizable({\n // Enable resize from top edge; triggered by class rg-top\n edges: { left: false, right: false, bottom: '.rg-bottom', top: false },\n // Set min and max height\n modifiers: [\n // Set maximum width\n interact.modifiers!.restrictSize({\n min: { width: 0, height: 200 },\n max: { width: 2000, height: 1200 },\n }),\n ],\n inertia: true,\n })\n .on('resizestart', function (event: any) {\n event.target.classList.add('card-resizable');\n })\n .on('resizeend', (event: any) => {\n event.target.classList.remove('card-resizable');\n this.markdownEditor.aceEditorContainer.getEditor().resize();\n })\n .on('resizemove', function (event: any) {\n // The first child is the markdown editor.\n const target = event.target.children && event.target.children[0];\n if (target) {\n // Update element height\n target.style.height = event.rect.height + 'px';\n }\n });\n\n // If forced to render, generate the instruction HTML.\n if (this.forceRender) {\n this.forceRenderSubscription = this.forceRender.subscribe(() => this.generateHtml());\n }\n }\n\n /**\n * Load the exercise hints and assign them to the task hint command.\n *\n * @param exerciseId for which to load the exercise hints.\n */\n loadExerciseHints(exerciseId: number) {\n this.exerciseHintService\n .findByExerciseId(exerciseId)\n .pipe(rxMap(({ body }) => body || []))\n .subscribe((exerciseHints: ExerciseHint[]) => {\n this.exerciseHints = exerciseHints;\n this.prepareTaskHints();\n });\n }\n\n /**\n * Prepares the task hints using exerciseHints\n */\n private prepareTaskHints() {\n this.taskHintCommand.setValues(this.exerciseHints.map(({ id, title }) => ({ id: id!.toString(10), value: title! })));\n }\n\n /** Save the problem statement on the server.\n * @param $event\n **/\n saveInstructions($event: any) {\n $event.stopPropagation();\n this.savingInstructions = true;\n return this.programmingExerciseService\n .updateProblemStatement(this.exercise.id!, this.exercise.problemStatement!)\n .pipe(\n tap(() => {\n this.unsavedChanges = false;\n }),\n catchError(() => {\n // TODO: move to programming exercise translations\n this.jhiAlertService.error(`artemisApp.editor.errors.problemStatementCouldNotBeUpdated`);\n return of(undefined);\n }),\n )\n .subscribe(() => {\n this.savingInstructions = false;\n });\n }\n\n updateProblemStatement(problemStatement: string) {\n if (this.exercise.problemStatement !== problemStatement) {\n this.exercise = { ...this.exercise, problemStatement };\n this.unsavedChanges = true;\n }\n }\n\n /**\n * Signal that the markdown should be rendered into html.\n */\n generateHtml() {\n this.generateHtmlSubject.next();\n }\n\n private setupTestCaseSubscription() {\n if (this.testCaseSubscription) {\n this.testCaseSubscription.unsubscribe();\n }\n\n // Only set up a subscription for test cases if the exercise already exists.\n if (this.editMode) {\n this.testCaseSubscription = this.testCaseService\n .subscribeForTestCases(this.exercise.id!)\n .pipe(\n switchMap((testCases: ProgrammingExerciseTestCase[] | undefined) => {\n // If there are test cases, map them to their names, sort them and use them for the markdown editor.\n if (testCases) {\n const sortedTestCaseNames = compose(\n map(({ testName }) => testName),\n filter(({ active }) => active),\n sortBy('testName'),\n )(testCases);\n return of(sortedTestCaseNames);\n } else if (this.exercise.templateParticipation) {\n // Legacy case: If there are no test cases, but a template participation, use its feedbacks for generating test names.\n return this.loadTestCasesFromTemplateParticipationResult(this.exercise.templateParticipation!.id!);\n }\n return of();\n }),\n tap((testCaseNames: string[]) => {\n this.exerciseTestCases = testCaseNames;\n this.testCaseCommand.setValues(this.exerciseTestCases.map((value) => ({ value, id: value })));\n }),\n catchError(() => of()),\n )\n .subscribe();\n }\n }\n\n /**\n * Generate test case names from the feedback of the exercise's templateParticipation.\n * This is the fallback for older programming exercises without test cases in the database.\n * @param templateParticipationId\n */\n loadTestCasesFromTemplateParticipationResult = (templateParticipationId: number): Observable<string[]> => {\n // Fallback for exercises that don't have test cases yet.\n return this.programmingExerciseParticipationService.getLatestResultWithFeedback(templateParticipationId).pipe(\n rxMap((result) => (!result || !result.feedbacks ? throwError('no result available') : result)),\n rxMap(({ feedbacks }: Result) =>\n compose(\n map(({ text }) => text),\n sortBy('text'),\n )(feedbacks),\n ),\n catchError(() => of([])),\n );\n };\n\n /**\n * On every update of the problem statement analysis, update the appropriate line numbers of the editor with the resuls of the analysis.\n * Will show warning symbols for every item.\n *\n * @param analysis that contains the resulting issues of the problem statement.\n */\n onAnalysisUpdate = (analysis: ProblemStatementAnalysis) => {\n const mapIssuesToAnnotations = ([lineNumber, issues]: [number, { [issueType: string]: string[] }]) =>\n compose(\n map((analysisIssues: string[]) => ({ row: lineNumber, column: 0, text: ' - ' + analysisIssues.join('\\n - '), type: 'warning' })),\n values,\n )(issues);\n\n const lineWarnings = compose(flatten, map(mapIssuesToAnnotations), toPairs)(analysis);\n\n this.markdownEditor.aceEditorContainer.getEditor().getSession().clearAnnotations();\n // We need to wait for the annotations to be removed before we can set the new annotations.\n // Otherwise changes in the editor will trigger the update of the existing annotations.\n setTimeout(() => {\n this.markdownEditor.aceEditorContainer.getEditor().getSession().setAnnotations(lineWarnings);\n }, 0);\n };\n}\n" }, { "alpha_fraction": 0.7120895385742188, "alphanum_fraction": 0.7161480784416199, "avg_line_length": 51.121795654296875, "blob_id": "6bba23b23dc53963b5adb8ca899072d269b188d0", "content_id": "144a8096e458a7f88bb775e1e98729c724f9258c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8131, "license_type": "permissive", "max_line_length": 150, "num_lines": 156, "path": "/src/test/javascript/spec/service/ide-build-and-test.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { TestBed } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { MockProgrammingSubmissionService } from '../helpers/mocks/service/mock-programming-submission.service';\nimport { Result } from 'app/entities/result.model';\nimport { BehaviorSubject, of } from 'rxjs';\nimport { Feedback, FeedbackType, STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER } from 'app/entities/feedback.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { BuildLogService } from 'app/exercises/programming/shared/service/build-log.service';\nimport { MockParticipationWebsocketService } from '../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockCodeEditorBuildLogService } from '../helpers/mocks/service/mock-code-editor-build-log.service';\nimport { OrionBuildAndTestService } from 'app/shared/orion/orion-build-and-test.service';\nimport { OrionConnectorService } from 'app/shared/orion/orion-connector.service';\nimport { MockOrionConnectorService } from '../helpers/mocks/service/mock-orion-connector.service';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { ArtemisTestModule } from '../test.module';\nimport { SubmissionService } from 'app/exercises/shared/submission/submission.service';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('IdeBuildAndTestService', () => {\n let serviceUnderTest: OrionBuildAndTestService;\n\n let onBuildFinishedSpy: SinonSpy;\n let onBuildStartedSpy: SinonSpy;\n let onTestResultSpy: SinonSpy;\n let onBuildFailedSpy: SinonSpy;\n let buildLogsStub: SinonStub;\n let participationSubscriptionStub: SinonStub;\n\n const feedbacks = [{ id: 2, positive: false, detailText: 'abc' } as Feedback, { id: 3, positive: true, detailText: 'cde' } as Feedback];\n const feedbacksWithStaticCodeAnalysis = [\n ...feedbacks,\n { id: 3, positive: false, detailText: 'fgh', type: FeedbackType.AUTOMATIC, text: STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER + 'a' } as Feedback,\n { id: 4, positive: false, detailText: 'ijk', type: FeedbackType.AUTOMATIC, text: STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER + 'b' } as Feedback,\n ];\n const result = { id: 1 } as Result;\n const submissionFailed = { id: 1, buildFailed: true } as ProgrammingSubmission;\n const submissionSuccess = { id: 1, buildFailed: false } as ProgrammingSubmission;\n const exercise = { id: 42, studentParticipations: [{ id: 32 }] } as ProgrammingExercise;\n const logs = [\n {\n time: '2019-05-15T10:32:11+02:00',\n log: '[ERROR] COMPILATION ERROR : ',\n },\n ];\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n providers: [\n OrionBuildAndTestService,\n { provide: SubmissionService, useClass: MockProgrammingSubmissionService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: OrionConnectorService, useClass: MockOrionConnectorService },\n { provide: BuildLogService, useClass: MockCodeEditorBuildLogService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n });\n\n serviceUnderTest = TestBed.inject(OrionBuildAndTestService);\n const javaBridge = TestBed.inject(OrionConnectorService);\n const buildLogService = TestBed.inject(BuildLogService);\n const participationService = TestBed.inject(ParticipationWebsocketService);\n\n onBuildFinishedSpy = spy(javaBridge, 'onBuildFinished');\n onBuildStartedSpy = spy(javaBridge, 'onBuildStarted');\n onTestResultSpy = spy(javaBridge, 'onTestResult');\n onBuildFailedSpy = spy(javaBridge, 'onBuildFailed');\n buildLogsStub = stub(buildLogService, 'getBuildLogs');\n participationSubscriptionStub = stub(participationService, 'subscribeForLatestResultOfParticipation');\n });\n\n afterEach(() => {\n onBuildFinishedSpy.restore();\n onBuildStartedSpy.restore();\n onTestResultSpy.restore();\n onBuildFailedSpy.restore();\n buildLogsStub.restore();\n participationSubscriptionStub.restore();\n });\n\n it('should fetch the build logs if submission is not available', () => {\n buildLogsStub.returns(of(logs));\n result.feedbacks = feedbacks;\n const subject = new BehaviorSubject(result);\n participationSubscriptionStub.returns(subject);\n\n serviceUnderTest.listenOnBuildOutputAndForwardChanges(exercise);\n\n expect(participationSubscriptionStub).to.have.been.calledOnceWithExactly(exercise.studentParticipations![0].id, true);\n expect(onBuildStartedSpy).to.have.been.called.calledOnce;\n expect(onTestResultSpy).to.not.have.been.called;\n expect(onBuildFinishedSpy).to.not.have.been.called;\n expect(onBuildFailedSpy).to.have.been.calledOnce;\n expect(buildLogsStub).to.have.been.calledOnce;\n });\n\n it('should fetch the build logs if submission is available and the submission could not be build', () => {\n buildLogsStub.returns(of(logs));\n result.feedbacks = feedbacks;\n result.submission = submissionFailed;\n const subject = new BehaviorSubject(result);\n participationSubscriptionStub.returns(subject);\n\n serviceUnderTest.listenOnBuildOutputAndForwardChanges(exercise);\n\n expect(participationSubscriptionStub).to.have.been.calledOnceWithExactly(exercise.studentParticipations![0].id, true);\n expect(onBuildStartedSpy).to.have.been.called.calledOnce;\n expect(onTestResultSpy).to.not.have.been.called;\n expect(onBuildFinishedSpy).to.not.have.been.called;\n expect(onBuildFailedSpy).to.have.been.calledOnce;\n expect(buildLogsStub).to.have.been.calledOnce;\n });\n\n it('should forward all testcase feedback if build was successful', () => {\n result.feedbacks = feedbacks;\n result.submission = submissionSuccess;\n const subject = new BehaviorSubject(result);\n participationSubscriptionStub.returns(subject);\n\n serviceUnderTest.listenOnBuildOutputAndForwardChanges(exercise);\n\n expect(participationSubscriptionStub).to.have.been.calledOnceWithExactly(exercise.studentParticipations![0].id, true);\n expect(onBuildStartedSpy).to.have.been.called.calledOnce;\n expect(onTestResultSpy).to.have.been.calledTwice;\n expect(onBuildFinishedSpy).to.have.been.calledOnce;\n expect(onBuildFailedSpy).to.not.have.been.called;\n expect(buildLogsStub).to.not.have.been.called;\n });\n\n it('should filter out static code analysis feedback before forwarding the test case feedback', () => {\n result.feedbacks = feedbacksWithStaticCodeAnalysis;\n result.submission = submissionSuccess;\n const subject = new BehaviorSubject(result);\n participationSubscriptionStub.returns(subject);\n\n serviceUnderTest.listenOnBuildOutputAndForwardChanges(exercise);\n\n expect(participationSubscriptionStub).to.have.been.calledOnceWithExactly(exercise.studentParticipations![0].id, true);\n expect(onBuildStartedSpy).to.have.been.called.calledOnce;\n expect(onTestResultSpy).to.have.been.calledTwice;\n feedbacks.forEach((feedback, index) => {\n expect(onTestResultSpy.getCall(index)).to.have.been.calledWithExactly(feedback.positive, feedback.text, feedback.detailText);\n });\n expect(onBuildFinishedSpy).to.have.been.calledOnce;\n expect(onBuildFailedSpy).to.not.have.been.called;\n expect(buildLogsStub).to.not.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.7753946781158447, "alphanum_fraction": 0.7848666310310364, "avg_line_length": 57.5031852722168, "blob_id": "c038a75ff5cbc236f99f23c6a93818eb9d3d461a", "content_id": "3e0001eb15fc7eefcd66bb702170b32b44b6c506", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9187, "license_type": "permissive", "max_line_length": 407, "num_lines": 157, "path": "/README.md", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "# Artemis: Interactive Learning with Individual Feedback \n\n[![Build Status](https://github.com/ls1intum/Artemis/workflows/Build/badge.svg)](https://github.com/ls1intum/Artemis/actions?query=branch%3Adevelop+workflow%3ABuild)\n[![Test Status](https://github.com/ls1intum/Artemis/workflows/Test/badge.svg)](https://github.com/ls1intum/Artemis/actions?query=branch%3Adevelop+workflow%3ATest)\n[![Documentation Status](https://readthedocs.org/projects/artemis-platform/badge/?version=latest)](https://artemis-platform.readthedocs.io/en/latest/?badge=latest)\n[![Dependency Status](https://img.shields.io/david/ls1intum/Artemis)](package.json)\n[![Dev Dependency Status](https://img.shields.io/david/dev/ls1intum/Artemis)](package.json)\n[![Code Quality Status](https://app.codacy.com/project/badge/Grade/89860aea5fa74d998ec884f1a875ed0c)](https://www.codacy.com/gh/ls1intum/Artemis?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=ls1intum/Artemis&amp;utm_campaign=Badge_Grade)\n[![Coverage Status](https://app.codacy.com/project/badge/Coverage/89860aea5fa74d998ec884f1a875ed0c)](https://www.codacy.com/gh/ls1intum/Artemis?utm_source=github.com&utm_medium=referral&utm_content=ls1intum/Artemis&utm_campaign=Badge_Coverage)\n\nArtemis was initially generated using JHipster 6.10.3. ([Documentation and help](http://www.jhipster.tech/documentation-archive/v6.10.3))\n\n[![Latest version)](https://img.shields.io/github/v/tag/ls1intum/Artemis?label=%20Latest%20version&sort=semver)](https://github.com/ls1intum/Artemis/releases/latest)\n\n## Main features\nArtemis supports the following exercises:\n1. **[Programming exercises](docs/user/exercises/programming.rst)** with version control and automatic assessment with test cases and continuous integration\n2. **[Quiz exercises](docs/user/exercises/quiz.rst)** with multiple choice, drag and drop and short answer quiz questions\n3. **[Modeling exercises](docs/user/exercises/modeling.rst)** with semi-automatic assessment using machine learning concepts\n4. **[Text exercises](docs/user/exercises/textual.rst)** with manual (and experimental semi-automatic) assessment\n5. **[File upload exercises](docs/user/exercises/file-upload.rst)** with manual assessment\n\nArtemis supports all these exercises to run either live in the lecture with instant feedback or as homework. Students can submit their solutions multiple times within the due date and use the (semi-)automatically provided feedback to improve their solution.\n\nArtemis also supports an exam mode now. You can find more information on [Exam mode student features](https://artemis.ase.in.tum.de/features/students) and on [Exam mode instructor features](https://artemis.ase.in.tum.de/features/instructors).\n\n## Setup, guides and contributing\n\n### Development setup, coding and design guidelines\n\n* [How to set up your local development environment](docs/dev/setup.rst)\n* [Server coding and design guidelines](docs/dev/guidelines/server.rst)\n* [Client coding and design guidelines](docs/dev/guidelines/client.rst)\n\n### Documentation\n\n[Read the Docs](https://readthedocs.org) hosts the [Artemis documentation](https://artemis-platform.readthedocs.io).\nYou can find a guide on [how to write documentation](docs/README.md).\n\n### Server setup\n\nYou can find the guide for setting up Artemis in conjunction with either `GitLab and Jenkins` [here](docs/dev/setup/jenkins-gitlab.rst) or with `Jira, Bitbucket and Bamboo` [here](docs/dev/setup/bamboo-bitbucket-jira.rst).\nArtemis uses these external tools for user management and the configuration of programming exercises.\n\n### Administration setup\n\nYou can find information on how to set up user registration [here](docs/admin/registration.rst)\n\n### Contributing \n\nPlease read the guide on [how to contribute](/CONTRIBUTING.md) to Artemis.\n\n### Building for production\n\nTo build and optimize the Artemis application for production, run:\n\n```\n./gradlew -Pprod -Pwar clean bootWar\n```\n\nThis will create a Artemis-<version>.war file in the folder `build/libs`. The build command compiles the TypeScript into JavaScript files, concatenates and minifies the created files (including HTML and CSS files). It will also modify `index.html` so it references these new files. To ensure everything worked, run the following command to start the application on your local computer:\n\n```\njava -jar build/libs/*.war --spring.profiles.active=dev,artemis,bamboo,bitbucket,jira\n```\n\n(You might need to copy a yml file into the folder build/libs before, also see [development setup](/docs/dev/setup.rst))\n\nThen navigate to [http://localhost:8080](http://localhost:8080) in your browser.\n\nRefer to [Using JHipster in production](http://www.jhipster.tech/production) for more details.\n\nThe following command can automate the deployment to a server. The example shows the deployment to the main Artemis test server (which runs a virtual machine):\n\n```\n./artemis-server-cli deploy [email protected] -w build/libs/Artemis-4.4.5.war\n```\n\n## Architecture\n\nThe following diagram shows the top level design of Artemis which is decomposed into an application client (running as Angular web app in the browser) and an application server (based on Spring Boot). For programming exercises, the application server connects to a version control system (VCS) and a continuous integration system (CIS). Authentication is handled by an external user management system (UMS).\n\n![Top-Level Design](docs/dev/system-design/TopLevelDesign.png \"Top-Level Design\")\n\nWhile Artemis includes generic adapters to these three external systems with a defined protocol that can be instantiated to connect to any VCS, CIS or UMS, it also provides 3 concrete implementations for these adapters to connect to:\n\n1. **VCS:** Atlassian Bitbucket Server\n2. **CIS:** Atlassian Bamboo Server\n3. **UMS:** Atlassian JIRA Server (more specifically Atlassian Crowd on the JIRA Server)\n\n### Server architecture\n\nThe following UML component diagram shows more details of the Artemis application server architecture and its REST interfaces to the application client.\n\n![Server Architecture](docs/dev/system-design/ServerArchitecture.png \"Server Architecture\")\n\n### Deployment\n\nThe following UML deployment diagram shows a typical deployment of Artemis application server and application client. Student, Instructor and Teaching Assistant (TA) computers are all equipped equally with the Artemis application client being displayed in the browser.\n\nThe Continuous Integration Server typically delegates the build jobs to local build agents within the university infrastructure or to remote build agents, e.g. hosted in the Amazon Cloud (AWS).\n\n![Deployment Overview](docs/dev/system-design/DeploymentOverview.svg \"Deployment Overview\")\n\n### Data model\n\nThe Artemis application server uses the following (simplified) data model in the MySQL database. It supports multiple courses with multiple exercises. Each student in the participating student group can participate in the exercise by clicking the **Start Exercise** button. \nThen a repository and a build plan for the student (User) will be created and configured. The initialization state helps to track the progress of this complex operation and allows recovering from errors. \nA student can submit multiple solutions by committing and pushing the source code changes to a given example code into the version control system or using the user interface. The continuous integration server automatically tests each submission, and notifies the Artemis application server, when a new result exists. \nIn addition, teaching assistants can assess student solutions and \"manually\" create results.\n\n![Data Model](docs/dev/system-design/DataModel.svg \"Data Model\")\n\nPlease note, that the actual database model is more complex. The UML class diagram above omits some details for readability (e.g. lectures, student questions, exercise details, static code analysis, quiz questions, exam sessions, submission subclasses, etc.)\n\n### Artemis Community\n\nThere is a growing community of university instructors who are using Artemis.\n\n#### Communication\n\nWe communicate using Github issues and pull requests. Additionally, you can join us on Slack to ask questions and get support. If you are interested, please send an email to [Stephan Krusche](mailto:[email protected]).\n\n#### Universities with Artemis in Use\n\nThe following universities are actively using Artemis or are currently evaluating Artemis.\n\n##### Technical University of Munich\n\n* https://artemis.ase.in.tum.de \n* Main contact person: [Stephan Krusche](mailto:[email protected])\n\n##### LFU Innsbruck, Uni Salzburg, JKU Linz, AAU Klagenfurt, TU Wien\n\n* https://artemis.codeability.uibk.ac.at\n* [codeAbility project](https://codeability.uibk.ac.at)\n* Main contact person: [Michael Breu](mailto:[email protected])\n\n##### University of Stuttgart\n\n* https://artemis.sqa.ddnss.org\n* Main contact person: [Steffen Becker](mailto:[email protected])\n\n##### Universität Bonn\n\n* https://alpro.besec.uni-bonn.de \n* Main contact person: [Alexander von Trostorff](mailto:[email protected])\n\n##### Universität Passau\n\n* https://artemis.se2.fim.uni-passau.de\n* Main contact person: [Christian Bachmaier](mailto:[email protected])\n\n##### Karlsruhe Institute of Technology\n\n* https://artemis.praktomat.cs.kit.edu\n* Main contact person: [Dominik Fuchß](mailto:[email protected])\n" }, { "alpha_fraction": 0.74686598777771, "alphanum_fraction": 0.7478302717208862, "avg_line_length": 36.70909118652344, "blob_id": "616703abb44c57411085d70e80615555f3d2a4b9", "content_id": "639f33f369ae1a7e297d483de434af0fe0f8568d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2074, "license_type": "permissive", "max_line_length": 150, "num_lines": 55, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsAuthorizationInterceptor.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.jenkins;\n\nimport java.io.IOException;\nimport java.net.URL;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.*;\nimport org.springframework.http.client.ClientHttpRequestExecution;\nimport org.springframework.http.client.ClientHttpRequestInterceptor;\nimport org.springframework.http.client.ClientHttpResponse;\nimport org.springframework.stereotype.Component;\nimport org.springframework.web.client.RestTemplate;\n\nimport com.fasterxml.jackson.databind.JsonNode;\n\n@Profile(\"jenkins\")\n@Component\npublic class JenkinsAuthorizationInterceptor implements ClientHttpRequestInterceptor {\n\n @Value(\"${artemis.continuous-integration.user}\")\n private String username;\n\n @Value(\"${artemis.continuous-integration.password}\")\n private String password;\n\n @Value(\"${artemis.continuous-integration.url}\")\n private URL jenkinsURL;\n\n @Value(\"${jenkins.use-crumb:#{true}}\")\n private boolean useCrumb;\n\n @NotNull\n @Override\n public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {\n request.getHeaders().setBasicAuth(username, password);\n if (useCrumb) {\n setCrumb(request.getHeaders());\n }\n return execution.execute(request, body);\n }\n\n private void setCrumb(final HttpHeaders headersToAuthenticate) {\n final var headers = new HttpHeaders();\n headers.setBasicAuth(username, password);\n final var entity = new HttpEntity<>(headers);\n\n final var response = new RestTemplate().exchange(jenkinsURL.toString() + \"/crumbIssuer/api/json\", HttpMethod.GET, entity, JsonNode.class);\n final var sessionId = response.getHeaders().get(\"Set-Cookie\").get(0);\n headersToAuthenticate.add(\"Jenkins-Crumb\", response.getBody().get(\"crumb\").asText());\n headersToAuthenticate.add(\"Cookie\", sessionId);\n }\n}\n" }, { "alpha_fraction": 0.694307267665863, "alphanum_fraction": 0.694307267665863, "avg_line_length": 47.087501525878906, "blob_id": "30cb2eb1f5d904c5ee6fbb1bb28c28964b7c07cb", "content_id": "769450b58dab1496472a0853bfa498d5d1a321c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3847, "license_type": "permissive", "max_line_length": 151, "num_lines": 80, "path": "/src/test/javascript/spec/component/learning-goals/learning-goal-detail-modal.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { LearningGoalDetailModalComponent } from 'app/course/learning-goals/learning-goal-detail-modal/learning-goal-detail-modal.component';\nimport { IndividualLearningGoalProgress, IndividualLectureUnitProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { SortService } from 'app/shared/service/sort.service';\nimport * as chai from 'chai';\nimport { JhiSortByDirective, JhiSortDirective, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('LearningGoalDetailModalComponent', () => {\n let learningGoalDetailModalComponentFixture: ComponentFixture<LearningGoalDetailModalComponent>;\n let learningGoalDetailModalComponent: LearningGoalDetailModalComponent;\n\n const activeModalStub = {\n close: () => {},\n dismiss: () => {},\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([])],\n declarations: [\n MockPipe(ArtemisTranslatePipe),\n MockDirective(JhiTranslateDirective),\n MockDirective(JhiSortDirective),\n LearningGoalDetailModalComponent,\n MockDirective(JhiSortByDirective),\n MockComponent(FaIconComponent),\n ],\n providers: [\n MockProvider(SortService),\n {\n provide: NgbActiveModal,\n useValue: activeModalStub,\n },\n MockProvider(LectureUnitService),\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n learningGoalDetailModalComponentFixture = TestBed.createComponent(LearningGoalDetailModalComponent);\n learningGoalDetailModalComponent = learningGoalDetailModalComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n learningGoalDetailModalComponentFixture.detectChanges();\n expect(learningGoalDetailModalComponent).to.be.ok;\n });\n\n it('should call sort service', fakeAsync(() => {\n const learningGoal = new LearningGoal();\n learningGoal.lectureUnits = [new TextUnit(), new VideoUnit()];\n const learningGoalProgress = new IndividualLearningGoalProgress();\n learningGoalProgress.progressInLectureUnits = [new IndividualLectureUnitProgress(), new IndividualLectureUnitProgress()];\n learningGoalDetailModalComponent.learningGoal = learningGoal;\n learningGoalDetailModalComponent.learningGoalProgress = learningGoalProgress;\n learningGoalDetailModalComponentFixture.detectChanges();\n const sortService = TestBed.inject(SortService);\n const sortByPropertySpy = sinon.spy(sortService, 'sortByProperty');\n learningGoalDetailModalComponent.sortConnectedLectureUnits();\n expect(sortByPropertySpy).to.have.been.calledOnce;\n }));\n});\n" }, { "alpha_fraction": 0.6660893559455872, "alphanum_fraction": 0.6676480770111084, "avg_line_length": 39.377620697021484, "blob_id": "2698bbae41e7792800f42b81447ad56285c7e2fb", "content_id": "e0ca594d46d8b61508ed37c605a84997c05d7b50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5774, "license_type": "permissive", "max_line_length": 138, "num_lines": 143, "path": "/src/test/javascript/spec/component/admin/system-notification-management/system-notification-management.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Directive, HostListener, Input } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ActivatedRoute, Router, RouterEvent, RouterOutlet } from '@angular/router';\nimport { NgbPagination } from '@ng-bootstrap/ng-bootstrap';\nimport { SystemNotificationManagementComponent } from 'app/admin/system-notification-management/system-notification-management.component';\nimport { SystemNotification } from 'app/entities/system-notification.model';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { JhiItemCountComponent, JhiSortDirective } from 'ng-jhipster';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../../helpers/mocks/service/mock-route.service';\nimport { ArtemisTestModule } from '../../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Directive({\n // tslint:disable-next-line:directive-selector\n selector: '[routerLink]',\n})\n// tslint:disable-next-line:directive-class-suffix\nclass RouterLinkSpy {\n @Input()\n routerLink = '';\n\n constructor(private router: Router) {}\n\n @HostListener('click')\n onClick() {\n this.router.navigateByUrl(this.routerLink);\n }\n}\n\ndescribe('SystemNotificationManagementComponent', () => {\n let managementComponentFixture: ComponentFixture<SystemNotificationManagementComponent>;\n let managementComponent: SystemNotificationManagementComponent;\n let router: any;\n\n const route = ({\n data: of({ pagingParams: {} }),\n children: [],\n } as any) as ActivatedRoute;\n\n beforeEach(() => {\n router = new MockRouter();\n router.setEvents(of({ id: 1, url: '' } as RouterEvent));\n\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [\n SystemNotificationManagementComponent,\n MockPipe(ArtemisDatePipe),\n MockPipe(ArtemisTranslatePipe),\n RouterLinkSpy,\n MockDirective(RouterOutlet),\n MockDirective(AlertComponent),\n MockDirective(JhiItemCountComponent),\n MockDirective(DeleteButtonDirective),\n MockDirective(JhiSortDirective),\n MockDirective(NgbPagination),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: Router, useValue: router },\n ],\n })\n .compileComponents()\n .then(() => {\n managementComponentFixture = TestBed.createComponent(SystemNotificationManagementComponent);\n managementComponent = managementComponentFixture.componentInstance;\n router = managementComponentFixture.debugElement.injector.get(Router);\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n managementComponentFixture.detectChanges();\n expect(managementComponent).to.be.ok;\n });\n\n it('navigate to the details page of system notification if details is clicked', fakeAsync(() => {\n const notification = new SystemNotification();\n notification.id = 1;\n notification.expireDate = moment();\n notification.notificationDate = moment();\n managementComponent.notifications = [notification];\n managementComponentFixture.detectChanges();\n\n const button = managementComponentFixture.debugElement.nativeElement.querySelector('#viewButton');\n button.click();\n\n tick();\n expect(router.navigateByUrl).to.have.been.calledOnce;\n const navigationArray = router.navigateByUrl.getCall(0).args[0];\n expect(navigationArray).to.deep.equal(['./', notification.id]);\n }));\n\n it('navigate to the edit page of system notification if details is clicked', fakeAsync(() => {\n const notification = new SystemNotification();\n notification.id = 2;\n notification.expireDate = moment();\n notification.notificationDate = moment();\n managementComponent.notifications = [notification];\n managementComponentFixture.detectChanges();\n\n const button = managementComponentFixture.debugElement.nativeElement.querySelector('#editButton');\n button.click();\n\n tick();\n expect(router.navigateByUrl).to.have.been.calledOnce;\n const navigationArray = router.navigateByUrl.getCall(0).args[0];\n expect(navigationArray).to.deep.equal(['./', notification.id, 'edit']);\n }));\n\n it('should unsubscribe on destroy', () => {\n const routeDataSpy = stub(managementComponent.routeData, 'unsubscribe');\n managementComponentFixture.destroy();\n expect(routeDataSpy).to.have.been.calledOnce;\n });\n\n it('should transition on page change', fakeAsync(() => {\n managementComponent.notifications = [];\n managementComponentFixture.detectChanges();\n\n const pagination = managementComponentFixture.debugElement.nativeElement.querySelector('#pagination');\n pagination.dispatchEvent(new Event('pageChange'));\n\n tick();\n const navigationArray = router.navigate.getCall(0).args[0];\n expect(navigationArray).to.deep.equal(['/admin/system-notification-management']);\n }));\n});\n" }, { "alpha_fraction": 0.6938998103141785, "alphanum_fraction": 0.6938998103141785, "avg_line_length": 30.65517234802246, "blob_id": "2622154c4d510c6fde5d8ce649400c2a209715ac", "content_id": "b4b78834a1c3652c57e1b4904bdf1fe0b3c1f6d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 918, "license_type": "permissive", "max_line_length": 82, "num_lines": 29, "path": "/src/main/webapp/app/exercises/quiz/manage/quiz-confirm-import-invalid-questions-modal.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter } from '@angular/core';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { Reason } from 'app/exercises/quiz/manage/quiz-exercise-detail.component';\n\n@Component({\n selector: 'jhi-quiz-confirm-import-invalid-questions-modal',\n templateUrl: './quiz-confirm-import-invalid-questions-modal.component.html',\n styleUrls: ['./quiz-confirm-import-invalid-questions-modal.scss'],\n})\nexport class QuizConfirmImportInvalidQuestionsModalComponent {\n constructor(public activeModal: NgbActiveModal) {}\n\n invalidFlaggedQuestions: Reason[];\n shouldImport: EventEmitter<void> = new EventEmitter<void>();\n\n /**\n * Reset the git repository.\n *\n * @function resetRepository\n */\n importQuestions() {\n this.activeModal.close();\n this.shouldImport.emit();\n }\n\n closeModal() {\n this.activeModal.dismiss('cancel');\n }\n}\n" }, { "alpha_fraction": 0.6005445718765259, "alphanum_fraction": 0.6029952168464661, "avg_line_length": 35.18226623535156, "blob_id": "4811e545166ab765b4d93692e526e965a8966962", "content_id": "9030bf1d3a7e71c7de414759f9c1b126b02075a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7345, "license_type": "permissive", "max_line_length": 142, "num_lines": 203, "path": "/src/main/webapp/app/lecture/lecture-attachments.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport * as moment from 'moment';\nimport { Subject } from 'rxjs';\nimport { FileService } from 'app/shared/http/file.service';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { AttachmentService } from 'app/lecture/attachment.service';\n\n@Component({\n selector: 'jhi-lecture-attachments',\n templateUrl: './lecture-attachments.component.html',\n styles: [\n `\n .edit-overlay {\n position: absolute;\n left: 0;\n right: 0;\n display: flex;\n justify-content: center;\n background-color: rgba(255, 255, 255, 0.9);\n z-index: 9;\n font-size: 18px;\n }\n `,\n ],\n})\nexport class LectureAttachmentsComponent implements OnInit, OnDestroy {\n @ViewChild('fileInput', { static: false }) fileInput: ElementRef;\n lecture: Lecture;\n attachments: Attachment[] = [];\n attachmentToBeCreated?: Attachment;\n attachmentBackup?: Attachment;\n attachmentFile?: Blob;\n isUploadingAttachment: boolean;\n isDownloadingAttachmentLink?: string;\n notificationText?: string;\n erroredFile?: Blob;\n errorMessage?: string;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(\n protected activatedRoute: ActivatedRoute,\n private attachmentService: AttachmentService,\n private httpClient: HttpClient,\n private fileUploaderService: FileUploaderService,\n private fileService: FileService,\n ) {}\n\n ngOnInit() {\n this.notificationText = undefined;\n this.activatedRoute.parent!.data.subscribe(({ lecture }) => {\n this.lecture = lecture;\n this.attachmentService.findAllByLectureId(this.lecture.id!).subscribe((attachmentsResponse: HttpResponse<Attachment[]>) => {\n this.attachments = attachmentsResponse.body!;\n });\n });\n }\n\n ngOnDestroy(): void {\n this.dialogErrorSource.unsubscribe();\n }\n\n addAttachment() {\n const newAttachment = new Attachment();\n newAttachment.lecture = this.lecture;\n newAttachment.attachmentType = AttachmentType.FILE;\n newAttachment.version = 0;\n newAttachment.uploadDate = moment();\n this.attachmentToBeCreated = newAttachment;\n }\n\n saveAttachment() {\n if (!this.attachmentToBeCreated) {\n return this.addAttachment();\n }\n this.attachmentToBeCreated.version!++;\n this.attachmentToBeCreated.uploadDate = moment();\n\n if (this.attachmentToBeCreated.id) {\n const requestOptions = {} as any;\n if (this.notificationText) {\n requestOptions.notificationText = this.notificationText;\n }\n this.attachmentService.update(this.attachmentToBeCreated, requestOptions).subscribe((attachmentRes: HttpResponse<Attachment>) => {\n this.attachmentToBeCreated = undefined;\n this.attachmentBackup = undefined;\n this.notificationText = undefined;\n this.attachments = this.attachments.map((el) => {\n return el.id === attachmentRes.body!.id ? attachmentRes.body! : el;\n });\n });\n } else {\n this.attachmentService.create(this.attachmentToBeCreated!).subscribe((attachmentRes: HttpResponse<Attachment>) => {\n this.attachments.push(attachmentRes.body!);\n this.attachmentToBeCreated = undefined;\n this.attachmentBackup = undefined;\n });\n }\n }\n\n editAttachment(attachment: Attachment) {\n this.attachmentToBeCreated = attachment;\n this.attachmentBackup = Object.assign({}, attachment, {});\n }\n\n deleteAttachment(attachment: Attachment) {\n this.attachmentService.delete(attachment.id!).subscribe(\n () => {\n this.attachments = this.attachments.filter((el) => el.id !== attachment.id);\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n cancel() {\n if (this.attachmentBackup) {\n this.resetAttachment();\n }\n this.attachmentToBeCreated = undefined;\n this.erroredFile = undefined;\n }\n\n resetAttachment() {\n if (this.attachmentBackup) {\n this.attachments = this.attachments.map((attachment) => {\n if (attachment.id === this.attachmentBackup!.id) {\n attachment = this.attachmentBackup as Attachment;\n }\n return attachment;\n });\n this.attachmentBackup = undefined;\n }\n }\n\n trackId(index: number, item: Attachment) {\n return item.id;\n }\n\n downloadAttachment(downloadUrl: string) {\n if (!this.isDownloadingAttachmentLink) {\n this.isDownloadingAttachmentLink = downloadUrl;\n this.fileService.downloadFileWithAccessToken(downloadUrl);\n this.isDownloadingAttachmentLink = undefined;\n }\n }\n\n /**\n * @function setLectureAttachment\n * @param $event {object} Event object which contains the uploaded file\n */\n setLectureAttachment($event: any): void {\n if ($event.target.files.length) {\n this.erroredFile = undefined;\n const fileList: FileList = $event.target.files;\n const attachmentFile = fileList[0];\n this.attachmentFile = attachmentFile;\n this.attachmentToBeCreated!.link = attachmentFile['name'];\n }\n }\n\n /**\n * @function uploadLectureAttachmentAndSave\n * @desc Upload the selected file and add it to the attachment\n */\n uploadLectureAttachmentAndSave(): void {\n const file = this.attachmentFile;\n\n if (!file && this.attachmentToBeCreated!.link) {\n return this.saveAttachment();\n }\n\n if (!this.attachmentToBeCreated!.name || !file) {\n return;\n }\n\n this.isUploadingAttachment = true;\n this.erroredFile = undefined;\n this.errorMessage = undefined;\n this.fileUploaderService.uploadFile(file, file['name'], { keepFileName: true }).then(\n (result) => {\n this.attachmentToBeCreated!.link = result.path;\n this.isUploadingAttachment = false;\n this.attachmentFile = undefined;\n this.saveAttachment();\n },\n (error) => {\n this.errorMessage = error.message;\n this.erroredFile = file;\n this.fileInput.nativeElement.value = '';\n this.attachmentToBeCreated!.link = undefined;\n this.isUploadingAttachment = false;\n this.attachmentFile = undefined;\n this.resetAttachment();\n },\n );\n }\n}\n" }, { "alpha_fraction": 0.7654075622558594, "alphanum_fraction": 0.7664015889167786, "avg_line_length": 40.06122589111328, "blob_id": "673302ad8dd37baab20573c77470571dc048f23e", "content_id": "fb9f808755668dbe43fcf65869d267f62a6d2079", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2012, "license_type": "permissive", "max_line_length": 157, "num_lines": 49, "path": "/src/test/java/de/tum/in/www1/artemis/service/ResourceLoaderServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.Charset;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.Assertions;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\n\npublic class ResourceLoaderServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ResourceLoaderService resourceLoaderService;\n\n @AfterEach\n public void cleanup() {\n new File(\"templates/java/java.txt\").delete();\n new File(\"templates/jenkins/jenkins.txt\").delete();\n }\n\n @Test\n public void testShouldLoadJavaFileFromClasspath() throws IOException {\n FileUtils.writeStringToFile(new File(\"templates/java/java.txt\"), \"filesystem\", Charset.defaultCharset());\n String fileContent = IOUtils.toString(resourceLoaderService.getResource(\"templates/java/java.txt\").getInputStream(), Charset.defaultCharset());\n\n Assertions.assertEquals(\"classpath\", fileContent.trim());\n }\n\n @Test\n public void testShouldLoadJenkinsFileFromFilesystem() throws IOException {\n FileUtils.writeStringToFile(new File(\"templates/jenkins/jenkins.txt\"), \"filesystem\", Charset.defaultCharset());\n String fileContent = IOUtils.toString(resourceLoaderService.getResource(\"templates/jenkins/jenkins.txt\").getInputStream(), Charset.defaultCharset());\n\n Assertions.assertEquals(\"filesystem\", fileContent.trim());\n }\n\n @Test\n public void testShouldLoadJenkinsFileFromClasspath_IfNotPresentInFileSystem() throws IOException {\n String fileContent = IOUtils.toString(resourceLoaderService.getResource(\"templates/jenkins/jenkins.txt\").getInputStream(), Charset.defaultCharset());\n\n Assertions.assertEquals(\"classpath\", fileContent.trim());\n }\n}\n" }, { "alpha_fraction": 0.5911445021629333, "alphanum_fraction": 0.5963231325149536, "avg_line_length": 40.085105895996094, "blob_id": "8bfc3f6f78541e70a7254ca3726d3eed268e1924", "content_id": "2faba91108f819ced659d335ccfe530026cc5292", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3862, "license_type": "permissive", "max_line_length": 134, "num_lines": 94, "path": "/src/test/javascript/spec/service/student-question-answer.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport * as chai from 'chai';\nimport { take } from 'rxjs/operators';\nimport { StudentQuestionAnswerService } from 'app/overview/student-questions/student-question-answer/student-question-answer.service';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\n\nconst expect = chai.expect;\n\ndescribe('StudentQuestionAnswer Service', () => {\n let injector: TestBed;\n let service: StudentQuestionAnswerService;\n let httpMock: HttpTestingController;\n let elemDefault: StudentQuestionAnswer;\n let expectedResult: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n expectedResult = {} as HttpResponse<StudentQuestionAnswer>;\n injector = getTestBed();\n service = injector.get(StudentQuestionAnswerService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new StudentQuestionAnswer();\n elemDefault.id = 0;\n elemDefault.answerDate = undefined;\n elemDefault.answerText = 'This is a test answer';\n });\n\n describe('Service methods', () => {\n it('should find a StudentQuestionAnswer', async () => {\n const returnedFromService = { ...elemDefault };\n service\n .find(1, 123)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(elemDefault);\n });\n\n it('should create a StudentQuestionAnswer', async () => {\n const returnedFromService = { ...elemDefault, id: 0 };\n const expected = { ...returnedFromService };\n service\n .create(1, new StudentQuestionAnswer())\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should update a StudentQuestionAnswer text field', async () => {\n const returnedFromService = { ...elemDefault, answerText: 'This is another test answer' };\n const expected = { ...returnedFromService };\n service\n .update(1, expected)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should update a StudentQuestionAnswer tutorApproved field', async () => {\n const returnedFromService = { ...elemDefault, tutorApproved: true };\n const expected = { ...returnedFromService };\n service\n .update(1, expected)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should delete a StudentQuestionAnswer', async () => {\n service.delete(1, 123).subscribe((resp) => (expectedResult = resp.ok));\n\n const req = httpMock.expectOne({ method: 'DELETE' });\n req.flush({ status: 200 });\n expect(expectedResult).to.be.true;\n });\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.6492834687232971, "alphanum_fraction": 0.6496815085411072, "avg_line_length": 38.873016357421875, "blob_id": "97ccff3840b3f77a6b469ff562e4eaff8ebe9724", "content_id": "3f4877837803e0611489bd0dff6088aeccea448e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2512, "license_type": "permissive", "max_line_length": 115, "num_lines": 63, "path": "/src/test/javascript/spec/component/drag-and-drop-question/drag-item.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { AngularFittextModule } from 'angular-fittext';\nimport { DragItemComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-item.component';\nimport { SecuredImageComponent } from 'app/shared/image/secured-image.component';\nimport * as chai from 'chai';\nimport { MockComponent, MockProvider } from 'ng-mocks';\nimport { DndModule } from 'ng2-dnd';\nimport { DeviceDetectorService, DeviceInfo } from 'ngx-device-detector';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('DragItemComponent', () => {\n let fixture: ComponentFixture<DragItemComponent>;\n let comp: DragItemComponent;\n let deviceDetectorService: DeviceDetectorService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, DndModule.forRoot(), AngularFittextModule],\n declarations: [MockComponent(SecuredImageComponent), DragItemComponent],\n providers: [MockProvider(DeviceDetectorService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(DragItemComponent);\n comp = fixture.componentInstance;\n deviceDetectorService = fixture.debugElement.injector.get(DeviceDetectorService);\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(comp).to.be.ok;\n });\n\n it('should get deviceInfo and isMobile from device service on init', () => {\n const deviceInfo = {\n userAgent: 'userAgent',\n os: 'os',\n browser: 'browser',\n device: 'device',\n os_version: 'os_version',\n browser_version: 'browser_version',\n deviceType: 'deviceType',\n orientation: 'orientation',\n } as DeviceInfo;\n const deviceInfoStub = sinon.stub(deviceDetectorService, 'getDeviceInfo').returns(deviceInfo);\n const isMobileStub = sinon.stub(deviceDetectorService, 'isMobile').returns(true);\n comp.ngOnInit();\n expect(deviceInfoStub).to.have.been.called;\n expect(isMobileStub).to.have.been.called;\n expect(comp.deviceInfo).to.deep.equal(deviceInfo);\n expect(comp.isMobile).to.equal(true);\n });\n});\n" }, { "alpha_fraction": 0.5420234799385071, "alphanum_fraction": 0.5436092615127563, "avg_line_length": 37.45121765136719, "blob_id": "4d3d3b505404358b99bad9d9906b141dc0effbf5", "content_id": "15160f09aa87f76d430ed9b6539f10b86bf53254", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3153, "license_type": "permissive", "max_line_length": 125, "num_lines": 82, "path": "/src/test/javascript/spec/component/list-of-complaints/list-of-complaints.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { RouterTestingModule } from '@angular/router/testing';\n\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { DifferencePipe } from 'ngx-moment';\nimport { ActivatedRoute } from '@angular/router';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { ListOfComplaintsComponent } from 'app/complaints/list-of-complaints/list-of-complaints.component';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\n\ndescribe('ListOfComplaintsComponent', () => {\n let comp: ListOfComplaintsComponent;\n let fixture: ComponentFixture<ListOfComplaintsComponent>;\n\n const complaints = [{ accepted: undefined }, { accepted: true }, { accepted: false }];\n\n const subscribe = {\n subscribe: (fn: (value: any) => void) => {\n fn({\n body: complaints,\n });\n },\n };\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisSharedModule, TranslateModule.forRoot(), ArtemisTestModule, RouterTestingModule.withRoutes([])],\n declarations: [ListOfComplaintsComponent],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: new MockActivatedRoute({ courseId: 123 }),\n },\n DifferencePipe,\n {\n provide: ComplaintService,\n useValue: {\n findAllByTutorIdForCourseId() {\n return subscribe;\n },\n findAllByTutorIdForExerciseId() {\n return subscribe;\n },\n findAllByCourseId() {\n return subscribe;\n },\n findAllByExerciseId() {\n return subscribe;\n },\n },\n },\n ],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ListOfComplaintsComponent);\n comp = fixture.componentInstance;\n comp.ngOnInit();\n });\n });\n\n afterEach(() => {});\n\n it('should hide addressed complaints by default', () => {\n expect(comp.complaintsToShow.length).toEqual(1);\n });\n\n it('should show addressed complaints when the checkbox is selected', () => {\n comp.triggerAddressedComplaints();\n expect(comp.complaintsToShow.length).toEqual(3);\n });\n});\n" }, { "alpha_fraction": 0.6751832962036133, "alphanum_fraction": 0.6798489093780518, "avg_line_length": 41.86666488647461, "blob_id": "5773b3b9817dfe05c49f10759e29265e9560ef84", "content_id": "7f4029f86ef31b5eeb0aa380dbe99d0f25fab041", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4501, "license_type": "permissive", "max_line_length": 176, "num_lines": 105, "path": "/src/test/javascript/spec/component/exam/exam-participant-scores.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslatePipe } from '@ngx-translate/core';\nimport { MockComponent, MockPipe, MockProvider } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ActivatedRoute } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ParticipantScoreAverageDTO, ParticipantScoreDTO, ParticipantScoresService } from 'app/shared/participant-scores/participant-scores.service';\nimport * as chai from 'chai';\nimport { HttpResponse } from '@angular/common/http';\nimport { ExamParticipantScoresComponent } from 'app/exam/manage/exam-participant-scores/exam-participant-scores.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-participant-scores-tables-container', template: '<div></div>' })\nclass ParticipantScoresTableContainerStubComponent {\n @Input()\n isLoading: boolean;\n @Input()\n participantScores: ParticipantScoreDTO[] = [];\n @Input()\n participantScoresAverage: ParticipantScoreAverageDTO[] = [];\n @Input()\n avgScore = 0;\n @Input()\n avgRatedScore = 0;\n @Output()\n reload = new EventEmitter<void>();\n}\n\ndescribe('ExamParticipantScores', () => {\n let fixture: ComponentFixture<ExamParticipantScoresComponent>;\n let component: ExamParticipantScoresComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n declarations: [ExamParticipantScoresComponent, ParticipantScoresTableContainerStubComponent, MockPipe(TranslatePipe), MockComponent(AlertComponent)],\n providers: [\n MockProvider(ParticipantScoresService),\n MockProvider(JhiAlertService),\n {\n provide: ActivatedRoute,\n useValue: { params: of({ examId: 1 }) },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExamParticipantScoresComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should load date when initialized', () => {\n const participantScoreService = TestBed.inject(ParticipantScoresService);\n\n // stub find all of exam\n const participantScoreDTO = new ParticipantScoreDTO();\n participantScoreDTO.id = 1;\n participantScoreDTO.userName = 'test';\n const findAllOfExamResponse: HttpResponse<ParticipantScoreDTO[]> = new HttpResponse({\n body: [participantScoreDTO],\n status: 200,\n });\n const findAllOfExamStub = sinon.stub(participantScoreService, 'findAllOfExam').returns(of(findAllOfExamResponse));\n // stub find average of exam\n const participantScoreAverageDTO = new ParticipantScoreAverageDTO();\n participantScoreAverageDTO.userName = 'test';\n participantScoreAverageDTO.averageScore = 10;\n const findAverageOfExamPerParticipantResponse: HttpResponse<ParticipantScoreAverageDTO[]> = new HttpResponse({\n body: [participantScoreAverageDTO],\n status: 200,\n });\n const findAverageOfExamPerParticipantStub = sinon.stub(participantScoreService, 'findAverageOfExamPerParticipant').returns(of(findAverageOfExamPerParticipantResponse));\n // stub find average of exam\n const findAverageOfExamResponse: HttpResponse<number> = new HttpResponse({\n body: 99,\n status: 200,\n });\n const findAverageOfExamStub = sinon.stub(participantScoreService, 'findAverageOfExam').returns(of(findAverageOfExamResponse));\n\n fixture.detectChanges();\n\n expect(component.participantScores).to.deep.equal([participantScoreDTO]);\n expect(component.participantScoresAverage).to.deep.equal([participantScoreAverageDTO]);\n expect(component.avgScore).to.equal(99);\n expect(component.avgRatedScore).to.equal(99);\n expect(findAllOfExamStub).to.have.been.called;\n expect(findAverageOfExamPerParticipantStub).to.have.been.called;\n expect(findAverageOfExamStub).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.6271243691444397, "alphanum_fraction": 0.6307070255279541, "avg_line_length": 52.18729782104492, "blob_id": "275815f63fb0c4142c4bfe841ff7561da4078560", "content_id": "5fa29c439144383e5d61faf14fbe7ddfc8b3b7d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 32657, "license_type": "permissive", "max_line_length": 180, "num_lines": 614, "path": "/src/main/webapp/app/course/course-scores/course-scores.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';\nimport { Subscription } from 'rxjs/Subscription';\nimport { ActivatedRoute } from '@angular/router';\nimport { User } from 'app/core/user/user.model';\nimport * as moment from 'moment';\nimport { sum } from 'lodash';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ExportToCsv } from 'export-to-csv';\nimport { Exercise, ExerciseType, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from '../manage/course-management.service';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { LocaleConversionService } from 'app/shared/service/locale-conversion.service';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { ParticipantScoresService, ScoresDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport { forkJoin } from 'rxjs';\nimport { round } from 'app/shared/util/utils';\nimport * as Sentry from '@sentry/browser';\n\nexport const PRESENTATION_SCORE_KEY = 'Presentation Score';\nexport const NAME_KEY = 'Name';\nexport const USERNAME_KEY = 'Username';\nexport const EMAIL_KEY = 'Email';\nexport const REGISTRATION_NUMBER_KEY = 'Registration Number';\nexport const OVERALL_COURSE_POINTS_KEY = 'Overall Course Points';\nexport const OVERALL_COURSE_SCORE_KEY = 'Overall Course Score';\nexport const POINTS_KEY = 'Points';\nexport const SCORE_KEY = 'Score';\n\n@Component({\n selector: 'jhi-course-scores',\n templateUrl: './course-scores.component.html',\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class CourseScoresComponent implements OnInit, OnDestroy {\n // supported exercise type\n\n readonly exerciseTypes = [ExerciseType.QUIZ, ExerciseType.PROGRAMMING, ExerciseType.MODELING, ExerciseType.TEXT, ExerciseType.FILE_UPLOAD];\n\n // Expose the function to the template\n readonly round = round;\n\n course: Course;\n allParticipationsOfCourse: StudentParticipation[] = [];\n exercisesOfCourseThatAreIncludedInScoreCalculation: Exercise[] = [];\n students: Student[] = [];\n\n exerciseSuccessfulPerType = new Map<ExerciseType, number[]>();\n exerciseParticipationsPerType = new Map<ExerciseType, number[]>();\n exerciseAveragePointsPerType = new Map<ExerciseType, number[]>();\n exerciseMaxPointsPerType = new Map<ExerciseType, number[]>();\n exerciseTitlesPerType = new Map<ExerciseType, string[]>();\n exercisesPerType = new Map<ExerciseType, Exercise[]>();\n\n exportReady = false;\n paramSub: Subscription;\n predicate: string;\n reverse: boolean;\n\n // max values\n maxNumberOfPointsPerExerciseType = new Map<ExerciseType, number>();\n maxNumberOfOverallPoints = 0;\n\n // average values\n averageNumberOfParticipatedExercises = 0;\n averageNumberOfSuccessfulExercises = 0;\n averageNumberOfPointsPerExerciseTypes = new Map<ExerciseType, number>();\n averageNumberOfOverallPoints = 0;\n\n // note: these represent the course scores using the participation score table. We might switch to this new\n // calculation method completely if it is confirmed that it produces correct results\n studentIdToCourseScoreDTOs: Map<number, ScoresDTO> = new Map<number, ScoresDTO>();\n\n private languageChangeSubscription?: Subscription;\n\n constructor(\n private route: ActivatedRoute,\n private courseService: CourseManagementService,\n private sortService: SortService,\n private changeDetector: ChangeDetectorRef,\n private languageHelper: JhiLanguageHelper,\n private localeConversionService: LocaleConversionService,\n private participantScoresService: ParticipantScoresService,\n ) {\n this.reverse = false;\n this.predicate = 'id';\n }\n\n /**\n * On init fetch the course, all released exercises and all participations with result for the course from the server.\n */\n ngOnInit() {\n this.paramSub = this.route.params.subscribe((params) => {\n this.courseService.findWithExercises(params['courseId']).subscribe((findWithExercisesResult) => {\n this.course = findWithExercisesResult.body!;\n const titleMap = new Map<string, number>();\n if (this.course.exercises) {\n for (const exercise of this.course.exercises) {\n const title = exercise.title!;\n\n if (titleMap.has(title)) {\n const currentValue = titleMap.get(title);\n titleMap.set(title, currentValue! + 1);\n } else {\n titleMap.set(title, 1);\n }\n }\n\n // this workaround is necessary if the course has exercises with the same title (we add the id to make it unique)\n for (const exercise of this.course.exercises) {\n if (titleMap.has(exercise.title!) && titleMap.get(exercise.title!)! > 1) {\n exercise.title = `${exercise.title} (id=${exercise.id})`;\n }\n }\n }\n\n this.exercisesOfCourseThatAreIncludedInScoreCalculation = this.course\n .exercises!.filter((exercise) => {\n const isReleasedExercise = !exercise.releaseDate || exercise.releaseDate.isBefore(moment());\n const isExerciseThatCounts = exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED;\n return isReleasedExercise && isExerciseThatCounts;\n })\n .sort((e1: Exercise, e2: Exercise) => {\n if (e1.dueDate! > e2.dueDate!) {\n return 1;\n }\n if (e1.dueDate! < e2.dueDate!) {\n return -1;\n }\n if (e1.title! > e2.title!) {\n return 1;\n }\n if (e1.title! < e2.title!) {\n return -1;\n }\n return 0;\n });\n this.calculateCourseStatistics(this.course.id!);\n });\n });\n\n // Update the view if the language was changed\n this.languageChangeSubscription = this.languageHelper.language.subscribe(() => {\n this.changeDetector.detectChanges();\n });\n }\n\n /**\n * Fetch all participations with results from the server for the specified course and calculate the corresponding course statistics\n * @param courseId Id of the course\n */\n calculateCourseStatistics(courseId: number) {\n const findParticipationsObservable = this.courseService.findAllParticipationsWithResults(courseId);\n // alternative course scores calculation using participant scores table\n const courseScoresObservable = this.participantScoresService.findCourseScores(courseId);\n forkJoin([findParticipationsObservable, courseScoresObservable]).subscribe(([participationsOfCourse, courseScoresResult]) => {\n this.allParticipationsOfCourse = participationsOfCourse;\n this.calculateExerciseLevelStatistics();\n this.calculateStudentLevelStatistics();\n\n // comparing with calculation from course scores (using new participation score table)\n const courseScoreDTOs = courseScoresResult.body!;\n this.compareNewCourseScoresCalculationWithOldCalculation(courseScoreDTOs);\n this.changeDetector.detectChanges();\n });\n }\n\n /**\n * This method compares the course scores computed on the client side with the ones on the server side\n * using the participations score table. In the future we might switch to the server side method, so we use\n * this method to detect discrepancys.\n * @param courseScoreDTOs the course scores sent from the server (new calculation method)\n */\n private compareNewCourseScoresCalculationWithOldCalculation(courseScoreDTOs: ScoresDTO[]) {\n if (!this.students || !courseScoreDTOs) {\n return;\n }\n for (const courseScoreDTO of courseScoreDTOs) {\n this.studentIdToCourseScoreDTOs.set(courseScoreDTO.studentId!, courseScoreDTO);\n }\n let noOfScoreDifferencesFound = 0;\n let noOfPointDifferencesFound = 0;\n let noOfComparisons = 0;\n for (const student of this.students) {\n const overAllPoints = round(student.overallPoints, 1);\n const overallScore = round((student.overallPoints / this.maxNumberOfOverallPoints) * 100, 1);\n const regularCalculation = {\n scoreAchieved: overallScore,\n pointsAchieved: overAllPoints,\n userId: student.user.id,\n userLogin: student.user.login,\n regularPointsAchievable: this.maxNumberOfOverallPoints,\n };\n // checking if the same as in the course scores map\n const courseScoreDTO = this.studentIdToCourseScoreDTOs.get(student.user.id!);\n if (!courseScoreDTO) {\n const errorMessage = `User scores not included in new calculation: ${JSON.stringify(regularCalculation)}`;\n this.logErrorOnSentry(errorMessage);\n } else {\n noOfComparisons += 1;\n courseScoreDTO.scoreAchieved = round(courseScoreDTO.scoreAchieved, 1);\n courseScoreDTO.pointsAchieved = round(courseScoreDTO.pointsAchieved, 1);\n\n if (Math.abs(courseScoreDTO.pointsAchieved - regularCalculation.pointsAchieved) > 0.1) {\n const errorMessage = `Different course points in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation: ${JSON.stringify(\n courseScoreDTO,\n )}`;\n noOfPointDifferencesFound += 1;\n this.logErrorOnSentry(errorMessage);\n }\n if (Math.abs(courseScoreDTO.scoreAchieved - regularCalculation.scoreAchieved) > 0.1) {\n const errorMessage = `Different course score in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation : ${JSON.stringify(\n courseScoreDTO,\n )}`;\n noOfScoreDifferencesFound += 1;\n this.logErrorOnSentry(errorMessage);\n }\n }\n }\n console.log(`Performed ${noOfComparisons} comparisons between old and new calculation method.`);\n console.log(`Found ${noOfPointDifferencesFound} point differences between old and new calculation method.`);\n console.log(`Found ${noOfScoreDifferencesFound} score differences between old and new calculation method.`);\n }\n\n logErrorOnSentry(errorMessage: string) {\n console.log(errorMessage);\n Sentry.captureException(new Error(errorMessage));\n }\n\n /**\n * Group the exercises by type and gather statistics for each type (titles, max points, accumulated max points).\n */\n calculateExerciseLevelStatistics() {\n for (const exerciseType of this.exerciseTypes) {\n const exercisesOfType = this.exercisesOfCourseThatAreIncludedInScoreCalculation.filter((exercise) => exercise.type === exerciseType);\n this.exercisesPerType.set(exerciseType, exercisesOfType);\n this.exerciseTitlesPerType.set(\n exerciseType,\n exercisesOfType.map((exercise) => exercise.title!),\n );\n\n const maxPointsOfAllExercisesOfType = exercisesOfType.map((exercise) => exercise.maxPoints!);\n\n this.exerciseMaxPointsPerType.set(exerciseType, maxPointsOfAllExercisesOfType);\n\n const maxPointsOfAllIncludedExercisesOfType = exercisesOfType\n // only exercises marked as included_completely increase the maximum reachable number of points\n .filter((exercise) => exercise.includedInOverallScore === IncludedInOverallScore.INCLUDED_COMPLETELY)\n .map((exercise) => exercise.maxPoints!);\n\n this.maxNumberOfPointsPerExerciseType.set(exerciseType, sum(maxPointsOfAllIncludedExercisesOfType));\n }\n this.maxNumberOfOverallPoints = 0;\n for (const maxNumberOfPointsPerExerciseTypeElement of this.maxNumberOfPointsPerExerciseType) {\n this.maxNumberOfOverallPoints += maxNumberOfPointsPerExerciseTypeElement[1];\n }\n }\n\n /**\n * Creates students and calculates the points for each exercise and exercise type.\n */\n calculateStudentLevelStatistics() {\n const studentsMap = new Map<number, Student>();\n\n for (const participation of this.allParticipationsOfCourse) {\n if (participation.results && participation.results.length > 0) {\n for (const result of participation.results) {\n // reconnect\n result.participation = participation;\n }\n }\n\n // find all students by iterating through the participations\n const participationStudents = participation.student ? [participation.student] : participation.team!.students!;\n for (const participationStudent of participationStudents) {\n let student = studentsMap.get(participationStudent.id!);\n if (!student) {\n student = new Student(participationStudent);\n studentsMap.set(participationStudent.id!, student);\n }\n student.participations.push(participation);\n if (participation.presentationScore) {\n student.presentationScore += participation.presentationScore;\n }\n }\n }\n\n // prepare exercises\n for (const exercise of this.exercisesOfCourseThatAreIncludedInScoreCalculation) {\n exercise.numberOfParticipationsWithRatedResult = 0;\n exercise.numberOfSuccessfulParticipations = 0;\n }\n\n studentsMap.forEach((student) => {\n this.students.push(student);\n\n for (const exercise of this.exercisesOfCourseThatAreIncludedInScoreCalculation) {\n const relevantMaxPoints = exercise.maxPoints!;\n const participation = student.participations.find((part) => part.exercise!.id === exercise.id);\n if (participation && participation.results && participation.results.length > 0) {\n // we found a result, there should only be one\n const result = participation.results[0];\n if (participation.results.length > 1) {\n console.warn('found more than one result for student ' + student.user.login + ' and exercise ' + exercise.title);\n }\n\n // Note: It is important that we round on the individual exercise level first and then sum up.\n // This is necessary so that the student arrives at the same overall result when doing his own recalculation.\n // Let's assume that the student achieved 1.05 points in each of 5 exercises.\n // In the client, these are now displayed rounded as 1.1 points.\n // If the student adds up the displayed points, he gets a total of 5.5 points.\n // In order to get the same total result as the student, we have to round before summing.\n const pointsAchievedByStudentInExercise = round((result.score! * relevantMaxPoints) / 100, 1);\n student.overallPoints += pointsAchievedByStudentInExercise;\n student.pointsPerExercise.set(exercise.id!, pointsAchievedByStudentInExercise);\n student.sumPointsPerExerciseType.set(exercise.type!, student.sumPointsPerExerciseType.get(exercise.type!)! + pointsAchievedByStudentInExercise);\n student.numberOfParticipatedExercises += 1;\n exercise.numberOfParticipationsWithRatedResult! += 1;\n if (result.score! >= 100) {\n student.numberOfSuccessfulExercises += 1;\n exercise.numberOfSuccessfulParticipations! += 1;\n }\n\n student.pointsPerExerciseType.get(exercise.type!)!.push(pointsAchievedByStudentInExercise);\n } else {\n // there is no result, the student has not participated or submitted too late\n student.pointsPerExercise.set(exercise.id!, 0);\n student.pointsPerExerciseType.get(exercise.type!)!.push(Number.NaN);\n }\n }\n for (const exerciseType of this.exerciseTypes) {\n if (this.maxNumberOfPointsPerExerciseType.get(exerciseType)! > 0) {\n student.scorePerExerciseType.set(\n exerciseType,\n (student.sumPointsPerExerciseType.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!) * 100,\n );\n }\n }\n });\n\n for (const exerciseType of this.exerciseTypes) {\n // TODO: can we calculate this average only with students who participated in the exercise?\n this.averageNumberOfPointsPerExerciseTypes.set(\n exerciseType,\n this.students.reduce((total, student) => total + student.sumPointsPerExerciseType.get(exerciseType)!, 0) / this.students.length,\n );\n }\n\n this.averageNumberOfOverallPoints = this.students.reduce((total, student) => total + student.overallPoints, 0) / this.students.length;\n this.averageNumberOfSuccessfulExercises = this.students.reduce((total, student) => total + student.numberOfSuccessfulExercises, 0) / this.students.length;\n this.averageNumberOfParticipatedExercises = this.students.reduce((total, student) => total + student.numberOfParticipatedExercises, 0) / this.students.length;\n\n for (const exerciseType of this.exerciseTypes) {\n this.exerciseAveragePointsPerType.set(exerciseType, []); // initialize with empty array\n this.exerciseParticipationsPerType.set(exerciseType, []); // initialize with empty array\n this.exerciseSuccessfulPerType.set(exerciseType, []); // initialize with empty array\n\n for (const exercise of this.exercisesPerType.get(exerciseType)!) {\n exercise.averagePoints = this.students.reduce((total, student) => total + student.pointsPerExercise.get(exercise.id!)!, 0) / this.students.length;\n this.exerciseAveragePointsPerType.get(exerciseType)!.push(exercise.averagePoints);\n this.exerciseParticipationsPerType.get(exerciseType)!.push(exercise.numberOfParticipationsWithRatedResult!);\n this.exerciseSuccessfulPerType.get(exerciseType)!.push(exercise.numberOfSuccessfulParticipations!);\n }\n }\n\n this.exportReady = true;\n }\n\n /**\n * Method for exporting the csv with the needed data\n */\n exportResults() {\n if (this.exportReady && this.students.length > 0) {\n const rows: any[] = [];\n const keys = [NAME_KEY, USERNAME_KEY, EMAIL_KEY, REGISTRATION_NUMBER_KEY];\n for (const exerciseType of this.exerciseTypes) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length > 0) {\n keys.push(...this.exerciseTitlesPerType.get(exerciseType)!);\n keys.push(exerciseTypeName + ' ' + POINTS_KEY);\n keys.push(exerciseTypeName + ' ' + SCORE_KEY);\n }\n }\n keys.push(OVERALL_COURSE_POINTS_KEY, OVERALL_COURSE_SCORE_KEY);\n if (this.course.presentationScore) {\n keys.push(PRESENTATION_SCORE_KEY);\n }\n\n for (const student of this.students.values()) {\n const rowData = {};\n rowData[NAME_KEY] = student.user.name!.trim();\n rowData[USERNAME_KEY] = student.user.login!.trim();\n rowData[EMAIL_KEY] = student.user.email!.trim();\n rowData[REGISTRATION_NUMBER_KEY] = student.user.visibleRegistrationNumber ? student.user.visibleRegistrationNumber!.trim() : '';\n\n for (const exerciseType of this.exerciseTypes) {\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n const exercisePointsPerType = student.sumPointsPerExerciseType.get(exerciseType)!;\n let exerciseScoresPerType = 0;\n if (this.maxNumberOfPointsPerExerciseType.get(exerciseType)! > 0) {\n exerciseScoresPerType = round((student.sumPointsPerExerciseType.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!) * 100);\n }\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n const exercisePointValues = student.pointsPerExerciseType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title, index) => {\n rowData[title] = this.localeConversionService.toLocaleString(round(exercisePointValues[index], 1));\n });\n rowData[exerciseTypeName + ' ' + POINTS_KEY] = this.localeConversionService.toLocaleString(exercisePointsPerType);\n rowData[exerciseTypeName + ' ' + SCORE_KEY] = this.localeConversionService.toLocalePercentageString(exerciseScoresPerType);\n }\n }\n\n const overallScore = round((student.overallPoints / this.maxNumberOfOverallPoints) * 100, 1);\n rowData[OVERALL_COURSE_POINTS_KEY] = this.localeConversionService.toLocaleString(student.overallPoints);\n rowData[OVERALL_COURSE_SCORE_KEY] = this.localeConversionService.toLocalePercentageString(overallScore);\n if (this.course.presentationScore) {\n rowData[PRESENTATION_SCORE_KEY] = this.localeConversionService.toLocaleString(student.presentationScore);\n }\n rows.push(rowData);\n }\n\n rows.push(this.emptyLine('')); // empty row as separator\n\n // max values\n const rowDataMax = this.emptyLine('Max');\n for (const exerciseType of this.exerciseTypes) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n const exerciseMaxPoints = this.exerciseMaxPointsPerType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title, index) => {\n rowDataMax[title] = this.localeConversionService.toLocaleString(exerciseMaxPoints[index]);\n });\n rowDataMax[exerciseTypeName + ' ' + POINTS_KEY] = this.localeConversionService.toLocaleString(this.maxNumberOfPointsPerExerciseType.get(exerciseType)!);\n rowDataMax[exerciseTypeName + ' ' + SCORE_KEY] = this.localeConversionService.toLocalePercentageString(100);\n }\n }\n rowDataMax[OVERALL_COURSE_POINTS_KEY] = this.localeConversionService.toLocaleString(this.maxNumberOfOverallPoints);\n rowDataMax[OVERALL_COURSE_SCORE_KEY] = this.localeConversionService.toLocalePercentageString(100);\n if (this.course.presentationScore) {\n rowDataMax[PRESENTATION_SCORE_KEY] = '';\n }\n rows.push(rowDataMax);\n\n // average values\n const rowDataAverage = this.emptyLine('Average');\n for (const exerciseType of this.exerciseTypes) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n const exerciseAveragePoints = this.exerciseAveragePointsPerType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title, index) => {\n rowDataAverage[title] = this.localeConversionService.toLocaleString(round(exerciseAveragePoints[index], 1));\n });\n\n const averageScore = round((this.averageNumberOfPointsPerExerciseTypes.get(exerciseType)! / this.maxNumberOfPointsPerExerciseType.get(exerciseType)!) * 100);\n\n rowDataAverage[exerciseTypeName + ' ' + POINTS_KEY] = this.localeConversionService.toLocaleString(\n this.averageNumberOfPointsPerExerciseTypes.get(exerciseType)!,\n );\n rowDataAverage[exerciseTypeName + ' ' + SCORE_KEY] = this.localeConversionService.toLocalePercentageString(averageScore);\n }\n }\n\n const averageOverallScore = round((this.averageNumberOfOverallPoints / this.maxNumberOfOverallPoints) * 100, 1);\n rowDataAverage[OVERALL_COURSE_POINTS_KEY] = this.localeConversionService.toLocaleString(this.averageNumberOfOverallPoints);\n rowDataAverage[OVERALL_COURSE_SCORE_KEY] = this.localeConversionService.toLocalePercentageString(averageOverallScore);\n if (this.course.presentationScore) {\n rowDataAverage[PRESENTATION_SCORE_KEY] = '';\n }\n rows.push(rowDataAverage);\n\n // participation\n const rowDataParticipation = this.emptyLine('Number of Participations');\n for (const exerciseType of this.exerciseTypes) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n const exerciseParticipations = this.exerciseParticipationsPerType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title, index) => {\n rowDataParticipation[title] = this.localeConversionService.toLocaleString(exerciseParticipations[index]);\n });\n rowDataParticipation[exerciseTypeName + ' ' + POINTS_KEY] = '';\n rowDataParticipation[exerciseTypeName + ' ' + SCORE_KEY] = '';\n }\n }\n rows.push(rowDataParticipation);\n\n // successful\n const rowDataParticipationSuccuessful = this.emptyLine('Number of Successful Participations');\n for (const exerciseType of this.exerciseTypes) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n const exerciseParticipationsSuccessful = this.exerciseSuccessfulPerType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title, index) => {\n rowDataParticipationSuccuessful[title] = this.localeConversionService.toLocaleString(exerciseParticipationsSuccessful[index]);\n });\n rowDataParticipationSuccuessful[exerciseTypeName + ' ' + POINTS_KEY] = '';\n rowDataParticipationSuccuessful[exerciseTypeName + ' ' + SCORE_KEY] = '';\n }\n }\n rows.push(rowDataParticipationSuccuessful);\n this.exportAsCsv(rows, keys);\n }\n }\n\n exportAsCsv(rows: any[], keys: string[]) {\n const options = {\n fieldSeparator: ';', // TODO: allow user to customize\n quoteStrings: '\"',\n decimalSeparator: 'locale',\n showLabels: true,\n showTitle: false,\n filename: 'Artemis Course ' + this.course.title + ' Scores',\n useTextFile: false,\n useBom: true,\n headers: keys,\n };\n\n const csvExporter = new ExportToCsv(options);\n csvExporter.generateCsv(rows); // includes download\n }\n\n /**\n *an empty line in csv-format with an empty row for each exercise type.\n * @param firstValue The first value/name key of the line\n */\n private emptyLine(firstValue: string) {\n const emptyLine = {};\n emptyLine[NAME_KEY] = firstValue;\n emptyLine[USERNAME_KEY] = '';\n emptyLine[EMAIL_KEY] = '';\n emptyLine[REGISTRATION_NUMBER_KEY] = '';\n emptyLine[OVERALL_COURSE_POINTS_KEY] = '';\n emptyLine[OVERALL_COURSE_SCORE_KEY] = '';\n\n for (const exerciseType of this.exerciseTypes) {\n // only add it if there are actually exercises in this type\n if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) {\n const exerciseTypeName = capitalizeFirstLetter(exerciseType);\n const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!;\n exerciseTitleKeys.forEach((title) => {\n emptyLine[title] = '';\n });\n emptyLine[exerciseTypeName + ' ' + POINTS_KEY] = '';\n emptyLine[exerciseTypeName + ' ' + SCORE_KEY] = '';\n }\n }\n\n if (this.course.presentationScore) {\n emptyLine[PRESENTATION_SCORE_KEY] = '';\n }\n\n return emptyLine;\n }\n\n sortRows() {\n this.sortService.sortByProperty(this.students, this.predicate, this.reverse);\n }\n\n getLocaleConversionService() {\n return this.localeConversionService;\n }\n\n /**\n * On destroy unsubscribe.\n */\n ngOnDestroy() {\n this.paramSub.unsubscribe();\n if (this.languageChangeSubscription) {\n this.languageChangeSubscription.unsubscribe();\n }\n }\n}\n\nclass Student {\n user: User;\n participations: StudentParticipation[] = [];\n presentationScore = 0;\n numberOfParticipatedExercises = 0;\n numberOfSuccessfulExercises = 0;\n overallPoints = 0;\n pointsPerExercise = new Map<number, number>(); // the index is the exercise id\n sumPointsPerExerciseType = new Map<ExerciseType, number>(); // the absolute number (sum) of points the students received per exercise type\n scorePerExerciseType = new Map<ExerciseType, number>(); // the relative number of points the students received per exercise type (divided by the max points per exercise type)\n pointsPerExerciseType = new Map<ExerciseType, number[]>(); // a string containing the points for all exercises of a specific type\n\n constructor(user: User) {\n this.user = user;\n // initialize with 0 or empty string\n for (const exerciseType of Object.values(ExerciseType)) {\n this.sumPointsPerExerciseType.set(exerciseType, 0);\n this.scorePerExerciseType.set(exerciseType, 0);\n this.pointsPerExerciseType.set(exerciseType, []);\n }\n }\n}\n\n/**\n * Capitalize the first letter of a string.\n * @param string\n */\nfunction capitalizeFirstLetter(string: String) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n}\n" }, { "alpha_fraction": 0.6975802183151245, "alphanum_fraction": 0.6993457078933716, "avg_line_length": 50.21808624267578, "blob_id": "41ee3da9b692cb99abe1bf8807d4d8f8c30f1b0d", "content_id": "e99196ee3507c1a4ec6749f1f2df282a73528b8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 28887, "license_type": "permissive", "max_line_length": 179, "num_lines": 564, "path": "/src/main/java/de/tum/in/www1/artemis/service/AuthorizationCheckService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException.NOT_ALLOWED;\n\nimport java.security.Principal;\nimport java.time.ZonedDateTime;\nimport java.util.Optional;\nimport java.util.function.Consumer;\n\nimport javax.annotation.Nullable;\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.lecture.LectureUnit;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\nimport de.tum.in.www1.artemis.web.rest.errors.AccessForbiddenException;\n\n/**\n * Service used to check whether user is authorized to perform actions on the entity.\n */\n@Service\npublic class AuthorizationCheckService {\n\n private final UserRepository userRepository;\n\n public AuthorizationCheckService(UserRepository userRepository) {\n this.userRepository = userRepository;\n }\n\n /**\n * Given any type of exercise, the method returns if the current user is at least TA for the course the exercise belongs to. If exercise is not present, it will return false,\n * because the optional will be empty, and therefore `isPresent()` will return false This is due how `filter` works: If a value is present, apply the provided mapping function\n * to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.\n * https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html#filter-java.util.function.Predicate\n *\n * @param exercise the exercise that needs to be checked\n * @param <T> The type of the concrete exercise, because Exercise is an abstract class\n * @return true if the user is at least a teaching assistant (also if the user is instructor or admin) in the course of the given exercise\n */\n public <T extends Exercise> boolean isAtLeastTeachingAssistantForExercise(Optional<T> exercise) {\n return exercise.filter(this::isAtLeastTeachingAssistantForExercise).isPresent();\n }\n\n /**\n * Checks if the currently logged in user is at least a teaching assistant in the course of the given exercise.\n * The course is identified from either {@link Exercise#course(Course)} or {@link Exam#getCourse()}\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @return true if the currently logged in user is at least a teaching assistant (also if the user is instructor or admin), false otherwise\n */\n public boolean isAtLeastTeachingAssistantForExercise(@NotNull Exercise exercise) {\n return isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), null);\n }\n\n /**\n * Checks if the currently logged in user is at least a teaching assistant in the course of the given exercise.\n * The course is identified from either {@link Exercise#course(Course)} or {@link Exam#getCourse()}\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @param user the user whose permissions should be checked\n */\n private void checkIsAtLeastTeachingAssistantForExerciseElseThrow(@NotNull Exercise exercise, @Nullable User user) {\n if (!isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user)) {\n throw new AccessForbiddenException(\"Exercise\", exercise.getId());\n }\n }\n\n /**\n * Checks if the passed user is at least a teaching assistant in the course of the given exercise.\n * The course is identified from {@link Exercise#getCourseViaExerciseGroupOrCourseMember()}\n *\n * @param exercise the exercise that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true if the passed user is at least a teaching assistant (also if the user is instructor or admin), false otherwise\n */\n public boolean isAtLeastTeachingAssistantForExercise(@NotNull Exercise exercise, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user);\n }\n\n /**\n * checks if the currently logged in user is at least a student in the course of the given exercise.\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @return true if the currently logged in user is at least a student (also if the user is teaching assistant, instructor or admin), false otherwise\n */\n public boolean isAtLeastStudentForExercise(@NotNull Exercise exercise) {\n return isAtLeastStudentForExercise(exercise, null);\n }\n\n /**\n * Checks if the passed user is at least a student in the course of the given exercise.\n * The course is identified from {@link Exercise#getCourseViaExerciseGroupOrCourseMember()}\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param exercise the exercise that needs to be checked\n * @param user the user whose permissions should be checked\n */\n private void checkIsAtLeastStudentForExerciseElseThrow(@NotNull Exercise exercise, @Nullable User user) {\n if (!isAtLeastStudentForExercise(exercise, user)) {\n throw new AccessForbiddenException(\"Exercise\", exercise.getId());\n }\n }\n\n /**\n * checks if the currently logged in user is at least a student in the course of the given exercise.\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @param user the user whose permissions should be checked\n * @return true if the currently logged in user is at least a student (also if the user is teaching assistant, instructor or admin), false otherwise\n */\n public boolean isAtLeastStudentForExercise(@NotNull Exercise exercise, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return isStudentInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user) || isAtLeastTeachingAssistantForExercise(exercise, user);\n }\n\n /**\n * Checks if the passed user is at least a teaching assistant in the given course.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n */\n private void checkIsAtLeastTeachingAssistantInCourseElseThrow(@NotNull Course course, @Nullable User user) {\n if (!isAtLeastTeachingAssistantInCourse(course, user)) {\n throw new AccessForbiddenException(\"Course\", course.getId());\n }\n }\n\n /**\n * Checks if the passed user is at least a teaching assistant in the given course.\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true if the passed user is at least a teaching assistant in the course (also if the user is instructor or admin), false otherwise\n */\n public boolean isAtLeastTeachingAssistantInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getInstructorGroupName()) || user.getGroups().contains(course.getTeachingAssistantGroupName()) || isAdmin(user);\n }\n\n /**\n * Checks if the passed user is at least a student in the given course.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n */\n private void checkIsAtLeastStudentInCourseElseThrow(@NotNull Course course, @Nullable User user) {\n if (!isAtLeastStudentInCourse(course, user)) {\n throw new AccessForbiddenException(\"Course\", course.getId());\n }\n }\n\n /**\n * checks if the passed user is at least a teaching assistant in the given course\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true if the passed user is at least a teaching assistant in the course (also if the user is instructor or admin), false otherwise\n */\n public boolean isAtLeastStudentInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getInstructorGroupName()) || user.getGroups().contains(course.getTeachingAssistantGroupName())\n || user.getGroups().contains(course.getStudentGroupName()) || isAdmin(user);\n }\n\n /**\n * Checks if the currently logged in user is at least an instructor in the course of the given exercise.\n * The course is identified from either exercise.course or exercise.exerciseGroup.exam.course\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @param user the user whose permissions should be checked\n * @return true if the currently logged in user is at least an instructor (or admin), false otherwise\n */\n public boolean isAtLeastInstructorForExercise(@NotNull Exercise exercise, @Nullable User user) {\n return isAtLeastInstructorInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user);\n }\n\n /**\n * checks if the currently logged in user is at least an instructor in the course of the given exercise.\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @return true if the currently logged in user is at least an instructor (or admin), false otherwise\n */\n public boolean isAtLeastInstructorForExercise(@NotNull Exercise exercise) {\n return isAtLeastInstructorForExercise(exercise, null);\n }\n\n /**\n * checks if the currently logged in user is at least an instructor in the course of the given exercise.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param exercise belongs to a course that will be checked for permission rights\n * @param user the user whose permissions should be checked (can be null)\n */\n private void checkIsAtLeastInstructorForExerciseElseThrow(@NotNull Exercise exercise, @Nullable User user) {\n if (!isAtLeastInstructorForExercise(exercise, user)) {\n throw new AccessForbiddenException(\"Exercise\", exercise.getId());\n }\n }\n\n /**\n * Checks if the passed user has at least the given role for the given exercise.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param role the role that should be checked\n * @param exercise belongs to a course that will be checked for permission rights\n * @param user the user whose permissions should be checked\n */\n public void checkHasAtLeastRoleForExerciseElseThrow(@NotNull Role role, @NotNull Exercise exercise, @Nullable User user) {\n // Note: the consumer is necessary to get an exhaustive check for the switch expression here, also see https://stackoverflow.com/questions/66204407\n Consumer<User> consumer = switch (role) {\n case ADMIN -> this::checkIsAdminElseThrow;\n case INSTRUCTOR -> userOrNull -> checkIsAtLeastInstructorForExerciseElseThrow(exercise, userOrNull);\n case TEACHING_ASSISTANT -> userOrNull -> checkIsAtLeastTeachingAssistantForExerciseElseThrow(exercise, userOrNull);\n case STUDENT -> userOrNull -> checkIsAtLeastStudentForExerciseElseThrow(exercise, userOrNull);\n // anonymous users never have access to exercises, so we have to throw an exception\n case ANONYMOUS -> throw new IllegalArgumentException(\"The role anonymous does not make sense in this context\");\n };\n consumer.accept(user);\n }\n\n /**\n * Checks if the passed user has at least the given role in the given course.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param role the role that should be checked\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n */\n public void checkHasAtLeastRoleInCourseElseThrow(@NotNull Role role, @NotNull Course course, @Nullable User user) {\n // Note: the consumer is necessary to get an exhaustive check for the switch expression here, also see https://stackoverflow.com/questions/66204407\n Consumer<User> consumer = switch (role) {\n case ADMIN -> this::checkIsAdminElseThrow;\n case INSTRUCTOR -> userOrNull -> checkIsAtLeastInstructorInCourseElseThrow(course, userOrNull);\n case TEACHING_ASSISTANT -> userOrNull -> checkIsAtLeastTeachingAssistantInCourseElseThrow(course, userOrNull);\n case STUDENT -> userOrNull -> checkIsAtLeastStudentInCourseElseThrow(course, userOrNull);\n // anonymous users never have access to courses, so we have to throw an exception\n case ANONYMOUS -> throw new IllegalArgumentException(\"The role anonymous does not make sense in this context\");\n };\n consumer.accept(user);\n }\n\n /**\n * Checks if the passed user is at least instructor in the given course.\n * Throws an AccessForbiddenException if the user has no access which returns a 403\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n */\n private void checkIsAtLeastInstructorInCourseElseThrow(@NotNull Course course, @Nullable User user) {\n if (!isAtLeastInstructorInCourse(course, user)) {\n throw new AccessForbiddenException(\"Course\", course.getId());\n }\n }\n\n /**\n * checks if the passed user is at least instructor in the given course\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true if the passed user is at least instructor in the course (also if the user is admin), false otherwise\n */\n public boolean isAtLeastInstructorInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getInstructorGroupName()) || isAdmin(user);\n }\n\n /**\n * checks if the passed user is instructor in the given course\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is instructor of this course, otherwise false\n */\n public boolean isInstructorInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getInstructorGroupName());\n }\n\n /**\n * checks if the currently logged in user is teaching assistant of this course\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is teaching assistant of this course, otherwise false\n */\n public boolean isTeachingAssistantInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getTeachingAssistantGroupName());\n }\n\n /**\n * checks if the currently logged in user is only a student of this course. This means the user is NOT a tutor, NOT an instructor and NOT an ADMIN\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is only student of this course, otherwise false\n */\n public boolean isOnlyStudentInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getStudentGroupName()) && !isAtLeastTeachingAssistantInCourse(course, user);\n }\n\n /**\n * checks if the currently logged in user is student in the given course\n *\n * @param course the course that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is student of this course, otherwise false\n */\n public boolean isStudentInCourse(@NotNull Course course, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n return user.getGroups().contains(course.getStudentGroupName());\n }\n\n /**\n * checks if the currently logged in user is owner of the given participation\n *\n * @param participation the participation that needs to be checked\n * @return true, if user is student is owner of this participation, otherwise false\n */\n public boolean isOwnerOfParticipation(@NotNull StudentParticipation participation) {\n if (participation.getParticipant() == null) {\n return false;\n }\n else {\n return participation.isOwnedBy(SecurityUtils.getCurrentUserLogin().get());\n }\n }\n\n /**\n * checks if the currently logged in user is owner of the given participation\n *\n * @param participation the participation that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is student is owner of this participation, otherwise false\n */\n public boolean isOwnerOfParticipation(@NotNull StudentParticipation participation, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n // only retrieve the user and the groups if the user is null or the groups are missing (to save performance)\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n if (participation.getParticipant() == null) {\n return false;\n }\n else {\n return participation.isOwnedBy(user);\n }\n }\n\n /**\n * checks if the currently logged in user is owner of the given team\n *\n * @param team the team that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true if user is owner of this team, otherwise false\n */\n public boolean isOwnerOfTeam(@NotNull Team team, @NotNull User user) {\n return user.equals(team.getOwner());\n }\n\n /**\n * checks if the currently logged in user is student of the given team\n *\n * @param course the course to which the team belongs to (acts as scope for team short name)\n * @param teamShortName the short name of the team that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is student is owner of this team, otherwise false\n */\n public boolean isStudentInTeam(@NotNull Course course, String teamShortName, @NotNull User user) {\n return userRepository.findAllInTeam(course.getId(), teamShortName).contains(user);\n }\n\n /**\n * Method used to check whether the user of the websocket message is owner of this participation\n *\n * @param participation participation to check the rights for\n * @param principal a representation of the currently logged in user\n * @return true, if user is student is owner of this participation, otherwise false\n */\n public boolean isOwnerOfParticipation(@NotNull StudentParticipation participation, @NotNull Principal principal) {\n return participation.getParticipant() != null && participation.isOwnedBy(principal.getName());\n }\n\n /**\n * checks if the passed user is allowed to see the given exercise, i.e. if the passed user is at least a student in the course\n *\n * @param exercise the exercise that needs to be checked\n * @param user the user whose permissions should be checked\n * @return true, if user is allowed to see this exercise, otherwise false\n */\n public boolean isAllowedToSeeExercise(@NotNull Exercise exercise, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n if (isAdmin(user)) {\n return true;\n }\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n return isAtLeastTeachingAssistantInCourse(course, user) || (isStudentInCourse(course, user) && exercise.isVisibleToStudents());\n }\n\n /**\n * Determines if a user is allowed to see a lecture unit\n *\n * @param lectureUnit the lectureUnit for which to check permission\n * @param user the user for which to check permission\n * @return true if the user is allowed, false otherwise\n */\n public boolean isAllowedToSeeLectureUnit(@NotNull LectureUnit lectureUnit, @Nullable User user) {\n if (user == null || user.getGroups() == null) {\n user = userRepository.getUserWithGroupsAndAuthorities();\n }\n if (isAdmin(user)) {\n return true;\n }\n Course course = lectureUnit.getLecture().getCourse();\n return isInstructorInCourse(course, user) || isTeachingAssistantInCourse(course, user) || (isStudentInCourse(course, user) && lectureUnit.isVisibleToStudents());\n }\n\n /**\n * NOTE: this method should only be used in a REST Call context, when the SecurityContext is correctly setup.\n * Preferably use the method isAdmin(user) below\n *\n * Checks if the currently logged in user is an admin user\n *\n * @return true, if user is admin, otherwise false\n */\n public boolean isAdmin() {\n return SecurityUtils.isCurrentUserInRole(Role.ADMIN.getAuthority());\n }\n\n /**\n * Checks if the passed user is an admin user\n * @param user the user with authorities. If the user is null, the currently logged in user will be used.\n *\n * @return true, if user is admin, otherwise false\n */\n public boolean isAdmin(@Nullable User user) {\n if (user == null) {\n return isAdmin();\n }\n return user.getAuthorities().contains(Authority.ADMIN_AUTHORITY);\n }\n\n /**\n * Checks if the passed user is an admin user. Throws an AccessForbiddenException in case the user is not an admin\n * @param user the user with authorities. If the user is null, the currently logged in user will be used.\n **/\n public void checkIsAdminElseThrow(@Nullable User user) {\n if (!isAdmin(user)) {\n throw new AccessForbiddenException(NOT_ALLOWED);\n }\n }\n\n /**\n * Checks if the currently logged in user is allowed to retrieve the given result.\n * The user is allowed to retrieve the result if (s)he is an instructor of the course, or (s)he is at least a student in the corresponding course, the\n * submission is his/her submission, the assessment due date of the corresponding exercise is in the past (or not set) and the result is finished.\n *\n * @param exercise the corresponding exercise\n * @param participation the participation the result belongs to\n * @param result the result that should be sent to the client\n * @return true if the user is allowed to retrieve the given result, false otherwise\n */\n public boolean isUserAllowedToGetResult(Exercise exercise, StudentParticipation participation, Result result) {\n return isAtLeastStudentForExercise(exercise) && (isOwnerOfParticipation(participation) || isAtLeastInstructorForExercise(exercise))\n && (exercise.getAssessmentDueDate() == null || exercise.getAssessmentDueDate().isBefore(ZonedDateTime.now())) && result.getAssessor() != null\n && result.getCompletionDate() != null;\n }\n\n /**\n * Checks if the user is allowed to see the exam result. Returns true if\n *\n * - the current user is at least teaching assistant in the course\n * - OR if the exercise is not part of an exam\n * - OR if the exam has not ended\n * - OR if the exam has already ended and the results were published\n *\n * @param exercise - Exercise that the result is requested for\n * @param user - User that requests the result\n * @return true if user is allowed to see the result, false otherwise\n */\n public boolean isAllowedToGetExamResult(Exercise exercise, User user) {\n return this.isAtLeastTeachingAssistantInCourse(exercise.getCourseViaExerciseGroupOrCourseMember(), user)\n || (exercise.isCourseExercise() || (exercise.isExamExercise() && exercise.getExerciseGroup().getExam().getEndDate().isAfter(ZonedDateTime.now()))\n || exercise.getExerciseGroup().getExam().resultsPublished());\n }\n\n /**\n * Check if a participation can be accessed with the current user.\n *\n * @param participation to access\n * @return can user access participation\n */\n public boolean canAccessParticipation(StudentParticipation participation) {\n return Optional.ofNullable(participation).isPresent() && userHasPermissionsToAccessParticipation(participation);\n }\n\n /**\n * Check if a user has permissions to access a certain participation. This includes not only the owner of the participation but also the TAs and instructors of the course.\n *\n * @param participation to access\n * @return does user has permissions to access participation\n */\n private boolean userHasPermissionsToAccessParticipation(StudentParticipation participation) {\n if (isOwnerOfParticipation(participation)) {\n return true;\n }\n // if the user is not the owner of the participation, the user can only see it in case he is\n // a teaching assistant or an instructor of the course, or in case he is admin\n User user = userRepository.getUserWithGroupsAndAuthorities();\n Course course = participation.getExercise().getCourseViaExerciseGroupOrCourseMember();\n return isAtLeastTeachingAssistantInCourse(course, user);\n }\n\n /**\n * Tutors of an exercise are allowed to assess the submissions, but only instructors are allowed to assess with a specific result\n *\n * @param exercise Exercise of the submission\n * @param user User the requests the assessment\n * @param resultId Id of the result he wants to assess\n * @return true if caller is allowed to assess submissions\n */\n public boolean isAllowedToAssesExercise(Exercise exercise, User user, Long resultId) {\n return this.isAtLeastTeachingAssistantForExercise(exercise, user) && (resultId == null || isAtLeastInstructorForExercise(exercise, user));\n }\n}\n" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 47.52941131591797, "blob_id": "957ab09eeef90f595a7f98f5ce19b06cd68f88b4", "content_id": "64c8e8d2fa594f0ed7028cd3e3b9da9e9929ca54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 825, "license_type": "permissive", "max_line_length": 100, "num_lines": 17, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-result.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { Observable, of } from 'rxjs';\nimport { IResultService } from 'app/exercises/shared/result/result.service';\nimport { Result } from 'app/entities/result.model';\n\nexport class MockResultService implements IResultService {\n create = (result: Result) => of();\n delete = (id: number) => Observable.empty();\n find = (id: number) => Observable.empty();\n findBySubmissionId = (submissionId: number) => Observable.empty();\n getFeedbackDetailsForResult = (resultId: number) => Observable.empty();\n getResultsForExercise = (courseId: number, exerciseId: number, req?: any) => Observable.empty();\n update = (result: Result) => of();\n getLatestResultWithFeedbacks(particpationId: number): Observable<HttpResponse<Result>> {\n return of();\n }\n}\n" }, { "alpha_fraction": 0.648219645023346, "alphanum_fraction": 0.648219645023346, "avg_line_length": 45.158416748046875, "blob_id": "9274b937afedbbdefae3e3d5db2a28e710058ccd", "content_id": "2f2c96095cc63caf551ab0cafd4126113e0db9e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4662, "license_type": "permissive", "max_line_length": 180, "num_lines": 101, "path": "/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-management.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { FileUploadExerciseDetailComponent } from './file-upload-exercise-detail.component';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { Observable } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { Injectable, NgModule } from '@angular/core';\nimport { filter, map } from 'rxjs/operators';\nimport { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';\nimport { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\n@Injectable({ providedIn: 'root' })\nexport class FileUploadExerciseResolve implements Resolve<FileUploadExercise> {\n constructor(private fileUploadExerciseService: FileUploadExerciseService, private courseService: CourseManagementService, private exerciseGroupService: ExerciseGroupService) {}\n\n /**\n * Resolves the route and initializes file upload exercise either from exerciseId (existing exercise) or\n * from course id (new exercise)\n * @param route\n */\n resolve(route: ActivatedRouteSnapshot) {\n if (route.params['exerciseId']) {\n return this.fileUploadExerciseService.find(route.params['exerciseId']).pipe(\n filter((res) => !!res.body),\n map((fileUploadExercise: HttpResponse<FileUploadExercise>) => fileUploadExercise.body!),\n );\n } else if (route.params['courseId']) {\n if (route.params['examId'] && route.params['groupId']) {\n return this.exerciseGroupService.find(route.params['courseId'], route.params['examId'], route.params['groupId']).pipe(\n filter((res) => !!res.body),\n map((exerciseGroup: HttpResponse<ExerciseGroup>) => {\n const fileUploadExercise = new FileUploadExercise(undefined, exerciseGroup.body!);\n fileUploadExercise.filePattern = 'pdf, png';\n return fileUploadExercise;\n }),\n );\n } else {\n return this.courseService.find(route.params['courseId']).pipe(\n filter((res) => !!res.body),\n map((course: HttpResponse<Course>) => {\n const fileUploadExercise = new FileUploadExercise(course.body!, undefined);\n fileUploadExercise.filePattern = 'pdf, png';\n return fileUploadExercise;\n }),\n );\n }\n }\n return Observable.of(new FileUploadExercise(undefined, undefined));\n }\n}\n\nconst routes: Routes = [\n {\n path: ':courseId/file-upload-exercises/new',\n component: FileUploadExerciseUpdateComponent,\n resolve: {\n fileUploadExercise: FileUploadExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/file-upload-exercises/:exerciseId/edit',\n component: FileUploadExerciseUpdateComponent,\n resolve: {\n fileUploadExercise: FileUploadExerciseResolve,\n },\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/file-upload-exercises/:exerciseId',\n component: FileUploadExerciseDetailComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.fileUploadExercise.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/file-upload-exercises',\n redirectTo: ':courseId/exercises',\n },\n];\n\n@NgModule({\n imports: [RouterModule.forChild(routes)],\n exports: [RouterModule],\n})\nexport class ArtemisFileUploadExerciseManagementRoutingModule {}\n" }, { "alpha_fraction": 0.6930099725723267, "alphanum_fraction": 0.6949465274810791, "avg_line_length": 40.07575607299805, "blob_id": "ac694288d40795616177a31c95947c1ccae701d1", "content_id": "05e0348c6a0bc8c50f194d6f34f1bd3d902a793f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10844, "license_type": "permissive", "max_line_length": 177, "num_lines": 264, "path": "/src/main/java/de/tum/in/www1/artemis/service/compass/controller/AutomaticAssessmentController.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.compass.controller;\n\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n\nimport com.hazelcast.core.HazelcastInstance;\n\nimport de.tum.in.www1.artemis.domain.Feedback;\nimport de.tum.in.www1.artemis.service.compass.assessment.CompassResult;\nimport de.tum.in.www1.artemis.service.compass.assessment.Score;\nimport de.tum.in.www1.artemis.service.compass.assessment.SimilaritySetAssessment;\nimport de.tum.in.www1.artemis.service.compass.umlmodel.UMLDiagram;\nimport de.tum.in.www1.artemis.service.compass.umlmodel.UMLElement;\n\npublic class AutomaticAssessmentController {\n\n private final Logger log = LoggerFactory.getLogger(AutomaticAssessmentController.class);\n\n private Map<Integer, SimilaritySetAssessment> similarityIdAssessmentMapping;\n\n private Map<Long, CompassResult> lastAssessmentResultMapping;\n\n HazelcastInstance hazelcastInstance;\n\n static Map<Long, Double> totalCoverages;\n\n static Map<Long, Double> totalConfidences;\n\n private Long exerciseId;\n\n public AutomaticAssessmentController(Long exerciseId, HazelcastInstance hazelcastInstance) {\n similarityIdAssessmentMapping = hazelcastInstance.getMap(\"modelAssessments - \" + exerciseId);\n lastAssessmentResultMapping = hazelcastInstance.getMap(\"modelResults - \" + exerciseId);\n this.hazelcastInstance = hazelcastInstance;\n this.exerciseId = exerciseId;\n }\n\n /**\n * Get the assessment for the similarity set with the given similarityId.\n *\n * @param similarityId the ID of the similarity set\n * @return an Optional containing the assessment if the similarity ID exists, an empty Optional otherwise\n */\n public Optional<SimilaritySetAssessment> getAssessmentForSimilaritySet(int similarityId) {\n SimilaritySetAssessment similaritySetAssessment = similarityIdAssessmentMapping.get(similarityId);\n return Optional.ofNullable(similaritySetAssessment);\n }\n\n /**\n * Add a new assessment for the similarity set with the given ID to the similarityId assessment mapping.\n *\n * @param similarityId the ID of the corresponding similarity set\n * @param similaritySetAssessment the assessment for the corresponding similarity set\n */\n protected void addSimilaritySetAssessment(int similarityId, SimilaritySetAssessment similaritySetAssessment) {\n similarityIdAssessmentMapping.putIfAbsent(similarityId, similaritySetAssessment);\n }\n\n /**\n * Used for statistics. Get the complete map of similarity set assessments.\n *\n * @return The complete map with all similarity set assessments\n */\n public Map<Integer, SimilaritySetAssessment> getAssessmentMap() {\n return this.similarityIdAssessmentMapping;\n }\n\n /**\n * For every model element it adds the feedback to the assessment of the corresponding similarity set. If there is no assessment for the similarity set yet, it creates a new\n * one.\n *\n * @param feedbacks list of feedbacks\n * @param model the UML model - contains all elements with its jsonIds\n */\n public void addFeedbacksToSimilaritySet(List<Feedback> feedbacks, UMLDiagram model) {\n for (Feedback feedback : feedbacks) {\n String jsonElementId = feedback.getReferenceElementId();\n if (jsonElementId != null) {\n UMLElement element = model.getElementByJSONID(jsonElementId);\n\n if (element == null) {\n log.warn(\"Element with id {} could not be found in model.\", jsonElementId);\n continue;\n }\n\n Optional<SimilaritySetAssessment> optionalAssessment = getAssessmentForSimilaritySet(element.getSimilarityID());\n\n if (optionalAssessment.isPresent()) {\n optionalAssessment.get().addFeedback(feedback);\n similarityIdAssessmentMapping.put(element.getSimilarityID(), optionalAssessment.get());\n }\n else {\n SimilaritySetAssessment newAssessment = new SimilaritySetAssessment(feedback);\n addSimilaritySetAssessment(element.getSimilarityID(), newAssessment);\n }\n }\n }\n }\n\n /**\n * Loop over all models and triggers their automatic assessment.\n *\n * @param modelIndex manages all models\n */\n // TODO CZ: only assess models automatically that do not already have a complete manual assessment?\n public void assessModelsAutomatically(ModelIndex modelIndex) {\n\n double totalCoverage = 0;\n double totalConfidence = 0;\n\n for (UMLDiagram model : modelIndex.getModelCollection()) {\n\n CompassResult compassResult = assessModelAutomatically(model);\n\n totalCoverage += compassResult.getCoverage();\n totalConfidence += compassResult.getConfidence();\n\n }\n\n totalConfidence /= modelIndex.getModelCollectionSize();\n totalCoverage /= modelIndex.getModelCollectionSize();\n\n setTotalConfidence(totalConfidence);\n setTotalCoverage(totalCoverage);\n }\n\n /**\n * Loop over all elements of the given model, get their assessments form the assessment index and build a Compass result with them.\n *\n * @param model the UML model which contains all the model elements\n * @return a Compass result built from the assessments of the model elements\n */\n public CompassResult assessModelAutomatically(UMLDiagram model) {\n double totalCount = 0;\n double missingCount = 0;\n\n Map<String, Score> scoreHashMap = new ConcurrentHashMap<>();\n\n for (UMLElement element : model.getAllModelElements()) {\n Optional<SimilaritySetAssessment> optionalAssessment = getAssessmentForSimilaritySet(element.getSimilarityID());\n totalCount++;\n\n if (optionalAssessment.isEmpty()) {\n missingCount++;\n }\n else {\n Score score = optionalAssessment.get().getScore();\n\n if (score == null) {\n log.debug(\"Unable to find score for element {} in model {} with the specific context\", element.getJSONElementID(), model.getModelSubmissionId());\n }\n else {\n scoreHashMap.put(element.getJSONElementID(), score);\n }\n }\n }\n\n double coverage = 1;\n\n if (totalCount != 0) {\n coverage = (totalCount - missingCount) / totalCount;\n }\n else {\n log.warn(\"'totalCount' was 0. Set coverage to 1 for a CompassResult\");\n }\n\n CompassResult compassResult = new CompassResult(scoreHashMap, coverage);\n\n lastAssessmentResultMapping.put(model.getModelSubmissionId(), compassResult);\n\n return compassResult;\n }\n\n public void setTotalCoverage(double totalCoverage) {\n if (AutomaticAssessmentController.totalCoverages == null) {\n AutomaticAssessmentController.totalCoverages = hazelcastInstance.getMap(\"totalCoverages\");\n }\n AutomaticAssessmentController.totalCoverages.put(exerciseId, totalCoverage);\n }\n\n public double getTotalCoverage() {\n if (AutomaticAssessmentController.totalCoverages == null) {\n AutomaticAssessmentController.totalCoverages = hazelcastInstance.getMap(\"totalCoverages\");\n }\n return AutomaticAssessmentController.totalCoverages.get(exerciseId);\n }\n\n public void setTotalConfidence(double totalConfidence) {\n if (AutomaticAssessmentController.totalConfidences == null) {\n AutomaticAssessmentController.totalConfidences = hazelcastInstance.getMap(\"totalCoverages\");\n }\n AutomaticAssessmentController.totalConfidences.put(exerciseId, totalConfidence);\n }\n\n public double getTotalConfidence() {\n if (AutomaticAssessmentController.totalConfidences == null) {\n AutomaticAssessmentController.totalConfidences = hazelcastInstance.getMap(\"totalCoverages\");\n }\n return AutomaticAssessmentController.totalConfidences.get(exerciseId);\n }\n\n /**\n * Set the lastAssessmentCompassResult that represents the most recent automatic assessment calculated by Compass for this diagram.\n *\n * @param submissionId submission that the result will be assigned to\n * @param compassResult the most recent Compass result for this diagram\n */\n public void setLastAssessmentCompassResult(Long submissionId, CompassResult compassResult) {\n lastAssessmentResultMapping.put(submissionId, compassResult);\n }\n\n /**\n * Returns the lastAssessmentCompassResult that represents the most recent automatic assessment calculated by Compass for this diagram.\n * This method is deprecated because the UML Diagram should not store such information. This should rather be stored somewhere else!\n *\n * @param submissionId submission whose result will be returned\n * @return the most recent Compass result for the submission\n */\n public CompassResult getLastAssessmentCompassResult(Long submissionId) {\n return lastAssessmentResultMapping.get(submissionId);\n }\n\n /**\n * Indicates if this diagram already has an automatic assessment calculated by Compass or not.\n *\n * @param submissionId submission that will be check if assessed or not\n * @return true if Compass has not already calculated an automatic assessment for the submission, false otherwise\n */\n public boolean isUnassessed(Long submissionId) {\n return getLastAssessmentCompassResult(submissionId) == null;\n }\n\n /**\n * Get the confidence of the last compass result, i.e. the most recent automatic assessment calculated by Compass for the submission.\n * @param submissionId id of the submission\n * @return The confidence of the last compass result, -1 if no compass result is available\n */\n public double getLastAssessmentConfidence(Long submissionId) {\n if (isUnassessed(submissionId)) {\n return -1;\n }\n\n return getLastAssessmentCompassResult(submissionId).getConfidence();\n }\n\n /**\n * Get the coverage for the last assessed compass result, i.e. the most recent automatic assessment calculated by Compass for the submission.\n *\n * @param submissionId id of the submission\n * @return The coverage of the last compass result, -1 if no compass result is available\n */\n public double getLastAssessmentCoverage(Long submissionId) {\n if (isUnassessed(submissionId)) {\n return -1;\n }\n\n return getLastAssessmentCompassResult(submissionId).getCoverage();\n }\n}\n" }, { "alpha_fraction": 0.8171021342277527, "alphanum_fraction": 0.8218527436256409, "avg_line_length": 29.071428298950195, "blob_id": "bf00769414d94d37f73cd5fe55ada1b5d6ddcd4c", "content_id": "7ea750031c7f72bac368a91abdc237490cae12c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 421, "license_type": "permissive", "max_line_length": 93, "num_lines": 14, "path": "/src/main/java/de/tum/in/www1/artemis/repository/SingleUserNotificationRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.notification.Notification;\n\n/**\n * Spring Data repository for the Notification entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface SingleUserNotificationRepository extends JpaRepository<Notification, Long> {\n}\n" }, { "alpha_fraction": 0.6338477730751038, "alphanum_fraction": 0.63517826795578, "avg_line_length": 40.75555419921875, "blob_id": "d603845956703d210b83902dcd31d8ed73b9786d", "content_id": "1f638df6207ef316193bd9941cd3c631532f992c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3758, "license_type": "permissive", "max_line_length": 147, "num_lines": 90, "path": "/src/main/webapp/app/shared/notification/connection-notification/connection-notification.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { User } from 'app/core/user/user.model';\nimport { ConnectionNotification, ConnectionNotificationType } from 'app/shared/notification/connection-notification/connection-notification.model';\nimport { IconProp } from '@fortawesome/fontawesome-svg-core';\n\n@Component({\n selector: 'jhi-connection-notification',\n templateUrl: './connection-notification.component.html',\n styleUrls: ['connection-notification.scss'],\n})\nexport class ConnectionNotificationComponent implements OnInit, OnDestroy {\n notification = new ConnectionNotification();\n alert?: { class: string; icon: IconProp; text: string };\n connected?: boolean;\n\n constructor(private accountService: AccountService, private jhiWebsocketService: JhiWebsocketService) {}\n\n ngOnInit() {\n this.accountService.getAuthenticationState().subscribe((user: User | undefined) => {\n if (user) {\n // listen to connect / disconnect events\n this.jhiWebsocketService.enableReconnect();\n this.jhiWebsocketService.bind('connect', this.onConnect);\n this.jhiWebsocketService.bind('disconnect', this.onDisconnect);\n } else {\n // On logout, reset component\n this.connected = undefined;\n this.alert = undefined;\n this.notification.type = undefined;\n this.jhiWebsocketService.disableReconnect();\n this.jhiWebsocketService.unbind('connect', this.onConnect);\n this.jhiWebsocketService.unbind('disconnect', this.onDisconnect);\n }\n });\n }\n\n ngOnDestroy() {\n this.jhiWebsocketService.unbind('connect', this.onConnect);\n this.jhiWebsocketService.unbind('disconnect', this.onDisconnect);\n }\n\n /**\n * Only update on connect if there is not already an active connection.\n * This alert is temporary and disappears after 5 seconds.\n **/\n\n onConnect = () => {\n if (this.connected === false) {\n this.notification.type = ConnectionNotificationType.RECONNECTED;\n this.updateAlert();\n // The reconnect alert should only be displayed temporarily\n setTimeout(() => {\n this.notification.type = ConnectionNotificationType.CONNECTED;\n this.updateAlert();\n }, 5000);\n }\n this.connected = true;\n };\n\n /**\n * Only update on disconnect if the connection was active before.\n * This needs to be checked because the websocket service triggers a disconnect before the connect.\n **/\n\n onDisconnect = () => {\n if (this.connected === true) {\n this.notification.type = ConnectionNotificationType.DISCONNECTED;\n this.updateAlert();\n this.connected = false;\n }\n };\n\n /**\n * Update the alert to fit the state of the notification.\n **/\n\n updateAlert(): void {\n if (this.notification) {\n if (this.notification.type === ConnectionNotificationType.DISCONNECTED) {\n this.alert = { class: 'alert-danger', icon: 'times-circle', text: 'artemisApp.connectionAlert.disconnected' };\n } else if (this.notification.type === ConnectionNotificationType.RECONNECTED) {\n this.alert = { class: 'alert-success', icon: 'check-circle', text: 'artemisApp.connectionAlert.reconnected' };\n } else if (this.notification.type === ConnectionNotificationType.CONNECTED) {\n this.alert = undefined;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6794683337211609, "alphanum_fraction": 0.6800979375839233, "avg_line_length": 43.12036895751953, "blob_id": "76d529bd08c70eb372afb91c45d9101dda1877a5", "content_id": "efb65f321866c2fe43c7faa8491c7fb3e63d776c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 14295, "license_type": "permissive", "max_line_length": 167, "num_lines": 324, "path": "/src/main/java/de/tum/in/www1/artemis/service/RepositoryService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.io.*;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.*;\nimport java.security.Principal;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Optional;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.io.FileUtils;\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.File;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.web.rest.dto.FileMove;\n\n/**\n * Service that provides utilities for managing files in a git repository.\n */\n@Service\npublic class RepositoryService {\n\n private final GitService gitService;\n\n private final AuthorizationCheckService authCheckService;\n\n private final UserRepository userRepository;\n\n private final Logger log = LoggerFactory.getLogger(RepositoryService.class);\n\n public RepositoryService(GitService gitService, AuthorizationCheckService authCheckService, UserRepository userRepository) {\n this.gitService = gitService;\n this.authCheckService = authCheckService;\n this.userRepository = userRepository;\n }\n\n /**\n * Get the repository content (files and folders).\n *\n * @param repository VCS repository to get files for.\n * @return a map of files with the information if they are a file or a folder.\n */\n public Map<String, FileType> getFiles(Repository repository) {\n var iterator = gitService.listFilesAndFolders(repository).entrySet().iterator();\n\n Map<String, FileType> fileList = new HashMap<>();\n\n while (iterator.hasNext()) {\n Map.Entry<File, FileType> pair = iterator.next();\n fileList.put(pair.getKey().toString(), pair.getValue());\n }\n\n return fileList;\n }\n\n /**\n * Get all files/folders with content from repository.\n *\n * @param repository in which the requested files are located\n * @return Files with code or an exception is thrown\n */\n public Map<String, String> getFilesWithContent(Repository repository) {\n var files = gitService.listFilesAndFolders(repository).entrySet().stream().filter(entry -> entry.getValue() == FileType.FILE).map(Map.Entry::getKey)\n .collect(Collectors.toList());\n Map<String, String> fileListWithContent = new HashMap<>();\n\n files.forEach(file -> {\n try {\n fileListWithContent.put(file.toString(), FileUtils.readFileToString(file, StandardCharsets.UTF_8));\n }\n catch (IOException e) {\n log.error(\"Content of file: {} could not be loaded and throws the following error: {}\", file.toString(), e.getMessage());\n }\n });\n return fileListWithContent;\n }\n\n /**\n * Get a single file/folder from repository.\n *\n * @param repository in which the requested file is located.\n * @param filename of the file to be retrieved.\n * @return The file if found or throw an exception.\n * @throws IOException if the file can't be found, is corrupt, etc.\n */\n public byte[] getFile(Repository repository, String filename) throws IOException {\n Optional<File> file = gitService.getFileByName(repository, filename);\n if (file.isEmpty()) {\n throw new FileNotFoundException();\n }\n InputStream inputStream = new FileInputStream(file.get());\n byte[] fileInBytes = org.apache.commons.io.IOUtils.toByteArray(inputStream);\n inputStream.close();\n return fileInBytes;\n }\n\n /**\n * Gets the files of the repository and checks whether they were changed during a student participation.\n * Compares the files from the students repository with the files of the template repository.\n *\n * @param repository the students repository with possibly new files and changed files\n * @param templateRepository the template repository with default files on which the student started working on\n * @return a map of files with the information if they were changed/are new.\n */\n public Map<String, Boolean> getFilesWithInformationAboutChange(Repository repository, Repository templateRepository) {\n Map<String, Boolean> filesWithInformationAboutChange = new HashMap<>();\n\n var repoFiles = gitService.listFilesAndFolders(repository).entrySet().stream().filter(entry -> entry.getValue() == FileType.FILE).map(Map.Entry::getKey)\n .collect(Collectors.toList());\n\n Map<String, File> templateRepoFiles = gitService.listFilesAndFolders(templateRepository).entrySet().stream().filter(entry -> entry.getValue() == FileType.FILE)\n .collect(Collectors.toMap(entry -> entry.getKey().toString(), Map.Entry::getKey));\n\n repoFiles.forEach(file -> {\n String fileName = file.toString();\n\n if (templateRepoFiles.get(fileName) == null) {\n filesWithInformationAboutChange.put(fileName, true);\n }\n else {\n File templateFile = templateRepoFiles.get(fileName);\n try {\n if (FileUtils.contentEquals(file, templateFile)) {\n filesWithInformationAboutChange.put(fileName, false);\n }\n else {\n filesWithInformationAboutChange.put(fileName, true);\n }\n }\n catch (IOException e) {\n log.error(\"Comparing files '{}' with '{}' failed: {}\", fileName, templateFile.toString(), e.getMessage());\n }\n }\n });\n return filesWithInformationAboutChange;\n }\n\n /**\n * Create a file in a repository.\n *\n * @param repository in which the file should be created.\n * @param filename of the file to be created.\n * @param inputStream byte representation of the file to be created.\n * @throws IOException if the inputStream is corrupt, the file can't be stored, the repository is unavailable, etc.\n */\n public void createFile(Repository repository, String filename, InputStream inputStream) throws IOException {\n File file = checkIfFileExistsInRepository(repository, filename);\n Files.copy(inputStream, file.toPath(), StandardCopyOption.REPLACE_EXISTING);\n repository.setContent(null); // invalidate cache\n inputStream.close();\n }\n\n private File checkIfFileExistsInRepository(Repository repository, String filename) throws FileAlreadyExistsException {\n if (gitService.getFileByName(repository, filename).isPresent()) {\n throw new FileAlreadyExistsException(\"file already exists\");\n }\n\n File file = new File(Paths.get(repository.getLocalPath().toString(), filename).toFile(), repository);\n if (!repository.isValidFile(file)) {\n throw new IllegalArgumentException();\n }\n return file;\n }\n\n /**\n * Create a folder in a repository.\n *\n * @param repository in which the folder should be created.\n * @param folderName of the folder to be created.\n * @param inputStream byte representation of the folder to be created.\n * @throws IOException if the inputStream is corrupt, the folder can't be stored, the repository is unavailable, etc.\n */\n public void createFolder(Repository repository, String folderName, InputStream inputStream) throws IOException {\n checkIfFileExistsInRepository(repository, folderName);\n Files.createDirectory(repository.getLocalPath().resolve(folderName));\n // We need to add an empty keep file so that the folder can be added to the git repository\n File keep = new File(repository.getLocalPath().resolve(folderName).resolve(\".keep\"), repository);\n Files.copy(inputStream, keep.toPath(), StandardCopyOption.REPLACE_EXISTING);\n repository.setContent(null); // invalidate cache\n inputStream.close();\n }\n\n /**\n * Rename a file in a repository.\n *\n * @param repository in which the file is located.\n * @param fileMove dto for describing the old and the new filename.\n * @throws FileNotFoundException if the file to rename is not available.\n * @throws FileAlreadyExistsException if the new filename is already taken.\n * @throws IllegalArgumentException if the new filename is not allowed (e.g. contains .. or /../)\n */\n public void renameFile(Repository repository, FileMove fileMove) throws FileNotFoundException, FileAlreadyExistsException, IllegalArgumentException {\n Optional<File> existingFile = gitService.getFileByName(repository, fileMove.getCurrentFilePath());\n if (existingFile.isEmpty()) {\n throw new FileNotFoundException();\n }\n if (!repository.isValidFile(existingFile.get())) {\n throw new IllegalArgumentException();\n }\n File newFile = new File(existingFile.get().toPath().getParent().resolve(fileMove.getNewFilename()), repository);\n if (gitService.getFileByName(repository, newFile.getName()).isPresent()) {\n throw new FileAlreadyExistsException(\"file already exists\");\n }\n boolean isRenamed = existingFile.get().renameTo(newFile);\n if (!isRenamed) {\n throw new FileNotFoundException();\n }\n\n repository.setContent(null); // invalidate cache\n }\n\n /**\n * Delete a file in a repository.\n *\n * @param repository in which the file to delete is located.\n * @param filename to delete.\n * @throws IOException if the file can't be deleted.\n * @throws FileNotFoundException if the file can't be found.\n * @throws IllegalArgumentException if the filename contains forbidden sequences (e.g. .. or /../).\n */\n public void deleteFile(Repository repository, String filename) throws IllegalArgumentException, IOException {\n\n Optional<File> file = gitService.getFileByName(repository, filename);\n\n if (file.isEmpty()) {\n throw new FileNotFoundException();\n }\n if (!repository.isValidFile(file.get())) {\n throw new IllegalArgumentException();\n }\n if (file.get().isFile()) {\n Files.delete(file.get().toPath());\n }\n else {\n FileUtils.deleteDirectory(file.get());\n }\n repository.setContent(null); // invalidate cache\n }\n\n /**\n * Pull from a git repository.\n *\n * @param repository for which to pull the current state of the remote.\n */\n public void pullChanges(Repository repository) {\n gitService.pullIgnoreConflicts(repository);\n }\n\n /**\n * Commit all staged and unstaged changes in the given repository.\n *\n * @param repository for which to execute the commit.\n * @param user the user who has committed the changes in the online editor\n * @throws GitAPIException if the staging/committing process fails.\n */\n public void commitChanges(Repository repository, User user) throws GitAPIException {\n gitService.stageAllChanges(repository);\n gitService.commitAndPush(repository, \"Changes by Online Editor\", user);\n }\n\n /**\n * Retrieve the status of the repository. Also pulls the repository.\n *\n * @param repositoryUrl of the repository to check the status for.\n * @return a dto to determine the status of the repository.\n * @throws InterruptedException if the repository can't be checked out on the server.\n * @throws GitAPIException if the repository status can't be retrieved.\n */\n public boolean isClean(VcsRepositoryUrl repositoryUrl) throws GitAPIException, InterruptedException {\n Repository repository = gitService.getOrCheckoutRepository(repositoryUrl, true);\n return gitService.isClean(repository);\n }\n\n /**\n * Retrieve a repository by its name.\n *\n * @param exercise to which the repository belongs.\n * @param repoUrl of the repository on the server.\n * @param pullOnCheckout if true pulls after checking out the git repository.\n * @return the repository if available.\n * @throws GitAPIException if the repository can't be checked out.\n * @throws IllegalAccessException if the user does not have access to the repository.\n * @throws InterruptedException if the repository can't be checked out.\n */\n public Repository checkoutRepositoryByName(Exercise exercise, VcsRepositoryUrl repoUrl, boolean pullOnCheckout)\n throws IllegalAccessException, InterruptedException, GitAPIException {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n boolean hasPermissions = authCheckService.isAtLeastTeachingAssistantInCourse(course, user);\n if (!hasPermissions) {\n throw new IllegalAccessException();\n }\n return gitService.getOrCheckoutRepository(repoUrl, pullOnCheckout);\n }\n\n /**\n * Retrieve a repository by its name.\n *\n * @param principal entity used for permission checking.\n * @param exercise to which the repository belongs.\n * @param repoUrl of the repository on the server.\n * @return the repository if available.\n * @throws GitAPIException if the repository can't be checked out.\n * @throws IllegalAccessException if the user does not have access to the repository.\n * @throws InterruptedException if the repository can't be checked out.\n */\n public Repository checkoutRepositoryByName(Principal principal, Exercise exercise, VcsRepositoryUrl repoUrl)\n throws IllegalAccessException, InterruptedException, GitAPIException {\n User user = userRepository.getUserWithGroupsAndAuthorities(principal.getName());\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n boolean hasPermissions = authCheckService.isAtLeastInstructorInCourse(course, user);\n if (!hasPermissions) {\n throw new IllegalAccessException();\n }\n return gitService.getOrCheckoutRepository(repoUrl, true);\n }\n}\n" }, { "alpha_fraction": 0.7612903118133545, "alphanum_fraction": 0.7612903118133545, "avg_line_length": 37.75, "blob_id": "a1f7eef165141703b26c2beae81b664650c5bee7", "content_id": "a3ebf0be41afdc04982dd1e30561e74d70fec3a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 465, "license_type": "permissive", "max_line_length": 76, "num_lines": 12, "path": "/src/main/webapp/app/core/legal/legal.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\nimport { LegalRoutingModule } from 'app/core/legal/legal-routing.module';\nimport { PrivacyComponent } from 'app/core/legal/privacy/privacy.component';\n\n@NgModule({\n declarations: [PrivacyComponent],\n imports: [CommonModule, ArtemisSharedModule, LegalRoutingModule],\n})\nexport class ArtemisLegalModule {}\n" }, { "alpha_fraction": 0.7802495956420898, "alphanum_fraction": 0.7802495956420898, "avg_line_length": 54.84848403930664, "blob_id": "6a8ed951f7cdda313f29d13a865ca30cec4706d8", "content_id": "030b0e50500389ed0047c02c89d4925c76ceadea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3686, "license_type": "permissive", "max_line_length": 151, "num_lines": 66, "path": "/src/main/webapp/app/admin/admin.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\nimport { adminState } from './admin.route';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\nimport { AdminFeatureToggleComponent } from 'app/admin/features/admin-feature-toggle.component';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { TagInputModule } from 'ngx-chips';\nimport { UserManagementDetailComponent } from 'app/admin/user-management/user-management-detail.component';\nimport { LogsComponent } from 'app/admin/logs/logs.component';\nimport { JhiMetricsMonitoringComponent } from 'app/admin/metrics/metrics.component';\nimport { HealthComponent } from 'app/admin/health/health.component';\nimport { JhiConfigurationComponent } from 'app/admin/configuration/configuration.component';\nimport { SystemNotificationManagementComponent } from 'app/admin/system-notification-management/system-notification-management.component';\nimport { SystemNotificationManagementUpdateComponent } from 'app/admin/system-notification-management/system-notification-management-update.component';\nimport { StatisticsComponent } from 'app/admin/statistics/statistics.component';\nimport { AuditsComponent } from 'app/admin/audits/audits.component';\nimport { HealthModalComponent } from 'app/admin/health/health-modal.component';\nimport { UserManagementComponent } from 'app/admin/user-management/user-management.component';\nimport { UserManagementUpdateComponent } from 'app/admin/user-management/user-management-update.component';\nimport { SystemNotificationManagementDetailComponent } from 'app/admin/system-notification-management/system-notification-management-detail.component';\nimport { UpcomingExamsAndExercisesComponent } from './upcoming-exams-and-exercises/upcoming-exams-and-exercises.component';\nimport { DocsComponent } from 'app/admin/docs/docs.component';\nimport { OrganizationManagementComponent } from './organization-management/organization-management.component';\nimport { OrganizationManagementDetailComponent } from './organization-management/organization-management-detail.component';\nimport { OrganizationManagementUpdateComponent } from './organization-management/organization-management-update.component';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\n\n/* jhipster-needle-add-admin-module-import - JHipster will add admin modules imports here */\n\nconst ENTITY_STATES = [...adminState];\n\n@NgModule({\n imports: [\n RouterModule.forChild(ENTITY_STATES),\n ArtemisSharedModule,\n FormDateTimePickerModule,\n TagInputModule,\n NgxDatatableModule,\n ArtemisDataTableModule,\n /* jhipster-needle-add-admin-module - JHipster will add admin modules here */\n ],\n declarations: [\n AuditsComponent,\n UserManagementComponent,\n UserManagementDetailComponent,\n UserManagementUpdateComponent,\n SystemNotificationManagementComponent,\n SystemNotificationManagementDetailComponent,\n SystemNotificationManagementUpdateComponent,\n LogsComponent,\n DocsComponent,\n JhiConfigurationComponent,\n HealthComponent,\n HealthModalComponent,\n StatisticsComponent,\n JhiMetricsMonitoringComponent,\n AdminFeatureToggleComponent,\n UpcomingExamsAndExercisesComponent,\n OrganizationManagementComponent,\n OrganizationManagementDetailComponent,\n OrganizationManagementUpdateComponent,\n ],\n entryComponents: [HealthModalComponent],\n})\nexport class ArtemisAdminModule {}\n" }, { "alpha_fraction": 0.7202904224395752, "alphanum_fraction": 0.7295885682106018, "avg_line_length": 49.98051834106445, "blob_id": "e9e96d01fe721aedec74a9c001b18f01708b929a", "content_id": "c858830ecbab96866fe76060eb1d3cbddeef8163", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7851, "license_type": "permissive", "max_line_length": 177, "num_lines": 154, "path": "/src/test/java/de/tum/in/www1/artemis/VideoUnitIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.Lecture;\nimport de.tum.in.www1.artemis.domain.lecture.VideoUnit;\nimport de.tum.in.www1.artemis.repository.LectureRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.repository.VideoUnitRepository;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class VideoUnitIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private VideoUnitRepository videoUnitRepository;\n\n @Autowired\n private LectureRepository lectureRepository;\n\n private Lecture lecture1;\n\n private VideoUnit videoUnit;\n\n @BeforeEach\n public void initTestCase() throws Exception {\n this.database.addUsers(1, 1, 1);\n this.lecture1 = this.database.createCourseWithLecture(true);\n this.videoUnit = new VideoUnit();\n this.videoUnit.setDescription(\"LoremIpsum\");\n this.videoUnit.setName(\"LoremIpsum\");\n this.videoUnit.setSource(\"oHg5SJYRHA0\");\n\n // Add users that are not in the course\n userRepository.save(ModelFactory.generateActivatedUser(\"student42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"tutor42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"instructor42\"));\n }\n\n private void testAllPreAuthorize() throws Exception {\n request.put(\"/api/lectures/\" + lecture1.getId() + \"/video-units\", videoUnit, HttpStatus.FORBIDDEN);\n request.post(\"/api/lectures/\" + lecture1.getId() + \"/video-units\", videoUnit, HttpStatus.FORBIDDEN);\n request.get(\"/api/lectures/\" + lecture1.getId() + \"/video-units/0\", HttpStatus.FORBIDDEN, VideoUnit.class);\n }\n\n @AfterEach\n public void resetDatabase() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testAll_asTutor() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testAll_asStudent() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createVideoUnit_asInstructor_shouldCreateVideoUnit() throws Exception {\n var persistedVideoUnit = request.postWithResponseBody(\"/api/lectures/\" + this.lecture1.getId() + \"/video-units\", videoUnit, VideoUnit.class, HttpStatus.CREATED);\n assertThat(persistedVideoUnit.getId()).isNotNull();\n }\n\n @Test\n @WithMockUser(username = \"instructor42\", roles = \"INSTRUCTOR\")\n public void createVideoUnit_InstructorNotInCourse_shouldReturnForbidden() throws Exception {\n request.postWithResponseBody(\"/api/lectures/\" + this.lecture1.getId() + \"/video-units\", videoUnit, VideoUnit.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateVideoUnit_asInstructor_shouldUpdateVideoUnit() throws Exception {\n this.videoUnit = videoUnitRepository.save(this.videoUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.videoUnit);\n lecture1 = lectureRepository.save(lecture1);\n\n this.videoUnit = (VideoUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n this.videoUnit.setDescription(\"Changed\");\n this.videoUnit = request.putWithResponseBody(\"/api/lectures/\" + lecture1.getId() + \"/video-units\", this.videoUnit, VideoUnit.class, HttpStatus.OK);\n assertThat(this.videoUnit.getDescription()).isEqualTo(\"Changed\");\n }\n\n @Test\n @WithMockUser(username = \"instructor42\", roles = \"INSTRUCTOR\")\n public void updateVideoUnit_InstructorNotInCourse_shouldReturnForbidden() throws Exception {\n this.videoUnit = videoUnitRepository.save(this.videoUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.videoUnit);\n lecture1 = lectureRepository.save(lecture1);\n\n this.videoUnit = (VideoUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n this.videoUnit.setDescription(\"Changed\");\n this.videoUnit = request.putWithResponseBody(\"/api/lectures/\" + lecture1.getId() + \"/video-units\", this.videoUnit, VideoUnit.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateVideoUnit_noId_shouldReturnBadRequest() throws Exception {\n this.videoUnit = videoUnitRepository.save(this.videoUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.videoUnit);\n lecture1 = lectureRepository.save(lecture1);\n this.videoUnit = (VideoUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n this.videoUnit.setId(null);\n this.videoUnit = request.putWithResponseBody(\"/api/lectures/\" + lecture1.getId() + \"/video-units\", this.videoUnit, VideoUnit.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getVideoUnit_correctId_shouldReturnVideoUnit() throws Exception {\n this.videoUnit = videoUnitRepository.save(this.videoUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.videoUnit);\n lecture1 = lectureRepository.save(lecture1);\n this.videoUnit = (VideoUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n VideoUnit videoUnitFromRequest = request.get(\"/api/lectures/\" + lecture1.getId() + \"/video-units/\" + this.videoUnit.getId(), HttpStatus.OK, VideoUnit.class);\n assertThat(this.videoUnit.getId()).isEqualTo(videoUnitFromRequest.getId());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteVideoUnit_correctId_shouldDeleteVideoUnit() throws Exception {\n this.videoUnit = videoUnitRepository.save(this.videoUnit);\n lecture1 = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n lecture1.addLectureUnit(this.videoUnit);\n lecture1 = lectureRepository.save(lecture1);\n this.videoUnit = (VideoUnit) lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get().getLectureUnits().stream().findFirst()\n .get();\n assertThat(this.videoUnit.getId()).isNotNull();\n request.delete(\"/api/lectures/\" + lecture1.getId() + \"/lecture-units/\" + this.videoUnit.getId(), HttpStatus.OK);\n request.get(\"/api/lectures/\" + lecture1.getId() + \"/video-units/\" + this.videoUnit.getId(), HttpStatus.NOT_FOUND, VideoUnit.class);\n }\n\n}\n" }, { "alpha_fraction": 0.6694779396057129, "alphanum_fraction": 0.6758232712745667, "avg_line_length": 49, "blob_id": "5852c9d7b1dcedf0221c5199778751e7e74d4e7d", "content_id": "d6b7e47de728a056ed9c9313ecdfd147b04bb8e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12450, "license_type": "permissive", "max_line_length": 167, "num_lines": 249, "path": "/src/test/javascript/spec/component/programming-assessment-dashboard/programming-assessment-dashboard.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule, TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ActivatedRoute, convertToParamMap, Router } from '@angular/router';\nimport { of } from 'rxjs';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { stub } from 'sinon';\nimport { ProgrammingAssessmentDashboardComponent } from 'app/exercises/programming/assess/programming-assessment-dashboard/programming-assessment-dashboard.component';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ProgrammingAssessmentManualResultService } from 'app/exercises/programming/assess/manual-result/programming-assessment-manual-result.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\n\nconst route = { params: of({ courseId: 3, exerciseId: 22 }) };\nconst programmingExercise1 = {\n id: 22,\n type: ExerciseType.PROGRAMMING,\n course: { id: 91 },\n numberOfAssessmentsOfCorrectionRounds: {},\n} as ProgrammingExercise;\nconst programmingExercise2 = {\n id: 22,\n type: ExerciseType.PROGRAMMING,\n exerciseGroup: { id: 94, exam: { id: 777, course: { id: 92 } } },\n numberOfAssessmentsOfCorrectionRounds: {},\n} as ProgrammingExercise;\n\nconst programmingSubmission1 = {\n id: 1,\n submitted: true,\n results: [{ id: 10, assessor: { id: 20, guidedTourSettings: [] } }],\n participation: { id: 41, exercise: programmingExercise1 },\n};\nconst programmingSubmission2 = {\n id: 2,\n submitted: true,\n results: [{ id: 20, assessor: { id: 30, guidedTourSettings: [] } }],\n participation: { id: 41, exercise: programmingExercise2 },\n};\n\ndescribe('FileUploadAssessmentDashboardComponent', () => {\n let component: ProgrammingAssessmentDashboardComponent;\n let fixture: ComponentFixture<ProgrammingAssessmentDashboardComponent>;\n let exerciseService: ExerciseService;\n let programmingSubmissionService: ProgrammingSubmissionService;\n let programmingAssessmentService: ProgrammingAssessmentManualResultService;\n let accountService: AccountService;\n let sortService: SortService;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule, TranslateModule.forRoot(), ArtemisTestModule],\n declarations: [ProgrammingAssessmentDashboardComponent],\n providers: [\n JhiLanguageHelper,\n { provide: Router, useClass: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: Router, useClass: MockRouter },\n { provide: AccountService, useClass: MockAccountService },\n {\n provide: ActivatedRoute,\n useValue: {\n snapshot: {\n paramMap: convertToParamMap({\n exerciseId: programmingExercise2.id,\n }),\n },\n },\n },\n ],\n })\n .overrideTemplate(ProgrammingAssessmentDashboardComponent, '')\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingAssessmentDashboardComponent);\n component = fixture.componentInstance;\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n programmingSubmissionService = fixture.debugElement.injector.get(ProgrammingSubmissionService);\n programmingAssessmentService = fixture.debugElement.injector.get(ProgrammingAssessmentManualResultService);\n accountService = fixture.debugElement.injector.get(AccountService);\n sortService = fixture.debugElement.injector.get(SortService);\n });\n }));\n\n it('should set parameters and call functions on init', fakeAsync(() => {\n // setup\n const exerciseServiceFind = stub(exerciseService, 'find');\n exerciseServiceFind.returns(of(new HttpResponse({ body: programmingExercise1 })));\n spyOn<any>(component, 'setPermissions');\n // test for init values\n expect(component).toBeTruthy();\n expect(component.submissions).toEqual([]);\n expect(component.reverse).toEqual(false);\n expect(component.predicate).toEqual('id');\n expect(component.filteredSubmissions).toEqual([]);\n\n // call\n component.ngOnInit();\n tick(500);\n\n // check\n expect(exerciseServiceFind).toHaveBeenCalledWith(programmingExercise2.id);\n expect(component['setPermissions']).toHaveBeenCalled();\n expect(component.exercise).toEqual(programmingExercise1 as ProgrammingExercise);\n }));\n\n it('should get Submissions', fakeAsync(() => {\n // test getSubmissions\n const exerciseServiceFind = stub(exerciseService, 'find');\n const getProgrammingSubmissionsForExerciseByCorrectionRoundStub = stub(programmingSubmissionService, 'getProgrammingSubmissionsForExerciseByCorrectionRound');\n const isAtLeastInstructorInCourseStub = stub(accountService, 'isAtLeastInstructorInCourse');\n exerciseServiceFind.returns(of(new HttpResponse({ body: programmingExercise1 })));\n getProgrammingSubmissionsForExerciseByCorrectionRoundStub.returns(of(new HttpResponse({ body: [programmingSubmission1] })));\n isAtLeastInstructorInCourseStub.returns(true);\n spyOn<any>(component, 'setPermissions');\n const getSubmissionSpy = spyOn<any>(component, 'getSubmissions');\n getSubmissionSpy.and.callThrough();\n // call\n component.ngOnInit();\n tick(500);\n // check\n expect(component['setPermissions']).toHaveBeenCalled();\n expect(component['getSubmissions']).toHaveBeenCalled();\n expect(getProgrammingSubmissionsForExerciseByCorrectionRoundStub).toHaveBeenCalled();\n expect(getProgrammingSubmissionsForExerciseByCorrectionRoundStub).toHaveBeenCalledWith(programmingExercise2.id, { submittedOnly: true });\n expect(exerciseServiceFind).toHaveBeenCalledWith(programmingExercise2.id);\n expect(component.submissions).toEqual([programmingSubmission1]);\n expect(component.filteredSubmissions).toEqual([programmingSubmission1]);\n }));\n\n it('should not get Submissions', fakeAsync(() => {\n const exerciseServiceFind = stub(exerciseService, 'find');\n const getProgrammingSubmissionsForExerciseByCorrectionRoundStub = stub(programmingSubmissionService, 'getProgrammingSubmissionsForExerciseByCorrectionRound');\n const isAtLeastInstructorInCourseStub = stub(accountService, 'isAtLeastInstructorInCourse');\n\n exerciseServiceFind.returns(of(new HttpResponse({ body: programmingExercise1 })));\n getProgrammingSubmissionsForExerciseByCorrectionRoundStub.returns(of(new HttpResponse({ body: [] })));\n isAtLeastInstructorInCourseStub.returns(true);\n // findExerciseStub.returns(of(new HttpResponse({ body: fileUploadExercise, headers: new HttpHeaders() })));\n exerciseServiceFind.returns(of(new HttpResponse({ body: programmingExercise2, headers: new HttpHeaders() })));\n const getSubmissionSpy = spyOn<any>(component, 'getSubmissions');\n getSubmissionSpy.and.callThrough();\n component.exercise = programmingExercise2;\n\n // call\n component.ngOnInit();\n\n tick(100);\n // check\n expect(component['getSubmissions']).toHaveBeenCalled();\n expect(exerciseServiceFind).toHaveBeenCalledWith(programmingExercise2.id);\n expect(component.submissions).toEqual([]);\n expect(component.filteredSubmissions).toEqual([]);\n }));\n\n it('should update filtered submissions', () => {\n // test updateFilteredSubmissions\n\n // setup\n component.ngOnInit();\n component.updateFilteredSubmissions([programmingSubmission1]);\n // check\n expect(component.filteredSubmissions).toEqual([programmingSubmission1]);\n });\n\n it('should cancelAssessment', fakeAsync(() => {\n // test cancelAssessment\n const windowSpy = spyOn(window, 'confirm').and.returnValue(true);\n const modelAssServiceCancelAssSpy = spyOn(programmingAssessmentService, 'cancelAssessment').and.returnValue(of(1));\n component.exercise = programmingExercise2;\n // call\n component.cancelAssessment(programmingSubmission2);\n tick();\n\n // check\n expect(modelAssServiceCancelAssSpy).toHaveBeenCalledWith(programmingSubmission2.id);\n expect(windowSpy).toHaveBeenCalled();\n }));\n\n it('should sortRows', () => {\n // test cancelAssessment\n const sortServiceSpy = spyOn(sortService, 'sortByProperty');\n component.predicate = 'predicate';\n component.reverse = false;\n component.submissions = [programmingSubmission2];\n component.sortRows();\n\n expect(sortServiceSpy).toHaveBeenCalledWith([programmingSubmission2], 'predicate', false);\n });\n\n it('should assessmentTypeTranslationKey', () => {\n const result = { id: 55, assessmentType: AssessmentType.SEMI_AUTOMATIC };\n expect(component.assessmentTypeTranslationKey(result)).toEqual(`artemisApp.AssessmentType.${result.assessmentType}`);\n expect(component.assessmentTypeTranslationKey(undefined)).toEqual(`artemisApp.AssessmentType.null`);\n });\n\n describe('shouldGetAssessmentLink', () => {\n it('should get assessment link for exam exercise', () => {\n const participationId = 8;\n component.exercise = programmingExercise1;\n component.exerciseId = programmingExercise1.id!;\n component.courseId = programmingExercise1.course!.id!;\n expect(component.getAssessmentLink(participationId)).toEqual([\n '/course-management',\n component.exercise.course!.id!.toString(),\n 'programming-exercises',\n component.exercise.id!.toString(),\n 'code-editor',\n participationId.toString(),\n 'assessment',\n ]);\n });\n\n it('should get assessment link for normal exercise', () => {\n const participationId = 9;\n component.exercise = programmingExercise2;\n component.exerciseId = programmingExercise2.id!;\n component.courseId = programmingExercise2.exerciseGroup!.exam!.course!.id!;\n component.examId = programmingExercise2.exerciseGroup!.exam!.id!;\n component.exerciseGroupId = programmingExercise2.exerciseGroup!.id!;\n expect(component.getAssessmentLink(participationId)).toEqual([\n '/course-management',\n component.exercise.exerciseGroup!.exam!.course!.id!.toString(),\n 'exams',\n component.exercise.exerciseGroup!.exam!.id!.toString(),\n 'exercise-groups',\n component.exercise.exerciseGroup!.id!.toString(),\n 'programming-exercises',\n component.exercise.id!.toString(),\n 'code-editor',\n participationId.toString(),\n 'assessment',\n ]);\n });\n });\n});\n" }, { "alpha_fraction": 0.653674840927124, "alphanum_fraction": 0.653674840927124, "avg_line_length": 34.91999816894531, "blob_id": "45eb811bb59715492993447a54df45aeba9f2af5", "content_id": "7d5989423482777ada4104d5e8b4358dbcf2efb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 898, "license_type": "permissive", "max_line_length": 101, "num_lines": 25, "path": "/src/main/webapp/app/admin/logs/logs.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Log } from 'app/admin/logs/log.model';\n\n@Injectable({ providedIn: 'root' })\nexport class LogsService {\n constructor(private http: HttpClient) {}\n\n /**\n * Sends a PUT request to change the log level for the given log\n * @param log for which the log level should be changed\n */\n changeLevel(log: Log): Observable<HttpResponse<void>> {\n return this.http.put<void>(SERVER_API_URL + 'management/logs', log, { observe: 'response' });\n }\n\n /**\n * Sends a GET request to retrieve all logs\n */\n findAll(): Observable<HttpResponse<Log[]>> {\n return this.http.get<Log[]>(SERVER_API_URL + 'management/logs', { observe: 'response' });\n }\n}\n" }, { "alpha_fraction": 0.692556619644165, "alphanum_fraction": 0.692556619644165, "avg_line_length": 27.090909957885742, "blob_id": "b754486ca99e5d049b67ddd0005b7958a1c1f1d7", "content_id": "cf2789a619f395dacce8a79d9cc4b336156c88ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 309, "license_type": "permissive", "max_line_length": 55, "num_lines": 11, "path": "/src/main/webapp/app/assessment/assessment-instructions/expandable-section/expandable-section.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\n\n@Component({\n selector: 'jhi-expandable-section',\n templateUrl: './expandable-section.component.html',\n})\nexport class ExpandableSectionComponent {\n @Input() headerKey: string;\n @Input() isCollapsed = false;\n @Input() hasTranslation = true;\n}\n" }, { "alpha_fraction": 0.6649275422096252, "alphanum_fraction": 0.6649275422096252, "avg_line_length": 36.5, "blob_id": "9edfc3a4c4605f54f6dfca61f1c6765f0793c523", "content_id": "d4d2a60de7b7f461b87b0f279a3825960da02511", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1725, "license_type": "permissive", "max_line_length": 148, "num_lines": 46, "path": "/src/main/webapp/app/exam/manage/students/students-exam-import-dialog/students-exam-import-button.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\nimport { ButtonSize, ButtonType } from 'app/shared/components/button.component';\nimport { StudentsExamImportDialogComponent } from 'app/exam/manage/students/students-exam-import-dialog/students-exam-import-dialog.component';\nimport { Exam } from 'app/entities/exam.model';\n\n@Component({\n selector: 'jhi-students-exam-import-button',\n template: `\n <jhi-button\n [btnType]=\"ButtonType.PRIMARY\"\n [btnSize]=\"buttonSize\"\n [icon]=\"'plus'\"\n [title]=\"'artemisApp.examManagement.examStudents.importStudents.buttonLabel'\"\n (onClick)=\"openStudentsExamImportDialog($event)\"\n ></jhi-button>\n `,\n})\nexport class StudentsExamImportButtonComponent {\n ButtonType = ButtonType;\n ButtonSize = ButtonSize;\n\n @Input() courseId: number;\n @Input() exam: Exam;\n @Input() buttonSize: ButtonSize = ButtonSize.SMALL;\n\n @Output() finish: EventEmitter<void> = new EventEmitter();\n\n constructor(private modalService: NgbModal) {}\n\n /**\n * Open up import dialog for students\n * @param {Event} event - Mouse Event which invoked the opening\n */\n openStudentsExamImportDialog(event: MouseEvent) {\n event.stopPropagation();\n const modalRef: NgbModalRef = this.modalService.open(StudentsExamImportDialogComponent, { keyboard: true, size: 'lg', backdrop: 'static' });\n modalRef.componentInstance.courseId = this.courseId;\n modalRef.componentInstance.exam = this.exam;\n\n modalRef.result.then(\n () => this.finish.emit(),\n () => {},\n );\n }\n}\n" }, { "alpha_fraction": 0.6072564721107483, "alphanum_fraction": 0.611352801322937, "avg_line_length": 54.04621887207031, "blob_id": "5ef6ce224c319ff89358ce7e71edd1891e9eb50f", "content_id": "2495f5e0422bc9b92986ff2b1577ec94695f1bfe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 39303, "license_type": "permissive", "max_line_length": 175, "num_lines": 714, "path": "/src/test/javascript/spec/service/guided-tour.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { Router } from '@angular/router';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { Observable, of } from 'rxjs';\nimport { CookieService } from 'ngx-cookie-service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisTestModule } from '../test.module';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { GuidedTour } from 'app/guided-tour/guided-tour.model';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { GuidedTourState, Orientation, ResetParticipation, UserInteractionEvent } from 'app/guided-tour/guided-tour.constants';\nimport { GuidedTourComponent } from 'app/guided-tour/guided-tour.component';\nimport { GuidedTourMapping, GuidedTourSetting } from 'app/guided-tour/guided-tour-setting.model';\nimport { AssessmentTaskTourStep, ModelingTaskTourStep, TextTourStep, UserInterActionTourStep } from 'app/guided-tour/guided-tour-step.model';\nimport { MockAccountService } from '../helpers/mocks/service/mock-account.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { Course } from 'app/entities/course.model';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { AssessmentObject, GuidedTourAssessmentTask, GuidedTourModelingTask, personUML } from 'app/guided-tour/guided-tour-task.model';\nimport { completedTour } from 'app/guided-tour/tours/general-tour';\nimport * as sinon from 'sinon';\nimport { SinonStub, stub } from 'sinon';\nimport { HttpResponse } from '@angular/common/http';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { NavbarComponent } from 'app/shared/layouts/navbar/navbar.component';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../helpers/mocks/service/mock-cookie.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { MockProvider } from 'ng-mocks';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('GuidedTourService', () => {\n const tour: GuidedTour = {\n settingsKey: 'tour',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' }),\n new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),\n ],\n };\n\n const tourWithUserInteraction: GuidedTour = {\n settingsKey: 'tour_user_interaction',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n new UserInterActionTourStep({\n highlightSelector: '.random-selector',\n headlineTranslateKey: '',\n contentTranslateKey: '',\n userInteractionEvent: UserInteractionEvent.CLICK,\n }),\n new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),\n ],\n };\n\n const tourWithCourseAndExercise: GuidedTour = {\n settingsKey: 'tour_with_course_and_exercise',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '' }),\n new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),\n ],\n };\n\n const tourWithModelingTask: GuidedTour = {\n settingsKey: 'tour_modeling_task',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n new ModelingTaskTourStep({\n headlineTranslateKey: '',\n contentTranslateKey: '',\n modelingTask: new GuidedTourModelingTask(personUML.name, ''),\n userInteractionEvent: UserInteractionEvent.MODELING,\n }),\n ],\n };\n\n describe('Service method', () => {\n let service: GuidedTourService;\n let httpMock: HttpTestingController;\n const expected = new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED);\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, HttpClientTestingModule],\n providers: [\n { provide: DeviceDetectorService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n MockProvider(TranslateService),\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents();\n\n service = TestBed.inject(GuidedTourService);\n httpMock = TestBed.inject(HttpTestingController);\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n\n it('should call the correct update URL and return the right JSON object', () => {\n service.guidedTourSettings = [];\n service['updateGuidedTourSettings']('guided_tour_key', 1, GuidedTourState.STARTED).subscribe();\n const req = httpMock.expectOne({ method: 'PUT' });\n const resourceUrl = SERVER_API_URL + 'api/guided-tour-settings';\n expect(req.request.url).equal(`${resourceUrl}`);\n expect(service.guidedTourSettings).to.eql([expected]);\n });\n\n it('should call the correct delete URL', () => {\n service.guidedTourSettings = [new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED)];\n service['deleteGuidedTourSetting']('guided_tour_key').subscribe();\n const req = httpMock.expectOne({ method: 'DELETE' });\n const resourceUrl = SERVER_API_URL + 'api/guided-tour-settings';\n expect(req.request.url).equal(`${resourceUrl}/guided_tour_key`);\n expect(service.guidedTourSettings).to.eql([]);\n });\n });\n\n describe('Guided tour methods', () => {\n let guidedTourComponent: GuidedTourComponent;\n let guidedTourComponentFixture: ComponentFixture<GuidedTourComponent>;\n let router: Router;\n let guidedTourService: GuidedTourService;\n let participationService: ParticipationService;\n let courseService: CourseManagementService;\n\n let findParticipationStub: SinonStub;\n let deleteParticipationStub: SinonStub;\n let deleteGuidedTourSettingStub: SinonStub;\n let navigationStub: SinonStub;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n ArtemisSharedModule,\n RouterTestingModule.withRoutes([\n {\n path: 'courses',\n component: NavbarComponent,\n },\n ]),\n ],\n declarations: [NavbarComponent, GuidedTourComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: DeviceDetectorService },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .overrideTemplate(NavbarComponent, '<div class=\"random-selector\"></div>')\n .compileComponents()\n .then(() => {\n guidedTourComponentFixture = TestBed.createComponent(GuidedTourComponent);\n guidedTourComponent = guidedTourComponentFixture.componentInstance;\n\n TestBed.createComponent(NavbarComponent);\n\n router = TestBed.inject(Router);\n guidedTourService = TestBed.inject(GuidedTourService);\n participationService = TestBed.inject(ParticipationService);\n courseService = TestBed.inject(CourseManagementService);\n\n findParticipationStub = stub(participationService, 'findParticipation');\n deleteParticipationStub = stub(participationService, 'deleteForGuidedTour');\n // @ts-ignore\n deleteGuidedTourSettingStub = stub(guidedTourService, 'deleteGuidedTourSetting');\n navigationStub = stub(router, 'navigateByUrl');\n });\n });\n\n function prepareGuidedTour(guidedTour: GuidedTour) {\n // Prepare GuidedTourService and GuidedTourComponent\n spyOn(guidedTourService, 'init').and.returnValue(of());\n spyOn(guidedTourService, 'getLastSeenTourStepIndex').and.returnValue(0);\n spyOn<any>(guidedTourService, 'checkSelectorValidity').and.returnValue(true);\n spyOn<any>(guidedTourService, 'checkTourState').and.returnValue(true);\n spyOn<any>(guidedTourService, 'updateGuidedTourSettings').and.returnValue(of());\n spyOn<any>(guidedTourService, 'enableTour').and.callFake(() => {\n guidedTourService['availableTourForComponent'] = guidedTour;\n guidedTourService.currentTour = guidedTour;\n });\n spyOn<any>(guidedTourComponent, 'subscribeToDotChanges').and.callFake(() => {});\n }\n\n async function startCourseOverviewTour(guidedTour: GuidedTour) {\n guidedTourComponent.ngAfterViewInit();\n\n await guidedTourComponentFixture.ngZone!.run(() => {\n router.navigateByUrl('/courses');\n });\n\n // Start course overview tour\n expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.not.exist;\n guidedTourService['enableTour'](guidedTour, true);\n guidedTourService['startTour']();\n guidedTourComponentFixture.detectChanges();\n expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.exist;\n expect(guidedTourService.isOnFirstStep).to.be.true;\n expect(guidedTourService.currentTourStepDisplay).to.equal(1);\n expect(guidedTourService.currentTourStepCount).to.equal(2);\n }\n\n describe('Tours without user interaction', () => {\n beforeEach(async () => {\n prepareGuidedTour(tour);\n await startCourseOverviewTour(tour);\n });\n\n it('should start and finish the course overview guided tour', async () => {\n // Navigate to next step\n const nextButton = guidedTourComponentFixture.debugElement.query(By.css('.next-button'));\n expect(nextButton).to.exist;\n nextButton.nativeElement.click();\n expect(guidedTourService.isOnLastStep).to.be.true;\n\n // Finish guided tour\n nextButton.nativeElement.click();\n guidedTourComponentFixture.detectChanges();\n expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.not.exist;\n });\n\n it('should start and skip the tour', () => {\n const skipButton = guidedTourComponentFixture.debugElement.query(By.css('.close'));\n expect(skipButton).to.exist;\n skipButton.nativeElement.click();\n guidedTourComponentFixture.detectChanges();\n expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.not.exist;\n });\n\n it('should prevent backdrop from advancing', () => {\n const backdrop = guidedTourComponentFixture.debugElement.queryAll(By.css('.guided-tour-overlay'));\n expect(backdrop).to.exist;\n expect(backdrop.length).to.equal(4);\n backdrop.forEach((overlay) => {\n overlay.nativeElement.click();\n });\n guidedTourComponentFixture.detectChanges();\n expect(guidedTourService.isOnFirstStep).to.be.true;\n });\n });\n\n describe('Tours with user interaction', () => {\n beforeEach(async () => {\n prepareGuidedTour(tourWithUserInteraction);\n await startCourseOverviewTour(tourWithUserInteraction);\n });\n\n it('should disable the next button', () => {\n guidedTourComponentFixture.detectChanges();\n const nextButton = guidedTourComponentFixture.debugElement.nativeElement.querySelector('.next-button').disabled;\n expect(nextButton).to.exist;\n });\n });\n\n describe('Tour for a certain course and exercise', () => {\n const guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: 'git' } } as GuidedTourMapping;\n const exercise1 = { id: 1, shortName: 'git', type: ExerciseType.PROGRAMMING } as Exercise;\n const exercise2 = { id: 2, shortName: 'test', type: ExerciseType.PROGRAMMING } as Exercise;\n const exercise3 = { id: 3, shortName: 'git', type: ExerciseType.MODELING } as Exercise;\n const course1 = { id: 1, shortName: 'tutorial', exercises: [exercise2, exercise1] } as Course;\n const course2 = { id: 2, shortName: 'test' } as Course;\n\n function resetCurrentTour(): void {\n guidedTourService['currentCourse'] = undefined;\n guidedTourService['currentExercise'] = undefined;\n guidedTourService.currentTour = completedTour;\n guidedTourService.resetTour();\n }\n\n function currentCourseAndExerciseNull(): void {\n expect(guidedTourService.currentTour).to.be.undefined;\n expect(guidedTourService['currentCourse']).to.be.undefined;\n expect(guidedTourService['currentExercise']).to.be.undefined;\n }\n\n beforeEach(async () => {\n guidedTourService.guidedTourMapping = guidedTourMapping;\n prepareGuidedTour(tourWithCourseAndExercise);\n resetCurrentTour();\n });\n\n it('should start the tour for the matching course title', () => {\n spyOn(courseService, 'findWithExercises').and.returnValue(of({ body: course1 } as HttpResponse<any>));\n const courses = [course1];\n\n // enable tour for matching course title\n guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.equal(tourWithCourseAndExercise);\n expect(guidedTourService['currentCourse']).to.equal(course1);\n expect(guidedTourService['currentExercise']).to.equal(exercise1);\n resetCurrentTour();\n\n guidedTourService.guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: '' } } as GuidedTourMapping;\n\n // enable tour for matching course title\n guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.equal(tourWithCourseAndExercise);\n expect(guidedTourService['currentCourse']).to.equal(course1);\n expect(guidedTourService['currentExercise']).to.be.undefined;\n resetCurrentTour();\n });\n\n it('should disable the tour for not matching course title', () => {\n const courses = [course2];\n // disable tour for not matching titles\n guidedTourService.enableTourForCourseOverview(courses, tourWithCourseAndExercise, true);\n currentCourseAndExerciseNull();\n });\n\n it('should start the tour for the matching exercise short name', () => {\n // disable tour for exercises without courses\n guidedTourService.currentTour = undefined;\n guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);\n currentCourseAndExerciseNull();\n resetCurrentTour();\n\n // disable tour for not matching course and exercise identifiers\n exercise2.course = course2;\n guidedTourService.enableTourForExercise(exercise2, tourWithCourseAndExercise, true);\n currentCourseAndExerciseNull();\n resetCurrentTour();\n\n // disable tour for not matching course identifier\n exercise3.course = course2;\n guidedTourService.enableTourForExercise(exercise3, tourWithCourseAndExercise, true);\n currentCourseAndExerciseNull();\n resetCurrentTour();\n\n // enable tour for matching course and exercise identifiers\n exercise1.course = course1;\n guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.equal(tourWithCourseAndExercise);\n expect(guidedTourService['currentCourse']).to.equal(course1);\n expect(guidedTourService['currentExercise']).to.equal(exercise1);\n });\n\n it('should start the tour for the matching course / exercise short name', () => {\n guidedTourService.currentTour = undefined;\n\n // enable tour for matching course / exercise short name\n guidedTourService.enableTourForCourseExerciseComponent(course1, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.equal(tourWithCourseAndExercise);\n\n course1.exercises!.forEach((exercise) => {\n exercise.course = course1;\n if (exercise === exercise1) {\n expect(guidedTourService['isGuidedTourAvailableForExercise'](exercise)).to.be.true;\n } else {\n expect(guidedTourService['isGuidedTourAvailableForExercise'](exercise)).to.be.false;\n }\n });\n\n // disable tour for not matching course without exercise\n guidedTourService.currentTour = undefined;\n guidedTourService.enableTourForCourseExerciseComponent(course2, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.be.undefined;\n\n // disable tour for not matching course but matching exercise identifier\n guidedTourService.currentTour = undefined;\n course2.exercises = [exercise3];\n guidedTourService.enableTourForCourseExerciseComponent(course2, tourWithCourseAndExercise, true);\n expect(guidedTourService.currentTour).to.be.undefined;\n });\n\n describe('Tour with student participation', () => {\n const studentParticipation1 = { id: 1, student: { id: 1 }, exercise: exercise1, initializationState: InitializationState.INITIALIZED } as StudentParticipation;\n const studentParticipation2 = { id: 2, student: { id: 1 }, exercise: exercise3, initializationState: InitializationState.INITIALIZED } as StudentParticipation;\n const httpResponse1 = { body: studentParticipation1 } as HttpResponse<StudentParticipation>;\n const httpResponse2 = { body: studentParticipation2 } as HttpResponse<StudentParticipation>;\n const exercise4 = { id: 4, title: 'git', type: ExerciseType.MODELING } as Exercise;\n\n function prepareParticipation(exercise: Exercise, studentParticipation: StudentParticipation, httpResponse: HttpResponse<StudentParticipation>) {\n exercise.course = course1;\n exercise.studentParticipations = [studentParticipation];\n findParticipationStub.reset();\n deleteParticipationStub.reset();\n deleteGuidedTourSettingStub.reset();\n navigationStub.reset();\n findParticipationStub.returns(Observable.of(httpResponse));\n deleteParticipationStub.returns(Observable.of(undefined));\n deleteGuidedTourSettingStub.returns(Observable.of(undefined));\n }\n\n it('should find and delete the student participation for exercise', () => {\n course1.exercises!.push(exercise4);\n\n prepareParticipation(exercise1, studentParticipation1, httpResponse1);\n guidedTourService.enableTourForExercise(exercise1, tourWithCourseAndExercise, true);\n guidedTourService.restartTour();\n expect(findParticipationStub).to.have.been.calledOnceWithExactly(1);\n expect(deleteParticipationStub).to.have.been.calledOnceWithExactly(1, { deleteBuildPlan: true, deleteRepository: true });\n expect(deleteGuidedTourSettingStub).to.have.been.calledOnceWith('tour_with_course_and_exercise');\n expect(navigationStub).to.have.been.calledOnceWith('/courses/1/exercises');\n\n prepareParticipation(exercise4, studentParticipation2, httpResponse2);\n guidedTourService.enableTourForExercise(exercise4, tourWithCourseAndExercise, true);\n guidedTourService.restartTour();\n expect(findParticipationStub).to.have.been.calledOnceWithExactly(4);\n expect(deleteParticipationStub).to.have.been.calledOnceWithExactly(2, { deleteBuildPlan: false, deleteRepository: false });\n expect(deleteGuidedTourSettingStub).to.have.been.calledOnceWith('tour_with_course_and_exercise');\n expect(navigationStub).to.have.been.calledOnceWith('/courses/1/exercises');\n\n const index = course1.exercises!.findIndex((exercise) => (exercise.id = exercise4.id));\n course1.exercises!.splice(index, 1);\n });\n });\n });\n\n describe('Modeling check', () => {\n it('should enable the next step if the results are correct', inject(\n [],\n fakeAsync(() => {\n const enableNextStep = spyOn<any>(guidedTourService, 'enableNextStepClick').and.returnValue(of());\n guidedTourService.currentTour = tourWithModelingTask;\n guidedTourService.updateModelingResult(personUML.name, true);\n tick(0);\n expect(enableNextStep.calls.count()).to.equal(1);\n }),\n ));\n });\n describe('init', () => {});\n describe('getGuidedTourAvailabilityStream', () => {});\n describe('checkModelingComponent', () => {});\n describe('updateModelingResult', () => {});\n describe('componentPageLoaded', () => {});\n\n describe('isCurrentStep', () => {\n const step1 = new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' });\n const step2 = new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT });\n const guidedTour: GuidedTour = {\n settingsKey: 'tour2',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [step1, step2],\n };\n it('should return true if it is the current Step', () => {\n guidedTourService.currentTour = guidedTour;\n expect(guidedTourService.isCurrentStep(step1)).to.be.true;\n guidedTourService.currentTourStepIndex += 1;\n expect(guidedTourService.isCurrentStep(step2)).to.be.true;\n });\n it('should return false if it is not the current Step', () => {\n guidedTourService.currentTour = guidedTour;\n expect(guidedTourService.isCurrentStep(step2)).to.be.false;\n guidedTourService.currentTourStepIndex += 1;\n expect(guidedTourService.isCurrentStep(step1)).to.be.false;\n });\n it('should return false if current Tour is undefined', () => {\n expect(guidedTourService.isCurrentStep(step1)).to.be.false;\n });\n });\n\n describe('isCurrentTour', () => {\n it('should return true if it is the current Tour', () => {\n guidedTourService.currentTour = tour;\n expect(guidedTourService.isCurrentTour(tour)).to.be.true;\n });\n it('should return false if it is not the current Tour', () => {\n expect(guidedTourService.isCurrentTour(tour)).to.be.false;\n });\n it('should return false if the current Tour is undefined', () => {\n guidedTourService.currentTour = tourWithCourseAndExercise;\n expect(guidedTourService.isCurrentTour(tour)).to.be.false;\n });\n });\n\n describe('getCurrentStepString', () => {\n it('should return nothing if currentTour is undefined', () => {\n expect(guidedTourService.getCurrentStepString()).to.be.undefined;\n });\n it('should return correct string if currentTour is defined', () => {\n guidedTourService.currentTour = tour;\n expect(guidedTourService.getCurrentStepString()).to.equal('1 / 2');\n });\n });\n\n describe('backStep, nextStep', () => {\n let currentDotSubjectSpy: any;\n let resetSpy: any;\n\n beforeEach(() => {\n currentDotSubjectSpy = spyOn<any>(guidedTourService.currentDotSubject, 'next');\n resetSpy = spyOn<any>(guidedTourService, 'resetTour');\n });\n afterEach(() => {\n jest.clearAllMocks();\n });\n it('backStep should just return if currentTour is not defined', () => {\n guidedTourService.backStep();\n expect(currentDotSubjectSpy.calls.count()).to.equal(0);\n expect(resetSpy.calls.count()).to.equal(0);\n });\n it('backStep should reset tour if currentTour is defined', () => {\n guidedTourService.currentTour = tour;\n guidedTourService.backStep();\n expect(currentDotSubjectSpy.calls.count()).to.equal(1);\n expect(resetSpy.calls.count()).to.equal(1);\n });\n it('nextStep should just return if currentTour is not defined', () => {\n guidedTourService.nextStep();\n expect(currentDotSubjectSpy.calls.count()).to.equal(0);\n expect(resetSpy.calls.count()).to.equal(0);\n });\n it('nextStep should reset return if currentTour is defined', () => {\n guidedTourService.currentTour = tour;\n guidedTourService.nextStep();\n expect(currentDotSubjectSpy.calls.count()).to.equal(1);\n });\n });\n describe('finishGuidedTour', () => {\n it('should just return if currentTour is not defined', () => {\n guidedTourService.finishGuidedTour();\n });\n });\n describe('skipTour', () => {\n it('should just return if currentTour is not defined', () => {\n guidedTourService.skipTour();\n });\n });\n describe('subscribeToAndUpdateGuidedTourSettings', () => {});\n describe('getLastSeenTourStepIndex', () => {});\n describe('resetTour', () => {});\n\n describe('enableUserInteraction', () => {\n const addEventListener = jest.fn();\n const htmlTarget = { addEventListener } as any;\n let observeMutationsStub: SinonStub;\n let handleWaitForSelectorEventSpy: any;\n let querySelectorSpy: any;\n\n beforeEach(() => {\n guidedTourService.currentTour = tour;\n observeMutationsStub = stub(guidedTourService, 'observeMutations');\n handleWaitForSelectorEventSpy = spyOn<any>(guidedTourService, 'handleWaitForSelectorEvent');\n querySelectorSpy = spyOn<any>(document, 'querySelector');\n });\n afterEach(() => {\n jest.clearAllMocks();\n sinon.restore();\n });\n it('should enableUserInteraction with UserInteractionEvent.WAIT_FOR_SELECTOR', fakeAsync(() => {\n const userinteractionEvent = UserInteractionEvent.WAIT_FOR_SELECTOR;\n guidedTourService.enableUserInteraction({} as any, userinteractionEvent);\n expect(handleWaitForSelectorEventSpy.calls.count()).to.equal(1);\n expect(querySelectorSpy.calls.count()).to.equal(0);\n }));\n it('should enableUserInteraction with UserInteractionEvent.CLICK', fakeAsync(() => {\n const userinteractionEvent = UserInteractionEvent.CLICK;\n guidedTourService.enableUserInteraction(htmlTarget, userinteractionEvent);\n expect(querySelectorSpy.calls.count()).to.equal(0);\n }));\n it('should enableUserInteraction with UserInteractionEvent.ACE_EDITOR', fakeAsync(() => {\n const userinteractionEvent = UserInteractionEvent.ACE_EDITOR;\n observeMutationsStub.returns(of({ addedNodes: { length: 0 } as NodeList, removedNodes: { length: 0 } as NodeList } as MutationRecord));\n guidedTourService.enableUserInteraction(htmlTarget, userinteractionEvent);\n expect(querySelectorSpy.calls.count()).to.equal(1);\n }));\n it('should enableUserInteraction with UserInteractionEvent.MODELING', fakeAsync(() => {\n const userinteractionEvent = UserInteractionEvent.MODELING;\n observeMutationsStub.returns(of({ addedNodes: { length: 0 } as NodeList, removedNodes: { length: 0 } as NodeList } as MutationRecord));\n guidedTourService.enableUserInteraction(htmlTarget, userinteractionEvent);\n expect(querySelectorSpy.calls.count()).to.equal(1);\n }));\n it('should enableUserInteraction with UserInteractionEvent.ASSESS_SUBMISSION', fakeAsync(() => {\n const isAssessmentCorrectSpy = spyOn<any>(guidedTourService, 'isAssessmentCorrect');\n const userinteractionEvent = UserInteractionEvent.ASSESS_SUBMISSION;\n guidedTourService.enableUserInteraction(htmlTarget, userinteractionEvent);\n expect(isAssessmentCorrectSpy.calls.count()).to.equal(1);\n expect(querySelectorSpy.calls.count()).to.equal(0);\n }));\n });\n\n describe('observeMutations', () => {});\n describe('initGuidedTour', () => {});\n describe('restartTour', () => {});\n describe('preventBackdropFromAdvancing', () => {});\n describe('enableTourForCourseExerciseComponent', () => {});\n describe('enableTourForCourseOverview', () => {});\n\n describe('enableTourForExercise', () => {\n const exerciseText = { id: 456, course: { id: 123 } as Course, type: ExerciseType.TEXT } as Exercise;\n const exerciseProgramming = { id: 456, course: { id: 123 } as Course, type: ExerciseType.PROGRAMMING } as Exercise;\n const guidedTourMapping = { courseShortName: 'tutorial', tours: { tour_with_course_and_exercise: 'git' } } as GuidedTourMapping;\n let enableTourSpy: any;\n let startTourSpy: any;\n let checkTourStateSpy: any;\n\n const guidedTourSettings = [new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED)];\n\n beforeEach(() => {\n enableTourSpy = spyOn<any>(guidedTourService, 'enableTour').and.returnValue(of());\n startTourSpy = spyOn<any>(guidedTourService, 'startTour').and.returnValue(of());\n checkTourStateSpy = spyOn<any>(guidedTourService, 'checkTourState').and.returnValue(of());\n guidedTourService.guidedTourMapping = guidedTourMapping;\n guidedTourService.guidedTourSettings = [];\n });\n afterEach(() => {\n jest.clearAllMocks();\n });\n describe('return undefined if parameters are undefined', () => {\n it('should return undefined if exercise.course is undefibed', fakeAsync(() => {\n const inputExercise = {} as Exercise;\n expect(guidedTourService.enableTourForExercise(inputExercise, tour, true)).to.be.undefined;\n expect(enableTourSpy.calls.count()).to.equal(0);\n }));\n it('should return undefined if guidedTour mapping is undefined', fakeAsync(() => {\n guidedTourService.guidedTourMapping = undefined;\n expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).to.be.undefined;\n }));\n });\n it('should enableTourForExercise for text exercise', fakeAsync(() => {\n expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).to.be.equal(exerciseText);\n expect(enableTourSpy.calls.count()).to.equal(1);\n expect(startTourSpy.calls.count()).to.equal(0);\n }));\n it('should enableTourForExercise for text exercise', fakeAsync(() => {\n expect(guidedTourService.enableTourForExercise(exerciseText, tour, true)).to.be.equal(exerciseText);\n expect(enableTourSpy.calls.count()).to.equal(1);\n expect(startTourSpy.calls.count()).to.equal(0);\n }));\n it('should enableTourForExercise for programming exercise', fakeAsync(() => {\n expect(guidedTourService.enableTourForExercise(exerciseProgramming, tour, true)).to.be.equal(exerciseProgramming);\n expect(enableTourSpy.calls.count()).to.equal(1);\n expect(startTourSpy.calls.count()).to.equal(0);\n }));\n it('should enableTourForExercise for text exercise with init set to false', fakeAsync(() => {\n guidedTourService.guidedTourSettings = guidedTourSettings;\n expect(guidedTourService.enableTourForExercise(exerciseText, tour, false)).to.be.equal(exerciseText);\n expect(enableTourSpy.calls.count()).to.equal(1);\n expect(startTourSpy.calls.count()).to.equal(0);\n }));\n });\n\n describe('updateAssessmentResult', () => {\n let tourWithAssessmentTourSteps: GuidedTour;\n let tourWithAssessmentTourStep: GuidedTour;\n let enableNextStepSpy: any;\n\n beforeEach(() => {\n const assessmentObject = new AssessmentObject(2, 3);\n const assessmentObjectScoreZero = new AssessmentObject(2, 0);\n const assessmentTask = new GuidedTourAssessmentTask('t', assessmentObject);\n tourWithAssessmentTourSteps = {\n settingsKey: 'tour',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n { assessmentTask } as AssessmentTaskTourStep,\n new TextTourStep({ highlightSelector: '.random-selector', headlineTranslateKey: '', contentTranslateKey: '' }),\n new TextTourStep({ headlineTranslateKey: '', contentTranslateKey: '', orientation: Orientation.TOPLEFT }),\n ],\n };\n tourWithAssessmentTourStep = {\n settingsKey: 'tour',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [{ assessmentTask: new GuidedTourAssessmentTask('t', assessmentObjectScoreZero) } as AssessmentTaskTourStep],\n };\n enableNextStepSpy = spyOn<any>(guidedTourService, 'enableNextStepClick').and.returnValue(of());\n });\n afterEach(() => {\n jest.clearAllMocks();\n });\n it('should updateAssessmentResult and enableNextStepClick', fakeAsync(() => {\n guidedTourService.currentTour = tourWithAssessmentTourSteps;\n guidedTourService.updateAssessmentResult(2, 3);\n tick(0);\n expect(enableNextStepSpy.calls.count()).to.equal(1);\n }));\n it('should updateAssessmentResult and not enableNextStepClick as number of assessments is not correct', fakeAsync(() => {\n guidedTourService.currentTour = tourWithAssessmentTourSteps;\n guidedTourService.updateAssessmentResult(3, 3);\n tick(0);\n expect(enableNextStepSpy.calls.count()).to.equal(0);\n }));\n it('should updateAssessmentResult and not enableNextStepClick as score not correct', fakeAsync(() => {\n guidedTourService.currentTour = tourWithAssessmentTourSteps;\n guidedTourService.updateAssessmentResult(2, 1);\n tick(0);\n expect(enableNextStepSpy.calls.count()).to.equal(0);\n }));\n it('should not updateAssessmentResult as there is no assessmentTask', fakeAsync(() => {\n guidedTourService.currentTour = tour;\n guidedTourService.updateAssessmentResult(2, 1);\n tick(0);\n expect(enableNextStepSpy.calls.count()).to.equal(0);\n }));\n it('should not updateAssessmentResult as the totalScore is 0', fakeAsync(() => {\n guidedTourService.currentTour = tourWithAssessmentTourStep;\n guidedTourService.updateAssessmentResult(2, 0);\n tick(0);\n expect(enableNextStepSpy.calls.count()).to.equal(1);\n }));\n });\n });\n});\n" }, { "alpha_fraction": 0.7163375020027161, "alphanum_fraction": 0.7199282050132751, "avg_line_length": 41.846153259277344, "blob_id": "601f3c55696e22b3bbbf3a1575727c8a893d1fd2", "content_id": "92b4b7b0eb0348ceb16799a79a6d6d8af8c6c116", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 557, "license_type": "permissive", "max_line_length": 134, "num_lines": 13, "path": "/docs/dev/use-local-user-management.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Using local user management\n===========================\n\nIf you want to test in a local environment using different users, it makes sense to rely on local instead of external user management.\n\n1. Go to the `application-artemis.yml` file, and set `use-external` in the `user-management` section to `false`.\n2. Remove the `jira` profile from your local Run Configuration for the Server.\n\n.. figure:: use-local-user-management/RemoveJira.png\n :align: center\n :alt: Removing the jira profile\n\n Remove the `jira` profile from the list shown in IntelliJ\n" }, { "alpha_fraction": 0.6562372446060181, "alphanum_fraction": 0.6588219404220581, "avg_line_length": 41.005714416503906, "blob_id": "6a5de9a76de9615cb945d412711d56f89fcf1416", "content_id": "bcc51cdb792e3ac01d24460735b60698e40c5dcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7351, "license_type": "permissive", "max_line_length": 158, "num_lines": 175, "path": "/src/test/javascript/spec/component/modeling-editor/modeling-editor.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Course } from 'app/entities/course.model';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute, convertToParamMap, Router } from '@angular/router';\nimport { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { of } from 'rxjs';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ApollonDiagram } from 'app/entities/apollon-diagram.model';\nimport { UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { MockRouter } from '../../helpers/mocks/service/mock-route.service';\nimport { UMLModel } from '@ls1intum/apollon';\nimport { Text } from '@ls1intum/apollon/lib/utils/svg/text';\nimport { ModelingEditorComponent } from 'app/exercises/modeling/shared/modeling-editor.component';\nimport * as testClassDiagram from '../../util/modeling/test-models/class-diagram.json';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { ArtemisModelingEditorModule } from 'app/exercises/modeling/shared/modeling-editor.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ArtemisTestModule } from '../../test.module';\nimport { cloneDeep } from 'lodash';\nimport { SimpleChange } from '@angular/core';\n\n// has to be overridden, because jsdom does not provide a getBBox() function for SVGTextElements\nText.size = () => {\n return { width: 0, height: 0 };\n};\n\ndescribe('ModelingEditorComponent Component', () => {\n let fixture: ComponentFixture<ModelingEditorComponent>;\n const sandbox = sinon.createSandbox();\n const course: Course = { id: 123 } as Course;\n const diagram: ApollonDiagram = new ApollonDiagram(UMLDiagramType.ClassDiagram, course.id!);\n\n beforeEach(() => {\n const route = ({ params: of({ id: 1, courseId: 123 }), snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute;\n diagram.id = 1;\n diagram.jsonRepresentation = JSON.stringify(testClassDiagram);\n\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule, ArtemisTestModule, ArtemisSharedModule, ArtemisModelingEditorModule],\n declarations: [],\n providers: [\n JhiAlertService,\n JhiLanguageHelper,\n GuidedTourService,\n { provide: NgbModal, useClass: MockNgbModalService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: route },\n { provide: Router, useValue: MockRouter },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ModelingEditorComponent);\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('ngAfterViewInit', () => {\n // @ts-ignore\n fixture.componentInstance.umlModel = testClassDiagram as UMLModel;\n fixture.detectChanges();\n\n // test\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n });\n\n it('ngOnDestroy', () => {\n // @ts-ignore\n fixture.componentInstance.umlModel = testClassDiagram as UMLModel;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n // test\n fixture.componentInstance.ngOnDestroy();\n expect(fixture.componentInstance['apollonEditor']).toBeFalsy();\n });\n\n it('ngOnChanges', () => {\n // @ts-ignore\n const model = testClassDiagram as UMLModel;\n fixture.componentInstance.umlModel = model;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n const changedModel = cloneDeep(model);\n changedModel.elements = [];\n changedModel.relationships = [];\n changedModel.interactive = { elements: [], relationships: [] };\n changedModel.size = { height: 0, width: 0 };\n\n // test\n fixture.componentInstance.ngOnChanges({\n umlModel: {\n currentValue: changedModel,\n previousValue: model,\n } as SimpleChange,\n });\n\n expect(fixture.componentInstance['apollonEditor']!.model).toEqual(changedModel);\n });\n\n it('isFullScreen false', () => {\n // test\n const fullScreen = fixture.componentInstance.isFullScreen;\n expect(fullScreen).toBeFalsy();\n });\n\n it('getCurrentModel', () => {\n // @ts-ignore\n fixture.componentInstance.umlModel = testClassDiagram as UMLModel;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n // test\n // const model = fixture.componentInstance.getCurrentModel();\n // TODO: uncomment after deserialization bugfix in Apollon library, see https://github.com/ls1intum/Apollon/issues/146\n // expect(model).toEqual(testClassDiagram);\n });\n\n it('elementWithClass', () => {\n // @ts-ignore\n const model = testClassDiagram as UMLModel;\n fixture.componentInstance.umlModel = model;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n // test\n const umlElement = fixture.componentInstance.elementWithClass('Sibling 2', model);\n expect(umlElement).toBeTruthy();\n });\n\n it('elementWithAttribute', () => {\n // @ts-ignore\n const model = testClassDiagram as UMLModel;\n fixture.componentInstance.umlModel = model;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n // test\n const umlElement = fixture.componentInstance.elementWithAttribute('attribute', model);\n expect(umlElement).toBeTruthy();\n });\n\n it('elementWithMethod', () => {\n // @ts-ignore\n const model = testClassDiagram as UMLModel;\n fixture.componentInstance.umlModel = model;\n fixture.detectChanges();\n fixture.componentInstance.ngAfterViewInit();\n expect(fixture.componentInstance['apollonEditor']).toBeTruthy();\n\n // test\n const umlElement = fixture.componentInstance.elementWithMethod('method', model);\n expect(umlElement).toBeTruthy();\n });\n});\n" }, { "alpha_fraction": 0.7058823704719543, "alphanum_fraction": 0.7094117403030396, "avg_line_length": 33.4594612121582, "blob_id": "43a1fa62c929acb6fa609ada37f8eeb4cead49db", "content_id": "ff9dfdfdeceae89e1a52a411e4a2092d7db5ea01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 2550, "license_type": "permissive", "max_line_length": 154, "num_lines": 74, "path": "/docs/user/exercises/file-upload.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "File Upload Exercise\n====================\n\n.. contents:: Content of this document\n :local:\n :depth: 2\n\n\nOverview\n--------\n\nConducting a file upload exercise consists of 3 steps:\n\n1. **Instructor prepares exercise:** Creates and configures the exercise in Artemis.\n2. **Student solves exercise:** Creates a submission file, and uploads it.\n3. **Instructor assesses submissions:** Review the handed in files and create manual results for the students.\n\nSetup\n--------\n\nThe following sections describe the supported features and the process of creating a new file upload exercise.\n\n- Open |course-management|\n- Navigate into **Exercises** of your preferred course\n\n .. figure:: programming/course-management-course-dashboard.png\n :align: center\n\n- Click on **Create new file upload exercise**\n\n .. figure:: file-upload/create-new-file-upload-exercise.png\n :align: center\n\n- Fill out all mandatory values and click on |save|\n- The exercise specific ``File Pattern`` defines which file types students can upload as solution.\n\n .. figure:: file-upload/file_upload_exercise_creation.png\n :align: center\n\n Result: **File Upload Exercise**\n\n .. figure:: file-upload/course-dashboard-exercise-file-upload.png\n :align: center\n\n- Click the |edit| button of the file upload exercise and adapt the interactive problem statement. There you can also set release and due dates.\n- You can get an overview of the exercise by clicking on the title.\n\nStudent Submission\n------------------\n\n- When the exercise is released the students can upload the requested file.\n- They can choose a file with |browse| and then submit the file with |submit|.\n\n .. figure:: file-upload/file_upload_exercise_student_view.png\n :align: center\n\n- After a file was uploaded it can then be downloaded again with the link below.\n\n .. figure:: file-upload/file_upload_exercise_student_submitted.png\n :align: center\n\nAssessment\n----------\n\n- When the due date is over you can assess the submissions. From the assessment dashboard go to exercise assessment dashboard of the file upload exercise.\n- There you can assess the submitted student submissions, by first downloading the file, and then creating feedback with points.\n\n.. |edit| image:: programming/edit.png\n.. |course-management| image:: programming/course-management.png\n.. |save| image:: file-upload/save_button.png\n.. |submit| image:: file-upload/submit.png\n :scale: 50\n.. |browse| image:: file-upload/browse.png\n :scale: 50\n" }, { "alpha_fraction": 0.6566501259803772, "alphanum_fraction": 0.6566501259803772, "avg_line_length": 32.86725616455078, "blob_id": "06b49baa81024b1fa04b070c3def662fd9deb4d3", "content_id": "e894968ff6120b1219f889842f92c1f63a5587bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3827, "license_type": "permissive", "max_line_length": 130, "num_lines": 113, "path": "/src/main/webapp/app/overview/student-questions/student-question/student-question.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { User } from 'app/core/user/user.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { StudentQuestionService } from 'app/overview/student-questions/student-question/student-question.service';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { StudentVotesAction, StudentVotesActionName } from 'app/overview/student-questions/student-votes/student-votes.component';\n\nexport interface StudentQuestionAction {\n name: QuestionActionName;\n studentQuestion: StudentQuestion;\n}\n\nexport enum QuestionActionName {\n DELETE,\n EXPAND,\n VOTE_CHANGE,\n}\n\n@Component({\n selector: 'jhi-student-question',\n templateUrl: './student-question.component.html',\n styleUrls: ['./../student-questions.scss'],\n})\nexport class StudentQuestionComponent implements OnInit {\n @Input() studentQuestion: StudentQuestion;\n @Input() user: User;\n @Input() isAtLeastTutorInCourse: boolean;\n @Output() interactQuestion = new EventEmitter<StudentQuestionAction>();\n editText?: string;\n isEditMode: boolean;\n EditorMode = EditorMode;\n courseId: number;\n\n // Only allow certain html tags and no attributes\n allowedHtmlTags: string[] = ['a', 'b', 'strong', 'i', 'em', 'mark', 'small', 'del', 'ins', 'sub', 'sup', 'p'];\n allowedHtmlAttributes: string[] = ['href'];\n\n constructor(private studentQuestionService: StudentQuestionService, private route: ActivatedRoute) {}\n\n /**\n * checks if the user is the author of the question\n * sets the question text as the editor text\n */\n ngOnInit(): void {\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n this.editText = this.studentQuestion.questionText;\n }\n\n /**\n * pass the studentQuestion to the row to delete\n */\n deleteQuestion(): void {\n this.interactQuestion.emit({\n name: QuestionActionName.DELETE,\n studentQuestion: this.studentQuestion,\n });\n }\n\n /**\n * Changes the question text\n */\n saveQuestion(): void {\n this.studentQuestion.questionText = this.editText;\n this.studentQuestionService.update(this.courseId, this.studentQuestion).subscribe(() => {\n this.isEditMode = false;\n });\n }\n\n /**\n * toggles the edit Mode\n * set the editor text to the question text\n */\n toggleEditMode(): void {\n this.isEditMode = !this.isEditMode;\n this.editText = this.studentQuestion.questionText;\n }\n\n /**\n * interact with actions sent from studentVotes\n * @param {StudentVotesAction} action\n */\n interactVotes(action: StudentVotesAction): void {\n switch (action.name) {\n case StudentVotesActionName.VOTE_CHANGE:\n this.updateVotes(action.value);\n break;\n }\n }\n\n /**\n * update the number of votes for this studentQuestion\n * @param {number} voteChange\n */\n updateVotes(voteChange: number): void {\n this.studentQuestionService.updateVotes(this.courseId, this.studentQuestion.id!, voteChange).subscribe((res) => {\n this.studentQuestion = res.body!;\n this.interactQuestion.emit({\n name: QuestionActionName.VOTE_CHANGE,\n studentQuestion: this.studentQuestion,\n });\n });\n }\n\n /**\n * Takes a studentQuestion and determines if the user is the author of it\n * @param {StudentQuestion} studentQuestion\n * @returns {boolean}\n */\n isAuthorOfQuestion(studentQuestion: StudentQuestion): boolean {\n return this.user ? studentQuestion.author!.id === this.user.id : false;\n }\n}\n" }, { "alpha_fraction": 0.5853484869003296, "alphanum_fraction": 0.587482213973999, "avg_line_length": 31.697673797607422, "blob_id": "01be06f19f849043305ddaa54f2ee0de1bf4d6b7", "content_id": "9ad335d0991eddb8371d78513db482f14ad7df40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1406, "license_type": "permissive", "max_line_length": 125, "num_lines": 43, "path": "/src/main/webapp/app/shared/table/table-editable-field.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, ElementRef, Input, ViewChild } from '@angular/core';\n\n/**\n * An inline editing field to use for tables.\n */\n@Component({\n selector: 'jhi-table-editable-field',\n styles: ['.table-editable-field {display: flex; align-items: center}', '.table-editable-field__input {flex: 2 1 auto;}'],\n template: `\n <div class=\"table-editable-field\">\n <input\n #editingInput\n [id]=\"id\"\n class=\"table-editable-field__input form-control mr-2\"\n (blur)=\"sendValueUpdate($event)\"\n (keyup.enter)=\"sendValueUpdate($event)\"\n [value]=\"inputValue\"\n (input)=\"inputValue = $event.target.value\"\n type=\"text\"\n />\n </div>\n `,\n})\nexport class TableEditableFieldComponent {\n @ViewChild('editingInput', { static: false }) editingInput: ElementRef;\n\n @Input() id: string;\n @Input() set value(value: any) {\n this.inputValue = value;\n }\n @Input() onValueUpdate: (value: any) => any;\n\n inputValue: any;\n\n /**\n * Triggers a value update signal and delegates the task to method specified in the Output decorator,\n * sending in also the updated value of the object.\n * @param event The event that occurred.\n */\n sendValueUpdate(event: any) {\n this.inputValue = this.onValueUpdate(event.target.value);\n }\n}\n" }, { "alpha_fraction": 0.7251808047294617, "alphanum_fraction": 0.7317554354667664, "avg_line_length": 62.375, "blob_id": "a1d555a45506cab5805e0382a5f401dda3790a1c", "content_id": "abff7b33979fb29ec0d1b087941c902a91662ef2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1521, "license_type": "permissive", "max_line_length": 153, "num_lines": 24, "path": "/src/main/webapp/app/shared/date-time-picker/date-time-picker.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { CommonModule } from '@angular/common';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { NgModule } from '@angular/core';\nimport { OWL_DATE_TIME_FORMATS, OwlDateTimeModule, OwlNativeDateTimeModule } from 'ng-pick-datetime';\nimport { FormDateTimePickerComponent } from './date-time-picker.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\n// It would be nice to use the moment adapter for ng-pick-datetime: https://danielykpan.github.io/date-time-picker/\n// However atm there is a compiler issue in angular 7 that conflicts with the compilation of this module: https://github.com/angular/angular/issues/23609\nexport const MY_NATIVE_FORMATS = {\n fullPickerInput: { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' },\n datePickerInput: { year: 'numeric', month: 'numeric', day: 'numeric' },\n timePickerInput: { hour: 'numeric', minute: 'numeric' },\n monthYearLabel: { year: 'numeric', month: 'short' },\n dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric' },\n monthYearA11yLabel: { year: 'numeric', month: 'long' },\n};\n@NgModule({\n imports: [CommonModule, FormsModule, OwlDateTimeModule, OwlNativeDateTimeModule, ReactiveFormsModule, ArtemisSharedModule],\n exports: [FormDateTimePickerComponent],\n declarations: [FormDateTimePickerComponent],\n providers: [{ provide: OWL_DATE_TIME_FORMATS, useValue: MY_NATIVE_FORMATS }],\n})\nexport class FormDateTimePickerModule {}\n" }, { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 23.75, "blob_id": "08a18bc5bbe19cb40b0f146e6d8ae381b0a59d22", "content_id": "afc233bec4fd3972ed2a0c0ee3f30af7cb700d14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 99, "license_type": "permissive", "max_line_length": 36, "num_lines": 4, "path": "/src/main/webapp/app/home/saml2-login/saml2.config.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class Saml2Config {\n public buttonLabel?: string;\n public enablePassword?: boolean;\n}\n" }, { "alpha_fraction": 0.6674364805221558, "alphanum_fraction": 0.6685912013053894, "avg_line_length": 23.05555534362793, "blob_id": "7f154a5e28dd4431d67a59ee6aba7ddf82048de7", "content_id": "69311081a707e4142be7a5772cc60ba0b27e17bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 866, "license_type": "permissive", "max_line_length": 154, "num_lines": 36, "path": "/src/main/java/de/tum/in/www1/artemis/service/compass/assessment/Score.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.compass.assessment;\n\nimport java.io.Serializable;\nimport java.util.List;\n\npublic class Score implements Serializable {\n\n private double points;\n\n private double confidence;\n\n private List<String> comments;\n\n public Score(double points, List<String> comments, double confidence) {\n this.points = points;\n this.comments = comments;\n this.confidence = confidence;\n }\n\n public double getPoints() {\n return points;\n }\n\n public List<String> getComments() {\n return comments;\n }\n\n /**\n * Returns the confidence of the score. The confidence is the percentage indicating how certain Compass is about the points and comments of the Score.\n *\n * @return the confidence of the score\n */\n public double getConfidence() {\n return confidence;\n }\n}\n" }, { "alpha_fraction": 0.5897250175476074, "alphanum_fraction": 0.6067293882369995, "avg_line_length": 32.70731735229492, "blob_id": "e77c9cdaae39184b31617eba6222cc5cded15475", "content_id": "6dc7355461e95f70a1106254efb6cc3ce4cdcfb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2764, "license_type": "permissive", "max_line_length": 138, "num_lines": 82, "path": "/src/main/webapp/app/exercises/shared/plagiarism/plagiarism-run-details/plagiarism-run-details.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges, SimpleChanges, ViewChild } from '@angular/core';\nimport { ChartDataSets, ChartOptions, ChartType } from 'chart.js';\nimport { BaseChartDirective, Label } from 'ng2-charts';\nimport { TextPlagiarismResult } from 'app/exercises/shared/plagiarism/types/text/TextPlagiarismResult';\nimport { ModelingPlagiarismResult } from 'app/exercises/shared/plagiarism/types/modeling/ModelingPlagiarismResult';\n\n@Component({\n selector: 'jhi-plagiarism-run-details',\n styleUrls: ['./plagiarism-run-details.component.scss'],\n templateUrl: './plagiarism-run-details.component.html',\n})\nexport class PlagiarismRunDetailsComponent implements OnChanges {\n /**\n * Result of the automated plagiarism detection\n */\n @Input() plagiarismResult: TextPlagiarismResult | ModelingPlagiarismResult;\n\n /**\n * Directive to manage the canvas element that renders the chart.\n */\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n /**\n * The labels of the chart are fixed and represent the 10 intervals we group the similarities into.\n */\n chartLabels: Label[] = ['0%-10%', '10%-20%', '20%-30%', '30%-40%', '40%-50%', '50%-60%', '60%-70%', '70%-80%', '80%-90%', '90%-100%'];\n\n /**\n * The similarity distribution is visualized in a bar chart.\n */\n chartType: ChartType = 'bar';\n\n /**\n * Array of datasets to plot.\n *\n * Only one dataset is necessary to display the similarity distribution.\n */\n chartDataSets: ChartDataSets[] = [\n {\n backgroundColor: 'lightskyblue',\n data: [],\n hoverBackgroundColor: 'dodgerblue',\n },\n ];\n\n /**\n * When visualizing the similarity distribution, we always want the y-axis to begin at zero.\n * Also, since values on the y-axis will always be integers, we set the step size to 1.\n */\n chartOptions: ChartOptions = {\n scales: {\n yAxes: [\n {\n ticks: {\n beginAtZero: true,\n stepSize: 1,\n },\n },\n ],\n },\n };\n\n ngOnChanges(changes: SimpleChanges) {\n if (changes.plagiarismResult) {\n this.updateChartDataSet(changes.plagiarismResult.currentValue.similarityDistribution || []);\n }\n }\n\n /**\n * Update the data of the dataset at the given index.\n *\n * @param data - the updated data array\n * @param index - index of the dataset to update (default: 0)\n */\n updateChartDataSet(data: number[], index = 0) {\n if (!this.chartDataSets.length || index >= this.chartDataSets.length) {\n return;\n }\n\n this.chartDataSets[index].data = data;\n }\n}\n" }, { "alpha_fraction": 0.6508545279502869, "alphanum_fraction": 0.6539937257766724, "avg_line_length": 47.32022476196289, "blob_id": "edfde0467794468c24850423aec159f8545835a2", "content_id": "bdd4092b7db17d539ae9aeb0261839bbe3599a0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8601, "license_type": "permissive", "max_line_length": 180, "num_lines": 178, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { By } from '@angular/platform-browser';\nimport { Observable, of } from 'rxjs';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-instructions-editor.module';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { TaskCommand } from 'app/shared/markdown-editor/domainCommands/programming-exercise/task.command';\nimport { HttpResponse } from '@angular/common/http';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { ExerciseHintService, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ProgrammingExerciseInstructionAnalysisComponent } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.component';\nimport { ProgrammingExerciseInstructionAnalysisService } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseInstructionInstructorAnalysis', () => {\n let comp: ProgrammingExerciseInstructionAnalysisComponent;\n let fixture: ComponentFixture<ProgrammingExerciseInstructionAnalysisComponent>;\n let debugElement: DebugElement;\n\n const testCaseOkId = 'instruction_analysis_test-case-ok';\n const testCaseIssuesId = 'instruction_analysis_test-case-issues';\n\n const hintOkId = 'instruction_analysis_hint-ok';\n const hintIssuesId = 'instruction_analysis_hint-issues';\n\n const taskCommand = new TaskCommand();\n const taskRegex = taskCommand.getTagRegex('g');\n const exerciseTestCases = ['test1', 'test2', 'test6', 'test7'];\n const problemStatement =\n '1. [task][SortStrategy Interface](test1,test2) \\n 2. [task][SortStrategy Interface](test3) \\n lorem ipsum \\n lorem \\n 3. [task][SortStrategy Interface](test2,test4)';\n\n const exerciseHints = [{ id: 1 }, { id: 2 }] as ExerciseHint[];\n\n describe('Component tests', () => {\n let analysisService: ProgrammingExerciseInstructionAnalysisService;\n\n let analyzeProblemStatementStub: SinonStub;\n let emitAnalysisSpy: SinonSpy;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, NgbModule, ArtemisProgrammingExerciseInstructionsEditorModule],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseInstructionAnalysisComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n\n analysisService = debugElement.injector.get(ProgrammingExerciseInstructionAnalysisService);\n\n analyzeProblemStatementStub = stub(analysisService, 'analyzeProblemStatement');\n emitAnalysisSpy = spy(comp.problemStatementAnalysis, 'emit');\n });\n });\n\n afterEach(() => {\n analyzeProblemStatementStub.restore();\n emitAnalysisSpy.restore();\n });\n\n it('should display the received analysis from the service', fakeAsync(() => {\n const completeAnalysis = {\n '0': { invalidTestCases: ['artemisApp.programmingExercise.testCaseAnalysis.invalidTestCase'] },\n '2': {\n invalidTestCases: ['artemisApp.programmingExercise.testCaseAnalysis.invalidTestCase'],\n },\n };\n const invalidTestCases = ['testMergeSort'];\n const invalidHints: string[] = [];\n const missingTestCases = ['testBubbleSort'];\n\n analyzeProblemStatementStub.returns({ completeAnalysis, invalidTestCases, invalidHints, missingTestCases });\n\n // dummy data.\n const hints = [{ id: 3 }] as ExerciseHint[];\n const testCases = ['testabc'];\n comp.problemStatement = problemStatement;\n comp.taskRegex = taskRegex;\n comp.exerciseHints = hints;\n comp.exerciseTestCases = testCases;\n\n comp.ngOnInit();\n\n triggerChanges(comp, { property: 'problemStatement', currentValue: problemStatement, previousValue: 'dolet amat', firstChange: false });\n tick(500); // Update is debounced, otherwise we would send updates on every change.\n fixture.detectChanges();\n\n // Check internal state and output of component.\n expect(comp.missingTestCases).to.deep.equal(missingTestCases);\n expect(comp.invalidTestCases).to.deep.equal(invalidTestCases);\n expect(comp.invalidHints).to.deep.equal(invalidHints);\n expect(emitAnalysisSpy).to.have.been.calledOnceWithExactly(completeAnalysis);\n\n // Check rendered html.\n const testCaseOk = debugElement.query(By.css(`#${testCaseOkId}`));\n const testCaseIssues = debugElement.query(By.css(`#${testCaseIssuesId}`));\n const hintOk = debugElement.query(By.css(`#${hintOkId}`));\n const hintIssues = debugElement.query(By.css(`#${hintIssuesId}`));\n\n // Test cases are not ok according to the analysis.\n expect(testCaseOk).not.to.exist;\n expect(testCaseIssues).to.exist;\n\n // Hints are ok according to the analysis.\n expect(hintOk).to.exist;\n expect(hintIssues).not.to.exist;\n }));\n });\n\n describe('Analysis service integration test', () => {\n let exerciseHintService: IExerciseHintService;\n let getHintsForExerciseStub: SinonStub;\n\n const missingTestCases = ['test6', 'test7'];\n const invalidTestCases = ['test3', 'test4'];\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, NgbModule, ArtemisProgrammingExerciseInstructionsEditorModule],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseInstructionAnalysisComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n\n exerciseHintService = debugElement.injector.get(ExerciseHintService);\n getHintsForExerciseStub = stub(exerciseHintService, 'findByExerciseId').returns(of({ body: exerciseHints }) as Observable<HttpResponse<ExerciseHint[]>>);\n });\n });\n\n afterEach(() => {\n getHintsForExerciseStub.restore();\n });\n\n it('should not render if no test cases were provided', () => {\n comp.problemStatement = problemStatement;\n comp.taskRegex = taskRegex;\n triggerChanges(comp, { property: 'problemStatement', currentValue: problemStatement });\n fixture.detectChanges();\n\n expect(debugElement.nativeElement.innerHtml).to.be.undefined;\n expect(comp.missingTestCases).to.be.empty;\n expect(comp.invalidTestCases).to.be.empty;\n });\n\n it('should render warnings on missing and invalid test cases', fakeAsync(() => {\n comp.problemStatement = problemStatement;\n comp.taskRegex = taskRegex;\n comp.exerciseTestCases = exerciseTestCases;\n comp.exerciseHints = exerciseHints;\n comp.ngOnInit();\n\n triggerChanges(\n comp,\n { property: 'problemStatement', currentValue: problemStatement, firstChange: false },\n { property: 'exerciseTestCases', currentValue: exerciseTestCases },\n );\n\n fixture.detectChanges();\n tick(500);\n\n expect(debugElement.nativeElement.innerHtml).not.to.equal('');\n expect(debugElement.query(By.css('fa-icon'))).to.exist;\n expect(comp.missingTestCases).to.be.deep.equal(missingTestCases);\n expect(comp.invalidTestCases).to.be.deep.equal(invalidTestCases);\n }));\n });\n});\n" }, { "alpha_fraction": 0.6744868159294128, "alphanum_fraction": 0.6744868159294128, "avg_line_length": 27.41666603088379, "blob_id": "b2d8d2c1c7fadba79bca37bdd170af82f7c598f2", "content_id": "b12b33f622e037093fe00ffdd5dbf07593e39bb5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 341, "license_type": "permissive", "max_line_length": 62, "num_lines": 12, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-active-modal.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SpyObject } from '../../spyobject';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { SinonStub } from 'sinon';\n\nexport class MockActiveModal extends SpyObject {\n dismissSpy: SinonStub;\n\n constructor() {\n super(NgbActiveModal);\n this.dismissSpy = this.spy('dismiss').andReturn(this);\n }\n}\n" }, { "alpha_fraction": 0.8277992010116577, "alphanum_fraction": 0.8277992010116577, "avg_line_length": 75.17646789550781, "blob_id": "a418924e878cabc9ac79534ec17a03879532be5c", "content_id": "7706db3fc889ba16e4da600adc4d4f428c4e9b7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1295, "license_type": "permissive", "max_line_length": 141, "num_lines": 17, "path": "/src/main/webapp/app/exercises/shared/result/result.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MomentModule } from 'ngx-moment';\nimport { ResultHistoryComponent } from 'app/overview/result-history/result-history.component';\nimport { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module';\nimport { SubmissionResultStatusComponent } from 'app/overview/submission-result-status.component';\nimport { UpdatingResultComponent } from 'app/exercises/shared/result/updating-result.component';\nimport { ResultComponent } from 'app/exercises/shared/result/result.component';\nimport { ResultDetailComponent } from 'app/exercises/shared/result/result-detail.component';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, MomentModule, ArtemisProgrammingExerciseActionsModule, ArtemisSharedComponentModule],\n declarations: [ResultComponent, UpdatingResultComponent, ResultDetailComponent, ResultHistoryComponent, SubmissionResultStatusComponent],\n exports: [ResultComponent, UpdatingResultComponent, ResultDetailComponent, ResultHistoryComponent, SubmissionResultStatusComponent],\n})\nexport class ArtemisResultModule {}\n" }, { "alpha_fraction": 0.6684492230415344, "alphanum_fraction": 0.6695187091827393, "avg_line_length": 20.744186401367188, "blob_id": "ba1bebc63a924348f1a90ddcc956446ddd863158", "content_id": "113e617e57d0d6c585d08d8f0f52e4b9bf5b8642", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 935, "license_type": "permissive", "max_line_length": 66, "num_lines": 43, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/bitbucket/dto/BitbucketUserDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.bitbucket.dto;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class BitbucketUserDTO {\n\n private String user;\n\n private Set<String> groups = new HashSet<>();\n\n public String getUser() {\n return user;\n }\n\n public void setUser(String username) {\n this.user = username;\n }\n\n public Set<String> getGroups() {\n return groups;\n }\n\n public void setGroups(Set<String> groups) {\n this.groups = groups;\n }\n\n /**\n * needed for Jackson\n */\n public BitbucketUserDTO() {\n }\n\n public BitbucketUserDTO(String username, Set<String> groups) {\n this.user = username;\n this.groups = groups;\n }\n}\n" }, { "alpha_fraction": 0.7397260069847107, "alphanum_fraction": 0.7407044768333435, "avg_line_length": 39.880001068115234, "blob_id": "6128bfc5c01214efab80fb6d804cfcc9d532fbf2", "content_id": "432df5b349f5b5166e484c5e617d9d76a7b613cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1022, "license_type": "permissive", "max_line_length": 93, "num_lines": 25, "path": "/src/main/webapp/app/exam/exam-scores/exam-scores.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ChartsModule } from 'ng2-charts';\nimport { ExamScoresComponent } from './exam-scores.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MomentModule } from 'ngx-moment';\nimport { ArtemisExamScoresRoutingModule } from 'app/exam/exam-scores/exam-scores.route';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\n\n@NgModule({\n declarations: [ExamScoresComponent],\n imports: [\n ArtemisSharedModule,\n ChartsModule,\n MomentModule,\n ArtemisExamScoresRoutingModule,\n ArtemisDataTableModule,\n NgxDatatableModule,\n ArtemisResultModule,\n ArtemisSharedComponentModule,\n ],\n})\nexport class ArtemisExamScoresModule {}\n" }, { "alpha_fraction": 0.6580459475517273, "alphanum_fraction": 0.6647509336471558, "avg_line_length": 20.306121826171875, "blob_id": "57484fcc10c030b85d058c724bed2c38bd19fe9f", "content_id": "7d87a157c6d66dd19d0852a685dc1a0d08ba5813", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1044, "license_type": "permissive", "max_line_length": 92, "num_lines": 49, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/ExerciseLtiConfigurationDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n/**\n * Created by Josias Montag on 26.09.16.\n */\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ExerciseLtiConfigurationDTO {\n\n private String launchUrl;\n\n private String ltiId;\n\n private String ltiPassport;\n\n public ExerciseLtiConfigurationDTO() {\n }\n\n public ExerciseLtiConfigurationDTO(String launchUrl, String ltiId, String ltiPassport) {\n this.launchUrl = launchUrl;\n this.ltiId = ltiId;\n this.ltiPassport = ltiPassport;\n }\n\n public String getLaunchUrl() {\n return launchUrl;\n }\n\n public void setLaunchUrl(String launchUrl) {\n this.launchUrl = launchUrl;\n }\n\n public String getLtiId() {\n return ltiId;\n }\n\n public void setLtiId(String ltiId) {\n this.ltiId = ltiId;\n }\n\n public String getLtiPassport() {\n return ltiPassport;\n }\n\n public void setLtiPassport(String ltiPassport) {\n this.ltiPassport = ltiPassport;\n }\n}\n" }, { "alpha_fraction": 0.6735050082206726, "alphanum_fraction": 0.6735050082206726, "avg_line_length": 40.654544830322266, "blob_id": "12e76876f92f03d21f837661c3dfebc4b0e29752", "content_id": "b00e4a1d6778c6e58e52f9989854525e9598bc7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9164, "license_type": "permissive", "max_line_length": 141, "num_lines": 220, "path": "/src/main/webapp/app/complaints/complaint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\n\nimport * as moment from 'moment';\n\nimport { Complaint, ComplaintType } from 'app/entities/complaint.model';\nimport { ComplaintResponseService } from 'app/complaints/complaint-response.service';\nimport { Exercise } from 'app/entities/exercise.model';\n\nexport type EntityResponseType = HttpResponse<Complaint>;\nexport type EntityResponseTypeArray = HttpResponse<Complaint[]>;\n\nexport interface IComplaintService {\n create: (complaint: Complaint, examId: number) => Observable<EntityResponseType>;\n findByResultId: (resultId: number) => Observable<EntityResponseType>;\n getNumberOfAllowedComplaintsInCourse: (courseId: number) => Observable<number>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ComplaintService implements IComplaintService {\n private apiUrl = SERVER_API_URL + 'api';\n private resourceUrl = this.apiUrl + '/complaints';\n\n constructor(private http: HttpClient, private complaintResponseService: ComplaintResponseService) {}\n\n /**\n * Checks if a complaint is locked for the currently logged in user\n *\n * A complaint is locked if the associated complaint response is locked\n *\n * @param complaint complaint to check the lock status for\n * @param exercise exercise used to find out if currently logged in user is instructor\n */\n isComplaintLockedForLoggedInUser(complaint: Complaint, exercise: Exercise) {\n if (complaint.complaintResponse && complaint.accepted === undefined) {\n return this.complaintResponseService.isComplaintResponseLockedForLoggedInUser(complaint.complaintResponse, exercise);\n } else {\n return false;\n }\n }\n\n /**\n * Checks if the lock on a complaint is active and if the currently logged in user is the creator of the lock\n * @param complaint complaint to check the lock status for\n */\n isComplaintLockedByLoggedInUser(complaint: Complaint) {\n if (complaint.complaintResponse && complaint.accepted === undefined) {\n return this.complaintResponseService.isComplaintResponseLockedByLoggedInUser(complaint.complaintResponse);\n } else {\n return false;\n }\n }\n\n /**\n * Checks if a complaint is locked\n * @param complaint complaint to check lock status for\n */\n isComplaintLocked(complaint: Complaint) {\n if (complaint.complaintResponse && complaint.accepted === undefined) {\n return complaint.complaintResponse.isCurrentlyLocked;\n } else {\n return false;\n }\n }\n\n /**\n * Create a new complaint.\n * @param complaint\n * @param examId the Id of the exam\n */\n create(complaint: Complaint, examId: number): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(complaint);\n if (examId) {\n return this.http\n .post<Complaint>(`${this.resourceUrl}/exam/${examId}`, copy, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n return this.http\n .post<Complaint>(this.resourceUrl, copy, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n /**\n * Find complaint by Result id.\n * @param resultId\n */\n findByResultId(resultId: number): Observable<EntityResponseType> {\n return this.http\n .get<Complaint>(`${this.resourceUrl}/result/${resultId}`, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n /**\n * Find complaints for tutor for specified exercise (complaintType == 'COMPLAINT').\n * @param exerciseId\n */\n getComplaintsForTutor(exerciseId: number): Observable<EntityResponseTypeArray> {\n return this.http\n .get<Complaint[]>(`${this.apiUrl}/exercises/${exerciseId}/complaints-for-assessment-dashboard`, { observe: 'response' })\n .map((res: EntityResponseTypeArray) => this.convertDateFromServerArray(res));\n }\n\n /**\n * Find complaints for instructor for specified test run exercise (complaintType == 'COMPLAINT').\n * @param exerciseId\n */\n getComplaintsForTestRun(exerciseId: number): Observable<EntityResponseTypeArray> {\n return this.http\n .get<Complaint[]>(`${this.apiUrl}/exercises/${exerciseId}/complaints-for-test-run-dashboard`, { observe: 'response' })\n .map((res: EntityResponseTypeArray) => this.convertDateFromServerArray(res));\n }\n\n /**\n * Find more feedback requests for tutor in this exercise.\n * @param exerciseId\n */\n getMoreFeedbackRequestsForTutor(exerciseId: number): Observable<EntityResponseTypeArray> {\n return this.http\n .get<Complaint[]>(`${this.apiUrl}/exercises/${exerciseId}/more-feedback-for-assessment-dashboard`, { observe: 'response' })\n .map((res: EntityResponseTypeArray) => this.convertDateFromServerArray(res));\n }\n\n /**\n * Get number of allowed complaints in this course.\n * @param courseId\n * @param teamMode If true, the number of allowed complaints for the user's team is returned\n */\n getNumberOfAllowedComplaintsInCourse(courseId: number, teamMode = false): Observable<number> {\n return this.http.get<number>(`${this.apiUrl}/courses/${courseId}/allowed-complaints?teamMode=${teamMode}`);\n }\n\n /**\n * Find all complaints by tutor id, course id and complaintType.\n * @param tutorId\n * @param courseId\n * @param complaintType\n */\n findAllByTutorIdForCourseId(tutorId: number, courseId: number, complaintType: ComplaintType): Observable<EntityResponseTypeArray> {\n const url = `${this.apiUrl}/courses/${courseId}/complaints?complaintType=${complaintType}&tutorId=${tutorId}`;\n return this.requestComplaintsFromUrl(url);\n }\n\n /**\n * Find all complaints by tutor id, exercise id and complaintType.\n * @param tutorId\n * @param exerciseId\n * @param complaintType\n */\n findAllByTutorIdForExerciseId(tutorId: number, exerciseId: number, complaintType: ComplaintType): Observable<EntityResponseTypeArray> {\n const url = `${this.apiUrl}/exercises/${exerciseId}/complaints?complaintType=${complaintType}&tutorId=${tutorId}`;\n return this.requestComplaintsFromUrl(url);\n }\n\n /**\n * Find all complaints by course id and complaintType.\n * @param courseId\n * @param complaintType\n */\n findAllByCourseId(courseId: number, complaintType: ComplaintType): Observable<EntityResponseTypeArray> {\n const url = `${this.apiUrl}/courses/${courseId}/complaints?complaintType=${complaintType}`;\n return this.requestComplaintsFromUrl(url);\n }\n\n /**\n * Find all complaints by course id and exam id.\n * @param courseId\n * @param examId\n */\n findAllByCourseIdAndExamId(courseId: number, examId: number): Observable<EntityResponseTypeArray> {\n const url = `${this.apiUrl}/courses/${courseId}/exams/${examId}/complaints`;\n return this.requestComplaintsFromUrl(url);\n }\n\n /**\n * Find all complaints by exercise id and complaintType.\n * @param exerciseId\n * @param complaintType\n */\n findAllByExerciseId(exerciseId: number, complaintType: ComplaintType): Observable<EntityResponseTypeArray> {\n const url = `${this.apiUrl}/exercises/${exerciseId}/complaints?complaintType=${complaintType}`;\n return this.requestComplaintsFromUrl(url);\n }\n\n private requestComplaintsFromUrl(url: string): Observable<EntityResponseTypeArray> {\n return this.http\n .get<Complaint[]>(url, { observe: 'response' })\n .map((res: EntityResponseTypeArray) => this.convertDateFromServerArray(res));\n }\n\n private convertDateFromClient(complaint: Complaint): Complaint {\n return Object.assign({}, complaint, {\n submittedTime: complaint.submittedTime && moment(complaint.submittedTime).isValid ? complaint.submittedTime.toJSON() : undefined,\n });\n }\n\n private convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.submittedTime = res.body.submittedTime ? moment(res.body.submittedTime) : undefined;\n if (res.body?.complaintResponse) {\n this.complaintResponseService.convertDatesToMoment(res.body.complaintResponse);\n }\n }\n return res;\n }\n\n private convertDateFromServerArray(res: EntityResponseTypeArray): EntityResponseTypeArray {\n if (res.body) {\n res.body.forEach((complaint) => {\n complaint.submittedTime = complaint.submittedTime ? moment(complaint.submittedTime) : undefined;\n if (complaint.complaintResponse) {\n this.complaintResponseService.convertDatesToMoment(complaint.complaintResponse);\n }\n });\n }\n\n return res;\n }\n}\n" }, { "alpha_fraction": 0.6576576828956604, "alphanum_fraction": 0.6576576828956604, "avg_line_length": 36, "blob_id": "7ecb0c7dba14cf9ee64c13ec36d6f3acebf4a6b1", "content_id": "639fe6c7e51eaafc9fa03d7b4c593ba011343735", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 111, "license_type": "permissive", "max_line_length": 73, "num_lines": 3, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-ngb-modal.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class MockNgbModalService {\n open = (component: any, options: any) => ({ componentInstance: {} });\n}\n" }, { "alpha_fraction": 0.6905311942100525, "alphanum_fraction": 0.6916859149932861, "avg_line_length": 20.121952056884766, "blob_id": "d513bab0f1f5ccf0a77ebffd013c169419c3cf69", "content_id": "70f7caacb133517a4adf8116508d1606e67e7626", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 866, "license_type": "permissive", "max_line_length": 61, "num_lines": 41, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/dto/BambooBuildLogDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.bamboo.dto;\n\nimport java.time.ZonedDateTime;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class BambooBuildLogDTO {\n\n private ZonedDateTime date;\n\n private String log;\n\n private String unstyledLog;\n\n public ZonedDateTime getDate() {\n return date;\n }\n\n public void setDate(ZonedDateTime date) {\n this.date = date;\n }\n\n public String getLog() {\n return log;\n }\n\n public void setLog(String log) {\n this.log = log;\n }\n\n public String getUnstyledLog() {\n return unstyledLog;\n }\n\n public void setUnstyledLog(String unstyledLog) {\n this.unstyledLog = unstyledLog;\n }\n}\n" }, { "alpha_fraction": 0.6997820138931274, "alphanum_fraction": 0.7074571251869202, "avg_line_length": 52.13703155517578, "blob_id": "5671fd7cd194ddcc88d66eff29a44cc26ca773e9", "content_id": "4cb3a5a80129808804daa8dd3385d2116db91a62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 32573, "license_type": "permissive", "max_line_length": 180, "num_lines": 613, "path": "/src/test/java/de/tum/in/www1/artemis/QuizSubmissionIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.ArgumentMatchers.*;\nimport static org.mockito.Mockito.*;\n\nimport java.security.Principal;\nimport java.time.Duration;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.List;\nimport java.util.concurrent.TimeUnit;\nimport java.util.stream.Collectors;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.EnumSource;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.Result;\nimport de.tum.in.www1.artemis.domain.enumeration.ScoringType;\nimport de.tum.in.www1.artemis.domain.quiz.*;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.QuizExerciseService;\nimport de.tum.in.www1.artemis.service.scheduled.quiz.QuizScheduleService;\nimport de.tum.in.www1.artemis.web.websocket.QuizSubmissionWebsocketService;\n\npublic class QuizSubmissionIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n private final Logger log = LoggerFactory.getLogger(getClass());\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private ExerciseRepository exerciseRepository;\n\n @Autowired\n private QuizExerciseService quizExerciseService;\n\n @Autowired\n private QuizExerciseRepository quizExerciseRepository;\n\n @Autowired\n private QuizScheduleService quizScheduleService;\n\n @Autowired\n private QuizSubmissionWebsocketService quizSubmissionWebsocketService;\n\n @Autowired\n private QuizSubmissionRepository quizSubmissionRepository;\n\n @Autowired\n private ParticipationRepository participationRepository;\n\n @Autowired\n private SubmissionRepository submissionRepository;\n\n @Autowired\n private ResultRepository resultRepository;\n\n private final int multiplier = 10;\n\n @BeforeEach\n public void init() {\n quizScheduleService.stopSchedule();\n database.addUsers(10 * multiplier, 5, 1);\n // do not use the schedule service based on a time interval in the tests, because this would result in flaky tests that run much slower\n }\n\n @AfterEach\n public void tearDown() {\n quizScheduleService.clearAllQuizData();\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmit() throws Exception {\n // change config to make test faster\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now(), null);\n quizExercise.duration(240);\n quizExercise.setIsPlannedToStart(true);\n quizExercise.setIsVisibleBeforeStart(true);\n quizExercise = quizExerciseService.save(quizExercise);\n\n int numberOfParticipants = 10 * multiplier;\n QuizSubmission quizSubmission;\n\n for (int i = 1; i <= numberOfParticipants; i++) {\n quizSubmission = database.generateSubmissionForThreeQuestions(quizExercise, i, false, null);\n final var username = \"student\" + i;\n final Principal principal = () -> username;\n // save\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, principal);\n }\n\n // only half of the students submit manually\n for (int i = 1; i <= numberOfParticipants / 2; i++) {\n quizSubmission = database.generateSubmissionForThreeQuestions(quizExercise, i, true, null);\n final var username = \"student\" + i;\n final Principal principal = () -> username;\n // submit\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, principal);\n }\n\n // before the quiz submissions are processed, none of them ends up in the database\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isEqualTo(0);\n\n // process first half of the submissions\n quizScheduleService.processCachedQuizSubmissions();\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isEqualTo(numberOfParticipants / 2);\n\n // End the quiz right now so that results can be processed\n quizExercise = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExercise).isNotNull();\n quizExercise.setDuration((int) (Duration.between(quizExercise.getReleaseDate(), ZonedDateTime.now()).getSeconds() - Constants.QUIZ_GRACE_PERIOD_IN_SECONDS));\n exerciseRepository.saveAndFlush(quizExercise);\n\n quizScheduleService.processCachedQuizSubmissions();\n\n // after the quiz submissions have been processed, all submission are saved to the database\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isEqualTo(numberOfParticipants);\n\n // Test the statistics directly from the database\n QuizExercise quizExerciseWithStatistic = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExerciseWithStatistic).isNotNull();\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsUnrated()).isEqualTo(0);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsRated()).isEqualTo(numberOfParticipants);\n int questionScore = quizExerciseWithStatistic.getQuizQuestions().stream().map(QuizQuestion::getPoints).reduce(0, Integer::sum);\n assertThat(quizExerciseWithStatistic.getMaxPoints()).isEqualTo(questionScore);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters().size()).isEqualTo(questionScore + 1);\n // check general statistics\n for (var pointCounter : quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters()) {\n if (pointCounter.getPoints() == 0.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(Math.round(numberOfParticipants / 3.0));\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n else if (pointCounter.getPoints() == 3.0 || pointCounter.getPoints() == 4.0 || pointCounter.getPoints() == 6.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(Math.round(numberOfParticipants / 6.0));\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n else if (pointCounter.getPoints() == 7.0 || pointCounter.getPoints() == 9.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(Math.round(numberOfParticipants / 12.0));\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n else {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n }\n // check statistic for each question\n for (var question : quizExerciseWithStatistic.getQuizQuestions()) {\n if (question instanceof MultipleChoiceQuestion) {\n assertThat(question.getQuizQuestionStatistic().getRatedCorrectCounter()).isEqualTo(Math.round(numberOfParticipants / 2.0));\n }\n else if (question instanceof DragAndDropQuestion) {\n assertThat(question.getQuizQuestionStatistic().getRatedCorrectCounter()).isEqualTo(Math.round(numberOfParticipants / 3.0));\n }\n else {\n assertThat(question.getQuizQuestionStatistic().getRatedCorrectCounter()).isEqualTo(Math.round(numberOfParticipants / 4.0));\n }\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getParticipantsRated()).isEqualTo(numberOfParticipants);\n assertThat(question.getQuizQuestionStatistic().getParticipantsUnrated()).isEqualTo(0);\n }\n\n // execute the scheduler again, this should remove the quiz exercise from the cache\n quizScheduleService.processCachedQuizSubmissions();\n // but of course keep all submissions\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isEqualTo(numberOfParticipants);\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmitPractice() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(false);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(10), null);\n quizExercise.setDueDate(ZonedDateTime.now().minusSeconds(8));\n quizExercise.setDuration(2);\n quizExercise.setIsPlannedToStart(true);\n quizExercise.setIsVisibleBeforeStart(true);\n quizExercise.setIsOpenForPractice(true);\n quizExerciseService.save(quizExercise);\n\n assertThat(quizSubmissionRepository.findAll().size()).isEqualTo(0);\n assertThat(participationRepository.findAll().size()).isEqualTo(0);\n\n var numberOfParticipants = 10;\n\n // submit 10 times for 10 different students\n for (int i = 1; i <= numberOfParticipants; i++) {\n QuizSubmission quizSubmission = database.generateSubmissionForThreeQuestions(quizExercise, i, true, null);\n database.changeUser(\"student\" + i);\n Result receivedResult = request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/practice\", quizSubmission, Result.class, HttpStatus.OK);\n assertThat(((QuizSubmission) receivedResult.getSubmission()).getSubmittedAnswers().size()).isEqualTo(quizSubmission.getSubmittedAnswers().size());\n }\n\n // after the quiz has ended, all submission are saved to the database\n assertThat(quizSubmissionRepository.findAll().size()).isEqualTo(numberOfParticipants);\n assertThat(participationRepository.findAll().size()).isEqualTo(numberOfParticipants);\n\n // processing the quiz submissions will update the statistics\n quizScheduleService.processCachedQuizSubmissions();\n\n // Test the statistics directly from the database\n QuizExercise quizExerciseWithStatistic = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExerciseWithStatistic).isNotNull();\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsRated()).isEqualTo(0);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsUnrated()).isEqualTo(numberOfParticipants);\n int questionScore = quizExerciseWithStatistic.getQuizQuestions().stream().map(QuizQuestion::getPoints).reduce(0, Integer::sum);\n assertThat(quizExerciseWithStatistic.getMaxPoints()).isEqualTo(questionScore);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters().size()).isEqualTo(questionScore + 1);\n // check general statistics\n for (var pointCounter : quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters()) {\n if (pointCounter.getPoints() == 0.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(3);\n }\n else if (pointCounter.getPoints() == 3.0 || pointCounter.getPoints() == 4.0 || pointCounter.getPoints() == 6.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(2);\n }\n else if (pointCounter.getPoints() == 7.0) {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(1);\n }\n else {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n }\n // check statistic for each question\n for (var question : quizExerciseWithStatistic.getQuizQuestions()) {\n if (question instanceof MultipleChoiceQuestion) {\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(5);\n }\n else if (question instanceof DragAndDropQuestion) {\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(3);\n }\n else {\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(2);\n }\n assertThat(question.getQuizQuestionStatistic().getRatedCorrectCounter()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getParticipantsUnrated()).isEqualTo(numberOfParticipants);\n assertThat(question.getQuizQuestionStatistic().getParticipantsRated()).isEqualTo(0);\n }\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmitPractice_badRequest() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExerciseServer = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseServer.setDueDate(ZonedDateTime.now().minusSeconds(2));\n quizExerciseServer.setDuration(2);\n quizExerciseServer.setIsPlannedToStart(true);\n quizExerciseServer.setIsVisibleBeforeStart(true);\n quizExerciseServer.setIsOpenForPractice(false);\n quizExerciseService.save(quizExerciseServer);\n\n assertThat(quizSubmissionRepository.findAll().size()).isEqualTo(0);\n\n QuizSubmission quizSubmission = new QuizSubmission();\n for (var question : quizExerciseServer.getQuizQuestions()) {\n for (int i = 1; i <= 10; i++) {\n var answer = database.generateSubmittedAnswerFor(question, i % 2 == 0);\n quizSubmission.addSubmittedAnswers(answer);\n // also remove once\n quizSubmission.removeSubmittedAnswers(answer);\n quizSubmission.addSubmittedAnswers(answer);\n }\n }\n quizSubmission.setSubmitted(true);\n // quiz not open for practice --> bad request expected\n Result result = request.postWithResponseBody(\"/api/exercises/\" + quizExerciseServer.getId() + \"/submissions/practice\", quizSubmission, Result.class,\n HttpStatus.BAD_REQUEST);\n assertThat(result).isNull();\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmitPreview_forbidden() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/preview\", new QuizSubmission(), Result.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmitPractice_forbidden() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n course.setStudentGroupName(\"abc\");\n courseRepository.save(course);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/practice\", new QuizSubmission(), Result.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(value = \"tutor1\", roles = \"TA\")\n public void testQuizSubmitPreview_forbidden_otherTa() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n course.setTeachingAssistantGroupName(\"tutor2\");\n courseRepository.save(course);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/preview\", new QuizSubmission(), Result.class, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testQuizSubmitPreview_badRequest_noQuiz() throws Exception {\n request.postWithResponseBody(\"/api/exercises/\" + 11223344 + \"/submissions/preview\", new QuizSubmission(), Result.class, HttpStatus.NOT_FOUND);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testQuizSubmitPractice_badRequest_noQuiz() throws Exception {\n request.postWithResponseBody(\"/api/exercises/\" + 11223344 + \"/submissions/practice\", new QuizSubmission(), Result.class, HttpStatus.NOT_FOUND);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testQuizSubmitPreview_badRequest_submissionId() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n var quizSubmission = new QuizSubmission();\n quizSubmission.setId(1L);\n request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/preview\", quizSubmission, Result.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testQuizSubmitPractice_badRequest_submissionId() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n var quizSubmission = new QuizSubmission();\n quizSubmission.setId(1L);\n request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/practice\", quizSubmission, Result.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testQuizSubmitPreview() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusSeconds(4), null);\n quizExerciseService.save(quizExercise);\n\n int numberOfParticipants = 10;\n\n for (int i = 1; i <= numberOfParticipants; i++) {\n QuizSubmission quizSubmission = new QuizSubmission();\n for (var question : quizExercise.getQuizQuestions()) {\n quizSubmission.addSubmittedAnswers(database.generateSubmittedAnswerFor(question, i % 2 == 0));\n }\n Result receivedResult = request.postWithResponseBody(\"/api/exercises/\" + quizExercise.getId() + \"/submissions/preview\", quizSubmission, Result.class, HttpStatus.OK);\n assertThat(((QuizSubmission) receivedResult.getSubmission()).getSubmittedAnswers().size()).isEqualTo(quizSubmission.getSubmittedAnswers().size());\n }\n\n // in the preview the submission will not be saved to the database\n assertThat(quizSubmissionRepository.findAll().size()).isEqualTo(0);\n\n quizScheduleService.processCachedQuizSubmissions();\n\n // all stats must be 0 because we have a preview here\n // Test the statistics directly from the database\n QuizExercise quizExerciseWithStatistic = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExerciseWithStatistic).isNotNull();\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsRated()).isEqualTo(0);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getParticipantsUnrated()).isEqualTo(0);\n int questionScore = quizExerciseWithStatistic.getQuizQuestions().stream().map(QuizQuestion::getPoints).reduce(0, Integer::sum);\n assertThat(quizExerciseWithStatistic.getMaxPoints()).isEqualTo(questionScore);\n assertThat(quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters().size()).isEqualTo(questionScore + 1);\n for (var pointCounter : quizExerciseWithStatistic.getQuizPointStatistic().getPointCounters()) {\n if (pointCounter.getPoints() == 0.0f) {\n // all participants have 0 points (and are unrated)\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n else {\n assertThat(pointCounter.getRatedCounter()).isEqualTo(0);\n assertThat(pointCounter.getUnRatedCounter()).isEqualTo(0);\n }\n }\n // check statistic for each question\n for (var question : quizExerciseWithStatistic.getQuizQuestions()) {\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getUnRatedCorrectCounter()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getRatedCorrectCounter()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getParticipantsUnrated()).isEqualTo(0);\n assertThat(question.getQuizQuestionStatistic().getParticipantsRated()).isEqualTo(0);\n }\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizSubmitScheduledAndDeleted() throws Exception {\n log.debug(\"// Start testQuizSubmitScheduledAndDeleted\");\n /*\n * The time we wait in between needs to be relatively high to make sure the concurrent tasks are finished in time, especially sending out the exercise can easily take up to\n * 100 ms, so we should leave about 200 ms for that, similar for the completion of all saving/updating/scheduling operations.\n */\n List<Course> courses = database.createCoursesWithExercisesAndLectures(true);\n Course course = courses.get(0);\n String publishQuizPath = \"/topic/courses/\" + course.getId() + \"/quizExercises\";\n log.debug(\"// Creating the quiz exercise 2s in the future\");\n var releaseDate = ZonedDateTime.now().plus(2, ChronoUnit.SECONDS);\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().plus(2000, ChronoUnit.MILLIS), null);\n quizExercise.duration(60);\n quizExercise.setIsPlannedToStart(true);\n quizExercise.setIsVisibleBeforeStart(true);\n\n // also schedules the quiz\n log.debug(\"// Saving the quiz initially\");\n quizExercise = quizExerciseService.save(quizExercise);\n\n checkQuizNotStarted(publishQuizPath);\n\n // wait a bit\n sleep(1000);\n checkQuizNotStarted(publishQuizPath);\n\n // reschedule\n log.debug(\"// Rescheduling the quiz for another 2s into the future\");\n releaseDate = releaseDate.plus(2000, ChronoUnit.MILLIS);\n quizExercise.releaseDate(releaseDate);\n quizExercise = quizExerciseService.save(quizExercise);\n\n // wait for the old release date to pass\n sleep(1500);\n\n // check that quiz has still not started now\n checkQuizNotStarted(publishQuizPath);\n\n // check that submission fails\n QuizSubmission quizSubmission = database.generateSubmissionForThreeQuestions(quizExercise, 1, true, null);\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, () -> \"student1\");\n\n quizScheduleService.processCachedQuizSubmissions();\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isZero();\n\n // wait for the new release date to pass\n sleep(2500);\n\n // check that quiz has started\n log.debug(\"// Check that the quiz has started\");\n verify(messagingTemplate, times(1)).send(eq(publishQuizPath), any());\n\n // process cached submissions\n quizScheduleService.processCachedQuizSubmissions();\n\n // save submissions\n int numberOfParticipants = 10;\n for (int i = 1; i <= numberOfParticipants; i++) {\n quizSubmission = database.generateSubmissionForThreeQuestions(quizExercise, i, false, null);\n final var username = \"student\" + i;\n final Principal principal = () -> username;\n // save\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, principal);\n }\n\n // process the saved but not submitted quiz submissions\n quizScheduleService.processCachedQuizSubmissions();\n\n // before the quiz submissions are submitted, none of them ends up in the database\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isZero();\n\n // set the quiz end to now and ...\n log.debug(\"// End the quiz and delete it\");\n quizExercise = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExercise).isNotNull();\n quizExercise.setDuration((int) Duration.between(quizExercise.getReleaseDate(), ZonedDateTime.now()).getSeconds() - Constants.QUIZ_GRACE_PERIOD_IN_SECONDS);\n quizExercise = exerciseRepository.saveAndFlush(quizExercise);\n quizScheduleService.updateQuizExercise(quizExercise);\n // ... directly delete the quiz\n exerciseRepository.delete(quizExercise);\n\n sleep(1000);\n\n // the deleted quiz should get removed, no submissions should be saved\n quizScheduleService.processCachedQuizSubmissions();\n\n // quiz is not cached anymore\n assertThat(quizScheduleService.getQuizExercise(quizExercise.getId())).isNull();\n // no submissions were marked as submitted and saved\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isZero();\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizScoringTypes() {\n Course course = database.createCourse();\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusMinutes(1), null);\n quizExercise.duration(60);\n quizExercise.setIsPlannedToStart(true);\n quizExercise.setIsVisibleBeforeStart(true);\n quizExercise = quizExerciseService.save(quizExercise);\n\n QuizSubmission quizSubmission = new QuizSubmission();\n for (var question : quizExercise.getQuizQuestions()) {\n quizSubmission.addSubmittedAnswers(database.generateSubmittedAnswerForQuizWithCorrectAndFalseAnswers(question));\n }\n quizSubmission.submitted(true);\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, () -> \"student1\");\n\n quizScheduleService.processCachedQuizSubmissions();\n\n // End the quiz right now so that results can be processed\n quizExercise = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assertThat(quizExercise).isNotNull();\n quizExercise.setDuration((int) Duration.between(quizExercise.getReleaseDate(), ZonedDateTime.now()).getSeconds() - Constants.QUIZ_GRACE_PERIOD_IN_SECONDS);\n exerciseRepository.saveAndFlush(quizExercise);\n\n quizScheduleService.processCachedQuizSubmissions();\n\n assertThat(quizSubmissionRepository.count()).isEqualTo(1);\n\n List<Result> results = resultRepository.findByParticipationExerciseIdOrderByCompletionDateAsc(quizExercise.getId());\n assertThat(results.size()).isEqualTo(1);\n var result = results.get(0);\n\n assertThat(result.getResultString()).isEqualTo(\"1 of 9 points\");\n\n var submittedAnswers = ((QuizSubmission) result.getSubmission()).getSubmittedAnswers();\n for (SubmittedAnswer submittedAnswer : submittedAnswers) {\n // MC submitted answers 0 points as one correct and one false -> ALL_OR_NOTHING\n if (submittedAnswer instanceof MultipleChoiceSubmittedAnswer) {\n assertThat(submittedAnswer.getScoreInPoints()).isEqualTo(0D);\n } // DND submitted answers 0 points as one correct and two false -> PROPORTIONAL_WITH_PENALTY\n else if (submittedAnswer instanceof DragAndDropSubmittedAnswer) {\n assertThat(submittedAnswer.getScoreInPoints()).isEqualTo(0D);\n } // SA submitted answers 1 points as one correct and one false -> PROPORTIONAL_WITHOUT_PENALTY\n else if (submittedAnswer instanceof ShortAnswerSubmittedAnswer) {\n assertThat(submittedAnswer.getScoreInPoints()).isEqualTo(1D);\n }\n }\n }\n\n @ParameterizedTest(name = \"{displayName} [{index}] {argumentsWithNames}\")\n @EnumSource(ScoringType.class)\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testQuizScoringType(ScoringType scoringType) {\n Course course = database.createCourse();\n QuizExercise quizExercise = database.createQuiz(course, ZonedDateTime.now().minusMinutes(1), null);\n quizExercise.duration(60);\n quizExercise.setIsPlannedToStart(true);\n quizExercise.setIsVisibleBeforeStart(true);\n quizExercise.setQuizQuestions(quizExercise.getQuizQuestions().stream().peek(quizQuestion -> quizQuestion.setScoringType(scoringType)).collect(Collectors.toList()));\n quizExercise = quizExerciseService.save(quizExercise);\n\n QuizSubmission quizSubmission = new QuizSubmission();\n for (var question : quizExercise.getQuizQuestions()) {\n quizSubmission.addSubmittedAnswers(database.generateSubmittedAnswerForQuizWithCorrectAndFalseAnswers(question));\n }\n quizSubmission.submitted(true);\n quizSubmissionWebsocketService.saveSubmission(quizExercise.getId(), quizSubmission, () -> \"student1\");\n\n quizScheduleService.processCachedQuizSubmissions();\n\n // End the quiz right now so that results can be processed\n quizExercise = quizExerciseRepository.findOneWithQuestionsAndStatistics(quizExercise.getId());\n assert quizExercise != null;\n quizExercise.setDuration((int) Duration.between(quizExercise.getReleaseDate(), ZonedDateTime.now()).getSeconds() - Constants.QUIZ_GRACE_PERIOD_IN_SECONDS);\n exerciseRepository.saveAndFlush(quizExercise);\n\n quizScheduleService.processCachedQuizSubmissions();\n\n assertThat(submissionRepository.countByExerciseIdSubmitted(quizExercise.getId())).isEqualTo(1);\n\n List<Result> results = resultRepository.findByParticipationExerciseIdOrderByCompletionDateAsc(quizExercise.getId());\n assertThat(results.size()).isEqualTo(1);\n var result = results.get(0);\n\n var resultString = switch (scoringType) {\n case ALL_OR_NOTHING, PROPORTIONAL_WITH_PENALTY -> \"0 of 9 points\";\n case PROPORTIONAL_WITHOUT_PENALTY -> \"4 of 9 points\";\n };\n assertThat(result.getResultString()).isEqualTo(resultString);\n }\n\n private void checkQuizNotStarted(String path) {\n // check that quiz has not started now\n log.debug(\"// Check that the quiz has not started and submissions are not allowed\");\n verify(messagingTemplate, never()).send(eq(path), any());\n }\n\n private void sleep(long millis) throws InterruptedException {\n log.debug(\"zzzzzzzzzzzzz Sleep {}ms\", millis);\n TimeUnit.MILLISECONDS.sleep(millis);\n }\n}\n" }, { "alpha_fraction": 0.6641891598701477, "alphanum_fraction": 0.6649492979049683, "avg_line_length": 47.32653045654297, "blob_id": "493cc493c284221fc3eedf6829f222ce13349f60", "content_id": "b3595b9ee906ee24b1f2f4260268f128edbd8f19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11840, "license_type": "permissive", "max_line_length": 176, "num_lines": 245, "path": "/src/main/webapp/app/exam/participate/exam-participation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Observable, Subject, throwError } from 'rxjs';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { HttpClient, HttpErrorResponse } from '@angular/common/http';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';\nimport { catchError, map } from 'rxjs/operators';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { Exam } from 'app/entities/exam.model';\nimport * as moment from 'moment';\nimport { getLatestSubmissionResult } from 'app/entities/submission.model';\nimport { cloneDeep } from 'lodash';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { addUserIndependentRepositoryUrl } from 'app/overview/participation-utils';\nimport { ExerciseType } from 'app/entities/exercise.model';\n\n@Injectable({ providedIn: 'root' })\nexport class ExamParticipationService {\n public currentlyLoadedStudentExam = new Subject<StudentExam>();\n\n public getResourceURL(courseId: number, examId: number): string {\n return `${SERVER_API_URL}api/courses/${courseId}/exams/${examId}`;\n }\n\n constructor(\n private httpClient: HttpClient,\n private localStorageService: LocalStorageService,\n private sessionStorage: SessionStorageService,\n private exerciseService: ExerciseService,\n ) {}\n\n private static getLocalStorageKeyForStudentExam(courseId: number, examId: number): string {\n const prefix = 'artemis_student_exam';\n return `${prefix}_${courseId}_${examId}`;\n }\n\n /**\n * Retrieves a {@link StudentExam} from server or localstorage. Will also mark the student exam as started\n * @param courseId the id of the course the exam is created in\n * @param examId the id of the exam\n */\n public loadStudentExamWithExercisesForConduction(courseId: number, examId: number): Observable<StudentExam> {\n const url = this.getResourceURL(courseId, examId) + '/student-exams/conduction';\n return this.getStudentExamFromServer(url, courseId, examId);\n }\n\n /**\n * Retrieves a {@link StudentExam} from the localstorage. Will also mark the student exam as started\n *\n * @param courseId the id of the course the exam is created in\n * @param examId the id of the exam\n */\n public loadStudentExamWithExercisesForConductionFromLocalStorage(courseId: number, examId: number): Observable<StudentExam> {\n const localStoredExam: StudentExam = JSON.parse(this.localStorageService.retrieve(ExamParticipationService.getLocalStorageKeyForStudentExam(courseId, examId)));\n return Observable.of(localStoredExam);\n }\n\n /**\n * Retrieves a {@link StudentExam} from server or localstorage for display of the summary.\n * @param courseId the id of the course the exam is created in\n * @param examId the id of the exam\n */\n public loadStudentExamWithExercisesForSummary(courseId: number, examId: number): Observable<StudentExam> {\n const url = this.getResourceURL(courseId, examId) + '/student-exams/summary';\n return this.getStudentExamFromServer(url, courseId, examId);\n }\n\n /**\n * Retrieves a {@link StudentExam} from server or localstorage.\n */\n private getStudentExamFromServer(url: string, courseId: number, examId: number): Observable<StudentExam> {\n return this.httpClient.get<StudentExam>(url).pipe(\n map((studentExam: StudentExam) => {\n if (studentExam.examSessions && studentExam.examSessions.length > 0 && studentExam.examSessions[0].sessionToken) {\n this.saveExamSessionTokenToSessionStorage(studentExam.examSessions[0].sessionToken);\n }\n return this.convertStudentExamFromServer(studentExam);\n }),\n catchError(() => {\n const localStoredExam: StudentExam = JSON.parse(this.localStorageService.retrieve(ExamParticipationService.getLocalStorageKeyForStudentExam(courseId, examId)));\n return Observable.of(localStoredExam);\n }),\n );\n }\n\n /**\n * Loads {@link Exam} object from server\n * @param courseId the id of the course the exam is created in\n * @param examId the id of the exam\n */\n public loadStudentExam(courseId: number, examId: number): Observable<StudentExam> {\n const url = this.getResourceURL(courseId, examId) + '/start';\n return this.httpClient.get<StudentExam>(url).map((studentExam: StudentExam) => {\n const convertedStudentExam = this.convertStudentExamDateFromServer(studentExam);\n this.adjustRepositoryUrlsForProgrammingExercises(convertedStudentExam);\n this.currentlyLoadedStudentExam.next(convertedStudentExam);\n return convertedStudentExam;\n });\n }\n\n public loadTestRunWithExercisesForConduction(courseId: number, examId: number, testRunId: number): Observable<StudentExam> {\n const url = this.getResourceURL(courseId, examId) + '/test-run/' + testRunId + '/conduction';\n return this.httpClient.get<StudentExam>(url).map((studentExam: StudentExam) => {\n const convertedStudentExam = this.convertStudentExamDateFromServer(studentExam);\n this.adjustRepositoryUrlsForProgrammingExercises(convertedStudentExam);\n this.currentlyLoadedStudentExam.next(convertedStudentExam);\n return convertedStudentExam;\n });\n }\n\n /**\n * Submits {@link StudentExam} - the exam cannot be updated afterwards anymore\n * @param courseId the id of the course the exam is created in\n * @param examId the id of the exam\n * @param studentExam: the student exam to submit\n * @return returns the studentExam version of the server\n */\n public submitStudentExam(courseId: number, examId: number, studentExam: StudentExam): Observable<StudentExam> {\n const url = this.getResourceURL(courseId, examId) + '/student-exams/submit';\n const studentExamCopy = cloneDeep(studentExam);\n ExamParticipationService.breakCircularDependency(studentExamCopy);\n\n return this.httpClient.post<StudentExam>(url, studentExamCopy).pipe(\n map((submittedStudentExam: StudentExam) => {\n return this.convertStudentExamFromServer(submittedStudentExam);\n }),\n catchError((error: HttpErrorResponse) => {\n if (error.status === 403 && error.headers.get('x-null-error') === 'error.submissionNotInTime') {\n return throwError(new Error('studentExam.submissionNotInTime'));\n } else if (error.status === 409 && error.headers.get('x-null-error') === 'error.alreadySubmitted') {\n return throwError(new Error('studentExam.alreadySubmitted'));\n } else {\n return throwError(new Error('studentExam.handInFailed'));\n }\n }),\n );\n }\n\n private static breakCircularDependency(studentExam: StudentExam) {\n studentExam.exercises!.forEach((exercise) => {\n if (!!exercise.studentParticipations) {\n for (const participation of exercise.studentParticipations) {\n if (!!participation.results) {\n for (const result of participation.results) {\n delete result.participation;\n }\n }\n if (!!participation.submissions) {\n for (const submission of participation.submissions) {\n delete submission.participation;\n const result = getLatestSubmissionResult(submission);\n if (!!result) {\n delete result.participation;\n delete result.submission;\n }\n }\n }\n delete participation.exercise;\n }\n }\n });\n }\n\n /**\n * save the studentExam to the local Storage\n *\n * @param courseId\n * @param examId\n * @param studentExam\n */\n public saveStudentExamToLocalStorage(courseId: number, examId: number, studentExam: StudentExam): void {\n const studentExamCopy = cloneDeep(studentExam);\n ExamParticipationService.breakCircularDependency(studentExamCopy);\n this.localStorageService.store(ExamParticipationService.getLocalStorageKeyForStudentExam(courseId, examId), JSON.stringify(studentExamCopy));\n }\n\n /**\n * saves latest examSessionToken to sessionStorage\n * @param examSessionToken latest examSessionToken\n */\n public saveExamSessionTokenToSessionStorage(examSessionToken: string): void {\n this.sessionStorage.store('ExamSessionToken', examSessionToken);\n }\n\n /**\n * Update a quizSubmission\n *\n * @param exerciseId\n * @param quizSubmission\n */\n public updateQuizSubmission(exerciseId: number, quizSubmission: QuizSubmission): Observable<QuizSubmission> {\n const url = `${SERVER_API_URL}api/exercises/${exerciseId}/submissions/exam`;\n return this.httpClient.put<QuizSubmission>(url, quizSubmission);\n }\n\n public setLastSaveFailed(saveFailed: boolean, courseId: number, examId: number): void {\n const key = ExamParticipationService.getLocalStorageKeyForStudentExam(courseId, examId) + '-save-failed';\n this.localStorageService.store(key, saveFailed);\n }\n\n public lastSaveFailed(courseId: number, examId: number): boolean {\n const key = ExamParticipationService.getLocalStorageKeyForStudentExam(courseId, examId) + '-save-failed';\n return this.localStorageService.retrieve(key);\n }\n\n private convertStudentExamFromServer(studentExam: StudentExam): StudentExam {\n studentExam.exercises = this.exerciseService.convertExercisesDateFromServer(studentExam.exercises);\n studentExam.exam = this.convertExamDateFromServer(studentExam.exam);\n this.adjustRepositoryUrlsForProgrammingExercises(studentExam);\n return studentExam;\n }\n\n private convertExamDateFromServer(exam?: Exam) {\n if (exam) {\n exam.visibleDate = exam.visibleDate ? moment(exam.visibleDate) : undefined;\n exam.startDate = exam.startDate ? moment(exam.startDate) : undefined;\n exam.endDate = exam.endDate ? moment(exam.endDate) : undefined;\n exam.publishResultsDate = exam.publishResultsDate ? moment(exam.publishResultsDate) : undefined;\n exam.examStudentReviewStart = exam.examStudentReviewStart ? moment(exam.examStudentReviewStart) : undefined;\n exam.examStudentReviewEnd = exam.examStudentReviewEnd ? moment(exam.examStudentReviewEnd) : undefined;\n }\n return exam;\n }\n\n private convertStudentExamDateFromServer(studentExam: StudentExam): StudentExam {\n studentExam.exam = this.convertExamDateFromServer(studentExam.exam);\n return studentExam;\n }\n\n private adjustRepositoryUrlsForProgrammingExercises(studentExam: StudentExam) {\n // add user indepentend repositoryUrl to all student participations\n if (studentExam.exercises) {\n studentExam.exercises!.forEach((ex) => {\n if (ex.type === ExerciseType.PROGRAMMING && ex.studentParticipations) {\n ex.studentParticipations!.forEach((sp) => {\n if (sp.type === ParticipationType.PROGRAMMING) {\n addUserIndependentRepositoryUrl(sp);\n }\n });\n }\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.7396751642227173, "alphanum_fraction": 0.7422037124633789, "avg_line_length": 62.139793395996094, "blob_id": "3ef00350f2f219d0a90bebcbba1bf85544071c4d", "content_id": "2b416fb53512a0bacddd918bbf56bdbc223e4f67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 79493, "license_type": "permissive", "max_line_length": 492, "num_lines": 1259, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ProgrammingExerciseResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.config.Constants.*;\nimport static de.tum.in.www1.artemis.service.util.TimeLogUtil.formatDurationFrom;\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.nio.file.Paths;\nimport java.util.*;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.core.io.InputStreamResource;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.*;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.domain.enumeration.RepositoryType;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.plagiarism.text.TextPlagiarismResult;\nimport de.tum.in.www1.artemis.exception.ContinuousIntegrationException;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.connectors.ContinuousIntegrationService;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.connectors.VersionControlService;\nimport de.tum.in.www1.artemis.service.feature.Feature;\nimport de.tum.in.www1.artemis.service.feature.FeatureToggle;\nimport de.tum.in.www1.artemis.service.plagiarism.PlagiarismService;\nimport de.tum.in.www1.artemis.service.programming.*;\nimport de.tum.in.www1.artemis.web.rest.dto.PageableSearchDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.RepositoryExportOptionsDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.SearchResultPageDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\nimport de.tum.in.www1.artemis.web.websocket.dto.ProgrammingExerciseTestCaseStateDTO;\nimport jplag.ExitException;\n\n/**\n * REST controller for managing ProgrammingExercise.\n */\n@RestController\n@RequestMapping(ProgrammingExerciseResource.Endpoints.ROOT)\npublic class ProgrammingExerciseResource {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseResource.class);\n\n private static final String ENTITY_NAME = \"programmingExercise\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final UserRepository userRepository;\n\n private final CourseService courseService;\n\n private final AuthorizationCheckService authCheckService;\n\n private final Optional<ContinuousIntegrationService> continuousIntegrationService;\n\n private final Optional<VersionControlService> versionControlService;\n\n private final ExerciseService exerciseService;\n\n private final PlagiarismService plagiarismService;\n\n private final PlagiarismResultRepository plagiarismResultRepository;\n\n private final ProgrammingExerciseService programmingExerciseService;\n\n private final ProgrammingExerciseImportService programmingExerciseImportService;\n\n private final ProgrammingExerciseExportService programmingExerciseExportService;\n\n private final StudentParticipationRepository studentParticipationRepository;\n\n private final StaticCodeAnalysisService staticCodeAnalysisService;\n\n private final GradingCriterionRepository gradingCriterionRepository;\n\n private final ProgrammingLanguageFeatureService programmingLanguageFeatureService;\n\n private final TemplateUpgradePolicy templateUpgradePolicy;\n\n private final CourseRepository courseRepository;\n\n private final GitService gitService;\n\n /**\n * Java package name Regex according to Java 14 JLS (https://docs.oracle.com/javase/specs/jls/se14/html/jls-7.html#jls-7.4.1),\n * with the restriction to a-z,A-Z,_ as \"Java letter\" and 0-9 as digits due to JavaScript/Browser Unicode character class limitations\n */\n private static final String packageNameRegex = \"^(?!.*(?:\\\\.|^)(?:abstract|continue|for|new|switch|assert|default|if|package|synchronized|boolean|do|goto|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while|_|true|false|null)(?:\\\\.|$))[A-Z_a-z][0-9A-Z_a-z]*(?:\\\\.[A-Z_a-z][0-9A-Z_a-z]*)*$\";\n\n /**\n * Swift package name Regex derived from (https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID412),\n * with the restriction to a-z,A-Z as \"Swift letter\" and 0-9 as digits where no separators are allowed\n */\n private static final String packageNameRegexForSwift = \"^(?!(?:associatedtype|class|deinit|enum|extension|fileprivate|func|import|init|inout|internal|let|open|operator|private|protocol|public|rethrows|static|struct|subscript|typealias|var|break|case|continue|default|defer|do|else|fallthrough|for|guard|if|in|repeat|return|switch|where|while|as|Any|catch|false|is|nil|super|self|Self|throw|throws|true|try|_)$)[A-Za-z][0-9A-Za-z]*$\";\n\n private final Pattern packageNamePattern = Pattern.compile(packageNameRegex);\n\n private final Pattern packageNamePatternForSwift = Pattern.compile(packageNameRegexForSwift);\n\n public ProgrammingExerciseResource(ProgrammingExerciseRepository programmingExerciseRepository, UserRepository userRepository, AuthorizationCheckService authCheckService,\n CourseService courseService, Optional<ContinuousIntegrationService> continuousIntegrationService, Optional<VersionControlService> versionControlService,\n ExerciseService exerciseService, ProgrammingExerciseService programmingExerciseService, StudentParticipationRepository studentParticipationRepository,\n PlagiarismService plagiarismService, PlagiarismResultRepository plagiarismResultRepository, ProgrammingExerciseImportService programmingExerciseImportService,\n ProgrammingExerciseExportService programmingExerciseExportService, StaticCodeAnalysisService staticCodeAnalysisService,\n GradingCriterionRepository gradingCriterionRepository, ProgrammingLanguageFeatureService programmingLanguageFeatureService, TemplateUpgradePolicy templateUpgradePolicy,\n CourseRepository courseRepository, GitService gitService) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.userRepository = userRepository;\n this.courseService = courseService;\n this.authCheckService = authCheckService;\n this.continuousIntegrationService = continuousIntegrationService;\n this.versionControlService = versionControlService;\n this.exerciseService = exerciseService;\n this.plagiarismService = plagiarismService;\n this.programmingExerciseService = programmingExerciseService;\n this.studentParticipationRepository = studentParticipationRepository;\n this.plagiarismResultRepository = plagiarismResultRepository;\n this.programmingExerciseImportService = programmingExerciseImportService;\n this.programmingExerciseExportService = programmingExerciseExportService;\n this.staticCodeAnalysisService = staticCodeAnalysisService;\n this.gradingCriterionRepository = gradingCriterionRepository;\n this.programmingLanguageFeatureService = programmingLanguageFeatureService;\n this.templateUpgradePolicy = templateUpgradePolicy;\n this.courseRepository = courseRepository;\n this.gitService = gitService;\n }\n\n /**\n * @param exercise the exercise object we want to check for errors\n * @return the error message as response or null if everything is fine\n */\n private ResponseEntity<ProgrammingExercise> checkProgrammingExerciseForError(ProgrammingExercise exercise) {\n if (!continuousIntegrationService.get().checkIfBuildPlanExists(exercise.getProjectKey(), exercise.getTemplateBuildPlanId())) {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createFailureAlert(applicationName, true, \"exercise\", ErrorKeys.INVALID_TEMPLATE_BUILD_PLAN_ID, \"The Template Build Plan ID seems to be invalid.\"))\n .body(null);\n }\n if (exercise.getVcsTemplateRepositoryUrl() == null || !versionControlService.get().repositoryUrlIsValid(exercise.getVcsTemplateRepositoryUrl())) {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createFailureAlert(applicationName, true, \"exercise\", ErrorKeys.INVALID_TEMPLATE_REPOSITORY_URL, \"The Template Repository URL seems to be invalid.\"))\n .body(null);\n }\n if (exercise.getSolutionBuildPlanId() != null && !continuousIntegrationService.get().checkIfBuildPlanExists(exercise.getProjectKey(), exercise.getSolutionBuildPlanId())) {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createFailureAlert(applicationName, true, \"exercise\", ErrorKeys.INVALID_SOLUTION_BUILD_PLAN_ID, \"The Solution Build Plan ID seems to be invalid.\"))\n .body(null);\n }\n var solutionRepositoryUrl = exercise.getVcsSolutionRepositoryUrl();\n if (solutionRepositoryUrl != null && !versionControlService.get().repositoryUrlIsValid(solutionRepositoryUrl)) {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createFailureAlert(applicationName, true, \"exercise\", ErrorKeys.INVALID_SOLUTION_REPOSITORY_URL, \"The Solution Repository URL seems to be invalid.\"))\n .body(null);\n }\n return null;\n }\n\n /**\n * Validates the course and programming exercise short name.\n * 1. Check presence and length of exercise short name\n * 2. Check presence and length of course short name\n * 3. Find forbidden patterns in exercise short name\n * 4. Check that the short name doesn't already exist withing course or exam exercises\n *\n * @param programmingExercise Programming exercise to be validated\n * @param course Course of the programming exercise\n * @return Optional validation error response\n */\n private Optional<ResponseEntity<ProgrammingExercise>> validateCourseAndExerciseShortName(ProgrammingExercise programmingExercise, Course course) {\n // Check if exercise shortname is set\n if (programmingExercise.getShortName() == null || programmingExercise.getShortName().length() < 3) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"The shortname of the programming exercise is not set or too short\", \"programmingExerciseShortnameInvalid\"))\n .body(null));\n }\n\n // Check if course shortname is set\n if (course.getShortName() == null || course.getShortName().length() < 3) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"The shortname of the course is not set or too short\", \"courseShortnameInvalid\")).body(null));\n }\n\n // Check if exercise shortname matches regex\n Matcher shortNameMatcher = SHORT_NAME_PATTERN.matcher(programmingExercise.getShortName());\n if (!shortNameMatcher.matches()) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The shortname is invalid\", \"shortnameInvalid\")).body(null));\n }\n\n // NOTE: we have to cover two cases here: exercises directly stored in the course and exercises indirectly stored in the course (exercise -> exerciseGroup -> exam ->\n // course)\n long numberOfProgrammingExercisesWithSameShortName = programmingExerciseRepository.countByShortNameAndCourse(programmingExercise.getShortName(), course)\n + programmingExerciseRepository.countByShortNameAndExerciseGroupExamCourse(programmingExercise.getShortName(), course);\n if (numberOfProgrammingExercisesWithSameShortName > 0) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName,\n \"A programming exercise with the same short name already exists. Please choose a different short name.\", \"shortnameAlreadyExists\")).body(null));\n }\n return Optional.empty();\n }\n\n /**\n * Validate the general course settings.\n * 1. Validate the title\n * 2. Validate the course and programming exercise short name.\n *\n * @param programmingExercise Programming exercise to be validated\n * @param course Course of the programming exercise\n * @return Optional validation error response\n */\n private Optional<ResponseEntity<ProgrammingExercise>> validateCourseSettings(ProgrammingExercise programmingExercise, Course course) {\n // Validate exercise title\n Optional<ResponseEntity<ProgrammingExercise>> optionalTitleValidationError = validateTitle(programmingExercise, course);\n if (optionalTitleValidationError.isPresent()) {\n return optionalTitleValidationError;\n }\n\n // Validate course and exercise short name\n return validateCourseAndExerciseShortName(programmingExercise, course);\n }\n\n /**\n * Validate the programming exercise title.\n * 1. Check presence and length of exercise title\n * 2. Find forbidden patterns in exercise title\n *\n * @param programmingExercise Programming exercise to be validated\n * @param course Course of the programming exercise\n * @return Optional validation error response\n */\n private Optional<ResponseEntity<ProgrammingExercise>> validateTitle(ProgrammingExercise programmingExercise, Course course) {\n // Check if exercise title is set\n if (programmingExercise.getTitle() == null || programmingExercise.getTitle().length() < 3) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"The title of the programming exercise is too short\", \"programmingExerciseTitleInvalid\")).body(null));\n }\n\n // Check if the exercise title matches regex\n Matcher titleMatcher = TITLE_NAME_PATTERN.matcher(programmingExercise.getTitle());\n if (!titleMatcher.matches()) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The title is invalid\", \"titleInvalid\")).body(null));\n }\n\n // Check that the exercise title is unique among all programming exercises in the course, otherwise the corresponding project in the VCS system cannot be generated\n long numberOfProgrammingExercisesWithSameTitle = programmingExerciseRepository.countByTitleAndCourse(programmingExercise.getTitle(), course)\n + programmingExerciseRepository.countByTitleAndExerciseGroupExamCourse(programmingExercise.getTitle(), course);\n if (numberOfProgrammingExercisesWithSameTitle > 0) {\n return Optional.of(ResponseEntity.badRequest().headers(\n HeaderUtil.createAlert(applicationName, \"A programming exercise with the same title already exists. Please choose a different title.\", \"titleAlreadyExists\"))\n .body(null));\n }\n\n return Optional.empty();\n }\n\n /**\n * Validates general programming exercise settings\n * 1. Validate score settings\n * 2. Validates the participation mode\n * 3. Validates the programming language\n *\n * @param programmingExercise exercise to validate\n * @return Optional validation error response\n */\n private Optional<ResponseEntity<ProgrammingExercise>> validateGeneralSettings(ProgrammingExercise programmingExercise) {\n // Validate score settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalScoreSettingsError = exerciseService.validateScoreSettings(programmingExercise);\n if (optionalScoreSettingsError.isPresent()) {\n return optionalScoreSettingsError;\n }\n\n // Check if a participation mode was selected\n if (!Boolean.TRUE.equals(programmingExercise.isAllowOnlineEditor()) && !Boolean.TRUE.equals(programmingExercise.isAllowOfflineIde())) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName,\n \"You need to allow at least one participation mode, the online editor or the offline IDE\", \"noParticipationModeAllowed\")).body(null));\n }\n\n // Check if programming language is set\n if (programmingExercise.getProgrammingLanguage() == null) {\n return Optional.of(\n ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"No programming language was specified\", \"programmingLanguageNotSet\")).body(null));\n }\n return Optional.empty();\n }\n\n /**\n * Validates static code analysis settings\n * 1. The flag staticCodeAnalysisEnabled must not be null\n * 2. Static code analysis and sequential test runs can't be active at the same time\n * 3. Static code analysis can only be enabled for supported programming languages\n * 4. Static code analysis max penalty must only be set if static code analysis is enabled\n * 5. Static code analysis max penalty must be positive\n *\n * @param programmingExercise exercise to validate\n * @return Optional validation error response\n */\n private Optional<ResponseEntity<ProgrammingExercise>> validateStaticCodeAnalysisSettings(ProgrammingExercise programmingExercise) {\n ProgrammingLanguageFeature programmingLanguageFeature = programmingLanguageFeatureService.getProgrammingLanguageFeatures(programmingExercise.getProgrammingLanguage());\n\n // Check if the static code analysis flag was set\n if (programmingExercise.isStaticCodeAnalysisEnabled() == null) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"The static code analysis flag must be set to true or false\", \"staticCodeAnalysisFlagNotSet\")).body(null));\n }\n\n // Check that programming exercise doesn't have sequential test runs and static code analysis enabled\n if (Boolean.TRUE.equals(programmingExercise.isStaticCodeAnalysisEnabled()) && programmingExercise.hasSequentialTestRuns()) {\n return Optional.of(ResponseEntity.badRequest().headers(\n HeaderUtil.createAlert(applicationName, \"The static code analysis with sequential test runs is not supported at the moment\", \"staticCodeAnalysisAndSequential\"))\n .body(null));\n }\n\n // Check if the programming language supports static code analysis\n if (Boolean.TRUE.equals(programmingExercise.isStaticCodeAnalysisEnabled()) && !programmingLanguageFeature.isStaticCodeAnalysis()) {\n return Optional.of(ResponseEntity.badRequest().headers(\n HeaderUtil.createAlert(applicationName, \"The static code analysis is not supported for this programming language\", \"staticCodeAnalysisNotSupportedForLanguage\"))\n .body(null));\n }\n\n // Static code analysis max penalty must only be set if static code analysis is enabled\n if (Boolean.FALSE.equals(programmingExercise.isStaticCodeAnalysisEnabled()) && programmingExercise.getMaxStaticCodeAnalysisPenalty() != null) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName,\n \"Max static code analysis penalty must only be set if static code analysis is enabled\", \"staticCodeAnalysisDisabledButPenaltySet\")).body(null));\n }\n\n // Static code analysis max penalty must be positive\n if (programmingExercise.getMaxStaticCodeAnalysisPenalty() != null && programmingExercise.getMaxStaticCodeAnalysisPenalty() < 0) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"Max static code analysis penalty must be positive\", \"staticCodeAnalysisMaxPenaltyNegative\")).body(null));\n }\n return Optional.empty();\n }\n\n /**\n * POST /programming-exercises/setup : Setup a new programmingExercise (with all needed repositories etc.)\n *\n * @param programmingExercise the programmingExercise to setup\n * @return the ResponseEntity with status 201 (Created) and with body the new programmingExercise, or with status 400 (Bad Request) if the parameters are invalid\n */\n @PostMapping(Endpoints.SETUP)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<ProgrammingExercise> createProgrammingExercise(@RequestBody ProgrammingExercise programmingExercise) {\n log.debug(\"REST request to setup ProgrammingExercise : {}\", programmingExercise);\n if (programmingExercise.getId() != null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"A new programmingExercise cannot already have an ID\", \"idexists\")).body(null);\n }\n\n // Valid exercises have set either a course or an exerciseGroup\n programmingExercise.checkCourseAndExerciseGroupExclusivity(ENTITY_NAME);\n Course course = courseService.retrieveCourseOverExerciseGroupOrCourseId(programmingExercise);\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);\n\n // Validate general programming exercise settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalGeneralError = validateGeneralSettings(programmingExercise);\n if (optionalGeneralError.isPresent()) {\n return optionalGeneralError.get();\n }\n\n ProgrammingLanguageFeature programmingLanguageFeature = programmingLanguageFeatureService.getProgrammingLanguageFeatures(programmingExercise.getProgrammingLanguage());\n\n // Check if package name is set\n if (programmingLanguageFeature.isPackageNameRequired()) {\n if (programmingExercise.getPackageName() == null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The package name is invalid\", \"packagenameInvalid\")).body(null);\n }\n\n // Check if package name matches regex\n Matcher packageNameMatcher;\n if (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.SWIFT) {\n packageNameMatcher = packageNamePatternForSwift.matcher(programmingExercise.getPackageName());\n }\n else {\n packageNameMatcher = packageNamePattern.matcher(programmingExercise.getPackageName());\n }\n if (!packageNameMatcher.matches()) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The package name is invalid\", \"packagenameInvalid\")).body(null);\n }\n }\n\n // Check if project type is selected\n if (programmingLanguageFeature.getProjectTypes().size() > 0) {\n if (programmingExercise.getProjectType() == null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The project type is not set\", \"projectTypeNotSet\")).body(null);\n }\n if (!programmingLanguageFeature.getProjectTypes().contains(programmingExercise.getProjectType())) {\n return ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName, \"The project type is not supported for this programming language\", \"projectTypeNotSupported\")).body(null);\n }\n }\n else {\n if (programmingExercise.getProjectType() != null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, \"The project type is set but not supported\", \"projectTypeSet\")).body(null);\n }\n }\n\n // Check if checkout solution repository is enabled\n if (programmingExercise.getCheckoutSolutionRepository() && !programmingLanguageFeature.isCheckoutSolutionRepositoryAllowed()) {\n return ResponseEntity.badRequest()\n .headers(\n HeaderUtil.createAlert(applicationName, \"Checking out the solution repository is only supported for Haskell exercises\", \"checkoutSolutionNotSupported\"))\n .body(null);\n }\n\n // Validate course settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalCourseError = validateCourseSettings(programmingExercise, course);\n if (optionalCourseError.isPresent()) {\n return optionalCourseError.get();\n }\n\n // Validate static code analysis settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalStaticCodeAnalysisError = validateStaticCodeAnalysisSettings(programmingExercise);\n if (optionalStaticCodeAnalysisError.isPresent()) {\n return optionalStaticCodeAnalysisError.get();\n }\n\n programmingExercise.generateAndSetProjectKey();\n Optional<ResponseEntity<ProgrammingExercise>> projectExistsError = checkIfProjectExists(programmingExercise);\n if (projectExistsError.isPresent()) {\n return projectExistsError.get();\n }\n\n try {\n // Setup all repositories etc\n ProgrammingExercise newProgrammingExercise = programmingExerciseService.createProgrammingExercise(programmingExercise);\n // Create default static code analysis categories\n if (Boolean.TRUE.equals(programmingExercise.isStaticCodeAnalysisEnabled())) {\n staticCodeAnalysisService.createDefaultCategories(newProgrammingExercise);\n }\n return ResponseEntity.created(new URI(\"/api/programming-exercises\" + newProgrammingExercise.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, newProgrammingExercise.getTitle())).body(newProgrammingExercise);\n }\n catch (IOException | URISyntaxException | InterruptedException | GitAPIException | ContinuousIntegrationException e) {\n log.error(\"Error while setting up programming exercise\", e);\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)\n .headers(HeaderUtil.createAlert(applicationName, \"An error occurred while setting up the exercise: \" + e.getMessage(), \"errorProgrammingExercise\")).body(null);\n }\n }\n\n /**\n * Checks if the project for the given programming exercise already exists in the version control system (VCS) and in the continuous integration system (CIS).\n * The check is done based on the project key (course short name + exercise short name) and the project name (course short name + exercise title).\n * This prevents errors then the actual projects will be generated later on.\n * An error response is returned in case the project does already exist. This will then e.g. stop the generation (or import) of the programming exercise.\n *\n * @param programmingExercise a typically new programming exercise for which the corresponding VCS and CIS projects should not yet exist.\n * @return an error response in case the project already exists or an empty optional in case it does not exist yet (which means the setup can continue as usual)\n */\n public Optional<ResponseEntity<ProgrammingExercise>> checkIfProjectExists(ProgrammingExercise programmingExercise) {\n String projectKey = programmingExercise.getProjectKey();\n String projectName = programmingExercise.getProjectName();\n boolean projectExists = versionControlService.get().checkIfProjectExists(projectKey, projectName);\n if (projectExists) {\n return Optional.of(ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName,\n \"Project already exists on the Version Control Server: \" + projectName + \". Please choose a different title and short name!\", \"vcsProjectExists\"))\n .body(null));\n }\n\n String errorMessageCI = continuousIntegrationService.get().checkIfProjectExists(projectKey, projectName);\n if (errorMessageCI != null) {\n return Optional.of(ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName, errorMessageCI, \"ciProjectExists\")).body(null));\n }\n // means the project does not exist in version control server and does not exist in continuous integration server\n return Optional.empty();\n }\n\n /**\n * POST /programming-exercises/import: Imports an existing programming exercise into an existing course\n * <p>\n * This will import the whole exercise, including all base build plans (template, solution) and repositories\n * (template, solution, test). Referenced entities, s.a. the test cases or the hints will get cloned and assigned\n * a new id. For a concrete list of what gets copied and what not have a look\n * at {@link ProgrammingExerciseImportService#importProgrammingExerciseBasis(ProgrammingExercise, ProgrammingExercise)}\n *\n * @param sourceExerciseId The ID of the original exercise which should get imported\n * @param newExercise The new exercise containing values that should get overwritten in the imported exercise, s.a. the title or difficulty\n * @param recreateBuildPlans Option determining whether the build plans should be copied or re-created from scratch\n * @param updateTemplate Option determining whether the template files should be updated with the most recent template version\n * @return The imported exercise (200), a not found error (404) if the template does not exist, or a forbidden error\n * (403) if the user is not at least an instructor in the target course.\n * @see ProgrammingExerciseImportService#importProgrammingExerciseBasis(ProgrammingExercise, ProgrammingExercise)\n * @see ProgrammingExerciseImportService#importBuildPlans(ProgrammingExercise, ProgrammingExercise)\n * @see ProgrammingExerciseImportService#importRepositories(ProgrammingExercise, ProgrammingExercise)\n */\n @PostMapping(Endpoints.IMPORT)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<ProgrammingExercise> importProgrammingExercise(@PathVariable long sourceExerciseId, @RequestBody ProgrammingExercise newExercise,\n @RequestParam(defaultValue = \"false\") boolean recreateBuildPlans, @RequestParam(defaultValue = \"false\") boolean updateTemplate) {\n if (sourceExerciseId < 0) {\n return badRequest();\n }\n\n // Valid exercises have set either a course or an exerciseGroup\n newExercise.checkCourseAndExerciseGroupExclusivity(ENTITY_NAME);\n\n log.debug(\"REST request to import programming exercise {} into course {}\", sourceExerciseId, newExercise.getCourseViaExerciseGroupOrCourseMember().getId());\n\n // Validate general programming exercise settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalGeneralError = validateGeneralSettings(newExercise);\n if (optionalGeneralError.isPresent()) {\n return optionalGeneralError.get();\n }\n\n // Validate static code analysis settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalStaticCodeAnalysisError = validateStaticCodeAnalysisSettings(newExercise);\n if (optionalStaticCodeAnalysisError.isPresent()) {\n return optionalStaticCodeAnalysisError.get();\n }\n\n final var user = userRepository.getUserWithGroupsAndAuthorities();\n Course course = courseService.retrieveCourseOverExerciseGroupOrCourseId(newExercise);\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, user);\n\n // Validate course settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalCourseError = validateCourseSettings(newExercise, course);\n if (optionalCourseError.isPresent()) {\n return optionalCourseError.get();\n }\n\n final var optionalOriginalProgrammingExercise = programmingExerciseRepository\n .findByIdWithEagerTestCasesStaticCodeAnalysisCategoriesHintsAndTemplateAndSolutionParticipations(sourceExerciseId);\n if (optionalOriginalProgrammingExercise.isEmpty()) {\n return notFound();\n }\n final var originalProgrammingExercise = optionalOriginalProgrammingExercise.get();\n\n // The static code analysis flag can only change, if the build plans are recreated and the template is upgraded\n if (newExercise.isStaticCodeAnalysisEnabled() != originalProgrammingExercise.isStaticCodeAnalysisEnabled() && !(recreateBuildPlans && updateTemplate)) {\n throw new BadRequestAlertException(\"Static code analysis can only change, if the recreation of build plans and update of template files is activated\", ENTITY_NAME,\n \"staticCodeAnalysisCannotChange\");\n }\n\n // Check if the user has the rights to access the original programming exercise\n Course originalCourse = courseService.retrieveCourseOverExerciseGroupOrCourseId(originalProgrammingExercise);\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, originalCourse, user);\n\n newExercise.generateAndSetProjectKey();\n Optional<ResponseEntity<ProgrammingExercise>> projectExistsError = checkIfProjectExists(newExercise);\n if (projectExistsError.isPresent()) {\n return projectExistsError.get();\n }\n\n final var importedProgrammingExercise = programmingExerciseImportService.importProgrammingExerciseBasis(originalProgrammingExercise, newExercise);\n HttpHeaders responseHeaders;\n programmingExerciseImportService.importRepositories(originalProgrammingExercise, importedProgrammingExercise);\n\n // Update the template files\n if (updateTemplate) {\n TemplateUpgradeService upgradeService = templateUpgradePolicy.getUpgradeService(importedProgrammingExercise.getProgrammingLanguage());\n upgradeService.upgradeTemplate(importedProgrammingExercise);\n }\n\n // Copy or recreate the build plans\n try {\n if (recreateBuildPlans) {\n // Create completely new build plans for the exercise\n programmingExerciseService.setupBuildPlansForNewExercise(importedProgrammingExercise);\n }\n else {\n // We have removed the automatic build trigger from test to base for new programming exercises.\n // We also remove this build trigger in the case of an import as the source exercise might still have this trigger.\n // The importBuildPlans method includes this process\n programmingExerciseImportService.importBuildPlans(originalProgrammingExercise, importedProgrammingExercise);\n }\n responseHeaders = HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, importedProgrammingExercise.getTitle());\n }\n catch (Exception e) {\n responseHeaders = HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"importExerciseTriggerPlanFail\", \"Unable to trigger imported build plans\");\n }\n\n programmingExerciseService.scheduleOperations(importedProgrammingExercise.getId());\n\n // Remove unnecessary fields\n importedProgrammingExercise.setTestCases(null);\n importedProgrammingExercise.setStaticCodeAnalysisCategories(null);\n importedProgrammingExercise.setTemplateParticipation(null);\n importedProgrammingExercise.setSolutionParticipation(null);\n importedProgrammingExercise.setExerciseHints(null);\n\n return ResponseEntity.ok().headers(responseHeaders).body(importedProgrammingExercise);\n }\n\n /**\n * PUT /programming-exercises : Updates an existing updatedProgrammingExercise.\n *\n * @param updatedProgrammingExercise the programmingExercise that has been updated on the client\n * @param notificationText to notify the student group about the update on the programming exercise\n * @return the ResponseEntity with status 200 (OK) and with body the updated ProgrammingExercise, or with status 400 (Bad Request) if the updated ProgrammingExercise\n * is not valid, or with status 500 (Internal Server Error) if the updated ProgrammingExercise couldn't be saved to the database\n */\n @PutMapping(Endpoints.PROGRAMMING_EXERCISES)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<ProgrammingExercise> updateProgrammingExercise(@RequestBody ProgrammingExercise updatedProgrammingExercise,\n @RequestParam(value = \"notificationText\", required = false) String notificationText) {\n log.debug(\"REST request to update ProgrammingExercise : {}\", updatedProgrammingExercise);\n if (updatedProgrammingExercise.getId() == null) {\n return badRequest();\n }\n\n // Valid exercises have set either a course or an exerciseGroup\n updatedProgrammingExercise.checkCourseAndExerciseGroupExclusivity(ENTITY_NAME);\n\n // Validate static code analysis settings\n Optional<ResponseEntity<ProgrammingExercise>> optionalStaticCodeAnalysisError = validateStaticCodeAnalysisSettings(updatedProgrammingExercise);\n if (optionalStaticCodeAnalysisError.isPresent()) {\n return optionalStaticCodeAnalysisError.get();\n }\n\n // fetch course from database to make sure client didn't change groups\n Course course = courseService.retrieveCourseOverExerciseGroupOrCourseId(updatedProgrammingExercise);\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.INSTRUCTOR, course, null);\n\n ResponseEntity<ProgrammingExercise> errorResponse = checkProgrammingExerciseForError(updatedProgrammingExercise);\n if (errorResponse != null) {\n return errorResponse;\n }\n\n var existingProgrammingExercise = programmingExerciseRepository.findById(updatedProgrammingExercise.getId());\n if (existingProgrammingExercise.isEmpty()) {\n throw new EntityNotFoundException(\"Cannot update a programming exercise that does not exist in the database\");\n }\n if (!Objects.equals(existingProgrammingExercise.get().getShortName(), updatedProgrammingExercise.getShortName())) {\n throw new BadRequestAlertException(\"The programming exercise short name cannot be changed\", ENTITY_NAME, \"shortNameCannotChange\");\n }\n if (existingProgrammingExercise.get().isStaticCodeAnalysisEnabled() != updatedProgrammingExercise.isStaticCodeAnalysisEnabled()) {\n throw new BadRequestAlertException(\"Static code analysis enabled flag must not be changed\", ENTITY_NAME, \"staticCodeAnalysisCannotChange\");\n }\n if (!Boolean.TRUE.equals(updatedProgrammingExercise.isAllowOnlineEditor()) && !Boolean.TRUE.equals(updatedProgrammingExercise.isAllowOfflineIde())) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName,\n \"You need to allow at least one participation mode, the online editor or the offline IDE\", \"noParticipationModeAllowed\")).body(null);\n }\n\n if (updatedProgrammingExercise.getBonusPoints() == null) {\n // make sure the default value is set properly\n updatedProgrammingExercise.setBonusPoints(0.0);\n }\n\n // TODO: if isAllowOfflineIde changes, we might want to change access for all existing student participations\n // false --> true: add access for students to all existing student participations\n // true --> false: remove access for students from all existing student participations\n\n // Forbid conversion between normal course exercise and exam exercise\n exerciseService.checkForConversionBetweenExamAndCourseExercise(updatedProgrammingExercise, existingProgrammingExercise.get(), ENTITY_NAME);\n\n // Only save after checking for errors\n ProgrammingExercise savedProgrammingExercise = programmingExerciseService.updateProgrammingExercise(updatedProgrammingExercise, notificationText);\n\n exerciseService.updatePointsInRelatedParticipantScores(existingProgrammingExercise.get(), updatedProgrammingExercise);\n\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, updatedProgrammingExercise.getTitle()))\n .body(savedProgrammingExercise);\n }\n\n /**\n * PUT /programming-exercises/timeline : Updates the timeline attributes of a given exercise\n * @param updatedProgrammingExercise containing the changes that have to be saved\n * @param notificationText an optional text to notify the student group about the update on the programming exercise\n * @return the ResponseEntity with status 200 (OK) with the updated ProgrammingExercise, or with status 403 (Forbidden)\n * if the user is not allowed to update the exercise or with 404 (Not Found) if the updated ProgrammingExercise couldn't be found in the database\n */\n @PutMapping(Endpoints.TIMELINE)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<ProgrammingExercise> updateProgrammingExerciseTimeline(@RequestBody ProgrammingExercise updatedProgrammingExercise,\n @RequestParam(value = \"notificationText\", required = false) String notificationText) {\n log.debug(\"REST request to update the timeline of ProgrammingExercise : {}\", updatedProgrammingExercise);\n var existingProgrammingExercise = programmingExerciseRepository.findByIdElseThrow(updatedProgrammingExercise.getId());\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, existingProgrammingExercise, null);\n updatedProgrammingExercise = programmingExerciseService.updateTimeline(updatedProgrammingExercise, notificationText);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, updatedProgrammingExercise.getTitle()))\n .body(updatedProgrammingExercise);\n\n }\n\n /**\n * PATCH /programming-exercises-problem: Updates the problem statement of the exercise.\n *\n * @param exerciseId The ID of the exercise for which to change the problem statement\n * @param updatedProblemStatement The new problemStatement\n * @param notificationText to notify the student group about the updated problemStatement on the programming exercise\n * @return the ResponseEntity with status 200 (OK) and with body the updated problemStatement, with status 404 if the programmingExercise could not be found, or with 403 if the user does not have permissions to access the programming exercise.\n */\n @PatchMapping(value = Endpoints.PROBLEM)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<ProgrammingExercise> updateProblemStatement(@PathVariable long exerciseId, @RequestBody String updatedProblemStatement,\n @RequestParam(value = \"notificationText\", required = false) String notificationText) {\n log.debug(\"REST request to update ProgrammingExercise with new problem statement: {}\", updatedProblemStatement);\n var updatedProgrammingExercise = programmingExerciseService.updateProblemStatement(exerciseId, updatedProblemStatement, notificationText);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, updatedProgrammingExercise.getTitle()))\n .body(updatedProgrammingExercise);\n }\n\n /**\n * GET /courses/:courseId/programming-exercises : get all the programming exercises.\n *\n * @param courseId of the course for which the exercise should be fetched\n * @return the ResponseEntity with status 200 (OK) and the list of programmingExercises in body\n */\n @GetMapping(Endpoints.GET_FOR_COURSE)\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<List<ProgrammingExercise>> getProgrammingExercisesForCourse(@PathVariable Long courseId) {\n log.debug(\"REST request to get all ProgrammingExercises for the course with id : {}\", courseId);\n Course course = courseRepository.findByIdElseThrow(courseId);\n authCheckService.checkHasAtLeastRoleInCourseElseThrow(Role.TEACHING_ASSISTANT, course, null);\n List<ProgrammingExercise> exercises = programmingExerciseRepository.findByCourseIdWithLatestResultForTemplateSolutionParticipations(courseId);\n for (ProgrammingExercise exercise : exercises) {\n // not required in the returned json body\n exercise.setStudentParticipations(null);\n exercise.setCourse(null);\n }\n return ResponseEntity.ok().body(exercises);\n }\n\n /**\n * GET /programming-exercises/:exerciseId : get the \"exerciseId\" programmingExercise.\n *\n * @param exerciseId the id of the programmingExercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the programmingExercise, or with status 404 (Not Found)\n */\n @GetMapping(Endpoints.PROGRAMMING_EXERCISE)\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<ProgrammingExercise> getProgrammingExercise(@PathVariable long exerciseId) {\n // TODO: Split this route in two: One for normal and one for exam exercises\n log.debug(\"REST request to get ProgrammingExercise : {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesElseThrow(exerciseId);\n // Fetch grading criterion into exercise of participation\n List<GradingCriterion> gradingCriteria = gradingCriterionRepository.findByExerciseIdWithEagerGradingCriteria(programmingExercise.getId());\n programmingExercise.setGradingCriteria(gradingCriteria);\n // If the exercise belongs to an exam, only instructors and admins are allowed to access it, otherwise also TA have access\n if (programmingExercise.isExamExercise()) {\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n }\n else {\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, null);\n }\n return ResponseEntity.ok().body(programmingExercise);\n }\n\n /**\n * GET /programming-exercises/:exerciseId/with-participations/ : get the \"exerciseId\" programmingExercise.\n *\n * @param exerciseId the id of the programmingExercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the programmingExercise, or with status 404 (Not Found)\n */\n @GetMapping(Endpoints.PROGRAMMING_EXERCISE_WITH_PARTICIPATIONS)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<ProgrammingExercise> getProgrammingExerciseWithSetupParticipations(@PathVariable long exerciseId) {\n log.debug(\"REST request to get ProgrammingExercise : {}\", exerciseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationLatestResultElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, user);\n var assignmentParticipation = studentParticipationRepository.findByExerciseIdAndStudentIdWithLatestResult(programmingExercise.getId(), user.getId());\n Set<StudentParticipation> participations = new HashSet<>();\n assignmentParticipation.ifPresent(participations::add);\n programmingExercise.setStudentParticipations(participations);\n return ResponseEntity.ok(programmingExercise);\n }\n\n /**\n * GET /programming-exercises/:exerciseId/with-template-and-solution-participation\n *\n * @param exerciseId the id of the programmingExercise to retrieve\n * @param withSubmissionResults get all submission results\n * @return the ResponseEntity with status 200 (OK) and the programming exercise with template and solution participation, or with status 404 (Not Found)\n */\n @GetMapping(Endpoints.PROGRAMMING_EXERCISE_WITH_TEMPLATE_AND_SOLUTION_PARTICIPATION)\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<ProgrammingExercise> getProgrammingExerciseWithTemplateAndSolutionParticipation(@PathVariable long exerciseId,\n @RequestParam(defaultValue = \"false\") boolean withSubmissionResults) {\n log.debug(\"REST request to get programming exercise with template and solution participation : {}\", exerciseId);\n ProgrammingExercise programmingExercise;\n if (withSubmissionResults) {\n programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationSubmissionsAndResultsElseThrow(exerciseId);\n }\n else {\n programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationElseThrow(exerciseId);\n }\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, null);\n return ResponseEntity.ok(programmingExercise);\n }\n\n /**\n * DELETE /programming-exercises/:id : delete the \"id\" programmingExercise.\n *\n * @param exerciseId the id of the programmingExercise to delete\n * @param deleteStudentReposBuildPlans boolean which states whether the corresponding build plan should be deleted as well\n * @param deleteBaseReposBuildPlans the ResponseEntity with status 200 (OK)\n * @return the ResponseEntity with status 200 (OK) when programming exercise has been successfully deleted or with status 404 (Not Found)\n */\n @DeleteMapping(Endpoints.PROGRAMMING_EXERCISE)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Void> deleteProgrammingExercise(@PathVariable long exerciseId, @RequestParam(defaultValue = \"false\") boolean deleteStudentReposBuildPlans,\n @RequestParam(defaultValue = \"false\") boolean deleteBaseReposBuildPlans) {\n log.info(\"REST request to delete ProgrammingExercise : {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesElseThrow(exerciseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, user);\n exerciseService.logDeletion(programmingExercise, programmingExercise.getCourseViaExerciseGroupOrCourseMember(), user);\n exerciseService.delete(exerciseId, deleteStudentReposBuildPlans, deleteBaseReposBuildPlans);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, programmingExercise.getTitle())).build();\n }\n\n /**\n * Combine all commits into one in the template repository of a given exercise.\n *\n * @param exerciseId of the exercise\n * @return the ResponseEntity with status\n * 200 (OK) if combine has been successfully executed\n * 403 (Forbidden) if the user is not admin and course instructor or\n * 500 (Internal Server Error)\n */\n @PutMapping(value = Endpoints.COMBINE_COMMITS, produces = MediaType.TEXT_PLAIN_VALUE)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Void> combineTemplateRepositoryCommits(@PathVariable long exerciseId) {\n log.debug(\"REST request to combine the commits of the template repository of ProgrammingExercise with id: {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n try {\n var exerciseRepoURL = programmingExercise.getVcsTemplateRepositoryUrl();\n gitService.combineAllCommitsOfRepositoryIntoOne(exerciseRepoURL);\n return new ResponseEntity<>(HttpStatus.OK);\n }\n catch (IllegalStateException | InterruptedException | GitAPIException ex) {\n return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);\n }\n }\n\n /**\n * POST /programming-exercises/:exerciseId/export-instructor-repository/:repositoryType : sends a test, solution or template repository as a zip file\n * @param exerciseId The id of the programming exercise\n * @param repositoryType The type of repository to zip and send\n * @return ResponseEntity with status\n * @throws IOException if something during the zip process went wrong\n */\n @GetMapping(Endpoints.EXPORT_INSTRUCTOR_REPOSITORY)\n @PreAuthorize(\"hasRole('TA')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Resource> exportInstructorRepository(@PathVariable long exerciseId, @PathVariable RepositoryType repositoryType) throws IOException {\n var programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, null);\n\n long start = System.nanoTime();\n File zipFile = programmingExerciseExportService.exportInstructorRepositoryForExercise(programmingExercise.getId(), repositoryType, new ArrayList<>());\n if (zipFile == null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"internalServerError\",\n \"There was an error on the server and the zip file could not be created.\")).body(null);\n }\n\n InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));\n\n log.info(\"Export of the repository of type {} programming exercise {} with title '{}' was successful in {}.\", repositoryType.getName(), programmingExercise.getId(),\n programmingExercise.getTitle(), formatDurationFrom(start));\n\n return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header(\"filename\", zipFile.getName()).body(resource);\n }\n\n /**\n * POST /programming-exercises/:exerciseId/export-repos-by-participant-identifiers/:participantIdentifiers : sends all submissions from participantIdentifiers as zip\n *\n * @param exerciseId the id of the exercise to get the repos from\n * @param participantIdentifiers the identifiers of the participants (student logins or team short names) for whom to zip the submissions, separated by commas\n * @param repositoryExportOptions the options that should be used for the export\n * @return ResponseEntity with status\n * @throws IOException if something during the zip process went wrong\n */\n @PostMapping(Endpoints.EXPORT_SUBMISSIONS_BY_PARTICIPANTS)\n @PreAuthorize(\"hasRole('TA')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Resource> exportSubmissionsByStudentLogins(@PathVariable long exerciseId, @PathVariable String participantIdentifiers,\n @RequestBody RepositoryExportOptionsDTO repositoryExportOptions) throws IOException {\n var programmingExercise = programmingExerciseRepository.findByIdWithStudentParticipationsAndLegalSubmissionsElseThrow(exerciseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, user);\n if (repositoryExportOptions.isExportAllParticipants()) {\n // only instructors are allowed to download all repos\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, user);\n }\n\n if (repositoryExportOptions.getFilterLateSubmissionsDate() == null) {\n repositoryExportOptions.setFilterLateSubmissionsDate(programmingExercise.getDueDate());\n }\n\n List<String> participantIdentifierList = new ArrayList<>();\n if (!repositoryExportOptions.isExportAllParticipants()) {\n participantIdentifiers = participantIdentifiers.replaceAll(\"\\\\s+\", \"\");\n participantIdentifierList = Arrays.asList(participantIdentifiers.split(\",\"));\n }\n\n // Select the participations that should be exported\n List<ProgrammingExerciseStudentParticipation> exportedStudentParticipations = new ArrayList<>();\n for (StudentParticipation studentParticipation : programmingExercise.getStudentParticipations()) {\n ProgrammingExerciseStudentParticipation programmingStudentParticipation = (ProgrammingExerciseStudentParticipation) studentParticipation;\n if (repositoryExportOptions.isExportAllParticipants() || (programmingStudentParticipation.getRepositoryUrl() != null && studentParticipation.getParticipant() != null\n && participantIdentifierList.contains(studentParticipation.getParticipantIdentifier()))) {\n exportedStudentParticipations.add(programmingStudentParticipation);\n }\n }\n return provideZipForParticipations(exportedStudentParticipations, programmingExercise, repositoryExportOptions);\n }\n\n /**\n * POST /programming-exercises/:exerciseId/export-repos-by-participation-ids/:participationIds : sends all submissions from participation ids as zip\n *\n * @param exerciseId the id of the exercise to get the repos from\n * @param participationIds the participationIds seperated via semicolon to get their submissions (used for double blind assessment)\n * @param repositoryExportOptions the options that should be used for the export. Export all students is not supported here!\n * @return ResponseEntity with status\n * @throws IOException if submissions can't be zippedRequestBody\n */\n @PostMapping(Endpoints.EXPORT_SUBMISSIONS_BY_PARTICIPATIONS)\n @PreAuthorize(\"hasRole('TA')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Resource> exportSubmissionsByParticipationIds(@PathVariable long exerciseId, @PathVariable String participationIds,\n @RequestBody RepositoryExportOptionsDTO repositoryExportOptions) throws IOException {\n var programmingExercise = programmingExerciseRepository.findByIdWithStudentParticipationsAndLegalSubmissionsElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, null);\n if (repositoryExportOptions.getFilterLateSubmissionsDate() == null) {\n repositoryExportOptions.setFilterLateSubmissionsDate(programmingExercise.getDueDate());\n }\n\n var participationIdSet = new ArrayList<>(Arrays.asList(participationIds.split(\",\"))).stream().map(String::trim).map(Long::parseLong).collect(Collectors.toSet());\n\n // Select the participations that should be exported\n List<ProgrammingExerciseStudentParticipation> exportedStudentParticipations = programmingExercise.getStudentParticipations().stream()\n .filter(participation -> participationIdSet.contains(participation.getId())).map(participation -> (ProgrammingExerciseStudentParticipation) participation)\n .collect(Collectors.toList());\n return provideZipForParticipations(exportedStudentParticipations, programmingExercise, repositoryExportOptions);\n }\n\n private ResponseEntity<Resource> provideZipForParticipations(@NotNull List<ProgrammingExerciseStudentParticipation> exportedStudentParticipations,\n ProgrammingExercise programmingExercise, RepositoryExportOptionsDTO repositoryExportOptions) throws IOException {\n\n long start = System.nanoTime();\n\n // TODO: in case we do not find participations for the given ids, we should inform the user in the client, that the student did not participate in the exercise.\n if (exportedStudentParticipations.isEmpty()) {\n return ResponseEntity.badRequest()\n .headers(HeaderUtil.createFailureAlert(applicationName, false, ENTITY_NAME, \"noparticipations\", \"No existing user was specified or no submission exists.\"))\n .body(null);\n }\n\n File zipFile = programmingExerciseExportService.exportStudentRepositoriesToZipFile(programmingExercise.getId(), exportedStudentParticipations, repositoryExportOptions);\n if (zipFile == null) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"internalServerError\",\n \"There was an error on the server and the zip file could not be created.\")).body(null);\n }\n\n InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));\n\n log.info(\"Export {} student repositories of programming exercise {} with title '{}' was successful in {}.\", exportedStudentParticipations.size(),\n programmingExercise.getId(), programmingExercise.getTitle(), formatDurationFrom(start));\n\n return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header(\"filename\", zipFile.getName()).body(resource);\n }\n\n /**\n * PUT /programming-exercises/{exerciseId}/generate-tests : Makes a call to StructureOracleGenerator to generate the structure oracle aka the test.json file\n *\n * @param exerciseId The ID of the programming exercise for which the structure oracle should get generated\n * @return The ResponseEntity with status 201 (Created) or with status 400 (Bad Request) if the parameters are invalid\n */\n @PutMapping(value = Endpoints.GENERATE_TESTS, produces = MediaType.TEXT_PLAIN_VALUE)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<String> generateStructureOracleForExercise(@PathVariable long exerciseId) {\n log.debug(\"REST request to generate the structure oracle for ProgrammingExercise with id: {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesElseThrow(exerciseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, user);\n if (programmingExercise.getPackageName() == null || programmingExercise.getPackageName().length() < 3) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createAlert(applicationName,\n \"This is a linked exercise and generating the structure oracle for this exercise is not possible.\", \"couldNotGenerateStructureOracle\")).body(null);\n }\n\n var solutionRepoURL = programmingExercise.getVcsSolutionRepositoryUrl();\n var exerciseRepoURL = programmingExercise.getVcsTemplateRepositoryUrl();\n var testRepoURL = programmingExercise.getVcsTestRepositoryUrl();\n\n try {\n String testsPath = Paths.get(\"test\", programmingExercise.getPackageFolderName()).toString();\n // Atm we only have one folder that can have structural tests, but this could change.\n testsPath = programmingExercise.hasSequentialTestRuns() ? Paths.get(\"structural\", testsPath).toString() : testsPath;\n boolean didGenerateOracle = programmingExerciseService.generateStructureOracleFile(solutionRepoURL, exerciseRepoURL, testRepoURL, testsPath, user);\n\n if (didGenerateOracle) {\n HttpHeaders responseHeaders = new HttpHeaders();\n responseHeaders.setContentType(MediaType.TEXT_PLAIN);\n return new ResponseEntity<>(\"Successfully generated the structure oracle for the exercise \" + programmingExercise.getProjectName(), responseHeaders, HttpStatus.OK);\n }\n else {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createAlert(applicationName, \"Did not update the oracle because there have not been any changes to it.\", \"didNotGenerateStructureOracle\"))\n .body(null);\n }\n }\n catch (Exception e) {\n return ResponseEntity.badRequest()\n .headers(HeaderUtil.createAlert(applicationName,\n \"An error occurred while generating the structure oracle for the exercise \" + programmingExercise.getProjectName() + \": \\n\" + e.getMessage(),\n \"errorStructureOracleGeneration\"))\n .body(null);\n }\n }\n\n /**\n * GET /programming-exercises/:exerciseId/test-case-state : Returns a DTO that offers information on the test case state of the programming exercise.\n *\n * @param exerciseId the id of a ProgrammingExercise\n * @return the ResponseEntity with status 200 (OK) and ProgrammingExerciseTestCaseStateDTO. Returns 404 (notFound) if the exercise does not exist.\n */\n @GetMapping(Endpoints.TEST_CASE_STATE)\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<ProgrammingExerciseTestCaseStateDTO> hasAtLeastOneStudentResult(@PathVariable long exerciseId) {\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, programmingExercise, null);\n boolean hasAtLeastOneStudentResult = programmingExerciseService.hasAtLeastOneStudentResult(programmingExercise);\n boolean isReleased = programmingExercise.isReleased();\n ProgrammingExerciseTestCaseStateDTO testCaseDTO = new ProgrammingExerciseTestCaseStateDTO().released(isReleased).studentResult(hasAtLeastOneStudentResult)\n .testCasesChanged(programmingExercise.getTestCasesChanged())\n .buildAndTestStudentSubmissionsAfterDueDate(programmingExercise.getBuildAndTestStudentSubmissionsAfterDueDate());\n return ResponseEntity.ok(testCaseDTO);\n }\n\n /**\n * Search for all programming exercises by title and course title. The result is pageable since there might be hundreds of exercises in the DB.\n *\n * @param search The pageable search containing the page size, page number and query string\n * @return The desired page, sorted and matching the given query\n */\n @GetMapping(Endpoints.PROGRAMMING_EXERCISES)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<SearchResultPageDTO<ProgrammingExercise>> getAllExercisesOnPage(PageableSearchDTO<String> search) {\n final var user = userRepository.getUserWithGroupsAndAuthorities();\n return ResponseEntity.ok(programmingExerciseService.getAllOnPageWithSize(search, user));\n }\n\n /**\n * GET /programming-exercises/{exerciseId}/plagiarism-result\n * <p>\n * Return the latest plagiarism result or null, if no plagiarism was detected for this exercise yet.\n *\n * @param exerciseId ID of the programming exercise for which the plagiarism result should be returned\n * @return The ResponseEntity with status 200 (Ok) or with status 400 (Bad Request) if the parameters are invalid\n */\n @GetMapping(Endpoints.PLAGIARISM_RESULT)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<TextPlagiarismResult> getPlagiarismResult(@PathVariable long exerciseId) {\n log.debug(\"REST request to get the latest plagiarism result for the programming exercise with id: {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n var plagiarismResult = plagiarismResultRepository.findFirstByExerciseIdOrderByLastModifiedDateDescElseThrow(programmingExercise.getId());\n return ResponseEntity.ok((TextPlagiarismResult) plagiarismResult);\n }\n\n /**\n * GET /programming-exercises/{exerciseId}/check-plagiarism\n * <p>\n * Start the automated plagiarism detection for the given exercise and return its result.\n *\n * @param exerciseId The ID of the programming exercise for which the plagiarism check should be executed\n * @param similarityThreshold ignore comparisons whose similarity is below this threshold (%)\n * @param minimumScore consider only submissions whose score is greater or equal to this value\n * @return The ResponseEntity with status 201 (Created) or with status 400 (Bad Request) if the parameters are invalid\n * @throws ExitException is thrown if JPlag exits unexpectedly\n * @throws IOException is thrown for file handling errors\n */\n @GetMapping(Endpoints.CHECK_PLAGIARISM)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<TextPlagiarismResult> checkPlagiarism(@PathVariable long exerciseId, @RequestParam float similarityThreshold, @RequestParam int minimumScore)\n throws ExitException, IOException {\n log.debug(\"REST request to check plagiarism for ProgrammingExercise with id: {}\", exerciseId);\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n\n ProgrammingLanguage language = programmingExercise.getProgrammingLanguage();\n ProgrammingLanguageFeature programmingLanguageFeature = programmingLanguageFeatureService.getProgrammingLanguageFeatures(language);\n\n if (!programmingLanguageFeature.isPlagiarismCheckSupported()) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"programmingLanguageNotSupported\",\n \"Artemis does not support plagiarism checks for the programming language \" + language)).body(null);\n }\n\n TextPlagiarismResult result = programmingExerciseExportService.checkPlagiarism(exerciseId, similarityThreshold, minimumScore);\n plagiarismService.savePlagiarismResultAndRemovePrevious(result);\n return ResponseEntity.ok(result);\n }\n\n /**\n * GET /programming-exercises/{exerciseId}/plagiarism-check : Uses JPlag to check for plagiarism\n * and returns the generated output as zip file\n *\n * @param exerciseId The ID of the programming exercise for which the plagiarism check should be\n * executed\n * @param similarityThreshold ignore comparisons whose similarity is below this threshold (%)\n * @param minimumScore consider only submissions whose score is greater or equal to this value\n * @return The ResponseEntity with status 201 (Created) or with status 400 (Bad Request) if the\n * parameters are invalid\n * @throws ExitException is thrown if JPlag exits unexpectedly\n * @throws IOException is thrown for file handling errors\n */\n @GetMapping(value = Endpoints.CHECK_PLAGIARISM_JPLAG_REPORT, produces = MediaType.TEXT_PLAIN_VALUE)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Resource> checkPlagiarismWithJPlagReport(@PathVariable long exerciseId, @RequestParam float similarityThreshold, @RequestParam int minimumScore)\n throws ExitException, IOException {\n log.debug(\"REST request to check plagiarism for ProgrammingExercise with id: {}\", exerciseId);\n long start = System.nanoTime();\n\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n\n var language = programmingExercise.getProgrammingLanguage();\n ProgrammingLanguageFeature programmingLanguageFeature = programmingLanguageFeatureService.getProgrammingLanguageFeatures(language);\n\n if (!programmingLanguageFeature.isPlagiarismCheckSupported()) {\n return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"programmingLanguageNotSupported\",\n \"Artemis does not support plagiarism checks for the programming language \" + language)).body(null);\n }\n\n File zipFile = programmingExerciseExportService.checkPlagiarismWithJPlagReport(exerciseId, similarityThreshold, minimumScore);\n\n if (zipFile == null) {\n return ResponseEntity.badRequest().headers(\n HeaderUtil.createFailureAlert(applicationName, true, ENTITY_NAME, \"internalServerError\", \"Insufficient amount of comparisons available for comparison.\"))\n .body(null);\n }\n\n InputStreamResource resource = new InputStreamResource(new FileInputStream(zipFile));\n\n log.info(\"Check plagiarism of programming exercise {} with title '{}' was successful in {}.\", programmingExercise.getId(), programmingExercise.getTitle(),\n formatDurationFrom(start));\n\n return ResponseEntity.ok().contentLength(zipFile.length()).contentType(MediaType.APPLICATION_OCTET_STREAM).header(\"filename\", zipFile.getName()).body(resource);\n }\n\n /**\n * Unlock all repositories of the given programming exercise.\n *\n * @param exerciseId of the exercise\n * @return The ResponseEntity with status 200 (OK) or with status 404 (Not Found) if the exerciseId is invalid\n */\n @PutMapping(value = Endpoints.UNLOCK_ALL_REPOSITORIES)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> unlockAllRepositories(@PathVariable Long exerciseId) {\n log.info(\"REST request to unlock all repositories of programming exercise {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n programmingExerciseService.unlockAllRepositories(exerciseId);\n log.info(\"Unlocked all repositories of programming exercise {} upon manual request\", exerciseId);\n return ResponseEntity.ok().build();\n }\n\n /**\n * Lock all repositories of the given programming exercise.\n *\n * @param exerciseId of the exercise\n * @return The ResponseEntity with status 200 (OK) or with status 404 (Not Found) if the exerciseId is invalid\n */\n @PutMapping(value = Endpoints.LOCK_ALL_REPOSITORIES)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> lockAllRepositories(@PathVariable Long exerciseId) {\n log.info(\"REST request to lock all repositories of programming exercise {}\", exerciseId);\n var programmingExercise = programmingExerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, programmingExercise, null);\n programmingExerciseService.lockAllRepositories(exerciseId);\n log.info(\"Locked all repositories of programming exercise {} upon manual request\", exerciseId);\n return ResponseEntity.ok().build();\n }\n\n public static final class Endpoints {\n\n public static final String ROOT = \"/api\";\n\n public static final String PROGRAMMING_EXERCISES = \"/programming-exercises\";\n\n public static final String SETUP = PROGRAMMING_EXERCISES + \"/setup\";\n\n public static final String GET_FOR_COURSE = \"/courses/{courseId}/programming-exercises\";\n\n public static final String IMPORT = PROGRAMMING_EXERCISES + \"/import/{sourceExerciseId}\";\n\n public static final String PROGRAMMING_EXERCISE = PROGRAMMING_EXERCISES + \"/{exerciseId}\";\n\n public static final String PROBLEM = PROGRAMMING_EXERCISE + \"/problem-statement\";\n\n public static final String TIMELINE = PROGRAMMING_EXERCISES + \"/timeline\";\n\n public static final String PROGRAMMING_EXERCISE_WITH_PARTICIPATIONS = PROGRAMMING_EXERCISE + \"/with-participations\";\n\n public static final String PROGRAMMING_EXERCISE_WITH_TEMPLATE_AND_SOLUTION_PARTICIPATION = PROGRAMMING_EXERCISE + \"/with-template-and-solution-participation\";\n\n public static final String COMBINE_COMMITS = PROGRAMMING_EXERCISE + \"/combine-template-commits\";\n\n public static final String EXPORT_SUBMISSIONS_BY_PARTICIPANTS = PROGRAMMING_EXERCISE + \"/export-repos-by-participant-identifiers/{participantIdentifiers}\";\n\n public static final String EXPORT_SUBMISSIONS_BY_PARTICIPATIONS = PROGRAMMING_EXERCISE + \"/export-repos-by-participation-ids/{participationIds}\";\n\n public static final String EXPORT_INSTRUCTOR_REPOSITORY = PROGRAMMING_EXERCISE + \"/export-instructor-repository/{repositoryType}\";\n\n public static final String GENERATE_TESTS = PROGRAMMING_EXERCISE + \"/generate-tests\";\n\n public static final String CHECK_PLAGIARISM = PROGRAMMING_EXERCISE + \"/check-plagiarism\";\n\n public static final String PLAGIARISM_RESULT = PROGRAMMING_EXERCISE + \"/plagiarism-result\";\n\n public static final String CHECK_PLAGIARISM_JPLAG_REPORT = PROGRAMMING_EXERCISE + \"/check-plagiarism-jplag-report\";\n\n public static final String TEST_CASE_STATE = PROGRAMMING_EXERCISE + \"/test-case-state\";\n\n public static final String UNLOCK_ALL_REPOSITORIES = PROGRAMMING_EXERCISE + \"/unlock-all-repositories\";\n\n public static final String LOCK_ALL_REPOSITORIES = PROGRAMMING_EXERCISE + \"/lock-all-repositories\";\n\n private Endpoints() {\n }\n }\n\n public static final class ErrorKeys {\n\n public static final String INVALID_TEMPLATE_REPOSITORY_URL = \"invalid.template.repository.url\";\n\n public static final String INVALID_SOLUTION_REPOSITORY_URL = \"invalid.solution.repository.url\";\n\n public static final String INVALID_TEMPLATE_BUILD_PLAN_ID = \"invalid.template.build.plan.id\";\n\n public static final String INVALID_SOLUTION_BUILD_PLAN_ID = \"invalid.solution.build.plan.id\";\n\n private ErrorKeys() {\n }\n }\n}\n" }, { "alpha_fraction": 0.6900175213813782, "alphanum_fraction": 0.6917688250541687, "avg_line_length": 20.148147583007812, "blob_id": "d2741f33a2a5a3c963ed24cecfab889f2cbb7d82", "content_id": "d57cd75f5168eec41fb780cde2a03474a0b7e933", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 571, "license_type": "permissive", "max_line_length": 62, "num_lines": 27, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/dto/CommitDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.jenkins.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class CommitDTO {\n\n private String hash;\n\n private String repositorySlug;\n\n public String getHash() {\n return hash;\n }\n\n public void setHash(String hash) {\n this.hash = hash;\n }\n\n public String getRepositorySlug() {\n return repositorySlug;\n }\n\n public void setRepositorySlug(String repositorySlug) {\n this.repositorySlug = repositorySlug;\n }\n}\n" }, { "alpha_fraction": 0.6661720871925354, "alphanum_fraction": 0.6750741600990295, "avg_line_length": 66.4000015258789, "blob_id": "1bd5474b109a8c97c3a3e4c3e26f258541dcaf71", "content_id": "f8e25a4c34522149eee141f39a2b29165293962c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 674, "license_type": "permissive", "max_line_length": 123, "num_lines": 10, "path": "/src/main/webapp/app/assessment/assessment-filters/assessment-filters.component.html", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<div class=\"d-flex align-items-center my-2\">\n <label class=\"radio-inline mb-0 d-flex align-items-center\">\n <input type=\"radio\" [ngModel]=\"filterProp\" (click)=\"updateFilter(FilterProp.ALL)\" [value]=\"FilterProp.ALL\" />\n <span class=\"ml-1\">{{ 'artemisApp.assessment.dashboard.filters.showAll' | artemisTranslate }}</span>\n </label>\n <label class=\"radio-inline ml-2 mb-0 d-flex align-items-center\">\n <input type=\"radio\" [ngModel]=\"filterProp\" (click)=\"updateFilter(FilterProp.LOCKED)\" [value]=\"FilterProp.LOCKED\" />\n <span class=\"ml-1\">{{ 'artemisApp.assessment.dashboard.filters.showLocked' | artemisTranslate }}</span>\n </label>\n</div>\n" }, { "alpha_fraction": 0.6448482275009155, "alphanum_fraction": 0.6448482275009155, "avg_line_length": 16.113073348999023, "blob_id": "db26ea993bafaf0b2aed758c8c81cfda526dfc29", "content_id": "0b8d8fcd450ca7a2b6ebf70d1a83e8981abdeb0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4843, "license_type": "permissive", "max_line_length": 45, "num_lines": 283, "path": "/src/main/webapp/app/core/icons/font-awesome-icons.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import {\n faAngleDoubleDown,\n faAngleDoubleUp,\n faAngleDown,\n faAngleRight,\n faAngleUp,\n faArchive,\n faArrowLeft,\n faArrowRight,\n faArrowsAlt,\n faArrowsAltV,\n faAsterisk,\n faBan,\n faBars,\n faBell,\n faBold,\n faBook,\n faCalendarAlt,\n faCalendarCheck,\n faCalendarMinus,\n faCalendarPlus,\n faChalkboardTeacher,\n faChartPie,\n faCheck,\n faCheckCircle,\n faCheckDouble,\n faChevronDown,\n faChevronLeft,\n faChevronRight,\n faChevronUp,\n faCircle,\n faCircleNotch,\n faClipboardList,\n faClock,\n faCloud,\n faCode,\n faCodeBranch,\n faCogs,\n faCompress,\n faCopy,\n faDownload,\n faEdit,\n faEquals,\n faEraser,\n faExclamationCircle,\n faExclamationTriangle,\n faExternalLinkAlt,\n faEye,\n faFile,\n faFileExport,\n faFilePowerpoint,\n faFileUpload,\n faFlag,\n faFolder,\n faFolderOpen,\n faFont,\n faGraduationCap,\n faGripLines,\n faGripLinesVertical,\n faHandPointUp,\n faHdd,\n faHeading,\n faHeart,\n faHome,\n faICursor,\n faImage,\n faInfoCircle,\n faItalic,\n faKeyboard,\n faLink,\n faList,\n faListAlt,\n faListOl,\n faListUl,\n faPaperclip,\n faPencilAlt,\n faPlayCircle,\n faPlus,\n faProjectDiagram,\n faQuestion,\n faQuestionCircle,\n faQuoteLeft,\n faRedo,\n faRoad,\n faRobot,\n faSave,\n faSearch,\n faSignal,\n faSignInAlt,\n faSignOutAlt,\n faSort,\n faSortAmountDown,\n faSortAmountUp,\n faSortDown,\n faSortNumericDown,\n faSortNumericUp,\n faSortUp,\n faSpinner,\n faSync,\n faTachometerAlt,\n faTasks,\n faTerminal,\n faThLarge,\n faThList,\n faTimes,\n faTimesCircle,\n faToggleOn,\n faTrash,\n faTrashAlt,\n faUnderline,\n faUndo,\n faUnlink,\n faUpload,\n faUser,\n faUserCheck,\n faUserMinus,\n faUserPlus,\n faVideo,\n faWrench,\n faChartArea,\n faChartBar,\n faPenSquare,\n faFileContract,\n faStamp,\n} from '@fortawesome/free-solid-svg-icons';\n\nimport {\n faCheckCircle as farCheckCircle,\n faCheckSquare as farCheckSquare,\n faCircle as farCircle,\n faCommentDots as farCommentDots,\n faDotCircle as farDotCircle,\n faFileAlt as farFileAlt,\n faFileCode as farFileCode,\n faFileImage as farFileImage,\n faListAlt as farListAlt,\n faPlayCircle as farPlayCircle,\n faQuestionCircle as farQuestionCircle,\n faSave as farSave,\n faSquare as farSquare,\n faTimesCircle as farTimeCircle,\n} from '@fortawesome/free-regular-svg-icons';\n\nexport const fontAwesomeIcons = [\n faUserMinus,\n faUserCheck,\n faCogs,\n faCalendarCheck,\n faCalendarMinus,\n faCalendarPlus,\n faUser,\n faSort,\n faSortUp,\n faSortDown,\n faSync,\n faEye,\n faBan,\n faTimes,\n faArrowLeft,\n faArrowRight,\n faArrowsAlt,\n faSave,\n faPlus,\n faPencilAlt,\n faPenSquare,\n faBars,\n faHome,\n faThList,\n faUserPlus,\n faRoad,\n faTachometerAlt,\n faHeart,\n faList,\n faListAlt,\n faBell,\n faTasks,\n faBook,\n faBold,\n faHdd,\n faFlag,\n faWrench,\n faClock,\n faCloud,\n faSignOutAlt,\n faSignInAlt,\n faCalendarAlt,\n faSearch,\n faTrashAlt,\n faTrash,\n faAsterisk,\n faArchive,\n faEraser,\n faDownload,\n faCheckDouble,\n faKeyboard,\n faProjectDiagram,\n faFileUpload,\n faFilePowerpoint,\n faFont,\n faThLarge,\n faAngleUp,\n faAngleDown,\n faSortAmountUp,\n faSortAmountDown,\n faSortNumericUp,\n faSortNumericDown,\n faChalkboardTeacher,\n faCheckCircle,\n faFileExport,\n faCircleNotch,\n faUndo,\n faExclamationTriangle,\n faUnlink,\n faFolder,\n faFolderOpen,\n faPlayCircle,\n faInfoCircle,\n faGraduationCap,\n faChartPie,\n faChartArea,\n faChartBar,\n faExternalLinkAlt,\n faSignal,\n faEdit,\n faChevronUp,\n faChevronDown,\n faChevronLeft,\n faChevronRight,\n faRedo,\n faExclamationCircle,\n faTerminal,\n faSpinner,\n faQuestionCircle,\n faQuestion,\n faTimesCircle,\n faAngleRight,\n faCheck,\n faUpload,\n faArrowsAltV,\n faFile,\n faCodeBranch,\n faCircle,\n faUnderline,\n faItalic,\n faQuoteLeft,\n faLink,\n faHeading,\n faCode,\n faCopy,\n faListUl,\n faListOl,\n faImage,\n faRobot,\n farQuestionCircle,\n farCheckCircle,\n farDotCircle,\n farTimeCircle,\n farCommentDots,\n farListAlt,\n farFileImage,\n farCheckSquare,\n farSquare,\n farFileAlt,\n farPlayCircle,\n farFileCode,\n farCircle,\n farSave,\n faGripLinesVertical,\n faGripLines,\n faPaperclip,\n faAngleDoubleDown,\n faAngleDoubleUp,\n faCompress,\n faEquals,\n faHandPointUp,\n faICursor,\n faVideo,\n faClipboardList,\n faToggleOn,\n faEdit,\n faFileContract,\n faStamp,\n];\n" }, { "alpha_fraction": 0.7052375078201294, "alphanum_fraction": 0.7064555287361145, "avg_line_length": 37.1860466003418, "blob_id": "7d28e691ebba620e058f62cd15ef14da76b1a70f", "content_id": "461df3d5a46334e2ed46d0f94f4f208ea9c42fa1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1642, "license_type": "permissive", "max_line_length": 127, "num_lines": 43, "path": "/src/main/webapp/app/overview/course-card.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { ARTEMIS_DEFAULT_COLOR } from 'app/app.constants';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\n@Component({\n selector: 'jhi-overview-course-card',\n templateUrl: './course-card.component.html',\n styleUrls: ['course-card.scss'],\n})\nexport class CourseCardComponent implements OnChanges {\n readonly ARTEMIS_DEFAULT_COLOR = ARTEMIS_DEFAULT_COLOR;\n @Input() course: Course;\n @Input() hasGuidedTour: boolean;\n\n nextRelevantExercise?: Exercise;\n\n constructor(\n private router: Router,\n private route: ActivatedRoute,\n private courseScoreCalculationService: CourseScoreCalculationService,\n private exerciseService: ExerciseService,\n ) {}\n\n ngOnChanges() {\n this.nextRelevantExercise = this.exerciseService.getNextExerciseForDays(this.course.exercises!);\n }\n\n displayTotalRelativeScore(): number {\n if (this.course.exercises && this.course.exercises.length > 0) {\n return this.courseScoreCalculationService.calculateTotalScores(this.course.exercises).get('currentRelativeScore')!;\n } else {\n return 0;\n }\n }\n\n startExercise(exercise: Exercise): void {\n this.router.navigate([this.course.id, 'exercises', exercise.id], { relativeTo: this.route });\n }\n}\n" }, { "alpha_fraction": 0.6561183929443359, "alphanum_fraction": 0.6581639051437378, "avg_line_length": 44.9171257019043, "blob_id": "c835f5c7b5b2a3276d73b42f35f205b37d1635ff", "content_id": "1c4a9ac33600fb43dc93dc957713821e31320442", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8311, "license_type": "permissive", "max_line_length": 171, "num_lines": 181, "path": "/src/main/webapp/app/shared/markdown.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { DomSanitizer, SafeHtml } from '@angular/platform-browser';\nimport * as showdown from 'showdown';\nimport * as showdownKatex from 'showdown-katex';\nimport * as showdownHighlight from 'showdown-highlight';\nimport * as DOMPurify from 'dompurify';\nimport { escapeStringForUseInRegex } from 'app/shared/util/global.utils';\nimport { ExplanationCommand } from 'app/shared/markdown-editor/domainCommands/explanation.command';\nimport { HintCommand } from 'app/shared/markdown-editor/domainCommands/hint.command';\nimport { TextHintExplanationInterface } from 'app/entities/quiz/quiz-question.model';\n\n/**\n * showdown will add the classes to the converted html\n * see: https://github.com/showdownjs/showdown/wiki/Add-default-classes-for-each-HTML-element\n */\nconst classMap = {\n table: 'table',\n};\n/**\n * extension to add add css classes to html tags\n * see: https://github.com/showdownjs/showdown/wiki/Add-default-classes-for-each-HTML-element\n */\nconst addCSSClass = Object.keys(classMap).map((key) => ({\n type: 'output',\n regex: new RegExp(`<${key}(.*)>`, 'g'),\n replace: `<${key} class=\"${classMap[key]}\" $1>`,\n}));\n\n@Injectable({ providedIn: 'root' })\nexport class ArtemisMarkdownService {\n static hintOrExpRegex = new RegExp(escapeStringForUseInRegex(`${ExplanationCommand.identifier}`) + '|' + escapeStringForUseInRegex(`${HintCommand.identifier}`), 'g');\n\n constructor(private sanitizer: DomSanitizer) {}\n\n /**\n * Parse the markdown text and apply the result to the target object's data\n *\n * The markdown text is split at HintCommand.identifier and ExplanationCommand.identifier tags.\n * => First part is text. Everything after HintCommand.identifier is Hint, anything after ExplanationCommand.identifier is explanation\n *\n * @param markdownText {string} the markdown text to parse\n * @param targetObject {object} the object that the result will be saved in. Fields modified are 'text', 'hint' and 'explanation'.\n */\n static parseTextHintExplanation(markdownText: string, targetObject: TextHintExplanationInterface) {\n if (!markdownText || !targetObject) {\n return;\n }\n // split markdownText into main text, hint and explanation\n const markdownTextParts = markdownText.split(ArtemisMarkdownService.hintOrExpRegex);\n targetObject.text = markdownTextParts[0].trim();\n if (markdownText.indexOf(HintCommand.identifier) !== -1 && markdownText.indexOf(ExplanationCommand.identifier) !== -1) {\n if (markdownText.indexOf(HintCommand.identifier) < markdownText.indexOf(ExplanationCommand.identifier)) {\n targetObject.hint = markdownTextParts[1].trim();\n targetObject.explanation = markdownTextParts[2].trim();\n } else {\n targetObject.hint = markdownTextParts[2].trim();\n targetObject.explanation = markdownTextParts[1].trim();\n }\n } else if (markdownText.indexOf(HintCommand.identifier) !== -1) {\n targetObject.hint = markdownTextParts[1].trim();\n targetObject.explanation = undefined;\n } else if (markdownText.indexOf(ExplanationCommand.identifier) !== -1) {\n targetObject.hint = undefined;\n targetObject.explanation = markdownTextParts[1].trim();\n } else {\n targetObject.hint = undefined;\n targetObject.explanation = undefined;\n }\n }\n\n /**\n * generate the markdown text for the given source object\n *\n * The markdown is generated according to these rules:\n *\n * 1. First the value of sourceObject.text is inserted\n * 2. If hint and/or explanation exist, they are added after the text with a linebreak and tab in front of them\n * 3. Hint starts with [-h], explanation starts with [-e]\n *\n * @param sourceObject\n * @return {string}\n */\n generateTextHintExplanation(sourceObject: TextHintExplanationInterface) {\n return !sourceObject.text\n ? ''\n : sourceObject.text +\n (sourceObject.hint ? '\\n\\t' + HintCommand.identifier + ' ' + sourceObject.hint : '') +\n (sourceObject.explanation ? '\\n\\t' + ExplanationCommand.identifier + ' ' + sourceObject.explanation : '');\n }\n\n /**\n * Converts markdown into html, sanitizes it and then declares it as safe to bypass further security.\n *\n * @param {string} markdownText the original markdown text\n * @param {showdown.ShowdownExtension[]} extensions to use for markdown parsing\n * @param {string[]} allowedHtmlTags to allow during sanitization\n * @param {string[]} allowedHtmlAttributes to allow during sanitization\n * @returns {string} the resulting html as a SafeHtml object that can be inserted into the angular template\n */\n safeHtmlForMarkdown(\n markdownText?: string,\n extensions: showdown.ShowdownExtension[] = [],\n allowedHtmlTags: string[] | undefined = undefined,\n allowedHtmlAttributes: string[] | undefined = undefined,\n ): SafeHtml {\n if (!markdownText || markdownText === '') {\n return '';\n }\n const convertedString = this.htmlForMarkdown(markdownText, [...extensions, ...addCSSClass], allowedHtmlTags, allowedHtmlAttributes);\n return this.sanitizer.bypassSecurityTrustHtml(convertedString);\n }\n\n /**\n * Converts markdown into html (string) and sanitizes it. Does NOT declare it as safe to bypass further security\n * Note: If possible, please use safeHtmlForMarkdown\n *\n * @param {string} markdownText the original markdown text\n * @param {showdown.ShowdownExtension[]} extensions to use for markdown parsing\n * @param {string[]} allowedHtmlTags to allow during sanitization\n * @param {string[]} allowedHtmlAttributes to allow during sanitization\n * @returns {string} the resulting html as a SafeHtml object that can be inserted into the angular template\n */\n htmlForMarkdown(\n markdownText?: string,\n extensions: showdown.ShowdownExtension[] = [],\n allowedHtmlTags: string[] | undefined = undefined,\n allowedHtmlAttributes: string[] | undefined = undefined,\n ): string {\n if (!markdownText || markdownText === '') {\n return '';\n }\n const converter = new showdown.Converter({\n parseImgDimensions: true,\n headerLevelStart: 3,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n strikethrough: true,\n tables: true,\n openLinksInNewWindow: true,\n backslashEscapesHTMLTags: true,\n extensions: [...extensions, showdownKatex(), showdownHighlight(), ...addCSSClass],\n });\n const html = converter.makeHtml(markdownText);\n const purifyParameters = {};\n if (allowedHtmlTags) {\n purifyParameters['ALLOWED_TAGS'] = allowedHtmlTags;\n }\n if (allowedHtmlAttributes) {\n purifyParameters['ALLOWED_ATTR'] = allowedHtmlAttributes;\n }\n return DOMPurify.sanitize(html, purifyParameters);\n }\n\n /**\n * Converts markdown into html, sanitizes it and then declares it as safe to bypass further security.\n *\n * @param {string} markdownText the original markdown text\n * @returns {string} the resulting html as a string\n */\n htmlForGuidedTourMarkdown(markdownText?: string): SafeHtml {\n if (!markdownText || markdownText === '') {\n return '';\n }\n const sanitized = DOMPurify.sanitize(markdownText, { ALLOWED_TAGS: ['a', 'p', 'ul', 'ol', 'li', 'tt', 'span'], ALLOWED_ATTR: ['class', 'href', 'rel', 'target'] });\n return this.sanitizer.bypassSecurityTrustHtml(sanitized);\n }\n\n markdownForHtml(htmlText: string): string {\n const converter = new showdown.Converter({\n parseImgDimensions: true,\n headerLevelStart: 3,\n simplifiedAutoLink: true,\n excludeTrailingPunctuationFromURLs: true,\n strikethrough: true,\n tables: true,\n openLinksInNewWindow: true,\n backslashEscapesHTMLTags: true,\n });\n return converter.makeMarkdown(htmlText);\n }\n}\n" }, { "alpha_fraction": 0.7426822185516357, "alphanum_fraction": 0.743638813495636, "avg_line_length": 53.45833206176758, "blob_id": "78a4f4702d2f108edc3d77ac977fb09847cb22d6", "content_id": "43c2c3f13a92c748c852f58807d3814e5d42337a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 5227, "license_type": "permissive", "max_line_length": 273, "num_lines": 96, "path": "/docs/dev/setup/programming-exercises.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Adjustments for programming exercises\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nThere are several variables that can be configured when using programming exercises.\nThey are presented in this separate page to keep the 'normal' setup guide shorter.\n\n\nPath variables\n##############\n\nThere are variables for several paths:\n\n- ``artemis.repo-clone-path``\n\n Repositories that the Artemis server needs are stored in this folder.\n This e.g. affects repositories from students which use the online code editor or the template/solution repositories of new exercises, as they are pushed to the VCS after modification.\n\n Files in this directory are usually not critical, as the latest pushed version of these repositories are also stored at the VCS.\n However, changed that are saved in the online code editor but not yet commited will be lost when this folder is deleted.\n\n- ``artemis.repo-download-clone-path``\n\n Repositories that were downloaded from Artemis are stored in this directory.\n\n Files in this directory can be removed without loss of data, if the downloaded repositories are still present at the VCS.\n No changes to the data in the VCS are stored in this directory (or they can be retrieved by performing the download-action again).\n\n- ``artemis.template-path``\n\n Templates are available within Artemis. The templates should fit to most environments, but there might be cases where one wants to change the templates.\n\n This value specifies the path to the templates which should overwrite the default ones.\n Note that this is the path to the folder where the `templates` folder is located, not the path to the `templates` folder itself.\n\n\n\nTemplates\n#########\n\nTemplates are shipped with Artemis (they can be found within the ``src/main/resources/templates`` folder in Github).\nThese templates should fit well for many deployments, but one might want to change some of them for special deployments.\n\nAs of now, you can overwrite the ``jenkins`` folders that is present within the ``src/main/resources/templates`` folder.\nFiles that are present in the file system will be used, if a file is not present in the file system, it is loaded from the classpath (e.g. the .war archive).\n\nWe plan to make other folders configurable as well, but this is not supported yet.\n\nJenkins template\n----------------\nThe build process in Jenkins is stored in a ``config.xml``-file (``src/main/resources/templates/jenkins``) that shares common steps for all programming languages (e.g. triggering a build when a push to GitLab occurred).\nIt is extended by a ``Jenkinsfile`` that is dependent on the used programming language which will be included in the generic ``config.xml`` file.\nThe builds steps (including used docker images, the checkout process, the actual build steps, and the reporting of the results to Artemis) is included in the ``Jenkinsfile``.\n\nA sample ``Jenkinsfile`` can be found at ``src/main/resources/templates/jenkins/java/Jenkinsfile``.\nNote that the ``Jenkinsfile`` **must** start either\n\n- with ``pipeline`` (there must not be a comment before pipeline, but there can be one at any other position, if the Jenkinsfile-syntax allows it)\n- or the special comment ``// ARTEMIS: JenkinsPipeline`` in the first line.\n\nThe variables `#dockerImage`, `#testRepository`, `#assignmentRepository`, `#jenkinsNotificationToken` and `#notificationsUrl` will automatically be replaced (for the normal Jenkinsfile, within the Jenkinsfile-staticCodeAnalysis, #staticCodeAnalysisScript is also replaced).\n\nYou should not need to touch any of these variables, except the `#dockerImage` variable, if you want to use a different agent setup (e.g. a Kubernetes setup).\n\n\nCaching example for Maven\n^^^^^^^^^^^^^^^^^^^^^^^^^\nThe Docker image used to run the maven-tests already contains a set of commonly used dependencies (see `artemis-maven-docker <https://github.com/ls1intum/artemis-maven-docker>`__).\nThis significantly speeds up builds as the dependencies do not have to be downloaded every time a build is started.\nHowever, the dependencies included in the Docker image might not match the dependencies required in your tests (e.g. because you added new dependencies or the Docker image is outdated).\n\nYou can cache the maven-dependencies also on the machine that runs the builds (that means, outside the docker container) using the following steps:\n\nAdjust the agent-args and add the environment block.\n\n\n.. code:: bash\n\n agent {\n docker {\n image '#dockerImage'\n label 'docker'\n args '-v $HOME/maven-cache-docker:/var/maven'\n }\n }\n environment {\n JAVA_TOOL_OPTIONS = '-Duser.home=/var/maven'\n }\n stages {\n stage('Checkout') {\n\n\n\nYou have to add permissions to the folder (which will be located at the $HOME folder of the user that jenkins uses), e.g. with ``sudo chmod 777 maven-cache-docker -R``.\n\nNote that this might allow students to access shared resources (e.g. jars used by Maven), and they might be able to overwrite them.\nYou can use `Artemis-java-testing-sandbox <https://github.com/ls1intum/artemis-java-test-sandbox>`__ to prevent this by restricting the resources the student's code can access." }, { "alpha_fraction": 0.676119863986969, "alphanum_fraction": 0.6956493854522705, "avg_line_length": 39.936676025390625, "blob_id": "cd3d14226f9c7645e9f60db2f961782d7334e3c1", "content_id": "af4dd6197077d6066de64026f6c187e0f1ac41cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 15515, "license_type": "permissive", "max_line_length": 458, "num_lines": 379, "path": "/build.gradle", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import org.gradle.api.tasks.testing.logging.TestExceptionFormat\nimport org.gradle.api.tasks.testing.logging.TestLogEvent\n\nbuildscript {\n repositories {\n mavenLocal()\n mavenCentral()\n maven { url \"https://repo.spring.io/plugins-release\" }\n jcenter()\n }\n dependencies {\n classpath \"io.spring.gradle:propdeps-plugin:0.0.10.RELEASE\"\n }\n}\n\nplugins {\n id \"checkstyle\"\n id \"java\"\n id \"maven-publish\"\n id \"idea\"\n id \"jacoco\"\n id \"org.springframework.boot\" version \"${spring_boot_version}\"\n id \"com.google.cloud.tools.jib\" version \"3.0.0\"\n id \"com.github.node-gradle.node\" version \"3.0.1\"\n id \"com.diffplug.spotless\" version \"5.11.1\"\n // this allows us to find outdated dependencies via ./gradlew dependencyUpdates\n id \"com.github.ben-manes.versions\" version \"0.38.0\"\n}\n\ngroup = \"de.tum.in.www1.artemis\"\nversion = \"4.11.3\"\ndescription = \"Interactive Learning with Individual Feedback\"\n\nsourceCompatibility=15\ntargetCompatibility=15\n\napply from: \"gradle/docker.gradle\"\n//this enables us to invoke ./gradlew liquibaseDiffChangelog\napply from: \"gradle/liquibase.gradle\"\n\nif (project.hasProperty(\"prod\")) {\n apply from: \"gradle/profile_prod.gradle\"\n} else {\n apply from: \"gradle/profile_dev.gradle\"\n}\n\nif (project.hasProperty(\"war\")) {\n apply from: \"gradle/war.gradle\"\n}\n\napply plugin: \"jacoco\"\n\nidea {\n module {\n excludeDirs += files(\"node_modules\")\n }\n}\n\nspotless {\n // allows to execute the code formatting commands ./gradlew spotlessApply and ./gradlew spotlessCheck\n java {\n target project.fileTree(project.rootDir) {\n include \"**/*.java\"\n exclude \"**/src/main/java/de/tum/in/www1/artemis/service/connectors/BambooService.java\", \"**/src/main/java/de/tum/in/www1/artemis/config/SecurityConfiguration.java\", \"**/src/main/java/de/tum/in/www1/artemis/config/SAML2Configuration.java\", \"**/src/test/resources/test-data/repository-export/EncodingISO_8559_1.java\", \"**/node_modules/**\", \"**/out/**\", \"**/repos/**\", \"**/build/**\", \"**/src/main/generated/**\", \"**/src/main/resources/templates/**\"\n }\n importOrderFile \"artemis-spotless.importorder\"\n eclipse().configFile \"artemis-spotless-style.xml\"\n\n removeUnusedImports()\n }\n}\n\ndefaultTasks \"bootRun\"\n\nspringBoot {\n mainClass = \"de.tum.in.www1.artemis.ArtemisApp\"\n}\n\n// Execute the test cases: ./gradlew executeTests\n\ntest {\n useJUnitPlatform()\n exclude \"**/*IT*\", \"**/*IntTest*\"\n testLogging {\n events \"FAILED\", \"SKIPPED\"\n }\n testLogging.showStandardStreams = true\n reports.html.enabled = false\n jvmArgs \"--illegal-access=warn\"\n}\n\ntask testReport(type: TestReport) {\n destinationDir = file(\"$buildDir/reports/tests\")\n reportOn test\n}\n\njacoco {\n toolVersion = \"0.8.6\"\n}\n\nprivate excludedClassFilesForReport(classDirectories) {\n classDirectories.setFrom(files(classDirectories.files.collect {\n fileTree(dir: it,\n exclude: [\n \"**/de/tum/in/www1/artemis/domain/**/*_*\",\n ]\n )\n }))\n}\n\njacocoTestReport {\n reports {\n xml.enabled true\n }\n // we want to ignore some generated files in the domain folders\n afterEvaluate {\n excludedClassFilesForReport(classDirectories)\n }\n}\n\njacocoTestCoverageVerification {\n violationRules {\n rule {\n limit {\n counter = \"INSTRUCTION\"\n value = \"COVEREDRATIO\"\n // TODO: in the future the following value should become at least 0.90\n minimum = 0.870\n }\n limit {\n counter = \"CLASS\"\n value = \"MISSEDCOUNT\"\n // TODO: in the future the following value should become less than 20\n maximum = 30\n }\n }\n }\n // we want to ignore some generated files in the domain folders\n afterEvaluate {\n excludedClassFilesForReport(classDirectories)\n }\n}\ncheck.dependsOn jacocoTestCoverageVerification\n\nconfigurations {\n providedRuntime\n}\n\nrepositories {\n mavenLocal()\n mavenCentral()\n jcenter()\n}\n\ndependencies {\n implementation \"com.offbytwo.jenkins:jenkins-client:0.3.8\"\n implementation \"org.gitlab4j:gitlab4j-api:4.15.7\"\n\n implementation files(\"libs/jplag-3.0.0.jar\")\n\n // https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit\n implementation \"org.eclipse.jgit:org.eclipse.jgit:5.11.0.202103091610-r\"\n implementation \"org.eclipse.jgit:org.eclipse.jgit.ssh.apache:5.11.0.202103091610-r\"\n // https://mvnrepository.com/artifact/net.sourceforge.plantuml/plantuml\n implementation \"net.sourceforge.plantuml:plantuml:8059\"\n implementation \"org.imsglobal:basiclti-util:1.2.0\"\n implementation \"org.jasypt:jasypt:1.9.3\"\n implementation \"me.xdrop:fuzzywuzzy:1.3.1\"\n implementation \"com.atlassian.bamboo:bamboo-specs:7.2.3\"\n implementation \"com.thoughtworks.qdox:qdox:2.0.0\"\n implementation \"io.sentry:sentry-spring-boot-starter:4.3.0\"\n implementation \"io.sentry:sentry-logback:4.3.0\"\n implementation \"org.jsoup:jsoup:1.13.1\"\n\n implementation \"org.springdoc:springdoc-openapi-ui:1.5.6\"\n\n // import JHipster dependencies BOM\n implementation platform(\"io.github.jhipster:jhipster-dependencies:${jhipster_dependencies_version}\" )\n\n implementation \"io.github.jhipster:jhipster-framework\"\n implementation \"org.springframework.boot:spring-boot-starter-cache:${spring_boot_version}\"\n implementation \"io.micrometer:micrometer-registry-prometheus:1.6.5\"\n implementation \"net.logstash.logback:logstash-logback-encoder:6.6\"\n implementation \"com.fasterxml.jackson.datatype:jackson-datatype-hppc:${fasterxml_version}\"\n implementation \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310:${fasterxml_version}\"\n implementation \"com.fasterxml.jackson.datatype:jackson-datatype-hibernate5:${fasterxml_version}\"\n implementation \"com.fasterxml.jackson.core:jackson-annotations:${fasterxml_version}\"\n implementation \"com.fasterxml.jackson.core:jackson-databind:${fasterxml_version}\"\n implementation \"com.hazelcast:hazelcast:${hazelcast_version}\"\n implementation \"com.hazelcast:hazelcast-spring:${hazelcast_version}\"\n implementation \"com.hazelcast:hazelcast-hibernate53:2.2.0\"\n implementation \"javax.cache:cache-api:1.1.1\"\n implementation \"org.hibernate:hibernate-core\"\n implementation \"com.zaxxer:HikariCP:4.0.3\"\n implementation \"org.apache.commons:commons-text:1.9\"\n implementation \"javax.transaction:javax.transaction-api:1.3\"\n implementation \"org.hibernate:hibernate-jcache:${hibernate_version}\"\n implementation \"org.hibernate:hibernate-entitymanager:${hibernate_version}\"\n implementation \"org.hibernate.validator:hibernate-validator:7.0.1.Final\"\n implementation \"org.liquibase:liquibase-core:4.3.2\"\n implementation \"org.springframework.boot:spring-boot-loader-tools:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-mail:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-logging:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-actuator:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-aop:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-data-jpa:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-security:${spring_boot_version}\"\n implementation (\"org.springframework.boot:spring-boot-starter-web:${spring_boot_version}\") {\n exclude module: \"spring-boot-starter-undertow\"\n }\n implementation \"org.springframework.boot:spring-boot-starter-tomcat:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-websocket:${spring_boot_version}\"\n implementation \"org.springframework.boot:spring-boot-starter-thymeleaf:${spring_boot_version}\"\n\n implementation \"org.springframework.ldap:spring-ldap-core:2.3.3.RELEASE\"\n implementation \"org.springframework.data:spring-data-ldap:2.4.7\"\n\n implementation \"org.springframework.cloud:spring-cloud-starter-netflix-eureka-client:3.0.2\"\n implementation \"org.springframework.cloud:spring-cloud-starter-config:3.0.3\"\n implementation \"org.springframework.boot:spring-boot-starter-cloud-connectors:2.2.13.RELEASE\"\n\n implementation \"io.netty:netty-all:4.1.63.Final\"\n implementation \"io.projectreactor.netty:reactor-netty:1.0.5\"\n implementation \"org.springframework:spring-messaging:5.3.5\"\n\n implementation \"org.springframework.security:spring-security-config:${spring_security_version}\"\n implementation \"org.springframework.security:spring-security-data:${spring_security_version}\"\n implementation \"org.springframework.security:spring-security-web:${spring_security_version}\"\n implementation \"org.springframework.security:spring-security-messaging:${spring_security_version}\"\n implementation \"org.springframework.security:spring-security-ldap:${spring_security_version}\"\n implementation \"org.springframework.security:spring-security-saml2-service-provider:${spring_security_version}\"\n implementation \"org.xmlbeam:xmlprojector:1.4.19\"\n implementation \"io.jsonwebtoken:jjwt-api:0.11.2\"\n implementation \"org.bouncycastle:bcprov-jdk15on:1.68\"\n runtimeOnly \"io.jsonwebtoken:jjwt-impl:0.11.2\"\n runtimeOnly \"io.jsonwebtoken:jjwt-jackson:0.11.2\"\n implementation (\"io.springfox:springfox-swagger2:3.0.0\") {\n exclude module: \"mapstruct\"\n }\n implementation \"io.springfox:springfox-bean-validators:3.0.0\"\n implementation \"mysql:mysql-connector-java:8.0.23\"\n\n implementation \"org.zalando:problem-spring-web:0.26.2\"\n implementation \"com.ibm.icu:icu4j:69.1\"\n implementation \"com.github.seancfoley:ipaddress:5.3.3\"\n implementation \"org.apache.maven:maven-model:3.8.1\"\n\n annotationProcessor \"org.hibernate:hibernate-jpamodelgen:${hibernate_version}\"\n annotationProcessor (\"org.glassfish.jaxb:jaxb-runtime:${jaxb_runtime_version}\") {\n exclude group: \"javax.ws.rs\", module: \"jsr311-api\"\n }\n annotationProcessor (\"org.springframework.boot:spring-boot-configuration-processor:${spring_boot_version}\") {\n exclude group: \"com.vaadin.external.google\", module: \"android-json\"\n }\n testImplementation (\"org.springframework.boot:spring-boot-starter-test:${spring_boot_version}\") {\n exclude module: \"junit\"\n exclude group: \"org.junit.vintage\", module: \"junit-vintage-engine\"\n exclude group: \"com.vaadin.external.google\", module: \"android-json\"\n }\n testImplementation \"org.springframework.security:spring-security-test:${spring_security_version}\"\n testImplementation \"org.springframework.boot:spring-boot-test:${spring_boot_version}\"\n testImplementation \"org.assertj:assertj-core:3.19.0\"\n testImplementation \"org.junit.jupiter:junit-jupiter:${junit_version}\"\n testImplementation \"com.tngtech.archunit:archunit-junit5-api:0.17.0\"\n testRuntimeOnly \"com.tngtech.archunit:archunit-junit5-engine:0.17.0\"\n testImplementation \"org.mockito:mockito-core:${mockito_version}\"\n testImplementation \"org.mockito:mockito-junit-jupiter:${mockito_version}\"\n testImplementation \"org.hamcrest:hamcrest-library:2.2\"\n testImplementation \"com.h2database:h2:1.4.200\"\n testImplementation \"org.awaitility:awaitility:4.0.3\"\n testImplementation \"org.apache.maven.shared:maven-invoker:3.1.0\"\n testImplementation \"org.apache.maven.surefire:surefire-report-parser:3.0.0-M5\"\n\n // Lightweight JSON library needed for the internals of the MockRestServiceServer\n testImplementation \"org.json:json:20210307\"\n}\n\ntask cleanResources(type: Delete) {\n delete \"build/resources\"\n}\n\ntask executeTests (type: Exec) {\n commandLine \"./gradlew\", \"test\", \"-x\", \"webpack\"\n}\n\n// Taken from here: https://stackoverflow.com/questions/3963708/gradle-how-to-display-test-results-in-the-console-in-real-time\ntasks.withType(Test) {\n testLogging {\n // set options for log level LIFECYCLE\n events TestLogEvent.FAILED,\n TestLogEvent.PASSED,\n TestLogEvent.SKIPPED\n exceptionFormat TestExceptionFormat.FULL\n showExceptions true\n showCauses true\n showStackTraces true\n\n info.events = debug.events\n info.exceptionFormat = debug.exceptionFormat\n\n afterSuite { desc, result ->\n if (!desc.parent) { // will match the outermost suite\n def output = \"Results: ${result.resultType} (${result.testCount} tests, ${result.successfulTestCount} successes, ${result.failedTestCount} failures, ${result.skippedTestCount} skipped)\"\n def startItem = \"| \", endItem = \" |\"\n def repeatLength = startItem.length() + output.length() + endItem.length()\n println(\"\\n\" + (\"-\" * repeatLength) + \"\\n\" + startItem + output + endItem + \"\\n\" + (\"-\" * repeatLength))\n }\n }\n }\n}\n\nwrapper {\n gradleVersion = \"7.0-rc-2\"\n}\n\ntask stage(dependsOn: \"bootWar\") {\n}\n\nnode {\n download = true\n version = \"${node_version}\"\n yarnVersion = \"${yarn_version}\"\n}\n\n// Command to execute the JavaDoc checkstyle verification ./gradlew checkstyleMain\ncheckstyle {\n toolVersion \"8.41.1\"\n configFile file(\"${rootDir}/checkstyle.xml\")\n checkstyleTest.enabled = false\n maxErrors = 0\n}\n\ntask executeCheckstyle (type: Exec) {\n commandLine \"./gradlew\", \"checkstyleMain\", \"-x\", \"yarn\", \"-x\", \"webpack\"\n}\n\ntask buildJarForDocker (type: Exec) {\n commandLine \"./gradlew\", \"build\", \"-x\", \"webpack\", \"-x\", \"test\", \"-x\", \"jacocoTestCoverageVerification\"\n}\n\ndef isNonStable = { String version ->\n def stableKeyword = [\"RELEASE\", \"FINAL\", \"GA\"].any { it -> version.toUpperCase().contains(it) }\n def regex = /^[0-9,.v-]+(-r)?$/\n return !stableKeyword && !(version ==~ regex)\n}\n\ntasks.named(\"dependencyUpdates\").configure {\n rejectVersionIf {\n isNonStable(it.candidate.version)\n }\n\n rejectVersionIf {\n isNonStable(it.candidate.version) && !isNonStable(it.currentVersion)\n }\n\n resolutionStrategy {\n componentSelection {\n all {\n if (isNonStable(it.candidate.version) && !isNonStable(it.currentVersion)) {\n reject(\"Release candidate\")\n }\n }\n }\n }\n}\n\n// Available commands:\n//\n// 1) Build production: ./gradlew -Pprod -Pwar clean bootWar\n// 2) Execute tests with coverage report: ./gradlew executeTests jacocoTestReport -x yarn -x webpack\n// 2a) Execute tests without coverage report: ./gradlew executeTests -x yarn -x webpack\n// 2b) Run a single test: ./gradlew test --tests ExamIntegrationTest or ./gradlew test --tests ExamIntegrationTest.testGetExamScore\n// 3) Check Java code format: ./gradlew spotlessCheck -x yarn -x webpack\n// 4) Apply Java code formatter: ./gradlew spotlessApply -x yarn -x webpack\n// 5) Find dependency updates: ./gradlew dependencyUpdates -Drevision=release\n// 6) Check JavaDoc: ./gradlew checkstyleMain -x yarn -x webpack\n// 7) Generate Liquibase diff: ./gradlew liquibaseDiffChangelog\n// 8) Clear Liquibase checksums: ./gradlew liquibaseClearChecksums\n// 9) Verify code coverage (after tests): ./gradlew jacocoTestCoverageVerification\n" }, { "alpha_fraction": 0.6527262926101685, "alphanum_fraction": 0.6691371202468872, "avg_line_length": 38.35416793823242, "blob_id": "fd9db8013b984464dd3ac51ad2a05ebe5d9dedac", "content_id": "aaba2080694f2943f94bf10e37fe55ae10932edb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1889, "license_type": "permissive", "max_line_length": 118, "num_lines": 48, "path": "/src/test/javascript/spec/component/overview/course-exams/course-exam-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { CourseExamDetailComponent } from 'app/overview/course-exams/course-exam-detail/course-exam-detail.component';\nimport { Exam } from 'app/entities/exam.model';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport * as moment from 'moment';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseExamDetailComponent', () => {\n let component: CourseExamDetailComponent;\n let componentFixture: ComponentFixture<CourseExamDetailComponent>;\n\n const startDate = moment('2020-06-11 11:29:51');\n const endDate = moment('2020-06-11 11:59:51');\n\n const testExam = {\n id: 1,\n startDate,\n endDate,\n } as Exam;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n providers: [{ provide: AccountService, useClass: MockAccountService }],\n declarations: [CourseExamDetailComponent],\n })\n .overrideTemplate(CourseExamDetailComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(CourseExamDetailComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should calculate exam duration', () => {\n component.exam = testExam;\n componentFixture.detectChanges();\n expect(component.examDuration).to.deep.equal(30);\n });\n});\n" }, { "alpha_fraction": 0.8022782802581787, "alphanum_fraction": 0.8047192692756653, "avg_line_length": 39.96666717529297, "blob_id": "8c9d3312b37822d4acfb7cdbb8d515d7dd4aee7e", "content_id": "5b2386994dc1aa6d9e9037e66dfb4f803b1ead0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1229, "license_type": "permissive", "max_line_length": 202, "num_lines": 30, "path": "/src/main/java/de/tum/in/www1/artemis/repository/TextClusterRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.util.List;\nimport java.util.Set;\n\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.TextCluster;\nimport de.tum.in.www1.artemis.domain.TextExercise;\n\n/**\n * Spring Data repository for the TextCluster entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface TextClusterRepository extends JpaRepository<TextCluster, Long> {\n\n @EntityGraph(type = LOAD, attributePaths = { \"blocks\", \"blocks.submission\", \"blocks.submission.results\" })\n List<TextCluster> findAllByExercise(TextExercise exercise);\n\n @Query(\"SELECT distinct cluster FROM TextCluster cluster LEFT JOIN FETCH cluster.blocks b LEFT JOIN FETCH b.submission blocksub LEFT JOIN FETCH blocksub.results WHERE cluster.id IN :#{#clusterIds}\")\n List<TextCluster> findAllByIdsWithEagerTextBlocks(@Param(\"clusterIds\") Set<Long> clusterIds);\n\n}\n" }, { "alpha_fraction": 0.6927493214607239, "alphanum_fraction": 0.694553792476654, "avg_line_length": 47.380950927734375, "blob_id": "225c6303d7ba2f6be19f9ac425ba11ffb93ab07f", "content_id": "b0d9ca53389ab82e7261d97f2c914c0ccb9b95fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6096, "license_type": "permissive", "max_line_length": 162, "num_lines": 126, "path": "/src/test/javascript/spec/component/programming-assessment/programming-assessment-repo-export-dialog.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { stub } from 'sinon';\nimport { of } from 'rxjs';\nimport { HttpResponse, HttpHeaders } from '@angular/common/http';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport * as moment from 'moment';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ProgrammingAssessmentRepoExportDialogComponent } from 'app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ProgrammingAssessmentRepoExportService } from 'app/exercises/programming/assess/repo-export/programming-assessment-repo-export.service';\nimport { ArtemisProgrammingAssessmentModule } from 'app/exercises/programming/assess/programming-assessment.module';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\nconst createBlobHttpResponse = () => {\n const blob = new Blob([JSON.stringify({ property: 'blob' })], { type: 'application/json' });\n const headers = new HttpHeaders().set('filename', 'blob file');\n return new HttpResponse({ body: blob, headers });\n};\n\ndescribe('ProgrammingAssessmentRepoExportDialogComponent', () => {\n let comp: ProgrammingAssessmentRepoExportDialogComponent;\n let fixture: ComponentFixture<ProgrammingAssessmentRepoExportDialogComponent>;\n let exerciseService: ExerciseService;\n let repoExportService: ProgrammingAssessmentRepoExportService;\n\n global.URL.createObjectURL = jest.fn(() => 'http://some.test.com');\n global.URL.revokeObjectURL = jest.fn(() => '');\n\n const exerciseId = 42;\n const participationIdList = [1];\n const singleParticipantMode = false;\n const programmingExercise = new ProgrammingExercise(new Course(), undefined);\n programmingExercise.id = exerciseId;\n programmingExercise.releaseDate = moment();\n programmingExercise.dueDate = moment().add(7, 'days');\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisProgrammingAssessmentModule],\n providers: [\n ExerciseService,\n ProgrammingAssessmentRepoExportService,\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n // Ignore console errors\n console.error = () => false;\n fixture = TestBed.createComponent(ProgrammingAssessmentRepoExportDialogComponent);\n comp = fixture.componentInstance;\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n repoExportService = fixture.debugElement.injector.get(ProgrammingAssessmentRepoExportService);\n\n // stubs\n stub(exerciseService, 'find').returns(of({ body: programmingExercise } as HttpResponse<Exercise>));\n\n comp.exerciseId = exerciseId;\n comp.participationIdList = participationIdList;\n comp.singleParticipantMode = singleParticipantMode;\n });\n });\n\n it('test initialization', () => {\n fixture.detectChanges();\n expect(comp.exerciseId).to.be.equal(42);\n });\n\n it('Exercise service should find the correct programming exercise', () => {\n fixture.detectChanges();\n expect(comp.exercise).to.be.equal(programmingExercise);\n });\n\n it('Export a repo by participations should download a zipped file', fakeAsync(() => {\n const httpResponse = createBlobHttpResponse();\n const exportReposStub = stub(repoExportService, 'exportReposByParticipations').returns(of(httpResponse));\n fixture.detectChanges();\n\n comp.exportRepos(exerciseId);\n tick();\n expect(comp.repositoryExportOptions.addParticipantName).to.be.false;\n expect(comp.repositoryExportOptions.hideStudentNameInZippedFolder).to.be.true;\n expect(comp.exportInProgress).to.be.false;\n expect(exportReposStub).to.be.calledOnce;\n }));\n\n it('Export a repo by participant identifiers should download a zipped file', fakeAsync(() => {\n comp.participationIdList = [];\n comp.participantIdentifierList = 'ALL';\n const httpResponse = createBlobHttpResponse();\n const exportReposStub = stub(repoExportService, 'exportReposByParticipantIdentifiers').returns(of(httpResponse));\n fixture.detectChanges();\n\n comp.exportRepos(exerciseId);\n tick();\n expect(comp.repositoryExportOptions.addParticipantName).to.be.true;\n expect(comp.exportInProgress).to.be.false;\n expect(exportReposStub).to.be.calledOnce;\n }));\n\n it('Export of multiple repos download multiple files', fakeAsync(() => {\n const programmingExercise2 = new ProgrammingExercise(new Course(), undefined);\n programmingExercise2.id = 43;\n comp.selectedProgrammingExercises = [programmingExercise, programmingExercise2];\n const httpResponse = createBlobHttpResponse();\n const exportReposStub = stub(repoExportService, 'exportReposByParticipations').returns(of(httpResponse));\n fixture.detectChanges();\n\n comp.bulkExportRepos();\n tick();\n expect(comp.repositoryExportOptions.exportAllParticipants).to.be.true;\n expect(comp.exportInProgress).to.be.false;\n expect(exportReposStub).to.be.calledTwice;\n }));\n});\n" }, { "alpha_fraction": 0.6668996214866638, "alphanum_fraction": 0.667132556438446, "avg_line_length": 39.88571548461914, "blob_id": "0c0f50756b83d91da50b629b737ab14654c74d01", "content_id": "19dc6ad641bc7e56360d4ef39b49b2631b8f4109", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4293, "license_type": "permissive", "max_line_length": 151, "num_lines": 105, "path": "/src/test/javascript/spec/component/admin/system-notification-management/system-notification-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { SystemNotificationManagementUpdateComponent } from 'app/admin/system-notification-management/system-notification-management-update.component';\nimport { SystemNotification } from 'app/entities/system-notification.model';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';\nimport { SystemNotificationService } from 'app/shared/notification/system-notification/system-notification.service';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { spy } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('SystemNotificationManagementUpdateComponent', () => {\n let updateComponentFixture: ComponentFixture<SystemNotificationManagementUpdateComponent>;\n let updateComponent: SystemNotificationManagementUpdateComponent;\n let service: SystemNotificationService;\n\n const route = ({\n parent: {\n data: of({ notification: { id: 1, title: 'test' } as SystemNotification }),\n },\n } as any) as ActivatedRoute;\n const router = { navigate() {} };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule],\n declarations: [\n SystemNotificationManagementUpdateComponent,\n MockPipe(ArtemisTranslatePipe),\n MockDirective(AlertErrorComponent),\n MockDirective(FormDateTimePickerComponent),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: Router, useValue: router },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n updateComponentFixture = TestBed.createComponent(SystemNotificationManagementUpdateComponent);\n updateComponent = updateComponentFixture.componentInstance;\n service = updateComponentFixture.debugElement.injector.get(SystemNotificationService);\n sinon.stub(router, 'navigate');\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n updateComponentFixture.detectChanges();\n expect(updateComponent).to.be.ok;\n });\n\n it('navigate back if cancel is clicked', fakeAsync(() => {\n const previousStateSpy = spy(updateComponent, 'previousState');\n updateComponentFixture.detectChanges();\n\n const button = updateComponentFixture.debugElement.nativeElement.querySelector('#cancelButton');\n button.click();\n\n tick();\n expect(previousStateSpy).to.have.been.calledOnce;\n }));\n\n it('should update if save is clicked', fakeAsync(() => {\n const saveSpy = spy(updateComponent, 'save');\n spyOn(service, 'update').and.returnValue(of(new HttpResponse()));\n updateComponentFixture.detectChanges();\n\n const button = updateComponentFixture.debugElement.nativeElement.querySelector('#saveButton');\n button.click();\n\n tick();\n expect(saveSpy).to.have.been.calledOnce;\n }));\n\n it('should create if save is clicked', fakeAsync(() => {\n const saveSpy = spy(updateComponent, 'save');\n spyOn(service, 'create').and.returnValue(of(new HttpResponse()));\n updateComponentFixture.detectChanges();\n\n // Set to invalid id to emulate a new notification\n updateComponent.notification.id = undefined;\n updateComponentFixture.detectChanges();\n\n const button = updateComponentFixture.debugElement.nativeElement.querySelector('#saveButton');\n button.click();\n\n tick();\n expect(saveSpy).to.have.been.calledOnce;\n }));\n});\n" }, { "alpha_fraction": 0.7411275506019592, "alphanum_fraction": 0.7442220449447632, "avg_line_length": 57.09550476074219, "blob_id": "a6afa77ffb0dd0a727a21b6538fa644756e1b90a", "content_id": "e6fc382c4ab2aced97a26d75d6020e50cf96614a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10341, "license_type": "permissive", "max_line_length": 180, "num_lines": 178, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseTestCaseService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.boot.actuate.audit.AuditEvent;\nimport org.springframework.boot.actuate.audit.AuditEventRepository;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.Visibility;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseTestCaseRepository;\nimport de.tum.in.www1.artemis.web.rest.dto.ProgrammingExerciseTestCaseDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n@Service\npublic class ProgrammingExerciseTestCaseService {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseTestCaseService.class);\n\n private final ProgrammingExerciseTestCaseRepository testCaseRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final ProgrammingSubmissionService programmingSubmissionService;\n\n private final AuditEventRepository auditEventRepository;\n\n public ProgrammingExerciseTestCaseService(ProgrammingExerciseTestCaseRepository testCaseRepository, ProgrammingExerciseRepository programmingExerciseRepository,\n ProgrammingSubmissionService programmingSubmissionService, AuditEventRepository auditEventRepository) {\n this.testCaseRepository = testCaseRepository;\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.programmingSubmissionService = programmingSubmissionService;\n this.auditEventRepository = auditEventRepository;\n }\n\n /**\n * Returns all test cases for a programming exercise.\n *\n * @param exerciseId of a programming exercise.\n * @return test cases of a programming exercise.\n */\n public Set<ProgrammingExerciseTestCase> findByExerciseId(Long exerciseId) {\n return this.testCaseRepository.findByExerciseId(exerciseId);\n }\n\n /**\n * Returns all active test cases for a programming exercise. Only active test cases are evaluated on build runs.\n *\n * @param exerciseId of a programming exercise.\n * @return active test cases of a programming exercise.\n */\n public Set<ProgrammingExerciseTestCase> findActiveByExerciseId(Long exerciseId) {\n return this.testCaseRepository.findByExerciseIdAndActive(exerciseId, true);\n }\n\n /**\n * Update the updatable attributes of the provided test case dtos. Returns an entry in the set for each test case that could be updated.\n *\n * @param exerciseId of exercise the test cases belong to.\n * @param testCaseProgrammingExerciseTestCaseDTOS of the test cases to update the weights and visibility of.\n * @return the updated test cases.\n * @throws EntityNotFoundException if the programming exercise could not be found.\n * @throws IllegalAccessException if the retriever does not have the permissions to fetch information related to the programming exercise.\n */\n public Set<ProgrammingExerciseTestCase> update(Long exerciseId, Set<ProgrammingExerciseTestCaseDTO> testCaseProgrammingExerciseTestCaseDTOS)\n throws EntityNotFoundException, IllegalAccessException {\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findWithTestCasesById(exerciseId)\n .orElseThrow(() -> new EntityNotFoundException(\"Programming Exercise\", exerciseId));\n\n Set<ProgrammingExerciseTestCase> existingTestCases = programmingExercise.getTestCases();\n Set<ProgrammingExerciseTestCase> updatedTests = new HashSet<>();\n for (ProgrammingExerciseTestCaseDTO programmingExerciseTestCaseDTO : testCaseProgrammingExerciseTestCaseDTOS) {\n Optional<ProgrammingExerciseTestCase> matchingTestCaseOpt = existingTestCases.stream()\n .filter(testCase -> testCase.getId().equals(programmingExerciseTestCaseDTO.getId())).findFirst();\n if (matchingTestCaseOpt.isEmpty()) {\n continue;\n }\n\n ProgrammingExerciseTestCase matchingTestCase = matchingTestCaseOpt.get();\n matchingTestCase.setWeight(programmingExerciseTestCaseDTO.getWeight());\n matchingTestCase.setVisibility(programmingExerciseTestCaseDTO.getVisibility());\n matchingTestCase.setBonusMultiplier(programmingExerciseTestCaseDTO.getBonusMultiplier());\n matchingTestCase.setBonusPoints(programmingExerciseTestCaseDTO.getBonusPoints());\n updatedTests.add(matchingTestCase);\n }\n\n // Make sure that at least one test has a weight so that students can still achieve 100% score\n var testWeightsSum = existingTestCases.stream().mapToDouble(testCase -> Optional.ofNullable(testCase.getWeight()).orElse(0.0)).sum();\n if (testWeightsSum <= 0) {\n throw new BadRequestAlertException(\"The sum of all test case weights is 0 or below.\", \"TestCaseGrading\", \"weightSumError\");\n }\n\n testCaseRepository.saveAll(updatedTests);\n // At least one test was updated with a new weight or runAfterDueDate flag. We use this flag to inform the instructor about outdated student results.\n programmingSubmissionService.setTestCasesChangedAndTriggerTestCaseUpdate(exerciseId);\n return updatedTests;\n }\n\n /**\n * Reset the weights of all test cases to 1.\n *\n * @param exerciseId to find exercise test cases\n * @return test cases that have been reset\n */\n public List<ProgrammingExerciseTestCase> reset(Long exerciseId) {\n Set<ProgrammingExerciseTestCase> testCases = this.testCaseRepository.findByExerciseId(exerciseId);\n for (ProgrammingExerciseTestCase testCase : testCases) {\n testCase.setWeight(1.0);\n testCase.setBonusMultiplier(1.0);\n testCase.setBonusPoints(0.0);\n }\n List<ProgrammingExerciseTestCase> updatedTestCases = testCaseRepository.saveAll(testCases);\n // The tests' weights were updated. We use this flag to inform the instructor about outdated student results.\n programmingSubmissionService.setTestCasesChangedAndTriggerTestCaseUpdate(exerciseId);\n return updatedTestCases;\n }\n\n /**\n * From a list of build run feedback, extract all test cases. If an already stored test case is not found anymore in the build result, it will not be deleted, but set inactive.\n * This way old test cases are not lost, some interfaces in the client might need this information to e.g. show warnings.\n *\n * @param feedbacks list of build log output.\n * @param exercise programming exercise.\n * @return Returns true if the test cases have changed, false if they haven't.\n */\n public boolean generateTestCasesFromFeedbacks(List<Feedback> feedbacks, ProgrammingExercise exercise) {\n Set<ProgrammingExerciseTestCase> existingTestCases = testCaseRepository.findByExerciseId(exercise.getId());\n // Do not generate test cases for static code analysis feedback\n Set<ProgrammingExerciseTestCase> testCasesFromFeedbacks = getTestCasesFromFeedbacks(feedbacks, exercise);\n // Get test cases that are not already in database - those will be added as new entries.\n Set<ProgrammingExerciseTestCase> newTestCases = testCasesFromFeedbacks.stream().filter(testCase -> existingTestCases.stream().noneMatch(testCase::isSameTestCase))\n .collect(Collectors.toSet());\n // Get test cases which activate state flag changed.\n Set<ProgrammingExerciseTestCase> testCasesWithUpdatedActivation = getTestCasesWithUpdatedActivation(existingTestCases, testCasesFromFeedbacks);\n\n Set<ProgrammingExerciseTestCase> testCasesToSave = new HashSet<>();\n testCasesToSave.addAll(newTestCases);\n testCasesToSave.addAll(testCasesWithUpdatedActivation);\n\n if (testCasesToSave.size() > 0) {\n testCaseRepository.saveAll(testCasesToSave);\n return true;\n }\n return false;\n }\n\n private Set<ProgrammingExerciseTestCase> getTestCasesFromFeedbacks(List<Feedback> feedbacks, ProgrammingExercise exercise) {\n // Filter out sca feedback and create test cases out of the feedbacks\n return feedbacks.stream().filter(feedback -> !feedback.isStaticCodeAnalysisFeedback())\n // we use default values for weight, bonus multiplier and bonus points\n .map(feedback -> new ProgrammingExerciseTestCase().testName(feedback.getText()).weight(1.0).bonusMultiplier(1.0).bonusPoints(0.0).exercise(exercise).active(true)\n .visibility(Visibility.ALWAYS))\n .collect(Collectors.toSet());\n }\n\n private Set<ProgrammingExerciseTestCase> getTestCasesWithUpdatedActivation(Set<ProgrammingExerciseTestCase> existingTestCases,\n Set<ProgrammingExerciseTestCase> testCasesFromFeedbacks) {\n // We compare the new generated test cases from feedback with the existing test cases from the database\n return existingTestCases.stream().filter(existing -> {\n Optional<ProgrammingExerciseTestCase> matchingTestCase = testCasesFromFeedbacks.stream().filter(existing::isSameTestCase).findFirst();\n // Either the test case was active and is not part of the feedback anymore OR was not active before and is now part of the feedback again.\n return matchingTestCase.isEmpty() && existing.isActive() || matchingTestCase.isPresent() && matchingTestCase.get().isActive() && !existing.isActive();\n }).map(existing -> existing.clone().active(!existing.isActive())).collect(Collectors.toSet());\n }\n\n public void logTestCaseReset(User user, ProgrammingExercise exercise, Course course) {\n var auditEvent = new AuditEvent(user.getLogin(), Constants.RESET_GRADING, \"exercise=\" + exercise.getTitle(), \"course=\" + course.getTitle());\n auditEventRepository.add(auditEvent);\n log.info(\"User {} requested to reset the grading configuration for exercise {} with id {}\", user.getLogin(), exercise.getTitle(), exercise.getId());\n }\n\n}\n" }, { "alpha_fraction": 0.6672128438949585, "alphanum_fraction": 0.6672128438949585, "avg_line_length": 47.610618591308594, "blob_id": "57d610269ab8fcb8007463e1098b7d5e5be73c9c", "content_id": "4adac5972ca96b0e783a43ba45f6fe09c6082ff1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5493, "license_type": "permissive", "max_line_length": 179, "num_lines": 113, "path": "/src/main/webapp/app/overview/course-learning-goals/course-learning-goals.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { onError } from 'app/shared/util/global.utils';\nimport { finalize } from 'rxjs/operators';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { forkJoin } from 'rxjs';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport * as _ from 'lodash';\nimport { AccountService } from 'app/core/auth/account.service';\nimport * as Sentry from '@sentry/browser';\n\n@Component({\n selector: 'jhi-course-learning-goals',\n templateUrl: './course-learning-goals.component.html',\n styles: [],\n})\nexport class CourseLearningGoalsComponent implements OnInit {\n @Input()\n courseId: number;\n\n isLoading = false;\n learningGoals: LearningGoal[] = [];\n learningGoalIdToLearningGoalProgress = new Map<number, IndividualLearningGoalProgress>();\n\n // this is calculated using the participant scores table on the server instead of going participation -> submission -> result\n // we calculate it here to find out if the participant scores table is robust enough to replace the classic way of finding the last result\n learningGoalIdToLearningGoalProgressUsingParticipantScoresTables = new Map<number, IndividualLearningGoalProgress>();\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private alertService: JhiAlertService,\n private learningGoalService: LearningGoalService,\n private accountService: AccountService,\n ) {}\n\n ngOnInit(): void {\n this.activatedRoute.parent!.params.subscribe((params) => {\n this.courseId = +params['courseId'];\n if (this.courseId) {\n this.loadData();\n }\n });\n }\n\n getLearningGoalProgress(learningGoal: LearningGoal) {\n return this.learningGoalIdToLearningGoalProgress.get(learningGoal.id!);\n }\n\n loadData() {\n this.isLoading = true;\n this.learningGoalService\n .getAllForCourse(this.courseId)\n .switchMap((res) => {\n this.learningGoals = res.body!;\n\n const progressObservable = this.learningGoals.map((lg) => {\n return this.learningGoalService.getProgress(lg.id!, this.courseId, false);\n });\n\n const progressObservableUsingParticipantScore = this.learningGoals.map((lg) => {\n return this.learningGoalService.getProgress(lg.id!, this.courseId, true);\n });\n\n return forkJoin([forkJoin(progressObservable), forkJoin(progressObservableUsingParticipantScore)]);\n })\n .pipe(\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n ([learningGoalProgressResponses, learningGoalProgressResponsesUsingParticipantScores]) => {\n for (const learningGoalProgressResponse of learningGoalProgressResponses) {\n const learningGoalProgress = learningGoalProgressResponse.body!;\n this.learningGoalIdToLearningGoalProgress.set(learningGoalProgress.learningGoalId, learningGoalProgress);\n }\n for (const learningGoalProgressResponse of learningGoalProgressResponsesUsingParticipantScores) {\n const learningGoalProgress = learningGoalProgressResponse.body!;\n this.learningGoalIdToLearningGoalProgressUsingParticipantScoresTables.set(learningGoalProgress.learningGoalId, learningGoalProgress);\n }\n this.testIfScoreUsingParticipantScoresTableDiffers();\n },\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n\n identify(index: number, learningGoal: LearningGoal) {\n return `${index}-${learningGoal.id}`;\n }\n\n /**\n * Using this test we want to find out if the progress calculation using the participant scores table leads to the same\n * result as going through participation -> submission -> result\n */\n private testIfScoreUsingParticipantScoresTableDiffers() {\n this.learningGoalIdToLearningGoalProgress.forEach((learningGoalProgress, learningGoalId) => {\n const learningGoalProgressParticipantScoresTable = this.learningGoalIdToLearningGoalProgressUsingParticipantScoresTables.get(learningGoalId);\n if (!_.isEqual(learningGoalProgress.pointsAchievedByStudentInLearningGoal, learningGoalProgressParticipantScoresTable!.pointsAchievedByStudentInLearningGoal)) {\n const userName = this.accountService.userIdentity?.login;\n const message = `Warning: Learning Goal(id=${\n learningGoalProgress.learningGoalId\n }) Progress different using participant scores for user ${userName}! Original: ${JSON.stringify(learningGoalProgress)} | Using ParticipantScores: ${JSON.stringify(\n learningGoalProgressParticipantScoresTable,\n )}!`;\n console.log(message);\n Sentry.captureException(new Error(message));\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.7384843826293945, "alphanum_fraction": 0.7384843826293945, "avg_line_length": 36.38888931274414, "blob_id": "4769b371db135ed907d7fd19a8208558a98c9cfe", "content_id": "9321665dd9f079711b7dd513ece052ad2c7ff802", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 673, "license_type": "permissive", "max_line_length": 105, "num_lines": 18, "path": "/src/main/webapp/app/shared/pipes/html-for-guided-tour-markdown.pipe.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Pipe, PipeTransform } from '@angular/core';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\n\n@Pipe({\n name: 'htmlForGuidedTourMarkdown',\n})\nexport class HtmlForGuidedTourMarkdownPipe implements PipeTransform {\n constructor(private markdownService: ArtemisMarkdownService) {}\n\n /**\n * Converts markdown into html, sanitizes it and then declares it as safe to bypass further security.\n * @param {string} markdown the original markdown text\n */\n transform(markdown: string): SafeHtml {\n return this.markdownService.htmlForGuidedTourMarkdown(markdown);\n }\n}\n" }, { "alpha_fraction": 0.7544154524803162, "alphanum_fraction": 0.7566582560539246, "avg_line_length": 46.560001373291016, "blob_id": "6baaecb5a62c2c62b252fd84dbc18dfceadb35a0", "content_id": "7b5a004958ca36abadfc8989b2dff3a96852ea6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3567, "license_type": "permissive", "max_line_length": 176, "num_lines": 75, "path": "/src/main/java/de/tum/in/www1/artemis/service/ExampleSubmissionService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.util.Optional;\n\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.domain.ExampleSubmission;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.Submission;\nimport de.tum.in.www1.artemis.domain.participation.TutorParticipation;\nimport de.tum.in.www1.artemis.repository.ExampleSubmissionRepository;\nimport de.tum.in.www1.artemis.repository.ExerciseRepository;\nimport de.tum.in.www1.artemis.repository.SubmissionRepository;\n\n@Service\npublic class ExampleSubmissionService {\n\n private final ExampleSubmissionRepository exampleSubmissionRepository;\n\n private final SubmissionRepository submissionRepository;\n\n private final ExerciseRepository exerciseRepository;\n\n public ExampleSubmissionService(ExampleSubmissionRepository exampleSubmissionRepository, SubmissionRepository submissionRepository, ExerciseRepository exerciseRepository) {\n this.exampleSubmissionRepository = exampleSubmissionRepository;\n this.submissionRepository = submissionRepository;\n this.exerciseRepository = exerciseRepository;\n }\n\n /**\n * First saves the corresponding submission with the exampleSubmission flag. Then the example submission itself is saved.\n *\n * @param exampleSubmission the example submission to save\n * @return the exampleSubmission entity\n */\n public ExampleSubmission save(ExampleSubmission exampleSubmission) {\n Submission submission = exampleSubmission.getSubmission();\n if (submission != null) {\n submission.setExampleSubmission(true);\n // Rebuild connection between result and submission, if it has been lost, because hibernate needs it\n if (submission.getLatestResult() != null && submission.getLatestResult().getSubmission() == null) {\n submission.getLatestResult().setSubmission(submission);\n }\n submissionRepository.save(submission);\n }\n return exampleSubmissionRepository.save(exampleSubmission);\n }\n\n /**\n * Deletes a ExampleSubmission with the given ID, cleans up the tutor participations, removes the result and the submission\n * @param exampleSubmissionId the ID of the ExampleSubmission which should be deleted\n */\n @Transactional // ok\n public void deleteById(long exampleSubmissionId) {\n Optional<ExampleSubmission> optionalExampleSubmission = exampleSubmissionRepository.findByIdWithResultsAndTutorParticipations(exampleSubmissionId);\n\n if (optionalExampleSubmission.isPresent()) {\n ExampleSubmission exampleSubmission = optionalExampleSubmission.get();\n\n for (TutorParticipation tutorParticipation : exampleSubmission.getTutorParticipations()) {\n tutorParticipation.getTrainedExampleSubmissions().remove(exampleSubmission);\n }\n\n Long exerciseId = exampleSubmission.getExercise().getId();\n Optional<Exercise> exerciseWithExampleSubmission = exerciseRepository.findByIdWithEagerExampleSubmissions(exerciseId);\n\n // Remove the reference to the exercise when the example submission is deleted\n exerciseWithExampleSubmission.ifPresent(exercise -> exercise.removeExampleSubmission(exampleSubmission));\n\n // due to Cascade.Remove this will also remove the submission and the result in case they exist\n exampleSubmissionRepository.delete(exampleSubmission);\n }\n }\n}\n" }, { "alpha_fraction": 0.6814562082290649, "alphanum_fraction": 0.6814562082290649, "avg_line_length": 35.625, "blob_id": "eacdda5f39d454b9d87c0ee32410dde4e2e2a7e4", "content_id": "8e3f17aeff3ddc8834047d6258c2446285f192cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 879, "license_type": "permissive", "max_line_length": 127, "num_lines": 24, "path": "/src/main/webapp/app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\n\n@Injectable({ providedIn: 'root' })\nexport class QuizReEvaluateService {\n private resourceUrl = SERVER_API_URL + 'api/quiz-exercises/';\n\n constructor(private http: HttpClient) {}\n\n update(quizExercise: QuizExercise) {\n const copy = this.convert(quizExercise);\n return this.http.put<QuizExercise>(this.resourceUrl + quizExercise.id + '/re-evaluate', copy, { observe: 'response' });\n }\n\n /**\n * Convert a QuizExercise to a JSON which can be sent to the server.\n */\n private convert(quizExercise: QuizExercise): QuizExercise {\n const copy: QuizExercise = Object.assign({}, quizExercise);\n return copy;\n }\n}\n" }, { "alpha_fraction": 0.6909143924713135, "alphanum_fraction": 0.692375123500824, "avg_line_length": 40.240962982177734, "blob_id": "101d030c840e86d516c1b2d45088bf6a4516cd0f", "content_id": "e853c5115d383cdca1a5db1f5e82e5bfa2aeb7c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3423, "license_type": "permissive", "max_line_length": 174, "num_lines": 83, "path": "/src/main/webapp/app/core/auth/auth-jwt.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Observable, of } from 'rxjs';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { map } from 'rxjs/operators';\n\nexport class Credentials {\n constructor(public username: string, public password: string, public rememberMe: boolean) {}\n}\n\ntype JwtToken = {\n id_token: string;\n};\n\nexport interface IAuthServerProvider {\n getToken: () => string;\n login: (credentials: Credentials) => Observable<void>;\n loginWithToken: (jwt: string, rememberMe: boolean) => Promise<string>;\n storeAuthenticationToken: (jwt: string, rememberMe: boolean) => void;\n removeAuthTokenFromCaches: () => Observable<undefined>;\n clearCaches: () => Observable<undefined>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class AuthServerProvider implements IAuthServerProvider {\n constructor(private http: HttpClient, private localStorage: LocalStorageService, private sessionStorage: SessionStorageService) {}\n\n getToken() {\n return this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');\n }\n\n login(credentials: Credentials): Observable<void> {\n return this.http.post<JwtToken>(SERVER_API_URL + 'api/authenticate', credentials).pipe(map((response) => this.authenticateSuccess(response, credentials.rememberMe)));\n }\n\n loginSAML2(rememberMe: boolean): Observable<void> {\n return this.http.post<JwtToken>(SERVER_API_URL + 'api/saml2', rememberMe.toString()).pipe(map((response) => this.authenticateSuccess(response, rememberMe)));\n }\n\n loginWithToken(jwt: string, rememberMe: boolean): Promise<string> {\n if (jwt) {\n this.storeAuthenticationToken(jwt, rememberMe);\n return Promise.resolve(jwt);\n } else {\n return Promise.reject('auth-jwt-service Promise reject'); // Put appropriate error message here\n }\n }\n\n private authenticateSuccess(response: JwtToken, rememberMe: boolean): void {\n const jwt = response.id_token;\n this.storeAuthenticationToken(jwt, rememberMe);\n }\n\n storeAuthenticationToken(jwt: string, rememberMe: boolean): void {\n if (rememberMe) {\n this.localStorage.store('authenticationToken', jwt);\n } else {\n this.sessionStorage.store('authenticationToken', jwt);\n }\n }\n\n /**\n * Removes the user's auth tokens from the browser's caches.\n * This will lead to all endpoint requests failing with a 401.\n */\n removeAuthTokenFromCaches(): Observable<undefined> {\n this.localStorage.clear('authenticationToken');\n this.sessionStorage.clear('authenticationToken');\n // The local or session storage might have to be cleared asynchronously in future due to updated browser apis. This is why this method is already acting asynchronous.\n return of(undefined);\n }\n\n /**\n * Clears all the caches, should be invoked during logout\n */\n clearCaches(): Observable<undefined> {\n this.localStorage.clear();\n this.sessionStorage.clear();\n // The local or session storage might have to be cleared asynchronously in future due to updated browser apis. This is why this method is already acting asynchronous.\n return of(undefined);\n }\n}\n" }, { "alpha_fraction": 0.7062706351280212, "alphanum_fraction": 0.7081565260887146, "avg_line_length": 28.873239517211914, "blob_id": "aeaf4622a30e7495365517d28a7f13e2a8d8e896", "content_id": "712d1d88c36e1c081095c52e19d82005f9a518c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2121, "license_type": "permissive", "max_line_length": 142, "num_lines": 71, "path": "/src/main/java/de/tum/in/www1/artemis/web/websocket/dto/TeamAssignmentPayload.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.websocket.dto;\n\nimport java.util.List;\nimport java.util.Objects;\nimport java.util.Optional;\n\nimport javax.annotation.Nullable;\nimport javax.validation.constraints.NotNull;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.Team;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class TeamAssignmentPayload {\n\n @NotNull\n private Exercise exercise;\n\n @Nullable\n private Team team;\n\n @NotNull\n private List<StudentParticipation> studentParticipations = List.of();\n\n public TeamAssignmentPayload(@NotNull Exercise exercise, @Nullable Team team) {\n this.exercise = exercise;\n this.team = team;\n }\n\n public TeamAssignmentPayload(@NotNull Exercise exercise, @Nullable Team team, @NotNull List<StudentParticipation> studentParticipations) {\n this(exercise, team);\n this.studentParticipations = studentParticipations;\n }\n\n public void setExercise(@NotNull Exercise exercise) {\n this.exercise = exercise;\n }\n\n public void setTeam(@Nullable Team team) {\n this.team = team;\n }\n\n public void setStudentParticipations(@NotNull List<StudentParticipation> studentParticipations) {\n this.studentParticipations = studentParticipations;\n }\n\n public long getExerciseId() {\n return this.exercise.getId();\n }\n\n public Long getTeamId() {\n return Optional.ofNullable(this.team).map(Team::getId).orElse(null);\n }\n\n public List<StudentParticipation> getStudentParticipations() {\n return this.studentParticipations;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n TeamAssignmentPayload that = (TeamAssignmentPayload) o;\n return exercise.equals(that.exercise) && Objects.equals(team, that.team) && studentParticipations.equals(that.studentParticipations);\n }\n}\n" }, { "alpha_fraction": 0.6363485455513, "alphanum_fraction": 0.6376763582229614, "avg_line_length": 50.93965530395508, "blob_id": "620bfbafc2c382c7a67d7d3cb21ef359eca426ff", "content_id": "b5afa001950339f5dff8b0e0a87b6cdf69556f2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 18075, "license_type": "permissive", "max_line_length": 190, "num_lines": 348, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlab/GitLabUserManagementService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.gitlab;\n\nimport static org.gitlab4j.api.models.AccessLevel.*;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.gitlab4j.api.GitLabApi;\nimport org.gitlab4j.api.GitLabApiException;\nimport org.gitlab4j.api.models.AccessLevel;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.service.connectors.VcsUserManagementService;\nimport de.tum.in.www1.artemis.service.user.PasswordService;\n\n@Service\n@Profile(\"gitlab\")\npublic class GitLabUserManagementService implements VcsUserManagementService {\n\n private final Logger log = LoggerFactory.getLogger(GitLabUserManagementService.class);\n\n private final PasswordService passwordService;\n\n private final UserRepository userRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final GitLabApi gitlabApi;\n\n @Value(\"${gitlab.use-pseudonyms:#{false}}\")\n private boolean usePseudonyms;\n\n public GitLabUserManagementService(ProgrammingExerciseRepository programmingExerciseRepository, GitLabApi gitlabApi, UserRepository userRepository,\n PasswordService passwordService) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.gitlabApi = gitlabApi;\n this.userRepository = userRepository;\n this.passwordService = passwordService;\n }\n\n @Override\n public void createVcsUser(User user) {\n final var userId = getUserIdCreateIfNotExists(user);\n\n // Add user to existing exercises\n if (user.getGroups() != null && user.getGroups().size() > 0) {\n final var instructorExercises = programmingExerciseRepository.findAllByCourse_InstructorGroupNameIn(user.getGroups());\n final var teachingAssistantExercises = programmingExerciseRepository.findAllByCourse_TeachingAssistantGroupNameIn(user.getGroups()).stream()\n .filter(programmingExercise -> !instructorExercises.contains(programmingExercise)).collect(Collectors.toList());\n addUserToGroups(userId, instructorExercises, MAINTAINER);\n addUserToGroups(userId, teachingAssistantExercises, REPORTER);\n }\n }\n\n @Override\n public void updateVcsUser(String vcsLogin, User user, Set<String> removedGroups, Set<String> addedGroups, boolean shouldSynchronizePassword) {\n try {\n var userApi = gitlabApi.getUserApi();\n final var gitlabUser = userApi.getUser(vcsLogin);\n if (gitlabUser == null) {\n // in case the user does not exist in Gitlab, we cannot update it\n log.warn(\"User {} does not exist in Gitlab and cannot be updated!\", user.getLogin());\n return;\n }\n\n // Update general user information. Skip confirmation is necessary\n // in order to update the email without user re-confirmation\n gitlabUser.setName(getUsersName(user));\n gitlabUser.setUsername(user.getLogin());\n gitlabUser.setEmail(user.getEmail());\n gitlabUser.setSkipConfirmation(true);\n\n if (shouldSynchronizePassword) {\n // update the user password in Gitlab with the one stored in the Artemis database\n userApi.updateUser(gitlabUser, passwordService.decryptPassword(user));\n }\n else {\n userApi.updateUser(gitlabUser, null);\n }\n\n // Add as member to new groups\n if (addedGroups != null && !addedGroups.isEmpty()) {\n final var exercisesWithAddedGroups = programmingExerciseRepository.findAllByInstructorOrTAGroupNameIn(addedGroups);\n for (final var exercise : exercisesWithAddedGroups) {\n final var accessLevel = addedGroups.contains(exercise.getCourseViaExerciseGroupOrCourseMember().getInstructorGroupName()) ? MAINTAINER : REPORTER;\n try {\n gitlabApi.getGroupApi().addMember(exercise.getProjectKey(), gitlabUser.getId(), accessLevel);\n }\n catch (GitLabApiException ex) {\n // if user is already member of group in GitLab, ignore the exception to synchronize the \"membership\" with artemis\n // ignore other errors\n if (!\"Member already exists\".equalsIgnoreCase(ex.getMessage())) {\n log.error(\"Gitlab Exception when adding a user \" + gitlabUser.getId() + \" to a group \" + exercise.getProjectKey(), ex);\n }\n }\n }\n }\n\n // Update/remove old groups\n if (removedGroups != null && !removedGroups.isEmpty()) {\n final var exercisesWithOutdatedGroups = programmingExerciseRepository.findAllByInstructorOrTAGroupNameIn(removedGroups);\n for (final var exercise : exercisesWithOutdatedGroups) {\n // If the the user is still in another group for the exercise (TA -> INSTRUCTOR or INSTRUCTOR -> TA),\n // then we have to add him as a member with the new access level\n final var course = exercise.getCourseViaExerciseGroupOrCourseMember();\n if (user.getGroups().contains(course.getInstructorGroupName())) {\n gitlabApi.getGroupApi().updateMember(exercise.getProjectKey(), gitlabUser.getId(), MAINTAINER);\n }\n else if (user.getGroups().contains(course.getTeachingAssistantGroupName())) {\n gitlabApi.getGroupApi().updateMember(exercise.getProjectKey(), gitlabUser.getId(), REPORTER);\n }\n else {\n // If the user is not a member of any relevant group any more, we can remove him from the exercise\n try {\n gitlabApi.getGroupApi().removeMember(exercise.getProjectKey(), gitlabUser.getId());\n }\n catch (GitLabApiException ex) {\n // If user membership to group is missing on Gitlab, ignore the exception\n // and let artemis synchronize with GitLab groups\n if (ex.getHttpStatus() != 404) {\n log.error(\"Gitlab Exception when removing a user \" + gitlabUser.getId() + \" to a group \" + exercise.getProjectKey(), ex);\n }\n }\n }\n }\n }\n }\n catch (GitLabApiException e) {\n throw new GitLabException(\"Error while trying to update user in GitLab: \" + user, e);\n }\n }\n\n @Override\n public void updateCoursePermissions(Course updatedCourse, String oldInstructorGroup, String oldTeachingAssistantGroup) {\n if (oldInstructorGroup.equals(updatedCourse.getInstructorGroupName()) && oldTeachingAssistantGroup.equals(updatedCourse.getTeachingAssistantGroupName())) {\n // Do nothing if the group names didn't change\n return;\n }\n\n final var exercises = programmingExerciseRepository.findAllByCourse(updatedCourse);\n // All users that we already updated\n\n // Update the old instructors of the course\n final var oldInstructors = userRepository.findAllInGroupWithAuthorities(oldInstructorGroup);\n // doUpgrade=false, because these users already are instructors.\n updateOldGroupMembers(exercises, oldInstructors, updatedCourse.getInstructorGroupName(), updatedCourse.getTeachingAssistantGroupName(), REPORTER, false);\n final var processedUsers = new HashSet<>(oldInstructors);\n\n // Update the old teaching assistant of the group\n final var oldTeachingAssistants = userRepository.findAllUserInGroupAndNotIn(oldTeachingAssistantGroup, oldInstructors);\n // doUpgrade=true, because these users should be upgraded from TA to instructor, if possible.\n updateOldGroupMembers(exercises, oldTeachingAssistants, updatedCourse.getTeachingAssistantGroupName(), updatedCourse.getInstructorGroupName(), MAINTAINER, true);\n processedUsers.addAll(oldTeachingAssistants);\n\n // Now, we only have to add all users that have not been updated yet AND that are part of one of the new groups\n // Find all NEW instructors, that did not belong to the old TAs or instructors\n final var remainingInstructors = userRepository.findAllUserInGroupAndNotIn(updatedCourse.getInstructorGroupName(), processedUsers);\n remainingInstructors.forEach(user -> {\n final var userId = getUserId(user.getLogin());\n addUserToGroups(userId, exercises, MAINTAINER);\n });\n processedUsers.addAll(remainingInstructors);\n\n // Find all NEW TAs that did not belong to the old TAs or instructors\n final var remainingTeachingAssistants = userRepository.findAllUserInGroupAndNotIn(updatedCourse.getTeachingAssistantGroupName(), processedUsers);\n remainingTeachingAssistants.forEach(user -> {\n final var userId = getUserId(user.getLogin());\n addUserToGroups(userId, exercises, REPORTER);\n });\n }\n\n /**\n * Updates all exercise groups in GitLab for the new course instructor/TA group names. Removes users that are no longer\n * in any group and moves users to the new group, if they still have a valid group (e.g. instructor to TA).\n * If a user still belongs to a group that is valid for the same access level, he will stay on this level. If a user\n * can be upgraded, i.e. from instructor to TA, this will also be done.\n * All cases:\n * <ul>\n * <li>DOWNGRADE from instructor to TA</li>\n * <li>STAY instructor, because other group name is valid for newInstructorGroup</li>\n * <li>UPGRADE from TA to instructor</li>\n * <li>REMOVAL from GitLab group, because no valid active group is present</li>\n * </ul>\n *\n * @param exercises All exercises for the updated course\n * @param users All user in the old group\n * @param newGroupName The name of the new group, e.g. \"newInstructors\"\n * @param alternativeGroupName The name of the other group (instructor or TA), e.g. \"newTeachingAssistant\"\n * @param alternativeAccessLevel The access level for the alternative group, e.g. REPORTER for TAs\n * @param doUpgrade True, if the alternative group would be an upgrade. This is the case if the old group was TA, so the new instructor group would be better (if applicable)\n */\n private void updateOldGroupMembers(List<ProgrammingExercise> exercises, List<User> users, String newGroupName, String alternativeGroupName, AccessLevel alternativeAccessLevel,\n boolean doUpgrade) {\n for (final var user : users) {\n final var userId = getUserId(user.getLogin());\n /*\n * Contains the access level of the other group, to which the user currently does NOT belong, IF the user could be in that group E.g. user1(groups=[foo,bar]),\n * oldInstructorGroup=foo, oldTAGroup=bar; newInstructorGroup=instr newTAGroup=bar So, while the instructor group changed, the TA group stayed the same. user1 was part\n * of the old instructor group, but isn't any more. BUT he could be a TA according to the new groups, so the alternative access level would be the level of the TA\n * group, i.e. REPORTER\n */\n final Optional<AccessLevel> newAccessLevel;\n if (user.getGroups().contains(alternativeGroupName)) {\n newAccessLevel = Optional.of(alternativeAccessLevel);\n }\n else {\n // No alternative access level, if the user does not belong to ANY of the new groups (i.e. TA or instructor)\n newAccessLevel = Optional.empty();\n }\n // The user still is in the TA or instructor group\n final var userStillInRelevantGroup = user.getGroups().contains(newGroupName);\n // We cannot upgrade the user (i.e. from TA to instructor) if the alternative group would be below the current\n // one (i.e. instructor down to TA), or if the user is not eligible for the new access level:\n // TA to instructor, BUT the user does not belong to the new instructor group.\n final var cannotUpgrade = !doUpgrade || newAccessLevel.isEmpty();\n if (userStillInRelevantGroup && cannotUpgrade) {\n continue;\n }\n\n exercises.forEach(exercise -> {\n try {\n /*\n * Update the user, if 1. The user can be upgraded: TA -> instructor 2. We have to downgrade the user (instructor -> TA), if he only belongs to the new TA\n * group, but not to the instructor group any more\n */\n if (newAccessLevel.isPresent()) {\n gitlabApi.getGroupApi().updateMember(exercise.getProjectKey(), userId, newAccessLevel.get());\n }\n else {\n // Remove the user from the all groups, if he no longer is a TA, or instructor\n gitlabApi.getGroupApi().removeMember(exercise.getProjectKey(), userId);\n }\n }\n catch (GitLabApiException e) {\n throw new GitLabException(\"Error while updating GitLab group \" + exercise.getProjectKey(), e);\n }\n });\n }\n }\n\n @Override\n public void deleteVcsUser(String login) {\n try {\n // Delete by login String doesn't work, so we need to get the actual userId first.\n final var userId = getUserId(login);\n gitlabApi.getUserApi().deleteUser(userId, true);\n }\n catch (GitLabUserDoesNotExistException e) {\n log.warn(\"Cannot delete user ''{}'' in GitLab. User does not exist!\", login);\n }\n catch (GitLabApiException e) {\n throw new GitLabException(String.format(\"Cannot delete user %s from GitLab!\", login), e);\n }\n }\n\n private int getUserIdCreateIfNotExists(User user) {\n try {\n var gitlabUser = gitlabApi.getUserApi().getUser(user.getLogin());\n if (gitlabUser == null) {\n gitlabUser = importUser(user);\n }\n\n return gitlabUser.getId();\n }\n catch (GitLabApiException e) {\n throw new GitLabException(\"Unable to get ID for user \" + user.getLogin(), e);\n }\n }\n\n /**\n * adds a Gitlab user to a Gitlab group based on the provided exercises (project key) and the given access level\n *\n * @param userId the Gitlab user id\n * @param exercises the list of exercises which project key is used as the Gitlab \"group\" (i.e. Gitlab project)\n * @param accessLevel the access level that the user should get as part of the group/project\n */\n public void addUserToGroups(int userId, List<ProgrammingExercise> exercises, AccessLevel accessLevel) {\n for (final var exercise : exercises) {\n try {\n gitlabApi.getGroupApi().addMember(exercise.getProjectKey(), userId, accessLevel);\n }\n catch (GitLabApiException e) {\n if (e.getMessage().equals(\"Member already exists\")) {\n log.warn(\"Member already exists for group {}\", exercise.getProjectKey());\n return;\n }\n throw new GitLabException(String.format(\"Error adding new user [%d] to group [%s]\", userId, exercise.toString()), e);\n }\n }\n }\n\n /**\n * creates a Gitlab user account based on the passed Artemis user account with the same email, login, name and password\n *\n * @param user a valid Artemis user (account)\n * @return a Gitlab user\n */\n public org.gitlab4j.api.models.User importUser(User user) {\n final var gitlabUser = new org.gitlab4j.api.models.User().withEmail(user.getEmail()).withUsername(user.getLogin()).withName(getUsersName(user)).withCanCreateGroup(false)\n .withCanCreateProject(false).withSkipConfirmation(true);\n try {\n return gitlabApi.getUserApi().createUser(gitlabUser, passwordService.decryptPassword(user), false);\n }\n catch (GitLabApiException e) {\n throw new GitLabException(\"Unable to create new user in GitLab \" + user.getLogin(), e);\n }\n }\n\n private String getUsersName(User user) {\n // Get User's name by checking the use of pseudonyms\n String name;\n if (usePseudonyms) {\n name = String.format(\"User %s\", user.getLogin());\n }\n else {\n name = user.getName();\n }\n return name;\n }\n\n /**\n * retrieves the user id of the Gitlab user with the given user name\n *\n * @param username the username for which the user id should be retrieved\n * @return the Gitlab user id\n */\n public int getUserId(String username) {\n try {\n var gitlabUser = gitlabApi.getUserApi().getUser(username);\n if (gitlabUser != null) {\n return gitlabUser.getId();\n }\n throw new GitLabUserDoesNotExistException(username);\n }\n catch (GitLabApiException e) {\n throw new GitLabException(\"Unable to get ID for user \" + username, e);\n }\n }\n}\n" }, { "alpha_fraction": 0.5729788541793823, "alphanum_fraction": 0.5735214352607727, "avg_line_length": 43.95121765136719, "blob_id": "dfe9eb55b5ddbd391f88fc513a46b7ae167ad5ad", "content_id": "c69b5d3cb23ef892e7ca298eb1cd24988cdbb7ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1843, "license_type": "permissive", "max_line_length": 175, "num_lines": 41, "path": "/src/main/webapp/app/exercises/shared/presentation-score/presentation-score.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\n@Component({\n selector: 'jhi-presentation-score-checkbox',\n template: `\n <ng-container *jhiHasAnyAuthority=\"[Authority.ADMIN, Authority.INSTRUCTOR]\">\n <div class=\"form-group\" *ngIf=\"this.showPresentationScoreCheckbox()\">\n <div class=\"form-check custom-control custom-checkbox\">\n <input\n type=\"checkbox\"\n class=\"form-check-input custom-control-input\"\n id=\"field_presentationScoreEnabled\"\n name=\"presentationScoreEnabled\"\n [ngModel]=\"exercise.presentationScoreEnabled\"\n (ngModelChange)=\"exercise.presentationScoreEnabled = !exercise.presentationScoreEnabled\"\n />\n <label class=\"form-check-label custom-control-label\" for=\"field_presentationScoreEnabled\" jhiTranslate=\"artemisApp.exercise.presentationScoreEnabled.title\"\n >Presentation Score Enabled</label\n >\n <fa-icon\n icon=\"question-circle\"\n class=\"text-secondary\"\n placement=\"top\"\n ngbTooltip=\"{{ 'artemisApp.exercise.presentationScoreEnabled.description' | translate }}\"\n ></fa-icon>\n </div>\n </div>\n </ng-container>\n `,\n})\nexport class PresentationScoreComponent {\n @Input() exercise: Exercise;\n\n Authority = Authority;\n\n showPresentationScoreCheckbox(): boolean {\n return !!(this.exercise.course && this.exercise.course.presentationScore !== 0);\n }\n}\n" }, { "alpha_fraction": 0.6984318494796753, "alphanum_fraction": 0.700844407081604, "avg_line_length": 30.884614944458008, "blob_id": "2f205449b10b5d6e80a78318d50903e373d9b6df", "content_id": "6e44a36594b05e5c9e2003b99724f1ca07b62047", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 829, "license_type": "permissive", "max_line_length": 123, "num_lines": 26, "path": "/src/main/webapp/app/shared/participant-scores/participant-scores-tables-container/participant-scores-tables-container.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ParticipantScoreAverageDTO, ParticipantScoreDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport { round } from 'app/shared/util/utils';\n\n@Component({\n selector: 'jhi-participant-scores-tables-container',\n templateUrl: './participant-scores-tables-container.component.html',\n})\nexport class ParticipantScoresTablesContainerComponent {\n readonly round = round;\n\n @Input()\n isLoading: boolean;\n @Input()\n participantScores: ParticipantScoreDTO[] = [];\n @Input()\n participantScoresAverage: ParticipantScoreAverageDTO[] = [];\n @Input()\n avgScore = 0;\n @Input()\n avgRatedScore = 0;\n @Output()\n reload = new EventEmitter<void>();\n\n mode: 'individual' | 'average' = 'individual';\n}\n" }, { "alpha_fraction": 0.5702054500579834, "alphanum_fraction": 0.5707762837409973, "avg_line_length": 29.736841201782227, "blob_id": "d308420bb8bdb36603a02a7cb57e704dd5f97968", "content_id": "c6af2c28ddbd571024b1dd89d4896bb3f082b12f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1752, "license_type": "permissive", "max_line_length": 127, "num_lines": 57, "path": "/src/main/webapp/app/overview/course-lectures/attachment-unit/attachment-unit.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { FileService } from 'app/shared/http/file.service';\n\n@Component({\n selector: 'jhi-attachment-unit',\n templateUrl: './attachment-unit.component.html',\n styleUrls: ['../lecture-unit.component.scss'],\n})\nexport class AttachmentUnitComponent implements OnInit {\n @Input()\n attachmentUnit: AttachmentUnit;\n\n isCollapsed = true;\n\n constructor(private fileService: FileService) {}\n\n ngOnInit(): void {}\n\n handleCollapse($event: any) {\n $event.stopPropagation();\n this.isCollapsed = !this.isCollapsed;\n }\n\n downloadAttachment() {\n if (this.attachmentUnit?.attachment?.link) {\n this.fileService.downloadFileWithAccessToken(this.attachmentUnit?.attachment?.link);\n }\n }\n\n getFileName() {\n if (this.attachmentUnit?.attachment?.link) {\n return this.attachmentUnit?.attachment?.link.substring(this.attachmentUnit?.attachment?.link.lastIndexOf('/') + 1);\n } else {\n return '';\n }\n }\n\n getAttachmentIcon() {\n if (this.attachmentUnit?.attachment?.link) {\n const fileExtension = this.attachmentUnit?.attachment?.link.split('.').pop()!.toLocaleLowerCase();\n switch (fileExtension) {\n case 'pdf':\n return 'file-pdf';\n case 'png':\n case 'jpg':\n case 'jpeg':\n case 'svg':\n return 'file-image';\n case 'zip':\n return 'file-archive';\n default:\n return 'file';\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6479339003562927, "alphanum_fraction": 0.648553729057312, "avg_line_length": 40.367523193359375, "blob_id": "e55108c83fd60329b6f5cb059e1179ae6e6c2ba1", "content_id": "d1ce89eda6def81f5f8649c79232a658b75d6f88", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4840, "license_type": "permissive", "max_line_length": 112, "num_lines": 117, "path": "/src/test/javascript/spec/component/lecture-unit/text-unit/text-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TextUnitComponent } from 'app/overview/course-lectures/text-unit/text-unit.component';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbCollapse, NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('TextUnitFormComponent', () => {\n const sandbox = sinon.createSandbox();\n const exampleName = 'Test';\n const exampleMarkdown = '# Sample Markdown';\n const exampleHTML = '<h1>Sample Markdown</h1>';\n let textUnitComponentFixture: ComponentFixture<TextUnitComponent>;\n let textUnitComponent: TextUnitComponent;\n let textUnit: TextUnit;\n\n beforeEach(() => {\n textUnit = new TextUnit();\n textUnit.name = exampleName;\n textUnit.content = exampleMarkdown;\n\n TestBed.configureTestingModule({\n imports: [],\n declarations: [\n TextUnitComponent,\n MockComponent(FaIconComponent),\n MockPipe(ArtemisTranslatePipe),\n MockDirective(NgbCollapse),\n MockDirective(NgbTooltip),\n MockPipe(ArtemisDatePipe),\n ],\n providers: [\n MockProvider(ArtemisMarkdownService, {\n safeHtmlForMarkdown: () => exampleHTML,\n htmlForMarkdown: () => exampleHTML,\n }),\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n textUnitComponentFixture = TestBed.createComponent(TextUnitComponent);\n textUnitComponent = textUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n textUnitComponentFixture.detectChanges();\n expect(textUnitComponent).to.be.ok;\n });\n\n it('should convert markdown to html and display it', () => {\n textUnitComponent.textUnit = textUnit;\n textUnitComponentFixture.detectChanges();\n\n expect(textUnitComponent.formattedContent).to.equal(exampleHTML);\n const markdown = textUnitComponentFixture.debugElement.nativeElement.querySelector('.markdown-preview');\n expect(markdown).to.be.ok;\n expect(markdown.innerHTML).to.equal(exampleHTML);\n });\n\n it('should collapse unit when header clicked', () => {\n textUnitComponent.textUnit = textUnit;\n textUnitComponentFixture.detectChanges();\n expect(textUnitComponent.isCollapsed).to.be.true;\n const handleCollapseSpy = sinon.spy(textUnitComponent, 'handleCollapse');\n\n const header = textUnitComponentFixture.debugElement.nativeElement.querySelector('.unit-card-header');\n expect(header).to.be.ok;\n header.click();\n\n textUnitComponentFixture.whenStable().then(() => {\n expect(handleCollapseSpy).to.have.been.called;\n expect(textUnitComponent.isCollapsed).to.be.false;\n });\n\n handleCollapseSpy.restore();\n });\n\n it('should display html in a new window when popup button is clicked', () => {\n const contentOfNewWindow: string[] = [];\n const innerHtmlCopy = window.document.body.innerHTML;\n\n const writeStub = sandbox.stub(window.document, 'write').callsFake((content: string) => {\n contentOfNewWindow.push(content);\n });\n const closeStub = sandbox.stub(window.document, 'close');\n const focusStub = sandbox.stub(window, 'focus');\n const openStub = sandbox.stub(window, 'open').returns(window);\n\n textUnitComponent.textUnit = textUnit;\n textUnitComponentFixture.detectChanges();\n const popButton = textUnitComponentFixture.debugElement.nativeElement.querySelector('#popupButton');\n popButton.click();\n textUnitComponentFixture.whenStable().then(() => {\n expect(textUnitComponent).to.be.ok;\n expect(openStub).to.have.been.calledOnce;\n expect(writeStub).to.have.callCount(4);\n expect(closeStub).to.have.been.calledOnce;\n expect(focusStub).to.have.been.calledOnce;\n expect(window.document.body.innerHTML).to.equal(exampleHTML);\n window.document.body.innerHTML = innerHtmlCopy;\n });\n });\n});\n" }, { "alpha_fraction": 0.6901482939720154, "alphanum_fraction": 0.6925317645072937, "avg_line_length": 40.4945068359375, "blob_id": "d743b04b24a5e6da3231f1ee9810486193155357", "content_id": "cf133c531a31026c01d87de15aadd3e2baa43fe3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3776, "license_type": "permissive", "max_line_length": 130, "num_lines": 91, "path": "/src/test/javascript/spec/component/student-questions/student-question-row.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { StudentQuestionRowComponent } from 'app/overview/student-questions/student-question-row/student-question-row.component';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentQuestionRowComponent', () => {\n let component: StudentQuestionRowComponent;\n let componentFixture: ComponentFixture<StudentQuestionRowComponent>;\n\n const user1 = {\n id: 1,\n } as User;\n\n const user2 = {\n id: 2,\n } as User;\n\n const unApprovedStudentQuestionAnswer = {\n id: 1,\n answerDate: undefined,\n answerText: 'not approved',\n tutorApproved: false,\n author: user1,\n } as StudentQuestionAnswer;\n\n const approvedStudentQuestionAnswer = {\n id: 2,\n answerDate: undefined,\n answerText: 'approved',\n tutorApproved: true,\n author: user2,\n } as StudentQuestionAnswer;\n\n const studentQuestion = {\n id: 1,\n creationDate: undefined,\n answers: [unApprovedStudentQuestionAnswer, approvedStudentQuestionAnswer],\n } as StudentQuestion;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },\n ],\n declarations: [StudentQuestionRowComponent],\n })\n .overrideTemplate(StudentQuestionRowComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(StudentQuestionRowComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should sort in approved and not approved answers', () => {\n component.studentQuestion = studentQuestion;\n component.sortQuestionAnswers();\n expect(component.approvedQuestionAnswers).to.deep.equal([approvedStudentQuestionAnswer]);\n expect(component.sortedQuestionAnswers).to.deep.equal([unApprovedStudentQuestionAnswer]);\n });\n\n it('should delete studentQuestionAnswer from list', () => {\n component.studentQuestion = studentQuestion;\n component.sortQuestionAnswers();\n component.deleteAnswerFromList(unApprovedStudentQuestionAnswer);\n expect(component.studentQuestion.answers).to.deep.equal([approvedStudentQuestionAnswer]);\n });\n\n it('should add studentQuestionAnswer to list', () => {\n component.studentQuestion = studentQuestion;\n component.sortQuestionAnswers();\n component.studentQuestion.answers = [approvedStudentQuestionAnswer];\n component.addAnswerToList(unApprovedStudentQuestionAnswer);\n expect(component.studentQuestion.answers).to.deep.equal([approvedStudentQuestionAnswer, unApprovedStudentQuestionAnswer]);\n });\n});\n" }, { "alpha_fraction": 0.6095179319381714, "alphanum_fraction": 0.6103096604347229, "avg_line_length": 23.875272750854492, "blob_id": "ffe26f17480f5207761fc50843db76b3f9c8a35d", "content_id": "d3a087c7038894036b543ce2dca33bdf5e0e8c6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11368, "license_type": "permissive", "max_line_length": 126, "num_lines": 457, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/dto/BambooBuildResultNotificationDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.bamboo.dto;\n\nimport static de.tum.in.www1.artemis.config.Constants.*;\n\nimport java.time.ZonedDateTime;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.service.dto.AbstractBuildResultNotificationDTO;\nimport de.tum.in.www1.artemis.service.dto.StaticCodeAnalysisReportDTO;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class BambooBuildResultNotificationDTO extends AbstractBuildResultNotificationDTO {\n\n private String secret;\n\n private String notificationType;\n\n private BambooBuildPlanDTO plan;\n\n private BambooBuildDTO build;\n\n public String getSecret() {\n return secret;\n }\n\n public void setSecret(String secret) {\n this.secret = secret;\n }\n\n public String getNotificationType() {\n return notificationType;\n }\n\n public void setNotificationType(String notificationType) {\n this.notificationType = notificationType;\n }\n\n public BambooBuildPlanDTO getPlan() {\n return plan;\n }\n\n public void setPlan(BambooBuildPlanDTO plan) {\n this.plan = plan;\n }\n\n public BambooBuildDTO getBuild() {\n return build;\n }\n\n public void setBuild(BambooBuildDTO build) {\n this.build = build;\n }\n\n @Override\n public ZonedDateTime getBuildRunDate() {\n return getBuild().getBuildCompletedDate();\n }\n\n @Override\n public Optional<String> getCommitHashFromAssignmentRepo() {\n return getCommitHashFromRepo(ASSIGNMENT_REPO_NAME);\n }\n\n @Override\n public Optional<String> getCommitHashFromTestsRepo() {\n return getCommitHashFromRepo(TEST_REPO_NAME);\n }\n\n @Override\n public boolean isBuildSuccessful() {\n return getBuild().isSuccessful();\n }\n\n @Override\n public Double getBuildScore() {\n // the real score is calculated in the grading service\n return 0D;\n }\n\n @Override\n public String getTestsPassedString() {\n if (\"No tests found\".equals(getBuild().getTestSummary().getDescription())) {\n return \"No tests found\";\n }\n\n int total = getBuild().getTestSummary().getTotalCount();\n int passed = getBuild().getTestSummary().getSuccessfulCount();\n return String.format(\"%d of %d passed\", passed, total);\n }\n\n private Optional<String> getCommitHashFromRepo(String repoName) {\n var repo = getBuild().getVcs().stream().filter(vcs -> vcs.getRepositoryName().equalsIgnoreCase(repoName)).findFirst();\n return repo.map(BambooVCSDTO::getId);\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooBuildDTO {\n\n private boolean artifact;\n\n private int number;\n\n private String reason;\n\n private ZonedDateTime buildCompletedDate;\n\n private boolean successful;\n\n private BambooTestSummaryDTO testSummary;\n\n private List<BambooVCSDTO> vcs;\n\n private List<BambooJobDTO> jobs;\n\n public boolean isArtifact() {\n return artifact;\n }\n\n public void setArtifact(boolean artifact) {\n this.artifact = artifact;\n }\n\n public int getNumber() {\n return number;\n }\n\n public void setNumber(int number) {\n this.number = number;\n }\n\n public String getReason() {\n return reason;\n }\n\n public void setReason(String reason) {\n this.reason = reason;\n }\n\n public ZonedDateTime getBuildCompletedDate() {\n return buildCompletedDate;\n }\n\n public void setBuildCompletedDate(ZonedDateTime buildCompletedDate) {\n this.buildCompletedDate = buildCompletedDate;\n }\n\n public boolean isSuccessful() {\n return successful;\n }\n\n public void setSuccessful(boolean successful) {\n this.successful = successful;\n }\n\n public BambooTestSummaryDTO getTestSummary() {\n return testSummary;\n }\n\n public void setTestSummary(BambooTestSummaryDTO testSummary) {\n this.testSummary = testSummary;\n }\n\n public List<BambooVCSDTO> getVcs() {\n return vcs;\n }\n\n public void setVcs(List<BambooVCSDTO> vcs) {\n this.vcs = vcs;\n }\n\n public List<BambooJobDTO> getJobs() {\n return jobs;\n }\n\n public void setJobs(List<BambooJobDTO> jobs) {\n this.jobs = jobs;\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooTestSummaryDTO {\n\n // We don't even know what unit this. It's doesn't align at all with the value displayed in Bamboo.\n // E.g. we got a value of 246 for an 8 second run?\n private int duration;\n\n private int ignoreCount;\n\n private int failedCount;\n\n private int existingFailedCount;\n\n private int quarantineCount;\n\n private int successfulCount;\n\n private String description;\n\n private int skippedCount;\n\n private int fixedCount;\n\n private int totalCount;\n\n private int newFailedCount;\n\n public int getDuration() {\n return duration;\n }\n\n public void setDuration(int duration) {\n this.duration = duration;\n }\n\n public int getIgnoreCount() {\n return ignoreCount;\n }\n\n public void setIgnoreCount(int ignoreCount) {\n this.ignoreCount = ignoreCount;\n }\n\n public int getFailedCount() {\n return failedCount;\n }\n\n public void setFailedCount(int failedCount) {\n this.failedCount = failedCount;\n }\n\n public int getExistingFailedCount() {\n return existingFailedCount;\n }\n\n public void setExistingFailedCount(int existingFailedCount) {\n this.existingFailedCount = existingFailedCount;\n }\n\n public int getQuarantineCount() {\n return quarantineCount;\n }\n\n public void setQuarantineCount(int quarantineCount) {\n this.quarantineCount = quarantineCount;\n }\n\n public int getSuccessfulCount() {\n return successfulCount;\n }\n\n public void setSuccessfulCount(int successfulCount) {\n this.successfulCount = successfulCount;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public int getSkippedCount() {\n return skippedCount;\n }\n\n public void setSkippedCount(int skippedCount) {\n this.skippedCount = skippedCount;\n }\n\n public int getFixedCount() {\n return fixedCount;\n }\n\n public void setFixedCount(int fixedCount) {\n this.fixedCount = fixedCount;\n }\n\n public int getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(int totalCount) {\n this.totalCount = totalCount;\n }\n\n public int getNewFailedCount() {\n return newFailedCount;\n }\n\n public void setNewFailedCount(int newFailedCount) {\n this.newFailedCount = newFailedCount;\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooVCSDTO {\n\n private String id;\n\n private String repositoryName;\n\n private List<BambooCommitDTO> commits = new ArrayList<>();\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n public void setRepositoryName(String repositoryName) {\n this.repositoryName = repositoryName;\n }\n\n public List<BambooCommitDTO> getCommits() {\n return commits;\n }\n\n public void setCommits(List<BambooCommitDTO> commits) {\n this.commits = commits;\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooCommitDTO {\n\n private String comment;\n\n private String id;\n\n public String getComment() {\n return comment;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooJobDTO {\n\n private int id;\n\n private List<BambooTestJobDTO> failedTests = new ArrayList<>();\n\n private List<BambooTestJobDTO> successfulTests = new ArrayList<>();\n\n private List<StaticCodeAnalysisReportDTO> staticCodeAnalysisReports = new ArrayList<>();\n\n private List<BambooBuildLogDTO> logs = new ArrayList<>();\n\n public List<BambooTestJobDTO> getSuccessfulTests() {\n return successfulTests;\n }\n\n public void setSuccessfulTests(List<BambooTestJobDTO> successfulTests) {\n this.successfulTests = successfulTests;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public List<BambooTestJobDTO> getFailedTests() {\n return failedTests;\n }\n\n public void setFailedTests(List<BambooTestJobDTO> failedTests) {\n this.failedTests = failedTests;\n }\n\n public List<StaticCodeAnalysisReportDTO> getStaticCodeAnalysisReports() {\n return staticCodeAnalysisReports;\n }\n\n public void setStaticCodeAnalysisReports(List<StaticCodeAnalysisReportDTO> staticCodeAnalysisReports) {\n this.staticCodeAnalysisReports = staticCodeAnalysisReports;\n }\n\n public List<BambooBuildLogDTO> getLogs() {\n return logs;\n }\n\n public void setLogs(List<BambooBuildLogDTO> logs) {\n this.logs = logs;\n }\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooTestJobDTO {\n\n private String name;\n\n private String methodName;\n\n private String className;\n\n private List<String> errors = new ArrayList<>();\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getMethodName() {\n return methodName;\n }\n\n public void setMethodName(String methodName) {\n this.methodName = methodName;\n }\n\n public String getClassName() {\n return className;\n }\n\n public void setClassName(String className) {\n this.className = className;\n }\n\n public List<String> getErrors() {\n return errors;\n }\n\n public void setErrors(List<String> errors) {\n this.errors = errors;\n }\n }\n}\n" }, { "alpha_fraction": 0.7771260738372803, "alphanum_fraction": 0.7771260738372803, "avg_line_length": 47.71428680419922, "blob_id": "795ee2a3c9e5ab2adae314ca9148c8428168e872", "content_id": "c6c2fdcdd707081b3ffc00bd99383f1ec509d871", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 341, "license_type": "permissive", "max_line_length": 99, "num_lines": 7, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-paging.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { of } from 'rxjs';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { PageableSearch, SearchResult } from 'app/shared/table/pageable-table';\n\nexport class MockProgrammingExercisePagingService {\n searchForExercises = (pageable: PageableSearch) => of({} as SearchResult<ProgrammingExercise>);\n}\n" }, { "alpha_fraction": 0.6406676173210144, "alphanum_fraction": 0.6445193290710449, "avg_line_length": 40.818790435791016, "blob_id": "f66b352f4baabe55ef15d39efca6892265879a34", "content_id": "c5e5b3ec5d86e75d4883c9e75a27342466802637", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6231, "license_type": "permissive", "max_line_length": 172, "num_lines": 149, "path": "/src/test/javascript/spec/component/plagiarism/text-submission-viewer.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SimpleChange } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisPlagiarismModule } from 'app/exercises/shared/plagiarism/plagiarism.module';\nimport { TextSubmissionViewerComponent } from 'app/exercises/shared/plagiarism/plagiarism-split-view/text-submission-viewer/text-submission-viewer.component';\nimport { CodeEditorRepositoryFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { FileType } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { PlagiarismSubmission } from 'app/exercises/shared/plagiarism/types/PlagiarismSubmission';\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\n\ndescribe('Text Submission Viewer Component', () => {\n let comp: TextSubmissionViewerComponent;\n let fixture: ComponentFixture<TextSubmissionViewerComponent>;\n let repositoryService: CodeEditorRepositoryFileService;\n let textSubmissionService: TextSubmissionService;\n\n const files = {\n 'src/': FileType.FOLDER,\n 'src/Main.java': FileType.FILE,\n 'src/Utils.java': FileType.FILE,\n 'src/Helper.java': FileType.FILE,\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisPlagiarismModule, TranslateTestingModule],\n providers: [\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(TextSubmissionViewerComponent);\n comp = fixture.componentInstance;\n repositoryService = fixture.debugElement.injector.get(CodeEditorRepositoryFileService);\n textSubmissionService = fixture.debugElement.injector.get(TextSubmissionService);\n });\n\n it('fetches a text submission', () => {\n comp.exercise = { type: ExerciseType.TEXT } as TextExercise;\n spyOn(textSubmissionService, 'getTextSubmission').and.returnValue(of({ text: 'Test' }));\n\n comp.ngOnChanges({\n plagiarismSubmission: { currentValue: { submissionId: 2 } } as SimpleChange,\n });\n\n expect(textSubmissionService.getTextSubmission).toHaveBeenCalledWith(2);\n expect(comp.isProgrammingExercise).toBe(false);\n });\n\n it('fetches a programming submission', () => {\n comp.exercise = { type: ExerciseType.PROGRAMMING } as ProgrammingExercise;\n spyOn(repositoryService, 'getRepositoryContent').and.returnValue(of([]));\n\n comp.ngOnChanges({\n plagiarismSubmission: { currentValue: { submissionId: 2 } } as SimpleChange,\n });\n\n expect(repositoryService.getRepositoryContent).toHaveBeenCalled();\n expect(comp.isProgrammingExercise).toBe(true);\n });\n\n it('filters files of type FILE', () => {\n const filtered = comp.filterFiles(files);\n\n expect(filtered).toHaveLength(3);\n });\n\n it('handles file selection', () => {\n comp.plagiarismSubmission = { submissionId: 1 } as PlagiarismSubmission<TextSubmissionElement>;\n\n const fileName = Object.keys(files)[1];\n spyOn(repositoryService, 'getFile').and.returnValue(of({ fileContent: 'Test' }));\n\n comp.handleFileSelect(fileName);\n\n expect(repositoryService.getFile).toHaveBeenCalledWith(fileName);\n expect(comp.currentFile).toEqual(fileName);\n });\n\n it('inserts a token', () => {\n const base = 'This is a test';\n const token = '<token>';\n const position = 4;\n const expectedResult = 'This<token> is a test';\n\n const result = comp.insertToken(base, token, position);\n\n expect(result).toEqual(expectedResult);\n });\n\n it('appends a token', () => {\n const base = 'This is a test';\n const token = '<token>';\n const position = 20;\n const expectedResult = 'This is a test<token>';\n\n const result = comp.insertToken(base, token, position);\n\n expect(result).toEqual(expectedResult);\n });\n\n it('inserts match tokens', () => {\n const mockMatches = [\n {\n from: {\n column: 1,\n line: 1,\n length: 5,\n } as TextSubmissionElement,\n to: {\n column: 13,\n line: 1,\n length: 5,\n } as TextSubmissionElement,\n },\n {\n from: {\n column: 1,\n line: 2,\n length: 10,\n } as TextSubmissionElement,\n to: {\n column: 23,\n line: 2,\n length: 5,\n } as TextSubmissionElement,\n },\n ];\n spyOn(comp, 'getMatchesForCurrentFile').and.returnValue(mockMatches);\n\n const fileContent = `Lorem ipsum dolor sit amet.\\nConsetetur sadipscing elitr.`;\n const expectedFileContent = `<span class=\"plagiarism-match\">Lorem ipsum dolor</span> sit amet.\\n<span class=\"plagiarism-match\">Consetetur sadipscing elitr</span>.`;\n\n const updatedFileContent = comp.insertMatchTokens(fileContent);\n\n expect(updatedFileContent).toEqual(expectedFileContent);\n });\n});\n" }, { "alpha_fraction": 0.7232320308685303, "alphanum_fraction": 0.7323965430259705, "avg_line_length": 51.58634567260742, "blob_id": "0727ecc47d113fe4ecfdd73a67b8c829cb531a1e", "content_id": "894c0deb8625ebae29abba740f3127dceed20267", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13094, "license_type": "permissive", "max_line_length": 179, "num_lines": 249, "path": "/src/test/java/de/tum/in/www1/artemis/StudentQuestionIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashSet;\nimport java.util.List;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class StudentQuestionIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private CourseRepository courseRepo;\n\n @Autowired\n private LectureRepository lectureRepo;\n\n @Autowired\n private AttachmentRepository attachmentRepo;\n\n @Autowired\n private StudentQuestionRepository studentQuestionRepository;\n\n @BeforeEach\n public void initTestCase() {\n database.addUsers(5, 5, 1);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createStudentQuestion() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n StudentQuestion studentQuestionToSave = new StudentQuestion();\n studentQuestionToSave.setQuestionText(\"Test Student Question 1\");\n studentQuestionToSave.setVisibleForStudents(true);\n studentQuestionToSave.setExercise(studentQuestion.getExercise());\n\n StudentQuestion createdStudentQuestion = request.postWithResponseBody(\"/api/courses/\" + studentQuestionToSave.getCourse().getId() + \"/student-questions\",\n studentQuestionToSave, StudentQuestion.class, HttpStatus.CREATED);\n\n assertThat(createdStudentQuestion).isNotNull();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createExistingStudentQuestion() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n\n request.postWithResponseBody(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions\", studentQuestion, StudentQuestion.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void editStudentQuestion_asInstructor() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n\n studentQuestion.setVisibleForStudents(false);\n studentQuestion.setQuestionText(\"New Test Student Question\");\n\n StudentQuestion updatedStudentQuestion = request.putWithResponseBody(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions\", studentQuestion,\n StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion.getQuestionText()).isEqualTo(\"New Test Student Question\");\n assertThat(updatedStudentQuestion.isVisibleForStudents()).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void editStudentQuestion_asTA() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n\n studentQuestion.setVisibleForStudents(false);\n studentQuestion.setQuestionText(\"New Test Student Question\");\n\n StudentQuestion updatedStudentQuestion = request.putWithResponseBody(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions\", studentQuestion,\n StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion.getQuestionText()).isEqualTo(\"New Test Student Question\");\n assertThat(updatedStudentQuestion.isVisibleForStudents()).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void editStudentQuestion_asStudent() throws Exception {\n List<StudentQuestion> questions = database.createCourseWithExerciseAndStudentQuestions();\n StudentQuestion studentQuestion_student1 = questions.get(0);\n StudentQuestion studentQuestion_student2 = questions.get(1);\n\n // update own question --> OK\n studentQuestion_student1.setVisibleForStudents(false);\n studentQuestion_student1.setQuestionText(\"New Test Student Question\");\n StudentQuestion updatedStudentQuestion1 = request.putWithResponseBody(\"/api/courses/\" + studentQuestion_student1.getCourse().getId() + \"/student-questions\",\n studentQuestion_student1, StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion1.getQuestionText()).isEqualTo(\"New Test Student Question\");\n assertThat(updatedStudentQuestion1.isVisibleForStudents()).isFalse();\n\n // update question from another student --> forbidden\n studentQuestion_student2.setVisibleForStudents(false);\n studentQuestion_student2.setQuestionText(\"New Test Student Question\");\n StudentQuestion updatedStudentQuestion2 = request.putWithResponseBody(\"/api/courses/\" + studentQuestion_student2.getCourse().getId() + \"/student-questions\",\n studentQuestion_student2, StudentQuestion.class, HttpStatus.FORBIDDEN);\n assertThat(updatedStudentQuestion2).isNull();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAllStudentQuestionsForExercise() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n Long exerciseID = studentQuestion.getExercise().getId();\n\n List<StudentQuestion> returnedStudentQuestions = request.getList(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/exercises/\" + exerciseID + \"/student-questions\",\n HttpStatus.OK, StudentQuestion.class);\n assertThat(returnedStudentQuestions.size()).isEqualTo(2);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAllStudentQuestionsForLecture() throws Exception {\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n ZonedDateTime futureTimestamp = ZonedDateTime.now().plusDays(5);\n ZonedDateTime futureFutureTimestamp = ZonedDateTime.now().plusDays(8);\n\n Course course1 = ModelFactory.generateCourse(null, pastTimestamp, futureTimestamp, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n\n Lecture lecture1 = ModelFactory.generateLecture(pastTimestamp, futureFutureTimestamp, course1);\n Attachment attachment1 = ModelFactory.generateAttachment(pastTimestamp, lecture1);\n lecture1.addAttachments(attachment1);\n courseRepo.save(course1);\n lectureRepo.save(lecture1);\n attachmentRepo.save(attachment1);\n\n StudentQuestion studentQuestion1 = database.createCourseWithExerciseAndStudentQuestions().get(0);\n studentQuestion1.setLecture(lecture1);\n StudentQuestion studentQuestion2 = database.createCourseWithExerciseAndStudentQuestions().get(0);\n studentQuestion2.setLecture(lecture1);\n studentQuestionRepository.save(studentQuestion1);\n studentQuestionRepository.save(studentQuestion2);\n\n List<StudentQuestion> returnedStudentQuestions = request\n .getList(\"/api/courses/\" + studentQuestion1.getCourse().getId() + \"/lectures/\" + lecture1.getId() + \"/student-questions\", HttpStatus.OK, StudentQuestion.class);\n assertThat(returnedStudentQuestions.size()).isEqualTo(2);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteStudentQuestions_asInstructor() throws Exception {\n List<StudentQuestion> studentQuestions = database.createCourseWithExerciseAndStudentQuestions();\n StudentQuestion studentQuestion = studentQuestions.get(0);\n StudentQuestion studentQuestion1 = studentQuestions.get(1);\n\n request.delete(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions/\" + studentQuestion.getId(), HttpStatus.OK);\n assertThat(studentQuestionRepository.count()).isEqualTo(1);\n\n // try to delete not existing question\n request.delete(\"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions/999\", HttpStatus.NOT_FOUND);\n\n // delete question with no lecture id --> OK\n studentQuestion1.setLecture(null);\n studentQuestionRepository.save(studentQuestion1);\n request.delete(\"/api/courses/\" + studentQuestion1.getCourse().getId() + \"/student-questions/\" + studentQuestion1.getId(), HttpStatus.OK);\n assertThat(studentQuestionRepository.count()).isEqualTo(0);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void deleteStudentQuestions_asTA() throws Exception {\n List<StudentQuestion> studentQuestions = database.createCourseWithExerciseAndStudentQuestions();\n StudentQuestion studentQuestion_student1 = studentQuestions.get(0);\n StudentQuestion studentQuestion1_student2 = studentQuestions.get(1);\n\n // delete own question --> OK\n request.delete(\"/api/courses/\" + studentQuestion_student1.getCourse().getId() + \"/student-questions/\" + studentQuestion_student1.getId(), HttpStatus.OK);\n assertThat(studentQuestionRepository.count()).isEqualTo(1);\n\n // delete question from another user --> OK\n request.delete(\"/api/courses/\" + studentQuestion1_student2.getCourse().getId() + \"/student-questions/\" + studentQuestion1_student2.getId(), HttpStatus.OK);\n assertThat(studentQuestionRepository.count()).isEqualTo(0);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void deleteStudentQuestions_asStudent() throws Exception {\n List<StudentQuestion> studentQuestions = database.createCourseWithExerciseAndStudentQuestions();\n StudentQuestion studentQuestion_student1 = studentQuestions.get(0);\n StudentQuestion studentQuestion1_student2 = studentQuestions.get(1);\n\n // delete own question --> OK\n request.delete(\"/api/courses/\" + studentQuestion_student1.getCourse().getId() + \"/student-questions/\" + studentQuestion_student1.getId(), HttpStatus.OK);\n assertThat(studentQuestionRepository.count()).isEqualTo(1);\n\n // delete question from another student --> forbidden\n request.delete(\"/api/courses/\" + studentQuestion1_student2.getCourse().getId() + \"/student-questions/\" + studentQuestion1_student2.getId(), HttpStatus.FORBIDDEN);\n assertThat(studentQuestionRepository.count()).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void editStudentQuestionVotes_asInstructor() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n\n StudentQuestion updatedStudentQuestion = request.putWithResponseBody(\n \"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions/\" + studentQuestion.getId() + \"/votes\", 1, StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion.getVotes()).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void editStudentQuestionVotes_asTA() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndStudentQuestions().get(0);\n\n StudentQuestion updatedStudentQuestion = request.putWithResponseBody(\n \"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions/\" + studentQuestion.getId() + \"/votes\", -1, StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion.getVotes()).isEqualTo(-1);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void editStudentQuestionVotes_asStudent() throws Exception {\n List<StudentQuestion> questions = database.createCourseWithExerciseAndStudentQuestions();\n StudentQuestion studentQuestion = questions.get(0);\n\n StudentQuestion updatedStudentQuestion = request.putWithResponseBody(\n \"/api/courses/\" + studentQuestion.getCourse().getId() + \"/student-questions/\" + studentQuestion.getId() + \"/votes\", 2, StudentQuestion.class, HttpStatus.OK);\n assertThat(updatedStudentQuestion.getVotes()).isEqualTo(2);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAllStudentQuestionsForCourse() throws Exception {\n StudentQuestion studentQuestion = database.createCourseWithExerciseAndLectureAndStudentQuestions().get(0);\n Long courseID = studentQuestion.getCourse().getId();\n\n List<StudentQuestion> returnedStudentQuestions = request.getList(\"/api/courses/\" + courseID + \"/student-questions\", HttpStatus.OK, StudentQuestion.class);\n assertThat(returnedStudentQuestions.size()).isEqualTo(4);\n }\n}\n" }, { "alpha_fraction": 0.6166945099830627, "alphanum_fraction": 0.6183918714523315, "avg_line_length": 46.623207092285156, "blob_id": "bda59a63e7f603d96390bbf63b55404c80b95b6b", "content_id": "d5b6a95cc34a21f6accd46ec7d209484d70eb94b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 36527, "license_type": "permissive", "max_line_length": 177, "num_lines": 767, "path": "/src/test/javascript/spec/component/team/teams-import-dialog.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { User } from 'app/core/user/user.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { Team, TeamImportStrategyType } from 'app/entities/team.model';\nimport { TeamExerciseSearchComponent } from 'app/exercises/shared/team/team-exercise-search/team-exercise-search.component';\nimport { TeamStudentsListComponent } from 'app/exercises/shared/team/team-students-list/team-students-list.component';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { TeamsImportDialogComponent } from 'app/exercises/shared/team/teams-import-dialog/teams-import-dialog.component';\nimport { TeamsImportFromFileFormComponent } from 'app/exercises/shared/team/teams-import-dialog/teams-import-from-file-form.component';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component.ts';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { flatMap } from 'lodash';\nimport { JhiAlertService, NgJhipsterModule } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockModule, MockPipe, MockProvider } from 'ng-mocks';\nimport { of, throwError } from 'rxjs';\nimport { restore, SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { mockExercise, mockSourceExercise, mockSourceTeams, mockSourceTeamStudents, mockTeam, mockTeams, mockTeamStudents } from '../../helpers/mocks/service/mock-team.service';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TeamsImportDialogComponent', () => {\n let comp: TeamsImportDialogComponent;\n let fixture: ComponentFixture<TeamsImportDialogComponent>;\n let ngbActiveModal: NgbActiveModal;\n let alertService: JhiAlertService;\n let teamService: TeamService;\n\n const teams: Team[] = mockTeams;\n const logins = flatMap(mockTeams, (team) => team.students?.map((student) => student.login));\n const registrationNumbers = flatMap(mockTeams, (team) => team.students?.map((student) => student.visibleRegistrationNumber));\n const exercise: Exercise = mockExercise;\n\n function resetComponent() {\n comp.teams = teams;\n comp.exercise = exercise;\n comp.searchingExercises = false;\n comp.searchingExercisesFailed = false;\n comp.searchingExercisesNoResultsForQuery = undefined;\n comp.loadingSourceTeams = false;\n comp.loadingSourceTeamsFailed = false;\n comp.importStrategy = undefined;\n comp.isImporting = false;\n comp.showImportFromExercise = true;\n comp.teamShortNamesAlreadyExistingInExercise = [];\n comp.sourceTeamsFreeOfConflicts = [];\n comp.sourceTeams = undefined;\n comp.sourceExercise = undefined;\n comp.studentsAppearInMultipleTeams = false;\n comp.conflictingLoginsSet = new Set();\n comp.conflictingRegistrationNumbersSet = new Set();\n }\n\n beforeEach(\n waitForAsync(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule, MockModule(NgJhipsterModule)],\n declarations: [\n TeamsImportDialogComponent,\n MockComponent(TeamsImportFromFileFormComponent),\n MockDirective(DeleteButtonDirective),\n MockPipe(ArtemisTranslatePipe),\n MockComponent(AlertComponent),\n MockComponent(AlertErrorComponent),\n MockComponent(TeamExerciseSearchComponent),\n MockComponent(TeamStudentsListComponent),\n MockComponent(HelpIconComponent),\n ],\n providers: [MockProvider(TeamService)],\n }).compileComponents();\n }),\n );\n beforeEach(() => {\n fixture = TestBed.createComponent(TeamsImportDialogComponent);\n comp = fixture.componentInstance;\n ngbActiveModal = TestBed.inject(NgbActiveModal);\n alertService = TestBed.inject(JhiAlertService);\n teamService = TestBed.inject(TeamService);\n });\n\n describe('OnInit', () => {\n beforeEach(() => {\n resetComponent();\n });\n\n it('should compute potential conflicts based on existing teams', () => {\n const potentialConflictSpy: SinonSpy = spy(comp, 'computePotentialConflictsBasedOnExistingTeams');\n comp.ngOnInit();\n expect(potentialConflictSpy).to.have.been.called;\n });\n });\n\n describe('loadSourceTeams', () => {\n let teamServiceStub: SinonStub;\n let computeSourceStub: SinonStub;\n beforeEach(() => {\n resetComponent();\n teamServiceStub = stub(teamService, 'findAllByExerciseId');\n computeSourceStub = stub(comp, 'computeSourceTeamsFreeOfConflicts');\n teamServiceStub.returns(\n of(\n new HttpResponse<Team[]>({ body: mockSourceTeams }),\n ),\n );\n });\n\n afterEach(() => {\n restore();\n });\n\n it('should load teams of given exercise if find was successful', () => {\n const sourceExercise = mockSourceExercise;\n comp.sourceTeams = [];\n comp.loadSourceTeams(sourceExercise);\n expect(comp.loadingSourceTeams).to.equal(false);\n expect(comp.loadingSourceTeamsFailed).to.equal(false);\n expect(teamServiceStub).to.have.been.calledWithExactly(sourceExercise.id);\n expect(comp.sourceTeams).to.deep.equal(mockSourceTeams);\n expect(computeSourceStub).to.have.been.called;\n });\n it('should not load teams of given exercise if find failed', () => {\n teamServiceStub.returns(throwError({ status: 404 }));\n const sourceExercise = mockSourceExercise;\n comp.sourceTeams = [];\n comp.loadSourceTeams(sourceExercise);\n expect(comp.sourceTeams).to.equal(undefined);\n expect(comp.loadingSourceTeams).to.equal(false);\n expect(comp.loadingSourceTeamsFailed).to.equal(true);\n expect(teamServiceStub).to.have.been.calledWithExactly(sourceExercise.id);\n expect(computeSourceStub).to.not.have.been.called;\n });\n });\n\n describe('loadSourceTeams', () => {\n let loadSourceStub: SinonStub;\n let initImportStrategy: SinonStub;\n beforeEach(() => {\n resetComponent();\n loadSourceStub = stub(comp, 'loadSourceTeams');\n initImportStrategy = stub(comp, 'initImportStrategy');\n });\n\n afterEach(() => {\n restore();\n });\n\n it('should load selected exercise', () => {\n const sourceExercise = mockSourceExercise;\n comp.onSelectSourceExercise(sourceExercise);\n expect(comp.sourceExercise).to.deep.equal(sourceExercise);\n expect(initImportStrategy).to.have.been.called;\n expect(loadSourceStub).to.have.been.calledWithExactly(sourceExercise);\n });\n });\n\n describe('initImportStrategy', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should set import strategy to default if there no teams', () => {\n comp.teams = [];\n comp.initImportStrategy();\n expect(comp.importStrategy).to.equal(comp.defaultImportStrategy);\n });\n it('should set import strategy to undefined if there are teams', () => {\n comp.initImportStrategy();\n expect(comp.importStrategy).to.equal(undefined);\n });\n });\n\n describe('computePotentialConflictsBasedOnExistingTeams', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should fill existing arrays current team values', () => {\n comp.computePotentialConflictsBasedOnExistingTeams();\n const shortNames = teams.map((team) => team.shortName);\n expect(comp.teamShortNamesAlreadyExistingInExercise).to.deep.equal(shortNames);\n expect(comp.conflictingLoginsSet).to.deep.equal(new Set(logins));\n expect(comp.conflictingRegistrationNumbersSet).to.deep.equal(new Set(registrationNumbers));\n });\n });\n\n describe('computeSourceTeamsFreeOfConflicts', () => {\n let sourceFreeStub: SinonStub;\n beforeEach(() => {\n resetComponent();\n sourceFreeStub = stub(comp, 'isSourceTeamFreeOfAnyConflicts');\n sourceFreeStub.returns(true);\n sourceFreeStub.withArgs(mockSourceTeams[1]).returns(false);\n });\n\n afterEach(() => {\n restore();\n });\n it('should filter source teams according to conflict', () => {\n comp.sourceTeams = mockSourceTeams;\n comp.computeSourceTeamsFreeOfConflicts();\n expect(comp.sourceTeamsFreeOfConflicts).to.deep.equal([mockSourceTeams[0], mockSourceTeams[2]]);\n expect(sourceFreeStub).to.have.been.callCount(mockSourceTeams.length);\n });\n });\n\n describe('isSourceTeamFreeOfAnyConflicts', () => {\n beforeEach(() => {\n resetComponent();\n });\n\n it('returns false if short name is in already existing short names', () => {\n comp.teamShortNamesAlreadyExistingInExercise = [mockTeam.shortName!];\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('returns true if short name is not in already existing short names', () => {\n comp.teamShortNamesAlreadyExistingInExercise = [];\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(true);\n });\n\n it('Import from exercise: returns false if one of the students login is in already existing students', () => {\n comp.conflictingLoginsSet = new Set([mockTeamStudents[0].login!]);\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('Import from exercise: returns true if none of the students login is in already existing students', () => {\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(true);\n });\n\n it('Import from file: returns false if one of the students login is in already existing students', () => {\n comp.conflictingLoginsSet = new Set([mockTeamStudents[0].login!]);\n comp.showImportFromExercise = false;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('Import from exercise: returns true if one of the students registration number is in already existing students', () => {\n comp.conflictingRegistrationNumbersSet = new Set([mockTeamStudents[0].visibleRegistrationNumber!]);\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(true);\n });\n\n it('Import from file: returns false if one of the students registration number is in already existing students', () => {\n comp.conflictingRegistrationNumbersSet = new Set([mockTeamStudents[0].visibleRegistrationNumber!]);\n comp.showImportFromExercise = false;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('Import from exercise: returns true if one of the students registration number is in already other source teams', () => {\n comp.conflictingRegistrationNumbersSet = new Set([mockTeamStudents[0].visibleRegistrationNumber!]);\n comp.studentsAppearInMultipleTeams = true;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(true);\n });\n\n it('Import from file: returns false if one of the students registration number is in already other source teams', () => {\n comp.conflictingRegistrationNumbersSet = new Set([mockTeamStudents[0].visibleRegistrationNumber!]);\n comp.studentsAppearInMultipleTeams = true;\n comp.showImportFromExercise = false;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('Import from file: returns false if one of the students login is in already other source teams', () => {\n comp.conflictingLoginsSet = new Set([mockTeamStudents[0].login!]);\n comp.studentsAppearInMultipleTeams = true;\n comp.showImportFromExercise = false;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(false);\n });\n\n it('Import from file: returns true if no student is in multiple teams', () => {\n comp.showImportFromExercise = false;\n expect(comp.isSourceTeamFreeOfAnyConflicts(mockTeam)).to.equal(true);\n });\n });\n\n describe('numberOfConflictFreeSourceTeams', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return length of source teams free of conflict', () => {\n expect(comp.numberOfConflictFreeSourceTeams).to.equal(0);\n comp.sourceTeamsFreeOfConflicts = mockTeams;\n expect(comp.numberOfConflictFreeSourceTeams).to.equal(mockTeams.length);\n });\n });\n\n describe('numberOfTeamsToBeDeleted', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return 0 if import strategy is CREATE_ONLY', () => {\n comp.importStrategy = TeamImportStrategyType.CREATE_ONLY;\n expect(comp.numberOfTeamsToBeDeleted).to.equal(0);\n });\n it('should return length of teams if import strategy is PURGE_EXISTING', () => {\n comp.importStrategy = TeamImportStrategyType.PURGE_EXISTING;\n expect(comp.numberOfTeamsToBeDeleted).to.equal(mockTeams.length);\n });\n });\n\n describe('numberOfTeamsToBeImported', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return conflict free teams number if import strategy is CREATE_ONLY', () => {\n comp.importStrategy = TeamImportStrategyType.CREATE_ONLY;\n comp.sourceTeamsFreeOfConflicts = mockSourceTeams;\n expect(comp.numberOfTeamsToBeImported).to.equal(mockSourceTeams.length);\n });\n it('should return length of source teams if import strategy is PURGE_EXISTING', () => {\n comp.sourceTeams = mockSourceTeams;\n comp.importStrategy = TeamImportStrategyType.PURGE_EXISTING;\n expect(comp.numberOfTeamsToBeImported).to.equal(mockSourceTeams.length);\n });\n });\n\n describe('numberOfTeamsAfterImport', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return current teams + conflict free teams number if import strategy is CREATE_ONLY', () => {\n comp.importStrategy = TeamImportStrategyType.CREATE_ONLY;\n comp.sourceTeamsFreeOfConflicts = mockSourceTeams;\n expect(comp.numberOfTeamsAfterImport).to.equal(mockSourceTeams.length + mockTeams.length);\n });\n it('should return length of source teams if import strategy is PURGE_EXISTING', () => {\n comp.sourceTeams = mockSourceTeams;\n comp.importStrategy = TeamImportStrategyType.PURGE_EXISTING;\n expect(comp.numberOfTeamsAfterImport).to.equal(mockSourceTeams.length);\n });\n });\n\n describe('showImportStrategyChoices', () => {\n beforeEach(() => {\n resetComponent();\n comp.sourceExercise = mockSourceExercise;\n comp.sourceTeams = mockSourceTeams;\n });\n it('Import from exercise: should return false if there is no sourceExercise', () => {\n comp.sourceExercise = undefined;\n expect(comp.showImportStrategyChoices).to.equal(false);\n });\n it('Import from exercise: should return true if there is a sourceExercise and source team', () => {\n expect(comp.showImportStrategyChoices).to.equal(true);\n });\n it('should return false if there is no source team', () => {\n comp.sourceTeams = [];\n expect(comp.showImportStrategyChoices).to.equal(false);\n });\n it('should return false if there is no existing team', () => {\n comp.teams = [];\n expect(comp.showImportStrategyChoices).to.equal(false);\n });\n it('Import from file: should return false if source teams undefined', () => {\n comp.sourceTeams = undefined;\n comp.showImportFromExercise = false;\n expect(comp.showImportStrategyChoices).to.equal(false);\n });\n it('Import from file: should return true if source exercise undefined', () => {\n comp.sourceExercise = undefined;\n comp.showImportFromExercise = false;\n expect(comp.showImportStrategyChoices).to.equal(true);\n });\n });\n\n describe('updateImportStrategy', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should set import strategy to given import strategy', () => {\n expect(comp.importStrategy).to.equal(undefined);\n comp.updateImportStrategy(TeamImportStrategyType.CREATE_ONLY);\n expect(comp.importStrategy).to.equal(TeamImportStrategyType.CREATE_ONLY);\n comp.updateImportStrategy(TeamImportStrategyType.PURGE_EXISTING);\n expect(comp.importStrategy).to.equal(TeamImportStrategyType.PURGE_EXISTING);\n });\n });\n\n describe('showImportPreviewNumbers', () => {\n describe('import from exercise', () => {\n beforeEach(() => {\n resetComponent();\n comp.sourceExercise = undefined;\n comp.importStrategy = TeamImportStrategyType.CREATE_ONLY;\n });\n it('Import from exercise: should return false if there is no sourceExercise', () => {\n expect(comp.showImportPreviewNumbers).to.equal(false);\n });\n it('Import from exercise: should return true if there is a sourceExercise and source team', () => {\n comp.sourceExercise = mockSourceExercise;\n comp.sourceTeams = mockSourceTeams;\n expect(comp.showImportPreviewNumbers).to.equal(true);\n });\n it('should return false if there is no source team', () => {\n expect(comp.showImportPreviewNumbers).to.equal(false);\n });\n it('Import from exercise: should return false if there is no import strategy', () => {\n expect(comp.showImportPreviewNumbers).to.equal(false);\n });\n });\n describe('import from exercise', () => {\n beforeEach(() => {\n resetComponent();\n comp.sourceExercise = undefined;\n comp.importStrategy = TeamImportStrategyType.CREATE_ONLY;\n comp.showImportFromExercise = false;\n });\n it('Import from file: should return false if there is no import strategy', () => {\n expect(comp.showImportPreviewNumbers).to.equal(false);\n });\n it('Import from file: should return false if no students in multiple teams and no import strategy', () => {\n comp.importStrategy = undefined;\n expect(comp.showImportPreviewNumbers).to.equal(false);\n });\n it('Import from file: should return true if there are students appear in multiple teams and conflicting registration numbers', () => {\n comp.conflictingRegistrationNumbersSet = new Set(['1', '2']);\n comp.studentsAppearInMultipleTeams = true;\n comp.importStrategy = undefined;\n expect(comp.showImportPreviewNumbers).to.equal(true);\n });\n it('Import from file: should return true if there are students appear in multiple teams and conflicting logins', () => {\n comp.conflictingLoginsSet = new Set(['l1', 'l2']);\n comp.studentsAppearInMultipleTeams = true;\n comp.importStrategy = undefined;\n expect(comp.showImportPreviewNumbers).to.equal(true);\n });\n });\n });\n\n describe('isSubmitDisabled', () => {\n beforeEach(() => {\n resetComponent();\n comp.sourceExercise = mockSourceExercise;\n comp.sourceTeams = mockSourceTeams;\n comp.importStrategy = TeamImportStrategyType.PURGE_EXISTING;\n });\n it('should return false', () => {\n expect(comp.isSubmitDisabled).to.equal(false);\n });\n it('Import from exercise: should return true if importing', () => {\n comp.isImporting = true;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from exercise: should return true if it has source exercise', () => {\n comp.sourceExercise = undefined;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from exercise: should return true if it has source teams', () => {\n comp.sourceTeams = undefined;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from exercise: should return true if it has import strategy', () => {\n comp.importStrategy = undefined;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from file: should return false if importing', () => {\n comp.isImporting = true;\n comp.showImportFromExercise = false;\n expect(comp.isSubmitDisabled).to.equal(false);\n });\n it('Import from file: should return false if it has no source exercise', () => {\n comp.sourceExercise = undefined;\n comp.showImportFromExercise = false;\n expect(comp.isSubmitDisabled).to.equal(false);\n });\n it('Import from file: should return true if it has source teams', () => {\n comp.sourceTeams = undefined;\n comp.showImportFromExercise = false;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from file: should return true if it has import strategy', () => {\n comp.importStrategy = undefined;\n comp.showImportFromExercise = false;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n it('Import from file: should return true if there same registration number is in two teams', () => {\n comp.conflictingRegistrationNumbersSet = new Set(['1', '2']);\n comp.studentsAppearInMultipleTeams = true;\n comp.showImportFromExercise = false;\n expect(comp.isSubmitDisabled).to.equal(true);\n });\n });\n\n describe('clear', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return false', () => {\n comp.clear();\n expect(ngbActiveModal.dismiss).to.have.been.calledWith('cancel');\n });\n });\n\n describe('purgeAndImportTeams', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return false', () => {\n const importTeamsStub = stub(comp, 'importTeams');\n comp.purgeAndImportTeams();\n expect(importTeamsStub).to.have.been.called;\n restore();\n });\n });\n\n describe('importTeams', () => {\n let importFromSourceExerciseStub: SinonStub;\n let importTeamsStub: SinonStub;\n let onSuccessStub: SinonStub;\n let onErrorStub: SinonStub;\n let fromExerciseResponse: HttpResponse<Team[]>;\n let fromFileResponse: HttpResponse<Team[]>;\n beforeEach(() => {\n resetComponent();\n fromExerciseResponse = new HttpResponse<Team[]>({ body: mockSourceTeams });\n importFromSourceExerciseStub = stub(teamService, 'importTeamsFromSourceExercise');\n importFromSourceExerciseStub.returns(of(fromExerciseResponse));\n fromFileResponse = new HttpResponse<Team[]>({ body: [...mockSourceTeams, mockTeam] });\n importTeamsStub = stub(teamService, 'importTeams');\n importTeamsStub.returns(of(fromFileResponse));\n onSuccessStub = stub(comp, 'onSaveSuccess');\n onErrorStub = stub(comp, 'onSaveError');\n comp.sourceExercise = mockSourceExercise;\n comp.sourceTeams = mockSourceTeams;\n comp.importStrategy = TeamImportStrategyType.PURGE_EXISTING;\n });\n afterEach(() => {\n restore();\n });\n it('should not call team service if submit disabled', () => {\n comp.importStrategy = undefined;\n comp.importTeams();\n expect(importFromSourceExerciseStub).to.not.have.been.called;\n expect(importTeamsStub).to.not.have.been.called;\n expect(onSuccessStub).to.not.have.been.called;\n expect(onErrorStub).to.not.have.been.called;\n expect(comp.isImporting).to.equal(false);\n });\n it('should call importTeamsFromSourceExercise if show import from exercise and call save success', () => {\n comp.importTeams();\n expect(importFromSourceExerciseStub).to.have.been.calledWithExactly(comp.exercise, comp.sourceExercise, comp.importStrategy);\n expect(importTeamsStub).to.not.have.been.called;\n expect(onSuccessStub).to.have.been.calledWithExactly(fromExerciseResponse);\n expect(onErrorStub).to.not.have.been.called;\n expect(comp.isImporting).to.equal(true);\n });\n it('should call importTeamsFromSourceExercise if show import from exercise and call save error on Error', () => {\n const error = { status: 404 };\n importFromSourceExerciseStub.returns(throwError(error));\n comp.importTeams();\n expect(importFromSourceExerciseStub).to.have.been.calledWithExactly(comp.exercise, comp.sourceExercise, comp.importStrategy);\n expect(importTeamsStub).to.not.have.been.called;\n expect(onSuccessStub).to.not.have.been.called;\n expect(onErrorStub).to.have.been.calledWithExactly(error);\n expect(comp.isImporting).to.equal(true);\n });\n it('should call importTeamsFromFile if not show import from exercise and call save success', () => {\n comp.showImportFromExercise = false;\n comp.importTeams();\n expect(importFromSourceExerciseStub).to.not.have.been.called;\n expect(importTeamsStub).to.have.been.calledWithExactly(comp.exercise, comp.sourceTeams, comp.importStrategy);\n expect(onSuccessStub).to.have.been.calledWithExactly(fromFileResponse);\n expect(onErrorStub).to.not.have.been.called;\n expect(comp.isImporting).to.equal(false);\n });\n it('should call importTeamsFromFile if not show import from exercise and call save error on Error', () => {\n const error = { status: 404 };\n comp.showImportFromExercise = false;\n importTeamsStub.returns(throwError(error));\n comp.importTeams();\n expect(importFromSourceExerciseStub).to.not.have.been.called;\n expect(importTeamsStub).to.have.been.calledWithExactly(comp.exercise, comp.sourceTeams, comp.importStrategy);\n expect(onSuccessStub).to.not.have.been.called;\n expect(onErrorStub).to.have.been.calledWithExactly(error);\n expect(comp.isImporting).to.equal(false);\n });\n });\n\n describe('onTeamsChanged', () => {\n let initImportStub: SinonStub;\n let computeSourceFreeOfConflictsStub: SinonStub;\n beforeEach(() => {\n resetComponent();\n initImportStub = stub(comp, 'initImportStrategy');\n computeSourceFreeOfConflictsStub = stub(comp, 'computeSourceTeamsFreeOfConflicts');\n });\n afterEach(() => {\n restore();\n });\n it('change component files and convert file teams to normal teams', () => {\n comp.onTeamsChanged(mockSourceTeams);\n expect(initImportStub).to.have.been.called;\n expect(comp.sourceTeams).to.deep.equal(mockSourceTeams);\n expect(comp.conflictingRegistrationNumbersSet).to.deep.equal(new Set(registrationNumbers));\n expect(comp.conflictingLoginsSet).to.deep.equal(new Set(logins));\n expect(computeSourceFreeOfConflictsStub).to.have.been.called;\n });\n it('adds registration number if a student is in two or more teams', () => {\n comp.onTeamsChanged([...mockSourceTeams, ...mockSourceTeams]);\n expect(comp.problematicRegistrationNumbers).to.deep.equal([...mockSourceTeamStudents.map((student) => student.visibleRegistrationNumber), ...registrationNumbers]);\n });\n it('adds login if a student is in two or more teams', () => {\n comp.onTeamsChanged([...mockSourceTeams, ...mockSourceTeams]);\n expect(comp.problematicLogins).to.deep.equal([...mockSourceTeamStudents.map((student) => student.login), ...logins]);\n });\n });\n\n describe('onSaveSuccess', () => {\n let response: HttpResponse<Team[]>;\n beforeEach(() => {\n resetComponent();\n response = new HttpResponse<Team[]>({ body: mockSourceTeams });\n });\n\n it('change component files and convert file teams to normal teams', fakeAsync(() => {\n comp.isImporting = true;\n comp.onSaveSuccess(response);\n tick(500);\n expect(ngbActiveModal.close).to.have.been.calledWithExactly(mockSourceTeams);\n expect(comp.isImporting).to.equal(false);\n expect(alertService.success).to.have.been.calledWith('artemisApp.team.importSuccess', { numberOfImportedTeams: comp.numberOfTeamsToBeImported });\n }));\n });\n\n describe('onSaveError', () => {\n let alertServiceStub: SinonStub;\n let response: HttpErrorResponse;\n beforeEach(() => {\n resetComponent();\n alertServiceStub = stub(alertService, 'error');\n });\n afterEach(() => {\n restore();\n });\n it('call alert service', () => {\n response = new HttpErrorResponse({ error: {} });\n comp.isImporting = true;\n comp.onSaveError(response);\n expect(comp.isImporting).to.equal(false);\n expect(alertServiceStub).to.have.been.calledWith('artemisApp.team.importError');\n });\n it('call alert service if students not found', () => {\n const notFoundRegistrationNumbers = ['1', '2', '3'];\n const notFoundLogins = ['l1', 'l2', 'l3'];\n response = new HttpErrorResponse({ error: { errorKey: 'studentsNotFound', params: { registrationNumbers: notFoundRegistrationNumbers, logins: notFoundLogins } } });\n comp.isImporting = true;\n comp.onSaveError(response);\n expect(comp.isImporting).to.equal(false);\n expect(alertServiceStub).to.have.been.calledWithExactly('artemisApp.team.errors.registrationNumbersNotFound', { registrationNumbers: notFoundRegistrationNumbers });\n expect(alertServiceStub).to.have.been.calledWithExactly('artemisApp.team.errors.loginsNotFound', { logins: notFoundLogins });\n });\n it('call alert service if students appear multiple times', () => {\n const students = [\n { first: 'l1', second: '1' },\n { first: 'l2', second: '2' },\n { first: 'l3', second: '3' },\n ];\n const message = 'l1:1,l2:2,l3:3';\n response = new HttpErrorResponse({ error: { errorKey: 'studentsAppearMultipleTimes', params: { students } } });\n comp.isImporting = true;\n comp.onSaveError(response);\n expect(comp.isImporting).to.equal(false);\n expect(alertServiceStub).to.have.been.calledWithExactly('artemisApp.team.errors.studentsAppearMultipleTimes', { students: message });\n });\n });\n\n describe('setShowImportFromExercise', () => {\n let initImportStrategyStub: SinonStub;\n const expectValuesToBeReset = () => {\n expect(comp.sourceTeams).to.equal(undefined);\n expect(comp.sourceExercise).to.equal(undefined);\n expect(comp.isImporting).to.equal(false);\n expect(comp.conflictingLoginsSet).to.deep.equal(new Set(logins));\n expect(comp.conflictingRegistrationNumbersSet).to.deep.equal(new Set(registrationNumbers));\n expect(initImportStrategyStub).to.have.been.called;\n };\n beforeEach(() => {\n resetComponent();\n initImportStrategyStub = stub(comp, 'initImportStrategy');\n comp.sourceTeams = mockSourceTeams;\n comp.sourceExercise = mockSourceExercise;\n comp.isImporting = true;\n comp.studentsAppearInMultipleTeams = true;\n comp.conflictingRegistrationNumbersSet = new Set(['1']);\n comp.conflictingLoginsSet = new Set(['l1']);\n });\n afterEach(() => {\n restore();\n });\n it('should set show import from exercise to true', () => {\n comp.showImportFromExercise = false;\n comp.setShowImportFromExercise(true);\n expect(comp.showImportFromExercise).to.equal(true);\n expectValuesToBeReset();\n });\n it('should set show import from exercise to false', () => {\n comp.setShowImportFromExercise(false);\n expect(comp.showImportFromExercise).to.equal(false);\n expectValuesToBeReset();\n });\n });\n\n describe('sampleTeamForLegend', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return a sample team', () => {\n const team = new Team();\n team.students = [{ ...new User(1, 'ga12abc', 'John', 'Doe', '[email protected]'), name: 'John Doe' }];\n expect(comp.sampleTeamForLegend).to.deep.equal(team);\n });\n });\n\n describe('sampleErrorStudentLoginsForLegend', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return a logins of sample team', () => {\n expect(comp.sampleErrorStudentLoginsForLegend).to.deep.equal(['ga12abc']);\n });\n });\n\n describe('showLegend', () => {\n beforeEach(() => {\n resetComponent();\n comp.sourceTeams = mockSourceTeams;\n });\n it('should return false no source teams', () => {\n comp.sourceTeams = undefined;\n expect(comp.showLegend).to.equal(false);\n });\n it('should return false source teams length is equal to conflict free teams length', () => {\n comp.sourceTeamsFreeOfConflicts = mockSourceTeams;\n expect(comp.showLegend).to.equal(false);\n });\n it('should return true source teams length not equal to conflict free teams length', () => {\n comp.sourceTeamsFreeOfConflicts = [];\n expect(comp.showLegend).to.equal(true);\n });\n });\n\n describe('problematicRegistrationNumbers', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return union of registration number arrays', () => {\n const conflictingRegistrationNumbers = ['1', '2', '3'];\n comp.conflictingRegistrationNumbersSet = new Set(conflictingRegistrationNumbers);\n expect(comp.problematicRegistrationNumbers).to.deep.equal(conflictingRegistrationNumbers);\n });\n });\n\n describe('problematicLogins', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return array of conflicting logins set', () => {\n const conflictingLogins = ['l1', 'l2', 'l3'];\n comp.conflictingLoginsSet = new Set(conflictingLogins);\n expect(comp.problematicLogins).to.deep.equal(conflictingLogins);\n });\n });\n});\n" }, { "alpha_fraction": 0.7047325968742371, "alphanum_fraction": 0.7055643200874329, "avg_line_length": 51.2739143371582, "blob_id": "1e0cf1907ff7bd73c28ffedca64c46e7c9e4ab8c", "content_id": "98cf8c144c3c3aca1bf48f818dd81ea7a53f3ec1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 12023, "license_type": "permissive", "max_line_length": 179, "num_lines": 230, "path": "/src/main/java/de/tum/in/www1/artemis/service/StaticCodeAnalysisService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.lang3.tuple.ImmutablePair;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.stereotype.Service;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.CategoryState;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.repository.StaticCodeAnalysisCategoryRepository;\nimport de.tum.in.www1.artemis.service.dto.StaticCodeAnalysisReportDTO;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingSubmissionService;\n\n@Service\npublic class StaticCodeAnalysisService {\n\n private final Logger log = LoggerFactory.getLogger(StaticCodeAnalysisService.class);\n\n @Qualifier(\"staticCodeAnalysisConfiguration\")\n private final Map<ProgrammingLanguage, List<StaticCodeAnalysisDefaultCategory>> staticCodeAnalysisDefaultConfigurations;\n\n private final StaticCodeAnalysisCategoryRepository staticCodeAnalysisCategoryRepository;\n\n ProgrammingSubmissionService programmingSubmissionService;\n\n public StaticCodeAnalysisService(StaticCodeAnalysisCategoryRepository staticCodeAnalysisCategoryRepository,\n Map<ProgrammingLanguage, List<StaticCodeAnalysisDefaultCategory>> staticCodeAnalysisDefaultConfigurations, ProgrammingSubmissionService programmingSubmissionService) {\n this.staticCodeAnalysisCategoryRepository = staticCodeAnalysisCategoryRepository;\n this.staticCodeAnalysisDefaultConfigurations = staticCodeAnalysisDefaultConfigurations;\n this.programmingSubmissionService = programmingSubmissionService;\n }\n\n /**\n * Returns all static code analysis categories of the given programming exercise.\n *\n * @param exerciseId of a programming exercise.\n * @return static code analysis categories of a programming exercise.\n */\n public Set<StaticCodeAnalysisCategory> findByExerciseId(Long exerciseId) {\n return staticCodeAnalysisCategoryRepository.findByExerciseId(exerciseId);\n }\n\n /**\n * Creates static code analysis categories for a programming exercise using @{staticCodeAnalysisDefaultConfigurations}\n * as a template.\n *\n * @param programmingExercise for which the static code analysis categories will be created\n */\n public void createDefaultCategories(ProgrammingExercise programmingExercise) {\n // Retrieve the default configuration for a specific programming language\n List<StaticCodeAnalysisDefaultCategory> defaultConfiguration = staticCodeAnalysisDefaultConfigurations.get(programmingExercise.getProgrammingLanguage());\n if (defaultConfiguration == null) {\n log.debug(\"Could not create default static code analysis categories for exercise {}. Default configuration not available.\", programmingExercise.getId());\n return;\n }\n\n // Create new static code analysis using the default configuration as a template\n List<StaticCodeAnalysisCategory> newCategories = new ArrayList<>();\n for (var defaultCategory : defaultConfiguration) {\n StaticCodeAnalysisCategory newCategory = new StaticCodeAnalysisCategory();\n newCategory.setName(defaultCategory.getName());\n newCategory.setPenalty(defaultCategory.getPenalty());\n newCategory.setMaxPenalty(defaultCategory.getMaxPenalty());\n newCategory.setState(defaultCategory.getState());\n newCategory.setProgrammingExercise(programmingExercise);\n newCategories.add(newCategory);\n }\n staticCodeAnalysisCategoryRepository.saveAll(newCategories);\n }\n\n /**\n * Updates the static code analysis categories of a programming exercise.\n *\n * @param exerciseId of a programming exercise\n * @param updatedCategories updates for categories\n * @return updated categories\n */\n public Set<StaticCodeAnalysisCategory> updateCategories(Long exerciseId, Collection<StaticCodeAnalysisCategory> updatedCategories) {\n Set<StaticCodeAnalysisCategory> originalCategories = findByExerciseId(exerciseId);\n for (StaticCodeAnalysisCategory originalCategory : originalCategories) {\n // Find an updated category with the same id\n Optional<StaticCodeAnalysisCategory> matchingCategoryOptional = updatedCategories.stream()\n .filter(updatedCategory -> originalCategory.getId().equals(updatedCategory.getId())).findFirst();\n\n // If no match is found, the original category won't be updated\n if (matchingCategoryOptional.isEmpty()) {\n continue;\n }\n StaticCodeAnalysisCategory matchingCategory = matchingCategoryOptional.get();\n\n // Update the original category\n originalCategory.setPenalty(matchingCategory.getPenalty());\n originalCategory.setMaxPenalty(matchingCategory.getMaxPenalty());\n originalCategory.setState(matchingCategory.getState());\n }\n staticCodeAnalysisCategoryRepository.saveAll(originalCategories);\n\n // At least one category was updated. We use this flag to inform the instructor about outdated student results.\n programmingSubmissionService.setTestCasesChangedAndTriggerTestCaseUpdate(exerciseId);\n\n return originalCategories;\n }\n\n /**\n * Restore the default configuration for static code analysis categories of the given exercise.\n * Categories without a default configuration are ignored.\n * Returns the original categories if a default configuration could not be found.\n *\n * @param exercise exercise for which the static code analysis category configuration should be restored\n * @return static code analysis categories with default configuration\n */\n public Set<StaticCodeAnalysisCategory> resetCategories(ProgrammingExercise exercise) {\n Set<StaticCodeAnalysisCategory> categories = findByExerciseId(exercise.getId());\n List<StaticCodeAnalysisDefaultCategory> defaultCategories = staticCodeAnalysisDefaultConfigurations.get(exercise.getProgrammingLanguage());\n if (defaultCategories == null) {\n log.debug(\"Could not reset static code analysis categories for exercise {}. Default configuration not available.\", exercise.getId());\n return categories;\n }\n\n // Restore the default configuration. Ignore unknown categories by iterating over the default categories\n for (var defaultCategory : defaultCategories) {\n var matchingCategory = categories.stream().filter(category -> Objects.equals(defaultCategory.getName(), category.getName())).findFirst();\n matchingCategory.ifPresent(cat -> {\n cat.setPenalty(defaultCategory.getPenalty());\n cat.setMaxPenalty(defaultCategory.getMaxPenalty());\n cat.setState(defaultCategory.getState());\n });\n }\n staticCodeAnalysisCategoryRepository.saveAll(categories);\n\n // We use this flag to inform the instructor about outdated student results.\n programmingSubmissionService.setTestCasesChangedAndTriggerTestCaseUpdate(exercise.getId());\n\n return categories;\n }\n\n /**\n * Links the categories of an exercise with the default category mappings.\n * @param programmingExercise The programming exercise\n * @return A list of pairs of categories and their mappings.\n */\n public List<ImmutablePair<StaticCodeAnalysisCategory, List<StaticCodeAnalysisDefaultCategory.CategoryMapping>>> getCategoriesWithMappingForExercise(\n ProgrammingExercise programmingExercise) {\n var categories = findByExerciseId(programmingExercise.getId());\n var defaultCategories = staticCodeAnalysisDefaultConfigurations.get(programmingExercise.getProgrammingLanguage());\n\n List<ImmutablePair<StaticCodeAnalysisCategory, List<StaticCodeAnalysisDefaultCategory.CategoryMapping>>> categoryPairsWithMapping = new ArrayList<>();\n\n for (var category : categories) {\n var defaultCategoryMatch = defaultCategories.stream().filter(defaultCategory -> defaultCategory.getName().equals(category.getName())).findFirst();\n if (defaultCategoryMatch.isPresent()) {\n var categoryMappings = defaultCategoryMatch.get().getCategoryMappings();\n categoryPairsWithMapping.add(new ImmutablePair<>(category, categoryMappings));\n }\n }\n\n return categoryPairsWithMapping;\n }\n\n /**\n * Sets the category for each feedback and removes feedback with no or an inactive category.\n * The feedback is removed permanently, which has the advantage that the server or client doesn't have to filter out\n * invisible feedback every time it is requested. The drawback is that the re-evaluate functionality can't take\n * the removed feedback into account.\n *\n * @param result of the build run\n * @param staticCodeAnalysisFeedback List of static code analysis feedback objects\n * @param programmingExercise The current exercise\n * @return The filtered list of feedback objects\n */\n public List<Feedback> categorizeScaFeedback(Result result, List<Feedback> staticCodeAnalysisFeedback, ProgrammingExercise programmingExercise) {\n var categoryPairs = getCategoriesWithMappingForExercise(programmingExercise);\n\n return staticCodeAnalysisFeedback.stream().filter(feedback -> {\n // ObjectMapper to extract the static code analysis issue from the feedback\n ObjectMapper mapper = new ObjectMapper();\n // the category for this feedback\n Optional<StaticCodeAnalysisCategory> category = Optional.empty();\n try {\n\n // extract the sca issue\n var issue = mapper.readValue(feedback.getDetailText(), StaticCodeAnalysisReportDTO.StaticCodeAnalysisIssue.class);\n\n // find the category for this issue\n for (var categoryPair : categoryPairs) {\n var categoryMappings = categoryPair.right;\n if (categoryMappings.stream()\n .anyMatch(mapping -> mapping.getTool().name().equals(feedback.getReference()) && mapping.getCategory().equals(issue.getCategory()))) {\n category = Optional.of(categoryPair.left);\n break;\n }\n }\n\n if (category.isPresent()) {\n if (category.get().getState() == CategoryState.GRADED) {\n // update the penalty of the issue\n issue.setPenalty(category.get().getPenalty());\n }\n else if (issue.getPenalty() != null) {\n // remove the penalty of the issue\n issue.setPenalty(null);\n }\n feedback.setDetailText(mapper.writeValueAsString(issue));\n }\n }\n catch (JsonProcessingException exception) {\n log.debug(\"Error occurred parsing feedback {} to static code analysis issue: {}\", feedback, exception.getMessage());\n }\n\n if (category.isEmpty() || category.get().getState().equals(CategoryState.INACTIVE)) {\n // remove feedback in no or inactive category\n result.removeFeedback(feedback);\n return false; // filter this feedback\n }\n else {\n // add the category name to the feedback text\n feedback.setText(Feedback.STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER + category.get().getName());\n return true; // keep this feedback\n }\n }).collect(Collectors.toList());\n }\n}\n" }, { "alpha_fraction": 0.6954787373542786, "alphanum_fraction": 0.6954787373542786, "avg_line_length": 29.079999923706055, "blob_id": "97063f89164c4312cb552ee4c1dfc3c13d968f25", "content_id": "637bf8fc6f25a8220385cbdb64b2274e33fc957a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 752, "license_type": "permissive", "max_line_length": 113, "num_lines": 25, "path": "/src/main/webapp/app/shared/pipes/artemis-time-ago.pipe.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectorRef, NgZone, OnDestroy, Pipe, PipeTransform } from '@angular/core';\nimport { TimeAgoPipe } from 'ngx-moment';\n\n@Pipe({\n name: 'artemisTimeAgo',\n pure: false,\n})\n/**\n * a simple wrapper to prevent compile errors in IntelliJ\n */\nexport class ArtemisTimeAgoPipe implements PipeTransform, OnDestroy {\n private timeAgoPipe: TimeAgoPipe;\n\n constructor(cdRef: ChangeDetectorRef, ngZone: NgZone) {\n this.timeAgoPipe = new TimeAgoPipe(cdRef, ngZone);\n }\n\n transform(value: moment.MomentInput, omitSuffix?: boolean, formatFn?: (m: moment.Moment) => string): string {\n return this.timeAgoPipe.transform(value, omitSuffix, formatFn);\n }\n\n ngOnDestroy() {\n this.timeAgoPipe.ngOnDestroy();\n }\n}\n" }, { "alpha_fraction": 0.7032520174980164, "alphanum_fraction": 0.7032520174980164, "avg_line_length": 46.30769348144531, "blob_id": "51e5469daa3a7ca9da6a82641355905df66f1808", "content_id": "768b95ddeed1b7eedfca3ce942f12bc7b687e908", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1230, "license_type": "permissive", "max_line_length": 159, "num_lines": 26, "path": "/src/main/webapp/app/exercises/programming/manage/services/programming-exercise-paging.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { PageableSearch, SearchResult } from 'app/shared/table/pageable-table';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\n\ntype EntityResponseType = SearchResult<ProgrammingExercise>;\n\n@Injectable({ providedIn: 'root' })\nexport class ProgrammingExercisePagingService {\n public resourceUrl = SERVER_API_URL + 'api/programming-exercises';\n\n constructor(private http: HttpClient) {}\n\n searchForExercises(pageable: PageableSearch): Observable<EntityResponseType> {\n const params = new HttpParams()\n .set('pageSize', String(pageable.pageSize))\n .set('page', String(pageable.page))\n .set('sortingOrder', pageable.sortingOrder)\n .set('searchTerm', pageable.searchTerm)\n .set('sortedColumn', pageable.sortedColumn);\n return this.http.get(`${this.resourceUrl}`, { params, observe: 'response' }).pipe(map((resp: HttpResponse<EntityResponseType>) => resp && resp.body!));\n }\n}\n" }, { "alpha_fraction": 0.7180808782577515, "alphanum_fraction": 0.725614607334137, "avg_line_length": 31.33333396911621, "blob_id": "8296b620611fd8505ff980ef0f8e89a2e787f160", "content_id": "106b8d46afe8f6c95734a40a8abd2b145f43861a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2522, "license_type": "permissive", "max_line_length": 139, "num_lines": 78, "path": "/src/main/java/de/tum/in/www1/artemis/security/jwt/AtheneTrackingTokenProvider.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.security.jwt;\n\nimport java.security.Key;\nimport java.util.Date;\n\nimport javax.annotation.PostConstruct;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Component;\n\nimport de.tum.in.www1.artemis.domain.Result;\nimport io.jsonwebtoken.Jwts;\nimport io.jsonwebtoken.SignatureAlgorithm;\nimport io.jsonwebtoken.io.Decoders;\nimport io.jsonwebtoken.security.Keys;\n\n/**\n * This component is used to create a jwt token for the tutor-assessment tracking.\n * <p>\n * The token is used to verify, that the tracking request belongs to the corresponding result that\n * is assessed\n */\n@Component\n@Profile(\"athene\")\npublic class AtheneTrackingTokenProvider {\n\n private final Logger log = LoggerFactory.getLogger(AtheneTrackingTokenProvider.class);\n\n @Value(\"${artemis.athene.base64-secret}\")\n private String BASE64_SECRET;\n\n private Key key;\n\n @Value(\"${artemis.athene.token-validity-in-seconds}\")\n private int TOKEN_VALIDITY_IN_SECONDS;\n\n private int tokenValidityInMilliseconds;\n\n /**\n * initializes the token provider based on the yml config file\n */\n @PostConstruct\n private void init() {\n byte[] keyBytes = Decoders.BASE64.decode(BASE64_SECRET);\n this.key = Keys.hmacShaKeyFor(keyBytes);\n this.tokenValidityInMilliseconds = 1000 * TOKEN_VALIDITY_IN_SECONDS;\n }\n\n /**\n * Create JWT Token to communicate with the Athene Tracking Component for a given Result.\n *\n * @param result Result Object\n * @return JWT Token\n */\n public String createToken(Result result) {\n log.trace(\"Create Athene Tracking Token for Result {}\", result);\n\n long now = (new Date()).getTime();\n Date validity = new Date(now + this.tokenValidityInMilliseconds);\n\n return Jwts.builder().claim(\"result_id\", result.getId()).signWith(key, SignatureAlgorithm.HS256).setExpiration(validity).compact();\n }\n\n /**\n * Create JWT Token to communicate with the Athene Tracking Component and add it as HTTP\n * Header.\n *\n * @param bodyBuilder HttpResponse BodyBuilder\n * @param result Result Object\n */\n public void addTokenToResponseEntity(ResponseEntity.BodyBuilder bodyBuilder, Result result) {\n bodyBuilder.header(\"X-Athene-Tracking-Authorization\", createToken(result));\n }\n}\n" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.4571428596973419, "avg_line_length": 17, "blob_id": "7f4a7c3056dfcb7eb6c5b642ee73a887aca75c9a", "content_id": "3f58af5cbf688944870612e61fdd25ccf226163c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 35, "license_type": "permissive", "max_line_length": 17, "num_lines": 2, "path": "/docs/user/exercises/modeling.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Modeling exercise\n=================" }, { "alpha_fraction": 0.6173725724220276, "alphanum_fraction": 0.6180904507637024, "avg_line_length": 38.79999923706055, "blob_id": "6811fa2f32fbb71f64bf810452062b0ef3c348f8", "content_id": "b9cb06549afc9302a8a1c1d71f8782472c53d866", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2786, "license_type": "permissive", "max_line_length": 178, "num_lines": 70, "path": "/src/main/webapp/app/shared/components/confirm-autofocus-button.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\n\n@Component({\n template: `\n <div class=\"modal-header\">\n <h4 class=\"modal-title\">{{ title | translate }}</h4>\n <button type=\"button\" class=\"close\" aria-label=\"Close button\" aria-describedby=\"modal-title\" (click)=\"modal.dismiss('Cross click')\">\n <span aria-hidden=\"true\">&times;</span>\n </button>\n </div>\n <div class=\"modal-body\">\n <p *ngIf=\"translateText === true\" style=\"white-space: pre-line\">{{ text | translate }}</p>\n <p *ngIf=\"translateText !== true\" style=\"white-space: pre-line\">{{ text }}</p>\n </div>\n <div class=\"modal-footer\">\n <button type=\"button\" class=\"btn btn-outline-secondary\" (click)=\"modal.dismiss('cancel click')\" jhiTranslate=\"global.form.cancel\">Cancel</button>\n <button type=\"button\" ngbAutofocus class=\"btn btn-danger\" (click)=\"modal.close('Ok click')\" jhiTranslate=\"global.form.confirm\">Confirm</button>\n </div>\n `,\n})\nexport class ConfirmAutofocusModalComponent {\n title: string;\n text: string;\n translateText: boolean;\n\n constructor(public modal: NgbActiveModal) {}\n}\n\n@Component({\n selector: 'jhi-confirm-button',\n template: ` <jhi-button [icon]=\"icon\" [title]=\"title\" [tooltip]=\"tooltip\" [disabled]=\"disabled\" [isLoading]=\"isLoading\" (onClick)=\"onOpenConfirmationModal()\"></jhi-button> `,\n})\nexport class ConfirmAutofocusButtonComponent {\n @Input() icon: string;\n @Input() title: string;\n @Input() tooltip: string;\n @Input() disabled = false;\n @Input() isLoading = false;\n\n @Input() confirmationTitle: string;\n @Input() confirmationText: string;\n @Input() translateText?: boolean;\n @Output() onConfirm = new EventEmitter<void>();\n @Output() onCancel = new EventEmitter<void>();\n\n constructor(private modalService: NgbModal) {}\n\n /**\n * open confirmation modal with text and title\n */\n onOpenConfirmationModal() {\n const modalRef: NgbModalRef = this.modalService.open(ConfirmAutofocusModalComponent as Component, { size: 'lg', backdrop: 'static' });\n modalRef.componentInstance.text = this.confirmationText;\n modalRef.componentInstance.title = this.confirmationTitle;\n if (this.translateText !== undefined) {\n modalRef.componentInstance.translateText = this.translateText;\n } else {\n modalRef.componentInstance.translateText = false;\n }\n modalRef.result.then(\n () => {\n this.onConfirm.emit();\n },\n () => {\n this.onCancel.emit();\n },\n );\n }\n}\n" }, { "alpha_fraction": 0.7669664621353149, "alphanum_fraction": 0.7677841186523438, "avg_line_length": 28.829267501831055, "blob_id": "32482d5e141bd770f097c57c9d1a4975f25bb2f8", "content_id": "d7749259af609a23af40a4eade643f523b1103be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1223, "license_type": "permissive", "max_line_length": 107, "num_lines": 41, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/IndividualLearningGoalProgress.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n/**\n * This DTO contains the information for a students progress in achieving a learning goal\n * The learning goal progress is calculated from the performance in a subset of the connected lecture units\n */\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class IndividualLearningGoalProgress {\n\n public Long studentId;\n\n public Long learningGoalId;\n\n public String learningGoalTitle;\n\n public Double pointsAchievedByStudentInLearningGoal;\n\n public Double totalPointsAchievableByStudentsInLearningGoal;\n\n /**\n * the students progress in the connected lecture units that were used for the progress calculation\n */\n public List<IndividualLectureUnitProgress> progressInLectureUnits = new ArrayList<>();\n\n /**\n * This DTO contains the information for a students progress in completing a lecture unit\n */\n public static class IndividualLectureUnitProgress {\n\n public Long lectureUnitId;\n\n public Double scoreAchievedByStudentInLectureUnit;\n\n public Double totalPointsAchievableByStudentsInLectureUnit;\n }\n}\n" }, { "alpha_fraction": 0.6413474082946777, "alphanum_fraction": 0.6413474082946777, "avg_line_length": 41.52809143066406, "blob_id": "ecd8e854ceceefd8244f3e63ac8f93ccf2153f08", "content_id": "5d633f1c5b4ec472af6bae77b5fa4bfd67091946", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7570, "license_type": "permissive", "max_line_length": 132, "num_lines": 178, "path": "/src/main/webapp/app/shared/notification/notification.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable, ReplaySubject } from 'rxjs';\nimport * as moment from 'moment';\nimport { map } from 'rxjs/operators';\n\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { Router } from '@angular/router';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { User } from 'app/core/user/user.model';\nimport { GroupNotification, GroupNotificationType } from 'app/entities/group-notification.model';\nimport { Notification } from 'app/entities/notification.model';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\n\n@Injectable({ providedIn: 'root' })\nexport class NotificationService {\n public resourceUrl = SERVER_API_URL + 'api/notifications';\n subscribedTopics: string[] = [];\n notificationObserver: ReplaySubject<Notification>;\n cachedNotifications: Observable<HttpResponse<Notification[]>>;\n\n constructor(\n private jhiWebsocketService: JhiWebsocketService,\n private router: Router,\n private http: HttpClient,\n private accountService: AccountService,\n private courseManagementService: CourseManagementService,\n ) {\n this.initNotificationObserver();\n }\n\n /**\n * Query all notifications.\n * @param req request options\n * @return Observable<HttpResponse<Notification[]>>\n */\n query(req?: any): Observable<HttpResponse<Notification[]>> {\n const options = createRequestOption(req);\n return this.http\n .get<Notification[]>(this.resourceUrl, { params: options, observe: 'response' })\n .pipe(map((res: HttpResponse<Notification[]>) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * Delete notification by id.\n * @param {number} id\n * @return Observable<HttpResponse<any>>\n */\n delete(id: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response' });\n }\n\n /**\n * Navigate to notification target.\n * @param {GroupNotification} notification\n */\n interpretNotification(notification: GroupNotification): void {\n if (notification.target) {\n const target = JSON.parse(notification.target);\n const courseId = target.course || notification.course?.id;\n this.router.navigate([target.mainPage, courseId, target.entity, target.id]);\n }\n }\n\n /**\n * Init new observer for notifications and reset topics.\n */\n cleanUp(): void {\n this.cachedNotifications = new Observable<HttpResponse<Notification[]>>();\n this.initNotificationObserver();\n this.subscribedTopics = [];\n }\n\n /**\n * Subscribe to single user notification, group notification and quiz updates if it was not already subscribed.\n * Then it returns a BehaviorSubject the calling component can listen on to actually receive the notifications.\n * @returns {ReplaySubject<Notification>}\n */\n subscribeToNotificationUpdates(): ReplaySubject<Notification> {\n this.subscribeToSingleUserNotificationUpdates();\n this.courseManagementService.getCoursesForNotifications().subscribe((courses) => {\n if (courses) {\n this.subscribeToGroupNotificationUpdates(courses);\n this.subscribeToQuizUpdates(courses);\n }\n });\n return this.notificationObserver;\n }\n\n private subscribeToSingleUserNotificationUpdates(): void {\n this.accountService.identity().then((user: User | undefined) => {\n if (user) {\n const userTopic = `/topic/user/${user.id}/notifications`;\n if (!this.subscribedTopics.includes(userTopic)) {\n this.subscribedTopics.push(userTopic);\n this.jhiWebsocketService.subscribe(userTopic);\n this.jhiWebsocketService.receive(userTopic).subscribe((notification: Notification) => {\n this.addNotificationToObserver(notification);\n });\n }\n }\n });\n }\n\n private subscribeToGroupNotificationUpdates(courses: Course[]): void {\n courses.forEach((course) => {\n let courseTopic = `/topic/course/${course.id}/${GroupNotificationType.STUDENT}`;\n if (this.accountService.isAtLeastInstructorInCourse(course)) {\n courseTopic = `/topic/course/${course.id}/${GroupNotificationType.INSTRUCTOR}`;\n } else if (this.accountService.isAtLeastTutorInCourse(course)) {\n courseTopic = `/topic/course/${course.id}/${GroupNotificationType.TA}`;\n }\n if (!this.subscribedTopics.includes(courseTopic)) {\n this.subscribedTopics.push(courseTopic);\n this.jhiWebsocketService.subscribe(courseTopic);\n this.jhiWebsocketService.receive(courseTopic).subscribe((notification: Notification) => {\n this.addNotificationToObserver(notification);\n });\n }\n });\n }\n\n private subscribeToQuizUpdates(courses: Course[]): void {\n courses.forEach((course) => {\n const quizExerciseTopic = '/topic/courses/' + course.id + '/quizExercises';\n if (!this.subscribedTopics.includes(quizExerciseTopic)) {\n this.subscribedTopics.push(quizExerciseTopic);\n this.jhiWebsocketService.subscribe(quizExerciseTopic);\n this.jhiWebsocketService.receive(quizExerciseTopic).subscribe((quizExercise: QuizExercise) => {\n if (quizExercise.visibleToStudents && quizExercise.started) {\n this.addNotificationToObserver(NotificationService.createNotificationFromStartedQuizExercise(quizExercise));\n }\n });\n }\n });\n }\n\n private static createNotificationFromStartedQuizExercise(quizExercise: QuizExercise): GroupNotification {\n return {\n title: 'Quiz started',\n text: 'Quiz \"' + quizExercise.title + '\" just started.',\n notificationDate: moment(),\n target: JSON.stringify({\n course: quizExercise.course!.id,\n mainPage: 'courses',\n entity: 'exercises',\n id: quizExercise.id,\n }),\n } as GroupNotification;\n }\n\n private addNotificationToObserver(notification: Notification): void {\n if (notification && notification.notificationDate) {\n notification.notificationDate = moment(notification.notificationDate);\n this.notificationObserver.next(notification);\n }\n }\n\n private convertDateArrayFromServer(res: HttpResponse<Notification[]>): HttpResponse<Notification[]> {\n if (res.body) {\n res.body.forEach((notification: Notification) => {\n notification.notificationDate = notification.notificationDate ? moment(notification.notificationDate) : undefined;\n });\n }\n return res;\n }\n\n /**\n * Set new notification observer.\n */\n private initNotificationObserver(): void {\n this.notificationObserver = new ReplaySubject<Notification>();\n }\n}\n" }, { "alpha_fraction": 0.6940129399299622, "alphanum_fraction": 0.695858359336853, "avg_line_length": 51.78544998168945, "blob_id": "e38b2729c4f77e0a1f70714a17a6461c76f2e68f", "content_id": "8b5a8af1f2249e68a6bcc633ac25b4417b4cf71d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 42809, "license_type": "permissive", "max_line_length": 179, "num_lines": 811, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseExportService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.*;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport javax.validation.constraints.NotNull;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.ParserConfigurationException;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\nimport javax.xml.xpath.*;\n\nimport org.apache.commons.io.FileUtils;\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.FileSystemUtils;\nimport org.w3c.dom.Document;\nimport org.w3c.dom.Node;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.SAXException;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.Submission;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.domain.enumeration.RepositoryType;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.plagiarism.text.TextPlagiarismResult;\nimport de.tum.in.www1.artemis.exception.GitException;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.repository.StudentParticipationRepository;\nimport de.tum.in.www1.artemis.service.FileService;\nimport de.tum.in.www1.artemis.service.UrlService;\nimport de.tum.in.www1.artemis.service.ZipFileService;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.util.TimeLogUtil;\nimport de.tum.in.www1.artemis.web.rest.dto.RepositoryExportOptionsDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport jplag.*;\nimport jplag.options.LanguageOption;\nimport jplag.reporting.Report;\n\n@Service\npublic class ProgrammingExerciseExportService {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseExportService.class);\n\n // The downloaded repos should be cloned into another path in order to not interfere with the repo used by the student\n @Value(\"${artemis.repo-download-clone-path}\")\n private String repoDownloadClonePath;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final StudentParticipationRepository studentParticipationRepository;\n\n private final FileService fileService;\n\n private final GitService gitService;\n\n private final ZipFileService zipFileService;\n\n private final UrlService urlService;\n\n private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());\n\n public ProgrammingExerciseExportService(ProgrammingExerciseRepository programmingExerciseRepository, StudentParticipationRepository studentParticipationRepository,\n FileService fileService, GitService gitService, ZipFileService zipFileService, UrlService urlService) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.studentParticipationRepository = studentParticipationRepository;\n this.fileService = fileService;\n this.gitService = gitService;\n this.zipFileService = zipFileService;\n this.urlService = urlService;\n }\n\n /**\n * Export a programming exercise by creating a zip file. The zip file includes all student, template, solution,\n * and tests repositories.\n *\n * @param exercise the programming exercise\n * @param pathToStoreZipFile The path to a directory that will be used to store the zipped programming exercise.\n * @param exportErrors List of failures that occurred during the export\n * @return the path to the zip file\n */\n public Path exportProgrammingExercise(ProgrammingExercise exercise, String pathToStoreZipFile, List<String> exportErrors) {\n // Will contain the zipped files. Note that there can be null elements\n // because e.g exportStudentRepositories returns null if student repositories don't\n // exist.\n var zipFiles = new ArrayList<File>();\n\n // Lazy load student participations and set the export options.\n var studentParticipations = studentParticipationRepository.findByExerciseId(exercise.getId()).stream()\n .map(studentParticipation -> (ProgrammingExerciseStudentParticipation) studentParticipation).collect(Collectors.toList());\n var exportOptions = new RepositoryExportOptionsDTO();\n exportOptions.setHideStudentNameInZippedFolder(false);\n\n // Export student repositories\n var studentZipFilePaths = exportStudentRepositories(exercise, studentParticipations, exportOptions, exportErrors).stream().filter(Objects::nonNull).map(Path::toFile)\n .collect(Collectors.toList());\n zipFiles.addAll(studentZipFilePaths);\n\n // Export the template, solution, and tests repositories\n zipFiles.add(exportInstructorRepositoryForExercise(exercise.getId(), RepositoryType.TEMPLATE, exportErrors));\n zipFiles.add(exportInstructorRepositoryForExercise(exercise.getId(), RepositoryType.SOLUTION, exportErrors));\n zipFiles.add(exportInstructorRepositoryForExercise(exercise.getId(), RepositoryType.TESTS, exportErrors));\n\n // Remove null elements and get the file path of each zip file.\n var zipFilePathsNonNull = zipFiles.stream().filter(Objects::nonNull).map(File::toPath).collect(Collectors.toList());\n\n try {\n // Zip the student and instructor repos together.\n var timestamp = ZonedDateTime.now().format(DateTimeFormatter.ofPattern(\"yyyyMMdd-Hmss\"));\n var filename = exercise.getCourseViaExerciseGroupOrCourseMember().getShortName() + \"-\" + exercise.getTitle() + \"-\" + exercise.getId() + \"-\" + timestamp + \".zip\";\n var pathToZippedExercise = Path.of(pathToStoreZipFile, filename);\n zipFileService.createZipFile(pathToZippedExercise, zipFilePathsNonNull, false);\n return pathToZippedExercise;\n }\n catch (IOException e) {\n var error = \"Failed to export programming exercise \" + exercise.getId() + \" because the zip file \" + pathToStoreZipFile + \" could not be created: \" + e.getMessage();\n log.info(error);\n exportErrors.add(error);\n return null;\n }\n finally {\n // Delete the zipped repo files since we don't need those anymore.\n zipFilePathsNonNull.forEach(zipFilePath -> fileService.scheduleForDeletion(zipFilePath, 1));\n }\n }\n\n /**\n * Exports a repository available for an instructor/tutor for a given programming exercise. This can be a template,\n * solution, or tests repository\n *\n * @param exerciseId The id of the programming exercise that has the repository\n * @param repositoryType the type of repository to export\n * @param exportErrors List of failures that occurred during the export\n * @return a zipped file\n */\n public File exportInstructorRepositoryForExercise(long exerciseId, RepositoryType repositoryType, List<String> exportErrors) {\n var exerciseOrEmpty = programmingExerciseRepository.findWithTemplateAndSolutionParticipationById(exerciseId);\n if (exerciseOrEmpty.isEmpty()) {\n var error = \"Failed to export instructor repository \" + repositoryType + \" because the exercise \" + exerciseId + \" does not exist.\";\n log.info(error);\n exportErrors.add(error);\n return null;\n }\n\n var exercise = exerciseOrEmpty.get();\n log.info(\"Request to export instructor repository of type {} of programming exercise {} with title '{}'\", repositoryType.getName(), exercise, exercise.getTitle());\n\n // Construct the name of the zip file\n String courseShortName = exercise.getCourseViaExerciseGroupOrCourseMember().getShortName();\n String zippedRepoName = courseShortName + \"-\" + exercise.getTitle() + \"-\" + repositoryType.getName();\n\n try {\n // Get the url to the repository and zip it.\n var repositoryUrl = exercise.getRepositoryURL(repositoryType);\n\n // It's not guaranteed that the repository url is defined (old courses).\n if (repositoryUrl == null) {\n var error = \"Failed to export instructor repository \" + repositoryType + \" because the repository url is not defined.\";\n log.info(error);\n exportErrors.add(error);\n return null;\n }\n\n Path zippedRepo = createZipForRepository(repositoryUrl, zippedRepoName);\n if (zippedRepo != null) {\n return new File(zippedRepo.toString());\n }\n }\n catch (InterruptedException | GitAPIException | GitException ex) {\n var error = \"Failed to export instructor repository \" + repositoryType + \" for programming exercise '\" + exercise.getTitle() + \"' (id: \" + exercise.getId()\n + \") because the repository couldn't be downloaded. \";\n log.info(error);\n exportErrors.add(error);\n }\n catch (IOException e) {\n var error = \"Failed to export instructor repository \" + repositoryType + \"because the zip file couldn't be created: \" + e.getMessage();\n log.error(error);\n exportErrors.add(error);\n }\n\n return null;\n }\n\n /**\n * Get participations of programming exercises of a requested list of students packed together in one zip file.\n *\n * @param programmingExerciseId the id of the exercise entity\n * @param participations participations that should be exported\n * @param repositoryExportOptions the options that should be used for the export\n * @return a zip file containing all requested participations\n */\n public File exportStudentRepositoriesToZipFile(long programmingExerciseId, @NotNull List<ProgrammingExerciseStudentParticipation> participations,\n RepositoryExportOptionsDTO repositoryExportOptions) {\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId)\n .get();\n\n var zippedRepos = exportStudentRepositories(programmingExercise, participations, repositoryExportOptions, new ArrayList<>());\n\n // delete project root folder\n final var targetPath = fileService.getUniquePathString(repoDownloadClonePath);\n deleteReposDownloadProjectRootDirectory(programmingExercise, targetPath);\n\n // Create a zip folder containing the zipped repositories.\n return createZipWithAllRepositories(programmingExercise, zippedRepos);\n }\n\n /**\n * Zip the participations of programming exercises of a requested list of students separately.\n *\n * @param programmingExercise the programming exercise\n * @param participations participations that should be exported\n * @param repositoryExportOptions the options that should be used for the export\n * @param exportErrors A list of errors that occured during export (populated by this function)\n * @return List of zip file paths\n */\n public List<Path> exportStudentRepositories(ProgrammingExercise programmingExercise, @NotNull List<ProgrammingExerciseStudentParticipation> participations,\n RepositoryExportOptionsDTO repositoryExportOptions, List<String> exportErrors) {\n var programmingExerciseId = programmingExercise.getId();\n if (repositoryExportOptions.isExportAllParticipants()) {\n log.info(\"Request to export all student or team repositories of programming exercise {} with title '{}'\", programmingExerciseId, programmingExercise.getTitle());\n }\n else {\n log.info(\"Request to export the repositories of programming exercise {} with title '{}' of the following students or teams: {}\", programmingExerciseId,\n programmingExercise.getTitle(), participations.stream().map(StudentParticipation::getParticipantIdentifier).collect(Collectors.joining(\", \")));\n }\n\n List<Path> zippedRepos = Collections.synchronizedList(new ArrayList<>());\n participations.parallelStream().forEach(participation -> {\n try {\n var zippedRepo = createZipForRepositoryWithParticipation(programmingExercise, participation, repositoryExportOptions);\n if (zippedRepo != null) {\n zippedRepos.add(zippedRepo);\n }\n }\n catch (IOException | GitAPIException | GitException | InterruptedException e) {\n var error = \"Failed to export the student repository with participation: \" + participation.getId() + \" for programming exercise '\" + programmingExercise.getTitle()\n + \"' (id: \" + programmingExercise.getId() + \") because the repository couldn't be downloaded. \";\n exportErrors.add(error);\n }\n });\n return zippedRepos;\n }\n\n /**\n * Creates a zip file with the contents of the git repository. Note that the zip file is deleted in 5 minutes.\n *\n * @param repositoryUrl The url of the repository to zip\n * @param zipFilename The name of the zip file\n * @return The path to the zip file.\n * @throws GitAPIException if the repos don't exist\n * @throws GitException if the repos don't exist\n * @throws InterruptedException something went wrong\n * @throws IOException something went wrong\n */\n private Path createZipForRepository(VcsRepositoryUrl repositoryUrl, String zipFilename) throws GitAPIException, GitException, InterruptedException, IOException {\n var repoProjectPath = fileService.getUniquePathString(repoDownloadClonePath);\n Repository repository = null;\n\n try {\n // Checkout the repository\n repository = gitService.getOrCheckoutRepository(repositoryUrl, repoProjectPath, true);\n gitService.resetToOriginMaster(repository);\n\n // Zip it\n Path zippedRepo = gitService.zipRepository(repository.getLocalPath(), zipFilename, repoProjectPath);\n\n // if repository is not closed, it causes weird IO issues when trying to delete the repository again\n // java.io.IOException: Unable to delete file: ...\\.git\\objects\\pack\\...\n repository.close();\n return zippedRepo;\n }\n finally {\n deleteTempLocalRepository(repository);\n fileService.scheduleForDirectoryDeletion(Path.of(repoProjectPath), 5);\n }\n }\n\n /**\n * Creates one single zip archive containing all zipped repositories found under the given paths\n *\n * @param programmingExercise The programming exercise to which all repos belong to\n * @param pathsToZippedRepos The paths to all zipped repositories\n * @return the zip file\n */\n private File createZipWithAllRepositories(ProgrammingExercise programmingExercise, List<Path> pathsToZippedRepos) {\n if (pathsToZippedRepos.isEmpty()) {\n log.warn(\"The zip file could not be created. Ignoring the request to export repositories for exercise {}\", programmingExercise.getTitle());\n return null;\n }\n\n try {\n log.debug(\"Create zip file for {} repositorie(s) of programming exercise: {}\", pathsToZippedRepos.size(), programmingExercise.getTitle());\n\n String filename = programmingExercise.getCourseViaExerciseGroupOrCourseMember().getShortName() + \"-\" + programmingExercise.getShortName() + \"-\"\n + System.currentTimeMillis() + \".zip\";\n Path zipFilePath = Paths.get(pathsToZippedRepos.get(0).getParent().toString(), filename);\n zipFileService.createZipFile(zipFilePath, pathsToZippedRepos, false);\n fileService.scheduleForDeletion(zipFilePath, 5);\n return new File(zipFilePath.toString());\n }\n catch (IOException ex) {\n log.error(\"Creating zip file for programming exercise {} did not work correctly: {} \", programmingExercise.getTitle(), ex.getMessage());\n return null;\n }\n finally {\n // we do some cleanup here to prevent future errors with file handling\n deleteTempZipRepoFiles(pathsToZippedRepos);\n }\n }\n\n /**\n * Checks out the repository for the given participation, zips it and adds the path to the given list of already\n * zipped repos.\n *\n * @param programmingExercise The programming exercise for the participation\n * @param participation The participation, for which the repository should get zipped\n * @param repositoryExportOptions The options, that should get applied to the zipeed repo\n * @return The checked out and zipped repository\n */\n private Path createZipForRepositoryWithParticipation(final ProgrammingExercise programmingExercise, final ProgrammingExerciseStudentParticipation participation,\n final RepositoryExportOptionsDTO repositoryExportOptions) throws IOException, GitAPIException, InterruptedException {\n if (participation.getVcsRepositoryUrl() == null) {\n log.warn(\"Ignore participation {} for export, because its repository URL is null\", participation.getId());\n return null;\n }\n final var targetPath = fileService.getUniquePathString(repoDownloadClonePath);\n Repository repository = null;\n try {\n // Checkout the repository\n repository = gitService.getOrCheckoutRepository(participation, targetPath);\n gitService.resetToOriginMaster(repository);\n\n if (repositoryExportOptions.isFilterLateSubmissions() && repositoryExportOptions.getFilterLateSubmissionsDate() != null) {\n filterLateSubmissions(repositoryExportOptions.getFilterLateSubmissionsDate(), participation, repository);\n }\n\n if (repositoryExportOptions.isAddParticipantName()) {\n log.debug(\"Adding student or team name to participation {}\", participation.toString());\n addParticipantIdentifierToProjectName(repository, programmingExercise, participation);\n }\n\n if (repositoryExportOptions.isCombineStudentCommits()) {\n log.debug(\"Combining commits for participation {}\", participation.toString());\n gitService.combineAllStudentCommits(repository, programmingExercise);\n }\n\n if (repositoryExportOptions.isNormalizeCodeStyle()) {\n try {\n log.debug(\"Normalizing code style for participation {}\", participation.toString());\n fileService.normalizeLineEndingsDirectory(repository.getLocalPath().toString());\n fileService.convertToUTF8Directory(repository.getLocalPath().toString());\n }\n catch (Exception ex) {\n log.warn(\"Cannot normalize code style in the repository {} due to the following exception: {}\", repository.getLocalPath(), ex.getMessage());\n }\n }\n\n log.debug(\"Create temporary zip file for repository {}\", repository.getLocalPath().toString());\n Path zippedRepoFile = gitService.zipRepositoryWithParticipation(repository, targetPath, repositoryExportOptions.isHideStudentNameInZippedFolder());\n\n // if repository is not closed, it causes weird IO issues when trying to delete the repository again\n // java.io.IOException: Unable to delete file: ...\\.git\\objects\\pack\\...\n repository.close();\n\n return zippedRepoFile;\n }\n finally {\n deleteTempLocalRepository(repository);\n fileService.scheduleForDirectoryDeletion(Path.of(targetPath), 5);\n }\n }\n\n /**\n * Delete all temporary zipped repositories created during export\n *\n * @param pathsToZipeedRepos A list of all paths to the zip files, that should be deleted\n */\n private void deleteTempZipRepoFiles(List<Path> pathsToZipeedRepos) {\n log.debug(\"Delete all temporary zip repo files\");\n // delete the temporary zipped repo files\n for (Path zippedRepoFile : pathsToZipeedRepos) {\n try {\n Files.delete(zippedRepoFile);\n }\n catch (Exception ex) {\n log.warn(\"Could not delete file {}. Error message: {}\", zippedRepoFile, ex.getMessage());\n }\n }\n }\n\n /**\n * downloads all repos of the exercise and runs JPlag\n *\n * @param programmingExerciseId the id of the programming exercises which should be checked\n * @param similarityThreshold ignore comparisons whose similarity is below this threshold (%)\n * @param minimumScore consider only submissions whose score is greater or equal to this value\n * @return a zip file that can be returned to the client\n * @throws ExitException is thrown if JPlag exits unexpectedly\n * @throws IOException is thrown for file handling errors\n */\n public TextPlagiarismResult checkPlagiarism(long programmingExerciseId, float similarityThreshold, int minimumScore) throws ExitException, IOException {\n long start = System.nanoTime();\n\n final var programmingExercise = programmingExerciseRepository.findWithAllParticipationsById(programmingExerciseId).get();\n\n final var numberOfParticipations = programmingExercise.getStudentParticipations().size();\n log.info(\"Download repositories for JPlag programming comparison with {} participations\", numberOfParticipations);\n\n final var targetPath = fileService.getUniquePathString(repoDownloadClonePath);\n List<ProgrammingExerciseParticipation> participations = studentParticipationsForComparison(programmingExercise, minimumScore);\n\n if (participations.size() < 2) {\n log.info(\"Insufficient amount of submissions for plagiarism detection. Return empty result.\");\n TextPlagiarismResult textPlagiarismResult = new TextPlagiarismResult();\n textPlagiarismResult.setExercise(programmingExercise);\n textPlagiarismResult.setSimilarityDistribution(new int[0]);\n\n return textPlagiarismResult;\n }\n\n List<Repository> repositories = downloadRepositories(programmingExercise, participations, targetPath);\n log.info(\"Downloading repositories done\");\n\n final var projectKey = programmingExercise.getProjectKey();\n final var repoFolder = Paths.get(targetPath, projectKey).toString();\n final LanguageOption programmingLanguage = getJPlagProgrammingLanguage(programmingExercise);\n\n final var templateRepoName = urlService.getRepositorySlugFromRepositoryUrl(programmingExercise.getTemplateParticipation().getVcsRepositoryUrl());\n\n JPlagOptions options = new JPlagOptions(repoFolder, programmingLanguage);\n if (templateRepoName != null) {\n options.setBaseCodeSubmissionName(templateRepoName);\n }\n\n // Important: for large courses with more than 1000 students, we might get more than one million results and 10 million files in the file system due to many 0% results,\n // therefore we limit the results to at least 50% or 0.5 similarity, the passed threshold is between 0 and 100%\n options.setSimilarityThreshold(similarityThreshold);\n\n log.info(\"Start JPlag programming comparison\");\n\n JPlag jplag = new JPlag(options);\n JPlagResult result = jplag.run();\n\n log.info(\"JPlag programming comparison finished with {} comparisons\", result.getComparisons().size());\n\n cleanupResourcesAsync(programmingExercise, repositories, targetPath);\n\n TextPlagiarismResult textPlagiarismResult = new TextPlagiarismResult(result);\n textPlagiarismResult.setExercise(programmingExercise);\n\n log.info(\"JPlag programming comparison for {} participations done in {}\", numberOfParticipations, TimeLogUtil.formatDurationFrom(start));\n\n return textPlagiarismResult;\n }\n\n /**\n * downloads all repos of the exercise and runs JPlag\n *\n * @param programmingExerciseId the id of the programming exercises which should be checked\n * @param similarityThreshold ignore comparisons whose similarity is below this threshold (%)\n * @param minimumScore consider only submissions whose score is greater or equal to this value\n * @return a zip file that can be returned to the client\n * @throws ExitException is thrown if JPlag exits unexpectedly\n * @throws IOException is thrown for file handling errors\n */\n public File checkPlagiarismWithJPlagReport(long programmingExerciseId, float similarityThreshold, int minimumScore) throws ExitException, IOException {\n long start = System.nanoTime();\n\n final var programmingExercise = programmingExerciseRepository.findWithAllParticipationsById(programmingExerciseId).get();\n final var numberOfParticipations = programmingExercise.getStudentParticipations().size();\n\n log.info(\"Download repositories for JPlag programming comparison with {} participations\", numberOfParticipations);\n final var targetPath = fileService.getUniquePathString(repoDownloadClonePath);\n List<ProgrammingExerciseParticipation> participations = studentParticipationsForComparison(programmingExercise, minimumScore);\n\n if (participations.size() < 2) {\n log.info(\"Insufficient amount of submissions for plagiarism detection. Return empty result.\");\n return null;\n }\n\n List<Repository> repositories = downloadRepositories(programmingExercise, participations, targetPath);\n log.info(\"Downloading repositories done\");\n\n final var output = \"output\";\n final var projectKey = programmingExercise.getProjectKey();\n final var outputFolder = Paths.get(targetPath, projectKey + \"-\" + output).toString();\n final var outputFolderFile = new File(outputFolder);\n\n outputFolderFile.mkdirs();\n\n final var repoFolder = Paths.get(targetPath, projectKey).toString();\n final LanguageOption programmingLanguage = getJPlagProgrammingLanguage(programmingExercise);\n\n final var templateRepoName = urlService.getRepositorySlugFromRepositoryUrl(programmingExercise.getTemplateParticipation().getVcsRepositoryUrl());\n\n JPlagOptions options = new JPlagOptions(repoFolder, programmingLanguage);\n if (templateRepoName != null) {\n options.setBaseCodeSubmissionName(templateRepoName);\n }\n\n // Important: for large courses with more than 1000 students, we might get more than one million results and 10 million files in the file system due to many 0% results,\n // therefore we limit the results to at least 50% or 0.5 similarity, the passed threshold is between 0 and 100%\n options.setSimilarityThreshold(similarityThreshold);\n\n log.info(\"Start JPlag programming comparison\");\n JPlag jplag = new JPlag(options);\n JPlagResult result = jplag.run();\n log.info(\"JPlag programming comparison finished with {} comparisons\", result.getComparisons().size());\n\n log.info(\"Write JPlag report to file system\");\n Report jplagReport = new Report(outputFolderFile);\n jplagReport.writeResult(result);\n\n log.info(\"JPlag report done. Will zip it now\");\n\n final var zipFilePath = Paths.get(targetPath, programmingExercise.getCourseViaExerciseGroupOrCourseMember().getShortName() + \"-\" + programmingExercise.getShortName() + \"-\"\n + System.currentTimeMillis() + \"-Jplag-Analysis-Output.zip\");\n zipFileService.createZipFileWithFolderContent(zipFilePath, Paths.get(outputFolder));\n\n log.info(\"JPlag report zipped. Delete report output folder\");\n\n // cleanup\n if (outputFolderFile.exists()) {\n FileSystemUtils.deleteRecursively(outputFolderFile);\n }\n\n cleanupResourcesAsync(programmingExercise, repositories, targetPath);\n\n log.info(\"Schedule deletion of zip file in 1 minute\");\n fileService.scheduleForDeletion(zipFilePath, 1);\n\n log.info(\"JPlag programming report for {} participations done in {}\", numberOfParticipations, TimeLogUtil.formatDurationFrom(start));\n\n return new File(zipFilePath.toString());\n }\n\n private void cleanupResourcesAsync(final ProgrammingExercise programmingExercise, final List<Repository> repositories, final String targetPath) {\n executor.schedule(() -> {\n log.info(\"Will delete local repositories\");\n deleteLocalRepositories(repositories);\n // delete project root folder in the repos download folder\n deleteReposDownloadProjectRootDirectory(programmingExercise, targetPath);\n log.info(\"Delete repositories done\");\n }, 10, TimeUnit.SECONDS);\n }\n\n private LanguageOption getJPlagProgrammingLanguage(ProgrammingExercise programmingExercise) {\n return switch (programmingExercise.getProgrammingLanguage()) {\n case JAVA -> LanguageOption.JAVA_1_9;\n case C -> LanguageOption.C_CPP;\n case PYTHON -> LanguageOption.PYTHON_3;\n default -> throw new BadRequestAlertException(\"Programming language \" + programmingExercise.getProgrammingLanguage() + \" not supported for plagiarism check.\",\n \"ProgrammingExercise\", \"notSupported\");\n };\n }\n\n private void deleteLocalRepositories(List<Repository> repositories) {\n repositories.parallelStream().forEach(repository -> {\n var localPath = repository.getLocalPath();\n try {\n deleteTempLocalRepository(repository);\n }\n catch (GitException ex) {\n log.error(\"Delete repository {} did not work as expected: {}\", localPath, ex.getMessage());\n }\n });\n }\n\n private void deleteReposDownloadProjectRootDirectory(ProgrammingExercise programmingExercise, String targetPath) {\n final String projectDirName = programmingExercise.getProjectKey();\n Path projectPath = Paths.get(targetPath, projectDirName);\n try {\n log.info(\"Delete project root directory {}\", projectPath.toFile());\n FileUtils.deleteDirectory(projectPath.toFile());\n }\n catch (IOException ex) {\n log.warn(\"The project root directory '\" + projectPath.toString() + \"' could not be deleted.\", ex);\n }\n }\n\n private List<Repository> downloadRepositories(ProgrammingExercise programmingExercise, List<ProgrammingExerciseParticipation> participations, String targetPath) {\n List<Repository> downloadedRepositories = new ArrayList<>();\n\n participations.forEach(participation -> {\n try {\n Repository repo = gitService.getOrCheckoutRepositoryForJPlag(participation, targetPath);\n gitService.resetToOriginMaster(repo); // start with clean state\n downloadedRepositories.add(repo);\n }\n catch (GitException | GitAPIException | InterruptedException ex) {\n log.error(\"Clone student repository {} in exercise '{}' did not work as expected: {}\", participation.getVcsRepositoryUrl(), programmingExercise.getTitle(),\n ex.getMessage());\n }\n });\n\n // clone the template repo\n try {\n Repository templateRepo = gitService.getOrCheckoutRepository(programmingExercise.getTemplateParticipation(), targetPath);\n gitService.resetToOriginMaster(templateRepo); // start with clean state\n downloadedRepositories.add(templateRepo);\n }\n catch (GitException | GitAPIException | InterruptedException ex) {\n log.error(\"Clone template repository {} in exercise '{}' did not work as expected: {}\", programmingExercise.getTemplateParticipation().getVcsRepositoryUrl(),\n programmingExercise.getTitle(), ex.getMessage());\n }\n\n return downloadedRepositories;\n }\n\n /**\n * Find all studentParticipations of the given exercise for plagiarism comparison.\n *\n * @param programmingExercise ProgrammingExercise to fetcch the participations for\n * @param minimumScore consider only submissions whose score is greater or equal to this value\n * @return List containing the latest text submission for every participation\n */\n public List<ProgrammingExerciseParticipation> studentParticipationsForComparison(ProgrammingExercise programmingExercise, int minimumScore) {\n var studentParticipations = studentParticipationRepository.findAllWithEagerLegalSubmissionsAndEagerResultsByExerciseId(programmingExercise.getId());\n\n return studentParticipations.parallelStream().filter(participation -> participation instanceof ProgrammingExerciseParticipation)\n .map(participation -> (ProgrammingExerciseParticipation) participation).filter(participation -> participation.getVcsRepositoryUrl() != null)\n .filter(participation -> {\n Submission submission = ((StudentParticipation) participation).findLatestSubmission().orElse(null);\n return minimumScore == 0 || submission != null && submission.getLatestResult() != null && submission.getLatestResult().getScore() != null\n && submission.getLatestResult().getScore() >= minimumScore;\n }).collect(Collectors.toList());\n }\n\n /**\n * Deletes the locally checked out repository.\n *\n * @param repository The repository that should get deleted\n */\n private void deleteTempLocalRepository(Repository repository) {\n // we do some cleanup here to prevent future errors with file handling\n // We can always delete the repository as it won't be used by the student (separate path)\n if (repository != null) {\n try {\n gitService.deleteLocalRepository(repository);\n }\n catch (Exception ex) {\n log.warn(\"Could not delete temporary repository {}: {}\", repository.getLocalPath().toString(), ex.getMessage());\n }\n }\n else {\n log.error(\"Cannot delete temp local repository because the passed repository is null\");\n }\n }\n\n /**\n * Filters out all late commits of submissions from the checked out repository of a participation\n *\n * @param submissionDate The submission date (inclusive), after which all submissions should get filtered out\n * @param participation The participation related to the repository\n * @param repo The repository for which to filter all late submissions\n */\n private void filterLateSubmissions(ZonedDateTime submissionDate, ProgrammingExerciseStudentParticipation participation, Repository repo) {\n log.debug(\"Filter late submissions for participation {}\", participation.toString());\n Optional<Submission> lastValidSubmission = participation.getSubmissions().stream()\n .filter(s -> s.getSubmissionDate() != null && s.getSubmissionDate().isBefore(submissionDate)).max(Comparator.comparing(Submission::getSubmissionDate));\n\n gitService.filterLateSubmissions(repo, lastValidSubmission, submissionDate);\n }\n\n /**\n * Adds the participant identifier (student login or team short name) of the given student participation to the project name in all .project (Eclipse)\n * and pom.xml (Maven) files found in the given repository.\n *\n * @param repository The repository for which the student id should get added\n * @param programmingExercise The checked out exercise in the repository\n * @param participation The student participation for the student/team identifier, which should be added.\n */\n public void addParticipantIdentifierToProjectName(Repository repository, ProgrammingExercise programmingExercise, StudentParticipation participation) {\n String participantIdentifier = participation.getParticipantIdentifier();\n\n // Get all files in repository expect .git files\n List<String> allRepoFiles = listAllFilesInPath(repository.getLocalPath());\n\n // is Java or Kotlin programming language\n if (programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.JAVA || programmingExercise.getProgrammingLanguage() == ProgrammingLanguage.KOTLIN) {\n // Filter all Eclipse .project files\n List<String> eclipseProjectFiles = allRepoFiles.stream().filter(file -> file.endsWith(\".project\")).collect(Collectors.toList());\n\n for (String eclipseProjectFilePath : eclipseProjectFiles) {\n addParticipantIdentifierToEclipseProjectName(repository, participantIdentifier, eclipseProjectFilePath);\n }\n\n // Filter all pom.xml files\n List<String> pomFiles = allRepoFiles.stream().filter(file -> file.endsWith(\"pom.xml\")).collect(Collectors.toList());\n for (String pomFilePath : pomFiles) {\n addParticipantIdentifierToMavenProjectName(repository, participantIdentifier, pomFilePath);\n }\n }\n\n try {\n gitService.stageAllChanges(repository);\n gitService.commit(repository, \"Add participant identifier (student login or team short name) to project name\");\n // if repo is not closed, it causes weird IO issues when trying to delete the repo again\n // java.io.IOException: Unable to delete file: ...\\.git\\objects\\pack\\...\n repository.close();\n }\n catch (GitAPIException ex) {\n log.error(\"Cannot stage or commit to the repository \" + repository.getLocalPath(), ex);\n }\n }\n\n private void addParticipantIdentifierToMavenProjectName(Repository repo, String participantIdentifier, String pomFilePath) {\n File pomFile = new File(pomFilePath);\n // check if file exists and full file name is pom.xml and not just the file ending.\n if (!pomFile.exists() || !pomFile.getName().equals(\"pom.xml\")) {\n return;\n }\n\n try {\n // 1- Build the doc from the XML file\n Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(pomFile.getPath()));\n doc.setXmlStandalone(true);\n\n // 2- Find the relevant nodes with xpath\n XPath xPath = XPathFactory.newInstance().newXPath();\n Node nameNode = (Node) xPath.compile(\"/project/name\").evaluate(doc, XPathConstants.NODE);\n Node artifactIdNode = (Node) xPath.compile(\"/project/artifactId\").evaluate(doc, XPathConstants.NODE);\n\n // 3- Append Participant Identifier (student login or team short name) to Project Names\n if (nameNode != null) {\n nameNode.setTextContent(nameNode.getTextContent() + \" \" + participantIdentifier);\n }\n if (artifactIdNode != null) {\n String artifactId = (artifactIdNode.getTextContent() + \"-\" + participantIdentifier).replaceAll(\" \", \"-\").toLowerCase();\n artifactIdNode.setTextContent(artifactId);\n }\n\n // 4- Save the result to a new XML doc\n Transformer xformer = TransformerFactory.newInstance().newTransformer();\n xformer.transform(new DOMSource(doc), new StreamResult(new File(pomFile.getPath())));\n\n }\n catch (SAXException | IOException | ParserConfigurationException | TransformerException | XPathException ex) {\n log.error(\"Cannot rename pom.xml file in \" + repo.getLocalPath(), ex);\n }\n }\n\n private void addParticipantIdentifierToEclipseProjectName(Repository repo, String participantIdentifier, String eclipseProjectFilePath) {\n File eclipseProjectFile = new File(eclipseProjectFilePath);\n // Check if file exists and full file name is .project and not just the file ending.\n if (!eclipseProjectFile.exists() || !eclipseProjectFile.getName().equals(\".project\")) {\n return;\n }\n\n try {\n // 1- Build the doc from the XML file\n Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(eclipseProjectFile.getPath()));\n doc.setXmlStandalone(true);\n\n // 2- Find the node with xpath\n XPath xPath = XPathFactory.newInstance().newXPath();\n Node nameNode = (Node) xPath.compile(\"/projectDescription/name\").evaluate(doc, XPathConstants.NODE);\n\n // 3- Append Participant Identifier (student login or team short name) to Project Name\n if (nameNode != null) {\n nameNode.setTextContent(nameNode.getTextContent() + \" \" + participantIdentifier);\n }\n\n // 4- Save the result to a new XML doc\n Transformer xformer = TransformerFactory.newInstance().newTransformer();\n xformer.transform(new DOMSource(doc), new StreamResult(new File(eclipseProjectFile.getPath())));\n\n }\n catch (SAXException | IOException | ParserConfigurationException | TransformerException | XPathException ex) {\n log.error(\"Cannot rename .project file in \" + repo.getLocalPath(), ex);\n }\n }\n\n /**\n * Get all files in path except .git files\n *\n * @param path The path for which all file names should be listed\n * @return A list of all file names under the given path\n */\n private List<String> listAllFilesInPath(Path path) {\n List<String> allRepoFiles = null;\n try (Stream<Path> walk = Files.walk(path)) {\n allRepoFiles = walk.filter(Files::isRegularFile).map(Path::toString).filter(s -> !s.contains(\".git\")).collect(Collectors.toList());\n }\n catch (IOException e) {\n e.printStackTrace();\n }\n return allRepoFiles;\n }\n}\n" }, { "alpha_fraction": 0.6332347989082336, "alphanum_fraction": 0.6338682174682617, "avg_line_length": 39.478633880615234, "blob_id": "a079054df97ff9fd451afcd8f12bf2ca4a16b4f7", "content_id": "69754b7e4a3b8a98fb5487f1c5205107a9a71b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4736, "license_type": "permissive", "max_line_length": 122, "num_lines": 117, "path": "/src/main/webapp/app/exercises/shared/submission/submission.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport * as moment from 'moment';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { Result } from 'app/entities/result.model';\nimport { getLatestSubmissionResult, setLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nimport { filter, map, tap } from 'rxjs/operators';\nimport { TextSubmission } from 'app/entities/text-submission.model';\n\nexport type EntityResponseType = HttpResponse<Submission>;\nexport type EntityArrayResponseType = HttpResponse<Submission[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class SubmissionService {\n public resourceUrl = SERVER_API_URL + 'api/submissions';\n public resourceUrlParticipation = SERVER_API_URL + 'api/participations';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Delete an existing submission\n * @param submissionId - The id of the submission to be deleted\n * @param req - A request with additional options in it\n */\n delete(submissionId: number, req?: any): Observable<HttpResponse<any>> {\n const options = createRequestOption(req);\n return this.http.delete<void>(`${this.resourceUrl}/${submissionId}`, { params: options, observe: 'response' });\n }\n\n /**\n * Find all submissions of a given participation\n * @param {number} participationId - The id of the participation to be searched for\n */\n findAllSubmissionsOfParticipation(participationId: number): Observable<EntityArrayResponseType> {\n return this.http\n .get<Submission[]>(`${this.resourceUrlParticipation}/${participationId}/submissions`, { observe: 'response' })\n .pipe(\n map((res) => this.convertDateArrayFromServer(res)),\n filter((res) => !!res.body),\n tap((res) =>\n res.body!.forEach((submission) => {\n this.reconnectSubmissionAndResult(submission);\n }),\n ),\n );\n }\n\n /**\n * reconnect submission and result\n * @param submission\n */\n private reconnectSubmissionAndResult(submission: Submission) {\n const result = getLatestSubmissionResult(submission);\n if (result) {\n setLatestSubmissionResult(submission, result);\n result.submission = submission;\n }\n }\n\n convertResultsDateFromServer(results?: Result[]) {\n const convertedResults: Result[] = [];\n if (results != undefined && results.length > 0) {\n results.forEach((result: Result) => {\n result.completionDate = result.completionDate ? moment(result.completionDate) : undefined;\n convertedResults.push(result);\n });\n }\n return convertedResults;\n }\n\n convertSubmissionsDateFromServer(submissions?: Submission[]) {\n const convertedSubmissions: Submission[] = [];\n if (submissions != undefined && submissions.length > 0) {\n submissions.forEach((submission: Submission) => {\n if (submission !== null) {\n submission.submissionDate = submission.submissionDate ? moment(submission.submissionDate) : undefined;\n this.reconnectSubmissionAndResult(submission);\n convertedSubmissions.push(submission);\n }\n });\n }\n return convertedSubmissions;\n }\n\n protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n this.convertSubmissionsDateFromServer(res.body);\n }\n return res;\n }\n\n getTestRunSubmissionsForExercise(exerciseId: number): Observable<HttpResponse<Submission[]>> {\n return this.http\n .get<TextSubmission[]>(`api/exercises/${exerciseId}/test-run-submissions`, {\n observe: 'response',\n })\n .pipe(map((res: HttpResponse<TextSubmission[]>) => this.convertArrayResponse(res)));\n }\n\n private convertArrayResponse(res: HttpResponse<Submission[]>): HttpResponse<Submission[]> {\n const jsonResponse: Submission[] = res.body!;\n const body: Submission[] = [];\n for (let i = 0; i < jsonResponse.length; i++) {\n body.push(this.convertItemFromServer(jsonResponse[i]));\n }\n return res.clone({ body });\n }\n\n /**\n * Convert a returned JSON object to TextSubmission.\n */\n private convertItemFromServer(submission: Submission): Submission {\n return Object.assign({}, submission);\n }\n}\n" }, { "alpha_fraction": 0.6234392523765564, "alphanum_fraction": 0.6256363391876221, "avg_line_length": 44.07487869262695, "blob_id": "1c4cc4b290e3e2f1809ee72a1fbaa7861331b54c", "content_id": "95df34ed0d2cbcb2ba996bfeee7f207c07997d7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 18661, "license_type": "permissive", "max_line_length": 175, "num_lines": 414, "path": "/src/test/javascript/spec/component/course/course-management.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport { Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { CourseManagementOverviewStatisticsDto } from 'app/course/manage/overview/course-management-overview-statistics-dto.model';\nimport { Course, CourseGroup } from 'app/entities/course.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\nimport { Organization } from 'app/entities/organization.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport * as chai from 'chai';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { take } from 'rxjs/operators';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Course Management Service', () => {\n let injector: TestBed;\n let service: CourseManagementService;\n let accountService: AccountService;\n let exerciseService: ExerciseService;\n let lectureService: LectureService;\n let httpMock: HttpTestingController;\n let isAtLeastTutorInCourseStub: sinon.SinonStub;\n let isAtLeastInstructorInCourseStub: sinon.SinonStub;\n let convertExercisesDateFromServerStub: sinon.SinonStub;\n let convertDatesForLecturesFromServerStub: sinon.SinonStub;\n let syncGroupsStub: sinon.SinonStub;\n const resourceUrl = SERVER_API_URL + 'api/courses';\n let course: Course;\n let exercises: Exercise[];\n let returnedFromService: any;\n let participations: StudentParticipation[];\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n providers: [\n { provide: Router, useClass: MockRouter },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n });\n injector = getTestBed();\n service = injector.get(CourseManagementService);\n httpMock = injector.get(HttpTestingController);\n accountService = injector.get(AccountService);\n exerciseService = injector.get(ExerciseService);\n lectureService = injector.get(LectureService);\n\n isAtLeastTutorInCourseStub = sinon.stub(accountService, 'isAtLeastTutorInCourse');\n isAtLeastInstructorInCourseStub = sinon.stub(accountService, 'isAtLeastInstructorInCourse');\n syncGroupsStub = sinon.stub(accountService, 'syncGroups');\n convertExercisesDateFromServerStub = sinon.stub(exerciseService, 'convertExercisesDateFromServer');\n convertDatesForLecturesFromServerStub = sinon.stub(lectureService, 'convertDatesForLecturesFromServer');\n course = new Course();\n course.id = 1234;\n course.title = 'testTitle';\n exercises = [new ModelingExercise(UMLDiagramType.ComponentDiagram, undefined, undefined), new ModelingExercise(UMLDiagramType.ComponentDiagram, undefined, undefined)];\n course.exercises = exercises;\n returnedFromService = { ...course };\n participations = [new StudentParticipation()];\n });\n\n const expectDateConversionToBeCalled = (courseForConversion: Course) => {\n expect(convertExercisesDateFromServerStub).to.have.been.calledWith(courseForConversion.exercises);\n expect(convertDatesForLecturesFromServerStub).to.have.been.calledWith(courseForConversion.lectures);\n };\n\n const expectAccessRightsToBeCalled = () => {\n expect(isAtLeastTutorInCourseStub).to.have.been.called;\n expect(isAtLeastInstructorInCourseStub).to.have.been.called;\n };\n\n const requestAndExpectDateConversion = (method: string, url: string, flushedObject: any = returnedFromService, courseToCheck: Course, checkAccessRights?: boolean) => {\n const req = httpMock.expectOne({ method, url });\n req.flush(flushedObject);\n expectDateConversionToBeCalled(courseToCheck);\n if (checkAccessRights) {\n expectAccessRightsToBeCalled();\n }\n };\n\n it('should create course', async () => {\n delete course.id;\n service\n .create({ ...course })\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n\n const req = httpMock.expectOne({ method: 'POST', url: resourceUrl });\n req.flush(returnedFromService);\n });\n\n it('should update course', async () => {\n service\n .update({ ...course })\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n\n const req = httpMock.expectOne({ method: 'PUT', url: resourceUrl });\n req.flush(returnedFromService);\n });\n\n it('should find the course', async () => {\n service\n .find(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}`, returnedFromService, course);\n });\n\n it('should get title of the course', async () => {\n returnedFromService = course.title!;\n service\n .getTitle(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course.title));\n\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/title` });\n req.flush(returnedFromService);\n });\n\n it('should find course with exercises', async () => {\n service\n .findWithExercises(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}/with-exercises`, returnedFromService, course);\n });\n\n it('should find course with exercises and participations', async () => {\n service\n .findWithExercisesAndParticipations(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}/with-exercises-and-relevant-participations`, returnedFromService, course);\n });\n\n it('should find course with organizations', async () => {\n course.organizations = [new Organization()];\n returnedFromService = { ...course };\n service\n .findWithOrganizations(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}/with-organizations`, returnedFromService, course);\n });\n\n it('should find all courses for dashboard', async () => {\n returnedFromService = [{ ...course }];\n service\n .findAllForDashboard()\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}/for-dashboard`, returnedFromService, course);\n });\n\n it('should find one course for dashboard', async () => {\n service\n .getCourseUpdates(course.id!)\n .pipe(take(1))\n .subscribe((updatedCourse) => {\n expect(updatedCourse).to.eq(course);\n });\n service\n .findOneForDashboard(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}/for-dashboard`, returnedFromService, course, true);\n });\n\n it('should find participations for the course', async () => {\n returnedFromService = [...participations];\n service\n .findAllParticipationsWithResults(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res).to.eq(participations));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/participations` });\n req.flush(returnedFromService);\n });\n\n it('should find reults for the course', async () => {\n service.findAllResultsOfCourseForExerciseAndCurrentUser(course.id!).subscribe((res) => expect(res).to.eq(course));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/results` });\n req.flush(returnedFromService);\n });\n\n it('should find all courses to register', async () => {\n returnedFromService = [{ ...course }];\n service\n .findAllToRegister()\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}/to-register`, returnedFromService, course);\n });\n\n it('should find course with interesting exercises', async () => {\n service\n .getCourseWithInterestingExercisesForTutors(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(course));\n requestAndExpectDateConversion('GET', `${resourceUrl}/${course.id}/for-assessment-dashboard`, returnedFromService, course);\n });\n\n it('should get stats of course', async () => {\n const stats = new StatsForDashboard();\n returnedFromService = { ...stats };\n service\n .getStatsForTutors(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(stats));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/stats-for-assessment-dashboard` });\n req.flush(returnedFromService);\n });\n\n it('should register for the course', async () => {\n const user = new User(1, 'name');\n service\n .registerForCourse(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(user));\n const req = httpMock.expectOne({ method: 'POST', url: `${resourceUrl}/${course.id}/register` });\n req.flush(user);\n expect(syncGroupsStub).to.have.been.calledWith(user);\n });\n\n it('should get all courses', async () => {\n returnedFromService = [{ ...course }];\n const params = { testParam: 'testParamValue' };\n service\n .getAll(params)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}?testParam=testParamValue`, returnedFromService, course, true);\n });\n\n it('should get all courses with quiz exercises', async () => {\n service.getCoursesForNotifications().subscribe((updatedCourse) => {\n expect(updatedCourse).to.eq(course);\n });\n returnedFromService = [{ ...course }];\n service\n .getAllCoursesWithQuizExercises()\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}/courses-with-quiz`, returnedFromService, course, true);\n });\n\n it('should get all courses together with user stats', async () => {\n service\n .getCoursesForNotifications()\n .pipe(take(1))\n .subscribe((updatedCourse) => {\n expect(updatedCourse).to.eq(course);\n });\n const params = { testParam: 'testParamValue' };\n returnedFromService = [{ ...course }];\n service\n .getWithUserStats(params)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}/with-user-stats?testParam=testParamValue`, returnedFromService, course, true);\n });\n\n it('should get all courses for overview', async () => {\n service.getCoursesForNotifications().subscribe((updatedCourse) => {\n expect(updatedCourse).to.eq(course);\n });\n const params = { testParam: 'testParamValue' };\n returnedFromService = [{ ...course }];\n service\n .getCourseOverview(params)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/course-management-overview?testParam=testParamValue` });\n req.flush(returnedFromService);\n expectAccessRightsToBeCalled();\n });\n\n it('should delete a course ', async () => {\n service\n .delete(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.not.exist);\n const req = httpMock.expectOne({ method: 'DELETE', url: `${resourceUrl}/${course.id}` });\n req.flush({});\n });\n\n it('should get stats of instructor', async () => {\n const stats = new StatsForDashboard();\n returnedFromService = { ...stats };\n service\n .getStatsForInstructors(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(stats));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/stats-for-instructor-dashboard` });\n req.flush(returnedFromService);\n });\n\n it('should get all exercise details ', async () => {\n returnedFromService = [{ ...course }];\n service\n .getExercisesForManagementOverview(true)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([course]));\n requestAndExpectDateConversion('GET', `${resourceUrl}/exercises-for-management-overview?onlyActive=true`, returnedFromService, course);\n });\n\n it('should get all stats for overview', async () => {\n const stats = [new CourseManagementOverviewStatisticsDto()];\n returnedFromService = [...stats];\n service\n .getStatsForManagementOverview(true)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq([stats]));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/stats-for-management-overview?onlyActive=true` });\n req.flush(returnedFromService);\n });\n\n it('should find all categories of course', async () => {\n const categories = ['category1', 'category2'];\n returnedFromService = [...categories];\n service\n .findAllCategoriesOfCourse(course.id!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(categories));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/categories` });\n req.flush(returnedFromService);\n });\n\n it('should find all users of course group', async () => {\n const users = [new User(1, 'user1'), new User(2, 'user2')];\n returnedFromService = [...users];\n const courseGroup = CourseGroup.STUDENTS;\n service\n .getAllUsersInCourseGroup(course.id!, courseGroup)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.eq(users));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/${courseGroup}` });\n req.flush(returnedFromService);\n });\n\n it('should find all users of course group', async () => {\n const expectedBlob = new Blob(['abc', 'cfe']);\n service.downloadCourseArchive(course.id!).subscribe((resp) => {\n expect(resp.body).to.equal(expectedBlob);\n });\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/download-archive` });\n req.flush(expectedBlob);\n });\n\n it('should archive the course', async () => {\n service.archiveCourse(course.id!).subscribe((res) => expect(res).to.eq(course));\n const req = httpMock.expectOne({ method: 'PUT', url: `${resourceUrl}/${course.id}/archive` });\n req.flush(returnedFromService);\n });\n\n it('should clean up the course', async () => {\n service.cleanupCourse(course.id!).subscribe((res) => expect(res).to.eq(course));\n const req = httpMock.expectOne({ method: 'DELETE', url: `${resourceUrl}/${course.id}/cleanup` });\n req.flush(returnedFromService);\n });\n\n it('should find all locked submissions of course', () => {\n const submission = new ModelingSubmission();\n const submissions = [submission];\n returnedFromService = [...submissions];\n service.findAllLockedSubmissionsOfCourse(course.id!).subscribe((res) => expect(res).to.eq(course));\n const req = httpMock.expectOne({ method: 'GET', url: `${resourceUrl}/${course.id}/lockedSubmissions` });\n req.flush(returnedFromService);\n });\n\n it('should add user to course group', () => {\n const user = new User(1, 'name');\n const courseGroup = CourseGroup.STUDENTS;\n service\n .addUserToCourseGroup(course.id!, courseGroup, user.login!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.not.exist);\n const req = httpMock.expectOne({ method: 'POST', url: `${resourceUrl}/${course.id}/${courseGroup}/${user.login}` });\n req.flush({});\n });\n\n it('should remove user from course group', () => {\n const user = new User(1, 'name');\n const courseGroup = CourseGroup.STUDENTS;\n service\n .removeUserFromCourseGroup(course.id!, courseGroup, user.login!)\n .pipe(take(1))\n .subscribe((res) => expect(res.body).to.not.exist);\n const req = httpMock.expectOne({ method: 'DELETE', url: `${resourceUrl}/${course.id}/${courseGroup}/${user.login}` });\n req.flush({});\n });\n\n afterEach(() => {\n httpMock.verify();\n sinon.restore();\n });\n});\n" }, { "alpha_fraction": 0.8063725233078003, "alphanum_fraction": 0.811274528503418, "avg_line_length": 26.200000762939453, "blob_id": "7b101f713249ba071c655968101026bb65d2b98d", "content_id": "f795292a6f9ec12d528376a9a5e52ddd5002a3f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 408, "license_type": "permissive", "max_line_length": 81, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/StatisticRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.QuizStatistic;\n\n/**\n * Spring Data JPA repository for the QuizStatistic entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface StatisticRepository extends JpaRepository<QuizStatistic, Long> {\n\n}\n" }, { "alpha_fraction": 0.7758921980857849, "alphanum_fraction": 0.7761417627334595, "avg_line_length": 55.43661880493164, "blob_id": "7409cd25d9914b0cb0e99a20a55b1614b34fa24c", "content_id": "47104294c393e2e8a12dc59c6b100e3b711ed517", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4007, "license_type": "permissive", "max_line_length": 156, "num_lines": 71, "path": "/src/main/webapp/app/overview/courses.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ChartsModule } from 'ng2-charts';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { MomentModule } from 'ngx-moment';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSidePanelModule } from 'app/shared/side-panel/side-panel.module';\nimport { CourseLectureRowComponent } from 'app/overview/course-lectures/course-lecture-row.component';\nimport { OrionModule } from 'app/shared/orion/orion.module';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { ProgrammingExerciseUtilsModule } from 'app/exercises/programming/shared/utils/programming-exercise-utils.module';\nimport { CourseCardComponent } from 'app/overview/course-card.component';\nimport { CourseStatisticsComponent } from 'app/overview/course-statistics/course-statistics.component';\nimport { CourseOverviewComponent } from 'app/overview/course-overview.component';\nimport { CourseExercisesComponent } from 'app/overview/course-exercises/course-exercises.component';\nimport { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared/exercise-headers/exercise-headers.module';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { CoursesComponent } from 'app/overview/courses.component';\nimport { ArtemisComplaintsModule } from 'app/complaints/complaints.module';\nimport { CourseLecturesComponent } from 'app/overview/course-lectures/course-lectures.component';\nimport { CourseRegistrationSelectorComponent } from 'app/overview/course-registration-selector/course-registration-selector.component';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ArtemisCoursesRoutingModule } from 'app/overview/courses-routing.module';\nimport { ArtemisTeamModule } from 'app/exercises/shared/team/team.module';\nimport { CourseExamsComponent } from 'app/overview/course-exams/course-exams.component';\nimport { CourseExamDetailComponent } from 'app/overview/course-exams/course-exam-detail/course-exam-detail.component';\nimport { ArtemisSharedPipesModule } from 'app/shared/pipes/shared-pipes.module';\nimport { RatingModule } from 'app/exercises/shared/rating/rating.module';\nimport { CourseLearningGoalsComponent } from './course-learning-goals/course-learning-goals.component';\nimport { ArtemisLearningGoalsModule } from 'app/course/learning-goals/learning-goal.module';\nimport { ArtemisExerciseButtonsModule } from 'app/overview/exercise-details/exercise-buttons.module';\nimport { ArtemisCourseExerciseRowModule } from 'app/overview/course-exercises/course-exercise-row.module';\nimport { CourseExerciseDetailsModule } from 'app/overview/exercise-details/course-exercise-details.module';\n\n@NgModule({\n imports: [\n ArtemisExerciseButtonsModule,\n ArtemisCourseExerciseRowModule,\n ArtemisSharedModule,\n ArtemisSharedComponentModule,\n ChartsModule,\n ClipboardModule,\n MomentModule,\n ArtemisSharedPipesModule,\n ArtemisResultModule,\n ArtemisSidePanelModule,\n ArtemisCoursesRoutingModule,\n ArtemisHeaderExercisePageWithDetailsModule,\n OrionModule,\n ArtemisComplaintsModule,\n FeatureToggleModule,\n ProgrammingExerciseUtilsModule,\n ArtemisTeamModule,\n RatingModule,\n ArtemisLearningGoalsModule,\n CourseExerciseDetailsModule, // Important: at the moment, we cannot lazy load this module, because otherwise the LTI integration won't work any more\n ],\n declarations: [\n CoursesComponent,\n CourseOverviewComponent,\n CourseRegistrationSelectorComponent,\n CourseCardComponent,\n CourseStatisticsComponent,\n CourseExercisesComponent,\n CourseLecturesComponent,\n CourseLectureRowComponent,\n CourseExamsComponent,\n CourseExamDetailComponent,\n CourseLearningGoalsComponent,\n ],\n})\nexport class ArtemisCoursesModule {}\n" }, { "alpha_fraction": 0.7543859481811523, "alphanum_fraction": 0.7543859481811523, "avg_line_length": 21.799999237060547, "blob_id": "65768c23e86ed5971b3c8cd8529501673649c21b", "content_id": "a8a4dbdc85f738daa758e9e6b623c377c52306ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 114, "license_type": "permissive", "max_line_length": 43, "num_lines": 5, "path": "/src/main/webapp/app/entities/exam-information.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\n\nexport class ExamInformationDTO {\n public latestIndividualEndDate: Moment;\n}\n" }, { "alpha_fraction": 0.6519965529441833, "alphanum_fraction": 0.6526406407356262, "avg_line_length": 44.22330093383789, "blob_id": "0185635d52ee9568fffe4db8ebdef85243e485ae", "content_id": "66418b55939d9160c6d3720e6e2481bf232ae440", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4658, "license_type": "permissive", "max_line_length": 98, "num_lines": 103, "path": "/src/test/javascript/spec/component/team/teams.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as ace from 'brace';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { By } from '@angular/platform-browser';\nimport { JhiEventManager, NgJhipsterModule } from 'ng-jhipster';\nimport { FormsModule } from '@angular/forms';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\n\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ArtemisTeamModule } from 'app/exercises/shared/team/team.module';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { TeamsComponent } from 'app/exercises/shared/team/teams.component';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { DifferencePipe } from 'ngx-moment';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { CookieService } from 'ngx-cookie-service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\nimport { mockTeams, MockTeamService } from '../../helpers/mocks/service/mock-team.service';\nimport { MockExerciseService } from '../../helpers/mocks/service/mock-exercise.service';\nimport { teamRoute } from 'app/exercises/shared/team/team.route.ts';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { Router, convertToParamMap } from '@angular/router';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { MockParticipationService } from '../../helpers/mocks/service/mock-participation.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TeamsComponent', () => {\n // needed to make sure ace is defined\n ace.acequire('ace/ext/modelist.js');\n\n let comp: TeamsComponent;\n let fixture: ComponentFixture<TeamsComponent>;\n let debugElement: DebugElement;\n let router: Router;\n\n const route = ({\n params: of({ exerciseId: 1 }),\n snapshot: { queryParamMap: convertToParamMap({}) },\n } as any) as ActivatedRoute;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [\n TranslateModule.forRoot(),\n ArtemisTestModule,\n FormsModule,\n NgJhipsterModule,\n NgbModule,\n ArtemisSharedModule,\n ArtemisSharedComponentModule,\n ArtemisTeamModule,\n RouterTestingModule.withRoutes([teamRoute[0]]),\n ],\n declarations: [],\n providers: [\n JhiEventManager,\n DifferencePipe,\n { provide: TeamService, useClass: MockTeamService },\n { provide: ExerciseService, useClass: MockExerciseService },\n { provide: ActivatedRoute, useValue: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n { provide: ParticipationService, useClass: MockParticipationService },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(TeamsComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n router = debugElement.injector.get(Router);\n fixture.ngZone!.run(() => {\n router.initialNavigation();\n });\n });\n });\n\n it('Teams are loaded correctly', fakeAsync(() => {\n comp.ngOnInit();\n tick();\n\n // Make sure that all 3 teams were received for exercise\n expect(comp.teams).to.have.length(mockTeams.length);\n\n // Check that ngx-datatable is present\n const datatable = debugElement.query(By.css('jhi-data-table'));\n expect(datatable).to.exist;\n }));\n});\n" }, { "alpha_fraction": 0.8017391562461853, "alphanum_fraction": 0.8017391562461853, "avg_line_length": 51.272727966308594, "blob_id": "d226d0e7b7c81e83ec01cb38e48ec52aa05ebd2f", "content_id": "f1a006d69bf4e4dbb998b5580ad5c77524dca774", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 575, "license_type": "permissive", "max_line_length": 133, "num_lines": 11, "path": "/src/main/webapp/app/exercises/modeling/manage/modeling-statistics/modeling-statistics.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ModelingStatisticsComponent } from './modeling-statistics.component';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisModelingStatisticsRoutingModule } from 'app/exercises/modeling/manage/modeling-statistics/modeling-statistics.route';\n\n@NgModule({\n imports: [ArtemisSharedModule, NgbModule, ArtemisModelingStatisticsRoutingModule],\n declarations: [ModelingStatisticsComponent],\n})\nexport class ArtemisModelingStatisticsModule {}\n" }, { "alpha_fraction": 0.7923416495323181, "alphanum_fraction": 0.7923416495323181, "avg_line_length": 47.5, "blob_id": "9f6b38690a4a5875b919d1f34ec70c54601da202", "content_id": "1bf8e1c178c229866b148a5b1d425889aa94a81c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 679, "license_type": "permissive", "max_line_length": 113, "num_lines": 14, "path": "/src/main/webapp/app/shared/category-selector/category-selector.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\n\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisColorSelectorModule } from 'app/shared/color-selector/color-selector.module';\nimport { TagInputModule } from 'ngx-chips';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { CategorySelectorComponent } from 'app/shared/category-selector/category-selector.component';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisColorSelectorModule, ReactiveFormsModule, FormsModule, TagInputModule],\n declarations: [CategorySelectorComponent],\n exports: [CategorySelectorComponent],\n})\nexport class ArtemisCategorySelectorModule {}\n" }, { "alpha_fraction": 0.779321014881134, "alphanum_fraction": 0.779321014881134, "avg_line_length": 42.20000076293945, "blob_id": "5b399787caf2edca64f37371456e2801255454c9", "content_id": "1c8f0811e5a6205a5b39041a0a545d42917866d8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 648, "license_type": "permissive", "max_line_length": 119, "num_lines": 15, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\n\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ExerciseLtiConfigurationComponent } from 'app/exercises/shared/exercise/exercise-lti-configuration.component';\nimport { exercisePopupRoute } from 'app/exercises/shared/exercise/exercise.route';\nimport { FormsModule } from '@angular/forms';\n\nconst ENTITY_STATES = [...exercisePopupRoute];\n\n@NgModule({\n imports: [ArtemisSharedModule, RouterModule.forChild(ENTITY_STATES), FormsModule],\n declarations: [ExerciseLtiConfigurationComponent],\n})\nexport class ArtemisExerciseModule {}\n" }, { "alpha_fraction": 0.7402299046516418, "alphanum_fraction": 0.7402299046516418, "avg_line_length": 30.071428298950195, "blob_id": "41f6d911eefbb524629cec5818c4be6cda42ed15", "content_id": "d56bfb1e4e55bf046d7f04f12bbd506a684fb40e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 435, "license_type": "permissive", "max_line_length": 83, "num_lines": 14, "path": "/src/main/webapp/app/entities/quiz/quiz-submission.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SubmittedAnswer } from 'app/entities/quiz/submitted-answer.model';\nimport { Submission, SubmissionExerciseType } from 'app/entities/submission.model';\n\nexport class QuizSubmission extends Submission {\n public scoreInPoints?: number;\n public submittedAnswers?: SubmittedAnswer[];\n\n // helper attributes\n public adjustedSubmissionDate?: Date;\n\n constructor() {\n super(SubmissionExerciseType.QUIZ);\n }\n}\n" }, { "alpha_fraction": 0.6698130965232849, "alphanum_fraction": 0.6698130965232849, "avg_line_length": 39.022220611572266, "blob_id": "6603194110db5cd449158160bad1989674d711cd", "content_id": "cd71d28bbd9628a9841d568a06e271048478f1ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5403, "license_type": "permissive", "max_line_length": 160, "num_lines": 135, "path": "/src/main/webapp/app/shared/participant-scores/participant-scores.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Injectable } from '@angular/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Observable } from 'rxjs';\n\nexport class ParticipantScoreDTO {\n public id?: number;\n public userId?: number;\n public userName?: string;\n public teamId?: number;\n public teamName?: string;\n public exerciseId?: number;\n public exerciseTitle?: string;\n public lastResultId?: number;\n public lastResultScore?: number;\n public lastPoints?: number;\n public lastRatedResultId?: number;\n public lastRatedResultScore?: number;\n public lastRatedPoints?: number;\n}\n\nexport class ParticipantScoreAverageDTO {\n public userName?: string;\n public teamName?: string;\n public averageScore?: number;\n public averageRatedScore?: number;\n public averagePoints?: number;\n public averageRatedPoints?: number;\n}\n\nexport class ScoresDTO {\n public studentId?: number;\n public studentLogin?: string;\n public pointsAchieved?: number;\n public scoreAchieved?: number;\n public regularPointsAchievable?: number;\n}\nexport type SortDirection = 'asc' | 'desc';\nexport type SortProperty = keyof ParticipantScoreDTO;\nexport type SortingParameter = {\n sortProperty: SortProperty;\n sortDirection: SortDirection;\n};\n\n@Injectable({ providedIn: 'root' })\nexport class ParticipantScoresService {\n public resourceUrl = SERVER_API_URL + 'api';\n\n constructor(private http: HttpClient) {}\n\n findCourseScores(courseId: number): Observable<HttpResponse<ScoresDTO[]>> {\n return this.http.get<ScoresDTO[]>(`${this.resourceUrl}/courses/${courseId}/course-scores`, {\n observe: 'response',\n });\n }\n\n findExamScores(examId: number): Observable<HttpResponse<ScoresDTO[]>> {\n return this.http.get<ScoresDTO[]>(`${this.resourceUrl}/exams/${examId}/exam-scores`, {\n observe: 'response',\n });\n }\n\n findAllOfCoursePaged(courseId: number, sortingParameters: SortingParameter[], page: number, size: number): Observable<HttpResponse<ParticipantScoreDTO[]>> {\n const params = this.createPageParameters(sortingParameters, page, size);\n return this.http.get<ParticipantScoreDTO[]>(`${this.resourceUrl}/courses/${courseId}/participant-scores`, {\n observe: 'response',\n params,\n });\n }\n\n findAllOfCourse(courseId: number): Observable<HttpResponse<ParticipantScoreDTO[]>> {\n let params = new HttpParams();\n params = params.set('getUnpaged', 'true');\n return this.http.get<ParticipantScoreDTO[]>(`${this.resourceUrl}/courses/${courseId}/participant-scores`, {\n observe: 'response',\n params,\n });\n }\n\n findAverageOfCourse(courseId: number, onlyConsiderRatedScores = true): Observable<HttpResponse<number>> {\n let params = new HttpParams();\n params = params.set('onlyConsiderRatedScores', onlyConsiderRatedScores + '');\n return this.http.get<number>(`${this.resourceUrl}/courses/${courseId}/participant-scores/average`, {\n observe: 'response',\n params,\n });\n }\n\n findAverageOfCoursePerParticipant(courseId: number): Observable<HttpResponse<ParticipantScoreAverageDTO[]>> {\n return this.http.get<ParticipantScoreAverageDTO[]>(`${this.resourceUrl}/courses/${courseId}/participant-scores/average-participant`, {\n observe: 'response',\n });\n }\n\n findAllOfExamPaged(examId: number, sortingParameters: SortingParameter[], page: number, size: number): Observable<HttpResponse<ParticipantScoreDTO[]>> {\n const params = this.createPageParameters(sortingParameters, page, size);\n return this.http.get<ParticipantScoreDTO[]>(`${this.resourceUrl}/courses/${examId}/participant-scores`, {\n observe: 'response',\n params,\n });\n }\n\n findAllOfExam(examId: number): Observable<HttpResponse<ParticipantScoreDTO[]>> {\n let params = new HttpParams();\n params = params.set('getUnpaged', 'true');\n return this.http.get<ParticipantScoreDTO[]>(`${this.resourceUrl}/exams/${examId}/participant-scores`, {\n observe: 'response',\n params,\n });\n }\n\n findAverageOfExam(examId: number, onlyConsiderRatedScores = true): Observable<HttpResponse<number>> {\n let params = new HttpParams();\n params = params.set('onlyConsiderRatedScores', onlyConsiderRatedScores + '');\n return this.http.get<number>(`${this.resourceUrl}/exams/${examId}/participant-scores/average`, {\n observe: 'response',\n params,\n });\n }\n\n findAverageOfExamPerParticipant(examId: number): Observable<HttpResponse<ParticipantScoreAverageDTO[]>> {\n return this.http.get<ParticipantScoreAverageDTO[]>(`${this.resourceUrl}/exams/${examId}/participant-scores/average-participant`, {\n observe: 'response',\n });\n }\n\n private createPageParameters(sortingParameters: SortingParameter[], page: number, size: number) {\n let params = new HttpParams();\n for (const sortParameter of sortingParameters) {\n params = params.append('sort', `${sortParameter.sortProperty},${sortParameter.sortDirection}`);\n }\n params = params.set('page', String(page));\n return params.set('size', String(size));\n }\n}\n" }, { "alpha_fraction": 0.7755775451660156, "alphanum_fraction": 0.7772276997566223, "avg_line_length": 45.61538314819336, "blob_id": "231f9757c61bdf1edd59440f4c6f19c4678181b8", "content_id": "dab27282c06b1128d2c3b53ccbf7bb8422f634be", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 606, "license_type": "permissive", "max_line_length": 93, "num_lines": 13, "path": "/src/main/webapp/app/shared/markdown-editor/markdown-editor.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { MarkdownEditorComponent } from './markdown-editor.component';\nimport { NgModule } from '@angular/core';\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { FormsModule } from '@angular/forms';\nimport { ArtemisColorSelectorModule } from 'app/shared/color-selector/color-selector.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, AceEditorModule, FormsModule, ArtemisColorSelectorModule],\n declarations: [MarkdownEditorComponent],\n exports: [MarkdownEditorComponent],\n})\nexport class ArtemisMarkdownEditorModule {}\n" }, { "alpha_fraction": 0.6323193907737732, "alphanum_fraction": 0.6338403224945068, "avg_line_length": 27.901098251342773, "blob_id": "40dc99e2ccfc8ae28d41492b46ae34293c84a3f4", "content_id": "7e90e80714d50a30f5c0f0dabac5281e1ebdc536", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2630, "license_type": "permissive", "max_line_length": 101, "num_lines": 91, "path": "/src/main/webapp/app/shared/markdown-editor/commands/command.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ElementRef } from '@angular/core';\n\n/**\n * abstract class for all commands - default and domain commands of Artemis\n * default commands: markdown commands e.g. bold, italic\n * domain commands: Artemis customized commands\n */\nexport abstract class Command {\n buttonIcon: string;\n buttonTranslationString: string;\n protected aceEditor: any;\n protected markdownWrapper: ElementRef;\n\n public setEditor(aceEditor: any): void {\n this.aceEditor = aceEditor;\n }\n\n public setMarkdownWrapper(ref: ElementRef) {\n this.markdownWrapper = ref;\n }\n\n protected getSelectedText(): string {\n return this.aceEditor.getSelectedText();\n }\n\n protected insertText(text: string) {\n this.aceEditor.insert(text);\n }\n\n protected focus() {\n this.aceEditor.focus();\n }\n\n protected getRange(): Range {\n return this.aceEditor.selection.getRange();\n }\n\n protected replace(range: Range, text: string) {\n this.aceEditor.session.replace(range, text);\n }\n\n protected clearSelection() {\n this.aceEditor.clearSelection();\n }\n\n protected moveCursorTo(row: number, column: number) {\n this.aceEditor.moveCursorTo(row, column);\n }\n\n protected getCursorPosition() {\n return this.aceEditor.getCursorPosition();\n }\n\n protected getLine(row: number) {\n return this.aceEditor.getSession().getLine(row);\n }\n\n protected getCurrentLine() {\n const cursor = this.getCursorPosition();\n return this.getLine(cursor.row);\n }\n\n protected moveCursorToEndOfRow() {\n const cursor = this.getCursorPosition();\n const currentLine = this.aceEditor.getSession().getLine(cursor.row);\n this.clearSelection();\n this.moveCursorTo(cursor.row, currentLine.length);\n }\n\n protected addCompleter(completer: any) {\n this.aceEditor.completers = [...(this.aceEditor.completers || []), completer];\n }\n\n abstract execute(input?: string): void;\n\n protected deleteWhiteSpace(text: string) {\n return text.trim();\n }\n\n protected addRefinedText(selectedText: string, textToAdd: string) {\n if (selectedText.charAt(0) === ' ' && selectedText.charAt(selectedText.length - 1) === ' ') {\n return this.insertText(' ' + textToAdd + ' ');\n } else if (selectedText.charAt(0) === ' ') {\n return this.insertText(' ' + textToAdd);\n } else if (selectedText.charAt(selectedText.length - 1) === ' ') {\n return this.insertText(textToAdd + ' ');\n } else {\n return this.insertText(textToAdd);\n }\n }\n}\n" }, { "alpha_fraction": 0.6507480144500732, "alphanum_fraction": 0.6536248326301575, "avg_line_length": 43.186439514160156, "blob_id": "abb284f09a1061f35f0d51c9a4cb15b76dafc638", "content_id": "83f905b9b8b78b153422d5355a920daa7148bc07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5214, "license_type": "permissive", "max_line_length": 120, "num_lines": 118, "path": "/src/test/javascript/spec/component/learning-goals/learning-goal.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { MockProvider } from 'ng-mocks';\nimport { take } from 'rxjs/operators';\nimport { LectureUnit } from 'app/entities/lecture-unit/lectureUnit.model';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('LearningGoalService', () => {\n let testBed: TestBed;\n let learningGoalService: LearningGoalService;\n let httpTestingController: HttpTestingController;\n let defaultLearningGoal: LearningGoal;\n let defaultLearningGoalProgress: IndividualLearningGoalProgress;\n let expectedResultLearningGoal: any;\n let expectedResultLearningGoalProgress: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n providers: [\n MockProvider(LectureUnitService, {\n convertDateArrayFromServerEntity<T extends LectureUnit>(res: T[]): T[] {\n return res;\n },\n convertDateArrayFromClient<T extends LectureUnit>(lectureUnits: T[]): T[] {\n return lectureUnits;\n },\n }),\n ],\n });\n expectedResultLearningGoal = {} as HttpResponse<LearningGoal>;\n expectedResultLearningGoalProgress = {} as HttpResponse<IndividualLearningGoalProgress>;\n\n testBed = getTestBed();\n learningGoalService = testBed.get(LearningGoalService);\n httpTestingController = testBed.get(HttpTestingController);\n\n defaultLearningGoal = new LearningGoal();\n defaultLearningGoal.id = 0;\n defaultLearningGoal.title = 'title';\n defaultLearningGoal.description = 'description';\n\n defaultLearningGoalProgress = new IndividualLearningGoalProgress();\n defaultLearningGoalProgress.learningGoalId = 0;\n defaultLearningGoalProgress.learningGoalTitle = 'title';\n });\n\n afterEach(() => {\n httpTestingController.verify();\n });\n\n it('should find a LearningGoal', async () => {\n const returnedFromService = { ...defaultLearningGoal };\n learningGoalService\n .findById(1, 1)\n .pipe(take(1))\n .subscribe((resp) => (expectedResultLearningGoal = resp));\n const req = httpTestingController.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResultLearningGoal.body).to.deep.equal(defaultLearningGoal);\n });\n\n it('should get Progress for a LearningGoal', async () => {\n const returnedFromService = { ...defaultLearningGoalProgress };\n learningGoalService\n .getProgress(1, 1)\n .pipe(take(1))\n .subscribe((resp) => (expectedResultLearningGoalProgress = resp));\n const req = httpTestingController.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResultLearningGoalProgress.body).to.deep.equal(defaultLearningGoalProgress);\n });\n\n it('should get all learning goals for a course', async () => {\n const returnedFromService = [{ ...defaultLearningGoalProgress }];\n let response: any = {} as HttpResponse<LearningGoal[]>;\n learningGoalService\n .getAllForCourse(1)\n .pipe(take(1))\n .subscribe((resp) => (response = resp));\n const req = httpTestingController.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(response.body).to.deep.equal([{ ...defaultLearningGoalProgress }]);\n });\n\n it('should create a LearningGoal', async () => {\n const returnedFromService = { ...defaultLearningGoal, id: 0 };\n const expected = { ...returnedFromService };\n learningGoalService\n .create(new LearningGoal(), 1)\n .pipe(take(1))\n .subscribe((resp) => (expectedResultLearningGoal = resp));\n const req = httpTestingController.expectOne({ method: 'POST' });\n req.flush(returnedFromService);\n expect(expectedResultLearningGoal.body).to.deep.equal(expected);\n });\n\n it('should update a LearningGoal', async () => {\n const returnedFromService = { ...defaultLearningGoal, title: 'Test' };\n const expected = { ...returnedFromService };\n learningGoalService\n .update(expected, 1)\n .pipe(take(1))\n .subscribe((resp) => (expectedResultLearningGoal = resp));\n const req = httpTestingController.expectOne({ method: 'PUT' });\n req.flush(returnedFromService);\n expect(expectedResultLearningGoal.body).to.deep.equal(expected);\n });\n});\n" }, { "alpha_fraction": 0.7629757523536682, "alphanum_fraction": 0.7629757523536682, "avg_line_length": 43.46154022216797, "blob_id": "79726b66fec5711b5e3b2bf5d7e79e45792af75c", "content_id": "7a8643831fa3fff88a3736d0c3696660e02fac57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 578, "license_type": "permissive", "max_line_length": 79, "num_lines": 13, "path": "/src/main/webapp/app/exercises/shared/rating/rating.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { RatingComponent } from 'app/exercises/shared/rating/rating.component';\nimport { RatingModule as StarratingModule } from 'ng-starrating';\nimport { RatingListComponent } from './rating-list/rating-list.component';\n\n@NgModule({\n declarations: [RatingComponent, RatingListComponent],\n exports: [RatingComponent],\n imports: [CommonModule, ArtemisSharedModule, StarratingModule],\n})\nexport class RatingModule {}\n" }, { "alpha_fraction": 0.7305107712745667, "alphanum_fraction": 0.7311828136444092, "avg_line_length": 40.33333206176758, "blob_id": "11c6fa265434b5e71e6ba2b5a670bb5322aa94a9", "content_id": "626e93bc4bbc0b5385829e572da52c183d682c62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1488, "license_type": "permissive", "max_line_length": 162, "num_lines": 36, "path": "/src/main/webapp/app/exercises/shared/result/result-utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Result } from 'app/entities/result.model';\nimport { cloneDeep } from 'lodash';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\n\n/**\n * Check if the given result was initialized and has a score\n *\n * @param result\n */\nexport const initializedResultWithScore = (result?: Result) => {\n return result != undefined && (result.score || result.score === 0);\n};\n\n/**\n * Prepare a result that contains a participation which is needed in the rating component\n */\nexport const addParticipationToResult = (result: Result | undefined, participation: StudentParticipation) => {\n const ratingResult = cloneDeep(result);\n if (ratingResult) {\n const ratingParticipation = cloneDeep(participation);\n // remove circular dependency\n ratingParticipation.exercise!.studentParticipations = [];\n ratingResult.participation = ratingParticipation;\n }\n return ratingResult;\n};\n\n/**\n * searches for all unreferenced feedback in an array of feedbacks of a result\n * @param feedbacks the feedback of a result\n * @returns an array with the unreferenced feedback of the result\n */\nexport const getUnreferencedFeedback = (feedbacks: Feedback[] | undefined): Feedback[] | undefined => {\n return feedbacks ? feedbacks.filter((feedbackElement) => !feedbackElement.reference && feedbackElement.type === FeedbackType.MANUAL_UNREFERENCED) : undefined;\n};\n" }, { "alpha_fraction": 0.5862926244735718, "alphanum_fraction": 0.5872873663902283, "avg_line_length": 37.07954406738281, "blob_id": "b3b2c7f95e1a2c2ac419ddd7923fd28edf74810a", "content_id": "38b0e6b473efb7020edb4c63ce55500c1e71c2a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10053, "license_type": "permissive", "max_line_length": 153, "num_lines": 264, "path": "/src/main/webapp/app/course/manage/course-group.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';\nimport { Subscription } from 'rxjs/Subscription';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { Subject } from 'rxjs';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { User } from 'app/core/user/user.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Course, CourseGroup, courseGroups } from 'app/entities/course.model';\nimport { capitalize } from 'lodash';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { Observable, of } from 'rxjs';\nimport { catchError, map, switchMap, tap } from 'rxjs/operators';\nimport { UserService } from 'app/core/user/user.service';\nimport { DataTableComponent } from 'app/shared/data-table/data-table.component';\nimport { iconsAsHTML } from 'app/utils/icons.utils';\n\nconst cssClasses = {\n alreadyMember: 'already-member',\n newlyAddedMember: 'newly-added-member',\n};\n\n@Component({\n selector: 'jhi-course-group',\n templateUrl: './course-group.component.html',\n styleUrls: ['./course-group.component.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class CourseGroupComponent implements OnInit, OnDestroy {\n @ViewChild(DataTableComponent) dataTable: DataTableComponent;\n\n readonly ActionType = ActionType;\n readonly capitalize = capitalize;\n\n course: Course;\n courseGroup: CourseGroup;\n allCourseGroupUsers: User[] = [];\n filteredUsersSize = 0;\n paramSub: Subscription;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n isLoading = false;\n isSearching = false;\n searchFailed = false;\n searchNoResults = false;\n isTransitioning = false;\n rowClass: string | undefined = undefined;\n\n constructor(\n private router: Router,\n private route: ActivatedRoute,\n private jhiAlertService: JhiAlertService,\n private eventManager: JhiEventManager,\n private courseService: CourseManagementService,\n private userService: UserService,\n ) {}\n\n /**\n * Init the course group component by loading all users of course group.\n */\n ngOnInit() {\n this.loadAll();\n }\n\n /**\n * Unsubscribe dialog error source on component destruction.\n */\n ngOnDestroy() {\n this.dialogErrorSource.unsubscribe();\n }\n\n /**\n * Load all users of given cours group.\n * Redirect to course-management when given course group is in predefined standard course groups.\n */\n loadAll() {\n this.isLoading = true;\n this.route.parent!.data.subscribe(({ course }) => {\n this.course = course;\n this.paramSub = this.route.params.subscribe((params) => {\n this.courseGroup = params['courseGroup'];\n if (!courseGroups.includes(this.courseGroup)) {\n return this.router.navigate(['/course-management']);\n }\n this.courseService.getAllUsersInCourseGroup(this.course.id!, this.courseGroup).subscribe((usersResponse) => {\n this.allCourseGroupUsers = usersResponse.body!;\n this.isLoading = false;\n });\n });\n });\n }\n\n /**\n * Receives the search text and filter results from DataTableComponent, modifies them and returns the result which will be used by ngbTypeahead.\n *\n * 1. Perform server-side search using the search text\n * 2. Return results from server query that contain all users (instead of only the client-side users who are group members already)\n *\n * @param stream$ stream of searches of the format {text, entities} where entities are the results\n * @return stream of users for the autocomplete\n */\n searchAllUsers = (stream$: Observable<{ text: string; entities: User[] }>): Observable<User[]> => {\n return stream$.pipe(\n switchMap(({ text: loginOrName }) => {\n this.searchFailed = false;\n this.searchNoResults = false;\n if (loginOrName.length < 3) {\n return of([]);\n }\n this.isSearching = true;\n return this.userService\n .search(loginOrName)\n .pipe(map((usersResponse) => usersResponse.body!))\n .pipe(\n tap((users) => {\n if (users.length === 0) {\n this.searchNoResults = true;\n }\n }),\n catchError(() => {\n this.searchFailed = true;\n return of([]);\n }),\n );\n }),\n tap(() => {\n this.isSearching = false;\n }),\n tap((users) => {\n setTimeout(() => {\n for (let i = 0; i < this.dataTable.typeaheadButtons.length; i++) {\n const isAlreadyInCourseGroup = this.allCourseGroupUsers.map((user) => user.id).includes(users[i].id);\n this.dataTable.typeaheadButtons[i].insertAdjacentHTML('beforeend', iconsAsHTML[isAlreadyInCourseGroup ? 'users' : 'users-plus']);\n if (isAlreadyInCourseGroup) {\n this.dataTable.typeaheadButtons[i].classList.add(cssClasses.alreadyMember);\n }\n }\n });\n }),\n );\n };\n\n /**\n * Receives the user that was selected in the autocomplete and the callback from DataTableComponent.\n * The callback inserts the search term of the selected entity into the search field and updates the displayed users.\n *\n * @param user The selected user from the autocomplete suggestions\n * @param callback Function that can be called with the selected user to trigger the DataTableComponent default behavior\n */\n onAutocompleteSelect = (user: User, callback: (user: User) => void): void => {\n // If the user is not part of this course group yet, perform the server call to add them\n if (!this.allCourseGroupUsers.map((u) => u.id).includes(user.id) && user.login) {\n this.isTransitioning = true;\n this.courseService.addUserToCourseGroup(this.course.id!, this.courseGroup, user.login).subscribe(\n () => {\n this.isTransitioning = false;\n\n // Add newly added user to the list of all users in the course group\n this.allCourseGroupUsers.push(user);\n\n // Hand back over to the data table for updating\n callback(user);\n\n // Flash green background color to signal to the user that this record was added\n this.flashRowClass(cssClasses.newlyAddedMember);\n },\n () => {\n this.isTransitioning = false;\n },\n );\n } else {\n // Hand back over to the data table\n callback(user);\n }\n };\n\n /**\n * Remove user from course group\n *\n * @param user User that should be removed from the currently viewed course group\n */\n removeFromGroup(user: User) {\n if (user.login) {\n this.courseService.removeUserFromCourseGroup(this.course.id!, this.courseGroup, user.login).subscribe(\n () => {\n this.allCourseGroupUsers = this.allCourseGroupUsers.filter((u) => u.login !== user.login);\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n }\n\n /**\n * Property that returns the course group name, e.g. \"artemis-test-students\"\n */\n get courseGroupName() {\n switch (this.courseGroup) {\n case CourseGroup.STUDENTS:\n return this.course.studentGroupName;\n case CourseGroup.TUTORS:\n return this.course.teachingAssistantGroupName;\n case CourseGroup.INSTRUCTORS:\n return this.course.instructorGroupName;\n }\n }\n\n /**\n * Property that returns the course group entity name, e.g. \"students\" or \"tutors\".\n * If the count of users is exactly 1, singular is used instead of plural.\n */\n get courseGroupEntityName(): string {\n return this.allCourseGroupUsers.length === 1 ? this.courseGroup.slice(0, -1) : this.courseGroup;\n }\n\n /**\n * Update the number of filtered users\n *\n * @param filteredUsersSize Total number of users after filters have been applied\n */\n handleUsersSizeChange = (filteredUsersSize: number) => {\n this.filteredUsersSize = filteredUsersSize;\n };\n\n /**\n * Formats the results in the autocomplete overlay.\n *\n * @param user\n */\n searchResultFormatter = (user: User) => {\n const { name, login } = user;\n return `${name} (${login})`;\n };\n\n /**\n * Converts a user object to a string that can be searched for. This is\n * used by the autocomplete select inside the data table.\n *\n * @param user User\n */\n searchTextFromUser = (user: User): string => {\n return user.login || '';\n };\n\n /**\n * Computes the row class that is being added to all rows of the datatable\n */\n dataTableRowClass = () => {\n return this.rowClass;\n };\n\n /**\n * Can be used to highlight rows temporarily by flashing a certain css class\n *\n * @param className Name of the class to be applied to all rows\n */\n flashRowClass = (className: string) => {\n this.rowClass = className;\n setTimeout(() => (this.rowClass = undefined));\n };\n}\n" }, { "alpha_fraction": 0.669639527797699, "alphanum_fraction": 0.6793064475059509, "avg_line_length": 45.20749282836914, "blob_id": "cda7e45b770ee7441f1b9f94b18506e2625cf53b", "content_id": "c26072016b82b1bf4855315f2d2dd36fc9982824", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16034, "license_type": "permissive", "max_line_length": 149, "num_lines": 347, "path": "/src/test/javascript/spec/component/text-submission-assessment/text-feedback-conflicts.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { ArtemisTestModule } from '../../test.module';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ActivatedRoute, RouterModule, Router, convertToParamMap } from '@angular/router';\nimport { By } from '@angular/platform-browser';\nimport { of } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TextFeedbackConflictsComponent } from 'app/exercises/text/assess/conflicts/text-feedback-conflicts.component';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { AssessmentInstructionsModule } from 'app/assessment/assessment-instructions/assessment-instructions.module';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { TextSharedModule } from 'app/exercises/text/shared/text-shared.module';\nimport { TextSubmissionAssessmentComponent } from 'app/exercises/text/assess/text-submission-assessment.component';\nimport { TextAssessmentAreaComponent } from 'app/exercises/text/assess/text-assessment-area/text-assessment-area.component';\nimport { TextblockAssessmentCardComponent } from 'app/exercises/text/assess/textblock-assessment-card/textblock-assessment-card.component';\nimport { TextblockFeedbackEditorComponent } from 'app/exercises/text/assess/textblock-feedback-editor/textblock-feedback-editor.component';\nimport { ManualTextblockSelectionComponent } from 'app/exercises/text/assess/manual-textblock-selection/manual-textblock-selection.component';\nimport { TextFeedbackConflictsHeaderComponent } from 'app/exercises/text/assess/conflicts/conflicts-header/text-feedback-conflicts-header.component';\nimport { getLatestSubmissionResult, SubmissionExerciseType, SubmissionType } from 'app/entities/submission.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport * as moment from 'moment';\nimport { FeedbackConflict, FeedbackConflictType } from 'app/entities/feedback-conflict';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { Course } from 'app/entities/course.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\n\ndescribe('TextFeedbackConflictsComponent', () => {\n let component: TextFeedbackConflictsComponent;\n let fixture: ComponentFixture<TextFeedbackConflictsComponent>;\n let textAssessmentService: TextAssessmentService;\n let router: Router;\n\n const exercise = {\n id: 20,\n type: ExerciseType.TEXT,\n assessmentType: AssessmentType.MANUAL,\n course: { id: 123, isAtLeastInstructor: true } as Course,\n } as TextExercise;\n const participation: StudentParticipation = ({\n type: ParticipationType.STUDENT,\n exercise,\n } as unknown) as StudentParticipation;\n const textSubmission = ({\n submissionExerciseType: SubmissionExerciseType.TEXT,\n id: 2278,\n submitted: true,\n type: SubmissionType.MANUAL,\n submissionDate: moment('2019-07-09T10:47:33.244Z'),\n text: 'First text. Second text.',\n participation,\n } as unknown) as TextSubmission;\n textSubmission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n completionDate: moment('2019-07-09T11:51:23.251Z'),\n successful: false,\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n textSubmission,\n } as unknown) as Result,\n ];\n textSubmission.latestResult = getLatestSubmissionResult(textSubmission);\n\n textSubmission.latestResult!.feedbacks = [\n {\n id: 1,\n detailText: 'First Feedback',\n credits: 1.5,\n reference: 'First text id',\n } as Feedback,\n ];\n textSubmission.blocks = [\n ({\n id: 'First text id',\n text: 'First text.',\n startIndex: 0,\n endIndex: 11,\n textSubmission,\n } as unknown) as TextBlock,\n ({\n id: 'second text id',\n text: 'Second text.',\n startIndex: 12,\n endIndex: 24,\n textSubmission,\n } as unknown) as TextBlock,\n ];\n textSubmission.latestResult!.feedbacks![0].conflictingTextAssessments = [\n {\n id: 1,\n conflict: true,\n conflictingFeedbackId: 5,\n createdAt: moment('2019-07-09T11:51:23.251Z'),\n type: FeedbackConflictType.INCONSISTENT_COMMENT,\n markedAsNoConflict: false,\n } as FeedbackConflict,\n ];\n\n const conflictingSubmission = ({\n submissionExerciseType: SubmissionExerciseType.TEXT,\n id: 2280,\n submitted: true,\n type: SubmissionType.MANUAL,\n submissionDate: moment('2019-07-09T10:47:33.244Z'),\n text: 'First Conflicting Submission Text.',\n } as unknown) as TextSubmission;\n conflictingSubmission.results = [\n ({\n id: 2375,\n completionDate: moment('2020-02-10T11:51:23.251Z'),\n successful: false,\n score: 3,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n conflictingSubmission,\n } as unknown) as Result,\n ];\n conflictingSubmission.latestResult = getLatestSubmissionResult(conflictingSubmission);\n conflictingSubmission.latestResult!.feedbacks = [\n {\n id: 5,\n detailText: 'Conflicting feedback',\n credits: 1.5,\n reference: 'Conflicting text id',\n } as Feedback,\n ];\n conflictingSubmission.blocks = [\n ({\n id: 'Conflicting text id',\n text: 'First Conflicting Submission Text.',\n startIndex: 0,\n endIndex: 34,\n conflictingSubmission,\n } as unknown) as TextBlock,\n ];\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n ArtemisSharedModule,\n ArtemisAssessmentSharedModule,\n AssessmentInstructionsModule,\n TranslateModule.forRoot(),\n ArtemisConfirmIconModule,\n RouterModule,\n RouterTestingModule,\n TextSharedModule,\n ],\n declarations: [\n TextFeedbackConflictsComponent,\n TextSubmissionAssessmentComponent,\n TextAssessmentAreaComponent,\n TextblockAssessmentCardComponent,\n TextblockFeedbackEditorComponent,\n ManualTextblockSelectionComponent,\n TextFeedbackConflictsHeaderComponent,\n ],\n providers: [{ provide: ActivatedRoute, useValue: { snapshot: { paramMap: convertToParamMap({ feedbackId: 1 }) } } }],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents();\n });\n\n beforeEach(() => {\n router = TestBed.inject(Router);\n spyOn(router, 'getCurrentNavigation').and.returnValues({ extras: { state: { submission: textSubmission } } } as any);\n fixture = TestBed.createComponent(TextFeedbackConflictsComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n });\n\n it('should set passed parameters correctly in constructor', () => {\n expect(component.leftSubmission).toBe(textSubmission);\n expect(component.leftFeedbackId).toBe(1);\n expect(component.exercise).toBe(exercise);\n });\n\n it('should use jhi-text-feedback-conflicts-header', () => {\n const headerComponent = fixture.debugElement.query(By.directive(TextFeedbackConflictsHeaderComponent));\n expect(headerComponent).toBeTruthy();\n });\n\n it('should set conflicting submission correctly', () => {\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n expect(component.rightSubmission).toBe(conflictingSubmission);\n expect(component.rightTotalScore).toBe(1.5);\n expect(component.feedbackConflicts).toBe(textSubmission.latestResult!.feedbacks![0].conflictingTextAssessments!);\n expect(component.rightTextBlockRefs[0].feedback).toBe(conflictingSubmission.latestResult!.feedbacks![0]);\n });\n\n it('should use jhi-text-assessment-area', () => {\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n const textAssessmentAreaComponent = fixture.debugElement.query(By.directive(TextAssessmentAreaComponent));\n expect(textAssessmentAreaComponent).toBeTruthy();\n });\n\n it('should solve conflict by overriding left submission', () => {\n textAssessmentService = fixture.debugElement.injector.get(TextAssessmentService);\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n\n expect(component.isOverrideDisabled).toBe(true);\n\n const textAssessmentArea = fixture.debugElement.query(By.directive(TextAssessmentAreaComponent));\n const textAssessmentAreaComponent = textAssessmentArea.componentInstance as TextAssessmentAreaComponent;\n const textBlockRef = textAssessmentAreaComponent.textBlockRefs[0];\n textBlockRef.feedback!.detailText = 'Correcting feedback text.';\n textBlockRef.feedback!.credits = 2;\n textAssessmentAreaComponent.textBlockRefsChangeEmit();\n\n expect(component.leftTotalScore).toBe(2);\n expect(component.isOverrideDisabled).toBe(false);\n\n spyOn(textAssessmentService, 'submit').and.returnValue(\n of(\n new HttpResponse({\n body: component.leftSubmission!.latestResult,\n }),\n ),\n );\n component.overrideLeftSubmission();\n expect(textAssessmentService.submit).toHaveBeenCalledWith(\n exercise.id!,\n textSubmission.latestResult!.id!,\n [component.leftTextBlockRefs[0].feedback!],\n [component.leftTextBlockRefs[0].block!],\n );\n });\n\n it('should be able to select conflicting feedback', () => {\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n\n const textBlockAssessmentAreas = fixture.debugElement.queryAll(By.directive(TextblockAssessmentCardComponent));\n textBlockAssessmentAreas.forEach((textBlockAssessmentCardArea) => {\n const textBlockAssessmentCardComponent = textBlockAssessmentCardArea.componentInstance as TextblockAssessmentCardComponent;\n if (textBlockAssessmentCardComponent.textBlockRef === component.rightTextBlockRefs[0]) {\n textBlockAssessmentCardComponent.select();\n }\n });\n\n expect(component.selectedRightFeedbackId).toBeTruthy();\n expect(component.selectedRightFeedbackId).toBe(conflictingSubmission.latestResult!.feedbacks![0].id);\n });\n\n it('should be able to un-select conflicting feedback', () => {\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n\n const textBlockAssessmentAreas = fixture.debugElement.queryAll(By.directive(TextblockAssessmentCardComponent));\n textBlockAssessmentAreas.forEach((textBlockAssessmentCardArea) => {\n const textBlockAssessmentCardComponent = textBlockAssessmentCardArea.componentInstance as TextblockAssessmentCardComponent;\n if (textBlockAssessmentCardComponent.textBlockRef === component.rightTextBlockRefs[0]) {\n textBlockAssessmentCardComponent.select();\n fixture.detectChanges();\n textBlockAssessmentCardComponent.select();\n }\n });\n\n expect(component.selectedRightFeedbackId).toBeFalsy();\n expect(component.selectedRightFeedbackId).toBe(undefined);\n });\n\n it('should not be able to select conflicting feedback for left submission', () => {\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n\n const textBlockAssessmentAreas = fixture.debugElement.queryAll(By.directive(TextblockAssessmentCardComponent));\n textBlockAssessmentAreas.forEach((textBlockAssessmentCardArea) => {\n const textBlockAssessmentCardComponent = textBlockAssessmentCardArea.componentInstance as TextblockAssessmentCardComponent;\n if (textBlockAssessmentCardComponent.textBlockRef === component.leftTextBlockRefs[0]) {\n spyOn(textBlockAssessmentCardComponent, 'didSelect');\n textBlockAssessmentCardComponent.select();\n expect(textBlockAssessmentCardComponent.didSelect).toHaveBeenCalledTimes(0);\n }\n });\n\n expect(component.selectedRightFeedbackId).toBeFalsy();\n expect(component.selectedRightFeedbackId).toBe(undefined);\n });\n\n it('should discard conflict', () => {\n textAssessmentService = fixture.debugElement.injector.get(TextAssessmentService);\n component['setPropertiesFromServerResponse']([conflictingSubmission]);\n fixture.detectChanges();\n\n component.didSelectConflictingFeedback(conflictingSubmission.latestResult!.feedbacks![0].id!);\n\n const feedbackConflict = textSubmission.latestResult!.feedbacks![0].conflictingTextAssessments![0];\n feedbackConflict.conflict = false;\n feedbackConflict.discard = true;\n spyOn(textAssessmentService, 'solveFeedbackConflict').and.returnValue(\n of(\n new HttpResponse({\n body: feedbackConflict,\n }),\n ),\n );\n component.discardConflict();\n expect(textAssessmentService.solveFeedbackConflict).toHaveBeenCalledWith(exercise.id!, feedbackConflict.id!);\n });\n\n it('should switch submissions when it changed in the header', () => {\n const secondConflictingSubmission = Object.assign({}, conflictingSubmission);\n secondConflictingSubmission.id! += 1;\n secondConflictingSubmission.latestResult!.feedbacks![0].id! += 1;\n secondConflictingSubmission.latestResult!.id! += 1;\n\n component['setPropertiesFromServerResponse']([conflictingSubmission, secondConflictingSubmission]);\n fixture.detectChanges();\n\n const textFeedbackConflictsHeader = fixture.debugElement.query(By.directive(TextFeedbackConflictsHeaderComponent));\n const textFeedbackConflictsHeaderComponent = textFeedbackConflictsHeader.componentInstance as TextFeedbackConflictsHeaderComponent;\n expect(textFeedbackConflictsHeaderComponent.numberOfConflicts).toBe(2);\n textFeedbackConflictsHeaderComponent.onNextConflict();\n expect(component.rightSubmission).toBe(secondConflictingSubmission);\n textFeedbackConflictsHeaderComponent.onPrevConflict();\n expect(component.rightSubmission).toBe(conflictingSubmission);\n });\n});\n" }, { "alpha_fraction": 0.48261758685112, "alphanum_fraction": 0.4948875308036804, "avg_line_length": 26.16666603088379, "blob_id": "b1a4a271757089afeab993f6e6a31a94becc2ae6", "content_id": "b564a1ebe65bf15c5367e640afe4175e6cbe2357", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 489, "license_type": "permissive", "max_line_length": 80, "num_lines": 18, "path": "/src/test/javascript/jest.config.ci.js", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "const mainConfig = require('./jest.config');\n\nmodule.exports = {\n ...mainConfig,\n globals: {\n 'ts-jest': {\n tsconfig: '<rootDir>/tsconfig.spec.json',\n stringifyContentPathRegex: '\\\\.html$',\n astTransformers: {\n before: [require.resolve('./InlineHtmlStripStylesTransformer')],\n },\n isolatedModules: true,\n diagnostics: {\n ignoreCodes: [151001],\n },\n },\n },\n};\n" }, { "alpha_fraction": 0.7084745764732361, "alphanum_fraction": 0.7152542471885681, "avg_line_length": 31.77777862548828, "blob_id": "0244e093c2248aee0bd11ae90d5a1e6b3d665b86", "content_id": "e63167a3bc119303f876fb326d8865f1915c3495", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 295, "license_type": "permissive", "max_line_length": 72, "num_lines": 9, "path": "/src/main/webapp/app/shared/util/crypto.utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { createHash } from 'crypto';\n\n/**\n * Generates and returns the hash digest using 'hex' algorithm.\n * @param string The string to which the algorithm will be applied upon.\n */\nexport function sha1Hex(string: string): string {\n return createHash('sha1').update(string).digest('hex');\n}\n" }, { "alpha_fraction": 0.7072498202323914, "alphanum_fraction": 0.7080378532409668, "avg_line_length": 27.200000762939453, "blob_id": "965c0b5af50812f2c7fb419fe43b6351038b0884", "content_id": "2bf5d091eb87eacb6a84dc7f8b8419a49229148f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2538, "license_type": "permissive", "max_line_length": 153, "num_lines": 90, "path": "/src/main/java/de/tum/in/www1/artemis/domain/ProgrammingSubmission.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.enumeration.SubmissionType;\n\n/**\n * A ProgrammingSubmission.\n */\n@Entity\n@DiscriminatorValue(value = \"P\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ProgrammingSubmission extends Submission {\n\n @Column(name = \"commit_hash\")\n private String commitHash;\n\n @Column(name = \"build_failed\")\n private boolean buildFailed;\n\n @Column(name = \"build_artifact\")\n private boolean buildArtifact;\n\n // Only present if buildFailed == true\n @OneToMany(mappedBy = \"programmingSubmission\", cascade = CascadeType.ALL, orphanRemoval = true)\n @OrderColumn\n @JsonIgnoreProperties(value = \"programmingSubmission\", allowSetters = true)\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private List<BuildLogEntry> buildLogEntries = new ArrayList<>();\n\n public String getCommitHash() {\n return commitHash;\n }\n\n public ProgrammingSubmission commitHash(String commitHash) {\n this.commitHash = commitHash;\n return this;\n }\n\n public void setCommitHash(String commitHash) {\n this.commitHash = commitHash;\n }\n\n public boolean isBuildFailed() {\n return buildFailed;\n }\n\n public void setBuildFailed(boolean buildFailed) {\n this.buildFailed = buildFailed;\n }\n\n public boolean isBuildArtifact() {\n return buildArtifact;\n }\n\n public void setBuildArtifact(boolean buildArtifact) {\n this.buildArtifact = buildArtifact;\n }\n\n public List<BuildLogEntry> getBuildLogEntries() {\n return buildLogEntries;\n }\n\n public void setBuildLogEntries(List<BuildLogEntry> buildLogEntries) {\n this.buildLogEntries = buildLogEntries;\n }\n\n public boolean belongsToTestRepository() {\n return SubmissionType.TEST.equals(getType());\n }\n\n @Override\n public boolean isEmpty() {\n return false; // programming submissions cannot be empty, they are only created for actual commits in the git repository\n }\n\n @Override\n public String toString() {\n return \"ProgrammingSubmission{\" + \"commitHash='\" + commitHash + '\\'' + \", buildFailed=\" + buildFailed + \", buildArtifact=\" + buildArtifact + '}';\n }\n}\n" }, { "alpha_fraction": 0.726746141910553, "alphanum_fraction": 0.7297274470329285, "avg_line_length": 51.88288116455078, "blob_id": "aee9ea5f26ba3287db20956b8da3a7706ee9b18b", "content_id": "9b63ad5e534e85e3079e49ca91e882543dd9b0f1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11740, "license_type": "permissive", "max_line_length": 179, "num_lines": 222, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/StudentQuestionAnswerResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.service.GroupNotificationService;\nimport de.tum.in.www1.artemis.service.SingleUserNotificationService;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\nimport io.github.jhipster.web.util.ResponseUtil;\n\n/**\n * REST controller for managing StudentQuestionAnswer.\n */\n@RestController\n@RequestMapping(\"/api\")\npublic class StudentQuestionAnswerResource {\n\n private final Logger log = LoggerFactory.getLogger(StudentQuestionAnswerResource.class);\n\n private static final String ENTITY_NAME = \"questionAnswer\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final StudentQuestionAnswerRepository studentQuestionAnswerRepository;\n\n private final CourseRepository courseRepository;\n\n private final StudentQuestionRepository studentQuestionRepository;\n\n private final AuthorizationCheckService authorizationCheckService;\n\n private final UserRepository userRepository;\n\n private final GroupNotificationService groupNotificationService;\n\n private final SingleUserNotificationService singleUserNotificationService;\n\n public StudentQuestionAnswerResource(StudentQuestionAnswerRepository studentQuestionAnswerRepository, GroupNotificationService groupNotificationService,\n SingleUserNotificationService singleUserNotificationService, AuthorizationCheckService authorizationCheckService, UserRepository userRepository,\n CourseRepository courseRepository, StudentQuestionRepository studentQuestionRepository) {\n this.studentQuestionAnswerRepository = studentQuestionAnswerRepository;\n this.courseRepository = courseRepository;\n this.studentQuestionRepository = studentQuestionRepository;\n this.groupNotificationService = groupNotificationService;\n this.singleUserNotificationService = singleUserNotificationService;\n this.authorizationCheckService = authorizationCheckService;\n this.userRepository = userRepository;\n }\n\n /**\n * POST /courses/{courseId}/question-answers : Create a new studentQuestionAnswer.\n *\n * @param courseId the id of the course the answer belongs to\n * @param studentQuestionAnswer the studentQuestionAnswer to create\n * @return the ResponseEntity with status 201 (Created) and with body the new studentQuestionAnswer, or with status 400 (Bad Request) if the studentQuestionAnswer has already\n * an ID\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PostMapping(\"courses/{courseId}/student-question-answers\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentQuestionAnswer> createStudentQuestionAnswer(@PathVariable Long courseId, @RequestBody StudentQuestionAnswer studentQuestionAnswer)\n throws URISyntaxException {\n log.debug(\"REST request to save StudentQuestionAnswer : {}\", studentQuestionAnswer);\n User user = this.userRepository.getUserWithGroupsAndAuthorities();\n if (studentQuestionAnswer.getId() != null) {\n throw new BadRequestAlertException(\"A new studentQuestionAnswer cannot already have an ID\", ENTITY_NAME, \"idexists\");\n }\n var course = courseRepository.findByIdElseThrow(courseId);\n if (!this.authorizationCheckService.isAtLeastStudentInCourse(course, user)) {\n return forbidden();\n }\n Optional<StudentQuestion> optionalStudentQuestion = studentQuestionRepository.findById(studentQuestionAnswer.getQuestion().getId());\n if (optionalStudentQuestion.isEmpty()) {\n return ResponseEntity.notFound().build();\n }\n if (!optionalStudentQuestion.get().getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n // answer to approved if written by an instructor\n studentQuestionAnswer.setTutorApproved(this.authorizationCheckService.isAtLeastInstructorInCourse(course, user));\n StudentQuestionAnswer result = studentQuestionAnswerRepository.save(studentQuestionAnswer);\n if (result.getQuestion().getExercise() != null) {\n groupNotificationService.notifyTutorAndInstructorGroupAboutNewAnswerForExercise(result);\n singleUserNotificationService.notifyUserAboutNewAnswerForExercise(result);\n }\n if (result.getQuestion().getLecture() != null) {\n groupNotificationService.notifyTutorAndInstructorGroupAboutNewAnswerForLecture(result);\n singleUserNotificationService.notifyUserAboutNewAnswerForLecture(result);\n }\n return ResponseEntity.created(new URI(\"/api/courses\" + courseId + \"/student-question-answers/\" + result.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString())).body(result);\n }\n\n /**\n * PUT /courses/{courseId}/question-answers : Updates an existing studentQuestionAnswer.\n *\n * @param courseId the id of the course the answer belongs to\n * @param studentQuestionAnswer the studentQuestionAnswer to update\n * @return the ResponseEntity with status 200 (OK) and with body the updated studentQuestionAnswer, or with status 400 (Bad Request) if the studentQuestionAnswer is not valid,\n * or with status 500 (Internal Server Error) if the studentQuestionAnswer couldn't be updated\n */\n @PutMapping(\"courses/{courseId}/student-question-answers\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentQuestionAnswer> updateStudentQuestionAnswer(@PathVariable Long courseId, @RequestBody StudentQuestionAnswer studentQuestionAnswer) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n log.debug(\"REST request to update StudentQuestionAnswer : {}\", studentQuestionAnswer);\n if (studentQuestionAnswer.getId() == null) {\n throw new BadRequestAlertException(\"Invalid id\", ENTITY_NAME, \"idnull\");\n }\n courseRepository.findByIdElseThrow(courseId);\n Optional<StudentQuestionAnswer> optionalStudentQuestionAnswer = studentQuestionAnswerRepository.findById(studentQuestionAnswer.getId());\n if (optionalStudentQuestionAnswer.isEmpty()) {\n return ResponseEntity.notFound().build();\n }\n if (!optionalStudentQuestionAnswer.get().getQuestion().getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n if (mayUpdateOrDeleteStudentQuestionAnswer(optionalStudentQuestionAnswer.get(), user)) {\n StudentQuestionAnswer result = studentQuestionAnswerRepository.save(studentQuestionAnswer);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, studentQuestionAnswer.getId().toString())).body(result);\n }\n else {\n return forbidden();\n }\n }\n\n /**\n * GET /courses/{courseId}/question-answers/:id : get the \"id\" questionAnswer.\n *\n * @param courseId the id of the course the answer belongs to\n * @param id the id of the questionAnswer to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the questionAnswer, or with status 404 (Not Found)\n */\n @GetMapping(\"courses/{courseId}/student-question-answers/{id}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<StudentQuestionAnswer> getStudentQuestionAnswer(@PathVariable Long courseId, @PathVariable Long id) {\n log.debug(\"REST request to get StudentQuestionAnswer : {}\", id);\n User user = this.userRepository.getUserWithGroupsAndAuthorities();\n var course = courseRepository.findByIdElseThrow(courseId);\n if (!this.authorizationCheckService.isAtLeastStudentInCourse(course, user)) {\n return forbidden();\n }\n Optional<StudentQuestionAnswer> questionAnswer = studentQuestionAnswerRepository.findById(id);\n if (questionAnswer.isEmpty()) {\n return ResponseEntity.notFound().build();\n }\n if (!questionAnswer.get().getQuestion().getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n return ResponseUtil.wrapOrNotFound(questionAnswer);\n }\n\n /**\n * DELETE /courses/{courseId}/question-answers/:id : delete the \"id\" questionAnswer.\n *\n * @param courseId the id of the course the answer belongs to\n * @param id the id of the questionAnswer to delete\n * @return the ResponseEntity with status 200 (OK)\n */\n @DeleteMapping(\"courses/{courseId}/student-question-answers/{id}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<Void> deleteStudentQuestionAnswer(@PathVariable Long courseId, @PathVariable Long id) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n Optional<StudentQuestionAnswer> optionalStudentQuestionAnswer = studentQuestionAnswerRepository.findById(id);\n if (optionalStudentQuestionAnswer.isEmpty()) {\n return ResponseEntity.notFound().build();\n }\n courseRepository.findByIdElseThrow(courseId);\n StudentQuestionAnswer studentQuestionAnswer = optionalStudentQuestionAnswer.get();\n Course course = studentQuestionAnswer.getQuestion().getCourse();\n String entity = \"\";\n if (studentQuestionAnswer.getQuestion().getLecture() != null) {\n entity = \"lecture with id: \" + studentQuestionAnswer.getQuestion().getLecture().getId();\n }\n else if (studentQuestionAnswer.getQuestion().getExercise() != null) {\n entity = \"exercise with id: \" + studentQuestionAnswer.getQuestion().getExercise().getId();\n }\n if (course == null) {\n return ResponseEntity.badRequest().build();\n }\n if (!course.getId().equals(courseId)) {\n return forbidden();\n }\n if (mayUpdateOrDeleteStudentQuestionAnswer(studentQuestionAnswer, user)) {\n log.info(\"StudentQuestionAnswer deleted by {}. Answer: {} for {}\", user.getLogin(), studentQuestionAnswer.getAnswerText(), entity);\n studentQuestionAnswerRepository.deleteById(id);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString())).build();\n }\n else {\n return forbidden();\n }\n }\n\n /**\n * Check if user can update or delete StudentQuestionAnswer\n *\n * @param studentQuestionAnswer studentQuestionAnswer for which to check\n * @param user user for which to check\n * @return Boolean if StudentQuestionAnswer can updated or deleted\n */\n private boolean mayUpdateOrDeleteStudentQuestionAnswer(StudentQuestionAnswer studentQuestionAnswer, User user) {\n Course course = studentQuestionAnswer.getQuestion().getCourse();\n Boolean hasCourseTAAccess = authorizationCheckService.isAtLeastTeachingAssistantInCourse(course, user);\n Boolean isUserAuthor = user.getId().equals(studentQuestionAnswer.getAuthor().getId());\n return hasCourseTAAccess || isUserAuthor;\n }\n}\n" }, { "alpha_fraction": 0.7248358726501465, "alphanum_fraction": 0.7248358726501465, "avg_line_length": 49.77777862548828, "blob_id": "1d3c5a483cf1bda1d5ef96f277d286c4071a5b5c", "content_id": "b9bc349b1af38b265367b23669a29c2381b56007", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1828, "license_type": "permissive", "max_line_length": 139, "num_lines": 36, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/attachmentUnit.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SERVER_API_URL } from 'app/app.constants';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\ntype EntityResponseType = HttpResponse<AttachmentUnit>;\n\n@Injectable({\n providedIn: 'root',\n})\nexport class AttachmentUnitService {\n private resourceURL = SERVER_API_URL + 'api';\n\n constructor(private httpClient: HttpClient, private lectureUnitService: LectureUnitService) {}\n\n findById(attachmentUnitId: number, lectureId: number) {\n return this.httpClient\n .get<AttachmentUnit>(`${this.resourceURL}/lectures/${lectureId}/attachment-units/${attachmentUnitId}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.lectureUnitService.convertDateFromServerResponse(res)));\n }\n\n create(attachmentUnit: AttachmentUnit, lectureId: number): Observable<EntityResponseType> {\n return this.httpClient\n .post<AttachmentUnit>(`${this.resourceURL}/lectures/${lectureId}/attachment-units`, attachmentUnit, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.lectureUnitService.convertDateFromServerResponse(res)));\n }\n\n update(attachmentUnit: AttachmentUnit, lectureId: number): Observable<EntityResponseType> {\n return this.httpClient\n .put<AttachmentUnit>(`${this.resourceURL}/lectures/${lectureId}/attachment-units`, attachmentUnit, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.lectureUnitService.convertDateFromServerResponse(res)));\n }\n}\n" }, { "alpha_fraction": 0.592654287815094, "alphanum_fraction": 0.5979276299476624, "avg_line_length": 42.584678649902344, "blob_id": "65a152a2236ea29d2774abe9d720e4df78634749", "content_id": "f0b3f1dae7b17b879c9c7bb42711a5647b7460da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10809, "license_type": "permissive", "max_line_length": 153, "num_lines": 248, "path": "/src/test/javascript/spec/component/exam/manage/student-exams/student-exam-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { StudentExamDetailComponent } from 'app/exam/manage/student-exams/student-exam-detail.component';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { Course } from 'app/entities/course.model';\nimport { User } from 'app/core/user/user.model';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ArtemisDurationFromSecondsPipe } from 'app/shared/pipes/artemis-duration-from-seconds.pipe';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { StudentExamService } from 'app/exam/manage/student-exams/student-exam.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { HttpResponse } from '@angular/common/http';\nimport { of } from 'rxjs';\nimport { ActivatedRoute, convertToParamMap, Params } from '@angular/router';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { FontAwesomeTestingModule } from '@fortawesome/angular-fontawesome/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport * as chai from 'chai';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { MockTranslateValuesDirective } from '../../../course/course-scores/course-scores.component.spec';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { Exam } from 'app/entities/exam.model';\nimport * as moment from 'moment';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { StudentExamDetailTableRowComponent } from 'app/exam/manage/student-exams/student-exam-detail-table-row/student-exam-detail-table-row.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentExamDetailComponent', () => {\n let studentExamDetailComponentFixture: ComponentFixture<StudentExamDetailComponent>;\n let studentExamDetailComponent: StudentExamDetailComponent;\n let course: Course;\n let student: User;\n let studentExam: StudentExam;\n let studentExam2: StudentExam;\n let exercise: Exercise;\n let exam: Exam;\n let studentParticipation: StudentParticipation;\n let result: Result;\n\n let courseManagementService: any;\n let studentExamService: any;\n\n beforeEach(() => {\n course = { id: 1 };\n\n student = {\n guidedTourSettings: [],\n name: 'name',\n login: 'login',\n email: 'email',\n visibleRegistrationNumber: 'visibleRegistrationNumber',\n };\n\n exam = {\n course,\n id: 1,\n registeredUsers: [student],\n visibleDate: moment().add(120, 'seconds'),\n };\n\n result = { score: 40 };\n studentParticipation = new StudentParticipation(ParticipationType.STUDENT);\n studentParticipation.results = [result];\n\n exercise = new ModelingExercise(UMLDiagramType.ActivityDiagram, course, new ExerciseGroup());\n exercise.maxPoints = 100;\n exercise.studentParticipations = [studentParticipation];\n\n studentExam = {\n id: 1,\n workingTime: 3600,\n exam,\n user: student,\n exercises: [exercise],\n };\n studentExam2 = {\n id: 1,\n workingTime: 3600,\n exam,\n user: student,\n submitted: true,\n submissionDate: moment(),\n exercises: [exercise],\n };\n\n return TestBed.configureTestingModule({\n imports: [\n RouterTestingModule.withRoutes([]),\n ArtemisDataTableModule,\n NgbModule,\n NgxDatatableModule,\n FontAwesomeTestingModule,\n ReactiveFormsModule,\n TranslateModule.forRoot(),\n ],\n declarations: [\n StudentExamDetailComponent,\n MockComponent(AlertComponent),\n MockPipe(ArtemisDurationFromSecondsPipe),\n MockPipe(ArtemisDatePipe),\n MockTranslateValuesDirective,\n MockPipe(ArtemisTranslatePipe),\n StudentExamDetailTableRowComponent,\n ],\n providers: [\n MockProvider(StudentExamService, {\n updateWorkingTime: () => {\n return of(\n new HttpResponse({\n body: studentExam,\n status: 200,\n }),\n );\n },\n toggleSubmittedState: () => {\n return of(\n new HttpResponse({\n body: studentExam2,\n status: 200,\n }),\n );\n },\n }),\n MockProvider(CourseManagementService, {\n find: () => {\n return of(\n new HttpResponse({\n body: course,\n status: 200,\n }),\n );\n },\n }),\n MockPipe(ArtemisDurationFromSecondsPipe),\n MockProvider(JhiAlertService),\n MockDirective(JhiTranslateDirective),\n {\n provide: ActivatedRoute,\n useValue: {\n params: {\n subscribe: (fn: (value: Params) => void) =>\n fn({\n courseId: 1,\n }),\n },\n data: {\n subscribe: (fn: (value: any) => void) =>\n fn({\n studentExam,\n }),\n },\n snapshot: {\n paramMap: convertToParamMap({\n courseId: '1',\n }),\n url: [],\n },\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n studentExamDetailComponentFixture = TestBed.createComponent(StudentExamDetailComponent);\n studentExamDetailComponent = studentExamDetailComponentFixture.componentInstance;\n courseManagementService = TestBed.inject(CourseManagementService);\n studentExamService = TestBed.inject(StudentExamService);\n });\n });\n afterEach(() => {\n sinon.restore();\n });\n\n it('initialize', () => {\n const findCourseSpy = sinon.spy(courseManagementService, 'find');\n studentExamDetailComponentFixture.detectChanges();\n\n expect(findCourseSpy).to.have.been.calledOnce;\n expect(course.id).to.equal(1);\n expect(studentExamDetailComponent.workingTimeForm).to.not.be.null;\n expect(studentExamDetailComponent.achievedTotalPoints).to.equal(40);\n });\n\n it('should save working time', () => {\n const studentExamSpy = sinon.spy(studentExamService, 'updateWorkingTime');\n studentExamDetailComponentFixture.detectChanges();\n\n studentExamDetailComponent.saveWorkingTime();\n expect(studentExamSpy).to.have.been.calledOnce;\n expect(studentExamDetailComponent.isSavingWorkingTime).to.equal(false);\n expect(course.id).to.equal(1);\n expect(studentExamDetailComponent.workingTimeForm).to.not.be.null;\n expect(studentExamDetailComponent.achievedTotalPoints).to.equal(40);\n expect(studentExamDetailComponent.maxTotalPoints).to.equal(100);\n });\n\n it('should not increase points when save working time is called more than once', () => {\n const studentExamSpy = sinon.spy(studentExamService, 'updateWorkingTime');\n studentExamDetailComponentFixture.detectChanges();\n studentExamDetailComponent.saveWorkingTime();\n studentExamDetailComponent.saveWorkingTime();\n studentExamDetailComponent.saveWorkingTime();\n expect(studentExamSpy).to.have.been.calledThrice;\n expect(studentExamDetailComponent.isSavingWorkingTime).to.equal(false);\n expect(course.id).to.equal(1);\n expect(studentExamDetailComponent.workingTimeForm).to.not.be.null;\n expect(studentExamDetailComponent.achievedTotalPoints).to.equal(40);\n expect(studentExamDetailComponent.maxTotalPoints).to.equal(100);\n });\n\n it('should get examIsOver', () => {\n studentExamDetailComponent.studentExam = studentExam;\n studentExam.exam!.gracePeriod = 100;\n expect(studentExamDetailComponent.examIsOver()).to.equal(false);\n studentExam.exam!.endDate = moment().add(-20, 'seconds');\n expect(studentExamDetailComponent.examIsOver()).to.equal(false);\n studentExam.exam!.endDate = moment().add(-200, 'seconds');\n expect(studentExamDetailComponent.examIsOver()).to.equal(true);\n studentExam.exam = undefined;\n expect(studentExamDetailComponent.examIsOver()).to.equal(false);\n });\n\n it('should toggle to unsubmitted', () => {\n const toggleSubmittedStateSpy = sinon.spy(studentExamService, 'toggleSubmittedState');\n studentExamDetailComponentFixture.detectChanges();\n expect(studentExamDetailComponent.studentExam.submitted).to.equal(undefined);\n expect(studentExamDetailComponent.studentExam.submissionDate).to.equal(undefined);\n\n studentExamDetailComponent.toggle();\n\n expect(toggleSubmittedStateSpy).to.have.been.calledOnce;\n expect(studentExamDetailComponent.studentExam.submitted).to.equal(true);\n expect(studentExamDetailComponent.studentExam.submissionDate).to.not.equal(undefined);\n });\n});\n" }, { "alpha_fraction": 0.5850083827972412, "alphanum_fraction": 0.5908710360527039, "avg_line_length": 33.11428451538086, "blob_id": "ecbb0a7ad28aa3f8a7f7d3a33c496f88bc194030", "content_id": "be564de2f0eca2972434125289b62531e67726ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2388, "license_type": "permissive", "max_line_length": 142, "num_lines": 70, "path": "/src/main/webapp/app/overview/result-history/result-history.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { MIN_SCORE_GREEN, MIN_SCORE_ORANGE } from 'app/app.constants';\nimport { IconProp } from '@fortawesome/fontawesome-svg-core';\nimport { Result } from 'app/entities/result.model';\nimport { round } from 'app/shared/util/utils';\n\n// Modal -> Result details view\n@Component({\n selector: 'jhi-result-history',\n templateUrl: './result-history.component.html',\n styleUrls: ['./result-history.scss'],\n})\nexport class ResultHistoryComponent {\n readonly round = round;\n\n @Input() results: Result[];\n @Input() maxScore?: number;\n @Input() showPreviousDivider = false;\n\n /**\n * get string for icon if score bigger than 80\n * @param {Result} result\n * @return {string} icon\n */\n resultIcon(result: Result): IconProp {\n if (result.score && result.score >= MIN_SCORE_GREEN) {\n return 'check';\n } else {\n return 'times';\n }\n }\n\n /**\n * get colour class depending on score\n * @param {Result} result\n * @return {string}\n */\n resultClass(result: Result): string {\n if (result.score && result.score >= MIN_SCORE_GREEN) {\n return 'success';\n } else if (result.score && result.score >= MIN_SCORE_ORANGE) {\n return 'warning';\n } else {\n return 'danger';\n }\n }\n\n /**\n * return number of points from resultString\n * @param {Result} result\n * @return {number | null}\n * // TODO: document the implementation of this method --> it is not really obvious\n * // TODO: save the return value of this method in the result object (as temp variable) to avoid that this method is invoked all the time\n */\n absoluteResult(result: Result): number | null {\n if (!result.resultString) {\n return 0;\n }\n if (result.resultString && (result.resultString.indexOf('failed') !== -1 || result.resultString.indexOf('passed')) !== -1) {\n return null;\n }\n if (result.resultString.indexOf('of') === -1) {\n if (result.resultString.indexOf('points') === -1) {\n return 0;\n }\n return parseInt(result.resultString.slice(0, result.resultString.indexOf('points')), 10);\n }\n return parseInt(result.resultString.slice(0, result.resultString.indexOf('of')), 10);\n }\n}\n" }, { "alpha_fraction": 0.7930654883384705, "alphanum_fraction": 0.7930654883384705, "avg_line_length": 59.56666564941406, "blob_id": "d13cdec22956e6ed08fc386330c0eedb517ba035", "content_id": "632657f4f869623588b7892c947bc5944efdb714", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1817, "license_type": "permissive", "max_line_length": 137, "num_lines": 30, "path": "/src/main/webapp/app/course/learning-goals/learning-goal.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\nimport { LearningGoalFormComponent } from './learning-goal-form/learning-goal-form.component';\nimport { CreateLearningGoalComponent } from './create-learning-goal/create-learning-goal.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { EditLearningGoalComponent } from './edit-learning-goal/edit-learning-goal.component';\nimport { LearningGoalManagementComponent } from './learning-goal-management/learning-goal-management.component';\nimport { LearningGoalCardComponent } from 'app/course/learning-goals/learning-goal-card/learning-goal-card.component';\nimport { LearningGoalDetailModalComponent } from './learning-goal-detail-modal/learning-goal-detail-modal.component';\nimport { LearningGoalsPopoverComponent } from './learning-goals-popover/learning-goals-popover.component';\nimport { LearningGoalCourseDetailModalComponent } from './learning-goal-course-detail-modal/learning-goal-course-detail-modal.component';\n\n@NgModule({\n imports: [ArtemisSharedModule, ReactiveFormsModule, ArtemisSharedComponentModule, RouterModule],\n declarations: [\n LearningGoalFormComponent,\n CreateLearningGoalComponent,\n EditLearningGoalComponent,\n LearningGoalManagementComponent,\n LearningGoalCardComponent,\n LearningGoalDetailModalComponent,\n LearningGoalsPopoverComponent,\n LearningGoalCourseDetailModalComponent,\n ],\n exports: [LearningGoalCardComponent, LearningGoalsPopoverComponent],\n entryComponents: [LearningGoalDetailModalComponent],\n})\nexport class ArtemisLearningGoalsModule {}\n" }, { "alpha_fraction": 0.6144716739654541, "alphanum_fraction": 0.6216181516647339, "avg_line_length": 45.922157287597656, "blob_id": "350fe9d100cd59ffa542429f766bcf6467ccf917", "content_id": "6f5be6514757c8807a5eb77f4c9b51a37874c65b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7836, "license_type": "permissive", "max_line_length": 148, "num_lines": 167, "path": "/src/main/webapp/app/overview/course-score-calculation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Result } from 'app/entities/result.model';\nimport { Course } from 'app/entities/course.model';\nimport { Exercise, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { round } from 'app/shared/util/utils';\n\nexport const ABSOLUTE_SCORE = 'absoluteScore';\nexport const RELATIVE_SCORE = 'relativeScore';\nexport const MAX_POINTS = 'maxPoints';\nexport const PRESENTATION_SCORE = 'presentationScore';\nexport const REACHABLE_POINTS = 'reachableScore';\nexport const CURRENT_RELATIVE_SCORE = 'currentRelativeScore';\n\n@Injectable({ providedIn: 'root' })\nexport class CourseScoreCalculationService {\n private SCORE_NORMALIZATION_VALUE = 0.01;\n private courses: Course[] = [];\n\n constructor() {}\n\n calculateTotalScores(courseExercises: Exercise[]): Map<string, number> {\n const scores = new Map<string, number>();\n let pointsAchievedByStudentInCourse = 0.0;\n let maxPointsInCourse = 0;\n let reachableMaxPointsInCourse = 0;\n let presentationScore = 0;\n for (const exercise of courseExercises) {\n const isExerciseFinished = !exercise.dueDate || exercise.dueDate.isBefore(moment());\n const isAssessmentOver = !exercise.assessmentDueDate || exercise.assessmentDueDate.isBefore(moment());\n const isExerciseIncluded = exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED;\n\n if (isExerciseFinished && isExerciseIncluded) {\n const maxPointsReachableInExercise = exercise.maxPoints!;\n if (exercise.includedInOverallScore === IncludedInOverallScore.INCLUDED_COMPLETELY) {\n maxPointsInCourse += maxPointsReachableInExercise;\n // points are reachable if the exercise is released and the assessment is over --> It was possible for the student to get points\n if (isAssessmentOver) {\n reachableMaxPointsInCourse += maxPointsReachableInExercise;\n }\n }\n const participation = this.getParticipationForExercise(exercise);\n if (participation) {\n const result = this.getResultForParticipation(participation, exercise.dueDate!);\n if (result && result.rated) {\n let score = result.score;\n // this should cover score is undefined and score is null\n if (score == undefined) {\n score = 0;\n }\n // Note: It is important that we round on the individual exercise level first and then sum up.\n // This is necessary so that the student arrives at the same overall result when doing his own recalculation.\n // Let's assume that the student achieved 1.05 points in each of 5 exercises.\n // In the client, these are now displayed rounded as 1.1 points.\n // If the student adds up the displayed points, he gets a total of 5.5 points.\n // In order to get the same total result as the student, we have to round before summing.\n pointsAchievedByStudentInCourse += round(score * this.SCORE_NORMALIZATION_VALUE * maxPointsReachableInExercise, 1);\n }\n presentationScore += participation.presentationScore ? participation.presentationScore : 0;\n }\n }\n }\n scores.set(ABSOLUTE_SCORE, round(pointsAchievedByStudentInCourse, 1));\n if (maxPointsInCourse > 0) {\n scores.set(RELATIVE_SCORE, round((pointsAchievedByStudentInCourse / maxPointsInCourse) * 100, 1));\n } else {\n scores.set(RELATIVE_SCORE, 0);\n }\n if (reachableMaxPointsInCourse > 0) {\n scores.set(CURRENT_RELATIVE_SCORE, round((pointsAchievedByStudentInCourse / reachableMaxPointsInCourse) * 100, 1));\n } else {\n scores.set(CURRENT_RELATIVE_SCORE, 0);\n }\n scores.set(MAX_POINTS, maxPointsInCourse);\n scores.set(PRESENTATION_SCORE, presentationScore);\n scores.set(REACHABLE_POINTS, reachableMaxPointsInCourse);\n return scores;\n }\n\n updateCourse(course: Course) {\n // filter out the old course object with the same id\n this.courses = this.courses.filter((existingCourses) => existingCourses.id !== existingCourses.id);\n this.courses.push(course);\n }\n\n setCourses(courses: Course[]) {\n this.courses = courses;\n }\n\n getCourse(courseId: number) {\n return this.courses.find((course) => course.id === courseId);\n }\n\n getParticipationForExercise(exercise: Exercise) {\n if (exercise.studentParticipations != undefined && exercise.studentParticipations.length > 0) {\n const exerciseParticipation: StudentParticipation = exercise.studentParticipations[0];\n return CourseScoreCalculationService.convertDateForParticipationFromServer(exerciseParticipation);\n }\n }\n\n getResultForParticipation(participation: Participation | undefined, dueDate: Moment) {\n if (!participation) {\n return undefined;\n }\n const results = participation.results;\n const resultsArray: Result[] = [];\n let chosenResult: Result;\n\n if (results) {\n for (let i = 0; i < results.length; i++) {\n resultsArray.push(CourseScoreCalculationService.convertDateForResultFromServer(results[i]));\n }\n\n if (resultsArray.length <= 0) {\n chosenResult = new Result();\n chosenResult.score = 0;\n return chosenResult;\n }\n\n const ratedResults = resultsArray.filter((el) => el.rated);\n\n if (ratedResults.length === 1) {\n return ratedResults[0];\n }\n\n // sorting in descending order to have the last result at the beginning\n resultsArray.sort((result1, result2): number => {\n if (result1.completionDate! > result2.completionDate!) {\n return -1;\n }\n if (result1.completionDate! < result2.completionDate!) {\n return 1;\n }\n return 0;\n });\n\n const gracePeriodInSeconds = 10;\n if (dueDate == undefined || dueDate.add(gracePeriodInSeconds, 'seconds') >= resultsArray[0].completionDate!) {\n // find the first result that is before the due date\n chosenResult = resultsArray[0];\n } else if (dueDate.add(gracePeriodInSeconds, 'seconds') < resultsArray[0].completionDate!) {\n chosenResult = new Result();\n chosenResult.score = 0;\n } else {\n chosenResult = resultsArray[resultsArray.length - 1];\n }\n } else {\n chosenResult = new Result();\n chosenResult.score = 0;\n }\n\n return chosenResult;\n }\n\n private static convertDateForResultFromServer(result: Result): Result {\n result.completionDate = result.completionDate ? moment(result.completionDate) : undefined;\n return result;\n }\n\n private static convertDateForParticipationFromServer(participation: Participation): Participation {\n participation.initializationDate = participation.initializationDate ? moment(participation.initializationDate) : undefined;\n return participation;\n }\n}\n" }, { "alpha_fraction": 0.7215619683265686, "alphanum_fraction": 0.7215619683265686, "avg_line_length": 28.450000762939453, "blob_id": "e89aa6cd9b16233833331d2b3f7e13b6d7c322b2", "content_id": "143d38124d3b3e4ae7e9241854391a7369cc08e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 589, "license_type": "permissive", "max_line_length": 58, "num_lines": 20, "path": "/src/main/webapp/app/entities/feedback-conflict.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { Moment } from 'moment';\n\nexport enum FeedbackConflictType {\n INCONSISTENT_COMMENT = 'INCONSISTENT_COMMENT',\n INCONSISTENT_SCORE = 'INCONSISTENT_SCORE',\n INCONSISTENT_FEEDBACK = 'INCONSISTENT_FEEDBACK',\n}\n\nexport class FeedbackConflict implements BaseEntity {\n public id?: number;\n public conflict?: boolean;\n public conflictingFeedbackId?: number;\n public createdAt?: Moment;\n public solvedAt?: Moment;\n public type?: FeedbackConflictType;\n public discard?: boolean;\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.6583850979804993, "alphanum_fraction": 0.6583850979804993, "avg_line_length": 33.5, "blob_id": "07921fdf101a61f687c8433a4187489fc8f5e15e", "content_id": "e640743dcf9670139190c23424fe2f3f90a22e6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 966, "license_type": "permissive", "max_line_length": 103, "num_lines": 28, "path": "/src/main/webapp/app/exercises/shared/mode-picker/mode-picker.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { Exercise, ExerciseMode } from 'app/entities/exercise.model';\n\n@Component({\n selector: 'jhi-mode-picker',\n templateUrl: './mode-picker.component.html',\n styles: ['.btn.disabled { pointer-events: none }', '.btn-group.disabled { cursor: not-allowed; }'],\n})\nexport class ModePickerComponent {\n readonly INDIVIDUAL = ExerciseMode.INDIVIDUAL;\n readonly TEAM = ExerciseMode.TEAM;\n\n @Input() exercise: Exercise;\n @Input() disabled = false;\n\n @Output() ngModelChange = new EventEmitter<ExerciseMode>();\n\n /**\n * Set the mode and emit the changes to the parent component to notice changes\n * @param mode chosen exercise solving mode of type {ExerciseMode}\n */\n setMode(mode: ExerciseMode) {\n if (!this.disabled && mode !== this.exercise.mode) {\n this.exercise.mode = mode;\n this.ngModelChange.emit(mode);\n }\n }\n}\n" }, { "alpha_fraction": 0.6696997284889221, "alphanum_fraction": 0.6696997284889221, "avg_line_length": 43.85714340209961, "blob_id": "f0c4d69f7cf18d3a8c2e9caee14ded681ea24876", "content_id": "50342b3697c74d67c4664a7a767c362301373e0b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2198, "license_type": "permissive", "max_line_length": 161, "num_lines": 49, "path": "/src/test/javascript/spec/component/assessment-dashboard/second-correction-enable-button.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { Router } from '@angular/router';\nimport { stub } from 'sinon';\n\nimport { SecondCorrectionEnableButtonComponent } from 'app/exercises/shared/dashboards/tutor/second-correction-button/second-correction-enable-button.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('SecondCorrectionEnableButtonComponent', () => {\n let comp: SecondCorrectionEnableButtonComponent;\n let fixture: ComponentFixture<SecondCorrectionEnableButtonComponent>;\n const router = new MockRouter();\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, TranslateModule.forRoot()],\n declarations: [SecondCorrectionEnableButtonComponent],\n providers: [\n JhiLanguageHelper,\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: Router, useValue: router },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(SecondCorrectionEnableButtonComponent);\n comp = fixture.componentInstance;\n fixture.detectChanges();\n });\n });\n\n it('test call', () => {\n const stubEmit = stub(comp.ngModelChange, 'emit');\n comp.triggerSecondCorrectionButton();\n expect(stubEmit).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.7946699261665344, "alphanum_fraction": 0.7946699261665344, "avg_line_length": 61.30188751220703, "blob_id": "a144df380ca89977da6b9bb9206156c8495af33c", "content_id": "04a8c1b3ebaccb6f4d2417bfa88d001ef7d2afbd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6604, "license_type": "permissive", "max_line_length": 147, "num_lines": 106, "path": "/src/main/webapp/app/course/manage/course-management.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { RouterModule } from '@angular/router';\nimport { ArtemisFileUploadExerciseManagementModule } from 'app/exercises/file-upload/manage/file-upload-exercise-management.module';\nimport { CourseExerciseCardComponent } from 'app/course/manage/course-exercise-card.component';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\nimport { ArtemisColorSelectorModule } from 'app/shared/color-selector/color-selector.module';\nimport { ImageCropperModule } from 'ngx-image-cropper';\nimport { MomentModule } from 'ngx-moment';\nimport { TagInputModule } from 'ngx-chips';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { CourseManagementExercisesComponent } from 'app/course/manage/course-management-exercises.component';\nimport { CourseDetailComponent } from 'app/course/manage/course-detail.component';\nimport { CourseUpdateComponent } from 'app/course/manage/course-update.component';\nimport { courseManagementState } from 'app/course/manage/course-management.route';\nimport { CourseManagementComponent } from 'app/course/manage/course-management.component';\nimport { OrionModule } from 'app/shared/orion/orion.module';\nimport { ArtemisProgrammingExerciseManagementModule } from 'app/exercises/programming/manage/programming-exercise-management.module';\nimport { ArtemisQuizManagementModule } from 'app/exercises/quiz/manage/quiz-management.module';\nimport { ArtemisExerciseModule } from 'app/exercises/shared/exercise/exercise.module';\nimport { ArtemisLectureModule } from 'app/lecture/lecture.module';\nimport { ArtemisTextExerciseManagementModule } from 'app/exercises/text/manage/text-exercise-management.module';\nimport { ArtemisDashboardsModule } from 'app/shared/dashboards/dashboards.module';\nimport { ArtemisParticipationModule } from 'app/exercises/shared/participation/participation.module';\nimport { ArtemisExerciseHintManagementModule } from 'app/exercises/shared/exercise-hint/manage/exercise-hint-management.module';\nimport { ArtemisModelingExerciseManagementModule } from 'app/exercises/modeling/manage/modeling-exercise-management.module';\nimport { ArtemisCourseScoresModule } from 'app/course/course-scores/course-scores.module';\nimport { ArtemisExerciseScoresModule } from 'app/exercises/shared/exercise-scores/exercise-scores.module';\nimport { ArtemisComplaintsForTutorModule } from 'app/complaints/complaints-for-tutor/complaints-for-tutor.module';\nimport { ArtemisFileUploadAssessmentModule } from 'app/exercises/file-upload/assess/file-upload-assessment.module';\nimport { ArtemisModelingAssessmentEditorModule } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.module';\nimport { CourseGroupComponent } from 'app/course/manage/course-group.component';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { ArtemisModelingExerciseModule } from 'app/exercises/modeling/manage/modeling-exercise.module';\nimport { ArtemisTextExerciseModule } from 'app/exercises/text/manage/text-exercise/text-exercise.module';\nimport { ArtemisProgrammingExerciseModule } from 'app/exercises/programming/shared/programming-exercise.module';\nimport { ArtemisListOfComplaintsModule } from 'app/complaints/list-of-complaints/list-of-complaints.module';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { ArtemisCourseQuestionsModule } from 'app/course/course-questions/course-questions.module';\nimport { ArtemisSharedPipesModule } from 'app/shared/pipes/shared-pipes.module';\nimport { ArtemisLearningGoalsModule } from 'app/course/learning-goals/learning-goal.module';\nimport { CourseManagementCardComponent } from 'app/course/manage/overview/course-management-card.component';\nimport { CourseManagementExerciseRowComponent } from './overview/course-management-exercise-row.component';\nimport { CourseManagementOverviewStatisticsComponent } from './overview/course-management-overview-statistics.component';\nimport { ArtemisTutorParticipationGraphModule } from 'app/shared/dashboards/tutor-participation-graph/tutor-participation-graph.module';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\nimport { ArtemisCourseParticipantScoresModule } from 'app/course/course-participant-scores/course-participant-scores.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { CourseManagementStatisticsComponent } from 'app/course/manage/course-management-statistics.component';\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n RouterModule.forChild(courseManagementState),\n FormDateTimePickerModule,\n ReactiveFormsModule,\n ImageCropperModule,\n OrionModule,\n MomentModule,\n TagInputModule,\n ArtemisExerciseModule,\n ArtemisLectureModule,\n ArtemisCourseScoresModule,\n ArtemisLearningGoalsModule,\n ArtemisExerciseScoresModule,\n ArtemisProgrammingExerciseManagementModule,\n ArtemisFileUploadExerciseManagementModule,\n ArtemisQuizManagementModule,\n ArtemisTextExerciseManagementModule,\n ArtemisModelingExerciseManagementModule,\n ArtemisProgrammingExerciseModule,\n ArtemisTextExerciseModule,\n ArtemisModelingExerciseModule,\n ArtemisColorSelectorModule,\n ArtemisDashboardsModule,\n ArtemisExerciseHintManagementModule,\n ArtemisParticipationModule,\n ArtemisComplaintsForTutorModule,\n ArtemisListOfComplaintsModule,\n ArtemisFileUploadAssessmentModule,\n ArtemisModelingAssessmentEditorModule,\n NgxDatatableModule,\n ArtemisDataTableModule,\n ArtemisAssessmentSharedModule,\n ArtemisCourseQuestionsModule,\n ArtemisSharedPipesModule,\n ArtemisTutorParticipationGraphModule,\n ArtemisMarkdownModule,\n ArtemisCourseParticipantScoresModule,\n ArtemisSharedComponentModule,\n ],\n declarations: [\n CourseManagementComponent,\n CourseDetailComponent,\n CourseUpdateComponent,\n CourseExerciseCardComponent,\n CourseManagementExercisesComponent,\n CourseManagementStatisticsComponent,\n CourseGroupComponent,\n CourseManagementCardComponent,\n CourseManagementExerciseRowComponent,\n CourseManagementOverviewStatisticsComponent,\n ],\n})\nexport class ArtemisCourseManagementModule {}\n" }, { "alpha_fraction": 0.7569915056228638, "alphanum_fraction": 0.7578982710838318, "avg_line_length": 57.53072738647461, "blob_id": "c17b72f3a28151de59fdaed14e89ea57baf138eb", "content_id": "6be0ebd7341cdac96be652a30b03bfb03fb70fa3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 20954, "license_type": "permissive", "max_line_length": 177, "num_lines": 358, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseImportService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport static de.tum.in.www1.artemis.config.Constants.*;\n\nimport java.io.IOException;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.data.util.Pair;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.BuildPlanType;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseMode;\nimport de.tum.in.www1.artemis.domain.enumeration.RepositoryType;\nimport de.tum.in.www1.artemis.domain.participation.SolutionProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.domain.participation.TemplateProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.exception.ContinuousIntegrationException;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.FileService;\nimport de.tum.in.www1.artemis.service.StaticCodeAnalysisService;\nimport de.tum.in.www1.artemis.service.connectors.ContinuousIntegrationService;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.connectors.VersionControlService;\n\n@Service\npublic class ProgrammingExerciseImportService {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseImportService.class);\n\n private final ExerciseHintRepository exerciseHintRepository;\n\n private final Optional<VersionControlService> versionControlService;\n\n private final Optional<ContinuousIntegrationService> continuousIntegrationService;\n\n private final ProgrammingExerciseParticipationService programmingExerciseParticipationService;\n\n private final ProgrammingExerciseTestCaseRepository programmingExerciseTestCaseRepository;\n\n private final StaticCodeAnalysisCategoryRepository staticCodeAnalysisCategoryRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final ProgrammingExerciseService programmingExerciseService;\n\n private final GitService gitService;\n\n private final FileService fileService;\n\n private final UserRepository userRepository;\n\n private final StaticCodeAnalysisService staticCodeAnalysisService;\n\n public ProgrammingExerciseImportService(ExerciseHintRepository exerciseHintRepository, Optional<VersionControlService> versionControlService,\n Optional<ContinuousIntegrationService> continuousIntegrationService, ProgrammingExerciseParticipationService programmingExerciseParticipationService,\n ProgrammingExerciseTestCaseRepository programmingExerciseTestCaseRepository, StaticCodeAnalysisCategoryRepository staticCodeAnalysisCategoryRepository,\n ProgrammingExerciseRepository programmingExerciseRepository, ProgrammingExerciseService programmingExerciseService, GitService gitService, FileService fileService,\n UserRepository userRepository, StaticCodeAnalysisService staticCodeAnalysisService) {\n this.exerciseHintRepository = exerciseHintRepository;\n this.versionControlService = versionControlService;\n this.continuousIntegrationService = continuousIntegrationService;\n this.programmingExerciseParticipationService = programmingExerciseParticipationService;\n this.programmingExerciseTestCaseRepository = programmingExerciseTestCaseRepository;\n this.staticCodeAnalysisCategoryRepository = staticCodeAnalysisCategoryRepository;\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.programmingExerciseService = programmingExerciseService;\n this.gitService = gitService;\n this.fileService = fileService;\n this.userRepository = userRepository;\n this.staticCodeAnalysisService = staticCodeAnalysisService;\n }\n\n /**\n * Imports a programming exercise creating a new entity, copying all basic values and saving it in the database.\n * All basic include everything except for repositories, or build plans on a remote version control server, or\n * continuous integration server. <br>\n * There are however, a couple of things that will never get copied:\n * <ul>\n * <li>The ID</li>\n * <li>The template and solution participation</li>\n * <li>The number of complaints, assessments and more feedback requests</li>\n * <li>The tutor/student participations</li>\n * <li>The questions asked by students</li>\n * <li>The example submissions</li>\n * </ul>\n *\n * @param templateExercise The template exercise which should get imported\n * @param newExercise The new exercise already containing values which should not get copied, i.e. overwritten\n * @return The newly created exercise\n */\n @Transactional // ok because we create many objects in a rather complex way and need a rollback in case of exceptions\n public ProgrammingExercise importProgrammingExerciseBasis(final ProgrammingExercise templateExercise, final ProgrammingExercise newExercise) {\n // Set values we don't want to copy to null\n setupExerciseForImport(newExercise);\n\n programmingExerciseParticipationService.setupInitialSolutionParticipation(newExercise);\n programmingExerciseParticipationService.setupInitalTemplateParticipation(newExercise);\n setupTestRepository(newExercise);\n programmingExerciseService.initParticipations(newExercise);\n\n // Hints, test cases and static code analysis categories\n exerciseHintRepository.copyExerciseHints(templateExercise, newExercise);\n programmingExerciseRepository.save(newExercise);\n importTestCases(templateExercise, newExercise);\n\n // Copy or create SCA categories\n if (Boolean.TRUE.equals(newExercise.isStaticCodeAnalysisEnabled() && Boolean.TRUE.equals(templateExercise.isStaticCodeAnalysisEnabled()))) {\n importStaticCodeAnalysisCategories(templateExercise, newExercise);\n }\n else if (Boolean.TRUE.equals(newExercise.isStaticCodeAnalysisEnabled()) && !Boolean.TRUE.equals(templateExercise.isStaticCodeAnalysisEnabled())) {\n staticCodeAnalysisService.createDefaultCategories(newExercise);\n }\n\n // An exam exercise can only be in individual mode\n if (!newExercise.isCourseExercise()) {\n newExercise.setMode(ExerciseMode.INDIVIDUAL);\n newExercise.setTeamAssignmentConfig(null);\n }\n\n return newExercise;\n }\n\n /**\n * Import all base repositories from one exercise. These include the template, the solution and the test\n * repository. Participation repositories from students or tutors will not get copied!\n *\n * @param templateExercise The template exercise having a reference to all base repositories\n * @param newExercise The new exercise without any repositories\n */\n public void importRepositories(final ProgrammingExercise templateExercise, final ProgrammingExercise newExercise) {\n final var targetProjectKey = newExercise.getProjectKey();\n final var sourceProjectKey = templateExercise.getProjectKey();\n\n // First, create a new project for our imported exercise\n versionControlService.get().createProjectForExercise(newExercise);\n // Copy all repositories\n final var reposToCopy = List.of(Pair.of(RepositoryType.TEMPLATE, templateExercise.getTemplateRepositoryName()),\n Pair.of(RepositoryType.SOLUTION, templateExercise.getSolutionRepositoryName()), Pair.of(RepositoryType.TESTS, templateExercise.getTestRepositoryName()));\n\n reposToCopy.forEach(repo -> versionControlService.get().copyRepository(sourceProjectKey, repo.getSecond(), targetProjectKey, repo.getFirst().getName()));\n\n // Unprotect the master branch of the template exercise repo.\n versionControlService.get().unprotectBranch(newExercise.getVcsTemplateRepositoryUrl(), \"master\");\n\n // Add the necessary hooks notifying Artemis about changes after commits have been pushed\n versionControlService.get().addWebHooksForExercise(newExercise);\n\n try {\n // Adjust placeholders that were replaced during creation of template exercise\n adjustProjectNames(templateExercise, newExercise);\n }\n catch (GitAPIException | IOException | InterruptedException e) {\n log.error(\"Error during adjustment of placeholders of ProgrammingExercise {}\", newExercise.getTitle(), e);\n }\n }\n\n /**\n * Imports all base build plans for an exercise. These include the template and the solution build plan, <b>not</b>\n * any participation plans!\n *\n * @param templateExercise The template exercise which plans should get copied\n * @param newExercise The new exercise to which all plans should get copied\n */\n public void importBuildPlans(final ProgrammingExercise templateExercise, final ProgrammingExercise newExercise) {\n final var templateParticipation = newExercise.getTemplateParticipation();\n final var solutionParticipation = newExercise.getSolutionParticipation();\n final var targetExerciseProjectKey = newExercise.getProjectKey();\n\n // Clone all build plans, enable them and setup the initial participations, i.e. setting the correct repo URLs and\n // running the plan for the first time\n cloneAndEnableAllBuildPlans(templateExercise, newExercise);\n\n updatePlanRepositoriesInBuildPlans(newExercise, templateParticipation, solutionParticipation, targetExerciseProjectKey, templateExercise.getTemplateRepositoryUrl(),\n templateExercise.getSolutionRepositoryUrl(), templateExercise.getTestRepositoryUrl());\n\n try {\n continuousIntegrationService.get().triggerBuild(templateParticipation);\n continuousIntegrationService.get().triggerBuild(solutionParticipation);\n }\n catch (ContinuousIntegrationException e) {\n log.error(\"Unable to trigger imported build plans\", e);\n throw e;\n }\n }\n\n private void updatePlanRepositoriesInBuildPlans(ProgrammingExercise newExercise, TemplateProgrammingExerciseParticipation templateParticipation,\n SolutionProgrammingExerciseParticipation solutionParticipation, String targetExerciseProjectKey, String oldExerciseRepoUrl, String oldSolutionRepoUrl,\n String oldTestRepoUrl) {\n // update 2 repositories for the template (BASE) build plan --> adapt the triggers so that only the assignment repo (and not the tests repo) will trigger the BASE build\n // plan\n continuousIntegrationService.get().updatePlanRepository(targetExerciseProjectKey, templateParticipation.getBuildPlanId(), ASSIGNMENT_REPO_NAME, targetExerciseProjectKey,\n newExercise.getTemplateRepositoryUrl(), oldExerciseRepoUrl, Optional.of(List.of(ASSIGNMENT_REPO_NAME)));\n continuousIntegrationService.get().updatePlanRepository(targetExerciseProjectKey, templateParticipation.getBuildPlanId(), TEST_REPO_NAME, targetExerciseProjectKey,\n newExercise.getTestRepositoryUrl(), oldTestRepoUrl, Optional.empty());\n\n // update 2 repositories for the solution (SOLUTION) build plan\n continuousIntegrationService.get().updatePlanRepository(targetExerciseProjectKey, solutionParticipation.getBuildPlanId(), ASSIGNMENT_REPO_NAME, targetExerciseProjectKey,\n newExercise.getSolutionRepositoryUrl(), oldSolutionRepoUrl, Optional.empty());\n continuousIntegrationService.get().updatePlanRepository(targetExerciseProjectKey, solutionParticipation.getBuildPlanId(), TEST_REPO_NAME, targetExerciseProjectKey,\n newExercise.getTestRepositoryUrl(), oldTestRepoUrl, Optional.empty());\n }\n\n private void cloneAndEnableAllBuildPlans(ProgrammingExercise templateExercise, ProgrammingExercise newExercise) {\n final var templateParticipation = newExercise.getTemplateParticipation();\n final var solutionParticipation = newExercise.getSolutionParticipation();\n final var targetExerciseProjectKey = newExercise.getProjectKey();\n final var templatePlanName = BuildPlanType.TEMPLATE.getName();\n final var solutionPlanName = BuildPlanType.SOLUTION.getName();\n final var templateKey = templateExercise.getProjectKey();\n final var targetKey = newExercise.getProjectKey();\n final var targetName = newExercise.getCourseViaExerciseGroupOrCourseMember().getShortName().toUpperCase() + \" \" + newExercise.getTitle();\n continuousIntegrationService.get().createProjectForExercise(newExercise);\n continuousIntegrationService.get().copyBuildPlan(templateKey, templatePlanName, targetKey, targetName, templatePlanName, false);\n continuousIntegrationService.get().copyBuildPlan(templateKey, solutionPlanName, targetKey, targetName, solutionPlanName, true);\n continuousIntegrationService.get().givePlanPermissions(newExercise, templatePlanName);\n continuousIntegrationService.get().givePlanPermissions(newExercise, solutionPlanName);\n programmingExerciseService.giveCIProjectPermissions(newExercise);\n continuousIntegrationService.get().enablePlan(targetExerciseProjectKey, templateParticipation.getBuildPlanId());\n continuousIntegrationService.get().enablePlan(targetExerciseProjectKey, solutionParticipation.getBuildPlanId());\n }\n\n /**\n * Copied test cases from one exercise to another. The test cases will get new IDs, thus being saved as a new entity.\n * The remaining contents stay the same, especially the weights.\n *\n * @param templateExercise The template exercise which test cases should get copied\n * @param targetExercise The new exercise to which all test cases should get copied to\n */\n private void importTestCases(final ProgrammingExercise templateExercise, final ProgrammingExercise targetExercise) {\n targetExercise.setTestCases(templateExercise.getTestCases().stream().map(testCase -> {\n final var copy = new ProgrammingExerciseTestCase();\n\n // Copy everything except for the referenced exercise\n copy.setActive(testCase.isActive());\n copy.setVisibility(testCase.getVisibility());\n copy.setTestName(testCase.getTestName());\n copy.setWeight(testCase.getWeight());\n copy.setBonusMultiplier(testCase.getBonusMultiplier());\n copy.setBonusPoints(testCase.getBonusPoints());\n copy.setExercise(targetExercise);\n programmingExerciseTestCaseRepository.save(copy);\n return copy;\n }).collect(Collectors.toSet()));\n }\n\n /**\n * Copies static code analysis categories from one exercise to another by creating new entities and copying the\n * appropriate fields.\n *\n * @param templateExercise with static code analysis categories which should get copied\n * @param targetExercise for which static code analysis categories will be copied\n */\n private void importStaticCodeAnalysisCategories(final ProgrammingExercise templateExercise, final ProgrammingExercise targetExercise) {\n targetExercise.setStaticCodeAnalysisCategories(templateExercise.getStaticCodeAnalysisCategories().stream().map(originalCategory -> {\n var categoryCopy = new StaticCodeAnalysisCategory();\n categoryCopy.setName(originalCategory.getName());\n categoryCopy.setPenalty(originalCategory.getPenalty());\n categoryCopy.setMaxPenalty(originalCategory.getMaxPenalty());\n categoryCopy.setState(originalCategory.getState());\n categoryCopy.setProgrammingExercise(targetExercise);\n\n staticCodeAnalysisCategoryRepository.save(categoryCopy);\n return categoryCopy;\n }).collect(Collectors.toSet()));\n }\n\n /**\n * Sets up a new exercise for importing it by setting all values, that should either never get imported, or\n * for which we should create new entities (e.g. test cases) to null. This ensures that we do not copy\n * anything by accident.\n *\n * @param newExercise the new exercises that should be created during import\n */\n private void setupExerciseForImport(ProgrammingExercise newExercise) {\n newExercise.setId(null);\n newExercise.setTemplateParticipation(null);\n newExercise.setSolutionParticipation(null);\n newExercise.setExerciseHints(null);\n newExercise.setTestCases(null);\n newExercise.setStaticCodeAnalysisCategories(null);\n newExercise.setAttachments(null);\n newExercise.setNumberOfMoreFeedbackRequests(null);\n newExercise.setNumberOfComplaints(null);\n newExercise.setTotalNumberOfAssessments(null);\n newExercise.setTutorParticipations(null);\n newExercise.setExampleSubmissions(null);\n newExercise.setStudentQuestions(null);\n newExercise.setStudentParticipations(null);\n\n if (newExercise.isTeamMode()) {\n newExercise.getTeamAssignmentConfig().setId(null);\n }\n }\n\n /**\n * Sets up the test repository for a new exercise by setting the repository URL. This does not create the actual\n * repository on the version control server!\n *\n * @param newExercise the new exercises that should be created during import\n */\n private void setupTestRepository(ProgrammingExercise newExercise) {\n final var testRepoName = newExercise.generateRepositoryName(RepositoryType.TESTS);\n newExercise.setTestRepositoryUrl(versionControlService.get().getCloneRepositoryUrl(newExercise.getProjectKey(), testRepoName).toString());\n }\n\n /**\n * Adjust project names in imported exercise for TEST, BASE and SOLUTION repositories.\n * Replace values inserted in {@link ProgrammingExerciseService#replacePlaceholders(ProgrammingExercise, Repository)}.\n * @param templateExercise the exercise from which the values that should be replaced are extracted\n * @param newExercise the exercise from which the values that should be inserted are extracted\n * @throws GitAPIException If the checkout/push of one repository fails\n * @throws InterruptedException If the checkout of one repository fails\n * @throws IOException If the values in the files could not be replaced\n */\n private void adjustProjectNames(ProgrammingExercise templateExercise, ProgrammingExercise newExercise) throws GitAPIException, InterruptedException, IOException {\n final var projectKey = newExercise.getProjectKey();\n\n Map<String, String> replacements = new HashMap<>();\n\n // Used in pom.xml\n replacements.put(\"<artifactId>\" + templateExercise.getTitle().replaceAll(\" \", \"-\"), \"<artifactId>\" + newExercise.getTitle().replaceAll(\" \", \"-\"));\n\n // Used in .project\n replacements.put(\"<name>\" + templateExercise.getTitle(), \"<name>\" + newExercise.getTitle());\n\n final var user = userRepository.getUser();\n\n adjustProjectName(replacements, projectKey, newExercise.generateRepositoryName(RepositoryType.TEMPLATE), user);\n adjustProjectName(replacements, projectKey, newExercise.generateRepositoryName(RepositoryType.TESTS), user);\n adjustProjectName(replacements, projectKey, newExercise.generateRepositoryName(RepositoryType.SOLUTION), user);\n }\n\n /**\n * Adjust project names in imported exercise for specific repository.\n * Replace values inserted in {@link ProgrammingExerciseService#replacePlaceholders(ProgrammingExercise, Repository)}.\n * @param replacements the replacements that should be applied\n * @param projectKey the project key of the new exercise\n * @param repositoryName the name of the repository that should be adjusted\n * @param user the user which performed the action (used as Git author)\n * @throws GitAPIException If the checkout/push of one repository fails\n * @throws InterruptedException If the checkout of one repository fails\n * @throws IOException If the values in the files could not be replaced\n */\n private void adjustProjectName(Map<String, String> replacements, String projectKey, String repositoryName, User user)\n throws GitAPIException, IOException, InterruptedException {\n final var repositoryUrl = versionControlService.get().getCloneRepositoryUrl(projectKey, repositoryName);\n Repository repository = gitService.getOrCheckoutRepository(repositoryUrl, true);\n fileService.replaceVariablesInFileRecursive(repository.getLocalPath().toAbsolutePath().toString(), replacements);\n gitService.stageAllChanges(repository);\n gitService.commitAndPush(repository, \"Template adjusted by Artemis\", user);\n repository.setFiles(null); // Clear cache to avoid multiple commits when Artemis server is not restarted between attempts\n }\n}\n" }, { "alpha_fraction": 0.7311828136444092, "alphanum_fraction": 0.7311828136444092, "avg_line_length": 30, "blob_id": "a7173741dece19a579a54ca374e312b54fcbadd3", "content_id": "9394ff19c0eee573d5fb6b913ebed24a29cc6af4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 93, "license_type": "permissive", "max_line_length": 67, "num_lines": 3, "path": "/src/main/resources/templates/bamboo/ocaml/regularRuns/1_build_and_test_the_code.sh", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "# the build process is specified in `run.sh` in the test repository\nchmod +x run.sh\n./run.sh\n" }, { "alpha_fraction": 0.6179990172386169, "alphanum_fraction": 0.619236946105957, "avg_line_length": 41.65119934082031, "blob_id": "9f8a4181ab40783abb03b6f02bf357529c608bff", "content_id": "6de815e34d4ed726de3da83e8007182926447e09", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 26657, "license_type": "permissive", "max_line_length": 176, "num_lines": 625, "path": "/src/main/webapp/app/exercises/programming/manage/grading/programming-exercise-configure-grading.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { of, Subscription, zip } from 'rxjs';\nimport { catchError, distinctUntilChanged, map, take, tap } from 'rxjs/operators';\nimport { differenceBy as _differenceBy, differenceWith as _differenceWith, intersectionWith as _intersectionWith, unionBy as _unionBy } from 'lodash';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ProgrammingExerciseTestCase, Visibility } from 'app/entities/programming-exercise-test-case.model';\nimport { ProgrammingExerciseWebsocketService } from 'app/exercises/programming/manage/services/programming-exercise-websocket.service';\nimport { ComponentCanDeactivate } from 'app/shared/guard/can-deactivate.model';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { IssuesMap, ProgrammingExerciseGradingStatistics, TestCaseStats } from 'app/entities/programming-exercise-test-case-statistics.model';\nimport { StaticCodeAnalysisCategory, StaticCodeAnalysisCategoryState } from 'app/entities/static-code-analysis-category.model';\nimport { Location } from '@angular/common';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport {\n ProgrammingExerciseGradingService,\n ProgrammingExerciseTestCaseUpdate,\n StaticCodeAnalysisCategoryUpdate,\n} from 'app/exercises/programming/manage/services/programming-exercise-grading.service';\n\n/**\n * Describes the editableField\n */\nexport enum EditableField {\n WEIGHT = 'weight',\n BONUS_MULTIPLIER = 'bonusMultiplier',\n BONUS_POINTS = 'bonusPoints',\n VISIBILITY = 'visibility',\n PENALTY = 'penalty',\n MAX_PENALTY = 'maxPenalty',\n STATE = 'state',\n}\n\nconst DefaultFieldValues = {\n [EditableField.WEIGHT]: 1,\n [EditableField.BONUS_MULTIPLIER]: 1,\n [EditableField.BONUS_POINTS]: 0,\n [EditableField.PENALTY]: 0,\n [EditableField.MAX_PENALTY]: 0,\n};\n\n@Component({\n selector: 'jhi-programming-exercise-configure-grading',\n templateUrl: './programming-exercise-configure-grading.component.html',\n styleUrls: ['./programming-exercise-configure-grading.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class ProgrammingExerciseConfigureGradingComponent implements OnInit, OnDestroy, ComponentCanDeactivate {\n EditableField = EditableField;\n CategoryState = StaticCodeAnalysisCategoryState;\n Visibility = Visibility;\n\n courseId: number;\n exercise: ProgrammingExercise;\n testCaseSubscription: Subscription;\n testCaseChangedSubscription: Subscription;\n paramSub: Subscription;\n\n testCasesValue: ProgrammingExerciseTestCase[] = [];\n changedTestCaseIds: number[] = [];\n filteredTestCases: ProgrammingExerciseTestCase[] = [];\n\n staticCodeAnalysisCategories: StaticCodeAnalysisCategory[] = [];\n changedCategoryIds: number[] = [];\n\n buildAfterDueDateActive: boolean;\n isReleasedAndHasResults: boolean;\n showInactiveValue = false;\n isSaving = false;\n isLoading = false;\n // This flag means that the grading config were edited, but no submission run was triggered yet.\n hasUpdatedGradingConfig = false;\n activeTab: string;\n\n gradingStatistics?: ProgrammingExerciseGradingStatistics;\n maxIssuesPerCategory = 0;\n\n categoryStateList = Object.entries(StaticCodeAnalysisCategoryState).map(([name, value]) => ({ value, name }));\n testCaseVisibilityList = Object.entries(Visibility).map(([name, value]) => ({ value, name }));\n\n testCaseColors = {};\n categoryColors = {};\n\n /**\n * Returns the value of testcases\n */\n get testCases() {\n return this.testCasesValue;\n }\n\n /**\n * Sets value of the testcases\n * @param testCases the test cases which should be set\n */\n set testCases(testCases: ProgrammingExerciseTestCase[]) {\n this.testCasesValue = testCases;\n this.updateTestCaseFilter();\n }\n\n /**\n * Returns the value of showInactive\n */\n get showInactive() {\n return this.showInactiveValue;\n }\n\n /**\n * Sets the value of showInactive\n * @param showInactive the value which should be set\n */\n set showInactive(showInactive: boolean) {\n this.showInactiveValue = showInactive;\n this.updateTestCaseFilter();\n }\n\n constructor(\n private gradingService: ProgrammingExerciseGradingService,\n private programmingExerciseService: ProgrammingExerciseService,\n private programmingExerciseWebsocketService: ProgrammingExerciseWebsocketService,\n private route: ActivatedRoute,\n private alertService: JhiAlertService,\n private translateService: TranslateService,\n private location: Location,\n private router: Router,\n ) {}\n\n /**\n * Subscribes to the route params to get the current exerciseId.\n * Uses the exerciseId to subscribe to the newest value of the exercise's test cases.\n *\n * Also checks if a change guard needs to be activated when the test cases where saved.\n */\n ngOnInit(): void {\n this.paramSub = this.route.params.pipe(distinctUntilChanged()).subscribe((params) => {\n this.isLoading = true;\n const exerciseId = Number(params['exerciseId']);\n this.courseId = Number(params['courseId']);\n\n if (this.exercise == undefined || this.exercise.id !== exerciseId) {\n if (this.testCaseSubscription) {\n this.testCaseSubscription.unsubscribe();\n }\n if (this.testCaseChangedSubscription) {\n this.testCaseChangedSubscription.unsubscribe();\n }\n\n const loadExercise = this.programmingExerciseService.find(exerciseId).pipe(\n map((res) => res.body!),\n tap((exercise) => (this.exercise = exercise)),\n tap(() => {\n if (this.exercise.staticCodeAnalysisEnabled) {\n this.loadStaticCodeAnalysisCategories();\n } else if (this.activeTab !== 'test-cases') {\n this.selectTab('test-cases');\n }\n }),\n catchError(() => of(null)),\n );\n\n const loadExerciseTestCaseState = this.getExerciseTestCaseState(exerciseId).pipe(\n tap((releaseState) => {\n this.hasUpdatedGradingConfig = releaseState.testCasesChanged;\n this.isReleasedAndHasResults = releaseState.released && releaseState.hasStudentResult;\n this.buildAfterDueDateActive = !!releaseState.buildAndTestStudentSubmissionsAfterDueDate;\n }),\n catchError(() => of(null)),\n );\n\n this.loadStatistics(exerciseId);\n\n zip(loadExercise, loadExerciseTestCaseState)\n .pipe(take(1))\n .subscribe(() => {\n // This subscription e.g. adds new new tests to the table that were just created.\n this.subscribeForTestCaseUpdates();\n // This subscription is used to determine if the programming exercise's properties necessitate build runs after the test cases are changed.\n this.subscribeForExerciseTestCasesChangedUpdates();\n this.isLoading = false;\n });\n } else {\n this.isLoading = false;\n }\n\n if (params['tab'] === 'test-cases' || params['tab'] === 'code-analysis') {\n this.activeTab = params['tab'];\n } else {\n this.selectTab('test-cases');\n }\n });\n }\n\n /**\n * If there is an existing subscription, unsubscribe\n */\n ngOnDestroy(): void {\n if (this.testCaseSubscription) {\n this.testCaseSubscription.unsubscribe();\n }\n if (this.testCaseChangedSubscription) {\n this.testCaseChangedSubscription.unsubscribe();\n }\n if (this.paramSub) {\n this.paramSub.unsubscribe();\n }\n }\n\n /**\n * Subscribes to test case updates\n * updates the list of test cases\n */\n private subscribeForTestCaseUpdates() {\n if (this.testCaseSubscription) {\n this.testCaseSubscription.unsubscribe();\n }\n this.testCaseSubscription = this.gradingService\n .subscribeForTestCases(this.exercise.id!)\n .pipe(\n tap((testCases: ProgrammingExerciseTestCase[]) => {\n this.testCases = testCases;\n }),\n tap(() => this.loadStatistics(this.exercise.id!)),\n )\n .subscribe();\n }\n\n /**\n * Subscribes to test case changes\n * checks if the test cases have changed\n */\n private subscribeForExerciseTestCasesChangedUpdates() {\n if (this.testCaseChangedSubscription) {\n this.testCaseChangedSubscription.unsubscribe();\n }\n this.testCaseChangedSubscription = this.programmingExerciseWebsocketService\n .getTestCaseState(this.exercise.id!)\n .pipe(tap((testCasesChanged: boolean) => (this.hasUpdatedGradingConfig = testCasesChanged)))\n .subscribe();\n }\n\n /**\n * Checks if the exercise is released and has at least one student result.\n */\n getExerciseTestCaseState(exerciseId: number) {\n return this.programmingExerciseService.getProgrammingExerciseTestCaseState(exerciseId).pipe(map(({ body }) => body!));\n }\n\n /**\n * Update a field of a test case in the component state (does not persist the value on the server!).\n * Adds the currently edited test case to the list of unsaved changes.\n *\n * @param newValue of updated field;\n * @param editedTestCase the edited test case;\n * @param field the edited field;\n */\n updateEditedField(editedTestCase: ProgrammingExerciseTestCase, field: EditableField) {\n return (newValue: any) => {\n newValue = this.checkFieldValue(newValue, editedTestCase[field], field);\n // Only mark the testcase as changed, if the field has changed.\n if (newValue !== editedTestCase[field]) {\n this.changedTestCaseIds = this.changedTestCaseIds.includes(editedTestCase.id!) ? this.changedTestCaseIds : [...this.changedTestCaseIds, editedTestCase.id!];\n this.testCases = this.testCases.map((testCase) => (testCase.id !== editedTestCase.id ? testCase : { ...testCase, [field]: newValue }));\n }\n return newValue;\n };\n }\n\n /**\n * Update a field of a sca category in the component state (does not persist the value on the server!).\n * Adds the currently edited category to the list of unsaved changes.\n *\n * @param editedCategory the edited category;\n * @param field the edited field;\n */\n updateEditedCategoryField(editedCategory: StaticCodeAnalysisCategory, field: EditableField) {\n return (newValue: any) => {\n newValue = this.checkFieldValue(newValue, editedCategory[field], field);\n // Only mark the category as changed, if the field has changed.\n if (newValue !== editedCategory[field]) {\n this.changedCategoryIds = this.changedCategoryIds.includes(editedCategory.id) ? this.changedCategoryIds : [...this.changedCategoryIds, editedCategory.id];\n this.staticCodeAnalysisCategories = this.staticCodeAnalysisCategories.map((category) =>\n category.id !== editedCategory.id ? category : { ...category, [field]: newValue },\n );\n }\n return newValue;\n };\n }\n\n /**\n * Check and validate the new value for an editable field. Optionally applies the default value for the field.\n * @param newValue The new edited value\n * @param oldValue The previous value\n * @param field The edited field\n */\n checkFieldValue(newValue: any, oldValue: any, field: EditableField) {\n // Don't allow an empty string as a value!\n if (newValue === '') {\n newValue = DefaultFieldValues[field];\n }\n if (typeof oldValue === 'number') {\n newValue = Number(newValue);\n if (isNaN(newValue)) {\n newValue = oldValue;\n }\n }\n\n return newValue;\n }\n\n /**\n * Save the unsaved (edited) changes of the test cases.\n */\n saveTestCases() {\n this.isSaving = true;\n\n const testCasesToUpdate = _intersectionWith(this.testCases, this.changedTestCaseIds, (testCase: ProgrammingExerciseTestCase, id: number) => testCase.id === id);\n\n const testCaseUpdates = testCasesToUpdate.map((testCase) => ProgrammingExerciseTestCaseUpdate.from(testCase));\n\n const isSumOfWeightsOK = this.isSumOfWeightsGreaterThanZero(testCaseUpdates);\n if (!isSumOfWeightsOK) {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.testCases.weightSumError`);\n this.isSaving = false;\n return;\n }\n\n const saveTestCases = this.gradingService.updateTestCase(this.exercise.id!, testCaseUpdates).pipe(\n tap((updatedTestCases: ProgrammingExerciseTestCase[]) => {\n // From successfully updated test cases from dirty checking list.\n this.changedTestCaseIds = _differenceWith(this.changedTestCaseIds, updatedTestCases, (id: number, testCase: ProgrammingExerciseTestCase) => testCase.id === id);\n\n // Generate the new list of test cases with the updated weights and notify the test case service.\n const newTestCases = _unionBy(updatedTestCases, this.testCases, 'id');\n\n this.gradingService.notifyTestCases(this.exercise.id!, newTestCases);\n\n // Find out if there are test cases that were not updated, show an error.\n const notUpdatedTestCases = _differenceBy(testCasesToUpdate, updatedTestCases, 'id');\n if (notUpdatedTestCases.length) {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.testCases.couldNotBeUpdated`, { testCases: notUpdatedTestCases });\n } else {\n this.alertService.success(`artemisApp.programmingExercise.configureGrading.testCases.updated`);\n }\n }),\n catchError((error: HttpErrorResponse) => {\n if (error.status === 400) {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.testCases.weightSumError`);\n } else {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.testCases.couldNotBeUpdated`, { testCases: testCasesToUpdate });\n }\n return of(null);\n }),\n );\n\n saveTestCases.subscribe(() => {\n this.isSaving = false;\n });\n }\n\n saveCategories() {\n this.isSaving = true;\n\n this.staticCodeAnalysisCategories = this.staticCodeAnalysisCategories.map((category) =>\n category.state === StaticCodeAnalysisCategoryState.Graded ? category : { ...category, penalty: 0, maxPenalty: 0 },\n );\n\n const categoriesToUpdate = _intersectionWith(\n this.staticCodeAnalysisCategories,\n this.changedCategoryIds,\n (codeAnalysisCategory: StaticCodeAnalysisCategory, id: number) => codeAnalysisCategory.id === id,\n );\n const categoryUpdates = categoriesToUpdate.map((category) => StaticCodeAnalysisCategoryUpdate.from(category));\n\n const saveCodeAnalysis = this.gradingService.updateCodeAnalysisCategories(this.exercise.id!, categoryUpdates).pipe(\n tap((updatedCategories: StaticCodeAnalysisCategory[]) => {\n // From successfully updated categories from dirty checking list.\n this.changedCategoryIds = _differenceWith(this.changedCategoryIds, updatedCategories, (id: number, category: StaticCodeAnalysisCategory) => category.id === id);\n\n // Generate the new list of categories.\n this.staticCodeAnalysisCategories = _unionBy(updatedCategories, this.staticCodeAnalysisCategories, 'id');\n\n // Find out if there are test cases that were not updated, show an error.\n const notUpdatedCategories = _differenceBy(categoriesToUpdate, updatedCategories, 'id');\n if (notUpdatedCategories.length) {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.categories.couldNotBeUpdated`, {\n categories: notUpdatedCategories.map((c) => c.name).join(', '),\n });\n } else {\n this.alertService.success(`artemisApp.programmingExercise.configureGrading.categories.updated`);\n }\n }),\n catchError(() => {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.categories.couldNotBeUpdated`, {\n categories: categoriesToUpdate.map((c) => c.name).join(', '),\n });\n return of(null);\n }),\n );\n\n saveCodeAnalysis.subscribe(() => {\n this.isSaving = false;\n });\n }\n\n /**\n * Reset all test cases.\n */\n resetTestCases() {\n this.isSaving = true;\n this.gradingService\n .resetTestCases(this.exercise.id!)\n .pipe(\n tap((testCases: ProgrammingExerciseTestCase[]) => {\n this.alertService.success(`artemisApp.programmingExercise.configureGrading.testCases.resetSuccessful`);\n this.gradingService.notifyTestCases(this.exercise.id!, testCases);\n }),\n catchError(() => {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.testCases.resetFailed`);\n return of(null);\n }),\n )\n .subscribe(() => {\n this.isSaving = false;\n this.changedTestCaseIds = [];\n });\n }\n\n resetCategories() {\n this.isSaving = true;\n this.gradingService\n .resetCategories(this.exercise.id!)\n .pipe(\n tap((categories: StaticCodeAnalysisCategory[]) => {\n this.alertService.success(`artemisApp.programmingExercise.configureGrading.categories.resetSuccessful`);\n this.staticCodeAnalysisCategories = categories;\n this.loadStatistics(this.exercise.id!);\n }),\n catchError(() => {\n this.alertService.error(`artemisApp.programmingExercise.configureGrading.categories.resetFailed`);\n return of(null);\n }),\n )\n .subscribe(() => {\n this.isSaving = false;\n this.changedCategoryIds = [];\n });\n }\n\n /**\n * Executes filtering on all available test cases with the specified params.\n */\n updateTestCaseFilter = () => {\n this.filteredTestCases = !this.showInactiveValue && this.testCases ? this.testCases.filter(({ active }) => active) : this.testCases;\n };\n\n /**\n * Makes inactive test cases grey.\n *\n * @param row\n */\n getRowClass(row: ProgrammingExerciseTestCase) {\n return !row.active ? 'test-case--inactive' : '';\n }\n\n /**\n * Checks if there are unsaved test cases or there was no submission run after the test cases were changed.\n * Provides a fitting text for the confirm.\n */\n canDeactivate() {\n if (!this.changedTestCaseIds.length && (!this.isReleasedAndHasResults || !this.hasUpdatedGradingConfig)) {\n return true;\n }\n const warning = this.changedTestCaseIds.length\n ? this.translateService.instant('pendingChanges')\n : this.translateService.instant('artemisApp.programmingExercise.configureGrading.updatedGradingConfig');\n return confirm(warning);\n }\n\n /**\n * Switch tabs\n * @param tab The target tab\n */\n selectTab(tab: string) {\n const parentUrl = this.router.url.substring(0, this.router.url.lastIndexOf('/'));\n this.location.replaceState(`${parentUrl}/${tab}`);\n this.activeTab = tab;\n }\n\n /**\n * Get the stats for a specific test case\n * @param testName The name of the test case\n */\n getTestCaseStats(testName: string): TestCaseStats | undefined {\n return this.gradingStatistics?.testCaseStatsMap ? this.gradingStatistics.testCaseStatsMap[testName] : undefined;\n }\n\n /**\n * Get the issues map for a specific category\n * @param categoryName The name of the category\n */\n getIssuesMap(categoryName: string): IssuesMap | undefined {\n return this.gradingStatistics?.categoryIssuesMap ? this.gradingStatistics.categoryIssuesMap[categoryName] : undefined;\n }\n\n tableSorts = { testCases: [{ prop: 'testName', dir: 'asc' }], codeAnalysis: [{ prop: 'name', dir: 'asc' }] };\n onSort(table: 'testCases' | 'codeAnalysis', config: any) {\n this.tableSorts[table] = config.sorts;\n }\n\n /**\n * Returns the correct sort-icon for the specified property\n * @param table The table of the property\n * @param prop The sorted property\n */\n iconForSortPropField(table: 'testCases' | 'codeAnalysis', prop: string) {\n const propSort = this.tableSorts[table].find((e) => e.prop === prop);\n if (!propSort) {\n return 'sort';\n }\n return propSort.dir === 'asc' ? 'sort-up' : 'sort-down';\n }\n\n /**\n * Comparator function for the passed percentage of test-cases.\n */\n comparePassedPercent = (_: any, __: any, rowA: ProgrammingExerciseTestCase, rowB: ProgrammingExerciseTestCase) => {\n const statsA = this.getTestCaseStats(rowA.testName!);\n const statsB = this.getTestCaseStats(rowB.testName!);\n const valA = (statsA?.numPassed ?? 0) - (statsA?.numFailed ?? 0);\n const valB = (statsB?.numPassed ?? 0) - (statsB?.numFailed ?? 0);\n return valA - valB;\n };\n\n valForState = (s: StaticCodeAnalysisCategoryState) => (s === StaticCodeAnalysisCategoryState.Inactive ? 0 : s === StaticCodeAnalysisCategoryState.Feedback ? 1 : 2);\n\n /**\n * Comparator function for the state of a sca category.\n */\n compareCategoryState = (_: any, __: any, rowA: StaticCodeAnalysisCategory, rowB: StaticCodeAnalysisCategory) => {\n return this.valForState(rowA.state) - this.valForState(rowB.state);\n };\n\n /**\n * Comparator function for the penalty of a sca category.\n */\n comparePenalty = (_: any, __: any, rowA: StaticCodeAnalysisCategory, rowB: StaticCodeAnalysisCategory) => {\n const valForPenalty = (c: StaticCodeAnalysisCategory) => this.valForState(c.state) + (c.state === StaticCodeAnalysisCategoryState.Graded ? c.penalty : 0);\n return valForPenalty(rowA) - valForPenalty(rowB);\n };\n\n /**\n * Comparator function for the max-penalty of a sca category.\n */\n compareMaxPenalty = (_: any, __: any, rowA: StaticCodeAnalysisCategory, rowB: StaticCodeAnalysisCategory) => {\n const valForMaxPenalty = (c: StaticCodeAnalysisCategory) => this.valForState(c.state) + (c.state === StaticCodeAnalysisCategoryState.Graded ? c.maxPenalty : 0);\n return valForMaxPenalty(rowA) - valForMaxPenalty(rowB);\n };\n\n /**\n * Comparator function for the detected issues of a sca category.\n */\n compareDetectedIssues = (_: any, __: any, rowA: StaticCodeAnalysisCategory, rowB: StaticCodeAnalysisCategory) => {\n const issuesA = this.getIssuesMap(rowA.name);\n const issuesB = this.getIssuesMap(rowB.name);\n const totalIssuesA = Object.values(issuesA ?? {}).reduce((sum, n) => sum + n, 0);\n const totalIssuesB = Object.values(issuesB ?? {}).reduce((sum, n) => sum + n, 0);\n return totalIssuesA !== totalIssuesB ? totalIssuesA - totalIssuesB : this.compareCategoryState(_, __, rowA, rowB);\n };\n\n /**\n * Load the static code analysis categories\n * @private\n */\n private loadStaticCodeAnalysisCategories() {\n this.gradingService\n .getCodeAnalysisCategories(this.exercise.id!)\n .pipe(\n tap((categories) => (this.staticCodeAnalysisCategories = categories)),\n catchError(() => of(null)),\n )\n .subscribe();\n }\n\n /**\n * Load the statistics for this exercise and calculate the\n * maximum number of issues in one category\n * @param exerciseId The current exercise id\n * @private\n */\n private loadStatistics(exerciseId: number) {\n this.gradingService\n .getGradingStatistics(exerciseId)\n .pipe(\n tap((statistics) => (this.gradingStatistics = statistics)),\n tap(() => {\n this.maxIssuesPerCategory = 0;\n if (this.gradingStatistics?.categoryIssuesMap) {\n // calculate the maximum number of issues in one category\n Object.values(this.gradingStatistics?.categoryIssuesMap).forEach((issuesMap) => {\n const maxIssues = Object.keys(issuesMap).reduce((max, issues) => Math.max(max, parseInt(issues, 10)), 0);\n if (maxIssues > this.maxIssuesPerCategory) {\n this.maxIssuesPerCategory = maxIssues;\n }\n });\n }\n }),\n catchError(() => of(null)),\n )\n .subscribe();\n }\n\n private isSumOfWeightsGreaterThanZero(testCaseUpdates: ProgrammingExerciseTestCaseUpdate[]): boolean {\n let weight = 0;\n this.testCases.forEach((testCase) => {\n const index = testCaseUpdates.findIndex((update) => testCase.id === update.id);\n if (index !== -1) {\n weight += testCaseUpdates[index].weight ?? 0;\n } else {\n weight += testCase.weight ?? 0;\n }\n });\n return weight > 0;\n }\n}\n" }, { "alpha_fraction": 0.6905516982078552, "alphanum_fraction": 0.7019657492637634, "avg_line_length": 34.84090805053711, "blob_id": "23347da7567783cd2280f1c61b92dc8e6d5ce348", "content_id": "71561502779e6f5a7ab4c6d4fc05545b2a5021a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1577, "license_type": "permissive", "max_line_length": 73, "num_lines": 44, "path": "/src/test/java/de/tum/in/www1/artemis/TutorGroupIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.Set;\n\nimport org.junit.jupiter.api.Test;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.TutorGroup;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.enumeration.Language;\nimport de.tum.in.www1.artemis.domain.enumeration.Weekday;\n\npublic class TutorGroupIntegrationTest {\n\n @Test\n public void testTutorGroup() {\n var tutor = new User();\n var course = new Course();\n\n TutorGroup tutorGroup = new TutorGroup();\n tutorGroup.setName(\"test\");\n tutorGroup.setCapacity(10);\n tutorGroup.setWeekday(Weekday.FRIDAY);\n tutorGroup.setTimeSlot(\"Fr 10-12\");\n tutorGroup.setLanguage(Language.ENGLISH);\n tutorGroup.setRoom(\"Zoom\");\n tutorGroup.setTutor(tutor);\n tutorGroup.setStudents(Set.of(tutor));\n tutorGroup.setCourse(course);\n\n assertThat(tutorGroup.getName()).isEqualTo(\"test\");\n assertThat(tutorGroup.getCapacity()).isEqualTo(10);\n assertThat(tutorGroup.getWeekday()).isEqualTo(Weekday.FRIDAY);\n assertThat(tutorGroup.getTimeSlot()).isEqualTo(\"Fr 10-12\");\n assertThat(tutorGroup.getLanguage()).isEqualTo(Language.ENGLISH);\n assertThat(tutorGroup.getRoom()).isEqualTo(\"Zoom\");\n assertThat(tutorGroup.getTutor()).isEqualTo(tutor);\n assertThat(tutorGroup.getStudents()).isEqualTo(Set.of(tutor));\n assertThat(tutorGroup.getCourse()).isEqualTo(course);\n }\n\n}\n" }, { "alpha_fraction": 0.685387134552002, "alphanum_fraction": 0.6870229244232178, "avg_line_length": 40.681819915771484, "blob_id": "079cdab3f17b743b90206d7d6de4b809bae080d3", "content_id": "ae4e9b93cc84aa328c0c42b07f9812be9857ac65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1834, "license_type": "permissive", "max_line_length": 137, "num_lines": 44, "path": "/src/test/javascript/spec/component/course/course-exercise-submission-result-simulation.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport { Result } from 'app/entities/result.model';\nimport { CourseExerciseSubmissionResultSimulationService } from 'app/course/manage/course-exercise-submission-result-simulation.service';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\n\nimport * as chai from 'chai';\nconst expect = chai.expect;\n\ndescribe('Participation Service', () => {\n let injector: TestBed;\n let service: CourseExerciseSubmissionResultSimulationService;\n let httpMock: HttpTestingController;\n let exerciseId: number;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n injector = getTestBed();\n service = injector.get(CourseExerciseSubmissionResultSimulationService);\n httpMock = injector.get(HttpTestingController);\n exerciseId = 123;\n });\n\n it('should simulate submission', async () => {\n const mockSubmission = new ProgrammingSubmission();\n service.simulateSubmission(exerciseId).subscribe((res) => expect(res.body).to.eq(mockSubmission));\n\n const req = httpMock.expectOne({ method: 'POST', url: `api/exercises/${exerciseId}/submissions/no-vcs-and-ci-available` });\n req.flush(mockSubmission);\n });\n\n it('should simulate result', async () => {\n const mockResult = new Result();\n service.simulateResult(exerciseId).subscribe((res) => expect(res.body).to.eq(mockResult));\n\n const req = httpMock.expectOne({ method: 'POST', url: `api/exercises/${exerciseId}/results/no-vcs-and-ci-available` });\n req.flush(mockResult);\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.676791250705719, "alphanum_fraction": 0.676791250705719, "avg_line_length": 37.3283576965332, "blob_id": "fee096797370e1fb925b0cde4660088ff82e4d9e", "content_id": "c8e64b4e7c705e29557cb6a9b8b3e25f2311e43e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2568, "license_type": "permissive", "max_line_length": 128, "num_lines": 67, "path": "/src/main/webapp/app/exercises/shared/exercise-headers/header-exercise-page-with-details.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges, OnInit } from '@angular/core';\nimport * as moment from 'moment';\nimport { Exercise, ExerciseCategory, ExerciseType, getIcon, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { Exam } from 'app/entities/exam.model';\nimport { IconProp } from '@fortawesome/fontawesome-svg-core';\n\n@Component({\n selector: 'jhi-header-exercise-page-with-details',\n templateUrl: './header-exercise-page-with-details.component.html',\n})\nexport class HeaderExercisePageWithDetailsComponent implements OnInit, OnChanges {\n readonly IncludedInOverallScore = IncludedInOverallScore;\n\n @Input() public exercise: Exercise;\n @Input() public onBackClick: () => void; // TODO: This can be removed once we are happy with the breadcrumb navigation\n @Input() public title: string;\n @Input() public exam: Exam | null;\n @Input() public isTestRun = false;\n @Input() public displayBackButton = true; // TODO: This can be removed once we are happy with the breadcrumb navigation\n\n public exerciseStatusBadge = 'badge-success';\n public exerciseCategories: ExerciseCategory[];\n public isExamMode = false;\n\n icon: IconProp;\n\n constructor(private exerciseService: ExerciseService) {}\n\n /**\n * Sets the status badge and categories of the exercise on init\n */\n ngOnInit(): void {\n this.setExerciseStatusBadge();\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise);\n this.setIcon(this.exercise.type);\n }\n\n /**\n * Sets the status badge and categories of the exercise on changes\n */\n ngOnChanges(): void {\n this.setExerciseStatusBadge();\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise);\n this.setIcon(this.exercise.type);\n\n if (this.exam) {\n this.isExamMode = true;\n }\n }\n\n private setExerciseStatusBadge(): void {\n if (this.exercise) {\n if (this.isExamMode) {\n this.exerciseStatusBadge = moment(this.exam?.endDate!).isBefore(moment()) ? 'badge-danger' : 'badge-success';\n } else {\n this.exerciseStatusBadge = moment(this.exercise.dueDate!).isBefore(moment()) ? 'badge-danger' : 'badge-success';\n }\n }\n }\n\n setIcon(exerciseType?: ExerciseType) {\n if (exerciseType) {\n this.icon = getIcon(exerciseType) as IconProp;\n }\n }\n}\n" }, { "alpha_fraction": 0.7714371681213379, "alphanum_fraction": 0.7733426690101624, "avg_line_length": 55.977142333984375, "blob_id": "d2cebd6f7944885c23f9d52fb3149b30f4788cd4", "content_id": "e610e86554026ff1c92f02c4d91e80b2c376b577", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10039, "license_type": "permissive", "max_line_length": 180, "num_lines": 175, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingSubmissionResultSimulationService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport java.time.ZonedDateTime;\nimport java.util.Optional;\n\nimport javax.annotation.Nullable;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.participation.Participant;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.ParticipationService;\nimport de.tum.in.www1.artemis.service.util.VCSSimulationUtils;\n\n/**\n * Only for local development\n * Simulates the creation of a programming exercise without a connection to the VCS and CI server\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n\n@Profile(\"dev\")\n@Service\npublic class ProgrammingSubmissionResultSimulationService {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseService.class);\n\n private final ParticipationRepository participationRepository;\n\n private final UserRepository userRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final ParticipationService participationService;\n\n private final ProgrammingSubmissionRepository programmingSubmissionRepository;\n\n private final ResultRepository resultRepository;\n\n private final ProgrammingExerciseSimulationService programmingExerciseSimulationService;\n\n public ProgrammingSubmissionResultSimulationService(ParticipationRepository participationRepository, UserRepository userRepository,\n ProgrammingExerciseRepository programmingExerciseRepository, ParticipationService participationService, ProgrammingSubmissionRepository programmingSubmissionRepository,\n ResultRepository resultRepository, ProgrammingExerciseSimulationService programmingExerciseSimulationService) {\n this.participationRepository = participationRepository;\n this.userRepository = userRepository;\n this.programmingSubmissionRepository = programmingSubmissionRepository;\n this.resultRepository = resultRepository;\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.participationService = participationService;\n this.programmingExerciseSimulationService = programmingExerciseSimulationService;\n }\n\n /**\n * This method creates a new participation for the provided user\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param programmingExercise the used programmingExercise\n * @param participant the participant object of the user\n * @param user the user who wants to particpate\n * @return the newly created and stored participation\n */\n public ProgrammingExerciseStudentParticipation createParticipation(ProgrammingExercise programmingExercise, Participant participant, User user) {\n ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipation = new ProgrammingExerciseStudentParticipation();\n programmingExerciseStudentParticipation.setBuildPlanId(programmingExercise.getProjectKey() + \"-\" + user.getLogin().toUpperCase());\n programmingExerciseStudentParticipation.setParticipant(participant);\n programmingExerciseStudentParticipation.setInitializationState(InitializationState.INITIALIZED);\n programmingExerciseStudentParticipation.setRepositoryUrl(\"http://\" + user.getLogin() + \"@\" + programmingExerciseSimulationService.domain\n + programmingExercise.getProjectKey() + \"/\" + programmingExercise.getProjectKey().toLowerCase() + \"-\" + user.getLogin() + \".git\");\n programmingExerciseStudentParticipation.setInitializationDate(ZonedDateTime.now());\n programmingExerciseStudentParticipation.setProgrammingExercise(programmingExercise);\n participationRepository.save(programmingExerciseStudentParticipation);\n return programmingExerciseStudentParticipation;\n }\n\n /**\n * This method creates a new submission for the provided user\n * @param exerciseId the exerciseId of the exercise for which a submission should be created\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @return the newly created and stored submission\n */\n public ProgrammingSubmission createSubmission(Long exerciseId) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n Participant participant = user;\n ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipation;\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findByIdWithStudentParticipationsAndLegalSubmissionsElseThrow(exerciseId);\n Optional<StudentParticipation> optionalStudentParticipation = participationService.findOneByExerciseAndStudentLoginWithEagerSubmissionsAnyState(programmingExercise,\n user.getLogin());\n if (optionalStudentParticipation.isEmpty()) {\n programmingExerciseStudentParticipation = createParticipation(programmingExercise, participant, user);\n }\n else {\n programmingExerciseStudentParticipation = (ProgrammingExerciseStudentParticipation) optionalStudentParticipation.get();\n }\n\n ProgrammingSubmission programmingSubmission = new ProgrammingSubmission();\n programmingSubmission.setCommitHash(VCSSimulationUtils.simulateCommitHash());\n programmingSubmission.setSubmitted(true);\n programmingSubmission.setSubmissionDate(ZonedDateTime.now());\n programmingSubmission.setType(SubmissionType.MANUAL);\n programmingExerciseStudentParticipation.addSubmission(programmingSubmission);\n\n programmingSubmissionRepository.save(programmingSubmission);\n return programmingSubmission;\n }\n\n /**\n * This method creates a new result for the provided participation\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param programmingExerciseStudentParticipation the participation for which the new result should be created\n * @return the newly created and stored result\n */\n public Result createResult(ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipation) {\n Optional<ProgrammingSubmission> programmingSubmission = programmingSubmissionRepository\n .findFirstByParticipationIdOrderByLegalSubmissionDateDesc(programmingExerciseStudentParticipation.getId());\n Result result = new Result();\n result.setSubmission(programmingSubmission.get());\n result.setParticipation(programmingExerciseStudentParticipation);\n result.setRated(true);\n result.resultString(\"7 of 13 passed\");\n result.setScore(7.0 / 13.0);\n result.setAssessmentType(AssessmentType.AUTOMATIC);\n result.setCompletionDate(ZonedDateTime.now());\n this.addFeedback(result);\n resultRepository.save(result);\n return result;\n }\n\n /**\n * Creates feedback for the provided result\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param result for which the feedback should be created\n * @param methodName of the testcase\n * @param positive is the testcase positive or not\n * @param errorMessageString will only added if the test case fails otherwise use null\n */\n public void createFeedback(Result result, String methodName, boolean positive, @Nullable String errorMessageString) {\n Feedback feedback = new Feedback();\n feedback.setText(methodName);\n feedback.setDetailText(errorMessageString);\n feedback.setType(FeedbackType.AUTOMATIC);\n feedback.setPositive(positive);\n result.addFeedback(feedback);\n }\n\n /**\n * adds the feedback to the result\n * currently only the Java standard template is supported\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param result to which the feedback should be added\n */\n public void addFeedback(Result result) {\n this.createFeedback(result, \"testClass[BubbleSort]\", false,\n \"The class 'BubbleSort' does not implement the interface 'SortStrategy' as expected. Implement the interface and its methods.\");\n this.createFeedback(result, \"testBubbleSort\", false, \"BubbleSort does not sort correctly\");\n this.createFeedback(result, \"testUseBubbleSortForSmallList\", false, \"The class 'Context' was not found within the submission. Make sure to implement it properly.\");\n this.createFeedback(result, \"testMergeSort\", false, \"MergeSort does not sort correctly\");\n this.createFeedback(result, \"testUseMergeSortForBigList\", false, \"The class 'Context' was not found within the submission. Make sure to implement it properly.\");\n this.createFeedback(result, \"testClass[MergeSort]\", false,\n \"The class 'MergeSort' does not implement the interface 'SortStrategy' as expected. Implement the interface and its methods.\");\n this.createFeedback(result, \"testClass[SortStrategy]\", true, null);\n this.createFeedback(result, \"testAttributes[Context]\", true, null);\n this.createFeedback(result, \"testMethods[Policy]\", true, null);\n this.createFeedback(result, \"testMethods[SortStrategy]\", true, null);\n this.createFeedback(result, \"testMethods[Context]\", true, null);\n this.createFeedback(result, \"testAttributes[Policy]\", true, null);\n this.createFeedback(result, \"testConstructors[Policy]\", true, null);\n }\n\n}\n" }, { "alpha_fraction": 0.5650510191917419, "alphanum_fraction": 0.6179847121238708, "avg_line_length": 35.46511459350586, "blob_id": "4cf7ee07fafe4c4b9ba49fead661f6f8c8ae4501", "content_id": "b043091beb6d85157739a0d42ec730affa6562f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1568, "license_type": "permissive", "max_line_length": 107, "num_lines": 43, "path": "/src/main/webapp/app/shared/layouts/footer/footer.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { VERSION } from 'app/app.constants';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { filter, tap } from 'rxjs/operators';\n\n@Component({\n selector: 'jhi-footer',\n templateUrl: './footer.component.html',\n})\nexport class FooterComponent implements OnInit {\n readonly releaseNotesUrl = `https://github.com/ls1intum/Artemis/releases/tag/${VERSION}`;\n\n email: string;\n imprintUrl: string;\n\n constructor(private profileService: ProfileService) {}\n\n ngOnInit(): void {\n this.profileService\n .getProfileInfo()\n .pipe(\n filter(Boolean),\n tap((info: ProfileInfo) => {\n this.contact = info.contact;\n this.imprintUrl = info.imprint;\n }),\n )\n .subscribe();\n }\n\n set contact(mail: string) {\n this.email =\n 'mailto:' +\n mail +\n '?body=Note%3A%20Please%20send%20only%20support%2Ffeature' +\n '%20request%20or%20bug%20reports%20regarding%20the%20Artemis' +\n '%20Platform%20to%20this%20address.%20Please%20check' +\n '%20our%20public%20bug%20tracker%20at%20https%3A%2F%2Fgithub.com' +\n '%2Fls1intum%2FArtemis%20for%20known%20bugs.%0AFor%20questions' +\n '%20regarding%20exercises%20and%20their%20content%2C%20please%20contact%20your%20instructors.';\n }\n}\n" }, { "alpha_fraction": 0.5865580439567566, "alphanum_fraction": 0.5865580439567566, "avg_line_length": 20.34782600402832, "blob_id": "245f105bbdf467d5b5918bff80b528b9bae2a653", "content_id": "6873351c14934348eaaf5d75ec6a0dbb3c4c0656", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 491, "license_type": "permissive", "max_line_length": 65, "num_lines": 23, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-cookie.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { CookieService } from 'ngx-cookie-service';\n\nexport class MockCookieService extends CookieService {\n get(key: string): string {\n return '';\n }\n\n getAll(): any {\n return {};\n }\n\n getObject(key: string): Object {\n return {};\n }\n\n put(key: string, value: string, options?: any): void {}\n\n putObject(key: string, value: Object, options?: any): void {}\n\n remove(key: string, options?: any): void {}\n\n removeAll(options?: any): void {}\n}\n" }, { "alpha_fraction": 0.5835537910461426, "alphanum_fraction": 0.5837742686271667, "avg_line_length": 45.28571319580078, "blob_id": "8d5506618471b8dbe41ec92e806b65db70abbc61", "content_id": "6099049a5946b125098ca1f47bca0692d1157692", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4536, "license_type": "permissive", "max_line_length": 164, "num_lines": 98, "path": "/src/main/webapp/app/course/learning-goals/edit-learning-goal/edit-learning-goal.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { onError } from 'app/shared/util/global.utils';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LearningGoalFormData } from 'app/course/learning-goals/learning-goal-form/learning-goal-form.component';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { finalize, switchMap, take } from 'rxjs/operators';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { forkJoin, combineLatest } from 'rxjs';\nimport { Lecture } from 'app/entities/lecture.model';\n\n@Component({\n selector: 'jhi-edit-learning-goal',\n templateUrl: './edit-learning-goal.component.html',\n styles: [],\n})\nexport class EditLearningGoalComponent implements OnInit {\n isLoading = false;\n learningGoal: LearningGoal;\n lecturesWithLectureUnits: Lecture[] = [];\n formData: LearningGoalFormData;\n courseId: number;\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private lectureService: LectureService,\n private router: Router,\n private learningGoalService: LearningGoalService,\n private alertService: JhiAlertService,\n ) {}\n\n ngOnInit(): void {\n this.isLoading = true;\n combineLatest(this.activatedRoute.paramMap, this.activatedRoute.parent!.parent!.paramMap)\n .pipe(\n take(1),\n switchMap(([params, parentParams]) => {\n const learningGoalId = Number(params.get('learningGoalId'));\n this.courseId = Number(parentParams.get('courseId'));\n\n const learningGoalObservable = this.learningGoalService.findById(learningGoalId, this.courseId);\n const lecturesObservable = this.lectureService.findAllByCourseId(this.courseId, true);\n return forkJoin([learningGoalObservable, lecturesObservable]);\n }),\n finalize(() => (this.isLoading = false)),\n )\n .subscribe(\n ([learningGoalResult, lecturesResult]) => {\n if (learningGoalResult.body) {\n this.learningGoal = learningGoalResult.body;\n // server will send undefined instead of empty array, therefore we set it here as it is easier to handle\n if (!this.learningGoal.lectureUnits) {\n this.learningGoal.lectureUnits = [];\n }\n }\n if (lecturesResult.body) {\n this.lecturesWithLectureUnits = lecturesResult.body;\n for (const lecture of this.lecturesWithLectureUnits) {\n // server will send undefined instead of empty array, therefore we set it here as it is easier to handle\n if (!lecture.lectureUnits) {\n lecture.lectureUnits = [];\n }\n }\n }\n\n this.formData = {\n title: this.learningGoal.title,\n description: this.learningGoal.description,\n connectedLectureUnits: this.learningGoal.lectureUnits,\n };\n },\n (res: HttpErrorResponse) => onError(this.alertService, res),\n );\n }\n\n updateLearningGoal(formData: LearningGoalFormData) {\n const { title, description, connectedLectureUnits } = formData;\n this.learningGoal.title = title;\n this.learningGoal.description = description;\n this.learningGoal.lectureUnits = connectedLectureUnits;\n this.isLoading = true;\n this.learningGoalService\n .update(this.learningGoal, this.courseId)\n .pipe(\n finalize(() => {\n this.isLoading = false;\n // currently at /course-management/{courseId}/goal-management/{learninGoalId}/edit, going back to /course-management/{courseId}/goal-management/\n this.router.navigate(['../../'], { relativeTo: this.activatedRoute });\n }),\n )\n .subscribe(\n () => {},\n (res: HttpErrorResponse) => onError(this.alertService, res),\n );\n }\n}\n" }, { "alpha_fraction": 0.6856886148452759, "alphanum_fraction": 0.6901819705963135, "avg_line_length": 43.5099983215332, "blob_id": "0ebc708a788707b324a61f5d95287f7c99594206", "content_id": "3ae51ca262e674c13f4ccd2138ca20c70fcb37a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4451, "license_type": "permissive", "max_line_length": 176, "num_lines": 100, "path": "/src/main/webapp/app/exercises/shared/dashboards/instructor/instructor-exercise-dashboard.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { JhiAlertService } from 'ng-jhipster';\nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { SortService } from 'app/shared/service/sort.service';\n\n@Component({\n selector: 'jhi-instructor-exercise-dashboard',\n templateUrl: './instructor-exercise-dashboard.component.html',\n providers: [],\n})\nexport class InstructorExerciseDashboardComponent implements OnInit {\n exercise: Exercise;\n courseId: number;\n\n stats = new StatsForDashboard();\n\n dataForAssessmentPieChart: number[];\n totalManualAssessmentPercentage = new DueDateStat();\n totalAutomaticAssessmentPercentage = new DueDateStat();\n\n constructor(\n private exerciseService: ExerciseService,\n private route: ActivatedRoute,\n private jhiAlertService: JhiAlertService,\n private resultService: ResultService,\n private router: Router,\n private sortService: SortService,\n ) {}\n\n /**\n * Extracts the course and exercise ids from the route params and fetches the exercise from the server\n */\n ngOnInit(): void {\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n const exerciseId = Number(this.route.snapshot.paramMap.get('exerciseId'));\n this.loadExercise(exerciseId);\n }\n\n /**\n * Navigates back to the instructor dashboard where the user came from\n */\n back() {\n this.router.navigate([`/course-management/${this.courseId}/instructor-dashboard`]);\n }\n\n /**\n * Computes the stats for the assessment charts.\n * Percentages are rounded towards zero.\n */\n public setStatistics() {\n if (this.stats.numberOfSubmissions.inTime > 0) {\n this.totalManualAssessmentPercentage.inTime = Math.floor(\n ((this.stats.totalNumberOfAssessments.inTime - this.stats.numberOfAutomaticAssistedAssessments.inTime) / this.stats.numberOfSubmissions.inTime) * 100,\n );\n this.totalAutomaticAssessmentPercentage.inTime = Math.floor((this.stats.numberOfAutomaticAssistedAssessments.inTime / this.stats.numberOfSubmissions.inTime) * 100);\n } else {\n this.totalManualAssessmentPercentage.inTime = 100;\n }\n if (this.stats.numberOfSubmissions.late > 0) {\n this.totalManualAssessmentPercentage.late = Math.floor(\n ((this.stats.totalNumberOfAssessments.late - this.stats.numberOfAutomaticAssistedAssessments.late) / this.stats.numberOfSubmissions.late) * 100,\n );\n this.totalAutomaticAssessmentPercentage.late = Math.floor((this.stats.numberOfAutomaticAssistedAssessments.late / this.stats.numberOfSubmissions.late) * 100);\n } else {\n this.totalManualAssessmentPercentage.late = 100;\n }\n\n this.dataForAssessmentPieChart = [\n this.stats.numberOfSubmissions.total - this.stats.totalNumberOfAssessments.total,\n this.stats.totalNumberOfAssessments.total - this.stats.numberOfAutomaticAssistedAssessments.total,\n this.stats.numberOfAutomaticAssistedAssessments.total,\n ];\n }\n\n private loadExercise(exerciseId: number) {\n this.exerciseService.find(exerciseId).subscribe(\n (res: HttpResponse<Exercise>) => (this.exercise = res.body!),\n (response: HttpErrorResponse) => this.onError(response.message),\n );\n\n this.exerciseService.getStatsForInstructors(exerciseId).subscribe(\n (res: HttpResponse<StatsForDashboard>) => {\n this.sortService.sortByProperty(this.stats.tutorLeaderboardEntries, 'points', false);\n this.stats = StatsForDashboard.from(Object.assign({}, this.stats, res.body));\n this.setStatistics();\n },\n (response: string) => this.onError(response),\n );\n }\n\n private onError(error: string) {\n this.jhiAlertService.error(error);\n }\n}\n" }, { "alpha_fraction": 0.6162698268890381, "alphanum_fraction": 0.6186507940292358, "avg_line_length": 33.52054977416992, "blob_id": "4671736e60be0fd433393ab1fbd21fa4e5c248b9", "content_id": "0ae40a707705f26c4e620cb75e64f0157a6c0dcc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2520, "license_type": "permissive", "max_line_length": 108, "num_lines": 73, "path": "/src/test/javascript/spec/service/exerciseUnit.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ExerciseUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/exerciseUnit.service';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { ExerciseUnit } from 'app/entities/lecture-unit/exerciseUnit.model';\nimport { ArtemisTestModule } from '../test.module';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { take } from 'rxjs/operators';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Exercise Unit Service', () => {\n let injector: TestBed;\n let service: ExerciseUnitService;\n let httpMock: HttpTestingController;\n let elemDefault: ExerciseUnit;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n providers: [\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n });\n injector = getTestBed();\n service = injector.get(ExerciseUnitService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new ExerciseUnit();\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n\n it('should be created', () => {\n expect(service).to.be.ok;\n });\n\n it('should create an ExerciseUnit', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n service.create(new ExerciseUnit(), 0).pipe(take(1)).subscribe();\n\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should find all by Lecture Id', async () => {\n const returnedFromService = [\n Object.assign(\n {\n id: 0,\n },\n elemDefault,\n ),\n ];\n service.findAllByLectureId(0).pipe(take(1)).subscribe();\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n});\n" }, { "alpha_fraction": 0.6649023294448853, "alphanum_fraction": 0.6690405011177063, "avg_line_length": 41.068824768066406, "blob_id": "60e5743c4d84e2a12caf85796a9827cc9c6927d4", "content_id": "2290eff0145eef607157c3b330ca2b6fc634b84b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10391, "license_type": "permissive", "max_line_length": 118, "num_lines": 247, "path": "/src/test/javascript/spec/component/exam/participate/exam-participation-cover.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClientModule } from '@angular/common/http';\nimport { EventEmitter } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { Router } from '@angular/router';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport { Course } from 'app/entities/course.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { ExamParticipationCoverComponent } from 'app/exam/participate/exam-cover/exam-participation-cover.component';\nimport { ExamParticipationService } from 'app/exam/participate/exam-participation.service';\nimport { ExamInformationComponent } from 'app/exam/participate/information/exam-information.component';\nimport { ExamTimerComponent } from 'app/exam/participate/timer/exam-timer.component';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent } from 'ng-mocks/dist/lib/mock-component/mock-component';\nimport { MockDirective } from 'ng-mocks/dist/lib/mock-directive/mock-directive';\nimport { MockPipe } from 'ng-mocks/dist/lib/mock-pipe/mock-pipe';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs/internal/observable/of';\nimport * as sinon from 'sinon';\nimport { spy } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../../helpers/mocks/service/mock-route.service';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ExamParticipationCoverComponent', () => {\n const course = { id: 456 } as Course;\n const exam: Exam = new Exam();\n exam.course = course;\n exam.id = 123;\n const studentExam: StudentExam = new StudentExam();\n studentExam.testRun = false;\n\n let component: ExamParticipationCoverComponent;\n let fixture: ComponentFixture<ExamParticipationCoverComponent>;\n let examParticipationService: ExamParticipationService;\n let accountService: AccountService;\n let artemisServerDateService: ArtemisServerDateService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientModule, FormsModule],\n declarations: [\n ExamParticipationCoverComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(FaIconComponent),\n MockComponent(AlertErrorComponent),\n MockComponent(ExamTimerComponent),\n MockComponent(ExamInformationComponent),\n MockDirective(JhiTranslateDirective),\n ],\n providers: [\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: Router, useValue: MockRouter },\n ],\n }).compileComponents();\n fixture = TestBed.createComponent(ExamParticipationCoverComponent);\n component = fixture.componentInstance;\n examParticipationService = TestBed.inject(ExamParticipationService);\n accountService = TestBed.inject(AccountService);\n artemisServerDateService = TestBed.inject(ArtemisServerDateService);\n });\n beforeEach(() => {\n component.startView = false;\n component.exam = exam;\n component.studentExam = studentExam;\n component.handInEarly = false;\n component.handInPossible = true;\n component.testRunStartTime = null;\n });\n\n afterEach(function () {\n component.ngOnDestroy();\n sinon.restore();\n jest.clearAllMocks();\n });\n\n it('should initialize with ngOnInit', fakeAsync(() => {\n const user = { name: 'admin' } as User;\n spyOn(accountService, 'identity').and.returnValue(Promise.resolve(user));\n\n let now = moment();\n component.studentExam.workingTime = 1;\n component.exam.gracePeriod = 1;\n component.exam.startDate = now;\n\n component.ngOnInit();\n tick();\n\n expect(component.graceEndDate).to.deep.equal(now.add(1, 'seconds').add(1, 'seconds'));\n expect(component.accountName).to.equal(user.name);\n\n now = moment();\n component.startView = true;\n component.exam.startDate = now;\n component.ngOnInit();\n expect(component.formattedStartDate).to.deep.equal(now.format('LT'));\n\n now = moment();\n component.studentExam.workingTime = 1;\n component.exam.gracePeriod = 1;\n component.testRunStartTime = now;\n component.studentExam.testRun = true;\n component.ngOnInit();\n expect(component.graceEndDate).to.deep.equal(now.add(1, 'seconds').add(1, 'seconds'));\n }));\n\n it('should update confirmation', () => {\n fixture.detectChanges();\n\n component.startView = true;\n component.updateConfirmation();\n expect(component.startEnabled).to.be.false;\n\n component.startView = false;\n component.updateConfirmation();\n expect(component.endEnabled).to.be.false;\n });\n\n it('should start exam', fakeAsync(() => {\n jest.useFakeTimers();\n component.testRun = true;\n const exercise = { id: 99, type: ExerciseType.MODELING } as Exercise;\n component.studentExam.exercises = [exercise];\n const saveStudentExamSpy = spy(examParticipationService, 'saveStudentExamToLocalStorage');\n\n component.startExam();\n\n expect(saveStudentExamSpy).to.be.calledOnceWith(exam!.course!.id, exam!.id, studentExam);\n\n component.testRun = false;\n spyOn(examParticipationService, 'loadStudentExamWithExercisesForConduction').and.returnValue(of(studentExam));\n component.exam.startDate = moment().subtract(1, 'days');\n\n component.startExam();\n tick();\n expect(component.studentExam).to.deep.equal(studentExam);\n\n component.testRun = false;\n const startDate = moment();\n const now = moment();\n component.exam.startDate = startDate.add(1, 'hours');\n spyOn(artemisServerDateService, 'now').and.returnValue(now);\n component.startExam();\n tick();\n jest.advanceTimersByTime(101); // simulate setInterval time passing\n expect(component.waitingForExamStart).to.be.true;\n const difference = Math.ceil(component.exam.startDate.diff(now, 'seconds') / 60);\n expect(component.timeUntilStart).to.equal(difference + ' min');\n\n component.exam.startDate = undefined;\n component.startExam();\n tick();\n jest.advanceTimersByTime(101); // simulate setInterval time passing\n expect(component.waitingForExamStart).to.be.true;\n expect(component.timeUntilStart).to.equal('');\n }));\n\n it('test run should always have already started', () => {\n component.testRun = true;\n expect(component.hasStarted()).to.be.true;\n });\n\n it('should update displayed times if exam suddenly started ', () => {\n component.testRun = true;\n component.exam.startDate = moment();\n component.onExamStarted = new EventEmitter<StudentExam>();\n const eventSpy = spy(component.onExamStarted, 'emit');\n\n component.updateDisplayedTimes(studentExam);\n expect(eventSpy).to.be.calledOnce;\n });\n\n it('should create the relative time text correctly', () => {\n let result = component.relativeTimeText(100);\n expect(result).to.equal('1 min 40 s');\n result = component.relativeTimeText(10);\n expect(result).to.equal('10 s');\n });\n\n it('should submit exam', () => {\n component.onExamEnded = new EventEmitter<StudentExam>();\n const saveStudentExamSpy = spy(component.onExamEnded, 'emit');\n component.submitExam();\n expect(saveStudentExamSpy).to.be.calledOnce;\n });\n\n it('should continue after handing in early', () => {\n component.onExamContinueAfterHandInEarly = new EventEmitter<void>();\n const saveStudentExamSpy = spy(component.onExamContinueAfterHandInEarly, 'emit');\n component.continueAfterHandInEarly();\n expect(saveStudentExamSpy).to.be.calledOnce;\n });\n\n it('should get start button enabled and end button enabled', () => {\n fixture.detectChanges();\n component.testRun = true;\n expect(component.startButtonEnabled).to.be.false;\n\n const now = moment();\n spyOn(artemisServerDateService, 'now').and.returnValue(now);\n component.testRun = false;\n component.enteredName = 'admin';\n component.accountName = 'admin';\n component.confirmed = true;\n component.exam.visibleDate = moment().subtract(1, 'hours');\n expect(component.startButtonEnabled).to.be.true;\n\n component.handInPossible = true;\n expect(component.endButtonEnabled).to.be.true;\n });\n\n it('should get end button enabled', () => {\n component.enteredName = 'admin';\n expect(component.inserted).to.be.true;\n });\n\n it('should get whether student failed to submit', () => {\n component.testRun = true;\n expect(component.studentFailedToSubmit).to.be.false;\n\n component.testRun = false;\n const startDate = moment();\n const now = moment();\n spyOn(artemisServerDateService, 'now').and.returnValue(now);\n component.exam.startDate = startDate.subtract(2, 'hours');\n component.studentExam.workingTime = 3600;\n component.exam.gracePeriod = 1;\n component.studentExam.submitted = false;\n expect(component.studentFailedToSubmit).to.be.true;\n });\n});\n" }, { "alpha_fraction": 0.6615605354309082, "alphanum_fraction": 0.6620392799377441, "avg_line_length": 39.17307662963867, "blob_id": "bfdfa65dc2cb10ac53fc66b455c48520256d483e", "content_id": "a37a3300cf3c8bd1741c58901a35f9dab41a3a63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2089, "license_type": "permissive", "max_line_length": 114, "num_lines": 52, "path": "/src/test/javascript/spec/component/markdown-editor/underline-command.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\n\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { ArtemisTestModule } from '../../test.module';\nimport * as sinon from 'sinon';\nimport { UnderlineCommand } from 'app/shared/markdown-editor/commands/underline.command';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Underline Command', () => {\n let comp: MarkdownEditorComponent;\n let fixture: ComponentFixture<MarkdownEditorComponent>;\n let underlineCommand = new UnderlineCommand();\n\n afterEach(() => {\n sinon.restore();\n });\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), AceEditorModule, ArtemisMarkdownEditorModule],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(MarkdownEditorComponent);\n comp = fixture.componentInstance;\n underlineCommand = new UnderlineCommand();\n comp.defaultCommands = [underlineCommand];\n });\n });\n it('should add <ins></ins> brackets on execute when no text is selected', () => {\n fixture.detectChanges();\n comp.ngAfterViewInit();\n\n underlineCommand.execute();\n expect(comp.aceEditorContainer.getEditor().getValue()).to.equal('<ins></ins>');\n });\n\n it('should add <ins></ins> around selected text on execute when text is selected', () => {\n fixture.detectChanges();\n comp.ngAfterViewInit();\n comp.aceEditorContainer.getEditor().setValue('lorem');\n underlineCommand.execute();\n expect(comp.aceEditorContainer.getEditor().getValue()).to.equal('<ins>lorem</ins>');\n });\n});\n" }, { "alpha_fraction": 0.7456406354904175, "alphanum_fraction": 0.7456406354904175, "avg_line_length": 50.72549057006836, "blob_id": "063e62500c23af2a42acaec0ce1757852a67e8be", "content_id": "6ac4cc40f4293894c4170255a2a115caa9a8bbac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2638, "license_type": "permissive", "max_line_length": 141, "num_lines": 51, "path": "/src/main/webapp/app/exercises/programming/manage/services/programming-exercise-simulation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { EntityResponseType, ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { HttpClient } from '@angular/common/http';\nimport { map } from 'rxjs/operators';\nimport { Observable } from 'rxjs/Observable';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\n/**\n *\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n@Injectable({ providedIn: 'root' })\nexport class ProgrammingExerciseSimulationService {\n public resourceUrl = SERVER_API_URL + 'api/programming-exercises';\n\n constructor(\n private http: HttpClient,\n private programmingExerciseService: ProgrammingExerciseService,\n private profileService: ProfileService,\n private exerciseService: ExerciseService,\n ) {}\n\n /**\n * Triggers the creation and setup of a new programming exercise without connection\n * to the VCS and CI\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param programmingExercise\n */\n automaticSetupWithoutConnectionToVCSandCI(programmingExercise: ProgrammingExercise): Observable<EntityResponseType> {\n let copy = this.programmingExerciseService.convertDataFromClient(programmingExercise);\n copy = this.exerciseService.setBonusPointsConstrainedByIncludedInOverallScore(copy);\n return this.http\n .post<ProgrammingExercise>(this.resourceUrl + '/no-vcs-and-ci-available', copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.programmingExerciseService.convertDateFromServer(res)));\n }\n\n /**\n * Checks if the current environment is production, if yes the method throws an error\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * It should prevent developers from misusing methods, which should be only used for testing\n */\n failsIfInProduction(isInProduction: boolean) {\n if (isInProduction) {\n alert('This action is NOT supported on production and should NOT be visible. Please contact a developer immediately!');\n throw new Error('This action is NOT supported on production and should NOT be visible. Please contact a developer immediately!');\n }\n }\n}\n" }, { "alpha_fraction": 0.6563845872879028, "alphanum_fraction": 0.656823992729187, "avg_line_length": 39.06690216064453, "blob_id": "bd2481bc49aec3d1226fc800b2a381a3b18d3583", "content_id": "71c3056b4bccb8730e2a47f5fff636a1963a676e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11379, "license_type": "permissive", "max_line_length": 169, "num_lines": 284, "path": "/src/main/webapp/app/exercises/shared/participation/participation.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { Subscription } from 'rxjs/Subscription';\nimport { JhiAlertService, JhiEventManager } from 'ng-jhipster';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { ParticipationService } from './participation.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ExerciseSubmissionState, ProgrammingSubmissionService, ProgrammingSubmissionState } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { Subject } from 'rxjs';\nimport { tap } from 'rxjs/operators';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { areManualResultsAllowed } from 'app/exercises/shared/exercise/exercise-utils';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { formatTeamAsSearchResult } from 'app/exercises/shared/team/team.utils';\nimport { AccountService } from 'app/core/auth/account.service';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { defaultLongDateTimeFormat } from 'app/shared/pipes/artemis-date.pipe';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\n\nenum FilterProp {\n ALL = 'all',\n FAILED = 'failed',\n NO_SUBMISSIONS = 'no-submissions',\n}\n\n@Component({\n selector: 'jhi-participation',\n templateUrl: './participation.component.html',\n})\nexport class ParticipationComponent implements OnInit, OnDestroy {\n // make constants available to html for comparison\n readonly FilterProp = FilterProp;\n\n readonly ExerciseType = ExerciseType;\n readonly ActionType = ActionType;\n readonly FeatureToggle = FeatureToggle;\n\n participations: StudentParticipation[] = [];\n filteredParticipationsSize = 0;\n eventSubscriber: Subscription;\n paramSub: Subscription;\n exercise: Exercise;\n newManualResultAllowed: boolean;\n hasLoadedPendingSubmissions = false;\n presentationScoreEnabled = false;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n participationCriteria: {\n filterProp: FilterProp;\n };\n\n exerciseSubmissionState: ExerciseSubmissionState;\n\n isLoading: boolean;\n\n constructor(\n private route: ActivatedRoute,\n private participationService: ParticipationService,\n private jhiAlertService: JhiAlertService,\n private eventManager: JhiEventManager,\n private exerciseService: ExerciseService,\n private programmingSubmissionService: ProgrammingSubmissionService,\n private accountService: AccountService,\n ) {\n this.participationCriteria = {\n filterProp: FilterProp.ALL,\n };\n }\n\n /**\n * Initialize component by calling loadAll and registerChangeInParticipation\n */\n ngOnInit() {\n this.loadAll();\n this.registerChangeInParticipations();\n }\n\n /**\n * Unsubscribe from all subscriptions and destroy eventSubscriber\n */\n ngOnDestroy() {\n this.programmingSubmissionService.unsubscribeAllWebsocketTopics(this.exercise);\n this.eventManager.destroy(this.eventSubscriber);\n this.dialogErrorSource.unsubscribe();\n }\n\n loadAll() {\n this.paramSub = this.route.params.subscribe((params) => {\n this.isLoading = true;\n this.hasLoadedPendingSubmissions = false;\n this.exerciseService.find(params['exerciseId']).subscribe((exerciseResponse) => {\n this.exercise = exerciseResponse.body!;\n this.participationService.findAllParticipationsByExercise(params['exerciseId'], true).subscribe((participationsResponse) => {\n this.participations = participationsResponse.body!;\n this.isLoading = false;\n });\n if (this.exercise.type === ExerciseType.PROGRAMMING) {\n this.programmingSubmissionService\n .getSubmissionStateOfExercise(this.exercise.id!)\n .pipe(\n tap((exerciseSubmissionState: ExerciseSubmissionState) => {\n this.exerciseSubmissionState = exerciseSubmissionState;\n }),\n )\n .subscribe(() => (this.hasLoadedPendingSubmissions = true));\n }\n this.newManualResultAllowed = areManualResultsAllowed(this.exercise);\n this.presentationScoreEnabled = this.checkPresentationScoreConfig();\n this.hasAccessRights();\n });\n });\n }\n\n formatDate(date: Moment | Date | undefined) {\n // TODO: we should try to use the artemis date pipe here\n return date ? moment(date).format(defaultLongDateTimeFormat) : '';\n }\n\n hasAccessRights() {\n if (this.exercise.course) {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.course);\n } else if (this.exercise.exerciseGroup) {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.exerciseGroup.exam?.course!);\n }\n }\n\n updateParticipationFilter(newValue: FilterProp) {\n this.isLoading = true;\n setTimeout(() => {\n this.participationCriteria.filterProp = newValue;\n this.isLoading = false;\n });\n }\n\n filterParticipationByProp = (participation: Participation) => {\n switch (this.participationCriteria.filterProp) {\n case FilterProp.FAILED:\n return this.hasFailedSubmission(participation);\n case FilterProp.NO_SUBMISSIONS:\n return participation.submissionCount === 0;\n case FilterProp.ALL:\n default:\n return true;\n }\n };\n\n private hasFailedSubmission(participation: Participation) {\n const submissionStateObj = this.exerciseSubmissionState[participation.id!];\n if (submissionStateObj) {\n const { submissionState } = submissionStateObj;\n return submissionState === ProgrammingSubmissionState.HAS_FAILED_SUBMISSION;\n }\n return false;\n }\n\n trackId(index: number, item: Participation) {\n return item.id;\n }\n\n registerChangeInParticipations() {\n this.eventSubscriber = this.eventManager.subscribe('participationListModification', () => this.loadAll());\n }\n\n checkPresentationScoreConfig(): boolean {\n if (!this.exercise.course) {\n return false;\n }\n return this.exercise.isAtLeastTutor === true && this.exercise.course.presentationScore !== 0 && this.exercise.presentationScoreEnabled === true;\n }\n\n addPresentation(participation: StudentParticipation) {\n if (!this.presentationScoreEnabled) {\n return;\n }\n participation.presentationScore = 1;\n this.participationService.update(participation).subscribe(\n () => {},\n () => {\n this.jhiAlertService.error('artemisApp.participation.addPresentation.error');\n },\n );\n }\n\n removePresentation(participation: StudentParticipation) {\n if (!this.presentationScoreEnabled) {\n return;\n }\n participation.presentationScore = 0;\n this.participationService.update(participation).subscribe(\n () => {},\n () => {\n this.jhiAlertService.error('artemisApp.participation.removePresentation.error');\n },\n );\n }\n\n /**\n * Deletes participation\n * @param participationId the id of the participation that we want to delete\n * @param $event passed from delete dialog to represent if checkboxes were checked\n */\n deleteParticipation(participationId: number, $event: { [key: string]: boolean }) {\n const deleteBuildPlan = $event.deleteBuildPlan ? $event.deleteBuildPlan : false;\n const deleteRepository = $event.deleteRepository ? $event.deleteRepository : false;\n this.participationService.delete(participationId, { deleteBuildPlan, deleteRepository }).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'participationListModification',\n content: 'Deleted an participation',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n /**\n * Cleans programming exercise participation\n * @param programmingExerciseParticipation the id of the participation that we want to delete\n */\n cleanupProgrammingExerciseParticipation(programmingExerciseParticipation: StudentParticipation) {\n this.participationService.cleanupBuildPlan(programmingExerciseParticipation).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'participationListModification',\n content: 'Cleanup the build plan of an participation',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n /**\n * Update the number of filtered participations\n *\n * @param filteredParticipationsSize Total number of participations after filters have been applied\n */\n handleParticipationsSizeChange = (filteredParticipationsSize: number) => {\n this.filteredParticipationsSize = filteredParticipationsSize;\n };\n\n /**\n * Formats the results in the autocomplete overlay.\n *\n * @param participation\n */\n searchResultFormatter = (participation: StudentParticipation) => {\n if (participation.student) {\n const { login, name } = participation.student;\n return `${login} (${name})`;\n } else if (participation.team) {\n return formatTeamAsSearchResult(participation.team);\n }\n };\n\n /**\n * Converts a participation object to a string that can be searched for. This is\n * used by the autocomplete select inside the data table.\n *\n * @param participation Student participation\n */\n searchTextFromParticipation = (participation: StudentParticipation): string => {\n return participation.student?.login || participation.team?.shortName || '';\n };\n\n /**\n * Removes the login from the repositoryURL\n *\n * @param participation Student participation\n * @param repoUrl original repository url\n */\n getRepositoryLink = (participation: StudentParticipation, repoUrl: String) => {\n if ((participation as ProgrammingExerciseStudentParticipation).repositoryUrl === repoUrl) {\n return (participation as ProgrammingExerciseStudentParticipation).userIndependentRepositoryUrl;\n }\n return repoUrl;\n };\n}\n" }, { "alpha_fraction": 0.7123953700065613, "alphanum_fraction": 0.7151097059249878, "avg_line_length": 54.61006164550781, "blob_id": "a212bd2dfbbd62ed81b70718e2d7d55dcf14f6e0", "content_id": "907c5c82632526a4f58eac8b0d9c356e0afdd5ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8842, "license_type": "permissive", "max_line_length": 179, "num_lines": 159, "path": "/src/main/java/de/tum/in/www1/artemis/service/compass/controller/ModelSelector.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.compass.controller;\n\nimport java.util.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.stream.Collectors;\n\nimport de.tum.in.www1.artemis.service.compass.umlmodel.UMLDiagram;\n\npublic class ModelSelector {\n\n /**\n * Maximal number of models that are considered for calculating the next optimal models that need to be assessed, i.e. we take the MAX_CANDIDATE_LIST_SIZE models with the\n * lowest coverage as candidates for the next optimal models at max. These candidates are then further processed (see selectNextModels method). We use this limit to prevent\n * that the selection of the next optimal models takes too much time.\n */\n private static final int MAX_CANDIDATE_LIST_SIZE = 50;\n\n /**\n * This is used when calculating the models with the highest similarity to all other models. The models are stored together with their calculated similarity in a\n * SortedMap<Double, Long> that maps similarity -> modelId (see computeModelsWithHighestSimilarity method). We add this small amount to every similarity to prevent duplicates.\n * E.g if all models are exactly the same, their similarity is exactly the same as well. This would result in only one element in the sorted map as duplicate keys are not\n * permitted. So we add a small epsilon value that does not impact the order of the similarities, but prevents these duplicate similarity values.\n */\n private static final double EPSILON = 0.0000001;\n\n /**\n * Tracks which models have been selected for assessment. Typically these models are the ones where Compass learns the most, when they are assessed. All models in this set do\n * not have a complete assessment. Models get removed from this set when they are locked by a tutor for assessment or a manual (complete) assessment exists. The key is the\n * ModelSubmission id.\n */\n private Set<Long> modelsWaitingForAssessment = ConcurrentHashMap.newKeySet();\n\n /**\n * Tracks which models have already been assessed completely or which have been marked as optimal before (they do not necessarily need to be completely assessed though).\n * Basically this set contains all modelsWaitingForAssessment + all models that are already assessed. Models that are in this set are not considered by the ModelSelector when\n * selecting the next optimal model. The key is the ModelSubmission id.\n */\n private Set<Long> alreadyHandledModels = ConcurrentHashMap.newKeySet();\n\n private AutomaticAssessmentController automaticAssessmentController;\n\n public ModelSelector(AutomaticAssessmentController automaticAssessmentController) {\n this.automaticAssessmentController = automaticAssessmentController;\n }\n\n /**\n * Calculate the given number of models which would mean the biggest knowledge gain to support the automatic assessment process. The selected models are currently unassessed\n * and not queued for assessment (i.e. in alreadyHandledModels). Which models mean the biggest knowledge gain is decided based on the coverage and the mean similarity of the\n * models, i.e. models that have a low coverage but a high mean similarity with reference to all other models are considered \"optimal\" and will be returned.\n *\n * @param modelIndex contains and manages all the models\n * @param numberOfModels the number of models that should be loaded\n * @return the ids of the models which should be assessed next by an assessor, or an empty list if there are no unhandled models\n */\n public List<Long> selectNextModels(ModelIndex modelIndex, int numberOfModels) {\n double threshold = 0.15;\n int maxCandidateListSize = 10;\n\n // Get all models that have not already been handled by the model selector\n List<UMLDiagram> unhandledModels = new ArrayList<>();\n for (UMLDiagram umlModel : modelIndex.getModelCollection()) {\n if (!alreadyHandledModels.contains(umlModel.getModelSubmissionId())) {\n unhandledModels.add(umlModel);\n }\n }\n\n List<UMLDiagram> candidates = unhandledModels;\n candidates.sort(Comparator.comparingDouble(model -> automaticAssessmentController.getLastAssessmentCoverage(model.getModelSubmissionId())));\n // Make sure that the candidate list is not too big\n if (!candidates.isEmpty()) {\n double smallestCoverage = automaticAssessmentController.getLastAssessmentCoverage(candidates.get(0).getModelSubmissionId());\n\n if (smallestCoverage < 1) {\n while (maxCandidateListSize + 5 < candidates.size()\n && smallestCoverage > (automaticAssessmentController.getLastAssessmentCoverage(candidates.get(maxCandidateListSize).getModelSubmissionId()) - threshold)\n && maxCandidateListSize < MAX_CANDIDATE_LIST_SIZE) {\n maxCandidateListSize += 5;\n }\n }\n\n candidates = candidates.subList(0, Math.min(candidates.size(), maxCandidateListSize));\n }\n\n List<Long> nextOptimalModels = computeModelsWithHighestSimilarity(numberOfModels, candidates, unhandledModels);\n\n if (!nextOptimalModels.isEmpty()) {\n alreadyHandledModels.addAll(nextOptimalModels);\n modelsWaitingForAssessment.addAll(nextOptimalModels);\n\n return nextOptimalModels;\n }\n\n // Fallback: if no optimal models could be determined by similarity, select any unassessed models\n for (UMLDiagram model : modelIndex.getModelCollection()) {\n if (automaticAssessmentController.isUnassessed(model.getModelSubmissionId()) && !alreadyHandledModels.contains(model.getModelSubmissionId())) {\n alreadyHandledModels.add(model.getModelSubmissionId());\n modelsWaitingForAssessment.add(model.getModelSubmissionId());\n\n return Collections.singletonList(model.getModelSubmissionId());\n }\n }\n\n return new ArrayList<>();\n }\n\n /**\n * Computes and returns the given number of candidate models with the highest mean similarity, i.e. for every model in the given list of candidate models, it calculates the\n * mean similarity compared to all models in the given list of unhandled models and sorts the candidate models according to the calculated mean similarity. I then returns the\n * given number of candidate models with the highest mean similarity.\n *\n * @param numberOfModels the number of models that should be returned\n * @param candidates the candidate models for which to calculate the mean similarity\n * @param unhandledModels the unhandled models used to calculate the mean similarity of the candidate models\n * @return the given number of candidate models with the highest mean similarity\n */\n private List<Long> computeModelsWithHighestSimilarity(int numberOfModels, List<UMLDiagram> candidates, List<UMLDiagram> unhandledModels) {\n if (numberOfModels == 0 || candidates == null || candidates.isEmpty() || unhandledModels == null || unhandledModels.isEmpty()) {\n return new ArrayList<>();\n }\n\n // Map similarity -> submissionId that is sorted by the similarity. Note, that the map is sorted in reverse order, i.e. highest similarity comes first.\n SortedMap<Double, Long> sortedSimilarityMap = new TreeMap<>(Collections.reverseOrder());\n double epsilon = EPSILON;\n\n for (UMLDiagram candidate : candidates) {\n double similarity = 0;\n\n for (UMLDiagram model : unhandledModels) {\n similarity += model.similarity(candidate);\n }\n\n similarity /= unhandledModels.size();\n // We add a small amount to every similarity to prevent duplicates. E.g if all models are exactly the same, their similarity is exactly the same as well. This would\n // result in only one element in the sorted map as duplicate keys are not permitted. So we add a small amount that does not impact the order of the similarities.\n similarity += epsilon;\n sortedSimilarityMap.put(similarity, candidate.getModelSubmissionId());\n\n epsilon += EPSILON;\n }\n\n return sortedSimilarityMap.values().stream().limit(numberOfModels).collect(Collectors.toList());\n }\n\n public List<Long> getModelsWaitingForAssessment() {\n return new ArrayList<>(modelsWaitingForAssessment);\n }\n\n public void addAlreadyHandledModel(long modelId) {\n alreadyHandledModels.add(modelId);\n }\n\n public void removeModelWaitingForAssessment(long modelId) {\n modelsWaitingForAssessment.remove(modelId);\n }\n\n public void removeAlreadyHandledModel(long modelId) {\n alreadyHandledModels.remove(modelId);\n }\n}\n" }, { "alpha_fraction": 0.7372213006019592, "alphanum_fraction": 0.7379010319709778, "avg_line_length": 52.30434799194336, "blob_id": "9944f47f121eafb236ba8410aaa62cae98a69137", "content_id": "727eebe7b4af11c516a43e23ce52cd0af31ed479", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7356, "license_type": "permissive", "max_line_length": 140, "num_lines": 138, "path": "/src/main/java/de/tum/in/www1/artemis/service/TextExerciseImportService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.repository.*;\n\n@Service\npublic class TextExerciseImportService extends ExerciseImportService {\n\n private final Logger log = LoggerFactory.getLogger(TextExerciseImportService.class);\n\n private final TextExerciseRepository textExerciseRepository;\n\n public TextExerciseImportService(TextExerciseRepository textExerciseRepository, ExampleSubmissionRepository exampleSubmissionRepository,\n SubmissionRepository submissionRepository, ResultRepository resultRepository, TextBlockRepository textBlockRepository) {\n super(exampleSubmissionRepository, submissionRepository, resultRepository, textBlockRepository);\n this.textExerciseRepository = textExerciseRepository;\n }\n\n /**\n * Imports a text exercise creating a new entity, copying all basic values and saving it in the database.\n * All basic include everything except Student-, Tutor participations, and student questions. <br>\n * This method calls {@link #copyTextExerciseBasis(TextExercise)} to set up the basis of the exercise\n * {@link #copyExampleSubmission(Exercise, Exercise)} for a hard copy of the example submissions.\n *\n * @param templateExercise The template exercise which should get imported\n * @param importedExercise The new exercise already containing values which should not get copied, i.e. overwritten\n * @return The newly created exercise\n */\n @NotNull\n public TextExercise importTextExercise(final TextExercise templateExercise, TextExercise importedExercise) {\n log.debug(\"Creating a new Exercise based on exercise {}\", templateExercise);\n TextExercise newExercise = copyTextExerciseBasis(importedExercise);\n textExerciseRepository.save(newExercise);\n newExercise.setExampleSubmissions(copyExampleSubmission(templateExercise, newExercise));\n return newExercise;\n }\n\n /** This helper method copies all attributes of the {@code importedExercise} into the new exercise.\n * Here we ignore all external entities as well as the start-, end-, and asseessment due date.\n *\n * @param importedExercise The exercise from which to copy the basis\n * @return the cloned TextExercise basis\n */\n @NotNull\n private TextExercise copyTextExerciseBasis(TextExercise importedExercise) {\n log.debug(\"Copying the exercise basis from {}\", importedExercise);\n TextExercise newExercise = new TextExercise();\n\n super.copyExerciseBasis(newExercise, importedExercise);\n newExercise.setSampleSolution(importedExercise.getSampleSolution());\n return newExercise;\n }\n\n /** This helper functions does a hard copy of the text blocks and inserts them into {@code newSubmission}\n *\n * @param originalTextBlocks The original text blocks to be copied\n * @param newSubmission The submission in which we enter the new text blocks\n * @return the cloned list of text blocks\n */\n private Set<TextBlock> copyTextBlocks(Set<TextBlock> originalTextBlocks, TextSubmission newSubmission) {\n log.debug(\"Copying the TextBlocks to new TextSubmission: {}\", newSubmission);\n var newTextBlocks = new HashSet<TextBlock>();\n for (TextBlock originalTextBlock : originalTextBlocks) {\n TextBlock newTextBlock = new TextBlock();\n newTextBlock.setAddedDistance(originalTextBlock.getAddedDistance());\n newTextBlock.setCluster(originalTextBlock.getCluster());\n newTextBlock.setEndIndex(originalTextBlock.getEndIndex());\n newTextBlock.setStartIndex(originalTextBlock.getStartIndex());\n newTextBlock.setSubmission(newSubmission);\n newTextBlock.setText(originalTextBlock.getText());\n newTextBlock.computeId();\n textBlockRepository.save(newTextBlock);\n newTextBlocks.add(newTextBlock);\n }\n return newTextBlocks;\n }\n\n /** This functions does a hard copy of the example submissions contained in {@code templateExercise}.\n * To copy the corresponding Submission entity this function calls {@link #copySubmission(Submission)}\n *\n * @param templateExercise {TextExercise} The original exercise from which to fetch the example submissions\n * @param newExercise The new exercise in which we will insert the example submissions\n * @return The cloned set of example submissions\n */\n @Override\n Set<ExampleSubmission> copyExampleSubmission(Exercise templateExercise, Exercise newExercise) {\n log.debug(\"Copying the ExampleSubmissions to new Exercise: {}\", newExercise);\n Set<ExampleSubmission> newExampleSubmissions = new HashSet<>();\n for (ExampleSubmission originalExampleSubmission : templateExercise.getExampleSubmissions()) {\n TextSubmission originalSubmission = (TextSubmission) originalExampleSubmission.getSubmission();\n TextSubmission newSubmission = copySubmission(originalSubmission);\n\n ExampleSubmission newExampleSubmission = new ExampleSubmission();\n newExampleSubmission.setExercise(newExercise);\n newExampleSubmission.setSubmission(newSubmission);\n newExampleSubmission.setAssessmentExplanation(originalExampleSubmission.getAssessmentExplanation());\n\n exampleSubmissionRepository.save(newExampleSubmission);\n newExampleSubmissions.add(newExampleSubmission);\n }\n return newExampleSubmissions;\n }\n\n /** This helper function does a hard copy of the {@code originalSubmission} and stores the values in {@code newSubmission}.\n * To copy the TextBlocks and the submission results this function calls {@link #copyTextBlocks(Set, TextSubmission)} and\n * {@link #copyExampleResult(Result, Submission)} respectively.\n *\n * @param originalSubmission The original submission to be copied.\n * @return The cloned submission\n */\n @Override\n TextSubmission copySubmission(final Submission originalSubmission) {\n TextSubmission newSubmission = new TextSubmission();\n if (originalSubmission != null) {\n log.debug(\"Copying the Submission to new ExampleSubmission: {}\", newSubmission);\n newSubmission.setExampleSubmission(true);\n newSubmission.setSubmissionDate(originalSubmission.getSubmissionDate());\n newSubmission.setLanguage(((TextSubmission) originalSubmission).getLanguage());\n newSubmission.setType(originalSubmission.getType());\n newSubmission.setParticipation(originalSubmission.getParticipation());\n newSubmission.setText(((TextSubmission) originalSubmission).getText());\n newSubmission = submissionRepository.saveAndFlush(newSubmission);\n newSubmission.setBlocks(copyTextBlocks(((TextSubmission) originalSubmission).getBlocks(), newSubmission));\n newSubmission.addResult(copyExampleResult(originalSubmission.getLatestResult(), newSubmission));\n newSubmission = submissionRepository.saveAndFlush(newSubmission);\n }\n return newSubmission;\n }\n}\n" }, { "alpha_fraction": 0.6021279692649841, "alphanum_fraction": 0.6082664132118225, "avg_line_length": 41.683406829833984, "blob_id": "752e21ed44de777bc83eac951377dec0df285dd8", "content_id": "7ac6ace68f985539f7dc23c2796cea4234e67031", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 19549, "license_type": "permissive", "max_line_length": 177, "num_lines": 458, "path": "/src/test/javascript/spec/component/modeling-assessment-editor/modeling-assessment-editor.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { Router } from '@angular/router';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { AssessmentHeaderComponent } from 'app/assessment/assessment-header/assessment-header.component';\nimport { AssessmentLayoutComponent } from 'app/assessment/assessment-layout/assessment-layout.component';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { User } from 'app/core/user/user.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { Complaint } from 'app/entities/complaint.model';\nimport { Course } from 'app/entities/course.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\nimport { Participation, ParticipationType } from 'app/entities/participation/participation.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { getLatestSubmissionResult } from 'app/entities/submission.model';\nimport { ModelingAssessmentEditorComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component';\nimport { ArtemisModelingAssessmentEditorModule } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.module';\nimport { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';\nimport { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of, throwError } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { SinonStub, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { mockedActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route-query-param-map';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ModelingAssessmentEditorComponent', () => {\n let component: ModelingAssessmentEditorComponent;\n let fixture: ComponentFixture<ModelingAssessmentEditorComponent>;\n let service: ModelingAssessmentService;\n let mockAuth: MockAccountService;\n let modelingSubmissionService: ModelingSubmissionService;\n let complaintService: ComplaintService;\n let modelingSubmissionStub: SinonStub;\n let complaintStub: SinonStub;\n let router: any;\n\n beforeEach(fakeAsync(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisModelingAssessmentEditorModule, RouterTestingModule],\n declarations: [],\n providers: [\n JhiLanguageHelper,\n mockedActivatedRoute({}, { showBackButton: 'false', submissionId: 'new', exerciseId: 1 }),\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ModelingAssessmentEditorComponent);\n component = fixture.componentInstance;\n service = TestBed.inject(ModelingAssessmentService);\n modelingSubmissionService = TestBed.inject(ModelingSubmissionService);\n complaintService = TestBed.inject(ComplaintService);\n router = TestBed.inject(Router);\n mockAuth = (fixture.debugElement.injector.get(AccountService) as any) as MockAccountService;\n mockAuth.hasAnyAuthorityDirect([]);\n mockAuth.identity();\n fixture.detectChanges();\n });\n }));\n\n afterEach(() => {\n sinon.restore();\n });\n describe('ngOnInit tests', () => {\n it('ngOnInit', fakeAsync(() => {\n modelingSubmissionStub = stub(modelingSubmissionService, 'getSubmission');\n complaintStub = stub(complaintService, 'findByResultId');\n const submission = ({\n id: 1,\n submitted: true,\n type: 'MANUAL',\n text: 'Test\\n\\nTest\\n\\nTest',\n participation: ({\n type: ParticipationType.SOLUTION,\n exercise: ({\n id: 1,\n problemStatement: 'problemo',\n gradingInstructions: 'grading',\n title: 'title',\n shortName: 'name',\n exerciseGroup: ({\n exam: ({\n course: new Course(),\n } as unknown) as Exam,\n } as unknown) as ExerciseGroup,\n } as unknown) as Exercise,\n } as unknown) as Participation,\n results: [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: true,\n feedbacks: [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ],\n } as unknown) as Result,\n ],\n } as unknown) as ModelingSubmission;\n\n modelingSubmissionStub.returns(of(submission));\n const user = <User>{ id: 99, groups: ['instructorGroup'] };\n const result: Result = <any>{\n feedbacks: [new Feedback()],\n participation: new StudentParticipation(),\n score: 80,\n successful: true,\n submission: new ProgrammingSubmission(),\n assessor: user,\n hasComplaint: true,\n assessmentType: AssessmentType.SEMI_AUTOMATIC,\n id: 2,\n };\n const complaint = <Complaint>{ id: 1, complaintText: 'Why only 80%?', result };\n complaintStub.returns(of({ body: complaint } as HttpResponse<Complaint>));\n\n component.ngOnInit();\n tick(500);\n expect(modelingSubmissionStub).to.have.been.calledOnce;\n expect(component.isLoading).to.be.false;\n expect(component.complaint).to.deep.equal(complaint);\n modelingSubmissionStub.restore();\n }));\n\n it('wrongly call ngOnInit and throw exception', fakeAsync(() => {\n modelingSubmissionStub = stub(modelingSubmissionService, 'getSubmission');\n const response = new HttpErrorResponse({ status: 403 });\n modelingSubmissionStub.returns(throwError(response));\n\n const accountStub = stub(mockAuth, 'hasAnyAuthorityDirect');\n accountStub.returns(true);\n\n component.ngOnInit();\n tick(500);\n expect(modelingSubmissionStub).to.have.been.calledOnce;\n expect(accountStub).to.have.been.calledTwice;\n modelingSubmissionStub.restore();\n accountStub.restore();\n }));\n });\n\n it('should propagate isAtLeastInstructor', fakeAsync(() => {\n const course = new Course();\n course.isAtLeastInstructor = true;\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n mockAuth.isAtLeastInstructorInCourse(course);\n component['checkPermissions']();\n fixture.detectChanges();\n expect(component.isAtLeastInstructor).to.be.true;\n\n let assessmentLayoutComponent: AssessmentHeaderComponent = fixture.debugElement.query(By.directive(AssessmentLayoutComponent)).componentInstance;\n expect(assessmentLayoutComponent.isAtLeastInstructor).to.be.true;\n\n course.isAtLeastInstructor = false;\n mockAuth.isAtLeastInstructorInCourse(course);\n component['checkPermissions']();\n fixture.detectChanges();\n expect(component.isAtLeastInstructor).to.be.false;\n assessmentLayoutComponent = fixture.debugElement.query(By.directive(AssessmentLayoutComponent)).componentInstance;\n expect(assessmentLayoutComponent.isAtLeastInstructor).to.be.false;\n }));\n\n describe('should test the overwrite access rights and return true', () => {\n it('tests the method with instructor rights', fakeAsync(() => {\n const course = new Course();\n course.isAtLeastInstructor = true;\n component.ngOnInit();\n tick(500);\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n expect(component.canOverride).to.be.true;\n }));\n\n it('tests the method with tutor rights and as assessor', fakeAsync(() => {\n const course = new Course();\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n component.isAssessor = true;\n component.complaint = new Complaint();\n component.complaint.id = 0;\n component.complaint.complaintText = 'complaint';\n component.complaint.resultBeforeComplaint = 'result';\n component.ngOnInit();\n tick(500);\n course.isAtLeastInstructor = false;\n mockAuth.isAtLeastInstructorInCourse(course);\n component['checkPermissions']();\n fixture.detectChanges();\n expect(component.isAtLeastInstructor).to.be.false;\n expect(component.canOverride).to.be.false;\n }));\n });\n\n it('should return if user is allowed to only read', fakeAsync(() => {\n component.ngOnInit();\n tick(500);\n component.isAtLeastInstructor = false;\n component.complaint = new Complaint();\n component.complaint.id = 0;\n component.complaint.complaintText = 'complaint';\n component.complaint.resultBeforeComplaint = 'result';\n component.isAssessor = true;\n expect(component.readOnly).to.be.true;\n }));\n\n it('should save assessment', fakeAsync(() => {\n const feedback = new Feedback();\n feedback.id = 2;\n feedback.text = 'This is a test feedback';\n feedback.detailText = 'Feedback';\n feedback.credits = 1;\n feedback.type = FeedbackType.MANUAL_UNREFERENCED;\n component.unreferencedFeedback = [feedback];\n\n component.result = ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n } as unknown) as Result;\n\n component.submission = ({\n id: 1,\n submitted: true,\n type: 'MANUAL',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as ModelingSubmission;\n component.submission.results = [component.result];\n getLatestSubmissionResult(component.submission)!.feedbacks = [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ];\n const fake = sinon.fake.returns(of(getLatestSubmissionResult(component.submission)));\n sinon.replace(service, 'saveAssessment', fake);\n\n component.ngOnInit();\n tick(500);\n component.onSaveAssessment();\n expect(fake).to.have.been.calledOnce;\n }));\n\n it('should try to submit assessment', fakeAsync(() => {\n const course = new Course();\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n component.modelingExercise.assessmentDueDate = moment().subtract(2, 'days');\n\n // make sure feedback is valid\n const feedback = new Feedback();\n feedback.id = 2;\n feedback.text = 'This is a test feedback';\n feedback.detailText = 'Feedback';\n feedback.credits = 1;\n feedback.type = FeedbackType.MANUAL_UNREFERENCED;\n component.unreferencedFeedback = [feedback];\n\n component.submission = ({\n id: 1,\n submitted: true,\n type: 'MANUAL',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as ModelingSubmission;\n component.submission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n } as unknown) as Result,\n ];\n getLatestSubmissionResult(component.submission)!.feedbacks = [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ];\n const fake = sinon.fake.returns(of(getLatestSubmissionResult(component.submission)));\n sinon.replace(service, 'saveAssessment', fake);\n\n const secondFake = sinon.fake.returns(false);\n sinon.replace(window, 'confirm', secondFake);\n\n component.ngOnInit();\n tick(500);\n\n component.onSubmitAssessment();\n\n expect(window.confirm).to.be.calledOnce;\n expect(component.highlightMissingFeedback).to.be.true;\n }));\n\n it('should update assessment after complaint', fakeAsync(() => {\n const complaintResponse = new ComplaintResponse();\n complaintResponse.id = 1;\n complaintResponse.responseText = 'response';\n\n component.submission = ({\n id: 1,\n submitted: true,\n type: 'MANUAL',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as ModelingSubmission;\n\n const comp_result = ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n participation: ({\n type: ParticipationType.SOLUTION,\n results: [],\n } as unknown) as Participation,\n } as unknown) as Result;\n\n const fake = sinon.fake.returns(of({ body: comp_result }));\n sinon.replace(service, 'updateAssessmentAfterComplaint', fake);\n\n component.ngOnInit();\n tick(500);\n\n component.onUpdateAssessmentAfterComplaint(complaintResponse);\n expect(fake).to.have.been.calledOnce;\n expect(component.result?.participation?.results).to.deep.equal([comp_result]);\n }));\n\n it('should cancel the current assessment', fakeAsync(() => {\n const windowFake = sinon.fake.returns(true);\n sinon.replace(window, 'confirm', windowFake);\n\n component.submission = ({\n id: 2,\n submitted: true,\n type: 'MANUAL',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as ModelingSubmission;\n\n const fake = sinon.fake.returns(of());\n sinon.replace(service, 'cancelAssessment', fake);\n\n component.ngOnInit();\n tick(500);\n\n component.onCancelAssessment();\n expect(windowFake).to.have.been.calledOnce;\n expect(fake).to.have.been.calledOnce;\n }));\n\n it('should handle changed feedback', fakeAsync(() => {\n const feedbacks = [\n {\n id: 0,\n credits: 3,\n reference: 'reference',\n } as Feedback,\n {\n id: 1,\n credits: 1,\n } as Feedback,\n ];\n\n component.ngOnInit();\n tick(500);\n\n const course = new Course();\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n component.modelingExercise.maxPoints = 5;\n component.modelingExercise.bonusPoints = 5;\n\n component.onFeedbackChanged(feedbacks);\n expect(component.referencedFeedback).to.have.lengthOf(1);\n expect(component.totalScore).to.be.equal(3);\n }));\n\n describe('test assessNext', () => {\n it('no submissions left', fakeAsync(() => {\n const course = new Course();\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n component.modelingExercise.id = 1;\n\n const routerStub = stub(router, 'navigate');\n const modelingSubmission: ModelingSubmission = { id: 1 };\n const fake = sinon.fake.returns(of(modelingSubmission));\n sinon.replace(modelingSubmissionService, 'getModelingSubmissionForExerciseForCorrectionRoundWithoutAssessment', fake);\n\n component.ngOnInit();\n\n const correctionRound = 1;\n const courseId = 1;\n const exerciseId = 1;\n component.correctionRound = correctionRound;\n component.courseId = courseId;\n component.modelingExercise = { id: exerciseId } as Exercise;\n component.exerciseId = exerciseId;\n const url = ['/course-management', courseId.toString(), 'modeling-exercises', exerciseId.toString(), 'submissions', modelingSubmission.id!.toString(), 'assessment'];\n const queryParams = { queryParams: { 'correction-round': correctionRound } };\n\n tick(500);\n component.assessNext();\n tick(500);\n\n expect(fake).to.have.been.calledOnce;\n expect(routerStub).to.have.been.calledWith(url, queryParams);\n }));\n\n it('throw error while assessNext', fakeAsync(() => {\n const course = new Course();\n component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course, undefined);\n component.modelingExercise.id = 1;\n\n const response = new HttpErrorResponse({ status: 403 });\n const fake = sinon.fake.returns(throwError(response));\n sinon.replace(modelingSubmissionService, 'getModelingSubmissionForExerciseForCorrectionRoundWithoutAssessment', fake);\n\n component.ngOnInit();\n tick(500);\n component.assessNext();\n expect(fake).to.have.been.calledOnce;\n }));\n });\n});\n" }, { "alpha_fraction": 0.6539589166641235, "alphanum_fraction": 0.6539589166641235, "avg_line_length": 33.099998474121094, "blob_id": "a08b1ada3e44f217f9401c0a358f56d067e4021c", "content_id": "b8f5b813f661dc56b2c4660fcde1391ef9957d45", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 341, "license_type": "permissive", "max_line_length": 148, "num_lines": 10, "path": "/src/main/webapp/app/shared/components/help-icon.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\n\n@Component({\n selector: 'jhi-help-icon',\n template: ` <fa-icon [icon]=\"'question-circle'\" class=\"text-secondary\" [placement]=\"placement\" ngbTooltip=\"{{ text | translate }}\"></fa-icon> `,\n})\nexport class HelpIconComponent {\n @Input() placement: string;\n @Input() text: string;\n}\n" }, { "alpha_fraction": 0.7015706896781921, "alphanum_fraction": 0.7015706896781921, "avg_line_length": 46.75, "blob_id": "d9ad224e56ebbbd78c73fd4e588ac4afa7c02fee", "content_id": "b7791375b8e82b11f45ab4e78912d4268077f8fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 573, "license_type": "permissive", "max_line_length": 82, "num_lines": 12, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-auth-server-provider.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Credentials, IAuthServerProvider } from 'app/core/auth/auth-jwt.service';\nimport { Observable } from 'rxjs/Observable';\nimport { of } from 'rxjs';\n\nexport class MockAuthServerProviderService implements IAuthServerProvider {\n getToken = () => 'abc';\n login = (credentials: Credentials) => Observable.empty();\n loginWithToken = (jwt: string, rememberMe: boolean) => Promise.resolve('abc');\n removeAuthTokenFromCaches = () => of(undefined);\n clearCaches = () => of(undefined);\n storeAuthenticationToken = (jwt: string, rememberMe: boolean) => {};\n}\n" }, { "alpha_fraction": 0.6683747172355652, "alphanum_fraction": 0.6696557402610779, "avg_line_length": 42.068965911865234, "blob_id": "0504636bb593b96af6a470e53776917dab5b9323", "content_id": "7339d0b91e0339293c346cd7f61a9e58f338465c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6245, "license_type": "permissive", "max_line_length": 154, "num_lines": 145, "path": "/src/main/java/de/tum/in/www1/artemis/service/exam/StudentExamAccessService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.exam;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\n\nimport java.time.ZonedDateTime;\nimport java.util.Optional;\n\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\n\n/**\n * Service implementation to check student exam access.\n */\n@Service\npublic class StudentExamAccessService {\n\n private final UserRepository userRepository;\n\n private final AuthorizationCheckService authorizationCheckService;\n\n private final CourseRepository courseRepository;\n\n private final ExamRepository examRepository;\n\n private final StudentExamRepository studentExamRepository;\n\n public StudentExamAccessService(CourseRepository courseRepository, UserRepository userRepository, AuthorizationCheckService authorizationCheckService,\n ExamRepository examRepository, StudentExamRepository studentExamRepository) {\n this.courseRepository = courseRepository;\n this.userRepository = userRepository;\n this.authorizationCheckService = authorizationCheckService;\n this.examRepository = examRepository;\n this.studentExamRepository = studentExamRepository;\n }\n\n /**\n * Checks if the current user is allowed to see the requested student exam.\n *\n * @param courseId the if of the course\n * @param examId the id of the exam\n * @param studentExamId the id of the student exam\n * @param isTestRun flag to determine if it is a test run or not\n * @param <T> The type of the return type of the requesting route so that the\n * response can be returned there\n * @return an Optional with a typed ResponseEntity. If it is empty all checks passed\n */\n public <T> Optional<ResponseEntity<T>> checkStudentExamAccess(Long courseId, Long examId, Long studentExamId, boolean isTestRun) {\n User currentUser = userRepository.getUserWithGroupsAndAuthorities();\n return checkStudentExamAccess(courseId, examId, studentExamId, currentUser, isTestRun);\n }\n\n /**\n * Checks if the current user is allowed to see the requested student exam.\n *\n * @param courseId the if of the course\n * @param examId the id of the exam\n * @param studentExamId the id of the student exam\n * @param currentUser the current user\n * @param isTestRun flag to determine if this is a test run or not\n * @param <T> The type of the return type of the requesting route so that the\n * response can be returned there\n * @return an Optional with a typed ResponseEntity. If it is empty all checks passed\n */\n public <T> Optional<ResponseEntity<T>> checkStudentExamAccess(Long courseId, Long examId, Long studentExamId, User currentUser, boolean isTestRun) {\n Optional<ResponseEntity<T>> courseAndExamAccessFailure = checkCourseAndExamAccess(courseId, examId, currentUser, isTestRun);\n if (courseAndExamAccessFailure.isPresent()) {\n return courseAndExamAccessFailure;\n }\n\n // Check that the student exam exists\n Optional<StudentExam> studentExam = studentExamRepository.findById(studentExamId);\n if (studentExam.isEmpty()) {\n return Optional.of(notFound());\n }\n\n // Check that the examId equals the id of the exam of the student exam\n if (!studentExam.get().getExam().getId().equals(examId)) {\n return Optional.of(conflict());\n }\n\n // Check that the student of the required student exam is the current user\n if (!studentExam.get().getUser().equals(currentUser)) {\n return Optional.of(forbidden());\n }\n\n return Optional.empty();\n }\n\n /**\n * Checks if the current user is allowed to access the requested exam.\n *\n * @param courseId the if of the course\n * @param examId the id of the exam\n * @param currentUser the user\n * @param isTestRun flag to determine if this is a testRun\n * @param <T> The type of the return type of the requesting route so that the\n * response can be returned there\n * @return an Optional with a typed ResponseEntity. If it is empty all checks passed\n */\n public <T> Optional<ResponseEntity<T>> checkCourseAndExamAccess(Long courseId, Long examId, User currentUser, boolean isTestRun) {\n // Check that the exam exists\n Optional<Exam> exam = examRepository.findById(examId);\n if (exam.isEmpty()) {\n return Optional.of(notFound());\n }\n\n // Check that the exam belongs to the course\n if (!exam.get().getCourse().getId().equals(courseId)) {\n return Optional.of(conflict());\n }\n\n Course course = courseRepository.findByIdElseThrow(courseId);\n if (isTestRun) {\n // Check that the current user is at least instructor in the course.\n if (!authorizationCheckService.isAtLeastInstructorInCourse(course, currentUser)) {\n return Optional.of(forbidden());\n }\n }\n else {\n // Check that the current user is at least student in the course.\n if (!authorizationCheckService.isAtLeastStudentInCourse(course, currentUser)) {\n return Optional.of(forbidden());\n }\n\n // Check that the exam is already visible. After the exam, we directly show the summary!\n if (exam.get().getVisibleDate() != null && (exam.get().getVisibleDate().isAfter(ZonedDateTime.now()))) {\n return Optional.of(forbidden());\n }\n\n // Check that the current user is registered for the exam\n if (!examRepository.isUserRegisteredForExam(examId, currentUser.getId())) {\n return Optional.of(forbidden());\n }\n }\n\n return Optional.empty();\n }\n}\n" }, { "alpha_fraction": 0.672441303730011, "alphanum_fraction": 0.6733111143112183, "avg_line_length": 45.29530334472656, "blob_id": "d69f16c89c539589d9b5e75fcfa770a2c2e27932", "content_id": "8154ccaa4b8dd37511e53d0a4c3e15c326798db0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13796, "license_type": "permissive", "max_line_length": 144, "num_lines": 298, "path": "/src/test/javascript/spec/component/file-upload-submission/file-upload-submission.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { AccountService } from 'app/core/auth/account.service';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Router } from '@angular/router';\nimport { DebugElement } from '@angular/core';\nimport { By } from '@angular/platform-browser';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { routes } from 'app/exercises/file-upload/participate/file-upload-participation.route';\nimport { FileUploadSubmissionComponent } from 'app/exercises/file-upload/participate/file-upload-submission.component';\nimport { MomentModule } from 'ngx-moment';\nimport { createFileUploadSubmission, MockFileUploadSubmissionService } from '../../helpers/mocks/service/mock-file-upload-submission.service';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { fileUploadExercise } from '../../helpers/mocks/service/mock-file-upload-exercise.service';\nimport { MAX_SUBMISSION_FILE_SIZE } from 'app/shared/constants/input.constants';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport * as moment from 'moment';\nimport { of } from 'rxjs';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service';\nimport { ComplaintsForTutorComponent } from 'app/complaints/complaints-for-tutor/complaints-for-tutor.component';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { ArtemisComplaintsModule } from 'app/complaints/complaints.module';\nimport { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared/exercise-headers/exercise-headers.module';\nimport { RatingModule } from 'app/exercises/shared/rating/rating.module';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('FileUploadSubmissionComponent', () => {\n let comp: FileUploadSubmissionComponent;\n let fixture: ComponentFixture<FileUploadSubmissionComponent>;\n let debugElement: DebugElement;\n let router: Router;\n let fileUploaderService: FileUploaderService;\n let jhiAlertService: JhiAlertService;\n let fileUploadSubmissionService: FileUploadSubmissionService;\n\n const result = { id: 1 } as Result;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n NgxDatatableModule,\n ArtemisResultModule,\n ArtemisSharedModule,\n MomentModule,\n ArtemisComplaintsModule,\n TranslateModule.forRoot(),\n RouterTestingModule.withRoutes([routes[0]]),\n ArtemisSharedComponentModule,\n ArtemisHeaderExercisePageWithDetailsModule,\n RatingModule,\n ],\n declarations: [FileUploadSubmissionComponent, MockComponent(ComplaintsForTutorComponent), MockPipe(HtmlForMarkdownPipe)],\n providers: [\n { provide: AccountService, useClass: MockAccountService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: ComplaintService, useClass: MockComplaintService },\n { provide: FileUploadSubmissionService, useClass: MockFileUploadSubmissionService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(FileUploadSubmissionComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n router = debugElement.injector.get(Router);\n fixture.ngZone!.run(() => {\n router.initialNavigation();\n });\n fileUploaderService = TestBed.inject(FileUploaderService);\n jhiAlertService = TestBed.inject(JhiAlertService);\n fileUploadSubmissionService = debugElement.injector.get(FileUploadSubmissionService);\n });\n });\n\n afterEach(fakeAsync(() => {\n tick();\n fixture.destroy();\n flush();\n }));\n\n it('File Upload Submission is correctly initialized from service', fakeAsync(() => {\n fixture.detectChanges();\n tick();\n // check if properties where assigned correctly on init\n expect(comp.acceptedFileExtensions.replace(/\\./g, '')).to.be.equal(fileUploadExercise.filePattern);\n expect(comp.fileUploadExercise).to.be.equal(fileUploadExercise);\n expect(comp.isAfterAssessmentDueDate).to.be.true;\n\n // check if fileUploadInput is available\n const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));\n expect(fileUploadInput).to.exist;\n expect(fileUploadInput.nativeElement.disabled).to.be.false;\n\n // check if fileUploadLabel value is not set\n const fileUploadLabel = debugElement.query(By.css('.custom-file-label.overflow-ellipsis'));\n expect(fileUploadLabel).to.exist;\n expect(fileUploadLabel.nativeElement.value).to.be.undefined;\n\n // check if extension elements are set\n const extension = debugElement.query(By.css('.ml-1.badge.badge-info'));\n expect(extension).to.exist;\n expect(extension.nativeElement.textContent.replace(/\\s/g, '')).to.be.equal(fileUploadExercise.filePattern!.split(',')[0].toUpperCase());\n }));\n\n it('Submission and file uploaded', fakeAsync(() => {\n // Ignore window confirm\n window.confirm = () => {\n return false;\n };\n const fileName = 'exampleSubmission';\n comp.submissionFile = new File([''], fileName, { type: 'application/pdf' });\n comp.submission = createFileUploadSubmission();\n fixture.detectChanges();\n\n // check if fileUploadLabel value is not set\n const fileUploadLabel = debugElement.query(By.css('.custom-file-label.overflow-ellipsis'));\n expect(fileUploadLabel).to.exist;\n expect(fileUploadLabel.nativeElement.textContent).to.be.equal(fileName);\n\n let submitFileButton = debugElement.query(By.css('jhi-button'));\n spyOn(fileUploaderService, 'uploadFile').and.returnValue(Promise.resolve({ path: 'test' }));\n submitFileButton.nativeElement.click();\n comp.submission!.submitted = true;\n comp.result = new Result();\n fixture.detectChanges();\n\n // check if fileUploadInput is available\n const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));\n expect(fileUploadInput).to.not.exist;\n\n submitFileButton = debugElement.query(By.css('.btn.btn-success'));\n expect(submitFileButton).to.be.null;\n }));\n\n it('Too big file can not be submitted', fakeAsync(() => {\n // Ignore console errors\n console.error = jest.fn();\n\n fixture.detectChanges();\n tick();\n\n const submissionFile = new File([''], 'exampleSubmission.png');\n Object.defineProperty(submissionFile, 'size', { value: MAX_SUBMISSION_FILE_SIZE + 1, writable: false });\n comp.submission = createFileUploadSubmission();\n const jhiErrorSpy = sinon.spy(jhiAlertService, 'error');\n const event = { target: { files: [submissionFile] } };\n comp.setFileSubmissionForExercise(event);\n fixture.detectChanges();\n\n // check that properties are set properly\n expect(jhiErrorSpy.callCount).to.be.equal(1);\n expect(comp.submissionFile).to.be.undefined;\n expect(comp.submission!.filePath).to.be.undefined;\n\n // check if fileUploadInput is available\n const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));\n expect(fileUploadInput).to.exist;\n expect(fileUploadInput.nativeElement.disabled).to.be.false;\n expect(fileUploadInput.nativeElement.value).to.be.equal('');\n }));\n\n it('Incorrect file type can not be submitted', fakeAsync(() => {\n // Ignore console errors\n console.error = jest.fn();\n\n fixture.detectChanges();\n tick();\n\n // Only png and pdf types are allowed\n const submissionFile = new File([''], 'exampleSubmission.jpg');\n comp.submission = createFileUploadSubmission();\n const jhiErrorSpy = sinon.spy(jhiAlertService, 'error');\n const event = { target: { files: [submissionFile] } };\n comp.setFileSubmissionForExercise(event);\n fixture.detectChanges();\n\n // check that properties are set properly\n expect(jhiErrorSpy.callCount).to.be.equal(1);\n expect(comp.submissionFile).to.be.undefined;\n expect(comp.submission!.filePath).to.be.undefined;\n\n // check if fileUploadInput is available\n const fileUploadInput = debugElement.query(By.css('#fileUploadInput'));\n expect(fileUploadInput).to.exist;\n expect(fileUploadInput.nativeElement.disabled).to.be.false;\n expect(fileUploadInput.nativeElement.value).to.be.equal('');\n\n tick();\n fixture.destroy();\n flush();\n }));\n\n it('should not allow to submit after the deadline if the initialization date is before the due date', fakeAsync(() => {\n const submission = createFileUploadSubmission();\n submission.participation!.initializationDate = moment().subtract(2, 'days');\n (<StudentParticipation>submission.participation).exercise!.dueDate = moment().subtract(1, 'days');\n stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));\n comp.submissionFile = new File([''], 'exampleSubmission.png');\n\n fixture.detectChanges();\n tick();\n\n const submitButton = debugElement.query(By.css('jhi-button'));\n expect(submitButton).to.exist;\n expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('true');\n\n tick();\n fixture.destroy();\n flush();\n }));\n\n it('should allow to submit after the deadline if the initialization date is after the due date', fakeAsync(() => {\n const submission = createFileUploadSubmission();\n submission.participation!.initializationDate = moment().add(1, 'days');\n (<StudentParticipation>submission.participation).exercise!.dueDate = moment();\n stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));\n comp.submissionFile = new File([''], 'exampleSubmission.png');\n\n fixture.detectChanges();\n tick();\n\n expect(comp.isLate).to.be.true;\n const submitButton = debugElement.query(By.css('jhi-button'));\n expect(submitButton).to.exist;\n expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('false');\n\n tick();\n fixture.destroy();\n flush();\n }));\n\n it('should not allow to submit if there is a result and no due date', fakeAsync(() => {\n stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(createFileUploadSubmission()));\n comp.submissionFile = new File([''], 'exampleSubmission.png');\n\n fixture.detectChanges();\n tick();\n\n comp.result = result;\n fixture.detectChanges();\n\n const submitButton = debugElement.query(By.css('jhi-button'));\n expect(submitButton).to.exist;\n expect(submitButton.attributes['ng-reflect-disabled']).to.be.equal('true');\n\n tick();\n fixture.destroy();\n flush();\n }));\n\n it('should get inactive as soon as the due date passes the current date', fakeAsync(() => {\n const submission = createFileUploadSubmission();\n (<StudentParticipation>submission.participation).exercise!.dueDate = moment().add(1, 'days');\n stub(fileUploadSubmissionService, 'getDataForFileUploadEditor').returns(of(submission));\n comp.submissionFile = new File([''], 'exampleSubmission.png');\n\n fixture.detectChanges();\n tick();\n comp.participation.initializationDate = moment();\n\n expect(comp.isActive).to.be.true;\n\n comp.fileUploadExercise.dueDate = moment().subtract(1, 'days');\n\n fixture.detectChanges();\n tick();\n\n expect(comp.isActive).to.be.false;\n\n tick();\n fixture.destroy();\n flush();\n }));\n});\n" }, { "alpha_fraction": 0.6068702340126038, "alphanum_fraction": 0.6068702340126038, "avg_line_length": 28.11111068725586, "blob_id": "01bd8f71c7332433af94b21a0dc2d13b7527d378", "content_id": "470691db6dcab4b6b511475c5407805785f67b26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 262, "license_type": "permissive", "max_line_length": 47, "num_lines": 9, "path": "/src/test/javascript/spec/helpers/mocks/mock-router.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { empty, Observable } from 'rxjs';\n\nexport class MockRouter {\n url: string;\n setUrl = (url: string) => (this.url = url);\n navigateByUrl = (url: string) => true;\n navigate = (commands: any[]) => true;\n events: Observable<Event> = empty();\n}\n" }, { "alpha_fraction": 0.6401497721672058, "alphanum_fraction": 0.6417875289916992, "avg_line_length": 35.844825744628906, "blob_id": "838122a5932e92339976ca42341c50e72000c3ab", "content_id": "4f16f46a89fb8fefed5ff497213d6dda4f60f570", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4274, "license_type": "permissive", "max_line_length": 136, "num_lines": 116, "path": "/src/main/webapp/app/exercises/text/assess/manual-textblock-selection/manual-textblock-selection.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, Output, EventEmitter } from '@angular/core';\nimport { TextBlockRef } from 'app/entities/text-block-ref.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextBlock } from 'app/entities/text-block.model';\n\n@Component({\n selector: 'jhi-manual-textblock-selection',\n templateUrl: './manual-textblock-selection.component.html',\n})\nexport class ManualTextblockSelectionComponent {\n @Input() set textBlockRefs(textBlockRefs: TextBlockRef[]) {\n this.textBlockRefGroups = TextBlockRefGroup.fromTextBlockRefs(textBlockRefs);\n }\n get textBlockRefs(): TextBlockRef[] {\n return this.textBlockRefGroups.reduce((previous: TextBlockRef[], group: TextBlockRefGroup) => [...previous, ...group.refs], []);\n }\n @Output() textBlockRefsChange = new EventEmitter<TextBlockRef[]>();\n @Output() textBlockRefAdded = new EventEmitter<TextBlockRef>();\n @Input() selectedRef?: TextBlockRef;\n @Input() readOnly: boolean;\n @Output() selectedRefChange = new EventEmitter<TextBlockRef | undefined>();\n @Input() submission: TextSubmission;\n textBlockRefGroups: TextBlockRefGroup[];\n\n textBlockRefsChangeEmit(): void {\n this.textBlockRefsChange.emit(this.textBlockRefs);\n }\n\n /**\n * Called by <jhi-manual-text-selection> component (form [jhiTextSelect] directive).\n * Select Text within text block ref group and emit to parent component if it is indeed a new text block.\n *\n * @param text response from directive.\n * @param group TextBlockRefGroup of text blocks allowed to select text in.\n */\n handleTextSelection(text: string, group: TextBlockRefGroup): void {\n // Text Selection returns <br> for linebreaks, model uses \\n so we need to convert.\n text = text.replace(/<br>/g, '\\n');\n\n // create new Text Block for text\n const textBlockRef = TextBlockRef.new();\n const textBlock = textBlockRef.block;\n\n const baseIndex = group.startIndex;\n const groupText = group.getText(this.submission);\n\n const startIndexInGroup = groupText.indexOf(text);\n\n if (text.length > groupText.length || startIndexInGroup === -1) {\n return;\n }\n\n if (textBlock) {\n textBlock.startIndex = baseIndex + startIndexInGroup;\n textBlock.endIndex = textBlock.startIndex + text.length;\n textBlock.setTextFromSubmission(this.submission);\n textBlock.computeId();\n const existingRef = this.textBlockRefs.find((ref) => ref.block?.id === textBlock.id);\n\n if (existingRef) {\n existingRef.initFeedback();\n this.selectedRefChange.emit(existingRef);\n } else {\n textBlockRef.initFeedback();\n this.textBlockRefAdded.emit(textBlockRef);\n }\n }\n }\n}\n\nclass TextBlockRefGroup {\n public refs: TextBlockRef[];\n\n constructor(textBlockRef: TextBlockRef) {\n this.refs = [textBlockRef];\n }\n\n get hasFeedback(): boolean {\n return this.refs.length === 1 && !!this.refs[0].feedback;\n }\n\n get singleRef(): TextBlockRef | null {\n return this.hasFeedback ? this.refs[0] : null;\n }\n\n get startIndex(): number {\n return this.refs[0].block!.startIndex!;\n }\n private get endIndex(): number {\n return this.refs[this.refs.length - 1].block!.endIndex!;\n }\n\n getText(submission: TextSubmission): string {\n const textBlock = new TextBlock();\n textBlock.startIndex = this.startIndex;\n textBlock.endIndex = this.endIndex;\n textBlock.setTextFromSubmission(submission);\n\n return textBlock.text!;\n }\n\n addRef(textBlockRef: TextBlockRef) {\n this.refs.push(textBlockRef);\n }\n\n static fromTextBlockRefs = (textBlockRefs: TextBlockRef[]): TextBlockRefGroup[] =>\n textBlockRefs.reduce((groups: TextBlockRefGroup[], elem: TextBlockRef) => {\n const lastGroup = groups[groups.length - 1];\n if (lastGroup && !lastGroup.hasFeedback && !elem.feedback) {\n lastGroup.addRef(elem);\n } else {\n groups.push(new TextBlockRefGroup(elem));\n }\n return groups;\n }, []);\n}\n" }, { "alpha_fraction": 0.614861786365509, "alphanum_fraction": 0.6189397573471069, "avg_line_length": 24.964706420898438, "blob_id": "7fb1afdcfd335a4a1baaf126524a6d95ea744964", "content_id": "8f5b342a46b6b1ea4e92cd16d6c1aac45c40aaa9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2207, "license_type": "permissive", "max_line_length": 176, "num_lines": 85, "path": "/src/main/java/de/tum/in/www1/artemis/service/dto/StudentDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.dto;\n\nimport java.util.Objects;\n\nimport javax.validation.constraints.Size;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class StudentDTO {\n\n @Size(max = 50)\n private String login;\n\n @Size(max = 50)\n private String firstName;\n\n @Size(max = 50)\n private String lastName;\n\n @Size(max = 10)\n private String registrationNumber;\n\n public String getLogin() {\n return login;\n }\n\n public void setLogin(String login) {\n this.login = login;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getRegistrationNumber() {\n return registrationNumber;\n }\n\n public void setRegistrationNumber(String registrationNumber) {\n this.registrationNumber = registrationNumber;\n }\n\n public StudentDTO registrationNumber(String registrationNumber) {\n this.registrationNumber = registrationNumber;\n return this;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o)\n return true;\n if (o == null || getClass() != o.getClass())\n return false;\n StudentDTO that = (StudentDTO) o;\n return Objects.equals(registrationNumber, that.registrationNumber) || Objects.equals(login, that.login);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(registrationNumber) ^ Objects.hash(login);\n }\n\n @Override\n public String toString() {\n return \"StudentDTO{\" + \"login='\" + login + '\\'' + \", firstName='\" + firstName + '\\'' + \", lastName='\" + lastName + '\\'' + \", registrationNumber='\" + registrationNumber\n + '\\'' + '}';\n }\n\n public String toDatabaseString() {\n return \"Student: login='\" + login + '\\'' + \", firstName='\" + firstName + '\\'' + \", lastName='\" + lastName + '\\'' + \", registrationNumber='\" + registrationNumber + '\\'';\n }\n}\n" }, { "alpha_fraction": 0.6926456689834595, "alphanum_fraction": 0.6957678198814392, "avg_line_length": 41.39215850830078, "blob_id": "77f36e67e0114ece0187e5cfe156f19f32579ed6", "content_id": "8acfeeac43b460406ae1124a66fe95fc36c60c86", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8648, "license_type": "permissive", "max_line_length": 131, "num_lines": 204, "path": "/src/test/javascript/spec/component/plagiarism/plagiarism-inspector.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\nimport { ExportToCsv } from 'export-to-csv';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { PlagiarismInspectorComponent } from 'app/exercises/shared/plagiarism/plagiarism-inspector/plagiarism-inspector.component';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { downloadFile } from 'app/shared/util/download.util';\nimport { ModelingPlagiarismResult } from 'app/exercises/shared/plagiarism/types/modeling/ModelingPlagiarismResult';\nimport { PlagiarismStatus } from 'app/exercises/shared/plagiarism/types/PlagiarismStatus';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ArtemisPlagiarismModule } from 'app/exercises/shared/plagiarism/plagiarism.module';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { TextPlagiarismResult } from 'app/exercises/shared/plagiarism/types/text/TextPlagiarismResult';\n\njest.mock('app/shared/util/download.util', () => ({\n downloadFile: jest.fn(),\n}));\n\nconst generateCsv = jest.fn();\n\njest.mock('export-to-csv', () => ({\n ExportToCsv: jest.fn().mockImplementation(() => ({\n generateCsv,\n })),\n}));\n\ndescribe('Plagiarism Inspector Component', () => {\n let comp: PlagiarismInspectorComponent;\n let fixture: ComponentFixture<PlagiarismInspectorComponent>;\n let modelingExerciseService: ModelingExerciseService;\n let programmingExerciseService: ProgrammingExerciseService;\n let textExerciseService: TextExerciseService;\n\n const modelingExercise = { id: 123, type: ExerciseType.MODELING } as ModelingExercise;\n const textExercise = { id: 234, type: ExerciseType.TEXT } as TextExercise;\n const programmingExercise = { id: 345, type: ExerciseType.PROGRAMMING } as ProgrammingExercise;\n const activatedRoute = {\n data: of({ exercise: modelingExercise }),\n };\n const plagiarismResult = {\n comparisons: [\n {\n submissionA: { studentLogin: 'student1A' },\n submissionB: { studentLogin: 'student1B' },\n similarity: 0.5,\n status: PlagiarismStatus.NONE,\n },\n {\n submissionA: { studentLogin: 'student2A' },\n submissionB: { studentLogin: 'student2B' },\n similarity: 0.8,\n status: PlagiarismStatus.NONE,\n },\n {\n submissionA: { studentLogin: 'student3A' },\n submissionB: { studentLogin: 'student3B' },\n similarity: 0.7,\n status: PlagiarismStatus.NONE,\n },\n ],\n } as ModelingPlagiarismResult;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisPlagiarismModule, TranslateTestingModule],\n providers: [{ provide: ActivatedRoute, useValue: activatedRoute }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(PlagiarismInspectorComponent);\n comp = fixture.componentInstance;\n modelingExerciseService = fixture.debugElement.injector.get(ModelingExerciseService);\n programmingExerciseService = fixture.debugElement.injector.get(ProgrammingExerciseService);\n textExerciseService = fixture.debugElement.injector.get(TextExerciseService);\n });\n\n it('should get the minimumSize tootip', () => {\n comp.exercise = { type: ExerciseType.PROGRAMMING } as Exercise;\n\n expect(comp.getMinimumSizeTooltip()).toEqual('artemisApp.plagiarism.minimum-size-tooltip');\n });\n\n it('should get the minimumSize tootip for modeling', () => {\n comp.exercise = { type: ExerciseType.MODELING } as Exercise;\n\n expect(comp.getMinimumSizeTooltip()).toEqual('artemisApp.plagiarism.minimum-size-tooltip-modeling');\n });\n\n it('should get the minimumSize tootip for text', () => {\n comp.exercise = { type: ExerciseType.TEXT } as Exercise;\n\n expect(comp.getMinimumSizeTooltip()).toEqual('artemisApp.plagiarism.minimum-size-tooltip-text');\n });\n\n it('should fetch the plagiarism detection results for modeling exercises', () => {\n comp.exercise = modelingExercise;\n spyOn(modelingExerciseService, 'checkPlagiarism').and.returnValue(of(plagiarismResult));\n\n comp.checkPlagiarism();\n\n expect(modelingExerciseService.checkPlagiarism).toHaveBeenCalled();\n });\n\n it('should fetch the plagiarism detection results for programming exercises', () => {\n comp.exercise = programmingExercise;\n spyOn(programmingExerciseService, 'checkPlagiarism').and.returnValue(of(plagiarismResult));\n\n comp.checkPlagiarism();\n\n expect(programmingExerciseService.checkPlagiarism).toHaveBeenCalled();\n });\n\n it('should fetch the plagiarism detection results for text exercises', () => {\n comp.exercise = textExercise;\n spyOn(textExerciseService, 'checkPlagiarism').and.returnValue(of(plagiarismResult));\n\n comp.checkPlagiarism();\n\n expect(textExerciseService.checkPlagiarism).toHaveBeenCalled();\n });\n\n it('should comparisons by similarity', () => {\n comp.sortComparisonsForResult(plagiarismResult);\n\n expect(plagiarismResult.comparisons[0].similarity).toEqual(0.8);\n });\n\n it('should select a comparison at the given index', () => {\n comp.selectedComparisonIndex = 0;\n comp.selectComparisonAtIndex(1);\n\n expect(comp.selectedComparisonIndex).toEqual(1);\n });\n\n it('should download the plagiarism detection results as JSON', () => {\n comp.exercise = modelingExercise;\n comp.plagiarismResult = plagiarismResult;\n comp.downloadPlagiarismResultsJson();\n\n expect(downloadFile).toHaveBeenCalled();\n });\n\n it('should download the plagiarism detection results as CSV', () => {\n comp.exercise = modelingExercise;\n comp.plagiarismResult = plagiarismResult;\n comp.downloadPlagiarismResultsCsv();\n\n expect(ExportToCsv).toHaveBeenCalled();\n expect(generateCsv).toHaveBeenCalled();\n });\n\n it('should get the latest plagiarism result for modeling exercise', fakeAsync(() => {\n comp.exercise = modelingExercise;\n\n const mockResult = {} as ModelingPlagiarismResult;\n spyOn(modelingExerciseService, 'getLatestPlagiarismResult').and.returnValue(of(mockResult));\n spyOn(comp, 'handlePlagiarismResult');\n\n comp.getLatestPlagiarismResult();\n expect(comp.detectionInProgress).toBe(true);\n\n tick();\n\n expect(modelingExerciseService.getLatestPlagiarismResult).toHaveBeenCalledWith(modelingExercise.id);\n expect(comp.handlePlagiarismResult).toHaveBeenCalledWith(mockResult);\n }));\n\n it('should get the latest plagiarism result for programming exercise', fakeAsync(() => {\n comp.exercise = programmingExercise;\n\n const mockResult = {} as TextPlagiarismResult;\n spyOn(programmingExerciseService, 'getLatestPlagiarismResult').and.returnValue(of(mockResult));\n spyOn(comp, 'handlePlagiarismResult');\n\n comp.getLatestPlagiarismResult();\n expect(comp.detectionInProgress).toBe(true);\n\n tick();\n\n expect(programmingExerciseService.getLatestPlagiarismResult).toHaveBeenCalledWith(programmingExercise.id);\n expect(comp.handlePlagiarismResult).toHaveBeenCalledWith(mockResult);\n }));\n\n it('should get the latest plagiarism result for text exercise', fakeAsync(() => {\n comp.exercise = textExercise;\n\n const mockResult = {} as TextPlagiarismResult;\n spyOn(textExerciseService, 'getLatestPlagiarismResult').and.returnValue(of(mockResult));\n spyOn(comp, 'handlePlagiarismResult');\n\n comp.getLatestPlagiarismResult();\n expect(comp.detectionInProgress).toBe(true);\n\n tick();\n\n expect(textExerciseService.getLatestPlagiarismResult).toHaveBeenCalledWith(textExercise.id);\n expect(comp.handlePlagiarismResult).toHaveBeenCalledWith(mockResult);\n }));\n});\n" }, { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.6734693646430969, "avg_line_length": 20, "blob_id": "d5c832c8efa3ad9b563a81332c31e30d78132223", "content_id": "d2327c916e9a5be7a2a7bb4bdc43c62a42040570", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 147, "license_type": "permissive", "max_line_length": 32, "num_lines": 7, "path": "/src/main/webapp/app/entities/lti-configuration.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class LtiConfiguration {\n public ltiId?: string;\n public ltiPassport?: string;\n public launchUrl?: string;\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.48425719141960144, "alphanum_fraction": 0.5733924508094788, "avg_line_length": 40, "blob_id": "722e9d73d295bcf98f555b2d0b54852e7f0ec64a", "content_id": "d323f68e56cbe59af75e6659630c396afecab107", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2255, "license_type": "permissive", "max_line_length": 110, "num_lines": 55, "path": "/src/test/javascript/spec/util/shared/utils.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { round, stringifyIgnoringFields } from 'app/shared/util/utils';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Utilities', () => {\n void it('Decimal length', () => {\n expect(round(14.821354, 4)).to.be.equal(14.8214);\n expect(round(14.821354, 3)).to.be.equal(14.821);\n expect(round(14.821354, 2)).to.be.equal(14.82);\n expect(round(14.821354, 1)).to.be.equal(14.8);\n expect(round(14.821354, 0)).to.be.equal(15);\n });\n\n void it('Turning points', () => {\n expect(round(2.4999999, 0)).to.be.equal(2);\n expect(round(2.5, 0)).to.be.equal(3);\n expect(round(2.55, 1)).to.be.equal(2.6);\n expect(round(2.555, 2)).to.be.equal(2.56);\n expect(round(2.5555, 3)).to.be.equal(2.556);\n expect(round(2.55555, 4)).to.be.equal(2.5556);\n });\n\n void it('Other', () => {\n expect(round(9.99999999, 0)).to.be.equal(10);\n expect(round(9.99999999, 1)).to.be.equal(10);\n expect(round(5.55555555, 0)).to.be.equal(6);\n expect(round(5.55555555, 1)).to.be.equal(5.6);\n expect(round(1.00000001, 0)).to.be.equal(1);\n expect(round(1.00000001, 1)).to.be.equal(1.0);\n });\n\n void it('should return NaN', () => {\n expect(round(Number.NaN, 2)).to.be.NaN;\n expect(round(Number.NaN, 1)).to.be.NaN;\n expect(round(9.9999, 0.5)).to.NaN;\n });\n});\n\ndescribe('stringifyIgnoringFields', () => {\n it('should ignore nothing', () => {\n expect(stringifyIgnoringFields({})).to.be.equal(JSON.stringify({}));\n expect(stringifyIgnoringFields({}, 'a', 'b')).to.be.equal(JSON.stringify({}));\n expect(stringifyIgnoringFields({ a: 'a' }, 'b')).to.be.equal(JSON.stringify({ a: 'a' }));\n expect(stringifyIgnoringFields({ a: 'a' })).to.be.equal(JSON.stringify({ a: 'a' }));\n });\n\n it('should ignore fields', () => {\n expect(stringifyIgnoringFields({ a: 1 }, 'a')).to.be.equal(JSON.stringify({}));\n expect(stringifyIgnoringFields({ a: 1, c: 2, b: 3 }, 'a', 'b')).to.be.equal(JSON.stringify({ c: 2 }));\n expect(stringifyIgnoringFields({ b: 1, c: 3 }, 'c', 'b')).to.be.equal(JSON.stringify({}));\n });\n});\n" }, { "alpha_fraction": 0.7485833168029785, "alphanum_fraction": 0.7562334537506104, "avg_line_length": 54.726314544677734, "blob_id": "7169c8b7f96bf7a8cc25865dd40a61f527dc9d32", "content_id": "5da4e17cf364eb0d6de03cf08939f8a8bc098ed0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10588, "license_type": "permissive", "max_line_length": 176, "num_lines": 190, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ModelingAssessmentResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport java.util.List;\nimport java.util.Objects;\n\nimport org.hibernate.Hibernate;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.AssessmentService;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.service.WebsocketMessagingService;\nimport de.tum.in.www1.artemis.service.compass.CompassService;\nimport de.tum.in.www1.artemis.service.exam.ExamService;\nimport de.tum.in.www1.artemis.web.rest.errors.ErrorConstants;\nimport io.swagger.annotations.ApiResponse;\nimport io.swagger.annotations.ApiResponses;\n\n/** REST controller for managing ModelingAssessment. */\n@RestController\n@RequestMapping(\"/api\")\npublic class ModelingAssessmentResource extends AssessmentResource {\n\n private final Logger log = LoggerFactory.getLogger(ModelingAssessmentResource.class);\n\n private static final String ENTITY_NAME = \"modelingAssessment\";\n\n private static final String PUT_SUBMIT_ASSESSMENT_200_REASON = \"Given assessment has been saved and used for automatic assessment by Compass\";\n\n private static final String POST_ASSESSMENT_AFTER_COMPLAINT_200_REASON = \"Assessment has been updated after complaint\";\n\n private final CompassService compassService;\n\n private final ModelingExerciseRepository modelingExerciseRepository;\n\n private final AuthorizationCheckService authCheckService;\n\n private final ModelingSubmissionRepository modelingSubmissionRepository;\n\n public ModelingAssessmentResource(AuthorizationCheckService authCheckService, UserRepository userRepository, CompassService compassService,\n ModelingExerciseRepository modelingExerciseRepository, AssessmentService assessmentService, ModelingSubmissionRepository modelingSubmissionRepository,\n ExampleSubmissionRepository exampleSubmissionRepository, WebsocketMessagingService messagingService, ExerciseRepository exerciseRepository,\n ResultRepository resultRepository, ExamService examService, SubmissionRepository submissionRepository) {\n super(authCheckService, userRepository, exerciseRepository, assessmentService, resultRepository, examService, messagingService, exampleSubmissionRepository,\n submissionRepository);\n this.compassService = compassService;\n this.modelingExerciseRepository = modelingExerciseRepository;\n this.authCheckService = authCheckService;\n this.modelingSubmissionRepository = modelingSubmissionRepository;\n }\n\n /**\n * Get the result of the modeling submission with the given id. See {@link AssessmentResource#getAssessmentBySubmissionId}.\n *\n * @param submissionId the id of the submission that should be sent to the client\n * @return the assessment of the given submission\n */\n @GetMapping(\"/modeling-submissions/{submissionId}/result\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<Result> getAssessmentBySubmissionId(@PathVariable Long submissionId) {\n return super.getAssessmentBySubmissionId(submissionId);\n }\n\n /**\n * Retrieve the result for an example submission, only if the user is an instructor or if the example submission is not used for tutorial purposes.\n *\n * @param exerciseId the id of the exercise\n * @param submissionId the id of the example submission\n * @return the result linked to the example submission\n */\n @GetMapping(\"/exercise/{exerciseId}/modeling-submissions/{submissionId}/example-assessment\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Result> getModelingExampleAssessment(@PathVariable long exerciseId, @PathVariable long submissionId) {\n log.debug(\"REST request to get example assessment for tutors text assessment: {}\", submissionId);\n return super.getExampleAssessment(exerciseId, submissionId);\n }\n\n /**\n * PUT modeling-submissions/:submissionId/result/resultId/assessment : save manual modeling assessment. See {@link AssessmentResource#saveAssessment}.\n *\n * @param submissionId id of the submission\n * @param resultId id of the result\n * @param feedbacks list of feedbacks\n * @param submit if true the assessment is submitted, else only saved\n * @return result after saving/submitting modeling assessment\n */\n @ResponseStatus(HttpStatus.OK)\n @ApiResponses({ @ApiResponse(code = 200, message = PUT_SUBMIT_ASSESSMENT_200_REASON, response = Result.class),\n @ApiResponse(code = 403, message = ErrorConstants.REQ_403_REASON), @ApiResponse(code = 404, message = ErrorConstants.REQ_404_REASON) })\n @PutMapping(\"/modeling-submissions/{submissionId}/result/{resultId}/assessment\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Result> saveModelingAssessment(@PathVariable long submissionId, @PathVariable long resultId,\n @RequestParam(value = \"submit\", defaultValue = \"false\") boolean submit, @RequestBody List<Feedback> feedbacks) {\n Submission submission = submissionRepository.findOneWithEagerResultAndFeedback(submissionId);\n ModelingExercise exercise = (ModelingExercise) submission.getParticipation().getExercise();\n\n ResponseEntity<Result> response = super.saveAssessment(submission, submit, feedbacks, resultId);\n\n if (response.getStatusCode().is2xxSuccessful() && submit && compassService.isSupported(exercise)) {\n compassService.addAssessment(exercise.getId(), submissionId, Objects.requireNonNull(response.getBody()).getFeedbacks());\n }\n\n return response;\n }\n\n /**\n * PUT modeling-submissions/:submissionId/example-assessment : save manual example modeling assessment\n *\n * @param exampleSubmissionId id of the example submission\n * @param feedbacks list of feedbacks\n * @return result after saving example modeling assessment\n */\n @ResponseStatus(HttpStatus.OK)\n @ApiResponses({ @ApiResponse(code = 200, message = PUT_SUBMIT_ASSESSMENT_200_REASON, response = Result.class),\n @ApiResponse(code = 403, message = ErrorConstants.REQ_403_REASON), @ApiResponse(code = 404, message = ErrorConstants.REQ_404_REASON) })\n @PutMapping(\"/modeling-submissions/{exampleSubmissionId}/example-assessment\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Result> saveModelingExampleAssessment(@PathVariable long exampleSubmissionId, @RequestBody List<Feedback> feedbacks) {\n log.debug(\"REST request to save modeling example assessment : {}\", exampleSubmissionId);\n return super.saveExampleAssessment(exampleSubmissionId, feedbacks);\n }\n\n /**\n * Update an assessment after a complaint was accepted. After the result is updated accordingly, Compass is notified about the changed assessment in order to adapt all\n * automatic assessments based on this result, as well.\n *\n * @param submissionId the id of the submission for which the assessment should be updated\n * @param assessmentUpdate the assessment update containing the new feedback items and the response to the complaint\n * @return the updated result\n */\n @ResponseStatus(HttpStatus.OK)\n @ApiResponses({ @ApiResponse(code = 200, message = POST_ASSESSMENT_AFTER_COMPLAINT_200_REASON, response = Result.class),\n @ApiResponse(code = 403, message = ErrorConstants.REQ_403_REASON), @ApiResponse(code = 404, message = ErrorConstants.REQ_404_REASON) })\n @PutMapping(\"/modeling-submissions/{submissionId}/assessment-after-complaint\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Result> updateModelingAssessmentAfterComplaint(@PathVariable Long submissionId, @RequestBody AssessmentUpdate assessmentUpdate) {\n log.debug(\"REST request to update the assessment of submission {} after complaint.\", submissionId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n ModelingSubmission modelingSubmission = modelingSubmissionRepository.findOneWithEagerResultAndFeedback(submissionId);\n StudentParticipation studentParticipation = (StudentParticipation) modelingSubmission.getParticipation();\n long exerciseId = studentParticipation.getExercise().getId();\n ModelingExercise modelingExercise = modelingExerciseRepository.findOne(exerciseId);\n checkAuthorization(modelingExercise, user);\n\n Result result = assessmentService.updateAssessmentAfterComplaint(modelingSubmission.getLatestResult(), modelingExercise, assessmentUpdate);\n\n if (compassService.isSupported(modelingExercise)) {\n compassService.addAssessment(exerciseId, submissionId, result.getFeedbacks());\n }\n\n // remove circular dependencies if the results of the participation are there\n if (result.getParticipation() != null && Hibernate.isInitialized(result.getParticipation().getResults()) && result.getParticipation().getResults() != null) {\n result.getParticipation().setResults(null);\n }\n\n if (result.getParticipation() != null && result.getParticipation() instanceof StudentParticipation\n && !authCheckService.isAtLeastInstructorForExercise(modelingExercise, user)) {\n ((StudentParticipation) result.getParticipation()).setParticipant(null);\n }\n\n return ResponseEntity.ok(result);\n }\n\n /**\n * Cancel an assessment of a given submission for the current user, i.e. delete the corresponding result / release the lock. Then the submission is available for assessment\n * again.\n *\n * @param submissionId the id of the submission for which the current assessment should be canceled\n * @return 200 Ok response if canceling was successful, 403 Forbidden if current user is not the assessor of the submission\n */\n @PutMapping(\"/modeling-submissions/{submissionId}/cancel-assessment\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Void> cancelAssessment(@PathVariable Long submissionId) {\n return super.cancelAssessment(submissionId);\n }\n\n @Override\n String getEntityName() {\n return ENTITY_NAME;\n }\n}\n" }, { "alpha_fraction": 0.6673210263252258, "alphanum_fraction": 0.671350359916687, "avg_line_length": 45.533653259277344, "blob_id": "60425ab4a999167818d9820553b882aeedad46f9", "content_id": "58ff4a2a1f12d231f4bdf21004e7e220d9c0daa4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9679, "license_type": "permissive", "max_line_length": 173, "num_lines": 208, "path": "/src/test/javascript/spec/component/exam/manage/student-exams/student-exam-import-dialog.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { By } from '@angular/platform-browser';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { Course } from 'app/entities/course.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { StudentDTO } from 'app/entities/student-dto.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { StudentsExamImportDialogComponent } from 'app/exam/manage/students/students-exam-import-dialog/students-exam-import-dialog.component';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentExamImportDialogComponent', () => {\n let fixture: ComponentFixture<StudentsExamImportDialogComponent>;\n let component: StudentsExamImportDialogComponent;\n let examManagementService: ExamManagementService;\n\n const studentCsvColumns = 'REGISTRATION_NUMBER,FIRST_NAME_OF_STUDENT,FAMILY_NAME_OF_STUDENT';\n\n const course: Course = { id: 1 };\n const exam: Exam = { course, id: 2, title: 'Exam Title' };\n\n beforeEach(() => {\n return TestBed.configureTestingModule({\n imports: [FormsModule],\n declarations: [\n StudentsExamImportDialogComponent,\n MockDirective(JhiTranslateDirective),\n MockPipe(ArtemisTranslatePipe),\n MockComponent(FaIconComponent),\n MockComponent(HelpIconComponent),\n MockComponent(AlertComponent),\n MockComponent(AlertErrorComponent),\n ],\n providers: [{ provide: NgbActiveModal, useValue: sinon.createStubInstance(NgbActiveModal) }, MockProvider(JhiAlertService), MockProvider(ExamManagementService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(StudentsExamImportDialogComponent);\n component = fixture.componentInstance;\n examManagementService = TestBed.inject(ExamManagementService);\n\n component.courseId = course.id!;\n component.exam = exam;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should reset dialog when selecting csv file', async () => {\n component.studentsToImport = [{ registrationNumber: '1', lastName: 'lastName', firstName: 'firstName', login: 'login1' }];\n component.notFoundStudents = [{ registrationNumber: '2', lastName: 'lastName2', firstName: 'firstName2', login: 'login2' }];\n component.hasImported = true;\n\n const event = { target: { files: [studentCsvColumns] } };\n await component.onCSVFileSelect(event);\n\n expect(component.studentsToImport).to.be.empty;\n expect(component.notFoundStudents).to.be.empty;\n });\n\n it('should read no students from csv file', async () => {\n const event = { target: { files: [studentCsvColumns] } };\n await component.onCSVFileSelect(event);\n\n expect(component.studentsToImport).to.be.empty;\n expect(component.notFoundStudents).to.be.empty;\n });\n\n it('should read students from csv file', async () => {\n const csv = `${studentCsvColumns}\\n\"1\",\"Max\",\"Mustermann\"\\n\"2\",\"John\",\"Wick\"`;\n const event = { target: { files: [csv] } };\n await component.onCSVFileSelect(event);\n\n expect(component.studentsToImport.length).to.equal(2);\n expect(component.notFoundStudents).to.be.empty;\n });\n\n it('should have validation error for invalid csv', async () => {\n // Csv without header\n const invalidCsv = `\"1\",\"Max\",\"Mustermann\"\\n\"2\",\"John\",\"Wick\"`;\n\n const event = { target: { files: [invalidCsv] } };\n await component.onCSVFileSelect(event);\n\n expect(component.validationError).to.not.be.empty;\n });\n\n it('should import students', function () {\n const studentsToImport: StudentDTO[] = [\n { registrationNumber: '1', firstName: 'Max', lastName: 'Musetermann', login: 'login1' },\n { registrationNumber: '2', firstName: 'Bob', lastName: 'Ross', login: 'login2' },\n ];\n const studentsNotFound: StudentDTO[] = [{ registrationNumber: '2', firstName: 'Bob', lastName: 'Ross', login: 'login2' }];\n\n const fakeResponse = { body: studentsNotFound } as HttpResponse<StudentDTO[]>;\n sinon.replace(examManagementService, 'addStudentsToExam', sinon.fake.returns(of(fakeResponse)));\n\n component.studentsToImport = studentsToImport;\n component.importStudents();\n\n expect(examManagementService.addStudentsToExam).to.have.been.calledOnce;\n expect(component.isImporting).to.be.false;\n expect(component.hasImported).to.be.true;\n expect(component.notFoundStudents.length).to.equal(studentsNotFound.length);\n });\n\n it('should compute invalid student entries', function () {\n let rowNumbersOrNull = component.computeInvalidStudentEntries([{ firstnameofstudent: 'Max' }]);\n expect(rowNumbersOrNull).to.equal('2');\n\n rowNumbersOrNull = component.computeInvalidStudentEntries([{ firstnameofstudent: 'Max' }, { registrationnumber: '1' }, { login: 'username' }]);\n expect(rowNumbersOrNull).to.equal('2');\n\n rowNumbersOrNull = component.computeInvalidStudentEntries([{ benutzer: 'Max' }, { benutzername: '1' }, { user: 'username' }]);\n expect(rowNumbersOrNull).to.be.null;\n\n rowNumbersOrNull = component.computeInvalidStudentEntries([{ matriculationnumber: '1' }, { matrikelnummer: '1' }]);\n expect(rowNumbersOrNull).to.be.null;\n\n rowNumbersOrNull = component.computeInvalidStudentEntries([{ firstnameofstudent: 'Max' }, { familynameofstudent: 'Mustermann' }]);\n expect(rowNumbersOrNull).to.equal('2, 3');\n\n rowNumbersOrNull = component.computeInvalidStudentEntries([]);\n expect(rowNumbersOrNull).to.be.null;\n });\n\n it('should import correctly', function () {\n const importedStudents: StudentDTO[] = [\n { registrationNumber: '1', firstName: 'Max', lastName: 'Musetermann', login: 'login1' },\n { registrationNumber: '2', firstName: 'Bob', lastName: 'Ross', login: 'login2' },\n ];\n const notImportedStudents: StudentDTO[] = [{ registrationNumber: '3', firstName: 'Some', lastName: 'Dude', login: 'login3' }];\n\n const fakeResponse = { body: notImportedStudents } as HttpResponse<StudentDTO[]>;\n sinon.replace(examManagementService, 'addStudentsToExam', sinon.fake.returns(of(fakeResponse)));\n\n component.studentsToImport = importedStudents.concat(notImportedStudents);\n component.importStudents();\n\n importedStudents.forEach((student) => expect(component.wasImported(student)).to.be.true);\n notImportedStudents.forEach((student) => expect(component.wasImported(student)).to.be.false);\n\n expect(component.numberOfStudentsImported).to.equal(importedStudents.length);\n expect(component.numberOfStudentsNotImported).to.equal(notImportedStudents.length);\n });\n\n it('should invoke REST call on \"Import\" but not on \"Finish\"', function () {\n const studentsToImport: StudentDTO[] = [\n { registrationNumber: '1', firstName: 'Max', lastName: 'Mustermann', login: 'login1' },\n { registrationNumber: '2', firstName: 'Bob', lastName: 'Ross', login: 'login2' },\n ];\n const studentsNotFound: StudentDTO[] = [{ registrationNumber: '3', firstName: 'Some', lastName: 'Dude', login: 'login3' }];\n\n const fakeResponse = { body: studentsNotFound } as HttpResponse<StudentDTO[]>;\n sinon.replace(examManagementService, 'addStudentsToExam', sinon.fake.returns(of(fakeResponse)));\n\n component.studentsToImport = studentsToImport;\n\n fixture.detectChanges();\n\n expect(component.hasImported).to.be.false;\n expect(component.isSubmitDisabled).to.be.false;\n const importButton = fixture.debugElement.query(By.css('#import'));\n expect(importButton).to.exist;\n\n importButton.nativeElement.click();\n\n expect(examManagementService.addStudentsToExam).to.have.been.calledOnce;\n expect(component.isImporting).to.be.false;\n expect(component.hasImported).to.be.true;\n expect(component.notFoundStudents.length).to.equal(studentsNotFound.length);\n\n // Reset call counter\n sinon.restore();\n sinon.replace(examManagementService, 'addStudentsToExam', sinon.fake.returns(of(fakeResponse)));\n\n component.hasImported = true;\n fixture.detectChanges();\n\n const finishButton = fixture.debugElement.query(By.css('#finish-button'));\n expect(finishButton).to.exist;\n\n finishButton.nativeElement.click();\n\n expect(examManagementService.addStudentsToExam).to.not.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.815936267375946, "alphanum_fraction": 0.8191235065460205, "avg_line_length": 47.269229888916016, "blob_id": "f99a8dec662e2c2d2e4fb100c405310fcd960d4a", "content_id": "bd89ee23ef2a923df48d94323642d06a3022bd64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1255, "license_type": "permissive", "max_line_length": 160, "num_lines": 26, "path": "/src/main/java/de/tum/in/www1/artemis/repository/PlagiarismComparisonRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Modifying;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.plagiarism.PlagiarismComparison;\nimport de.tum.in.www1.artemis.domain.plagiarism.PlagiarismStatus;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data JPA repository for the PlagiarismComparison entity.\n */\n@Repository\npublic interface PlagiarismComparisonRepository extends JpaRepository<PlagiarismComparison<?>, Long> {\n\n @Modifying\n @Query(\"UPDATE PlagiarismComparison plagiarismComparison set plagiarismComparison.status = :status where plagiarismComparison.id = :plagiarismComparisonId\")\n void updatePlagiarismComparisonStatus(@Param(\"plagiarismComparisonId\") Long plagiarismComparisonId, @Param(\"status\") PlagiarismStatus status);\n\n default PlagiarismComparison<?> findByIdElseThrow(long comparisonId) {\n return findById(comparisonId).orElseThrow(() -> new EntityNotFoundException(\"PlagiarismComparison\", comparisonId));\n }\n}\n" }, { "alpha_fraction": 0.6673082113265991, "alphanum_fraction": 0.6673082113265991, "avg_line_length": 48.82191848754883, "blob_id": "002c7552704c1ac14793888034064a3cdf977043", "content_id": "6e9110fd91a5fd8d2ed153518a560272dd4754d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3637, "license_type": "permissive", "max_line_length": 118, "num_lines": 73, "path": "/src/test/javascript/spec/service/user-route-access.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { async, ComponentFixture, TestBed } from '@angular/core/testing';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { ActivatedRouteSnapshot, Route } from '@angular/router';\nimport { ArtemisTestModule } from '../test.module';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../helpers/mocks/service/mock-cookie.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../helpers/mocks/service/mock-account.service';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { CookieService } from 'ngx-cookie-service';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport { Mutable } from '../helpers/mutable';\nimport { mockedActivatedRouteSnapshot } from '../helpers/mocks/activated-route/mock-activated-route-snapshot';\nimport { CourseExerciseDetailsComponent } from 'app/overview/exercise-details/course-exercise-details.component';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('UserRouteAccessService', () => {\n const routeStateMock: any = { snapshot: {}, url: '/' };\n const route = 'courses/:courseId/exercises/:exerciseId';\n let fixture: ComponentFixture<CourseExerciseDetailsComponent>;\n let service: UserRouteAccessService;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n HttpClientTestingModule,\n RouterTestingModule.withRoutes([\n {\n path: route,\n component: CourseExerciseDetailsComponent,\n },\n ]),\n ],\n declarations: [CourseExerciseDetailsComponent],\n providers: [\n mockedActivatedRouteSnapshot(route),\n { provide: AccountService, useClass: MockAccountService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: DeviceDetectorService },\n ],\n })\n .overrideTemplate(CourseExerciseDetailsComponent, '')\n .compileComponents()\n .then(() => {\n service = TestBed.inject(UserRouteAccessService);\n fixture = TestBed.createComponent(CourseExerciseDetailsComponent);\n });\n }));\n\n it('should store the JWT token for LTI users', () => {\n const snapshot = fixture.debugElement.injector.get(ActivatedRouteSnapshot) as Mutable<ActivatedRouteSnapshot>;\n const routeConfig = snapshot.routeConfig as Route;\n routeConfig.path = route;\n snapshot.queryParams = { ['jwt']: 'testToken' };\n snapshot.data = { authorities: [Authority.USER] };\n\n service.canActivate(snapshot, routeStateMock);\n expect(MockSyncStorage.retrieve('authenticationToken')).to.equal('testToken');\n });\n});\n" }, { "alpha_fraction": 0.717391312122345, "alphanum_fraction": 0.717391312122345, "avg_line_length": 29.66666603088379, "blob_id": "b299438052f776e67a91b04a6567078cdd3afc49", "content_id": "f8a8d65e60d01ad67ee5cfbc1b8b8326d92c5d43", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 92, "license_type": "permissive", "max_line_length": 32, "num_lines": 3, "path": "/src/main/webapp/app/polyfills.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import 'zone.js/dist/zone';\nimport '@angular/localize/init';\nrequire('../manifest.webapp');\n" }, { "alpha_fraction": 0.5544809699058533, "alphanum_fraction": 0.5622179508209229, "avg_line_length": 27.72222137451172, "blob_id": "1bd5628bf07f9ff1e91cb3e3e042750577dcce1f", "content_id": "f0b6c6357ee3ff6d6f84361d5298b4c388339729", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1551, "license_type": "permissive", "max_line_length": 94, "num_lines": 54, "path": "/src/main/webapp/app/core/sentry/sentry.error-handler.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ErrorHandler, Injectable } from '@angular/core';\nimport { captureException, init } from '@sentry/browser';\nimport { VERSION } from 'app/app.constants';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\n\n@Injectable({ providedIn: 'root' })\nexport class SentryErrorHandler extends ErrorHandler {\n private environment: string;\n\n /**\n * Initialize Sentry with profile information.\n * @param profileInfo\n */\n public async initSentry(profileInfo: ProfileInfo): Promise<void> {\n if (!profileInfo || !profileInfo.sentry) {\n return;\n }\n\n if (profileInfo.testServer != undefined) {\n if (profileInfo.testServer) {\n this.environment = 'test';\n } else {\n this.environment = 'prod';\n }\n } else {\n this.environment = 'local';\n }\n\n init({\n dsn: profileInfo.sentry.dsn,\n release: VERSION,\n environment: this.environment,\n });\n }\n\n constructor() {\n super();\n }\n\n /**\n * Send an HttpError to Sentry. Only if it's not in the range 400-499.\n * @param error\n */\n handleError(error: any): void {\n if (error.name === 'HttpErrorResponse' && error.status < 500 && error.status >= 400) {\n super.handleError(error);\n return;\n }\n if (this.environment !== 'local') {\n captureException(error.originalError || error);\n }\n super.handleError(error);\n }\n}\n" }, { "alpha_fraction": 0.5445095300674438, "alphanum_fraction": 0.5619326233863831, "avg_line_length": 37.806819915771484, "blob_id": "211ca7ea3a70955e953cd65331d8f1f01167d273", "content_id": "3e38629e26b9aa70b64966530d430fdc88346cd7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6830, "license_type": "permissive", "max_line_length": 173, "num_lines": 176, "path": "/src/test/javascript/spec/service/text-assessment.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { take } from 'rxjs/operators';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Result } from 'app/entities/result.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { FeedbackConflict } from 'app/entities/feedback-conflict';\nimport { getLatestSubmissionResult } from 'app/entities/submission.model';\n\ndescribe('TextAssessment Service', () => {\n let injector: TestBed;\n let service: TextAssessmentService;\n let httpMock: HttpTestingController;\n let textSubmission: TextSubmission;\n let mockResponse: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n injector = getTestBed();\n service = injector.get(TextAssessmentService);\n httpMock = injector.get(HttpTestingController);\n\n textSubmission = new TextSubmission();\n\n mockResponse = {\n type: 'student',\n id: 1,\n results: [\n {\n id: 6,\n resultString: '1 of 1 points',\n completionDate: '2020-07-09T16:28:18.138615+02:00',\n successful: true,\n score: 100,\n rated: true,\n hasFeedback: false,\n feedbacks: [\n {\n id: 6,\n detailText: 'Test',\n reference: '8c8d2463ec548efca05e66423bee537b6357e880',\n credits: 1.0,\n positive: true,\n type: 'MANUAL',\n },\n ],\n assessmentType: 'MANUAL',\n },\n ],\n submissions: [\n {\n submissionExerciseType: 'text',\n id: 1,\n submitted: true,\n type: 'MANUAL',\n submissionDate: '2020-07-07T14:34:25.194518+02:00',\n durationInMinutes: 0,\n text: 'Test\\n\\nTest\\n\\nTest',\n },\n ],\n };\n });\n\n it('should not send feedback', async () => {\n service.trackAssessment();\n httpMock.expectNone({ method: 'POST' });\n });\n\n it('should not send feedback', async () => {\n service.trackAssessment();\n httpMock.expectNone({ method: 'POST' });\n });\n\n it('should send feedback', async () => {\n textSubmission.atheneTextAssessmentTrackingToken = '12345';\n service.trackAssessment(textSubmission);\n httpMock.expectOne({ url: `${SERVER_API_URL}/athene-tracking/text-exercise-assessment`, method: 'POST' });\n });\n\n it('should not parse jwt from header', async () => {\n service.getFeedbackDataForExerciseSubmission(1).subscribe((studentParticipation) => {\n expect((studentParticipation.submissions![0] as TextSubmission).atheneTextAssessmentTrackingToken).toBeUndefined();\n });\n\n const mockRequest = httpMock.expectOne({ method: 'GET' });\n mockRequest.flush(mockResponse);\n });\n\n it('should parse jwt from header', async () => {\n service.getFeedbackDataForExerciseSubmission(1).subscribe((studentParticipation) => {\n expect((studentParticipation.submissions![0] as TextSubmission).atheneTextAssessmentTrackingToken).toEqual('12345');\n });\n\n const mockRequest = httpMock.expectOne({ method: 'GET' });\n\n mockRequest.flush(mockResponse, { headers: { 'x-athene-tracking-authorization': '12345' } });\n });\n\n it('should get feedback data for submission', async () => {\n const submissionId = 42;\n const returnedFromService = Object.assign({}, mockResponse);\n service\n .getFeedbackDataForExerciseSubmission(submissionId)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: mockResponse }));\n\n const req = httpMock.expectOne({ url: `${SERVER_API_URL}api/text-assessments/submission/${submissionId}?correction-round=0`, method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should get conflicting text submissions', async () => {\n const submissionId = 42;\n const feedbackId = 42;\n const submission = ({\n id: 1,\n submitted: true,\n type: 'AUTOMATIC',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as TextSubmission;\n submission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n } as unknown) as Result,\n ];\n getLatestSubmissionResult(submission)!.feedbacks = [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ];\n const returnedFromService = Object.assign({}, [submission]);\n service\n .getConflictingTextSubmissions(submissionId, feedbackId)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: [submission] }));\n\n const req = httpMock.expectOne({ url: `${SERVER_API_URL}api/text-assessments/submission/${submissionId}/feedback/${feedbackId}/feedback-conflicts`, method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should solve feedback conflicts', async () => {\n const exerciseId = 1;\n const feedbackConflict = ({\n id: 1,\n conflict: false,\n type: 'INCONSISTENT_COMMENT',\n firstFeedback: new Feedback(),\n secondFeedback: new Feedback(),\n } as unknown) as FeedbackConflict;\n const returnedFromService = Object.assign({}, feedbackConflict);\n service\n .solveFeedbackConflict(exerciseId, feedbackConflict.id!)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: feedbackConflict }));\n\n const req = httpMock.expectOne({\n url: `${SERVER_API_URL}api/text-assessments/exercise/${exerciseId}/feedbackConflict/${feedbackConflict.id}/solve-feedback-conflict`,\n method: 'GET',\n });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.6969696879386902, "alphanum_fraction": 0.6969696879386902, "avg_line_length": 41.42856979370117, "blob_id": "18a39c0411aa773da63459d2dc7dc370d11f5c76", "content_id": "ae86c747cb63fbafbe2dd7dfaabc69c574c8a247", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2970, "license_type": "permissive", "max_line_length": 161, "num_lines": 70, "path": "/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-lifecycle.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport * as moment from 'moment';\nimport { TranslateService } from '@ngx-translate/core';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { Moment } from 'moment';\n\n@Component({\n selector: 'jhi-programming-exercise-lifecycle',\n templateUrl: './programming-exercise-lifecycle.component.html',\n styleUrls: ['./programming-exercise-test-schedule-picker.scss'],\n})\nexport class ProgrammingExerciseLifecycleComponent implements OnInit {\n @Input() exercise: ProgrammingExercise;\n @Input() isExamMode: boolean;\n\n readonly assessmentType = AssessmentType;\n\n constructor(private translator: TranslateService) {}\n\n /**\n * If the programming exercise does not have an id, set the assessment Type to AUTOMATIC\n */\n ngOnInit(): void {\n if (!this.exercise.id) {\n this.exercise.assessmentType = AssessmentType.AUTOMATIC;\n }\n }\n\n /**\n * Toggles the assessment type between AUTOMATIC (only tests in repo will be run using build plans) and\n * SEMI_AUTOMATIC (After all automatic tests have been run, the tutors will have to make a final manual assessment)\n *\n */\n toggleHasManualAssessment() {\n this.exercise.assessmentType = this.exercise.assessmentType === AssessmentType.SEMI_AUTOMATIC ? AssessmentType.AUTOMATIC : AssessmentType.SEMI_AUTOMATIC;\n // when the new value is AssessmentType.AUTOMATIC, we need to reset assessment due date\n if (this.exercise.assessmentType === AssessmentType.AUTOMATIC) {\n this.exercise.assessmentDueDate = undefined;\n }\n }\n\n /**\n * Sets the new release date and updates \"due date\" and \"after due date\" if the release date is after the due date\n *\n * @param newReleaseDate The new release date\n */\n updateReleaseDate(newReleaseDate?: Moment) {\n if (this.exercise.dueDate && newReleaseDate && moment(newReleaseDate).isAfter(this.exercise.dueDate)) {\n this.updateDueDate(newReleaseDate);\n }\n this.exercise.releaseDate = newReleaseDate;\n }\n\n /**\n * Updates the due Date of the programming exercise\n * @param dueDate the new dueDate\n */\n private updateDueDate(dueDate: Moment) {\n alert(this.translator.instant('artemisApp.programmingExercise.timeline.alertNewDueDate'));\n this.exercise.dueDate = dueDate;\n\n // If the new due date is after the \"After Due Date\", then we have to set the \"After Due Date\" to the new due date\n const afterDue = this.exercise.buildAndTestStudentSubmissionsAfterDueDate;\n if (afterDue && moment(dueDate).isAfter(afterDue)) {\n this.exercise.buildAndTestStudentSubmissionsAfterDueDate = dueDate;\n alert(this.translator.instant('artemisApp.programmingExercise.timeline.alertNewAfterDueDate'));\n }\n }\n}\n" }, { "alpha_fraction": 0.6197991371154785, "alphanum_fraction": 0.6224294304847717, "avg_line_length": 43.48936080932617, "blob_id": "c91bbf026a7470ee9d316ddf4df9d2026b5e77a8", "content_id": "f6c796166bfe779881385a0c162ae1d98b84066d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8364, "license_type": "permissive", "max_line_length": 179, "num_lines": 188, "path": "/src/test/javascript/spec/component/learning-goals/edit-learning-goal.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { MockPipe, MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { LearningGoalFormData } from 'app/course/learning-goals/learning-goal-form/learning-goal-form.component';\nimport { EditLearningGoalComponent } from 'app/course/learning-goals/edit-learning-goal/edit-learning-goal.component';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-learning-goal-form', template: '' })\nclass LearningGoalFormStubComponent {\n @Input() formData: LearningGoalFormData;\n @Input() courseId: number;\n @Input() isEditMode = false;\n @Input()\n lecturesOfCourseWithLectureUnits: Lecture[] = [];\n @Output() formSubmitted: EventEmitter<LearningGoalFormData> = new EventEmitter<LearningGoalFormData>();\n}\n\ndescribe('EditLearningGoalComponent', () => {\n let editLearningGoalComponentFixture: ComponentFixture<EditLearningGoalComponent>;\n let editLearningGoalComponent: EditLearningGoalComponent;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [LearningGoalFormStubComponent, EditLearningGoalComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n MockProvider(LectureService),\n MockProvider(LearningGoalService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'learningGoalId':\n return 1;\n }\n },\n }),\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'courseId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n editLearningGoalComponentFixture = TestBed.createComponent(EditLearningGoalComponent);\n editLearningGoalComponent = editLearningGoalComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n editLearningGoalComponentFixture.detectChanges();\n expect(editLearningGoalComponent).to.be.ok;\n });\n\n it('should set form data correctly', () => {\n // mocking learning goal service\n const learningGoalService = TestBed.inject(LearningGoalService);\n const lectureUnit = new TextUnit();\n lectureUnit.id = 1;\n\n const learningGoalOfResponse = new LearningGoal();\n learningGoalOfResponse.id = 1;\n learningGoalOfResponse.title = 'test';\n learningGoalOfResponse.description = 'lorem ipsum';\n learningGoalOfResponse.lectureUnits = [lectureUnit];\n\n const learningGoalResponse: HttpResponse<LearningGoal> = new HttpResponse({\n body: learningGoalOfResponse,\n status: 200,\n });\n\n const findByIdStub = sinon.stub(learningGoalService, 'findById').returns(of(learningGoalResponse));\n\n // mocking lecture service\n const lectureService = TestBed.inject(LectureService);\n const lectureOfResponse = new Lecture();\n lectureOfResponse.id = 1;\n lectureOfResponse.lectureUnits = [lectureUnit];\n\n const lecturesResponse: HttpResponse<Lecture[]> = new HttpResponse<Lecture[]>({\n body: [lectureOfResponse],\n status: 200,\n });\n\n const findAllByCourseStub = sinon.stub(lectureService, 'findAllByCourseId').returns(of(lecturesResponse));\n\n editLearningGoalComponentFixture.detectChanges();\n const learningGoalFormStubComponent: LearningGoalFormStubComponent = editLearningGoalComponentFixture.debugElement.query(By.directive(LearningGoalFormStubComponent))\n .componentInstance;\n expect(findByIdStub).to.have.been.calledOnce;\n expect(findAllByCourseStub).to.have.been.calledOnce;\n\n expect(editLearningGoalComponent.formData.title).to.equal(learningGoalOfResponse.title);\n expect(editLearningGoalComponent.formData.description).to.equal(learningGoalOfResponse.description);\n expect(editLearningGoalComponent.formData.connectedLectureUnits).to.deep.equal(learningGoalOfResponse.lectureUnits);\n expect(editLearningGoalComponent.lecturesWithLectureUnits).to.deep.equal([lectureOfResponse]);\n expect(learningGoalFormStubComponent.formData).to.deep.equal(editLearningGoalComponent.formData);\n });\n\n it('should send PUT request upon form submission and navigate', () => {\n const router: Router = TestBed.inject(Router);\n const learningGoalService = TestBed.inject(LearningGoalService);\n const lectureService = TestBed.inject(LectureService);\n\n const textUnit = new TextUnit();\n textUnit.id = 1;\n const learningGoalDatabase: LearningGoal = new LearningGoal();\n learningGoalDatabase.id = 1;\n learningGoalDatabase.title = 'test';\n learningGoalDatabase.description = 'lorem ipsum';\n learningGoalDatabase.lectureUnits = [textUnit];\n\n const findByIdResponse: HttpResponse<LearningGoal> = new HttpResponse({\n body: learningGoalDatabase,\n status: 200,\n });\n const findByIdStub = sinon.stub(learningGoalService, 'findById').returns(of(findByIdResponse));\n sinon.stub(lectureService, 'findAllByCourseId').returns(\n of(\n new HttpResponse({\n body: [new Lecture()],\n status: 200,\n }),\n ),\n );\n editLearningGoalComponentFixture.detectChanges();\n expect(findByIdStub).to.have.been.calledOnce;\n expect(editLearningGoalComponent.learningGoal).to.deep.equal(learningGoalDatabase);\n\n const changedUnit: LearningGoal = {\n ...learningGoalDatabase,\n title: 'Changed',\n };\n\n const updateResponse: HttpResponse<LearningGoal> = new HttpResponse({\n body: changedUnit,\n status: 200,\n });\n const updatedStub = sinon.stub(learningGoalService, 'update').returns(of(updateResponse));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n const learningGoalForm: LearningGoalFormStubComponent = editLearningGoalComponentFixture.debugElement.query(By.directive(LearningGoalFormStubComponent)).componentInstance;\n learningGoalForm.formSubmitted.emit({\n title: changedUnit.title,\n description: changedUnit.description,\n connectedLectureUnits: changedUnit.lectureUnits,\n });\n\n expect(updatedStub).to.have.been.calledOnce;\n expect(navigateSpy).to.have.been.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.6892978549003601, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 40.459259033203125, "blob_id": "4bc8454c75c2a9c096bcd204940901cf5e005a57", "content_id": "b0fb6784cd06467c536e7ef870527e64464994db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5597, "license_type": "permissive", "max_line_length": 134, "num_lines": 135, "path": "/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { FileUploadExerciseService } from './file-upload-exercise.service';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { Exercise, ExerciseCategory, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport { navigateBackFromExerciseUpdate } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-file-upload-exercise-update',\n templateUrl: './file-upload-exercise-update.component.html',\n styleUrls: ['./file-upload-exercise-update.component.scss'],\n})\nexport class FileUploadExerciseUpdateComponent implements OnInit {\n readonly IncludedInOverallScore = IncludedInOverallScore;\n\n checkedFlag: boolean;\n isExamMode: boolean;\n fileUploadExercise: FileUploadExercise;\n isSaving: boolean;\n exerciseCategories: ExerciseCategory[];\n existingCategories: ExerciseCategory[];\n EditorMode = EditorMode;\n domainCommandsProblemStatement = [new KatexCommand()];\n domainCommandsSampleSolution = [new KatexCommand()];\n domainCommandsGradingInstructions = [new KatexCommand()];\n\n constructor(\n private fileUploadExerciseService: FileUploadExerciseService,\n private activatedRoute: ActivatedRoute,\n private courseService: CourseManagementService,\n private exerciseService: ExerciseService,\n private jhiAlertService: JhiAlertService,\n private router: Router,\n ) {}\n\n /**\n * Initializes information relevant to file upload exercise\n */\n ngOnInit() {\n this.checkedFlag = false; // default value of grading instructions toggle\n\n // This is used to scroll page to the top of the page, because the routing keeps the position for the\n // new page from previous page.\n window.scroll(0, 0);\n\n this.isSaving = false;\n this.activatedRoute.data.subscribe(({ fileUploadExercise }) => {\n this.fileUploadExercise = fileUploadExercise;\n this.isExamMode = this.fileUploadExercise.exerciseGroup !== undefined;\n if (!this.isExamMode) {\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.fileUploadExercise);\n this.courseService.findAllCategoriesOfCourse(this.fileUploadExercise.course!.id!).subscribe(\n (categoryRes: HttpResponse<string[]>) => {\n this.existingCategories = this.exerciseService.convertExerciseCategoriesAsStringFromServer(categoryRes.body!);\n },\n (categoryRes: HttpErrorResponse) => this.onError(categoryRes),\n );\n }\n });\n }\n\n /**\n * Revert to the previous state, equivalent with pressing the back button on your browser\n * Returns to the detail page if there is no previous state and we edited an existing exercise\n * Returns to the overview page if there is no previous state and we created a new exercise\n * Returns to the exercise group page if we are in exam mode\n */\n previousState() {\n navigateBackFromExerciseUpdate(this.router, this.fileUploadExercise);\n }\n\n /**\n * Creates or updates file upload exercise\n */\n save() {\n Exercise.sanitize(this.fileUploadExercise);\n\n this.isSaving = true;\n if (this.fileUploadExercise.id !== undefined) {\n this.subscribeToSaveResponse(this.fileUploadExerciseService.update(this.fileUploadExercise, this.fileUploadExercise.id));\n } else {\n this.subscribeToSaveResponse(this.fileUploadExerciseService.create(this.fileUploadExercise));\n }\n }\n /**\n * Validates if the date is correct\n */\n validateDate() {\n this.exerciseService.validateDate(this.fileUploadExercise);\n }\n /**\n * Updates categories for file upload exercise\n * @param categories list of exercies categories\n */\n updateCategories(categories: ExerciseCategory[]) {\n this.fileUploadExercise.categories = categories.map((el) => JSON.stringify(el));\n }\n\n private subscribeToSaveResponse(result: Observable<HttpResponse<FileUploadExercise>>) {\n result.subscribe(\n () => this.onSaveSuccess(),\n (res: HttpErrorResponse) => this.onSaveError(res),\n );\n }\n\n private onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n private onSaveError(error: HttpErrorResponse) {\n const errorMessage = error.headers.get('X-artemisApp-alert')!;\n // TODO: this is a workaround to avoid translation not found issues. Provide proper translations\n const jhiAlert = this.jhiAlertService.error(errorMessage);\n jhiAlert.msg = errorMessage;\n this.isSaving = false;\n }\n\n private onError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n }\n /**\n * gets the flag of the structured grading instructions slide toggle\n */\n getCheckedFlag(event: boolean) {\n this.checkedFlag = event;\n }\n}\n" }, { "alpha_fraction": 0.6906384229660034, "alphanum_fraction": 0.6906384229660034, "avg_line_length": 40.715789794921875, "blob_id": "94b50ab383d9a81ed8f868935104db001a8bc01a", "content_id": "21637fac646008374b98ac748b407284a1160b21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3963, "license_type": "permissive", "max_line_length": 122, "num_lines": 95, "path": "/src/test/javascript/spec/component/plagiarism/plagiarism-header.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Subject, of } from 'rxjs';\nimport { PlagiarismHeaderComponent } from 'app/exercises/shared/plagiarism/plagiarism-header/plagiarism-header.component';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { PlagiarismComparison } from 'app/exercises/shared/plagiarism/types/PlagiarismComparison';\nimport { ModelingSubmissionElement } from 'app/exercises/shared/plagiarism/types/modeling/ModelingSubmissionElement';\nimport { PlagiarismStatus } from 'app/exercises/shared/plagiarism/types/PlagiarismStatus';\n\ndescribe('Plagiarism Header Component', () => {\n let comp: PlagiarismHeaderComponent;\n let fixture: ComponentFixture<PlagiarismHeaderComponent>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateTestingModule],\n declarations: [PlagiarismHeaderComponent],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(PlagiarismHeaderComponent);\n comp = fixture.componentInstance;\n\n comp.comparison = {\n submissionA: { studentLogin: 'studentA' },\n submissionB: { studentLogin: 'studentB' },\n status: PlagiarismStatus.NONE,\n } as PlagiarismComparison<ModelingSubmissionElement>;\n comp.splitControlSubject = new Subject<string>();\n });\n\n it('should confirm a plagiarism', () => {\n spyOn(comp, 'updatePlagiarismStatus');\n comp.confirmPlagiarism();\n\n expect(comp.updatePlagiarismStatus).toHaveBeenCalledWith(PlagiarismStatus.CONFIRMED);\n });\n\n it('should deny a plagiarism', () => {\n spyOn(comp, 'updatePlagiarismStatus');\n comp.denyPlagiarism();\n\n expect(comp.updatePlagiarismStatus).toHaveBeenCalledWith(PlagiarismStatus.DENIED);\n });\n\n it('should update the plagiarism status', fakeAsync(() => {\n spyOn(comp.http, 'put').and.returnValue(of({ response: {} }));\n comp.updatePlagiarismStatus(PlagiarismStatus.CONFIRMED);\n\n tick();\n\n expect(comp.http.put).toHaveBeenCalled();\n expect(comp.comparison.status).toEqual(PlagiarismStatus.CONFIRMED);\n }));\n\n it('should emit when expanding left split view pane', () => {\n comp.splitControlSubject = new Subject<string>();\n spyOn(comp.splitControlSubject, 'next');\n\n const nativeElement = fixture.nativeElement;\n const splitLeftButton = nativeElement.querySelector(\"[data-qa='split-view-left']\");\n splitLeftButton.dispatchEvent(new Event('click'));\n\n fixture.detectChanges();\n\n expect(comp.splitControlSubject.next).toHaveBeenCalledWith('left');\n });\n\n it('should emit when expanding right split view pane', () => {\n comp.splitControlSubject = new Subject<string>();\n spyOn(comp.splitControlSubject, 'next');\n\n const nativeElement = fixture.nativeElement;\n const splitRightButton = nativeElement.querySelector(\"[data-qa='split-view-right']\");\n splitRightButton.dispatchEvent(new Event('click'));\n\n fixture.detectChanges();\n\n expect(comp.splitControlSubject.next).toHaveBeenCalledWith('right');\n });\n\n it('should emit when resetting the split panes', () => {\n comp.splitControlSubject = new Subject<string>();\n spyOn(comp.splitControlSubject, 'next');\n\n const nativeElement = fixture.nativeElement;\n const splitHalfButton = nativeElement.querySelector(\"[data-qa='split-view-even']\");\n splitHalfButton.dispatchEvent(new Event('click'));\n\n fixture.detectChanges();\n\n expect(comp.splitControlSubject.next).toHaveBeenCalledWith('even');\n });\n});\n" }, { "alpha_fraction": 0.8274336457252502, "alphanum_fraction": 0.8318583965301514, "avg_line_length": 29.133333206176758, "blob_id": "6dddb3c5e47d7d225399d1d85e818189654ad001", "content_id": "59bb7dae656f65f86f1c75f8e838d8075d47591a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 452, "license_type": "permissive", "max_line_length": 107, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ShortAnswerSubmittedTextRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.ShortAnswerSubmittedText;\n\n/**\n * Spring Data repository for the ShortAnswerSubmittedText entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ShortAnswerSubmittedTextRepository extends JpaRepository<ShortAnswerSubmittedText, Long> {\n\n}\n" }, { "alpha_fraction": 0.7670209407806396, "alphanum_fraction": 0.772304892539978, "avg_line_length": 53.339935302734375, "blob_id": "cfca5462d15c90bf0507093242f14d6b71b3e630", "content_id": "0ef4db1ee7be7f759ba7e913da3d6ee6b5806542", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16465, "license_type": "permissive", "max_line_length": 178, "num_lines": 303, "path": "/src/test/java/de/tum/in/www1/artemis/util/ProgrammingExerciseResultTestService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.util;\n\nimport static de.tum.in.www1.artemis.config.Constants.NEW_RESULT_RESOURCE_PATH;\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.*;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Service;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.SolutionProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.ResultService;\nimport de.tum.in.www1.artemis.service.StaticCodeAnalysisService;\nimport de.tum.in.www1.artemis.service.connectors.bamboo.dto.BambooBuildResultNotificationDTO;\nimport de.tum.in.www1.artemis.service.dto.AbstractBuildResultNotificationDTO;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseGradingService;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseTestCaseService;\n\n/**\n * Note: this class should be independent of the actual VCS and CIS and contains common test logic for both scenarios:\n * 1) Bamboo + Bitbucket\n * 2) Jenkins + Gitlab\n */\n@Service\npublic class ProgrammingExerciseResultTestService {\n\n @Value(\"${artemis.continuous-integration.artemis-authentication-token-value}\")\n private String ARTEMIS_AUTHENTICATION_TOKEN_VALUE;\n\n @Autowired\n private DatabaseUtilService database;\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n @Autowired\n private SolutionProgrammingExerciseParticipationRepository solutionProgrammingExerciseRepository;\n\n @Autowired\n private ProgrammingSubmissionRepository programmingSubmissionRepository;\n\n @Autowired\n private BuildLogEntryRepository buildLogEntryRepository;\n\n @Autowired\n private ProgrammingExerciseGradingService gradingService;\n\n @Autowired\n private ResultService resultService;\n\n @Autowired\n private StaticCodeAnalysisService staticCodeAnalysisService;\n\n @Autowired\n private ProgrammingExerciseTestCaseService programmingExerciseTestCaseService;\n\n @Autowired\n private FeedbackRepository feedbackRepository;\n\n @Autowired\n private ProgrammingExerciseStudentParticipationRepository participationRepository;\n\n @Autowired\n private ResultRepository resultRepository;\n\n @Autowired\n private RequestUtilService request;\n\n private ProgrammingExercise programmingExercise;\n\n private SolutionProgrammingExerciseParticipation solutionParticipation;\n\n private ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipation;\n\n private ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipationStaticCodeAnalysis;\n\n public void setup() {\n database.addUsers(10, 2, 2);\n setupForProgrammingLanguage(ProgrammingLanguage.JAVA);\n }\n\n public void setupForProgrammingLanguage(ProgrammingLanguage programmingLanguage) {\n Course course = database.addCourseWithOneProgrammingExercise(false, programmingLanguage);\n programmingExercise = programmingExerciseRepository.findAll().get(0);\n ProgrammingExercise programmingExerciseWithStaticCodeAnalysis = database.addProgrammingExerciseToCourse(course, true, programmingLanguage);\n staticCodeAnalysisService.createDefaultCategories(programmingExerciseWithStaticCodeAnalysis);\n // This is done to avoid an unproxy issue in the processNewResult method of the ResultService.\n solutionParticipation = solutionProgrammingExerciseRepository.findWithEagerResultsAndSubmissionsByProgrammingExerciseId(programmingExercise.getId()).get();\n programmingExerciseStudentParticipation = database.addStudentParticipationForProgrammingExercise(programmingExercise, \"student1\");\n programmingExerciseStudentParticipationStaticCodeAnalysis = database.addStudentParticipationForProgrammingExercise(programmingExerciseWithStaticCodeAnalysis, \"student2\");\n }\n\n public void tearDown() {\n database.resetDatabase();\n }\n\n // Test\n public void shouldUpdateFeedbackInSemiAutomaticResult(AbstractBuildResultNotificationDTO buildResultNotification, String loginName) throws Exception {\n // Make sure we only have one participation\n participationRepository.deleteAll();\n programmingExerciseStudentParticipation = database.addStudentParticipationForProgrammingExercise(programmingExercise, loginName);\n\n // Add a student submission with two manual results and a semi automatic result\n var submission = database.createProgrammingSubmission(programmingExerciseStudentParticipation, false, TestConstants.COMMIT_HASH_STRING);\n var accessor = database.getUserByLogin(\"instructor1\");\n database.addResultToSubmission(submission, AssessmentType.MANUAL, accessor);\n database.addResultToSubmission(submission, AssessmentType.MANUAL, accessor);\n database.addResultToSubmission(submission, AssessmentType.SEMI_AUTOMATIC, accessor);\n\n // Add a manual feedback to the semi automatic result\n var feedback = new Feedback();\n feedback.setType(FeedbackType.MANUAL);\n feedback.setText(\"feedback1\");\n feedback.setCredits(10.0);\n\n var resultsWithFeedback = resultRepository.findAllWithEagerFeedbackByAssessorIsNotNullAndParticipation_ExerciseIdAndCompletionDateIsNotNull(programmingExercise.getId());\n var semiAutoResult = resultsWithFeedback.get(2);\n database.addFeedbackToResult(feedback, semiAutoResult);\n\n // Assert that the results have been created successfully.\n resultsWithFeedback = resultRepository.findAllWithEagerFeedbackByAssessorIsNotNullAndParticipation_ExerciseIdAndCompletionDateIsNotNull(programmingExercise.getId());\n assertThat(resultsWithFeedback.size()).isEqualTo(3);\n assertThat(resultsWithFeedback.get(0).getAssessmentType()).isEqualTo(AssessmentType.MANUAL);\n assertThat(resultsWithFeedback.get(1).getAssessmentType()).isEqualTo(AssessmentType.MANUAL);\n assertThat(resultsWithFeedback.get(2).getAssessmentType()).isEqualTo(AssessmentType.SEMI_AUTOMATIC);\n\n // Re-trigger the build. We create a notification with feedback of a successful test\n database.changeUser(\"instructor1\");\n postResult(buildResultNotification);\n\n // Retrieve updated results\n var updatedResults = resultRepository.findAllWithEagerFeedbackByAssessorIsNotNullAndParticipation_ExerciseIdAndCompletionDateIsNotNull(programmingExercise.getId());\n assertThat(updatedResults.size()).isEqualTo(3);\n\n // Assert that the result order stays the same\n assertThat(updatedResults.get(0).getId()).isEqualTo(resultsWithFeedback.get(0).getId());\n assertThat(updatedResults.get(1).getId()).isEqualTo(resultsWithFeedback.get(1).getId());\n assertThat(updatedResults.get(2).getId()).isEqualTo(resultsWithFeedback.get(2).getId());\n\n // Assert that the last result is the SEMI_AUTOMATIC result\n semiAutoResult = updatedResults.get(2);\n assertThat(semiAutoResult.getAssessmentType()).isEqualTo(AssessmentType.SEMI_AUTOMATIC);\n // Assert that the SEMI_AUTOMATIC result has two feedbacks whereas the last one is the automatic one\n assertThat(semiAutoResult.getFeedbacks().size()).isEqualTo(2);\n assertThat(semiAutoResult.getFeedbacks().get(0).getType()).isEqualTo(FeedbackType.MANUAL);\n assertThat(semiAutoResult.getFeedbacks().get(1).getType()).isEqualTo(FeedbackType.AUTOMATIC);\n }\n\n private void postResult(AbstractBuildResultNotificationDTO requestBodyMap) throws Exception {\n ObjectMapper mapper = new ObjectMapper();\n mapper.registerModule(new JavaTimeModule());\n final var alteredObj = mapper.convertValue(requestBodyMap, Object.class);\n\n HttpHeaders httpHeaders = new HttpHeaders();\n httpHeaders.add(\"Authorization\", ARTEMIS_AUTHENTICATION_TOKEN_VALUE);\n request.postWithoutLocation(\"/api\" + NEW_RESULT_RESOURCE_PATH, alteredObj, HttpStatus.OK, httpHeaders);\n }\n\n private ProgrammingExerciseTestCase createTest(String testName, long testId) {\n return new ProgrammingExerciseTestCase().exercise(programmingExercise).testName(testName).active(true).weight(1.0).id(testId).bonusMultiplier(1D).bonusPoints(0D)\n .visibility(Visibility.ALWAYS);\n }\n\n // Test\n public void shouldUpdateTestCasesAndResultScoreFromSolutionParticipationResult(Object resultNotification, boolean withFailedTest) {\n database.createProgrammingSubmission(programmingExerciseStudentParticipation, false);\n\n Set<ProgrammingExerciseTestCase> expectedTestCases = new HashSet<>();\n expectedTestCases.add(createTest(\"test1\", 1L));\n expectedTestCases.add(createTest(\"test2\", 2L));\n expectedTestCases.add(createTest(\"test4\", 4L));\n if (withFailedTest) {\n expectedTestCases.add(createTest(\"test3\", 3L));\n }\n\n final var optionalResult = gradingService.processNewProgrammingExerciseResult(solutionParticipation, resultNotification);\n\n Set<ProgrammingExerciseTestCase> testCases = programmingExerciseTestCaseService.findByExerciseId(programmingExercise.getId());\n assertThat(testCases).usingElementComparatorIgnoringFields(\"exercise\", \"id\").containsExactlyInAnyOrderElementsOf(expectedTestCases);\n assertThat(optionalResult).isPresent();\n if (withFailedTest) {\n assertThat(optionalResult.get().getScore()).isEqualTo(75L);\n }\n else {\n assertThat(optionalResult.get().getScore()).isEqualTo(100L);\n }\n\n // Call again and shouldn't re-create new submission.\n gradingService.processNewProgrammingExerciseResult(solutionParticipation, resultNotification);\n var latestSubmissions = programmingSubmissionRepository.findAll();\n // One submission from the student participation and the other from solution participation\n assertThat(latestSubmissions.size()).isEqualTo(2);\n }\n\n // Test\n public void shouldStoreFeedbackForResultWithStaticCodeAnalysisReport(Object resultNotification, ProgrammingLanguage programmingLanguage) {\n final var optionalResult = gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipationStaticCodeAnalysis, resultNotification);\n final var savedResult = resultService.findOneWithEagerSubmissionAndFeedback(optionalResult.get().getId());\n\n // Should be one because programmingExerciseStudentParticipationStaticCodeAnalysis doesn't have a submission\n var submissions = programmingSubmissionRepository.findAll();\n assertThat(submissions.size()).isEqualTo(1);\n\n // Create comparator to explicitly compare feedback attributes (equals only compares id)\n Comparator<? super Feedback> scaFeedbackComparator = (Comparator<Feedback>) (fb1, fb2) -> {\n if (Objects.equals(fb1.getDetailText(), fb2.getDetailText()) && Objects.equals(fb1.getText(), fb2.getText())\n && Objects.equals(fb1.getReference(), fb2.getReference())) {\n return 0;\n }\n else {\n return 1;\n }\n };\n\n assertThat(optionalResult).isPresent();\n var result = optionalResult.get();\n assertThat(result.getFeedbacks()).usingElementComparator(scaFeedbackComparator).containsAll(savedResult.getFeedbacks());\n assertThat(result.getFeedbacks().stream().filter(Feedback::isStaticCodeAnalysisFeedback).count())\n .isEqualTo(StaticCodeAnalysisTool.getToolsForProgrammingLanguage(programmingLanguage).size());\n\n // Call again and shouln't re-create new submission.\n gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipationStaticCodeAnalysis, resultNotification);\n assertThat(programmingSubmissionRepository.findAll().size()).isEqualTo(submissions.size());\n }\n\n // Test\n public void shouldStoreBuildLogsForSubmission(Object resultNotification) {\n final var optionalResult = gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n\n var submission = programmingSubmissionRepository.findFirstByParticipationIdOrderByLegalSubmissionDateDesc(programmingExerciseStudentParticipation.getId());\n var submissionWithLogs = programmingSubmissionRepository.findWithEagerBuildLogEntriesById(submission.get().getId());\n var expectedNoOfLogs = getNumberOfBuildLogs(resultNotification) - 3; // 3 of those should be filtered\n assertThat(((ProgrammingSubmission) optionalResult.get().getSubmission()).getBuildLogEntries()).hasSize(expectedNoOfLogs);\n assertThat(submissionWithLogs.get().getBuildLogEntries()).hasSize(expectedNoOfLogs);\n\n // Call again and should not re-create new submission.\n gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n assertThat(programmingSubmissionRepository.findAll().size()).isEqualTo(1);\n }\n\n public void shouldSaveBuildLogsInBuildLogRepository(Object resultNotification) {\n buildLogEntryRepository.deleteAll();\n gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n\n var savedBuildLogs = buildLogEntryRepository.findAll();\n var expectedBuildLogs = getNumberOfBuildLogs(resultNotification) - 3; // 3 of those should be filtered\n\n assertThat(savedBuildLogs.size()).isEqualTo(expectedBuildLogs);\n savedBuildLogs.forEach(\n buildLogEntry -> assertThat(buildLogEntry.getProgrammingSubmission().getParticipation().getId()).isEqualTo(programmingExerciseStudentParticipation.getId()));\n\n // Call again and should not re-create new submission.\n gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n assertThat(programmingSubmissionRepository.findAll().size()).isEqualTo(1);\n }\n\n // Test\n public void shouldGenerateNewManualResultIfManualAssessmentExists(Object resultNotification) {\n var programmingSubmission = database.createProgrammingSubmission(programmingExerciseStudentParticipation, false);\n programmingSubmission = database.addProgrammingSubmissionWithResultAndAssessor(programmingExercise, programmingSubmission, \"student1\", \"tutor1\",\n AssessmentType.SEMI_AUTOMATIC, true);\n\n List<Feedback> feedback = ModelFactory.generateManualFeedback();\n feedback = feedbackRepository.saveAll(feedback);\n programmingSubmission.getFirstResult().addFeedbacks(feedback);\n resultRepository.save(programmingSubmission.getFirstResult());\n\n final var optionalResult = gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n\n assertThat(optionalResult).isPresent();\n\n var result = optionalResult.get();\n\n assertThat(result.getAssessmentType()).isEqualTo(AssessmentType.SEMI_AUTOMATIC);\n assertThat(result.getFeedbacks()).hasSize(6);\n assertThat(result.getFeedbacks().stream().filter((fb) -> fb.getType() == FeedbackType.AUTOMATIC).count()).isEqualTo(3);\n\n // Call again and shouln't re-create new submission.\n gradingService.processNewProgrammingExerciseResult(programmingExerciseStudentParticipation, resultNotification);\n assertThat(programmingSubmissionRepository.findAll().size()).isEqualTo(1);\n }\n\n private int getNumberOfBuildLogs(Object resultNotification) {\n if (resultNotification instanceof BambooBuildResultNotificationDTO) {\n return ((BambooBuildResultNotificationDTO) resultNotification).getBuild().getJobs().iterator().next().getLogs().size();\n }\n throw new UnsupportedOperationException(\"Build logs are only part of the Bamboo notification\");\n }\n\n public ProgrammingExercise getProgrammingExercise() {\n return programmingExercise;\n }\n}\n" }, { "alpha_fraction": 0.45884618163108826, "alphanum_fraction": 0.4615315794944763, "avg_line_length": 54.032020568847656, "blob_id": "014a89f8b75b26b87f3f281084b5e73c5c984a29", "content_id": "1fe54bfe3299dbd7e5468ea53cafdff1c2d489d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 22343, "license_type": "permissive", "max_line_length": 173, "num_lines": 406, "path": "/src/main/webapp/app/exam/manage/exams/exam-checklist-component/exam-checklist.component.html", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<div *ngIf=\"isAtLeastInstructor\">\n <h3>\n <span>{{ 'artemisApp.examManagement.checklist.title' | artemisTranslate }}</span>\n </h3>\n <p>\n <span>{{ 'artemisApp.examManagement.checklist.introduction' | artemisTranslate }}</span>\n <a href=\"https://artemis-platform.readthedocs.io/en/latest/user/exams/instructors_guide/\">\n <span>{{ 'artemisApp.examManagement.checklist.linkDescription' | artemisTranslate }}</span></a\n >\n <br />\n </p>\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th>\n <span>#</span>\n </th>\n <th>\n <span>{{ 'artemisApp.examManagement.checklist.checklistItem' | artemisTranslate }}</span>\n </th>\n <th>\n <span>{{ 'artemisApp.examManagement.checklist.description' | artemisTranslate }}</span>\n </th>\n <th>\n <span>{{ 'artemisApp.examManagement.checklist.goTo' | artemisTranslate }}</span>\n </th>\n </tr>\n </thead>\n\n <tbody>\n <tr>\n <td>1</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.exerciseGroups' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.exerciseGroups' | artemisTranslate }}</span>\n <hr />\n <ul class=\"list-unstyled\">\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"exam.exerciseGroups && exam.exerciseGroups.length > 0\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.leastoneexercisegroup' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check\n [checkAttribute]=\"exam.exerciseGroups && exam.exerciseGroups.length == exam.numberOfExercisesInExam\"\n ></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.numberofexercisegroupsequal' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"allGroupsContainExercise\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.eachexercisegroup' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"pointsExercisesEqual\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.pointsexercisegroupequal' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"totalPointsMandatory && totalPointsMandatoryOptional\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.totalpointspossible' | artemisTranslate }}</span>\n </span>\n </li>\n </ul>\n\n <hr />\n <!-- Exercise Group table -->\n <jhi-exam-checklist-exercisegroup-table [exerciseGroups]=\"exam.exerciseGroups || []\"></jhi-exam-checklist-exercisegroup-table>\n </td>\n <td>\n <a\n *ngIf=\"isAtLeastInstructor\"\n type=\"submit\"\n [routerLink]=\"getExamRoutesByIdentifier('exercise-groups')\"\n class=\"btn btn-primary\"\n id=\"exercises-button-groups-table\"\n >\n <fa-icon [icon]=\"'list-alt'\"></fa-icon>\n <span>{{ 'artemisApp.examManagement.exerciseGroups' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>2</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.testRun' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.testRun' | artemisTranslate }}</span>\n <hr />\n <ul class=\"list-unstyled\">\n <li *ngIf=\"examChecklist\" class=\"list-group-item border-1\">\n <span>{{ 'artemisApp.examManagement.checklist.textitems.testruns' | artemisTranslate }}</span>\n {{ examChecklist.numberOfTestRuns }}\n </li>\n </ul>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('test-runs')\" class=\"btn btn-info\">\n <fa-icon [icon]=\"'user'\"></fa-icon>\n <span>{{ 'artemisApp.examManagement.testRun.testRun' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>3</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.register' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.register' | artemisTranslate }}</span>\n <hr />\n <ul class=\"list-unstyled\">\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"!!exam.numberOfRegisteredUsers && exam.numberOfRegisteredUsers! > 0\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.leastonestudent' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>{{ 'artemisApp.examManagement.checklist.textitems.studentsregistered' | artemisTranslate }}</span>\n <span> {{ exam.registeredUsers?.length || 0 }} </span>\n </li>\n </ul>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('students')\" class=\"btn btn-info\">\n <fa-icon [icon]=\"'user'\"></fa-icon>\n <span>{{ 'artemisApp.examManagement.students' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>4</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.generateStudentExams' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.generateStudentExams' | artemisTranslate }}</span>\n <hr />\n <ul class=\"list-unstyled\">\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"allExamsGenerated\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.allexamsgenerated' | artemisTranslate }}</span>\n </span>\n </li>\n </ul>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('student-exams')\" class=\"btn btn-primary\">\n <fa-icon [icon]=\"'eye'\"></fa-icon>\n <span class=\"d-none d-md-inline\">{{ 'artemisApp.examManagement.studentExams' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>5</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.prepareExerciseStart' | artemisTranslate }}</span>\n </td>\n <td>\n <span\n >{{ 'artemisApp.examManagement.checklist.descriptionItem.prepareExerciseStart' | artemisTranslate }}\n <hr />\n <ul class=\"list-unstyled\">\n <li *ngIf=\"examChecklist\" class=\"list-group-item border-1\">\n <jhi-exam-checklist-check [checkAttribute]=\"!!examChecklist.allExamExercisesAllStudentsPrepared\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.allExercisesPrepared' | artemisTranslate }}</span>\n </li>\n </ul>\n </span>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('student-exams')\" class=\"btn btn-primary\">\n <fa-icon [icon]=\"'eye'\"></fa-icon>\n <span class=\"d-none d-md-inline\">{{ 'artemisApp.examManagement.studentExams' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>6</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.examDetails' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.examDetails' | artemisTranslate }}</span>\n </td>\n <td>\n <a id=\"editButton_table\" *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('edit')\" class=\"btn btn-warning\">\n <fa-icon [icon]=\"'wrench'\"></fa-icon>&nbsp;<span jhiTranslate=\"entity.action.edit\"> Edit</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>7</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.conductExam' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.conductExam' | artemisTranslate }}</span>\n <hr />\n <!-- Display started exams-->\n <div\n *ngIf=\"\n examChecklist &&\n examChecklist.numberOfGeneratedStudentExams !== null &&\n examChecklist.numberOfGeneratedStudentExams !== 0 &&\n examChecklist.numberOfExamsStarted > 0\n \"\n >\n <!-- -->\n <span>{{ 'artemisApp.examManagement.checklist.textitems.startedExam' | artemisTranslate }}:</span>\n <div style=\"padding-top: 5px\">\n <jhi-progress-bar\n [denominator]=\"examChecklist.numberOfGeneratedStudentExams!\"\n [numerator]=\"examChecklist.numberOfExamsStarted!\"\n [percentage]=\"(100 * examChecklist.numberOfExamsStarted!) / examChecklist.numberOfGeneratedStudentExams!\"\n >\n </jhi-progress-bar>\n </div>\n <hr />\n </div>\n <!-- Display submitted exams-->\n <div\n *ngIf=\"\n examChecklist &&\n examChecklist.numberOfGeneratedStudentExams !== null &&\n examChecklist.numberOfGeneratedStudentExams !== 0 &&\n examChecklist.numberOfExamsSubmitted > 0\n \"\n >\n <span>{{ 'artemisApp.examManagement.checklist.textitems.submittedExam' | artemisTranslate }}:</span>\n <div style=\"padding-top: 5px\">\n <jhi-progress-bar\n [denominator]=\"examChecklist.numberOfExamsStarted\"\n [numerator]=\"examChecklist.numberOfExamsSubmitted!\"\n [percentage]=\"(100 * examChecklist.numberOfExamsSubmitted!) / examChecklist.numberOfExamsStarted!\"\n >\n </jhi-progress-bar>\n </div>\n <br />\n </div>\n <div *ngIf=\"examChecklist && examChecklist.numberOfExamsSubmitted! === 0\">\n <span>{{ 'artemisApp.examManagement.checklist.textitems.noSubmissions' | artemisTranslate }}</span>\n </div>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('student-exams')\" class=\"btn btn-primary\">\n <fa-icon [icon]=\"'eye'\"></fa-icon>\n <span class=\"d-none d-md-inline\">{{ 'artemisApp.examManagement.studentExams' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>8</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.assessAllSubmissions' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.assessAllSubmissions' | artemisTranslate }}</span>\n\n <hr />\n <!-- Display assessment progress summed up over all exercises, by correction round -->\n\n <div *ngIf=\"examChecklist && examChecklist.numberOfTotalExamAssessmentsFinishedByCorrectionRound !== null && examChecklist.numberOfExamsSubmitted !== 0\">\n <div *ngFor=\"let finishedByCorrectionRound of examChecklist.numberOfTotalExamAssessmentsFinishedByCorrectionRound; let index = index\">\n <hr *ngIf=\"index > 0\" />\n <span> {{ 'artemisApp.examManagement.checklist.textitems.correctionRound' | artemisTranslate }} {{ index + 1 }}: </span>\n <div style=\"padding-top: 5px\">\n <jhi-progress-bar\n [denominator]=\"examChecklist.numberOfTotalParticipationsForAssessment\"\n [numerator]=\"finishedByCorrectionRound!\"\n [percentage]=\"(finishedByCorrectionRound! / examChecklist.numberOfTotalParticipationsForAssessment) * 100\"\n >\n </jhi-progress-bar>\n </div>\n </div>\n </div>\n <div *ngIf=\"examChecklist && examChecklist.numberOfExamsSubmitted === 0\">\n <span>{{ 'artemisApp.examManagement.checklist.textitems.noSubmissions' | artemisTranslate }}</span>\n </div>\n <br />\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('assessment-dashboard')\" class=\"btn btn-primary\">\n <fa-icon [icon]=\"'th-list'\"></fa-icon>\n <span>{{ 'artemisApp.examManagement.assessmentDashboard' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>9</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.publishResults' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.publishResults' | artemisTranslate }}</span>\n\n <hr />\n <ul class=\"list-unstyled\">\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"!!exam.publishResultsDate\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.pulishingdateset' | artemisTranslate }}</span>\n </span>\n </li>\n </ul>\n </td>\n <td>\n <a id=\"editButton_publish\" *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('edit')\" class=\"btn btn-warning\">\n <fa-icon [icon]=\"'wrench'\"></fa-icon>&nbsp;<span jhiTranslate=\"entity.action.edit\"> Edit</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>10</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.examReview' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.examReview' | artemisTranslate }}</span>\n\n <hr />\n <ul class=\"list-unstyled\">\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"!!exam.examStudentReviewStart\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.startdatereviewset' | artemisTranslate }}</span>\n </span>\n </li>\n <li class=\"list-group-item border-1\">\n <span>\n <jhi-exam-checklist-check [checkAttribute]=\"!!exam.examStudentReviewEnd\"></jhi-exam-checklist-check>\n <span>{{ 'artemisApp.examManagement.checklist.textitems.enddatereviewset' | artemisTranslate }}</span>\n </span>\n </li>\n </ul>\n </td>\n <td>\n <a id=\"editButton_review\" *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('edit')\" class=\"btn btn-warning\">\n <fa-icon [icon]=\"'wrench'\"></fa-icon>&nbsp;<span jhiTranslate=\"entity.action.edit\">Edit</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>11</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.resolveComplaints' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.resolveComplaints' | artemisTranslate }}</span>\n <hr />\n <div *ngIf=\"examChecklist && examChecklist.numberOfAllComplaintsDone !== null && examChecklist.numberOfAllComplaints !== 0\">\n <div style=\"padding-top: 5px\">\n <jhi-progress-bar\n [denominator]=\"examChecklist.numberOfAllComplaints!\"\n [numerator]=\"examChecklist.numberOfAllComplaintsDone!\"\n [percentage]=\"(examChecklist.numberOfAllComplaintsDone! / examChecklist.numberOfAllComplaints!) * 100\"\n >\n </jhi-progress-bar>\n </div>\n </div>\n <div *ngIf=\"examChecklist && examChecklist.numberOfAllComplaints === 0\">\n <span>{{ 'artemisApp.examManagement.checklist.textitems.noComplaints' | artemisTranslate }}</span>\n </div>\n <br />\n </td>\n <td>\n <a\n *ngIf=\"isAtLeastInstructor\"\n [routerLink]=\"getExamRoutesByIdentifier('assessment-dashboard')\"\n class=\"btn btn-primary\"\n id=\"tutor-exam-dashboard-button_table_complaints\"\n >\n <fa-icon [icon]=\"'th-list'\"></fa-icon>\n <span>{{ 'artemisApp.examManagement.assessmentDashboard' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n <tr>\n <td>12</td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.tableItem.exportResults' | artemisTranslate }}</span>\n </td>\n <td>\n <span>{{ 'artemisApp.examManagement.checklist.descriptionItem.exportResults' | artemisTranslate }}</span>\n </td>\n <td>\n <a *ngIf=\"isAtLeastInstructor\" [routerLink]=\"getExamRoutesByIdentifier('scores')\" class=\"btn btn-info\" id=\"scores-button_publish_result\">\n <fa-icon [icon]=\"'eye'\"></fa-icon>\n <span>{{ 'entity.action.scores' | artemisTranslate }}</span>\n </a>\n </td>\n </tr>\n </tbody>\n </table>\n</div>\n" }, { "alpha_fraction": 0.6804546117782593, "alphanum_fraction": 0.6828768253326416, "avg_line_length": 38.1751823425293, "blob_id": "5fda75985eab6c567ebd9ffc68e5278e3df75013", "content_id": "007394bc46b5c24a84e25a086e1c0df51a2c5e57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5367, "license_type": "permissive", "max_line_length": 133, "num_lines": 137, "path": "/src/test/javascript/spec/component/plagiarism/plagiarism-split-view.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SimpleChange } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Subject } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { PlagiarismComparison } from 'app/exercises/shared/plagiarism/types/PlagiarismComparison';\nimport { PlagiarismSplitViewComponent } from 'app/exercises/shared/plagiarism/plagiarism-split-view/plagiarism-split-view.component';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ArtemisPlagiarismModule } from 'app/exercises/shared/plagiarism/plagiarism.module';\nimport { PlagiarismSubmission } from 'app/exercises/shared/plagiarism/types/PlagiarismSubmission';\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\nimport { PlagiarismMatch } from 'app/exercises/shared/plagiarism/types/PlagiarismMatch';\n\nconst collapse = jest.fn();\nconst setSizes = jest.fn();\n\njest.mock('split.js', () => ({\n default: jest.fn().mockImplementation(() => ({\n collapse,\n setSizes,\n })),\n}));\n\ndescribe('Plagiarism Split View Component', () => {\n let comp: PlagiarismSplitViewComponent;\n let fixture: ComponentFixture<PlagiarismSplitViewComponent>;\n\n const modelingExercise = { id: 123, type: ExerciseType.MODELING } as ModelingExercise;\n const textExercise = { id: 234, type: ExerciseType.TEXT } as TextExercise;\n const splitControlSubject = new Subject<string>();\n\n const submissionA = { studentLogin: 'studentA' } as PlagiarismSubmission<TextSubmissionElement>;\n const submissionB = { studentLogin: 'studentB' } as PlagiarismSubmission<TextSubmissionElement>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisPlagiarismModule, TranslateTestingModule],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(PlagiarismSplitViewComponent);\n comp = fixture.componentInstance;\n\n comp.comparison = {\n submissionA,\n submissionB,\n } as PlagiarismComparison<TextSubmissionElement>;\n comp.splitControlSubject = splitControlSubject;\n });\n\n it('checks type of modeling exercise', () => {\n comp.ngOnChanges({\n exercise: { currentValue: modelingExercise } as SimpleChange,\n });\n\n expect(comp.isModelingExercise).toEqual(true);\n expect(comp.isProgrammingOrTextExercise).toEqual(false);\n });\n\n it('checks type of text exercise', () => {\n comp.ngOnChanges({\n exercise: { currentValue: textExercise } as SimpleChange,\n });\n\n expect(comp.isProgrammingOrTextExercise).toEqual(true);\n expect(comp.isModelingExercise).toEqual(false);\n });\n\n it('should subscribe to the split control subject', () => {\n comp.exercise = textExercise;\n spyOn(splitControlSubject, 'subscribe');\n\n fixture.detectChanges();\n expect(comp.splitControlSubject.subscribe).toHaveBeenCalled();\n });\n\n it('should collapse the left pane', () => {\n comp.exercise = textExercise;\n comp.split = ({ collapse } as unknown) as Split.Instance;\n\n comp.handleSplitControl('left');\n\n expect(collapse).toHaveBeenCalledWith(1);\n });\n\n it('should collapse the right pane', () => {\n comp.exercise = textExercise;\n comp.split = ({ collapse } as unknown) as Split.Instance;\n\n comp.handleSplitControl('right');\n\n expect(collapse).toHaveBeenCalledWith(0);\n });\n\n it('should reset the split panes', () => {\n comp.exercise = textExercise;\n comp.split = ({ setSizes } as unknown) as Split.Instance;\n\n comp.handleSplitControl('even');\n\n expect(setSizes).toHaveBeenCalledWith([50, 50]);\n });\n\n it('should get the first modeling submission', () => {\n const modelingSubmissionA = comp.getModelingSubmissionA();\n expect(modelingSubmissionA).toEqual(submissionA);\n });\n\n it('should get the second modeling submission', () => {\n const modelingSubmissionB = comp.getModelingSubmissionB();\n expect(modelingSubmissionB).toEqual(submissionB);\n });\n\n it('should get the first text submission', () => {\n const textSubmissionA = comp.getTextSubmissionA();\n expect(textSubmissionA).toEqual(submissionA);\n });\n\n it('should get the second text submission', () => {\n const textSubmissionB = comp.getTextSubmissionB();\n expect(textSubmissionB).toEqual(submissionB);\n });\n\n it('parses text matches', () => {\n spyOn(comp, 'mapMatchesToElements').and.returnValue(new Map());\n\n const matches: PlagiarismMatch[] = [];\n comp.parseTextMatches({ submissionA, submissionB, matches } as PlagiarismComparison<TextSubmissionElement>);\n\n expect(comp.matchesA).toBeDefined();\n expect(comp.matchesB).toBeDefined();\n expect(comp.mapMatchesToElements).toHaveBeenCalledTimes(2);\n });\n});\n" }, { "alpha_fraction": 0.7071823477745056, "alphanum_fraction": 0.7071823477745056, "avg_line_length": 38.73170852661133, "blob_id": "6f416c34448fae0228fa908a4a4510dc3dc6f29c", "content_id": "0786a9527e032c280376e45a6cc3a4fb530c5f1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1629, "license_type": "permissive", "max_line_length": 129, "num_lines": 41, "path": "/src/main/webapp/app/assessment/assessment-header/assessment-header.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { Result } from 'app/entities/result.model';\n\n/**\n * The <jhi-assessment-header> component is used in the shared assessment layout.\n * It displays a header bar above the assessment editor with information of locking, as well as offering save/submit/etc buttons.\n * This guarantees a unified look and feel for both interfaces.\n * Depending Components need to perform actions based on the save/submit/cancel/nextSubmission/navigateBack outputs.\n */\n@Component({\n selector: 'jhi-assessment-header',\n templateUrl: './assessment-header.component.html',\n styleUrls: ['./assessment-header.component.scss'],\n})\nexport class AssessmentHeaderComponent {\n @Input() isLoading: boolean;\n @Input() saveBusy: boolean;\n @Input() submitBusy: boolean;\n @Input() cancelBusy: boolean;\n @Input() nextSubmissionBusy: boolean;\n\n @Input() isTeamMode: boolean;\n @Input() isAssessor: boolean;\n @Input() isAtLeastInstructor: boolean;\n @Input() isTestRun = false;\n @Input() exerciseDashboardLink: string[];\n @Input() canOverride: boolean;\n\n @Input() result: Result | null;\n @Input() isIllegalSubmission: boolean;\n @Input() hasComplaint = false;\n @Input() hasMoreFeedbackRequest = false;\n @Input() complaintHandled = false;\n @Input() assessmentsAreValid: boolean;\n @Input() hasAssessmentDueDatePassed: boolean;\n\n @Output() save = new EventEmitter<void>();\n @Output() submit = new EventEmitter<void>();\n @Output() cancel = new EventEmitter<void>();\n @Output() nextSubmission = new EventEmitter<void>();\n}\n" }, { "alpha_fraction": 0.740487813949585, "alphanum_fraction": 0.7424390316009521, "avg_line_length": 32.064517974853516, "blob_id": "2405e30c2d24b0a695acb71cf5493c79eb998716", "content_id": "fdcf8f6606eaaa69fbfa6f20db83f1efd5c41dce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1025, "license_type": "permissive", "max_line_length": 90, "num_lines": 31, "path": "/src/main/java/de/tum/in/www1/artemis/security/PBEPasswordEncoder.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.security;\n\nimport org.jasypt.encryption.pbe.PBEStringEncryptor;\nimport org.springframework.security.crypto.password.PasswordEncoder;\n\n/**\n * PBEPasswordEncoder for Spring, based on org.jasypt.spring.security3.PBEPasswordEncoder;\n */\npublic class PBEPasswordEncoder implements PasswordEncoder {\n\n private final PBEStringEncryptor pbeStringEncryptor;\n\n public PBEPasswordEncoder(final PBEStringEncryptor pbeStringEncryptor) {\n this.pbeStringEncryptor = pbeStringEncryptor;\n }\n\n @Override\n public String encode(CharSequence rawPassword) {\n return this.pbeStringEncryptor.encrypt(rawPassword.toString());\n }\n\n @Override\n public boolean matches(CharSequence rawPassword, String encodedPassword) {\n String decPassword = this.pbeStringEncryptor.decrypt(encodedPassword);\n\n if (decPassword == null || rawPassword == null) {\n return (decPassword == rawPassword);\n }\n return decPassword.equals(rawPassword.toString());\n }\n}\n" }, { "alpha_fraction": 0.7159610986709595, "alphanum_fraction": 0.7162471413612366, "avg_line_length": 55.84552764892578, "blob_id": "532d136632046f4d8335d952325bef21a8dd33b8", "content_id": "157b18cf89ace68e3bf99302338989f50b4e524f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6992, "license_type": "permissive", "max_line_length": 134, "num_lines": 123, "path": "/src/test/javascript/spec/service/markdown.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { getTestBed } from '@angular/core/testing';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Markdown Service', () => {\n let markdownService: ArtemisMarkdownService;\n\n beforeEach(() => {\n const injector = getTestBed();\n markdownService = injector.get(ArtemisMarkdownService);\n });\n\n const hintText = 'Add an explanation here (only visible in feedback after quiz has ended)';\n const markdownHint = '[hint] ' + hintText;\n const explanationText = 'Add an explanation here (only visible in feedback after quiz has ended)';\n const markdownExplanation = '[exp] ' + explanationText;\n\n it('should return correct parsed text hint and explanation for MC questions', () => {\n let markdownElement = new MultipleChoiceQuestion();\n const markdownString = '[ ] Enter a correct answer option here';\n\n ArtemisMarkdownService.parseTextHintExplanation(markdownString, markdownElement);\n expect(markdownElement.text).to.equal(markdownString);\n expect(markdownElement.hint).to.be.undefined;\n expect(markdownElement.explanation).to.be.undefined;\n\n markdownElement = new MultipleChoiceQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownHint}`, markdownElement);\n expect(markdownElement.text).to.equal('');\n expect(markdownElement.hint).to.equal(hintText);\n expect(markdownElement.explanation).to.be.undefined;\n\n markdownElement = new MultipleChoiceQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownExplanation}`, markdownElement);\n expect(markdownElement.text).to.equal('');\n expect(markdownElement.hint).to.be.undefined;\n expect(markdownElement.explanation).to.equal(explanationText);\n\n markdownElement = new MultipleChoiceQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownString} ${markdownHint} ${markdownExplanation}`, markdownElement);\n expect(markdownElement.text).to.equal(markdownString);\n expect(markdownElement.hint).to.equal(hintText);\n expect(markdownElement.explanation).to.equal(explanationText);\n });\n\n it('should return correct parsed text hint and explanation for SA questions', () => {\n let markdownElement = new ShortAnswerQuestion();\n const markdownString =\n 'Enter your long question if needed\\n' +\n 'Select a part of the text and click on Add Spot to automatically create an input field and the corresponding mapping\\n' +\n 'You can define a input field like this: This [-spot 1] an [-spot 2] field.\\n' +\n 'To define the solution for the input fields you need to create a mapping (multiple mapping also possible):';\n\n ArtemisMarkdownService.parseTextHintExplanation(markdownString, markdownElement);\n expect(markdownElement.text).to.equal(markdownString);\n expect(markdownElement.hint).to.be.undefined;\n expect(markdownElement.explanation).to.be.undefined;\n\n markdownElement = new ShortAnswerQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownHint}`, markdownElement);\n expect(markdownElement.text).to.equal('');\n expect(markdownElement.hint).to.equal(hintText);\n expect(markdownElement.explanation).to.be.undefined;\n\n markdownElement = new ShortAnswerQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownExplanation}`, markdownElement);\n expect(markdownElement.text).to.equal('');\n expect(markdownElement.hint).to.be.undefined;\n expect(markdownElement.explanation).to.equal(explanationText);\n\n markdownElement = new ShortAnswerQuestion();\n ArtemisMarkdownService.parseTextHintExplanation(`${markdownString} ${markdownHint} ${markdownExplanation}`, markdownElement);\n expect(markdownElement.text).to.equal(markdownString);\n expect(markdownElement.hint).to.equal(hintText);\n expect(markdownElement.explanation).to.equal(explanationText);\n });\n\n it('should return sanitized markdown for undefined input', () => {\n const emptyMarkdown = undefined;\n const safeMarkdown = markdownService.htmlForMarkdown(emptyMarkdown);\n expect(safeMarkdown).to.equal('');\n });\n\n it('should return sanitized markdown for html input', () => {\n const markdownString = '<b style=\"background-color: blue\">Will this render blue?</b>';\n\n // Don't disable any html tags or tags\n const safeMarkdownWithTagsAndAttributes = markdownService.htmlForMarkdown(markdownString);\n expect(safeMarkdownWithTagsAndAttributes).to.equal('<p><b style=\"background-color: blue\">Will this render blue?</b></p>');\n\n // Don't disable any html tags but disallow attributes\n const safeMarkdownWithTags = markdownService.htmlForMarkdown(markdownString, [], undefined, []);\n expect(safeMarkdownWithTags).to.equal('<p><b>Will this render blue?</b></p>');\n\n // Don't disable any html tags and allow one specific attribute\n const safeMarkdownWithTagsAndAttributeA = markdownService.htmlForMarkdown(markdownString, [], undefined, ['unused']);\n expect(safeMarkdownWithTagsAndAttributeA).to.equal('<p><b>Will this render blue?</b></p>');\n const safeMarkdownWithTagsAndAttributeB = markdownService.htmlForMarkdown(markdownString, [], undefined, ['style']);\n expect(safeMarkdownWithTagsAndAttributeB).to.equal('<p><b style=\"background-color: blue\">Will this render blue?</b></p>');\n\n // Don't disable any html attributes but disallow tags (attributes of disallowed tags are gone too)\n const safeMarkdownWithAttributes = markdownService.htmlForMarkdown(markdownString, [], []);\n expect(safeMarkdownWithAttributes).to.equal('Will this render blue?');\n\n // Only allow one specific html tag but disallow attributes\n const safeMarkdownWithSingleTagAndNoAttributes = markdownService.htmlForMarkdown(markdownString, [], ['b'], []);\n expect(safeMarkdownWithSingleTagAndNoAttributes).to.equal('<b>Will this render blue?</b>');\n\n // Only allow one specific html tag and allow all attributes\n const safeMarkdownWithSingleTagAndAttributes = markdownService.htmlForMarkdown(markdownString, [], ['b']);\n expect(safeMarkdownWithSingleTagAndAttributes).to.equal('<b style=\"background-color: blue\">Will this render blue?</b>');\n\n // Disable all html tags or attributes\n const safeMarkdownWithoutExtras = markdownService.htmlForMarkdown(markdownString, [], [], []);\n expect(safeMarkdownWithoutExtras).to.equal('Will this render blue?');\n });\n});\n" }, { "alpha_fraction": 0.615651547908783, "alphanum_fraction": 0.6193211078643799, "avg_line_length": 47.493228912353516, "blob_id": "728bf6abd0a5877436a6918c43f839e4d2e77ed2", "content_id": "5d03f08239f14c75c5544353e378266442e97104", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 25071, "license_type": "permissive", "max_line_length": 178, "num_lines": 517, "path": "/src/main/webapp/app/exam/exam-scores/exam-scores.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { forkJoin, Subscription } from 'rxjs';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { ExportToCsv } from 'export-to-csv';\nimport {\n AggregatedExamResult,\n AggregatedExerciseGroupResult,\n AggregatedExerciseResult,\n ExamScoreDTO,\n ExerciseGroup,\n StudentResult,\n} from 'app/exam/exam-scores/exam-score-dtos.model';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { onError } from 'app/shared/util/global.utils';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { round } from 'app/shared/util/utils';\nimport { LocaleConversionService } from 'app/shared/service/locale-conversion.service';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport * as SimpleStatistics from 'simple-statistics';\nimport * as Chart from 'chart.js';\nimport { ChartDataSets, ChartOptions, ChartType, LinearTickOptions } from 'chart.js';\nimport { BaseChartDirective, Label } from 'ng2-charts';\nimport { DataSet } from 'app/exercises/quiz/manage/statistics/quiz-statistic/quiz-statistic.component';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ParticipantScoresService, ScoresDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport * as Sentry from '@sentry/browser';\n\n@Component({\n selector: 'jhi-exam-scores',\n templateUrl: './exam-scores.component.html',\n changeDetection: ChangeDetectionStrategy.OnPush,\n styleUrls: ['./exam-scores.component.scss'],\n})\nexport class ExamScoresComponent implements OnInit, OnDestroy {\n public examScoreDTO: ExamScoreDTO;\n public exerciseGroups: ExerciseGroup[];\n public studentResults: StudentResult[];\n\n // Data structures for calculated statistics\n // TODO: Cache already calculated filter dependent statistics\n public aggregatedExamResults: AggregatedExamResult;\n public aggregatedExerciseGroupResults: AggregatedExerciseGroupResult[];\n public binWidth = 5;\n public histogramData: number[] = Array(100 / this.binWidth).fill(0);\n public noOfExamsFiltered: number;\n\n // exam score dtos\n studentIdToExamScoreDTOs: Map<number, ScoresDTO> = new Map<number, ScoresDTO>();\n\n public predicate = 'id';\n public reverse = false;\n public isLoading = true;\n public filterForSubmittedExams = false;\n public filterForNonEmptySubmissions = false;\n\n // Histogram related properties\n public barChartOptions: ChartOptions = {};\n public barChartLabels: Label[] = [];\n public barChartType: ChartType = 'bar';\n public barChartLegend = true;\n public barChartData: ChartDataSets[] = [];\n\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n private languageChangeSubscription?: Subscription;\n constructor(\n private route: ActivatedRoute,\n private examService: ExamManagementService,\n private sortService: SortService,\n private jhiAlertService: JhiAlertService,\n private changeDetector: ChangeDetectorRef,\n private languageHelper: JhiLanguageHelper,\n private localeConversionService: LocaleConversionService,\n private translateService: TranslateService,\n private participantScoresService: ParticipantScoresService,\n ) {}\n\n ngOnInit() {\n this.route.params.subscribe((params) => {\n const getExamScoresObservable = this.examService.getExamScores(params['courseId'], params['examId']);\n // alternative exam scores calculation using participant scores table\n const findExamScoresObservable = this.participantScoresService.findExamScores(params['examId']);\n\n forkJoin([getExamScoresObservable, findExamScoresObservable]).subscribe(\n ([getExamScoresResponse, findExamScoresResponse]) => {\n this.examScoreDTO = getExamScoresResponse!.body!;\n if (this.examScoreDTO) {\n this.studentResults = this.examScoreDTO.studentResults;\n this.exerciseGroups = this.examScoreDTO.exerciseGroups;\n\n const titleMap = new Map<string, number>();\n if (this.exerciseGroups) {\n for (const exerciseGroup of this.exerciseGroups) {\n if (titleMap.has(exerciseGroup.title)) {\n const currentValue = titleMap.get(exerciseGroup.title);\n titleMap.set(exerciseGroup.title, currentValue! + 1);\n } else {\n titleMap.set(exerciseGroup.title, 1);\n }\n }\n\n // this workaround is necessary if the exam has exercise groups with the same title (we add the id to make it unique)\n for (const exerciseGroup of this.exerciseGroups) {\n if (titleMap.has(exerciseGroup.title) && titleMap.get(exerciseGroup.title)! > 1) {\n exerciseGroup.title = `${exerciseGroup.title} (id=${exerciseGroup.id})`;\n }\n }\n }\n }\n // Only try to calculate statistics if the exam has exercise groups and student results\n if (this.studentResults && this.exerciseGroups) {\n // Exam statistics must only be calculated once as they are not filter dependent\n this.calculateExamStatistics();\n this.calculateFilterDependentStatistics();\n }\n this.isLoading = false;\n this.createChart();\n this.changeDetector.detectChanges();\n this.compareNewExamScoresCalculationWithOldCalculation(findExamScoresResponse.body!);\n },\n (res: HttpErrorResponse) => onError(this.jhiAlertService, res),\n );\n });\n\n // Update the view if the language was changed\n this.languageChangeSubscription = this.languageHelper.language.subscribe(() => {\n this.changeDetector.detectChanges();\n });\n }\n\n ngOnDestroy() {\n if (this.languageChangeSubscription) {\n this.languageChangeSubscription.unsubscribe();\n }\n }\n\n toggleFilterForSubmittedExam() {\n this.filterForSubmittedExams = !this.filterForSubmittedExams;\n this.calculateFilterDependentStatistics();\n this.changeDetector.detectChanges();\n }\n\n toggleFilterForNonEmptySubmission() {\n this.filterForNonEmptySubmissions = !this.filterForNonEmptySubmissions;\n this.calculateFilterDependentStatistics();\n this.changeDetector.detectChanges();\n }\n\n private calculateTickMax() {\n const max = Math.max(...this.histogramData);\n return Math.ceil((max + 1) / 10) * 10 + 20;\n }\n\n private createChart() {\n const labels: string[] = [];\n let i;\n for (i = 0; i < this.histogramData.length; i++) {\n labels[i] = `[${i * this.binWidth},${(i + 1) * this.binWidth}`;\n labels[i] += i === this.histogramData.length - 1 ? ']' : ')';\n }\n this.barChartLabels = labels;\n\n const component = this;\n\n this.barChartOptions = {\n responsive: true,\n maintainAspectRatio: false,\n legend: {\n align: 'start',\n position: 'bottom',\n },\n scales: {\n yAxes: [\n {\n scaleLabel: {\n display: true,\n labelString: this.translateService.instant('artemisApp.examScores.yAxes'),\n },\n ticks: {\n maxTicksLimit: 11,\n beginAtZero: true,\n precision: 0,\n min: 0,\n max: this.calculateTickMax(),\n } as LinearTickOptions,\n },\n ],\n xAxes: [\n {\n scaleLabel: {\n display: true,\n labelString: this.translateService.instant('artemisApp.examScores.xAxes'),\n },\n },\n ],\n },\n hover: {\n animationDuration: 0,\n },\n animation: {\n duration: 1,\n onComplete() {\n const chartInstance = this.chart,\n ctx = chartInstance.ctx;\n\n ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);\n ctx.textAlign = 'center';\n ctx.textBaseline = 'bottom';\n\n this.data.datasets.forEach(function (dataset: DataSet, j: number) {\n const meta = chartInstance.controller.getDatasetMeta(j);\n meta.data.forEach(function (bar: any, index: number) {\n const data = dataset.data[index];\n ctx.fillText(data, bar._model.x, bar._model.y - 20);\n ctx.fillText(`(${component.roundAndPerformLocalConversion((data * 100) / component.noOfExamsFiltered, 2, 2)}%)`, bar._model.x, bar._model.y - 5);\n });\n });\n },\n },\n };\n\n this.barChartData = [\n {\n label: '# of students',\n data: this.histogramData,\n backgroundColor: 'rgba(0,0,0,0.5)',\n },\n ];\n }\n\n /**\n * Calculates filter dependent exam statistics. Must be triggered if filter settings change.\n * 1. The average points and number of participants for each exercise group and exercise\n * 2. Distribution of scores\n */\n private calculateFilterDependentStatistics() {\n this.histogramData.fill(0);\n\n // Create data structures holding the statistics for all exercise groups and exercises\n const groupIdToGroupResults = new Map<number, AggregatedExerciseGroupResult>();\n for (const exerciseGroup of this.exerciseGroups) {\n const groupResult = new AggregatedExerciseGroupResult(exerciseGroup.id, exerciseGroup.title, exerciseGroup.maxPoints, exerciseGroup.numberOfParticipants);\n // We initialize the data structure for exercises here as it can happen that no student was assigned to an exercise\n exerciseGroup.containedExercises.forEach((exerciseInfo) => {\n const exResult = new AggregatedExerciseResult(exerciseInfo.exerciseId, exerciseInfo.title, exerciseInfo.maxPoints, exerciseInfo.numberOfParticipants);\n groupResult.exerciseResults.push(exResult);\n });\n groupIdToGroupResults.set(exerciseGroup.id, groupResult);\n }\n\n // Calculate the total points and number of participants when filters apply for each exercise group and exercise\n for (const studentResult of this.studentResults) {\n // Do not take un-submitted exams into account for the exercise statistics if the option was set\n if (!studentResult.submitted && this.filterForSubmittedExams) {\n continue;\n }\n // Update histogram data structure\n let histogramIndex = Math.floor(studentResult.overallScoreAchieved! / this.binWidth);\n if (histogramIndex >= 100 / this.binWidth) {\n // This happens, for 100%, if the exam total points were not set correctly or bonus points were given\n histogramIndex = 100 / this.binWidth - 1;\n }\n this.histogramData[histogramIndex]++;\n if (!studentResult.exerciseGroupIdToExerciseResult) {\n continue;\n }\n const entries = Object.entries(studentResult.exerciseGroupIdToExerciseResult);\n\n for (const [exGroupId, studentExerciseResult] of entries) {\n // Ignore exercise results with only empty submission if the option was set\n if (!studentExerciseResult.hasNonEmptySubmission && this.filterForNonEmptySubmissions) {\n continue;\n }\n // Update the exerciseGroup statistic\n const exGroupResult = groupIdToGroupResults.get(Number(exGroupId));\n if (!exGroupResult) {\n // This should never been thrown. Indicates that the information in the ExamScoresDTO is inconsistent\n throw new Error(`ExerciseGroup with id ${exGroupId} does not exist in this exam!`);\n }\n exGroupResult.noOfParticipantsWithFilter++;\n exGroupResult.totalPoints += studentExerciseResult.achievedPoints!;\n\n // Update the specific exercise statistic\n const exerciseResult = exGroupResult.exerciseResults.find((exResult) => exResult.exerciseId === studentExerciseResult.exerciseId);\n if (!exerciseResult) {\n // This should never been thrown. Indicates that the information in the ExamScoresDTO is inconsistent\n throw new Error(`Exercise with id ${studentExerciseResult.exerciseId} does not exist in this exam!`);\n } else {\n exerciseResult.noOfParticipantsWithFilter++;\n exerciseResult.totalPoints += studentExerciseResult.achievedPoints!;\n }\n }\n }\n this.noOfExamsFiltered = SimpleStatistics.sum(this.histogramData);\n // Calculate exercise group and exercise statistics\n const exerciseGroupResults = Array.from(groupIdToGroupResults.values());\n this.calculateExerciseGroupStatistics(exerciseGroupResults);\n\n if (this.chart) {\n this.chart.options!.scales!.yAxes![0]!.ticks!.max = this.calculateTickMax();\n this.chart.update(0);\n }\n }\n\n /**\n * Calculates statistics on exam granularity for submitted exams and for all exams.\n */\n private calculateExamStatistics() {\n const studentPointsSubmitted: number[] = [];\n const studentPointsTotal: number[] = [];\n\n // Collect student points independent from the filter settings\n for (const studentResult of this.studentResults) {\n studentPointsTotal.push(studentResult.overallPointsAchieved!);\n if (studentResult.submitted) {\n studentPointsSubmitted.push(studentResult.overallPointsAchieved!);\n }\n }\n\n const examStatistics = new AggregatedExamResult();\n // Calculate statistics for submitted exams\n if (studentPointsSubmitted.length) {\n examStatistics.meanPoints = SimpleStatistics.mean(studentPointsSubmitted);\n examStatistics.median = SimpleStatistics.median(studentPointsSubmitted);\n examStatistics.standardDeviation = SimpleStatistics.standardDeviation(studentPointsSubmitted);\n examStatistics.noOfExamsFiltered = studentPointsSubmitted.length;\n if (this.examScoreDTO.maxPoints) {\n examStatistics.meanPointsRelative = (examStatistics.meanPoints / this.examScoreDTO.maxPoints) * 100;\n examStatistics.medianRelative = (examStatistics.median / this.examScoreDTO.maxPoints) * 100;\n }\n }\n // Calculate total statistics\n if (studentPointsTotal.length) {\n examStatistics.meanPointsTotal = SimpleStatistics.mean(studentPointsTotal);\n examStatistics.medianTotal = SimpleStatistics.median(studentPointsTotal);\n examStatistics.standardDeviationTotal = SimpleStatistics.standardDeviation(studentPointsTotal);\n examStatistics.noOfRegisteredUsers = this.studentResults.length;\n if (this.examScoreDTO.maxPoints) {\n examStatistics.meanPointsRelativeTotal = (examStatistics.meanPointsTotal / this.examScoreDTO.maxPoints) * 100;\n examStatistics.medianRelativeTotal = (examStatistics.medianTotal / this.examScoreDTO.maxPoints) * 100;\n }\n }\n this.aggregatedExamResults = examStatistics;\n }\n\n /**\n * Calculate statistics on exercise group and exercise granularity. These statistics are filter dependent.\n * @param exerciseGroupResults Data structure holding the aggregated points and number of participants\n */\n private calculateExerciseGroupStatistics(exerciseGroupResults: AggregatedExerciseGroupResult[]) {\n for (const groupResult of exerciseGroupResults) {\n // For average points for exercise groups\n if (groupResult.noOfParticipantsWithFilter) {\n groupResult.averagePoints = groupResult.totalPoints / groupResult.noOfParticipantsWithFilter;\n groupResult.averagePercentage = (groupResult.averagePoints / groupResult.maxPoints) * 100;\n }\n // Calculate average points for exercises\n groupResult.exerciseResults.forEach((exResult) => {\n if (exResult.noOfParticipantsWithFilter) {\n exResult.averagePoints = exResult.totalPoints / exResult.noOfParticipantsWithFilter;\n exResult.averagePercentage = (exResult.averagePoints / exResult.maxPoints) * 100;\n }\n });\n }\n this.aggregatedExerciseGroupResults = exerciseGroupResults;\n }\n\n sortRows() {\n this.sortService.sortByProperty(this.examScoreDTO.studentResults, this.predicate, this.reverse);\n this.changeDetector.detectChanges();\n }\n\n exportToCsv() {\n const headers = ['Name', 'Login', 'E-Mail', 'Matriculation Number'];\n this.exerciseGroups.forEach((exerciseGroup) => {\n headers.push(exerciseGroup.title + ' Assigned Exercise');\n headers.push(exerciseGroup.title + ' Achieved Points');\n headers.push(exerciseGroup.title + ' Achieved Score (%)');\n });\n headers.push('Overall Points');\n headers.push('Overall Score (%)');\n headers.push('Submitted');\n\n const rows = this.studentResults.map((studentResult) => {\n return this.convertToCSVRow(studentResult);\n });\n\n this.exportAsCsv(rows, headers);\n }\n\n exportAsCsv(rows: any[], headers: string[]) {\n const options = {\n fieldSeparator: ';',\n quoteStrings: '\"',\n decimalSeparator: 'locale',\n showLabels: true,\n title: this.examScoreDTO.title,\n filename: this.examScoreDTO.title + 'Results',\n useTextFile: false,\n useBom: true,\n headers,\n };\n\n const csvExporter = new ExportToCsv(options);\n csvExporter.generateCsv(rows);\n }\n\n /**\n * Wrapper for round utility function so it can be used in the template.\n * @param value\n * @param exp\n */\n round(value: any, exp: number) {\n return round(value, exp);\n }\n\n private convertToCSVRow(studentResult: StudentResult) {\n const csvRow: any = {\n name: studentResult.name ? studentResult.name : '',\n login: studentResult.login ? studentResult.login : '',\n eMail: studentResult.eMail ? studentResult.eMail : '',\n registrationNumber: studentResult.registrationNumber ? studentResult.registrationNumber : '',\n };\n\n this.exerciseGroups.forEach((exerciseGroup) => {\n const exerciseResult = studentResult.exerciseGroupIdToExerciseResult[exerciseGroup.id];\n if (exerciseResult) {\n csvRow[exerciseGroup.title + ' Assigned Exercise'] = exerciseResult.title ? exerciseResult.title : '';\n csvRow[exerciseGroup.title + ' Achieved Points'] =\n exerciseResult.achievedPoints == undefined ? '' : this.localeConversionService.toLocaleString(round(exerciseResult.achievedPoints, 1));\n csvRow[exerciseGroup.title + ' Achieved Score (%)'] =\n exerciseResult.achievedScore == undefined ? '' : this.localeConversionService.toLocaleString(round(exerciseResult.achievedScore, 2), 2);\n } else {\n csvRow[exerciseGroup.title + ' Assigned Exercise'] = '';\n csvRow[exerciseGroup.title + ' Achieved Points'] = '';\n csvRow[exerciseGroup.title + ' Achieved Score (%)'] = '';\n }\n });\n\n csvRow.overAllPoints = studentResult.overallPointsAchieved == undefined ? '' : this.localeConversionService.toLocaleString(round(studentResult.overallPointsAchieved, 1));\n csvRow.overAllScore = studentResult.overallScoreAchieved == undefined ? '' : this.localeConversionService.toLocaleString(round(studentResult.overallScoreAchieved, 2), 2);\n csvRow.submitted = studentResult.submitted ? 'yes' : 'no';\n return csvRow;\n }\n\n toLocaleString(points: number) {\n return this.localeConversionService.toLocaleString(points);\n }\n\n roundAndPerformLocalConversion(points: number | undefined, exp: number, fractions = 1) {\n return this.localeConversionService.toLocaleString(round(points, exp), fractions);\n }\n\n /**\n * This method compares the exam scores computed via the two approaches on the server (one using\n * participation -> submission -> result and the other one using the participationScores table)\n * In the future we might switch to the server side method, so we use this method to detect discrepancies.\n * @param examScoreDTOs the exam scores sent from the server (new calculation method)\n */\n private compareNewExamScoresCalculationWithOldCalculation(examScoreDTOs: ScoresDTO[]) {\n if (!this.studentResults || !examScoreDTOs) {\n return;\n }\n for (const examScoreDTO of examScoreDTOs) {\n this.studentIdToExamScoreDTOs.set(examScoreDTO.studentId!, examScoreDTO);\n }\n let noOfScoreDifferencesFound = 0;\n let noOfPointDifferencesFound = 0;\n let noOfComparisons = 0;\n for (const studentResult of this.studentResults) {\n const overAllPoints = round(studentResult.overallPointsAchieved, 1);\n const overallScore = round(studentResult.overallScoreAchieved, 1);\n\n const regularCalculation = {\n scoreAchieved: overallScore,\n pointsAchieved: overAllPoints,\n userId: studentResult.userId,\n userLogin: studentResult.login,\n };\n // checking if the same as in the exam scores map\n const examScoreDTO = this.studentIdToExamScoreDTOs.get(studentResult.userId);\n if (!examScoreDTO) {\n const errorMessage = `Exam scores not included in new calculation: ${JSON.stringify(regularCalculation)}`;\n this.logErrorOnSentry(errorMessage);\n } else {\n noOfComparisons += 1;\n examScoreDTO.scoreAchieved = round(examScoreDTO.scoreAchieved, 1);\n examScoreDTO.pointsAchieved = round(examScoreDTO.pointsAchieved, 1);\n\n if (Math.abs(examScoreDTO.pointsAchieved - regularCalculation.pointsAchieved) > 0.1) {\n const errorMessage = `Different exam points in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation: ${JSON.stringify(\n examScoreDTO,\n )}`;\n noOfPointDifferencesFound += 1;\n this.logErrorOnSentry(errorMessage);\n }\n if (Math.abs(examScoreDTO.scoreAchieved - regularCalculation.scoreAchieved) > 0.1) {\n const errorMessage = `Different exam score in new calculation. Regular Calculation: ${JSON.stringify(regularCalculation)}. New Calculation : ${JSON.stringify(\n examScoreDTO,\n )}`;\n noOfScoreDifferencesFound += 1;\n this.logErrorOnSentry(errorMessage);\n }\n }\n }\n console.log(`Performed ${noOfComparisons} comparisons between old and new calculation method.`);\n console.log(`Found ${noOfPointDifferencesFound} point differences between old and new calculation method.`);\n console.log(`Found ${noOfScoreDifferencesFound} point differences between old and new calculation method.`);\n }\n\n logErrorOnSentry(errorMessage: string) {\n console.log(errorMessage);\n Sentry.captureException(new Error(errorMessage));\n }\n}\n" }, { "alpha_fraction": 0.6292160749435425, "alphanum_fraction": 0.6320578455924988, "avg_line_length": 46.26865768432617, "blob_id": "1cbc3638365f93facfc302dd1f8e8c46461698b4", "content_id": "af73e9b905e6550ec1d7226372c0d0b4ff0f4d8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 34837, "license_type": "permissive", "max_line_length": 180, "num_lines": 737, "path": "/src/main/java/de/tum/in/www1/artemis/service/FileService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static java.nio.file.StandardCopyOption.REPLACE_EXISTING;\n\nimport java.io.*;\nimport java.nio.charset.Charset;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.*;\nimport java.time.ZonedDateTime;\nimport java.util.Collection;\nimport java.util.Map;\nimport java.util.UUID;\nimport java.util.concurrent.*;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.io.FilenameUtils;\nimport org.apache.commons.io.filefilter.FileFilterUtils;\nimport org.apache.commons.io.filefilter.IOFileFilter;\nimport org.apache.commons.lang3.math.NumberUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.DisposableBean;\nimport org.springframework.cache.annotation.CacheEvict;\nimport org.springframework.cache.annotation.Cacheable;\nimport org.springframework.core.io.Resource;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.FileSystemUtils;\n\nimport com.ibm.icu.text.CharsetDetector;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.FileUploadSubmission;\nimport de.tum.in.www1.artemis.exception.FilePathParsingException;\n\n@Service\npublic class FileService implements DisposableBean {\n\n private final Logger log = LoggerFactory.getLogger(FileService.class);\n\n private final Map<Path, ScheduledFuture<?>> futures = new ConcurrentHashMap<>();\n\n private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());\n\n @Override\n public void destroy() {\n futures.values().forEach(future -> future.cancel(true));\n futures.clear();\n }\n\n /**\n * Get the file for the given path as a byte[]\n *\n * @param path the path for the file to load\n * @return file contents as a byte[], or null, if the file doesn't exist\n * @throws IOException if the file can't be accessed.\n */\n @Cacheable(value = \"files\", unless = \"#result == null\")\n public byte[] getFileForPath(String path) throws IOException {\n File file = new File(path);\n if (file.exists()) {\n return Files.readAllBytes(file.toPath());\n }\n else {\n return null;\n }\n }\n\n @CacheEvict(value = \"files\", key = \"#path\")\n public void resetOnPath(String path) {\n log.info(\"Invalidate files cache for {}\", path);\n // Intentionally blank\n }\n\n /**\n * Takes care of any changes that have to be made to the filesystem (deleting old files, moving temporary files into their proper location) and returns the public path for the\n * resulting file (as it might have been moved from newFilePath to another path)\n *\n * @param oldFilePath the old file path (this file will be deleted if not null and different from newFilePath)\n * @param newFilePath the new file path (this file will be moved into its proper location, if it was a temporary file)\n * @param targetFolder the folder that a temporary file should be moved to\n * @param entityId id of the entity this file belongs to (needed to generate public path). If this is null, a placeholder will be inserted where the id would be\n * @return the resulting public path (is identical to newFilePath, if file didn't need to be moved)\n */\n public String manageFilesForUpdatedFilePath(String oldFilePath, String newFilePath, String targetFolder, Long entityId) {\n return manageFilesForUpdatedFilePath(oldFilePath, newFilePath, targetFolder, entityId, false);\n }\n\n /**\n * Takes care of any changes that have to be made to the filesystem (deleting old files, moving temporary files into their proper location) and returns the public path for the\n * resulting file (as it might have been moved from newFilePath to another path)\n *\n * @param oldFilePath the old file path (this file will be deleted if not null and different from newFilePath)\n * @param newFilePath the new file path (this file will be moved into its proper location, if it was a temporary file)\n * @param targetFolder the folder that a temporary file should be moved to\n * @param entityId id of the entity this file belongs to (needed to generate public path). If this is null, a placeholder will be inserted where the id would be\n * @param keepFileName flag for determining if the current filename should be kept.\n * @return the resulting public path (is identical to newFilePath, if file didn't need to be moved)\n */\n public String manageFilesForUpdatedFilePath(String oldFilePath, String newFilePath, String targetFolder, Long entityId, Boolean keepFileName) {\n if (oldFilePath != null) {\n if (oldFilePath.equals(newFilePath)) {\n // Do nothing\n return newFilePath;\n }\n else {\n // delete old file\n log.debug(\"Delete old file {}\", oldFilePath);\n try {\n File oldFile = new File(actualPathForPublicPath(oldFilePath));\n\n if (!FileSystemUtils.deleteRecursively(oldFile)) {\n log.warn(\"FileService.manageFilesForUpdatedFilePath: Could not delete old file: {}\", oldFile);\n }\n else {\n log.debug(\"Deleted Orphaned File: {}\", oldFile);\n }\n }\n catch (Exception ex) {\n log.warn(\"FileService.manageFilesForUpdatedFilePath: Could not delete old file '{}' due to exception {}\", oldFilePath, ex.getMessage());\n }\n }\n }\n // check if newFilePath is a temp file\n if (newFilePath != null && newFilePath.contains(\"files/temp\")) {\n // rename and move file\n try {\n Path source = Paths.get(actualPathForPublicPath(newFilePath));\n File targetFile = generateTargetFile(newFilePath, targetFolder, keepFileName);\n Path target = targetFile.toPath();\n Files.move(source, target, REPLACE_EXISTING);\n newFilePath = publicPathForActualPath(target.toString(), entityId);\n log.debug(\"Moved File from {} to {}\", source, target);\n }\n catch (IOException e) {\n log.error(\"Error moving file: {}\", newFilePath);\n }\n }\n return newFilePath;\n }\n\n /**\n * Convert the given public file url to its corresponding local path\n *\n * @param publicPath the public file url to convert\n * @return the actual path to that file in the local filesystem\n */\n public String actualPathForPublicPath(String publicPath) {\n // first extract the filename from the url\n String filename = publicPath.substring(publicPath.lastIndexOf(\"/\") + 1);\n\n // check for known path to convert\n if (publicPath.contains(\"files/temp\")) {\n return Paths.get(FilePathService.getTempFilePath(), filename).toString();\n }\n if (publicPath.contains(\"files/drag-and-drop/backgrounds\")) {\n return Paths.get(FilePathService.getDragAndDropBackgroundFilePath(), filename).toString();\n }\n if (publicPath.contains(\"files/drag-and-drop/drag-items\")) {\n return Paths.get(FilePathService.getDragItemFilePath(), filename).toString();\n }\n if (publicPath.contains(\"files/course/icons\")) {\n return Paths.get(FilePathService.getCourseIconFilePath(), filename).toString();\n }\n if (publicPath.contains(\"files/attachments/lecture\")) {\n String lectureId = publicPath.replace(filename, \"\").replace(\"/api/files/attachments/lecture/\", \"\");\n return Paths.get(FilePathService.getLectureAttachmentFilePath(), lectureId, filename).toString();\n }\n if (publicPath.contains(\"files/attachments/attachment-unit\")) {\n String attachmentUnitId = publicPath.replace(filename, \"\").replace(\"/api/files/attachments/attachment-unit/\", \"\");\n return Paths.get(FilePathService.getAttachmentUnitFilePath(), attachmentUnitId, filename).toString();\n }\n if (publicPath.contains(\"files/file-upload-exercises\")) {\n final var uploadSubPath = publicPath.replace(filename, \"\").replace(\"/api/files/file-upload-exercises/\", \"\").split(\"/\");\n final var shouldBeExerciseId = uploadSubPath[0];\n final var shouldBeSubmissionId = uploadSubPath.length >= 3 ? uploadSubPath[2] : null;\n if (!NumberUtils.isCreatable(shouldBeExerciseId) || !NumberUtils.isCreatable(shouldBeSubmissionId)) {\n throw new FilePathParsingException(\"Public path does not contain correct exerciseId or submissionId: \" + publicPath);\n }\n final var exerciseId = Long.parseLong(shouldBeExerciseId);\n final var submissionId = Long.parseLong(shouldBeSubmissionId);\n return Paths.get(FileUploadSubmission.buildFilePath(exerciseId, submissionId), filename).toString();\n }\n\n // path is unknown => cannot convert\n throw new FilePathParsingException(\"Unknown Filepath: \" + publicPath);\n }\n\n /**\n * Generate the public path for the file at the given path\n *\n * @param actualPath the path to the file in the local filesystem\n * @param entityId the id of the entity associated with the file (may be null)\n * @return the public file url that can be used by users to access the file from outside\n */\n public String publicPathForActualPath(String actualPath, Long entityId) {\n // first extract filename\n String filename = Paths.get(actualPath).getFileName().toString();\n\n // generate part for id\n String id = entityId == null ? Constants.FILEPATH_ID_PLACEHOLDER : entityId.toString();\n\n // check for known path to convert\n if (actualPath.contains(FilePathService.getTempFilePath())) {\n return \"/api/files/temp/\" + filename;\n }\n if (actualPath.contains(FilePathService.getDragAndDropBackgroundFilePath())) {\n return \"/api/files/drag-and-drop/backgrounds/\" + id + \"/\" + filename;\n }\n if (actualPath.contains(FilePathService.getDragItemFilePath())) {\n return \"/api/files/drag-and-drop/drag-items/\" + id + \"/\" + filename;\n }\n if (actualPath.contains(FilePathService.getCourseIconFilePath())) {\n return \"/api/files/course/icons/\" + id + \"/\" + filename;\n }\n if (actualPath.contains(FilePathService.getLectureAttachmentFilePath())) {\n return \"/api/files/attachments/lecture/\" + id + \"/\" + filename;\n }\n if (actualPath.contains(FilePathService.getAttachmentUnitFilePath())) {\n return \"/api/files/attachments/attachment-unit/\" + id + \"/\" + filename;\n }\n if (actualPath.contains(FilePathService.getFileUploadExercisesFilePath())) {\n final var path = Paths.get(actualPath);\n final long exerciseId;\n try {\n // The last name is the file name, the one one before that is the submissionId and the one before that is the exerciseId, in which we are interested\n final var shouldBeExerciseId = path.getName(path.getNameCount() - 3).toString();\n exerciseId = Long.parseLong(shouldBeExerciseId);\n }\n catch (IllegalArgumentException e) {\n throw new FilePathParsingException(\"Unexpected String in upload file path. Exercise ID should be present here: \" + actualPath);\n }\n return \"/api/files/file-upload-exercises/\" + exerciseId + \"/submissions/\" + id + \"/\" + filename;\n }\n\n // path is unknown => cannot convert\n throw new FilePathParsingException(\"Unknown Filepath: \" + actualPath);\n }\n\n /**\n * Creates a new file at the given location with a proper filename consisting of type, timestamp and a random part\n *\n * @param originalFilename the original filename of the file (needed to determine the file type)\n * @param targetFolder the folder where the new file should be created\n * @return the newly created file\n * @throws IOException if the file can't be generated.\n */\n private File generateTargetFile(String originalFilename, String targetFolder, Boolean keepFileName) throws IOException {\n // determine the base for the filename\n String filenameBase = \"Unspecified_\";\n if (targetFolder.equals(FilePathService.getDragAndDropBackgroundFilePath())) {\n filenameBase = \"DragAndDropBackground_\";\n }\n if (targetFolder.equals(FilePathService.getDragItemFilePath())) {\n filenameBase = \"DragItem_\";\n }\n if (targetFolder.equals(FilePathService.getCourseIconFilePath())) {\n filenameBase = \"CourseIcon_\";\n }\n if (targetFolder.contains(FilePathService.getLectureAttachmentFilePath())) {\n filenameBase = \"LectureAttachment_\";\n }\n if (targetFolder.contains(FilePathService.getAttachmentUnitFilePath())) {\n filenameBase = \"AttachmentUnit_\";\n }\n\n // extract the file extension\n String fileExtension = FilenameUtils.getExtension(originalFilename);\n\n // create folder if necessary\n File folder = new File(targetFolder);\n if (!folder.exists()) {\n if (!folder.mkdirs()) {\n log.error(\"Could not create directory: {}\", targetFolder);\n throw new IOException(\"Could not create directory: \" + targetFolder);\n }\n }\n\n // create the file (retry if filename already exists)\n boolean fileCreated;\n File newFile;\n String filename;\n do {\n if (keepFileName) {\n if (originalFilename.contains(\"/api/files/temp/\")) {\n originalFilename = originalFilename.replace(\"/api/files/temp/\", \"\");\n }\n filename = originalFilename;\n }\n else {\n filename = filenameBase + ZonedDateTime.now().toString().substring(0, 23).replaceAll(\"[:.]\", \"-\") + \"_\" + UUID.randomUUID().toString().substring(0, 8) + \".\"\n + fileExtension;\n }\n var path = Paths.get(targetFolder, filename).toString();\n\n newFile = new File(path);\n if (keepFileName && newFile.exists()) {\n newFile.delete();\n }\n fileCreated = newFile.createNewFile();\n }\n while (!fileCreated);\n\n return newFile;\n }\n\n /**\n * This copies the directory at the old directory path to the new path, including all files and sub folders\n *\n * @param resources the resources that should be copied\n * @param prefix cut everything until the end of the prefix (e.g. exercise-abc -> abc when prefix = exercise)\n * @param targetDirectoryPath the path of the folder where the copy should be located\n * @param keepParentFolder if true also creates the resources with the folder they are currently in (e.g. current/parent/* -> new/parent/*)\n * @throws IOException if the copying operation fails.\n */\n public void copyResources(Resource[] resources, String prefix, String targetDirectoryPath, Boolean keepParentFolder) throws IOException {\n\n for (Resource resource : resources) {\n\n // Replace windows separator with \"/\"\n String fileUrl = java.net.URLDecoder.decode(resource.getURL().toString(), StandardCharsets.UTF_8).replaceAll(\"\\\\\\\\\", \"/\");\n // cut the prefix (e.g. 'exercise', 'solution', 'test') from the actual path\n int index = fileUrl.indexOf(prefix);\n String targetFilePath = keepParentFolder ? fileUrl.substring(index + prefix.length()) : \"/\" + resource.getFilename();\n // special case for '.git.ignore.file' file which would not be included in build otherwise\n if (targetFilePath.endsWith(\"git.ignore.file\")) {\n targetFilePath = targetFilePath.replaceAll(\"git.ignore.file\", \".gitignore\");\n }\n // special case for '.gitattributes' file which would not be included in build otherwise\n if (targetFilePath.endsWith(\"git.attributes.file\")) {\n targetFilePath = targetFilePath.replaceAll(\"git.attributes.file\", \".gitattributes\");\n }\n // special case for 'Makefile' files which would not be included in the build otherwise\n if (targetFilePath.endsWith(\"Makefile.file\")) {\n targetFilePath = targetFilePath.replace(\"Makefile.file\", \"Makefile\");\n }\n // special case for '.project' files which would not be included in the build otherwise\n if (targetFilePath.endsWith(\"project.file\")) {\n targetFilePath = targetFilePath.replace(\"project.file\", \".project\");\n }\n // special case for '.classpath' files which would not be included in the build otherwise\n if (targetFilePath.endsWith(\"classpath.file\")) {\n targetFilePath = targetFilePath.replace(\"classpath.file\", \".classpath\");\n }\n // special case for 'dune' files which would not be included in the build otherwise\n if (targetFilePath.endsWith(\"dune.file\")) {\n targetFilePath = targetFilePath.replace(\"dune.file\", \"dune\");\n }\n\n Path copyPath = Paths.get(targetDirectoryPath + targetFilePath);\n File parentFolder = copyPath.toFile().getParentFile();\n if (!parentFolder.exists()) {\n Files.createDirectories(parentFolder.toPath());\n }\n\n Files.copy(resource.getInputStream(), copyPath, StandardCopyOption.REPLACE_EXISTING);\n }\n }\n\n /**\n * This renames the directory at the old directory path to the new path\n *\n * @param oldDirectoryPath the path of the folder that should be renamed\n * @param targetDirectoryPath the path of the folder where the renamed folder should be located\n * @throws IOException if the directory could not be renamed.\n */\n public void renameDirectory(String oldDirectoryPath, String targetDirectoryPath) throws IOException {\n File oldDirectory = new File(oldDirectoryPath);\n if (!oldDirectory.exists()) {\n log.error(\"Directory {} should be renamed but does not exist.\", oldDirectoryPath);\n throw new RuntimeException(\"Directory \" + oldDirectoryPath + \" should be renamed but does not exist.\");\n }\n\n File targetDirectory = new File(targetDirectoryPath);\n\n FileUtils.moveDirectory(oldDirectory, targetDirectory);\n }\n\n /**\n * Look for sections that start and end with a section marker (e.g. %section-start% and %section-end%). Overrides the given file in filePath with a new file!\n *\n * @param filePath of file to look for replaceable sections in.\n * @param sections of structure String (section name) / Boolean (keep content in section or remove it).\n */\n public void replacePlaceholderSections(String filePath, Map<String, Boolean> sections) {\n Map<Pattern, Boolean> patternBooleanMap = sections.entrySet().stream().collect(Collectors.toMap(e -> Pattern.compile(\".*%\" + e.getKey() + \".*%.*\"), Map.Entry::getValue));\n File file = new File(filePath);\n File tempFile = new File(filePath + \"_temp\");\n FileReader fr;\n FileWriter fw;\n BufferedReader reader;\n BufferedWriter writer;\n\n try {\n fr = new FileReader(file);\n fw = new FileWriter(tempFile);\n }\n catch (IOException ex) {\n throw new FilePathParsingException(\"File \" + filePath + \" should be updated but does not exist.\");\n }\n\n reader = new BufferedReader(fr);\n writer = new BufferedWriter(fw);\n\n try {\n\n Map.Entry<Pattern, Boolean> matchingStartPattern = null;\n String line = reader.readLine();\n while (line != null) {\n // If there is no starting pattern matched atm, check if the current line is a start pattern.\n if (matchingStartPattern == null) {\n for (Map.Entry<Pattern, Boolean> entry : patternBooleanMap.entrySet()) {\n if (entry.getKey().matcher(line).matches()) {\n matchingStartPattern = entry;\n break;\n }\n }\n // If a pattern is matched, don't write anything so that the section qualifier is removed.\n if (matchingStartPattern != null) {\n line = reader.readLine();\n continue;\n }\n }\n else {\n // If there is a starting pattern matched, check if an ending pattern is encountered.\n boolean endMatcherFound = false;\n for (Map.Entry<Pattern, Boolean> entry : patternBooleanMap.entrySet()) {\n if (entry.getKey().matcher(line).matches()) {\n endMatcherFound = true;\n break;\n }\n }\n if (endMatcherFound) {\n matchingStartPattern = null;\n line = reader.readLine();\n continue;\n }\n }\n\n if (matchingStartPattern == null || matchingStartPattern.getValue()) {\n writer.write(line);\n writer.newLine();\n }\n\n line = reader.readLine();\n }\n // Accessing already opened files will cause an exception on Windows machines, therefore close the streams\n reader.close();\n writer.close();\n Files.delete(file.toPath());\n FileUtils.moveFile(tempFile, new File(filePath));\n }\n catch (IOException ex) {\n throw new RuntimeException(\"Error encountered when reading File \" + filePath + \".\");\n }\n finally {\n try {\n reader.close();\n writer.close();\n }\n catch (IOException ex) {\n log.info(\"Error encountered when closing file readers / writers for {}\", file);\n }\n }\n }\n\n /**\n * This replace all occurrences of the target String with the replacement String in the given directory (recursive!)\n *\n * @param startPath the path where the file is located\n * @param targetString the string that should be replaced\n * @param replacementString the string that should be used to replace the target\n * @throws IOException if an issue occurs on file access for the replacement of the variables.\n */\n public void replaceVariablesInDirectoryName(String startPath, String targetString, String replacementString) throws IOException {\n log.debug(\"Replacing {} with {} in directory {}\", targetString, replacementString, startPath);\n File directory = new File(startPath);\n if (!directory.exists() || !directory.isDirectory()) {\n throw new RuntimeException(\"Directory \" + startPath + \" should be replaced but does not exist.\");\n }\n\n if (startPath.contains(targetString)) {\n log.debug(\"Target String found, replacing..\");\n String targetPath = startPath.replace(targetString, replacementString);\n renameDirectory(startPath, targetPath);\n directory = new File(targetPath);\n }\n\n // Get all subdirectories\n final var subDirectories = directory.list((current, name) -> new File(current, name).isDirectory());\n\n if (subDirectories != null) {\n for (String subDirectory : subDirectories) {\n replaceVariablesInDirectoryName(Paths.get(directory.getAbsolutePath(), subDirectory).toString(), targetString, replacementString);\n }\n }\n }\n\n /**\n * This replaces all occurrences of the target Strings with the replacement Strings in the given file and saves the file\n * <p>\n * {@link #replaceVariablesInFile(String, Map) replaceVariablesInFile}\n *\n * @param startPath the path where the start directory is located\n * @param replacements the replacements that should be applied\n * @throws IOException if an issue occurs on file access for the replacement of the variables.\n */\n public void replaceVariablesInFileRecursive(String startPath, Map<String, String> replacements) throws IOException {\n log.debug(\"Replacing {} in files in directory {}\", replacements, startPath);\n File directory = new File(startPath);\n if (!directory.exists() || !directory.isDirectory()) {\n throw new RuntimeException(\"Files in directory \" + startPath + \" should be replaced but the directory does not exist.\");\n }\n\n // Get all files in directory\n String[] files = directory.list((current, name) -> new File(current, name).isFile());\n if (files != null) {\n for (String file : files) {\n\n replaceVariablesInFile(Paths.get(directory.getAbsolutePath(), file).toString(), replacements);\n }\n }\n\n // Recursive call: get all subdirectories\n String[] subDirectories = directory.list((current, name) -> new File(current, name).isDirectory());\n if (subDirectories != null) {\n for (String subDirectory : subDirectories) {\n if (subDirectory.equalsIgnoreCase(\".git\")) {\n // ignore files in the '.git' folder\n continue;\n }\n replaceVariablesInFileRecursive(Paths.get(directory.getAbsolutePath(), subDirectory).toString(), replacements);\n }\n }\n }\n\n /**\n * This replaces all occurrences of the target Strings with the replacement Strings in the given file and saves the file. It assumes that the size of the lists is equal and the\n * order of the argument is the same\n *\n * @param filePath the path where the file is located\n * @param replacements the replacements that should be applied\n * @throws IOException if an issue occurs on file access for the replacement of the variables.\n */\n public void replaceVariablesInFile(String filePath, Map<String, String> replacements) throws IOException {\n log.debug(\"Replacing {} in file {}\", replacements, filePath);\n // https://stackoverflow.com/questions/3935791/find-and-replace-words-lines-in-a-file\n Path replaceFilePath = Paths.get(filePath);\n Charset charset = StandardCharsets.UTF_8;\n\n String fileContent = Files.readString(replaceFilePath, charset);\n for (Map.Entry<String, String> replacement : replacements.entrySet()) {\n fileContent = fileContent.replace(replacement.getKey(), replacement.getValue());\n }\n Files.writeString(replaceFilePath, fileContent, charset);\n }\n\n /**\n * This normalizes all line endings to UNIX-line-endings recursively from the startPath.\n * <p>\n * {@link #normalizeLineEndings(String) normalizeLineEndings}\n *\n * @param startPath the path where the start directory is located\n * @throws IOException if an issue occurs on file access for the normalizing of the line endings.\n */\n public void normalizeLineEndingsDirectory(String startPath) throws IOException {\n log.debug(\"Normalizing file endings in directory {}\", startPath);\n File directory = new File(startPath);\n if (!directory.exists() || !directory.isDirectory()) {\n throw new RuntimeException(\"File endings in directory \" + startPath + \" should be normalized but the directory does not exist.\");\n }\n\n // Ignore the .git repository\n IOFileFilter directoryFileFilter = FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(\".git\"));\n // Get all files in directory\n Collection<File> files = FileUtils.listFiles(directory, FileFilterUtils.trueFileFilter(), directoryFileFilter);\n\n for (File file : files) {\n normalizeLineEndings(file.getAbsolutePath());\n }\n }\n\n /**\n * This normalizes all line endings to UNIX-line-endings in a specific file.\n * '\\r\\n' gets replaced to '\\n'\n * '\\r' gets replaced to '\\n'\n *\n * @param filePath the path where the file is located\n * @throws IOException if an issue occurs on file access for the normalizing of the line endings.\n */\n public void normalizeLineEndings(String filePath) throws IOException {\n log.debug(\"Normalizing line endings in file {}\", filePath);\n // https://stackoverflow.com/questions/3776923/how-can-i-normalize-the-eol-character-in-java\n Path replaceFilePath = Paths.get(filePath);\n Charset charset = StandardCharsets.UTF_8;\n\n String fileContent = Files.readString(replaceFilePath, charset);\n fileContent = fileContent.replaceAll(\"\\\\r\\\\n?\", \"\\n\");\n Files.writeString(replaceFilePath, fileContent, charset);\n }\n\n /**\n * This converts all files to the UTF-8 encoding recursively from the startPath.\n * <p>\n * {@link #convertToUTF8(String) convertToUTF8}\n *\n * @param startPath the path where the start directory is located\n * @throws IOException if an issue occurs on file access when converting to UTF-8.\n */\n public void convertToUTF8Directory(String startPath) throws IOException {\n log.debug(\"Converting files in directory {} to UTF-8\", startPath);\n File directory = new File(startPath);\n if (!directory.exists() || !directory.isDirectory()) {\n throw new RuntimeException(\"Files in directory \" + startPath + \" should be converted to UTF-8 but the directory does not exist.\");\n }\n\n // Ignore the .git repository\n IOFileFilter directoryFileFilter = FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(\".git\"));\n // Get all files in directory\n Collection<File> files = FileUtils.listFiles(directory, FileFilterUtils.trueFileFilter(), directoryFileFilter);\n\n for (File file : files) {\n convertToUTF8(file.getAbsolutePath());\n }\n }\n\n /**\n * This converts a specific file to the UTF-8 encoding.\n * To determine the encoding of the file, the library com.ibm.icu.text is used.\n *\n * @param filePath the path where the file is located\n * @throws IOException if an issue occurs on file access when converting to UTF-8.\n */\n public void convertToUTF8(String filePath) throws IOException {\n log.debug(\"Converting file {} to UTF-8\", filePath);\n Path replaceFilePath = Paths.get(filePath);\n byte[] contentArray = Files.readAllBytes(replaceFilePath);\n\n Charset charset = detectCharset(contentArray);\n log.debug(\"Detected charset for file {} is {}\", filePath, charset.name());\n\n String fileContent = new String(contentArray, charset);\n\n Files.writeString(replaceFilePath, fileContent, StandardCharsets.UTF_8);\n }\n\n /**\n * Detect the charset of a byte array\n *\n * @param contentArray The content that should be checked\n * @return The detected charset\n */\n public Charset detectCharset(byte[] contentArray) {\n CharsetDetector charsetDetector = new CharsetDetector();\n charsetDetector.setText(contentArray);\n String charsetName = charsetDetector.detect().getName();\n return Charset.forName(charsetName);\n }\n\n /**\n * Schedule the deletion of the given path with a given delay\n *\n * @param path The path that should be deleted\n * @param delayInMinutes The delay in minutes after which the path should be deleted\n */\n public void scheduleForDeletion(Path path, long delayInMinutes) {\n ScheduledFuture<?> future = executor.schedule(() -> {\n try {\n if (Files.exists(path)) {\n log.info(\"Delete file {}\", path);\n Files.delete(path);\n }\n futures.remove(path);\n }\n catch (IOException e) {\n log.error(\"Deleting the file \" + path + \" did not work\", e);\n }\n }, delayInMinutes, TimeUnit.MINUTES);\n\n futures.put(path, future);\n }\n\n /**\n * Schedule the recursive deletion of the given directory with a given delay.\n *\n * @param path The path to the directory that should be deleted\n * @param delayInMinutes The delay in minutes after which the path should be deleted\n */\n public void scheduleForDirectoryDeletion(Path path, long delayInMinutes) {\n ScheduledFuture<?> future = executor.schedule(() -> {\n try {\n if (Files.exists(path) && Files.isDirectory(path)) {\n log.info(\"Delete directory {}\", path);\n FileUtils.deleteDirectory(path.toFile());\n }\n futures.remove(path);\n }\n catch (IOException e) {\n log.error(\"Deleting the directory \" + path + \" did not work\", e);\n }\n }, delayInMinutes, TimeUnit.MINUTES);\n\n futures.put(path, future);\n }\n\n /**\n * create a unique path by appending a folder named with the current milliseconds (e.g. 1609579674868) of the system\n * Note: the method also tries to create the mentioned folder\n *\n * @param path the original path, e.g. /opt/artemis/repos-download\n * @return the unique path as string, e.g. /opt/artemis/repos-download/1609579674868\n */\n public String getUniquePathString(String path) {\n return getUniquePath(path).toString();\n }\n\n /**\n * create a unique path by appending a folder named with the current milliseconds (e.g. 1609579674868) of the system\n * Note: the method also tries to create the mentioned folder\n *\n * @param path the original path, e.g. /opt/artemis/repos-download\n * @return the unique path, e.g. /opt/artemis/repos-download/1609579674868\n */\n public Path getUniquePath(String path) {\n var uniquePath = Paths.get(path, String.valueOf(System.currentTimeMillis()));\n if (!Files.exists(uniquePath) && Files.isDirectory(uniquePath)) {\n try {\n Files.createDirectories(uniquePath);\n }\n catch (IOException e) {\n log.warn(\"could not create the directories for the path {}\", uniquePath);\n }\n }\n return uniquePath;\n }\n}\n" }, { "alpha_fraction": 0.7086614370346069, "alphanum_fraction": 0.7086614370346069, "avg_line_length": 30.75, "blob_id": "c228301dc2ce584c7bee272fadd7c1fa3e8c5360", "content_id": "3c7068ca88c17656d08e9a369e280cbf7b406224", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 254, "license_type": "permissive", "max_line_length": 55, "num_lines": 8, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/unit-creation-card/unit-creation-card.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'jhi-unit-creation-card',\n templateUrl: './unit-creation-card.component.html',\n styleUrls: ['./unit-creation-card.component.scss'],\n})\nexport class UnitCreationCardComponent {}\n" }, { "alpha_fraction": 0.7079669833183289, "alphanum_fraction": 0.7079669833183289, "avg_line_length": 47.11538314819336, "blob_id": "eb3e54c83b0f068fd1cff3b856bfafc5aad5729e", "content_id": "ce5468ac120f3ed4fa8d2ea61dc8732267096535", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3753, "license_type": "permissive", "max_line_length": 155, "num_lines": 78, "path": "/src/main/webapp/app/course/learning-goals/learningGoal.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { map } from 'rxjs/operators';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { CourseLearningGoalProgress } from 'app/course/learning-goals/learning-goal-course-progress.dtos.model';\n\ntype EntityResponseType = HttpResponse<LearningGoal>;\ntype EntityArrayResponseType = HttpResponse<LearningGoal[]>;\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LearningGoalService {\n private resourceURL = SERVER_API_URL + 'api';\n\n constructor(private httpClient: HttpClient, private lectureUnitService: LectureUnitService) {}\n\n getAllForCourse(courseId: number): Observable<EntityArrayResponseType> {\n return this.httpClient.get<LearningGoal[]>(`${this.resourceURL}/courses/${courseId}/goals`, { observe: 'response' });\n }\n\n getProgress(learningGoalId: number, courseId: number, useParticipantScoreTable = false) {\n let params = new HttpParams();\n params = params.set('useParticipantScoreTable', String(useParticipantScoreTable));\n return this.httpClient.get<IndividualLearningGoalProgress>(`${this.resourceURL}/courses/${courseId}/goals/${learningGoalId}/individual-progress`, {\n observe: 'response',\n params,\n });\n }\n\n getCourseProgress(learningGoalId: number, courseId: number, useParticipantScoreTable = false) {\n let params = new HttpParams();\n params = params.set('useParticipantScoreTable', String(useParticipantScoreTable));\n return this.httpClient.get<CourseLearningGoalProgress>(`${this.resourceURL}/courses/${courseId}/goals/${learningGoalId}/course-progress`, {\n observe: 'response',\n params,\n });\n }\n\n findById(learningGoalId: number, courseId: number) {\n return this.httpClient\n .get<LearningGoal>(`${this.resourceURL}/courses/${courseId}/goals/${learningGoalId}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServerResponse(res)));\n }\n\n create(learningGoal: LearningGoal, courseId: number): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(learningGoal);\n return this.httpClient.post<LearningGoal>(`${this.resourceURL}/courses/${courseId}/goals`, copy, { observe: 'response' });\n }\n\n update(learningGoal: LearningGoal, courseId: number): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(learningGoal);\n return this.httpClient.put(`${this.resourceURL}/courses/${courseId}/goals`, copy, { observe: 'response' });\n }\n\n delete(learningGoalId: number, courseId: number) {\n return this.httpClient.delete(`${this.resourceURL}/courses/${courseId}/goals/${learningGoalId}`, { observe: 'response' });\n }\n\n convertDateFromServerResponse(res: EntityResponseType): EntityResponseType {\n if (res.body?.lectureUnits) {\n res.body.lectureUnits = this.lectureUnitService.convertDateArrayFromServerEntity(res.body.lectureUnits);\n }\n return res;\n }\n\n convertDateFromClient(learningGoal: LearningGoal): LearningGoal {\n const copy = Object.assign({}, learningGoal);\n if (copy.lectureUnits) {\n copy.lectureUnits = this.lectureUnitService.convertDateArrayFromClient(copy.lectureUnits);\n }\n return copy;\n }\n}\n" }, { "alpha_fraction": 0.6374269127845764, "alphanum_fraction": 0.6413255333900452, "avg_line_length": 31.0625, "blob_id": "41b84710c0329ac8e4b6e33f2b00a60eda5107b1", "content_id": "36c496f80c1d20b64de0c701fc42ddc7a18a4b8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1026, "license_type": "permissive", "max_line_length": 94, "num_lines": 32, "path": "/src/main/webapp/app/entities/text-block.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { sha1Hex } from 'app/shared/util/crypto.utils';\nimport { TextSubmission } from 'app/entities/text-submission.model';\n\nexport enum TextBlockType {\n AUTOMATIC = 'AUTOMATIC',\n MANUAL = 'MANUAL',\n}\n\nexport class TextBlock {\n id?: string;\n text?: string;\n startIndex?: number;\n endIndex?: number;\n submission?: TextSubmission;\n type?: TextBlockType;\n\n /**\n * Identical with de.tum.in.www1.artemis.domain.TextBlock:computeId\n */\n computeId(): void {\n const submissionId = this.submission ? this.submission.id : 0;\n const idString = `${submissionId};${this.startIndex}-${this.endIndex};${this.text}`;\n this.id = sha1Hex(idString);\n }\n\n setTextFromSubmission(submission?: TextSubmission): void {\n this.submission = submission || this.submission;\n if (this.submission && !(this.startIndex === undefined || this.startIndex === null)) {\n this.text = this.submission.text?.substring(this.startIndex, this.endIndex) || '';\n }\n }\n}\n" }, { "alpha_fraction": 0.822857141494751, "alphanum_fraction": 0.822857141494751, "avg_line_length": 57.33333206176758, "blob_id": "8726ffc4ac843b9b7d4d2ca31651974650c957bf", "content_id": "86e2b342baff4944da90bbac43c72f1830311f15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 700, "license_type": "permissive", "max_line_length": 169, "num_lines": 12, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/participate/exercise-hint-participation.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ExerciseHintStudentComponent, ExerciseHintStudentDialogComponent } from 'app/exercises/shared/exercise-hint/participate/exercise-hint-student-dialog.component';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisMarkdownModule],\n declarations: [ExerciseHintStudentDialogComponent, ExerciseHintStudentComponent],\n entryComponents: [ExerciseHintStudentDialogComponent],\n exports: [ExerciseHintStudentDialogComponent, ExerciseHintStudentComponent],\n})\nexport class ArtemisExerciseHintParticipationModule {}\n" }, { "alpha_fraction": 0.6338480710983276, "alphanum_fraction": 0.6341999769210815, "avg_line_length": 42.13282775878906, "blob_id": "ed137809d05619ece7615e065223586a331dda62", "content_id": "a0aefe5b76aa74011f64789dcfd637d8279f084d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 22731, "license_type": "permissive", "max_line_length": 153, "num_lines": 527, "path": "/src/main/webapp/app/shared/layouts/navbar/navbar.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { Subscription, of, Observable } from 'rxjs';\nimport { tap, map, switchMap, filter } from 'rxjs/operators';\nimport { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\nimport { JhiAlertService, JhiLanguageService } from 'ng-jhipster';\nimport { SessionStorageService } from 'ngx-webstorage';\nimport { User } from 'app/core/user/user.model';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { SERVER_API_URL, VERSION } from 'app/app.constants';\nimport * as moment from 'moment';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { LoginService } from 'app/core/login/login.service';\nimport { Router, NavigationEnd, ActivatedRoute, RouterEvent } from '@angular/router';\nimport { ExamParticipationService } from 'app/exam/participate/exam-participation.service';\nimport { Exam } from 'app/entities/exam.model';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\nimport { LocaleConversionService } from 'app/shared/service/locale-conversion.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { onError } from 'app/shared/util/global.utils';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ApollonDiagramService } from 'app/exercises/quiz/manage/apollon-diagrams/apollon-diagram.service';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\n\n@Component({\n selector: 'jhi-navbar',\n templateUrl: './navbar.component.html',\n styleUrls: ['navbar.scss'],\n})\nexport class NavbarComponent implements OnInit, OnDestroy {\n readonly SERVER_API_URL = SERVER_API_URL;\n\n inProduction: boolean;\n isNavbarCollapsed: boolean;\n isTourAvailable: boolean;\n languages: string[];\n openApiEnabled?: boolean;\n modalRef: NgbModalRef;\n version: string;\n currAccount?: User;\n isRegistrationEnabled = false;\n passwordResetEnabled = false;\n breadcrumbs: Breadcrumb[];\n\n private authStateSubscription: Subscription;\n private routerEventSubscription: Subscription;\n private exam?: Exam;\n private examId?: number;\n private routeExamId = 0;\n private routeCourseId = 0;\n private lastRouteUrlSegment: string;\n\n constructor(\n private loginService: LoginService,\n private languageService: JhiLanguageService,\n private languageHelper: JhiLanguageHelper,\n private localeConversionService: LocaleConversionService,\n private sessionStorage: SessionStorageService,\n private accountService: AccountService,\n private profileService: ProfileService,\n private participationWebsocketService: ParticipationWebsocketService,\n public guidedTourService: GuidedTourService,\n private router: Router,\n private route: ActivatedRoute,\n private examParticipationService: ExamParticipationService,\n private serverDateService: ArtemisServerDateService,\n private jhiAlertService: JhiAlertService,\n private courseManagementService: CourseManagementService,\n private exerciseService: ExerciseService,\n private hintService: ExerciseHintService,\n private apollonDiagramService: ApollonDiagramService,\n private lectureService: LectureService,\n private examService: ExamManagementService,\n ) {\n this.version = VERSION ? VERSION : '';\n this.isNavbarCollapsed = true;\n this.getExamId();\n }\n\n ngOnInit() {\n this.languages = this.languageHelper.getAll();\n\n this.profileService.getProfileInfo().subscribe((profileInfo) => {\n if (profileInfo) {\n this.inProduction = profileInfo.inProduction;\n this.openApiEnabled = profileInfo.openApiEnabled;\n this.isRegistrationEnabled = profileInfo.registrationEnabled || false;\n this.passwordResetEnabled = this.isRegistrationEnabled || profileInfo.saml2?.enablePassword || false;\n }\n });\n\n this.subscribeForGuidedTourAvailability();\n\n // The current user is needed to hide menu items for not logged in users.\n this.authStateSubscription = this.accountService\n .getAuthenticationState()\n .pipe(tap((user: User) => (this.currAccount = user)))\n .subscribe();\n\n this.examParticipationService.currentlyLoadedStudentExam.subscribe((studentExam) => {\n this.exam = studentExam.exam;\n });\n\n this.buildBreadcrumbs(this.router.url);\n this.router.events.pipe(filter((event) => event instanceof NavigationEnd)).subscribe((event: NavigationEnd) => this.buildBreadcrumbs(event.url));\n }\n\n ngOnDestroy(): void {\n if (this.authStateSubscription) {\n this.authStateSubscription.unsubscribe();\n }\n if (this.routerEventSubscription) {\n this.routerEventSubscription.unsubscribe();\n }\n }\n\n breadcrumbTranslation = {\n new: 'global.generic.create',\n create: 'global.generic.create',\n edit: 'global.generic.edit',\n audits: 'audits.title',\n configuration: 'configuration.title',\n feature_toggles: 'featureToggles.title',\n health: 'health.title',\n logs: 'logs.title',\n docs: 'global.menu.admin.apidocs',\n metrics: 'metrics.title',\n user_statistics: 'statistics.title',\n user_management: 'userManagement.home.title',\n system_notification_management: 'artemisApp.systemNotification.systemNotifications',\n upcoming_exams_and_exercises: 'artemisApp.upcomingExamsAndExercises.upcomingExamsAndExercises',\n account: 'global.menu.account.main',\n activate: 'activate.title',\n password: 'global.menu.account.password',\n reset: 'global.menu.account.password',\n register: 'register.title',\n settings: 'global.menu.account.settings',\n course_management: 'global.menu.course',\n exercises: 'artemisApp.course.exercises',\n text_exercises: 'artemisApp.course.exercises',\n programming_exercises: 'artemisApp.course.exercises',\n modeling_exercises: 'artemisApp.course.exercises',\n file_upload_exercises: 'artemisApp.course.exercises',\n quiz_exercises: 'artemisApp.course.exercises',\n participations: 'artemisApp.participation.home.title',\n submissions: 'artemisApp.exercise.submissions',\n complaints: 'artemisApp.complaint.listOfComplaints.title',\n more_feedback_requests: 'artemisApp.moreFeedback.list.title',\n instructor_dashboard: 'entity.action.instructorDashboard',\n assessment_dashboard: 'artemisApp.assessmentDashboard.home.title',\n test_run_exercise_assessment_dashboard: 'artemisApp.exerciseAssessmentDashboard.home.title',\n lti_configuration: 'artemisApp.programmingExercise.home.title',\n teams: 'artemisApp.team.home.title',\n hints: 'artemisApp.exerciseHint.home.title',\n ratings: 'artemisApp.ratingList.pageTitle',\n goal_management: 'artemisApp.learningGoal.manageLearningGoals.title',\n assessment_locks: 'artemisApp.assessment.locks.home.title',\n apollon_diagrams: 'artemisApp.apollonDiagram.home.title',\n questions: 'artemisApp.studentQuestion.overview.title',\n scores: 'entity.action.scores',\n assessment: 'artemisApp.assessment.assessment',\n export: 'artemisApp.quizExercise.export.title',\n re_evaluate: 'entity.action.re-evaluate',\n solution: 'artemisApp.quizExercise.solution',\n preview: 'artemisApp.quizExercise.previewMode',\n quiz_statistic: 'artemisApp.quizExercise.statistics',\n quiz_point_statistic: 'artemisApp.quizExercise.statistics',\n import: 'artemisApp.exercise.import.table.doImport',\n plagiarism: 'artemisApp.plagiarism.plagiarism-detection',\n example_solution: 'artemisApp.modelingExercise.exampleSolution',\n example_submissions: 'artemisApp.exampleSubmission.home.title',\n text_feedback_conflict: 'artemisApp.textAssessment.title',\n grading: 'artemisApp.programmingExercise.configureGrading.shortTitle',\n test: 'artemisApp.editor.home.title',\n ide: 'artemisApp.editor.home.title',\n lectures: 'artemisApp.lecture.home.title',\n attachments: 'artemisApp.lecture.attachments.title',\n unit_management: 'artemisApp.lectureUnit.home.title',\n exams: 'artemisApp.examManagement.title',\n exercise_groups: 'artemisApp.examManagement.exerciseGroups',\n students: 'artemisApp.course.students',\n tutors: 'artemisApp.course.tutors',\n instructors: 'artemisApp.course.instructors',\n test_runs: 'artemisApp.examManagement.testRun.testRun',\n assess: 'artemisApp.examManagement.assessmentDashboard',\n summary: 'artemisApp.exam.summary',\n conduction: 'artemisApp.exam.title',\n student_exams: 'artemisApp.studentExams.title',\n test_assessment_dashboard: 'artemisApp.examManagement.assessmentDashboard',\n tutor_exam_dashboard: 'artemisApp.examManagement.assessmentDashboard',\n organization_management: 'organizationManagement.title',\n course_statistics: 'statistics.course_statistics_title',\n };\n\n /**\n * Fills the breadcrumbs array with entries for admin and course-management routes\n */\n private buildBreadcrumbs(fullURI: string): void {\n this.breadcrumbs = [];\n\n if (!fullURI) {\n return;\n }\n\n // Temporarily restrict routes\n if (!fullURI.startsWith('/admin') && !fullURI.startsWith('/course-management')) {\n return;\n }\n\n // try catch for extra safety measures\n try {\n let currentPath = '/';\n\n // Remove the leading slash\n let uri = fullURI.substring(1);\n\n // Remove any query parameters\n const questionMark = uri.indexOf('?');\n if (questionMark >= 0) {\n uri = uri.substring(0, questionMark);\n }\n\n // Go through all segments of the route starting from the root\n for (const segment of uri.split('/')) {\n currentPath += segment + '/';\n\n // If we parse an entity ID we need to check the previous segment which entity the ID refers to\n if (!isNaN(Number(segment))) {\n this.addBreadcrumbForNumberSegment(currentPath, segment);\n } else {\n this.addBreadcrumbForUrlSegment(currentPath, segment);\n }\n\n this.lastRouteUrlSegment = segment;\n }\n } catch (e) {}\n }\n\n /**\n * Adds a breadcrumb depending on the given entityID as string\n *\n * @param currentPath the complete path up until the breadcrumb to add\n * @param segment the current url segment (string representation of an entityID) to add a crumb for\n */\n private addBreadcrumbForNumberSegment(currentPath: string, segment: string): void {\n switch (this.lastRouteUrlSegment) {\n // Displays the path segment as breadcrumb (no other title exists)\n case 'system-notification-management':\n case 'teams':\n case 'code-editor':\n this.addBreadcrumb(currentPath, segment, false);\n break;\n case 'course-management':\n this.addResolvedTitleAsCrumb(this.courseManagementService.getTitle(Number(segment)), currentPath, segment);\n break;\n case 'exercises':\n case 'text-exercises':\n case 'modeling-exercises':\n case 'file-upload-exercises':\n case 'programming-exercises':\n case 'quiz-exercises':\n this.addResolvedTitleAsCrumb(this.exerciseService.getTitle(Number(segment)), currentPath, segment);\n break;\n case 'hints':\n this.addResolvedTitleAsCrumb(this.hintService.getTitle(Number(segment)), currentPath, segment);\n break;\n case 'apollon-diagrams':\n this.addResolvedTitleAsCrumb(this.apollonDiagramService.getTitle(Number(segment)), currentPath, segment);\n break;\n case 'lectures':\n this.addResolvedTitleAsCrumb(this.lectureService.getTitle(Number(segment)), currentPath, segment);\n break;\n case 'exams':\n this.routeExamId = Number(segment);\n this.addResolvedTitleAsCrumb(this.examService.getTitle(this.routeExamId), currentPath, segment);\n break;\n case 'import':\n // Special case: Don't display the ID here but the name directly (clicking the ID wouldn't work)\n // This has to go in the future\n this.addTranslationAsCrumb(currentPath, 'import');\n break;\n case 'example-submissions':\n // Special case: Don't display the ID here but the name directly (clicking the ID wouldn't work)\n this.addTranslationAsCrumb(currentPath, 'example-submissions');\n break;\n case 'text-feedback-conflict':\n // Special case: Don't display the ID here but the name directly (clicking the ID wouldn't work)\n this.addTranslationAsCrumb(currentPath, 'text-feedback-conflict');\n break;\n // No breadcrumbs for those segments\n case 'goal-management':\n case 'unit-management':\n case 'exercise-groups':\n case 'student-exams':\n case 'test-runs':\n case 'mc-question-statistic':\n case 'dnd-question-statistic':\n case 'sa-question-statistic':\n default:\n break;\n }\n }\n\n /**\n * Adds a breadcrumb for the given url segment\n *\n * @param currentPath the complete path up until the breadcrumb to add\n * @param segment the current url segment to add a (translated) crumb for\n */\n private addBreadcrumbForUrlSegment(currentPath: string, segment: string): void {\n // When we're not dealing with an ID we need to translate the current part\n // The translation might still depend on the previous parts\n switch (segment) {\n // No breadcrumbs for those segments\n case 'reset':\n case 'groups':\n case 'code-editor':\n case 'admin':\n case 'ide':\n case 'example-submissions':\n case 'text-units':\n case 'exercise-units':\n case 'attachment-units':\n case 'video-units':\n case 'text-feedback-conflict':\n case 'grading':\n case 'mc-question-statistic':\n case 'dnd-question-statistic':\n case 'sa-question-statistic':\n break;\n default:\n // Special cases:\n if (this.lastRouteUrlSegment === 'user-management') {\n // - Users display their login name directly as crumb\n this.addBreadcrumb(currentPath, segment, false);\n break;\n } else if (this.lastRouteUrlSegment === 'example-submissions') {\n // - Creating a new example submission should display the text for example submissions\n this.addTranslationAsCrumb(currentPath, 'example-submissions');\n break;\n } else if (this.lastRouteUrlSegment === 'grading') {\n // - Opening a grading tab should only display the text for grading\n this.addTranslationAsCrumb(currentPath, 'grading');\n break;\n } else if (this.lastRouteUrlSegment === 'code-editor' && segment === 'new') {\n // - This route is bogus an needs to be replaced in the future, display no crumb\n break;\n } else if (this.lastRouteUrlSegment === 'programming-exercises' && segment === 'import') {\n // - This route is bogus an needs to be replaced in the future, display no crumb\n break;\n }\n\n this.addTranslationAsCrumb(currentPath, segment);\n break;\n }\n }\n\n /**\n * Appends a breadcrumb to the list of breadcrumbs\n *\n * @param uri the uri/path for the breadcrumb\n * @param label the displayed label for the breadcrumb\n * @param translate if the label should be translated\n */\n private addBreadcrumb(uri: string, label: string, translate: boolean): void {\n this.setBreadcrumb(uri, label, translate, this.breadcrumbs.length);\n }\n\n /**\n * Sets a breadcrumb in the list of breadcrumbs at the given index\n *\n * @param uri the uri/path for the breadcrumb\n * @param label the displayed label for the breadcrumb\n * @param translate if the label should be translated\n * @param index the index of the breadcrumbs array to set the breadcrumb at\n */\n private setBreadcrumb(uri: string, label: string, translate: boolean, index: number): void {\n const crumb = new Breadcrumb();\n crumb.label = label;\n crumb.translate = translate;\n crumb.uri = uri;\n this.breadcrumbs[index] = crumb;\n }\n\n /**\n * Uses the server response to add a title for a breadcrumb\n * While waiting for the response or in case of an error the segment is displayed directly as fallback\n *\n * @param observable the observable returning an entity to display the title of\n * @param uri the uri/path for the breadcrumb\n * @param segment the current url segment to add a breadcrumb for\n */\n private addResolvedTitleAsCrumb(observable: Observable<HttpResponse<string>>, uri: string, segment: string): void {\n // Insert the segment until we fetched a title from the server to insert at the correct index\n const index = this.breadcrumbs.length;\n this.addBreadcrumb(uri, segment, false);\n\n observable.subscribe(\n (response: HttpResponse<string>) => {\n // Fall back to the segment in case there is no body returned\n const title = response.body ?? segment;\n this.setBreadcrumb(uri, title, false, index);\n },\n (error: HttpErrorResponse) => onError(this.jhiAlertService, error, false),\n );\n }\n\n /**\n * Adds a breadcrumb with a translated label\n * If no translation can be found the key is displayed\n *\n * @param uri the uri/path for the breadcrumb\n * @param translationKey the string to index the breadcrumbTranslation table with\n */\n private addTranslationAsCrumb(uri: string, translationKey: string): void {\n const key = translationKey.split('-').join('_');\n if (this.breadcrumbTranslation[key]) {\n this.addBreadcrumb(uri, this.breadcrumbTranslation[key], true);\n } else {\n // If there is no valid entry in the mapping display the raw key instead of a \"not found\"\n this.addBreadcrumb(uri, translationKey, false);\n }\n }\n\n /**\n * Check if a guided tour is available for the current route to display the start tour button in the account menu\n */\n subscribeForGuidedTourAvailability(): void {\n // Check availability after first subscribe call since the router event been triggered already\n this.guidedTourService.getGuidedTourAvailabilityStream().subscribe((isAvailable) => {\n this.isTourAvailable = isAvailable;\n });\n }\n\n changeLanguage(languageKey: string) {\n this.sessionStorage.store('locale', languageKey);\n this.languageService.changeLanguage(languageKey);\n moment.locale(languageKey);\n this.localeConversionService.locale = languageKey;\n }\n\n collapseNavbar() {\n this.isNavbarCollapsed = true;\n }\n\n isAuthenticated() {\n return this.accountService.isAuthenticated();\n }\n\n logout() {\n this.participationWebsocketService.resetLocalCache();\n this.collapseNavbar();\n this.loginService.logout(true);\n }\n\n toggleNavbar() {\n this.isNavbarCollapsed = !this.isNavbarCollapsed;\n }\n\n getImageUrl() {\n return this.accountService.getImageUrl();\n }\n\n /**\n * Determine the label for initiating the guided tour based on the last seen tour step\n */\n guidedTourInitLabel(): string {\n switch (this.guidedTourService.getLastSeenTourStepForInit()) {\n case -1: {\n return 'global.menu.restartTutorial';\n }\n case 0: {\n return 'global.menu.startTutorial';\n }\n default: {\n return 'global.menu.continueTutorial';\n }\n }\n }\n\n /**\n * get exam id from current route\n */\n getExamId() {\n this.routerEventSubscription = this.router.events.pipe(filter((event: RouterEvent) => event instanceof NavigationEnd)).subscribe((event) => {\n const examId = of(event).pipe(\n map(() => this.route.root),\n map((root) => root.firstChild),\n switchMap((firstChild) => {\n if (firstChild) {\n return firstChild?.paramMap.pipe(map((paramMap) => paramMap.get('examId')));\n } else {\n return of(null);\n }\n }),\n );\n examId.subscribe((id) => {\n if (id !== null && !event.url.includes('management')) {\n this.examId = +id;\n } else {\n this.examId = undefined;\n }\n });\n });\n }\n\n /**\n * check if exam mode is active\n */\n examModeActive(): boolean {\n if (this.exam && this.exam.id === this.examId && this.exam.startDate && this.exam.endDate) {\n return this.serverDateService.now().isBetween(this.exam.startDate, this.exam.endDate);\n }\n return false;\n }\n}\n\nclass Breadcrumb {\n label: string;\n uri: string;\n translate: boolean;\n}\n" }, { "alpha_fraction": 0.7394276261329651, "alphanum_fraction": 0.7507699131965637, "avg_line_length": 52.03984069824219, "blob_id": "0c8c4d50ab5a628f8b4141b4e82d99a820b5f6a7", "content_id": "0d63b960a12ae8c7d9fcbb91598d1ab1d4857b32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13313, "license_type": "permissive", "max_line_length": 174, "num_lines": 251, "path": "/src/test/java/de/tum/in/www1/artemis/service/AutomaticFeedbackConflictServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static org.awaitility.Awaitility.await;\nimport static org.hamcrest.MatcherAssert.assertThat;\nimport static org.hamcrest.Matchers.*;\n\nimport java.util.*;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.connector.athene.AtheneRequestMockProvider;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.FeedbackConflictType;\nimport de.tum.in.www1.artemis.domain.enumeration.Language;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.dto.FeedbackConflictResponseDTO;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class AutomaticFeedbackConflictServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private FeedbackConflictRepository feedbackConflictRepository;\n\n @Autowired\n private FeedbackRepository feedbackRepository;\n\n @Autowired\n private TextClusterRepository textClusterRepository;\n\n @Autowired\n private TextSubmissionRepository textSubmissionRepository;\n\n @Autowired\n private ResultRepository resultRepository;\n\n @Autowired\n private AtheneRequestMockProvider atheneRequestMockProvider;\n\n @Autowired\n private AutomaticTextAssessmentConflictService automaticTextAssessmentConflictService;\n\n private TextExercise textExercise;\n\n @BeforeEach\n public void init() {\n database.addUsers(2, 1, 0);\n textExercise = (TextExercise) database.addCourseWithOneFinishedTextExercise().getExercises().iterator().next();\n atheneRequestMockProvider.enableMockingOfRequests();\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n atheneRequestMockProvider.reset();\n }\n\n /**\n * Creates two text submissions with text blocks and feedback, adds text blocks to a cluster.\n * Mocks TextAssessmentConflictService class to not to connect to remote Athene service\n * Then checks if the text assessment conflicts are created and stored correctly.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void createFeedbackConflicts() {\n TextSubmission textSubmission1 = ModelFactory.generateTextSubmission(\"first text submission\", Language.ENGLISH, true);\n TextSubmission textSubmission2 = ModelFactory.generateTextSubmission(\"second text submission\", Language.ENGLISH, true);\n database.saveTextSubmission(textExercise, textSubmission1, \"student1\");\n database.saveTextSubmission(textExercise, textSubmission2, \"student1\");\n\n final TextCluster cluster = new TextCluster().exercise(textExercise);\n textClusterRepository.save(cluster);\n\n final TextBlock textBlock1 = new TextBlock().startIndex(0).endIndex(21).automatic().cluster(cluster);\n final TextBlock textBlock2 = new TextBlock().startIndex(0).endIndex(22).automatic().cluster(cluster);\n\n database.addAndSaveTextBlocksToTextSubmission(Set.of(textBlock1), textSubmission1);\n database.addAndSaveTextBlocksToTextSubmission(Set.of(textBlock2), textSubmission2);\n\n cluster.blocks(List.of(textBlock1, textBlock2));\n textClusterRepository.save(cluster);\n\n Feedback feedback1 = new Feedback().detailText(\"Good answer\").credits(1D).reference(textBlock1.getId());\n Feedback feedback2 = new Feedback().detailText(\"Good answer\").credits(2D).reference(textBlock2.getId());\n\n textSubmission1 = database.addTextSubmissionWithResultAndAssessorAndFeedbacks(textExercise, textSubmission1, \"student1\", \"tutor1\", List.of(feedback1));\n textSubmission2 = database.addTextSubmissionWithResultAndAssessorAndFeedbacks(textExercise, textSubmission2, \"student2\", \"tutor1\", List.of(feedback2));\n\n // important: use the updated feedback that was already saved to the database and not the feedback1 and feedback2 objects\n feedback1 = textSubmission1.getLatestResult().getFeedbacks().get(0);\n feedback2 = textSubmission2.getLatestResult().getFeedbacks().get(0);\n\n atheneRequestMockProvider.mockFeedbackConsistency(createRemoteServiceResponse(feedback1, feedback2));\n automaticTextAssessmentConflictService.asyncCheckFeedbackConsistency(Set.of(textBlock1), new ArrayList<>(Collections.singletonList(feedback1)), textExercise.getId());\n\n await().until(() -> feedbackConflictRepository.count() >= 0);\n\n assertThat(feedbackConflictRepository.findAll(), hasSize(1));\n assertThat(feedbackConflictRepository.findAll().get(0).getFirstFeedback(), either(is(feedback1)).or(is(feedback2)));\n assertThat(feedbackConflictRepository.findAll().get(0).getSecondFeedback(), either(is(feedback1)).or(is(feedback2)));\n }\n\n /**\n * Creates and stores a Text Assessment Conflict in the database.\n * Then sends a conflict with same feedback ids and different conflict type.\n * Checks if the conflict type in the database has changed.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void changedFeedbackConflictsType() {\n TextSubmission textSubmission = ModelFactory.generateTextSubmission(\"text submission\", Language.ENGLISH, true);\n database.saveTextSubmission(textExercise, textSubmission, \"student1\");\n\n final TextCluster cluster = new TextCluster().exercise(textExercise);\n textClusterRepository.save(cluster);\n\n final TextBlock textBlock = new TextBlock().startIndex(0).endIndex(15).automatic().cluster(cluster);\n database.addAndSaveTextBlocksToTextSubmission(Set.of(textBlock), textSubmission);\n\n Feedback feedback1 = new Feedback().detailText(\"Good answer\").credits(1D).reference(textBlock.getId());\n Feedback feedback2 = new Feedback().detailText(\"Bad answer\").credits(2D);\n textSubmission = database.addTextSubmissionWithResultAndAssessorAndFeedbacks(textExercise, textSubmission, \"student1\", \"tutor1\", List.of(feedback1, feedback2));\n\n // important: use the updated feedback that was already saved to the database and not the feedback1 and feedback2 objects\n feedback1 = textSubmission.getLatestResult().getFeedbacks().get(0);\n feedback2 = textSubmission.getLatestResult().getFeedbacks().get(1);\n FeedbackConflict feedbackConflict = ModelFactory.generateFeedbackConflictBetweenFeedbacks(feedback1, feedback2);\n feedbackConflict.setType(FeedbackConflictType.INCONSISTENT_COMMENT);\n feedbackConflictRepository.save(feedbackConflict);\n\n atheneRequestMockProvider.mockFeedbackConsistency(createRemoteServiceResponse(feedback1, feedback2));\n automaticTextAssessmentConflictService.asyncCheckFeedbackConsistency(Set.of(textBlock), new ArrayList<>(Collections.singletonList(feedback1)), textExercise.getId());\n\n await().until(() -> feedbackConflictRepository.count() >= 0);\n\n assertThat(feedbackConflictRepository.findAll(), hasSize(1));\n assertThat(feedbackConflictRepository.findAll().get(0).getFirstFeedback(), is(feedback1));\n assertThat(feedbackConflictRepository.findAll().get(0).getSecondFeedback(), is(feedback2));\n assertThat(feedbackConflictRepository.findAll().get(0).getType(), is(FeedbackConflictType.INCONSISTENT_SCORE));\n }\n\n /**\n * Creates and stores a Text Assessment Conflict in the database.\n * Then a same feedback is sent to the conflict checking class.\n * Empty list is returned from the mock object. (meaning: no conflicts have found)\n * Checks if the conflict set as solved in the database.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void solveFeedbackConflicts() {\n TextSubmission textSubmission = ModelFactory.generateTextSubmission(\"text submission\", Language.ENGLISH, true);\n database.saveTextSubmission(textExercise, textSubmission, \"student1\");\n\n final TextCluster cluster = new TextCluster().exercise(textExercise);\n textClusterRepository.save(cluster);\n\n final TextBlock textBlock = new TextBlock().startIndex(0).endIndex(15).automatic().cluster(cluster);\n database.addAndSaveTextBlocksToTextSubmission(Set.of(textBlock), textSubmission);\n\n Feedback feedback1 = new Feedback().detailText(\"Good answer\").credits(1D).reference(textBlock.getId());\n Feedback feedback2 = new Feedback().detailText(\"Bad answer\").credits(2D);\n textSubmission = database.addTextSubmissionWithResultAndAssessorAndFeedbacks(textExercise, textSubmission, \"student1\", \"tutor1\", List.of(feedback1, feedback2));\n\n // important: use the updated feedback that was already saved to the database and not the feedback1 and feedback2 objects\n feedback1 = textSubmission.getLatestResult().getFeedbacks().get(0);\n feedback2 = textSubmission.getLatestResult().getFeedbacks().get(1);\n FeedbackConflict feedbackConflict = ModelFactory.generateFeedbackConflictBetweenFeedbacks(feedback1, feedback2);\n feedbackConflictRepository.save(feedbackConflict);\n\n atheneRequestMockProvider.mockFeedbackConsistency(List.of());\n automaticTextAssessmentConflictService.asyncCheckFeedbackConsistency(Set.of(textBlock), new ArrayList<>(List.of(feedback1, feedback2)), textExercise.getId());\n\n await().until(() -> feedbackConflictRepository.count() >= 0);\n\n assertThat(feedbackConflictRepository.findAll(), hasSize(1));\n assertThat(feedbackConflictRepository.findAll().get(0).getFirstFeedback(), is(feedback1));\n assertThat(feedbackConflictRepository.findAll().get(0).getSecondFeedback(), is(feedback2));\n assertThat(feedbackConflictRepository.findAll().get(0).getConflict(), is(Boolean.FALSE));\n assertThat(feedbackConflictRepository.findAll().get(0).getSolvedAt(), is(notNullValue()));\n }\n\n /**\n * Checks if deletion of submission delete the text assessment conflicts from the database.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testSubmissionDelete() {\n TextSubmission textSubmission = createTextSubmissionWithResultFeedbackAndConflicts();\n textSubmissionRepository.deleteById(textSubmission.getId());\n assertThat(feedbackConflictRepository.findAll(), hasSize(0));\n }\n\n /**\n * Checks if deletion of a result delete the text assessment conflicts from the database.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testResultDelete() {\n TextSubmission textSubmission = createTextSubmissionWithResultFeedbackAndConflicts();\n resultRepository.deleteById(textSubmission.getLatestResult().getId());\n assertThat(feedbackConflictRepository.findAll(), hasSize(0));\n }\n\n /**\n * Checks if deletion of feedback delete the text assessment conflicts from the database.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testFeedbackDelete() {\n this.createTextSubmissionWithResultFeedbackAndConflicts();\n feedbackRepository.deleteAll();\n assertThat(feedbackConflictRepository.findAll(), hasSize(0));\n }\n\n /**\n * Checks the deletion of text assessment conflicts do not cause deletion of feedback.\n */\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testFeedbackConflictDelete() {\n createTextSubmissionWithResultFeedbackAndConflicts();\n feedbackConflictRepository.deleteAll();\n assertThat(feedbackRepository.findAll(), hasSize(2));\n }\n\n private List<FeedbackConflictResponseDTO> createRemoteServiceResponse(Feedback firstFeedback, Feedback secondFeedback) {\n FeedbackConflictResponseDTO feedbackConflictResponseDTO = new FeedbackConflictResponseDTO();\n feedbackConflictResponseDTO.setFirstFeedbackId(firstFeedback.getId());\n feedbackConflictResponseDTO.setSecondFeedbackId(secondFeedback.getId());\n feedbackConflictResponseDTO.setType(FeedbackConflictType.INCONSISTENT_SCORE);\n return List.of(feedbackConflictResponseDTO);\n }\n\n private TextSubmission createTextSubmissionWithResultFeedbackAndConflicts() {\n TextSubmission textSubmission = ModelFactory.generateTextSubmission(\"text submission\", Language.ENGLISH, true);\n final Feedback feedback1 = new Feedback().detailText(\"Good answer\").credits(1D);\n final Feedback feedback2 = new Feedback().detailText(\"Bad answer\").credits(2D);\n textSubmission = database.addTextSubmissionWithResultAndAssessorAndFeedbacks(textExercise, textSubmission, \"student1\", \"tutor1\", List.of(feedback1, feedback2));\n\n // important: use the updated feedback that was already saved to the database and not the feedback1 and feedback2 objects\n FeedbackConflict feedbackConflict = ModelFactory.generateFeedbackConflictBetweenFeedbacks(textSubmission.getLatestResult().getFeedbacks().get(0),\n textSubmission.getLatestResult().getFeedbacks().get(1));\n feedbackConflictRepository.save(feedbackConflict);\n return textSubmission;\n }\n\n}\n" }, { "alpha_fraction": 0.7092764973640442, "alphanum_fraction": 0.7097203731536865, "avg_line_length": 39.9636344909668, "blob_id": "ac5002dbc8f13cf157c0449518976bd654cdcd48", "content_id": "2d8cb3d6a2f5ca7bf39588fb572eb019b72b4232", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2253, "license_type": "permissive", "max_line_length": 139, "num_lines": 55, "path": "/src/main/webapp/app/assessment/assessment-detail/assessment-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output, AfterViewInit } from '@angular/core';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Feedback, FeedbackType } from 'app/entities/feedback.model';\nimport { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service';\n\n@Component({\n selector: 'jhi-assessment-detail',\n templateUrl: './assessment-detail.component.html',\n styleUrls: ['./assessment-detail.component.scss'],\n})\nexport class AssessmentDetailComponent implements AfterViewInit {\n @Input() public assessment: Feedback;\n @Output() public assessmentChange = new EventEmitter<Feedback>();\n @Output() public deleteAssessment = new EventEmitter<Feedback>();\n @Input() public disabled = false;\n @Input() public readOnly: boolean;\n disableEditScore = false;\n\n public FeedbackType_AUTOMATIC = FeedbackType.AUTOMATIC;\n constructor(private translateService: TranslateService, public structuredGradingCriterionService: StructuredGradingCriterionService) {}\n\n ngAfterViewInit(): void {\n this.computeDisableEditScore();\n }\n\n /**\n * Emits assessment changes to parent component\n */\n public emitChanges(): void {\n if (this.assessment.type === FeedbackType.AUTOMATIC) {\n this.assessment.type = FeedbackType.AUTOMATIC_ADAPTED;\n }\n this.assessmentChange.emit(this.assessment);\n }\n /**\n * Emits the delete of an assessment\n */\n public delete() {\n const text: string = this.translateService.instant('artemisApp.feedback.delete.question', { id: this.assessment.id ?? '' });\n const confirmation = confirm(text);\n if (confirmation) {\n this.deleteAssessment.emit(this.assessment);\n }\n }\n\n updateAssessmentOnDrop(event: Event) {\n this.structuredGradingCriterionService.updateFeedbackWithStructuredGradingInstructionEvent(this.assessment, event);\n this.computeDisableEditScore();\n this.assessmentChange.emit(this.assessment);\n }\n\n private computeDisableEditScore() {\n this.disableEditScore = !!(this.assessment.gradingInstruction && this.assessment.gradingInstruction.usageCount !== 0);\n }\n}\n" }, { "alpha_fraction": 0.6806041598320007, "alphanum_fraction": 0.6806041598320007, "avg_line_length": 45.00847625732422, "blob_id": "f3eefb883d8c50514127cf737ec073a9da171acb", "content_id": "327f898f06ccca9b31ade71da26598d88e188437", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5429, "license_type": "permissive", "max_line_length": 167, "num_lines": 118, "path": "/src/main/webapp/app/shared/notification/system-notification/system-notification.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport * as moment from 'moment';\nimport { map } from 'rxjs/operators';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { Router } from '@angular/router';\nimport { SystemNotification } from 'app/entities/system-notification.model';\n\ntype EntityResponseType = HttpResponse<SystemNotification>;\ntype EntityArrayResponseType = HttpResponse<SystemNotification[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class SystemNotificationService {\n public resourceUrl = SERVER_API_URL + 'api/system-notifications';\n\n constructor(private router: Router, private http: HttpClient) {}\n\n /**\n * Create a notification on the server using a POST request.\n * @param notification The notification to create.\n */\n create(notification: SystemNotification): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(notification);\n return this.http\n .post<SystemNotification>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Update a notification on the server using a PUT request.\n * @param notification The notification to update.\n */\n update(notification: SystemNotification): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(notification);\n return this.http\n .put<SystemNotification>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Find a notification on the server using a GET request.\n * @param id The id of the notification to get.\n */\n find(id: number): Observable<EntityResponseType> {\n return this.http\n .get<SystemNotification>(`${this.resourceUrl}/${id}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n query(req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n return this.http\n .get<SystemNotification[]>(this.resourceUrl, { params: options, observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * Delete a notification on the server using a DELETE request.\n * @param id The id of the notification to delete.\n */\n delete(id: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response' });\n }\n\n /**\n * If the user is not authenticated we do an explicit request for an active system notification. Otherwise get recent system notifications.\n */\n getActiveNotification(): Observable<SystemNotification | null> {\n return this.http\n .get<SystemNotification>(`${this.resourceUrl}/active-notification`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)))\n .pipe(map((res) => res.body));\n }\n\n /**\n * Convert notification dates from client format to ISO format.\n * @param {SystemNotification} notification The notification to format.\n * @return {SystemNotification} A copy of notification with formatted dates.\n */\n protected convertDateFromClient(notification: SystemNotification): SystemNotification {\n const copy: SystemNotification = Object.assign({}, notification, {\n notificationDate:\n notification.notificationDate && moment(notification.notificationDate).isValid() ? moment(notification.notificationDate).toISOString(true) : undefined,\n expireDate: notification.expireDate && moment(notification.expireDate).isValid() ? moment(notification.expireDate).toISOString(true) : undefined,\n });\n return copy;\n }\n\n /**\n * Convert server response dates from server format to ISO format.\n * @param {EntityResponseType} res The server response to format.\n * @return {EntityResponseType} The server response with formatted dates.\n */\n convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.notificationDate = res.body.notificationDate ? moment(res.body.notificationDate) : undefined;\n res.body.expireDate = res.body.expireDate ? moment(res.body.expireDate) : undefined;\n }\n return res;\n }\n\n /**\n * Convert server response dates from server format to ISO format for an array of responses.\n * @param {EntityResponseType} res The array of server responses to format.\n * @return {EntityResponseType} The array of server responses with formatted dates.\n */\n convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((notification: SystemNotification) => {\n notification.notificationDate = notification.notificationDate ? moment(notification.notificationDate) : undefined;\n notification.expireDate = notification.expireDate ? moment(notification.expireDate) : undefined;\n });\n }\n return res;\n }\n}\n" }, { "alpha_fraction": 0.7808057069778442, "alphanum_fraction": 0.7831753492355347, "avg_line_length": 29.14285659790039, "blob_id": "23f244f4a1f04e19fb26a13d2c9b5b0625ed3ca6", "content_id": "623ee2cd90f6b24214566ee4690e2f06991ab932", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 844, "license_type": "permissive", "max_line_length": 106, "num_lines": 28, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/CourseManagementStatisticsDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport java.util.List;\n\nimport de.tum.in.www1.artemis.domain.statistics.CourseStatisticsAverageScore;\n\npublic class CourseManagementStatisticsDTO {\n\n private Double averageScoreOfCourse;\n\n private List<CourseStatisticsAverageScore> averageScoresOfExercises;\n\n public Double getAverageScoreOfCourse() {\n return averageScoreOfCourse;\n }\n\n public void setAverageScoreOfCourse(Double averageScoreOfCourse) {\n this.averageScoreOfCourse = averageScoreOfCourse;\n }\n\n public List<CourseStatisticsAverageScore> getAverageScoresOfExercises() {\n return averageScoresOfExercises;\n }\n\n public void setAverageScoresOfExercises(List<CourseStatisticsAverageScore> averageScoresOfExercises) {\n this.averageScoresOfExercises = averageScoresOfExercises;\n }\n}\n" }, { "alpha_fraction": 0.554246723651886, "alphanum_fraction": 0.554246723651886, "avg_line_length": 34.844444274902344, "blob_id": "0d145b0c5dcf44ca3d8c14014aea5ed23978b2dc", "content_id": "9effbd681110a89db74bfb1952ee193ca71b2962", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3226, "license_type": "permissive", "max_line_length": 103, "num_lines": 90, "path": "/src/main/webapp/app/overview/courses-routing.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { RouterModule, Routes } from '@angular/router';\nimport { CoursesComponent } from 'app/overview/courses.component';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { CourseOverviewComponent } from 'app/overview/course-overview.component';\nimport { CourseExercisesComponent } from 'app/overview/course-exercises/course-exercises.component';\nimport { CourseLecturesComponent } from 'app/overview/course-lectures/course-lectures.component';\nimport { CourseExamsComponent } from 'app/overview/course-exams/course-exams.component';\nimport { CourseStatisticsComponent } from 'app/overview/course-statistics/course-statistics.component';\nimport { TeamComponent } from 'app/exercises/shared/team/team.component';\nimport { NgModule } from '@angular/core';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\nconst routes: Routes = [\n {\n path: 'courses',\n component: CoursesComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'courses/:courseId',\n component: CourseOverviewComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.course',\n },\n canActivate: [UserRouteAccessService],\n children: [\n {\n path: 'exercises',\n component: CourseExercisesComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.course',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'lectures',\n component: CourseLecturesComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.lectures',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'statistics',\n component: CourseStatisticsComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.statistics',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'exams',\n component: CourseExamsComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'overview.exams',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: '',\n redirectTo: 'exercises',\n pathMatch: 'full',\n },\n ],\n },\n {\n path: 'courses/:courseId/exercises/:exerciseId/teams/:teamId',\n component: TeamComponent,\n data: {\n authorities: [Authority.USER],\n pageTitle: 'artemisApp.team.detail.title',\n },\n canActivate: [UserRouteAccessService],\n },\n];\n\n@NgModule({\n imports: [RouterModule.forChild(routes)],\n exports: [RouterModule],\n})\nexport class ArtemisCoursesRoutingModule {}\n" }, { "alpha_fraction": 0.5977805852890015, "alphanum_fraction": 0.6059668660163879, "avg_line_length": 44.80833435058594, "blob_id": "8c9752e16a60492cc9ac30ca2dbbdcaef7eeb217", "content_id": "56265d6698fb28031aeab1a57221891be06e14cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5497, "license_type": "permissive", "max_line_length": 161, "num_lines": 120, "path": "/src/main/webapp/app/exercises/programming/manage/grading/charts/test-case-distribution-chart.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';\nimport { ProgrammingExerciseTestCase, Visibility } from 'app/entities/programming-exercise-test-case.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { TestCaseStatsMap } from 'app/entities/programming-exercise-test-case-statistics.model';\nimport { HorizontalStackedBarChartPreset } from 'app/shared/chart/presets/horizontalStackedBarChartPreset';\nimport { ChartDataSets } from 'chart.js';\n\n@Component({\n selector: 'jhi-test-case-distribution-chart',\n template: `\n <div>\n <div>\n <h4>{{ 'artemisApp.programmingExercise.configureGrading.charts.testCaseWeights.title' | translate }}</h4>\n <p [innerHTML]=\"'artemisApp.programmingExercise.configureGrading.charts.testCaseWeights.description' | translate\"></p>\n </div>\n <div class=\"bg-light\">\n <jhi-chart [preset]=\"weightChartPreset\" [datasets]=\"weightChartDatasets\"></jhi-chart>\n </div>\n <div class=\"mt-4\">\n <h4>{{ 'artemisApp.programmingExercise.configureGrading.charts.testCasePoints.title' | translate }}</h4>\n <p [innerHTML]=\"'artemisApp.programmingExercise.configureGrading.charts.testCasePoints.description' | translate\"></p>\n </div>\n <div class=\"bg-light\" style=\"height: 100px\">\n <jhi-chart [preset]=\"pointsChartPreset\" [datasets]=\"pointsChartDatasets\"></jhi-chart>\n </div>\n </div>\n `,\n})\nexport class TestCaseDistributionChartComponent implements OnChanges {\n @Input() testCases: ProgrammingExerciseTestCase[];\n @Input() testCaseStatsMap?: TestCaseStatsMap;\n @Input() totalParticipations?: number;\n @Input() exercise: ProgrammingExercise;\n\n @Output() testCaseColorsChange = new EventEmitter<{}>();\n\n weightChartPreset = new HorizontalStackedBarChartPreset(['Weight', 'Weight & Bonus'], ['all weights', 'all weights and bonuses']);\n pointsChartPreset = new HorizontalStackedBarChartPreset(['Points'], ['all exercise points']);\n\n weightChartDatasets: ChartDataSets[] = [];\n pointsChartDatasets: ChartDataSets[] = [];\n\n ngOnChanges(): void {\n this.testCases = this.testCases.filter((testCase) => testCase.visibility !== Visibility.Never);\n\n // sum of all weights\n const totalWeight = this.testCases.reduce((sum, testCase) => sum + testCase.weight!, 0);\n // max points for the exercise\n const maxPoints = this.exercise.maxPoints!;\n // exercise max score with bonus in percent\n const maxScoreInPercent = (maxPoints + (this.exercise.bonusPoints || 0)) / maxPoints;\n\n // total of achievable points for this exercise\n const totalPoints = maxPoints * (this.totalParticipations || 0);\n\n const testCaseScores = this.testCases.map((testCase) => {\n // calculated score for this test case\n const testCaseScore = (totalWeight > 0 ? (testCase.weight! * testCase.bonusMultiplier!) / totalWeight : 0) + (testCase.bonusPoints || 0) / maxPoints;\n\n const score = Math.min(testCaseScore, maxScoreInPercent);\n const stats = this.testCaseStatsMap ? this.testCaseStatsMap[testCase.testName!] : undefined;\n\n return {\n label: testCase.testName!,\n // relative weight percentage\n relWeight: totalWeight > 0 ? (testCase.weight! / totalWeight) * 100 : 0,\n // relative score percentage\n relScore: score * 100,\n // relative points percentage\n relPoints: stats && totalPoints > 0 ? ((stats.numPassed! * score * maxPoints) / totalPoints) * 100 : 0,\n };\n });\n\n if (this.weightChartDatasets.length !== testCaseScores.length) {\n const testCaseColors = {};\n\n this.weightChartDatasets = [];\n this.pointsChartDatasets = [];\n\n for (let i = 0; i < testCaseScores.length; i++) {\n const element = testCaseScores[i];\n\n const label = element.label;\n const backgroundColor = this.getColor(+i / this.testCases.length, 50);\n const hoverBackgroundColor = this.getColor(+i / this.testCases.length, 60);\n\n testCaseColors[label] = backgroundColor;\n\n this.weightChartDatasets.push({\n label,\n backgroundColor,\n hoverBackgroundColor,\n data: [element.relWeight, element.relScore],\n });\n\n this.pointsChartDatasets.push({\n label,\n backgroundColor,\n hoverBackgroundColor,\n data: [element.relPoints],\n });\n }\n\n // update colors for test case table\n this.testCaseColorsChange.emit(testCaseColors);\n } else {\n // update values in-place\n for (let i = 0; i < testCaseScores.length; i++) {\n const element = testCaseScores[i];\n this.weightChartDatasets[i].data![0] = element.relWeight;\n this.weightChartDatasets[i].data![1] = element.relScore;\n this.pointsChartDatasets[i].data![0] = element.relPoints;\n }\n }\n }\n\n getColor(i: number, l: number): string {\n return `hsl(${(i * 360 * 3) % 360}, 55%, ${l}%)`;\n }\n}\n" }, { "alpha_fraction": 0.8190128207206726, "alphanum_fraction": 0.8190128207206726, "avg_line_length": 35.46666717529297, "blob_id": "de06d1467d646ccee45c6afd874d5d08383d5763", "content_id": "642bedf69a673be49205f0785ab6547909a200ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 547, "license_type": "permissive", "max_line_length": 67, "num_lines": 15, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-individual-progress-dtos.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class IndividualLearningGoalProgress {\n public studentId: number;\n public learningGoalId: number;\n public learningGoalTitle: string;\n public pointsAchievedByStudentInLearningGoal: number;\n public totalPointsAchievableByStudentsInLearningGoal: number;\n\n public progressInLectureUnits: IndividualLectureUnitProgress[];\n}\n\nexport class IndividualLectureUnitProgress {\n public lectureUnitId: number;\n public scoreAchievedByStudentInLectureUnit: number;\n public totalPointsAchievableByStudentsInLectureUnit: number;\n}\n" }, { "alpha_fraction": 0.666265070438385, "alphanum_fraction": 0.6670683026313782, "avg_line_length": 42.68421173095703, "blob_id": "9abccc2638c8812e8394b7a4c15193b2572a342c", "content_id": "761d9508d547d41d35743ebda4fa1fdf9ad761e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2490, "license_type": "permissive", "max_line_length": 156, "num_lines": 57, "path": "/src/main/webapp/app/exam/manage/exam-participant-scores/exam-participant-scores.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpErrorResponse } from '@angular/common/http';\nimport { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { ParticipantScoreAverageDTO, ParticipantScoreDTO, ParticipantScoresService } from 'app/shared/participant-scores/participant-scores.service';\nimport { onError } from 'app/shared/util/global.utils';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { finalize } from 'rxjs/operators';\nimport { forkJoin } from 'rxjs';\n\n@Component({\n selector: 'jhi-exam-participant-scores',\n templateUrl: './exam-participant-scores.component.html',\n})\nexport class ExamParticipantScoresComponent implements OnInit {\n examId: number;\n isLoading: boolean;\n participantScores: ParticipantScoreDTO[] = [];\n participantScoresAverage: ParticipantScoreAverageDTO[] = [];\n avgScore = 0;\n avgRatedScore = 0;\n\n constructor(private participantScoreService: ParticipantScoresService, private activatedRoute: ActivatedRoute, private alertService: JhiAlertService) {}\n\n ngOnInit(): void {\n this.activatedRoute.params.subscribe((params) => {\n this.examId = +params['examId'];\n if (this.examId) {\n this.loadData();\n }\n });\n }\n\n loadData() {\n this.isLoading = true;\n\n const scoresObservable = this.participantScoreService.findAllOfExam(this.examId);\n const scoresAverageObservable = this.participantScoreService.findAverageOfExamPerParticipant(this.examId);\n const avgScoreObservable = this.participantScoreService.findAverageOfExam(this.examId, false);\n const avgRatedScoreObservable = this.participantScoreService.findAverageOfExam(this.examId, true);\n\n forkJoin([scoresObservable, scoresAverageObservable, avgScoreObservable, avgRatedScoreObservable])\n .pipe(\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n ([scoresResult, scoresAverageResult, avgScoreResult, avgRatedScoreResult]) => {\n this.participantScoresAverage = scoresAverageResult.body!;\n this.participantScores = scoresResult.body!;\n this.avgScore = avgScoreResult.body!;\n this.avgRatedScore = avgRatedScoreResult.body!;\n },\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n}\n" }, { "alpha_fraction": 0.6797671318054199, "alphanum_fraction": 0.7236171960830688, "avg_line_length": 46.379310607910156, "blob_id": "f60abacc5b5e1b07d291860a4997914258a8eaa9", "content_id": "511067e7736942956c12242b32ce8bac51aa1a4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5496, "license_type": "permissive", "max_line_length": 265, "num_lines": 116, "path": "/src/test/java/de/tum/in/www1/artemis/LtiIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.junit.jupiter.api.Assertions.assertTrue;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.*;\n\nimport java.net.URI;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpHeaders;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.security.test.context.support.WithAnonymousUser;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.exception.ArtemisAuthenticationException;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.web.rest.dto.ExerciseLtiConfigurationDTO;\n\npublic class LtiIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n private ProgrammingExercise programmingExercise;\n\n private final String requestBody = \"\"\"\n custom_component_display_name=Exercise\\\n &lti_version=LTI-1p0\\\n &oauth_nonce=171298047571430710991572204884\\\n &resource_link_id=courses.edx.org-16a90aca094448ab95caf484b5c35d32\\\n &context_id=course-v1%3ATUMx%2BSEECx%2B1T2018\\\n &oauth_signature_method=HMAC-SHA1\\\n &oauth_timestamp=1572204884\\\n &custom_require_existing_user=false\\\n &lis_person_contact_email_primary=anh.montag%40tum.de\\\n &oauth_signature=GYXApaIv0x7k%2FOPT9%2FoU38IBQRc%3D\\\n &context_title=Software+Engineering+Essentials\\\n &lti_message_type=basic-lti-launch-request\\\n &custom_lookup_user_by_email=false\\\n &launch_presentation_return_url=\\\n &context_label=TUMx\\\n &user_id=ff30145d6884eeb2c1cef50298939383\\\n &roles=Student\\\n &oauth_version=1.0\\\n &oauth_consumer_key=artemis_lti_key\\\n &lis_result_sourcedid=course-v1%253ATUMx%252BSEECx%252B1T2018%3Acourses.edx.org-16a90aca094448ab95caf484b5c35d32%3Aff30145d6884eeb2c1cef50298939383\\\n &launch_presentation_locale=en\\\n &lis_outcome_service_url=https%3A%2F%2Fcourses.edx.org%2Fcourses%2Fcourse-v1%3ATUMx%2BSEECx%2B1T2018%2Fxblock%2Fblock-v1%3ATUMx%2BSEECx%2B1T2018%2Btype%40lti_consumer%2Bblock%4016a90aca094448ab95caf484b5c35d32%2Fhandler_noauth%2Foutcome_service_handler\\\n &lis_person_sourcedid=lovaiible\\\n &oauth_callback=about%3Ablank\"\"\";\n\n @BeforeEach\n void init() {\n /* We mock the following methods because we don't have the OAuth secret for edx */\n doReturn(null).when(ltiService).verifyRequest(any());\n doNothing().when(ltiService).handleLaunchRequest(any(), any());\n\n database.addUsers(1, 1, 1);\n\n database.addCourseWithOneProgrammingExercise();\n programmingExercise = programmingExerciseRepository.findAll().get(0);\n }\n\n @AfterEach\n void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithAnonymousUser\n void launchAsAnonymousUser() throws Exception {\n Long exerciseId = programmingExercise.getId();\n Long courseId = programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId();\n URI header = request.post(\"/api/lti/launch/\" + exerciseId, requestBody, HttpStatus.FOUND, MediaType.APPLICATION_FORM_URLENCODED, false);\n\n assertTrue(header.toString().contains(\"?login&jwt=\"));\n assertTrue(header.toString().contains(\"/courses/\" + courseId + \"/exercises/\" + exerciseId));\n\n this.checkExceptions();\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n void launchAsNewStudent() throws Exception {\n Long exerciseId = programmingExercise.getId();\n Long courseId = programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId();\n URI header = request.post(\"/api/lti/launch/\" + exerciseId, requestBody, HttpStatus.FOUND, MediaType.APPLICATION_FORM_URLENCODED, false);\n\n assertTrue(header.toString().contains(\"?welcome&jwt=\"));\n assertTrue(header.toString().contains(\"/courses/\" + courseId + \"/exercises/\" + exerciseId));\n\n this.checkExceptions();\n }\n\n private void checkExceptions() throws Exception {\n request.postWithoutLocation(\"/api/lti/launch/\" + programmingExercise.getId() + 1, requestBody, HttpStatus.NOT_FOUND, new HttpHeaders());\n\n doThrow(ArtemisAuthenticationException.class).when(ltiService).handleLaunchRequest(any(), any());\n request.postWithoutLocation(\"/api/lti/launch/\" + programmingExercise.getId(), requestBody, HttpStatus.INTERNAL_SERVER_ERROR, new HttpHeaders());\n\n doReturn(\"error\").when(ltiService).verifyRequest(any());\n request.postWithoutLocation(\"/api/lti/launch/\" + programmingExercise.getId(), requestBody, HttpStatus.UNAUTHORIZED, new HttpHeaders());\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"TA\")\n void exerciseLtiConfiguration() throws Exception {\n request.get(\"/api/lti/configuration/\" + programmingExercise.getId(), HttpStatus.OK, ExerciseLtiConfigurationDTO.class);\n request.get(\"/api/lti/configuration/1234254354\", HttpStatus.NOT_FOUND, ExerciseLtiConfigurationDTO.class);\n }\n}\n" }, { "alpha_fraction": 0.6457252502441406, "alphanum_fraction": 0.6486071348190308, "avg_line_length": 35.654930114746094, "blob_id": "d9854c5c8449f23fd0dbb64cfacd9de5a8e1eecf", "content_id": "4017dc6c94b8bdc92d797452ed3003b96cef832c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5205, "license_type": "permissive", "max_line_length": 146, "num_lines": 142, "path": "/src/main/webapp/app/exercises/shared/plagiarism/plagiarism-split-view/plagiarism-split-view.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, Directive, ElementRef, Input, OnChanges, OnInit, QueryList, SimpleChanges, ViewChildren } from '@angular/core';\n// @ts-ignore\nimport Split from 'split.js';\nimport { Subject } from 'rxjs';\nimport { PlagiarismComparison } from 'app/exercises/shared/plagiarism/types/PlagiarismComparison';\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\nimport { ModelingSubmissionElement } from 'app/exercises/shared/plagiarism/types/modeling/ModelingSubmissionElement';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { PlagiarismSubmission } from 'app/exercises/shared/plagiarism/types/PlagiarismSubmission';\n\n@Directive({ selector: '[jhiPane]' })\nexport class SplitPaneDirective {\n constructor(public el: ElementRef) {}\n}\n\n@Component({\n selector: 'jhi-plagiarism-split-view',\n styleUrls: ['./plagiarism-split-view.component.scss'],\n templateUrl: './plagiarism-split-view.component.html',\n})\nexport class PlagiarismSplitViewComponent implements AfterViewInit, OnChanges, OnInit {\n @Input() comparison: PlagiarismComparison<TextSubmissionElement | ModelingSubmissionElement>;\n @Input() exercise: Exercise;\n @Input() splitControlSubject: Subject<string>;\n\n @ViewChildren(SplitPaneDirective) panes!: QueryList<SplitPaneDirective>;\n\n public split: Split.Instance;\n\n public isModelingExercise: boolean;\n public isProgrammingOrTextExercise: boolean;\n\n public matchesA: Map<string, { from: TextSubmissionElement; to: TextSubmissionElement }[]>;\n public matchesB: Map<string, { from: TextSubmissionElement; to: TextSubmissionElement }[]>;\n\n /**\n * Initialize third party libs inside this lifecycle hook.\n */\n ngAfterViewInit(): void {\n const paneElements = this.panes.map((pane: SplitPaneDirective) => pane.el.nativeElement);\n\n this.split = Split(paneElements, {\n minSize: 100,\n sizes: [50, 50],\n gutterSize: 8,\n });\n }\n\n ngOnInit(): void {\n this.splitControlSubject.subscribe((pane: string) => this.handleSplitControl(pane));\n }\n\n ngOnChanges(changes: SimpleChanges) {\n if (changes.exercise) {\n const exercise = changes.exercise.currentValue;\n\n this.isModelingExercise = exercise.type === ExerciseType.MODELING;\n this.isProgrammingOrTextExercise = exercise.type === ExerciseType.PROGRAMMING || exercise.type === ExerciseType.TEXT;\n }\n\n if (changes.comparison && this.isProgrammingOrTextExercise) {\n this.parseTextMatches(changes.comparison.currentValue as PlagiarismComparison<TextSubmissionElement>);\n }\n }\n\n parseTextMatches({ submissionA, submissionB, matches }: PlagiarismComparison<TextSubmissionElement>) {\n const matchesA = matches\n .map((match) => ({\n start: match.startA,\n length: match.length,\n }))\n .sort((a, b) => a.start - b.start);\n\n const matchesB = matches\n .map((match) => ({\n start: match.startB,\n length: match.length,\n }))\n .sort((a, b) => a.start - b.start);\n\n this.matchesA = this.mapMatchesToElements(matchesA, submissionA);\n this.matchesB = this.mapMatchesToElements(matchesB, submissionB);\n }\n\n /**\n * Create a map of file names to matches elements.\n * @param matches list of objects containing the index and length of matched elements\n * @param submission the submission to map the elements of\n */\n mapMatchesToElements(matches: { start: number; length: number }[], submission: PlagiarismSubmission<TextSubmissionElement>) {\n const filesToMatchedElements = new Map();\n\n matches.forEach(({ start, length }) => {\n const file = submission.elements[start].file || 'none';\n\n if (!filesToMatchedElements.has(file)) {\n filesToMatchedElements.set(file, []);\n }\n\n const fileMatches = filesToMatchedElements.get(file)!;\n\n fileMatches.push({\n from: submission.elements[start],\n to: submission.elements[start + length - 1],\n });\n });\n\n return filesToMatchedElements;\n }\n\n getModelingSubmissionA() {\n return this.comparison.submissionA as PlagiarismSubmission<ModelingSubmissionElement>;\n }\n\n getModelingSubmissionB() {\n return this.comparison.submissionB as PlagiarismSubmission<ModelingSubmissionElement>;\n }\n\n getTextSubmissionA() {\n return this.comparison.submissionA as PlagiarismSubmission<TextSubmissionElement>;\n }\n\n getTextSubmissionB() {\n return this.comparison.submissionB as PlagiarismSubmission<TextSubmissionElement>;\n }\n\n handleSplitControl(pane: string) {\n switch (pane) {\n case 'left': {\n this.split.collapse(1);\n return;\n }\n case 'right': {\n this.split.collapse(0);\n return;\n }\n case 'even': {\n this.split.setSizes([50, 50]);\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7025697231292725, "alphanum_fraction": 0.7025697231292725, "avg_line_length": 40.568180084228516, "blob_id": "52652d7033cf3d23cdd1a3163a6b439349435e22", "content_id": "58d01c928096abc142620b63598ff7afef5cbbe0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1829, "license_type": "permissive", "max_line_length": 161, "num_lines": 44, "path": "/src/main/webapp/app/exercises/programming/shared/actions/programming-exercise-instructor-repo-download.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { ButtonSize, ButtonType } from 'app/shared/components/button.component';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { ProgrammingExerciseInstructorRepositoryType, ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { downloadZipFileFromResponse } from 'app/shared/util/download.util';\nimport { JhiAlertService } from 'ng-jhipster';\n\n@Component({\n selector: 'jhi-programming-exercise-instructor-repo-download',\n template: `\n <jhi-button\n [disabled]=\"!exerciseId\"\n [btnType]=\"ButtonType.INFO\"\n [btnSize]=\"ButtonSize.SMALL\"\n [shouldSubmit]=\"false\"\n [featureToggle]=\"FeatureToggle.PROGRAMMING_EXERCISES\"\n [icon]=\"'download'\"\n [title]=\"'artemisApp.programmingExercise.export.downloadRepo'\"\n (onClick)=\"exportRepository()\"\n ></jhi-button>\n `,\n})\nexport class ProgrammingExerciseInstructorRepoDownloadComponent {\n ButtonType = ButtonType;\n ButtonSize = ButtonSize;\n readonly FeatureToggle = FeatureToggle;\n\n @Input()\n exerciseId: number;\n\n @Input()\n repositoryType: ProgrammingExerciseInstructorRepositoryType;\n\n constructor(private programmingExerciseService: ProgrammingExerciseService, private alertService: JhiAlertService) {}\n\n exportRepository() {\n if (this.exerciseId && this.repositoryType) {\n this.programmingExerciseService.exportInstructorRepository(this.exerciseId, this.repositoryType).subscribe((response) => {\n downloadZipFileFromResponse(response);\n this.alertService.success('artemisApp.programmingExercise.export.successMessage');\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.7830374836921692, "alphanum_fraction": 0.7830374836921692, "avg_line_length": 45.09090805053711, "blob_id": "11cf2f9a1b673256e4b698b4ccca10df389d1068", "content_id": "c547492f77cf46d19165fea70ad3bd995ae75e61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 507, "license_type": "permissive", "max_line_length": 105, "num_lines": 11, "path": "/src/main/webapp/app/course/course-scores/course-scores.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MomentModule } from 'ngx-moment';\nimport { CourseScoresComponent } from './course-scores.component';\nimport { ArtemisCourseScoresRoutingModule } from 'app/course/course-scores/course-scores-routing.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, MomentModule, ArtemisCourseScoresRoutingModule],\n declarations: [CourseScoresComponent],\n})\nexport class ArtemisCourseScoresModule {}\n" }, { "alpha_fraction": 0.6321974396705627, "alphanum_fraction": 0.6509988307952881, "avg_line_length": 25.59375, "blob_id": "19e75f07785dcb6e0a6a394948d0641e207fff88", "content_id": "d2347a46bb88a1ca73581d3c0bff2ceb78ab57b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 851, "license_type": "permissive", "max_line_length": 64, "num_lines": 32, "path": "/src/main/webapp/app/shared/breakpoints/breakpoints.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\n\nexport const CustomBreakpointNames = {\n extraSmall: 'extraSmall',\n small: 'small',\n medium: 'medium',\n large: 'large',\n extraLarge: 'extraLarge',\n};\n\n@Injectable({\n providedIn: 'root',\n})\nexport class BreakpointsService {\n breakpoints: object = {\n '(max-width: 576px)': CustomBreakpointNames.extraSmall,\n '(min-width: 576px)': CustomBreakpointNames.small,\n '(min-width: 768px)': CustomBreakpointNames.medium,\n '(min-width: 992px)': CustomBreakpointNames.large,\n '(min-width: 1200px)': CustomBreakpointNames.extraLarge,\n };\n\n constructor() {}\n\n getBreakpoints(): string[] {\n return Object.keys(this.breakpoints);\n }\n\n getBreakpointName(breakpointValue: string): string {\n return this.breakpoints[breakpointValue];\n }\n}\n" }, { "alpha_fraction": 0.8020618557929993, "alphanum_fraction": 0.8020618557929993, "avg_line_length": 47.5, "blob_id": "7d973feb34460eecd0341c1c67c75676dbb4a476", "content_id": "aa99cc85d0b0ba0674c3848b1d274193ff500eea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 485, "license_type": "permissive", "max_line_length": 105, "num_lines": 10, "path": "/src/main/webapp/app/exam/manage/exam-participant-scores/exam-participant-scores.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisParticipantScoresModule } from 'app/shared/participant-scores/participant-scores.module';\nimport { ExamParticipantScoresComponent } from './exam-participant-scores.component';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisParticipantScoresModule],\n declarations: [ExamParticipantScoresComponent],\n})\nexport class ArtemisExamParticipantScoresModule {}\n" }, { "alpha_fraction": 0.6339590549468994, "alphanum_fraction": 0.6390784978866577, "avg_line_length": 44.07692337036133, "blob_id": "62bdea3a2bf0c9ef3dc7cf5e2cb960e4ff7ee38d", "content_id": "441fa7de930d43d3c2c4f3210405423b5f33435f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1172, "license_type": "permissive", "max_line_length": 172, "num_lines": 26, "path": "/src/main/webapp/app/exam/manage/student-exams/student-exam-status.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\n\n/**\n * Status indicator for student exams\n * Number of student exams should match the number of registered users\n */\n@Component({\n selector: 'jhi-student-exam-status',\n template: `\n <div class=\"d-flex justify-content-end mt-2 mb-3\">\n <div *ngIf=\"hasStudentsWithoutExam; else allStudentsHaveExams\" class=\"d-flex badge badge-warning\">\n <fa-icon class=\"ml-2 text-white\" icon=\"exclamation-triangle\" [ngbTooltip]=\"'artemisApp.studentExams.studentExamStatusWarningTooltip' | translate\"></fa-icon>\n <span class=\"ml-1\" jhiTranslate=\"artemisApp.studentExams.studentExamStatusWarning\"></span>\n </div>\n <ng-template #allStudentsHaveExams>\n <div class=\"d-flex badge badge-success\">\n <fa-icon class=\"ml-2 text-white\" icon=\"check-circle\"></fa-icon>\n <span class=\"ml-1\" jhiTranslate=\"artemisApp.studentExams.studentExamStatusSuccess\"></span>\n </div>\n </ng-template>\n </div>\n `,\n})\nexport class StudentExamStatusComponent {\n @Input() hasStudentsWithoutExam: boolean;\n}\n" }, { "alpha_fraction": 0.7817567586898804, "alphanum_fraction": 0.7824324369430542, "avg_line_length": 48.33333206176758, "blob_id": "04838954b3c995d61cc18e73272b0b4299a5df1f", "content_id": "5ecd8dcb29cbff0da55363ace1d7f04e94b1c613", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1480, "license_type": "permissive", "max_line_length": 147, "num_lines": 30, "path": "/src/main/webapp/app/exercises/shared/dashboards/instructor/instructor-exercise-dashboard.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\nimport { instructorExerciseDashboardRoute } from './instructor-exercise-dashboard.route';\nimport { InstructorExerciseDashboardComponent } from './instructor-exercise-dashboard.component';\nimport { MomentModule } from 'ngx-moment';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { ChartsModule } from 'ng2-charts';\nimport { ArtemisSidePanelModule } from 'app/shared/side-panel/side-panel.module';\nimport { ArtemisTutorLeaderboardModule } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared/exercise-headers/exercise-headers.module';\nimport { ArtemisInstructorCourseStatsDashboardModule } from 'app/course/dashboards/instructor-course-dashboard/instructor-course-dashboard.module';\n\nconst ENTITY_STATES = instructorExerciseDashboardRoute;\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n MomentModule,\n ClipboardModule,\n RouterModule.forChild(ENTITY_STATES),\n ChartsModule,\n ArtemisInstructorCourseStatsDashboardModule,\n ArtemisHeaderExercisePageWithDetailsModule,\n ArtemisSidePanelModule,\n ArtemisTutorLeaderboardModule,\n ],\n declarations: [InstructorExerciseDashboardComponent],\n})\nexport class ArtemisInstructorExerciseStatsDashboardModule {}\n" }, { "alpha_fraction": 0.6357930898666382, "alphanum_fraction": 0.6383237242698669, "avg_line_length": 45.38028335571289, "blob_id": "90497a0f9c3c7bb566f5336559d4af43cf25e947", "content_id": "d4e3d994b4a64bde8d58bab06f228aabbc52f5e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9879, "license_type": "permissive", "max_line_length": 186, "num_lines": 213, "path": "/src/test/javascript/spec/component/exam/manage/exams/exam-checklist.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport { Component } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute, Data } from '@angular/router';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { Course } from 'app/entities/course.model';\nimport { ExamChecklist } from 'app/entities/exam-checklist.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ExamChecklistCheckComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-check/exam-checklist-check.component';\nimport { ExamChecklistExerciseGroupTableComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-exercisegroup-table/exam-checklist-exercisegroup-table.component';\nimport { ExamChecklistComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist.component';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { ProgressBarComponent } from 'app/shared/dashboards/tutor-participation-graph/progress-bar/progress-bar.component';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({\n template: '',\n})\nclass DummyComponent {}\n\ndescribe('ExamChecklistComponent', () => {\n let examChecklistComponentFixture: ComponentFixture<ExamChecklistComponent>;\n let examDetailComponent: ExamChecklistComponent;\n let findAllForExamStub;\n const exam = new Exam();\n const examChecklist = new ExamChecklist();\n const dueDateStatArray = [{ inTime: 0, late: 0, total: 0 }];\n let exerciseGroupService: ExerciseGroupService;\n\n function getExerciseGroups(equalPoints: boolean) {\n const exerciseGroups = [\n {\n id: 1,\n exercises: [\n { id: 3, maxPoints: 100, numberOfAssessmentsOfCorrectionRounds: dueDateStatArray, studentAssignedTeamIdComputed: false, secondCorrectionEnabled: false },\n { id: 2, maxPoints: 100, numberOfAssessmentsOfCorrectionRounds: dueDateStatArray, studentAssignedTeamIdComputed: false, secondCorrectionEnabled: false },\n ],\n },\n ];\n if (!equalPoints) {\n exerciseGroups[0].exercises[0].maxPoints = 50;\n }\n return exerciseGroups;\n }\n\n const responseExerciseGroup = { body: getExerciseGroups(false) } as HttpResponse<ExerciseGroup[]>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule.withRoutes([\n { path: 'course-management/:courseId/exams/:examId/edit', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/exercise-groups', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/assessment-dashboard', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/scores', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/student-exams', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/test-runs', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/students', component: DummyComponent },\n ]),\n HttpClientTestingModule,\n ],\n declarations: [\n ExamChecklistComponent,\n DummyComponent,\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockComponent(AlertComponent),\n MockComponent(AlertErrorComponent),\n MockDirective(JhiTranslateDirective),\n MockDirective(HasAnyAuthorityDirective),\n ExamChecklistCheckComponent,\n ExamChecklistExerciseGroupTableComponent,\n ProgressBarComponent,\n MockDirective(NgbTooltip),\n MockComponent(FaIconComponent),\n ],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n data: {\n subscribe: (fn: (value: Data) => void) =>\n fn({\n exam,\n }),\n },\n snapshot: {},\n },\n },\n MockProvider(AccountService, {\n isAtLeastInstructorInCourse: () => true,\n }),\n ],\n })\n .compileComponents()\n .then(() => {\n examChecklistComponentFixture = TestBed.createComponent(ExamChecklistComponent);\n examDetailComponent = examChecklistComponentFixture.componentInstance;\n exerciseGroupService = TestBed.inject(ExerciseGroupService);\n findAllForExamStub = stub(exerciseGroupService, 'findAllForExam');\n findAllForExamStub.returns(of(responseExerciseGroup));\n });\n });\n\n beforeEach(() => {\n // reset exam\n exam.id = 1;\n exam.title = 'Example Exam';\n exam.numberOfRegisteredUsers = 3;\n exam.maxPoints = 100;\n exam.course = new Course();\n exam.course.id = 1;\n examDetailComponent.exam = exam;\n\n examChecklist.numberOfGeneratedStudentExams = 1;\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n describe('test checkTotalPointsMandatory', () => {\n beforeEach(() => {\n examDetailComponent.exam.exerciseGroups = getExerciseGroups(true);\n });\n\n it('should set totalPointsMandatory to false', () => {\n examDetailComponent.checkTotalPointsMandatory();\n expect(examDetailComponent.totalPointsMandatory).to.be.equal(false);\n });\n\n it('should set checkTotalPointsMandatory to true', () => {\n examDetailComponent.pointsExercisesEqual = true;\n examDetailComponent.checkTotalPointsMandatory();\n expect(examDetailComponent.totalPointsMandatory).to.be.equal(true);\n });\n\n it('should set totalPointsMandatoryOptional to false', () => {\n examDetailComponent.checkTotalPointsMandatory();\n expect(examDetailComponent.totalPointsMandatoryOptional).to.be.equal(false);\n });\n\n it('should set checkTotalPointsMandatoryOptional to true', () => {\n examDetailComponent.pointsExercisesEqual = true;\n examDetailComponent.checkTotalPointsMandatory();\n expect(examDetailComponent.totalPointsMandatoryOptional).to.be.equal(true);\n });\n });\n\n describe('test checkAllExamsGenerated', () => {\n beforeEach(() => {\n examDetailComponent.examChecklist = examChecklist;\n examDetailComponent.exam.exerciseGroups = getExerciseGroups(true);\n });\n\n it('should set allExamsGenerated to true', () => {\n examChecklist.numberOfGeneratedStudentExams = 3;\n examDetailComponent.checkAllExamsGenerated();\n expect(examDetailComponent.allExamsGenerated).to.be.equal(true);\n });\n\n it('should set allExamsGenerated to false', () => {\n examDetailComponent.checkAllExamsGenerated();\n expect(examDetailComponent.allExamsGenerated).to.be.equal(false);\n });\n });\n\n describe('test checkEachGroupContainsExercise', () => {\n it('should set allGroupsContainExercise to true', () => {\n examDetailComponent.exam.exerciseGroups = getExerciseGroups(false);\n examDetailComponent.checkAllGroupContainsExercise();\n expect(examDetailComponent.allGroupsContainExercise).to.be.equal(true);\n });\n\n it('should set allGroupsContainExercise to false', () => {\n examDetailComponent.exam.exerciseGroups = [{ id: 1, exercises: [] }];\n examDetailComponent.checkAllGroupContainsExercise();\n expect(examDetailComponent.allGroupsContainExercise).to.be.equal(false);\n });\n });\n\n describe('test function checkPointsExercisesEqual', () => {\n it('should return checkPointsExercisesEqual as true ', () => {\n examDetailComponent.exam.exerciseGroups = getExerciseGroups(true);\n examDetailComponent.checkPointsExercisesEqual();\n expect(examDetailComponent.pointsExercisesEqual).to.be.equal(true);\n });\n it('should return checkPointsExercisesEqual as false', () => {\n examDetailComponent.exam.exerciseGroups = getExerciseGroups(false);\n examDetailComponent.checkPointsExercisesEqual();\n expect(examDetailComponent.pointsExercisesEqual).to.be.equal(false);\n });\n });\n});\n" }, { "alpha_fraction": 0.6458495855331421, "alphanum_fraction": 0.6458495855331421, "avg_line_length": 33.621620178222656, "blob_id": "b2d43b302a34a627caa9bc7dd6e751db83c1fb5d", "content_id": "653834310276bf9c4edc7846b6cb57ce974cfe6a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3843, "license_type": "permissive", "max_line_length": 138, "num_lines": 111, "path": "/src/main/webapp/app/lecture/lecture-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { LectureService } from './lecture.service';\nimport { CourseManagementService } from '../course/manage/course-management.service';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { Course } from 'app/entities/course.model';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport { navigateBack } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-lecture-update',\n templateUrl: './lecture-update.component.html',\n styleUrls: ['./lecture-update.component.scss'],\n})\nexport class LectureUpdateComponent implements OnInit {\n EditorMode = EditorMode;\n lecture: Lecture;\n isSaving: boolean;\n\n courses: Course[];\n startDate: string;\n endDate: string;\n\n domainCommandsDescription = [new KatexCommand()];\n\n constructor(\n protected jhiAlertService: JhiAlertService,\n protected lectureService: LectureService,\n protected courseService: CourseManagementService,\n protected activatedRoute: ActivatedRoute,\n private router: Router,\n ) {}\n\n /**\n * Life cycle hook called by Angular to indicate that Angular is done creating the component\n */\n ngOnInit() {\n this.isSaving = false;\n this.activatedRoute.parent!.data.subscribe((data) => {\n // Create a new lecture to use unless we fetch an existing lecture\n const lecture = data['lecture'];\n this.lecture = lecture ?? new Lecture();\n\n const course = data['course'];\n if (course) {\n this.lecture.course = course;\n }\n });\n }\n\n /**\n * Revert to the previous state, equivalent with pressing the back button on your browser\n * Returns to the detail page if there is no previous state and we edited an existing lecture\n * Returns to the overview page if there is no previous state and we created a new lecture\n */\n previousState() {\n if (this.lecture.id) {\n navigateBack(this.router, ['course-management', this.lecture.course!.id!.toString(), 'lectures', this.lecture.id.toString()]);\n } else {\n navigateBack(this.router, ['course-management', this.lecture.course!.id!.toString(), 'lectures']);\n }\n }\n\n /**\n * Save the changes on a lecture\n * This function is called by pressing save after creating or editing a lecture\n */\n save() {\n this.isSaving = true;\n if (this.lecture.id !== undefined) {\n this.subscribeToSaveResponse(this.lectureService.update(this.lecture));\n } else {\n this.subscribeToSaveResponse(this.lectureService.create(this.lecture));\n }\n }\n\n /**\n * @callback Callback function after saving a lecture, handles appropriate action in case of error\n * @param result The Http response from the server\n */\n protected subscribeToSaveResponse(result: Observable<HttpResponse<Lecture>>) {\n result.subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n }\n\n /**\n * Action on successful lecture creation or edit\n */\n protected onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n /**\n * Action on unsuccessful lecture creation or edit\n */\n protected onSaveError() {\n this.isSaving = false;\n // TODO: No feedback given to user\n }\n\n protected onError(errorMessage: string) {\n this.jhiAlertService.error(errorMessage);\n }\n}\n" }, { "alpha_fraction": 0.8104304671287537, "alphanum_fraction": 0.8104304671287537, "avg_line_length": 66.11111450195312, "blob_id": "76e7a9afb97a7b17ca814d62e19118133218a1f5", "content_id": "6ace33ddbe8a7270d999a2d569f5dfd6c2b8c1b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1208, "license_type": "permissive", "max_line_length": 159, "num_lines": 18, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-management.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { RouterModule } from '@angular/router';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { exerciseHintRoute } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.route';\nimport { ExerciseHintDetailComponent } from 'app/exercises/shared/exercise-hint/manage/exercise-hint-detail.component';\nimport { ExerciseHintUpdateComponent } from 'app/exercises/shared/exercise-hint/manage/exercise-hint-update.component';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { ExerciseHintComponent } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.component';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\n\nconst ENTITY_STATES = [...exerciseHintRoute];\n\n@NgModule({\n imports: [ArtemisSharedModule, RouterModule.forChild(ENTITY_STATES), FormsModule, ReactiveFormsModule, ArtemisMarkdownModule, ArtemisMarkdownEditorModule],\n declarations: [ExerciseHintComponent, ExerciseHintDetailComponent, ExerciseHintUpdateComponent],\n})\nexport class ArtemisExerciseHintManagementModule {}\n" }, { "alpha_fraction": 0.6437744498252869, "alphanum_fraction": 0.6437744498252869, "avg_line_length": 32.79245376586914, "blob_id": "adbe5778e8733e248c640fd905ef63b3e7bd3530", "content_id": "9e6966696257ef97584f669761d22f77d5ca7a2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1791, "license_type": "permissive", "max_line_length": 102, "num_lines": 53, "path": "/src/main/webapp/app/exercises/text/shared/manual-text-selection/manual-text-selection.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, Output, EventEmitter } from '@angular/core';\nimport { SelectionRectangle, TextSelectEvent } from 'app/exercises/text/shared/text-select.directive';\nimport { convertToHtmlLinebreaks } from 'app/utils/text.utils';\n\n@Component({\n selector: 'jhi-manual-text-selection',\n templateUrl: './manual-text-selection.component.html',\n styleUrls: ['./manual-text-selection.component.scss'],\n})\nexport class ManualTextSelectionComponent {\n @Input() public disabled = false;\n @Input() public positionRelative = false;\n @Output() public assess = new EventEmitter<string>();\n\n public hostRectangle: SelectionRectangle | undefined;\n public selectedText: string | undefined;\n\n /**\n * Handle user's selection of solution text.\n * @param $event fired on text selection of type {TextSelectEvent}\n */\n didSelectSolutionText($event: TextSelectEvent): void {\n if (this.disabled) {\n return;\n }\n\n // If a new selection has been created, the viewport and host rectangles will\n // exist. Or, if a selection is being removed, the rectangles will be null.\n if ($event.hostRectangle) {\n this.hostRectangle = $event.hostRectangle;\n this.selectedText = convertToHtmlLinebreaks($event.text);\n } else {\n this.hostRectangle = undefined;\n this.selectedText = undefined;\n }\n }\n\n /**\n * Remove selection from text.\n */\n deselectText(): void {\n document.getSelection()!.removeAllRanges();\n this.hostRectangle = undefined;\n this.selectedText = undefined;\n }\n\n assessAction(): void {\n if (this.selectedText) {\n this.assess.emit(this.selectedText);\n this.deselectText();\n }\n }\n}\n" }, { "alpha_fraction": 0.7532467246055603, "alphanum_fraction": 0.7532467246055603, "avg_line_length": 37.5, "blob_id": "6389431cf6284c1b41d426807fa30584769aa382", "content_id": "04863f8952b1370563ac8e27c911183cb29f0796", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 231, "license_type": "permissive", "max_line_length": 80, "num_lines": 6, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-participation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Participation } from 'app/entities/participation/participation.model';\nimport { of } from 'rxjs';\n\nexport class MockParticipationService {\n findWithLatestResult = (participationId: number) => of({} as Participation);\n}\n" }, { "alpha_fraction": 0.5370452404022217, "alphanum_fraction": 0.5390416979789734, "avg_line_length": 36.25619888305664, "blob_id": "d1e20e7da833f4fa1b9e668a7754c318447bea45", "content_id": "7318928f7da67f23921b7eb8b4553801eae98e8c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4508, "license_type": "permissive", "max_line_length": 135, "num_lines": 121, "path": "/src/main/webapp/app/core/login/login.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Router } from '@angular/router';\nimport { EMPTY, from } from 'rxjs';\nimport { catchError, switchMap, tap } from 'rxjs/operators';\n\nimport { AuthServerProvider, Credentials } from 'app/core/auth/auth-jwt.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { NotificationService } from 'app/shared/notification/notification.service';\n\n@Injectable({ providedIn: 'root' })\nexport class LoginService {\n logoutWasForceful = false;\n\n constructor(\n private accountService: AccountService,\n private websocketService: JhiWebsocketService,\n private authServerProvider: AuthServerProvider,\n private router: Router,\n private alertService: JhiAlertService,\n private notificationService: NotificationService,\n ) {}\n\n /**\n * Login the user with the given credentials.\n * @param credentials {Credentials} Credentials of the user to login.\n */\n login(credentials: Credentials) {\n return new Promise<void>((resolve, reject) => {\n this.authServerProvider.login(credentials).subscribe(\n () => {\n this.accountService.identity(true).then(() => {\n resolve();\n });\n },\n (err) => {\n this.logout(false);\n reject(err);\n },\n );\n });\n }\n\n /**\n * Login the user with SAML2.\n * @param rememberMe whether or not to remember the user\n */\n loginSAML2(rememberMe: boolean) {\n return new Promise<void>((resolve, reject) => {\n this.authServerProvider.loginSAML2(rememberMe).subscribe(\n () => {\n this.accountService.identity(true).then(() => {\n resolve();\n });\n },\n (err) => {\n this.logout(false);\n reject(err);\n },\n );\n });\n }\n\n /**\n * Login with JWT token.\n * @param jwt {string} The JWT token.\n * @param rememberMe {boolean} True to save JWT in localStorage, false to save it in sessionStorage.\n */\n loginWithToken(jwt: string, rememberMe: boolean) {\n return this.authServerProvider.loginWithToken(jwt, rememberMe);\n }\n\n /**\n * Log out the user and remove all traces of the login from the browser:\n * Tokens, Alerts, User object in memory.\n * Will redirect to home when done.\n */\n logout(wasInitiatedByUser: boolean) {\n this.logoutWasForceful = !wasInitiatedByUser;\n\n this.authServerProvider\n // 1: Clear the auth tokens from the browser's caches.\n .removeAuthTokenFromCaches()\n .pipe(\n // 2: Clear all other caches (this is important so if a new user logs in, no old values are available\n tap(() => {\n if (wasInitiatedByUser) {\n // only clear caches on an intended logout. Do not clear the caches, when the user was logged out automatically\n return this.authServerProvider.clearCaches();\n }\n }),\n // 3: Set the user's auth object to null as components might have to act on the user being logged out.\n tap(() => {\n return this.accountService.authenticate(undefined);\n }),\n // 4: Clear all existing alerts of the user.\n tap(() => {\n return this.alertService.clear();\n }),\n // 5: Clean up notification service.\n tap(() => {\n return this.notificationService.cleanUp();\n }),\n // 6: Navigate to the login screen.\n switchMap(() => {\n return from(this.router.navigateByUrl('/'));\n }),\n // If something happens during the logout, show the error to the user.\n catchError((error: any) => {\n this.alertService.error('logout.failed', { error });\n return EMPTY;\n }),\n )\n .subscribe();\n }\n\n lastLogoutWasForceful(): boolean {\n return this.logoutWasForceful;\n }\n}\n" }, { "alpha_fraction": 0.6776978373527527, "alphanum_fraction": 0.6776978373527527, "avg_line_length": 30.590909957885742, "blob_id": "8ab0ab5e75939b220ffbf2cd0ddcc0b7b64d0536", "content_id": "9ca3c430c8924ac24b4a7cfbf3feb10c7f73705a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 695, "license_type": "permissive", "max_line_length": 110, "num_lines": 22, "path": "/src/main/webapp/app/shared/orion/orion-button/orion-button.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\n\n@Component({\n selector: 'jhi-ide-button',\n templateUrl: './orion-button.component.html',\n styleUrls: ['./orion-button.component.scss'],\n})\nexport class OrionButtonComponent {\n @Input() buttonLabel: string;\n @Input() buttonLoading = false;\n @Input() outlined = false;\n @Input() smallButton = false;\n @Input() disabled = false;\n @Input() featureToggle: FeatureToggle = FeatureToggle.PROGRAMMING_EXERCISES; // Disable by feature toggle.\n\n constructor() {}\n\n public get btnPrimary(): boolean {\n return !this.outlined;\n }\n}\n" }, { "alpha_fraction": 0.6767123341560364, "alphanum_fraction": 0.6767123341560364, "avg_line_length": 39.55555725097656, "blob_id": "72ba115f6575b552b4a443067e17c2ef764a1e69", "content_id": "28e6db61a89816699878f3b0f3480217abb6dcc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1460, "license_type": "permissive", "max_line_length": 128, "num_lines": 36, "path": "/src/test/javascript/spec/component/exam/participate/summary/exercises/text-exam-summary.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { TextExamSummaryComponent } from 'app/exam/participate/summary/exercises/text-exam-summary/text-exam-summary.component';\nimport { TextSubmission } from 'app/entities/text-submission.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TextExamSummaryComponent', () => {\n let fixture: ComponentFixture<TextExamSummaryComponent>;\n let component: TextExamSummaryComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({ declarations: [TextExamSummaryComponent] })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(TextExamSummaryComponent);\n component = fixture.componentInstance;\n });\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n expect(fixture.debugElement.nativeElement.querySelector('div').innerHTML).to.equal('No submission');\n });\n\n it('should display the submission text', () => {\n const submissionText = 'A test submission text';\n component.submission = { text: submissionText } as TextSubmission;\n fixture.detectChanges();\n expect(component).to.be.ok;\n expect(fixture.debugElement.nativeElement.querySelector('div').innerHTML).to.equal(submissionText);\n });\n});\n" }, { "alpha_fraction": 0.7446882724761963, "alphanum_fraction": 0.7502612471580505, "avg_line_length": 42.5, "blob_id": "3d4f238a41f785bb5620c26d084a9b7f5c16873b", "content_id": "e01aeebfd6d1b1718ed9335cab0014e72349349b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2871, "license_type": "permissive", "max_line_length": 172, "num_lines": 66, "path": "/src/test/java/de/tum/in/www1/artemis/util/ModelingExerciseUtilService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.util;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.ExampleSubmission;\nimport de.tum.in.www1.artemis.domain.enumeration.DiagramType;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\n\n@Service\npublic class ModelingExerciseUtilService {\n\n @Autowired\n protected DatabaseUtilService database;\n\n /**\n * Create modeling exercise for a given course\n * @param courseId id of the given course\n * @return created modeling exercise\n */\n public ModelingExercise createModelingExercise(Long courseId) {\n return createModelingExercise(courseId, null);\n }\n\n /**\n * Create modeling exercise with a given id for a given course\n * @param courseId id of the given course\n * @param exerciseId id of modeling exercise\n * @return created modeling exercise\n */\n public ModelingExercise createModelingExercise(Long courseId, Long exerciseId) {\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n ZonedDateTime futureTimestamp = ZonedDateTime.now().plusDays(5);\n ZonedDateTime futureFutureTimestamp = ZonedDateTime.now().plusDays(8);\n\n Course course1 = ModelFactory.generateCourse(courseId, pastTimestamp, futureTimestamp, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n ModelingExercise modelingExercise = ModelFactory.generateModelingExercise(pastTimestamp, futureTimestamp, futureFutureTimestamp, DiagramType.ClassDiagram, course1);\n modelingExercise.setGradingInstructions(\"Grading instructions\");\n modelingExercise.getCategories().add(\"Modeling\");\n modelingExercise.setId(exerciseId);\n course1.addExercises(modelingExercise);\n\n return modelingExercise;\n }\n\n /**\n * Add example submission to modeling exercise\n * @param modelingExercise modeling exercise for which the example submission should be added\n * @return modeling exercise with example submission\n * @throws Exception if the resources file is not found\n */\n public ModelingExercise addExampleSubmission(ModelingExercise modelingExercise) throws Exception {\n Set<ExampleSubmission> exampleSubmissionSet = new HashSet<>();\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n var exampleSubmission = database.generateExampleSubmission(validModel, modelingExercise, true);\n exampleSubmission.assessmentExplanation(\"explanation\");\n exampleSubmissionSet.add(exampleSubmission);\n modelingExercise.setExampleSubmissions(exampleSubmissionSet);\n return modelingExercise;\n }\n}\n" }, { "alpha_fraction": 0.5488404631614685, "alphanum_fraction": 0.5527055263519287, "avg_line_length": 38.25517272949219, "blob_id": "5d333f72456cebeca511f6e0c319c8b27a6c4736", "content_id": "e094f6a92035e7f391784cdd7a7315fc45ba1b6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5692, "license_type": "permissive", "max_line_length": 149, "num_lines": 145, "path": "/src/main/webapp/app/shared/statistics-graph/statistics-average-score-graph.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit, ViewChild } from '@angular/core';\nimport { StatisticsService } from 'app/shared/statistics-graph/statistics.service';\nimport { ChartDataSets, ChartOptions, ChartType } from 'chart.js';\nimport { BaseChartDirective, Label } from 'ng2-charts';\nimport { DataSet } from 'app/exercises/quiz/manage/statistics/quiz-statistic/quiz-statistic.component';\nimport { TranslateService } from '@ngx-translate/core';\nimport { GraphColors, Graphs, SpanType } from 'app/entities/statistics.model';\nimport { CourseManagementStatisticsModel } from 'app/entities/quiz/course-management-statistics-model';\n\n@Component({\n selector: 'jhi-statistics-average-score-graph',\n templateUrl: './statistics-average-score-graph.component.html',\n})\nexport class StatisticsAverageScoreGraphComponent implements OnInit {\n @Input()\n exerciseAverageScores: CourseManagementStatisticsModel[];\n @Input()\n courseAverage: number;\n\n // Html properties\n LEFT = false;\n RIGHT = true;\n SpanType = SpanType;\n Graphs = Graphs;\n\n // Histogram related properties\n barChartOptions: ChartOptions = {};\n barChartType: ChartType = 'bar';\n lineChartType: ChartType = 'line';\n exerciseAverageLegend: string;\n courseAverageLegend: string;\n chartName: string;\n barChartLegend = true;\n\n // Data\n barChartLabels: Label[] = [];\n chartData: ChartDataSets[] = [];\n dataForSpanType: number[];\n\n // Left arrow -> decrease, right arrow -> increase\n currentPeriod = 0;\n\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n constructor(private service: StatisticsService, private translateService: TranslateService) {}\n\n ngOnInit(): void {\n this.chartName = this.translateService.instant(`artemisApp.course.averageScore`);\n this.exerciseAverageLegend = this.translateService.instant('artemisApp.courseStatistics.exerciseAverage');\n this.courseAverageLegend = this.translateService.instant('artemisApp.courseStatistics.courseAverage');\n this.initializeChart();\n this.createCharts();\n }\n\n private initializeChart(): void {\n this.barChartLabels = this.exerciseAverageScores.slice(this.currentPeriod, 10 + this.currentPeriod).map((exercise) => exercise.exerciseName);\n this.chartData = [\n {\n // Average course score line\n label: this.courseAverageLegend,\n data: new Array(this.barChartLabels.length).fill(this.courseAverage),\n backgroundColor: GraphColors.BLUE,\n fill: false,\n pointBackgroundColor: GraphColors.BLUE_TRANSPARENT,\n pointBorderColor: GraphColors.BLUE_TRANSPARENT,\n pointHoverBackgroundColor: GraphColors.BLUE,\n pointHoverBorderColor: GraphColors.BLUE_TRANSPARENT,\n borderColor: GraphColors.BLUE,\n hoverBackgroundColor: GraphColors.BLUE,\n hoverBorderColor: GraphColors.BLUE,\n },\n {\n // Average exercise score bars\n label: this.exerciseAverageLegend,\n data: this.exerciseAverageScores.slice(this.currentPeriod, 10 + this.currentPeriod).map((exercise) => exercise.averageScore),\n type: 'bar',\n backgroundColor: GraphColors.DARK_BLUE,\n borderColor: GraphColors.DARK_BLUE,\n hoverBackgroundColor: GraphColors.DARK_BLUE,\n },\n ];\n }\n\n private createCharts() {\n this.barChartOptions = {\n layout: {\n padding: {\n top: 20,\n },\n },\n responsive: true,\n hover: {\n animationDuration: 0,\n },\n animation: {\n duration: 1,\n onComplete() {\n const chartInstance = this.chart,\n ctx = chartInstance.ctx;\n ctx.textAlign = 'center';\n ctx.textBaseline = 'bottom';\n\n this.data.datasets.forEach(function (dataset: DataSet, j: number) {\n const meta = chartInstance.controller.getDatasetMeta(j);\n meta.data.forEach(function (bar: any, index: number) {\n const data = dataset.data[index];\n ctx.fillText(String(data), bar._model.x, bar._model.y - 5);\n });\n });\n },\n },\n scales: {\n yAxes: [\n {\n ticks: {\n beginAtZero: true,\n min: 0,\n max: 100,\n },\n },\n ],\n xAxes: [\n {\n gridLines: {\n offsetGridLines: false,\n },\n ticks: {\n autoSkip: false,\n callback(title: string) {\n return title.length > 10 ? title.substr(0, 10) + '...' : title;\n },\n },\n },\n ],\n },\n };\n }\n\n // handles arrow clicks and updates the exercises which are shown, forward is boolean since it is either forward or backward\n public switchTimeSpan(forward: boolean): void {\n // eslint-disable-next-line chai-friendly/no-unused-expressions\n this.currentPeriod += forward ? 1 : -1;\n this.initializeChart();\n }\n}\n" }, { "alpha_fraction": 0.7076919078826904, "alphanum_fraction": 0.709345817565918, "avg_line_length": 54.588401794433594, "blob_id": "08f31c036440c92bc55550ef362b507d473d79e7", "content_id": "f9772636bc8517a3277ae8c2b3a794639f0583bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 39301, "license_type": "permissive", "max_line_length": 180, "num_lines": 707, "path": "/src/main/java/de/tum/in/www1/artemis/service/exam/ExamService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.exam;\n\nimport static de.tum.in.www1.artemis.service.util.RoundingUtil.round;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.boot.actuate.audit.AuditEvent;\nimport org.springframework.boot.actuate.audit.AuditEventRepository;\nimport org.springframework.scheduling.annotation.Async;\nimport org.springframework.stereotype.Service;\n\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.quiz.QuizExercise;\nimport de.tum.in.www1.artemis.domain.quiz.QuizSubmission;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService;\nimport de.tum.in.www1.artemis.service.util.TimeLogUtil;\nimport de.tum.in.www1.artemis.web.rest.dto.*;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Service Implementation for managing exams.\n */\n@Service\npublic class ExamService {\n\n @Value(\"${artemis.course-archives-path}\")\n private String examArchivesDirPath;\n\n private final Logger log = LoggerFactory.getLogger(ExamService.class);\n\n private final UserRepository userRepository;\n\n private final ExerciseService exerciseService;\n\n private final StudentParticipationRepository studentParticipationRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final QuizExerciseRepository quizExerciseRepository;\n\n private final ExamQuizService examQuizService;\n\n private final InstanceMessageSendService instanceMessageSendService;\n\n private final ExamRepository examRepository;\n\n private final StudentExamRepository studentExamRepository;\n\n private final AuditEventRepository auditEventRepository;\n\n private final ComplaintRepository complaintRepository;\n\n private final ComplaintResponseRepository complaintResponseRepository;\n\n private final ResultRepository resultRepository;\n\n private final SubmissionRepository submissionRepository;\n\n private final TutorLeaderboardService tutorLeaderboardService;\n\n private final GitService gitService;\n\n private final CourseExamExportService courseExamExportService;\n\n private final GroupNotificationService groupNotificationService;\n\n public ExamService(ExamRepository examRepository, StudentExamRepository studentExamRepository, ExamQuizService examQuizService, ExerciseService exerciseService,\n InstanceMessageSendService instanceMessageSendService, TutorLeaderboardService tutorLeaderboardService, AuditEventRepository auditEventRepository,\n StudentParticipationRepository studentParticipationRepository, ComplaintRepository complaintRepository, ComplaintResponseRepository complaintResponseRepository,\n UserRepository userRepository, ProgrammingExerciseRepository programmingExerciseRepository, QuizExerciseRepository quizExerciseRepository,\n ResultRepository resultRepository, SubmissionRepository submissionRepository, CourseExamExportService courseExamExportService, GitService gitService,\n GroupNotificationService groupNotificationService) {\n this.examRepository = examRepository;\n this.studentExamRepository = studentExamRepository;\n this.userRepository = userRepository;\n this.studentParticipationRepository = studentParticipationRepository;\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.examQuizService = examQuizService;\n this.instanceMessageSendService = instanceMessageSendService;\n this.exerciseService = exerciseService;\n this.auditEventRepository = auditEventRepository;\n this.complaintRepository = complaintRepository;\n this.complaintResponseRepository = complaintResponseRepository;\n this.quizExerciseRepository = quizExerciseRepository;\n this.resultRepository = resultRepository;\n this.submissionRepository = submissionRepository;\n this.tutorLeaderboardService = tutorLeaderboardService;\n this.courseExamExportService = courseExamExportService;\n this.groupNotificationService = groupNotificationService;\n this.gitService = gitService;\n }\n\n /**\n * Get one exam by id with exercise groups and exercises.\n * Also fetches the template and solution participation for programming exercises and questions for quiz exercises.\n *\n * @param examId the id of the entity\n * @return the exam with exercise groups\n */\n @NotNull\n public Exam findByIdWithExerciseGroupsAndExercisesElseThrow(Long examId) {\n log.debug(\"Request to get exam with exercise groups : {}\", examId);\n Exam exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException(\"Exam\", examId));\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n for (Exercise exercise : exerciseGroup.getExercises()) {\n if (exercise instanceof ProgrammingExercise) {\n ProgrammingExercise exerciseWithTemplateAndSolutionParticipation = programmingExerciseRepository\n .findByIdWithTemplateAndSolutionParticipationWithResultsElseThrow(exercise.getId());\n ((ProgrammingExercise) exercise).setTemplateParticipation(exerciseWithTemplateAndSolutionParticipation.getTemplateParticipation());\n ((ProgrammingExercise) exercise).setSolutionParticipation(exerciseWithTemplateAndSolutionParticipation.getSolutionParticipation());\n }\n if (exercise instanceof QuizExercise) {\n QuizExercise quizExercise = quizExerciseRepository.findByIdWithQuestionsElseThrow(exercise.getId());\n ((QuizExercise) exercise).setQuizQuestions(quizExercise.getQuizQuestions());\n }\n }\n }\n return exam;\n }\n\n /**\n * Fetches the exam and eagerly loads all required elements and deletes all elements associated with the\n * exam including:\n * <ul>\n * <li>The Exam</li>\n * <li>All ExerciseGroups</li>\n * <li>All Exercises including:\n * Submissions, Participations, Results, Repositories and build plans, see {@link ExerciseService#delete}</li>\n * <li>All StudentExams</li>\n * </ul>\n * Note: StudentExams and ExerciseGroups are not explicitly deleted as the delete operation of the exam is cascaded by the database.\n *\n * @param examId the ID of the exam to be deleted\n */\n public void delete(@NotNull long examId) {\n User user = userRepository.getUser();\n Exam exam = examRepository.findOneWithEagerExercisesGroupsAndStudentExams(examId);\n log.info(\"User {} has requested to delete the exam {}\", user.getLogin(), exam.getTitle());\n AuditEvent auditEvent = new AuditEvent(user.getLogin(), Constants.DELETE_EXAM, \"exam=\" + exam.getTitle());\n auditEventRepository.add(auditEvent);\n\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n if (exerciseGroup != null) {\n for (Exercise exercise : exerciseGroup.getExercises()) {\n exerciseService.delete(exercise.getId(), true, true);\n }\n }\n }\n examRepository.deleteById(exam.getId());\n }\n\n /**\n * Puts students, result and exerciseGroups together for ExamScoresDTO\n *\n * @param examId the id of the exam\n * @return return ExamScoresDTO with students, scores and exerciseGroups for exam\n */\n public ExamScoresDTO calculateExamScores(Long examId) {\n Exam exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException(\"Exam\", examId));\n\n List<StudentParticipation> studentParticipations = studentParticipationRepository.findByExamIdWithSubmissionRelevantResult(examId); // without test run participations\n\n // Adding exam information to DTO\n ExamScoresDTO scores = new ExamScoresDTO(exam.getId(), exam.getTitle(), exam.getMaxPoints());\n\n // Counts how many participants each exercise has\n Map<Long, Long> exerciseIdToNumberParticipations = studentParticipations.stream()\n .collect(Collectors.groupingBy(studentParticipation -> studentParticipation.getExercise().getId(), Collectors.counting()));\n\n // Adding exercise group information to DTO\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n // Find the maximum points for this exercise group\n OptionalDouble optionalMaxPointsGroup = exerciseGroup.getExercises().stream().mapToDouble(Exercise::getMaxPoints).max();\n Double maxPointsGroup = optionalMaxPointsGroup.orElse(0);\n\n // Counter for exerciseGroup participations. Is calculated by summing up the number of exercise participations\n long numberOfExerciseGroupParticipants = 0;\n // Add information about exercise groups and exercises\n var exerciseGroupDTO = new ExamScoresDTO.ExerciseGroup(exerciseGroup.getId(), exerciseGroup.getTitle(), maxPointsGroup);\n for (Exercise exercise : exerciseGroup.getExercises()) {\n Long participantsForExercise = exerciseIdToNumberParticipations.get(exercise.getId());\n // If no participation exists for an exercise then no entry exists in the map\n if (participantsForExercise == null) {\n participantsForExercise = 0L;\n }\n numberOfExerciseGroupParticipants += participantsForExercise;\n exerciseGroupDTO.containedExercises\n .add(new ExamScoresDTO.ExerciseGroup.ExerciseInfo(exercise.getId(), exercise.getTitle(), exercise.getMaxPoints(), participantsForExercise));\n }\n exerciseGroupDTO.numberOfParticipants = numberOfExerciseGroupParticipants;\n scores.exerciseGroups.add(exerciseGroupDTO);\n }\n\n // Adding registered student information to DTO\n Set<StudentExam> studentExams = studentExamRepository.findByExamId(examId); // fetched without test runs\n ObjectMapper objectMapper = new ObjectMapper();\n for (StudentExam studentExam : studentExams) {\n\n User user = studentExam.getUser();\n var studentResult = new ExamScoresDTO.StudentResult(user.getId(), user.getName(), user.getEmail(), user.getLogin(), user.getRegistrationNumber(),\n studentExam.isSubmitted());\n\n // Adding student results information to DTO\n List<StudentParticipation> participationsOfStudent = studentParticipations.stream()\n .filter(studentParticipation -> studentParticipation.getStudent().get().getId().equals(studentResult.userId)).collect(Collectors.toList());\n\n studentResult.overallPointsAchieved = 0.0;\n for (StudentParticipation studentParticipation : participationsOfStudent) {\n Exercise exercise = studentParticipation.getExercise();\n\n // Relevant Result is already calculated\n if (studentParticipation.getResults() != null && !studentParticipation.getResults().isEmpty()) {\n Result relevantResult = studentParticipation.getResults().iterator().next();\n // Note: It is important that we round on the individual exercise level first and then sum up.\n // This is necessary so that the student arrives at the same overall result when doing his own recalculation.\n // Let's assume that the student achieved 1.05 points in each of 5 exercises.\n // In the client, these are now displayed rounded as 1.1 points.\n // If the student adds up the displayed points, he gets a total of 5.5 points.\n // In order to get the same total result as the student, we have to round before summing.\n double achievedPoints = round(relevantResult.getScore() / 100.0 * exercise.getMaxPoints());\n\n // points earned in NOT_INCLUDED exercises do not count towards the students result in the exam\n if (!exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED)) {\n studentResult.overallPointsAchieved += achievedPoints;\n }\n\n // Check whether the student attempted to solve the exercise\n boolean hasNonEmptySubmission = hasNonEmptySubmission(studentParticipation.getSubmissions(), exercise, objectMapper);\n studentResult.exerciseGroupIdToExerciseResult.put(exercise.getExerciseGroup().getId(), new ExamScoresDTO.ExerciseResult(exercise.getId(), exercise.getTitle(),\n exercise.getMaxPoints(), relevantResult.getScore(), achievedPoints, hasNonEmptySubmission));\n }\n\n }\n\n if (scores.maxPoints != null) {\n studentResult.overallScoreAchieved = (studentResult.overallPointsAchieved / scores.maxPoints) * 100.0;\n }\n scores.studentResults.add(studentResult);\n }\n\n // Updating exam information in DTO\n double sumOverallPoints = scores.studentResults.stream().mapToDouble(studentResult -> studentResult.overallPointsAchieved).sum();\n\n int numberOfStudentResults = scores.studentResults.size();\n\n if (numberOfStudentResults != 0) {\n scores.averagePointsAchieved = sumOverallPoints / numberOfStudentResults;\n }\n\n return scores;\n }\n\n /**\n * Checks whether one of the submissions is not empty\n *\n * @param submissions Submissions to check\n * @param exercise Exercise of the submissions\n * @param jacksonObjectMapper Mapper to parse a modeling exercise model string to JSON\n * @return true if at least one submission is not empty else false\n */\n private boolean hasNonEmptySubmission(Set<Submission> submissions, Exercise exercise, ObjectMapper jacksonObjectMapper) {\n if (exercise instanceof ProgrammingExercise) {\n return submissions.stream().anyMatch(submission -> submission.getType() == SubmissionType.MANUAL);\n }\n else if (exercise instanceof FileUploadExercise) {\n FileUploadSubmission textSubmission = (FileUploadSubmission) submissions.iterator().next();\n return textSubmission.getFilePath() != null && !textSubmission.getFilePath().isEmpty();\n }\n else if (exercise instanceof TextExercise) {\n TextSubmission textSubmission = (TextSubmission) submissions.iterator().next();\n return textSubmission.getText() != null && !textSubmission.getText().isBlank();\n }\n else if (exercise instanceof ModelingExercise) {\n ModelingSubmission modelingSubmission = (ModelingSubmission) submissions.iterator().next();\n try {\n return !modelingSubmission.isEmpty(jacksonObjectMapper);\n }\n catch (Exception e) {\n // Then the student most likely submitted something which breaks the model, if parsing fails\n return true;\n }\n }\n else if (exercise instanceof QuizExercise) {\n QuizSubmission quizSubmission = (QuizSubmission) submissions.iterator().next();\n return quizSubmission != null && !quizSubmission.getSubmittedAnswers().isEmpty();\n }\n else {\n throw new IllegalArgumentException(\"The exercise type of the exercise with id \" + exercise.getId() + \" is not supported\");\n }\n }\n\n /**\n * Validates exercise settings.\n *\n * @param exam exam which is validated\n * @throws BadRequestAlertException an exception if the exam is not configured correctly\n */\n public void validateForStudentExamGeneration(Exam exam) throws BadRequestAlertException {\n List<ExerciseGroup> exerciseGroups = exam.getExerciseGroups();\n long numberOfExercises = exam.getNumberOfExercisesInExam() != null ? exam.getNumberOfExercisesInExam() : 0;\n long numberOfOptionalExercises = numberOfExercises - exerciseGroups.stream().filter(ExerciseGroup::getIsMandatory).count();\n\n // Ensure that all exercise groups have at least one exercise\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n if (exerciseGroup.getExercises().isEmpty()) {\n throw new BadRequestAlertException(\"All exercise groups must have at least one exercise\", \"Exam\", \"artemisApp.exam.validation.atLeastOneExercisePerExerciseGroup\");\n }\n }\n\n // Check that numberOfExercisesInExam is set\n if (exam.getNumberOfExercisesInExam() == null) {\n throw new BadRequestAlertException(\"The number of exercises in the exam is not set.\", \"Exam\", \"artemisApp.exam.validation.numberOfExercisesInExamNotSet\");\n }\n\n // Check that there are enough exercise groups\n if (exam.getExerciseGroups().size() < exam.getNumberOfExercisesInExam()) {\n throw new BadRequestAlertException(\"The number of exercise groups is too small\", \"Exam\", \"artemisApp.exam.validation.tooFewExerciseGroups\");\n }\n\n // Check that there are not too much mandatory exercise groups\n if (numberOfOptionalExercises < 0) {\n throw new BadRequestAlertException(\"The number of mandatory exercise groups is too large\", \"Exam\", \"artemisApp.exam.validation.tooManyMandatoryExerciseGroups\");\n }\n\n // Ensure that all exercises in an exercise group have the same meaning for the exam score calculation\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n Set<IncludedInOverallScore> meaningsForScoreCalculation = exerciseGroup.getExercises().stream().map(Exercise::getIncludedInOverallScore).collect(Collectors.toSet());\n if (meaningsForScoreCalculation.size() > 1) {\n throw new BadRequestAlertException(\"All exercises in an exercise group must have the same meaning for the exam score\", \"Exam\",\n \"artemisApp.exam.validation.allExercisesInExerciseGroupOfSameIncludedType\");\n }\n }\n\n // Check that the exam max points is set\n if (exam.getMaxPoints() == null) {\n throw new BadRequestAlertException(\"The exam max points is not set.\", \"Exam\", \"artemisApp.exam.validation.maxPointsNotSet\");\n }\n\n // Ensure that all exercises in an exercise group have the same amount of max points and max bonus points\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n Set<Double> allMaxPoints = exerciseGroup.getExercises().stream().map(Exercise::getMaxPoints).collect(Collectors.toSet());\n Set<Double> allBonusPoints = exerciseGroup.getExercises().stream().map(Exercise::getBonusPoints).collect(Collectors.toSet());\n\n if (allMaxPoints.size() > 1 || allBonusPoints.size() > 1) {\n throw new BadRequestAlertException(\"All exercises in an exercise group need to give the same amount of points\", \"Exam\",\n \"artemisApp.exam.validation.allExercisesInExerciseGroupGiveSameNumberOfPoints\");\n }\n }\n\n // Ensure that the sum of all max points of mandatory exercise groups is not bigger than the max points set in the exam\n // At this point we are already sure that each exercise group has at least one exercise, all exercises in the group have the same no of points\n // and all are of the same calculation type, therefore we can just use any as representation for the group here\n Double pointsReachableByMandatoryExercises = 0.0;\n Set<ExerciseGroup> mandatoryExerciseGroups = exam.getExerciseGroups().stream().filter(ExerciseGroup::getIsMandatory).collect(Collectors.toSet());\n for (ExerciseGroup exerciseGroup : mandatoryExerciseGroups) {\n Exercise groupRepresentativeExercise = exerciseGroup.getExercises().stream().findAny().get();\n if (groupRepresentativeExercise.getIncludedInOverallScore().equals(IncludedInOverallScore.INCLUDED_COMPLETELY)) {\n pointsReachableByMandatoryExercises += groupRepresentativeExercise.getMaxPoints();\n }\n }\n if (pointsReachableByMandatoryExercises > exam.getMaxPoints()) {\n throw new BadRequestAlertException(\"Check that you set the exam max points correctly! The max points a student can earn in the mandatory exercise groups is too big\",\n \"Exam\", \"artemisApp.exam.validation.tooManyMaxPoints\");\n }\n\n // Ensure that the sum of all max points of all exercise groups is at least as big as the max points set in the exam\n Double pointsReachable = 0.0;\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n Exercise groupRepresentativeExercise = exerciseGroup.getExercises().stream().findAny().get();\n if (groupRepresentativeExercise.getIncludedInOverallScore().equals(IncludedInOverallScore.INCLUDED_COMPLETELY)) {\n pointsReachable += groupRepresentativeExercise.getMaxPoints();\n }\n }\n if (pointsReachable < exam.getMaxPoints()) {\n throw new BadRequestAlertException(\"Check that you set the exam max points correctly! The max points a student can earn in the exercise groups is too low\", \"Exam\",\n \"artemisApp.exam.validation.tooFewMaxPoints\");\n }\n }\n\n /**\n * Gets all statistics for the instructor checklist regarding an exam\n *\n * @param exam the exam for which to get statistics for\n * @return a examStatisticsDTO filled with all statistics regarding the exam\n */\n public ExamChecklistDTO getStatsForChecklist(Exam exam) {\n log.info(\"getStatsForChecklist invoked for exam {}\", exam.getId());\n int numberOfCorrectionRoundsInExam = exam.getNumberOfCorrectionRoundsInExam();\n long start = System.nanoTime();\n ExamChecklistDTO examChecklistDTO = new ExamChecklistDTO();\n\n List<Long> numberOfComplaintsOpenByExercise = new ArrayList<>();\n List<Long> numberOfComplaintResponsesByExercise = new ArrayList<>();\n List<DueDateStat[]> numberOfAssessmentsFinishedOfCorrectionRoundsByExercise = new ArrayList<>();\n List<Long> numberOfParticipationsGeneratedByExercise = new ArrayList<>();\n List<Long> numberOfParticipationsForAssessmentGeneratedByExercise = new ArrayList<>();\n\n // loop over all exercises and retrieve all needed counts for the properties at once\n exam.getExerciseGroups().forEach(exerciseGroup -> exerciseGroup.getExercises().forEach(exercise -> {\n // number of complaints open\n numberOfComplaintsOpenByExercise.add(complaintRepository.countByResultParticipationExerciseIdAndComplaintTypeIgnoreTestRuns(exercise.getId(), ComplaintType.COMPLAINT));\n\n log.debug(\"StatsTimeLog: number of complaints open done in {} for exercise {}\", TimeLogUtil.formatDurationFrom(start), exercise.getId());\n // number of complaints finished\n numberOfComplaintResponsesByExercise\n .add(complaintResponseRepository.countComplaintResponseByExerciseIdAndComplaintTypeAndSubmittedTimeIsNotNull(exercise.getId(), ComplaintType.COMPLAINT));\n\n log.debug(\"StatsTimeLog: number of complaints finished done in {} for exercise {}\", TimeLogUtil.formatDurationFrom(start), exercise.getId());\n // number of assessments done\n numberOfAssessmentsFinishedOfCorrectionRoundsByExercise\n .add(resultRepository.countNumberOfFinishedAssessmentsForExamExerciseForCorrectionRounds(exercise, numberOfCorrectionRoundsInExam));\n\n log.debug(\"StatsTimeLog: number of assessments done in {} for exercise {}\", TimeLogUtil.formatDurationFrom(start), exercise.getId());\n // get number of all generated participations\n numberOfParticipationsGeneratedByExercise.add(studentParticipationRepository.countParticipationsIgnoreTestRunsByExerciseId(exercise.getId()));\n\n log.debug(\"StatsTimeLog: number of generated participations in {} for exercise {}\", TimeLogUtil.formatDurationFrom(start), exercise.getId());\n if (!(exercise instanceof QuizExercise || exercise.getAssessmentType() == AssessmentType.AUTOMATIC)) {\n numberOfParticipationsForAssessmentGeneratedByExercise.add(submissionRepository.countByExerciseIdSubmittedBeforeDueDateIgnoreTestRuns(exercise.getId()));\n }\n }));\n\n long totalNumberOfComplaints = 0;\n long totalNumberOfComplaintResponse = 0;\n Long[] totalNumberOfAssessmentsFinished = new Long[numberOfCorrectionRoundsInExam];\n long totalNumberOfParticipationsGenerated = 0;\n long totalNumberOfParticipationsForAssessment = 0;\n\n // sum up all counts for the different properties\n for (Long numberOfParticipations : numberOfParticipationsGeneratedByExercise) {\n totalNumberOfParticipationsGenerated += numberOfParticipations != null ? numberOfParticipations : 0;\n }\n // sum up all counts for the different properties\n for (Long numberOfParticipationsForAssessment : numberOfParticipationsForAssessmentGeneratedByExercise) {\n totalNumberOfParticipationsForAssessment += numberOfParticipationsForAssessment != null ? numberOfParticipationsForAssessment : 0;\n }\n\n for (DueDateStat[] dateStats : numberOfAssessmentsFinishedOfCorrectionRoundsByExercise) {\n for (int i = 0; i < numberOfCorrectionRoundsInExam; i++) {\n if (totalNumberOfAssessmentsFinished[i] == null) {\n totalNumberOfAssessmentsFinished[i] = 0L;\n }\n totalNumberOfAssessmentsFinished[i] += dateStats[i].getInTime();\n }\n }\n for (Long numberOfComplaints : numberOfComplaintsOpenByExercise) {\n totalNumberOfComplaints += numberOfComplaints;\n }\n for (Long numberOfComplaintResponse : numberOfComplaintResponsesByExercise) {\n totalNumberOfComplaintResponse += numberOfComplaintResponse;\n }\n examChecklistDTO.setNumberOfTotalExamAssessmentsFinishedByCorrectionRound(totalNumberOfAssessmentsFinished);\n examChecklistDTO.setNumberOfAllComplaints(totalNumberOfComplaints);\n examChecklistDTO.setNumberOfAllComplaintsDone(totalNumberOfComplaintResponse);\n\n // set number of student exams that have been generated\n long numberOfGeneratedStudentExams = examRepository.countGeneratedStudentExamsByExamWithoutTestRuns(exam.getId());\n examChecklistDTO.setNumberOfGeneratedStudentExams(numberOfGeneratedStudentExams);\n\n log.debug(\"StatsTimeLog: number of generated student exams done in {}\", TimeLogUtil.formatDurationFrom(start));\n\n // set number of test runs\n long numberOfTestRuns = studentExamRepository.countTestRunsByExamId(exam.getId());\n examChecklistDTO.setNumberOfTestRuns(numberOfTestRuns);\n\n log.debug(\"StatsTimeLog: number of test runs done in {}\", TimeLogUtil.formatDurationFrom(start));\n\n // check if all exercises have been prepared for all students;\n boolean exercisesPrepared = numberOfGeneratedStudentExams != 0\n && (exam.getNumberOfExercisesInExam() * numberOfGeneratedStudentExams) == totalNumberOfParticipationsGenerated;\n examChecklistDTO.setAllExamExercisesAllStudentsPrepared(exercisesPrepared);\n\n // set started and submitted exam properties\n long numberOfStudentExamsStarted = studentExamRepository.countStudentExamsStartedByExamIdIgnoreTestRuns(exam.getId());\n log.debug(\"StatsTimeLog: number of student exams started done in {}\", TimeLogUtil.formatDurationFrom(start));\n long numberOfStudentExamsSubmitted = studentExamRepository.countStudentExamsSubmittedByExamIdIgnoreTestRuns(exam.getId());\n log.debug(\"StatsTimeLog: number of student exams submitted done in {}\", TimeLogUtil.formatDurationFrom(start));\n examChecklistDTO.setNumberOfTotalParticipationsForAssessment(totalNumberOfParticipationsForAssessment);\n examChecklistDTO.setNumberOfExamsStarted(numberOfStudentExamsStarted);\n examChecklistDTO.setNumberOfExamsSubmitted(numberOfStudentExamsSubmitted);\n return examChecklistDTO;\n }\n\n /**\n * Evaluates all the quiz exercises of an exam\n *\n * @param examId id of the exam for which the quiz exercises should be evaluated\n * @return number of evaluated exercises\n */\n public Integer evaluateQuizExercises(Long examId) {\n var exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException(\"Exam\", examId));\n\n // Collect all quiz exercises for the given exam\n Set<QuizExercise> quizExercises = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n for (Exercise exercise : exerciseGroup.getExercises()) {\n if (exercise instanceof QuizExercise) {\n quizExercises.add((QuizExercise) exercise);\n }\n }\n }\n\n long start = System.nanoTime();\n log.info(\"Evaluating {} quiz exercises in exam {}\", quizExercises.size(), examId);\n // Evaluate all quizzes for that exercise\n quizExercises.forEach(quiz -> examQuizService.evaluateQuizAndUpdateStatistics(quiz.getId()));\n log.info(\"Evaluated {} quiz exercises in exam {} in {}\", quizExercises.size(), examId, TimeLogUtil.formatDurationFrom(start));\n\n return quizExercises.size();\n }\n\n /**\n * Unlocks all repositories of an exam\n *\n * @param examId id of the exam for which the repositories should be unlocked\n * @return number of exercises for which the repositories are unlocked\n */\n public Integer unlockAllRepositories(Long examId) {\n var exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException(\"Exam\", examId));\n\n // Collect all programming exercises for the given exam\n Set<ProgrammingExercise> programmingExercises = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n for (Exercise exercise : exerciseGroup.getExercises()) {\n if (exercise instanceof ProgrammingExercise) {\n programmingExercises.add((ProgrammingExercise) exercise);\n }\n }\n }\n\n for (ProgrammingExercise programmingExercise : programmingExercises) {\n // Run the runnable immediately so that the repositories are unlocked as fast as possible\n instanceMessageSendService.sendUnlockAllRepositories(programmingExercise.getId());\n }\n\n return programmingExercises.size();\n }\n\n /**\n * Locks all repositories of an exam\n *\n * @param examId id of the exam for which the repositories should be locked\n * @return number of exercises for which the repositories are locked\n */\n public Integer lockAllRepositories(Long examId) {\n var exam = examRepository.findWithExerciseGroupsAndExercisesById(examId).orElseThrow(() -> new EntityNotFoundException(\"Exam\", examId));\n\n // Collect all programming exercises for the given exam\n Set<ProgrammingExercise> programmingExercises = new HashSet<>();\n for (ExerciseGroup exerciseGroup : exam.getExerciseGroups()) {\n for (Exercise exercise : exerciseGroup.getExercises()) {\n if (exercise instanceof ProgrammingExercise) {\n programmingExercises.add((ProgrammingExercise) exercise);\n }\n }\n }\n\n for (ProgrammingExercise programmingExercise : programmingExercises) {\n // Run the runnable immediately so that the repositories are locked as fast as possible\n instanceMessageSendService.sendLockAllRepositories(programmingExercise.getId());\n }\n\n return programmingExercises.size();\n }\n\n /**\n * Sets exam exercise transient properties for different exercise types\n * @param exam - the exam for which we set the exercise properties\n */\n public void setExamExerciseProperties(Exam exam) {\n exam.getExerciseGroups().forEach(exerciseGroup -> {\n exerciseGroup.getExercises().forEach(exercise -> {\n // Set transient property for quiz exam exercise if test runs exist\n if (exercise instanceof QuizExercise) {\n exerciseService.checkTestRunsExist(exercise);\n }\n });\n });\n }\n\n /**\n * Gets a collection of useful statistics for the tutor exam-assessment-dashboard, including: - number of submissions to the course - number of\n * assessments - number of assessments assessed by the tutor - number of complaints\n *\n * @param course - the couse of the exam\n * @param examId - the id of the exam to retrieve stats from\n * @return data about a exam including all exercises, plus some data for the tutor as tutor status for assessment\n */\n public StatsForDashboardDTO getStatsForExamAssessmentDashboard(Course course, Long examId) {\n Exam exam = examRepository.findById(examId).orElseThrow();\n StatsForDashboardDTO stats = new StatsForDashboardDTO();\n\n final long numberOfSubmissions = submissionRepository.countByExamIdSubmittedSubmissionsIgnoreTestRuns(examId)\n + programmingExerciseRepository.countLegalSubmissionsByExamIdSubmitted(examId);\n stats.setNumberOfSubmissions(new DueDateStat(numberOfSubmissions, 0));\n\n DueDateStat[] numberOfAssessmentsOfCorrectionRounds = resultRepository.countNumberOfFinishedAssessmentsForExamForCorrectionRounds(examId,\n exam.getNumberOfCorrectionRoundsInExam());\n stats.setNumberOfAssessmentsOfCorrectionRounds(numberOfAssessmentsOfCorrectionRounds);\n\n final long numberOfComplaints = complaintRepository.countByResult_Participation_Exercise_ExerciseGroup_Exam_IdAndComplaintType(examId, ComplaintType.COMPLAINT);\n stats.setNumberOfComplaints(numberOfComplaints);\n\n final long numberOfAssessmentLocks = submissionRepository.countLockedSubmissionsByUserIdAndExamId(userRepository.getUserWithGroupsAndAuthorities().getId(), examId);\n stats.setNumberOfAssessmentLocks(numberOfAssessmentLocks);\n\n final long totalNumberOfAssessmentLocks = submissionRepository.countLockedSubmissionsByExamId(examId);\n stats.setTotalNumberOfAssessmentLocks(totalNumberOfAssessmentLocks);\n\n List<TutorLeaderboardDTO> leaderboardEntries = tutorLeaderboardService.getExamLeaderboard(course, exam);\n stats.setTutorLeaderboardEntries(leaderboardEntries);\n return stats;\n }\n\n /**\n * Archives the exam by creating a zip file with student submissions for\n * exercises of the exam.\n *\n * @param exam the exam to archive\n */\n @Async\n public void archiveExam(Exam exam) {\n SecurityUtils.setAuthorizationObject();\n\n // Archiving a course is only possible after the exam is over\n if (ZonedDateTime.now().isBefore(exam.getEndDate())) {\n return;\n }\n\n // This contains possible errors encountered during the archive process\n ArrayList<String> exportErrors = new ArrayList<>();\n\n groupNotificationService.notifyInstructorGroupAboutExamArchiveState(exam, NotificationType.EXAM_ARCHIVE_STARTED, exportErrors);\n\n try {\n // Create exam archives directory if it doesn't exist\n Files.createDirectories(Path.of(examArchivesDirPath));\n log.info(\"Created the exam archives directory at {} because it didn't exist.\", examArchivesDirPath);\n\n // Export the exam to the archives directory.\n var archivedExamPath = courseExamExportService.exportExam(exam, examArchivesDirPath, exportErrors);\n\n // Attach the path to the archive to the exam and save it in the database\n if (archivedExamPath.isPresent()) {\n exam.setExamArchivePath(archivedExamPath.get().toString());\n examRepository.save(exam);\n }\n else {\n groupNotificationService.notifyInstructorGroupAboutExamArchiveState(exam, NotificationType.EXAM_ARCHIVE_FAILED, exportErrors);\n return;\n }\n }\n catch (IOException e) {\n var error = \"Failed to create exam archives directory \" + examArchivesDirPath + \": \" + e.getMessage();\n exportErrors.add(error);\n log.info(error);\n }\n\n groupNotificationService.notifyInstructorGroupAboutExamArchiveState(exam, NotificationType.EXAM_ARCHIVE_FINISHED, exportErrors);\n }\n\n /**\n * Combines the template commits of all programming exercises in the exam.\n * This is executed before the individual student exams are generated.\n *\n * @param exam - the exam which template commits should be combined\n */\n public void combineTemplateCommitsOfAllProgrammingExercisesInExam(Exam exam) {\n exam.getExerciseGroups().forEach(group -> group.getExercises().stream().filter(exercise -> exercise instanceof ProgrammingExercise).forEach(exercise -> {\n try {\n ProgrammingExercise programmingExerciseWithTemplateParticipation = programmingExerciseRepository\n .findByIdWithTemplateAndSolutionParticipationElseThrow(exercise.getId());\n gitService.combineAllCommitsOfRepositoryIntoOne(programmingExerciseWithTemplateParticipation.getTemplateParticipation().getVcsRepositoryUrl());\n log.debug(\"Finished combination of template commits for programming exercise {}\", programmingExerciseWithTemplateParticipation.toString());\n }\n catch (InterruptedException | GitAPIException e) {\n log.error(\"An error occurred when trying to combine template commits for exam \" + exam.getId() + \".\", e);\n }\n }));\n }\n}\n" }, { "alpha_fraction": 0.7340530157089233, "alphanum_fraction": 0.7576054930686951, "avg_line_length": 49.95000076293945, "blob_id": "f318d25b611b6aa8dc33408f376f23ba73dde371", "content_id": "10e981a2da3017002b5df7440395e7d091054a30", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1019, "license_type": "permissive", "max_line_length": 176, "num_lines": 20, "path": "/src/main/docker/bamboo/Dockerfile", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "FROM atlassian/bamboo-server:7.1.2\n\nLABEL description=\"Bamboo pre-configured for Artemis\"\n\nUSER root\nENV DEBIAN_FRONTEND noninteractive\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n software-properties-common \\\n apt-utils \\\n maven=3.6.0*\nRUN add-apt-repository -y ppa:linuxuprising/java\nRUN echo debconf shared/accepted-oracle-license-v1-2 select true | debconf-set-selections && echo debconf shared/accepted-oracle-license-v1-2 seen true | debconf-set-selections\nRUN apt-get install -y oracle-java15-installer\nRUN update-alternatives --install /usr/bin/java java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1\nRUN update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java\n# Add file in /artemis/bin/mvn that uses the correct java version and passes all arguments to mvn\nRUN mkdir /artemis && mkdir /artemis/bin && printf '#!/bin/bash\\nJAVA_HOME=/usr/lib/jvm/java-15-oracle /usr/bin/mvn \"$@\"\\n' > /artemis/bin/mvn && chmod 777 /artemis/bin/mvn\n\nUSER ${BAMBOO_USER}\n" }, { "alpha_fraction": 0.5843980312347412, "alphanum_fraction": 0.5863520503044128, "avg_line_length": 33.832462310791016, "blob_id": "b67cc3f01a33f369d0ae517a4a7e02225958a385", "content_id": "2c0ad1c8aef1d84ab80f4f73ebcf4a7a2a4f2e06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6653, "license_type": "permissive", "max_line_length": 143, "num_lines": 191, "path": "/src/main/webapp/app/admin/user-management/user-management.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, Data, ParamMap, Router } from '@angular/router';\nimport { JhiEventManager, JhiParseLinks } from 'ng-jhipster';\nimport { Subscription } from 'rxjs/Subscription';\nimport { onError } from 'app/shared/util/global.utils';\nimport { User } from 'app/core/user/user.model';\nimport { UserService } from 'app/core/user/user.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { combineLatest, Subject } from 'rxjs';\nimport { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { SortingOrder } from 'app/shared/table/pageable-table';\nimport { debounceTime, switchMap, tap } from 'rxjs/operators';\nimport { AbstractControl, FormControl, FormGroup } from '@angular/forms';\n\n@Component({\n selector: 'jhi-user-management',\n templateUrl: './user-management.component.html',\n})\nexport class UserManagementComponent implements OnInit, OnDestroy {\n search = new Subject<string>();\n loadingSearchResult = false;\n currentAccount?: User;\n users: User[];\n userListSubscription?: Subscription;\n totalItems = 0;\n itemsPerPage = ITEMS_PER_PAGE;\n page!: number;\n predicate!: string;\n ascending!: boolean;\n searchTermString = '';\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n userSearchForm: FormGroup;\n\n constructor(\n private userService: UserService,\n private alertService: JhiAlertService,\n private accountService: AccountService,\n private parseLinks: JhiParseLinks,\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private eventManager: JhiEventManager,\n ) {\n this.search\n .pipe(\n tap(() => (this.loadingSearchResult = true)),\n debounceTime(1000),\n switchMap(() =>\n this.userService.query({\n page: this.page - 1,\n pageSize: this.itemsPerPage,\n searchTerm: this.searchTermString,\n sortingOrder: this.ascending ? SortingOrder.ASCENDING : SortingOrder.DESCENDING,\n sortedColumn: this.predicate,\n }),\n ),\n )\n .subscribe(\n (res: HttpResponse<User[]>) => {\n this.loadingSearchResult = false;\n this.onSuccess(res.body || [], res.headers);\n },\n (res: HttpErrorResponse) => {\n this.loadingSearchResult = false;\n onError(this.alertService, res);\n },\n );\n }\n\n /**\n * Retrieves the current user and calls the {@link loadAll} and {@link registerChangeInUsers} methods on init\n */\n ngOnInit(): void {\n this.userSearchForm = new FormGroup({\n searchControl: new FormControl('', { validators: [this.validateUserSearch], updateOn: 'blur' }),\n });\n this.accountService.identity().then((user) => {\n this.currentAccount = user!;\n this.userListSubscription = this.eventManager.subscribe('userListModification', () => this.loadAll());\n this.handleNavigation();\n });\n }\n\n /**\n * clean up the subscriptions\n */\n ngOnDestroy(): void {\n if (this.userListSubscription) {\n this.eventManager.destroy(this.userListSubscription);\n }\n this.dialogErrorSource.unsubscribe();\n }\n\n /**\n * Update the user's activation status\n * @param user whose activation status should be changed\n * @param isActivated true if user should be activated, otherwise false\n */\n setActive(user: User, isActivated: boolean) {\n user.activated = isActivated;\n this.userService.update(user).subscribe(() => {\n this.loadAll();\n });\n }\n\n /**\n * Retrieve the list of users from the user service for a single page in the user management based on the page, size and sort configuration\n */\n loadAll() {\n if (this.searchTerm.length >= 3 || this.searchTerm.length === 0) {\n this.search.next();\n }\n }\n\n /**\n * Returns the unique identifier for items in the collection\n * @param index of a user in the collection\n * @param item current user\n */\n trackIdentity(index: number, item: User) {\n return item.id;\n }\n\n /**\n * Transitions to another page and/or sorting order\n */\n transition(): void {\n this.router.navigate(['/admin/user-management'], {\n relativeTo: this.activatedRoute.parent,\n queryParams: {\n page: this.page,\n sort: this.predicate + ',' + (this.ascending ? 'asc' : 'desc'),\n },\n });\n }\n\n private handleNavigation(): void {\n combineLatest(this.activatedRoute.data, this.activatedRoute.queryParamMap, (data: Data, params: ParamMap) => {\n const page = params.get('page');\n this.page = page !== null ? +page : 1;\n const sort = (params.get('sort') ?? data['defaultSort']).split(',');\n this.predicate = sort[0];\n this.ascending = sort[1] === 'asc';\n this.loadAll();\n }).subscribe();\n }\n\n /**\n * Deletes a user\n * @param login of the user that should be deleted\n */\n deleteUser(login: string) {\n this.userService.delete(login).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'userListModification',\n content: 'Deleted a user',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n private onSuccess(users: User[], headers: HttpHeaders) {\n this.totalItems = Number(headers.get('X-Total-Count'));\n this.users = users;\n }\n\n set searchTerm(searchTerm: string) {\n this.searchTermString = searchTerm;\n }\n\n get searchTerm(): string {\n return this.searchTermString;\n }\n\n validateUserSearch(control: AbstractControl) {\n if (control.value.length >= 1 && control.value.length <= 2) {\n return { searchControl: true };\n }\n return null;\n }\n\n get searchControl() {\n return this.userSearchForm.get('searchControl')!;\n }\n}\n" }, { "alpha_fraction": 0.774760365486145, "alphanum_fraction": 0.774760365486145, "avg_line_length": 49.08000183105469, "blob_id": "c0675e19b9e74f87ba17845704df88379a5c57cf", "content_id": "ddea25810714f703940de0a2a48047d62dbb63a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1252, "license_type": "permissive", "max_line_length": 167, "num_lines": 25, "path": "/src/main/webapp/app/exercises/programming/assess/programming-assessment-dashboard/programming-assessment-dashboard.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ProgrammingAssessmentDashboardComponent } from 'app/exercises/programming/assess/programming-assessment-dashboard/programming-assessment-dashboard.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { AssessmentInstructionsModule } from 'app/assessment/assessment-instructions/assessment-instructions.module';\nimport { FormsModule } from '@angular/forms';\nimport { RouterModule } from '@angular/router';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n FormDateTimePickerModule,\n FormsModule,\n FeatureToggleModule,\n AssessmentInstructionsModule,\n RouterModule.forChild([]),\n ArtemisResultModule,\n ArtemisAssessmentSharedModule,\n ],\n declarations: [ProgrammingAssessmentDashboardComponent],\n})\nexport class ArtemisProgrammingAssessmentDashboardModule {}\n" }, { "alpha_fraction": 0.8110687136650085, "alphanum_fraction": 0.8120229244232178, "avg_line_length": 36.42856979370117, "blob_id": "2ffbace602b336ff7aa1b13b7ded9233b3b79a6d", "content_id": "2b24f99d9e599875ddbd91d08148b6e1c963b2bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1048, "license_type": "permissive", "max_line_length": 150, "num_lines": 28, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/gitlab/GitLabAuthorizationInterceptor.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.gitlab;\n\nimport java.io.IOException;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.HttpRequest;\nimport org.springframework.http.client.ClientHttpRequestExecution;\nimport org.springframework.http.client.ClientHttpRequestInterceptor;\nimport org.springframework.http.client.ClientHttpResponse;\nimport org.springframework.stereotype.Component;\n\n@Profile(\"gitlab\")\n@Component\npublic class GitLabAuthorizationInterceptor implements ClientHttpRequestInterceptor {\n\n @Value(\"${artemis.version-control.token}\")\n private String gitlabPrivateToken;\n\n @NotNull\n @Override\n public ClientHttpResponse intercept(HttpRequest request, @NotNull byte[] body, @NotNull ClientHttpRequestExecution execution) throws IOException {\n request.getHeaders().add(\"Private-Token\", gitlabPrivateToken);\n return execution.execute(request, body);\n }\n}\n" }, { "alpha_fraction": 0.6833095550537109, "alphanum_fraction": 0.6833095550537109, "avg_line_length": 27.040000915527344, "blob_id": "aa01f671eadfddb16ca84154623bb64c7b04155e", "content_id": "1f99f36ae6cab5108b48bcacacce7d45d9ef75f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 701, "license_type": "permissive", "max_line_length": 122, "num_lines": 25, "path": "/src/main/webapp/app/shared/markdown-editor/domainCommands/programming-exercise/task-hint.command.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { DomainMultiOptionListCommand } from 'app/shared/markdown-editor/domainCommands/domain-multi-option-list.command';\n\nexport class TaskHintCommand extends DomainMultiOptionListCommand {\n buttonTranslationString = 'artemisApp.programmingExercise.problemStatement.exerciseHintCommand';\n\n protected getValueMeta(): string {\n return 'exerciseHint';\n }\n\n /**\n * @function getOpeningIdentifier\n * @desc identify the start of the task\n */\n getOpeningIdentifier(): string {\n return '{';\n }\n\n /**\n * @function getClosingIdentifier\n * @desc identify the end of the explanation\n */\n getClosingIdentifier(): string {\n return '}';\n }\n}\n" }, { "alpha_fraction": 0.6398428082466125, "alphanum_fraction": 0.6417288780212402, "avg_line_length": 51.80083084106445, "blob_id": "52f8249ade9ff0a38742603f3072b4214199dea9", "content_id": "3593fcf50eec8dab7756d8c40e58f7c74f3eb02f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12725, "license_type": "permissive", "max_line_length": 133, "num_lines": 241, "path": "/src/test/javascript/spec/component/exam-exercise-row-buttons/exam-exercise-row-buttons.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { NO_ERRORS_SCHEMA } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { CookieService } from 'ngx-cookie-service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ExamExerciseRowButtonsComponent } from 'app/exercises/shared/exam-exercise-row-buttons/exam-exercise-row-buttons.component';\nimport { Course } from 'app/entities/course.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { Exam } from 'app/entities/exam.model';\nimport * as moment from 'moment';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { SinonSpy, SinonStub, stub } from 'sinon';\nimport { of, throwError } from 'rxjs';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport * as sinon from 'sinon';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ExamExerciseRowButtonsComponent', () => {\n const course = { id: 3 } as Course;\n const exam = { id: 4 } as Exam;\n\n let modelingExerciseService: ModelingExerciseService;\n let textExerciseService: TextExerciseService;\n let quizExerciseService: QuizExerciseService;\n let fileUploadExerciseService: FileUploadExerciseService;\n let programmingExerciseService: ProgrammingExerciseService;\n\n const modelingExercise = { id: 123, type: ExerciseType.MODELING } as ModelingExercise;\n const textExercise = { id: 234, type: ExerciseType.TEXT } as TextExercise;\n const quizExercise = { id: 345, type: ExerciseType.QUIZ } as QuizExercise;\n const fileUploadExercise = { id: 456, type: ExerciseType.FILE_UPLOAD } as FileUploadExercise;\n const programmingExercise = { id: 963, type: ExerciseType.PROGRAMMING } as ProgrammingExercise;\n const quizResponse = { body: { id: 789, type: ExerciseType.QUIZ, quizQuestions: {} } as QuizExercise };\n\n let deleteTextExerciseStub: SinonStub;\n let deleteModelingExerciseStub: SinonStub;\n let deleteQuizExercsieStub: SinonStub;\n let deleteFileUploadExerciseStub: SinonStub;\n let deleteProgrammingExerciseStub: SinonStub;\n let quizExerciseServiceFindStub: SinonStub;\n\n let onDeleteExerciseEmitSpy: SinonSpy;\n let quizExerciseExportSpy: SinonSpy;\n\n let fixture: ComponentFixture<ExamExerciseRowButtonsComponent>;\n let component: ExamExerciseRowButtonsComponent;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n ArtemisSharedModule,\n RouterTestingModule.withRoutes([\n {\n path: 'courses',\n component: ExamExerciseRowButtonsComponent,\n },\n ]),\n ],\n declarations: [ExamExerciseRowButtonsComponent],\n schemas: [NO_ERRORS_SCHEMA],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: DeviceDetectorService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExamExerciseRowButtonsComponent);\n component = fixture.debugElement.componentInstance;\n textExerciseService = TestBed.inject(TextExerciseService);\n modelingExerciseService = TestBed.inject(ModelingExerciseService);\n fileUploadExerciseService = TestBed.inject(FileUploadExerciseService);\n quizExerciseService = TestBed.inject(QuizExerciseService);\n programmingExerciseService = TestBed.inject(ProgrammingExerciseService);\n component.course = course;\n component.exam = exam;\n\n deleteTextExerciseStub = stub(textExerciseService, 'delete');\n deleteModelingExerciseStub = stub(modelingExerciseService, 'delete');\n deleteQuizExercsieStub = stub(quizExerciseService, 'delete');\n deleteFileUploadExerciseStub = stub(fileUploadExerciseService, 'delete');\n deleteProgrammingExerciseStub = stub(programmingExerciseService, 'delete');\n quizExerciseServiceFindStub = stub(quizExerciseService, 'find');\n onDeleteExerciseEmitSpy = sinon.spy(component.onDeleteExercise, 'emit');\n quizExerciseExportSpy = sinon.spy(quizExerciseService, 'exportQuiz');\n });\n });\n describe('isExamOver', () => {\n it('should return true if over', () => {\n component.latestIndividualEndDate = moment().subtract(1, 'hours');\n expect(component.isExamOver()).is.true;\n });\n it('should return false if not yet over', () => {\n component.latestIndividualEndDate = moment().add(1, 'hours');\n expect(component.isExamOver()).is.false;\n });\n it('should return false if endDate is undefined', () => {\n expect(component.isExamOver()).is.false;\n });\n });\n describe('hasExamStarted', () => {\n it('should return true if started', () => {\n component.exam.startDate = moment().subtract(1, 'hours');\n expect(component.hasExamStarted()).is.true;\n });\n it('should return false if not yet started', () => {\n component.exam.startDate = moment().add(1, 'hours');\n expect(component.hasExamStarted()).is.false;\n });\n it('should return false if startDate is undefined', () => {\n expect(component.hasExamStarted()).is.false;\n });\n });\n describe('deleteExercise', () => {\n describe('deleteTextExercise', () => {\n it('should deleteTextExercise', () => {\n deleteTextExerciseStub.returns(of({}));\n component.exercise = textExercise;\n component.deleteExercise();\n expect(deleteTextExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.have.been.calledOnce;\n });\n it('should handle error for textexercise', () => {\n const error = { message: 'error occured!' } as HttpErrorResponse;\n deleteTextExerciseStub.returns(throwError(error));\n component.exercise = textExercise;\n component.deleteExercise();\n expect(deleteTextExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.not.have.been.calledOnce;\n });\n });\n describe('deleteModelingExercise', () => {\n it('should deleteModelingExercise', () => {\n deleteModelingExerciseStub.returns(of({}));\n component.exercise = modelingExercise;\n component.deleteExercise();\n expect(deleteModelingExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.have.been.calledOnce;\n });\n it('should handle error for modelingexercise', () => {\n const error = { message: 'error occured!' } as HttpErrorResponse;\n deleteModelingExerciseStub.returns(throwError(error));\n component.exercise = modelingExercise;\n component.deleteExercise();\n expect(deleteModelingExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.not.have.been.called;\n });\n });\n describe('deleteFileUploadExercise', () => {\n it('should deleteFileUploadExercise', () => {\n deleteFileUploadExerciseStub.returns(of({}));\n component.exercise = fileUploadExercise;\n component.deleteExercise();\n expect(deleteFileUploadExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.have.been.calledOnce;\n });\n it('should handle error for fileupload exercise', () => {\n const error = { message: 'error occured!' } as HttpErrorResponse;\n deleteFileUploadExerciseStub.returns(throwError(error));\n component.exercise = fileUploadExercise;\n component.deleteExercise();\n expect(deleteFileUploadExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.not.have.been.called;\n });\n });\n describe('should deleteQuizExercise', () => {\n it('should deleteQuizExercise', () => {\n deleteQuizExercsieStub.returns(of({}));\n component.exercise = quizExercise;\n component.deleteExercise();\n expect(deleteQuizExercsieStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.have.been.calledOnce;\n });\n it('should handle error for quizexercise', () => {\n const error = { message: 'error occured!' } as HttpErrorResponse;\n deleteQuizExercsieStub.returns(throwError(error));\n component.exercise = quizExercise;\n component.deleteExercise();\n expect(deleteQuizExercsieStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.not.have.been.called;\n });\n });\n });\n describe('deleteProgrammingExercise', () => {\n it('should deleteProgrammingExercise', () => {\n deleteProgrammingExerciseStub.returns(of({}));\n component.exercise = programmingExercise;\n component.deleteProgrammingExercise({});\n expect(deleteProgrammingExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.have.been.calledOnce;\n });\n it('should handle error for programmingExercise', () => {\n const error = { message: 'error occured!' } as HttpErrorResponse;\n deleteProgrammingExerciseStub.returns(throwError(error));\n component.exercise = programmingExercise;\n component.deleteProgrammingExercise({});\n expect(deleteProgrammingExerciseStub).to.have.been.calledOnce;\n expect(onDeleteExerciseEmitSpy).to.not.have.been.called;\n });\n });\n describe('exportQuizById', () => {\n it('should export Quiz, exportAll true', () => {\n quizExerciseServiceFindStub.returns(of(quizResponse));\n component.exercise = quizExercise;\n component.exportQuizById(true);\n expect(quizExerciseExportSpy).to.have.been.called;\n expect(quizExerciseExportSpy).to.have.been.calledWith({}, true);\n });\n it('should export Quiz, exportAll false', () => {\n quizExerciseServiceFindStub.returns(of(quizResponse));\n component.exercise = quizExercise;\n component.exportQuizById(false);\n expect(quizExerciseExportSpy).to.have.been.called;\n expect(quizExerciseExportSpy).to.have.been.calledWith({}, false);\n });\n });\n});\n" }, { "alpha_fraction": 0.6457482576370239, "alphanum_fraction": 0.6479762196540833, "avg_line_length": 38.60293960571289, "blob_id": "a58c1d8bdb329ad82123783f962a8d985ed9223c", "content_id": "16da1d4bcd6143dc3a8f9e744eba98694ff7be12", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2693, "license_type": "permissive", "max_line_length": 124, "num_lines": 68, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\n\nimport { ArtemisTestModule } from '../../test.module';\nimport { ProgrammingExerciseDetailComponent } from 'app/exercises/programming/manage/programming-exercise-detail.component';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { TranslateModule } from '@ngx-translate/core';\n\ndescribe('ProgrammingExercise Management Detail Component', () => {\n let comp: ProgrammingExerciseDetailComponent;\n let fixture: ComponentFixture<ProgrammingExerciseDetailComponent>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot()],\n declarations: [ProgrammingExerciseDetailComponent],\n providers: [{ provide: ActivatedRoute, useValue: new MockActivatedRoute() }],\n })\n .overrideTemplate(ProgrammingExerciseDetailComponent, '')\n .compileComponents();\n fixture = TestBed.createComponent(ProgrammingExerciseDetailComponent);\n comp = fixture.componentInstance;\n });\n\n describe('OnInit for course exercise', () => {\n const programmingExercise = new ProgrammingExercise(new Course(), undefined);\n programmingExercise.id = 123;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.data = of({ programmingExercise });\n });\n\n it('Should not be in exam mode', () => {\n // WHEN\n comp.ngOnInit();\n\n // THEN\n expect(comp.programmingExercise).toEqual(programmingExercise);\n expect(comp.isExamExercise).toBeFalsy();\n });\n });\n\n describe('OnInit for exam exercise', () => {\n const exerciseGroup = new ExerciseGroup();\n const programmingExercise = new ProgrammingExercise(undefined, undefined);\n programmingExercise.id = 123;\n programmingExercise.exerciseGroup = exerciseGroup;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.data = of({ programmingExercise });\n });\n\n it('Should be in exam mode', () => {\n // WHEN\n comp.ngOnInit();\n\n // THEN\n expect(comp.programmingExercise).toEqual(programmingExercise);\n expect(comp.isExamExercise).toBeTruthy();\n });\n });\n});\n" }, { "alpha_fraction": 0.6658614873886108, "alphanum_fraction": 0.6658614873886108, "avg_line_length": 31.6842098236084, "blob_id": "e099c8ce16b229899e018a90b6ae34daf228b694", "content_id": "998df7530730e38d5e58240ef3214d682e36b508", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1242, "license_type": "permissive", "max_line_length": 103, "num_lines": 38, "path": "/src/test/javascript/spec/service/password.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonStub, stub } from 'sinon';\nimport { MockHttpService } from '../helpers/mocks/service/mock-http.service';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { PasswordService } from 'app/account/password/password.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ActivateService', () => {\n let passwordService: PasswordService;\n let httpService: MockHttpService;\n let postStub: SinonStub;\n\n const postURL = SERVER_API_URL + 'api/account/change-password';\n\n beforeEach(async(() => {\n httpService = new MockHttpService();\n // @ts-ignore\n passwordService = new PasswordService(httpService);\n postStub = stub(httpService, 'post');\n }));\n\n afterEach(() => {\n postStub.restore();\n });\n\n it('should set a new password for the current user', async () => {\n const newPassword = 'newPassword';\n const currentPassword = 'currentPassword';\n\n await passwordService.save(newPassword, currentPassword);\n\n expect(postStub).to.have.been.calledOnceWithExactly(postURL, { currentPassword, newPassword });\n });\n});\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 34.0625, "blob_id": "a607e16b49453f30d8112993e0426644873e7ea3", "content_id": "ccd086f3b6a66d6031c22e9abdeae85c2d5c77de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1122, "license_type": "permissive", "max_line_length": 116, "num_lines": 32, "path": "/src/main/webapp/app/overview/course-exams/course-exam-detail/course-exam-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { Router } from '@angular/router';\nimport { Exam } from 'app/entities/exam.model';\nimport { Course } from 'app/entities/course.model';\nimport * as moment from 'moment';\n\n@Component({\n selector: 'jhi-course-exam-detail',\n templateUrl: './course-exam-detail.component.html',\n})\nexport class CourseExamDetailComponent {\n @Input() exam: Exam;\n @Input() course: Course;\n\n constructor(private router: Router) {}\n\n /**\n * navigate to /courses/:courseid/exams/:examId\n */\n openExam(): void {\n this.router.navigate(['courses', this.course.id, 'exams', this.exam.id]);\n // TODO: store the (plain) selected exam in the some service so that it can be obtained on other pages\n // also make sure that the exam objects does not contain the course and all exercises\n }\n\n /**\n * calculate the duration in minutes between the start and end date of the exam\n */\n get examDuration(): number {\n return Math.round(moment.duration(moment(this.exam.endDate).diff(moment(this.exam.startDate))).asMinutes());\n }\n}\n" }, { "alpha_fraction": 0.6950185298919678, "alphanum_fraction": 0.7083995938301086, "avg_line_length": 38.51832580566406, "blob_id": "bee98bdd547d4efbb1447e43330cdc6cb5e4de6b", "content_id": "d80e4aeba96849433d5776f1e91863209049b58f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7548, "license_type": "permissive", "max_line_length": 95, "num_lines": 191, "path": "/src/test/java/de/tum/in/www1/artemis/service/CourseServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.ArrayList;\nimport java.util.HashSet;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.TextSubmission;\nimport de.tum.in.www1.artemis.domain.enumeration.Language;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class CourseServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private CourseService courseService;\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private SubmissionRepository submissionRepository;\n\n @Autowired\n private StudentParticipationRepository studentParticipationRepo;\n\n @Autowired\n private ExerciseRepository exerciseRepo;\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n public void testGetActiveStudents() {\n SecurityUtils.setAuthorizationObject();\n var course = database.addEmptyCourse();\n var now = ZonedDateTime.now();\n var exercise = ModelFactory.generateTextExercise(now, now, now, course);\n course.addExercises(exercise);\n exercise = exerciseRepo.save(exercise);\n\n var users = database.addUsers(2, 0, 0);\n var student1 = users.get(0);\n var participation1 = new StudentParticipation();\n participation1.setParticipant(student1);\n participation1.exercise(exercise);\n studentParticipationRepo.save(participation1);\n var student2 = users.get(1);\n var participation2 = new StudentParticipation();\n participation2.setParticipant(student2);\n participation2.exercise(exercise);\n studentParticipationRepo.save(participation2);\n var participation3 = new StudentParticipation();\n participation3.setParticipant(student2);\n participation3.exercise(exercise);\n studentParticipationRepo.save(participation3);\n var participation4 = new StudentParticipation();\n participation4.setParticipant(student2);\n participation4.exercise(exercise);\n studentParticipationRepo.save(participation4);\n\n var submission1 = new TextSubmission();\n submission1.text(\"text of text submission1\");\n submission1.setLanguage(Language.ENGLISH);\n submission1.setSubmitted(true);\n submission1.setParticipation(participation1);\n submission1.setSubmissionDate(now);\n\n var submission2 = new TextSubmission();\n submission2.text(\"text of text submission2\");\n submission2.setLanguage(Language.ENGLISH);\n submission2.setSubmitted(true);\n submission2.setParticipation(participation2);\n submission2.setSubmissionDate(now);\n\n var submission3 = new TextSubmission();\n submission3.text(\"text of text submission3\");\n submission3.setLanguage(Language.ENGLISH);\n submission3.setSubmitted(true);\n submission3.setSubmissionDate(now.minusDays(14));\n submission3.setParticipation(participation3);\n\n var submission4 = new TextSubmission();\n submission4.text(\"text of text submission4\");\n submission4.setLanguage(Language.ENGLISH);\n submission4.setSubmitted(true);\n submission4.setSubmissionDate(now.minusDays(7));\n submission4.setParticipation(participation4);\n\n submissionRepository.save(submission1);\n submissionRepository.save(submission2);\n submissionRepository.save(submission3);\n submissionRepository.save(submission4);\n\n var exerciseList = new ArrayList<Long>();\n exerciseList.add(exercise.getId());\n var activeStudents = courseService.getActiveStudents(exerciseList);\n assertThat(activeStudents.length).isEqualTo(4);\n assertThat(activeStudents).isEqualTo(new Integer[] { 0, 1, 1, 2 });\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void testGetOverviewAsAdmin() {\n // Minimal testcase: Admins always see all courses\n // Add two courses, one not active\n database.addEmptyCourse();\n var inactiveCourse = database.createCourse();\n inactiveCourse.setEndDate(ZonedDateTime.now().minusDays(7));\n courseRepository.save(inactiveCourse);\n\n // 'addUsers' adds the admin as well\n database.addUsers(0, 0, 0);\n\n var courses = courseService.getAllCoursesForManagementOverview(false);\n assertThat(courses.size()).isEqualTo(2);\n\n courses = courseService.getAllCoursesForManagementOverview(true);\n assertThat(courses.size()).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetOverviewAsInstructor() {\n // Testcase: Instructors see their courses\n // Add three courses, containing one not active and one not belonging to the instructor\n database.addEmptyCourse();\n var inactiveCourse = database.createCourse();\n inactiveCourse.setEndDate(ZonedDateTime.now().minusDays(7));\n inactiveCourse.setInstructorGroupName(\"test-instructors\");\n courseRepository.save(inactiveCourse);\n var instructorsCourse = database.createCourse();\n instructorsCourse.setInstructorGroupName(\"test-instructors\");\n courseRepository.save(instructorsCourse);\n\n var users = database.addUsers(0, 0, 1);\n var instructor = users.get(0);\n var groups = new HashSet<String>();\n groups.add(\"test-instructors\");\n instructor.setGroups(groups);\n userRepository.save(instructor);\n\n var courses = courseService.getAllCoursesForManagementOverview(false);\n assertThat(courses.size()).isEqualTo(2);\n\n courses = courseService.getAllCoursesForManagementOverview(true);\n assertThat(courses.size()).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(value = \"student1\", roles = \"USER\")\n public void testGetOverviewAsStudent() {\n // Testcase: Students should not see courses\n // Add three courses, containing one not active and one not belonging to the student\n database.addEmptyCourse();\n var inactiveCourse = database.createCourse();\n inactiveCourse.setEndDate(ZonedDateTime.now().minusDays(7));\n inactiveCourse.setStudentGroupName(\"test-students\");\n courseRepository.save(inactiveCourse);\n var instructorsCourse = database.createCourse();\n instructorsCourse.setStudentGroupName(\"test-students\");\n courseRepository.save(instructorsCourse);\n\n var users = database.addUsers(1, 0, 0);\n var student = users.get(0);\n var groups = new HashSet<String>();\n groups.add(\"test-students\");\n student.setGroups(groups);\n userRepository.save(student);\n\n var courses = courseService.getAllCoursesForManagementOverview(false);\n assertThat(courses.size()).isEqualTo(0);\n\n courses = courseService.getAllCoursesForManagementOverview(true);\n assertThat(courses.size()).isEqualTo(0);\n }\n}\n" }, { "alpha_fraction": 0.8289963006973267, "alphanum_fraction": 0.8289963006973267, "avg_line_length": 66.25, "blob_id": "470651cd763741176982728cb9adf0fb5ce4bba1", "content_id": "557358c59f4d0d03fdc0a738527fd123b798f976", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 807, "license_type": "permissive", "max_line_length": 141, "num_lines": 12, "path": "/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-solution.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisModelingEditorModule } from 'app/exercises/modeling/shared/modeling-editor.module';\nimport { ExampleModelingSolutionComponent } from 'app/exercises/modeling/manage/example-modeling/example-modeling-solution.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisExampleModelingSolutionRoutingModule } from 'app/exercises/modeling/manage/example-modeling/example-modeling-solution.route';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisModelingEditorModule, ArtemisExampleModelingSolutionRoutingModule, ArtemisMarkdownModule],\n declarations: [ExampleModelingSolutionComponent],\n})\nexport class ArtemisExampleModelingSolutionModule {}\n" }, { "alpha_fraction": 0.7784408926963806, "alphanum_fraction": 0.7825438380241394, "avg_line_length": 69.5526351928711, "blob_id": "85d19fbfd93c985f2691a8c803061ddb8935f4ef", "content_id": "348bf016415b46184eebf1700e831632c7fd8278", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 5427, "license_type": "permissive", "max_line_length": 186, "num_lines": 76, "path": "/src/main/resources/public/content/privacy_statement.html", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<p>\n Der <a href=\"https://ase.in.tum.de/\" target=\"_blank\" rel=\"external noopener noreferrer\">Lehrstuhl für Angewandte Softwaretechnik</a> (LS1) der Technischen Universität München\n (TUM) nimmt den Schutz von personenbezogenen Daten sehr ernst und nutzt eine sichere und verschlüsselte Kommunikation nach bewährten Verfahren und modernsten Technologien\n (HTTPS mit sicherem Zeritifkat der TUM, TLS 1.3, Strict Transport Security, Forward Secrecy, Same Site Cookie Schutz, etc.) um die Privatssphäre der Nutzer von Artemis bestmöglich zu\n schützen. Wir verarbeiten personenbezogene Daten, die beim Besuch unserer Webseiten erhoben werden, unter Beachtung der geltenden datenschutzrechtlichen Bestimmungen,\n insbesondere dem <a href=\"http://gesetze-bayern.de/Content/Document/BayDSG\" target=\"_blank\" rel=\"external noopener noreferrer\">Bayrischen Datenschutz (BayDSG)</a>, dem\n <a href=\"http://www.gesetze-im-internet.de/tmg/\" target=\"_blank\" rel=\"external noopener noreferrer\">Telemediengesetz (TMG)</a> und der\n <a href=\"http://data.europa.eu/eli/reg/2016/679/oj\" target=\"_blank\" rel=\"external noopener noreferrer\">Datenschutz Grundverordnung (DSGVO)</a>.\n</p>\n<p>\n Nachfolgend informieren wir Sie über Art, Umfang und Zweck der Erhebung und Verwendung personenbezogener Daten. Diese Informationen können jederzeit von unserer Webseite\n abgerufen werden.\n</p>\n<p></p>\n\n<h4 id=\"TechnischeUmsetzung\">Technische Umsetzung</h4>\n<p>\n Die Webserver der Artemis Plattform werden durch den Lehrstuhl für Angewandte Softwaretechnik in Zusammenarbeit mit der\n <a href=\"https://www.rbg.tum.de\" target=\"_blank\" rel=\"external noopener noreferrer\">Rechnerbetriebsgruppe</a> der Technischen Universität München und dem\n <a href=\"https://www.lrz.de\" target=\"_blank\" rel=\"external noopener noreferrer\">Leibniz-Rechenzentrum (LRZ)</a> betrieben.\n</p>\n<p></p>\n\n<h4 id=\"Protokollierung\">Protokollierung</h4>\n<p>\n Wenn Sie diese oder andere Internetseiten von Artemis aufrufen, übermitteln Sie über Ihren Internetbrowser Daten an unseren Webserver. Die folgenden Daten können während einer\n laufenden Verbindung zur Kommunikation zwischen Ihrem Internetbrowser und unserem Webserver temporär in einer Logdatei aufgezeichnet werden:\n</p>\n<ul>\n <li>IP-Adresse des anfragenden Rechners</li>\n <li>Datum und Uhrzeit des Zugriffs</li>\n <li>Name, URL und übertragene Datenmenge der abgerufenen Datei</li>\n <li>Zugriffsstatus (angeforderte Datei übertragen, nicht gefunden etc.)</li>\n <li>Erkennungsdaten des verwendeten Browser- und Betriebssystems (sofern vom anfragenden Webbrowser übermittelt)</li>\n <li>Webseite, von der aus der Zugriff erfolgte (sofern vom anfragenden Webbrowser übermittelt)</li>\n</ul>\n<p>Die Verarbeitung der Daten in dieser Logdatei kann wie folgt geschehen:</p>\n<ul>\n <li>Die Logeinträge können kontinuierlich und automatisch ausgewertet werden, um Angriffe auf die Webserver erkennen und entsprechend reagieren zu können.</li>\n <li>In Einzelfällen, d.h. bei gemeldeten Störungen, Fehlern und Sicherheitsvorfällen, kann eine manuelle Analyse erfolgen.</li>\n</ul>\n<p></p>\n\n<h4 id=\"Cookies\">Cookies</h4>\n<p>\n Um den Funktionsumfang unseres Internetangebotes zu erweitern und die Nutzung für Sie komfortabler zu gestalten, verwenden wir zum Teil so genannte „Cookies\". Mit Hilfe dieser\n Cookies können bei dem Aufruf unserer Webseite Daten auf Ihrem Rechner gespeichert werden. Sie können das Speichern von Cookies jedoch deaktivieren oder Ihren Browser so\n einstellen, dass Cookies nur für die Dauer der jeweiligen Verbindung zum Internet gespeichert werden. Hierdurch könnte allerdings der Funktionsumfang unseres Angebotes\n eingeschränkt werden.\n</p>\n<p></p>\n\n<h4 id=\"Email\">E-Mail Kommunikation</h4>\n<p>\n Informationen, die Sie unverschlüsselt per E-Mail an uns senden, können möglicherweise auf dem Übertragungsweg von Dritten gelesen werden. Wir können in der Regel auch Ihre\n Identität nicht überprüfen und wissen nicht, wer sich hinter einer E-Mail Adresse verbirgt. Eine rechtssichere Kommunikation durch einfache E-Mail ist daher nicht\n gewährleistet.\n</p>\n<p></p>\n\n<h4 id=\"Aenderung\">Änderung der Datenschutzerklärung</h4>\n<p>\n Wir behalten uns vor, unsere Datenschutzerklärung gelegentlich anzupassen, damit sie stets den aktuellen rechtlichen Anforderungen entspricht oder um Änderungen unserer\n Leistungen in der Datenschutzerklärung umzusetzen. Wir empfehlen Ihnen, diese Datenschutzerklärung regelmäßig zu lesen, um über den Schutz der von uns erfassten persönlichen\n Daten auf dem Laufenden zu bleiben. Durch die fortgesetzte Nutzung der Artemis Plattform erklären Sie sich mit dieser Datenschutzerklärung und deren Aktualisierung\n einverstanden.\n</p>\n<p></p>\n\n<h4 id=\"Auskunft\">Auskunft und Berichtigung</h4>\n<p>\n Sie haben das Recht, auf schriftlichen Antrag und unentgeltlich Auskunft über die personenbezogenen Daten zu erhalten, die über Sie gespeichert sind. Zusätzlich haben Sie das\n Recht auf Berichtigung unrichtiger Daten, Sperrung und Löschung. Den behördlichen Datenschutzbeauftragten der Technischen Universität München erreichen Sie per E-Mail unter\n beauftragter(at)datenschutz.tum.de oder über <a href=\"https://www.datenschutz.tum.de/\" target=\"_blank\" rel=\"external noopener noreferrer\">www.datenschutz.tum.de</a>.\n</p>\n<p></p>\n" }, { "alpha_fraction": 0.6416496634483337, "alphanum_fraction": 0.644586980342865, "avg_line_length": 42.10594177246094, "blob_id": "ee5a04cc91f2ea3fd92c240cbb02934503715a9b", "content_id": "313c14b58a44064b5a5b7f1d1ebc4669b534d920", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16682, "license_type": "permissive", "max_line_length": 152, "num_lines": 387, "path": "/src/test/javascript/spec/component/modeling-assessment-dashboard/modeling-assessment-dashboard.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule, TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { Router } from '@angular/router';\nimport { of, Subscription } from 'rxjs';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { ModelingAssessmentDashboardComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { HttpResponse } from '@angular/common/http';\nimport { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { routes } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.route';\n\nconst route = { params: of({ courseId: 3, exerciseId: 22 }) };\nconst course = { id: 1 };\nconst modelingExercise = {\n id: 22,\n course,\n type: ExerciseType.MODELING,\n studentAssignedTeamIdComputed: true,\n assessmentType: AssessmentType.SEMI_AUTOMATIC,\n numberOfAssessmentsOfCorrectionRounds: [],\n secondCorrectionEnabled: true,\n};\nconst modelingExerciseOfExam = {\n id: 23,\n exerciseGroup: { id: 111, exam: { id: 112, course } },\n type: ExerciseType.MODELING,\n studentAssignedTeamIdComputed: true,\n assessmentType: AssessmentType.SEMI_AUTOMATIC,\n numberOfAssessmentsOfCorrectionRounds: [],\n secondCorrectionEnabled: true,\n};\nconst modelingSubmission = { id: 1, submitted: true, results: [{ id: 10, assessor: { id: 20, guidedTourSettings: [] } }] };\nconst modelingSubmission2 = { id: 2, submitted: true, results: [{ id: 20, assessor: { id: 30, guidedTourSettings: [] } }] };\nconst userId = 30;\n\ndescribe('ModelingAssessmentDashboardComponent', () => {\n let component: ModelingAssessmentDashboardComponent;\n let fixture: ComponentFixture<ModelingAssessmentDashboardComponent>;\n let exerciseService: ExerciseService;\n let courseService: CourseManagementService;\n let modelingSubmissionService: ModelingSubmissionService;\n let modelingAssessmentService: ModelingAssessmentService;\n let sortService: SortService;\n let router: Router;\n let exerciseFindSpy: jasmine.Spy;\n let courseFindSpy: jasmine.Spy;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([routes[2]]), TranslateModule.forRoot(), ArtemisTestModule],\n declarations: [ModelingAssessmentDashboardComponent],\n providers: [\n JhiLanguageHelper,\n { provide: Router, useClass: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: Router, useClass: MockRouter },\n { provide: AccountService, useClass: MockAccountService },\n ],\n })\n .overrideTemplate(ModelingAssessmentDashboardComponent, '')\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ModelingAssessmentDashboardComponent);\n component = fixture.componentInstance;\n router = fixture.debugElement.injector.get(Router);\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n courseService = fixture.debugElement.injector.get(CourseManagementService);\n modelingSubmissionService = fixture.debugElement.injector.get(ModelingSubmissionService);\n modelingAssessmentService = fixture.debugElement.injector.get(ModelingAssessmentService);\n sortService = fixture.debugElement.injector.get(SortService);\n exerciseFindSpy = spyOn(exerciseService, 'find').and.returnValue(of(new HttpResponse({ body: modelingExercise })));\n courseFindSpy = spyOn(courseService, 'find').and.returnValue(of(new HttpResponse({ body: course })));\n fixture.detectChanges();\n });\n }));\n\n afterEach(() => {\n component.ngOnDestroy();\n });\n\n it('should set parameters and call functions on init', () => {\n // setup\n const getSubmissionsSpy = spyOn(component, 'getSubmissions');\n const registerChangeInResultsSpy = spyOn(component, 'registerChangeInResults');\n\n // test for init values\n expect(component).toBeTruthy();\n expect(component.submissions).toEqual([]);\n expect(component.reverse).toEqual(false);\n expect(component.predicate).toEqual('id');\n expect(component.filteredSubmissions).toEqual([]);\n expect(component.optimalSubmissions).toEqual([]);\n expect(component.otherSubmissions).toEqual([]);\n\n // call\n component.ngOnInit();\n\n // check\n expect(getSubmissionsSpy).toHaveBeenCalledWith(true);\n expect(registerChangeInResultsSpy).toHaveBeenCalled();\n expect(courseFindSpy).toHaveBeenCalled();\n expect(exerciseFindSpy).toHaveBeenCalled();\n expect(component.course).toEqual(course);\n expect(component.exercise).toEqual(modelingExercise as ModelingExercise);\n });\n\n it('should get Submissions', () => {\n // test getSubmissions\n const filterSubmissionsSpy = spyOn(component, 'filterSubmissions');\n const modelingSubmissionServiceSpy = spyOn(modelingSubmissionService, 'getModelingSubmissionsForExerciseByCorrectionRound').and.returnValue(\n of(new HttpResponse({ body: [modelingSubmission] })),\n );\n\n // call\n component.ngOnInit();\n\n // check\n expect(modelingSubmissionServiceSpy).toHaveBeenCalledWith(modelingExercise.id, { submittedOnly: true });\n expect(component.submissions).toEqual([modelingSubmission]);\n expect(component.filteredSubmissions).toEqual([modelingSubmission]);\n expect(filterSubmissionsSpy).toHaveBeenCalled();\n });\n\n it('should update filtered submissions', () => {\n // test updateFilteredSubmissions\n const applyFilter = spyOn(component, 'applyFilter');\n\n // setup\n component.ngOnInit();\n component.updateFilteredSubmissions([modelingSubmission]);\n\n // check\n expect(component.filteredSubmissions).toEqual([modelingSubmission]);\n expect(applyFilter).toHaveBeenCalled();\n });\n\n it('should refresh', () => {\n // test refresh\n const getSubmissionsSpy = spyOn(component, 'getSubmissions');\n\n component.refresh();\n\n expect(getSubmissionsSpy).toHaveBeenCalledWith(true);\n });\n\n describe('filter Submissions', () => {\n it('should filter Submissions', () => {\n // test filterSubmissions\n // setup\n const applyFilter = spyOn(component, 'applyFilter');\n const getOptimalSubmissionsSpy = spyOn(modelingAssessmentService, 'getOptimalSubmissions').and.returnValue(of([1]));\n component.exercise = modelingExercise;\n component.nextOptimalSubmissionIds = [];\n\n // call\n component.filterSubmissions(true);\n\n // check\n expect(getOptimalSubmissionsSpy).toHaveBeenCalled();\n expect(component.nextOptimalSubmissionIds).toEqual([1]);\n expect(applyFilter).toHaveBeenCalled();\n });\n it('should not filter Submissions', () => {\n // test filterSubmissions\n // setup\n const applyFilter = spyOn(component, 'applyFilter');\n const getOptimalSubmissionsSpy = spyOn(modelingAssessmentService, 'getOptimalSubmissions').and.returnValue(of([1]));\n\n component.exercise = modelingExercise;\n component.exercise.assessmentType = AssessmentType.AUTOMATIC;\n component.nextOptimalSubmissionIds = [];\n\n // call\n component.filterSubmissions(true);\n\n // check\n expect(getOptimalSubmissionsSpy).not.toHaveBeenCalled();\n expect(component.nextOptimalSubmissionIds).toEqual([]);\n expect(applyFilter).toHaveBeenCalled();\n });\n });\n\n it('should apply filters ', () => {\n // test applyFilters\n // setup\n component.submissions = [modelingSubmission, modelingSubmission2];\n component.userId = userId;\n component.nextOptimalSubmissionIds = [1, 2];\n component.filteredSubmissions = component.submissions;\n // call\n component.applyFilter();\n\n // check\n expect(component.otherSubmissions.length).toBe(1);\n expect(component.optimalSubmissions.length).toBe(1);\n expect(component.optimalSubmissions[0].id).toEqual(modelingSubmission2.id);\n expect(component.otherSubmissions[0].id).toEqual(modelingSubmission.id);\n });\n describe('reset optimality', () => {\n it('should reset optimality', fakeAsync(() => {\n component.exercise.assessmentType = AssessmentType.SEMI_AUTOMATIC;\n component.exercise = modelingExercise;\n const serviceResetOptSpy = spyOn(modelingAssessmentService, 'resetOptimality').and.returnValue(of(1));\n const filterSubmissionsSpy = spyOn(component, 'filterSubmissions');\n\n // call\n component.resetOptimality();\n\n tick();\n\n expect(serviceResetOptSpy).toHaveBeenCalledWith(modelingExercise.id);\n expect(filterSubmissionsSpy).toHaveBeenCalledWith(true);\n }));\n\n it('should not reset optimality', () => {\n // setup\n component.exercise.assessmentType = AssessmentType.AUTOMATIC;\n const filterSubmissionsSpy = spyOn(component, 'filterSubmissions');\n\n // call\n component.resetOptimality();\n\n // check\n expect(filterSubmissionsSpy).not.toHaveBeenCalled();\n });\n });\n\n describe('makeAllSubmissionsVisible', () => {\n it('should make all submissions visible ', () => {\n // setup\n component.busy = false;\n component.allSubmissionsVisible = false;\n // call\n component.makeAllSubmissionsVisible();\n // check\n expect(component.allSubmissionsVisible).toBe(true);\n });\n\n it('should not make all submissions visible ', () => {\n // setup\n component.busy = true;\n component.allSubmissionsVisible = false;\n // call\n component.makeAllSubmissionsVisible();\n // check\n expect(component.allSubmissionsVisible).toBe(false);\n });\n });\n\n describe('assessNextOptimal', () => {\n it('should assess next optimal submission', () => {\n // setup\n component.nextOptimalSubmissionIds = [];\n component.busy = true;\n component.courseId = 1;\n component.exerciseId = 2;\n const routerNavigateSpy = spyOn(router, 'navigate');\n const serviceResetOptSpy = spyOn(modelingAssessmentService, 'getOptimalSubmissions').and.returnValue(of([1]));\n const navigateToNextSpy = spyOn<any>(component, 'navigateToNextRandomOptimalSubmission').and.callThrough(); // <any> bc of private method\n component.exercise = modelingExercise;\n\n // call\n component.assessNextOptimal();\n\n // check\n expect(serviceResetOptSpy).toHaveBeenCalledWith(modelingExercise.id);\n expect(component.busy).toBe(false);\n expect(navigateToNextSpy).toHaveBeenCalled();\n expect(routerNavigateSpy).toHaveBeenCalled();\n });\n\n it('should navigate to next random optimal submission', () => {\n // setup\n component.nextOptimalSubmissionIds = [1];\n component.busy = false;\n component.courseId = 1;\n component.exerciseId = 2;\n const routerNavigateSpy = spyOn(router, 'navigate');\n const navigateToNextSpy = spyOn<any>(component, 'navigateToNextRandomOptimalSubmission').and.callThrough(); // <any> bc of private method\n\n // call\n component.assessNextOptimal();\n\n // check\n expect(component.busy).toBe(true);\n expect(navigateToNextSpy).toHaveBeenCalled();\n expect(routerNavigateSpy).toHaveBeenCalled();\n });\n });\n\n it('should cancelAssessment', fakeAsync(() => {\n // test cancelAssessment\n const windowSpy = spyOn(window, 'confirm').and.returnValue(true);\n const refreshSpy = spyOn(component, 'refresh');\n\n const modelAssServiceCancelAssSpy = spyOn(modelingAssessmentService, 'cancelAssessment').and.returnValue(of(1));\n\n // call\n component.cancelAssessment(modelingSubmission);\n tick();\n\n // check\n expect(modelAssServiceCancelAssSpy).toHaveBeenCalledWith(modelingSubmission.id);\n expect(windowSpy).toHaveBeenCalled();\n expect(refreshSpy).toHaveBeenCalled();\n }));\n\n it('should sortRows', () => {\n // test cancelAssessment\n const sortServiceSpy = spyOn(sortService, 'sortByProperty');\n component.otherSubmissions = [modelingSubmission];\n component.predicate = 'predicate';\n component.reverse = false;\n\n component.sortRows();\n\n expect(sortServiceSpy).toHaveBeenCalledWith([modelingSubmission], 'predicate', false);\n });\n\n it('ngOnDestroy', () => {\n // setup\n component.paramSub = new Subscription();\n const paramSubSpy = spyOn(component.paramSub, 'unsubscribe');\n\n // call\n component.ngOnDestroy();\n\n // check\n expect(paramSubSpy).toHaveBeenCalled();\n });\n\n describe('shouldGetAssessmentLink', () => {\n it('should get assessment link for exam exercise', () => {\n const submissionId = 7;\n component.exercise = modelingExercise;\n component.exerciseId = modelingExercise.id!;\n component.courseId = modelingExercise.course!.id!;\n expect(component.getAssessmentLink(submissionId)).toEqual([\n '/course-management',\n component.exercise.course!.id!.toString(),\n 'modeling-exercises',\n component.exercise.id!.toString(),\n 'submissions',\n submissionId.toString(),\n 'assessment',\n ]);\n });\n\n it('should get assessment link for normal exercise', () => {\n const submissionId = 8;\n component.exercise = modelingExerciseOfExam;\n component.exerciseId = modelingExerciseOfExam.id!;\n component.courseId = modelingExerciseOfExam.exerciseGroup!.exam!.course!.id!;\n component.examId = modelingExerciseOfExam.exerciseGroup!.exam!.id!;\n component.exerciseGroupId = modelingExerciseOfExam.exerciseGroup!.id!;\n expect(component.getAssessmentLink(submissionId)).toEqual([\n '/course-management',\n component.exercise.exerciseGroup!.exam!.course!.id!.toString(),\n 'exams',\n component.exercise.exerciseGroup!.exam!.id!.toString(),\n 'exercise-groups',\n component.exercise.exerciseGroup!.id!.toString(),\n 'modeling-exercises',\n component.exercise.id!.toString(),\n 'submissions',\n submissionId.toString(),\n 'assessment',\n ]);\n });\n });\n});\n" }, { "alpha_fraction": 0.7178571224212646, "alphanum_fraction": 0.7178571224212646, "avg_line_length": 30.11111068725586, "blob_id": "15ddc060e366a7a87c81cfddf1a13e955b367904", "content_id": "ab8104800fcedc7f6a42c6c4d3eaaa60b3d17079", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 280, "license_type": "permissive", "max_line_length": 58, "num_lines": 9, "path": "/src/main/webapp/app/entities/exercise-hint.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Exercise } from 'app/entities/exercise.model';\nimport { BaseEntity } from 'app/shared/model/base-entity';\n\nexport class ExerciseHint implements BaseEntity {\n public id?: number;\n public title?: string;\n public content?: string;\n public exercise?: Exercise;\n}\n" }, { "alpha_fraction": 0.6804888248443604, "alphanum_fraction": 0.6911426782608032, "avg_line_length": 47.11055374145508, "blob_id": "4ab26d500411bcedda4c099cb5373441fc452eb5", "content_id": "7ac1a6c4ad70499c9deb58467d434e20133fd77a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9574, "license_type": "permissive", "max_line_length": 172, "num_lines": 199, "path": "/src/test/java/de/tum/in/www1/artemis/StatisticsIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.YearMonth;\nimport java.time.ZonedDateTime;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\nimport org.springframework.util.LinkedMultiValueMap;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\nimport de.tum.in.www1.artemis.domain.enumeration.GraphType;\nimport de.tum.in.www1.artemis.domain.enumeration.SpanType;\nimport de.tum.in.www1.artemis.repository.TextExerciseRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.util.ModelFactory;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseManagementStatisticsDTO;\n\npublic class StatisticsIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private TextExerciseRepository textExerciseRepository;\n\n @Autowired\n UserRepository userRepository;\n\n Course course;\n\n @BeforeEach\n public void initTestCase() {\n database.addUsers(12, 10, 10);\n\n course = database.addCourseWithOneModelingExercise();\n var now = ZonedDateTime.now();\n TextExercise textExercise = ModelFactory.generateTextExercise(now.minusDays(1), now.minusHours(2), now.plusHours(1), course);\n course.addExercises(textExercise);\n textExerciseRepository.save(textExercise);\n\n // one submission today\n TextSubmission textSubmission = new TextSubmission();\n textSubmission.submissionDate(ZonedDateTime.now().minusSeconds(1));\n var submission = database.addSubmission(textExercise, textSubmission, \"student1\");\n database.addResultToSubmission(submission, AssessmentType.MANUAL);\n\n for (int i = 2; i <= 12; i++) {\n textSubmission = new TextSubmission();\n textSubmission.submissionDate(ZonedDateTime.now().minusMonths(i - 1).withDayOfMonth(10));\n submission = database.addSubmission(textExercise, textSubmission, \"student\" + i);\n database.addResultToSubmission(submission, AssessmentType.MANUAL);\n }\n }\n\n @AfterEach\n public void resetDatabase() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDataForDayEachGraph() throws Exception {\n\n SpanType span = SpanType.DAY;\n for (GraphType graph : GraphType.values()) {\n int periodIndex = 0;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n Integer[] result = request.get(\"/api/management/statistics/data\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(24);\n }\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDataForWeekEachGraph() throws Exception {\n\n SpanType span = SpanType.WEEK;\n for (GraphType graph : GraphType.values()) {\n int periodIndex = 0;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n Integer[] result = request.get(\"/api/management/statistics/data\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(7);\n }\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDataForMonthEachGraph() throws Exception {\n ZonedDateTime now = ZonedDateTime.now();\n SpanType span = SpanType.MONTH;\n for (GraphType graph : GraphType.values()) {\n int periodIndex = 0;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n Integer[] result = request.get(\"/api/management/statistics/data\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(YearMonth.of(now.getYear(), now.minusMonths(1 - periodIndex).plusDays(1).getMonth()).lengthOfMonth());\n }\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDataForQuarterEachGraph() throws Exception {\n SpanType span = SpanType.QUARTER;\n for (GraphType graph : GraphType.values()) {\n int periodIndex = 0;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n Integer[] result = request.get(\"/api/management/statistics/data\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(12);\n }\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDataForYearEachGraph() throws Exception {\n\n SpanType span = SpanType.YEAR;\n for (GraphType graph : GraphType.values()) {\n int periodIndex = 0;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n Integer[] result = request.get(\"/api/management/statistics/data\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(12);\n }\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetChartDataForCourse() throws Exception {\n var courseId = course.getId();\n SpanType span = SpanType.WEEK;\n int periodIndex = 0;\n var graph = GraphType.SUBMISSIONS;\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"span\", \"\" + span);\n parameters.add(\"periodIndex\", \"\" + periodIndex);\n parameters.add(\"graphType\", \"\" + graph);\n parameters.add(\"courseId\", \"\" + courseId);\n Integer[] result = request.get(\"/api/management/statistics/data-for-course\", HttpStatus.OK, Integer[].class, parameters);\n assertThat(result.length).isEqualTo(7);\n // one submission was manually added right before the request\n assertThat(result[6]).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetCourseStatistics() throws Exception {\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n TextExercise firstTextExercise = database.createIndividualTextExercise(course, pastTimestamp, pastTimestamp, pastTimestamp);\n TextExercise secondTextExercise = database.createIndividualTextExercise(course, pastTimestamp.minusDays(1), pastTimestamp.minusDays(1), pastTimestamp.minusDays(1));\n\n var firstTextExerciseId = firstTextExercise.getId();\n var secondTextExerciseId = secondTextExercise.getId();\n User student1 = userRepository.findOneByLogin(\"student1\").orElseThrow();\n User student2 = userRepository.findOneByLogin(\"student2\").orElseThrow();\n\n // Creating result for student1 and student2 for firstExercise\n database.createParticipationSubmissionAndResult(firstTextExerciseId, student1, 10.0, 0.0, 50, true);\n database.createParticipationSubmissionAndResult(firstTextExerciseId, student2, 10.0, 0.0, 100, true);\n\n // Creating result for student1 and student2 for secondExercise\n database.createParticipationSubmissionAndResult(secondTextExerciseId, student1, 10.0, 0.0, 0, true);\n database.createParticipationSubmissionAndResult(secondTextExerciseId, student2, 10.0, 0.0, 80, true);\n\n Long courseId = course.getId();\n LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();\n parameters.add(\"courseId\", \"\" + courseId);\n CourseManagementStatisticsDTO result = request.get(\"/api/management/statistics/course-statistics\", HttpStatus.OK, CourseManagementStatisticsDTO.class, parameters);\n\n assertThat(result.getAverageScoreOfCourse()).isEqualTo(57.5);\n assertThat(result.getAverageScoresOfExercises().size()).isEqualTo(2);\n\n var firstTextExerciseStatistics = result.getAverageScoresOfExercises().get(0);\n assertThat(firstTextExerciseStatistics.getAverageScore()).isEqualTo(75.0);\n assertThat(firstTextExerciseStatistics.getExerciseId()).isEqualTo(firstTextExerciseId);\n assertThat(firstTextExerciseStatistics.getExerciseName()).isEqualTo(firstTextExercise.getTitle());\n\n var secondTextExerciseStatistics = result.getAverageScoresOfExercises().get(1);\n assertThat(secondTextExerciseStatistics.getAverageScore()).isEqualTo(40.0);\n assertThat(secondTextExerciseStatistics.getExerciseId()).isEqualTo(secondTextExerciseId);\n assertThat(secondTextExerciseStatistics.getExerciseName()).isEqualTo(secondTextExercise.getTitle());\n }\n}\n" }, { "alpha_fraction": 0.6264805793762207, "alphanum_fraction": 0.6268578171730042, "avg_line_length": 47.02536392211914, "blob_id": "aff49b14a1440fb1854bfd36e6b0ce14a86dfa06", "content_id": "c2e0ef150041218d9d6a758e8691ac5f751c7144", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13255, "license_type": "permissive", "max_line_length": 179, "num_lines": 276, "path": "/src/main/java/de/tum/in/www1/artemis/domain/notification/GroupNotificationFactory.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.notification;\n\nimport java.util.List;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.GroupNotificationType;\nimport de.tum.in.www1.artemis.domain.enumeration.NotificationType;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\n\npublic class GroupNotificationFactory {\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param attachment for which a notification should be created\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @param notificationText custom notification text\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(Attachment attachment, User author, GroupNotificationType groupNotificationType, NotificationType notificationType,\n String notificationText) {\n String title, text;\n if (notificationType == NotificationType.ATTACHMENT_CHANGE) {\n title = \"Attachment updated\";\n text = \"Attachment \\\"\" + attachment.getName() + \"\\\" updated.\";\n }\n else {\n throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n if (notificationText != null) {\n text = notificationText;\n }\n\n Lecture lecture;\n // we get the lecture either from the directly connected lecture or from the attachment unit\n if (attachment.getAttachmentUnit() != null) {\n lecture = attachment.getAttachmentUnit().getLecture();\n }\n else {\n lecture = attachment.getLecture();\n }\n Course course = lecture.getCourse();\n GroupNotification notification = new GroupNotification(course, title, text, author, groupNotificationType);\n\n notification.setTarget(notification.getAttachmentUpdated(lecture));\n\n return notification;\n }\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param exercise for which a notification should be created\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @param notificationText custom notification text\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(Exercise exercise, User author, GroupNotificationType groupNotificationType, NotificationType notificationType,\n String notificationText) {\n String title, text;\n switch (notificationType) {\n case EXERCISE_CREATED -> {\n title = \"Exercise created\";\n text = \"A new exercise \\\"\" + exercise.getTitle() + \"\\\" got created.\";\n }\n case EXERCISE_PRACTICE -> {\n title = \"Exercise open for practice\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" is now open for practice.\";\n }\n case QUIZ_EXERCISE_STARTED -> {\n title = \"Quiz started\";\n text = \"Quiz \\\"\" + exercise.getTitle() + \"\\\" just started.\";\n }\n case EXERCISE_UPDATED -> {\n title = \"Exercise updated\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" updated.\";\n }\n case DUPLICATE_TEST_CASE -> {\n title = \"Duplicate test case was found.\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" has multiple test cases with the same name.\";\n }\n case ILLEGAL_SUBMISSION -> {\n title = \"Illegal submission of a student.\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" has illegal submissions of students.\";\n }\n\n default -> throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n if (notificationText != null) {\n text = notificationText;\n }\n\n GroupNotification notification = new GroupNotification(exercise.getCourseViaExerciseGroupOrCourseMember(), title, text, author, groupNotificationType);\n\n // Exercises for exams\n if (exercise.isExamExercise()) {\n if (exercise instanceof ProgrammingExercise) {\n notification.setTarget(notification.getExamProgrammingExerciseOrTestCaseTarget((ProgrammingExercise) exercise, \"exerciseUpdated\"));\n }\n }\n // Exercises for courses (not for exams)\n else if (notificationType == NotificationType.EXERCISE_CREATED) {\n notification.setTarget(notification.getExerciseCreatedTarget(exercise));\n }\n else if (notificationType == NotificationType.DUPLICATE_TEST_CASE) {\n notification.setTarget(notification.getExamProgrammingExerciseOrTestCaseTarget((ProgrammingExercise) exercise, \"duplicateTestCase\"));\n }\n else {\n notification.setTarget(notification.getExerciseUpdatedTarget(exercise));\n }\n\n return notification;\n }\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param question for which a notification should be created\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(StudentQuestion question, User author, GroupNotificationType groupNotificationType, NotificationType notificationType) {\n String title, text;\n Course course;\n switch (notificationType) {\n case NEW_QUESTION_FOR_EXERCISE -> {\n Exercise exercise = question.getExercise();\n title = \"New Question\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" got a new question.\";\n course = exercise.getCourseViaExerciseGroupOrCourseMember();\n }\n case NEW_QUESTION_FOR_LECTURE -> {\n Lecture lecture = question.getLecture();\n title = \"New Question\";\n text = \"Lecture \\\"\" + lecture.getTitle() + \"\\\" got a new question.\";\n course = lecture.getCourse();\n }\n default -> throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n GroupNotification notification = new GroupNotification(course, title, text, author, groupNotificationType);\n\n if (notificationType == NotificationType.NEW_QUESTION_FOR_EXERCISE) {\n notification.setTarget(notification.getExerciseQuestionTarget(question.getExercise()));\n }\n else {\n notification.setTarget(notification.getLectureQuestionTarget(question.getLecture()));\n }\n\n return notification;\n }\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param answer for which a notification should be created\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(StudentQuestionAnswer answer, User author, GroupNotificationType groupNotificationType, NotificationType notificationType) {\n String text, title;\n Course course;\n switch (notificationType) {\n case NEW_ANSWER_FOR_EXERCISE -> {\n Exercise exercise = answer.getQuestion().getExercise();\n title = \"New Answer\";\n text = \"Exercise \\\"\" + exercise.getTitle() + \"\\\" got a new answer.\";\n course = exercise.getCourseViaExerciseGroupOrCourseMember();\n }\n case NEW_ANSWER_FOR_LECTURE -> {\n Lecture lecture = answer.getQuestion().getLecture();\n title = \"New Answer\";\n text = \"Lecture \\\"\" + lecture.getTitle() + \"\\\" got a new answer.\";\n course = lecture.getCourse();\n }\n default -> throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n GroupNotification notification = new GroupNotification(course, title, text, author, groupNotificationType);\n\n if (notificationType == NotificationType.NEW_ANSWER_FOR_EXERCISE) {\n notification.setTarget(notification.getExerciseAnswerTarget(answer.getQuestion().getExercise()));\n }\n else {\n notification.setTarget(notification.getLectureAnswerTarget(answer.getQuestion().getLecture()));\n }\n\n return notification;\n }\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param course the course being archived\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @param archiveErrors a list of errors that occured during archiving\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(Course course, User author, GroupNotificationType groupNotificationType, NotificationType notificationType,\n List<String> archiveErrors) {\n String title, text;\n switch (notificationType) {\n case COURSE_ARCHIVE_STARTED -> {\n title = \"Course archival started\";\n text = \"The course \\\"\" + course.getTitle() + \"\\\" is being archived.\";\n }\n case COURSE_ARCHIVE_FINISHED -> {\n title = \"Course archival finished\";\n text = \"The course \\\"\" + course.getTitle() + \"\\\" has been archived.\";\n\n if (!archiveErrors.isEmpty()) {\n text += \" Some exercises couldn't be included in the archive:<br/><br/>\" + String.join(\"<br/><br/>\", archiveErrors);\n }\n }\n case COURSE_ARCHIVE_FAILED -> {\n title = \"Course archival failed\";\n text = \"The was a problem archiving course \\\"\" + course.getTitle() + \"\\\": <br/><br/>\" + String.join(\"<br/><br/>\", archiveErrors);\n }\n default -> throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n GroupNotification notification = new GroupNotification(course, title, text, author, groupNotificationType);\n notification.setTarget(notification.getCourseTarget(course, \"courseArchiveUpdated\"));\n return notification;\n }\n\n /**\n * Creates an instance of GroupNotification based on the passed parameters.\n *\n * @param exam the exam being archived\n * @param author of the notification\n * @param groupNotificationType user group type the notification should target\n * @param notificationType type of the notification that should be created\n * @param archiveErrors a list of errors that occured during archiving\n * @return an instance of GroupNotification\n */\n public static GroupNotification createNotification(Exam exam, User author, GroupNotificationType groupNotificationType, NotificationType notificationType,\n List<String> archiveErrors) {\n String title, text;\n switch (notificationType) {\n case EXAM_ARCHIVE_STARTED -> {\n title = \"Exam archival started\";\n text = \"The exam \\\"\" + exam.getTitle() + \"\\\" is being archived.\";\n }\n case EXAM_ARCHIVE_FINISHED -> {\n title = \"Exam archival finished\";\n text = \"The exam \\\"\" + exam.getTitle() + \"\\\" has been archived.\";\n\n if (!archiveErrors.isEmpty()) {\n text += \" Some exercises couldn't be included in the archive:<br/><br/>\" + String.join(\"<br/><br/>\", archiveErrors);\n }\n }\n case EXAM_ARCHIVE_FAILED -> {\n title = \"Exam archival failed\";\n text = \"The was a problem archiving exam \\\"\" + exam.getTitle() + \"\\\": <br/><br/>\" + String.join(\"<br/><br/>\", archiveErrors);\n }\n default -> throw new UnsupportedOperationException(\"Unsupported NotificationType: \" + notificationType);\n }\n\n GroupNotification notification = new GroupNotification(exam.getCourse(), title, text, author, groupNotificationType);\n notification.setTarget(notification.getCourseTarget(exam.getCourse(), \"examArchiveUpdated\"));\n return notification;\n }\n}\n" }, { "alpha_fraction": 0.6795653700828552, "alphanum_fraction": 0.6807091236114502, "avg_line_length": 27.98342514038086, "blob_id": "2f947991a7bbe35bd79ec297ba72cb5e600cb455", "content_id": "26f42fb3ee5cb9419db1ba999d80c38d6c60ad6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5246, "license_type": "permissive", "max_line_length": 175, "num_lines": 181, "path": "/src/main/java/de/tum/in/www1/artemis/domain/ProgrammingExerciseTestCase.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport javax.annotation.Nonnull;\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.enumeration.Visibility;\n\n/**\n * A ProgrammingExerciseTestCase.\n */\n@Entity\n@Table(name = \"programming_exercise_test_case\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ProgrammingExerciseTestCase extends DomainObject {\n\n @Column(name = \"test_name\")\n private String testName;\n\n @Column(name = \"weight\")\n private Double weight;\n\n @Column(name = \"active\")\n private Boolean active;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"visibility\")\n private Visibility visibility;\n\n @Column(name = \"bonus_multiplier\")\n private Double bonusMultiplier;\n\n @Column(name = \"bonus_points\")\n private Double bonusPoints;\n\n @ManyToOne(fetch = FetchType.LAZY)\n @JsonIgnoreProperties(\"programmingExerciseTestCase\")\n private ProgrammingExercise exercise;\n\n public ProgrammingExerciseTestCase id(Long id) {\n setId(id);\n return this;\n }\n\n public String getTestName() {\n return testName;\n }\n\n public ProgrammingExerciseTestCase testName(String testName) {\n this.testName = testName;\n return this;\n }\n\n public void setTestName(String testName) {\n this.testName = testName;\n }\n\n public Double getWeight() {\n return weight;\n }\n\n public ProgrammingExerciseTestCase weight(Double weight) {\n this.weight = weight;\n return this;\n }\n\n public void setWeight(Double weight) {\n this.weight = weight;\n }\n\n @Nonnull\n public Double getBonusMultiplier() {\n return bonusMultiplier != null ? bonusMultiplier : 1.0;\n }\n\n public ProgrammingExerciseTestCase bonusMultiplier(Double bonusMultiplier) {\n this.bonusMultiplier = bonusMultiplier;\n return this;\n }\n\n public void setBonusMultiplier(Double bonusMultiplier) {\n this.bonusMultiplier = bonusMultiplier;\n }\n\n @Nonnull\n public Double getBonusPoints() {\n return bonusPoints != null ? bonusPoints : 0.0;\n }\n\n public ProgrammingExerciseTestCase bonusPoints(Double bonusPoints) {\n this.bonusPoints = bonusPoints;\n return this;\n }\n\n public void setBonusPoints(Double bonusPoints) {\n this.bonusPoints = bonusPoints;\n }\n\n public Boolean isActive() {\n return active;\n }\n\n public ProgrammingExerciseTestCase active(Boolean active) {\n this.active = active;\n return this;\n }\n\n public void setActive(Boolean active) {\n this.active = active;\n }\n\n public Exercise getExercise() {\n return exercise;\n }\n\n public ProgrammingExerciseTestCase exercise(ProgrammingExercise exercise) {\n this.exercise = exercise;\n return this;\n }\n\n public void setExercise(ProgrammingExercise exercise) {\n this.exercise = exercise;\n }\n\n @JsonIgnore\n public boolean isAfterDueDate() {\n return visibility == Visibility.AFTER_DUE_DATE;\n }\n\n @JsonIgnore\n public boolean isInvisible() {\n return visibility == Visibility.NEVER;\n }\n\n public Visibility getVisibility() {\n return visibility;\n }\n\n public void setVisibility(Visibility visibility) {\n this.visibility = visibility;\n }\n\n public ProgrammingExerciseTestCase visibility(Visibility visibility) {\n this.visibility = visibility;\n return this;\n }\n\n /**\n * This method needs to be checked and updated if there is a new class attribute. Creates a clone with all attributes set to the value of the object, including the id.\n *\n * @return a clone of the object.\n */\n public ProgrammingExerciseTestCase clone() {\n ProgrammingExerciseTestCase clone = new ProgrammingExerciseTestCase().testName(this.getTestName()).weight(this.getWeight()).active(this.isActive())\n .bonusPoints(this.getBonusPoints()).bonusMultiplier(this.getBonusMultiplier()).visibility(visibility).exercise(this.exercise);\n clone.setId(this.getId());\n return clone;\n }\n\n /**\n * this methods checks for logical equality based on the name and the exercise\n * @param testCase another test case which should be checked for being the same\n * @return whether this and the other test case are the same based on name and exercise\n */\n public boolean isSameTestCase(ProgrammingExerciseTestCase testCase) {\n return testCase.getTestName().equalsIgnoreCase(this.getTestName()) && this.getExercise().getId().equals(testCase.getExercise().getId());\n }\n\n @Override\n public String toString() {\n return \"ProgrammingExerciseTestCase{\" + \"id=\" + getId() + \", testName='\" + testName + '\\'' + \", weight=\" + weight + \", active=\" + active + \", visibility=\" + visibility\n + \", bonusMultiplier=\" + bonusMultiplier + \", bonusPoints=\" + bonusPoints + '}';\n }\n}\n" }, { "alpha_fraction": 0.8132992386817932, "alphanum_fraction": 0.8184143304824829, "avg_line_length": 29.076923370361328, "blob_id": "c48a76dd5f3c4a34cd29d435095c16743cdb236d", "content_id": "22b3cf75f1df418dc30a3a431fcd8810c9964623", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 391, "license_type": "permissive", "max_line_length": 87, "num_lines": 13, "path": "/src/main/java/de/tum/in/www1/artemis/repository/AttachmentUnitRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.lecture.AttachmentUnit;\n\n/**\n * Spring Data JPA repository for the Attachment Unit entity.\n */\n@Repository\npublic interface AttachmentUnitRepository extends JpaRepository<AttachmentUnit, Long> {\n}\n" }, { "alpha_fraction": 0.6632829308509827, "alphanum_fraction": 0.6638965010643005, "avg_line_length": 46.306068420410156, "blob_id": "4f3736494420a2303190446433de4818ee7e6aa4", "content_id": "c3c42485722767d12cddef0a5675b0ac75ebbfd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 17929, "license_type": "permissive", "max_line_length": 180, "num_lines": 379, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport * as moment from 'moment';\nimport { Exercise, ExerciseCategory, ExerciseType, IncludedInOverallScore, ParticipationStatus } from 'app/entities/exercise.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { ParticipationService } from '../participation/participation.service';\nimport { map } from 'rxjs/operators';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { LtiConfiguration } from 'app/entities/lti-configuration.model';\nimport { CourseExerciseStatisticsDTO } from 'app/exercises/shared/exercise/exercise-statistics-dto.model';\nimport { TranslateService } from '@ngx-translate/core';\n\nexport type EntityResponseType = HttpResponse<Exercise>;\nexport type EntityArrayResponseType = HttpResponse<Exercise[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class ExerciseService {\n public resourceUrl = SERVER_API_URL + 'api/exercises';\n\n constructor(private http: HttpClient, private participationService: ParticipationService, private accountService: AccountService, private translateService: TranslateService) {}\n\n /**\n * Persist a new exercise\n * @param { Exercise } exercise - Exercise that will be persisted\n * return\n */\n create(exercise: Exercise): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(exercise);\n return this.http\n .post<Exercise>(this.resourceUrl, copy, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n /**\n * Update existing exercise\n * @param { Exercise } exercise - Exercise that will be updated\n */\n update(exercise: Exercise): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(exercise);\n return this.http\n .put<Exercise>(this.resourceUrl, copy, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res));\n }\n\n /**\n * Validates if the date is correct\n */\n validateDate(exercise: Exercise) {\n exercise.dueDateError = exercise.releaseDate && exercise.dueDate ? !exercise.dueDate.isAfter(exercise.releaseDate) : false;\n\n exercise.assessmentDueDateError =\n exercise.assessmentDueDate && exercise.releaseDate\n ? !exercise.assessmentDueDate.isAfter(exercise.releaseDate)\n : exercise.assessmentDueDate && exercise.dueDate\n ? !exercise.assessmentDueDate.isAfter(exercise.dueDate)\n : false;\n }\n\n /**\n * Get exercise with exerciseId from server\n * @param { number } exerciseId - Exercise that should be loaded\n */\n find(exerciseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Exercise>(`${this.resourceUrl}/${exerciseId}`, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res))\n .map((res: EntityResponseType) => this.checkPermission(res));\n }\n\n /**\n * Fetches the title of the exercise with the given id\n *\n * @param exerciseId the id of the exercise\n * @return the title of the exercise in an HttpResponse, or an HttpErrorResponse on error\n */\n getTitle(exerciseId: number): Observable<HttpResponse<string>> {\n return this.http.get(`${this.resourceUrl}/${exerciseId}/title`, { observe: 'response', responseType: 'text' });\n }\n\n /**\n * Delete student build plans (except BASE/SOLUTION) and optionally git repositories of all exercise student participations.\n * @param { number } exerciseId - programming exercise for which build plans in respective student participations are deleted\n * @param { boolean } deleteRepositories - if true, the repositories get deleted\n */\n cleanup(exerciseId: number, deleteRepositories: boolean): Observable<HttpResponse<void>> {\n const params = new HttpParams().set('deleteRepositories', deleteRepositories.toString());\n return this.http.delete<void>(`${this.resourceUrl}/${exerciseId}/cleanup`, { params, observe: 'response' });\n }\n\n /**\n * Resets an Exercise with exerciseId by deleting all its participations.\n * @param { number } exerciseId - Id of exercise that should be resetted\n */\n reset(exerciseId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/${exerciseId}/reset`, { observe: 'response' });\n }\n\n /**\n * Get exercise details including all results for the currently logged in user\n * @param { number } exerciseId - Id of the exercise to get the repos from\n */\n getExerciseDetails(exerciseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Exercise>(`${this.resourceUrl}/${exerciseId}/details`, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertDateFromServer(res))\n .map((res: EntityResponseType) => {\n if (res.body) {\n // insert an empty list to avoid additional calls in case the list is empty on the server (because then it would be undefined in the client)\n if (res.body.exerciseHints === undefined) {\n res.body.exerciseHints = [];\n }\n if (res.body.studentQuestions === undefined) {\n res.body.studentQuestions = [];\n }\n }\n return res;\n })\n .map((res: EntityResponseType) => this.checkPermission(res));\n }\n\n getUpcomingExercises(): Observable<EntityArrayResponseType> {\n return this.http\n .get<Exercise[]>(`${this.resourceUrl}/upcoming`, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * Return all exercises of input exercises that are due in delayInDays or 7 days if not specified\n * @param { Exercise[] } exercises - Considered exercises\n * @param { number} delayInDays - If set, amount of days that are considered\n */\n getNextExerciseForDays(exercises?: Exercise[], delayInDays = 7) {\n if (!exercises) {\n return undefined;\n }\n return exercises.find((exercise) => {\n const dueDate = exercise.dueDate!;\n return moment().isBefore(dueDate) && moment().add(delayInDays, 'day').isSameOrAfter(dueDate);\n })!;\n }\n\n /**\n * Returns an active quiz, a visible quiz or an exercise due in delayInHours or 12 hours if not specified\n * @param { Exercise[] } exercises - Considered exercises\n * @param { number} delayInHours - If set, amount of hours that are considered\n */\n getNextExerciseForHours(exercises?: Exercise[], delayInHours = 12) {\n // check for quiz exercise in order to prioritize before other exercise types\n const nextQuizExercises = exercises?.filter((exercise: QuizExercise) => exercise.type === ExerciseType.QUIZ && !exercise.ended);\n return (\n // 1st priority is an active quiz\n nextQuizExercises?.find((exercise: QuizExercise) => this.isActiveQuiz(exercise)) ||\n // 2nd priority is a visible quiz\n nextQuizExercises?.find((exercise: QuizExercise) => exercise.isVisibleBeforeStart) ||\n // 3rd priority is the next due exercise\n exercises?.find((exercise) => {\n const dueDate = exercise.dueDate!;\n return moment().isBefore(dueDate) && moment().add(delayInHours, 'hours').isSameOrAfter(dueDate);\n })\n );\n }\n\n isActiveQuiz(exercise: Exercise) {\n return (\n exercise.participationStatus === ParticipationStatus.QUIZ_UNINITIALIZED ||\n exercise.participationStatus === ParticipationStatus.QUIZ_ACTIVE ||\n exercise.participationStatus === ParticipationStatus.QUIZ_SUBMITTED\n );\n }\n\n /**\n * Converts all dates of a server-exercise to the client timezone\n * @param { Exercise } exercise - Exercise from server whose date is adjusted\n * @returns { Exercise } - Exercise with adjusted times\n */\n convertExerciseDateFromServer(exercise?: Exercise) {\n if (exercise) {\n exercise.releaseDate = exercise.releaseDate ? moment(exercise.releaseDate) : undefined;\n exercise.dueDate = exercise.dueDate ? moment(exercise.dueDate) : undefined;\n exercise.assessmentDueDate = exercise.assessmentDueDate ? moment(exercise.assessmentDueDate) : undefined;\n exercise.studentParticipations = this.participationService.convertParticipationsDateFromServer(exercise.studentParticipations);\n }\n return exercise;\n }\n\n /**\n * Converts all dates of server-exercises to the client timezone\n * @param { Exercise[] } exercises - Array of server-exercises whose date are adjusted\n * @returns { Exercise[] } - Array of exercises with adjusted times\n */\n convertExercisesDateFromServer(exercises?: Exercise[]): Exercise[] {\n const convertedExercises: Exercise[] = [];\n if (exercises && exercises.length > 0) {\n exercises.forEach((exercise: Exercise) => {\n const convertedExercise = this.convertExerciseDateFromServer(exercise);\n if (convertedExercise) {\n convertedExercises.push(convertedExercise);\n }\n });\n }\n return convertedExercises;\n }\n\n /**\n * Converts all dates of a client-exercise to the server timezone\n * @param { Exercise } exercise - Exercise from client whose date is adjusted\n */\n convertDateFromClient<E extends Exercise>(exercise: E): E {\n return Object.assign({}, exercise, {\n releaseDate: exercise.releaseDate && moment(exercise.releaseDate).isValid() ? moment(exercise.releaseDate).toJSON() : undefined,\n dueDate: exercise.dueDate && moment(exercise.dueDate).isValid() ? moment(exercise.dueDate).toJSON() : undefined,\n assessmentDueDate: exercise.assessmentDueDate && moment(exercise.assessmentDueDate).isValid() ? moment(exercise.assessmentDueDate).toJSON() : undefined,\n });\n }\n\n /**\n * Replace dates in http-response including an exercise with the corresponding client time\n * @param { ERT } res - Response from server including one exercise\n */\n convertDateFromServer<ERT extends EntityResponseType>(res: ERT): ERT {\n if (res.body) {\n res.body.releaseDate = res.body.releaseDate ? moment(res.body.releaseDate) : undefined;\n res.body.dueDate = res.body.dueDate ? moment(res.body.dueDate) : undefined;\n res.body.assessmentDueDate = res.body.assessmentDueDate ? moment(res.body.assessmentDueDate) : undefined;\n res.body.studentParticipations = this.participationService.convertParticipationsDateFromServer(res.body.studentParticipations);\n }\n return res;\n }\n\n /**\n * Look up permissions and add/replace isAtLeastInstuctor and isAtLeastTutor to http request containing a course\n * @param { ERT } res - Response from server including a course\n */\n checkPermission<ERT extends EntityResponseType>(res: ERT): ERT {\n if (res.body && res.body.course) {\n res.body.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(res.body.course);\n res.body.isAtLeastTutor = this.accountService.isAtLeastTutorInCourse(res.body.course);\n }\n return res;\n }\n\n /**\n * Replace dates in http-response including an array of exercises with the corresponding client time\n * @param { EART } res - Response from server including an array of exercise\n */\n convertDateArrayFromServer<E extends Exercise, EART extends EntityArrayResponseType>(res: EART): EART {\n if (res.body) {\n res.body.forEach((exercise: E) => {\n this.convertExerciseDateFromServer(exercise);\n });\n }\n return res;\n }\n\n /**\n * Create Array of exercise categories from exercise\n * @param { Exercise } exercise whos categories should be converted\n */\n convertExerciseCategoriesFromServer(exercise: Exercise): ExerciseCategory[] {\n if (!exercise || !exercise.categories) {\n return [];\n }\n return exercise.categories.map((el) => JSON.parse(el));\n }\n\n /**\n * Create Array of exercise categories from array of strings\n * @param { string[] } categories that are converted to categories\n */\n convertExerciseCategoriesAsStringFromServer(categories: string[]): ExerciseCategory[] {\n return categories.map((el) => JSON.parse(el));\n }\n\n /**\n * Prepare client-exercise to be uploaded to the server\n * @param { Exercise } exercise - Exercise that will be modified\n */\n convertExerciseForServer<E extends Exercise>(exercise: E): Exercise {\n let copy = Object.assign(exercise, {});\n copy = this.convertDateFromClient(copy);\n if (copy.course) {\n copy.course.exercises = [];\n copy.course.lectures = [];\n }\n copy.studentParticipations = [];\n return copy;\n }\n\n /**\n * Get the \"exerciseId\" exercise with data useful for tutors.\n * @param { number } exerciseId - Id of exercise to retreive\n */\n getForTutors(exerciseId: number): Observable<HttpResponse<Exercise>> {\n return this.http\n .get<Exercise>(`${this.resourceUrl}/${exerciseId}/for-assessment-dashboard`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Retrieve a collection of useful statistics for the tutor exercise dashboard of the exercise with the given exerciseId\n * @param { number } exerciseId - Id of exercise to retrieve the stats for\n */\n getStatsForTutors(exerciseId: number): Observable<HttpResponse<StatsForDashboard>> {\n return this.http.get<StatsForDashboard>(`${this.resourceUrl}/${exerciseId}/stats-for-assessment-dashboard`, { observe: 'response' });\n }\n\n /**\n * Retrieve a collection of useful statistics for the instructor exercise dashboard of the exercise with the given exerciseId\n * @param { number } exerciseId - Id of exercise to retreive the stats for\n */\n getStatsForInstructors(exerciseId: number): Observable<HttpResponse<StatsForDashboard>> {\n return this.http.get<StatsForDashboard>(`${this.resourceUrl}/${exerciseId}/stats-for-instructor-dashboard`, { observe: 'response' });\n }\n\n /**\n * Retrieves useful statistics for course exercises\n *\n * Gets the {@link CourseExerciseStatisticsDTO} for each exercise proved in <code>exerciseIds</code>. Either the results of the last submission or the results of the last rated\n * submission are considered for a student/team, depending on the value of <code>onlyConsiderRatedResults</code>\n * @param onlyConsiderRatedResults - either the results of the last submission or the results of the last rated submission are considered\n * @param exerciseIds - list of exercise ids (must be belong to the same course)\n */\n getCourseExerciseStatistics(exerciseIds: number[], onlyConsiderRatedResults: boolean): Observable<HttpResponse<CourseExerciseStatisticsDTO[]>> {\n let params = new HttpParams();\n params = params.append('exerciseIds', exerciseIds.join(', '));\n params = params.append('onlyConsiderRatedResults', onlyConsiderRatedResults.toString());\n return this.http.get<CourseExerciseStatisticsDTO[]>(`${this.resourceUrl}/exercises/course-exercise-statistics`, {\n params,\n observe: 'response',\n });\n }\n\n /**\n * Makes sure that bonus points are zero and respect the constraint by includedInOverallScore\n * @param exercise exercise for which to set the bonus points\n */\n setBonusPointsConstrainedByIncludedInOverallScore(exercise: Exercise) {\n if (exercise.bonusPoints === undefined || exercise.includedInOverallScore !== IncludedInOverallScore.INCLUDED_COMPLETELY) {\n exercise.bonusPoints = 0;\n }\n return exercise;\n }\n\n isIncludedInScore(exercise: Exercise | undefined) {\n if (!exercise?.includedInOverallScore) {\n return '';\n }\n switch (exercise.includedInOverallScore) {\n case IncludedInOverallScore.INCLUDED_AS_BONUS:\n return this.translateService.instant('artemisApp.exercise.bonus');\n case IncludedInOverallScore.INCLUDED_COMPLETELY:\n return this.translateService.instant('artemisApp.exercise.yes');\n case IncludedInOverallScore.NOT_INCLUDED:\n return this.translateService.instant('artemisApp.exercise.no');\n }\n }\n\n toggleSecondCorrection(exerciseId: number): Observable<Boolean> {\n return this.http.put<boolean>(`${this.resourceUrl}/${exerciseId}/toggle-second-correction`, { observe: 'response' });\n }\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ExerciseLtiConfigurationService {\n private resourceUrl = SERVER_API_URL + 'api/lti/configuration';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Load exercise with exerciseId from server\n * @param { number } exerciseId - Id of exercise that is loaded\n */\n find(exerciseId: number): Observable<HttpResponse<LtiConfiguration>> {\n return this.http.get<LtiConfiguration>(`${this.resourceUrl}/${exerciseId}`, { observe: 'response' });\n }\n}\n" }, { "alpha_fraction": 0.734645664691925, "alphanum_fraction": 0.7405511736869812, "avg_line_length": 36.91044616699219, "blob_id": "35313b01b030df4a2282cac23ebf28dbc7df3da9", "content_id": "0fd7381e1ed66e3ddd4615904d9a952cb361f214", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2540, "license_type": "permissive", "max_line_length": 164, "num_lines": 67, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/AtheneResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.Result;\nimport de.tum.in.www1.artemis.service.connectors.athene.AtheneService;\nimport de.tum.in.www1.artemis.web.rest.dto.AtheneDTO;\n\n/**\n * REST controller for managing Athene results.\n */\n@RestController\n@RequestMapping(Constants.ATHENE_RESULT_API_PATH)\n@Profile(\"athene\")\npublic class AtheneResource {\n\n @Value(\"${artemis.athene.base64-secret}\")\n private String atheneApiSecret;\n\n private final Logger log = LoggerFactory.getLogger(AtheneResource.class);\n\n private final AtheneService atheneService;\n\n public AtheneResource(AtheneService atheneService) {\n this.atheneService = atheneService;\n }\n\n /**\n * Saves automatic textAssessments of Athene\n *\n * @param exerciseId The exerciseId of the exercise which will be saved\n * @param requestBody The calculation results containing blocks and clusters\n * @param auth The secret for authorization\n * @return 200 Ok if successful or 401 unauthorized if secret is wrong\n */\n @PostMapping(value = \"/{exerciseId}\", consumes = APPLICATION_JSON_VALUE)\n public ResponseEntity<Result> saveAtheneResult(@PathVariable Long exerciseId, @RequestBody AtheneDTO requestBody, @RequestHeader(\"Authorization\") String auth) {\n log.debug(\"REST call to inform about new Athene results for exercise: {}\", exerciseId);\n\n // Check Authorization header\n if (!atheneApiSecret.equals(auth)) {\n return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();\n }\n\n // Check if job should be running, otherwise reject results\n if (!atheneService.isTaskRunning(exerciseId)) {\n return ResponseEntity.status(HttpStatus.PRECONDITION_FAILED).build();\n }\n\n // The atheneService will manage the processing and database saving\n atheneService.processResult(requestBody.getClusters(), requestBody.getBlocks(), exerciseId);\n\n log.debug(\"REST call for new Athene results for exercise {} finished\", exerciseId);\n\n return ResponseEntity.ok().build();\n }\n\n}\n" }, { "alpha_fraction": 0.5578431487083435, "alphanum_fraction": 0.5578431487083435, "avg_line_length": 36.77777862548828, "blob_id": "97495cbc0735c4b015312ed3eb78e76dac1b9e84", "content_id": "8dc7b4864415d32c4597053cf9c4f0164de9a991", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3060, "license_type": "permissive", "max_line_length": 131, "num_lines": 81, "path": "/src/main/webapp/app/admin/organization-management/organization-management.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { ActivatedRouteSnapshot, Resolve, Route } from '@angular/router';\nimport { JhiResolvePagingParams } from 'ng-jhipster';\nimport { OrganizationManagementComponent } from 'app/admin/organization-management/organization-management.component';\nimport { OrganizationManagementUpdateComponent } from 'app/admin/organization-management/organization-management-update.component';\nimport { OrganizationManagementDetailComponent } from 'app/admin/organization-management/organization-management-detail.component';\nimport { OrganizationManagementService } from 'app/admin/organization-management/organization-management.service';\nimport { Organization } from 'app/entities/organization.model';\n\n@Injectable({ providedIn: 'root' })\nexport class OrganizationMgmtResolve implements Resolve<any> {\n constructor(private organizationManagementService: OrganizationManagementService) {}\n\n resolve(route: ActivatedRouteSnapshot) {\n if (route.params['id']) {\n return this.organizationManagementService.getOrganizationById(route.params['id']);\n }\n return new Organization();\n }\n}\n\nexport const organizationMgmtRoute: Route[] = [\n {\n path: 'organization-management',\n component: OrganizationManagementComponent,\n resolve: {\n pagingParams: JhiResolvePagingParams,\n },\n data: {\n pageTitle: 'organizationManagement.title',\n },\n },\n {\n path: 'organization-management',\n data: {\n pageTitle: 'organizationManagement.title',\n },\n children: [\n {\n path: 'new',\n component: OrganizationManagementUpdateComponent,\n resolve: {\n organization: OrganizationMgmtResolve,\n },\n data: {\n pageTitle: 'organizationManagement.addLabel',\n },\n },\n {\n path: ':id',\n component: OrganizationManagementDetailComponent,\n resolve: {\n organization: OrganizationMgmtResolve,\n },\n data: {\n pageTitle: 'organizationManagement.title',\n breadcrumbLabelVariable: 'organization.id',\n },\n },\n {\n path: ':id',\n resolve: {\n organization: OrganizationMgmtResolve,\n },\n data: {\n breadcrumbLabelVariable: 'organization.id',\n },\n children: [\n {\n path: 'edit',\n component: OrganizationManagementUpdateComponent,\n data: {\n pageTitle: 'organizationManagement.addOrEditLabel',\n breadcrumbLabelVariable: 'organization.id',\n },\n },\n ],\n },\n ],\n },\n];\n" }, { "alpha_fraction": 0.7565217614173889, "alphanum_fraction": 0.7565217614173889, "avg_line_length": 27.75, "blob_id": "f0417400ffcc3e5870a6f7f270fb1b604359df58", "content_id": "a96f8c13606839456717edcc0e983c7dc2def770", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 230, "license_type": "permissive", "max_line_length": 77, "num_lines": 8, "path": "/src/main/webapp/app/exercises/shared/plagiarism/types/text/TextSubmissionElement.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { PlagiarismSubmissionElement } from '../PlagiarismSubmissionElement';\n\nexport class TextSubmissionElement extends PlagiarismSubmissionElement {\n column: number;\n line: number;\n file: string;\n length: number;\n}\n" }, { "alpha_fraction": 0.7391040325164795, "alphanum_fraction": 0.7403948307037354, "avg_line_length": 52.75510025024414, "blob_id": "7fd73f687b817fab0cfc2b7c3d889d963b1c2c3a", "content_id": "16323188fb3010b5cfbe491ab3b34b38ae14e52b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 13170, "license_type": "permissive", "max_line_length": 179, "num_lines": 245, "path": "/src/main/java/de/tum/in/www1/artemis/service/TutorParticipationService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.util.*;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.TutorParticipationStatus;\nimport de.tum.in.www1.artemis.domain.participation.TutorParticipation;\nimport de.tum.in.www1.artemis.repository.ExampleSubmissionRepository;\nimport de.tum.in.www1.artemis.repository.TutorParticipationRepository;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Service Implementation for managing TutorParticipation.\n */\n@Service\npublic class TutorParticipationService {\n\n private final Logger log = LoggerFactory.getLogger(TutorParticipationService.class);\n\n private final ExampleSubmissionRepository exampleSubmissionRepository;\n\n private static final String ENTITY_NAME = \"TutorParticipation\";\n\n private final TutorParticipationRepository tutorParticipationRepository;\n\n private final ExampleSubmissionService exampleSubmissionService;\n\n private static final float scoreRangePercentage = 10;\n\n public TutorParticipationService(TutorParticipationRepository tutorParticipationRepository, ExampleSubmissionRepository exampleSubmissionRepository,\n ExampleSubmissionService exampleSubmissionService) {\n this.tutorParticipationRepository = tutorParticipationRepository;\n this.exampleSubmissionRepository = exampleSubmissionRepository;\n this.exampleSubmissionService = exampleSubmissionService;\n }\n\n /**\n * Save a tutorParticipations.\n *\n * @param tutorParticipation the entity to save\n * @return the persisted entity\n */\n public TutorParticipation save(TutorParticipation tutorParticipation) {\n log.debug(\"Request to save TutorParticipation : {}\", tutorParticipation);\n return tutorParticipationRepository.saveAndFlush(tutorParticipation);\n }\n\n /**\n * Get one tutorParticipations by id.\n *\n * @param id the id of the entity\n * @return the entity\n */\n public TutorParticipation findOne(Long id) {\n log.debug(\"Request to get TutorParticipation : {}\", id);\n Optional<TutorParticipation> tutorParticipation = tutorParticipationRepository.findById(id);\n return tutorParticipation.orElse(null);\n }\n\n /**\n * Given an exercise and a tutor, it retrieves the participation of the tutor for that exercise. If there isn't any participation in the database, it returns a participation\n * with status NOT_PARTICIPATED\n *\n * @param exercise the exercise we want to retrieve the tutor participation\n * @param tutor the tutor of who we want to retrieve the participation\n * @return a tutor participation object for the pair (exercise, tutor) passed as argument\n */\n public TutorParticipation findByExerciseAndTutor(Exercise exercise, User tutor) {\n TutorParticipation participation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, tutor);\n\n if (participation == null) {\n participation = new TutorParticipation();\n participation.setStatus(TutorParticipationStatus.NOT_PARTICIPATED);\n }\n return participation;\n }\n\n /**\n * Checks if the tutor participation for the given values already exists to prevent duplicated values in the database\n * @param assessedExerciseId the exercise we want to retrieve the tutor participation\n * @param tutorId the tutor of who we want to retrieve the participation\n * @return true if the tutor participation exists, false otherwise\n */\n public Boolean existsByAssessedExerciseIdAndTutorId(Long assessedExerciseId, Long tutorId) {\n return tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(assessedExerciseId, tutorId);\n }\n\n /**\n * Given an exercise and a tutor it creates the participation of the tutor to that exercise The tutor starts a participation when she reads the grading instruction. If no\n * grading instructions are available, then she starts her participation clicking on \"Start participation\". Usually, the first step is `REVIEWED_INSTRUCTIONS`: after that, she\n * has to train reviewing some example submissions, and assessing others. If no example submissions are available, because the instructor hasn't created any, then she goes\n * directly to the next step, that allows her to assess students' participations\n *\n * @param exercise the exercise the tutor is going to participate to\n * @param tutor the tutor who is going to participate to the exercise\n * @return a TutorParticipation for the exercise\n */\n public TutorParticipation createNewParticipation(Exercise exercise, User tutor) {\n TutorParticipation tutorParticipation = new TutorParticipation();\n\n Long exampleSubmissionsCount = exampleSubmissionRepository.countAllByExerciseId(exercise.getId());\n\n if (exampleSubmissionsCount == 0) {\n tutorParticipation.setStatus(TutorParticipationStatus.TRAINED);\n }\n else {\n tutorParticipation.setStatus(TutorParticipationStatus.REVIEWED_INSTRUCTIONS);\n }\n\n tutorParticipation.setTutor(tutor);\n tutorParticipation.setAssessedExercise(exercise);\n\n return save(tutorParticipation);\n }\n\n /**\n * Given a course and a tutor, it finds all the participation of that tutor in the course, with related assessed exercise and trained example submissions\n *\n * @param course - the course we are interested in\n * @param user - the tutor who is querying the service\n * @return a list of tutor participation for the course\n */\n public List<TutorParticipation> findAllByCourseAndTutor(Course course, User user) {\n return tutorParticipationRepository.findAllByAssessedExercise_Course_IdAndTutor_Id(course.getId(), user.getId());\n }\n\n /**\n * Given an exercise, it adds to the tutor participation of that exercise the example submission passed as argument, if it is valid (e.g: if it is an example submission used\n * for tutorial, we check the result is close enough to the one of the instructor)\n *\n * @param exercise - the exercise we are referring to\n * @param exampleSubmission - the example submission to add\n * @param user - the user who invokes this request\n * @return the updated tutor participation\n * @throws EntityNotFoundException if example submission or tutor participation is not found\n * @throws BadRequestAlertException if tutor didn't review the instructions before assessing example submissions\n */\n public TutorParticipation addExampleSubmission(Exercise exercise, ExampleSubmission exampleSubmission, User user) throws EntityNotFoundException, BadRequestAlertException {\n TutorParticipation existingTutorParticipation = this.findByExerciseAndTutor(exercise, user);\n // Do not trust the user input\n Optional<ExampleSubmission> exampleSubmissionFromDatabase = exampleSubmissionRepository.findByIdWithResultsAndTutorParticipations(exampleSubmission.getId());\n\n if (existingTutorParticipation == null || exampleSubmissionFromDatabase.isEmpty()) {\n throw new EntityNotFoundException(\"There isn't such example submission, or there isn't any tutor participation for this exercise\");\n }\n\n ExampleSubmission originalExampleSubmission = exampleSubmissionFromDatabase.get();\n\n // Cannot start an example submission if the tutor hasn't participated to the exercise yet\n if (existingTutorParticipation.getStatus() == TutorParticipationStatus.NOT_PARTICIPATED) {\n throw new BadRequestAlertException(\"The tutor needs review the instructions before assessing example submissions\", ENTITY_NAME, \"wrongStatus\");\n }\n\n // Check if it is a tutorial or not\n boolean isTutorial = Boolean.TRUE.equals(originalExampleSubmission.isUsedForTutorial());\n\n // If it is a tutorial we check the assessment\n if (isTutorial) {\n // Retrieve the example feedback created by the instructor\n List<Feedback> existingFeedback = exampleSubmissionRepository.getFeedbackForExampleSubmission(exampleSubmission.getId());\n\n // Check if the result is the same\n // TODO: at the moment we check only the score +/10%, maybe we want to do something smarter?\n float instructorScore = calculateTotalScore(existingFeedback);\n float lowerInstructorScore = instructorScore - instructorScore / scoreRangePercentage;\n float higherInstructorScore = instructorScore + instructorScore / scoreRangePercentage;\n\n float tutorScore = calculateTotalScore(exampleSubmission.getSubmission().getLatestResult().getFeedbacks());\n\n if (lowerInstructorScore > tutorScore) {\n throw new BadRequestAlertException(\"tooLow\", ENTITY_NAME, \"tooLow\");\n }\n\n if (tutorScore > higherInstructorScore) {\n throw new BadRequestAlertException(\"tooHigh\", ENTITY_NAME, \"tooHigh\");\n }\n }\n\n List<ExampleSubmission> alreadyAssessedSubmissions = new ArrayList<>(existingTutorParticipation.getTrainedExampleSubmissions());\n\n // If the example submission was already assessed, we do not assess it again, we just return the current participation\n if (alreadyAssessedSubmissions.contains(exampleSubmission)) {\n return existingTutorParticipation;\n }\n\n long numberOfExampleSubmissionsForTutor = exampleSubmissionRepository.findAllWithResultByExerciseId(exercise.getId()).stream()\n // We are only interested in example submissions with an assessment as these are the ones that can be reviewed/assessed by tutors.\n // Otherwise, the tutor could not reach the total number of example submissions, if there are example submissions without assessment.\n // In this case the tutor could not reach status \"TRAINED\" in the if statement below and would not be allowed\n // to asses student submissions in the assessment dashboard.\n .filter(exSub -> exSub.getSubmission() != null && exSub.getSubmission().getLatestResult() != null && exSub.getSubmission().getLatestResult().isExampleResult())\n .count();\n int numberOfAlreadyAssessedSubmissions = alreadyAssessedSubmissions.size() + 1; // +1 because we haven't added yet the one we just did\n\n /*\n * When the tutor has read and assessed all the exercises, the tutor status goes to the next step.\n */\n if (numberOfAlreadyAssessedSubmissions >= numberOfExampleSubmissionsForTutor) {\n existingTutorParticipation.setStatus(TutorParticipationStatus.TRAINED);\n }\n\n // keep example submission set reference with loaded submission.results to reconnect after save response from DB\n var exampleSubmissionSet = existingTutorParticipation.getTrainedExampleSubmissions();\n\n existingTutorParticipation = existingTutorParticipation.addTrainedExampleSubmissions(originalExampleSubmission);\n exampleSubmissionService.save(originalExampleSubmission);\n existingTutorParticipation = save(existingTutorParticipation);\n\n existingTutorParticipation.setTrainedExampleSubmissions(exampleSubmissionSet);\n existingTutorParticipation.getTrainedExampleSubmissions().add(originalExampleSubmission);\n\n return existingTutorParticipation;\n }\n\n /**\n * This method removes the tutor participation for the example submission of an exercise\n * @param exercise the exercise to which the example submission and tutor participation are linked to\n * @param user the user for which the tutor participation should be removed\n */\n public void removeTutorParticipations(Exercise exercise, User user) {\n if (!tutorParticipationRepository.existsByAssessedExerciseIdAndTutorId(exercise.getId(), user.getId())) {\n return;\n }\n\n Set<ExampleSubmission> exampleSubmissions = exampleSubmissionRepository.findAllByExerciseId(exercise.getId());\n TutorParticipation tutorParticipation = tutorParticipationRepository.findWithEagerExampleSubmissionAndResultsByAssessedExerciseAndTutor(exercise, user);\n\n for (ExampleSubmission exampleSubmission : exampleSubmissions) {\n Optional<ExampleSubmission> exampleSubmissionWithTutorParticipation = exampleSubmissionRepository.findByIdWithResultsAndTutorParticipations(exampleSubmission.getId());\n if (exampleSubmissionWithTutorParticipation.isPresent()) {\n exampleSubmissionWithTutorParticipation.get().removeTutorParticipations(tutorParticipation);\n tutorParticipationRepository.delete(tutorParticipation);\n }\n }\n }\n\n private float calculateTotalScore(List<Feedback> feedbacks) {\n return (float) feedbacks.stream().mapToDouble(Feedback::getCredits).sum();\n }\n}\n" }, { "alpha_fraction": 0.7125311493873596, "alphanum_fraction": 0.7323780655860901, "avg_line_length": 56.620513916015625, "blob_id": "b349a96b688eae9b84a9694b20bdd45432a23521", "content_id": "1f47106b0c20ce3850f48e3e6f2fa41380ec50d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11236, "license_type": "permissive", "max_line_length": 179, "num_lines": 195, "path": "/src/test/java/de/tum/in/www1/artemis/service/StudentExamAccessServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.StudentExam;\nimport de.tum.in.www1.artemis.repository.CourseRepository;\nimport de.tum.in.www1.artemis.repository.StudentExamRepository;\nimport de.tum.in.www1.artemis.service.exam.StudentExamAccessService;\n\npublic class StudentExamAccessServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private StudentExamAccessService studentExamAccessService;\n\n @Autowired\n private StudentExamRepository studentExamRepository;\n\n @Autowired\n private CourseRepository courseRepository;\n\n private List<User> users;\n\n private Course course1;\n\n private Course course2;\n\n private Exam exam1;\n\n private Exam exam2;\n\n private StudentExam studentExam1;\n\n @BeforeEach\n void init() {\n users = database.addUsers(2, 0, 0);\n course1 = database.addEmptyCourse();\n course2 = database.addEmptyCourse();\n course2.setStudentGroupName(\"another-group\");\n courseRepository.save(course2);\n exam1 = database.addActiveExamWithRegisteredUser(course1, users.get(0));\n studentExam1 = database.addStudentExam(exam1);\n studentExam1.setUser(users.get(0));\n studentExamRepository.save(studentExam1);\n exam2 = database.addExam(course2);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testIsAtLeastStudentInCourse() {\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkCourseAndExamAccess(course2.getId(), exam2.getId(), users.get(0), false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course2.getId(), exam2.getId(), studentExam1.getId(), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure3 = studentExamAccessService.checkStudentExamAccess(course2.getId(), exam2.getId(), studentExam1.getId(), users.get(0), false);\n assertThat(accessFailure3.isPresent()).isTrue();\n assertThat(accessFailure3.get()).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testExamExists() {\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkCourseAndExamAccess(course1.getId(), 1255L, users.get(0), false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(notFound());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), 1255L, studentExam1.getId(), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(notFound());\n Optional<ResponseEntity<Void>> accessFailure3 = studentExamAccessService.checkStudentExamAccess(course1.getId(), 1255L, studentExam1.getId(), users.get(0), false);\n assertThat(accessFailure3.isPresent()).isTrue();\n assertThat(accessFailure3.get()).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testExamBelongsToCourse() {\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkCourseAndExamAccess(course1.getId(), exam2.getId(), users.get(0), false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(conflict());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam2.getId(), studentExam1.getId(), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(conflict());\n Optional<ResponseEntity<Void>> accessFailure3 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam2.getId(), studentExam1.getId(), users.get(0), false);\n assertThat(accessFailure3.isPresent()).isTrue();\n assertThat(accessFailure3.get()).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testExamIsLive() {\n // Exam is not visible.\n Exam examNotStarted = database.addExam(course1, users.get(0), ZonedDateTime.now().plusHours(1), ZonedDateTime.now().plusHours(2), ZonedDateTime.now().plusHours(3));\n Optional<ResponseEntity<Void>> accessFailure1_1 = studentExamAccessService.checkCourseAndExamAccess(course1.getId(), examNotStarted.getId(), users.get(0), false);\n assertThat(accessFailure1_1.isPresent()).isTrue();\n assertThat(accessFailure1_1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure1_2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examNotStarted.getId(), studentExam1.getId(), false);\n assertThat(accessFailure1_2.isPresent()).isTrue();\n assertThat(accessFailure1_2.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure1_3 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examNotStarted.getId(), studentExam1.getId(),\n users.get(0), false);\n assertThat(accessFailure1_3.isPresent()).isTrue();\n assertThat(accessFailure1_3.get()).isEqualTo(forbidden());\n\n // Exam has ended. After exam has ended, it should still be retrievable by the students to see their participation\n Exam examEnded = database.addExam(course1, users.get(0), ZonedDateTime.now().minusHours(4), ZonedDateTime.now().minusHours(3), ZonedDateTime.now().minusHours(1));\n StudentExam studentExamEnded = database.addStudentExam(examEnded);\n studentExamEnded.setUser(users.get(0));\n studentExamRepository.save(studentExamEnded);\n Optional<ResponseEntity<Void>> accessFailure2_1 = studentExamAccessService.checkCourseAndExamAccess(course1.getId(), examEnded.getId(), users.get(0), false);\n assertThat(accessFailure2_1.isPresent()).isFalse();\n Optional<ResponseEntity<Void>> accessFailure2_2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examEnded.getId(), studentExamEnded.getId(), false);\n assertThat(accessFailure2_2.isPresent()).isFalse();\n Optional<ResponseEntity<Void>> accessFailure2_3 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examEnded.getId(), studentExamEnded.getId(),\n users.get(0), false);\n assertThat(accessFailure2_3.isPresent()).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testUserIsRegisteredForExam() {\n Exam examNotRegistered = database.addExam(course1, users.get(1), ZonedDateTime.now().minusHours(4), ZonedDateTime.now().minusHours(1), ZonedDateTime.now().plusHours(1));\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkCourseAndExamAccess(course1.getId(), examNotRegistered.getId(), users.get(0), false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examNotRegistered.getId(), studentExam1.getId(), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure3 = studentExamAccessService.checkStudentExamAccess(course1.getId(), examNotRegistered.getId(), studentExam1.getId(),\n users.get(0), false);\n assertThat(accessFailure3.isPresent()).isTrue();\n assertThat(accessFailure3.get()).isEqualTo(forbidden());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testUserStudentExamExists() {\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), 55L, false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(notFound());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), 55L, users.get(0), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(notFound());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testExamIdEqualsExamOfStudentExam() {\n StudentExam studentExamNotRelatedToExam1 = database.addStudentExam(exam2);\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), studentExamNotRelatedToExam1.getId(),\n false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(conflict());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), studentExamNotRelatedToExam1.getId(),\n users.get(0), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(conflict());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCurrentUserIsUserOfStudentExam() {\n StudentExam studentExamWithOtherUser = database.addStudentExam(exam1);\n studentExamWithOtherUser.setUser(users.get(1));\n studentExamRepository.save(studentExamWithOtherUser);\n Optional<ResponseEntity<Void>> accessFailure1 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), studentExamWithOtherUser.getId(), false);\n assertThat(accessFailure1.isPresent()).isTrue();\n assertThat(accessFailure1.get()).isEqualTo(forbidden());\n Optional<ResponseEntity<Void>> accessFailure2 = studentExamAccessService.checkStudentExamAccess(course1.getId(), exam1.getId(), studentExamWithOtherUser.getId(),\n users.get(0), false);\n assertThat(accessFailure2.isPresent()).isTrue();\n assertThat(accessFailure2.get()).isEqualTo(forbidden());\n }\n}\n" }, { "alpha_fraction": 0.7384615540504456, "alphanum_fraction": 0.7384615540504456, "avg_line_length": 46.66666793823242, "blob_id": "029d59c94292649063cf1b8f3252028be217c81e", "content_id": "c4eda51f81e6873b4f94d3c4ad3bc029d81ac64d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1430, "license_type": "permissive", "max_line_length": 149, "num_lines": 30, "path": "/src/main/webapp/app/course/manage/course-exercise-submission-result-simulation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { Observable } from 'rxjs/Observable';\nimport { HttpResponse, HttpClient } from '@angular/common/http';\n\n/**\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n\n@Injectable({ providedIn: 'root' })\nexport class CourseExerciseSubmissionResultSimulationService {\n constructor(private http: HttpClient) {}\n\n /**\n * Simulate a submission to a programming exercise (only for testing purposes noVersionControlAndContinuousIntegrationAvailable).\n * @param exerciseId Id of the exercise to submit to.\n */\n simulateSubmission(exerciseId: number): Observable<HttpResponse<ProgrammingSubmission>> {\n return this.http.post<ProgrammingSubmission>(`api/exercises/${exerciseId}/submissions/no-vcs-and-ci-available`, {}, { observe: 'response' });\n }\n\n /**\n * Simulate a result of a programming exercise (only for testing purposes noVersionControlAndContinuousIntegrationAvailable).\n * @param exerciseId Id of the exercise the result is for.\n */\n simulateResult(exerciseId: number): Observable<HttpResponse<Result>> {\n return this.http.post<Result>(`api/exercises/${exerciseId}/results/no-vcs-and-ci-available`, {}, { observe: 'response' });\n }\n}\n" }, { "alpha_fraction": 0.6495770215988159, "alphanum_fraction": 0.6511151194572449, "avg_line_length": 39.216495513916016, "blob_id": "c53ea183d561be2d83257092b820c9404ecf0477", "content_id": "70050b2d4d71e503a88690fea6e2ceeca3ee994d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3901, "license_type": "permissive", "max_line_length": 132, "num_lines": 97, "path": "/src/main/webapp/app/shared/notification/notification-popup/notification-popup.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Router, UrlTree } from '@angular/router';\nimport { NotificationService } from 'app/shared/notification/notification.service';\nimport { User } from 'app/core/user/user.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { Notification } from 'app/entities/notification.model';\nimport { GroupNotification } from 'app/entities/group-notification.model';\n\n@Component({\n selector: 'jhi-notification-popup',\n templateUrl: './notification-popup.component.html',\n styleUrls: ['./notification-popup.scss'],\n})\nexport class NotificationPopupComponent implements OnInit {\n notifications: Notification[] = [];\n\n constructor(private accountService: AccountService, private notificationService: NotificationService, private router: Router) {}\n\n /**\n * Subscribe to notification updates that are received via websocket if the user is logged in.\n */\n ngOnInit(): void {\n this.accountService.getAuthenticationState().subscribe((user: User | undefined) => {\n if (user) {\n this.subscribeToNotificationUpdates();\n }\n });\n }\n\n /**\n * Removes the notification at the specified index from the notifications array.\n * @param index {number}\n */\n removeNotification(index: number): void {\n this.notifications.splice(index, 1);\n }\n\n /**\n * Navigate to the target (view) of the notification that the user clicked.\n * @param notification {Notification}\n */\n navigateToTarget(notification: Notification): void {\n this.router.navigateByUrl(this.notificationTargetRoute(notification));\n }\n\n private notificationTargetRoute(notification: Notification): UrlTree | string {\n if (notification.target) {\n const target = JSON.parse(notification.target);\n return this.router.createUrlTree([target.mainPage, target.course, target.entity, target.id]);\n }\n return this.router.url;\n }\n\n private subscribeToNotificationUpdates(): void {\n this.notificationService.subscribeToNotificationUpdates().subscribe((notification: Notification) => {\n this.addNotification(notification);\n });\n }\n\n private addNotification(notification: Notification): void {\n // Only add a notification if it does not already exist.\n if (notification && !this.notifications.some(({ id }) => id === notification.id)) {\n // For now only notifications about a started quiz should be displayed.\n if (notification.title === 'Quiz started') {\n this.addQuizNotification(notification);\n this.setRemovalTimeout(notification);\n }\n }\n }\n\n /**\n * Will add a notification about a started quiz to the component's state. The notification will\n * only be added if the user is not already on the target page (or the live participation page).\n * @param notification {Notification}\n */\n private addQuizNotification(notification: Notification): void {\n if (notification.target) {\n const target = JSON.parse(notification.target);\n target.entity = 'quiz-exercises';\n const notificationWithLiveQuizTarget = {\n target: JSON.stringify(target),\n } as GroupNotification;\n if (\n !this.router.isActive(this.notificationTargetRoute(notification), true) &&\n !this.router.isActive(this.notificationTargetRoute(notificationWithLiveQuizTarget) + '/live', true)\n ) {\n this.notifications.unshift(notification);\n }\n }\n }\n\n private setRemovalTimeout(notification: Notification): void {\n setTimeout(() => {\n this.notifications = this.notifications.filter(({ id }) => id !== notification.id);\n }, 30000);\n }\n}\n" }, { "alpha_fraction": 0.598238468170166, "alphanum_fraction": 0.6023035049438477, "avg_line_length": 43.727272033691406, "blob_id": "812fd8e605994c1ec9c7b32e9d958d25ce96b512", "content_id": "f4ddd3f3441f4e9ad259348e0785155e9914d7e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1476, "license_type": "permissive", "max_line_length": 125, "num_lines": 33, "path": "/src/main/webapp/app/core/interceptor/errorhandler.interceptor.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { tap } from 'rxjs/operators';\n\n@Injectable()\nexport class ErrorHandlerInterceptor implements HttpInterceptor {\n constructor(private eventManager: JhiEventManager) {}\n\n /**\n * Identifies and handles a given HTTP request. If the request's error status is not 401 and the error message is empty\n * or the error url includes '/api/account' the httpError is broadcasted to the observer.\n * @param request The outgoing request object to handle.\n * @param next The next interceptor in the chain, or the server\n * if no interceptors remain in the chain.\n * @returns An observable of the event stream.\n */\n intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n return next.handle(request).pipe(\n tap(\n () => {},\n (err: any) => {\n if (err instanceof HttpErrorResponse) {\n if (!(err.status === 401 && (err.message === '' || (err.url && err.url.includes('/api/account'))))) {\n this.eventManager.broadcast({ name: 'artemisApp.httpError', content: err });\n }\n }\n },\n ),\n );\n }\n}\n" }, { "alpha_fraction": 0.6776119470596313, "alphanum_fraction": 0.6801306009292603, "avg_line_length": 49.09345626831055, "blob_id": "c9bce07bc5756733e6425ecb20577007f09c8f2e", "content_id": "66a9c79ec43073b16005de4dc151e3aad16b3afd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10720, "license_type": "permissive", "max_line_length": 174, "num_lines": 214, "path": "/src/test/javascript/spec/component/code-editor/code-editor-ace.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { DebugElement, EventEmitter } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { TreeviewModule } from 'ngx-treeview';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { Subject } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { CreateFileChange, FileType, RenameFileChange } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { CodeEditorRepositoryFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { CodeEditorFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-file.service';\nimport { CodeEditorAceComponent } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component';\nimport { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { MockLocalStorageService } from '../../helpers/mocks/service/mock-local-storage.service';\nimport { ArtemisProgrammingManualAssessmentModule } from 'app/exercises/programming/assess/programming-manual-assessment.module';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockPipe } from 'ng-mocks';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorAceComponent', () => {\n let comp: CodeEditorAceComponent;\n let fixture: ComponentFixture<CodeEditorAceComponent>;\n let debugElement: DebugElement;\n let codeEditorRepositoryFileService: CodeEditorRepositoryFileService;\n let loadRepositoryFileStub: SinonStub;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, AceEditorModule, TreeviewModule.forRoot(), ArtemisProgrammingManualAssessmentModule],\n declarations: [CodeEditorAceComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n CodeEditorFileService,\n { provide: CodeEditorRepositoryFileService, useClass: MockCodeEditorRepositoryFileService },\n { provide: LocalStorageService, useClass: MockLocalStorageService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CodeEditorAceComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n codeEditorRepositoryFileService = debugElement.injector.get(CodeEditorRepositoryFileService);\n loadRepositoryFileStub = stub(codeEditorRepositoryFileService, 'getFile');\n });\n });\n\n afterEach(() => {\n loadRepositoryFileStub.restore();\n });\n\n it('without any inputs, should still render correctly without ace, showing a placeholder', () => {\n fixture.detectChanges();\n const placeholder = debugElement.query(By.css('#no-file-selected'));\n expect(placeholder).to.exist;\n const aceEditor = debugElement.query(By.css('#ace-code-editor'));\n expect(aceEditor.nativeElement.hasAttribute('hidden')).to.be.true;\n });\n\n it('if the component is loading a file from server, it should show the editor in a readonly state', () => {\n comp.selectedFile = 'dummy';\n comp.isLoading = true;\n fixture.detectChanges();\n const placeholder = debugElement.query(By.css('#no-file-selected'));\n expect(placeholder).not.to.exist;\n const aceEditor = debugElement.query(By.css('#ace-code-editor'));\n expect(aceEditor.nativeElement.hasAttribute('hidden')).to.be.true;\n expect(comp.editor.getEditor().getReadOnly()).to.be.true;\n\n comp.isLoading = false;\n fixture.detectChanges();\n expect(aceEditor.nativeElement.hasAttribute('hidden')).to.be.false;\n expect(comp.editor.getEditor().getReadOnly()).to.be.false;\n });\n\n it('if a file is selected and the component is not loading a file from server, the editor should be usable', () => {\n comp.selectedFile = 'dummy';\n comp.isLoading = false;\n fixture.detectChanges();\n const placeholder = debugElement.query(By.css('#no-file-selected'));\n expect(placeholder).not.to.exist;\n const aceEditor = debugElement.query(By.css('#ace-code-editor'));\n expect(aceEditor.nativeElement.hasAttribute('hidden')).to.be.false;\n expect(comp.editor.getEditor().getReadOnly()).to.be.false;\n });\n\n it('should not load the file from server on selected file change if the file is already in session', () => {\n const selectedFile = 'dummy';\n const fileSession = {};\n const loadFileSubject = new Subject();\n const initEditorAfterFileChangeSpy = spy(comp, 'initEditorAfterFileChange');\n loadRepositoryFileStub.returns(loadFileSubject);\n comp.selectedFile = selectedFile;\n comp.fileSession = fileSession;\n\n triggerChanges(comp, { property: 'selectedFile', currentValue: selectedFile });\n fixture.detectChanges();\n\n expect(comp.isLoading).to.be.true;\n expect(loadRepositoryFileStub).to.have.been.calledOnceWithExactly(selectedFile);\n expect(initEditorAfterFileChangeSpy).to.not.have.been.called;\n loadFileSubject.next({ fileName: selectedFile, fileContent: 'lorem ipsum' });\n fixture.detectChanges();\n\n expect(comp.isLoading).to.be.false;\n expect(initEditorAfterFileChangeSpy).to.have.been.calledOnceWithExactly();\n });\n\n it('should not load the file from server on selected file change if the file is already in session', () => {\n const selectedFile = 'dummy';\n const fileSession = { [selectedFile]: { code: 'lorem ipsum', cursor: { column: 0, row: 0 } } };\n const initEditorAfterFileChangeSpy = spy(comp, 'initEditorAfterFileChange');\n const loadFileSpy = spy(comp, 'loadFile');\n comp.selectedFile = selectedFile;\n comp.fileSession = fileSession;\n\n triggerChanges(comp, { property: 'selectedFile', currentValue: selectedFile });\n fixture.detectChanges();\n\n expect(initEditorAfterFileChangeSpy).to.have.been.calledOnceWithExactly();\n expect(loadFileSpy).not.to.have.been.called;\n });\n\n it('should update file session references on file rename', () => {\n const selectedFile = 'file';\n const newFileName = 'newFilename';\n const fileChange = new RenameFileChange(FileType.FILE, selectedFile, newFileName);\n const fileSession = { [selectedFile]: { code: 'lorem ipsum', cursor: { column: 0, row: 0 } }, anotherFile: { code: 'lorem ipsum 2', cursor: { column: 0, row: 0 } } };\n comp.selectedFile = newFileName;\n comp.fileSession = fileSession;\n\n comp.onFileChange(fileChange);\n\n expect(comp.fileSession).to.deep.equal({ anotherFile: fileSession.anotherFile, [fileChange.newFileName]: fileSession[selectedFile] });\n });\n\n it('should init editor on newly created file if selected', () => {\n const selectedFile = 'file';\n const fileChange = new CreateFileChange(FileType.FILE, selectedFile);\n const fileSession = { anotherFile: { code: 'lorem ipsum 2', cursor: { column: 0, row: 0 } } };\n const initEditorAfterFileChangeSpy = spy(comp, 'initEditorAfterFileChange');\n comp.selectedFile = selectedFile;\n comp.fileSession = fileSession;\n\n comp.onFileChange(fileChange);\n\n expect(initEditorAfterFileChangeSpy).to.have.been.calledOnceWithExactly();\n expect(comp.fileSession).to.deep.equal({ anotherFile: fileSession.anotherFile, [fileChange.fileName]: { code: '', cursor: { row: 0, column: 0 } } });\n });\n\n it('should not do anything on file content change if the code has not changed', () => {\n const textChangeEmitter = new EventEmitter<string>();\n comp.editor.textChanged = textChangeEmitter;\n const onFileContentChangeSpy = spy(comp.onFileContentChange, 'emit');\n\n const selectedFile = 'file';\n const fileSession = { [selectedFile]: { code: 'lorem ipsum', cursor: { column: 0, row: 0 } } };\n comp.selectedFile = selectedFile;\n comp.fileSession = fileSession;\n\n textChangeEmitter.emit('lorem ipsum');\n\n expect(onFileContentChangeSpy).to.not.have.been.called;\n });\n\n it('should update build log errors and emit a message on file text change', () => {\n const onFileContentChangeSpy = spy(comp.onFileContentChange, 'emit');\n\n const selectedFile = 'file';\n const newFileContent = 'lorem ipsum new';\n const fileSession = { [selectedFile]: { code: 'lorem ipsum', cursor: { column: 0, row: 0 } } };\n const annotations = [{ fileName: selectedFile, row: 5, column: 4, text: 'error', type: 'error', timestamp: 0 }];\n const editorChange = { start: { row: 1, column: 1 }, end: { row: 2, column: 1 }, action: 'remove' };\n\n comp.selectedFile = selectedFile;\n comp.fileSession = fileSession;\n comp.annotationsArray = annotations;\n\n comp.updateAnnotations(editorChange);\n comp.onFileTextChanged(newFileContent);\n\n expect(onFileContentChangeSpy).to.have.been.calledOnceWithExactly({ file: selectedFile, fileContent: newFileContent });\n const newAnnotations = [{ fileName: selectedFile, text: 'error', type: 'error', timestamp: 0, row: 4, column: 4 }];\n expect(comp.annotationsArray).to.deep.equal(newAnnotations);\n });\n\n it('should be in readonly mode and display feedback when in tutor assessment', () => {\n comp.isTutorAssessment = true;\n comp.fileFeedbacks = [];\n const displayFeedbacksSpy = spy(comp, 'displayFeedbacks');\n comp.onFileTextChanged('newFileContent');\n\n expect(comp.editor.getEditor().getReadOnly()).to.be.true;\n expect(displayFeedbacksSpy).to.have.been.calledOnce;\n });\n\n it('should setup inline comment buttons in gutter', () => {\n comp.isTutorAssessment = true;\n comp.readOnlyManualFeedback = false;\n comp.fileFeedbacks = [];\n const setupLineIconsSpy = spy(comp, 'setupLineIcons');\n const observerDomSpy = spy(comp, 'observerDom');\n comp.onFileTextChanged('newFileContent');\n\n expect(setupLineIconsSpy).to.be.calledOnce;\n expect(observerDomSpy).to.be.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.7057324647903442, "alphanum_fraction": 0.7087048888206482, "avg_line_length": 40.31578826904297, "blob_id": "55b577acb23cc30ae62d09d0161f2e8ea34825db", "content_id": "a6c9fd98c181c9266f1846ba2b7966f27468672e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2355, "license_type": "permissive", "max_line_length": 185, "num_lines": 57, "path": "/src/main/java/de/tum/in/www1/artemis/repository/TeamScoreRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.Team;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.scores.TeamScore;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreAverageDTO;\n\n@Repository\npublic interface TeamScoreRepository extends JpaRepository<TeamScore, Long> {\n\n void deleteAllByTeam(Team team);\n\n @EntityGraph(type = LOAD, attributePaths = { \"team\", \"exercise\", \"lastResult\", \"lastRatedResult\" })\n Optional<TeamScore> findTeamScoreByExerciseAndTeam(Exercise exercise, Team team);\n\n @EntityGraph(type = LOAD, attributePaths = { \"team\", \"exercise\", \"lastResult\", \"lastRatedResult\" })\n List<TeamScore> findAllByExerciseIn(Set<Exercise> exercises, Pageable pageable);\n\n @Query(\"\"\"\n SELECT new de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreAverageDTO(t.team, AVG(t.lastScore), AVG(t.lastRatedScore), AVG(t.lastPoints), AVG(t.lastRatedPoints))\n FROM TeamScore t\n WHERE t.exercise IN :exercises\n GROUP BY t.team\n\n \"\"\")\n List<ParticipantScoreAverageDTO> getAvgScoreOfTeamInExercises(@Param(\"exercises\") Set<Exercise> exercises);\n\n @Query(\"\"\"\n SELECT DISTINCT t\n FROM TeamScore t\n WHERE t.exercise = :exercise AND :user MEMBER OF t.team.students\n \"\"\")\n Optional<TeamScore> findTeamScoreByExerciseAndUserLazy(@Param(\"exercise\") Exercise exercise, @Param(\"user\") User user);\n\n @Query(\"\"\"\n SELECT ts.team, SUM(ts.lastRatedPoints)\n FROM TeamScore ts\n WHERE ts.exercise IN :exercises\n GROUP BY ts.team\n \"\"\")\n List<Object[]> getAchievedPointsOfTeams(@Param(\"exercises\") Set<Exercise> exercises);\n\n}\n" }, { "alpha_fraction": 0.7321428656578064, "alphanum_fraction": 0.7321428656578064, "avg_line_length": 23, "blob_id": "e0511e05718903a55a6e09b7f3905087a7330b9f", "content_id": "cb13e1230d9526ca884aa4e26152d6cb9b3dfb7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 168, "license_type": "permissive", "max_line_length": 46, "num_lines": 7, "path": "/src/main/webapp/app/entities/quiz/course-management-statistics-model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class CourseManagementStatisticsModel {\n public exerciseId: number;\n public exerciseName: string;\n public averageScore: number;\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.6769638061523438, "alphanum_fraction": 0.6778464317321777, "avg_line_length": 46.705265045166016, "blob_id": "41ea3c69b05fb6c44b803e86ef3e8ac454574812", "content_id": "483101935aef248a944433fc372791e642d10aef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4532, "license_type": "permissive", "max_line_length": 179, "num_lines": 95, "path": "/src/test/javascript/spec/component/programming-assessment/programming-assessment-inline-feedback.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { spy } from 'sinon';\n\nimport { CodeEditorTutorAssessmentInlineFeedbackComponent } from 'app/exercises/programming/assess/code-editor-tutor-assessment-inline-feedback.component';\nimport { ArtemisProgrammingManualAssessmentModule } from 'app/exercises/programming/assess/programming-manual-assessment.module';\nimport { FeedbackType } from 'app/entities/feedback.model';\nimport { GradingInstruction } from 'app/exercises/shared/structured-grading-criterion/grading-instruction.model';\nimport { StructuredGradingCriterionService } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorTutorAssessmentInlineFeedbackComponent', () => {\n let comp: CodeEditorTutorAssessmentInlineFeedbackComponent;\n let fixture: ComponentFixture<CodeEditorTutorAssessmentInlineFeedbackComponent>;\n let sgiService: StructuredGradingCriterionService;\n const fileName = 'testFile';\n const codeLine = 1;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisProgrammingManualAssessmentModule],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n // Ignore console errors\n console.error = () => {\n return false;\n };\n fixture = TestBed.createComponent(CodeEditorTutorAssessmentInlineFeedbackComponent);\n comp = fixture.componentInstance;\n // @ts-ignore\n comp.feedback = undefined;\n comp.readOnly = false;\n comp.selectedFile = fileName;\n comp.codeLine = codeLine;\n sgiService = fixture.debugElement.injector.get(StructuredGradingCriterionService);\n });\n });\n\n it('should update feedback and emit to parent', () => {\n const onUpdateFeedbackSpy = spy(comp.onUpdateFeedback, 'emit');\n comp.updateFeedback();\n\n expect(comp.feedback.reference).to.be.equal(`file:${fileName}_line:${codeLine}`);\n expect(comp.feedback.type).to.be.equal(FeedbackType.MANUAL);\n expect(onUpdateFeedbackSpy).to.be.calledOnceWithExactly(comp.feedback);\n });\n\n it('should enable edit feedback and emit to parent', () => {\n const onEditFeedbackSpy = spy(comp.onEditFeedback, 'emit');\n comp.editFeedback(codeLine);\n\n expect(onEditFeedbackSpy).to.be.calledOnceWithExactly(codeLine);\n });\n\n it('should cancel feedback and emit to parent', () => {\n const onCancelFeedbackSpy = spy(comp.onCancelFeedback, 'emit');\n comp.cancelFeedback();\n\n expect(onCancelFeedbackSpy).to.be.calledOnceWithExactly(codeLine);\n });\n\n it('should delete feedback and emit to parent', () => {\n const onDeleteFeedbackSpy = spy(comp.onDeleteFeedback, 'emit');\n global.confirm = () => true;\n const confirmSpy = spy(window, 'confirm');\n comp.deleteFeedback();\n\n expect(confirmSpy).to.be.calledOnce;\n expect(onDeleteFeedbackSpy).to.be.calledOnceWithExactly(comp.feedback);\n });\n\n it('should update feedback with SGI and emit to parent', () => {\n const instruction: GradingInstruction = { id: 1, credits: 2, feedback: 'test', gradingScale: 'good', instructionDescription: 'description of instruction', usageCount: 0 };\n // Fake call as a DragEvent cannot be created programmatically\n spyOn(sgiService, 'updateFeedbackWithStructuredGradingInstructionEvent').and.callFake(() => {\n comp.feedback.gradingInstruction = instruction;\n comp.feedback.credits = instruction.credits;\n comp.feedback.detailText = instruction.feedback;\n });\n // Call spy function with empty event\n comp.updateFeedbackOnDrop(new Event(''));\n\n expect(comp.feedback.gradingInstruction).to.be.equal(instruction);\n expect(comp.feedback.credits).to.be.equal(instruction.credits);\n expect(comp.feedback.detailText).to.be.equal(instruction.feedback);\n expect(comp.feedback.reference).to.be.equal(`file:${fileName}_line:${codeLine}`);\n });\n});\n" }, { "alpha_fraction": 0.5800978541374207, "alphanum_fraction": 0.5823817253112793, "avg_line_length": 30.275510787963867, "blob_id": "52b27fcfe975c6006f972648e77c4481c3c0ad5f", "content_id": "5a8da5d197f12b9b088ce26b30387916ede912e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3065, "license_type": "permissive", "max_line_length": 101, "num_lines": 98, "path": "/src/main/webapp/app/overview/student-questions/student-votes/student-votes.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, EventEmitter, Input, Output } from '@angular/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { User } from 'app/core/user/user.model';\n\nexport interface StudentVotesAction {\n name: StudentVotesActionName;\n value: number;\n}\n\ninterface StudentVote {\n isPositive: boolean;\n}\n\n/**\n * Names for interacting with parent component\n * @enum { number }\n */\nexport enum StudentVotesActionName {\n VOTE_CHANGE,\n}\n\n@Component({\n selector: 'jhi-student-votes',\n templateUrl: './student-votes.component.html',\n styleUrls: ['./../student-questions.scss'],\n})\nexport class StudentVotesComponent implements OnInit {\n @Input() questionId: number;\n @Input() votes: number;\n @Output() interactVotes = new EventEmitter<StudentVotesAction>();\n\n user: User;\n userVote: StudentVote | null;\n voteValueChange = 0;\n\n constructor(private localStorage: LocalStorageService, private accountService: AccountService) {}\n\n /**\n * load user's vote\n */\n ngOnInit(): void {\n this.accountService.identity().then((user: User) => {\n this.user = user;\n this.userVote = this.localStorage.retrieve(`q${this.questionId}u${this.user.id}`);\n });\n }\n\n /**\n * toggle upvote\n */\n toggleUpVote(): void {\n if (this.userVote) {\n if (this.userVote.isPositive) {\n this.userVote = null;\n this.voteValueChange = -1;\n this.localStorage.clear(`q${this.questionId}u${this.user.id}`);\n } else {\n this.userVote.isPositive = true;\n this.voteValueChange = 2;\n this.localStorage.store(`q${this.questionId}u${this.user.id}`, this.userVote);\n }\n } else {\n this.userVote = { isPositive: true };\n this.voteValueChange = 1;\n this.localStorage.store(`q${this.questionId}u${this.user.id}`, this.userVote);\n }\n this.interactVotes.emit({\n name: StudentVotesActionName.VOTE_CHANGE,\n value: this.voteValueChange,\n });\n }\n\n /**\n * toggle downvote\n */\n toggleDownVote(): void {\n if (this.userVote) {\n if (this.userVote.isPositive) {\n this.userVote.isPositive = false;\n this.voteValueChange = -2;\n this.localStorage.store(`q${this.questionId}u${this.user.id}`, this.userVote);\n } else {\n this.userVote = null;\n this.voteValueChange = 1;\n this.localStorage.clear(`q${this.questionId}u${this.user.id}`);\n }\n } else {\n this.userVote = { isPositive: false };\n this.voteValueChange = -1;\n this.localStorage.store(`q${this.questionId}u${this.user.id}`, this.userVote);\n }\n this.interactVotes.emit({\n name: StudentVotesActionName.VOTE_CHANGE,\n value: this.voteValueChange,\n });\n }\n}\n" }, { "alpha_fraction": 0.7114682197570801, "alphanum_fraction": 0.7136595845222473, "avg_line_length": 47.89285659790039, "blob_id": "1e324c6a31d58a29bd6ceeaefabaea01ec728b82", "content_id": "3320bd3325266b0d64f7c8b7ce34e258106b8d41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4107, "license_type": "permissive", "max_line_length": 161, "num_lines": 84, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-card/learning-goal-card.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnDestroy, OnInit } from '@angular/core';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { LearningGoalDetailModalComponent } from 'app/course/learning-goals/learning-goal-detail-modal/learning-goal-detail-modal.component';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { CourseLearningGoalProgress } from 'app/course/learning-goals/learning-goal-course-progress.dtos.model';\nimport { LearningGoalCourseDetailModalComponent } from 'app/course/learning-goals/learning-goal-course-detail-modal/learning-goal-course-detail-modal.component';\n\n@Component({\n selector: 'jhi-learning-goal-card',\n templateUrl: './learning-goal-card.component.html',\n styleUrls: ['./learning-goal-card.component.scss'],\n})\nexport class LearningGoalCardComponent implements OnInit, OnDestroy {\n @Input()\n learningGoal: LearningGoal;\n @Input()\n learningGoalProgress: IndividualLearningGoalProgress | CourseLearningGoalProgress | undefined;\n\n public predicate = 'id';\n public reverse = false;\n public progressText = '';\n public progressInPercent = 0;\n public isProgressAvailable = false;\n\n public DetailModalComponent = LearningGoalDetailModalComponent;\n public CourseDetailModalComponent = LearningGoalCourseDetailModalComponent;\n\n constructor(private modalService: NgbModal, public lectureUnitService: LectureUnitService, public translateService: TranslateService) {}\n\n ngOnInit(): void {\n if (!this.learningGoalProgress || this.learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal === 0) {\n this.isProgressAvailable = false;\n } else {\n this.isProgressAvailable = true;\n this.progressText = this.translateService.instant('artemisApp.learningGoal.learningGoalCard.achieved');\n let pointsAchieved;\n if (this.isIndividualProgress(this.learningGoalProgress)) {\n pointsAchieved = this.learningGoalProgress.pointsAchievedByStudentInLearningGoal;\n } else {\n pointsAchieved = this.learningGoalProgress.averagePointsAchievedByStudentInLearningGoal;\n }\n\n const progress = (pointsAchieved / this.learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal) * 100;\n this.progressInPercent = Math.round(progress * 10) / 10;\n }\n }\n\n isIndividualProgress(progress: IndividualLearningGoalProgress | CourseLearningGoalProgress): progress is IndividualLearningGoalProgress {\n return (progress as IndividualLearningGoalProgress).studentId !== undefined;\n }\n\n isCourseProgress(progress: IndividualLearningGoalProgress | CourseLearningGoalProgress): progress is CourseLearningGoalProgress {\n return (progress as CourseLearningGoalProgress).courseId !== undefined;\n }\n\n ngOnDestroy(): void {\n if (this.modalService.hasOpenModals()) {\n this.modalService.dismissAll();\n }\n }\n\n openLearningGoalDetailsModal() {\n if (this.learningGoalProgress && this.isCourseProgress(this.learningGoalProgress)) {\n const modalRef = this.modalService.open(this.CourseDetailModalComponent, {\n size: 'xl',\n });\n if (modalRef) {\n modalRef.componentInstance.learningGoal = this.learningGoal;\n modalRef.componentInstance.learningGoalCourseProgress = this.learningGoalProgress;\n }\n } else {\n const modalRef = this.modalService.open(this.DetailModalComponent, {\n size: 'xl',\n });\n if (modalRef) {\n modalRef.componentInstance.learningGoal = this.learningGoal;\n modalRef.componentInstance.learningGoalProgress = this.learningGoalProgress;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6301671266555786, "alphanum_fraction": 0.6301671266555786, "avg_line_length": 37.54237365722656, "blob_id": "b9d518cc4e4e6d2721220143459d41296d15ec33", "content_id": "1fdf47c12a14309e821ac98dac69d60c8545fd39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2274, "license_type": "permissive", "max_line_length": 121, "num_lines": 59, "path": "/src/test/javascript/spec/component/modeling-explanation-editor/modeling-explanation-editor.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { By } from '@angular/platform-browser';\nimport { ModelingExplanationEditorComponent } from 'app/exercises/modeling/shared/modeling-explanation-editor.component';\nimport * as chai from 'chai';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ModelingExplanationEditorComponent', () => {\n let fixture: ComponentFixture<ModelingExplanationEditorComponent>;\n let comp: ModelingExplanationEditorComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [FormsModule],\n declarations: [ModelingExplanationEditorComponent],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ModelingExplanationEditorComponent);\n comp = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(ModelingExplanationEditorComponent).to.be.ok;\n });\n\n it('should change explanation value bidirectionally between component and template', () => {\n comp.explanation = 'Initial Explanation';\n fixture.detectChanges();\n fixture.whenStable().then(() => {\n const textareaDebugElement = fixture.debugElement.query(By.css('textarea'));\n expect(textareaDebugElement).to.exist;\n const textarea = textareaDebugElement.nativeElement;\n expect(textarea.value).to.equal('Initial Explanation');\n textarea.value = 'Test';\n textarea.dispatchEvent(new Event('input'));\n expect(comp.explanation).to.equal('Test');\n expect(textarea.value).to.equal('Test');\n\n // Test tab event\n textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Tab' }));\n textarea.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n expect(textarea.value).to.equal('Test\\t');\n expect(comp.explanation).to.equal('Test\\t');\n });\n });\n});\n" }, { "alpha_fraction": 0.5990012288093567, "alphanum_fraction": 0.6006242036819458, "avg_line_length": 44.771427154541016, "blob_id": "274ca5b22c304acb8b30f5c8c3e9a258be1c422e", "content_id": "4d969801996a58ed27c2f2ad90c6d719c28278aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16020, "license_type": "permissive", "max_line_length": 173, "num_lines": 350, "path": "/src/main/webapp/app/exercises/shared/result/result-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';\nimport { catchError, map, switchMap, tap } from 'rxjs/operators';\nimport { of, throwError } from 'rxjs';\nimport { BuildLogEntry, BuildLogEntryArray, BuildLogType } from 'app/entities/build-log.model';\nimport { Feedback, FeedbackType, STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER } from 'app/entities/feedback.model';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { Result } from 'app/entities/result.model';\nimport { BuildLogService } from 'app/exercises/programming/shared/service/build-log.service';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { StaticCodeAnalysisIssue } from 'app/entities/static-code-analysis-issue.model';\nimport { ScoreChartPreset } from 'app/shared/chart/presets/scoreChartPreset';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { TranslateService } from '@ngx-translate/core';\nimport {\n isProgrammingExerciseParticipation,\n isProgrammingExerciseStudentParticipation,\n isResultPreliminary,\n} from 'app/exercises/programming/shared/utils/programming-exercise.utils';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { round } from 'app/shared/util/utils';\n\nexport enum FeedbackItemType {\n Issue,\n Test,\n Feedback,\n}\n\nexport class FeedbackItem {\n type: FeedbackItemType;\n category: string;\n title?: string;\n text?: string;\n positive?: boolean;\n credits?: number;\n appliedCredits?: number;\n}\n\n// Modal -> Result details view\n@Component({\n selector: 'jhi-result-detail',\n templateUrl: './result-detail.component.html',\n styleUrls: ['./result-detail.scss'],\n})\nexport class ResultDetailComponent implements OnInit {\n readonly BuildLogType = BuildLogType;\n readonly AssessmentType = AssessmentType;\n readonly round = round;\n\n @Input() result: Result;\n // Specify the feedback.text values that should be shown, all other values will not be visible.\n @Input() feedbackFilter: string[];\n @Input() showTestDetails = false;\n @Input() showScoreChart = false;\n @Input() exerciseType: ExerciseType;\n\n isLoading = false;\n loadingFailed = false;\n feedbackList: FeedbackItem[];\n filteredFeedbackList: FeedbackItem[];\n buildLogs: BuildLogEntryArray;\n\n scoreChartPreset: ScoreChartPreset;\n showScoreChartTooltip = false;\n\n constructor(public activeModal: NgbActiveModal, private resultService: ResultService, private buildLogService: BuildLogService, translateService: TranslateService) {\n const pointsLabel = translateService.instant('artemisApp.result.chart.points');\n const deductionsLabel = translateService.instant('artemisApp.result.chart.deductions');\n this.scoreChartPreset = new ScoreChartPreset([pointsLabel, deductionsLabel]);\n }\n\n /**\n * Load the result feedbacks if necessary and assign them to the component.\n * When a result has feedbacks assigned to it, no server call will be executed.\n *\n */\n ngOnInit(): void {\n this.isLoading = true;\n of(this.result.feedbacks)\n .pipe(\n // If the result already has feedbacks assigned to it, don't query the server.\n switchMap((feedbacks: Feedback[] | undefined | null) => (feedbacks && feedbacks.length ? of(feedbacks) : this.getFeedbackDetailsForResult(this.result.id!))),\n switchMap((feedbacks: Feedback[] | undefined | null) => {\n // In case the exerciseType is not set, we try to set it back if the participation is from a programming exercise\n if (!this.exerciseType && isProgrammingExerciseParticipation(this.result?.participation)) {\n this.exerciseType = ExerciseType.PROGRAMMING;\n }\n\n /*\n * If we have feedback, filter it if needed, distinguish between test case and static code analysis\n * feedback and assign the lists to the component\n */\n if (feedbacks && feedbacks.length) {\n this.result.feedbacks = feedbacks!;\n const filteredFeedback = this.filterFeedback(feedbacks);\n this.feedbackList = this.createFeedbackItems(filteredFeedback);\n this.filteredFeedbackList = this.filterFeedbackItems(this.feedbackList);\n if (this.showScoreChart) {\n this.updateChart(this.feedbackList);\n }\n }\n // If we don't receive a submission or the submission is marked with buildFailed, fetch the build logs.\n if (\n this.exerciseType === ExerciseType.PROGRAMMING &&\n this.result.participation &&\n (!this.result.submission || (this.result.submission as ProgrammingSubmission).buildFailed)\n ) {\n return this.fetchAndSetBuildLogs(this.result.participation.id!);\n }\n return of(null);\n }),\n catchError(() => {\n this.loadingFailed = true;\n return of(null);\n }),\n )\n .subscribe(() => {\n this.isLoading = false;\n });\n }\n\n /**\n * Loads the missing feedback details\n * @param resultId The current result\n * @private\n */\n private getFeedbackDetailsForResult(resultId: number) {\n return this.resultService.getFeedbackDetailsForResult(resultId).pipe(map(({ body: feedbackList }) => feedbackList!));\n }\n\n /**\n * Filters the feedback based on the filter input\n * @param feedbackList The full list of feedback\n */\n private filterFeedback = (feedbackList: Feedback[]) => {\n if (!this.feedbackFilter) {\n return [...feedbackList];\n } else {\n return this.feedbackFilter\n .map((filterText) => {\n return feedbackList.find(({ text }) => text === filterText);\n })\n .filter(Boolean) as Feedback[];\n }\n };\n\n /**\n * Creates a feedback item with a category, title and text for each feedback object.\n * @param feedbacks The list of feedback objects.\n * @private\n */\n private createFeedbackItems(feedbacks: Feedback[]): FeedbackItem[] {\n if (this.exerciseType === ExerciseType.PROGRAMMING) {\n return feedbacks.map((feedback) => {\n if (Feedback.isStaticCodeAnalysisFeedback(feedback)) {\n const scaCategory = feedback.text!.substring(STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER.length);\n const scaIssue = StaticCodeAnalysisIssue.fromFeedback(feedback);\n return {\n type: FeedbackItemType.Issue,\n category: 'Code Issue',\n title: `${scaCategory} Issue in file ${this.getIssueLocation(scaIssue)}`.trim(),\n text: this.showTestDetails ? `${scaIssue.rule}: ${scaIssue.message}` : scaIssue.message,\n positive: false,\n credits: scaIssue.penalty ? -scaIssue.penalty : feedback.credits,\n appliedCredits: feedback.credits,\n };\n } else if (feedback.type === FeedbackType.AUTOMATIC) {\n return {\n type: FeedbackItemType.Test,\n category: this.showTestDetails ? 'Test Case' : 'Feedback',\n title: !this.showTestDetails\n ? undefined\n : feedback.positive === undefined\n ? `No result information for ${feedback.text}`\n : `Test ${feedback.text} ${feedback.positive ? 'passed' : 'failed'}`,\n text: feedback.detailText,\n positive: feedback.positive,\n credits: feedback.credits,\n };\n } else {\n return {\n type: FeedbackItemType.Feedback,\n category: this.showTestDetails ? 'Tutor' : 'Feedback',\n title: feedback.text,\n text: feedback.detailText,\n positive: feedback.positive,\n credits: feedback.credits,\n };\n }\n });\n } else {\n return feedbacks.map((feedback) => ({\n type: FeedbackItemType.Feedback,\n category: 'Feedback',\n title: feedback.text,\n text: feedback.detailText,\n positive: feedback.positive,\n credits: feedback.credits,\n }));\n }\n }\n\n /**\n * Builds the location string for a static code analysis issue\n * @param issue The sca issue\n */\n getIssueLocation(issue: StaticCodeAnalysisIssue): string {\n const lineText = !issue.endLine || issue.startLine === issue.endLine ? ` at line ${issue.startLine}` : ` at lines ${issue.startLine}-${issue.endLine}`;\n let columnText = '';\n if (issue.startColumn) {\n columnText = !issue.endColumn || issue.startColumn === issue.endColumn ? ` column ${issue.startColumn}` : ` columns ${issue.startColumn}-${issue.endColumn}`;\n }\n return issue.filePath + lineText + columnText;\n }\n\n /**\n * Fetches build logs for a participation\n * @param participationId The active participation\n */\n private fetchAndSetBuildLogs = (participationId: number) => {\n return this.buildLogService.getBuildLogs(participationId).pipe(\n tap((repoResult: BuildLogEntry[]) => {\n this.buildLogs = BuildLogEntryArray.fromBuildLogs(repoResult);\n }),\n catchError((error: HttpErrorResponse) => {\n /**\n * The request returns 403 if the build was successful and therefore no build logs exist.\n * If no submission is available, the client will attempt to fetch the build logs anyways.\n * We catch the error here as it would prevent the displaying of feedback.\n */\n if (error.status === 403) {\n return of(null);\n }\n return throwError(error);\n }),\n );\n };\n\n /**\n * Filters / Summarizes positive test cases for a student and programming exercise result\n * @param feedbackList The list of feedback items\n * @private\n */\n private filterFeedbackItems(feedbackList: FeedbackItem[]) {\n if (this.exerciseType !== ExerciseType.PROGRAMMING || this.showTestDetails) {\n return [...feedbackList];\n } else {\n const positiveTestCasesWithoutDetailText = feedbackList.filter((feedbackItem) => {\n return feedbackItem.type === FeedbackItemType.Test && feedbackItem.positive && !feedbackItem.text;\n });\n if (positiveTestCasesWithoutDetailText.length > 0) {\n return [\n {\n type: FeedbackItemType.Test,\n category: 'Feedback',\n title: positiveTestCasesWithoutDetailText.length + ' passed test' + (positiveTestCasesWithoutDetailText.length > 1 ? 's' : ''),\n positive: true,\n credits: positiveTestCasesWithoutDetailText.reduce((sum, feedbackItem) => sum + (feedbackItem.credits || 0), 0),\n },\n ...feedbackList.filter((feedbackItem) => !positiveTestCasesWithoutDetailText.includes(feedbackItem)),\n ];\n } else {\n return [...feedbackList];\n }\n }\n }\n\n /**\n * Handles the coloring of each feedback items based on its type and credits.\n * @param feedback The feedback item\n */\n getClassNameForFeedbackItem(feedback: FeedbackItem): string {\n if (feedback.type === FeedbackItemType.Issue) {\n return 'alert-warning';\n } else if (feedback.type === FeedbackItemType.Test) {\n return feedback.positive ? 'alert-success' : 'alert-danger';\n } else {\n if (feedback.credits === 0) {\n return 'alert-warning';\n } else {\n return feedback.positive || (feedback.credits && feedback.credits > 0) ? 'alert-success' : 'alert-danger';\n }\n }\n }\n\n /**\n * Calculates and updates the values of the score chart\n * @param feedbackList The list of feedback items.\n * @private\n */\n private updateChart(feedbackList: FeedbackItem[]) {\n if (!this.result.participation?.exercise || feedbackList.length === 0) {\n this.showScoreChart = false;\n return;\n }\n\n const sumCredits = (sum: number, feedbackItem: FeedbackItem) => sum + (feedbackItem.credits || 0);\n const sumAppliedCredits = (sum: number, feedbackItem: FeedbackItem) => sum + (feedbackItem.appliedCredits || 0);\n\n let testCaseCredits = feedbackList.filter((item) => item.type === FeedbackItemType.Test).reduce(sumCredits, 0);\n const positiveCredits = feedbackList.filter((item) => item.type !== FeedbackItemType.Test && item.credits && item.credits > 0).reduce(sumCredits, 0);\n\n let codeIssueCredits = -feedbackList.filter((item) => item.type === FeedbackItemType.Issue).reduce(sumAppliedCredits, 0);\n const codeIssuePenalties = -feedbackList.filter((item) => item.type === FeedbackItemType.Issue).reduce(sumCredits, 0);\n const negativeCredits = -feedbackList.filter((item) => item.type !== FeedbackItemType.Issue && item.credits && item.credits < 0).reduce(sumCredits, 0);\n\n const exercise = this.result.participation.exercise;\n\n // cap test points\n const maxPoints = exercise.maxPoints!;\n const maxPointsWithBonus = maxPoints + (exercise.bonusPoints || 0);\n\n if (testCaseCredits > maxPointsWithBonus) {\n testCaseCredits = maxPointsWithBonus;\n }\n\n // cap sca penalty points\n if (exercise.type === ExerciseType.PROGRAMMING) {\n const programmingExercise = exercise as ProgrammingExercise;\n if (programmingExercise.staticCodeAnalysisEnabled && programmingExercise.maxStaticCodeAnalysisPenalty != undefined) {\n const maxPenaltyCredits = (maxPoints * programmingExercise.maxStaticCodeAnalysisPenalty) / 100;\n codeIssueCredits = Math.min(codeIssueCredits, maxPenaltyCredits);\n }\n }\n\n const appliedNegativePoints = codeIssueCredits + negativeCredits;\n const receivedNegativePoints = codeIssuePenalties + negativeCredits;\n const positivePoints = testCaseCredits + positiveCredits;\n\n if (appliedNegativePoints !== receivedNegativePoints) {\n this.showScoreChartTooltip = true;\n }\n\n // the chart preset handles the capping to the maximum score of the exercise\n this.scoreChartPreset.setValues(positivePoints, appliedNegativePoints, receivedNegativePoints, maxPoints, maxPointsWithBonus);\n }\n\n /**\n * Checks if the current result is preliminary and has hidden test cases.\n */\n resultIsPreliminary() {\n return (\n this.result.participation &&\n isProgrammingExerciseStudentParticipation(this.result.participation) &&\n isResultPreliminary(this.result!, this.result.participation.exercise as ProgrammingExercise)\n );\n }\n}\n" }, { "alpha_fraction": 0.6648260951042175, "alphanum_fraction": 0.6649290323257446, "avg_line_length": 46.87849044799805, "blob_id": "50f50d866ab5ad11376f6d46d5d604aef758cf92", "content_id": "b67a1aa91bab38952bde3e182da895dfe7b9f097", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 29158, "license_type": "permissive", "max_line_length": 176, "num_lines": 609, "path": "/src/main/webapp/app/course/manage/course-management.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport * as moment from 'moment';\nimport { filter, map, tap } from 'rxjs/operators';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Course, CourseGroup } from 'app/entities/course.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { User } from 'app/core/user/user.model';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { getLatestSubmissionResult, setLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nimport { SubjectObservablePair } from 'app/utils/rxjs.utils';\nimport { participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\nimport { CourseManagementOverviewStatisticsDto } from 'app/course/manage/overview/course-management-overview-statistics-dto.model';\nimport { addUserIndependentRepositoryUrl } from 'app/overview/participation-utils';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\n\nexport type EntityResponseType = HttpResponse<Course>;\nexport type EntityArrayResponseType = HttpResponse<Course[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class CourseManagementService {\n private resourceUrl = SERVER_API_URL + 'api/courses';\n\n private readonly courses: Map<number, SubjectObservablePair<Course>> = new Map();\n\n private coursesForNotifications: BehaviorSubject<Course[] | null> = new BehaviorSubject<Course[] | null>(null);\n private fetchingCoursesForNotifications = false;\n\n constructor(private http: HttpClient, private exerciseService: ExerciseService, private lectureService: LectureService, private accountService: AccountService) {}\n\n /**\n * creates a course using a POST request\n * @param course - the course to be created on the server\n */\n create(course: Course): Observable<EntityResponseType> {\n const copy = CourseManagementService.convertDateFromClient(course);\n return this.http\n .post<Course>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * updates a course using a PUT request\n * @param course - the course to be updated\n */\n update(course: Course): Observable<EntityResponseType> {\n const copy = CourseManagementService.convertDateFromClient(course);\n return this.http\n .put<Course>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * finds the course with the provided unique identifier\n * @param courseId - the id of the course to be found\n */\n find(courseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Course>(`${this.resourceUrl}/${courseId}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)))\n .pipe(map((res: EntityResponseType) => this.checkAccessRightsCourse(res)));\n }\n\n /**\n * Fetches the title of the course with the given id\n *\n * @param courseId the id of the course\n * @return the title of the course in an HttpResponse, or an HttpErrorResponse on error\n */\n getTitle(courseId: number): Observable<HttpResponse<string>> {\n return this.http.get(`${this.resourceUrl}/${courseId}/title`, { observe: 'response', responseType: 'text' });\n }\n\n /**\n * finds the course with the provided unique identifier together with its exercises\n * @param courseId - the id of the course to be found\n */\n findWithExercises(courseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Course>(`${this.resourceUrl}/${courseId}/with-exercises`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * finds the course with the provided unique identifier together with its exercises and participants\n * @param courseId - the id of the course to be found\n */\n findWithExercisesAndParticipations(courseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Course>(`${this.resourceUrl}/${courseId}/with-exercises-and-relevant-participations`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * finds a course with the given id and eagerly loaded organizations\n * @param courseId the id of the course to be found\n */\n findWithOrganizations(courseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Course>(`${this.resourceUrl}/${courseId}/with-organizations`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n // TODO: separate course overview and course management REST API calls in a better way\n /**\n * finds all courses using a GET request\n */\n findAllForDashboard(): Observable<EntityArrayResponseType> {\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(`${this.resourceUrl}/for-dashboard`, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)))\n .pipe(map((res: EntityArrayResponseType) => this.checkAccessRights(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setParticipationStatusForExercisesInCourses(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setCoursesForNotifications(res)));\n }\n\n findOneForDashboard(courseId: number): Observable<EntityResponseType> {\n return this.http\n .get<Course>(`${this.resourceUrl}/${courseId}/for-dashboard`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)))\n .pipe(map((res: EntityResponseType) => this.checkAccessRightsCourse(res)))\n .pipe(map((res: EntityResponseType) => this.setParticipationStatusForExercisesInCourse(res)))\n .pipe(tap((res: EntityResponseType) => this.courseWasUpdated(res.body)));\n }\n\n courseWasUpdated(course: Course | null): void {\n if (course) {\n return this.courses.get(course.id!)?.subject.next(course);\n }\n }\n\n getCourseUpdates(courseId: number): Observable<Course> {\n if (!this.courses.has(courseId)) {\n this.courses.set(courseId, new SubjectObservablePair());\n }\n return this.courses.get(courseId)!.observable;\n }\n\n /**\n * finds all participants of the course corresponding to the given unique identifier\n * @param courseId - the id of the course\n */\n findAllParticipationsWithResults(courseId: number): Observable<StudentParticipation[]> {\n return this.http.get<StudentParticipation[]>(`${this.resourceUrl}/${courseId}/participations`);\n }\n\n /**\n * finds all results of exercises of the course corresponding to the given unique identifier for the current user\n * @param courseId - the id of the course\n */\n findAllResultsOfCourseForExerciseAndCurrentUser(courseId: number): Observable<Course> {\n return this.http.get<Course>(`${this.resourceUrl}/${courseId}/results`);\n }\n\n /**\n * finds all courses that can be registered to\n */\n findAllToRegister(): Observable<EntityArrayResponseType> {\n return this.http\n .get<Course[]>(`${this.resourceUrl}/to-register`, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * returns the course with the provided unique identifier for the assessment dashboard\n * @param courseId - the id of the course\n */\n getCourseWithInterestingExercisesForTutors(courseId: number): Observable<EntityResponseType> {\n const url = `${this.resourceUrl}/${courseId}/for-assessment-dashboard`;\n return this.http\n .get<Course>(url, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * returns the stats of the course with the provided unique identifier for the assessment dashboard\n * @param courseId - the id of the course\n */\n getStatsForTutors(courseId: number): Observable<HttpResponse<StatsForDashboard>> {\n return this.http.get<StatsForDashboard>(`${this.resourceUrl}/${courseId}/stats-for-assessment-dashboard`, { observe: 'response' });\n }\n\n /**\n * register to the course with the provided unique identifier using a POST request\n * NB: the body is null, because the server can identify the user anyway\n * @param courseId - the id of the course\n */\n registerForCourse(courseId: number): Observable<HttpResponse<User>> {\n return this.http\n .post<User>(`${this.resourceUrl}/${courseId}/register`, null, { observe: 'response' })\n .pipe(\n map((res: HttpResponse<User>) => {\n if (res.body != undefined) {\n this.accountService.syncGroups(res.body);\n }\n return res;\n }),\n );\n }\n\n /**\n * finds all courses using a GET request\n * @param req\n */\n getAll(req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(this.resourceUrl, { params: options, observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)))\n .pipe(map((res: EntityArrayResponseType) => this.checkAccessRights(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setCoursesForNotifications(res)));\n }\n\n /**\n * finds all courses with quiz exercises using a GET request\n */\n getAllCoursesWithQuizExercises(): Observable<EntityArrayResponseType> {\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(this.resourceUrl + '/courses-with-quiz', { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)))\n .pipe(map((res: EntityArrayResponseType) => this.checkAccessRights(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setCoursesForNotifications(res)));\n }\n\n /**\n * finds all courses together with user stats using a GET request\n * @param req\n */\n getWithUserStats(req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(`${this.resourceUrl}/with-user-stats`, { params: options, observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)))\n .pipe(map((res: EntityArrayResponseType) => this.checkAccessRights(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setCoursesForNotifications(res)));\n }\n\n /**\n * finds all courses for the overview using a GET request\n * @param req a dictionary which is send as request option along the REST call\n */\n getCourseOverview(req?: any): Observable<HttpResponse<Course[]>> {\n const options = createRequestOption(req);\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(`${this.resourceUrl}/course-management-overview`, { params: options, observe: 'response' })\n .pipe(tap((res: HttpResponse<Course[]>) => res.body!.forEach((course) => this.checkAndSetCourseRights(course))));\n }\n\n /**\n * deletes the course corresponding to the given unique identifier using a DELETE request\n * @param courseId - the id of the course to be deleted\n */\n delete(courseId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/${courseId}`, { observe: 'response' });\n }\n\n /**\n * returns the stats of the course with the provided unique identifier for the instructor dashboard\n * @param courseId - the id of the course\n */\n getStatsForInstructors(courseId: number): Observable<HttpResponse<StatsForDashboard>> {\n return this.http.get<StatsForDashboard>(`${this.resourceUrl}/${courseId}/stats-for-instructor-dashboard`, { observe: 'response' });\n }\n\n /**\n * returns the exercise details of the courses for the courses management dashboard\n * @param onlyActive - if true, only active courses will be considered in the result\n */\n getExercisesForManagementOverview(onlyActive: boolean): Observable<HttpResponse<Course[]>> {\n let httpParams = new HttpParams();\n httpParams = httpParams.append('onlyActive', onlyActive.toString());\n return this.http\n .get<Course[]>(`${this.resourceUrl}/exercises-for-management-overview`, { params: httpParams, observe: 'response' })\n .pipe(map((res: HttpResponse<Course[]>) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * returns the stats of the courses for the courses management dashboard\n * @param onlyActive - if true, only active courses will be considered in the result\n */\n getStatsForManagementOverview(onlyActive: boolean): Observable<HttpResponse<CourseManagementOverviewStatisticsDto[]>> {\n let httpParams = new HttpParams();\n httpParams = httpParams.append('onlyActive', onlyActive.toString());\n return this.http.get<CourseManagementOverviewStatisticsDto[]>(`${this.resourceUrl}/stats-for-management-overview`, { params: httpParams, observe: 'response' });\n }\n\n /**\n * returns all the categories of the course corresponding to the given unique identifier\n * @param courseId - the id of the course\n */\n findAllCategoriesOfCourse(courseId: number): Observable<HttpResponse<string[]>> {\n return this.http.get<string[]>(`${this.resourceUrl}/${courseId}/categories`, { observe: 'response' });\n }\n\n /**\n * returns all the users in the the given group of the course corresponding to the given unique identifier\n * @param courseId - the id of the course\n * @param courseGroup - the course group we want to get users from\n */\n getAllUsersInCourseGroup(courseId: number, courseGroup: CourseGroup): Observable<HttpResponse<User[]>> {\n return this.http.get<User[]>(`${this.resourceUrl}/${courseId}/${courseGroup}`, { observe: 'response' });\n }\n\n /**\n * Downloads the course archive of the specified courseId. Returns an error\n * if the archive does not exist.\n * @param courseId The id of the course\n */\n downloadCourseArchive(courseId: number): Observable<HttpResponse<Blob>> {\n return this.http.get(`${this.resourceUrl}/${courseId}/download-archive`, {\n observe: 'response',\n responseType: 'blob',\n });\n }\n\n /**\n * Archives the course of the specified courseId.\n * @param courseId The id of the course to archive\n */\n archiveCourse(courseId: number): Observable<HttpResponse<any>> {\n return this.http.put(`${this.resourceUrl}/${courseId}/archive`, {}, { observe: 'response' });\n }\n\n cleanupCourse(courseId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/${courseId}/cleanup`, { observe: 'response' });\n }\n\n /**\n * Find all locked submissions of a given course for user\n * @param {number} courseId - The id of the course to be searched for\n */\n findAllLockedSubmissionsOfCourse(courseId: number): Observable<HttpResponse<Submission[]>> {\n return this.http\n .get<Submission[]>(`${this.resourceUrl}/${courseId}/lockedSubmissions`, { observe: 'response' })\n .pipe(\n filter((res) => !!res.body),\n tap((res) =>\n res.body!.forEach((submission: Submission) => {\n // reconnect some associations\n const latestResult = getLatestSubmissionResult(submission);\n if (latestResult) {\n latestResult.submission = submission;\n latestResult.participation = submission.participation;\n submission.participation!.results = [latestResult!];\n setLatestSubmissionResult(submission, latestResult);\n }\n }),\n ),\n );\n }\n\n /**\n * adds a user to the given courseGroup of the course corresponding to the given unique identifier using a POST request\n * @param courseId - the id of the course\n * @param courseGroup - the course group we want to add a user to\n * @param login - login of the user to be added\n */\n addUserToCourseGroup(courseId: number, courseGroup: CourseGroup, login: string): Observable<HttpResponse<void>> {\n return this.http.post<void>(`${this.resourceUrl}/${courseId}/${courseGroup}/${login}`, {}, { observe: 'response' });\n }\n\n /**\n * removes a user from the given group of the course corresponding to the given unique identifier using a DELETE request\n * @param courseId - the id of the course\n * @param courseGroup - the course group\n * @param login - login of the user to be removed\n */\n removeUserFromCourseGroup(courseId: number, courseGroup: CourseGroup, login: string): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/${courseId}/${courseGroup}/${login}`, { observe: 'response' });\n }\n\n checkAndSetCourseRights(course: Course) {\n course.isAtLeastTutor = this.accountService.isAtLeastTutorInCourse(course);\n course.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(course);\n }\n\n /**\n * Gets the cached courses. If there none the courses for the current user will be fetched.\n * @returns {BehaviorSubject<Course[] | null>}\n */\n getCoursesForNotifications(): BehaviorSubject<Course[] | null> {\n // The timeout is set to ensure that the request for retrieving courses\n // here is only made if there was no similar request made before.\n setTimeout(() => {\n // Retrieve courses if no courses were fetched before and are not queried at the moment.\n if (!this.fetchingCoursesForNotifications && !this.coursesForNotifications) {\n this.findAllForNotifications().subscribe(\n (res: HttpResponse<Course[]>) => {\n this.coursesForNotifications.next(res.body);\n },\n () => (this.fetchingCoursesForNotifications = false),\n );\n }\n }, 500);\n return this.coursesForNotifications;\n }\n\n private setCoursesForNotifications(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n this.coursesForNotifications.next(res.body);\n this.fetchingCoursesForNotifications = false;\n }\n return res;\n }\n\n private static convertDateFromClient(course: Course): Course {\n // copy of the object\n return Object.assign({}, course, {\n startDate: course.startDate && moment(course.startDate).isValid() ? course.startDate.toJSON() : undefined,\n endDate: course.endDate && moment(course.endDate).isValid() ? course.endDate.toJSON() : undefined,\n });\n }\n\n private convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n this.setCourseDates(res.body);\n }\n return res;\n }\n\n private convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((course: Course) => this.setCourseDates(course));\n }\n return res;\n }\n\n private setCourseDates(course: Course) {\n course.startDate = course.startDate ? moment(course.startDate) : undefined;\n course.endDate = course.endDate ? moment(course.endDate) : undefined;\n course.exercises = this.exerciseService.convertExercisesDateFromServer(course.exercises);\n course.lectures = this.lectureService.convertDatesForLecturesFromServer(course.lectures);\n }\n\n private checkAccessRightsCourse(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n this.checkAndSetCourseRights(res.body);\n }\n return res;\n }\n\n private checkAccessRights(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((course: Course) => {\n this.checkAndSetCourseRights(course);\n });\n }\n return res;\n }\n\n private setParticipationStatusForExercisesInCourse(res: EntityResponseType): EntityResponseType {\n if (res.body?.exercises) {\n res.body.exercises.forEach((exercise) => (exercise.participationStatus = participationStatus(exercise)));\n }\n return res;\n }\n\n private setParticipationStatusForExercisesInCourses(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((course: Course) => {\n if (course.exercises) {\n course.exercises.forEach((exercise) => (exercise.participationStatus = participationStatus(exercise)));\n }\n });\n }\n return res;\n }\n\n private findAllForNotifications(): Observable<EntityArrayResponseType> {\n this.fetchingCoursesForNotifications = true;\n return this.http\n .get<Course[]>(`${this.resourceUrl}/for-notifications`, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)))\n .pipe(map((res: EntityArrayResponseType) => this.setCoursesForNotifications(res)));\n }\n}\n\n@Injectable({ providedIn: 'root' })\nexport class CourseExerciseService {\n private resourceUrl = SERVER_API_URL + `api/courses`;\n\n constructor(private http: HttpClient, private participationWebsocketService: ParticipationWebsocketService) {}\n\n /**\n * returns all programming exercises for the course corresponding to courseId\n * Note: the exercises in the response do not contain participations and do not contain the course to save network bandwidth\n * @param courseId\n */\n findAllProgrammingExercisesForCourse(courseId: number): Observable<HttpResponse<ProgrammingExercise[]>> {\n return this.http\n .get<ProgrammingExercise[]>(`${this.resourceUrl}/${courseId}/programming-exercises/`, { observe: 'response' })\n .map((res: HttpResponse<ProgrammingExercise[]>) => this.convertDateArrayFromServer(res));\n }\n\n /**\n * returns all modeling exercises for the course corresponding to courseId\n * Note: the exercises in the response do not contain participations and do not contain the course to save network bandwidth\n * @param courseId - the unique identifier of the course\n */\n findAllModelingExercisesForCourse(courseId: number): Observable<HttpResponse<ModelingExercise[]>> {\n return this.http\n .get<ModelingExercise[]>(`${this.resourceUrl}/${courseId}/modeling-exercises/`, { observe: 'response' })\n .map((res: HttpResponse<ModelingExercise[]>) => this.convertDateArrayFromServer(res));\n }\n\n /**\n * returns all text exercises for the course corresponding to courseId\n * Note: the exercises in the response do not contain participations and do not contain the course to save network bandwidth\n * @param courseId - the unique identifier of the course\n */\n findAllTextExercisesForCourse(courseId: number): Observable<HttpResponse<TextExercise[]>> {\n return this.http\n .get<TextExercise[]>(`${this.resourceUrl}/${courseId}/text-exercises/`, { observe: 'response' })\n .map((res: HttpResponse<TextExercise[]>) => this.convertDateArrayFromServer(res));\n }\n\n /**\n * returns all file upload exercises for the course corresponding to courseId\n * Note: the exercises in the response do not contain participations and do not contain the course to save network bandwidth\n * @param courseId - the unique identifier of the course\n */\n findAllFileUploadExercisesForCourse(courseId: number): Observable<HttpResponse<FileUploadExercise[]>> {\n return this.http\n .get<FileUploadExercise[]>(`${this.resourceUrl}/${courseId}/file-upload-exercises/`, { observe: 'response' })\n .map((res: HttpResponse<FileUploadExercise[]>) => this.convertDateArrayFromServer(res));\n }\n\n /**\n * starts the exercise with the identifier exerciseId for the course corresponding to courseId\n * @param courseId - the unique identifier of the course\n * @param exerciseId - the unique identifier of the modelling exercise\n */\n startExercise(courseId: number, exerciseId: number): Observable<StudentParticipation> {\n return this.http.post<StudentParticipation>(`${this.resourceUrl}/${courseId}/exercises/${exerciseId}/participations`, {}).map((participation: StudentParticipation) => {\n if (participation.type === ParticipationType.PROGRAMMING) {\n addUserIndependentRepositoryUrl(participation);\n }\n return this.handleParticipation(participation);\n });\n }\n\n /**\n * resumes the programming exercise with the identifier exerciseId for the course corresponding to courseId\n * @param courseId - the unique identifier of the course\n * @param exerciseId - the unique identifier of the modelling exercise\n */\n resumeProgrammingExercise(courseId: number, exerciseId: number): Observable<StudentParticipation> {\n return this.http\n .put<StudentParticipation>(`${this.resourceUrl}/${courseId}/exercises/${exerciseId}/resume-programming-participation`, {})\n .map((participation: StudentParticipation) => {\n if (participation.type === ParticipationType.PROGRAMMING) {\n addUserIndependentRepositoryUrl(participation);\n }\n return this.handleParticipation(participation);\n });\n }\n\n /**\n * handle the given student participaon by adding in the participationWebsocketService\n * @param participation - the participation to be handled\n */\n handleParticipation(participation: StudentParticipation) {\n if (participation) {\n // convert date\n participation.initializationDate = participation.initializationDate ? moment(participation.initializationDate) : undefined;\n if (participation.exercise) {\n const exercise = participation.exercise;\n exercise.dueDate = exercise.dueDate ? moment(exercise.dueDate) : undefined;\n exercise.releaseDate = exercise.releaseDate ? moment(exercise.releaseDate) : undefined;\n exercise.studentParticipations = [participation];\n }\n this.participationWebsocketService.addParticipation(participation);\n }\n return participation;\n }\n\n convertDateFromServer<T extends Exercise>(res: T): T {\n res.releaseDate = res.releaseDate ? moment(res.releaseDate) : undefined;\n res.dueDate = res.dueDate ? moment(res.dueDate) : undefined;\n return res;\n }\n\n protected convertDateArrayFromServer<T extends Exercise>(res: HttpResponse<T[]>): HttpResponse<T[]> {\n if (res.body) {\n res.body.forEach((exercise: T) => {\n exercise.releaseDate = exercise.releaseDate ? moment(exercise.releaseDate) : undefined;\n exercise.dueDate = exercise.dueDate ? moment(exercise.dueDate) : undefined;\n exercise.assessmentDueDate = exercise.assessmentDueDate ? moment(exercise.assessmentDueDate) : undefined;\n });\n }\n return res;\n }\n}\n" }, { "alpha_fraction": 0.6840025782585144, "alphanum_fraction": 0.6873592734336853, "avg_line_length": 49.39614486694336, "blob_id": "41851cd8bafde8276edf3d70b79c1e6e17a58f81", "content_id": "b7ce0a206c0eefe4639041e443e06640ecf5c747", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 23535, "license_type": "permissive", "max_line_length": 180, "num_lines": 467, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/FileResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.*;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.nio.file.StandardCopyOption;\nimport java.time.ZonedDateTime;\nimport java.util.*;\n\nimport javax.activation.MimetypesFileTypeMap;\nimport javax.validation.constraints.NotNull;\n\nimport org.apache.commons.io.FilenameUtils;\nimport org.apache.commons.io.IOUtils;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.*;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.security.core.Authentication;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.web.bind.annotation.*;\nimport org.springframework.web.multipart.MultipartFile;\n\nimport de.tum.in.www1.artemis.domain.FileUploadExercise;\nimport de.tum.in.www1.artemis.domain.FileUploadSubmission;\nimport de.tum.in.www1.artemis.domain.Lecture;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.domain.enumeration.ProjectType;\nimport de.tum.in.www1.artemis.domain.lecture.AttachmentUnit;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.jwt.TokenProvider;\nimport de.tum.in.www1.artemis.service.FilePathService;\nimport de.tum.in.www1.artemis.service.FileService;\nimport de.tum.in.www1.artemis.service.ResourceLoaderService;\n\n/**\n * REST controller for managing Course.\n */\n@RestController\n@RequestMapping(\"/api\")\npublic class FileResource {\n\n private final Logger log = LoggerFactory.getLogger(FileResource.class);\n\n private final FileService fileService;\n\n private final ResourceLoaderService resourceLoaderService;\n\n private final LectureRepository lectureRepository;\n\n private final AttachmentUnitRepository attachmentUnitRepository;\n\n private final FileUploadSubmissionRepository fileUploadSubmissionRepository;\n\n private final TokenProvider tokenProvider;\n\n private final FileUploadExerciseRepository fileUploadExerciseRepository;\n\n // NOTE: this list has to be the same as in file-uploader.service.ts\n private final List<String> allowedFileExtensions = new ArrayList<>(Arrays.asList(\"png\", \"jpg\", \"jpeg\", \"svg\", \"pdf\", \"zip\"));\n\n public void addAllowedFileExtension(String fileExtension) {\n this.allowedFileExtensions.add(fileExtension);\n }\n\n public void addRemoveFileExtension(String fileExtension) {\n this.allowedFileExtensions.remove(fileExtension);\n }\n\n public FileResource(FileService fileService, ResourceLoaderService resourceLoaderService, LectureRepository lectureRepository, TokenProvider tokenProvider,\n FileUploadSubmissionRepository fileUploadSubmissionRepository, FileUploadExerciseRepository fileUploadExerciseRepository,\n AttachmentUnitRepository attachmentUnitRepository) {\n this.fileService = fileService;\n this.resourceLoaderService = resourceLoaderService;\n this.lectureRepository = lectureRepository;\n this.tokenProvider = tokenProvider;\n this.fileUploadSubmissionRepository = fileUploadSubmissionRepository;\n this.fileUploadExerciseRepository = fileUploadExerciseRepository;\n this.attachmentUnitRepository = attachmentUnitRepository;\n }\n\n /**\n * POST /fileUpload : Upload a new file.\n *\n * @param file The file to save\n * @param keepFileName specifies if original file name should be kept\n * @return The path of the file\n * @throws URISyntaxException if response path can't be converted into URI\n */\n @PostMapping(\"/fileUpload\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<String> saveFile(@RequestParam(value = \"file\") MultipartFile file, @RequestParam(defaultValue = \"false\") boolean keepFileName) throws URISyntaxException {\n log.debug(\"REST request to upload file : {}\", file.getOriginalFilename());\n return handleSaveFile(file, keepFileName, false);\n\n }\n\n /**\n * GET /files/temp/:filename : Get the temporary file with the given filename\n *\n * @param filename The filename of the file to get\n * @return The requested file, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/temp/{filename:.+}\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<byte[]> getTempFile(@PathVariable String filename) {\n log.debug(\"REST request to get file : {}\", filename);\n return responseEntityForFilePath(FilePathService.getTempFilePath(), filename);\n }\n\n /**\n * POST /markdown-file-upload : Upload a new file for markdown.\n *\n * @param file The file to save\n * @param keepFileName specifies if original file name should be kept\n * @return The path of the file\n * @throws URISyntaxException if response path can't be converted into URI\n */\n @PostMapping(\"/markdown-file-upload\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<String> saveMarkdownFile(@RequestParam(value = \"file\") MultipartFile file, @RequestParam(defaultValue = \"false\") boolean keepFileName)\n throws URISyntaxException {\n log.debug(\"REST request to upload file for markdown: {}\", file.getOriginalFilename());\n return handleSaveFile(file, keepFileName, true);\n }\n\n /**\n * GET /files/markdown/:filename : Get the markdown file with the given filename\n *\n * @param filename The filename of the file to get\n * @return The requested file, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/markdown/{filename:.+}\")\n @PreAuthorize(\"permitAll()\")\n public ResponseEntity<byte[]> getMarkdownFile(@PathVariable String filename) {\n log.debug(\"REST request to get file : {}\", filename);\n return responseEntityForFilePath(FilePathService.getMarkdownFilePath(), filename);\n }\n\n /**\n * GET /files/templates/:filename : Get the template file with the given filename\n *\n * @param filename The filename of the file to get\n * @param language The programming language for which the template file should be returned\n * @param projectType The project type for which the template file should be returned. If omitted, a default depending on the language will be used.\n * @return The requested file, or 404 if the file doesn't exist\n */\n @GetMapping({ \"files/templates/{language}/{projectType}/{filename}\", \"files/templates/{language}/{filename}\", \"/files/templates/{filename:.+}\" })\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<byte[]> getTemplateFile(@PathVariable Optional<ProgrammingLanguage> language, @PathVariable Optional<ProjectType> projectType,\n @PathVariable String filename) {\n log.debug(\"REST request to get file '{}' for programming language {} and project type {}\", filename, language, projectType);\n try {\n String languagePrefix = language.map(programmingLanguage -> programmingLanguage.name().toLowerCase()).orElse(\"\");\n String projectTypePrefix = projectType.map(type -> type.name().toLowerCase()).orElse(\"\");\n\n Resource fileResource = resourceLoaderService.getResource(\"templates\", languagePrefix, projectTypePrefix, filename);\n if (!fileResource.exists()) {\n // Load without project type if not found with project type\n fileResource = resourceLoaderService.getResource(\"templates\", languagePrefix, filename);\n }\n\n var fileContent = IOUtils.toByteArray(fileResource.getInputStream());\n HttpHeaders responseHeaders = new HttpHeaders();\n responseHeaders.setContentType(MediaType.TEXT_PLAIN);\n return new ResponseEntity<>(fileContent, responseHeaders, HttpStatus.OK);\n }\n catch (IOException ex) {\n log.debug(\"Error when retrieving template file : {}\", ex.getMessage());\n HttpHeaders responseHeaders = new HttpHeaders();\n return new ResponseEntity<>(null, responseHeaders, HttpStatus.NOT_FOUND);\n }\n }\n\n /**\n * GET /files/drag-and-drop/backgrounds/:questionId/:filename : Get the background file with the given name for the given drag and drop question\n *\n * @param questionId ID of the drag and drop question, the file belongs to\n * @param filename the filename of the file\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/drag-and-drop/backgrounds/{questionId}/{filename:.+}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<byte[]> getDragAndDropBackgroundFile(@PathVariable Long questionId, @PathVariable String filename) {\n log.debug(\"REST request to get file : {}\", filename);\n return responseEntityForFilePath(FilePathService.getDragAndDropBackgroundFilePath(), filename);\n }\n\n /**\n * GET /files/drag-and-drop/drag-items/:dragItemId/:filename : Get the drag item file with the given name for the given drag item\n *\n * @param dragItemId ID of the drag item, the file belongs to\n * @param filename the filename of the file\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/drag-and-drop/drag-items/{dragItemId}/{filename:.+}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<byte[]> getDragItemFile(@PathVariable Long dragItemId, @PathVariable String filename) {\n log.debug(\"REST request to get file : {}\", filename);\n return responseEntityForFilePath(FilePathService.getDragItemFilePath(), filename);\n }\n\n /**\n * GET /files/file-upload/submission/:submissionId/:filename : Get the file upload exercise submission file\n *\n * @param submissionId id of the submission, the file belongs to\n * @param exerciseId id of the exercise, the file belongs to\n * @param filename the filename of the file\n * @param temporaryAccessToken The access token is required to authenticate the user that accesses it\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/file-upload-exercises/{exerciseId}/submissions/{submissionId}/{filename:.+}\")\n @PreAuthorize(\"permitAll()\")\n public ResponseEntity<byte[]> getFileUploadSubmission(@PathVariable Long exerciseId, @PathVariable Long submissionId, @PathVariable String filename,\n @RequestParam(\"access_token\") String temporaryAccessToken) {\n log.debug(\"REST request to get file : {}\", filename);\n if (!validateTemporaryAccessToken(temporaryAccessToken, filename)) {\n // NOTE: this is a special case, because we like to show this error message directly in the browser (without the angular client being active)\n String errorMessage = \"You don't have the access rights for this file! Please login to Artemis and download the file in the corresponding exercise\";\n return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorMessage.getBytes());\n }\n\n Optional<FileUploadSubmission> optionalSubmission = fileUploadSubmissionRepository.findById(submissionId);\n Optional<FileUploadExercise> optionalFileUploadExercise = fileUploadExerciseRepository.findById(exerciseId);\n if (optionalSubmission.isEmpty()) {\n return ResponseEntity.badRequest().build();\n }\n return buildFileResponse(FileUploadSubmission.buildFilePath(optionalFileUploadExercise.get().getId(), optionalSubmission.get().getId()), filename);\n }\n\n /**\n * GET /files/course/icons/:courseId/:filename : Get the course image\n *\n * @param courseId ID of the course, the image belongs to\n * @param filename the filename of the file\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"/files/course/icons/{courseId}/{filename:.+}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<byte[]> getCourseIcon(@PathVariable Long courseId, @PathVariable String filename) {\n log.debug(\"REST request to get file : {}\", filename);\n return responseEntityForFilePath(FilePathService.getCourseIconFilePath(), filename);\n }\n\n /**\n * GET /files/attachments/access-token/{filename:.+} : Generates an access token that is valid for 30 seconds and given filename\n *\n * @param filename name of the file, the access token is for\n * @return The generated access token\n */\n @GetMapping(\"files/attachments/access-token/{filename:.+}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<String> getTemporaryFileAccessToken(@PathVariable String filename) {\n Authentication authentication = SecurityContextHolder.getContext().getAuthentication();\n if (filename == null) {\n return ResponseEntity.badRequest().build();\n }\n String temporaryAccessToken = tokenProvider.createFileTokenWithCustomDuration(authentication, 30, filename);\n return ResponseEntity.ok(temporaryAccessToken);\n }\n\n /**\n * GET /files/course/icons/:lectureId/:filename : Get the lecture attachment\n *\n * @param lectureId ID of the lecture, the attachment belongs to\n * @param filename the filename of the file\n * @param temporaryAccessToken The access token is required to authenticate the user that accesses it\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"files/attachments/lecture/{lectureId}/{filename:.+}\")\n @PreAuthorize(\"permitAll()\")\n public ResponseEntity<byte[]> getLectureAttachment(@PathVariable Long lectureId, @PathVariable String filename, @RequestParam(\"access_token\") String temporaryAccessToken) {\n log.debug(\"REST request to get file : {}\", filename);\n Optional<Lecture> optionalLecture = lectureRepository.findById(lectureId);\n if (optionalLecture.isEmpty()) {\n return ResponseEntity.badRequest().build();\n }\n if (!validateTemporaryAccessToken(temporaryAccessToken, filename)) {\n // NOTE: this is a special case, because we like to show this error message directly in the browser (without the angular client being active)\n String errorMessage = \"You don't have the access rights for this file! Please login to Artemis and download the attachment in the corresponding lecture\";\n return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorMessage.getBytes());\n }\n return buildFileResponse(Paths.get(FilePathService.getLectureAttachmentFilePath(), String.valueOf(optionalLecture.get().getId())).toString(), filename);\n }\n\n /**\n * GET files/attachments/attachment-unit/:attachmentUnitId/:filename : Get the lecture unit attachment\n *\n * @param attachmentUnitId ID of the attachment unit, the attachment belongs to\n * @param filename the filename of the file\n * @param temporaryAccessToken The access token is required to authenticate the user that accesses it\n * @return The requested file, 403 if the logged in user is not allowed to access it, or 404 if the file doesn't exist\n */\n @GetMapping(\"files/attachments/attachment-unit/{attachmentUnitId}/{filename:.+}\")\n @PreAuthorize(\"permitAll()\")\n public ResponseEntity<byte[]> getAttachmentUnitAttachment(@PathVariable Long attachmentUnitId, @PathVariable String filename,\n @RequestParam(\"access_token\") String temporaryAccessToken) {\n log.debug(\"REST request to get file : {}\", filename);\n Optional<AttachmentUnit> optionalAttachmentUnit = attachmentUnitRepository.findById(attachmentUnitId);\n if (optionalAttachmentUnit.isEmpty()) {\n return ResponseEntity.badRequest().build();\n }\n if (!validateTemporaryAccessToken(temporaryAccessToken, filename)) {\n // NOTE: this is a special case, because we like to show this error message directly in the browser (without the angular client being active)\n String errorMessage = \"You don't have the access rights for this file! Please login to Artemis and download the attachment in the corresponding attachmentUnit\";\n return ResponseEntity.status(HttpStatus.FORBIDDEN).body(errorMessage.getBytes());\n }\n return buildFileResponse(Paths.get(FilePathService.getAttachmentUnitFilePath(), String.valueOf(optionalAttachmentUnit.get().getId())).toString(), filename);\n }\n\n /**\n * Validates temporary access token\n *\n * @param temporaryAccessToken token to be validated\n * @param filename the name of the file\n * @return true if temporaryAccessToken is valid for this file, false otherwise\n */\n private boolean validateTemporaryAccessToken(String temporaryAccessToken, String filename) {\n if (temporaryAccessToken == null || !this.tokenProvider.validateTokenForAuthorityAndFile(temporaryAccessToken, TokenProvider.DOWNLOAD_FILE_AUTHORITY, filename)) {\n log.info(\"Attachment with invalid token was accessed\");\n return false;\n }\n return true;\n }\n\n /**\n * Helper method which handles the file creation for both normal file uploads and for markdown\n * @param file The file to be uplaoded\n * @param keepFileName specifies if original file name should be kept\n * @param markdown boolean which is set to true, when we are uploading a file within the markdown editor\n * @return The path of the file\n * @throws URISyntaxException if response path can't be converted into URI\n */\n @NotNull\n private ResponseEntity<String> handleSaveFile(MultipartFile file, boolean keepFileName, boolean markdown) throws URISyntaxException {\n // NOTE: Maximum file size is set in resources/config/application.yml\n // Currently set to 10 MB\n\n // check for file type\n String fileExtension = FilenameUtils.getExtension(file.getOriginalFilename());\n if (fileExtension == null || this.allowedFileExtensions.stream().noneMatch(fileExtension::equalsIgnoreCase)) {\n return ResponseEntity.badRequest().body(\"Unsupported file type! Allowed file types: \" + String.join(\", \", this.allowedFileExtensions));\n }\n\n final String filePath;\n final String fileNameAddition;\n final StringBuilder responsePath = new StringBuilder();\n\n // set the appropriate values depending on the use case\n if (markdown) {\n filePath = FilePathService.getMarkdownFilePath();\n fileNameAddition = \"Markdown_\";\n responsePath.append(\"/api/files/markdown/\");\n }\n else {\n filePath = FilePathService.getTempFilePath();\n fileNameAddition = \"Temp_\";\n responsePath.append(\"/api/files/temp/\");\n }\n\n try {\n // create folder if necessary\n File folder;\n folder = new File(filePath);\n if (!folder.exists()) {\n if (!folder.mkdirs()) {\n log.error(\"Could not create directory: {}\", filePath);\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();\n }\n }\n\n // create file (generate new filename, if file already exists)\n boolean fileCreated;\n File newFile;\n String filename;\n do {\n if (keepFileName) {\n filename = file.getOriginalFilename().replaceAll(\"\\\\s\", \"\");\n }\n else {\n filename = fileNameAddition + ZonedDateTime.now().toString().substring(0, 23).replaceAll(\":|\\\\.\", \"-\") + \"_\" + UUID.randomUUID().toString().substring(0, 8)\n + \".\" + fileExtension;\n }\n String path = Paths.get(filePath, filename).toString();\n\n newFile = new File(path);\n if (keepFileName && newFile.exists()) {\n newFile.delete();\n }\n fileCreated = newFile.createNewFile();\n }\n while (!fileCreated);\n responsePath.append(filename);\n\n // copy contents of uploaded file into newly created file\n Files.copy(file.getInputStream(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);\n\n // return path for getting the file\n String responseBody = \"{\\\"path\\\":\\\"\" + responsePath.toString() + \"\\\"}\";\n return ResponseEntity.created(new URI(responsePath.toString())).body(responseBody);\n }\n catch (IOException e) {\n e.printStackTrace();\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();\n }\n }\n\n /**\n * Builds the response with headers, body and content type for specified path and file name\n *\n * @param path to the file\n * @param filename the name of the file\n * @return response entity\n */\n private ResponseEntity<byte[]> buildFileResponse(String path, String filename) {\n try {\n var actualPath = Paths.get(path, filename).toString();\n var file = fileService.getFileForPath(actualPath);\n if (file == null) {\n return ResponseEntity.notFound().build();\n }\n\n ContentDisposition contentDisposition = ContentDisposition.builder(\"inline\").filename(filename).build();\n HttpHeaders headers = new HttpHeaders();\n headers.setContentDisposition(contentDisposition);\n FileNameMap fileNameMap = URLConnection.getFileNameMap();\n String mimeType = fileNameMap.getContentTypeFor(filename);\n\n // If we were unable to find mimeType with previous method, try another one, which returns application/octet-stream mime type,\n // if it also can't determine mime type\n if (mimeType == null) {\n MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();\n mimeType = fileTypeMap.getContentType(filename);\n }\n return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType(mimeType)).header(\"filename\", filename).body(file);\n }\n catch (IOException ex) {\n log.error(\"Failed to download file: \" + filename + \"on path: \" + path, ex);\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();\n }\n }\n\n /**\n * Reads the file and turns it into a ResponseEntity\n *\n * @param path the path for the file to read\n * @return ResponseEntity with status 200 and the file as byte stream, status 404 if the file doesn't exist, or status 500 if there is an error while reading the file\n */\n private ResponseEntity<byte[]> responseEntityForFilePath(String path, String filename) {\n try {\n var actualPath = Paths.get(path, filename).toString();\n var file = fileService.getFileForPath(actualPath);\n if (file == null) {\n return ResponseEntity.notFound().build();\n }\n return ResponseEntity.ok(file);\n }\n catch (IOException e) {\n e.printStackTrace();\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();\n }\n }\n\n}\n" }, { "alpha_fraction": 0.6337270140647888, "alphanum_fraction": 0.6347768902778625, "avg_line_length": 34.7746467590332, "blob_id": "2c3b2f2826c385b56b67d3e95e9bdcca84ae9261", "content_id": "14c187c70d79eb2450290292b4a651ee026dc0de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7620, "license_type": "permissive", "max_line_length": 134, "num_lines": 213, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/jobs/JenkinsJobService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.jenkins.jobs;\n\nimport java.io.IOException;\nimport java.io.StringWriter;\n\nimport javax.xml.transform.TransformerException;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.jsoup.Jsoup;\nimport org.jsoup.parser.Parser;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Service;\nimport org.w3c.dom.Document;\n\nimport com.offbytwo.jenkins.JenkinsServer;\nimport com.offbytwo.jenkins.model.FolderJob;\nimport com.offbytwo.jenkins.model.JobWithDetails;\n\nimport de.tum.in.www1.artemis.exception.JenkinsException;\nimport de.tum.in.www1.artemis.service.util.XmlFileUtils;\n\n@Service\n@Profile(\"jenkins\")\npublic class JenkinsJobService {\n\n private static final Logger log = LoggerFactory.getLogger(JenkinsJobService.class);\n\n @Value(\"${jenkins.use-crumb:#{true}}\")\n private boolean useCrumb;\n\n private final JenkinsServer jenkinsServer;\n\n public JenkinsJobService(JenkinsServer jenkinsServer) {\n this.jenkinsServer = jenkinsServer;\n }\n\n /**\n * Retrieves the job inside a folder job or null if it doesn't exist.\n * @param folderJobName the name of the folder job\n * @param jobName the name of the job\n * @return the job with details\n */\n public JobWithDetails getJobInFolder(String folderJobName, String jobName) {\n if (folderJobName == null || jobName == null) {\n log.warn(\"Cannot get the job, because projectKey {} or jobName {} is null\", folderJobName, jobName);\n return null;\n }\n\n final var folder = getFolderJob(folderJobName);\n if (folder == null) {\n log.warn(\"Cannot get the job {} in folder {} because it doesn't exist.\", jobName, folderJobName);\n return null;\n }\n\n try {\n return jenkinsServer.getJob(folder, jobName);\n }\n catch (IOException e) {\n log.error(e.getMessage(), e);\n throw new JenkinsException(e.getMessage(), e);\n }\n }\n\n /**\n * Gets the folder job or null if it doesn't exist\n * @param folderName the name of the folder job\n * @return the folder job\n */\n public FolderJob getFolderJob(String folderName) {\n try {\n final var job = jenkinsServer.getJob(folderName);\n if (job == null) {\n return null;\n }\n\n final var folderJob = jenkinsServer.getFolderJob(job);\n if (!folderJob.isPresent()) {\n return null;\n }\n return folderJob.get();\n }\n catch (IOException e) {\n log.error(e.getMessage(), e);\n throw new JenkinsException(e.getMessage(), e);\n }\n }\n\n /**\n * Gets the xml config of the job that is inside a folder\n * @param folderName the name of the folder\n * @param jobName the name of the job\n * @return the xml document\n */\n public Document getJobConfigForJobInFolder(String folderName, String jobName) {\n try {\n var folder = getFolderJob(folderName);\n if (folder == null) {\n throw new JenkinsException(\"The folder \" + folderName + \"does not exist.\");\n }\n\n var xmlString = jenkinsServer.getJobXml(folder, jobName);\n return XmlFileUtils.readFromString(xmlString);\n }\n catch (IOException e) {\n log.error(e.getMessage(), e);\n throw new JenkinsException(e.getMessage(), e);\n }\n }\n\n /**\n * Gets the xml config of the folder job.\n * @param folderName the name of the folder\n * @return the xml document or null if the folder doesn't exist\n * @throws IOException in case of errors\n */\n public org.jsoup.nodes.Document getFolderConfig(String folderName) throws IOException {\n if (jenkinsServer.getJob(folderName) == null) {\n return null;\n }\n\n var folderXml = jenkinsServer.getJobXml(folderName);\n\n // Parse the config xml file for the job and insert the permissions into it.\n var document = Jsoup.parse(folderXml, \"\", Parser.xmlParser());\n document.outputSettings().indentAmount(0).prettyPrint(false);\n\n return document;\n }\n\n /**\n * Creates a job inside a folder\n * @param jobConfig the config of the job to create\n * @param folderName the name of the folder\n * @param jobName the name of the job\n */\n public void createJobInFolder(Document jobConfig, String folderName, String jobName) {\n try {\n var folder = getFolderJob(folderName);\n if (folder == null) {\n throw new JenkinsException(\"Cannot create job \" + jobName + \" because the folder \" + folderName + \" does not exist.\");\n }\n jenkinsServer.createJob(folder, jobName, writeXmlToString(jobConfig), useCrumb);\n }\n catch (IOException e) {\n log.error(e.getMessage(), e);\n throw new JenkinsException(e.getMessage(), e);\n }\n }\n\n /**\n * Writes the xml document into a string.\n * @param doc the xml document\n * @return the xml as string\n */\n public String writeXmlToString(Document doc) {\n try {\n final var tf = TransformerFactory.newInstance();\n final var transformer = tf.newTransformer();\n final var writer = new StringWriter();\n transformer.transform(new DOMSource(doc), new StreamResult(writer));\n return writer.getBuffer().toString();\n }\n catch (TransformerException e) {\n final var errorMessage = \"Unable to parse XML document to String! \" + doc;\n log.error(errorMessage, e);\n throw new JenkinsException(errorMessage, e);\n }\n }\n\n /**\n * Gets the job config of a job that is inside a folder\n * @param folderName the name of the folder\n * @param jobName the name of the job\n * @return the job config as an xml document or null if the job doesn't exist\n * @throws IOException in case of errors\n */\n public org.jsoup.nodes.Document getJobConfig(String folderName, String jobName) throws IOException {\n var job = jenkinsServer.getJob(folderName);\n if (job == null) {\n return null;\n }\n var folder = jenkinsServer.getFolderJob(job);\n var jobXml = jenkinsServer.getJobXml(folder.orNull(), jobName);\n\n // Parse the config xml file for the job and insert the permissions into it.\n var document = Jsoup.parse(jobXml, \"\", Parser.xmlParser());\n document.outputSettings().indentAmount(0).prettyPrint(false);\n return document;\n }\n\n /**\n * Updates a job.\n * @param folderName optional folder name where the job resides\n * @param jobName the name of the job\n * @param jobConfig the updated job config\n * @throws IOException in case of errors\n */\n public void updateJob(String folderName, String jobName, org.jsoup.nodes.Document jobConfig) throws IOException {\n if (folderName != null && !folderName.isEmpty()) {\n var job = jenkinsServer.getJob(folderName);\n var folder = jenkinsServer.getFolderJob(job);\n jenkinsServer.updateJob(folder.orNull(), jobName, jobConfig.toString(), useCrumb);\n }\n else {\n jenkinsServer.updateJob(jobName, jobConfig.toString(), useCrumb);\n }\n }\n}\n" }, { "alpha_fraction": 0.797468364238739, "alphanum_fraction": 0.799578070640564, "avg_line_length": 66.71428680419922, "blob_id": "9187c340b471d39966e77b0112b61bc43a2a4393", "content_id": "ed467e6f4f88ea9a7ac504a0025d3c79c03293d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 474, "license_type": "permissive", "max_line_length": 176, "num_lines": 7, "path": "/src/main/java/de/tum/in/www1/artemis/domain/enumeration/NotificationType.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.enumeration;\n\npublic enum NotificationType {\n ATTACHMENT_CHANGE, EXERCISE_CREATED, EXERCISE_PRACTICE, QUIZ_EXERCISE_STARTED, EXERCISE_UPDATED, NEW_ANSWER_FOR_EXERCISE, NEW_ANSWER_FOR_LECTURE, NEW_QUESTION_FOR_EXERCISE,\n NEW_QUESTION_FOR_LECTURE, COURSE_ARCHIVE_STARTED, COURSE_ARCHIVE_FINISHED, COURSE_ARCHIVE_FAILED, DUPLICATE_TEST_CASE, EXAM_ARCHIVE_STARTED, EXAM_ARCHIVE_FINISHED,\n EXAM_ARCHIVE_FAILED, ILLEGAL_SUBMISSION\n}\n" }, { "alpha_fraction": 0.7222440242767334, "alphanum_fraction": 0.7245543003082275, "avg_line_length": 58.27906799316406, "blob_id": "f7571b4922437a9443d5c2eb0dc93cf7d1d01ebc", "content_id": "1b0bfbfd98adc43f7d6f5cc6a192b15c7b528542", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 22941, "license_type": "permissive", "max_line_length": 169, "num_lines": 387, "path": "/src/test/javascript/spec/integration/code-editor/code-editor-instructor.integration.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ChangeDetectorRef, DebugElement } from '@angular/core';\nimport { ActivatedRoute, Params, Router } from '@angular/router';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { BehaviorSubject, Observable, of, Subject, throwError } from 'rxjs';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as ace from 'brace';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { DomainType, FileType } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { problemStatement } from '../../helpers/sample/problemStatement.json';\nimport { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { CodeEditorInstructorContainerComponent } from 'app/exercises/programming/manage/code-editor/code-editor-instructor-container.component';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { MockCourseExerciseService } from '../../helpers/mocks/service/mock-course-exercise.service';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport {\n CodeEditorBuildLogService,\n CodeEditorRepositoryFileService,\n CodeEditorRepositoryService,\n} from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { DomainService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain.service';\nimport { TemplateProgrammingExerciseParticipation } from 'app/entities/participation/template-programming-exercise-participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { SolutionProgrammingExerciseParticipation } from 'app/entities/participation/solution-programming-exercise-participation.model';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockResultService } from '../../helpers/mocks/service/mock-result.service';\nimport { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service';\nimport { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service';\nimport { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockParticipationService } from '../../helpers/mocks/service/mock-participation.service';\nimport { MockProgrammingExerciseService } from '../../helpers/mocks/service/mock-programming-exercise.service';\nimport { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { MockWebsocketService } from '../../helpers/mocks/service/mock-websocket.service';\nimport { ArtemisCodeEditorManagementModule } from 'app/exercises/programming/manage/code-editor/code-editor-management.module';\nimport { CourseExerciseService } from 'app/course/manage/course-management.service';\nimport { ArtemisCodeEditorModule } from 'app/exercises/programming/shared/code-editor/code-editor.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorInstructorIntegration', () => {\n // needed to make sure ace is defined\n ace.acequire('ace/ext/modelist');\n let container: CodeEditorInstructorContainerComponent;\n let containerFixture: ComponentFixture<CodeEditorInstructorContainerComponent>;\n let containerDebugElement: DebugElement;\n let domainService: DomainService;\n let route: ActivatedRoute;\n\n let checkIfRepositoryIsCleanStub: SinonStub;\n let getRepositoryContentStub: SinonStub;\n let subscribeForLatestResultOfParticipationStub: SinonStub;\n let getFeedbackDetailsForResultStub: SinonStub;\n let getBuildLogsStub: SinonStub;\n let findWithParticipationsStub: SinonStub;\n let getLatestResultWithFeedbacksStub: SinonStub;\n let getHintsForExerciseStub: SinonStub;\n\n let checkIfRepositoryIsCleanSubject: Subject<{ isClean: boolean }>;\n let getRepositoryContentSubject: Subject<{ [fileName: string]: FileType }>;\n let subscribeForLatestResultOfParticipationSubject: BehaviorSubject<Result | null>;\n let findWithParticipationsSubject: Subject<{ body: ProgrammingExercise }>;\n let routeSubject: Subject<Params>;\n\n const exerciseHints = [{ id: 1 }, { id: 2 }];\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisCodeEditorManagementModule, ArtemisCodeEditorModule],\n declarations: [],\n providers: [\n JhiLanguageHelper,\n ChangeDetectorRef,\n DeviceDetectorService,\n { provide: Router, useClass: MockRouter },\n { provide: AccountService, useClass: MockAccountService },\n { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: ResultService, useClass: MockResultService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: CourseExerciseService, useClass: MockCourseExerciseService },\n { provide: CodeEditorRepositoryService, useClass: MockCodeEditorRepositoryService },\n { provide: CodeEditorRepositoryFileService, useClass: MockCodeEditorRepositoryFileService },\n { provide: CodeEditorBuildLogService, useClass: MockCodeEditorBuildLogService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: ResultService, useClass: MockResultService },\n { provide: ParticipationService, useClass: MockParticipationService },\n { provide: ProgrammingExerciseParticipationService, useClass: MockProgrammingExerciseParticipationService },\n { provide: ProgrammingExerciseService, useClass: MockProgrammingExerciseService },\n { provide: ExerciseHintService, useClass: MockExerciseHintService },\n { provide: JhiWebsocketService, useClass: MockWebsocketService },\n ],\n })\n .compileComponents()\n .then(() => {\n containerFixture = TestBed.createComponent(CodeEditorInstructorContainerComponent);\n container = containerFixture.componentInstance;\n containerDebugElement = containerFixture.debugElement;\n\n const codeEditorRepositoryService = containerDebugElement.injector.get(CodeEditorRepositoryService);\n const codeEditorRepositoryFileService = containerDebugElement.injector.get(CodeEditorRepositoryFileService);\n const participationWebsocketService = containerDebugElement.injector.get(ParticipationWebsocketService);\n const resultService = containerDebugElement.injector.get(ResultService);\n const buildLogService = containerDebugElement.injector.get(CodeEditorBuildLogService);\n const programmingExerciseParticipationService = containerDebugElement.injector.get(ProgrammingExerciseParticipationService);\n const programmingExerciseService = containerDebugElement.injector.get(ProgrammingExerciseService);\n domainService = containerDebugElement.injector.get(DomainService);\n route = containerDebugElement.injector.get(ActivatedRoute);\n const exerciseHintService = containerDebugElement.injector.get(ExerciseHintService);\n containerDebugElement.injector.get(Router);\n\n checkIfRepositoryIsCleanSubject = new Subject<{ isClean: boolean }>();\n getRepositoryContentSubject = new Subject<{ [fileName: string]: FileType }>();\n subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | null>(null);\n findWithParticipationsSubject = new Subject<{ body: ProgrammingExercise }>();\n\n routeSubject = new Subject<Params>();\n // @ts-ignore\n (route as MockActivatedRouteWithSubjects).setSubject(routeSubject);\n\n checkIfRepositoryIsCleanStub = stub(codeEditorRepositoryService, 'getStatus');\n getRepositoryContentStub = stub(codeEditorRepositoryFileService, 'getRepositoryContent');\n subscribeForLatestResultOfParticipationStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation');\n getFeedbackDetailsForResultStub = stub(resultService, 'getFeedbackDetailsForResult');\n getLatestResultWithFeedbacksStub = stub(programmingExerciseParticipationService, 'getLatestResultWithFeedback').returns(throwError('no result'));\n getBuildLogsStub = stub(buildLogService, 'getBuildLogs');\n getHintsForExerciseStub = stub(exerciseHintService, 'findByExerciseId').returns(of({ body: exerciseHints }) as Observable<HttpResponse<ExerciseHint[]>>);\n\n findWithParticipationsStub = stub(programmingExerciseService, 'findWithTemplateAndSolutionParticipationAndResults');\n findWithParticipationsStub.returns(findWithParticipationsSubject);\n\n subscribeForLatestResultOfParticipationStub.returns(subscribeForLatestResultOfParticipationSubject);\n getRepositoryContentStub.returns(getRepositoryContentSubject);\n checkIfRepositoryIsCleanStub.returns(checkIfRepositoryIsCleanSubject);\n });\n });\n\n afterEach(() => {\n checkIfRepositoryIsCleanStub.restore();\n getRepositoryContentStub.restore();\n subscribeForLatestResultOfParticipationStub.restore();\n getFeedbackDetailsForResultStub.restore();\n getBuildLogsStub.restore();\n findWithParticipationsStub.restore();\n getLatestResultWithFeedbacksStub.restore();\n\n subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | null>(null);\n subscribeForLatestResultOfParticipationStub.returns(subscribeForLatestResultOfParticipationSubject);\n\n routeSubject = new Subject<Params>();\n // @ts-ignore\n (route as MockActivatedRouteWithSubjects).setSubject(routeSubject);\n\n findWithParticipationsSubject = new Subject<{ body: ProgrammingExercise }>();\n findWithParticipationsStub.returns(findWithParticipationsSubject);\n\n checkIfRepositoryIsCleanSubject = new Subject<{ isClean: boolean }>();\n checkIfRepositoryIsCleanStub.returns(checkIfRepositoryIsCleanSubject);\n\n getRepositoryContentSubject = new Subject<{ [p: string]: FileType }>();\n getRepositoryContentStub.returns(getRepositoryContentSubject);\n });\n\n const initContainer = (exercise: ProgrammingExercise) => {\n container.ngOnInit();\n routeSubject.next({ exerciseId: 1 });\n expect(container.codeEditorContainer).to.be.undefined;\n expect(findWithParticipationsStub).to.have.been.calledOnceWithExactly(exercise.id);\n expect(container.loadingState).to.equal(container.LOADING_STATE.INITIALIZING);\n };\n\n it('should load the exercise and select the template participation if no participation id is provided', () => {\n jest.resetModules();\n // @ts-ignore\n const exercise = {\n id: 1,\n problemStatement,\n studentParticipations: [{ id: 2, repositoryUrl: 'test' }],\n templateParticipation: { id: 3, repositoryUrl: 'test2', results: [{ id: 9, submission: { id: 1, buildFailed: false } }] },\n solutionParticipation: { id: 4, repositoryUrl: 'test3' },\n course: { id: 1 },\n } as ProgrammingExercise;\n exercise.studentParticipations = exercise.studentParticipations?.map((p) => {\n p.exercise = exercise;\n return p;\n });\n exercise.templateParticipation = { ...exercise.templateParticipation, programmingExercise: exercise };\n exercise.solutionParticipation = { ...exercise.solutionParticipation, programmingExercise: exercise };\n\n getFeedbackDetailsForResultStub.returns(of([]));\n const setDomainSpy = spy(domainService, 'setDomain');\n // @ts-ignore\n (container.router as MockRouter).setUrl('code-editor-instructor/1');\n initContainer(exercise);\n\n findWithParticipationsSubject.next({ body: exercise });\n\n expect(getLatestResultWithFeedbacksStub).not.to.have.been.called;\n expect(setDomainSpy).to.have.been.calledOnce;\n expect(setDomainSpy).to.have.been.calledOnceWithExactly([DomainType.PARTICIPATION, exercise.templateParticipation]);\n expect(container.exercise).to.deep.equal(exercise);\n expect(container.selectedRepository).to.equal(container.REPOSITORY.TEMPLATE);\n expect(container.selectedParticipation).to.deep.equal(container.selectedParticipation);\n expect(container.loadingState).to.equal(container.LOADING_STATE.CLEAR);\n expect(container.domainChangeSubscription).to.exist;\n\n containerFixture.detectChanges();\n expect(container.codeEditorContainer.grid).to.exist;\n\n checkIfRepositoryIsCleanSubject.next({ isClean: true });\n getRepositoryContentSubject.next({ file: FileType.FILE, folder: FileType.FOLDER });\n containerFixture.detectChanges();\n\n // Submission could be built\n expect(getBuildLogsStub).to.not.have.been.called;\n // Once called by each build-output & instructions\n expect(getFeedbackDetailsForResultStub).to.have.been.calledTwice;\n\n expect(container.codeEditorContainer.grid).to.exist;\n expect(container.codeEditorContainer.fileBrowser).to.exist;\n expect(container.codeEditorContainer.actions).to.exist;\n expect(container.editableInstructions).to.exist;\n expect(container.editableInstructions.participation.id).to.deep.equal(exercise.templateParticipation.id);\n expect(container.resultComp).to.exist;\n expect(container.codeEditorContainer.buildOutput).to.exist;\n expect(container.editableInstructions.exerciseHints).to.deep.equal(exerciseHints);\n\n // Called once by each build-output, instructions, result and twice by instructor-exercise-status (=templateParticipation,solutionParticipation) &\n expect(subscribeForLatestResultOfParticipationStub.callCount).to.equal(5);\n\n // called once by instructions (hints are only visible if assignment repo is selected).\n expect(getHintsForExerciseStub).to.have.been.calledOnce;\n expect(getHintsForExerciseStub).to.have.been.calledWithExactly(exercise.id);\n });\n\n it('should go into error state when loading the exercise failed', () => {\n const exercise = { id: 1, studentParticipations: [{ id: 2 }], templateParticipation: { id: 3 }, solutionParticipation: { id: 4 } } as ProgrammingExercise;\n const setDomainSpy = spy(domainService, 'setDomain');\n initContainer(exercise);\n\n findWithParticipationsSubject.error('fatal error');\n\n expect(setDomainSpy).to.not.have.been.called;\n expect(container.loadingState).to.equal(container.LOADING_STATE.FETCHING_FAILED);\n expect(container.selectedRepository).to.be.undefined;\n\n containerFixture.detectChanges();\n expect(container.codeEditorContainer).to.be.undefined;\n });\n\n it('should load test repository if specified in url', () => {\n const exercise = {\n id: 1,\n problemStatement,\n studentParticipations: [{ id: 2 }],\n templateParticipation: { id: 3 },\n solutionParticipation: { id: 4 },\n course: { id: 1 },\n } as ProgrammingExercise;\n const setDomainSpy = spy(domainService, 'setDomain');\n // @ts-ignore\n (container.router as MockRouter).setUrl('code-editor-instructor/1/test');\n container.ngOnDestroy();\n initContainer(exercise);\n\n findWithParticipationsSubject.next({ body: exercise });\n\n expect(setDomainSpy).to.have.been.calledOnceWithExactly([DomainType.TEST_REPOSITORY, exercise]);\n expect(container.selectedParticipation).not.to.exist;\n expect(container.selectedRepository).to.equal(container.REPOSITORY.TEST);\n expect(getBuildLogsStub).not.to.have.been.called;\n expect(getFeedbackDetailsForResultStub).not.to.have.been.called;\n\n containerFixture.detectChanges();\n\n expect(container.codeEditorContainer).to.exist;\n expect(container.editableInstructions).to.exist;\n expect(container.editableInstructions.participation).to.deep.equal(exercise.templateParticipation);\n expect(container.resultComp).not.to.exist;\n expect(container.codeEditorContainer.buildOutput).not.to.exist;\n });\n\n const checkSolutionRepository = (exercise: ProgrammingExercise) => {\n expect(container.selectedRepository).to.equal(container.REPOSITORY.SOLUTION);\n expect(container.selectedParticipation).to.deep.equal(exercise.solutionParticipation);\n expect(container.codeEditorContainer).to.exist;\n expect(container.editableInstructions).to.exist;\n expect(container.resultComp).to.exist;\n expect(container.codeEditorContainer.buildOutput).to.exist;\n expect(container.codeEditorContainer.buildOutput.participation).to.deep.equal(exercise.solutionParticipation);\n expect(container.editableInstructions.participation).to.deep.equal(exercise.solutionParticipation);\n };\n\n it('should be able to switch between the repos and update the child components accordingly', () => {\n // @ts-ignore\n const exercise = {\n id: 1,\n course: { id: 1 },\n problemStatement,\n } as ProgrammingExercise;\n exercise.templateParticipation = { id: 3, repositoryUrl: 'test2', programmingExercise: exercise } as TemplateProgrammingExerciseParticipation;\n exercise.solutionParticipation = { id: 4, repositoryUrl: 'test3', programmingExercise: exercise } as SolutionProgrammingExerciseParticipation;\n // @ts-ignore\n exercise.studentParticipations = [{ id: 2, repositoryUrl: 'test', exercise } as ProgrammingExerciseStudentParticipation];\n\n const setDomainSpy = spy(domainService, 'setDomain');\n\n // Start with assignment repository\n // @ts-ignore\n (container.router as MockRouter).setUrl('code-editor-instructor/1/2');\n container.ngOnInit();\n routeSubject.next({ exerciseId: 1, participationId: 2 });\n findWithParticipationsSubject.next({ body: exercise });\n\n containerFixture.detectChanges();\n\n expect(container.selectedRepository).to.equal(container.REPOSITORY.ASSIGNMENT);\n expect(container.selectedParticipation).to.deep.equal(exercise.studentParticipations[0]);\n expect(container.codeEditorContainer).to.exist;\n expect(container.editableInstructions).to.exist;\n expect(container.resultComp).to.exist;\n expect(container.codeEditorContainer.buildOutput).to.exist;\n expect(container.codeEditorContainer.buildOutput.participation).to.deep.equal(exercise.studentParticipations[0]);\n expect(container.editableInstructions.participation).to.deep.equal(exercise.studentParticipations[0]);\n\n // New select solution repository\n // @ts-ignore\n (container.router as MockRouter).setUrl('code-editor-instructor/1/4');\n routeSubject.next({ exerciseId: 1, participationId: 4 });\n\n containerFixture.detectChanges();\n\n checkSolutionRepository(exercise);\n\n expect(findWithParticipationsStub).to.have.been.calledOnceWithExactly(exercise.id);\n expect(setDomainSpy).to.have.been.calledTwice;\n expect(setDomainSpy).to.have.been.calledWith([DomainType.PARTICIPATION, exercise.studentParticipations[0]]);\n expect(setDomainSpy).to.have.been.calledWith([DomainType.PARTICIPATION, exercise.solutionParticipation]);\n });\n\n it('should not be able to select a repository without repositoryUrl', () => {\n // @ts-ignore\n const exercise = {\n id: 1,\n course: { id: 1 },\n problemStatement,\n } as ProgrammingExercise;\n // @ts-ignore\n exercise.studentParticipations = [{ id: 2, repositoryUrl: 'test', exercise } as ProgrammingExerciseStudentParticipation];\n exercise.templateParticipation = { id: 3, programmingExercise: exercise } as TemplateProgrammingExerciseParticipation;\n exercise.solutionParticipation = { id: 4, repositoryUrl: 'test3', programmingExercise: exercise } as SolutionProgrammingExerciseParticipation;\n\n const setDomainSpy = spy(domainService, 'setDomain');\n\n // Start with assignment repository\n // @ts-ignore\n (container.router as MockRouter).setUrl('code-editor-instructor/1/3');\n container.ngOnInit();\n routeSubject.next({ exerciseId: 1, participationId: 3 });\n findWithParticipationsSubject.next({ body: exercise });\n\n containerFixture.detectChanges();\n\n expect(setDomainSpy).to.have.been.calledOnce;\n expect(setDomainSpy).to.have.been.calledOnceWithExactly([DomainType.PARTICIPATION, exercise.solutionParticipation]);\n checkSolutionRepository(exercise);\n });\n});\n" }, { "alpha_fraction": 0.8017621040344238, "alphanum_fraction": 0.8050661087036133, "avg_line_length": 48.08108139038086, "blob_id": "2c74eb39e588e94ec24ca70e9ff4b6b9d6569b90", "content_id": "68b56b9396423b0657f7841a07ffbad1645c7b3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1816, "license_type": "permissive", "max_line_length": 175, "num_lines": 37, "path": "/src/main/java/de/tum/in/www1/artemis/service/SystemNotificationService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Objects;\n\nimport org.springframework.messaging.simp.SimpMessageSendingOperations;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.notification.SystemNotification;\nimport de.tum.in.www1.artemis.repository.SystemNotificationRepository;\nimport de.tum.in.www1.artemis.security.SecurityUtils;\n\n@Service\npublic class SystemNotificationService {\n\n private final SimpMessageSendingOperations messagingTemplate;\n\n private final SystemNotificationRepository systemNotificationRepository;\n\n public SystemNotificationService(SimpMessageSendingOperations messagingTemplate, SystemNotificationRepository systemNotificationRepository) {\n this.messagingTemplate = messagingTemplate;\n this.systemNotificationRepository = systemNotificationRepository;\n }\n\n public SystemNotification findActiveSystemNotification() {\n // The 'user' does not need to be logged into Artemis, this leads to an issue when accessing custom repository methods. Therefore a mock auth object has to be created.\n SecurityUtils.setAuthorizationObject();\n List<SystemNotification> allActiveSystemNotification = systemNotificationRepository.findAllActiveSystemNotification(ZonedDateTime.now());\n return allActiveSystemNotification.size() > 0 ? allActiveSystemNotification.get(0) : null;\n }\n\n public void sendNotification(SystemNotification systemNotification) {\n // we cannot send null over websockets so in case the systemNotification object is null, we send 'deleted' and handle this case in the client\n messagingTemplate.convertAndSend(\"/topic/system-notification\", Objects.requireNonNullElse(systemNotification, \"deleted\"));\n }\n}\n" }, { "alpha_fraction": 0.7274817228317261, "alphanum_fraction": 0.7297805547714233, "avg_line_length": 47.33333206176758, "blob_id": "66ef534da1e9b6d0f8287c91a06e0d3a58b8a2fa", "content_id": "9536ec3a79e644a9c851f2bc925a1977b6905f49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4785, "license_type": "permissive", "max_line_length": 161, "num_lines": 99, "path": "/src/test/javascript/spec/component/learning-goals/learning-goal-card.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { TranslateService } from '@ngx-translate/core';\nimport { LearningGoalCardComponent } from 'app/course/learning-goals/learning-goal-card/learning-goal-card.component';\nimport { LearningGoalCourseDetailModalComponent } from 'app/course/learning-goals/learning-goal-course-detail-modal/learning-goal-course-detail-modal.component';\nimport { LearningGoalDetailModalComponent } from 'app/course/learning-goals/learning-goal-detail-modal/learning-goal-detail-modal.component';\nimport { IndividualLearningGoalProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { MockComponent, MockPipe, MockProvider } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\n@Component({ selector: 'jhi-circular-progress-bar', template: '' })\nclass CircularProgressBarStubComponent {\n @Input()\n progressInPercent = 0;\n @Input()\n progressText = 'Completed';\n}\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('LearningGoalCardComponent', () => {\n let learningGoalCardComponentFixture: ComponentFixture<LearningGoalCardComponent>;\n let learningGoalCardComponent: LearningGoalCardComponent;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [LearningGoalCardComponent, MockPipe(ArtemisTranslatePipe), CircularProgressBarStubComponent],\n providers: [MockProvider(LectureUnitService), MockProvider(TranslateService), MockProvider(NgbModal)],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n learningGoalCardComponentFixture = TestBed.createComponent(LearningGoalCardComponent);\n learningGoalCardComponent = learningGoalCardComponentFixture.componentInstance;\n learningGoalCardComponent.DetailModalComponent = MockComponent(LearningGoalDetailModalComponent);\n learningGoalCardComponent.CourseDetailModalComponent = MockComponent(LearningGoalCourseDetailModalComponent);\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n learningGoalCardComponentFixture.detectChanges();\n expect(learningGoalCardComponent).to.be.ok;\n });\n\n it('should display progress bar when progress is available', () => {\n const learningGoal = new LearningGoal();\n learningGoal.id = 1;\n const learningGoalProgress = new IndividualLearningGoalProgress();\n learningGoalProgress.studentId = 1;\n learningGoalProgress.learningGoalId = 1;\n learningGoalProgress.pointsAchievedByStudentInLearningGoal = 5;\n learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 10;\n\n learningGoalCardComponent.learningGoal = learningGoal;\n learningGoalCardComponent.learningGoalProgress = learningGoalProgress;\n\n learningGoalCardComponentFixture.detectChanges();\n\n const circularProgress = learningGoalCardComponentFixture.debugElement.query(By.directive(CircularProgressBarStubComponent)).componentInstance;\n expect(circularProgress).to.be.ok;\n expect(circularProgress.progressInPercent).to.equal(50);\n });\n\n it('should not display progress bar when progress is not available', () => {\n const learningGoal = new LearningGoal();\n learningGoal.id = 1;\n learningGoalCardComponent.learningGoal = learningGoal;\n\n learningGoalCardComponentFixture.detectChanges();\n\n const circularProgress = learningGoalCardComponentFixture.debugElement.query(By.directive(CircularProgressBarStubComponent));\n expect(circularProgress).to.not.exist;\n });\n\n it('should open learning details modal when card is clicked', () => {\n const learningGoal = new LearningGoal();\n learningGoal.id = 1;\n learningGoalCardComponent.learningGoal = learningGoal;\n learningGoalCardComponentFixture.detectChanges();\n\n const card = learningGoalCardComponentFixture.debugElement.nativeElement.querySelector('.course-goal-card');\n const modalService = TestBed.inject(NgbModal);\n const openSpy = sinon.spy(modalService, 'open');\n card.click();\n expect(openSpy).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.6840964555740356, "alphanum_fraction": 0.7190463542938232, "avg_line_length": 43.469879150390625, "blob_id": "632a2cd668c7e04af56ef063f74b826c8c6fb1f1", "content_id": "4df9dc7d27033aa20e489ea44e18eff0b861d283", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 3691, "license_type": "permissive", "max_line_length": 216, "num_lines": 83, "path": "/src/main/docker/jenkins/swift/Dockerfile", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "FROM jenkins/jenkins:lts\n\nLABEL description=\"Jenkins with maven, python3.6, gcc and swift libraries pre-installed for Artemis\"\n\nUSER root\n\nRUN apt update\n\n# Install Java and Maven dependencies\nRUN apt-get install -y maven\nRUN cd /usr/lib/jvm && \\\n wget https://github.com/AdoptOpenJDK/openjdk16-binaries/releases/download/jdk-16%2B36/OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz && \\\n tar -zxf OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz \\\n && mv jdk-16+36 java-16-openjdk-amd64 \\\n && rm OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz\nRUN chown -R root:root /usr/lib/jvm/java-16-openjdk-amd64\nRUN JAVA_HOME=\"/usr/lib/jvm/java-16-openjdk-amd64\" && export JAVA_HOME\nENV JAVA_HOME /usr/lib/jvm/java-16-openjdk-amd64\n\n# Install C dependencies\nRUN apt install -y gcc gdb make libubsan0 liblsan0 libtsan0\n\n# Some packages need to be installed to avoid some known problems for python3.6, see: https://github.com/pyenv/pyenv/wiki/Common-build-problems\nRUN apt install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \\\n libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \\\n xz-utils tk-dev libffi-dev liblzma-dev\n\n# Install Python3.8\nRUN wget https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tgz && \\\n tar xvf Python-3.8.6.tgz \\\n && cd Python-3.8.6 \\\n && ./configure --enable-shared \\\n && make -j8 \\\n && make altinstall\nRUN apt install -y python3 python3-pip\nRUN cd ..\nRUN rm -r -f Python3.8.6/ && rm -f Python-3.8.6.tgz\n\n# Install pytest for python exercises\nRUN pip3 install -U pytest\n\n# Install Swift and SwiftLint (adapted from norionomura/swift and norionomura/swiftlint)\nENV SWIFT_BRANCH swift-5.3.1-release\nENV SWIFT_PLATFORM ubuntu18.04\nENV SWIFT_VERSION 5.3.1-RELEASE\nRUN apt-get install -y --no-install-recommends \\\n gnupg2 \\\n libcurl4-openssl-dev \\\n libxml2-dev \\\n && rm -r /var/lib/apt/lists/*\n# Install Swift keys\nRUN curl https://swift.org/keys/all-keys.asc | gpg2 --import -\n# Install Swift toolchain\n# -> https://swift.org/builds/swift-5.3.1-release/ubuntu1804/swift-5.3.1-RELEASE/swift-5.3.1-RELEASE-ubuntu18.04.tar.gz\nRUN SWIFT_ARCHIVE_NAME=swift-$SWIFT_VERSION-$SWIFT_PLATFORM && \\\n SWIFT_URL=https://swift.org/builds/$SWIFT_BRANCH/$(echo \"$SWIFT_PLATFORM\" | tr -d .)/swift-$SWIFT_VERSION/$SWIFT_ARCHIVE_NAME.tar.gz && \\\n curl -O $SWIFT_URL && \\\n curl -O $SWIFT_URL.sig && \\\n gpg2 --verify $SWIFT_ARCHIVE_NAME.tar.gz.sig && \\\n tar -xvzf $SWIFT_ARCHIVE_NAME.tar.gz --directory / --strip-components=1 && \\\n rm -rf $SWIFT_ARCHIVE_NAME* /tmp/* /var/tmp/* && \\\n chmod -R o+r /usr/lib/swift\n# Install SwiftLint\nRUN git clone --branch master https://github.com/realm/SwiftLint.git && \\\n cd SwiftLint && \\\n swift build --configuration release -Xswiftc -static-stdlib && \\\n mv $(swift build --configuration release -Xswiftc -static-stdlib --show-bin-path)/swiftlint /usr/bin && \\\n cd .. && \\\n rm -rf SwiftLint\n\n# Install third-party plugins required by Artemis\nCOPY ../plugins.yml /usr/share/jenkins/ref/plugins.yml\nRUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.yml\n\n# Install docker client (if you want a local build agent)\n# (Uncomment this line if you want to use a local docker build agent e.g for development purposes)\n#RUN curl https://download.docker.com/linux/static/stable/x86_64/docker-19.03.8.tgz | tar xvz --directory /tmp && mv -v /tmp/docker/docker /usr/local/bin/docker && chmod +x /usr/local/bin/docker && rm -rf /tmp/docker\n\n# Disables the first-time setup wizard of Jenkins\n# (Uncomment this line if you're using jenknis-casc-config.yml for auto-configuration)\n#ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false\n\nUSER jenkins\n" }, { "alpha_fraction": 0.678260862827301, "alphanum_fraction": 0.679347813129425, "avg_line_length": 20.904762268066406, "blob_id": "1608fe995dab8cc46db0a68b9608896b2c4bc626", "content_id": "a11f3b5a991c0a8b4a972a46f1d03c61ffff664a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 920, "license_type": "permissive", "max_line_length": 61, "num_lines": 42, "path": "/src/main/java/de/tum/in/www1/artemis/domain/FileUploadExercise.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport javax.persistence.*;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n/**\n * A FileUploadExercise.\n */\n@Entity\n@DiscriminatorValue(value = \"F\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class FileUploadExercise extends Exercise {\n\n @Column(name = \"sample_solution\")\n @Lob\n private String sampleSolution;\n\n @Column(name = \"filePattern\")\n private String filePattern;\n\n public String getFilePattern() {\n return filePattern;\n }\n\n public void setFilePattern(String filePattern) {\n this.filePattern = filePattern;\n }\n\n public String getSampleSolution() {\n return sampleSolution;\n }\n\n public void setSampleSolution(String sampleSolution) {\n this.sampleSolution = sampleSolution;\n }\n\n @Override\n public String toString() {\n return \"FileUploadExercise{\" + \"id=\" + getId() + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.6880202889442444, "alphanum_fraction": 0.6898298859596252, "avg_line_length": 44.295082092285156, "blob_id": "e5b5bace32c359220a3e50f32a8513ff771837eb", "content_id": "63099f4c9f66b895f5cf11c753f10ccd6e5a6b37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5526, "license_type": "permissive", "max_line_length": 157, "num_lines": 122, "path": "/src/test/javascript/spec/component/exam/manage/exercise-group-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClientModule, HttpErrorResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { ActivatedRoute, convertToParamMap, Router } from '@angular/router';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport { EntityResponseType } from 'app/complaints/complaint.service';\nimport { Course } from 'app/entities/course.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ExerciseGroupUpdateComponent } from 'app/exam/manage/exercise-groups/exercise-group-update.component';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { MockComponent } from 'ng-mocks/dist/lib/mock-component/mock-component';\nimport { MockPipe } from 'ng-mocks/dist/lib/mock-pipe/mock-pipe';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of, throwError } from 'rxjs';\nimport * as sinon from 'sinon';\nimport { SinonStub, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ExerciseGroupUpdateComponent', () => {\n const course = { id: 456 } as Course;\n const exam: Exam = new Exam();\n const exerciseGroup: ExerciseGroup = new ExerciseGroup();\n exam.course = course;\n exam.id = 123;\n exerciseGroup.id = 1;\n exerciseGroup.exam = exam;\n\n let component: ExerciseGroupUpdateComponent;\n let fixture: ComponentFixture<ExerciseGroupUpdateComponent>;\n let service: ExerciseGroupService;\n const mockRouter = new MockRouter();\n let alertServiceStub: SinonStub;\n let alertService: JhiAlertService;\n\n const data = of({ exam, exerciseGroup });\n const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id, examId: exam.id }) }, data } as any) as ActivatedRoute;\n const navigateSpy = sinon.spy(mockRouter, 'navigate');\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientModule, FormsModule],\n declarations: [ExerciseGroupUpdateComponent, MockPipe(ArtemisTranslatePipe), MockComponent(FaIconComponent), MockComponent(AlertErrorComponent)],\n providers: [\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: route },\n { provide: Router, useValue: mockRouter },\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(ExerciseGroupUpdateComponent);\n component = fixture.componentInstance;\n service = TestBed.inject(ExerciseGroupService);\n alertService = TestBed.inject(JhiAlertService);\n });\n\n // Always initialized and bind before tests\n beforeEach(fakeAsync(() => {\n fixture.detectChanges();\n tick();\n expect(component).to.be.ok;\n expect(component.exam).to.deep.equal(exam);\n expect(component.exerciseGroup).to.deep.equal(exerciseGroup);\n }));\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('Should save exercise group', fakeAsync(() => {\n const responseFakeExerciseGroup = { body: exerciseGroup } as EntityResponseType;\n sinon.replace(service, 'update', sinon.fake.returns(of(responseFakeExerciseGroup)));\n\n component.save();\n\n expect(component.isSaving).to.be.false;\n expect(navigateSpy).to.have.been.calledWith(['course-management', course.id, 'exams', route.snapshot.paramMap.get('examId'), 'exercise-groups']);\n flush();\n }));\n\n it('Should save exercise group without ID', fakeAsync(() => {\n component.exerciseGroup.id = undefined;\n\n const responseFakeExerciseGroup = { body: exerciseGroup } as EntityResponseType;\n sinon.replace(service, 'create', sinon.fake.returns(of(responseFakeExerciseGroup)));\n\n component.save();\n\n expect(component.isSaving).to.be.false;\n expect(component.exam).to.deep.equal(exam);\n expect(navigateSpy).to.have.been.calledWith(['course-management', course.id, 'exams', route.snapshot.paramMap.get('examId'), 'exercise-groups']);\n flush();\n }));\n\n it('Should fail while saving with ErrorResponse', fakeAsync(() => {\n alertServiceStub = stub(alertService, 'error');\n const error = { status: 404 };\n component.exerciseGroup.id = undefined;\n\n sinon.replace(service, 'create', sinon.fake.returns(throwError(new HttpErrorResponse(error))));\n\n component.save();\n\n expect(component.isSaving).to.be.false;\n expect(component.exam).to.deep.equal(exam);\n expect(alertServiceStub).to.have.been.calledOnce;\n flush();\n }));\n});\n" }, { "alpha_fraction": 0.664599597454071, "alphanum_fraction": 0.6770021319389343, "avg_line_length": 41.11940383911133, "blob_id": "3b37b5055df175a9e3036d35faea63845d71ce10", "content_id": "572c2476e1630568e5510937b238923492face7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5644, "license_type": "permissive", "max_line_length": 131, "num_lines": 134, "path": "/src/test/javascript/spec/service/programming-exercise-grading.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { of, Subject } from 'rxjs';\nimport { tap } from 'rxjs/operators';\nimport * as sinonChai from 'sinon-chai';\nimport { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service';\nimport { IWebsocketService } from 'app/core/websocket/websocket.service.ts';\nimport { ProgrammingExerciseGradingService } from 'app/exercises/programming/manage/services/programming-exercise-grading.service';\nimport { MockHttpService } from '../helpers/mocks/service/mock-http.service';\nimport { ProgrammingExerciseTestCase } from 'app/entities/programming-exercise-test-case.model';\nimport { Result } from 'app/entities/result.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseGradingService', () => {\n let websocketService: IWebsocketService;\n let httpService: MockHttpService;\n let exercise1TestCaseSubject: Subject<Result>;\n let exercise2TestCaseSubject: Subject<Result>;\n let subscribeSpy: SinonSpy;\n let receiveStub: SinonStub;\n let unsubscribeSpy: SinonSpy;\n let getStub: SinonStub;\n\n let gradingService: ProgrammingExerciseGradingService;\n\n const exercise1 = { id: 1 };\n const exercise2 = { id: 2 };\n\n const testCases1 = [\n { testName: 'testBubbleSort', active: true },\n { testName: 'testMergeSort', active: true },\n { testName: 'otherTest', active: false },\n ] as ProgrammingExerciseTestCase[];\n const testCases2 = [\n { testName: 'testBubbleSort', active: false },\n { testName: 'testMergeSort', active: true },\n { testName: 'otherTest', active: true },\n ] as ProgrammingExerciseTestCase[];\n\n const exercise1Topic = `/topic/programming-exercise/${exercise1.id}/test-cases`;\n const exercise2Topic = `/topic/programming-exercise/${exercise2.id}/test-cases`;\n\n beforeEach(async(() => {\n websocketService = new MockWebsocketService();\n httpService = new MockHttpService();\n gradingService = new ProgrammingExerciseGradingService(websocketService as any, httpService as any);\n\n subscribeSpy = spy(websocketService, 'subscribe');\n unsubscribeSpy = spy(websocketService, 'unsubscribe');\n receiveStub = stub(websocketService, 'receive');\n getStub = stub(httpService, 'get');\n\n exercise1TestCaseSubject = new Subject();\n exercise2TestCaseSubject = new Subject();\n receiveStub.withArgs(exercise1Topic).returns(exercise1TestCaseSubject);\n receiveStub.withArgs(exercise2Topic).returns(exercise2TestCaseSubject);\n getStub.withArgs(`${gradingService.resourceUrl}/${exercise1.id}/test-cases`).returns(of(testCases1));\n getStub.withArgs(`${gradingService.resourceUrl}/${exercise2.id}/test-cases`).returns(of(testCases2));\n }));\n\n afterEach(() => {\n subscribeSpy.restore();\n unsubscribeSpy.restore();\n receiveStub.restore();\n getStub.restore();\n });\n\n it('should fetch the test cases via REST call if there is nothing stored yet for a given exercise', () => {\n let testCasesExercise1;\n let testCasesExercise2;\n\n gradingService\n .subscribeForTestCases(exercise1.id)\n .pipe(tap((newTestCases) => (testCasesExercise1 = newTestCases)))\n .subscribe();\n\n expect(getStub).to.have.been.calledOnce;\n expect(testCasesExercise1).to.deep.equal(testCases1);\n expect(testCasesExercise2).to.be.undefined;\n\n gradingService\n .subscribeForTestCases(exercise2.id)\n .pipe(tap((newTestCases) => (testCasesExercise2 = newTestCases)))\n .subscribe();\n\n expect(getStub).to.have.been.calledTwice;\n expect(testCasesExercise1).to.deep.equal(testCases1);\n expect(testCasesExercise2).to.deep.equal(testCases2);\n });\n\n it('should reuse the same subject when there already is a connection established and not call the REST endpoint', () => {\n let testCasesExercise1;\n // Subscriber 1.\n gradingService\n .subscribeForTestCases(exercise1.id)\n .pipe(tap((newTestCases) => (testCasesExercise1 = newTestCases)))\n .subscribe();\n // Subscriber 2.\n gradingService\n .subscribeForTestCases(exercise1.id)\n .pipe(tap((newTestCases) => (testCasesExercise1 = newTestCases)))\n .subscribe();\n\n expect(getStub).to.have.been.calledOnce;\n expect(testCasesExercise1).to.equal(testCases1);\n });\n\n it('should notify subscribers on new test case value', () => {\n const newTestCasesOracle = testCases1.map((testCase) => ({ ...testCase, weight: 30 }));\n let testCasesExercise1Subscriber1;\n let testCasesExercise1Subscriber2;\n // Subscriber 1.\n gradingService\n .subscribeForTestCases(exercise1.id)\n .pipe(tap((newTestCases) => (testCasesExercise1Subscriber1 = newTestCases)))\n .subscribe();\n // Subscriber 2.\n gradingService\n .subscribeForTestCases(exercise1.id)\n .pipe(tap((newTestCases) => (testCasesExercise1Subscriber2 = newTestCases)))\n .subscribe();\n\n expect(testCasesExercise1Subscriber1).to.equal(testCases1);\n expect(testCasesExercise1Subscriber2).to.equal(testCases1);\n\n gradingService.notifyTestCases(exercise1.id, newTestCasesOracle);\n\n expect(testCasesExercise1Subscriber1).to.equal(newTestCasesOracle);\n expect(testCasesExercise1Subscriber2).to.equal(newTestCasesOracle);\n });\n});\n" }, { "alpha_fraction": 0.6842607259750366, "alphanum_fraction": 0.6874403953552246, "avg_line_length": 40.93333435058594, "blob_id": "b1ecd720858c69e59a6d4bcfc5f6721eb8cede9f", "content_id": "d81b8838cea3dcb532857d289ecc211640faec58", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3145, "license_type": "permissive", "max_line_length": 124, "num_lines": 75, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ExerciseHintRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.ExerciseHint;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data repository for the ExerciseHint entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ExerciseHintRepository extends JpaRepository<ExerciseHint, Long> {\n\n Set<ExerciseHint> findByExerciseId(Long exerciseId);\n\n @NotNull\n default ExerciseHint findByIdElseThrow(long exerciseHintId) throws EntityNotFoundException {\n return findById(exerciseHintId).orElseThrow(() -> new EntityNotFoundException(\"Exercise Hint\", exerciseHintId));\n }\n\n /**\n * Copies the hints of an exercise to a new target exercise by cloning the hint objects and saving them\n * resulting in new IDs for the copied hints. The contents stay the same. On top of that, all hints in the\n * problem statement of the target exercise get replaced by the new IDs.\n *\n * @param template The template exercise containing the hints that should be copied\n * @param target The new target exercise, to which all hints should get copied to.\n */\n default void copyExerciseHints(final Exercise template, final Exercise target) {\n final Map<Long, Long> hintIdMapping = new HashMap<>();\n target.setExerciseHints(template.getExerciseHints().stream().map(hint -> {\n final var copiedHint = new ExerciseHint();\n copiedHint.setExercise(target);\n copiedHint.setContent(hint.getContent());\n copiedHint.setTitle(hint.getTitle());\n save(copiedHint);\n hintIdMapping.put(hint.getId(), copiedHint.getId());\n return copiedHint;\n }).collect(Collectors.toSet()));\n\n String patchedStatement = target.getProblemStatement();\n for (final var idMapping : hintIdMapping.entrySet()) {\n // Replace any old hint ID in the imported statement with the new hint ID\n // $1 --> everything before the old hint ID; $3 --> Everything after the old hint ID --> $1 newHintID $3\n final var replacement = \"$1\" + idMapping.getValue() + \"$3\";\n patchedStatement = patchedStatement.replaceAll(\"(\\\\{[^}]*)(\" + idMapping.getKey() + \")([^}]*\\\\})\", replacement);\n }\n target.setProblemStatement(patchedStatement);\n }\n\n /**\n * Returns the title of the hint with the given id\n *\n * @param hintId the id of the hint\n * @return the name/title of the hint or null if the hint does not exist\n */\n @Query(\"\"\"\n SELECT h.title\n FROM ExerciseHint h\n WHERE h.id = :hintId\n \"\"\")\n String getHintTitle(@Param(\"hintId\") Long hintId);\n}\n" }, { "alpha_fraction": 0.7171514630317688, "alphanum_fraction": 0.7191574573516846, "avg_line_length": 22.738094329833984, "blob_id": "0156b097647e771e0e625b46fa8635439afee1d1", "content_id": "9407c5a23d011e3b055863557a9a98eff82d6998", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 997, "license_type": "permissive", "max_line_length": 70, "num_lines": 42, "path": "/src/main/java/de/tum/in/www1/artemis/service/dto/FeedbackConflictResponseDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.enumeration.FeedbackConflictType;\n\n/**\n * A DTO representing feedback conflicts (e.g. retrieved from Athene)\n */\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class FeedbackConflictResponseDTO {\n\n private long firstFeedbackId;\n\n private long secondFeedbackId;\n\n private FeedbackConflictType type;\n\n public long getFirstFeedbackId() {\n return firstFeedbackId;\n }\n\n public void setFirstFeedbackId(long firstFeedbackId) {\n this.firstFeedbackId = firstFeedbackId;\n }\n\n public long getSecondFeedbackId() {\n return secondFeedbackId;\n }\n\n public void setSecondFeedbackId(long secondFeedbackId) {\n this.secondFeedbackId = secondFeedbackId;\n }\n\n public FeedbackConflictType getType() {\n return type;\n }\n\n public void setType(FeedbackConflictType type) {\n this.type = type;\n }\n}\n" }, { "alpha_fraction": 0.6342869400978088, "alphanum_fraction": 0.6533234715461731, "avg_line_length": 41.6884880065918, "blob_id": "adc38fc8ffa11a4f2c5870f0b88ce924f86e86a1", "content_id": "1766d33939585f9772b97421ffd4bbfa7b5a709c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 18911, "license_type": "permissive", "max_line_length": 137, "num_lines": 443, "path": "/src/test/javascript/spec/component/exam/exam-scores/exam-scores.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { ExamScoreDTO, ExerciseGroup, ExerciseInfo, ExerciseResult, StudentResult } from 'app/exam/exam-scores/exam-score-dtos.model';\nimport { ExamScoresComponent } from 'app/exam/exam-scores/exam-scores.component';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { ParticipantScoresService, ScoresDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { SortService } from 'app/shared/service/sort.service';\nimport * as chai from 'chai';\nimport { cloneDeep } from 'lodash';\nimport { JhiAlertService, JhiSortByDirective, JhiSortDirective, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { ChartsModule } from 'ng2-charts';\nimport { empty, of } from 'rxjs';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ExamScoresComponent', () => {\n let fixture: ComponentFixture<ExamScoresComponent>;\n let comp: ExamScoresComponent;\n let examService: ExamManagementService;\n\n const exInfo1 = {\n exerciseId: 11,\n title: 'ex1_1',\n maxPoints: 100,\n numberOfParticipants: 1,\n } as ExerciseInfo;\n const exInfo2 = {\n exerciseId: 12,\n title: 'ex1_2',\n maxPoints: 100,\n numberOfParticipants: 1,\n } as ExerciseInfo;\n\n const exGroup1Id = 1;\n const exGroup1 = {\n id: exGroup1Id,\n title: 'group',\n maxPoints: 100,\n numberOfParticipants: 2,\n containedExercises: [exInfo1, exInfo2],\n } as ExerciseGroup;\n\n const exResult1ForGroup1 = {\n exerciseId: 11,\n title: 'exResult1_1',\n maxScore: 100,\n achievedScore: 100,\n achievedPoints: 100,\n hasNonEmptySubmission: true,\n } as ExerciseResult;\n\n const exResult2ForGroup1 = {\n exerciseId: 12,\n title: 'exResult1_2',\n maxScore: 100,\n achievedScore: 20,\n achievedPoints: 20,\n hasNonEmptySubmission: true,\n } as ExerciseResult;\n\n const exResult3ForGroup1 = {\n exerciseId: 12,\n title: 'exResult1_2',\n maxScore: 100,\n achievedScore: 50,\n achievedPoints: 50,\n hasNonEmptySubmission: true,\n } as ExerciseResult;\n\n const studentResult1 = {\n userId: 1,\n name: 'user1',\n login: 'user1',\n eMail: '[email protected]',\n registrationNumber: '111',\n overallPointsAchieved: 100,\n overallScoreAchieved: 100,\n submitted: true,\n exerciseGroupIdToExerciseResult: { [exGroup1Id]: exResult1ForGroup1 },\n } as StudentResult;\n\n const studentResult2 = {\n userId: 2,\n name: 'user2',\n login: 'user2',\n eMail: '[email protected]',\n registrationNumber: '222',\n overallPointsAchieved: 20,\n overallScoreAchieved: 20,\n submitted: true,\n exerciseGroupIdToExerciseResult: { [exGroup1Id]: exResult2ForGroup1 },\n } as StudentResult;\n\n const studentResult3 = {\n userId: 3,\n name: 'user3',\n login: 'user3',\n eMail: '[email protected]',\n registrationNumber: '333',\n overallPointsAchieved: 50,\n overallScoreAchieved: 50,\n submitted: false,\n exerciseGroupIdToExerciseResult: { [exGroup1Id]: exResult3ForGroup1 },\n } as StudentResult;\n\n let findExamScoresSpy: sinon.SinonStub;\n\n const examScoreStudent1 = new ScoresDTO();\n examScoreStudent1.studentId = studentResult1.userId;\n examScoreStudent1.pointsAchieved = studentResult1.overallPointsAchieved;\n examScoreStudent1.studentLogin = studentResult1.login;\n examScoreStudent1.scoreAchieved = studentResult1.overallScoreAchieved;\n const examScoreStudent2 = new ScoresDTO();\n examScoreStudent2.studentId = studentResult2.userId;\n examScoreStudent2.pointsAchieved = studentResult2.overallPointsAchieved;\n examScoreStudent2.studentLogin = studentResult2.login;\n examScoreStudent2.scoreAchieved = studentResult2.overallScoreAchieved;\n const examScoreStudent3 = new ScoresDTO();\n examScoreStudent3.studentId = studentResult3.userId;\n examScoreStudent3.pointsAchieved = studentResult3.overallPointsAchieved;\n examScoreStudent3.studentLogin = studentResult3.login;\n examScoreStudent3.scoreAchieved = studentResult3.overallScoreAchieved;\n const examScoreDTO = {\n examId: 1,\n title: 'exam1',\n maxPoints: 100,\n averagePointsAchieved: 60,\n exerciseGroups: [exGroup1],\n studentResults: [studentResult1, studentResult2, studentResult3],\n } as ExamScoreDTO;\n\n global.URL.createObjectURL = jest.fn(() => 'http://some.test.com');\n global.URL.revokeObjectURL = jest.fn(() => '');\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ChartsModule],\n declarations: [\n ExamScoresComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(AlertComponent),\n MockComponent(FaIconComponent),\n MockComponent(HelpIconComponent),\n MockDirective(JhiTranslateDirective),\n MockDirective(JhiSortByDirective),\n MockDirective(JhiSortDirective),\n MockDirective(DeleteButtonDirective),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: { params: of({ courseId: 1, examId: 1 }) } },\n MockProvider(TranslateService),\n MockProvider(ExamManagementService),\n MockProvider(SortService),\n MockProvider(JhiAlertService),\n MockProvider(ParticipantScoresService),\n MockProvider(JhiLanguageHelper, { language: empty() }),\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExamScoresComponent);\n comp = fixture.componentInstance;\n examService = fixture.debugElement.injector.get(ExamManagementService);\n const participationScoreService = fixture.debugElement.injector.get(ParticipantScoresService);\n findExamScoresSpy = sinon\n .stub(participationScoreService, 'findExamScores')\n .returns(of(new HttpResponse({ body: [examScoreStudent1, examScoreStudent2, examScoreStudent3] })));\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(comp).to.be.ok;\n });\n\n it('should not log error on sentry when correct participant score calculation', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n fixture.detectChanges();\n const errorSpy = sinon.spy(comp, 'logErrorOnSentry');\n fixture.detectChanges();\n expect(errorSpy).to.not.have.been.called;\n });\n\n it('should log error on sentry when missing participant score calculation', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n findExamScoresSpy.returns(of(new HttpResponse({ body: [] })));\n const errorSpy = sinon.spy(comp, 'logErrorOnSentry');\n fixture.detectChanges();\n expect(errorSpy).to.have.been.calledThrice;\n });\n it('should log error on sentry when wrong points calculation', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n const cs1 = cloneDeep(examScoreStudent1);\n cs1.pointsAchieved = 99;\n const cs2 = cloneDeep(examScoreStudent2);\n cs2.pointsAchieved = 99;\n const cs3 = cloneDeep(examScoreStudent3);\n cs3.pointsAchieved = 99;\n findExamScoresSpy.returns(of(new HttpResponse({ body: [cs1, cs2, cs3] })));\n const errorSpy = sinon.spy(comp, 'logErrorOnSentry');\n fixture.detectChanges();\n expect(errorSpy).to.have.been.calledThrice;\n });\n\n it('should log error on sentry when wrong score calculation', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n const cs1 = cloneDeep(examScoreStudent1);\n cs1.scoreAchieved = 99;\n const cs2 = cloneDeep(examScoreStudent2);\n cs2.scoreAchieved = 99;\n const cs3 = cloneDeep(examScoreStudent3);\n cs3.scoreAchieved = 99;\n findExamScoresSpy.returns(of(new HttpResponse({ body: [cs1, cs2, cs3] })));\n const errorSpy = sinon.spy(comp, 'logErrorOnSentry');\n fixture.detectChanges();\n expect(errorSpy).to.have.been.calledThrice;\n });\n\n it('should make duplicated titles unique', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n\n const newExerciseGroup = new ExerciseGroup();\n newExerciseGroup.title = 'group';\n newExerciseGroup.id = 2;\n examScoreDTO.exerciseGroups.push(newExerciseGroup);\n fixture.detectChanges();\n\n expect(examScoreDTO.exerciseGroups[0].title).to.equal(`group (id=1)`);\n expect(examScoreDTO.exerciseGroups[1].title).to.equal(`group (id=2)`);\n\n // reset state\n examScoreDTO.exerciseGroups.pop();\n examScoreDTO.exerciseGroups[0].title = 'group';\n });\n\n it('histogram should have correct entries', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n fixture.detectChanges();\n\n expectCorrectExamScoreDto(comp, examScoreDTO);\n\n const noOfSubmittedExercises = examScoreDTO.studentResults.length;\n\n // check histogram\n expectCorrectHistogram(comp, examScoreDTO);\n // expect three distinct scores\n expect(comp.histogramData.filter((hd) => hd === 1).length).to.equal(3);\n expect(comp.noOfExamsFiltered).to.equal(noOfSubmittedExercises);\n\n // expect correct calculated exercise group statistics\n const groupResult1 = comp.aggregatedExerciseGroupResults.find((groupRes) => groupRes.exerciseGroupId === exGroup1.id);\n expect(groupResult1).to.be.not.undefined;\n\n const totalPoints = exResult1ForGroup1.achievedPoints! + exResult2ForGroup1.achievedPoints! + exResult3ForGroup1.achievedPoints!;\n expect(groupResult1!.totalPoints).to.equal(totalPoints);\n const averagePoints = totalPoints / noOfSubmittedExercises;\n expect(groupResult1!.averagePoints).to.equal(averagePoints);\n expect(groupResult1!.averagePercentage).to.equal((averagePoints / groupResult1!.maxPoints) * 100);\n\n // expect correct average points for exercises\n expect(groupResult1!.exerciseResults.length).to.equal(2);\n groupResult1!.exerciseResults.forEach((exResult) => {\n let averageExPoints = 0;\n let exInfo;\n if (exResult.exerciseId === 11) {\n // result for ex 1_1\n averageExPoints = exResult1ForGroup1.achievedPoints!;\n expect(exResult.averagePoints).to.equal(averageExPoints);\n exInfo = exGroup1.containedExercises.find((ex) => ex.exerciseId === 11)!;\n expect(exResult.averagePercentage).to.equal((averageExPoints / exInfo.maxPoints) * 100);\n } else if (exResult.exerciseId === 12) {\n // result for ex 1_2\n averageExPoints = (exResult2ForGroup1.achievedPoints! + exResult3ForGroup1.achievedPoints!) / 2;\n expect(exResult.averagePoints).to.equal(averageExPoints);\n exInfo = exGroup1.containedExercises.find((ex) => ex.exerciseId === 12)!;\n expect(exResult.averagePercentage).to.equal((averageExPoints / exInfo.maxPoints) * 100);\n }\n });\n });\n\n it('histogram should skip not submitted exams', () => {\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n fixture.detectChanges();\n comp.toggleFilterForSubmittedExam();\n\n expectCorrectExamScoreDto(comp, examScoreDTO);\n\n // it should skip the not submitted one\n const noOfSubmittedExercises = examScoreDTO.studentResults.length - 1;\n // check histogram\n expectCorrectHistogram(comp, examScoreDTO);\n // expect two distinct scores\n expect(comp.histogramData.filter((hd) => hd === 1).length).to.equal(noOfSubmittedExercises);\n expect(comp.noOfExamsFiltered).to.equal(noOfSubmittedExercises);\n\n // expect correct calculated exercise group statistics\n const groupResult1 = comp.aggregatedExerciseGroupResults.find((groupRes) => groupRes.exerciseGroupId === exGroup1.id);\n expect(groupResult1).to.be.not.undefined;\n\n const totalPoints = exResult1ForGroup1.achievedPoints! + exResult2ForGroup1.achievedPoints!;\n expect(groupResult1!.totalPoints).to.equal(totalPoints);\n const averagePoints = totalPoints / noOfSubmittedExercises;\n expect(groupResult1!.averagePoints).to.equal(averagePoints);\n expect(groupResult1!.averagePercentage).to.equal((averagePoints / groupResult1!.maxPoints) * 100);\n\n // expect correct average points for exercises\n expect(groupResult1!.exerciseResults.length).to.equal(2);\n groupResult1!.exerciseResults.forEach((exResult) => {\n let averageExPoints = 0;\n let exInfo;\n if (exResult.exerciseId === 11) {\n // result for ex 1_1\n averageExPoints = exResult1ForGroup1.achievedPoints!;\n exInfo = exGroup1.containedExercises.find((ex) => ex.exerciseId === 11)!;\n expect(exResult.averagePoints).to.equal(averageExPoints);\n expect(exResult.averagePercentage).to.equal((averageExPoints / exInfo.maxPoints) * 100);\n } else if (exResult.exerciseId === 12) {\n // result for ex 1_2\n averageExPoints = exResult2ForGroup1.achievedPoints!;\n exInfo = exGroup1.containedExercises.find((ex) => ex.exerciseId === 12)!;\n expect(exResult.averagePoints).to.equal(averageExPoints);\n expect(exResult.averagePercentage).to.equal((averageExPoints / exInfo.maxPoints) * 100);\n }\n });\n });\n\n it('should generate csv correctly', () => {\n const noOfSubmittedExercises = examScoreDTO.studentResults.length;\n spyOn(examService, 'getExamScores').and.returnValue(of(new HttpResponse({ body: examScoreDTO })));\n fixture.detectChanges();\n\n const exportAsCsvStub = sinon.stub(comp, 'exportAsCsv');\n // create csv\n comp.exportToCsv();\n const generatedRows = exportAsCsvStub.getCall(0).args[0];\n expect(generatedRows.length).to.equal(noOfSubmittedExercises);\n const user1Row = generatedRows[0];\n validateUserRow(\n user1Row,\n studentResult1.name,\n studentResult1.login,\n studentResult1.eMail,\n studentResult1.registrationNumber,\n 'exResult1_1',\n '100',\n '100',\n '100',\n '100',\n studentResult1.submitted ? 'yes' : 'no',\n );\n const user2Row = generatedRows[1];\n validateUserRow(\n user2Row,\n studentResult2.name,\n studentResult2.login,\n studentResult2.eMail,\n studentResult2.registrationNumber,\n 'exResult1_2',\n '20',\n '20',\n '20',\n '20',\n studentResult2.submitted ? 'yes' : 'no',\n );\n const user3Row = generatedRows[2];\n validateUserRow(\n user3Row,\n studentResult3.name,\n studentResult3.login,\n studentResult3.eMail,\n studentResult3.registrationNumber,\n 'exResult1_2',\n '50',\n '50',\n '50',\n '50',\n studentResult3.submitted ? 'yes' : 'no',\n );\n });\n});\n\nfunction expectCorrectExamScoreDto(comp: ExamScoresComponent, examScoreDTO: ExamScoreDTO) {\n expect(comp.examScoreDTO).to.equal(examScoreDTO);\n expect(comp.studentResults).to.equal(examScoreDTO.studentResults);\n expect(comp.exerciseGroups).to.equal(examScoreDTO.exerciseGroups);\n}\n\nfunction expectCorrectHistogram(comp: ExamScoresComponent, examScoreDTO: ExamScoreDTO) {\n examScoreDTO.studentResults.forEach((studentResult) => {\n let histogramIndex = Math.floor(studentResult.overallScoreAchieved! / comp.binWidth);\n if (histogramIndex >= comp.histogramData.length) {\n histogramIndex = comp.histogramData.length - 1;\n }\n // expect one exercise with 20% and one with 100%\n if (studentResult.submitted || !comp.filterForSubmittedExams) {\n expect(comp.histogramData[histogramIndex]).to.equal(1);\n } else {\n // the not submitted exercise counts not towards histogram\n expect(comp.histogramData[histogramIndex]).to.equal(0);\n }\n });\n}\n\nfunction validateUserRow(\n userRow: any,\n expectedName: string,\n expectedUsername: string,\n expectedEmail: string,\n expectedRegistrationNumber: string,\n expectedExerciseTitle: string,\n expectedAchievedPoints: string,\n expectedAchievedScore: string,\n expectedOverAllPoints: string,\n expectedOverAllScore: string,\n expectedSubmitted: string,\n) {\n expect(userRow.name).to.equal(expectedName);\n expect(userRow.login).to.equal(expectedUsername);\n expect(userRow.eMail).to.equal(expectedEmail);\n expect(userRow.registrationNumber).to.equal(expectedRegistrationNumber);\n expect(userRow['group Assigned Exercise']).to.equal(expectedExerciseTitle);\n expect(userRow['group Achieved Points']).to.equal(expectedAchievedPoints);\n expect(userRow['group Achieved Score (%)']).to.equal(expectedAchievedScore);\n expect(userRow.overAllPoints).to.equal(expectedOverAllPoints);\n expect(userRow.overAllScore).to.equal(expectedOverAllScore);\n expect(userRow.submitted).to.equal(expectedSubmitted);\n}\n" }, { "alpha_fraction": 0.7269866466522217, "alphanum_fraction": 0.7301337718963623, "avg_line_length": 42.82758712768555, "blob_id": "ab0d33e535786fe5f5b24d15069a8c9ae4b2e9d3", "content_id": "7641ab9101477f1951987b1bc59f36d43d51489f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1271, "license_type": "permissive", "max_line_length": 125, "num_lines": 29, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-exercise-hint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { Observable, of } from 'rxjs';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ExerciseHintResponse, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\n\nexport class MockExerciseHintService implements IExerciseHintService {\n private exerciseHintDummy = { id: 1 } as ExerciseHint;\n private exerciseHintDummy2 = { id: 2 } as ExerciseHint;\n\n create(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse> {\n return of({ body: this.exerciseHintDummy }) as Observable<ExerciseHintResponse>;\n }\n\n delete(id: number): Observable<HttpResponse<any>> {\n return of();\n }\n\n find(id: number): Observable<ExerciseHintResponse> {\n return of({ body: this.exerciseHintDummy }) as Observable<ExerciseHintResponse>;\n }\n\n findByExerciseId(exerciseId: number): Observable<HttpResponse<ExerciseHint[]>> {\n return of({ body: [this.exerciseHintDummy, this.exerciseHintDummy2] }) as Observable<HttpResponse<ExerciseHint[]>>;\n }\n\n update(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse> {\n return of({ body: this.exerciseHintDummy }) as Observable<ExerciseHintResponse>;\n }\n}\n" }, { "alpha_fraction": 0.6563275456428528, "alphanum_fraction": 0.656947910785675, "avg_line_length": 51.565216064453125, "blob_id": "a9652caed11b21cd5a3176edd64095b9627c07f0", "content_id": "67980edfe1b0b76ad8d022e36ea56e8385d9e44f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4836, "license_type": "permissive", "max_line_length": 180, "num_lines": 92, "path": "/src/test/javascript/spec/component/course/course-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { of } from 'rxjs';\nimport { FormControl, FormGroup } from '@angular/forms';\nimport { ArtemisTestModule } from '../../test.module';\nimport { CourseUpdateComponent } from 'app/course/manage/course-update.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Course } from 'app/entities/course.model';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockProvider } from 'ng-mocks';\n\ndescribe('Course Management Update Component', () => {\n let comp: CourseUpdateComponent;\n let fixture: ComponentFixture<CourseUpdateComponent>;\n let service: CourseManagementService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n providers: [{ provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, MockProvider(TranslateService)],\n declarations: [CourseUpdateComponent],\n })\n .overrideTemplate(CourseUpdateComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(CourseUpdateComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(CourseManagementService);\n });\n\n describe('save', () => {\n it('Should call update service on save for existing entity', fakeAsync(() => {\n // GIVEN\n const entity = new Course();\n entity.id = 123;\n spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.course = entity;\n comp.courseForm = new FormGroup({\n id: new FormControl(entity.id),\n onlineCourse: new FormControl(entity.onlineCourse),\n registrationEnabled: new FormControl(entity.registrationEnabled),\n presentationScore: new FormControl(entity.presentationScore),\n maxComplaints: new FormControl(entity.maxComplaints),\n maxTeamComplaints: new FormControl(entity.maxTeamComplaints),\n maxComplaintTimeDays: new FormControl(entity.maxComplaintTimeDays),\n complaintsEnabled: new FormControl(entity.complaintsEnabled),\n studentQuestionsEnabled: new FormControl(entity.studentQuestionsEnabled),\n requestMoreFeedbackEnabled: new FormControl(entity.requestMoreFeedbackEnabled),\n maxRequestMoreFeedbackTimeDays: new FormControl(entity.maxRequestMoreFeedbackTimeDays),\n isAtLeastTutor: new FormControl(entity.isAtLeastTutor),\n isAtLeastInstructor: new FormControl(entity.isAtLeastInstructor),\n });\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.update).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should call create service on save for new entity', fakeAsync(() => {\n // GIVEN\n const entity = new Course();\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.course = entity;\n comp.courseForm = new FormGroup({\n onlineCourse: new FormControl(entity.onlineCourse),\n registrationEnabled: new FormControl(entity.registrationEnabled),\n presentationScore: new FormControl(entity.presentationScore),\n maxComplaints: new FormControl(entity.maxComplaints),\n maxTeamComplaints: new FormControl(entity.maxTeamComplaints),\n maxComplaintTimeDays: new FormControl(entity.maxComplaintTimeDays),\n complaintsEnabled: new FormControl(entity.complaintsEnabled),\n studentQuestionsEnabled: new FormControl(entity.studentQuestionsEnabled),\n requestMoreFeedbackEnabled: new FormControl(entity.requestMoreFeedbackEnabled),\n maxRequestMoreFeedbackTimeDays: new FormControl(entity.maxRequestMoreFeedbackTimeDays),\n isAtLeastTutor: new FormControl(entity.isAtLeastTutor),\n isAtLeastInstructor: new FormControl(entity.isAtLeastInstructor),\n }); // mocking reactive form\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n });\n});\n" }, { "alpha_fraction": 0.7401075959205627, "alphanum_fraction": 0.7525403499603271, "avg_line_length": 55.3299674987793, "blob_id": "379389d2025543ccb6d46415b4b4c01f5baa6535", "content_id": "c1279a942a221139a193c874615e4166ca87fa64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16730, "license_type": "permissive", "max_line_length": 179, "num_lines": 297, "path": "/src/test/java/de/tum/in/www1/artemis/ParticipantScoreIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.lecture.ExerciseUnit;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.ModelFactory;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreAverageDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ScoreDTO;\n\npublic class ParticipantScoreIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n private Long idOfExam;\n\n private Long idOfCourse;\n\n private Long idOfTeam1;\n\n private Long idOfStudent1;\n\n private Long idOfIndividualTextExercise;\n\n private Long getIdOfIndividualTextExerciseOfExam;\n\n private Long idOfTeamTextExercise;\n\n private Long idOfExerciseUnit;\n\n @Autowired\n private ExerciseRepository exerciseRepository;\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private TeamRepository teamRepository;\n\n @Autowired\n private ExamRepository examRepository;\n\n @Autowired\n private LectureRepository lectureRepository;\n\n @Autowired\n private LearningGoalRepository learningGoalRepository;\n\n @Autowired\n private LectureUnitRepository lectureUnitRepository;\n\n @Autowired\n private StudentParticipationRepository studentParticipationRepository;\n\n @AfterEach\n public void resetDatabase() {\n database.resetDatabase();\n }\n\n @BeforeEach\n public void setupTestScenario() {\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n // creating the users student1-student5, tutor1-tutor10 and instructors1-instructor10\n this.database.addUsers(5, 10, 10);\n // creating course\n Course course = this.database.createCourse();\n Lecture lecture = new Lecture();\n lecture.setTitle(\"ExampleLecture\");\n lecture.setCourse(course);\n lecture = lectureRepository.saveAndFlush(lecture);\n idOfCourse = course.getId();\n TextExercise textExercise = database.createIndividualTextExercise(course, pastTimestamp, pastTimestamp, pastTimestamp);\n ExerciseUnit exerciseUnit = database.createExerciseUnit(textExercise);\n database.addLectureUnitsToLecture(lecture, Set.of(exerciseUnit));\n lecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture.getId()).get();\n exerciseUnit = (ExerciseUnit) lecture.getLectureUnits().get(0);\n idOfExerciseUnit = exerciseUnit.getId();\n LearningGoal learningGoal = new LearningGoal();\n learningGoal.setTitle(\"ExampleLearningGoal\");\n learningGoal.setCourse(course);\n learningGoal.addLectureUnit(exerciseUnit);\n learningGoalRepository.saveAndFlush(learningGoal);\n idOfIndividualTextExercise = textExercise.getId();\n Exercise teamExercise = database.createTeamTextExercise(course, pastTimestamp, pastTimestamp, pastTimestamp);\n idOfTeamTextExercise = teamExercise.getId();\n User student1 = userRepository.findOneByLogin(\"student1\").get();\n idOfStudent1 = student1.getId();\n User tutor1 = userRepository.findOneByLogin(\"tutor1\").get();\n idOfTeam1 = database.createTeam(Set.of(student1), tutor1, teamExercise).getId();\n\n // Creating result for student1\n database.createParticipationSubmissionAndResult(idOfIndividualTextExercise, student1, 10.0, 10.0, 50, true);\n // Creating result for team1\n Team team = teamRepository.findById(idOfTeam1).get();\n database.createParticipationSubmissionAndResult(idOfTeamTextExercise, team, 10.0, 10.0, 50, true);\n\n // setting up exam\n Exam exam = ModelFactory.generateExam(course);\n ModelFactory.generateExerciseGroup(true, exam);\n exam.addRegisteredUser(student1);\n exam = examRepository.save(exam);\n idOfExam = exam.getId();\n createIndividualTextExerciseForExam();\n database.createParticipationSubmissionAndResult(getIdOfIndividualTextExerciseOfExam, student1, 10.0, 10.0, 50, true);\n }\n\n private void testAllPreAuthorize() throws Exception {\n request.getList(\"/api/courses/\" + idOfCourse + \"/participant-scores\", HttpStatus.FORBIDDEN, ParticipantScoreDTO.class);\n request.getList(\"/api/courses/\" + idOfCourse + \"/participant-scores/average-participant\", HttpStatus.FORBIDDEN, ParticipantScoreAverageDTO.class);\n request.get(\"/api/courses/\" + idOfCourse + \"/participant-scores/average\", HttpStatus.FORBIDDEN, Long.class);\n request.getList(\"/api/exams/\" + idOfExam + \"/participant-scores\", HttpStatus.FORBIDDEN, ParticipantScoreDTO.class);\n request.getList(\"/api/exams/\" + idOfExam + \"/participant-scores/average-participant\", HttpStatus.FORBIDDEN, ParticipantScoreAverageDTO.class);\n request.get(\"/api/exams/\" + idOfExam + \"/participant-scores/\", HttpStatus.FORBIDDEN, Long.class);\n request.getList(\"/api/courses/\" + idOfCourse + \"/course-scores\", HttpStatus.FORBIDDEN, ScoreDTO.class);\n request.getList(\"/api/exams/\" + idOfExam + \"/exam-scores\", HttpStatus.FORBIDDEN, ScoreDTO.class);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testAll_asTutor() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testAll_asStudent() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteParticipation_asInstructorOfCourse_shouldDeleteParticipation() throws Exception {\n List<StudentParticipation> participations = studentParticipationRepository.findByExerciseIdAndStudentId(idOfIndividualTextExercise, idOfStudent1);\n assertThat(participations).isNotEmpty();\n for (StudentParticipation studentParticipation : participations) {\n database.createSubmissionAndResult(studentParticipation, 30, false);\n }\n participations = studentParticipationRepository.findByExerciseIdAndStudentId(idOfIndividualTextExercise, idOfStudent1);\n assertThat(participations).isNotEmpty();\n for (StudentParticipation studentParticipation : participations) {\n request.delete(\"/api/participations/\" + studentParticipation.getId(), HttpStatus.OK);\n }\n participations = studentParticipationRepository.findByExerciseIdAndStudentId(idOfIndividualTextExercise, idOfStudent1);\n assertThat(participations).isEmpty();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteExercise_asInstructorOfCourse_shouldDeleteExercise() throws Exception {\n request.delete(\"/api/text-exercises/\" + idOfIndividualTextExercise, HttpStatus.OK);\n assertThat(exerciseRepository.existsById(idOfIndividualTextExercise)).isFalse();\n assertThat(lectureUnitRepository.existsById(idOfExerciseUnit)).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void deleteCourse_asInstructorOfCourse_shouldDeleteExercise() throws Exception {\n request.delete(\"/api/courses/\" + idOfCourse, HttpStatus.OK);\n assertThat(courseRepository.existsById(idOfCourse)).isFalse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getCourseScores_asInstructorOfCourse_shouldReturnCourseScores() throws Exception {\n List<ScoreDTO> courseScores = request.getList(\"/api/courses/\" + idOfCourse + \"/course-scores\", HttpStatus.OK, ScoreDTO.class);\n assertThat(courseScores.size()).isEqualTo(25);\n ScoreDTO scoreOfStudent1 = courseScores.stream().filter(scoreDTO -> scoreDTO.studentId.equals(idOfStudent1)).findFirst().get();\n assertThat(scoreOfStudent1.studentLogin).isEqualTo(\"student1\");\n assertThat(scoreOfStudent1.pointsAchieved).isEqualTo(10.0);\n assertThat(scoreOfStudent1.scoreAchieved).isEqualTo(50.0);\n assertThat(scoreOfStudent1.regularPointsAchievable).isEqualTo(20.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getExamScores_asInstructorOfCourse_shouldReturnExamScores() throws Exception {\n List<ScoreDTO> courseScores = request.getList(\"/api/exams/\" + idOfExam + \"/exam-scores\", HttpStatus.OK, ScoreDTO.class);\n assertThat(courseScores.size()).isEqualTo(1);\n ScoreDTO scoreOfStudent1 = courseScores.stream().filter(scoreDTO -> scoreDTO.studentId.equals(idOfStudent1)).findFirst().get();\n assertThat(scoreOfStudent1.studentLogin).isEqualTo(\"student1\");\n assertThat(scoreOfStudent1.pointsAchieved).isEqualTo(5.0);\n assertThat(scoreOfStudent1.scoreAchieved).isEqualTo(5.6);\n assertThat(scoreOfStudent1.regularPointsAchievable).isEqualTo(90.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getParticipantScoresOfCourse_asInstructorOfCourse_shouldReturnParticipantScores() throws Exception {\n List<ParticipantScoreDTO> participantScoresOfCourse = request.getList(\"/api/courses/\" + idOfCourse + \"/participant-scores\", HttpStatus.OK, ParticipantScoreDTO.class);\n assertThat(participantScoresOfCourse.size()).isEqualTo(2);\n ParticipantScoreDTO student1Result = participantScoresOfCourse.stream().filter(participantScoreDTO -> participantScoreDTO.userId != null).findFirst().get();\n ParticipantScoreDTO team1Result = participantScoresOfCourse.stream().filter(participantScoreDTO -> participantScoreDTO.teamId != null).findFirst().get();\n assertParticipantScoreDTOStructure(student1Result, idOfStudent1, null, idOfIndividualTextExercise, 50D, 50D, 5.0, 5.0);\n assertParticipantScoreDTOStructure(team1Result, null, idOfTeam1, idOfTeamTextExercise, 50D, 50D, 5.0, 5.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAverageScoreOfParticipantInCourse_asInstructorOfCourse_shouldReturnAverageParticipantScores() throws Exception {\n List<ParticipantScoreAverageDTO> participantScoreAverageDTOS = request.getList(\"/api/courses/\" + idOfCourse + \"/participant-scores/average-participant\", HttpStatus.OK,\n ParticipantScoreAverageDTO.class);\n assertThat(participantScoreAverageDTOS.size()).isEqualTo(2);\n ParticipantScoreAverageDTO student1Result = participantScoreAverageDTOS.stream().filter(participantScoreAverageDTO -> participantScoreAverageDTO.userName != null)\n .findFirst().get();\n ParticipantScoreAverageDTO team1Result = participantScoreAverageDTOS.stream().filter(participantScoreAverageDTO -> participantScoreAverageDTO.teamName != null).findFirst()\n .get();\n assertAverageParticipantScoreDTOStructure(student1Result, \"student1\", null, 50.0, 50.0, 5.0, 5.0);\n assertAverageParticipantScoreDTOStructure(team1Result, null, \"team1\", 50.0, 50.0, 5.0, 5.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAverageScoreOfCourses_asInstructorOfCourse_shouldReturnAverageScore() throws Exception {\n Double averageRated = request.get(\"/api/courses/\" + idOfCourse + \"/participant-scores/average?onlyConsiderRatedScores=true\", HttpStatus.OK, Double.class);\n assertThat(averageRated).isEqualTo(50D);\n Double average = request.get(\"/api/courses/\" + idOfCourse + \"/participant-scores/average?onlyConsiderRatedScores=false\", HttpStatus.OK, Double.class);\n assertThat(average).isEqualTo(50D);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getParticipantScoresOfExam_asInstructorOfCourse_shouldReturnParticipantScores() throws Exception {\n List<ParticipantScoreDTO> participantScoresOfExam = request.getList(\"/api/exams/\" + idOfExam + \"/participant-scores\", HttpStatus.OK, ParticipantScoreDTO.class);\n assertThat(participantScoresOfExam.size()).isEqualTo(1);\n ParticipantScoreDTO student1Result = participantScoresOfExam.stream().filter(participantScoreDTO -> participantScoreDTO.userId != null).findFirst().get();\n assertParticipantScoreDTOStructure(student1Result, idOfStudent1, null, getIdOfIndividualTextExerciseOfExam, 50D, 50D, 5.0, 5.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAverageScoreOfParticipantInExam_asInstructorOfCourse_shouldReturnAverageParticipantScores() throws Exception {\n List<ParticipantScoreAverageDTO> participantScoreAverageDTOS = request.getList(\"/api/exams/\" + idOfExam + \"/participant-scores/average-participant\", HttpStatus.OK,\n ParticipantScoreAverageDTO.class);\n assertThat(participantScoreAverageDTOS.size()).isEqualTo(1);\n ParticipantScoreAverageDTO student1Result = participantScoreAverageDTOS.stream().filter(participantScoreAverageDTO -> participantScoreAverageDTO.userName != null)\n .findFirst().get();\n assertAverageParticipantScoreDTOStructure(student1Result, \"student1\", null, 50.0, 50.0, 5.0, 5.0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getAverageScoreOfExam_asInstructorOfCourse_shouldReturnAverageScore() throws Exception {\n Double averageRated = request.get(\"/api/exams/\" + idOfExam + \"/participant-scores/average?onlyConsiderRatedScores=true\", HttpStatus.OK, Double.class);\n assertThat(averageRated).isEqualTo(50D);\n Double average = request.get(\"/api/exams/\" + idOfExam + \"/participant-scores/average?onlyConsiderRatedScores=false\", HttpStatus.OK, Double.class);\n assertThat(average).isEqualTo(50D);\n }\n\n private void createIndividualTextExerciseForExam() {\n Exam exam;\n exam = examRepository.findWithExerciseGroupsAndExercisesById(idOfExam).get();\n var exerciseGroup0 = exam.getExerciseGroups().get(0);\n TextExercise textExercise = ModelFactory.generateTextExerciseForExam(exerciseGroup0);\n textExercise.setMaxPoints(10.0);\n textExercise.setBonusPoints(0.0);\n textExercise = exerciseRepository.save(textExercise);\n getIdOfIndividualTextExerciseOfExam = textExercise.getId();\n }\n\n private void assertParticipantScoreDTOStructure(ParticipantScoreDTO participantScoreDTO, Long expectedUserId, Long expectedTeamId, Long expectedExerciseId,\n Double expectedLastResultScore, Double expectedLastRatedResultScore, Double expectedLastPoints, Double exptectedLastRatedPoints) {\n assertThat(participantScoreDTO.userId).isEqualTo(expectedUserId);\n assertThat(participantScoreDTO.teamId).isEqualTo(expectedTeamId);\n assertThat(participantScoreDTO.exerciseId).isEqualTo(expectedExerciseId);\n assertThat(participantScoreDTO.lastResultScore).isEqualTo(expectedLastResultScore);\n assertThat(participantScoreDTO.lastRatedResultScore).isEqualTo(expectedLastRatedResultScore);\n assertThat(participantScoreDTO.lastPoints).isEqualTo(expectedLastPoints);\n assertThat(participantScoreDTO.lastRatedPoints).isEqualTo(exptectedLastRatedPoints);\n }\n\n private void assertAverageParticipantScoreDTOStructure(ParticipantScoreAverageDTO participantScoreAverageDTO, String expectedUserName, String expectedTeamName,\n Double expectedAverageScore, Double expectedAverageRatedScore, Double expectedAveragePoints, Double expectedAverageRatedPoints) {\n assertThat(participantScoreAverageDTO.userName).isEqualTo(expectedUserName);\n assertThat(participantScoreAverageDTO.teamName).isEqualTo(expectedTeamName);\n assertThat(participantScoreAverageDTO.averageScore).isEqualTo(expectedAverageScore);\n assertThat(participantScoreAverageDTO.averageRatedScore).isEqualTo(expectedAverageRatedScore);\n assertThat(participantScoreAverageDTO.averagePoints).isEqualTo(expectedAveragePoints);\n assertThat(participantScoreAverageDTO.averageRatedPoints).isEqualTo(expectedAverageRatedPoints);\n\n }\n}\n" }, { "alpha_fraction": 0.8063725233078003, "alphanum_fraction": 0.811274528503418, "avg_line_length": 26.200000762939453, "blob_id": "3c13b19184153de05198cabbf53a4161d1742d53", "content_id": "441a8a45c7ed57b27e841cd9be65525bac849531", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 408, "license_type": "permissive", "max_line_length": 83, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/DropLocationRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.DropLocation;\n\n/**\n * Spring Data JPA repository for the DropLocation entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface DropLocationRepository extends JpaRepository<DropLocation, Long> {\n\n}\n" }, { "alpha_fraction": 0.6397557854652405, "alphanum_fraction": 0.6411126255989075, "avg_line_length": 38.83783721923828, "blob_id": "588d7596932fdf169e48eccfeea2a3fe985e382c", "content_id": "296394672ba0335217c279d83f56a5ebf46978bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4422, "license_type": "permissive", "max_line_length": 154, "num_lines": 111, "path": "/src/main/webapp/app/exam/manage/exams/exam-checklist-component/exam-checklist.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { Exam } from 'app/entities/exam.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { ExamChecklist } from 'app/entities/exam-checklist.model';\nimport { filter, map } from 'rxjs/operators';\n\n@Component({\n selector: 'jhi-exam-checklist',\n templateUrl: './exam-checklist.component.html',\n})\nexport class ExamChecklistComponent implements OnInit {\n @Input() exam: Exam;\n @Input() getExamRoutesByIdentifier: any;\n @Input() isAtLeastInstructor = false;\n\n examChecklist: ExamChecklist;\n isLoading = false;\n pointsExercisesEqual = false;\n allExamsGenerated = false;\n allGroupsContainExercise = false;\n totalPointsMandatory = false;\n totalPointsMandatoryOptional = false;\n\n constructor(private accountService: AccountService, private examService: ExamManagementService, private exerciseGroupService: ExerciseGroupService) {}\n\n ngOnInit() {\n this.checkPointsExercisesEqual();\n this.checkTotalPointsMandatory();\n this.checkAllGroupContainsExercise();\n this.examService\n .getExamStatistics(this.exam.course!.id!, this.exam.id!)\n .pipe(\n filter((res) => !!res.body),\n map((examStatistics: HttpResponse<ExamChecklist>) => examStatistics.body!),\n )\n .subscribe((examStats) => {\n this.examChecklist = examStats;\n this.checkAllExamsGenerated();\n });\n }\n\n /**\n * Set allExamsGenerated to true if all registered students have a student exam\n */\n checkAllExamsGenerated() {\n this.allExamsGenerated = this.examChecklist.numberOfGeneratedStudentExams === this.exam.numberOfRegisteredUsers;\n }\n\n /**\n * Set totalPointsMandatory to true if total points of exam is smaller or equal to all mandatory points\n * Set checkTotalPointsMandatoryOptional to true if total points of exam is bigger or equal to all mandatory points\n */\n checkTotalPointsMandatory() {\n this.totalPointsMandatory = false;\n this.totalPointsMandatoryOptional = false;\n let sumPointsExerciseGroupsMandatory = 0;\n let sumPointsExerciseGroupsOptional = 0;\n\n // calculate mandatory points and optional points\n if (this.pointsExercisesEqual) {\n this.exam.exerciseGroups!.forEach((exerciseGroup) => {\n if (exerciseGroup.isMandatory) {\n sumPointsExerciseGroupsMandatory += exerciseGroup!.exercises![0]!.maxPoints!;\n } else {\n sumPointsExerciseGroupsOptional += exerciseGroup!.exercises![0]!.maxPoints!;\n }\n });\n\n if (sumPointsExerciseGroupsMandatory <= this.exam.maxPoints!) {\n this.totalPointsMandatory = true;\n }\n if (sumPointsExerciseGroupsMandatory + sumPointsExerciseGroupsOptional >= this.exam.maxPoints!) {\n this.totalPointsMandatoryOptional = true;\n }\n }\n }\n\n /**\n * Set pointsExercisesEqual to true if exercises have the same number of maxPoints within each exercise group\n */\n checkPointsExercisesEqual() {\n this.pointsExercisesEqual = true;\n this.exam.exerciseGroups!.forEach((exerciseGroup) => {\n const maxPoints = exerciseGroup.exercises?.[0].maxPoints;\n return exerciseGroup.exercises?.some((exercise) => {\n if (exercise.maxPoints !== maxPoints) {\n this.pointsExercisesEqual = false;\n return true;\n }\n return false;\n });\n });\n }\n\n /**\n * Set pointsExercisesEqual to true if exercises have the same number of maxPoints within each exercise groups\n */\n checkAllGroupContainsExercise() {\n this.allGroupsContainExercise = true;\n this.exam.exerciseGroups!.some((exerciseGroup) => {\n if (!exerciseGroup.exercises || exerciseGroup.exercises.length === 0) {\n this.allGroupsContainExercise = false;\n return true;\n }\n return false;\n });\n }\n}\n" }, { "alpha_fraction": 0.798561155796051, "alphanum_fraction": 0.798561155796051, "avg_line_length": 57.80769348144531, "blob_id": "d33ff8bdc379c7a7347def9e5c0a4d76dbff3052", "content_id": "e2c98cac86bda60107951738b8eba913d9ef4175", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1529, "license_type": "permissive", "max_line_length": 174, "num_lines": 26, "path": "/src/main/webapp/app/shared/components/shared-component.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { ConfirmAutofocusButtonComponent, ConfirmAutofocusModalComponent } from 'app/shared/components/confirm-autofocus-button.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component';\nimport { ButtonComponent } from 'app/shared/components/button.component';\nimport { CloneRepoButtonComponent } from 'app/shared/components/clone-repo-button/clone-repo-button.component';\nimport { ExerciseActionButtonComponent } from 'app/shared/components/exercise-action-button.component';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { CourseExamArchiveButtonComponent } from 'app/shared/components/course-exam-archive-button/course-exam-archive-button.component';\n\n@NgModule({\n imports: [ArtemisSharedModule, FeatureToggleModule, ClipboardModule],\n entryComponents: [ConfirmAutofocusModalComponent],\n declarations: [\n ButtonComponent,\n HelpIconComponent,\n ConfirmAutofocusButtonComponent,\n ConfirmAutofocusModalComponent,\n CloneRepoButtonComponent,\n ExerciseActionButtonComponent,\n CourseExamArchiveButtonComponent,\n ],\n exports: [ButtonComponent, HelpIconComponent, ConfirmAutofocusButtonComponent, CloneRepoButtonComponent, ExerciseActionButtonComponent, CourseExamArchiveButtonComponent],\n})\nexport class ArtemisSharedComponentModule {}\n" }, { "alpha_fraction": 0.6439117193222046, "alphanum_fraction": 0.6443880200386047, "avg_line_length": 40.1699333190918, "blob_id": "9d8ed2cc09657ebaa8712c7afdcd72e2734fc809", "content_id": "ffc2e469b9de0bb50c0f96acba5bc42199b58f16", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6299, "license_type": "permissive", "max_line_length": 170, "num_lines": 153, "path": "/src/main/webapp/app/overview/exercise-details/exercise-details-student-actions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, HostBinding, Input } from '@angular/core';\nimport * as moment from 'moment';\nimport { CourseExerciseService } from 'app/course/manage/course-management.service';\nimport { Router } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { HttpClient } from '@angular/common/http';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { Exercise, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport { isStartExerciseAvailable, participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\n\n@Component({\n selector: 'jhi-exercise-details-student-actions',\n templateUrl: './exercise-details-student-actions.component.html',\n styleUrls: ['../course-overview.scss'],\n providers: [SourceTreeService],\n})\nexport class ExerciseDetailsStudentActionsComponent {\n FeatureToggle = FeatureToggle;\n readonly ExerciseType = ExerciseType;\n readonly ParticipationStatus = ParticipationStatus;\n\n @Input() @HostBinding('class.col') equalColumns = true;\n @Input() @HostBinding('class.col-auto') smallColumns = false;\n\n @Input() exercise: Exercise;\n @Input() courseId: number;\n\n @Input() actionsOnly: boolean;\n @Input() smallButtons: boolean;\n @Input() showResult: boolean;\n\n @Input() examMode: boolean;\n\n constructor(private jhiAlertService: JhiAlertService, private courseExerciseService: CourseExerciseService, private httpClient: HttpClient, private router: Router) {}\n\n /**\n * check if practiceMode is available\n * @return {boolean}\n */\n isPracticeModeAvailable(): boolean {\n const quizExercise = this.exercise as QuizExercise;\n return quizExercise.isPlannedToStart! && quizExercise.isOpenForPractice! && moment(quizExercise.dueDate!).isBefore(moment());\n }\n\n /**\n * see exercise-utils -> isStartExerciseAvailable\n */\n isStartExerciseAvailable(): boolean {\n return isStartExerciseAvailable(this.exercise as ProgrammingExercise);\n }\n\n /**\n * check if onlineEditor is allowed\n * @return {boolean}\n */\n isOnlineEditorAllowed() {\n return (this.exercise as ProgrammingExercise).allowOnlineEditor;\n }\n\n /**\n * check if offline IDE is allowed\n * @return {boolean}\n */\n isOfflineIdeAllowed() {\n return (this.exercise as ProgrammingExercise).allowOfflineIde;\n }\n\n /**\n * start the exercise\n */\n startExercise() {\n if (this.exercise.type === ExerciseType.QUIZ) {\n // Start the quiz\n return this.router.navigate(['/courses', this.courseId, 'quiz-exercises', this.exercise.id, 'live']);\n }\n\n this.exercise.loading = true;\n this.courseExerciseService\n .startExercise(this.courseId, this.exercise.id!)\n .finally(() => (this.exercise.loading = false))\n .subscribe(\n (participation) => {\n if (participation) {\n this.exercise.studentParticipations = [participation];\n this.exercise.participationStatus = participationStatus(this.exercise);\n }\n if (this.exercise.type === ExerciseType.PROGRAMMING) {\n if ((this.exercise as ProgrammingExercise).allowOfflineIde) {\n this.jhiAlertService.success('artemisApp.exercise.personalRepositoryClone');\n } else {\n this.jhiAlertService.success('artemisApp.exercise.personalRepositoryOnline');\n }\n }\n },\n () => {\n this.jhiAlertService.warning('artemisApp.exercise.startError');\n },\n );\n }\n\n /**\n * resume the programming exercise\n */\n resumeProgrammingExercise() {\n this.exercise.loading = true;\n this.courseExerciseService\n .resumeProgrammingExercise(this.courseId, this.exercise.id!)\n .finally(() => (this.exercise.loading = false))\n .subscribe(\n (participation: StudentParticipation) => {\n if (participation) {\n // Otherwise the client would think that all results are loaded, but there would not be any (=> no graded result).\n participation.results = this.exercise.studentParticipations![0] ? this.exercise.studentParticipations![0].results : [];\n this.exercise.studentParticipations = [participation];\n this.exercise.participationStatus = participationStatus(this.exercise);\n }\n },\n (error) => {\n this.jhiAlertService.error(`artemisApp.${error.error.entityName}.errors.${error.error.errorKey}`);\n },\n );\n }\n\n /**\n * Wrapper for using participationStatus() in the template\n *\n * @return {ParticipationStatus}\n */\n participationStatusWrapper(): ParticipationStatus {\n return participationStatus(this.exercise);\n }\n\n /**\n * Returns the id of the team that the student is assigned to (only applicable to team-based exercises)\n *\n * @return {assignedTeamId}\n */\n get assignedTeamId(): number | undefined {\n const participation = this.exercise.studentParticipations![0];\n return participation ? participation.team?.id : this.exercise.studentAssignedTeamId;\n }\n\n repositoryUrl(participation: Participation) {\n const programmingParticipation = participation as ProgrammingExerciseStudentParticipation;\n return programmingParticipation.repositoryUrl;\n }\n}\n" }, { "alpha_fraction": 0.6778334379196167, "alphanum_fraction": 0.6784595847129822, "avg_line_length": 46.6716423034668, "blob_id": "3ad037336f82c3115a2478dd71c4029ce8f6c792", "content_id": "f10978363cf655092037405c76b6db7f28980a40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3194, "license_type": "permissive", "max_line_length": 138, "num_lines": 67, "path": "/src/test/javascript/spec/component/code-editor/code-editor-status.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { DebugElement } from '@angular/core/';\nimport { async, ComponentFixture, TestBed } from '@angular/core/testing';\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport * as chai from 'chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { By } from '@angular/platform-browser';\nimport { CodeEditorStatusComponent } from 'app/exercises/programming/shared/code-editor/status/code-editor-status.component';\nimport { CommitState, EditorState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { TranslatePipeMock } from '../../helpers/mocks/service/mock-translate.service';\n\nconst expect = chai.expect;\n\ndescribe('CodeEditorStatusComponent', () => {\n let comp: CodeEditorStatusComponent;\n let fixture: ComponentFixture<CodeEditorStatusComponent>;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, AceEditorModule, NgbModule],\n declarations: [CodeEditorStatusComponent, TranslatePipeMock],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CodeEditorStatusComponent);\n comp = fixture.componentInstance;\n });\n }));\n\n it('should show an empty status segment for EditorState if no EditorState is given', () => {\n const editorStateSegment = fixture.debugElement.query(By.css('#editor_state'));\n expect(editorStateSegment.children).to.be.empty;\n });\n\n it('should show an empty status segment for EditorState if no EditorState is given', () => {\n const commitStateSegment = fixture.debugElement.query(By.css('#commit_state'));\n expect(commitStateSegment.children).to.be.empty;\n });\n\n Object.keys(EditorState).map((editorState) =>\n it(`should show exactly one status segment for EditorState ${editorState} with an icon and a non empty description`, function () {\n comp.editorState = editorState as EditorState;\n fixture.detectChanges();\n const editorStateSegment = fixture.debugElement.query(By.css('#editor_state'));\n showsExactlyOneStatusSegment(editorStateSegment);\n }),\n );\n\n Object.keys(CommitState).map((commitState) =>\n it(`should show exactly one status segment for CommitState ${commitState} with an icon and a non empty description`, function () {\n comp.commitState = commitState as CommitState;\n fixture.detectChanges();\n const commitStateSegment = fixture.debugElement.query(By.css('#commit_state'));\n showsExactlyOneStatusSegment(commitStateSegment);\n }),\n );\n\n const showsExactlyOneStatusSegment = (stateSegment: DebugElement) => {\n expect(stateSegment.children).to.have.length(1);\n const icon = stateSegment.query(By.css('fa-icon'));\n expect(icon).to.exist;\n const text = stateSegment.query(By.css('span'));\n expect(text).to.exist;\n expect(text.nativeElement.textContent).not.to.equal('');\n };\n});\n" }, { "alpha_fraction": 0.6278189420700073, "alphanum_fraction": 0.6281343698501587, "avg_line_length": 41.55704879760742, "blob_id": "1940b1d696ab256bd6c29fd7b969a4f5cdf05b85", "content_id": "0f6f2b10ac5b19d12db9b6c8c5857801d9bb29db", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6341, "license_type": "permissive", "max_line_length": 160, "num_lines": 149, "path": "/src/main/webapp/app/lecture/lecture.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpParams, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport * as moment from 'moment';\nimport { map } from 'rxjs/operators';\n\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\n\ntype EntityResponseType = HttpResponse<Lecture>;\ntype EntityArrayResponseType = HttpResponse<Lecture[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class LectureService {\n public resourceUrl = SERVER_API_URL + 'api/lectures';\n\n constructor(protected http: HttpClient, private accountService: AccountService, private lectureUnitService: LectureUnitService) {}\n\n create(lecture: Lecture): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(lecture);\n return this.http\n .post<Lecture>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n update(lecture: Lecture): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(lecture);\n return this.http\n .put<Lecture>(this.resourceUrl, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n find(lectureId: number): Observable<EntityResponseType> {\n return this.http\n .get<Lecture>(`${this.resourceUrl}/${lectureId}`, { observe: 'response' })\n .map((res: EntityResponseType) => {\n if (res.body) {\n // insert an empty list to avoid additional calls in case the list is empty on the server (because then it would be undefined in the client)\n if (res.body.studentQuestions === undefined) {\n res.body.studentQuestions = [];\n }\n }\n return res;\n })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * Fetches the title of the lecture with the given id\n *\n * @param lectureId the id of the lecture\n * @return the title of the lecture in an HttpResponse, or an HttpErrorResponse on error\n */\n getTitle(lectureId: number): Observable<HttpResponse<string>> {\n return this.http.get(`${this.resourceUrl}/${lectureId}/title`, { observe: 'response', responseType: 'text' });\n }\n\n query(req?: any): Observable<EntityArrayResponseType> {\n const options = createRequestOption(req);\n return this.http\n .get<Lecture[]>(this.resourceUrl, { params: options, observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));\n }\n\n findAllByCourseId(courseId: number, withLectureUnits = false): Observable<EntityArrayResponseType> {\n const params = new HttpParams().set('withLectureUnits', withLectureUnits ? '1' : '0');\n return this.http\n .get<Lecture[]>(`api/courses/${courseId}/lectures`, {\n params,\n observe: 'response',\n })\n .pipe(\n map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)),\n map((res: EntityArrayResponseType) => this.checkPermission(res)),\n );\n }\n\n delete(lectureId: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}/${lectureId}`, { observe: 'response' });\n }\n\n protected convertDateFromClient(lecture: Lecture): Lecture {\n const copy: Lecture = Object.assign({}, lecture, {\n startDate: lecture.startDate && lecture.startDate.isValid() ? lecture.startDate.toJSON() : undefined,\n endDate: lecture.endDate && lecture.endDate.isValid() ? lecture.endDate.toJSON() : undefined,\n });\n if (copy.lectureUnits) {\n copy.lectureUnits = this.lectureUnitService.convertDateArrayFromClient(copy.lectureUnits);\n }\n if (copy.course) {\n copy.course.exercises = undefined;\n copy.course.lectures = undefined;\n }\n return copy;\n }\n\n protected convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.startDate = res.body.startDate ? moment(res.body.startDate) : undefined;\n res.body.endDate = res.body.endDate ? moment(res.body.endDate) : undefined;\n if (res.body.lectureUnits) {\n res.body.lectureUnits = this.lectureUnitService.convertDateArrayFromServerEntity(res.body.lectureUnits);\n }\n }\n return res;\n }\n\n protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.map((lecture: Lecture) => {\n return this.convertDatesForLectureFromServer(lecture);\n });\n }\n return res;\n }\n\n private checkPermission<ERT extends EntityArrayResponseType>(res: ERT): ERT {\n if (res.body) {\n res.body.forEach((lecture: Lecture) => {\n if (lecture.course) {\n lecture.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(lecture.course);\n }\n });\n }\n return res;\n }\n\n public convertDatesForLectureFromServer(lecture?: Lecture) {\n if (lecture) {\n lecture.startDate = lecture.startDate ? moment(lecture.startDate) : undefined;\n lecture.endDate = lecture.endDate ? moment(lecture.endDate) : undefined;\n if (lecture.lectureUnits) {\n lecture.lectureUnits = this.lectureUnitService.convertDateArrayFromServerEntity(lecture.lectureUnits);\n }\n }\n return lecture;\n }\n\n public convertDatesForLecturesFromServer(lectures?: Lecture[]) {\n if (lectures) {\n return lectures.map((lecture) => {\n return this.convertDatesForLectureFromServer(lecture)!;\n });\n }\n }\n}\n" }, { "alpha_fraction": 0.7111980319023132, "alphanum_fraction": 0.7126650214195251, "avg_line_length": 52.25520706176758, "blob_id": "b889c27986ba7f612a5caec95a451ea677705c01", "content_id": "8c75467c1de73e7bdbe81279142ee3c5bae35629", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10225, "license_type": "permissive", "max_line_length": 177, "num_lines": 192, "path": "/src/main/java/de/tum/in/www1/artemis/service/AutomaticTextAssessmentConflictService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static java.util.stream.Collectors.*;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Stream;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.scheduling.annotation.Async;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.exception.NetworkingError;\nimport de.tum.in.www1.artemis.repository.FeedbackConflictRepository;\nimport de.tum.in.www1.artemis.repository.FeedbackRepository;\nimport de.tum.in.www1.artemis.repository.TextBlockRepository;\nimport de.tum.in.www1.artemis.service.connectors.athene.TextAssessmentConflictService;\nimport de.tum.in.www1.artemis.service.dto.FeedbackConflictResponseDTO;\nimport de.tum.in.www1.artemis.service.dto.TextFeedbackConflictRequestDTO;\n\n@Service\n@Profile(\"athene\")\npublic class AutomaticTextAssessmentConflictService {\n\n private final Logger log = LoggerFactory.getLogger(AutomaticTextAssessmentConflictService.class);\n\n private final FeedbackConflictRepository feedbackConflictRepository;\n\n private final FeedbackRepository feedbackRepository;\n\n private final TextBlockRepository textBlockRepository;\n\n private final TextAssessmentConflictService textAssessmentConflictService;\n\n public AutomaticTextAssessmentConflictService(FeedbackConflictRepository feedbackConflictRepository, FeedbackRepository feedbackRepository,\n TextBlockRepository textBlockRepository, TextAssessmentConflictService textAssessmentConflictService) {\n this.feedbackConflictRepository = feedbackConflictRepository;\n this.feedbackRepository = feedbackRepository;\n this.textBlockRepository = textBlockRepository;\n this.textAssessmentConflictService = textAssessmentConflictService;\n }\n\n /**\n * This function asynchronously calls remote Athene service to check feedback consistency for the assessed submission.\n * The call is made if the automatic assessments are enabled and the passed text blocks belong to any cluster.\n *\n * @param textBlocks - all text blocks in the text assessment\n * @param feedbackList - all feedback in the text assessment\n * @param exerciseId - exercise id of the assessed text exercise\n */\n @Async\n public void asyncCheckFeedbackConsistency(Set<TextBlock> textBlocks, List<Feedback> feedbackList, long exerciseId) {\n // Null blocks are passed in some test cases\n if (textBlocks == null || feedbackList == null || textBlocks.isEmpty()) {\n return;\n }\n\n // remove the feedback that does not belong to any text block\n feedbackList.removeIf(f -> !f.hasReference());\n\n // If text block doesn't have a cluster id don't create an object\n List<TextFeedbackConflictRequestDTO> textFeedbackConflictRequestDTOS = feedbackList.stream().flatMap(feedback -> {\n Optional<TextBlock> textBlock = textBlockRepository\n .findById(textBlocks.stream().filter(block -> block.getId().equals(feedback.getReference())).findFirst().get().getId());\n if (textBlock.isPresent() && textBlock.get().getCluster() != null && feedback.getDetailText() != null) {\n return Stream.of(new TextFeedbackConflictRequestDTO(textBlock.get().getId(), textBlock.get().getText(), textBlock.get().getCluster().getId(), feedback.getId(),\n feedback.getDetailText(), feedback.getCredits()));\n }\n else {\n return Stream.empty();\n }\n }).collect(toList());\n\n if (textFeedbackConflictRequestDTOS.isEmpty()) {\n return;\n }\n\n // remote service call to athene\n final List<FeedbackConflictResponseDTO> feedbackConflictResponseDTOS;\n try {\n feedbackConflictResponseDTOS = textAssessmentConflictService.checkFeedbackConsistencies(textFeedbackConflictRequestDTOS, exerciseId, 0);\n }\n catch (NetworkingError networkingError) {\n log.error(networkingError.getMessage(), networkingError);\n return;\n }\n\n // create an array to store conflicts\n List<FeedbackConflict> feedbackConflicts = new ArrayList<>();\n\n // look for new conflicts\n // Athene may find conflicts with feedback ids that are not in the feedback repository any more. So check for them. (May happen if the feedback is deleted in Artemis but\n // already stored in Athene)\n feedbackConflictResponseDTOS.forEach(conflict -> {\n Optional<Feedback> firstFeedback = feedbackRepository.findById(conflict.getFirstFeedbackId());\n Optional<Feedback> secondFeedback = feedbackRepository.findById(conflict.getSecondFeedbackId());\n List<FeedbackConflict> storedConflicts = this.feedbackConflictRepository.findConflictsOrDiscardedOnesByFirstAndSecondFeedback(conflict.getFirstFeedbackId(),\n conflict.getSecondFeedbackId());\n // if the found conflict is present but its type has changed, update it\n if (!storedConflicts.isEmpty() && !storedConflicts.get(0).getType().equals(conflict.getType())) {\n storedConflicts.get(0).setType(conflict.getType());\n feedbackConflicts.add(storedConflicts.get(0));\n }\n\n // new conflict\n if (firstFeedback.isPresent() && secondFeedback.isPresent() && storedConflicts.isEmpty()) {\n FeedbackConflict feedbackConflict = new FeedbackConflict();\n feedbackConflict.setConflict(true);\n feedbackConflict.setFirstFeedback(firstFeedback.get());\n feedbackConflict.setSecondFeedback(secondFeedback.get());\n feedbackConflict.setType(conflict.getType());\n feedbackConflict.setCreatedAt(ZonedDateTime.now());\n feedbackConflict.setDiscard(false);\n feedbackConflicts.add(feedbackConflict);\n }\n });\n\n // find solved conflicts and add them to list\n feedbackConflicts.addAll(this.findSolvedConflictsInResponse(textFeedbackConflictRequestDTOS, feedbackConflictResponseDTOS));\n\n feedbackConflictRepository.saveAll(feedbackConflicts);\n }\n\n /**\n * Finds and returns the submissions which have the conflicting feedback with the passed feedback\n *\n * @param feedbackId - passed feedback id\n * @return Set of text submissions\n */\n public Set<TextSubmission> getConflictingSubmissions(long feedbackId) {\n List<FeedbackConflict> feedbackConflicts = this.feedbackConflictRepository.findAllWithEagerFeedbackResultAndSubmissionByFeedbackId(feedbackId);\n Set<TextSubmission> textSubmissionSet = feedbackConflicts.stream().map(conflict -> {\n if (conflict.getFirstFeedback().getId() == feedbackId) {\n TextSubmission textSubmission = (TextSubmission) conflict.getSecondFeedback().getResult().getSubmission();\n textSubmission.setResults(List.of(conflict.getSecondFeedback().getResult()));\n return textSubmission;\n }\n else {\n TextSubmission textSubmission = (TextSubmission) conflict.getFirstFeedback().getResult().getSubmission();\n textSubmission.setResults(List.of(conflict.getFirstFeedback().getResult()));\n return textSubmission;\n }\n }).collect(toSet());\n final var allTextBlocks = textBlockRepository.findAllBySubmissionIdIn(textSubmissionSet.stream().map(TextSubmission::getId).collect(toSet()));\n final var textBlockGroupedBySubmissionId = allTextBlocks.stream().collect(groupingBy(block -> block.getSubmission().getId(), toSet()));\n textSubmissionSet.forEach(textSubmission -> textSubmission.setBlocks(textBlockGroupedBySubmissionId.get(textSubmission.getId())));\n return textSubmissionSet;\n }\n\n /**\n * Set feedbackConflict as solved. Done by user marking the conflict as solved.\n *\n * @param feedbackConflict - feedbackConflict to set as solved\n */\n public void solveFeedbackConflict(FeedbackConflict feedbackConflict) {\n feedbackConflict.setSolvedAt(ZonedDateTime.now());\n feedbackConflict.setConflict(false);\n feedbackConflict.setDiscard(true);\n this.feedbackConflictRepository.save(feedbackConflict);\n }\n\n /**\n * Searches if the feedback that are sent to Athene already have conflicts in the database(storedConflicts),\n * If the stored conflicts are not returned from Athene after the consistency check, it means that they are solved and set as solved.\n *\n * @param textFeedbackConflictRequestDTOS the list sent to Athene for check\n * @param feedbackConflictResponseDTOS returned list with found conflicts.\n * @return solved conflicts\n */\n private List<FeedbackConflict> findSolvedConflictsInResponse(List<TextFeedbackConflictRequestDTO> textFeedbackConflictRequestDTOS,\n List<FeedbackConflictResponseDTO> feedbackConflictResponseDTOS) {\n List<Long> feedbackIds = textFeedbackConflictRequestDTOS.stream().map(TextFeedbackConflictRequestDTO::getFeedbackId).collect(toList());\n List<FeedbackConflict> storedConflicts = this.feedbackConflictRepository.findAllConflictsByFeedbackList(feedbackIds);\n\n storedConflicts.forEach(conflict -> {\n boolean isPresent = feedbackConflictResponseDTOS.stream().anyMatch(newConflicts -> (newConflicts.getFirstFeedbackId() == conflict.getFirstFeedback().getId()\n && newConflicts.getSecondFeedbackId() == conflict.getSecondFeedback().getId())\n || (newConflicts.getFirstFeedbackId() == conflict.getSecondFeedback().getId() && newConflicts.getSecondFeedbackId() == conflict.getFirstFeedback().getId()));\n if (!isPresent) {\n conflict.setConflict(false);\n conflict.setSolvedAt(ZonedDateTime.now());\n }\n });\n // remove the ones that are already in the database.\n storedConflicts.removeIf(FeedbackConflict::getConflict);\n\n return storedConflicts;\n }\n}\n" }, { "alpha_fraction": 0.6564299464225769, "alphanum_fraction": 0.6564299464225769, "avg_line_length": 34.522727966308594, "blob_id": "80aff6a42f1e53f4893357574e9cf765e4d69da4", "content_id": "76b5378bc870d11136e72739e451c6160268acfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1563, "license_type": "permissive", "max_line_length": 114, "num_lines": 44, "path": "/src/main/webapp/app/overview/course-lectures/text-unit/text-unit.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { SERVER_API_URL } from 'app/app.constants';\n\n@Component({\n selector: 'jhi-text-unit',\n templateUrl: './text-unit.component.html',\n styleUrls: ['../lecture-unit.component.scss'],\n})\nexport class TextUnitComponent implements OnInit {\n @Input()\n textUnit: TextUnit;\n isCollapsed = true;\n\n formattedContent?: SafeHtml;\n\n constructor(private artemisMarkdown: ArtemisMarkdownService) {}\n\n ngOnInit(): void {\n if (this.textUnit?.content) {\n this.formattedContent = this.artemisMarkdown.safeHtmlForMarkdown(this.textUnit.content);\n }\n }\n\n handleCollapse($event: any) {\n $event.stopPropagation();\n this.isCollapsed = !this.isCollapsed;\n }\n\n openPopup($event: any) {\n $event.stopPropagation();\n\n const win = window.open('about:blank', '_blank');\n win!.document.write(`<html><head><title>${this.textUnit.name}</title>`);\n win!.document.write(`<link rel=\"stylesheet\" href=\"${SERVER_API_URL}public/content/github-markdown.css\">`);\n win!.document.write('</head><body class=\"markdown-body\">');\n win!.document.write('</body></html>');\n win!.document.close();\n win!.document.body.innerHTML = this.artemisMarkdown.htmlForMarkdown(this.textUnit.content, []);\n win!.focus();\n }\n}\n" }, { "alpha_fraction": 0.5789473652839661, "alphanum_fraction": 0.5868028402328491, "avg_line_length": 43.929412841796875, "blob_id": "7536df11ff5dc5b794175d1984ebae0d34ceedff", "content_id": "26c34fb86774c3e3736f53433308e0845b956a11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7638, "license_type": "permissive", "max_line_length": 136, "num_lines": 170, "path": "/src/test/javascript/spec/service/programming-exercise.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { map, take } from 'rxjs/operators';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { routes } from 'app/exercises/programming/manage/programming-exercise-management-routing.module';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ArtemisTestModule } from '../test.module';\nimport { FormsModule } from '@angular/forms';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { ArtemisProgrammingExerciseManagementModule } from 'app/exercises/programming/manage/programming-exercise-management.module';\nimport * as moment from 'moment';\nimport { TemplateProgrammingExerciseParticipation } from 'app/entities/participation/template-programming-exercise-participation.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Result } from 'app/entities/result.model';\n\ndescribe('ProgrammingExercise Service', () => {\n let injector: TestBed;\n let service: ProgrammingExerciseService;\n let httpMock: HttpTestingController;\n let elemDefault: ProgrammingExercise;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n HttpClientTestingModule,\n RouterTestingModule.withRoutes(routes),\n ArtemisTestModule,\n FormsModule,\n ArtemisSharedModule,\n ArtemisSharedComponentModule,\n ArtemisProgrammingExerciseManagementModule,\n ],\n providers: [\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n });\n injector = getTestBed();\n service = injector.get(ProgrammingExerciseService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new ProgrammingExercise(undefined, undefined);\n });\n\n describe('Service methods', () => {\n it('should find an element', async () => {\n const returnedFromService = Object.assign({}, elemDefault);\n service\n .find(123)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault }));\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should create a ProgrammingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n const expected = Object.assign({}, returnedFromService);\n service\n .automaticSetup(new ProgrammingExercise(undefined, undefined))\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should reconnect template submission with result', async () => {\n const templateParticipation = new TemplateProgrammingExerciseParticipation();\n const tempSubmission = new ProgrammingSubmission();\n const tempResult = new Result();\n tempResult.id = 2;\n tempSubmission.results = [tempResult];\n templateParticipation.submissions = [tempSubmission];\n const returnedFromService = Object.assign({ id: 0 }, { ...elemDefault, templateParticipation });\n const expected = Object.assign({}, returnedFromService);\n service\n .findWithTemplateAndSolutionParticipation(expected.id, true)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n });\n\n it('should update a ProgrammingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n templateRepositoryUrl: 'BBBBBB',\n solutionRepositoryUrl: 'BBBBBB',\n templateBuildPlanId: 'BBBBBB',\n publishBuildPlanUrl: true,\n allowOnlineEditor: true,\n },\n elemDefault,\n );\n\n const expected = Object.assign({}, returnedFromService);\n service\n .update(expected)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should update the Timeline of a ProgrammingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n releaseDate: moment('2020-12-10 10:00:00'),\n dueDate: moment('2021-01-01 10:00:00'),\n assessmentDueDate: moment('2021-01-02 10:00:00'),\n },\n elemDefault,\n );\n const expected = Object.assign({}, returnedFromService);\n service\n .updateTimeline(expected)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should return a list of ProgrammingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n templateRepositoryUrl: 'BBBBBB',\n solutionRepositoryUrl: 'BBBBBB',\n templateBuildPlanId: 'BBBBBB',\n publishBuildPlanUrl: true,\n allowOnlineEditor: true,\n },\n elemDefault,\n );\n const expected = Object.assign({}, returnedFromService);\n service\n .query(expected)\n .pipe(\n take(1),\n map((resp) => resp.body),\n )\n .subscribe((body) => expect(body).toContain(expected));\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify([returnedFromService]));\n httpMock.verify();\n });\n\n it('should delete a ProgrammingExercise', async () => {\n service.delete(123, false, false).subscribe((resp) => expect(resp.ok));\n\n const req = httpMock.expectOne({ method: 'DELETE' });\n req.flush({ status: 200 });\n });\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.5467672944068909, "alphanum_fraction": 0.5467672944068909, "avg_line_length": 35.71084213256836, "blob_id": "597aa21de9da30dda41cc7aff150a7cf7b950249", "content_id": "dc01341a4e232d4608ed59eafcfef4529df143ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3047, "license_type": "permissive", "max_line_length": 157, "num_lines": 83, "path": "/src/main/webapp/app/admin/user-management/user-management.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { ActivatedRouteSnapshot, Resolve, Route } from '@angular/router';\nimport { JhiResolvePagingParams } from 'ng-jhipster';\nimport { User } from 'app/core/user/user.model';\nimport { UserService } from 'app/core/user/user.service';\nimport { UserManagementDetailComponent } from 'app/admin/user-management/user-management-detail.component';\nimport { UserManagementComponent } from 'app/admin/user-management/user-management.component';\nimport { UserManagementUpdateComponent } from 'app/admin/user-management/user-management-update.component';\n\n@Injectable({ providedIn: 'root' })\nexport class UserMgmtResolve implements Resolve<any> {\n constructor(private userService: UserService) {}\n\n /**\n * Resolve route to find the user before the route is activated\n * @param route contains the information about a route associated with a component loaded in an outlet at a particular moment in time\n */\n resolve(route: ActivatedRouteSnapshot) {\n if (route.params['login']) {\n return this.userService.find(route.params['login']);\n }\n return new User();\n }\n}\n\nexport const userMgmtRoute: Route[] = [\n {\n path: 'user-management',\n component: UserManagementComponent,\n resolve: {\n pagingParams: JhiResolvePagingParams,\n },\n data: {\n pageTitle: 'userManagement.home.title',\n defaultSort: 'id,asc',\n },\n },\n {\n // Create a new path without a component defined to prevent resolver caching and the UserManagementComponent from being always rendered\n path: 'user-management',\n data: {\n pageTitle: 'userManagement.home.title',\n },\n children: [\n {\n path: 'new',\n component: UserManagementUpdateComponent,\n resolve: {\n user: UserMgmtResolve,\n },\n data: {\n pageTitle: 'userManagement.home.createLabel',\n },\n },\n {\n path: ':login',\n component: UserManagementDetailComponent,\n resolve: {\n user: UserMgmtResolve,\n },\n data: {\n pageTitle: 'userManagement.home.title',\n },\n },\n {\n // Create a new path without a component defined to prevent resolver caching and the UserManagementDetailComponent from being always rendered\n path: ':login',\n resolve: {\n user: UserMgmtResolve,\n },\n children: [\n {\n path: 'edit',\n component: UserManagementUpdateComponent,\n data: {\n pageTitle: 'userManagement.home.createOrEditLabel',\n },\n },\n ],\n },\n ],\n },\n];\n" }, { "alpha_fraction": 0.640807032585144, "alphanum_fraction": 0.6436487436294556, "avg_line_length": 38.83773422241211, "blob_id": "1ae06e79c7f85277a096d3133615aa362a81ea11", "content_id": "4e51697fb255224e749a29f8eb6faf5cf922f2c3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10557, "license_type": "permissive", "max_line_length": 159, "num_lines": 265, "path": "/src/main/webapp/app/exercises/quiz/manage/statistics/question-statistic.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { calculateHeightOfChart, createOptions, DataSet, DataSetProvider } from 'app/exercises/quiz/manage/statistics/quiz-statistic/quiz-statistic.component';\nimport { QuizQuestion } from 'app/entities/quiz/quiz-question.model';\nimport { QuizQuestionStatistic } from 'app/entities/quiz/quiz-question-statistic.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { Subscription } from 'rxjs';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { ChartOptions, ChartType } from 'chart.js';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { CanBecomeInvalid } from 'app/entities/quiz/drop-location.model';\nimport { BaseChartDirective, Color } from 'ng2-charts';\n\nexport const redColor = '#d9534f';\nexport const greenColor = '#5cb85c';\nexport const blueColor = '#428bca';\nexport const lightBlueColor = '#5bc0de';\nexport const greyColor = '#838383';\n\n@Component({ template: '' })\nexport abstract class QuestionStatisticComponent implements DataSetProvider, OnInit, OnDestroy {\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n question: QuizQuestion;\n questionStatistic: QuizQuestionStatistic;\n\n quizExercise: QuizExercise;\n questionIdParam: number;\n sub: Subscription;\n\n chartLabels: string[] = [];\n data: number[] = [];\n chartType: ChartType = 'bar';\n datasets: DataSet[] = [];\n\n // TODO: why do we have a second variable for labels?\n labels: string[] = [];\n // solutionLabels is currently only used for multiple choice questions\n solutionLabels: string[] = [];\n ratedData: number[] = [];\n unratedData: number[] = [];\n\n ratedCorrectData: number;\n unratedCorrectData: number;\n\n maxScore: number;\n rated = true;\n showSolution = false;\n participants: number;\n websocketChannelForData: string;\n\n questionTextRendered?: SafeHtml;\n\n options: ChartOptions;\n\n backgroundColors: string[] = [];\n backgroundSolutionColors: string[] = [];\n colors: Color[] = [];\n\n constructor(\n protected route: ActivatedRoute,\n protected router: Router,\n protected accountService: AccountService,\n protected translateService: TranslateService,\n protected quizExerciseService: QuizExerciseService,\n protected jhiWebsocketService: JhiWebsocketService,\n ) {}\n\n ngOnInit() {\n this.sub = this.route.params.subscribe((params) => {\n this.questionIdParam = +params['questionId'];\n // use different REST-call if the User is a Student\n if (this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.quizExerciseService.find(params['exerciseId']).subscribe((res) => {\n this.loadQuiz(res.body!, false);\n });\n }\n\n // subscribe websocket for new statistical data\n this.websocketChannelForData = '/topic/statistic/' + params['exerciseId'];\n this.jhiWebsocketService.subscribe(this.websocketChannelForData);\n\n // ask for new Data if the websocket for new statistical data was notified\n this.jhiWebsocketService.receive(this.websocketChannelForData).subscribe((quiz) => {\n this.loadQuiz(quiz, true);\n });\n });\n }\n\n ngOnDestroy() {\n this.jhiWebsocketService.unsubscribe(this.websocketChannelForData);\n }\n\n getDataSets() {\n return this.datasets;\n }\n\n getParticipants() {\n return this.participants;\n }\n\n /**\n * reset old charts data\n */\n resetLabelsColors() {\n this.labels = [];\n this.solutionLabels = [];\n this.backgroundColors = [];\n this.backgroundSolutionColors = [];\n }\n\n resetData() {\n this.ratedData = [];\n this.unratedData = [];\n }\n\n addData(rated: number, unrated: number) {\n this.ratedData.push(rated);\n this.unratedData.push(unrated);\n }\n\n /**\n * converts a number in a letter (0 -> A, 1 -> B, ...)\n *\n * @param index the given number\n */\n getLetter(index: number) {\n return String.fromCharCode(65 + index);\n }\n\n updateData() {\n // add data for the last bar (correct Solutions)\n this.ratedCorrectData = this.questionStatistic.ratedCorrectCounter!;\n this.unratedCorrectData = this.questionStatistic.unRatedCorrectCounter!;\n this.chartLabels = this.labels;\n this.loadDataInDiagram();\n }\n\n /**\n * switch between showing and hiding the solution in the chart\n * 1. change the amount of participants\n * 2. change the bar-data\n */\n switchRated() {\n this.rated = !this.rated;\n this.loadDataInDiagram();\n }\n\n /**\n * switch between showing and hiding the solution in the chart\n * 1. change the BackgroundColor of the bars\n * 2. change the bar-Labels\n */\n switchSolution() {\n this.showSolution = !this.showSolution;\n this.loadDataInDiagram();\n }\n\n abstract loadQuiz(quiz: QuizExercise, refresh: boolean): void;\n\n loadQuizCommon(quiz: QuizExercise) {\n // if the Student finds a way to the Website\n // -> the Student will be send back to Courses\n if (!this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.router.navigateByUrl('courses');\n }\n // search selected question in quizExercise based on questionId\n this.quizExercise = quiz;\n const updatedQuestion = this.quizExercise.quizQuestions?.filter((question) => this.questionIdParam === question.id)[0];\n // if anyone finds a way to the Website, with a wrong combination of QuizId and QuestionId, go back to Courses\n if (!updatedQuestion) {\n this.router.navigateByUrl('courses');\n return undefined;\n }\n this.question = updatedQuestion;\n this.questionStatistic = updatedQuestion.quizQuestionStatistic!;\n return updatedQuestion;\n }\n\n /**\n * change label and color if an element is invalid\n */\n loadInvalidLayout(possibleInvalidElements: CanBecomeInvalid[]) {\n // set Background for invalid answers = grey\n const invalidLabel = this.translateService.instant('showStatistic.invalid');\n possibleInvalidElements.forEach((element, i) => {\n if (element.invalid) {\n this.backgroundColors[i] = greyColor;\n this.backgroundSolutionColors[i] = greyColor;\n // add 'invalid' to bar-Label\n this.labels[i] = this.getLetter(i) + '. ' + invalidLabel;\n }\n });\n }\n\n /**\n * add Layout for the last bar\n */\n addLastBarLayout(length: number) {\n // add Color for last bar\n this.backgroundColors.push(lightBlueColor);\n this.backgroundSolutionColors[length] = lightBlueColor;\n\n // add Text for last label based on the language\n const lastLabel = this.translateService.instant('showStatistic.quizStatistic.yAxes');\n this.solutionLabels[length] = lastLabel.split(' ');\n this.labels[length] = lastLabel.split(' ');\n this.chartLabels = this.labels;\n }\n\n /**\n * check if the rated or unrated, then load the rated or unrated data into the diagram\n */\n loadDataInDiagram() {\n // if show Solution is true use the label, backgroundColor and Data, which show the solution\n if (this.showSolution) {\n // show Solution: use the backgroundColor which shows the solution\n this.colors = this.backgroundSolutionColors.map((backgroundColor) => ({ backgroundColor }));\n if (this.rated) {\n this.participants = this.questionStatistic.participantsRated!;\n // if rated is true use the rated Data and add the rated CorrectCounter\n this.data = [...this.ratedData];\n // additionally show how many people on average have the complete answer correct (which should only be shown when the solution is displayed)\n this.data.push(this.ratedCorrectData);\n } else {\n this.participants = this.questionStatistic.participantsUnrated!;\n // if rated is false use the unrated Data and add the unrated CorrectCounter\n this.data = [...this.unratedData];\n // additionally show how many people on average have the complete answer correct (which should only be shown when the solution is displayed)\n this.data.push(this.unratedCorrectData);\n }\n // show Solution\n this.chartLabels = this.solutionLabels;\n } else {\n // don't show Solution: use the backgroundColor which doesn't show the solution\n this.colors = this.backgroundColors.map((backgroundColor) => ({ backgroundColor }));\n // if rated is true use the rated Data\n if (this.rated) {\n this.participants = this.questionStatistic.participantsRated!;\n this.data = [...this.ratedData];\n } else {\n // if rated is false use the unrated Data\n this.participants = this.questionStatistic.participantsUnrated!;\n this.data = [...this.unratedData];\n }\n // don't show Solution\n this.chartLabels = this.labels;\n }\n\n this.datasets = [{ data: this.data, backgroundColor: this.colors.map((color) => color.backgroundColor as string) }];\n // recalculate the height of the chart because rated/unrated might have changed or new results might have appeared\n const height = calculateHeightOfChart(this);\n // add Axes-labels based on selected language\n const xLabel = this.translateService.instant('showStatistic.questionStatistic.xAxes');\n const yLabel = this.translateService.instant('showStatistic.questionStatistic.yAxes');\n this.options = createOptions(this, height, height / 5, xLabel, yLabel);\n if (this.chart) {\n this.chart.update(0);\n }\n }\n}\n" }, { "alpha_fraction": 0.7432494163513184, "alphanum_fraction": 0.7437071204185486, "avg_line_length": 44.52083206176758, "blob_id": "2b293006301e0cd6a4ed5b80f5fd2ce69db23fa5", "content_id": "018a93f73b8d7f9d53b0f50fc5dcc20b7632cbee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2185, "license_type": "permissive", "max_line_length": 162, "num_lines": 48, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/util/ResponseUtil.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.util;\n\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\n\npublic final class ResponseUtil implements io.github.jhipster.web.util.ResponseUtil {\n\n // TODO: This is always null because spring does not allow static field injection\n @Value(\"${jhipster.clientApp.name}\")\n private static String applicationName;\n\n public static <X> ResponseEntity<X> ok() {\n return ResponseEntity.ok().build();\n }\n\n public static <X> ResponseEntity<X> notFound() {\n return ResponseEntity.status(HttpStatus.NOT_FOUND).build();\n }\n\n public static <X> ResponseEntity<X> forbidden() {\n return ResponseEntity.status(HttpStatus.FORBIDDEN).build();\n }\n\n public static <X> ResponseEntity<X> forbidden(String entityName, String errorKey, String message) {\n return ResponseEntity.status(HttpStatus.FORBIDDEN).headers(HeaderUtil.createFailureAlert(applicationName, true, entityName, errorKey, message)).build();\n }\n\n public static <X> ResponseEntity<X> forbidden(String applicationName, String entityName, String errorKey, String message) {\n return ResponseEntity.status(HttpStatus.FORBIDDEN).headers(HeaderUtil.createFailureAlert(applicationName, true, entityName, errorKey, message)).build();\n }\n\n public static <X> ResponseEntity<X> badRequest() {\n return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();\n }\n\n public static <X> ResponseEntity<X> badRequest(String entityName, String errorKey, String message) {\n return ResponseEntity.status(HttpStatus.BAD_REQUEST).headers(HeaderUtil.createFailureAlert(applicationName, true, entityName, errorKey, message)).build();\n }\n\n public static <X> ResponseEntity<X> conflict() {\n return ResponseEntity.status(HttpStatus.CONFLICT).build();\n }\n\n public static <X> ResponseEntity<X> conflict(String entityName, String errorKey, String message) {\n return ResponseEntity.status(HttpStatus.CONFLICT).headers(HeaderUtil.createFailureAlert(applicationName, true, entityName, errorKey, message)).build();\n }\n}\n" }, { "alpha_fraction": 0.6359315514564514, "alphanum_fraction": 0.6368821263313293, "avg_line_length": 25.299999237060547, "blob_id": "fa177e969518356ebc3f6e393da3dac684312f84", "content_id": "501789a8d328044d4a1716a3ad9009f32c4baa42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1052, "license_type": "permissive", "max_line_length": 97, "num_lines": 40, "path": "/src/main/java/de/tum/in/www1/artemis/domain/File.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport java.nio.file.Path;\n\npublic class File extends java.io.File {\n\n private Repository repository;\n\n public File(java.io.File file, Repository repository) {\n super(file.getPath());\n this.repository = repository;\n }\n\n public File(Path path, Repository repository) {\n super(path.toString());\n this.repository = repository;\n }\n\n public File(String path, Repository repository) {\n super(path);\n this.repository = repository;\n }\n\n public Repository getRepository() {\n return repository;\n }\n\n public void setRepository(Repository repository) {\n this.repository = repository;\n }\n\n @Override\n public String toString() {\n // Make windows paths safe\n String safeFilename = super.toString().replaceAll(\"\\\\\\\\\", \"/\");\n String safeRepositoryPath = repository.getLocalPath().toString().replaceAll(\"\\\\\\\\\", \"/\");\n\n return safeFilename.replaceFirst(safeRepositoryPath, \"\").replaceAll(\"^/+\", \"\");\n }\n}\n" }, { "alpha_fraction": 0.5465563535690308, "alphanum_fraction": 0.5663716793060303, "avg_line_length": 38.082706451416016, "blob_id": "13e65064f7a4c9d3f1024760e5e9ca0026ba8e54", "content_id": "f61e46499f2f0a0e27d68c93e1c6d79550f26917", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5198, "license_type": "permissive", "max_line_length": 170, "num_lines": 133, "path": "/src/main/webapp/app/shared/chart/presets/scoreChartPreset.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChartComponent, ChartPreset } from 'app/shared/chart/chart.component';\nimport { ChartDataSets, ChartLegendLabelItem } from 'chart.js';\n\nexport class ScoreChartPreset implements ChartPreset {\n private chart: ChartComponent;\n private datasets: ChartDataSets[] = [];\n\n private readonly redGreenPattern: CanvasPattern;\n private readonly redTransparentPattern: CanvasPattern;\n private readonly labels: string[];\n private valueLabels: string[];\n private showValues: boolean;\n\n constructor(labels: string[], showValues = true) {\n this.labels = labels;\n this.valueLabels = ['', ''];\n this.showValues = showValues;\n this.redGreenPattern = this.createPattern('#28a745');\n this.redTransparentPattern = this.createPattern('transparent');\n }\n\n applyTo(chart: ChartComponent): void {\n this.chart = chart;\n chart.setType('horizontalBar');\n chart.setYAxe(0, { stacked: true }, false);\n chart.setXAxe(0, { stacked: true, ticks: { min: 0, stepSize: 25, suggestedMax: 100, callback: (value) => value + '%' } }, false);\n chart.setLegend({\n position: 'bottom',\n labels: {\n generateLabels: () =>\n [\n {\n datasetIndex: 0,\n text: this.labels[0] + (this.showValues ? `: ${this.valueLabels[0]}` : ''),\n fillStyle: '#28a745',\n strokeStyle: '#28a745',\n lineWidth: 1,\n },\n {\n datasetIndex: 1,\n text: this.labels[1] + (this.showValues ? `: ${this.valueLabels[1]}` : ''),\n fillStyle: this.redTransparentPattern,\n strokeStyle: '#dc3545',\n lineWidth: 1,\n },\n ] as ChartLegendLabelItem[],\n },\n });\n chart.chartDatasets = this.datasets;\n }\n\n /**\n * Updates the datasets of the charts with the correct values and colors.\n * @param receivedPositive Sum of positive credits of the score\n * @param appliedNegative Sum of applied negative credits\n * @param receivedNegative Sum of received negative credits\n * @param maxScore The relevant maximal points of the exercise\n * @param maxScoreWithBonus The actual received points + optional bonus points\n */\n setValues(receivedPositive: number, appliedNegative: number, receivedNegative: number, maxScore: number, maxScoreWithBonus: number) {\n let appliedPositive = receivedPositive;\n\n // cap to min and max values while maintaining correct negative points\n if (appliedPositive - appliedNegative > maxScoreWithBonus) {\n appliedPositive = maxScoreWithBonus;\n appliedNegative = 0;\n } else if (appliedPositive > maxScoreWithBonus) {\n appliedNegative -= appliedPositive - maxScoreWithBonus;\n appliedPositive = maxScoreWithBonus;\n } else if (appliedPositive - appliedNegative < 0) {\n appliedNegative = appliedPositive;\n }\n\n this.valueLabels[0] = this.roundToDecimals(appliedPositive, 1) + (appliedPositive !== receivedPositive ? ` of ${this.roundToDecimals(receivedPositive, 1)}` : '');\n this.valueLabels[1] = this.roundToDecimals(appliedNegative, 1) + (appliedNegative !== receivedNegative ? ` of ${this.roundToDecimals(receivedNegative, 1)}` : '');\n\n this.datasets = [\n {\n data: [this.roundToDecimals(((appliedPositive - appliedNegative) / maxScore) * 100, 2)],\n backgroundColor: '#28a745',\n hoverBackgroundColor: '#28a745',\n },\n {\n data: [this.roundToDecimals((appliedNegative / maxScore) * 100, 2)],\n backgroundColor: this.redGreenPattern,\n hoverBackgroundColor: this.redGreenPattern,\n },\n ];\n if (this.chart) {\n this.chart.chartDatasets = this.datasets;\n }\n }\n\n private roundToDecimals(i: number, n: number) {\n const f = 10 ** n;\n return Math.round(i * f) / f;\n }\n\n /**\n * Generates a diagonal red stripes pattern used for the deductions bar.\n * @param fillStyle The background of the pattern\n * @private\n */\n private createPattern(fillStyle: string) {\n const c = document.createElement('canvas');\n c.width = 10;\n c.height = 10;\n const ctx = c.getContext('2d')!;\n\n const x0 = 12;\n const y0 = -2;\n\n const x1 = -2;\n const y1 = 12;\n const offset = 10;\n\n ctx.fillStyle = fillStyle;\n ctx.fillRect(0, 0, 10, 10);\n\n ctx.strokeStyle = '#dc3545';\n ctx.lineWidth = 3;\n ctx.beginPath();\n ctx.moveTo(x0, y0);\n ctx.lineTo(x1, y1);\n ctx.moveTo(x0 - offset, y0);\n ctx.lineTo(x1 - offset, y1);\n ctx.moveTo(x0 + offset, y0);\n ctx.lineTo(x1 + offset, y1);\n ctx.stroke();\n\n return ctx.createPattern(c, 'repeat')!;\n }\n}\n" }, { "alpha_fraction": 0.6093618273735046, "alphanum_fraction": 0.6111137866973877, "avg_line_length": 44.663272857666016, "blob_id": "27b60b07612a699343d2d6b6bb00ba15bb785d9b", "content_id": "21f5fde857efc05885ae577c10bb53e6a2a4da2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 62787, "license_type": "permissive", "max_line_length": 178, "num_lines": 1375, "path": "/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-detail.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectionStrategy, ChangeDetectorRef, Component, HostListener, OnChanges, OnInit, QueryList, SimpleChanges, ViewChildren, ViewEncapsulation } from '@angular/core';\nimport { QuizExerciseService } from './quiz-exercise.service';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { DragAndDropQuestionUtil } from 'app/exercises/quiz/shared/drag-and-drop-question-util.service';\nimport { ShortAnswerQuestionUtil } from 'app/exercises/quiz/shared/short-answer-question-util.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { Duration, Option } from './quiz-exercise-interfaces';\nimport { NgbDate, NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { Location } from '@angular/common';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ComponentCanDeactivate } from 'app/shared/guard/can-deactivate.model';\nimport { QuizQuestion, QuizQuestionType, ScoringType } from 'app/entities/quiz/quiz-question.model';\nimport { Exercise, ExerciseCategory, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { Course } from 'app/entities/course.model';\nimport { QuizQuestionEdit } from 'app/exercises/quiz/manage/quiz-question-edit.interface';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ShortAnswerSolution } from 'app/entities/quiz/short-answer-solution.model';\nimport { ShortAnswerMapping } from 'app/entities/quiz/short-answer-mapping.model';\nimport { ShortAnswerSpot } from 'app/entities/quiz/short-answer-spot.model';\nimport { DropLocation } from 'app/entities/quiz/drop-location.model';\nimport { DragItem } from 'app/entities/quiz/drag-item.model';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { QuizConfirmImportInvalidQuestionsModalComponent } from 'app/exercises/quiz/manage/quiz-confirm-import-invalid-questions-modal.component';\nimport * as Sentry from '@sentry/browser';\nimport { cloneDeep } from 'lodash';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\n\n// False-positives:\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { DragAndDropQuestionEditComponent } from 'app/exercises/quiz/manage/drag-and-drop-question/drag-and-drop-question-edit.component';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { MultipleChoiceQuestionEditComponent } from 'app/exercises/quiz/manage/multiple-choice-question/multiple-choice-question-edit.component';\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport { ShortAnswerQuestionEditComponent } from 'app/exercises/quiz/manage/short-answer-question/short-answer-question-edit.component';\n\nexport interface Reason {\n translateKey: string;\n translateValues: any;\n}\n\ninterface Warning {\n translateKey: string;\n translateValues: any;\n}\n\n@Component({\n selector: 'jhi-quiz-exercise-detail',\n templateUrl: './quiz-exercise-detail.component.html',\n changeDetection: ChangeDetectionStrategy.OnPush,\n providers: [DragAndDropQuestionUtil, ShortAnswerQuestionUtil],\n styleUrls: ['./quiz-exercise-detail.component.scss', '../shared/quiz.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class QuizExerciseDetailComponent implements OnInit, OnChanges, ComponentCanDeactivate {\n // Make constants available to html for comparison\n readonly DRAG_AND_DROP = QuizQuestionType.DRAG_AND_DROP;\n readonly MULTIPLE_CHOICE = QuizQuestionType.MULTIPLE_CHOICE;\n readonly SHORT_ANSWER = QuizQuestionType.SHORT_ANSWER;\n\n @ViewChildren('editMultipleChoice')\n editMultipleChoiceQuestionComponents: QueryList<MultipleChoiceQuestionEditComponent>;\n\n @ViewChildren('editDragAndDrop')\n editDragAndDropQuestionComponents: QueryList<DragAndDropQuestionEditComponent>;\n\n @ViewChildren('editShortAnswer')\n editShortAnswerQuestionComponents: QueryList<ShortAnswerQuestionEditComponent>;\n\n course: Course;\n quizExercise: QuizExercise;\n exerciseGroup?: ExerciseGroup;\n courseRepository: CourseManagementService;\n notificationText?: string;\n\n // TODO: why do we have entity, savedEntity and quizExercise?\n entity: QuizExercise;\n savedEntity: QuizExercise;\n\n isExamMode: boolean;\n\n /** Constants for 'Add existing questions' and 'Import file' features **/\n showExistingQuestions = false;\n showExistingQuestionsFromCourse = true;\n showExistingQuestionsFromExam = false;\n showExistingQuestionsFromFile = false;\n\n exams: Exam[] = [];\n selectedExamId?: number;\n\n courses: Course[] = [];\n selectedCourseId?: number;\n quizExercises: QuizExercise[];\n allExistingQuestions: QuizQuestion[];\n existingQuestions: QuizQuestion[];\n importFile?: Blob;\n importFileName: string;\n searchQueryText: string;\n dndFilterEnabled: boolean;\n mcqFilterEnabled: boolean;\n shortAnswerFilterEnabled: boolean;\n\n /** Duration object **/\n duration = new Duration(0, 0);\n\n /** Status constants **/\n isSaving = false;\n quizIsValid: boolean;\n warningQuizCache = false;\n pendingChangesCache: boolean;\n\n /** Status Options **/\n statusOptionsVisible: Option[] = [new Option(false, 'Hidden'), new Option(true, 'Visible')];\n statusOptionsPractice: Option[] = [new Option(false, 'Closed'), new Option(true, 'Open for Practice')];\n statusOptionsActive: Option[] = [new Option(true, 'Active')];\n\n exerciseCategories: ExerciseCategory[];\n existingCategories: ExerciseCategory[];\n\n /** Route params **/\n examId?: number;\n courseId?: number;\n private invalidFlaggedQuestions: {\n [title: string]: (AnswerOption | ShortAnswerSolution | ShortAnswerMapping | ShortAnswerSpot | DropLocation | DragItem | DragAndDropMapping)[] | undefined;\n } = {};\n\n constructor(\n private route: ActivatedRoute,\n private courseService: CourseManagementService,\n private examRepository: ExamManagementService,\n private quizExerciseService: QuizExerciseService,\n private dragAndDropQuestionUtil: DragAndDropQuestionUtil,\n private shortAnswerQuestionUtil: ShortAnswerQuestionUtil,\n private router: Router,\n private translateService: TranslateService,\n private fileUploaderService: FileUploaderService,\n private exerciseService: ExerciseService,\n private jhiAlertService: JhiAlertService,\n private location: Location,\n private modalService: NgbModal,\n private changeDetector: ChangeDetectorRef,\n private exerciseGroupService: ExerciseGroupService,\n ) {}\n\n /**\n * Initialize variables and load course and quiz from server.\n */\n ngOnInit(): void {\n /** Initialize local constants **/\n this.showExistingQuestions = false;\n this.quizExercises = [];\n this.allExistingQuestions = [];\n this.existingQuestions = [];\n this.importFile = undefined;\n this.importFileName = '';\n this.searchQueryText = '';\n this.dndFilterEnabled = true;\n this.mcqFilterEnabled = true;\n this.shortAnswerFilterEnabled = true;\n this.notificationText = undefined;\n\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n this.examId = Number(this.route.snapshot.paramMap.get('examId'));\n const quizId = Number(this.route.snapshot.paramMap.get('exerciseId'));\n const groupId = Number(this.route.snapshot.paramMap.get('groupId'));\n if (this.examId && groupId) {\n this.isExamMode = true;\n }\n /** Query the courseService for the participationId given by the params */\n if (this.courseId) {\n this.courseService.find(this.courseId).subscribe((response: HttpResponse<Course>) => {\n this.course = response.body!;\n // Load exerciseGroup and set exam mode\n if (this.isExamMode) {\n this.exerciseGroupService.find(this.courseId!, this.examId!, groupId).subscribe((groupResponse: HttpResponse<ExerciseGroup>) => {\n // Make sure to call init if we didn't receive an id => new quiz-exercise\n this.exerciseGroup = groupResponse.body || undefined;\n if (!quizId) {\n this.init();\n }\n });\n }\n // Make sure to call init if we didn't receive an id => new quiz-exercise\n if (!quizId && !this.isExamMode) {\n this.init();\n }\n });\n }\n if (quizId) {\n this.quizExerciseService.find(quizId).subscribe((response: HttpResponse<QuizExercise>) => {\n this.quizExercise = response.body!;\n this.init();\n if (this.isExamMode && this.quizExercise.testRunParticipationsExist) {\n this.jhiAlertService.warning(this.translateService.instant('artemisApp.quizExercise.edit.testRunSubmissionsExist'));\n }\n });\n }\n // TODO: we should try to avoid calling this.init() above more than once\n this.courseRepository = this.courseService;\n }\n\n /**\n * Initializes local constants and prepares the QuizExercise entity\n */\n init(): void {\n if (this.quizExercise) {\n this.entity = this.quizExercise;\n } else {\n this.entity = new QuizExercise(undefined, undefined);\n this.entity.title = '';\n this.entity.duration = 600;\n this.entity.isVisibleBeforeStart = false;\n this.entity.isOpenForPractice = false;\n this.entity.isPlannedToStart = false;\n this.entity.releaseDate = moment();\n this.entity.randomizeQuestionOrder = true;\n this.entity.quizQuestions = [];\n this.quizExercise = this.entity;\n }\n this.prepareEntity(this.entity);\n // Assign savedEntity to identify local changes\n this.savedEntity = this.entity.id ? cloneDeep(this.entity) : new QuizExercise(undefined, undefined);\n if (!this.quizExercise.course && !this.isExamMode) {\n this.quizExercise.course = this.course;\n }\n if (!this.quizExercise.exerciseGroup && this.isExamMode) {\n this.quizExercise.exerciseGroup = this.exerciseGroup;\n }\n if (!this.isExamMode) {\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.quizExercise);\n this.courseService.findAllCategoriesOfCourse(this.quizExercise.course!.id!).subscribe(\n (res: HttpResponse<string[]>) => {\n this.existingCategories = this.exerciseService.convertExerciseCategoriesAsStringFromServer(res.body!);\n },\n (res: HttpErrorResponse) => this.onError(res),\n );\n }\n this.updateDuration();\n this.cacheValidation();\n }\n\n /**\n * Apply updates for changed course and quizExercise\n * @param changes the changes to apply\n */\n ngOnChanges(changes: SimpleChanges): void {\n if (changes.course || changes.quizExercise) {\n this.init();\n }\n }\n\n /**\n * Update the categories and overwrite the cache, overwrites existing categories\n * @param categories the new categories\n */\n updateCategories(categories: ExerciseCategory[]) {\n this.quizExercise.categories = categories.map((el) => JSON.stringify(el));\n this.cacheValidation();\n }\n\n /**\n * Determine which dropdown to display depending on the relationship between start time, end time, and current time\n * @returns {string} Name of the dropdown to show\n */\n get showDropdown(): string {\n if (this.quizExercise && this.quizExercise.isPlannedToStart) {\n const releaseDate = this.quizExercise.releaseDate!;\n const plannedEndMoment = moment(releaseDate).add(this.quizExercise.duration, 'seconds');\n if (plannedEndMoment.isBefore(moment())) {\n return 'isOpenForPractice';\n } else if (moment(releaseDate).isBefore(moment())) {\n return 'active';\n }\n }\n return 'isVisibleBeforeStart';\n }\n\n /**\n * Returns whether pending changes are present, preventing a deactivation.\n */\n canDeactivate(): boolean {\n return !this.pendingChangesCache;\n }\n\n /**\n * displays the alert for confirming refreshing or closing the page if there are unsaved changes\n */\n @HostListener('window:beforeunload', ['$event'])\n unloadNotification($event: any) {\n if (!this.canDeactivate()) {\n $event.returnValue = this.translateService.instant('pendingChanges');\n }\n }\n\n /**\n * @desc Callback for datepicker to decide whether given date should be disabled\n * All dates which are in the past (< today) are disabled\n */\n isDateInPast = (date: NgbDate, current: { month: number }) =>\n current.month < moment().month() + 1 ||\n moment()\n .year(date.year)\n .month(date.month - 1)\n .date(date.day)\n .isBefore(moment());\n\n /**\n * Add an empty multiple choice question to the quiz\n */\n addMultipleChoiceQuestion() {\n if (this.quizExercise == undefined) {\n this.quizExercise = this.entity;\n }\n\n const mcQuestion = new MultipleChoiceQuestion();\n mcQuestion.title = '';\n mcQuestion.text = 'Enter your long question if needed';\n mcQuestion.hint = 'Add a hint here (visible during the quiz via ?-Button)';\n mcQuestion.scoringType = ScoringType.ALL_OR_NOTHING; // explicit default value for multiple questions\n mcQuestion.randomizeOrder = true;\n mcQuestion.points = 1;\n\n const correctSampleAnswerOption = new AnswerOption();\n correctSampleAnswerOption.isCorrect = true;\n correctSampleAnswerOption.text = 'Enter a correct answer option here';\n correctSampleAnswerOption.hint = 'Add a hint here (visible during the quiz via ?-Button)';\n correctSampleAnswerOption.explanation = 'Add an explanation here (only visible in feedback after quiz has ended)';\n\n const incorrectSampleAnswerOption = new AnswerOption();\n incorrectSampleAnswerOption.isCorrect = false;\n incorrectSampleAnswerOption.text = 'Enter a wrong answer option here';\n\n mcQuestion.answerOptions = [correctSampleAnswerOption, incorrectSampleAnswerOption];\n this.quizExercise.quizQuestions!.push(mcQuestion);\n this.cacheValidation();\n }\n\n /**\n * Add an empty drag and drop question to the quiz\n */\n addDragAndDropQuestion(): void {\n if (this.quizExercise == undefined) {\n this.quizExercise = this.entity;\n }\n\n const dndQuestion = new DragAndDropQuestion();\n dndQuestion.title = '';\n dndQuestion.text = 'Enter your long question if needed';\n dndQuestion.hint = 'Add a hint here (visible during the quiz via ?-Button)';\n dndQuestion.scoringType = ScoringType.PROPORTIONAL_WITH_PENALTY; // explicit default value for drag and drop questions\n dndQuestion.randomizeOrder = true;\n dndQuestion.points = 1;\n dndQuestion.dropLocations = [];\n dndQuestion.dragItems = [];\n dndQuestion.correctMappings = [];\n this.quizExercise.quizQuestions!.push(dndQuestion);\n this.cacheValidation();\n }\n\n /**\n * Add an empty short answer question to the quiz\n */\n addShortAnswerQuestion(): void {\n if (this.quizExercise == undefined) {\n this.quizExercise = this.entity;\n }\n\n const shortAnswerQuestion = new ShortAnswerQuestion();\n shortAnswerQuestion.title = '';\n shortAnswerQuestion.text =\n 'Enter your long question if needed\\n\\n' +\n 'Select a part of the text and click on Add Spot to automatically create an input field and the corresponding mapping\\n\\n' +\n 'You can define a input field like this: This [-spot 1] an [-spot 2] field.\\n\\n' +\n 'To define the solution for the input fields you need to create a mapping (multiple mapping also possible):\\n\\n' +\n '[-option 1] is\\n' +\n '[-option 2] input\\n' +\n '[-option 1,2] correctInBothFields';\n shortAnswerQuestion.scoringType = ScoringType.PROPORTIONAL_WITHOUT_PENALTY; // explicit default value for short answer questions\n shortAnswerQuestion.randomizeOrder = true;\n shortAnswerQuestion.points = 1;\n shortAnswerQuestion.spots = [];\n shortAnswerQuestion.solutions = [];\n shortAnswerQuestion.correctMappings = [];\n this.quizExercise.quizQuestions!.push(shortAnswerQuestion);\n this.cacheValidation();\n }\n\n /**\n * Iterates over the questions of the quizExercise and calculates the sum of all question scores\n */\n calculateMaxExerciseScore(): number {\n let scoreSum = 0;\n this.quizExercise.quizQuestions!.forEach((question) => (scoreSum += question.points!));\n return scoreSum;\n }\n\n /**\n * Toggles existing questions view\n */\n showHideExistingQuestions(): void {\n if (!this.quizExercise) {\n this.quizExercise = this.entity;\n }\n\n // If courses are not populated, then populate list of courses\n if (this.courses.length === 0) {\n this.courseRepository.getAllCoursesWithQuizExercises().subscribe((res: HttpResponse<Course[]>) => {\n this.courses = res.body!;\n });\n }\n // If exams are not populated, then populate list of exams\n if (this.exams.length === 0) {\n this.examRepository.findAllExamsAccessibleToUser(this.courseId!).subscribe((res: HttpResponse<Exam[]>) => {\n this.exams = res.body!;\n });\n }\n this.showExistingQuestions = !this.showExistingQuestions;\n this.setExistingQuestionSourceToCourse();\n }\n\n /**\n * Callback function for when a user selected a Course from the Dropdown list from 'Add existing questions'\n * Populates list of quiz exercises for the selected course\n */\n onCourseSelect(): void {\n this.allExistingQuestions = this.existingQuestions = [];\n if (!this.selectedCourseId) {\n return;\n }\n\n /** Search the selected course by id in all available courses **/\n const selectedCourse = this.courses.find((course) => course.id === Number(this.selectedCourseId))!;\n\n // TODO: the following code seems duplicated (see quiz-exercise-export.component.ts in the method loadForCourse). Try to avoid duplication!\n // For the given course, get list of all quiz exercises. And for all quiz exercises, get list of all questions in a quiz exercise,\n this.quizExerciseService.findForCourse(selectedCourse.id!).subscribe(\n (quizExercisesResponse: HttpResponse<QuizExercise[]>) => {\n if (quizExercisesResponse.body) {\n this.applyQuestionsAndFilter(quizExercisesResponse.body!);\n }\n },\n (res: HttpErrorResponse) => this.onError(res),\n );\n }\n\n onExamSelect(): void {\n this.allExistingQuestions = this.existingQuestions = [];\n if (!this.selectedExamId) {\n return;\n }\n\n /** Search the selected exam by id in all available exams **/\n const selectedExam = this.exams.find((exam) => exam.id === Number(this.selectedExamId))!;\n\n // For the given exam, get list of all quiz exercises. And for all quiz exercises, get list of all questions in a quiz exercise\n this.quizExerciseService.findForExam(selectedExam.id!).subscribe(\n (quizExercisesResponse: HttpResponse<QuizExercise[]>) => {\n if (quizExercisesResponse.body) {\n this.applyQuestionsAndFilter(quizExercisesResponse.body!);\n }\n },\n (res: HttpErrorResponse) => this.onError(res),\n );\n }\n\n private applyQuestionsAndFilter(quizExercises: QuizExercise[]) {\n for (const quizExercise of quizExercises) {\n this.quizExerciseService.find(quizExercise.id!).subscribe((response: HttpResponse<QuizExercise>) => {\n const quizExerciseResponse = response.body!;\n if (quizExerciseResponse.quizQuestions && quizExerciseResponse.quizQuestions.length > 0) {\n for (const question of quizExerciseResponse.quizQuestions) {\n question.exercise = quizExercise;\n this.allExistingQuestions.push(question);\n }\n }\n this.applyFilter();\n });\n }\n }\n\n private onError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n }\n\n /**\n * Applies filter on questions shown in add existing questions view.\n */\n applyFilter(): void {\n this.existingQuestions = [];\n /**\n * Depending on the filter selected by user, filter out questions.\n * allExistingQuestions contains list of all questions.\n * We don't change it. We populate existingQuestions list depending on the filter options.\n */\n for (const question of this.allExistingQuestions) {\n if (!this.searchQueryText || this.searchQueryText === '' || question.title!.toLowerCase().indexOf(this.searchQueryText.toLowerCase()) !== -1) {\n if (this.mcqFilterEnabled && question.type === QuizQuestionType.MULTIPLE_CHOICE) {\n this.existingQuestions.push(question);\n }\n if (this.dndFilterEnabled && question.type === QuizQuestionType.DRAG_AND_DROP) {\n this.existingQuestions.push(question);\n }\n if (this.shortAnswerFilterEnabled && question.type === QuizQuestionType.SHORT_ANSWER) {\n this.existingQuestions.push(question);\n }\n }\n }\n this.cacheValidation();\n }\n\n /**\n * Assigns the uploaded import file\n * @param $event object containing the uploaded file\n */\n setImportFile($event: any): void {\n if ($event.target.files.length) {\n const fileList: FileList = $event.target.files;\n this.importFile = fileList[0];\n this.importFileName = this.importFile['name'];\n }\n this.changeDetector.detectChanges();\n }\n\n /**\n * Adds selected quizzes to current quiz exercise\n */\n addExistingQuestions(): void {\n const questions: QuizQuestion[] = [];\n for (const question of this.existingQuestions) {\n if (question.exportQuiz) {\n questions.push(question);\n }\n }\n this.verifyAndImportQuestions(questions);\n this.showExistingQuestions = !this.showExistingQuestions;\n this.showExistingQuestionsFromCourse = true;\n this.showExistingQuestionsFromExam = false;\n this.showExistingQuestionsFromFile = false;\n this.selectedCourseId = undefined;\n this.selectedExamId = undefined;\n this.allExistingQuestions = this.existingQuestions = [];\n this.cacheValidation();\n }\n\n /**\n * 1. Check whether the inputs in the quiz are valid\n * 2. Check if warning are needed for the inputs\n * 3. Display the warnings/invalid reasons in the html file if needed\n */\n cacheValidation(): void {\n this.warningQuizCache = this.computeInvalidWarnings().length > 0;\n this.quizIsValid = this.validQuiz();\n this.pendingChangesCache = this.pendingChanges();\n this.checkForInvalidFlaggedQuestions();\n this.computeInvalidReasons();\n this.computeInvalidWarnings();\n this.changeDetector.detectChanges();\n }\n\n /**\n * Remove question from the quiz\n * @param questionToDelete {QuizQuestion} the question to remove\n */\n deleteQuestion(questionToDelete: QuizQuestion): void {\n this.quizExercise.quizQuestions = this.quizExercise.quizQuestions?.filter((question) => question !== questionToDelete);\n this.cacheValidation();\n }\n\n /**\n * Handles the change of a question by replacing the array with a copy (allows for shallow comparison)\n */\n onQuestionUpdated(): void {\n this.cacheValidation();\n this.quizExercise.quizQuestions = Array.from(this.quizExercise.quizQuestions!);\n }\n\n /**\n * Determine if there are any changes waiting to be saved\n * @returns {boolean} true if there are any pending changes, false otherwise\n */\n pendingChanges(): boolean {\n if (!this.quizExercise || !this.savedEntity) {\n return false;\n }\n const keysToCompare = [\n 'title',\n 'difficulty',\n 'duration',\n 'isPlannedToStart',\n 'isVisibleBeforeStart',\n 'isOpenForPractice',\n 'randomizeQuestionOrder',\n 'includedInOverallScore',\n ];\n\n // Unsaved changes if any of the stated object key values are not equal or the questions/release dates differ\n return (\n keysToCompare.some((key) => this.quizExercise[key] !== this.savedEntity[key]) ||\n !this.areDatesIdentical(this.quizExercise.releaseDate!, this.savedEntity.releaseDate!) ||\n !this.areCategoriesIdentical(this.quizExercise.categories, this.savedEntity.categories) ||\n !this.areQuizExerciseEntityQuestionsIdentical(this.quizExercise.quizQuestions, this.savedEntity.quizQuestions)\n );\n }\n\n /**\n * Checks whether the used and saved categories are the same.\n * @param categoriesUsed the categories currently used\n * @param categoriesSaved the categories that are saved\n * @returns {boolean} true if the used and saved categories are identical.\n */\n areCategoriesIdentical(categoriesUsed?: string[], categoriesSaved?: string[]): boolean {\n return JSON.stringify(categoriesUsed || []).toLowerCase() === JSON.stringify(categoriesSaved || []).toLowerCase();\n }\n\n /**\n * Compares the provided question array objects\n * @param QA1 {QuizQuestion[]} First question array to compare\n * @param QA2 {QuizQuestion[]} Second question array to compare against\n * @return {boolean} true if the provided Question[] objects are identical, false otherwise\n */\n areQuizExerciseEntityQuestionsIdentical(QA1?: QuizQuestion[], QA2?: QuizQuestion[]): boolean {\n return JSON.stringify(QA1 || []) === JSON.stringify(QA2 || []);\n }\n\n /**\n * This function compares the provided dates with help of the moment library\n * Since we might be receiving an string instead of a moment object (e.g. when receiving it from the server)\n * we wrap both dates in a moment object. If it's already a moment object, this will just be ignored.\n * @param date1 {string|Moment} First date to compare\n * @param date2 {string|Moment} Second date to compare to\n * @return {boolean} True if the dates are identical, false otherwise\n */\n areDatesIdentical(date1: string | Moment, date2: string | Moment): boolean {\n return moment(date1).isSame(moment(date2));\n }\n\n /**\n * Check if the current inputs are valid\n * @returns {boolean} true if valid, false otherwise\n */\n private validQuiz(): boolean {\n if (!this.quizExercise) {\n return false;\n }\n // Release date is valid if it's not null/undefined and a valid date; Precondition: isPlannedToStart is set\n // Release date should also not be in the past\n const releaseDateValidAndNotInPastCondition =\n !this.quizExercise.isPlannedToStart ||\n (this.quizExercise.releaseDate !== undefined && moment(this.quizExercise.releaseDate).isValid() && moment(this.quizExercise.releaseDate).isAfter(moment()));\n\n const isGenerallyValid =\n this.quizExercise.title != undefined &&\n this.quizExercise.title !== '' &&\n this.quizExercise.title.length < 250 &&\n this.quizExercise.duration !== 0 &&\n releaseDateValidAndNotInPastCondition &&\n this.quizExercise.quizQuestions != undefined &&\n !!this.quizExercise.quizQuestions.length;\n const areAllQuestionsValid = this.quizExercise.quizQuestions?.every(function (question) {\n if (question.points == undefined || question.points < 1) {\n return false;\n }\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE) {\n const mcQuestion = question as MultipleChoiceQuestion;\n if (mcQuestion.answerOptions!.some((answerOption) => answerOption.isCorrect)) {\n return question.title && question.title !== '' && question.title.length < 250;\n }\n } else if (question.type === QuizQuestionType.DRAG_AND_DROP) {\n const dndQuestion = question as DragAndDropQuestion;\n return (\n question.title &&\n question.title !== '' &&\n question.title.length < 250 &&\n dndQuestion.correctMappings &&\n dndQuestion.correctMappings.length > 0 &&\n this.dragAndDropQuestionUtil.solve(dndQuestion).length &&\n this.dragAndDropQuestionUtil.validateNoMisleadingCorrectMapping(dndQuestion)\n );\n } else if (question.type === QuizQuestionType.SHORT_ANSWER) {\n const shortAnswerQuestion = question as ShortAnswerQuestion;\n return (\n question.title &&\n question.title !== '' &&\n shortAnswerQuestion.correctMappings &&\n shortAnswerQuestion.correctMappings.length > 0 &&\n this.shortAnswerQuestionUtil.validateNoMisleadingShortAnswerMapping(shortAnswerQuestion) &&\n this.shortAnswerQuestionUtil.everySpotHasASolution(shortAnswerQuestion.correctMappings, shortAnswerQuestion.spots) &&\n this.shortAnswerQuestionUtil.everyMappedSolutionHasASpot(shortAnswerQuestion.correctMappings) &&\n shortAnswerQuestion.solutions?.filter((solution) => solution.text!.trim() === '').length === 0 &&\n !this.shortAnswerQuestionUtil.hasMappingDuplicateValues(shortAnswerQuestion.correctMappings) &&\n this.shortAnswerQuestionUtil.atLeastAsManySolutionsAsSpots(shortAnswerQuestion)\n );\n } else {\n Sentry.captureException(new Error('Unknown question type: ' + question));\n return question.title && question.title !== '';\n }\n }, this);\n\n const maxPointsReachableInQuiz = this.quizExercise.quizQuestions?.map((quizQuestion) => quizQuestion.points ?? 0).reduce((a, b) => a + b, 0);\n\n const noTestRunExists = !this.isExamMode || !this.quizExercise.testRunParticipationsExist;\n\n return (\n isGenerallyValid &&\n areAllQuestionsValid === true &&\n this.isEmpty(this.invalidFlaggedQuestions) &&\n maxPointsReachableInQuiz !== undefined &&\n maxPointsReachableInQuiz > 0 &&\n noTestRunExists\n );\n }\n\n /**\n * Iterates through the questions is search for invalid flags. Updates {@link invalidFlaggedQuestions} accordingly.\n * Check the invalid flag of the question as well as all elements which can be set as invalid, for each quiz exercise type.\n * @param questions optional parameter, if it is not set, it iterates over the exercise questions.\n */\n checkForInvalidFlaggedQuestions(questions: QuizQuestion[] = []) {\n if (!this.quizExercise) {\n return;\n }\n if (questions.length === 0) {\n questions = this.quizExercise.quizQuestions!;\n }\n const invalidQuestions: {\n [questionId: number]: (AnswerOption | ShortAnswerSolution | ShortAnswerMapping | ShortAnswerSpot | DropLocation | DragItem | DragAndDropMapping)[] | undefined;\n } = {};\n questions.forEach(function (question) {\n const invalidQuestion = question.invalid;\n const invalidElements: (AnswerOption | ShortAnswerSolution | ShortAnswerMapping | ShortAnswerSpot | DropLocation | DragItem | DragAndDropMapping)[] = [];\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE && (<MultipleChoiceQuestion>question).answerOptions !== undefined) {\n (<MultipleChoiceQuestion>question).answerOptions!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n } else if (question.type === QuizQuestionType.DRAG_AND_DROP) {\n if ((<DragAndDropQuestion>question).dragItems !== undefined) {\n (<DragAndDropQuestion>question).dragItems!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n if ((<DragAndDropQuestion>question).correctMappings !== undefined) {\n (<DragAndDropQuestion>question).correctMappings!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n if ((<DragAndDropQuestion>question).dropLocations !== undefined) {\n (<DragAndDropQuestion>question).dropLocations!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n } else {\n if ((<ShortAnswerQuestion>question).solutions !== undefined) {\n (<ShortAnswerQuestion>question).solutions!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n if ((<ShortAnswerQuestion>question).correctMappings !== undefined) {\n (<ShortAnswerQuestion>question).correctMappings!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n if ((<ShortAnswerQuestion>question).spots !== undefined) {\n (<ShortAnswerQuestion>question).spots!.forEach(function (option) {\n if (option.invalid) {\n invalidElements.push(option);\n }\n });\n }\n }\n if (invalidQuestion || invalidElements.length !== 0) {\n invalidQuestions[question.title!] = invalidElements.length !== 0 ? { invalidElements } : {};\n }\n });\n this.invalidFlaggedQuestions = invalidQuestions;\n }\n\n /**\n * Get the reasons, why the quiz needs warnings\n * @returns {Array} array of objects with fields 'translateKey' and 'translateValues'\n */\n computeInvalidWarnings(): Warning[] {\n const invalidWarnings = !this.quizExercise\n ? []\n : this.quizExercise.quizQuestions\n ?.map((question, index) => {\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE && (<MultipleChoiceQuestion>question).answerOptions!.some((option) => !option.explanation)) {\n return {\n translateKey: 'artemisApp.quizExercise.invalidReasons.explanationIsMissing',\n translateValues: { index: index + 1 },\n };\n }\n })\n .filter(Boolean);\n\n return invalidWarnings as Warning[];\n }\n\n /**\n * Get the reasons, why the quiz is invalid\n * @returns {Array} array of objects with fields 'translateKey' and 'translateValues'\n */\n computeInvalidReasons(): Reason[] {\n const invalidReasons = new Array<Reason>();\n if (!this.quizExercise) {\n return [];\n }\n\n if (!this.quizExercise.title || this.quizExercise.title === '') {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.quizTitle',\n translateValues: {},\n });\n }\n if (this.quizExercise.title!.length >= 250) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.quizTitleLength',\n translateValues: {},\n });\n }\n if (!this.quizExercise.duration) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.quizDuration',\n translateValues: {},\n });\n }\n if (!this.quizExercise.quizQuestions || this.quizExercise.quizQuestions.length === 0) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.noQuestion',\n translateValues: {},\n });\n }\n if (this.isExamMode && this.quizExercise.testRunParticipationsExist) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.edit.testRunSubmissionsExist',\n translateValues: {},\n });\n }\n\n /** We only verify the releaseDate if the checkbox is activated **/\n if (this.quizExercise.isPlannedToStart) {\n if (!this.quizExercise.releaseDate || !moment(this.quizExercise.releaseDate).isValid()) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.invalidStartTime',\n translateValues: {},\n });\n }\n // Release Date valid but lies in the past\n if (this.quizExercise.releaseDate && moment(this.quizExercise.releaseDate).isValid()) {\n if (moment(this.quizExercise.releaseDate).isBefore(moment())) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.startTimeInPast',\n translateValues: {},\n });\n }\n }\n }\n this.quizExercise.quizQuestions!.forEach(function (question: QuizQuestion, index: number) {\n if (!question.title || question.title === '') {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionTitle',\n translateValues: { index: index + 1 },\n });\n }\n if (question.points == undefined || question.points < 1) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionScore',\n translateValues: { index: index + 1 },\n });\n }\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE) {\n const mcQuestion = question as MultipleChoiceQuestion;\n if (!mcQuestion.answerOptions!.some((answerOption) => answerOption.isCorrect)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionCorrectAnswerOption',\n translateValues: { index: index + 1 },\n });\n }\n if (!mcQuestion.answerOptions!.every((answerOption) => answerOption.explanation !== '')) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.explanationIsMissing',\n translateValues: { index: index + 1 },\n });\n }\n }\n if (question.title && question.title.length >= 250) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionTitleLength',\n translateValues: { index: index + 1 },\n });\n }\n\n if (question.type === QuizQuestionType.DRAG_AND_DROP) {\n const dndQuestion = question as DragAndDropQuestion;\n if (!dndQuestion.correctMappings || dndQuestion.correctMappings.length === 0) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionCorrectMapping',\n translateValues: { index: index + 1 },\n });\n } else if (this.dragAndDropQuestionUtil.solve(dndQuestion, []).length === 0) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionUnsolvable',\n translateValues: { index: index + 1 },\n });\n }\n if (!this.dragAndDropQuestionUtil.validateNoMisleadingCorrectMapping(dndQuestion)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.misleadingCorrectMapping',\n translateValues: { index: index + 1 },\n });\n }\n }\n if (question.type === QuizQuestionType.SHORT_ANSWER) {\n const shortAnswerQuestion = question as ShortAnswerQuestion;\n if (!shortAnswerQuestion.correctMappings || shortAnswerQuestion.correctMappings.length === 0) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionCorrectMapping',\n translateValues: { index: index + 1 },\n });\n }\n if (!this.shortAnswerQuestionUtil.validateNoMisleadingShortAnswerMapping(shortAnswerQuestion)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.misleadingCorrectMapping',\n translateValues: { index: index + 1 },\n });\n }\n if (!this.shortAnswerQuestionUtil.everySpotHasASolution(shortAnswerQuestion.correctMappings, shortAnswerQuestion.spots)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.shortAnswerQuestionEverySpotHasASolution',\n translateValues: { index: index + 1 },\n });\n }\n if (!this.shortAnswerQuestionUtil.everyMappedSolutionHasASpot(shortAnswerQuestion.correctMappings)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.shortAnswerQuestionEveryMappedSolutionHasASpot',\n translateValues: { index: index + 1 },\n });\n }\n if (!(shortAnswerQuestion.solutions?.filter((solution) => solution.text!.trim() === '').length === 0)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.shortAnswerQuestionSolutionHasNoValue',\n translateValues: { index: index + 1 },\n });\n }\n if (this.shortAnswerQuestionUtil.hasMappingDuplicateValues(shortAnswerQuestion.correctMappings)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.shortAnswerQuestionDuplicateMapping',\n translateValues: { index: index + 1 },\n });\n }\n if (!this.shortAnswerQuestionUtil.atLeastAsManySolutionsAsSpots(shortAnswerQuestion)) {\n invalidReasons.push({\n translateKey: 'artemisApp.quizExercise.invalidReasons.shortAnswerQuestionUnsolvable',\n translateValues: { index: index + 1 },\n });\n }\n }\n }, this);\n const invalidFlaggedReasons = !this.quizExercise\n ? []\n : this.quizExercise.quizQuestions\n ?.map((question, index) => {\n if (this.invalidFlaggedQuestions[question.title!]) {\n return {\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionHasInvalidFlaggedElements',\n translateValues: { index: index + 1 },\n };\n }\n })\n .filter(Boolean);\n\n return invalidReasons.concat(invalidFlaggedReasons as Reason[]);\n }\n\n /**\n * Get the reasons, why the quiz is invalid as an HTML string\n * @return {string} the reasons in HTML\n */\n invalidReasonsHTML(): string {\n const translate = this.translateService;\n let reasonString = '';\n for (const reason of this.computeInvalidReasons()) {\n translate.get(reason['translateKey'], reason['translateValues']).subscribe((res: string) => {\n reasonString += res + ' - ';\n });\n }\n return reasonString.substr(0, reasonString.length - 5);\n }\n\n /**\n * Move file reader creation to separate function to be able to mock\n * https://fromanegg.com/post/2015/04/22/easy-testing-of-code-involving-native-methods-in-javascript/\n */\n generateFileReader() {\n return new FileReader();\n }\n\n onFileLoadImport(fileReader: FileReader) {\n try {\n // Read the file and get list of questions from the file\n const questions = JSON.parse(fileReader.result as string) as QuizQuestion[];\n this.verifyAndImportQuestions(questions);\n // Clearing html elements,\n this.importFile = undefined;\n this.importFileName = '';\n const control = document.getElementById('importFileInput') as HTMLInputElement;\n if (control) {\n control.value = '';\n }\n } catch (e) {\n alert('Import Quiz Failed! Invalid quiz file.');\n }\n }\n\n /**\n * Imports a json quiz file and adds questions to current quiz exercise.\n */\n async importQuiz() {\n if (!this.importFile) {\n return;\n }\n const fileReader = this.generateFileReader();\n fileReader.onload = () => this.onFileLoadImport(fileReader);\n fileReader.readAsText(this.importFile);\n this.cacheValidation();\n }\n\n /**\n * Calls {@link checkForInvalidFlaggedQuestions} to verify whether any question or its elements have the invalid flag set.\n * If this is the case, the user is notified using the {@link QuizConfirmImportInvalidQuestionsModalComponent} modal.\n * If the user accepts importing the questions with invalid flags, all these flags are reset. See {@link addQuestions}.\n * @param questions the question which are being imported.\n */\n verifyAndImportQuestions(questions: QuizQuestion[]) {\n this.checkForInvalidFlaggedQuestions(questions);\n if (!this.isEmpty(this.invalidFlaggedQuestions)) {\n const modal = this.modalService.open(QuizConfirmImportInvalidQuestionsModalComponent, { keyboard: true, size: 'lg' });\n modal.componentInstance.invalidFlaggedQuestions = questions\n .map((question, index) => {\n if (this.invalidFlaggedQuestions[question.title!]) {\n return {\n translateKey: 'artemisApp.quizExercise.invalidReasons.questionHasInvalidFlaggedElements',\n translateValues: { index: index + 1 },\n };\n }\n })\n .filter(Boolean);\n\n modal.componentInstance.shouldImport.subscribe(() => {\n this.addQuestions(questions);\n // Reset the invalid flagged questions\n this.invalidFlaggedQuestions = {};\n });\n } else {\n this.addQuestions(questions);\n }\n }\n\n /**\n * Adds given questions to current quiz exercise.\n * Ids are removed from new questions so that new id is assigned upon saving the quiz exercise.\n * Caution: All \"invalid\" flags are also removed.\n * Images are duplicated for drag and drop questions.\n * @param questions list of questions\n */\n async addQuestions(questions: QuizQuestion[]) {\n // To make sure all questions are duplicated (new resources are created), we need to remove some fields from the input questions,\n // This contains removing all ids, duplicating images in case of dnd questions, the question statistic and the exercise\n for (const question of questions) {\n // do not set question.exercise = this.quizExercise, because it will cause a cycle when converting to json\n question.exercise = undefined;\n question.quizQuestionStatistic = undefined;\n question.invalid = false;\n question.id = undefined;\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE) {\n const mcQuestion = question as MultipleChoiceQuestion;\n mcQuestion.answerOptions!.forEach((answerOption) => {\n answerOption.id = undefined;\n answerOption.invalid = false;\n });\n } else if (question.type === QuizQuestionType.DRAG_AND_DROP) {\n const dndQuestion = question as DragAndDropQuestion;\n // Get image from the old question and duplicate it on the server and then save new image to the question,\n let fileUploadResponse = await this.fileUploaderService.duplicateFile(dndQuestion.backgroundFilePath!);\n dndQuestion.backgroundFilePath = fileUploadResponse.path;\n\n // For DropLocations, DragItems and CorrectMappings we need to provide tempID,\n // This tempID is used for keep tracking of mappings by server. The server removes tempID and generated a new id,\n dndQuestion.dropLocations!.forEach((dropLocation) => {\n dropLocation.tempID = dropLocation.id;\n dropLocation.id = undefined;\n dropLocation.invalid = false;\n });\n for (const dragItem of dndQuestion.dragItems || []) {\n // Duplicating image on server. This is only valid for image drag items. For text drag items, pictureFilePath is undefined,\n if (dragItem.pictureFilePath) {\n fileUploadResponse = await this.fileUploaderService.duplicateFile(dragItem.pictureFilePath);\n dragItem.pictureFilePath = fileUploadResponse.path;\n }\n dragItem.tempID = dragItem.id;\n dragItem.id = undefined;\n dragItem.invalid = false;\n }\n for (const correctMapping of dndQuestion.correctMappings || []) {\n // Following fields are not required for dnd question. They will be generated by the server,\n correctMapping.id = undefined;\n correctMapping.dragItemIndex = undefined;\n correctMapping.dropLocationIndex = undefined;\n correctMapping.invalid = false;\n\n // Duplicating image on server. This is only valid for image drag items. For text drag items, pictureFilePath is undefined,\n const correctMappingDragItem = correctMapping.dragItem!;\n if (correctMappingDragItem.pictureFilePath) {\n fileUploadResponse = await this.fileUploaderService.duplicateFile(correctMappingDragItem.pictureFilePath);\n correctMappingDragItem.pictureFilePath = fileUploadResponse.path;\n }\n correctMappingDragItem.tempID = correctMappingDragItem?.id;\n correctMapping.dragItem!.id = undefined;\n correctMapping.dropLocation!.tempID = correctMapping.dropLocation!.id;\n correctMapping.dropLocation!.id = undefined;\n }\n } else if (question.type === QuizQuestionType.SHORT_ANSWER) {\n const shortAnswerQuestion = question as ShortAnswerQuestion;\n\n // For Spots, Solutions and CorrectMappings we need to provide tempID,\n // This tempID is used for keep tracking of mappings by server. The server removes tempID and generated a new id,\n shortAnswerQuestion.spots!.forEach((spot) => {\n spot.tempID = spot.id;\n spot.id = undefined;\n spot.invalid = false;\n });\n shortAnswerQuestion.solutions!.forEach((solution) => {\n solution.tempID = solution.id;\n solution.id = undefined;\n solution.invalid = false;\n });\n shortAnswerQuestion.correctMappings!.forEach((correctMapping) => {\n // Following fields are not required for short answer question. They will be generated by the server,\n correctMapping.id = undefined;\n correctMapping.shortAnswerSolutionIndex = undefined;\n correctMapping.shortAnswerSpotIndex = undefined;\n correctMapping.invalid = false;\n\n correctMapping.solution!.tempID = correctMapping.solution!.id;\n correctMapping.solution!.id = undefined;\n correctMapping.spot!.tempID = correctMapping.spot!.id;\n correctMapping.spot!.id = undefined;\n });\n }\n this.quizExercise.quizQuestions = this.quizExercise.quizQuestions!.concat([question]);\n }\n }\n\n /**\n * triggers the parsing of the editor content in the designated edit component\n */\n parseAllQuestions(): void {\n const editQuestionComponents: QuizQuestionEdit[] = [\n ...this.editMultipleChoiceQuestionComponents.toArray(),\n ...this.editDragAndDropQuestionComponents.toArray(),\n ...this.editShortAnswerQuestionComponents.toArray(),\n ];\n editQuestionComponents.forEach((component) => component.prepareForSave());\n }\n\n /**\n * Save the quiz to the server and invoke callback functions depending of result\n */\n save(): void {\n if (this.hasSavedQuizStarted || !this.pendingChangesCache || !this.quizIsValid) {\n return;\n }\n\n Exercise.sanitize(this.quizExercise);\n\n this.isSaving = true;\n this.parseAllQuestions();\n if (this.quizExercise.id !== undefined) {\n const requestOptions = {} as any;\n if (this.notificationText) {\n requestOptions.notificationText = this.notificationText;\n }\n this.quizExerciseService.update(this.quizExercise, requestOptions).subscribe(\n (quizExerciseResponse: HttpResponse<QuizExercise>) => {\n this.notificationText = undefined;\n if (quizExerciseResponse.body) {\n this.onSaveSuccess(quizExerciseResponse.body);\n } else {\n this.onSaveError();\n }\n },\n () => this.onSaveError(),\n );\n } else {\n this.quizExerciseService.create(this.quizExercise).subscribe(\n (quizExerciseResponse: HttpResponse<QuizExercise>) => {\n if (quizExerciseResponse.body) {\n this.onSaveSuccess(quizExerciseResponse.body);\n } else {\n this.onSaveError();\n }\n },\n () => this.onSaveError(),\n );\n }\n }\n\n /**\n * Callback function for when the save succeeds\n * Terminates the saving process and assign the returned quizExercise to the local entities\n * @param {QuizExercise} quizExercise: Saved quizExercise entity\n */\n private onSaveSuccess(quizExercise: QuizExercise): void {\n this.isSaving = false;\n this.pendingChangesCache = false;\n this.prepareEntity(quizExercise);\n this.savedEntity = cloneDeep(quizExercise);\n this.quizExercise = quizExercise;\n this.changeDetector.detectChanges();\n }\n\n /**\n * Callback function for when the save fails\n */\n private onSaveError = (): void => {\n console.error('Saving Quiz Failed! Please try again later.');\n this.jhiAlertService.error('artemisApp.quizExercise.saveError');\n this.isSaving = false;\n this.changeDetector.detectChanges();\n };\n\n /**\n * Makes sure the entity is well formed and its fields are of the correct types\n * @param quizExercise {QuizExercise} exercise which will be prepared\n */\n prepareEntity(quizExercise: QuizExercise): void {\n if (this.isExamMode) {\n quizExercise.releaseDate = moment(quizExercise.releaseDate);\n } else {\n quizExercise.releaseDate = quizExercise.releaseDate ? moment(quizExercise.releaseDate) : moment();\n quizExercise.duration = Number(quizExercise.duration);\n quizExercise.duration = isNaN(quizExercise.duration) ? 10 : quizExercise.duration;\n }\n }\n\n /**\n * Reach to changes of duration inputs by updating model and ui\n */\n onDurationChange(): void {\n if (!this.isExamMode) {\n const duration = moment.duration(this.duration);\n this.quizExercise.duration = Math.min(Math.max(duration.asSeconds(), 0), 10 * 60 * 60);\n this.updateDuration();\n this.cacheValidation();\n } else if (this.quizExercise.releaseDate && this.quizExercise.dueDate) {\n const duration = moment(this.quizExercise.dueDate).diff(this.quizExercise.releaseDate, 's');\n this.quizExercise.duration = Math.round(duration);\n this.updateDuration();\n this.cacheValidation();\n }\n }\n\n /**\n * Update ui to current value of duration\n */\n updateDuration(): void {\n const duration = moment.duration(this.quizExercise.duration, 'seconds');\n this.changeDetector.detectChanges();\n // when input fields are empty do not update their values\n if (this.duration.minutes !== undefined) {\n this.duration.minutes = 60 * duration.hours() + duration.minutes();\n }\n if (this.duration.seconds !== undefined) {\n this.duration.seconds = duration.seconds();\n }\n }\n\n /**\n * Update adding existing questions from a file or course or exam\n */\n setExistingQuestionSourceToCourse(): void {\n this.showExistingQuestionsFromCourse = true;\n this.showExistingQuestionsFromExam = false;\n this.showExistingQuestionsFromFile = false;\n this.updateSelectionAndView();\n }\n\n /**\n * Update adding existing questions from an exam\n */\n setExistingQuestionSourceToExam(): void {\n this.showExistingQuestionsFromCourse = false;\n this.showExistingQuestionsFromExam = true;\n this.showExistingQuestionsFromFile = false;\n this.updateSelectionAndView();\n }\n\n /**\n * Update adding existing questions from a file\n */\n setExistingQuestionSourceToFile(): void {\n this.showExistingQuestionsFromCourse = false;\n this.showExistingQuestionsFromExam = false;\n this.showExistingQuestionsFromFile = true;\n this.updateSelectionAndView();\n }\n\n private updateSelectionAndView() {\n this.selectedCourseId = undefined;\n this.selectedExamId = undefined;\n this.allExistingQuestions = this.existingQuestions = [];\n this.importFile = undefined;\n this.importFileName = '';\n const control = document.getElementById('importFileInput') as HTMLInputElement;\n if (control) {\n control.value = '';\n }\n this.changeDetector.detectChanges();\n }\n\n /**\n * Navigate back\n */\n cancel(): void {\n if (!this.isExamMode) {\n this.router.navigate(['/course-management', this.quizExercise.course!.id, 'quiz-exercises']);\n } else {\n this.router.navigate(['/course-management', this.courseId, 'exams', this.examId, 'exercise-groups']);\n }\n }\n\n /**\n * Check if the saved quiz has started\n * @return {boolean} true if the saved quiz has started, otherwise false\n */\n get hasSavedQuizStarted(): boolean {\n return !!(this.savedEntity && this.savedEntity.isPlannedToStart && moment(this.savedEntity.releaseDate!).isBefore(moment()));\n }\n\n /**\n * check if Dictionary is empty\n * @param obj the dictionary to be checked\n */\n private isEmpty(obj: {}) {\n return Object.keys(obj).length === 0;\n }\n\n includedInOverallScoreChange(includedInOverallScore: IncludedInOverallScore) {\n this.quizExercise.includedInOverallScore = includedInOverallScore;\n this.cacheValidation();\n }\n}\n" }, { "alpha_fraction": 0.6856217980384827, "alphanum_fraction": 0.6856217980384827, "avg_line_length": 41, "blob_id": "a458be44859bf8eff4f14d980dfc34f1e9603fe0", "content_id": "61a1933459b9722421862862ba27ac458680dc95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4326, "license_type": "permissive", "max_line_length": 175, "num_lines": 103, "path": "/src/main/webapp/app/overview/student-questions/student-question-answer/student-question-answer.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport * as moment from 'moment';\nimport { map } from 'rxjs/operators';\n\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\n\ntype EntityResponseType = HttpResponse<StudentQuestionAnswer>;\ntype EntityArrayResponseType = HttpResponse<StudentQuestionAnswer[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class StudentQuestionAnswerService {\n public resourceUrl = SERVER_API_URL + 'api/courses/';\n\n constructor(protected http: HttpClient) {}\n\n /**\n * create studentQuestionAnswer\n * @param {number} courseId\n * @param {StudentQuestionAnswer} studentQuestionAnswer\n * @return {Observable<EntityResponseType>}\n */\n create(courseId: number, studentQuestionAnswer: StudentQuestionAnswer): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(studentQuestionAnswer);\n return this.http\n .post<StudentQuestionAnswer>(`${this.resourceUrl}${courseId}/student-question-answers`, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * update studentQuestionAnswer\n * @param {number} courseId\n * @param {StudentQuestionAnswer} studentQuestionAnswer\n * @return {Observable<EntityResponseType>}\n */\n update(courseId: number, studentQuestionAnswer: StudentQuestionAnswer): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(studentQuestionAnswer);\n return this.http\n .put<StudentQuestionAnswer>(`${this.resourceUrl}${courseId}/student-question-answers`, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * find studentQuestionAnswer by id\n * @param {number} courseId\n * @param {number} id\n * @return {Observable<EntityResponseType>}\n */\n find(courseId: number, id: number): Observable<EntityResponseType> {\n return this.http\n .get<StudentQuestionAnswer>(`${this.resourceUrl}${courseId}/student-question-answers/${id}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * delete studentQuestionAnswer by id\n * @param {number} courseId\n * @param {number} id\n * @return {Observable<HttpResponse<any>>}\n */\n delete(courseId: number, id: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}${courseId}/student-question-answers/${id}`, { observe: 'response' });\n }\n\n /**\n * Takes a studentQuestionAnswer and converts the date from the client\n * @param {StudentQuestionAnswer} studentQuestionAnswer\n * @return {StudentQuestionAnswer}\n */\n protected convertDateFromClient(studentQuestionAnswer: StudentQuestionAnswer): StudentQuestionAnswer {\n return Object.assign({}, studentQuestionAnswer, {\n answerDate: studentQuestionAnswer.answerDate && moment(studentQuestionAnswer.answerDate).isValid() ? moment(studentQuestionAnswer.answerDate).toJSON() : undefined,\n });\n }\n\n /**\n * Takes a studentQuestionAnswer and converts the date from the server\n * @param {EntityResponseType} res\n * @return {StudentQuestionAnswer}\n */\n protected convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.answerDate = res.body.answerDate ? moment(res.body.answerDate) : undefined;\n }\n return res;\n }\n\n /**\n * Takes an array of studentQuestionAnswers and converts the date from the server\n * @param {EntityArrayResponseType} res\n * @return {EntityArrayResponseType}\n */\n protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((studentQuestionAnswer: StudentQuestionAnswer) => {\n studentQuestionAnswer.answerDate = studentQuestionAnswer.answerDate ? moment(studentQuestionAnswer.answerDate) : undefined;\n });\n }\n return res;\n }\n}\n" }, { "alpha_fraction": 0.6280193328857422, "alphanum_fraction": 0.6280193328857422, "avg_line_length": 22, "blob_id": "a6ab59421a8923d3abd7a8793f095f5ac24d0ca2", "content_id": "860f1d076d8aaffff8f418c4a0133b0c9e312105", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 207, "license_type": "permissive", "max_line_length": 84, "num_lines": 9, "path": "/src/main/webapp/app/exercises/text/participate/franc.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export enum FrancLanguage {\n ENGLISH = 'eng',\n GERMAN = 'deu',\n UNDEFINED = 'und',\n}\n\nexport interface Franc {\n all(text: string, options?: { only: FrancLanguage[] }): [FrancLanguage, number];\n}\n" }, { "alpha_fraction": 0.5737330317497253, "alphanum_fraction": 0.5737330317497253, "avg_line_length": 42, "blob_id": "804b4422788b34638065adbaa8e6a40681875261", "content_id": "63a38873c3822ef4f5fdb4a6da9083c37acaf96e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7439, "license_type": "permissive", "max_line_length": 141, "num_lines": 173, "path": "/src/main/webapp/app/course/manage/course-management.route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router';\nimport { UserRouteAccessService } from 'app/core/auth/user-route-access-service';\nimport { Observable, of } from 'rxjs';\nimport { filter, map } from 'rxjs/operators';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from './course-management.service';\nimport { CourseManagementComponent } from './course-management.component';\nimport { CourseDetailComponent } from './course-detail.component';\nimport { CourseUpdateComponent } from './course-update.component';\nimport { CourseManagementExercisesComponent } from './course-management-exercises.component';\nimport { CourseGroupComponent } from 'app/course/manage/course-group.component';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { RatingListComponent } from 'app/exercises/shared/rating/rating-list/rating-list.component';\nimport { LearningGoalManagementComponent } from 'app/course/learning-goals/learning-goal-management/learning-goal-management.component';\nimport { CreateLearningGoalComponent } from 'app/course/learning-goals/create-learning-goal/create-learning-goal.component';\nimport { EditLearningGoalComponent } from 'app/course/learning-goals/edit-learning-goal/edit-learning-goal.component';\nimport { CourseParticipantScoresComponent } from 'app/course/course-participant-scores/course-participant-scores.component';\nimport { CourseManagementStatisticsComponent } from './course-management-statistics.component';\n\n@Injectable({ providedIn: 'root' })\nexport class CourseResolve implements Resolve<Course> {\n constructor(private service: CourseManagementService) {}\n\n /**\n * Resolves the route by extracting the courseId and returns the course with that Id if it exists\n * and creates a new course otherwise\n * @param route - contains the information about the route to be resolved\n */\n resolve(route: ActivatedRouteSnapshot): Observable<Course> {\n if (route.params['courseId']) {\n return this.service.find(route.params['courseId']).pipe(\n filter((response: HttpResponse<Course>) => response.ok),\n map((course: HttpResponse<Course>) => course.body!),\n );\n }\n return of(new Course());\n }\n}\n\nexport const courseManagementState: Routes = [\n {\n path: '',\n component: CourseManagementComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.course.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'new',\n component: CourseUpdateComponent,\n data: {\n authorities: [Authority.ADMIN],\n pageTitle: 'global.generic.create',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId',\n component: CourseDetailComponent,\n resolve: {\n course: CourseResolve,\n },\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.course.home.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':courseId/participant-scores',\n component: CourseParticipantScoresComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.participantScores.pageTitle',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n // Create a new path without a component defined to prevent resolver caching and the CourseDetailComponent from being always rendered\n path: ':courseId',\n resolve: {\n course: CourseResolve,\n },\n children: [\n {\n path: 'exercises',\n component: CourseManagementExercisesComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.TA, Authority.ADMIN],\n pageTitle: 'artemisApp.course.exercises',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'course-statistics',\n component: CourseManagementStatisticsComponent,\n data: {\n authorities: [Authority.TA, Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.courseStatistics.statistics',\n breadcrumbLabelVariable: '',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'edit',\n component: CourseUpdateComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.course.home.editLabel',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'groups/:courseGroup',\n component: CourseGroupComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'userManagement.groups',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'ratings',\n component: RatingListComponent,\n data: {\n authorities: [Authority.INSTRUCTOR, Authority.ADMIN],\n pageTitle: 'artemisApp.ratingList.pageTitle',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: 'goal-management',\n component: LearningGoalManagementComponent,\n data: {\n authorities: ['ROLE_ADMIN', 'ROLE_INSTRUCTOR'],\n pageTitle: 'artemisApp.learningGoal.manageLearningGoals.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n // Create a new path without a component defined to prevent the LearningGoalManagementComponent from being always rendered\n path: 'goal-management',\n data: {\n pageTitle: 'artemisApp.learningGoal.manageLearningGoals.title',\n },\n children: [\n {\n path: 'create',\n component: CreateLearningGoalComponent,\n data: {\n authorities: ['ROLE_ADMIN', 'ROLE_INSTRUCTOR'],\n pageTitle: 'artemisApp.learningGoal.createLearningGoal.title',\n },\n canActivate: [UserRouteAccessService],\n },\n {\n path: ':learningGoalId/edit',\n component: EditLearningGoalComponent,\n data: {\n authorities: ['ROLE_ADMIN', 'ROLE_INSTRUCTOR'],\n pageTitle: 'artemisApp.learningGoal.editLearningGoal.title',\n },\n canActivate: [UserRouteAccessService],\n },\n ],\n },\n ],\n },\n];\n" }, { "alpha_fraction": 0.6848198771476746, "alphanum_fraction": 0.6864869594573975, "avg_line_length": 46.77433776855469, "blob_id": "5e19dd89a6d96f3171a56782f67b309e5e766e8a", "content_id": "3ffed79f34f61b19866a6596485fa3831d34c19a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10797, "license_type": "permissive", "max_line_length": 360, "num_lines": 226, "path": "/src/main/java/de/tum/in/www1/artemis/repository/FeedbackRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static de.tum.in.www1.artemis.config.Constants.FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS;\nimport static java.util.stream.Collectors.*;\n\nimport java.util.*;\nimport java.util.function.Predicate;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.FeedbackType;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.domain.enumeration.StaticCodeAnalysisTool;\nimport de.tum.in.www1.artemis.service.dto.StaticCodeAnalysisReportDTO;\n\n/**\n * Spring Data JPA repository for the Feedback entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface FeedbackRepository extends JpaRepository<Feedback, Long> {\n\n String DEFAULT_FILEPATH = \"notAvailable\";\n\n Pattern JVM_RESULT_MESSAGE_MATCHER = prepareJVMResultMessageMatcher(\n List.of(\"java.lang.AssertionError\", \"org.opentest4j.AssertionFailedError\", \"de.tum.in.test.api.util.UnexpectedExceptionError\"));\n\n Predicate<String> IS_NOT_STACK_TRACE_LINE = line -> !line.startsWith(\"\\tat \");\n\n List<Feedback> findByResult(Result result);\n\n List<Feedback> findByReferenceInAndResult_Submission_Participation_Exercise(List<String> references, Exercise exercise);\n\n /**\n * Delete all feedbacks that belong to the given result\n * @param resultId the Id of the result where the feedbacks should be deleted\n */\n void deleteByResult_Id(long resultId);\n\n /**\n * Save the given feedback elements to the database in case they are not yet connected to a result\n *\n * @param feedbackList the feedback items that should be saved\n * @return all elements of the original list with the saved feedback items (i.e. the ones without result) having an id now.\n */\n default List<Feedback> saveFeedbacks(List<Feedback> feedbackList) {\n List<Feedback> updatedFeedbackList = new ArrayList<>();\n for (var feedback : feedbackList) {\n if (feedback.getResult() == null) {\n // only save feedback not yet connected to a result\n updatedFeedbackList.add(save(feedback));\n }\n else {\n updatedFeedbackList.add(feedback);\n }\n }\n return updatedFeedbackList;\n }\n\n /**\n * Find all existing Feedback Elements referencing a text block part of a TextCluster.\n *\n * @param cluster TextCluster requesting existing Feedbacks for.\n * @return Map<TextBlockId, Feedback>\n */\n default Map<String, Feedback> getFeedbackForTextExerciseInCluster(TextCluster cluster) {\n final List<String> references = cluster.getBlocks().stream().map(TextBlock::getId).collect(toList());\n final TextExercise exercise = cluster.getExercise();\n return findByReferenceInAndResult_Submission_Participation_Exercise(references, exercise).parallelStream().collect(toMap(Feedback::getReference, feedback -> feedback));\n }\n\n /**\n * Transforms static code analysis reports to feedback objects.\n * As we reuse the Feedback entity to store static code analysis findings, a mapping to those attributes\n * has to be defined, violating the first normal form.\n *\n * Mapping:\n * - text: STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER\n * - reference: Tool\n * - detailText: Issue object as JSON\n *\n * @param reports Static code analysis reports to be transformed\n * @return Feedback objects representing the static code analysis findings\n */\n default List<Feedback> createFeedbackFromStaticCodeAnalysisReports(List<StaticCodeAnalysisReportDTO> reports) {\n ObjectMapper mapper = new ObjectMapper();\n List<Feedback> feedbackList = new ArrayList<>();\n for (final var report : reports) {\n StaticCodeAnalysisTool tool = report.getTool();\n\n for (final var issue : report.getIssues()) {\n // Remove CI specific path segments\n issue.setFilePath(removeCIDirectoriesFromPath(issue.getFilePath()));\n\n Feedback feedback = new Feedback();\n feedback.setText(Feedback.STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER);\n feedback.setReference(tool.name());\n feedback.setType(FeedbackType.AUTOMATIC);\n feedback.setPositive(false);\n\n // Store static code analysis in JSON format\n try {\n feedback.setDetailText(mapper.writeValueAsString(issue));\n }\n catch (JsonProcessingException e) {\n continue;\n }\n feedbackList.add(feedback);\n }\n }\n return feedbackList;\n }\n\n /**\n * Create an automatic feedback object from a test job.\n *\n * @param testName the test case name.\n * @param testMessages a list of informational messages generated by the test job\n * @param successful if the test case was successful.\n * @param programmingLanguage the programming language of the exercise.\n * @return Feedback object for the test job\n */\n default Feedback createFeedbackFromTestCase(String testName, List<String> testMessages, boolean successful, final ProgrammingLanguage programmingLanguage) {\n Feedback feedback = new Feedback();\n feedback.setText(testName);\n\n if (!successful) {\n String errorMessageString = testMessages.stream().map(errorString -> processResultErrorMessage(programmingLanguage, errorString)).collect(Collectors.joining(\"\\n\\n\"));\n if (errorMessageString.length() > FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS) {\n errorMessageString = errorMessageString.substring(0, FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS);\n }\n feedback.setDetailText(errorMessageString);\n }\n else if (!testMessages.isEmpty()) {\n feedback.setDetailText(String.join(\"\\n\\n\", testMessages));\n }\n else {\n feedback.setDetailText(null);\n }\n\n feedback.setType(FeedbackType.AUTOMATIC);\n feedback.setPositive(successful);\n\n return feedback;\n }\n\n /**\n * Filters and processes a feedback error message, thereby removing any unwanted strings depending on\n * the programming language, or just reformatting it to only show the most important details.\n *\n * @param programmingLanguage The programming language for which the feedback was generated\n * @param message The raw error message in the feedback\n * @return A filtered and better formatted error message\n */\n private static String processResultErrorMessage(final ProgrammingLanguage programmingLanguage, final String message) {\n final String timeoutDetailText = \"The test case execution timed out. This indicates issues in your code such as endless for / while loops or issues with recursion. Please carefully review your code to avoid such issues. In case you are absolutely sure that there are no issues like this, please contact your instructor to check the setup of the test.\";\n final String exceptionPrefix = \"Exception message: \";\n // Overwrite timeout exception messages for Junit4, Junit5 and other\n List<String> exceptions = Arrays.asList(\"org.junit.runners.model.TestTimedOutException\", \"java.util.concurrent.TimeoutException\",\n \"org.awaitility.core.ConditionTimeoutException\", \"Timed?OutException\");\n // Defining two pattern groups, (1) the exception name and (2) the exception text\n Pattern findTimeoutPattern = Pattern.compile(\"^.*(\" + String.join(\"|\", exceptions) + \"):?(.*)\");\n Matcher matcher = findTimeoutPattern.matcher(message);\n if (matcher.find()) {\n String exceptionText = matcher.group(2);\n return timeoutDetailText + \"\\n\" + exceptionPrefix + exceptionText.trim();\n }\n // Defining one pattern group, (1) the exception text\n Pattern findGeneralTimeoutPattern = Pattern.compile(\"^.*:(.*timed out after.*)\", Pattern.CASE_INSENSITIVE);\n matcher = findGeneralTimeoutPattern.matcher(message);\n if (matcher.find()) {\n // overwrite AJTS: TimeoutException\n String generalTimeOutExceptionText = matcher.group(1);\n return timeoutDetailText + \"\\n\" + exceptionPrefix + generalTimeOutExceptionText.trim();\n }\n\n // Filter out unneeded Exception classnames\n if (programmingLanguage == ProgrammingLanguage.JAVA || programmingLanguage == ProgrammingLanguage.KOTLIN) {\n String messageWithoutStackTrace = message.lines().takeWhile(IS_NOT_STACK_TRACE_LINE).collect(Collectors.joining(\"\\n\")).trim();\n return JVM_RESULT_MESSAGE_MATCHER.matcher(messageWithoutStackTrace).replaceAll(\"\");\n }\n\n return message;\n }\n\n /**\n * Builds the regex used in {@link #processResultErrorMessage(ProgrammingLanguage, String)} on results from JVM languages.\n *\n * @param jvmExceptionsToFilter Exceptions at the start of lines that should be filtered out in the processing step\n * @return A regex that can be used to process result messages\n */\n private static Pattern prepareJVMResultMessageMatcher(List<String> jvmExceptionsToFilter) {\n // Replace all \".\" with \"\\\\.\" and join with regex alternative symbol \"|\"\n String assertionRegex = jvmExceptionsToFilter.stream().map(s -> s.replaceAll(\"\\\\.\", \"\\\\\\\\.\")).reduce(\"\", (a, b) -> String.join(\"|\", a, b));\n // Match any of the exceptions at the start of the line and with \": \" after it\n String pattern = String.format(\"^(?:%s): \\n*\", assertionRegex);\n\n return Pattern.compile(pattern, Pattern.MULTILINE);\n }\n\n /**\n * Removes CI specific path segments. Uses the assignment directory to decide where to cut the path.\n *\n * @param sourcePath Path to be shortened\n * @return Shortened path if it contains an assignment directory, otherwise the full path\n */\n private String removeCIDirectoriesFromPath(String sourcePath) {\n if (sourcePath == null || sourcePath.isEmpty()) {\n return DEFAULT_FILEPATH;\n }\n int workingDirectoryStart = sourcePath.indexOf(Constants.ASSIGNMENT_DIRECTORY);\n if (workingDirectoryStart == -1) {\n return sourcePath;\n }\n return sourcePath.substring(workingDirectoryStart + Constants.ASSIGNMENT_DIRECTORY.length());\n }\n}\n" }, { "alpha_fraction": 0.7697670459747314, "alphanum_fraction": 0.7759451270103455, "avg_line_length": 54.134376525878906, "blob_id": "c0a1c1d71aca4730d03b3d4da614b8b1a5c930d7", "content_id": "4898fd40a861214021975b05ec1e99b967b33116", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 17643, "license_type": "permissive", "max_line_length": 175, "num_lines": 320, "path": "/src/test/java/de/tum/in/www1/artemis/service/ProgrammingExerciseScheduleServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.*;\n\nimport java.net.URISyntaxException;\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.Set;\n\nimport org.eclipse.jgit.lib.ObjectId;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.params.ParameterizedTest;\nimport org.junit.jupiter.params.provider.ValueSource;\nimport org.mockito.Mockito;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.connector.bitbucket.BitbucketRequestMockProvider;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.VcsRepositoryUrl;\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\nimport de.tum.in.www1.artemis.domain.enumeration.Visibility;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseTestCaseRepository;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageReceiveService;\nimport de.tum.in.www1.artemis.util.TimeService;\n\nclass ProgrammingExerciseScheduleServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private InstanceMessageReceiveService instanceMessageReceiveService;\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n @Autowired\n private ProgrammingExerciseTestCaseRepository programmingExerciseTestCaseRepository;\n\n @Autowired\n private TimeService timeService;\n\n @Autowired\n private BitbucketRequestMockProvider bitbucketRequestMockProvider;\n\n private ProgrammingExercise programmingExercise;\n\n // When the scheduler is invoked, there is a small delay until the runnable is called.\n // TODO: This could be improved by e.g. manually setting the system time instead of waiting for actual time to pass.\n private final long SCHEDULER_TASK_TRIGGER_DELAY_MS = 1500;\n\n @BeforeEach\n void init() {\n bitbucketRequestMockProvider.enableMockingOfRequests();\n doReturn(ObjectId.fromString(\"fffb09455885349da6e19d3ad7fd9c3404c5a0df\")).when(gitService).getLastCommitHash(any());\n\n database.addUsers(2, 2, 2);\n database.addCourseWithOneProgrammingExerciseAndTestCases();\n programmingExercise = programmingExerciseRepository.findAll().get(0);\n\n database.addStudentParticipationForProgrammingExercise(programmingExercise, \"student1\");\n database.addStudentParticipationForProgrammingExercise(programmingExercise, \"student2\");\n programmingExercise = programmingExerciseRepository.findAllWithEagerParticipations().get(0);\n }\n\n @AfterEach\n void tearDown() {\n database.resetDatabase();\n }\n\n private void verifyLockStudentRepositoryOperation(boolean wasCalled) {\n int callCount = wasCalled ? 1 : 0;\n Set<StudentParticipation> studentParticipations = programmingExercise.getStudentParticipations();\n for (StudentParticipation studentParticipation : studentParticipations) {\n ProgrammingExerciseStudentParticipation programmingExerciseStudentParticipation = (ProgrammingExerciseStudentParticipation) studentParticipation;\n verify(versionControlService, Mockito.times(callCount)).setRepositoryPermissionsToReadOnly(programmingExerciseStudentParticipation.getVcsRepositoryUrl(),\n programmingExercise.getProjectKey(), programmingExerciseStudentParticipation.getStudents());\n verify(versionControlService, Mockito.times(callCount)).setRepositoryPermissionsToReadOnly(programmingExerciseStudentParticipation.getVcsRepositoryUrl(),\n programmingExercise.getProjectKey(), programmingExerciseStudentParticipation.getStudents());\n }\n }\n\n private void mockStudentRepoLocks() throws URISyntaxException {\n for (final var participation : programmingExercise.getStudentParticipations()) {\n final var repositorySlug = (programmingExercise.getProjectKey() + \"-\" + participation.getParticipantIdentifier()).toLowerCase();\n bitbucketRequestMockProvider.mockSetRepositoryPermissionsToReadOnly(repositorySlug, programmingExercise.getProjectKey(), participation.getStudents());\n }\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldExecuteScheduledBuildAndTestAfterDueDate() throws Exception {\n mockStudentRepoLocks();\n long delayMS = 1000;\n final var dueDateDelayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plus(dueDateDelayMS / 2, ChronoUnit.MILLIS));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(dueDateDelayMS)));\n programmingExerciseRepository.save(programmingExercise);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(delayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n // Lock student repository must be called once per participation.\n verifyLockStudentRepositoryOperation(true);\n // Instructor build should have been triggered.\n verify(programmingSubmissionService, Mockito.times(1)).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotExecuteScheduledIfBuildAndTestAfterDueDateHasPassed() throws Exception {\n programmingExercise.setDueDate(ZonedDateTime.now().minusHours(1L));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().minusHours(1L));\n programmingExerciseRepository.save(programmingExercise);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n // Lock student repository must be called once per participation.\n verifyLockStudentRepositoryOperation(false);\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotExecuteScheduledIfBuildAndTestAfterDueDateIsNull() throws Exception {\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n // Lock student repository must be called once per participation.\n verifyLockStudentRepositoryOperation(false);\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n // Update all scores should not have been triggered.\n verify(programmingExerciseGradingService, never()).updateAllResults(programmingExercise);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotExecuteScheduledTwiceIfSameExercise() throws Exception {\n mockStudentRepoLocks();\n long delayMS = 200; // 200 ms.\n programmingExercise.setDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS / 2)));\n // Setting it the first time.\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS)));\n programmingExercise = programmingExerciseRepository.save(programmingExercise);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n // Setting it the second time.\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS * 2)));\n programmingExercise = programmingExerciseRepository.save(programmingExercise);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(delayMS * 2 + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n // Lock student repository must be called once per participation.\n verifyLockStudentRepositoryOperation(true);\n verify(programmingSubmissionService, Mockito.times(1)).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotExecuteScheduledIfBuildAndTestAfterDueDateChangesToNull() throws Exception {\n long delayMS = 200;\n // Setting it the first time.\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS)));\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n // Now setting the date to null - this must also clear the old scheduled task!\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(null);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(delayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n verifyLockStudentRepositoryOperation(false);\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n verify(programmingExerciseGradingService, never()).updateAllResults(programmingExercise);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldScheduleExercisesWithBuildAndTestDateInFuture() throws Exception {\n mockStudentRepoLocks();\n long delayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS / 2)));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS)));\n programmingExerciseRepository.save(programmingExercise);\n\n database.addCourseWithOneProgrammingExercise();\n ProgrammingExercise programmingExercise2 = programmingExerciseRepository.findAll().get(1);\n programmingExercise2.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().minusHours(1));\n programmingExerciseRepository.save(programmingExercise2);\n\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(delayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n verifyLockStudentRepositoryOperation(true);\n verify(programmingSubmissionService, Mockito.times(1)).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldScheduleExercisesWithManualAssessment() throws Exception {\n mockStudentRepoLocks();\n long delayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(delayMS / 2)));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(null);\n programmingExercise.setAssessmentType(AssessmentType.SEMI_AUTOMATIC);\n programmingExerciseRepository.save(programmingExercise);\n\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(delayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n // Only lock participations\n verifyLockStudentRepositoryOperation(true);\n // but do not build all\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldUpdateScoresIfHasTestsAfterDueDateAndNoBuildAfterDueDate() throws Exception {\n mockStudentRepoLocks();\n final var dueDateDelayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plus(dueDateDelayMS / 2, ChronoUnit.MILLIS));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(null);\n programmingExerciseRepository.save(programmingExercise);\n var testCases = programmingExerciseTestCaseRepository.findByExerciseId(programmingExercise.getId());\n testCases.stream().findFirst().get().setVisibility(Visibility.AFTER_DUE_DATE);\n programmingExerciseTestCaseRepository.saveAll(testCases);\n\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(dueDateDelayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n verifyLockStudentRepositoryOperation(true);\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n // has AFTER_DUE_DATE tests and no additional build after due date => update the scores to show those test cases in it\n verify(programmingExerciseGradingService, Mockito.times(1)).updateAllResults(programmingExercise);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotUpdateScoresIfHasTestsAfterDueDateAndBuildAfterDueDate() throws Exception {\n mockStudentRepoLocks();\n final var dueDateDelayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plus(dueDateDelayMS / 2, ChronoUnit.MILLIS));\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(dueDateDelayMS)));\n programmingExerciseRepository.save(programmingExercise);\n var testCases = programmingExerciseTestCaseRepository.findByExerciseId(programmingExercise.getId());\n testCases.stream().findFirst().get().setVisibility(Visibility.AFTER_DUE_DATE);\n programmingExerciseTestCaseRepository.saveAll(testCases);\n\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(dueDateDelayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n verifyLockStudentRepositoryOperation(true);\n verify(programmingSubmissionService, Mockito.times(1)).triggerInstructorBuildForExercise(programmingExercise.getId());\n // has AFTER_DUE_DATE tests, but also buildAfterDueDate => do not update results, but use the results created on additional build run\n verify(programmingExerciseGradingService, never()).updateAllResults(programmingExercise);\n }\n\n @ParameterizedTest(name = \"{displayName} [{index}] {argumentsWithNames}\")\n @ValueSource(booleans = { true, false })\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n void shouldNotUpdateScoresIfHasNoTestsAfterDueDate(boolean hasBuildAndTestAfterDueDate) throws Exception {\n mockStudentRepoLocks();\n final var dueDateDelayMS = 200;\n programmingExercise.setDueDate(ZonedDateTime.now().plus(dueDateDelayMS / 2, ChronoUnit.MILLIS));\n if (hasBuildAndTestAfterDueDate) {\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(ZonedDateTime.now().plusNanos(timeService.milliSecondsToNanoSeconds(dueDateDelayMS)));\n }\n else {\n programmingExercise.setBuildAndTestStudentSubmissionsAfterDueDate(null);\n }\n programmingExerciseRepository.save(programmingExercise);\n var testCases = programmingExerciseTestCaseRepository.findByExerciseId(programmingExercise.getId());\n testCases.forEach(testCase -> testCase.setVisibility(Visibility.ALWAYS));\n programmingExerciseTestCaseRepository.saveAll(testCases);\n\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(dueDateDelayMS + SCHEDULER_TASK_TRIGGER_DELAY_MS);\n\n verifyLockStudentRepositoryOperation(true);\n if (hasBuildAndTestAfterDueDate) {\n verify(programmingSubmissionService, Mockito.times(1)).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n else {\n verify(programmingSubmissionService, never()).triggerInstructorBuildForExercise(programmingExercise.getId());\n }\n // no tests marked as AFTER_DUE_DATE => do not update scores on due date\n verify(programmingExerciseGradingService, never()).updateAllResults(programmingExercise);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCombineTemplateBeforeRelease() throws Exception {\n ProgrammingExercise programmingExerciseWithTemplate = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationElseThrow(programmingExercise.getId());\n VcsRepositoryUrl repositoryUrl = programmingExerciseWithTemplate.getVcsTemplateRepositoryUrl();\n doNothing().when(gitService).combineAllCommitsOfRepositoryIntoOne(repositoryUrl);\n\n programmingExercise.releaseDate(ZonedDateTime.now().plusSeconds(Constants.SECONDS_BEFORE_RELEASE_DATE_FOR_COMBINING_TEMPLATE_COMMITS + 1));\n programmingExerciseRepository.save(programmingExercise);\n instanceMessageReceiveService.processScheduleProgrammingExercise(programmingExercise.getId());\n\n Thread.sleep(1500);\n\n verify(gitService, times(1)).combineAllCommitsOfRepositoryIntoOne(repositoryUrl);\n }\n}\n" }, { "alpha_fraction": 0.6858168840408325, "alphanum_fraction": 0.6881251335144043, "avg_line_length": 40.04210662841797, "blob_id": "d35de746b7adea898e7e4ff79b5bc0c080178da3", "content_id": "9ed40a6dc895b88a2bdc3737f629467872506a1d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3899, "license_type": "permissive", "max_line_length": 140, "num_lines": 95, "path": "/src/main/webapp/app/course/course-questions/course-questions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { StudentQuestionService } from 'app/overview/student-questions/student-question/student-question.service';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { Moment } from 'moment';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { Lecture } from 'app/entities/lecture.model';\n\nexport type StudentQuestionForOverview = {\n id: number;\n questionText?: string;\n creationDate?: Moment;\n votes: number;\n answers: number;\n approvedAnswers: number;\n exerciseOrLectureId: number;\n exerciseOrLectureTitle: string;\n belongsToExercise: boolean;\n exercise: Exercise;\n lecture: Lecture;\n};\n\n@Component({\n selector: 'jhi-course-questions',\n styles: ['.question-cell { max-width: 40vw; max-height: 120px; overflow: auto;}'],\n templateUrl: './course-questions.component.html',\n})\nexport class CourseQuestionsComponent implements OnInit {\n courseId: number;\n studentQuestions: StudentQuestionForOverview[];\n studentQuestionsToDisplay: StudentQuestionForOverview[];\n\n showQuestionsWithApprovedAnswers = false;\n\n predicate = 'id';\n reverse = true;\n\n constructor(private route: ActivatedRoute, private studentQuestionsService: StudentQuestionService, private sortService: SortService) {}\n\n /**\n * On init fetch the course and the studentQuestions\n * convert studentQuestions to StudentQuestionForOverview type to allow sorting by all displayed fields\n */\n ngOnInit() {\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n this.studentQuestionsService.findQuestionsForCourse(this.courseId).subscribe((res) => {\n this.studentQuestions = res.body!.map((question) => ({\n id: question.id!,\n questionText: question.questionText!,\n creationDate: question.creationDate!,\n answers: question.answers ? question.answers!.length : 0,\n approvedAnswers: this.getNumberOfApprovedAnswers(question),\n votes: question.votes!,\n exerciseOrLectureId: question.exercise ? question.exercise!.id! : question.lecture!.id!,\n exerciseOrLectureTitle: question.exercise ? question.exercise!.title! : question.lecture!.title!,\n belongsToExercise: !!question.exercise,\n exercise: question.exercise!,\n lecture: question.lecture!,\n }));\n this.studentQuestionsToDisplay = this.studentQuestions.filter((question) => question.approvedAnswers === 0);\n });\n }\n\n /**\n * returns the number of approved answers for a question\n * @param { StudentQuestion }studentQuestion\n */\n getNumberOfApprovedAnswers(studentQuestion: StudentQuestion): number {\n return studentQuestion.answers ? studentQuestion.answers.filter((question) => question.tutorApproved).length : 0;\n }\n\n sortRows() {\n this.sortService.sortByProperty(this.studentQuestionsToDisplay, this.predicate, this.reverse);\n }\n\n /**\n * removes all questions with approved answers from questions to display\n */\n hideQuestionsWithApprovedAnswers(): void {\n this.studentQuestionsToDisplay = this.studentQuestions.filter((question) => question.approvedAnswers === 0);\n }\n\n /**\n * toggles showing questions with approved answers and sets the questions to display\n */\n toggleHideQuestions(): void {\n if (!this.showQuestionsWithApprovedAnswers) {\n this.studentQuestionsToDisplay = this.studentQuestions;\n } else {\n this.hideQuestionsWithApprovedAnswers();\n }\n this.showQuestionsWithApprovedAnswers = !this.showQuestionsWithApprovedAnswers;\n }\n}\n" }, { "alpha_fraction": 0.7815884351730347, "alphanum_fraction": 0.7855997085571289, "avg_line_length": 52.6129035949707, "blob_id": "5a7367cf667f5fc8abe67ed38a7a0a00509b38c9", "content_id": "047ff8a14d9355cc47550a9a67a6419fbcda1823", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4986, "license_type": "permissive", "max_line_length": 178, "num_lines": 93, "path": "/src/test/java/de/tum/in/www1/artemis/programmingexercise/ProgrammingExerciseTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.programmingexercise;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.web.rest.ProgrammingExerciseResource;\n\nclass ProgrammingExerciseTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n private Long programmingExerciseId;\n\n @BeforeEach\n void init() {\n database.addUsers(2, 2, 2);\n database.addCourseWithOneProgrammingExercise();\n programmingExerciseId = programmingExerciseRepository.findAll().get(0).getId();\n }\n\n @AfterEach\n void tearDown() {\n database.resetDatabase();\n }\n\n void updateProgrammingExercise(ProgrammingExercise programmingExercise, String newProblem, String newTitle) throws Exception {\n bambooRequestMockProvider.enableMockingOfRequests();\n bitbucketRequestMockProvider.enableMockingOfRequests();\n programmingExercise.setProblemStatement(newProblem);\n programmingExercise.setTitle(newTitle);\n\n bambooRequestMockProvider.mockBuildPlanExists(programmingExercise.getTemplateBuildPlanId(), true, false);\n bambooRequestMockProvider.mockBuildPlanExists(programmingExercise.getSolutionBuildPlanId(), true, false);\n bitbucketRequestMockProvider.mockRepositoryUrlIsValid(programmingExercise.getVcsTemplateRepositoryUrl(), programmingExercise.getProjectKey(), true);\n bitbucketRequestMockProvider.mockRepositoryUrlIsValid(programmingExercise.getVcsSolutionRepositoryUrl(), programmingExercise.getProjectKey(), true);\n\n ProgrammingExercise updatedProgrammingExercise = request.putWithResponseBody(\"/api/programming-exercises\", programmingExercise, ProgrammingExercise.class, HttpStatus.OK);\n\n // The result from the put response should be updated with the new data.\n assertThat(updatedProgrammingExercise.getProblemStatement()).isEqualTo(newProblem);\n assertThat(updatedProgrammingExercise.getTitle()).isEqualTo(newTitle);\n\n // There should still be only 1 programming exercise.\n assertThat(programmingExerciseRepository.count()).isEqualTo(1);\n // The programming exercise in the db should also be updated.\n ProgrammingExercise programmingExerciseFromDb = programmingExerciseRepository\n .findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExercise.getId()).get();\n assertThat(programmingExerciseFromDb.getProblemStatement()).isEqualTo(newProblem);\n assertThat(programmingExerciseFromDb.getTitle()).isEqualTo(newTitle);\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n void updateProgrammingExerciseOnce() throws Exception {\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId)\n .get();\n updateProgrammingExercise(programmingExercise, \"new problem 1\", \"new title 1\");\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n void updateProgrammingExerciseTwice() throws Exception {\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId)\n .get();\n updateProgrammingExercise(programmingExercise, \"new problem 1\", \"new title 1\");\n updateProgrammingExercise(programmingExercise, \"new problem 2\", \"new title 2\");\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n void updateProblemStatement() throws Exception {\n final var newProblem = \"a new problem statement\";\n final var endpoint = \"/api\" + ProgrammingExerciseResource.Endpoints.PROBLEM.replace(\"{exerciseId}\", String.valueOf(programmingExerciseId));\n ProgrammingExercise updatedProgrammingExercise = request.patchWithResponseBody(endpoint, newProblem, ProgrammingExercise.class, HttpStatus.OK, MediaType.TEXT_PLAIN);\n\n assertThat(updatedProgrammingExercise.getProblemStatement()).isEqualTo(newProblem);\n\n ProgrammingExercise fromDb = programmingExerciseRepository.findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExerciseId).get();\n assertThat(fromDb.getProblemStatement()).isEqualTo(newProblem);\n }\n\n}\n" }, { "alpha_fraction": 0.680080235004425, "alphanum_fraction": 0.6813338398933411, "avg_line_length": 40.11855697631836, "blob_id": "88a9969fd36a102178d4128db45949a0fbdb8e38", "content_id": "9238d1c0d59fcdc7f3d16c199bf6596f8bf30202", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7977, "license_type": "permissive", "max_line_length": 179, "num_lines": 194, "path": "/src/main/java/de/tum/in/www1/artemis/service/SubmissionExportService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.nio.file.Paths;\nimport java.time.ZonedDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport javax.annotation.Nullable;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.Submission;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.ExerciseRepository;\nimport de.tum.in.www1.artemis.web.rest.dto.SubmissionExportOptionsDTO;\n\n@Service\npublic abstract class SubmissionExportService {\n\n private final Logger log = LoggerFactory.getLogger(SubmissionExportService.class);\n\n private final ExerciseRepository exerciseRepository;\n\n private final ZipFileService zipFileService;\n\n private final FileService fileService;\n\n public SubmissionExportService(ExerciseRepository exerciseRepository, ZipFileService zipFileService, FileService fileService) {\n this.exerciseRepository = exerciseRepository;\n this.zipFileService = zipFileService;\n this.fileService = fileService;\n }\n\n @Value(\"${artemis.submission-export-path}\")\n private String submissionExportPath;\n\n /**\n * Exports student submissions to a zip file for an exercise\n * @param exerciseId the id of the exercise to be exported\n * @param submissionExportOptions the options for the export\n * @return a reference to the zipped file\n * @throws IOException if an error occurred while zipping\n */\n public Optional<File> exportStudentSubmissions(Long exerciseId, SubmissionExportOptionsDTO submissionExportOptions) throws IOException {\n\n Optional<Exercise> exerciseOpt = exerciseRepository.findWithEagerStudentParticipationsStudentAndSubmissionsById(exerciseId);\n\n if (exerciseOpt.isEmpty()) {\n return Optional.empty();\n }\n\n Exercise exercise = exerciseOpt.get();\n\n // Select the participations that should be exported\n List<StudentParticipation> exportedStudentParticipations;\n\n if (submissionExportOptions.isExportAllParticipants()) {\n exportedStudentParticipations = new ArrayList<>(exercise.getStudentParticipations());\n }\n else {\n List<String> participantIds = Arrays.stream(submissionExportOptions.getParticipantIdentifierList().split(\",\")).map(String::trim).collect(Collectors.toList());\n\n exportedStudentParticipations = exercise.getStudentParticipations().stream().filter(participation -> participantIds.contains(participation.getParticipantIdentifier()))\n .collect(Collectors.toList());\n }\n\n if (exportedStudentParticipations.isEmpty()) {\n return Optional.empty();\n }\n\n ZonedDateTime filterLateSubmissionsDate = null;\n if (submissionExportOptions.isFilterLateSubmissions()) {\n if (submissionExportOptions.getFilterLateSubmissionsDate() == null) {\n filterLateSubmissionsDate = exercise.getDueDate();\n }\n else {\n filterLateSubmissionsDate = submissionExportOptions.getFilterLateSubmissionsDate();\n }\n }\n\n return this.createZipFileFromParticipations(exercise, exportedStudentParticipations, filterLateSubmissionsDate);\n\n }\n\n /**\n * Creates a zip file from a list of participations for an exercise\n * @param exercise the exercise in question\n * @param participations a list of participations to include\n * @param lateSubmissionFilter an optional date filter for submissions\n * @return the zipped file\n * @throws IOException if an error occurred while zipping\n */\n private Optional<File> createZipFileFromParticipations(Exercise exercise, List<StudentParticipation> participations, @Nullable ZonedDateTime lateSubmissionFilter)\n throws IOException {\n\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n\n String zipGroupName = course.getShortName() + \"-\" + exercise.getTitle() + \"-\" + exercise.getId();\n String zipFileName = zipGroupName + \"-\" + ZonedDateTime.now().format(DateTimeFormatter.ofPattern(\"yyyyMMdd-Hmss\")) + \".zip\";\n\n Path submissionsFolderPath = Paths.get(submissionExportPath, \"zippedSubmissions\", zipGroupName);\n Path zipFilePath = Paths.get(submissionExportPath, \"zippedSubmissions\", zipFileName);\n\n File submissionFolder = submissionsFolderPath.toFile();\n if (!submissionFolder.exists() && !submissionFolder.mkdirs()) {\n log.error(\"Couldn't create dir: {}\", submissionFolder);\n return Optional.empty();\n }\n\n // Save all Submissions\n List<Path> submissionFilePaths = participations.stream().map((participation) -> {\n\n Set<Submission> submissions = participation.getSubmissions();\n Submission latestSubmission = null;\n\n for (Submission submission : submissions) {\n if (submission.getSubmissionDate() == null) {\n // ignore unsubmitted submissions\n continue;\n }\n if (lateSubmissionFilter == null || submission.getSubmissionDate().isBefore(lateSubmissionFilter)) {\n if (latestSubmission == null || submission.getSubmissionDate().isAfter(latestSubmission.getSubmissionDate())) {\n latestSubmission = submission;\n }\n }\n }\n\n if (latestSubmission == null) {\n return Optional.<Path>empty();\n }\n\n String submissionFileName = exercise.getTitle() + \"-\" + participation.getParticipantIdentifier() + \"-\" + latestSubmission.getId()\n + this.getFileEndingForSubmission(latestSubmission);\n Path submissionFilePath = Paths.get(submissionsFolderPath.toString(), submissionFileName);\n\n try {\n this.saveSubmissionToFile(exercise, latestSubmission, submissionFilePath.toFile());\n return Optional.of(submissionFilePath);\n }\n catch (IOException ioException) {\n log.error(\"Could not create file {} for exporting: {}\", submissionFilePath.toString(), ioException.getMessage());\n return Optional.<Path>empty();\n }\n\n }).filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());\n\n if (submissionFilePaths.isEmpty()) {\n return Optional.empty();\n }\n\n try {\n zipFileService.createZipFile(zipFilePath, submissionFilePaths, submissionsFolderPath);\n }\n finally {\n deleteTempFiles(submissionFilePaths);\n }\n\n fileService.scheduleForDeletion(zipFilePath, 5);\n\n return Optional.of(zipFilePath.toFile());\n }\n\n protected abstract void saveSubmissionToFile(Exercise exercise, Submission submission, File file) throws IOException;\n\n protected abstract String getFileEndingForSubmission(Submission submission);\n\n /**\n * Delete all temporary files created during export\n *\n * @param pathsToTempFiles A list of all paths to temporary files, that should be deleted\n */\n private void deleteTempFiles(List<Path> pathsToTempFiles) {\n log.debug(\"Delete all temporary files\");\n // delete the temporary zipped repo files\n for (Path tempFile : pathsToTempFiles) {\n try {\n Files.delete(tempFile);\n }\n catch (Exception ex) {\n log.warn(\"Could not delete file {}. Error message: {}\", tempFile, ex.getMessage());\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6388518214225769, "alphanum_fraction": 0.648197591304779, "avg_line_length": 30.87234115600586, "blob_id": "96e5f55bcb8e15f3e5298e0bebc442084966db28", "content_id": "36509821b859df2365030c14b3d5f1f1d5ac33c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1498, "license_type": "permissive", "max_line_length": 89, "num_lines": 47, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-complaint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { EntityResponseType, IComplaintService } from 'app/complaints/complaint.service';\nimport { User } from 'app/core/user/user.model';\nimport { Result } from 'app/entities/result.model';\nimport { Observable, of } from 'rxjs';\nimport { Complaint, ComplaintType } from 'app/entities/complaint.model';\n\nexport const MockComplaintResponse: any = {\n body: {\n complaintType: ComplaintType.COMPLAINT,\n accepted: undefined,\n complaintText: 'I think my answer was better than 2',\n id: 123,\n result: new Result(),\n resultBeforeComplaint: '',\n student: new User(),\n },\n};\n\nexport const MockComplaintResponse2: any = {\n body: {\n complaintType: ComplaintType.MORE_FEEDBACK,\n accepted: true,\n complaintText: 'I think my answer was better than 2',\n id: 111,\n result: new Result(),\n resultBeforeComplaint: '',\n student: new User(),\n },\n};\n\nexport class MockComplaintService implements IComplaintService {\n create(complaint: Complaint): Observable<EntityResponseType> {\n return of();\n }\n find(id: number): Observable<EntityResponseType> {\n return of();\n }\n findByResultId(resultId: number): Observable<EntityResponseType> {\n if (resultId === 111) {\n return of(MockComplaintResponse2);\n }\n return of(MockComplaintResponse);\n }\n getNumberOfAllowedComplaintsInCourse(courseId: number): Observable<number> {\n return of(3);\n }\n}\n" }, { "alpha_fraction": 0.5804196000099182, "alphanum_fraction": 0.5909090638160706, "avg_line_length": 94.33333587646484, "blob_id": "6db2651712ad73ef2d14b14774ad14023e4706b2", "content_id": "3a7f8572abdb3233e12ca59462f99b7806ddb613", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 286, "license_type": "permissive", "max_line_length": 176, "num_lines": 3, "path": "/src/main/webapp/app/utils/text.utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export const escapeString = (input: string): string => input.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/'/g, '&#039;');\n\nexport const convertToHtmlLinebreaks = (input: string): string => input.replace(/(?:\\r\\n|\\r|\\n)/g, '<br>');\n" }, { "alpha_fraction": 0.6115916967391968, "alphanum_fraction": 0.6185120940208435, "avg_line_length": 27.19512176513672, "blob_id": "d42adbce8eef828e8f1908bd68fb7e2ae787a861", "content_id": "5e515500a99be18cdec5a60b6b97153569f063f3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1156, "license_type": "permissive", "max_line_length": 70, "num_lines": 41, "path": "/src/main/webapp/app/shared/dashboards/tutor-participation-graph/progress-bar/progress-bar.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\n\n@Component({\n selector: 'jhi-progress-bar',\n templateUrl: './progress-bar.component.html',\n})\nexport class ProgressBarComponent implements OnInit {\n @Input() public tooltip: string;\n @Input() public percentage: number;\n @Input() public numerator: number;\n @Input() public denominator: number;\n\n ngOnInit() {\n this.percentage = Math.round(this.percentage);\n }\n\n /**\n * Function to render the correct progress bar class\n * @param percentage The completed percentage of the progress bar\n */\n calculateProgressBarClass(percentage: number): string {\n if (percentage < 50) {\n return 'bg-danger';\n } else if (percentage < 100) {\n return 'bg-warning';\n }\n\n return 'bg-success';\n }\n\n /**\n * Function to change the text color to indicate a finished status\n * @param percentage The completed percentage of the progress bar\n */\n chooseProgressBarTextColor(percentage: number) {\n if (percentage < 100) {\n return 'text-dark';\n }\n return 'text-white';\n }\n}\n" }, { "alpha_fraction": 0.7437185645103455, "alphanum_fraction": 0.7437185645103455, "avg_line_length": 35.181819915771484, "blob_id": "fa513a5869f7f17daacd1ca97c59c9d35be7ab5d", "content_id": "cb12ecb36cda4fa97bc6f2060b030141c75fe3ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 398, "license_type": "permissive", "max_line_length": 118, "num_lines": 11, "path": "/src/main/webapp/app/entities/modeling-submission.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Submission, SubmissionExerciseType } from 'app/entities/submission.model';\n\nexport class ModelingSubmission extends Submission {\n public model?: string;\n public explanationText?: string;\n public optimal?: boolean; // used by compass to determine whether a submission leads to the most learning possible\n\n constructor() {\n super(SubmissionExerciseType.MODELING);\n }\n}\n" }, { "alpha_fraction": 0.6613546013832092, "alphanum_fraction": 0.662350594997406, "avg_line_length": 20.826086044311523, "blob_id": "9f8d4ac4e82e7049578bd17f4782e2fd9a39c792", "content_id": "4edda91da867841b1b952ef850c1f739e2ea2fa8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1004, "license_type": "permissive", "max_line_length": 93, "num_lines": 46, "path": "/src/main/java/de/tum/in/www1/artemis/domain/LtiUserId.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n/**\n * A LtiUserId.\n */\n@Entity\n@Table(name = \"lti_user_id\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class LtiUserId extends DomainObject {\n\n @Column(name = \"lti_user_id\")\n private String ltiUserId;\n\n @OneToOne\n @JoinColumn(unique = true)\n private User user;\n\n public String getLtiUserId() {\n return ltiUserId;\n }\n\n public void setLtiUserId(String ltiUserId) {\n this.ltiUserId = ltiUserId;\n }\n\n public User getUser() {\n return user;\n }\n\n public void setUser(User user) {\n this.user = user;\n }\n\n @Override\n public String toString() {\n return \"LtiUserId{\" + \"id=\" + getId() + \", ltiUserId='\" + getLtiUserId() + \"'\" + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.7123602628707886, "alphanum_fraction": 0.7143326997756958, "avg_line_length": 27.16666603088379, "blob_id": "1f8eb94331c1d4f226804f69c5a159ee06aec825", "content_id": "dd43daaa2f367184ab128a5e126aa3f1c5164106", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3042, "license_type": "permissive", "max_line_length": 103, "num_lines": 108, "path": "/src/main/webapp/app/exam/exam-scores/exam-score-dtos.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class ExamScoreDTO {\n public examId: number;\n public title: string;\n public maxPoints: number;\n public averagePointsAchieved: number;\n public exerciseGroups: ExerciseGroup[];\n public studentResults: StudentResult[];\n\n constructor() {}\n}\n\nexport class ExerciseGroup {\n public id: number;\n public title: string;\n public maxPoints: number;\n public numberOfParticipants: number;\n public containedExercises: ExerciseInfo[];\n\n constructor() {}\n}\n\nexport class ExerciseInfo {\n public exerciseId: number;\n public title: string;\n public maxPoints: number;\n public numberOfParticipants: number;\n\n constructor() {}\n}\n\nexport class StudentResult {\n public userId: number;\n public name: string;\n public login: string;\n public eMail: string;\n public registrationNumber: string;\n public overallPointsAchieved?: number;\n public overallScoreAchieved?: number;\n public submitted: boolean;\n public exerciseGroupIdToExerciseResult: { [key: number]: ExerciseResult };\n\n constructor() {}\n}\n\nexport class ExerciseResult {\n public exerciseId: number;\n public title: string;\n public maxScore: number;\n public achievedScore?: number;\n public achievedPoints?: number;\n public hasNonEmptySubmission: boolean;\n\n constructor() {}\n}\n\nexport class AggregatedExamResult {\n public meanPoints: number;\n public meanPointsRelative: number;\n public meanPointsTotal: number;\n public meanPointsRelativeTotal: number;\n public median: number;\n public medianRelative: number;\n public medianTotal: number;\n public medianRelativeTotal: number;\n public standardDeviation: number;\n public standardDeviationTotal: number;\n public noOfExamsFiltered = 0;\n public noOfRegisteredUsers = 0;\n\n constructor() {}\n}\n\nexport class AggregatedExerciseGroupResult {\n public exerciseGroupId: number;\n public title: string;\n public maxPoints: number;\n public totalParticipants: number;\n public noOfParticipantsWithFilter = 0;\n public totalPoints = 0;\n public averagePoints?: number;\n public averagePercentage?: number;\n public exerciseResults: AggregatedExerciseResult[] = [];\n\n constructor(exerciseGroupId: number, title: string, maxPoints: number, totalParticipants: number) {\n this.exerciseGroupId = exerciseGroupId;\n this.title = title;\n this.maxPoints = maxPoints;\n this.totalParticipants = totalParticipants;\n }\n}\n\nexport class AggregatedExerciseResult {\n public exerciseId: number;\n public title: string;\n public maxPoints: number;\n public totalParticipants: number;\n public noOfParticipantsWithFilter = 0;\n public totalPoints = 0;\n public averagePoints?: number;\n public averagePercentage?: number;\n\n constructor(exerciseId: number, title: string, maxPoints: number, totalParticipants: number) {\n this.exerciseId = exerciseId;\n this.title = title;\n this.maxPoints = maxPoints;\n this.totalParticipants = totalParticipants;\n }\n}\n" }, { "alpha_fraction": 0.7607192397117615, "alphanum_fraction": 0.7634854912757874, "avg_line_length": 41.52941131591797, "blob_id": "2c67a3b688b5b2a5a9fc2934a67d9e7e97a5689d", "content_id": "e14b7bc1a52ec555bc2e53a5cbd4b4eaa060f4c8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1446, "license_type": "permissive", "max_line_length": 149, "num_lines": 34, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ProgrammingExerciseTestCaseRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.Set;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExerciseTestCase;\n\n/**\n * Spring Data repository for the ProgrammingExerciseTestCase entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ProgrammingExerciseTestCaseRepository extends JpaRepository<ProgrammingExerciseTestCase, Long> {\n\n Set<ProgrammingExerciseTestCase> findByExerciseId(Long exerciseId);\n\n Set<ProgrammingExerciseTestCase> findByExerciseIdAndActive(Long exerciseId, Boolean active);\n\n /**\n * Returns the number of test cases marked as {@link de.tum.in.www1.artemis.domain.enumeration.Visibility#AFTER_DUE_DATE} for the given exercise.\n * @param exerciseId the exercise which test cases should be considered.\n * @return the number of test cases marked as {@link de.tum.in.www1.artemis.domain.enumeration.Visibility#AFTER_DUE_DATE}.\n */\n @Query(\"\"\"\n SELECT COUNT (DISTINCT testCase) FROM ProgrammingExerciseTestCase testCase\n WHERE testCase.exercise.id = :#{#exerciseId}\n AND testCase.visibility = 'AFTER_DUE_DATE'\n \"\"\")\n long countAfterDueDateByExerciseId(@Param(\"exerciseId\") Long exerciseId);\n}\n" }, { "alpha_fraction": 0.7345783114433289, "alphanum_fraction": 0.7361676692962646, "avg_line_length": 37.71923065185547, "blob_id": "c581da6934c499ef45c65fe67a34029f58bb116f", "content_id": "fe44fef76caf952c2a63cd1865866110167d980b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10067, "license_type": "permissive", "max_line_length": 116, "num_lines": 260, "path": "/src/test/java/de/tum/in/www1/artemis/authentication/UserJenkinsGitlabIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.authentication;\n\nimport java.io.IOException;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\nimport org.springframework.test.util.ReflectionTestUtils;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationJenkinsGitlabTest;\nimport de.tum.in.www1.artemis.service.connectors.gitlab.GitLabUserManagementService;\nimport de.tum.in.www1.artemis.service.connectors.jenkins.JenkinsUserManagementService;\nimport de.tum.in.www1.artemis.util.UserTestService;\nimport de.tum.in.www1.artemis.web.rest.vm.ManagedUserVM;\n\npublic class UserJenkinsGitlabIntegrationTest extends AbstractSpringIntegrationJenkinsGitlabTest {\n\n @Value(\"${artemis.continuous-integration.user}\")\n private String jenkinsAdminUsername;\n\n @Value(\"${jenkins.use-pseudonyms:#{false}}\")\n private boolean usePseudonymsJenkins;\n\n @Value(\"${gitlab.use-pseudonyms:#{false}}\")\n private boolean usePseudonymsGitlab;\n\n @Autowired\n private UserTestService userTestService;\n\n @Autowired\n private JenkinsUserManagementService jenkinsUserManagementService;\n\n @Autowired\n private GitLabUserManagementService gitLabUserManagementService;\n\n @BeforeEach\n public void setUp() throws Exception {\n userTestService.setup(this);\n gitlabRequestMockProvider.enableMockingOfRequests();\n jenkinsRequestMockProvider.enableMockingOfRequests(jenkinsServer);\n }\n\n @AfterEach\n public void teardown() throws IOException {\n userTestService.tearDown();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void updateUser_asAdmin_isSuccessful() throws Exception {\n userTestService.updateUser_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void updateUser_withNullPassword_oldPasswordNotChanged() throws Exception {\n userTestService.updateUser_withNullPassword_oldPasswordNotChanged();\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateUser_asInstructor_forbidden() throws Exception {\n request.put(\"/api/users\", new ManagedUserVM(userTestService.getStudent()), HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(value = \"tutor1\", roles = \"TA\")\n public void updateUser_asTutor_forbidden() throws Exception {\n request.put(\"/api/users\", new ManagedUserVM(userTestService.getStudent()), HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUserWithPseudonymsIsSuccessful() throws Exception {\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"usePseudonyms\", true);\n ReflectionTestUtils.setField(gitLabUserManagementService, \"usePseudonyms\", true);\n userTestService.createUser_asAdmin_isSuccessful();\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"usePseudonyms\", usePseudonymsJenkins);\n ReflectionTestUtils.setField(gitLabUserManagementService, \"usePseudonyms\", usePseudonymsGitlab);\n\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createAdminUserSkippedInJenkins() throws Exception {\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", \"batman\");\n userTestService.createUser_asAdmin_isSuccessful();\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", jenkinsAdminUsername);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void deleteAdminUserSkippedInJenkins() throws Exception {\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", \"student1\");\n userTestService.deleteUser_isSuccessful();\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", jenkinsAdminUsername);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void updateAdminUserSkippedInJenkins() throws Exception {\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", \"student1\");\n userTestService.updateUser_asAdmin_isSuccessful();\n ReflectionTestUtils.setField(jenkinsUserManagementService, \"jenkinsAdminUsername\", jenkinsAdminUsername);\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_isSuccessful() throws Exception {\n userTestService.createUser_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_existsInCi_internalError() throws Exception {\n userTestService.createUser_asAdmin_existsInCi_internalError();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_illegalLogin_internalError() throws Exception {\n userTestService.createUser_asAdmin_illegalLogin_internalError();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_failInExternalUserManagement_internalError() throws Exception {\n userTestService.createUser_asAdmin_failInExternalCiUserManagement_internalError();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_failInExternalCiUserManagement_cannotGetCiUser_internalError() throws Exception {\n userTestService.createUser_asAdmin_failInExternalCiUserManagement_cannotGetCiUser_internalError();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_asAdmin_failInExternalVcsUserManagement_internalError() throws Exception {\n userTestService.createUser_asAdmin_failInExternalVcsUserManagement_internalError();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUser_withNullAsPassword_generatesRandomPassword() throws Exception {\n userTestService.createUser_withNullAsPassword_generatesRandomPassword();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void deleteUser_isSuccessful() throws Exception {\n userTestService.deleteUser_isSuccessful();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void deleteUser_doesntExistInUserManagement_isSuccessful() throws Exception {\n userTestService.deleteUser_doesntExistInUserManagement_isSuccessful();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void deleteUser_FailsInExternalCiUserManagement_isNotSuccessful() throws Exception {\n userTestService.deleteUser_FailsInExternalCiUserManagement_isNotSuccessful();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void deleteUser_FailsInExternalVcsUserManagement_isNotSuccessful() throws Exception {\n userTestService.deleteUser_FailsInExternalVcsUserManagement_isNotSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void getUsers_asAdmin_isSuccessful() throws Exception {\n userTestService.getUsers_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void searchUsers_asInstructor_isSuccessful() throws Exception {\n userTestService.searchUsers_asInstructor_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void searchUsers_asAdmin_badRequest() throws Exception {\n userTestService.searchUsers_asAdmin_badRequest();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void searchUsers_asTutor_forbidden() throws Exception {\n userTestService.searchUsers_asTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void getUserViaFilter_asAdmin_isSuccessful() throws Exception {\n userTestService.getUserViaFilter_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void getAuthorities_asAdmin_isSuccessful() throws Exception {\n userTestService.getAuthorities_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getUsersOrAuthorities_asInstructor_forbidden() throws Exception {\n userTestService.getUsersOrAuthorities_asInstructor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void getUsersOrAuthorities_asTutor_forbidden() throws Exception {\n userTestService.getUsersOrAuthorities_asTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getUsersOrAuthorities_asStudent_forbidden() throws Exception {\n userTestService.getUsersOrAuthorities_asStudent_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void getUser_asAdmin_isSuccessful() throws Exception {\n userTestService.getUser_asAdmin_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void updateUserNotificationDate_asStudent_isSuccessful() throws Exception {\n userTestService.updateUserNotificationDate_asStudent_isSuccessful();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void createUserWithGroups() throws Exception {\n userTestService.createUserWithGroups();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void updateUserGroups() throws Exception {\n userTestService.updateUserGroups();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void updateUserLogin() throws Exception {\n userTestService.updateUserLogin();\n }\n}\n" }, { "alpha_fraction": 0.7240546941757202, "alphanum_fraction": 0.730088472366333, "avg_line_length": 62.74359130859375, "blob_id": "817af5c513d7dc499c653de1ad5a3fd2c121deb7", "content_id": "2b9265725417d4340a2ae373be1fbc9f39d95955", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 2486, "license_type": "permissive", "max_line_length": 208, "num_lines": 39, "path": "/.github/PULL_REQUEST_TEMPLATE.md", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<!-- Thanks for contributing to Artemis! Before you submit your pull request, please make sure to check the following boxes by putting an x in the [ ] (don't: [x ], [ x], do: [x]) -->\n<!-- If your pull request is not ready for review yet, create a draft pull request! -->\n\n### Checklist\n- [ ] I tested *all* changes and *all* related features with different users (student, tutor, instructor, admin) on the test server https://artemistest.ase.in.tum.de.\n- [ ] Server: I followed the [coding and design guidelines](https://artemis-platform.readthedocs.io/en/latest/dev/guidelines/server.html).\n- [ ] Server: I added multiple integration tests (Spring) related to the features (with a high test coverage)\n- [ ] Server: I added `@PreAuthorize` and check the course groups for all new REST Calls (security)\n- [ ] Server: I implemented the changes with a good performance and prevented too many database calls\n- [ ] Server: I documented the Java code using JavaDoc style.\n- [ ] Client: I followed the [coding and design guidelines](https://artemis-platform.readthedocs.io/en/latest/dev/guidelines/client.html).\n- [ ] Client: I added multiple integration tests (Jest) related to the features (with a high test coverage)\n- [ ] Client: I added `authorities` to all new routes and check the course groups for displaying navigation elements (links, buttons)\n- [ ] Client: I documented the TypeScript code using JSDoc style.\n- [ ] Client: I added multiple screenshots/screencasts of my UI changes\n- [ ] Client: I translated all the newly inserted strings into German and English\n\n### Motivation and Context\n<!-- Why is this change required? What problem does it solve? -->\n<!-- If it fixes an open issue, please link to the issue here. -->\n\n### Description\n<!-- Describe your changes in detail -->\n\n### Steps for Testing\n<!-- Please describe in detail how the reviewer can test your changes. -->\n\n1. Log in to Artemis\n2. Navigate to Course Administration\n3. ...\n\n### Test Coverage\n<!-- Please add the test coverage for all changes files here. You can see this when executing the tests locally (see build.gradle and package.json) or when looking into the corresponding Bamboo build plan -->\n<!-- * ExerciseService.java: 85% -->\n<!-- * programming-exercise.component.ts 95% -->\n\n### Screenshots\n<!-- Add screenshots to demonstrate the changes in the UI. -->\n<!-- Create a GIF file from a screen recording in a docker container https://toub.es/2017/09/11/high-quality-gif-with-ffmpeg-and-docker/ -->\n" }, { "alpha_fraction": 0.6720852255821228, "alphanum_fraction": 0.6771300435066223, "avg_line_length": 36.16666793823242, "blob_id": "32fc6dbbf9fb1d0f82508e2f646e167ad5305c54", "content_id": "9e06d3ac3774c7dbdb163bb75dc6f7201751b527", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3568, "license_type": "permissive", "max_line_length": 100, "num_lines": 96, "path": "/src/test/javascript/spec/component/overview/course-questions/course-questions.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { CourseQuestionsComponent } from 'app/course/course-questions/course-questions.component';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { StudentQuestionForOverview } from 'app/course/course-questions/course-questions.component';\nimport { User } from 'app/core/user/user.model';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseQuestionsComponent', () => {\n let component: CourseQuestionsComponent;\n let componentFixture: ComponentFixture<CourseQuestionsComponent>;\n\n const user1 = {\n id: 1,\n } as User;\n\n const user2 = {\n id: 2,\n } as User;\n\n const unApprovedStudentQuestionAnswer = {\n id: 1,\n answerDate: undefined,\n answerText: 'not approved',\n tutorApproved: false,\n author: user1,\n } as StudentQuestionAnswer;\n\n const approvedStudentQuestionAnswer = {\n id: 2,\n answerDate: undefined,\n answerText: 'approved',\n tutorApproved: true,\n author: user2,\n } as StudentQuestionAnswer;\n\n const studentQuestion = {\n id: 1,\n questionText: 'question',\n creationDate: undefined,\n answers: [unApprovedStudentQuestionAnswer, approvedStudentQuestionAnswer],\n } as StudentQuestion;\n\n const studentQuestionForOverview = {\n id: 1,\n questionText: 'question',\n creationDate: undefined,\n votes: 1,\n answers: 2,\n approvedAnswers: 1,\n exerciseOrLectureId: 1,\n exerciseOrLectureTitle: 'Test exercise',\n belongsToExercise: true,\n } as StudentQuestionForOverview;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n declarations: [CourseQuestionsComponent],\n })\n .overrideTemplate(CourseQuestionsComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(CourseQuestionsComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should count approved answers correctly', () => {\n expect(component.getNumberOfApprovedAnswers(studentQuestion)).to.deep.equal(1);\n });\n\n it('should hide questions with approved answers', () => {\n component.studentQuestions = [studentQuestionForOverview];\n component.hideQuestionsWithApprovedAnswers();\n expect(component.studentQuestionsToDisplay.length).to.deep.equal(0);\n });\n\n it('should toggle hiding questions with approved answers', () => {\n component.studentQuestions = [studentQuestionForOverview];\n expect(component.showQuestionsWithApprovedAnswers).to.be.false;\n component.toggleHideQuestions();\n expect(component.showQuestionsWithApprovedAnswers).to.be.true;\n expect(component.studentQuestionsToDisplay.length).to.deep.equal(1);\n component.toggleHideQuestions();\n expect(component.showQuestionsWithApprovedAnswers).to.be.false;\n expect(component.studentQuestionsToDisplay.length).to.deep.equal(0);\n });\n});\n" }, { "alpha_fraction": 0.6025286316871643, "alphanum_fraction": 0.6025286316871643, "avg_line_length": 35.157142639160156, "blob_id": "9d8b5fcb932e3e36caaf95928827f68fa27f12c8", "content_id": "5a3d8b38781ee17b0376bfb15020fb4c38211482", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5062, "license_type": "permissive", "max_line_length": 171, "num_lines": 140, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of, Subscription } from 'rxjs';\nimport { catchError, map, tap } from 'rxjs/operators';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ExerciseHintService } from './exercise-hint.service';\nimport { EditorMode, MarkdownEditorHeight } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport { navigateBack } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-exercise-hint-update',\n templateUrl: './exercise-hint-update.component.html',\n styleUrls: ['./exercise-hint.scss'],\n})\nexport class ExerciseHintUpdateComponent implements OnInit, OnDestroy {\n MarkdownEditorHeight = MarkdownEditorHeight;\n\n courseId: number;\n exerciseId: number;\n exerciseHint = new ExerciseHint();\n\n isSaving: boolean;\n isLoading: boolean;\n exerciseNotFound: boolean;\n paramSub: Subscription;\n\n domainCommands = [new KatexCommand()];\n editorMode = EditorMode.LATEX;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n protected jhiAlertService: JhiAlertService,\n protected exerciseHintService: ExerciseHintService,\n protected exerciseService: ExerciseService,\n ) {}\n\n /**\n * Fetches the exercise from the server and assigns it on the exercise hint\n */\n ngOnInit() {\n this.isLoading = true;\n this.paramSub = this.route.params.subscribe((params) => {\n this.courseId = params['courseId'];\n this.exerciseId = params['exerciseId'];\n this.isSaving = false;\n this.exerciseNotFound = false;\n });\n this.route.data.subscribe(({ exerciseHint }) => {\n this.exerciseHint = exerciseHint;\n // If the exercise was not yet created, load the exercise from the current route to set it as its exercise.\n if (!this.exerciseHint.id) {\n this.exerciseService\n .find(this.exerciseId)\n .pipe(\n map(({ body }) => body),\n tap((res: Exercise) => {\n this.exerciseHint.exercise = res;\n }),\n catchError((res: HttpErrorResponse) => {\n this.exerciseNotFound = true;\n this.onError(res.message);\n return of(null);\n }),\n )\n .subscribe(() => {\n this.isLoading = false;\n });\n } else {\n this.isLoading = false;\n }\n });\n }\n\n /**\n * Unsubscribes from the param subscription\n */\n ngOnDestroy(): void {\n if (this.paramSub) {\n this.paramSub.unsubscribe();\n }\n }\n\n /**\n * Setter to update the exercise hint content\n * @param newContent New value to set\n */\n updateHintContent(newContent: string) {\n this.exerciseHint.content = newContent;\n }\n\n /**\n * Navigate to the previous page when the user cancels the update process\n * Returns to the detail page if there is no previous state and we edited an existing hint\n * Returns to the overview page if there is no previous state and we created a new hint\n */\n previousState() {\n if (this.exerciseHint.id) {\n navigateBack(this.router, ['course-management', this.courseId.toString(), 'exercises', this.exerciseId.toString(), 'hints', this.exerciseHint.id!.toString()]);\n } else {\n navigateBack(this.router, ['course-management', this.courseId.toString(), 'exercises', this.exerciseId.toString(), 'hints']);\n }\n }\n\n /**\n * Saves the exercise hint by creating or updating it on the server\n */\n save() {\n this.isSaving = true;\n if (this.exerciseHint.id !== undefined) {\n this.subscribeToSaveResponse(this.exerciseHintService.update(this.exerciseHint));\n } else {\n this.subscribeToSaveResponse(this.exerciseHintService.create(this.exerciseHint));\n }\n }\n\n protected subscribeToSaveResponse(result: Observable<HttpResponse<ExerciseHint>>) {\n result.subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n }\n\n protected onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n protected onSaveError() {\n this.isSaving = false;\n }\n protected onError(errorMessage: string) {\n this.jhiAlertService.error(errorMessage);\n }\n}\n" }, { "alpha_fraction": 0.6699768304824829, "alphanum_fraction": 0.6699768304824829, "avg_line_length": 37.24050521850586, "blob_id": "1fc0590d24f56818eed146504a723d8176f7c599", "content_id": "23e480ff1e7d1b92459c119cd1560aca30460071", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3021, "license_type": "permissive", "max_line_length": 113, "num_lines": 79, "path": "/src/main/webapp/app/exercises/shared/example-submission/example-submission.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\n\nimport { ExampleSubmission } from 'app/entities/example-submission.model';\n\nexport type EntityResponseType = HttpResponse<ExampleSubmission>;\n\n@Injectable({ providedIn: 'root' })\nexport class ExampleSubmissionService {\n constructor(private http: HttpClient) {}\n\n /**\n * Creates an example submission\n * @param exampleSubmission Example submission to create\n * @param exerciseId Id of the exercise to which it belongs\n */\n create(exampleSubmission: ExampleSubmission, exerciseId: number): Observable<EntityResponseType> {\n const copy = this.convert(exampleSubmission);\n return this.http\n .post<ExampleSubmission>(`api/exercises/${exerciseId}/example-submissions`, copy, {\n observe: 'response',\n })\n .map((res: EntityResponseType) => this.convertResponse(res));\n }\n\n /**\n * Updates an example submission\n * @param exampleSubmission Example submission to update\n * @param exerciseId Id of the exercise to which it belongs\n */\n update(exampleSubmission: ExampleSubmission, exerciseId: number): Observable<EntityResponseType> {\n const copy = this.convert(exampleSubmission);\n return this.http\n .put<ExampleSubmission>(`api/exercises/${exerciseId}/example-submissions`, copy, {\n observe: 'response',\n })\n .map((res: EntityResponseType) => this.convertResponse(res));\n }\n\n /**\n * Gets an example submission\n * @param exampleSubmissionId Id of example submission to get\n */\n get(exampleSubmissionId: number): Observable<EntityResponseType> {\n return this.http\n .get<ExampleSubmission>(`api/example-submissions/${exampleSubmissionId}`, {\n observe: 'response',\n })\n .map((res: HttpResponse<ExampleSubmission>) => this.convertResponse(res));\n }\n\n /**\n * Deletes an example submission\n * @param exampleSubmissionId Id of example submission to delete\n */\n delete(exampleSubmissionId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`api/example-submissions/${exampleSubmissionId}`, { observe: 'response' });\n }\n\n private convertResponse(res: EntityResponseType): EntityResponseType {\n const body: ExampleSubmission = this.convertItemFromServer(res.body!);\n return res.clone({ body });\n }\n\n /**\n * Convert a returned JSON object to ExampleSubmission.\n */\n private convertItemFromServer(exampleSubmission: ExampleSubmission): ExampleSubmission {\n return Object.assign({}, exampleSubmission);\n }\n\n /**\n * Convert a ExampleSubmission to a JSON which can be sent to the server.\n */\n private convert(exampleSubmission: ExampleSubmission): ExampleSubmission {\n return Object.assign({}, exampleSubmission);\n }\n}\n" }, { "alpha_fraction": 0.6272189617156982, "alphanum_fraction": 0.6274380683898926, "avg_line_length": 43.30097198486328, "blob_id": "0c03b6fa212da5d1bfb7fbbcf1c0aa595ba5a9bd", "content_id": "747a5850ed6262c85b530e563f27811c2a090133", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4563, "license_type": "permissive", "max_line_length": 171, "num_lines": 103, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/create-attachment-unit/create-attachment-unit.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, ViewChild } from '@angular/core';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport * as moment from 'moment';\nimport { AttachmentUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/attachmentUnit.service';\nimport { finalize } from 'rxjs/operators';\nimport { onError } from 'app/shared/util/global.utils';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { AttachmentUnitFormComponent, AttachmentUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/attachment-unit-form/attachment-unit-form.component';\nimport { combineLatest } from 'rxjs';\n\n@Component({\n selector: 'jhi-create-attachment-unit',\n templateUrl: './create-attachment-unit.component.html',\n styles: [],\n})\nexport class CreateAttachmentUnitComponent implements OnInit {\n @ViewChild('attachmentUnitForm')\n attachmentUnitForm: AttachmentUnitFormComponent;\n attachmentUnitToCreate: AttachmentUnit = new AttachmentUnit();\n attachmentToCreate: Attachment = new Attachment();\n\n isLoading: boolean;\n lectureId: number;\n courseId: number;\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private attachmentService: AttachmentService,\n private fileUploaderService: FileUploaderService,\n private attachmentUnitService: AttachmentUnitService,\n private alertService: JhiAlertService,\n ) {}\n\n ngOnInit() {\n const lectureRoute = this.activatedRoute.parent!.parent!;\n combineLatest(lectureRoute.paramMap, lectureRoute.parent!.paramMap).subscribe(([params, parentParams]) => {\n this.lectureId = Number(params.get('lectureId'));\n this.courseId = Number(parentParams.get('courseId'));\n });\n this.attachmentUnitToCreate = new AttachmentUnit();\n this.attachmentToCreate = new Attachment();\n }\n\n createAttachmentUnit(formData: AttachmentUnitFormData): void {\n if (!formData?.formProperties?.name || !formData?.fileProperties?.file || !formData?.fileProperties?.fileName) {\n return;\n }\n const { description, name, releaseDate } = formData.formProperties;\n const { file, fileName } = formData.fileProperties;\n // === Setting attachment ===\n\n if (name) {\n this.attachmentToCreate.name = name;\n }\n if (releaseDate) {\n this.attachmentToCreate.releaseDate = releaseDate;\n }\n this.attachmentToCreate.attachmentType = AttachmentType.FILE;\n this.attachmentToCreate.version = 1;\n this.attachmentToCreate.uploadDate = moment();\n\n // === Setting attachmentUnit ===\n if (description) {\n this.attachmentUnitToCreate.description = description;\n }\n\n this.isLoading = true;\n this.fileUploaderService.uploadFile(file, fileName, { keepFileName: true }).then(\n (result) => {\n // update link to the path provided by the server\n this.attachmentToCreate.link = result.path;\n this.attachmentUnitService\n .create(this.attachmentUnitToCreate!, this.lectureId)\n .concatMap((response: HttpResponse<AttachmentUnit>) => {\n this.attachmentToCreate.attachmentUnit = response.body!;\n return this.attachmentService.create(this.attachmentToCreate);\n })\n .pipe(\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n () => {\n this.router.navigate(['../../'], { relativeTo: this.activatedRoute });\n },\n (res: HttpErrorResponse) => onError(this.alertService, res),\n );\n },\n (error) => {\n // displaying the file upload error in the form but not resetting the form]\n this.attachmentUnitForm.setFileUploadError(error.message);\n this.isLoading = false;\n },\n );\n }\n}\n" }, { "alpha_fraction": 0.6239805817604065, "alphanum_fraction": 0.6332378387451172, "avg_line_length": 51.1494255065918, "blob_id": "684cb9c7c351b2ee531009e6213ce46ea2ac11a1", "content_id": "b7abf8aa30341ec66a167a2c555892ead00cbddd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4537, "license_type": "permissive", "max_line_length": 156, "num_lines": 87, "path": "/src/main/webapp/app/exercises/programming/manage/grading/charts/sca-category-distribution-chart.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnChanges, Output } from '@angular/core';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { StaticCodeAnalysisCategory, StaticCodeAnalysisCategoryState } from 'app/entities/static-code-analysis-category.model';\nimport { HorizontalStackedBarChartPreset } from 'app/shared/chart/presets/horizontalStackedBarChartPreset';\nimport { ChartDataSets } from 'chart.js';\nimport { CategoryIssuesMap } from 'app/entities/programming-exercise-test-case-statistics.model';\n\n@Component({\n selector: 'jhi-sca-category-distribution-chart',\n template: `\n <div>\n <div>\n <h4>{{ 'artemisApp.programmingExercise.configureGrading.charts.categoryDistribution.title' | translate }}</h4>\n <p [innerHTML]=\"'artemisApp.programmingExercise.configureGrading.charts.categoryDistribution.description' | translate\"></p>\n </div>\n <div class=\"bg-light\">\n <jhi-chart [preset]=\"chartPreset\" [datasets]=\"chartDatasets\"></jhi-chart>\n </div>\n </div>\n `,\n})\nexport class ScaCategoryDistributionChartComponent implements OnChanges {\n @Input() categories: StaticCodeAnalysisCategory[];\n @Input() categoryIssuesMap?: CategoryIssuesMap;\n @Input() exercise: ProgrammingExercise;\n\n @Output() categoryColorsChange = new EventEmitter<{}>();\n\n chartPreset = new HorizontalStackedBarChartPreset(['Penalty', 'Issues', 'Deductions'], ['all penalties', 'all detected issues', 'all deducted points']);\n chartDatasets: ChartDataSets[] = [];\n\n ngOnChanges(): void {\n const categoryPenalties = this.categories\n .map((category) => ({\n ...category,\n penalty: category.state === StaticCodeAnalysisCategoryState.Graded ? category.penalty : 0,\n maxPenalty: category.state === StaticCodeAnalysisCategoryState.Graded ? category.maxPenalty : 0,\n }))\n .map((category) => {\n const issuesMap = this.categoryIssuesMap ? this.categoryIssuesMap[category.name] || {} : {};\n\n // total number of issues in this category\n const issuesSum = Object.entries(issuesMap).reduce((sum, [issues, students]) => sum + parseInt(issues, 10) * students, 0);\n\n // total number of penalty points in this category\n let penaltyPointsSum = Object.entries(issuesMap)\n .map(([issues, students]) => students * Math.min(parseInt(issues, 10) * category.penalty, category.maxPenalty))\n .reduce((sum, penaltyPoints) => sum + penaltyPoints, 0);\n\n if ((this.exercise.maxStaticCodeAnalysisPenalty || Infinity) < penaltyPointsSum) {\n penaltyPointsSum = this.exercise.maxStaticCodeAnalysisPenalty!;\n }\n\n return { category, issues: issuesSum || 0, penaltyPoints: penaltyPointsSum };\n });\n\n // sum of all penalties\n const totalPenalty = categoryPenalties.reduce((sum, { category }) => sum + Math.min(category.penalty, category.maxPenalty), 0);\n // sum of all issues\n const totalIssues = categoryPenalties.reduce((sum, { issues }) => sum + issues, 0);\n // sum of all penalty points\n const totalPenaltyPoints = categoryPenalties.reduce((sum, { penaltyPoints }) => sum + penaltyPoints, 0);\n\n this.chartDatasets = categoryPenalties.map((element, i) => ({\n label: element.category.name,\n data: [\n // relative penalty percentage\n totalPenalty > 0 ? (Math.min(element.category.penalty, element.category.maxPenalty) / totalPenalty) * 100 : 0,\n // relative issues percentage\n totalIssues > 0 ? (element.issues / totalIssues) * 100 : 0,\n // relative penalty points percentage\n totalPenaltyPoints > 0 ? (element.penaltyPoints / totalPenaltyPoints) * 100 : 0,\n ],\n backgroundColor: this.getColor(i / this.categories.length, 50),\n hoverBackgroundColor: this.getColor(i / this.categories.length, 60),\n }));\n\n // update colors for category table\n const categoryColors = {};\n this.chartDatasets.forEach(({ label, backgroundColor }) => (categoryColors[label!] = backgroundColor));\n this.categoryColorsChange.emit(categoryColors);\n }\n\n getColor(i: number, l: number): string {\n return `hsl(${(i * 360 * 3) % 360}, 55%, ${l}%)`;\n }\n}\n" }, { "alpha_fraction": 0.789435088634491, "alphanum_fraction": 0.7909024357795715, "avg_line_length": 37.94285583496094, "blob_id": "94f48d491cc245684177905ee1c0d6fe6e25a972", "content_id": "81c12eb32a5af032fc0652ea234a2a9f2ec84ecb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1363, "license_type": "permissive", "max_line_length": 132, "num_lines": 35, "path": "/src/main/java/de/tum/in/www1/artemis/repository/PersistenceAuditEventRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.time.Instant;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.jetbrains.annotations.NotNull;\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\n\nimport de.tum.in.www1.artemis.domain.PersistentAuditEvent;\n\n/**\n * Spring Data JPA repository for the PersistentAuditEvent entity.\n */\npublic interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {\n\n @EntityGraph(type = LOAD, attributePaths = { \"data\" })\n List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principle, Instant after, String type);\n\n @EntityGraph(type = LOAD, attributePaths = { \"data\" })\n Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);\n\n @NotNull\n @EntityGraph(type = LOAD, attributePaths = { \"data\" })\n Page<PersistentAuditEvent> findAll(@NotNull Pageable pageable);\n\n @NotNull\n @EntityGraph(type = LOAD, attributePaths = { \"data\" })\n Optional<PersistentAuditEvent> findById(@NotNull Long auditEventId);\n}\n" }, { "alpha_fraction": 0.6952740550041199, "alphanum_fraction": 0.6960945129394531, "avg_line_length": 48.14516067504883, "blob_id": "db7fb4d6bdb09e2586bf4f304f35b0f480190e96", "content_id": "212a0dbdb89ac3aafe4a28d4aa41b489dbc0c121", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6094, "license_type": "permissive", "max_line_length": 172, "num_lines": 124, "path": "/src/main/webapp/app/overview/course-exercises/course-exercise-row.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, HostBinding, Input, OnDestroy, OnInit } from '@angular/core';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { Subscription } from 'rxjs/Subscription';\nimport { Course } from 'app/entities/course.model';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpClient } from '@angular/common/http';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { Exercise, ExerciseCategory, ExerciseType, getIcon, getIconTooltip, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\n\n@Component({\n selector: 'jhi-course-exercise-row',\n templateUrl: './course-exercise-row.component.html',\n styleUrls: ['./course-exercise-row.scss'],\n})\nexport class CourseExerciseRowComponent implements OnInit, OnDestroy {\n readonly QUIZ = ExerciseType.QUIZ;\n readonly PROGRAMMING = ExerciseType.PROGRAMMING;\n readonly MODELING = ExerciseType.MODELING;\n readonly TEXT = ExerciseType.TEXT;\n readonly FILE_UPLOAD = ExerciseType.FILE_UPLOAD;\n readonly IncludedInOverallScore = IncludedInOverallScore;\n @HostBinding('class') classes = 'exercise-row';\n @Input() exercise: Exercise;\n @Input() course: Course;\n @Input() extendedLink = false;\n @Input() hasGuidedTour: boolean;\n /**\n * PresentationMode deactivates the interactivity of the component\n */\n @Input() isPresentationMode = false;\n\n getIcon = getIcon;\n getIconTooltip = getIconTooltip;\n public exerciseCategories: ExerciseCategory[];\n isAfterAssessmentDueDate: boolean;\n\n participationUpdateListener: Subscription;\n\n constructor(\n private accountService: AccountService,\n private participationService: ParticipationService,\n private exerciseService: ExerciseService,\n private httpClient: HttpClient,\n private router: Router,\n private route: ActivatedRoute,\n private participationWebsocketService: ParticipationWebsocketService,\n ) {}\n\n ngOnInit() {\n const cachedParticipation = this.participationWebsocketService.getParticipationForExercise(this.exercise.id!);\n if (cachedParticipation) {\n this.exercise.studentParticipations = [cachedParticipation];\n }\n this.participationUpdateListener = this.participationWebsocketService.subscribeForParticipationChanges().subscribe((changedParticipation: StudentParticipation) => {\n if (changedParticipation && this.exercise && changedParticipation.exercise!.id === this.exercise.id) {\n this.exercise.studentParticipations =\n this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0\n ? this.exercise.studentParticipations.map((el) => {\n return el.id === changedParticipation.id ? changedParticipation : el;\n })\n : [changedParticipation];\n this.exercise.participationStatus = participationStatus(this.exercise);\n }\n });\n this.exercise.participationStatus = participationStatus(this.exercise);\n if (this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0) {\n this.exercise.studentParticipations[0].exercise = this.exercise;\n }\n this.exercise.isAtLeastTutor = this.accountService.isAtLeastTutorInCourse(this.course || this.exercise.exerciseGroup!.exam!.course);\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.course || this.exercise.exerciseGroup!.exam!.course);\n this.isAfterAssessmentDueDate = !this.exercise.assessmentDueDate || moment().isAfter(this.exercise.assessmentDueDate);\n if (this.exercise.type === ExerciseType.QUIZ) {\n const quizExercise = this.exercise as QuizExercise;\n quizExercise.isActiveQuiz = this.exerciseService.isActiveQuiz(this.exercise);\n quizExercise.isPracticeModeAvailable = quizExercise.isPlannedToStart && quizExercise.isOpenForPractice && moment(this.exercise.dueDate!).isBefore(moment());\n this.exercise = quizExercise;\n }\n this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise);\n }\n\n ngOnDestroy() {\n if (this.participationUpdateListener) {\n this.participationUpdateListener.unsubscribe();\n }\n }\n\n getUrgentClass(date?: Moment) {\n if (!date) {\n return undefined;\n }\n const remainingDays = date.diff(moment(), 'days');\n if (0 <= remainingDays && remainingDays < 7) {\n return 'text-danger';\n }\n }\n\n asProgrammingExercise(exercise: Exercise): ProgrammingExercise {\n return exercise as ProgrammingExercise;\n }\n\n asQuizExercise(exercise: Exercise): QuizExercise {\n return exercise as QuizExercise;\n }\n\n showDetails(event: any) {\n const isClickOnAction = event.target.closest('jhi-exercise-details-student-actions') && event.target.closest('.btn');\n const isClickResult = event.target.closest('jhi-result') && event.target.closest('.result');\n if (!isClickOnAction && !isClickResult) {\n if (this.extendedLink) {\n this.router.navigate(['courses', this.course.id, 'exercises', this.exercise.id]);\n } else {\n this.router.navigate([this.exercise.id], { relativeTo: this.route });\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.5703305602073669, "alphanum_fraction": 0.5712565779685974, "avg_line_length": 44.75847625732422, "blob_id": "ba75a0f49f18a8abd6bdd42512dee908a34c879c", "content_id": "d3e6ada7d391b021e2fd92caf99ea3d91a72211d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10809, "license_type": "permissive", "max_line_length": 175, "num_lines": 236, "path": "/src/main/webapp/app/exercises/modeling/assess/modeling-assessment.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse, HttpParams } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { UMLElementType, UMLModel, UMLRelationshipType } from '@ls1intum/apollon';\nimport * as moment from 'moment';\nimport { ComplaintResponse } from 'app/entities/complaint-response.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { Result } from 'app/entities/result.model';\n\nexport type EntityResponseType = HttpResponse<Result>;\n\n@Injectable({ providedIn: 'root' })\nexport class ModelingAssessmentService {\n private readonly MAX_FEEDBACK_TEXT_LENGTH = 500;\n private readonly MAX_FEEDBACK_DETAIL_TEXT_LENGTH = 5000;\n private resourceUrl = SERVER_API_URL + 'api';\n\n constructor(private http: HttpClient) {}\n\n saveAssessment(resultId: number, feedbacks: Feedback[], submissionId: number, submit = false): Observable<Result> {\n let params = new HttpParams();\n if (submit) {\n params = params.set('submit', 'true');\n }\n const url = `${this.resourceUrl}/modeling-submissions/${submissionId}/result/${resultId}/assessment`;\n return this.http\n .put<Result>(url, feedbacks, { params })\n .map((res: Result) => this.convertResult(res));\n }\n\n saveExampleAssessment(feedbacks: Feedback[], exampleSubmissionId: number): Observable<Result> {\n const url = `${this.resourceUrl}/modeling-submissions/${exampleSubmissionId}/example-assessment`;\n return this.http.put<Result>(url, feedbacks).map((res) => this.convertResult(res));\n }\n\n updateAssessmentAfterComplaint(feedbacks: Feedback[], complaintResponse: ComplaintResponse, submissionId: number): Observable<EntityResponseType> {\n const url = `${this.resourceUrl}/modeling-submissions/${submissionId}/assessment-after-complaint`;\n const assessmentUpdate = {\n feedbacks,\n complaintResponse,\n };\n return this.http\n .put<Result>(url, assessmentUpdate, { observe: 'response' })\n .map((res: EntityResponseType) => this.convertResponse(res));\n }\n\n getAssessment(submissionId: number): Observable<Result> {\n return this.http.get<Result>(`${this.resourceUrl}/modeling-submissions/${submissionId}/result`).map((res) => this.convertResult(res));\n }\n\n getExampleAssessment(exerciseId: number, submissionId: number): Observable<Result> {\n const url = `${this.resourceUrl}/exercise/${exerciseId}/modeling-submissions/${submissionId}/example-assessment`;\n return this.http.get<Result>(url).map((res) => this.convertResult(res));\n }\n\n /**\n * TODO delete\n * @deprecated do not use any more, instead use modeling-submission-service.getModelingSubmissionForExerciseForCorrectionRoundWithoutAssessment(...)\n * @param exerciseId the modeling exercise id\n */\n getOptimalSubmissions(exerciseId: number): Observable<number[]> {\n return this.http.get<number[]>(`${this.resourceUrl}/exercises/${exerciseId}/optimal-model-submissions`);\n }\n\n /**\n * TODO delete\n * @deprecated do not use any more\n * @param exerciseId the modeling exercise id\n */\n resetOptimality(exerciseId: number): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/exercises/${exerciseId}/optimal-model-submissions`, { observe: 'response' });\n }\n\n cancelAssessment(submissionId: number): Observable<void> {\n return this.http.put<void>(`${this.resourceUrl}/modeling-submissions/${submissionId}/cancel-assessment`, null);\n }\n\n private convertResponse(res: EntityResponseType): EntityResponseType {\n let result = this.convertItemFromServer(res.body!);\n result = this.convertResult(result);\n\n if (result.completionDate) {\n result.completionDate = moment(result.completionDate);\n }\n if (result.submission && result.submission.submissionDate) {\n result.submission.submissionDate = moment(result.submission.submissionDate);\n }\n if (result.participation && result.participation.initializationDate) {\n result.participation.initializationDate = moment(result.participation.initializationDate);\n }\n\n return res.clone({ body: result });\n }\n\n private convertItemFromServer(result: Result): Result {\n return Object.assign({}, result);\n }\n\n /**\n * Iterates over all feedback elements of a response and converts the reference field of the feedback into\n * separate referenceType and referenceId fields. The reference field is of the form <referenceType>:<referenceId>.\n */\n convertResult(result: Result): Result {\n if (!result || !result.feedbacks) {\n return result;\n }\n for (const feedback of result.feedbacks) {\n if (feedback.reference) {\n feedback.referenceType = feedback.reference.split(':')[0];\n feedback.referenceId = feedback.reference.split(':')[1];\n }\n }\n return result;\n }\n\n /**\n * Creates the labels for the assessment elements for displaying them in the modeling and assessment editor.\n */\n // TODO: define a mapping or simplify this complex monster in a another way so that we can support other diagram types as well\n getNamesForAssessments(result: Result, model: UMLModel): Map<string, Map<string, string>> {\n const assessmentsNames = new Map<string, Map<string, string>>();\n for (const feedback of result.feedbacks!) {\n const referencedModelType = feedback.referenceType! as UMLElementType;\n const referencedModelId = feedback.referenceId!;\n if (referencedModelType in UMLElementType) {\n const element = model.elements.find((elem) => elem.id === referencedModelId);\n if (!element) {\n // prevent errors when element could not be found, should never happen\n assessmentsNames[referencedModelId] = { name: '', type: '' };\n continue;\n }\n\n const name = element.name;\n let type: string;\n switch (element.type) {\n case UMLElementType.Class:\n type = 'class';\n break;\n case UMLElementType.Package:\n type = 'package';\n break;\n case UMLElementType.Interface:\n type = 'interface';\n break;\n case UMLElementType.AbstractClass:\n type = 'abstract class';\n break;\n case UMLElementType.Enumeration:\n type = 'enum';\n break;\n case UMLElementType.ClassAttribute:\n type = 'attribute';\n break;\n case UMLElementType.ClassMethod:\n type = 'method';\n break;\n case UMLElementType.ActivityInitialNode:\n type = 'initial node';\n break;\n case UMLElementType.ActivityFinalNode:\n type = 'final node';\n break;\n case UMLElementType.ActivityObjectNode:\n type = 'object';\n break;\n case UMLElementType.ActivityActionNode:\n type = 'action';\n break;\n case UMLElementType.ActivityForkNode:\n type = 'fork node';\n break;\n case UMLElementType.ActivityMergeNode:\n type = 'merge node';\n break;\n default:\n type = '';\n break;\n }\n assessmentsNames[referencedModelId] = { type, name };\n } else if (referencedModelType in UMLRelationshipType) {\n const relationship = model.relationships.find((rel) => rel.id === referencedModelId)!;\n const source = model.elements.find((element) => element.id === relationship.source.element)!.name;\n const target = model.elements.find((element) => element.id === relationship.target.element)!.name;\n const relationshipType = relationship.type;\n let type = 'association';\n let relation: string;\n switch (relationshipType) {\n case UMLRelationshipType.ClassBidirectional:\n relation = ' <-> ';\n break;\n case UMLRelationshipType.ClassUnidirectional:\n relation = ' --> ';\n break;\n case UMLRelationshipType.ClassAggregation:\n relation = ' --◇ ';\n break;\n case UMLRelationshipType.ClassInheritance:\n relation = ' --▷ ';\n break;\n case UMLRelationshipType.ClassDependency:\n relation = ' ╌╌> ';\n break;\n case UMLRelationshipType.ClassComposition:\n relation = ' --◆ ';\n break;\n case UMLRelationshipType.ActivityControlFlow:\n relation = ' --> ';\n type = 'control flow';\n break;\n default:\n relation = ' --- ';\n }\n assessmentsNames[referencedModelId] = { type, name: source + relation + target };\n } else {\n assessmentsNames[referencedModelId] = { type: referencedModelType, name: '' };\n }\n }\n return assessmentsNames;\n }\n\n /**\n * Checks if the feedback text and detail text of every feedback item is smaller than the configured maximum length. Returns true if the length of the texts is valid or if\n * there is no feedback, false otherwise.\n */\n isFeedbackTextValid(feedback: Feedback[]): boolean {\n if (!feedback) {\n return true;\n }\n return feedback.every(\n (feedbackItem) =>\n (!feedbackItem.text || feedbackItem.text.length <= this.MAX_FEEDBACK_TEXT_LENGTH) &&\n (!feedbackItem.detailText || feedbackItem.detailText.length <= this.MAX_FEEDBACK_DETAIL_TEXT_LENGTH),\n );\n }\n}\n" }, { "alpha_fraction": 0.6657366156578064, "alphanum_fraction": 0.6657366156578064, "avg_line_length": 38.82222366333008, "blob_id": "96d4f9bfc07408cf9f4dfef0162d7221c2e67c35", "content_id": "e05455b5b85a8bdbfa732c6eda91898ee2f534ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1792, "license_type": "permissive", "max_line_length": 173, "num_lines": 45, "path": "/src/main/webapp/app/exercises/modeling/manage/modeling-statistics/modeling-statistics.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { JhiAlertService } from 'ng-jhipster';\nimport { Component, OnDestroy, OnInit } from '@angular/core';\nimport { Subscription } from 'rxjs/Subscription';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpResponse } from '@angular/common/http';\nimport { ModelingStatistic } from 'app/entities/modeling-statistic.model';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\n\n@Component({\n selector: 'jhi-statistic-dashboard',\n templateUrl: './modeling-statistics.component.html',\n providers: [ModelingExerciseService],\n})\nexport class ModelingStatisticsComponent implements OnInit, OnDestroy {\n statistics: ModelingStatistic;\n paramSub: Subscription;\n modelIds: string[] = [];\n elementIds: string[] = [];\n\n constructor(private route: ActivatedRoute, private jhiAlertService: JhiAlertService, private router: Router, private modelingExerciseService: ModelingExerciseService) {}\n\n /**\n * Displays the statistics for this modeling exercise on initialization\n */\n ngOnInit() {\n this.paramSub = this.route.params.subscribe((params) => {\n this.modelingExerciseService.getStatistics(params['exerciseId']).subscribe((res: HttpResponse<ModelingStatistic>) => {\n this.statistics = res.body!;\n for (const key of Object.keys(this.statistics.models)) {\n this.modelIds.push(key);\n }\n for (const key of Object.keys(this.statistics.uniqueElements)) {\n this.elementIds.push(key);\n }\n });\n });\n }\n\n /**\n * Unsubscribe the parameter subscription on component destruction\n */\n ngOnDestroy() {\n this.paramSub.unsubscribe();\n }\n}\n" }, { "alpha_fraction": 0.7212747931480408, "alphanum_fraction": 0.7244898080825806, "avg_line_length": 46.06578826904297, "blob_id": "1c3574e3e6aa03ceacfbf1275fd3057fa58b7915", "content_id": "419795ca21fe85b39496ec3eeb8b0f29888d2ff1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 7154, "license_type": "permissive", "max_line_length": 176, "num_lines": 152, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/lecture/AttachmentUnitResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.lecture;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.Lecture;\nimport de.tum.in.www1.artemis.domain.lecture.AttachmentUnit;\nimport de.tum.in.www1.artemis.repository.AttachmentUnitRepository;\nimport de.tum.in.www1.artemis.repository.LectureRepository;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\n\n@RestController\n@RequestMapping(\"/api\")\npublic class AttachmentUnitResource {\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final Logger log = LoggerFactory.getLogger(AttachmentUnitResource.class);\n\n private static final String ENTITY_NAME = \"attachmentUnit\";\n\n private final AttachmentUnitRepository attachmentUnitRepository;\n\n private final LectureRepository lectureRepository;\n\n private final AuthorizationCheckService authorizationCheckService;\n\n public AttachmentUnitResource(AttachmentUnitRepository attachmentUnitRepository, LectureRepository lectureRepository, AuthorizationCheckService authorizationCheckService) {\n this.attachmentUnitRepository = attachmentUnitRepository;\n this.lectureRepository = lectureRepository;\n this.authorizationCheckService = authorizationCheckService;\n }\n\n /**\n * GET /lectures/:lectureId/attachment-units/:attachmentUnitId : gets the attachment unit with the specified id\n *\n * @param attachmentUnitId the id of the attachmentUnit to retrieve\n * @param lectureId the id of the lecture to which the unit belongs\n * @return the ResponseEntity with status 200 (OK) and with body the attachment unit, or with status 404 (Not Found)\n */\n @GetMapping(\"/lectures/{lectureId}/attachment-units/{attachmentUnitId}\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<AttachmentUnit> getAttachmentUnit(@PathVariable Long attachmentUnitId, @PathVariable Long lectureId) {\n log.debug(\"REST request to get AttachmentUnit : {}\", attachmentUnitId);\n Optional<AttachmentUnit> optionalAttachmentUnit = attachmentUnitRepository.findById(attachmentUnitId);\n if (optionalAttachmentUnit.isEmpty()) {\n return notFound();\n }\n AttachmentUnit attachmentUnit = optionalAttachmentUnit.get();\n if (attachmentUnit.getLecture() == null || attachmentUnit.getLecture().getCourse() == null) {\n return conflict();\n }\n if (!attachmentUnit.getLecture().getId().equals(lectureId)) {\n return conflict();\n }\n\n if (!authorizationCheckService.isAtLeastInstructorInCourse(attachmentUnit.getLecture().getCourse(), null)) {\n return forbidden();\n }\n return ResponseEntity.ok().body(attachmentUnit);\n }\n\n /**\n * PUT /lectures/:lectureId/attachment-units : Updates an existing attachment unit .\n *\n * @param lectureId the id of the lecture to which the attachment unit belongs to update\n * @param attachmentUnit the attachment unit to update\n * @return the ResponseEntity with status 200 (OK) and with body the updated attachmentUnit\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PutMapping(\"/lectures/{lectureId}/attachment-units\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<AttachmentUnit> updateAttachmentUnit(@PathVariable Long lectureId, @RequestBody AttachmentUnit attachmentUnit) throws URISyntaxException {\n log.debug(\"REST request to update an attachment unit : {}\", attachmentUnit);\n if (attachmentUnit.getId() == null) {\n return badRequest();\n }\n\n if (attachmentUnit.getLecture() == null || attachmentUnit.getLecture().getCourse() == null) {\n return conflict();\n }\n\n if (!authorizationCheckService.isAtLeastInstructorInCourse(attachmentUnit.getLecture().getCourse(), null)) {\n return forbidden();\n }\n\n if (!attachmentUnit.getLecture().getId().equals(lectureId)) {\n return conflict();\n }\n\n // Make sure that the original references are preserved.\n AttachmentUnit originalAttachmentUnit = attachmentUnitRepository.findById(attachmentUnit.getId()).get();\n attachmentUnit.setAttachment(originalAttachmentUnit.getAttachment());\n\n AttachmentUnit result = attachmentUnitRepository.save(attachmentUnit);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, attachmentUnit.getId().toString())).body(result);\n }\n\n /**\n * POST /lectures/:lectureId/attachment-units : creates a new attachment unit.\n *\n * @param lectureId the id of the lecture to which the attachment unit should be added\n * @param attachmentUnit the attachment unit that should be created\n * @return the ResponseEntity with status 201 (Created) and with body the new attachment unit\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PostMapping(\"/lectures/{lectureId}/attachment-units\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<AttachmentUnit> createAttachmentUnit(@PathVariable Long lectureId, @RequestBody AttachmentUnit attachmentUnit) throws URISyntaxException {\n log.debug(\"REST request to create AttachmentUnit : {}\", attachmentUnit);\n if (attachmentUnit.getId() != null) {\n return badRequest();\n }\n Optional<Lecture> lectureOptional = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lectureId);\n if (lectureOptional.isEmpty()) {\n return badRequest();\n }\n Lecture lecture = lectureOptional.get();\n if (lecture.getCourse() == null) {\n return conflict();\n }\n if (!authorizationCheckService.isAtLeastInstructorInCourse(lecture.getCourse(), null)) {\n return forbidden();\n }\n\n // persist lecture unit before lecture to prevent \"null index column for collection\" error\n attachmentUnit.setLecture(null);\n attachmentUnit = attachmentUnitRepository.saveAndFlush(attachmentUnit);\n attachmentUnit.setLecture(lecture);\n lecture.addLectureUnit(attachmentUnit);\n Lecture updatedLecture = lectureRepository.save(lecture);\n\n AttachmentUnit persistedAttachmentUnit = (AttachmentUnit) updatedLecture.getLectureUnits().get(updatedLecture.getLectureUnits().size() - 1);\n\n return ResponseEntity.created(new URI(\"/api/attachment-units/\" + persistedAttachmentUnit.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, \"\")).body(persistedAttachmentUnit);\n\n }\n\n}\n" }, { "alpha_fraction": 0.6425081491470337, "alphanum_fraction": 0.6425081491470337, "avg_line_length": 28.95121955871582, "blob_id": "67163bf7a4c479bb1b8750921acad0eb3c93d28b", "content_id": "b0506325af69af0f7f1bb0a1a359a60e7538175f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1228, "license_type": "permissive", "max_line_length": 80, "num_lines": 41, "path": "/src/test/javascript/spec/service/activate.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonStub, stub } from 'sinon';\nimport { ActivateService } from 'app/account/activate/activate.service';\nimport { MockHttpService } from '../helpers/mocks/service/mock-http.service';\nimport { HttpParams } from '@angular/common/http';\n\nimport { SERVER_API_URL } from 'app/app.constants';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ActivateService', () => {\n let activateService: ActivateService;\n let httpService: MockHttpService;\n let getStub: SinonStub;\n\n const getURL = SERVER_API_URL + 'api/activate';\n\n beforeEach(async(() => {\n httpService = new MockHttpService();\n // @ts-ignore\n activateService = new ActivateService(httpService);\n getStub = stub(httpService, 'get');\n }));\n\n afterEach(() => {\n getStub.restore();\n });\n\n it('should send a request to the server to activate the user', async () => {\n const key = 'key';\n\n await activateService.get(key);\n\n expect(getStub).to.have.been.calledOnceWithExactly(getURL, {\n params: new HttpParams().set('key', key),\n });\n });\n});\n" }, { "alpha_fraction": 0.6959327459335327, "alphanum_fraction": 0.6999202370643616, "avg_line_length": 55.528690338134766, "blob_id": "3a70c0afe74e41a4023752cbe2d1886512d8773f", "content_id": "9ca810a6de32d4f47db474f9bd8a18bc9204cbbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13793, "license_type": "permissive", "max_line_length": 171, "num_lines": 244, "path": "/src/test/javascript/spec/component/assessment-dashboard/assessment-dashboard.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { SinonStub, stub } from 'sinon';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ActivatedRoute, convertToParamMap, RouterModule, UrlSegment } from '@angular/router';\nimport { of } from 'rxjs';\nimport { TutorParticipationGraphComponent } from 'app/shared/dashboards/tutor-participation-graph/tutor-participation-graph.component';\nimport { TutorLeaderboardComponent } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.component';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { TutorParticipationStatus } from 'app/entities/participation/tutor-participation.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { SecondCorrectionEnableButtonComponent } from 'app/exercises/shared/dashboards/tutor/second-correction-button/second-correction-enable-button.component';\nimport { AssessmentDashboardComponent } from 'app/course/dashboards/assessment-dashboard/assessment-dashboard.component';\nimport { AssessmentDashboardInformationComponent } from 'app/course/dashboards/assessment-dashboard/assessment-dashboard-information.component';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { TutorLeaderboardElement } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.model';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\nimport { TimeAgoPipe } from 'ngx-moment';\nimport { Course } from 'app/entities/course.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('AssessmentDashboardInformationComponent', () => {\n let comp: AssessmentDashboardComponent;\n let fixture: ComponentFixture<AssessmentDashboardComponent>;\n\n let examManagementService: ExamManagementService;\n let getExamWithInterestingExercisesForAssessmentDashboardStub: SinonStub;\n let getStatsForExamAssessmentDashboardStub: SinonStub;\n\n let courseManagementService: CourseManagementService;\n let getCourseWithInterestingExercisesForTutorsStub: SinonStub;\n let getStatsForTutorsStub: SinonStub;\n\n let exerciseService: ExerciseService;\n let toggleSecondCorrectionStub: SinonStub;\n\n let accountService: AccountService;\n let isAtLeastInstructorInCourseStub: SinonStub;\n\n const programmingExercise = {\n id: 16,\n type: ExerciseType.PROGRAMMING,\n tutorParticipations: [{ status: TutorParticipationStatus.TRAINED }],\n secondCorrectionEnabled: false,\n } as ProgrammingExercise;\n const modelingExercise = {\n id: 17,\n type: ExerciseType.MODELING,\n tutorParticipations: [{ status: TutorParticipationStatus.TRAINED }],\n } as ModelingExercise;\n const textExercise = {\n id: 18,\n type: ExerciseType.TEXT,\n tutorParticipations: [{ status: TutorParticipationStatus.TRAINED }],\n secondCorrectionEnabled: false,\n } as TextExercise;\n const fileUploadExercise = {\n id: 19,\n type: ExerciseType.FILE_UPLOAD,\n tutorParticipations: [{ status: TutorParticipationStatus.TRAINED }],\n secondCorrectionEnabled: false,\n numberOfSubmissions: { inTime: 5, late: 0 },\n numberOfAssessmentsOfCorrectionRounds: [{ inTime: 5, late: 0 }],\n totalNumberOfAssessments: { inTime: 5, late: 0 },\n numberOfOpenComplaints: 0,\n numberOfOpenMoreFeedbackRequests: 0,\n } as FileUploadExercise;\n\n const course = { id: 10, exercises: [programmingExercise, modelingExercise, textExercise, modelingExercise] } as Course;\n const exercises = [programmingExercise, fileUploadExercise, modelingExercise, textExercise];\n const exerciseGroup1 = { id: 141, exercises: [programmingExercise, modelingExercise] } as ExerciseGroup;\n const exerciseGroup2 = { id: 142, exercises: [textExercise, fileUploadExercise] } as ExerciseGroup;\n const exam = { id: 20, exerciseGroups: [exerciseGroup1, exerciseGroup2], course: { id: 10 } } as Exam;\n\n const numberOfAssessmentsOfCorrectionRounds = [{ inTime: 1, late: 1 } as DueDateStat, { inTime: 8, late: 0 } as DueDateStat];\n const tutorLeaderboardEntries = [] as TutorLeaderboardElement[];\n const courseTutorStats = {\n numberOfSubmissions: { inTime: 5, late: 0 } as DueDateStat,\n totalNumberOfAssessments: { inTime: 3, late: 0 } as DueDateStat,\n numberOfAssessmentsOfCorrectionRounds,\n numberOfComplaints: 0,\n numberOfMoreFeedbackRequests: 0,\n numberOfOpenMoreFeedbackRequests: 0,\n numberOfAssessmentLocks: 2,\n tutorLeaderboardEntries,\n numberOfStudents: 5,\n numberOfAutomaticAssistedAssessments: { inTime: 0, late: 0 },\n numberOfOpenComplaints: 0,\n totalNumberOfAssessmentLocks: 2,\n } as StatsForDashboard;\n\n const route = ({\n snapshot: {\n paramMap: convertToParamMap({ courseId: course.id, examId: exam.id }),\n url: { path: '/course-management/10/assessment-dashboard', parameterMap: {}, parameters: {} } as UrlSegment,\n },\n } as any) as ActivatedRoute;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisSharedComponentModule, RouterModule, TranslateModule.forRoot(), ArtemisAssessmentSharedModule],\n declarations: [\n AssessmentDashboardComponent,\n MockComponent(TutorLeaderboardComponent),\n MockComponent(TutorParticipationGraphComponent),\n MockComponent(AssessmentDashboardInformationComponent),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockPipe(TimeAgoPipe),\n MockComponent(SecondCorrectionEnableButtonComponent),\n MockPipe(HtmlForMarkdownPipe),\n ],\n providers: [\n JhiLanguageHelper,\n DeviceDetectorService,\n { provide: ActivatedRoute, useValue: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(AssessmentDashboardComponent);\n comp = fixture.componentInstance;\n\n examManagementService = TestBed.inject(ExamManagementService);\n courseManagementService = TestBed.inject(CourseManagementService);\n exerciseService = TestBed.inject(ExerciseService);\n accountService = TestBed.inject(AccountService);\n\n getExamWithInterestingExercisesForAssessmentDashboardStub = stub(examManagementService, 'getExamWithInterestingExercisesForAssessmentDashboard');\n getStatsForExamAssessmentDashboardStub = stub(examManagementService, 'getStatsForExamAssessmentDashboard');\n toggleSecondCorrectionStub = stub(exerciseService, 'toggleSecondCorrection');\n //\n getCourseWithInterestingExercisesForTutorsStub = stub(courseManagementService, 'getCourseWithInterestingExercisesForTutors');\n getStatsForTutorsStub = stub(courseManagementService, 'getStatsForTutors');\n\n isAtLeastInstructorInCourseStub = stub(accountService, 'isAtLeastInstructorInCourse');\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n describe('ngOnInit', () => {\n it('should loadAll for course', () => {\n const newRoute = ({\n snapshot: {\n paramMap: convertToParamMap({ courseId: course.id }),\n url: { path: '/course-management/10/assessment-dashboard', parameterMap: {}, parameters: {} } as UrlSegment,\n },\n } as any) as ActivatedRoute;\n const activatedRoute: ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);\n activatedRoute.snapshot = newRoute.snapshot;\n TestBed.inject(ActivatedRoute);\n\n // TODO: for some very odd reason those two stubs do not work. I could not figure out why. This test tests nothing atm.\n getCourseWithInterestingExercisesForTutorsStub = getCourseWithInterestingExercisesForTutorsStub.returns(of({ body: course }));\n getStatsForTutorsStub = getStatsForTutorsStub.returns(of(courseTutorStats));\n\n // let getCourseWithReturnValue: Observable<Course> = of({});\n // getCourseWithInterestingExercisesForTutorsStub.returns(getCourseWithReturnValue);\n // getStatsForTutorsStub = stub(courseManagementService, 'getStatsForTutors').returns(of(new HttpResponse({body: courseTutorStats })));\n // sinon.replace(courseManagementService, 'getStatsForTutors', sinon.fake.returns(of(new HttpResponse({body: courseTutorStats }))));\n\n comp.ngOnInit();\n // expect(getCourseWithInterestingExercisesForTutorsStub).to.have.been.called;\n // expect(getStatsForTutorsStub).to.have.been.called;\n });\n it('should loadAll for exam', () => {\n getExamWithInterestingExercisesForAssessmentDashboardStub.returns(of({ body: exam }));\n getStatsForExamAssessmentDashboardStub.returns(of(courseTutorStats));\n isAtLeastInstructorInCourseStub.returns(of(true));\n\n comp.ngOnInit();\n expect(getExamWithInterestingExercisesForAssessmentDashboardStub).to.have.been.called;\n expect(getStatsForExamAssessmentDashboardStub).to.have.been.called;\n expect(comp.exam).to.deep.equal(exam);\n expect(comp.unfinishedExercises.length).to.be.equal(3);\n expect(comp.finishedExercises.length).to.equal(1);\n });\n });\n describe('toggle second correctoinRound', () => {\n it('should toggle correctionRound for exercises', () => {\n comp.exercises = exercises;\n toggleSecondCorrectionStub.returns(of(true));\n comp.toggleSecondCorrection(fileUploadExercise.id!);\n expect(comp.exercises.find((exercise) => exercise.id === fileUploadExercise.id!)!.secondCorrectionEnabled).to.be.true;\n toggleSecondCorrectionStub.returns(of(false));\n comp.toggleSecondCorrection(fileUploadExercise.id!);\n expect(comp.exercises.find((exercise) => exercise.id === fileUploadExercise.id!)!.secondCorrectionEnabled).to.be.false;\n expect(comp.toggelingSecondCorrectionButton).to.be.false;\n });\n });\n describe('getAssessmentDashboardLinkForExercise', () => {\n beforeEach(() => {\n comp.courseId = course.id!;\n comp.examId = exam.id!;\n });\n it('should getAssessmentDashboardLinkForExercise for exam', () => {\n comp.isExamMode = true;\n const link = ['/course-management', comp.courseId.toString(), 'exams', comp.examId.toString(), 'assessment-dashboard', fileUploadExercise.id!.toString()];\n expect(comp.getAssessmentDashboardLinkForExercise(fileUploadExercise)).to.deep.equal(link);\n });\n it('should getAssessmentDashboardLinkForExercise for exam and testrun', () => {\n comp.isExamMode = true;\n comp.isTestRun = true;\n const link = ['/course-management', comp.courseId.toString(), 'exams', comp.examId.toString(), 'test-assessment-dashboard', fileUploadExercise.id!.toString()];\n expect(comp.getAssessmentDashboardLinkForExercise(fileUploadExercise)).to.deep.equal(link);\n });\n it('should getAssessmentDashboardLinkForExercise for course', () => {\n comp.isExamMode = false;\n const link = ['/course-management', comp.courseId.toString(), 'assessment-dashboard', fileUploadExercise.id!.toString()];\n expect(comp.getAssessmentDashboardLinkForExercise(fileUploadExercise)).to.deep.equal(link);\n });\n });\n});\n" }, { "alpha_fraction": 0.7551258206367493, "alphanum_fraction": 0.7657269239425659, "avg_line_length": 49.494117736816406, "blob_id": "ce619974ea05698790bb559292d11c0d30d7300b", "content_id": "fc59177775fc4ad3978eb02cf6297f964159265f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8584, "license_type": "permissive", "max_line_length": 163, "num_lines": 170, "path": "/src/test/java/de/tum/in/www1/artemis/programmingexercise/ProgrammingExerciseTestCaseServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.programmingexercise;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.ArgumentMatchers.any;\nimport static org.mockito.Mockito.*;\n\nimport java.util.*;\n\nimport org.eclipse.jgit.lib.ObjectId;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.ArgumentMatchers;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.Feedback;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.ProgrammingExerciseTestCase;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseTestCaseRepository;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseTestCaseService;\nimport de.tum.in.www1.artemis.util.ModelFactory;\nimport de.tum.in.www1.artemis.web.rest.dto.ProgrammingExerciseTestCaseDTO;\n\npublic class ProgrammingExerciseTestCaseServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ProgrammingExerciseTestCaseRepository testCaseRepository;\n\n @Autowired\n private ProgrammingExerciseTestCaseService testCaseService;\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n private ProgrammingExercise programmingExercise;\n\n @BeforeEach\n public void setUp() {\n database.addUsers(5, 1, 1);\n database.addCourseWithOneProgrammingExerciseAndTestCases();\n var programmingExercises = programmingExerciseRepository.findAllWithEagerTemplateAndSolutionParticipations();\n programmingExercise = programmingExercises.get(0);\n bambooRequestMockProvider.enableMockingOfRequests();\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n bambooRequestMockProvider.reset();\n }\n\n @Test\n public void shouldSetAllTestCasesToInactiveIfFeedbackListIsEmpty() {\n List<Feedback> feedbacks = new ArrayList<>();\n testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise);\n\n Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId());\n assertThat(testCases).hasSize(3);\n\n assertThat(testCases.stream().noneMatch(ProgrammingExerciseTestCase::isActive)).isTrue();\n }\n\n @Test\n public void shouldUpdateActiveFlagsOfTestCases() {\n List<Feedback> feedbacks = new ArrayList<>();\n feedbacks.add(new Feedback().text(\"test1\"));\n feedbacks.add(new Feedback().text(\"test2\"));\n feedbacks.add(new Feedback().text(\"test4\"));\n feedbacks.add(new Feedback().text(\"test5\"));\n testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise);\n\n Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId());\n assertThat(testCases).hasSize(5);\n\n assertThat(testCases.stream().allMatch(testCase -> {\n if (testCase.getTestName().equals(\"test3\")) {\n return !testCase.isActive();\n }\n else {\n return testCase.isActive();\n }\n })).isTrue();\n }\n\n @Test\n public void shouldGenerateNewTestCases() {\n testCaseRepository.deleteAll();\n\n List<Feedback> feedbacks = new ArrayList<>();\n feedbacks.add(new Feedback().text(\"test1\"));\n feedbacks.add(new Feedback().text(\"test2\"));\n testCaseService.generateTestCasesFromFeedbacks(feedbacks, programmingExercise);\n\n Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId());\n assertThat(testCases).hasSize(2);\n\n assertThat(testCases.stream().allMatch(ProgrammingExerciseTestCase::isActive)).isTrue();\n }\n\n @Test\n public void shouldNotGenerateNewTestCasesForStaticCodeAnalysisFeedback() {\n testCaseRepository.deleteAll();\n\n List<Feedback> feedbackList = ModelFactory.generateStaticCodeAnalysisFeedbackList(5);\n testCaseService.generateTestCasesFromFeedbacks(feedbackList, programmingExercise);\n\n Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId());\n assertThat(testCases).hasSize(0);\n }\n\n @Test\n @WithMockUser(value = \"tutor1\", roles = \"TA\")\n public void shouldResetTestWeights() throws Exception {\n String dummyHash = \"9b3a9bd71a0d80e5bbc42204c319ed3d1d4f0d6d\";\n when(gitService.getLastCommitHash(ArgumentMatchers.any())).thenReturn(ObjectId.fromString(dummyHash));\n database.addProgrammingParticipationWithResultForExercise(programmingExercise, \"student1\");\n new ArrayList<>(testCaseRepository.findByExerciseId(programmingExercise.getId())).get(0).weight(50.0);\n // After a test case reset, the solution and template repository should be build, so the ContinuousIntegrationService needs to be triggered\n bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getSolutionParticipation());\n bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getTemplateParticipation());\n\n assertThat(programmingExercise.getTestCasesChanged()).isFalse();\n\n testCaseService.reset(programmingExercise.getId());\n\n Set<ProgrammingExerciseTestCase> testCases = testCaseRepository.findByExerciseId(programmingExercise.getId());\n ProgrammingExercise updatedProgrammingExercise = programmingExerciseRepository\n .findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExercise.getId()).get();\n assertThat(testCases.stream().mapToDouble(ProgrammingExerciseTestCase::getWeight).sum()).isEqualTo(testCases.size());\n assertThat(updatedProgrammingExercise.getTestCasesChanged()).isTrue();\n verify(groupNotificationService, times(1)).notifyInstructorGroupAboutExerciseUpdate(updatedProgrammingExercise, Constants.TEST_CASES_CHANGED_NOTIFICATION);\n verify(websocketMessagingService, times(1)).sendMessage(\"/topic/programming-exercises/\" + programmingExercise.getId() + \"/test-cases-changed\", true);\n }\n\n @Test\n @WithMockUser(value = \"tutor1\", roles = \"TA\")\n public void shouldUpdateTestWeight() throws Exception {\n // After a test case update, the solution and template repository should be build, so the ContinuousIntegrationService needs to be triggered\n bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getSolutionParticipation());\n bambooRequestMockProvider.mockTriggerBuild(programmingExercise.getTemplateParticipation());\n String dummyHash = \"9b3a9bd71a0d80e5bbc42204c319ed3d1d4f0d6d\";\n doReturn(ObjectId.fromString(dummyHash)).when(gitService).getLastCommitHash(any());\n\n database.addProgrammingParticipationWithResultForExercise(programmingExercise, \"student1\");\n\n ProgrammingExerciseTestCase testCase = testCaseRepository.findAll().get(0);\n\n Set<ProgrammingExerciseTestCaseDTO> programmingExerciseTestCaseDTOS = new HashSet<>();\n ProgrammingExerciseTestCaseDTO programmingExerciseTestCaseDTO = new ProgrammingExerciseTestCaseDTO();\n programmingExerciseTestCaseDTO.setId(testCase.getId());\n programmingExerciseTestCaseDTO.setWeight(400.0);\n programmingExerciseTestCaseDTOS.add(programmingExerciseTestCaseDTO);\n\n assertThat(programmingExercise.getTestCasesChanged()).isFalse();\n\n testCaseService.update(programmingExercise.getId(), programmingExerciseTestCaseDTOS);\n\n ProgrammingExercise updatedProgrammingExercise = programmingExerciseRepository\n .findWithTemplateAndSolutionParticipationTeamAssignmentConfigCategoriesById(programmingExercise.getId()).get();\n\n assertThat(testCaseRepository.findById(testCase.getId()).get().getWeight()).isEqualTo(400);\n assertThat(updatedProgrammingExercise.getTestCasesChanged()).isTrue();\n verify(groupNotificationService, times(1)).notifyInstructorGroupAboutExerciseUpdate(updatedProgrammingExercise, Constants.TEST_CASES_CHANGED_NOTIFICATION);\n verify(websocketMessagingService, times(1)).sendMessage(\"/topic/programming-exercises/\" + programmingExercise.getId() + \"/test-cases-changed\", true);\n }\n}\n" }, { "alpha_fraction": 0.6382932066917419, "alphanum_fraction": 0.6437636613845825, "avg_line_length": 37.40336227416992, "blob_id": "99e60fd0271a728ed7f23b1d6419a0de70d03a3c", "content_id": "19e5666754216d85a60b46ed1ca377308294b92b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4570, "license_type": "permissive", "max_line_length": 135, "num_lines": 119, "path": "/src/test/javascript/spec/component/course-registration-selector/course-registration-selector.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { CourseRegistrationSelectorComponent } from 'app/overview/course-registration-selector/course-registration-selector.component';\nimport { Course } from 'app/entities/course.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs/internal/observable/of';\nimport { HttpResponse } from '@angular/common/http';\nimport { User } from 'app/core/user/user.model';\nimport { MockProvider } from 'ng-mocks';\nimport { TranslateService } from '@ngx-translate/core';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseRegistrationSelectorComponent', () => {\n let fixture: ComponentFixture<CourseRegistrationSelectorComponent>;\n let component: CourseRegistrationSelectorComponent;\n let courseService: CourseManagementService;\n let mockRouter: any;\n let mockActivatedRoute: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [CourseRegistrationSelectorComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: ActivatedRoute, useValue: mockActivatedRoute },\n { provide: Router, useValue: mockRouter },\n MockProvider(TranslateService),\n ],\n })\n .overrideTemplate(CourseRegistrationSelectorComponent, '')\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseRegistrationSelectorComponent);\n component = fixture.componentInstance;\n courseService = TestBed.inject(CourseManagementService);\n\n mockRouter = sinon.createStubInstance(Router);\n mockActivatedRoute = sinon.createStubInstance(ActivatedRoute);\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', fakeAsync(() => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n }));\n\n it('should track course by Id', fakeAsync(() => {\n const indexNumber = 1;\n const course = new Course();\n course.id = 1;\n expect(component.trackCourseById(indexNumber, course)).to.equal(indexNumber);\n }));\n\n it('should cancel the registration', fakeAsync(() => {\n component.showCourseSelection = true;\n component.cancelRegistration();\n expect(component.showCourseSelection).to.be.false;\n }));\n\n it('should show registratable courses', fakeAsync(() => {\n const course1 = new Course();\n course1.id = 1;\n const course2 = new Course();\n course2.id = 2;\n const fake = sinon.fake.returns(of(new HttpResponse({ body: [course1] })));\n component.courses = [course2];\n sinon.replace(courseService, 'findAllToRegister', fake);\n\n component.startRegistration();\n tick();\n\n expect(component.coursesToSelect.length).to.equal(1);\n }));\n\n it('should wait until timeout', fakeAsync(() => {\n const course1 = new Course();\n course1.id = 1;\n const course2 = new Course();\n course2.id = 2;\n const fake = sinon.fake.returns(of(new HttpResponse({ body: [course1] })));\n component.courses = [course1, course2];\n sinon.replace(courseService, 'findAllToRegister', fake);\n\n component.startRegistration();\n tick(4000);\n\n expect(component.courseToRegister).to.be.undefined;\n expect(component.showCourseSelection).to.be.false;\n }));\n\n it('should register for course', fakeAsync(() => {\n const course = new Course();\n course.id = 1;\n component.courseToRegister = course;\n\n const fake = sinon.fake.returns(of(new HttpResponse({ body: new User() })));\n sinon.replace(courseService, 'registerForCourse', fake);\n\n component.registerForCourse();\n tick();\n\n expect(component.addedSuccessful).to.be.true;\n flush();\n }));\n});\n" }, { "alpha_fraction": 0.5990841388702393, "alphanum_fraction": 0.599399983882904, "avg_line_length": 40.39215850830078, "blob_id": "8fb286c0ea5ef20496f7216149c1d90c77a86d4b", "content_id": "a2b05b137a9f39d9828987a95d90066d1899ef93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6333, "license_type": "permissive", "max_line_length": 135, "num_lines": 153, "path": "/src/test/javascript/spec/component/team/teams-import-from-file-form.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectorRef, DebugElement } from '@angular/core';\nimport { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Team } from 'app/entities/team.model';\nimport { TeamsImportFromFileFormComponent } from 'app/exercises/shared/team/teams-import-dialog/teams-import-from-file-form.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component.ts';\nimport * as chai from 'chai';\nimport { MockComponent, MockProvider } from 'ng-mocks';\nimport { restore, SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { mockFileStudents, mockFileTeamsConverted } from '../../helpers/mocks/service/mock-team.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TeamsImportFromFileFormComponent', () => {\n let comp: TeamsImportFromFileFormComponent;\n let fixture: ComponentFixture<TeamsImportFromFileFormComponent>;\n let debugElement: DebugElement;\n let changeDetector: ChangeDetectorRef;\n\n function resetComponent() {\n comp.sourceTeams = undefined;\n comp.importedTeams = [];\n comp.importFile = undefined;\n comp.importFileName = '';\n comp.loading = false;\n }\n\n beforeEach(\n waitForAsync(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [TeamsImportFromFileFormComponent, MockComponent(HelpIconComponent), MockComponent(FaIconComponent)],\n providers: [MockProvider(TranslateService)],\n }).compileComponents();\n }),\n );\n beforeEach(() => {\n fixture = TestBed.createComponent(TeamsImportFromFileFormComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n changeDetector = debugElement.injector.get(ChangeDetectorRef);\n });\n describe('importing file', () => {\n beforeEach(() => {\n resetComponent();\n });\n afterEach(() => {\n restore();\n });\n it('should convert and call teamsChanged with converted teams', () => {\n const setImportStub: SinonSpy = spy(comp, 'setImportFile');\n const inputElement = debugElement.query(By.css('input')).nativeElement;\n inputElement.dispatchEvent(new Event('change'));\n expect(setImportStub).to.have.been.called;\n });\n });\n describe('generateFileReader', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should return file reader when called', () => {\n expect(comp.generateFileReader()).to.deep.equal(new FileReader());\n });\n });\n\n describe('onFileLoadImport', () => {\n let convertTeamsStub: SinonStub;\n let teams: Team[];\n let reader: FileReader;\n let getElementStub: SinonStub;\n const element = document.createElement('input');\n const control = { ...element, value: 'test' };\n beforeEach(() => {\n resetComponent();\n convertTeamsStub = stub(comp, 'convertTeams').returns(mockFileTeamsConverted);\n comp.teamsChanged.subscribe((value: Team[]) => (teams = value));\n reader = { ...reader, result: JSON.stringify(mockFileStudents), onload: null };\n comp.importFile = new File([''], 'file.txt', { type: 'text/plain' });\n comp.importFileName = 'file.txt';\n getElementStub = stub(document, 'getElementById').returns(control);\n });\n afterEach(() => {\n restore();\n });\n it('should parse file and send converted teams', () => {\n expect(control.value).to.equal('test');\n comp.onFileLoadImport(reader);\n expect(convertTeamsStub).to.have.been.called;\n expect(comp.importedTeams).to.deep.equal(mockFileStudents);\n expect(comp.sourceTeams).to.deep.equal(mockFileTeamsConverted);\n expect(teams).to.deep.equal(mockFileTeamsConverted);\n expect(comp.loading).to.equal(false);\n expect(comp.importFile).to.equal(undefined);\n expect(comp.importFileName).to.equal('');\n expect(getElementStub).to.have.been.called;\n expect(control.value).to.equal('');\n });\n });\n\n describe('setImportFile', () => {\n let changeDetectorDetectChangesStub: SinonStub;\n beforeEach(() => {\n resetComponent();\n changeDetectorDetectChangesStub = stub(changeDetector.constructor.prototype, 'detectChanges');\n });\n afterEach(() => {\n restore();\n });\n it('should set import file correctly', () => {\n const file = new File(['content'], 'testFileName', { type: 'text/plain' });\n const ev = { target: { files: [file] } };\n comp.setImportFile(ev);\n expect(comp.importFile).to.deep.equal(file);\n expect(comp.importFileName).to.equal('testFileName');\n expect(changeDetectorDetectChangesStub).to.have.been.called;\n });\n it('should set import file correctly', () => {\n const ev = { target: { files: [] } };\n comp.setImportFile(ev);\n expect(comp.importFile).to.equal(undefined);\n expect(comp.importFileName).to.equal('');\n expect(changeDetectorDetectChangesStub).to.not.have.been.called;\n });\n });\n\n describe('convertTeams', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should convert file teams correctly', () => {\n expect(comp.convertTeams(mockFileStudents)).to.deep.equal(mockFileTeamsConverted);\n });\n });\n\n describe('Invalid team name throws exception', () => {\n beforeEach(() => {\n resetComponent();\n });\n it('should throw error', () => {\n const invalidFileStudents = [...mockFileStudents];\n invalidFileStudents[0].teamName = '1invalidTeamName';\n try {\n comp.convertTeams(invalidFileStudents);\n } catch (e) {\n expect(e.stack).to.not.be.null;\n }\n });\n });\n});\n" }, { "alpha_fraction": 0.6688741445541382, "alphanum_fraction": 0.6688741445541382, "avg_line_length": 35.2400016784668, "blob_id": "ecfb1386aa06f29d26c3e2b514142d25904b8259", "content_id": "8b74fbae2c4da306acc270e22ec822042ac87f55", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 906, "license_type": "permissive", "max_line_length": 133, "num_lines": 25, "path": "/src/main/webapp/app/exercises/programming/shared/service/sourceTree.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClient } from '@angular/common/http';\nimport { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\n\n@Injectable({ providedIn: 'root' })\nexport class SourceTreeService {\n constructor(private httpClient: HttpClient) {}\n\n /**\n * Build source tree url.\n * @param baseUrl - the base url of the version control system (e.g. Bitbucket or Bamboo)\n * @param cloneUrl - url of the target.\n */\n buildSourceTreeUrl(baseUrl: string, cloneUrl: string | undefined) {\n return cloneUrl ? 'sourcetree://cloneRepo?type=stash&cloneUrl=' + encodeURI(cloneUrl) + '&baseWebUrl=' + baseUrl : undefined;\n }\n\n /**\n * Return password of the repository.\n */\n getRepositoryPassword(): Observable<Object> {\n return this.httpClient.get(`${SERVER_API_URL}/api/account/password`);\n }\n}\n" }, { "alpha_fraction": 0.643062949180603, "alphanum_fraction": 0.6559514999389648, "avg_line_length": 39.96273422241211, "blob_id": "2f9190014b005c5b7cf9078d63bf4130b73d1f91", "content_id": "2f35eadd445f7efd6674cd845510386abfd005f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6595, "license_type": "permissive", "max_line_length": 133, "num_lines": 161, "path": "/src/test/javascript/spec/component/organization/organization-management-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';\nimport { Observable, of, throwError } from 'rxjs';\nimport { HttpResponse, HttpErrorResponse } from '@angular/common/http';\n\nimport { OrganizationManagementDetailComponent } from 'app/admin/organization-management/organization-management-detail.component';\nimport { OrganizationManagementService } from 'app/admin/organization-management/organization-management.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { Organization } from 'app/entities/organization.model';\nimport { User } from 'app/core/user/user.model';\nimport { Course } from 'app/entities/course.model';\nimport { UserService } from 'app/core/user/user.service';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { DataTableComponent } from 'app/shared/data-table/data-table.component';\n\ndescribe('OrganizationManagementDetailComponent', () => {\n let component: OrganizationManagementDetailComponent;\n let fixture: ComponentFixture<OrganizationManagementDetailComponent>;\n let organizationService: OrganizationManagementService;\n let userService: UserService;\n let dataTable: DataTableComponent;\n\n const organization1 = new Organization();\n organization1.id = 5;\n const route = ({\n data: of({ organization: organization1 }),\n } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, NgxDatatableModule],\n declarations: [OrganizationManagementDetailComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: route },\n { provide: DataTableComponent, useClass: DataTableComponent },\n ],\n })\n .overrideTemplate(OrganizationManagementDetailComponent, '')\n .overrideTemplate(DataTableComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(OrganizationManagementDetailComponent);\n component = fixture.componentInstance;\n organizationService = TestBed.inject(OrganizationManagementService);\n dataTable = TestBed.inject(DataTableComponent);\n userService = TestBed.inject(UserService);\n });\n\n afterEach(async () => {\n jest.clearAllMocks();\n });\n\n it('should initialize and load organization from route', fakeAsync(() => {\n const user = new User();\n user.id = 5;\n user.login = 'user5';\n const course = new Course();\n course.id = 5;\n course.title = 'course5';\n\n organization1.name = 'orgOne';\n organization1.shortName = 'oO1';\n organization1.emailPattern = '.*1';\n organization1.users = [user];\n organization1.courses = [course];\n\n spyOn(organizationService, 'getOrganizationByIdWithUsersAndCourses').and.returnValue(Observable.of(organization1));\n\n component.ngOnInit();\n tick();\n\n expect(component.organization.id).toEqual(organization1.id);\n expect(component.organization.users?.length).toEqual(1);\n expect(component.organization.courses?.length).toEqual(1);\n }));\n\n it('should track id', fakeAsync(() => {\n const user = new User();\n user.id = 5;\n\n expect(component.trackIdentity(0, user)).toEqual(5);\n }));\n\n it('should remove user from organization', fakeAsync(() => {\n organization1.users = createTestUsers();\n component.organization = organization1;\n spyOn(organizationService, 'removeUserFromOrganization').and.returnValue(of(new HttpResponse<void>()));\n\n component.removeFromOrganization(organization1.users[0]);\n tick();\n expect(component.organization.users?.length).toEqual(2);\n }));\n\n it('should not remove user from organization if error occurred', fakeAsync(() => {\n organization1.users = createTestUsers();\n component.organization = organization1;\n spyOn(organizationService, 'removeUserFromOrganization').and.returnValue(throwError(new HttpErrorResponse({ status: 404 })));\n\n component.removeFromOrganization(organization1.users[0]);\n tick();\n expect(component.organization.users?.length).toEqual(3);\n }));\n\n it('should load all current organization users', fakeAsync(() => {\n const user1 = new User();\n user1.id = 11;\n const user2 = new User();\n user2.id = 12;\n const course1 = new Course();\n course1.id = 21;\n organization1.users = [user1, user2];\n organization1.courses = [course1];\n\n spyOn(organizationService, 'getOrganizationByIdWithUsersAndCourses').and.returnValue(Observable.of(organization1));\n\n component.loadAll();\n expect(component.organization.users?.length).toEqual(2);\n expect(component.organization.courses?.length).toEqual(1);\n }));\n\n it('should search users in the used DataTable component', fakeAsync(() => {\n const user1 = { id: 11, login: 'user1' } as User;\n const user2 = { id: 12, login: 'user2' } as User;\n\n spyOn(userService, 'search').and.returnValue(of(new HttpResponse({ body: [user1, user2] })));\n\n component.dataTable = dataTable;\n\n const result = component.searchAllUsers(of({ text: 'user', entities: [] }));\n\n result.subscribe((a) => {\n expect(a).toStrictEqual([\n { id: user1.id, login: user1.login },\n { id: user2.id, login: user2.login },\n ]);\n expect(component.searchNoResults).toEqual(false);\n expect(component.searchFailed).toEqual(false);\n });\n\n tick();\n expect(userService.search).toHaveBeenCalled();\n }));\n\n function createTestUsers() {\n const user1 = new User();\n user1.id = 11;\n user1.login = 'userOne';\n const user2 = new User();\n user2.id = 12;\n const user3 = new User();\n user3.id = 13;\n return [user1, user2, user3];\n }\n});\n" }, { "alpha_fraction": 0.5560123324394226, "alphanum_fraction": 0.5560123324394226, "avg_line_length": 39.12371063232422, "blob_id": "572b6ff5ff51b314258b69064f9639eaf6177dce", "content_id": "d7bcc0c1c1976d08a49e131f52322bcbd548fe3a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3892, "license_type": "permissive", "max_line_length": 119, "num_lines": 97, "path": "/src/main/webapp/app/exercises/shared/exercise-detail-common-actions/non-programming-exercise-detail-common-actions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { Subject } from 'rxjs';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\n\n@Component({\n selector: 'jhi-non-programming-exercise-detail-common-actions',\n templateUrl: './non-programming-exercise-detail-common-actions.component.html',\n styles: [],\n})\nexport class NonProgrammingExerciseDetailCommonActionsComponent {\n @Input()\n exercise: Exercise;\n\n @Input()\n courseId: number;\n\n @Input()\n isExamExercise = false;\n\n dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(\n private textExerciseService: TextExerciseService,\n private fileUploadExerciseService: FileUploadExerciseService,\n private modelingExerciseService: ModelingExerciseService,\n private eventManager: JhiEventManager,\n ) {}\n\n /**\n * Returns the route for editing the exercise. Exam and course exercises have different routes.\n */\n getEditRoute() {\n if (this.isExamExercise) {\n return [\n '/course-management',\n this.exercise.exerciseGroup?.exam?.course?.id,\n 'exams',\n this.exercise.exerciseGroup?.exam?.id,\n 'exercise-groups',\n this.exercise.exerciseGroup?.id,\n this.exercise.type! + '-exercises',\n this.exercise.id,\n 'edit',\n ];\n } else {\n return ['/course-management', this.courseId, this.exercise.type! + '-exercises', this.exercise.id, 'edit'];\n }\n }\n\n deleteExercise() {\n switch (this.exercise.type) {\n case ExerciseType.TEXT:\n this.textExerciseService.delete(this.exercise.id!).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'textExerciseListModification',\n content: 'Deleted a textExercise',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n break;\n case ExerciseType.FILE_UPLOAD:\n this.fileUploadExerciseService.delete(this.exercise.id!).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'fileUploadExerciseListModification',\n content: 'Deleted an fileUploadExercise',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n break;\n case ExerciseType.MODELING:\n this.modelingExerciseService.delete(this.exercise.id!).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'modelingExerciseListModification',\n content: 'Deleted an modelingExercise',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n break;\n default:\n }\n }\n}\n" }, { "alpha_fraction": 0.5384615659713745, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 20.66666603088379, "blob_id": "a67fd5eb01010835989aca6fad9d695a62aab3a0", "content_id": "258961ab54ff887e558e1e754451d6911bbf9f11", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 65, "license_type": "permissive", "max_line_length": 26, "num_lines": 3, "path": "/docs/requirements.txt", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Sphinx==3.2.1\nsphinx-rtd-theme==0.5.0\nsphinx-autobuild==2020.9.1\n" }, { "alpha_fraction": 0.5151286125183105, "alphanum_fraction": 0.5269793272018433, "avg_line_length": 36.771427154541016, "blob_id": "c37488f02243d0b6c45536e542c7882de2b415d8", "content_id": "42d300bb868a9c2ce41317274e3a7bb43b0aac62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 7932, "license_type": "permissive", "max_line_length": 119, "num_lines": 210, "path": "/src/main/resources/config/liquibase/migrationSQL/fillParticipantScore.sql", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "-- FILL IN LAST SCORE INDIVIDUAL\nINSERT INTO participant_score(user_id, exercise_id, last_result_id, last_score, discriminator, last_points)\nWITH last_result AS (\n SELECT DISTINCT e.id as \"exercise_id\",\n e.max_points as \"exercise_max_points\",\n p.student_id as \"student_id\",\n r.id as \"last_result_id\",\n r.score as \"last_result_score\"\n FROM exercise e\n JOIN participation p on e.id = p.exercise_id\n JOIN result r on r.participation_id = p.id\n WHERE e.mode = 'INDIVIDUAL'\n AND p.student_id IS NOT NULL\n AND (p.test_run IS NULL OR p.test_run = 0)\n AND (\n p.discriminator = 'SP'\n OR p.discriminator = 'PESP'\n )\n AND r.score IS NOT NULL\n AND r.completion_date IS NOT NULL\n AND NOT EXISTS(\n SELECT *\n FROM participation p2\n WHERE p2.student_id IS NOT NULL\n AND (p2.test_run IS NULL OR p2.test_run = 0)\n AND (\n p2.discriminator = 'SP'\n OR p2.discriminator = 'PESP'\n )\n AND p2.student_id = p.student_id\n AND p2.exercise_id = p.exercise_id\n AND p2.id > p.id\n )\n AND NOT EXISTS(\n SELECT *\n FROM result r2\n WHERE r2.id <> r.id\n AND r2.score IS NOT NULL\n AND r2.completion_date IS NOT NULL\n AND r2.participation_id = p.id\n AND (r2.completion_date > r.completion_date OR (r2.completion_date = r.completion_date AND r2.id > r.id))\n )\n)\nSELECT lr.student_id,\n lr.exercise_id,\n lr.last_result_id,\n lr.last_result_score,\n 'SS',\n IF(lr.last_result_score IS NOT NULL, ROUND(lr.last_result_score * 0.01 * lr.exercise_max_points, 1), NULL)\nFROM last_result lr;\n\n\n-- UPDATE LAST RATED SCORE INDIVIDUAL\nWITH last_rated_result AS (\n SELECT DISTINCT e.id as \"exercise_id\",\n e.max_points as \"exercise_max_points\",\n p.student_id as \"student_id\",\n r.id as \"last_rated_result_id\",\n r.score as \"last_rated_result_score\"\n FROM exercise e\n JOIN participation p on e.id = p.exercise_id\n JOIN result r on r.participation_id = p.id\n WHERE e.mode = 'INDIVIDUAL'\n AND p.student_id IS NOT NULL\n AND (p.test_run IS NULL OR p.test_run = 0)\n AND (\n p.discriminator = 'SP'\n OR p.discriminator = 'PESP'\n )\n AND r.score IS NOT NULL\n AND r.rated = TRUE\n AND r.completion_date IS NOT NULL\n AND NOT EXISTS(\n SELECT *\n FROM participation p2\n WHERE p2.student_id IS NOT NULL\n AND (p2.test_run IS NULL OR p2.test_run = 0)\n AND (\n p2.discriminator = 'SP'\n OR p2.discriminator = 'PESP'\n )\n AND p2.student_id = p.student_id\n AND p2.exercise_id = p.exercise_id\n AND p2.id > p.id\n )\n AND NOT EXISTS(\n SELECT *\n FROM result r2\n WHERE r2.id <> r.id\n AND r2.score IS NOT NULL\n AND r2.rated = true\n AND r2.completion_date IS NOT NULL\n AND r2.participation_id = p.id\n AND (r2.completion_date > r.completion_date OR (r2.completion_date = r.completion_date AND r2.id > r.id))\n )\n)\nUPDATE participant_score ps,\n (SELECT * from last_rated_result) lr\nSET ps.last_rated_result_id = lr.last_rated_result_id,\n ps.last_rated_score = lr.last_rated_result_score,\n ps.last_rated_points = IF(lr.last_rated_result_score IS NOT NULL,\n ROUND(lr.last_rated_result_score * 0.01 * lr.exercise_max_points, 1), NULL)\nWHERE ps.exercise_id = lr.exercise_id\n AND ps.user_id = lr.student_id;\n\n\n-- FILL IN LAST SCORE TEAM\nINSERT INTO participant_score(team_id, exercise_id, last_result_id, last_score, discriminator, last_points)\nWITH last_result AS (\n SELECT DISTINCT e.id as \"exercise_id\",\n e.max_points as \"exercise_max_points\",\n p.team_id as \"team_id\",\n r.id as \"last_result_id\",\n r.score as \"last_result_score\"\n FROM exercise e\n JOIN participation p on e.id = p.exercise_id\n JOIN result r on r.participation_id = p.id\n WHERE e.mode = 'TEAM'\n AND p.team_id IS NOT NULL\n AND (p.test_run IS NULL OR p.test_run = 0)\n AND (\n p.discriminator = 'SP'\n OR p.discriminator = 'PESP'\n )\n AND r.score IS NOT NULL\n AND r.completion_date IS NOT NULL\n AND NOT EXISTS(\n SELECT *\n FROM participation p2\n WHERE p2.team_id IS NOT NULL\n AND (p2.test_run IS NULL OR p2.test_run = 0)\n AND (\n p2.discriminator = 'SP'\n OR p2.discriminator = 'PESP'\n )\n AND p2.team_id = p.team_id\n AND p2.exercise_id = p.exercise_id\n AND p2.id > p.id\n )\n AND NOT EXISTS(\n SELECT *\n FROM result r2\n WHERE r2.id <> r.id\n AND r2.score IS NOT NULL\n AND r2.completion_date IS NOT NULL\n AND r2.participation_id = p.id\n AND (r2.completion_date > r.completion_date OR (r2.completion_date = r.completion_date AND r2.id > r.id))\n )\n)\nSELECT lr.team_id,\n lr.exercise_id,\n lr.last_result_id,\n lr.last_result_score,\n 'TS',\n IF(lr.last_result_score IS NOT NULL, ROUND(lr.last_result_score * 0.01 * lr.exercise_max_points, 1), NULL)\nFROM last_result lr;\n\n-- UPDATE LAST RATED SCORE TEAM\n\nWITH last_rated_result AS (\n SELECT DISTINCT e.id as \"exercise_id\",\n e.max_points as \"exercise_max_points\",\n p.team_id as \"team_id\",\n r.id as \"last_rated_result_id\",\n r.score as \"last_rated_result_score\"\n FROM exercise e\n JOIN participation p on e.id = p.exercise_id\n JOIN result r on r.participation_id = p.id\n WHERE e.mode = 'TEAM'\n AND p.team_id IS NOT NULL\n AND (p.test_run IS NULL OR p.test_run = 0)\n AND (\n p.discriminator = 'SP'\n OR p.discriminator = 'PESP'\n )\n AND r.score IS NOT NULL\n AND r.rated = TRUE\n AND r.completion_date IS NOT NULL\n AND NOT EXISTS(\n SELECT *\n FROM participation p2\n WHERE p2.team_id IS NOT NULL\n AND (p2.test_run IS NULL OR p2.test_run = 0)\n AND (\n p2.discriminator = 'SP'\n OR p2.discriminator = 'PESP'\n )\n AND p2.team_id = p.team_id\n AND p2.exercise_id = p.exercise_id\n AND p2.id > p.id\n )\n AND NOT EXISTS(\n SELECT *\n FROM result r2\n WHERE r2.id <> r.id\n AND r2.score IS NOT NULL\n AND r2.rated = true\n AND r2.completion_date IS NOT NULL\n AND r2.participation_id = p.id\n AND (r2.completion_date > r.completion_date OR (r2.completion_date = r.completion_date AND r2.id > r.id))\n )\n)\nUPDATE participant_score ps,\n (SELECT * from last_rated_result) lr\nSET ps.last_rated_result_id = lr.last_rated_result_id,\n ps.last_rated_score = lr.last_rated_result_score,\n ps.last_rated_points = IF(lr.last_rated_result_score IS NOT NULL,\n ROUND(lr.last_rated_result_score * 0.01 * lr.exercise_max_points, 1), NULL)\nWHERE ps.exercise_id = lr.exercise_id\n AND ps.team_id = lr.team_id;\n" }, { "alpha_fraction": 0.7734330892562866, "alphanum_fraction": 0.7760523557662964, "avg_line_length": 47.15315246582031, "blob_id": "df0273d7ea9aab56b305989ffecd657112f697b0", "content_id": "655fd60733f42b757f47fb9133f3ec50cba43171", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5345, "license_type": "permissive", "max_line_length": 179, "num_lines": 111, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ProgrammingExerciseSimulationResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.repository.CourseRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.service.feature.Feature;\nimport de.tum.in.www1.artemis.service.feature.FeatureToggle;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseSimulationService;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\n\n/**\n * Only for local development\n * Simulates the creation of a programming exercise without a connection to the VCS and CI server\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n\n@Profile(\"dev\")\n@RestController\n@RequestMapping(ProgrammingExerciseSimulationResource.Endpoints.ROOT)\npublic class ProgrammingExerciseSimulationResource {\n\n private final Logger log = LoggerFactory.getLogger(ProgrammingExerciseResource.class);\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private static final String ENTITY_NAME = \"programmingExercise\";\n\n private final CourseRepository courseRepository;\n\n private final ProgrammingExerciseSimulationService programmingExerciseSimulationService;\n\n private final UserRepository userRepository;\n\n private final AuthorizationCheckService authCheckService;\n\n public ProgrammingExerciseSimulationResource(CourseRepository courseRepository, ProgrammingExerciseSimulationService programmingExerciseSimulationService,\n UserRepository userRepository, AuthorizationCheckService authCheckService) {\n this.courseRepository = courseRepository;\n this.programmingExerciseSimulationService = programmingExerciseSimulationService;\n this.userRepository = userRepository;\n this.authCheckService = authCheckService;\n }\n\n /**\n * POST /programming-exercises/no-vcs-and-ci-available: Setup a new programmingExercise\n * This method creates a new exercise\n * This exercise is only a SIMULATION for the testing of programming exercises without a connection to the VCS and CI server\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n * @param programmingExercise the input to create/setup new exercise\n * @return a Response Entity\n */\n @PostMapping(ProgrammingExerciseSimulationResource.Endpoints.EXERCISES_SIMULATION)\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<ProgrammingExercise> createProgrammingExerciseWithoutVersionControlAndContinuousIntegrationAvailable(\n @RequestBody ProgrammingExercise programmingExercise) {\n log.debug(\"REST request to setup ProgrammingExercise : {}\", programmingExercise);\n\n // fetch course from database to make sure client didn't change groups\n Course course = courseRepository.findByIdElseThrow(programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId());\n User user = userRepository.getUserWithGroupsAndAuthorities();\n if (!authCheckService.isAtLeastInstructorInCourse(course, user)) {\n return forbidden();\n }\n\n programmingExercise.setCourse(course);\n\n programmingExercise.generateAndSetProjectKey();\n try {\n ProgrammingExercise newProgrammingExercise = programmingExerciseSimulationService\n .createProgrammingExerciseWithoutVersionControlAndContinuousIntegrationAvailable(programmingExercise);\n // Setup all repositories etc\n programmingExerciseSimulationService.setupInitialSubmissionsAndResults(programmingExercise);\n return ResponseEntity.created(new URI(\"/api/programming-exercises\" + newProgrammingExercise.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, newProgrammingExercise.getTitle())).body(newProgrammingExercise);\n }\n catch (URISyntaxException e) {\n log.error(\"Error while setting up programming exercise\", e);\n return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)\n .headers(HeaderUtil.createAlert(applicationName, \"An error occurred while setting up the exercise: \" + e.getMessage(), \"errorProgrammingExercise\")).body(null);\n }\n }\n\n public static final class Endpoints {\n\n public static final String ROOT = \"/api\";\n\n public static final String PROGRAMMING_EXERCISES = \"/programming-exercises\";\n\n public static final String EXERCISES_SIMULATION = PROGRAMMING_EXERCISES + \"/no-vcs-and-ci-available\";\n\n }\n}\n" }, { "alpha_fraction": 0.6450533866882324, "alphanum_fraction": 0.649523913860321, "avg_line_length": 51.23351287841797, "blob_id": "5b656f3d30047405d4ddc0c1c972d45546ddeada", "content_id": "fea30c42a94d70b94fae8c1f6e65f5f2d7e582d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 29303, "license_type": "permissive", "max_line_length": 178, "num_lines": 561, "path": "/src/main/webapp/app/overview/course-statistics/course-statistics.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { Subscription } from 'rxjs/Subscription';\nimport { TranslateService } from '@ngx-translate/core';\nimport { sortBy } from 'lodash';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Result } from 'app/entities/result.model';\nimport * as moment from 'moment';\nimport { Exercise, ExerciseType, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport {\n ABSOLUTE_SCORE,\n CourseScoreCalculationService,\n CURRENT_RELATIVE_SCORE,\n MAX_POINTS,\n PRESENTATION_SCORE,\n REACHABLE_POINTS,\n RELATIVE_SCORE,\n} from 'app/overview/course-score-calculation.service';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { round } from 'app/shared/util/utils';\n\nconst QUIZ_EXERCISE_COLOR = '#17a2b8';\nconst PROGRAMMING_EXERCISE_COLOR = '#fd7e14';\nconst MODELING_EXERCISE_COLOR = '#6610f2';\nconst TEXT_EXERCISE_COLOR = '#B00B6B';\nconst FILE_UPLOAD_EXERCISE_COLOR = '#2D9C88';\n\nexport interface CourseStatisticsDataSet {\n data: Array<number>;\n backgroundColor: Array<any>;\n}\n\n@Component({\n selector: 'jhi-course-statistics',\n templateUrl: './course-statistics.component.html',\n styleUrls: ['../course-overview.scss'],\n})\nexport class CourseStatisticsComponent implements OnInit, OnDestroy {\n readonly QUIZ = ExerciseType.QUIZ;\n\n courseId: number;\n private courseExercises: Exercise[];\n private paramSubscription: Subscription;\n private courseUpdatesSubscription: Subscription;\n private translateSubscription: Subscription;\n course?: Course;\n\n // TODO: improve the types here and use maps instead of java script objects\n\n // overall points\n overallPoints = 0;\n overallPointsPerExercise = {};\n\n // relative score\n totalRelativeScore = 0;\n relativeScoresPerExercise = {};\n\n // max points\n overallMaxPoints = 0;\n overallMaxPointsPerExercise = {};\n\n // reachable points\n reachablePoints = 0;\n reachablePointsPerExercise = {};\n\n // current relative score\n currentRelativeScore = 0;\n currentRelativeScoresPerExercise = {};\n\n // presentation score\n overallPresentationScore = 0;\n presentationScoresPerExercise = {};\n presentationScoreEnabled = false;\n\n // this is not an actual exercise, it contains more entries\n // TODO: use a proper type here\n groupedExercises: any[][] = [];\n doughnutChartColors = [QUIZ_EXERCISE_COLOR, PROGRAMMING_EXERCISE_COLOR, MODELING_EXERCISE_COLOR, TEXT_EXERCISE_COLOR, FILE_UPLOAD_EXERCISE_COLOR, 'rgba(0, 0, 0, 0.5)'];\n\n public doughnutChartLabels: string[] = ['Quiz Points', 'Programming Points', 'Modeling Points', 'Text Points', 'File Upload Points', 'Missing Points'];\n public exerciseTitles: object = {\n quiz: {\n name: this.translateService.instant('artemisApp.course.quizExercises'),\n color: QUIZ_EXERCISE_COLOR,\n },\n modeling: {\n name: this.translateService.instant('artemisApp.course.modelingExercises'),\n color: MODELING_EXERCISE_COLOR,\n },\n programming: {\n name: this.translateService.instant('artemisApp.course.programmingExercises'),\n color: PROGRAMMING_EXERCISE_COLOR,\n },\n text: {\n name: this.translateService.instant('artemisApp.course.textExercises'),\n color: TEXT_EXERCISE_COLOR,\n },\n 'file-upload': {\n name: this.translateService.instant('artemisApp.course.fileUploadExercises'),\n color: FILE_UPLOAD_EXERCISE_COLOR,\n },\n };\n\n public doughnutChartData: CourseStatisticsDataSet[] = [\n {\n data: [0, 0, 0, 0, 0, 0],\n backgroundColor: this.doughnutChartColors,\n },\n ];\n\n public barChartOptions: any = {\n scaleShowVerticalLines: false,\n maintainAspectRatio: false,\n responsive: true,\n scales: {\n xAxes: [\n {\n stacked: true,\n ticks: {\n autoSkip: false,\n maxRotation: 0,\n minRotation: 0,\n },\n gridLines: {\n display: false,\n },\n },\n ],\n yAxes: [\n {\n stacked: true,\n },\n ],\n },\n tooltips: {\n backgroundColor: 'rgba(0, 0, 0, 1)',\n width: 120,\n callbacks: {\n label: (tooltipItem: any, data: any) => {\n return data.datasets[tooltipItem.datasetIndex].tooltips[tooltipItem.index];\n },\n afterLabel: (tooltipItem: any, data: any) => {\n return data.datasets[tooltipItem.datasetIndex].footer[tooltipItem.index];\n },\n },\n },\n };\n public barChartType = 'horizontalBar';\n\n public doughnutChartType = 'doughnut';\n public totalScoreOptions: object = {\n cutoutPercentage: 75,\n scaleShowVerticalLines: false,\n responsive: false,\n tooltips: {\n backgroundColor: 'rgba(0, 0, 0, 1)',\n },\n };\n\n constructor(\n private courseService: CourseManagementService,\n private courseCalculationService: CourseScoreCalculationService,\n private translateService: TranslateService,\n private route: ActivatedRoute,\n ) {}\n\n ngOnInit() {\n this.paramSubscription = this.route.parent!.params.subscribe((params) => {\n this.courseId = parseInt(params['courseId'], 10);\n });\n\n this.course = this.courseCalculationService.getCourse(this.courseId);\n this.onCourseLoad();\n\n this.courseUpdatesSubscription = this.courseService.getCourseUpdates(this.courseId).subscribe((course: Course) => {\n this.courseCalculationService.updateCourse(course);\n this.course = this.courseCalculationService.getCourse(this.courseId);\n this.onCourseLoad();\n });\n\n this.translateSubscription = this.translateService.onLangChange.subscribe(() => {\n this.exerciseTitles = {\n quiz: {\n name: this.translateService.instant('artemisApp.course.quizExercises'),\n color: QUIZ_EXERCISE_COLOR,\n },\n modeling: {\n name: this.translateService.instant('artemisApp.course.modelingExercises'),\n color: MODELING_EXERCISE_COLOR,\n },\n programming: {\n name: this.translateService.instant('artemisApp.course.programmingExercises'),\n color: PROGRAMMING_EXERCISE_COLOR,\n },\n text: {\n name: this.translateService.instant('artemisApp.course.textExercises'),\n color: TEXT_EXERCISE_COLOR,\n },\n 'file-upload': {\n name: this.translateService.instant('artemisApp.course.fileUploadExercises'),\n color: FILE_UPLOAD_EXERCISE_COLOR,\n },\n };\n this.groupExercisesByType();\n });\n }\n\n ngOnDestroy() {\n this.translateSubscription.unsubscribe();\n this.courseUpdatesSubscription.unsubscribe();\n this.paramSubscription.unsubscribe();\n }\n\n private onCourseLoad() {\n this.courseExercises = this.course!.exercises!;\n this.calculateMaxPoints();\n this.calculateReachablePoints();\n this.calculateAbsoluteScores();\n this.calculateRelativeScores();\n this.calculatePresentationScores();\n this.calculateCurrentRelativeScores();\n this.groupExercisesByType();\n }\n\n groupExercisesByType() {\n let exercises = this.course!.exercises;\n const groupedExercises: any[] = [];\n const exerciseTypes: string[] = [];\n // adding several years to be sure that exercises without due date are sorted at the end. this is necessary for the order inside the statistic charts\n exercises = sortBy(exercises, [(exercise: Exercise) => (exercise.dueDate || moment().add(5, 'year')).valueOf()]);\n exercises.forEach((exercise) => {\n if (!exercise.dueDate || exercise.dueDate.isBefore(moment()) || exercise.type === ExerciseType.PROGRAMMING) {\n let index = exerciseTypes.indexOf(exercise.type!);\n if (index === -1) {\n index = exerciseTypes.length;\n exerciseTypes.push(exercise.type!);\n }\n if (!groupedExercises[index]) {\n groupedExercises[index] = {\n type: exercise.type,\n relativeScore: 0,\n overallMaxPoints: 0,\n absoluteScore: 0,\n presentationScore: 0,\n presentationScoreEnabled: exercise.presentationScoreEnabled,\n names: [],\n scores: { data: [], label: 'Score', tooltips: [], footer: [], backgroundColor: [], hoverBackgroundColor: [] }, // part of dataset\n missedScores: { data: [], label: 'Missed score', tooltips: [], footer: [], backgroundColor: 'Salmon', hoverBackgroundColor: 'Salmon' }, // part of dataset\n notGraded: { data: [], label: 'Not graded', tooltips: [], footer: [], backgroundColor: 'SkyBlue', hoverBackgroundColor: 'SkyBlue' }, // part of dataset\n reachableScore: 0,\n currentRelativeScore: 0,\n };\n }\n\n if (!exercise.studentParticipations || exercise.studentParticipations.length === 0) {\n groupedExercises[index] = this.createPlaceholderChartElement(groupedExercises[index], exercise.title!, 'exerciseNotParticipated', false);\n } else {\n const scoreColor = this.getScoreColor(exercise.includedInOverallScore!);\n exercise.studentParticipations.forEach((participation) => {\n if (participation.results && participation.results.length > 0) {\n const participationResult = this.courseCalculationService.getResultForParticipation(participation, exercise.dueDate!);\n if (participationResult && participationResult.rated) {\n const roundedParticipationScore = round(participationResult.score!);\n const cappedParticipationScore = roundedParticipationScore >= 100 ? 100 : roundedParticipationScore;\n const missedScore = 100 - cappedParticipationScore;\n groupedExercises[index].scores.data.push(roundedParticipationScore);\n groupedExercises[index].scores.backgroundColor.push(scoreColor);\n groupedExercises[index].scores.hoverBackgroundColor.push(scoreColor);\n groupedExercises[index].missedScores.data.push(missedScore);\n groupedExercises[index].notGraded.data.push(0);\n groupedExercises[index].notGraded.tooltips.push(null);\n groupedExercises[index].names.push(exercise.title);\n groupedExercises[index].scores.footer.push(null);\n groupedExercises[index].missedScores.footer.push(null);\n groupedExercises[index].notGraded.footer.push(null);\n this.generateTooltip(participationResult, groupedExercises[index], exercise.includedInOverallScore!);\n }\n } else {\n if (\n participation.initializationState === InitializationState.FINISHED &&\n (!exercise.dueDate || participation.initializationDate!.isBefore(exercise.dueDate!))\n ) {\n groupedExercises[index] = this.createPlaceholderChartElement(groupedExercises[index], exercise.title!, 'exerciseNotGraded', true);\n } else {\n groupedExercises[index] = this.createPlaceholderChartElement(groupedExercises[index], exercise.title!, 'exerciseParticipatedAfterDueDate', false);\n }\n }\n });\n }\n\n groupedExercises[index].relativeScore = this.relativeScoresPerExercise[exercise.type!];\n groupedExercises[index].overallMaxPoints = this.overallMaxPointsPerExercise[exercise.type!];\n groupedExercises[index].currentRelativeScore = this.currentRelativeScoresPerExercise[exercise.type!];\n groupedExercises[index].reachableScore = this.reachablePointsPerExercise[exercise.type!];\n groupedExercises[index].absoluteScore = this.overallPointsPerExercise[exercise.type!];\n groupedExercises[index].presentationScore = this.presentationScoresPerExercise[exercise.type!];\n // check if presentation score is enabled for at least one exercise\n groupedExercises[index].presentationScoreEnabled = groupedExercises[index].presentationScoreEnabled || exercise.presentationScoreEnabled;\n groupedExercises[index].values = [groupedExercises[index].scores, groupedExercises[index].missedScores, groupedExercises[index].notGraded];\n }\n });\n this.groupedExercises = groupedExercises;\n }\n\n getScoreColor(includedInOverallScore: IncludedInOverallScore): string {\n switch (includedInOverallScore) {\n case IncludedInOverallScore.INCLUDED_COMPLETELY:\n return 'limeGreen';\n case IncludedInOverallScore.NOT_INCLUDED:\n return 'lightGray';\n case IncludedInOverallScore.INCLUDED_AS_BONUS:\n return 'gold';\n }\n }\n\n createPlaceholderChartElement(chartElement: any, exerciseTitle: string, tooltipMessage: string, isNotGraded: boolean) {\n const tooltip = this.translateService.instant(`artemisApp.courseOverview.statistics.${tooltipMessage}`, { exercise: exerciseTitle });\n chartElement.notGraded.data.push(isNotGraded ? 100 : 0);\n chartElement.scores.data.push(0);\n chartElement.missedScores.data.push(isNotGraded ? 0 : 100);\n chartElement.names.push(exerciseTitle);\n chartElement.notGraded.tooltips.push(isNotGraded ? tooltip : null);\n chartElement.scores.tooltips.push(null);\n chartElement.missedScores.tooltips.push(isNotGraded ? null : tooltip);\n chartElement.scores.footer.push(null);\n chartElement.missedScores.footer.push(\n tooltipMessage === 'exerciseParticipatedAfterDueDate' ? this.translateService.instant(`artemisApp.courseOverview.statistics.noPointsForExercise`) : null,\n );\n chartElement.notGraded.footer.push(null);\n return chartElement;\n }\n\n generateTooltipExtension(includedInOverallScore: IncludedInOverallScore): string {\n switch (includedInOverallScore) {\n case IncludedInOverallScore.INCLUDED_AS_BONUS:\n return ' | ' + this.translateService.instant('artemisApp.courseOverview.statistics.bonusPointTooltip');\n case IncludedInOverallScore.NOT_INCLUDED:\n return ' | ' + this.translateService.instant('artemisApp.courseOverview.statistics.notIncludedTooltip');\n default:\n return '';\n }\n }\n\n generateTooltip(result: Result, groupedExercise: any, includedInOverallScore: IncludedInOverallScore): void {\n if (!result.resultString) {\n groupedExercise.scores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseAchievedScore', {\n points: 0,\n percentage: 0,\n }) + this.generateTooltipExtension(includedInOverallScore),\n );\n groupedExercise.missedScores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseMissedScore', {\n points: '',\n percentage: 100,\n }),\n );\n return;\n }\n\n const replaced = result.resultString.replace(',', '.');\n const split = replaced.split(' ');\n\n const missedPoints = parseFloat(split[2]) - parseFloat(split[0]) > 0 ? parseFloat(split[2]) - parseFloat(split[0]) : 0;\n // This score is used to cap bonus points, so that we not have negative values for the missedScores\n const roundedScore = round(result.score!);\n const score = roundedScore >= 100 ? 100 : roundedScore;\n // custom result strings\n if (!replaced.includes('passed') && !replaced.includes('points')) {\n if (roundedScore! >= 50) {\n groupedExercise.scores.tooltips.push(`${result.resultString} (${roundedScore}%)` + this.generateTooltipExtension(includedInOverallScore));\n groupedExercise.missedScores.tooltips.push(`(${100 - score}%)`);\n } else {\n groupedExercise.scores.tooltips.push(`(${roundedScore}%)` + this.generateTooltipExtension(includedInOverallScore));\n groupedExercise.missedScores.tooltips.push(`${result.resultString} (${100 - score}%)`);\n }\n\n return;\n }\n\n // exercise results strings are mostly 'x points' or 'x of y points'\n if (replaced.includes('points')) {\n if (split.length === 2) {\n groupedExercise.scores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseAchievedScore', {\n points: parseFloat(split[0]),\n percentage: roundedScore,\n }) + this.generateTooltipExtension(includedInOverallScore),\n );\n groupedExercise.missedScores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseMissedScore', {\n points: '',\n percentage: 100 - score,\n }),\n );\n return;\n }\n if (split.length === 4) {\n groupedExercise.scores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseAchievedScore', {\n points: parseFloat(split[0]),\n percentage: roundedScore,\n }) + this.generateTooltipExtension(includedInOverallScore),\n );\n groupedExercise.missedScores.tooltips.push(\n this.translateService.instant('artemisApp.courseOverview.statistics.exerciseMissedScore', {\n points: missedPoints,\n percentage: 100 - score,\n }),\n );\n return;\n }\n }\n\n // programming exercise result strings are mostly 'x passed' or 'x of y passed'\n if (replaced.includes('passed')) {\n if (split.length === 2) {\n groupedExercise.scores.tooltips.push(parseFloat(split[0]) + ' tests passed (' + roundedScore + '%).' + this.generateTooltipExtension(includedInOverallScore));\n groupedExercise.missedScores.tooltips.push('(' + (100 - score) + '%)');\n return;\n }\n if (split.length === 4) {\n groupedExercise.scores.tooltips.push(parseFloat(split[0]) + ' tests passed (' + roundedScore + '%).' + this.generateTooltipExtension(includedInOverallScore));\n groupedExercise.missedScores.tooltips.push(missedPoints + ' tests failed (' + (100 - score) + '%).');\n return;\n }\n }\n }\n\n calculateAbsoluteScores(): void {\n const quizzesTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, ABSOLUTE_SCORE);\n const programmingExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, ABSOLUTE_SCORE);\n const modelingExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, ABSOLUTE_SCORE);\n const textExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, ABSOLUTE_SCORE);\n const fileUploadExerciseTotalScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, ABSOLUTE_SCORE);\n this.overallPoints = this.calculateTotalScoreForTheCourse(ABSOLUTE_SCORE);\n let totalMissedPoints = this.reachablePoints - this.overallPoints;\n if (totalMissedPoints < 0) {\n totalMissedPoints = 0;\n }\n const absoluteScores = {};\n absoluteScores[ExerciseType.QUIZ] = quizzesTotalScore;\n absoluteScores[ExerciseType.PROGRAMMING] = programmingExerciseTotalScore;\n absoluteScores[ExerciseType.MODELING] = modelingExerciseTotalScore;\n absoluteScores[ExerciseType.TEXT] = textExerciseTotalScore;\n absoluteScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseTotalScore;\n this.overallPointsPerExercise = absoluteScores;\n this.doughnutChartData[0].data = [\n quizzesTotalScore,\n programmingExerciseTotalScore,\n modelingExerciseTotalScore,\n textExerciseTotalScore,\n fileUploadExerciseTotalScore,\n totalMissedPoints,\n ];\n }\n\n calculateMaxPoints() {\n const quizzesTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, MAX_POINTS);\n const programmingExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, MAX_POINTS);\n const modelingExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, MAX_POINTS);\n const textExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, MAX_POINTS);\n const fileUploadExerciseTotalMaxPoints = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, MAX_POINTS);\n const overallMaxPoints = {};\n overallMaxPoints[ExerciseType.QUIZ] = quizzesTotalMaxPoints;\n overallMaxPoints[ExerciseType.PROGRAMMING] = programmingExerciseTotalMaxPoints;\n overallMaxPoints[ExerciseType.MODELING] = modelingExerciseTotalMaxPoints;\n overallMaxPoints[ExerciseType.TEXT] = textExerciseTotalMaxPoints;\n overallMaxPoints[ExerciseType.FILE_UPLOAD] = fileUploadExerciseTotalMaxPoints;\n this.overallMaxPointsPerExercise = overallMaxPoints;\n this.overallMaxPoints = this.calculateTotalScoreForTheCourse(MAX_POINTS);\n }\n\n calculateRelativeScores(): void {\n const quizzesRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, RELATIVE_SCORE);\n const programmingExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, RELATIVE_SCORE);\n const modelingExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, RELATIVE_SCORE);\n const textExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, RELATIVE_SCORE);\n const fileUploadExerciseRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, RELATIVE_SCORE);\n const relativeScores = {};\n relativeScores[ExerciseType.QUIZ] = quizzesRelativeScore;\n relativeScores[ExerciseType.PROGRAMMING] = programmingExerciseRelativeScore;\n relativeScores[ExerciseType.MODELING] = modelingExerciseRelativeScore;\n relativeScores[ExerciseType.TEXT] = textExerciseRelativeScore;\n relativeScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseRelativeScore;\n this.relativeScoresPerExercise = relativeScores;\n this.totalRelativeScore = this.calculateTotalScoreForTheCourse(RELATIVE_SCORE);\n }\n\n calculateReachablePoints() {\n const quizzesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, REACHABLE_POINTS);\n const programmingExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, REACHABLE_POINTS);\n const modelingExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, REACHABLE_POINTS);\n const textExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, REACHABLE_POINTS);\n const fileUploadExercisesReachablePoints = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, REACHABLE_POINTS);\n const reachablePoints = {};\n reachablePoints[ExerciseType.QUIZ] = quizzesReachablePoints;\n reachablePoints[ExerciseType.PROGRAMMING] = programmingExercisesReachablePoints;\n reachablePoints[ExerciseType.MODELING] = modelingExercisesReachablePoints;\n reachablePoints[ExerciseType.TEXT] = textExercisesReachablePoints;\n reachablePoints[ExerciseType.FILE_UPLOAD] = fileUploadExercisesReachablePoints;\n this.reachablePointsPerExercise = reachablePoints;\n this.reachablePoints = this.calculateTotalScoreForTheCourse(REACHABLE_POINTS);\n }\n\n calculateCurrentRelativeScores(): void {\n const quizzesCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.QUIZ, CURRENT_RELATIVE_SCORE);\n const programmingExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, CURRENT_RELATIVE_SCORE);\n const modelingExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, CURRENT_RELATIVE_SCORE);\n const textExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, CURRENT_RELATIVE_SCORE);\n const fileUploadExerciseCurrentRelativeScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, CURRENT_RELATIVE_SCORE);\n const currentRelativeScores = {};\n currentRelativeScores[ExerciseType.QUIZ] = quizzesCurrentRelativeScore;\n currentRelativeScores[ExerciseType.PROGRAMMING] = programmingExerciseCurrentRelativeScore;\n currentRelativeScores[ExerciseType.MODELING] = modelingExerciseCurrentRelativeScore;\n currentRelativeScores[ExerciseType.TEXT] = textExerciseCurrentRelativeScore;\n currentRelativeScores[ExerciseType.FILE_UPLOAD] = fileUploadExerciseCurrentRelativeScore;\n this.currentRelativeScoresPerExercise = currentRelativeScores;\n this.currentRelativeScore = this.calculateTotalScoreForTheCourse(CURRENT_RELATIVE_SCORE);\n }\n\n calculatePresentationScores(): void {\n const programmingExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.PROGRAMMING, PRESENTATION_SCORE);\n const modelingExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.MODELING, PRESENTATION_SCORE);\n const textExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.TEXT, PRESENTATION_SCORE);\n const fileUploadExercisePresentationScore = this.calculateScoreTypeForExerciseType(ExerciseType.FILE_UPLOAD, PRESENTATION_SCORE);\n // TODO: use a proper type here, e.g. a map\n const presentationScores = {};\n presentationScores[ExerciseType.QUIZ] = 0;\n presentationScores[ExerciseType.PROGRAMMING] = programmingExercisePresentationScore;\n presentationScores[ExerciseType.MODELING] = modelingExercisePresentationScore;\n presentationScores[ExerciseType.TEXT] = textExercisePresentationScore;\n presentationScores[ExerciseType.FILE_UPLOAD] = fileUploadExercisePresentationScore;\n this.presentationScoresPerExercise = presentationScores;\n this.overallPresentationScore = this.calculateTotalScoreForTheCourse(PRESENTATION_SCORE);\n }\n\n calculateScores(filterFunction: (courseExercise: Exercise) => boolean) {\n let courseExercises = this.courseExercises;\n if (filterFunction) {\n courseExercises = courseExercises.filter(filterFunction);\n }\n return this.courseCalculationService.calculateTotalScores(courseExercises);\n }\n\n calculateScoreTypeForExerciseType(exerciseType: ExerciseType, scoreType: string): number {\n if (exerciseType != undefined && scoreType != undefined) {\n const filterFunction = (courseExercise: Exercise) => courseExercise.type === exerciseType;\n const scores = this.calculateScores(filterFunction);\n return scores.get(scoreType)!;\n } else {\n return NaN;\n }\n }\n\n calculateTotalScoreForTheCourse(scoreType: string): number {\n const scores = this.courseCalculationService.calculateTotalScores(this.courseExercises);\n return scores.get(scoreType)!;\n }\n}\n" }, { "alpha_fraction": 0.6669520735740662, "alphanum_fraction": 0.6720890402793884, "avg_line_length": 22.360000610351562, "blob_id": "11a2e421ab2dcd36d944d81cd9f3b40abcf5a8f2", "content_id": "0ae4997614aaf85b4372759456bbae9c16adabb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1168, "license_type": "permissive", "max_line_length": 112, "num_lines": 50, "path": "/src/main/java/de/tum/in/www1/artemis/domain/leaderboard/tutor/TutorLeaderboardComplaints.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.leaderboard.tutor;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n// Custom object for sql query\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class TutorLeaderboardComplaints {\n\n private final long userId;\n\n private final long allComplaints;\n\n private final long acceptedComplaints;\n\n private final double points;\n\n public long getAllComplaints() {\n return allComplaints;\n }\n\n public long getAcceptedComplaints() {\n return acceptedComplaints;\n }\n\n public double getPoints() {\n return points;\n }\n\n public long getUserId() {\n return userId;\n }\n\n public TutorLeaderboardComplaints(long userId, long allComplaints, long acceptedComplaints, double points) {\n this.userId = userId;\n this.allComplaints = allComplaints;\n this.acceptedComplaints = acceptedComplaints;\n this.points = points;\n }\n\n public TutorLeaderboardComplaints() {\n this.userId = 0L;\n this.allComplaints = 0L;\n this.acceptedComplaints = 0L;\n this.points = 0.0;\n }\n\n public Long getKey() {\n return userId;\n }\n}\n" }, { "alpha_fraction": 0.5306122303009033, "alphanum_fraction": 0.5343227982521057, "avg_line_length": 27.36842155456543, "blob_id": "af8a7754acc41954d1ba0a8a67b2ca04229102b7", "content_id": "ed68e6b0f60891321dcb094eb41dae7565e3837a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 539, "license_type": "permissive", "max_line_length": 61, "num_lines": 19, "path": "/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\n\nexport class MockActivatedRoute extends ActivatedRoute {\n testParams: { submissionId: string; exerciseId: number };\n constructor(parameters?: any) {\n super();\n this.queryParams = of(parameters);\n this.params = of(parameters);\n this.data = of({\n ...parameters,\n pagingParams: {\n page: 10,\n ascending: false,\n predicate: 'id',\n },\n });\n }\n}\n" }, { "alpha_fraction": 0.7223974466323853, "alphanum_fraction": 0.7223974466323853, "avg_line_length": 25.41666603088379, "blob_id": "71ad39f02a4db28786382ecf1c82503cbfb73a8a", "content_id": "e8b2451137e345eb36862cd7f4ea3e3ac36fb8e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 317, "license_type": "permissive", "max_line_length": 81, "num_lines": 12, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-feature-toggle.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { of } from 'rxjs';\n\nexport class MockFeatureToggleService {\n getFeatureToggleActive(toggle: FeatureToggle) {\n return of(true);\n }\n\n subscribeFeatureToggleUpdates() {}\n\n unsubscribeFeatureToggleUpdates() {}\n}\n" }, { "alpha_fraction": 0.6046297550201416, "alphanum_fraction": 0.6056819558143616, "avg_line_length": 36.45320129394531, "blob_id": "fde215e173f21023c988be5c045581db110b0854", "content_id": "04bad976cae1003d51dca175fd95bcce98054ed0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7603, "license_type": "permissive", "max_line_length": 133, "num_lines": 203, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/lecture-unit-management.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute, NavigationEnd, Router } from '@angular/router';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { debounceTime, filter, finalize, map } from 'rxjs/operators';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { LectureUnit, LectureUnitType } from 'app/entities/lecture-unit/lectureUnit.model';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { onError } from 'app/shared/util/global.utils';\nimport { Subject, Subscription } from 'rxjs';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { ExerciseUnit } from 'app/entities/lecture-unit/exerciseUnit.model';\n\n@Component({\n selector: 'jhi-lecture-unit-management',\n templateUrl: './lecture-unit-management.component.html',\n styleUrls: ['./lecture-unit-management.component.scss'],\n})\nexport class LectureUnitManagementComponent implements OnInit, OnDestroy {\n lectureId: number;\n lectureUnits: LectureUnit[] = [];\n lecture: Lecture;\n isLoading = false;\n updateOrderSubject: Subject<any>;\n updateOrderSubjectSubscription: Subscription;\n navigationEndSubscription: Subscription;\n readonly LectureUnitType = LectureUnitType;\n readonly ActionType = ActionType;\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private lectureService: LectureService,\n private alertService: JhiAlertService,\n private lectureUnitService: LectureUnitService,\n ) {}\n\n ngOnDestroy(): void {\n this.updateOrder();\n this.updateOrderSubjectSubscription.unsubscribe();\n this.dialogErrorSource.unsubscribe();\n this.navigationEndSubscription.unsubscribe();\n }\n\n ngOnInit(): void {\n this.navigationEndSubscription = this.router.events.pipe(filter((value) => value instanceof NavigationEnd)).subscribe(() => {\n this.loadData();\n });\n\n this.updateOrderSubject = new Subject();\n this.activatedRoute.parent!.params.subscribe((params) => {\n this.lectureId = +params['lectureId'];\n if (this.lectureId) {\n this.loadData();\n }\n });\n\n // debounceTime limits the amount of put requests sent for updating the lecture unit order\n this.updateOrderSubjectSubscription = this.updateOrderSubject.pipe(debounceTime(1000)).subscribe(() => {\n this.updateOrder();\n });\n }\n\n loadData() {\n this.isLoading = true;\n this.lectureService\n .find(this.lectureId)\n .pipe(\n map((response: HttpResponse<Lecture>) => response.body!),\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n (lecture) => {\n this.lecture = lecture;\n if (lecture?.lectureUnits) {\n this.lectureUnits = lecture?.lectureUnits;\n } else {\n this.lectureUnits = [];\n }\n },\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n\n updateOrder() {\n this.lectureUnitService\n .updateOrder(this.lectureId, this.lectureUnits)\n .pipe(map((response: HttpResponse<LectureUnit[]>) => response.body!))\n .subscribe(\n () => {},\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n\n moveUp(index: number): void {\n if (this.lectureUnits) {\n [this.lectureUnits[index], this.lectureUnits[index - 1]] = [this.lectureUnits[index - 1], this.lectureUnits[index]];\n }\n this.updateOrderSubject.next('up');\n }\n\n moveDown(index: number): void {\n if (this.lectureUnits) {\n [this.lectureUnits[index], this.lectureUnits[index + 1]] = [this.lectureUnits[index + 1], this.lectureUnits[index]];\n }\n this.updateOrderSubject.next('down');\n }\n\n identify(index: number, lectureUnit: LectureUnit) {\n return `${index}-${lectureUnit.id}`;\n }\n\n getDeleteQuestionKey(lectureUnit: LectureUnit) {\n switch (lectureUnit.type) {\n case LectureUnitType.EXERCISE:\n return 'artemisApp.exerciseUnit.delete.question';\n case LectureUnitType.ATTACHMENT:\n return 'artemisApp.attachmentUnit.delete.question';\n case LectureUnitType.VIDEO:\n return 'artemisApp.videoUnit.delete.question';\n case LectureUnitType.TEXT:\n return 'artemisApp.textUnit.delete.question';\n }\n }\n\n getDeleteConfirmationTextKey(lectureUnit: LectureUnit) {\n switch (lectureUnit.type) {\n case LectureUnitType.EXERCISE:\n return 'artemisApp.exerciseUnit.delete.typeNameToConfirm';\n case LectureUnitType.ATTACHMENT:\n return 'artemisApp.attachmentUnit.delete.typeNameToConfirm';\n case LectureUnitType.VIDEO:\n return 'artemisApp.videoUnit.delete.typeNameToConfirm';\n case LectureUnitType.TEXT:\n return 'artemisApp.textUnit.delete.typeNameToConfirm';\n }\n }\n\n getActionType(lectureUnit: LectureUnit) {\n if (lectureUnit.type === LectureUnitType.EXERCISE) {\n return ActionType.Unlink;\n } else {\n return ActionType.Delete;\n }\n }\n\n deleteLectureUnit(lectureUnitId: number) {\n this.lectureUnitService.delete(lectureUnitId, this.lectureId).subscribe(\n () => {\n this.dialogErrorSource.next('');\n this.loadData();\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n editButtonAvailable(lectureUnit: LectureUnit) {\n switch (lectureUnit?.type) {\n case LectureUnitType.ATTACHMENT:\n case LectureUnitType.TEXT:\n case LectureUnitType.VIDEO:\n return true;\n default:\n return false;\n }\n }\n\n editButtonRouterLink(lectureUnit: LectureUnit) {\n switch (lectureUnit?.type) {\n case LectureUnitType.ATTACHMENT:\n return ['attachment-units', lectureUnit.id, 'edit'];\n break;\n case LectureUnitType.VIDEO: {\n return ['video-units', lectureUnit.id, 'edit'];\n break;\n }\n case LectureUnitType.TEXT: {\n return ['text-units', lectureUnit.id, 'edit'];\n break;\n }\n default:\n return;\n }\n }\n\n getLectureUnitName(lectureUnit: LectureUnit): string | undefined {\n switch (lectureUnit?.type) {\n case LectureUnitType.ATTACHMENT:\n return (<AttachmentUnit>lectureUnit)?.attachment?.name;\n case LectureUnitType.EXERCISE:\n return (<ExerciseUnit>lectureUnit)?.exercise?.title;\n default:\n return lectureUnit.name;\n }\n }\n}\n" }, { "alpha_fraction": 0.619087815284729, "alphanum_fraction": 0.6252111196517944, "avg_line_length": 36.88800048828125, "blob_id": "9bb177d46913f16366dff766883920a92ba0ec30", "content_id": "27ff8cd724cb07663ea098c647fc1fe4758c4f99", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4736, "license_type": "permissive", "max_line_length": 170, "num_lines": 125, "path": "/src/main/webapp/app/exam/participate/summary/points-summary/exam-points-summary.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport * as moment from 'moment';\nimport { Exercise, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\nimport { Exam } from 'app/entities/exam.model';\nimport { round } from 'app/shared/util/utils';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\n@Component({\n selector: 'jhi-exam-points-summary',\n templateUrl: './exam-points-summary.component.html',\n})\nexport class ExamPointsSummaryComponent {\n readonly IncludedInOverallScore = IncludedInOverallScore;\n @Input() exercises: Exercise[];\n @Input() exam: Exam;\n\n constructor(private serverDateService: ArtemisServerDateService, public exerciseService: ExerciseService) {}\n\n /**\n * The points summary table will only be shown if:\n * - exam.publishResultsDate is set\n * - we are after the exam.publishResultsDate\n * - at least one exercise has a result\n */\n show(): boolean {\n return !!(this.exam && this.exam.publishResultsDate && moment(this.exam.publishResultsDate).isBefore(this.serverDateService.now()) && this.hasAtLeastOneResult());\n }\n\n /**\n * Calculate the achieved points of an exercise.\n * @param exercise\n */\n calculateAchievedPoints(exercise: Exercise): number {\n if (ExamPointsSummaryComponent.hasResultScore(exercise)) {\n return round(exercise.maxPoints! * (exercise.studentParticipations![0].results![0].score! / 100), 1);\n }\n return 0;\n }\n\n /**\n * Calculate the sum of points the student achieved in exercises that count towards his or her score.\n */\n calculatePointsSum(): number {\n if (this.exercises) {\n const exercisesIncluded = this.exercises?.filter((exercise) => exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED);\n return round(\n exercisesIncluded.reduce((sum: number, nextExercise: Exercise) => sum + this.calculateAchievedPoints(nextExercise), 0),\n 1,\n );\n }\n return 0;\n }\n\n /**\n * Calculate the max. achievable points.\n */\n calculateMaxPointsSum(): number {\n if (this.exercises) {\n const exercisesIncluded = this.exercises?.filter((exercise) => exercise.includedInOverallScore === IncludedInOverallScore.INCLUDED_COMPLETELY);\n return round(\n exercisesIncluded.reduce((sum: number, nextExercise: Exercise) => sum + ExamPointsSummaryComponent.getMaxScore(nextExercise), 0),\n 1,\n );\n }\n return 0;\n }\n\n /**\n * Calculate the max. achievable bonusPoints.\n */\n calculateMaxBonusPointsSum(): number {\n if (this.exercises) {\n const exercisesIncluded = this.exercises?.filter((exercise) => exercise.includedInOverallScore !== IncludedInOverallScore.NOT_INCLUDED);\n return round(\n exercisesIncluded.reduce((sum: number, nextExercise: Exercise) => sum + ExamPointsSummaryComponent.getBonusPoints(nextExercise), 0),\n 1,\n );\n }\n return 0;\n }\n\n private hasAtLeastOneResult(): boolean {\n if (this.exercises && this.exercises.length > 0) {\n return this.exercises.some((exercise) => {\n return (\n exercise.studentParticipations &&\n exercise.studentParticipations.length > 0 &&\n exercise.studentParticipations[0].results &&\n exercise.studentParticipations[0].results.length > 0\n );\n });\n }\n return false;\n }\n\n private static hasResultScore(exercise: Exercise): boolean {\n return !!(\n exercise &&\n exercise.maxPoints &&\n exercise.studentParticipations &&\n exercise.studentParticipations.length > 0 &&\n exercise.studentParticipations[0].results &&\n exercise.studentParticipations[0].results.length > 0 &&\n exercise.studentParticipations[0].results[0].score\n );\n }\n\n private static getMaxScore(exercise: Exercise): number {\n if (exercise && exercise.maxPoints) {\n return exercise.maxPoints;\n }\n return 0;\n }\n\n private static getBonusPoints(exercise: Exercise): number {\n if (exercise && exercise.includedInOverallScore === IncludedInOverallScore.INCLUDED_AS_BONUS && exercise.maxPoints) {\n return exercise.maxPoints;\n } else if (exercise && exercise.bonusPoints) {\n return exercise.bonusPoints;\n } else {\n return 0;\n }\n }\n}\n" }, { "alpha_fraction": 0.6232464909553528, "alphanum_fraction": 0.6232464909553528, "avg_line_length": 28.352941513061523, "blob_id": "cc2c913792c8571939ef922a22ce64e10d0e1a4e", "content_id": "38a77c731fd140ac742f84a2057d195244be2020", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 499, "license_type": "permissive", "max_line_length": 75, "num_lines": 17, "path": "/src/test/javascript/jest.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import 'jest-preset-angular/setup-jest';\nimport './jest-global-mocks';\nimport 'jest-canvas-mock';\n\nconst noop = () => {};\n\nObject.defineProperty(window, 'scrollTo', { value: noop, writable: true });\nObject.defineProperty(window, 'scroll', { value: noop, writable: true });\nObject.defineProperty(window, 'alert', { value: noop, writable: true });\n\nObject.defineProperty(window, 'getComputedStyle', {\n value: () => ({\n getPropertyValue: () => {\n return '';\n },\n }),\n});\n" }, { "alpha_fraction": 0.6107226014137268, "alphanum_fraction": 0.6107226014137268, "avg_line_length": 31.29032325744629, "blob_id": "1bf4b7ad756587719a34679acf33066a868f6b37", "content_id": "1abe4332cd6830a8c11d7c9108ddb49d1d7e3dd3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3003, "license_type": "permissive", "max_line_length": 172, "num_lines": 93, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/participate/exercise-hint-student-dialog.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { of } from 'rxjs';\nimport { catchError, map, tap } from 'rxjs/operators';\n\nimport { NgbActiveModal, NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\n\nimport { ExerciseHintService } from '../manage/exercise-hint.service';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\n\n/**\n * This component is a modal that shows the exercise's hints.\n */\n@Component({\n selector: 'jhi-exercise-hint-student-dialog',\n templateUrl: './exercise-hint-student-dialog.component.html',\n styleUrls: ['./exercise-hint-student-dialog.scss'],\n})\nexport class ExerciseHintStudentDialogComponent {\n @Input() exerciseHints: ExerciseHint[];\n\n constructor(public activeModal: NgbActiveModal) {}\n\n /**\n * Dismisses the modal\n */\n clear() {\n this.activeModal.dismiss('cancel');\n }\n}\n\n/**\n * This component is a question mark icon the user can click on the see the provided exercise's hints.\n */\n@Component({\n selector: 'jhi-exercise-hint-student',\n template: `\n <fa-icon\n *ngIf=\"exerciseHints && exerciseHints.length\"\n [icon]=\"['far', 'question-circle']\"\n (click)=\"openModal()\"\n class=\"hint-icon text-secondary\"\n ngbTooltip=\"{{ 'artemisApp.exerciseHint.studentDialog.tooltip' | translate }}\"\n ></fa-icon>\n `,\n styleUrls: ['./exercise-hint-student-dialog.scss'],\n})\nexport class ExerciseHintStudentComponent implements OnInit, OnDestroy {\n @Input() exerciseId: number;\n @Input() exerciseHints: ExerciseHint[] | null;\n protected ngbModalRef: NgbModalRef | null;\n\n constructor(protected exerciseHintService: ExerciseHintService, protected activatedRoute: ActivatedRoute, protected router: Router, protected modalService: NgbModal) {}\n\n /**\n * Fetches all exercise hints for an exercise from the server\n */\n ngOnInit() {\n if (!this.exerciseHints) {\n this.exerciseHintService\n .findByExerciseId(this.exerciseId)\n .pipe(\n map(({ body }) => body),\n tap((hints: ExerciseHint[]) => (this.exerciseHints = hints)),\n catchError(() => of()),\n )\n .subscribe();\n }\n }\n\n /**\n * Open the exercise hint student dialog (see component above).\n */\n openModal() {\n this.ngbModalRef = this.modalService.open(ExerciseHintStudentDialogComponent as Component, { size: 'lg', backdrop: 'static' });\n this.ngbModalRef.componentInstance.exerciseHints = this.exerciseHints;\n this.ngbModalRef.result.then(\n () => {\n this.ngbModalRef = null;\n },\n () => {\n this.ngbModalRef = null;\n },\n );\n }\n\n /**\n * Resets the modal ref\n */\n ngOnDestroy() {\n this.ngbModalRef = null;\n }\n}\n" }, { "alpha_fraction": 0.7268738746643066, "alphanum_fraction": 0.7294332981109619, "avg_line_length": 35.46666717529297, "blob_id": "b273a2b598a404054d23ae350d11752892443dda", "content_id": "3a3075ca8efba3859771741d7aa733da08dd1d8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2735, "license_type": "permissive", "max_line_length": 90, "num_lines": 75, "path": "/src/test/java/de/tum/in/www1/artemis/GitlabServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.net.URISyntaxException;\nimport java.net.URL;\n\nimport org.gitlab4j.api.GitLabApiException;\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\n\nimport de.tum.in.www1.artemis.exception.VersionControlException;\n\npublic class GitlabServiceTest extends AbstractSpringIntegrationJenkinsGitlabTest {\n\n @Value(\"${artemis.version-control.url}\")\n private URL gitlabServerUrl;\n\n @BeforeEach\n public void initTestCase() {\n gitlabRequestMockProvider.enableMockingOfRequests();\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n gitlabRequestMockProvider.reset();\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void testCheckIfProjectExistsFails() throws GitLabApiException {\n gitlabRequestMockProvider.mockFailToCheckIfProjectExists(\"project-key\");\n try {\n versionControlService.checkIfProjectExists(\"project-key\", \"project-name\");\n }\n catch (VersionControlException e) {\n assertThat(e.getMessage()).isNotEmpty();\n }\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void testHealthOk() throws URISyntaxException, JsonProcessingException {\n gitlabRequestMockProvider.mockHealth(\"ok\", HttpStatus.OK);\n var health = versionControlService.health();\n assertThat(health.getAdditionalInfo().get(\"url\")).isEqualTo(gitlabServerUrl);\n assertThat(health.isUp()).isEqualTo(true);\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void testHealthNotOk() throws URISyntaxException, JsonProcessingException {\n gitlabRequestMockProvider.mockHealth(\"notok\", HttpStatus.OK);\n var health = versionControlService.health();\n assertThat(health.getAdditionalInfo().get(\"url\")).isEqualTo(gitlabServerUrl);\n assertThat(health.getAdditionalInfo().get(\"status\")).isEqualTo(\"notok\");\n assertThat(health.isUp()).isEqualTo(false);\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void testHealthException() throws URISyntaxException, JsonProcessingException {\n gitlabRequestMockProvider.mockHealth(\"ok\", HttpStatus.INTERNAL_SERVER_ERROR);\n var health = versionControlService.health();\n assertThat(health.isUp()).isEqualTo(false);\n assertThat(health.getException()).isNotNull();\n }\n}\n" }, { "alpha_fraction": 0.6426955461502075, "alphanum_fraction": 0.6431717872619629, "avg_line_length": 47.83139419555664, "blob_id": "69ea0526a450816d2f37eaf4d104ecdcf71bd7b2", "content_id": "1e0a675903bd607ab59c266e03db497b1521355c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8399, "license_type": "permissive", "max_line_length": 177, "num_lines": 172, "path": "/src/main/webapp/app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { TranslateService } from '@ngx-translate/core';\nimport { compose, filter, flatten, map, reduce, uniq } from 'lodash/fp';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { matchRegexWithLineNumbers, RegExpLineNumberMatchArray } from 'app/shared/util/global.utils';\nimport {\n AnalysisItem,\n ProblemStatementAnalysis,\n ProblemStatementIssue,\n} from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.model';\n\n/**\n * Analyzes the problem statement of a programming-exercise and provides information support concerning potential issues.\n */\n@Injectable()\nexport class ProgrammingExerciseInstructionAnalysisService {\n private readonly TEST_CASE_REGEX = new RegExp('.*?\\\\((.*)\\\\)');\n private readonly HINT_REGEX = new RegExp('.*{(.*)}');\n private readonly INVALID_TEST_CASE_TRANSLATION = 'artemisApp.programmingExercise.testCaseAnalysis.invalidTestCase';\n private readonly INVALID_HINT_TRANSLATION = 'artemisApp.programmingExercise.hintsAnalysis.invalidHint';\n\n constructor(private translateService: TranslateService) {}\n\n /**\n * Given a programming exercise's problem statement, analyze the test cases and hints contained (or not contained!) in it.\n * Will give out a mixed object that contains singular analysis for test cases / hints and a accumulated analysis object.\n *\n * @param problemStatement multiline string.\n * @param taskRegex identifies tasks in a problem statement.\n * @param exerciseTestCases used to check if a test case is valid / missing.\n * @param exerciseHints used to check if a hint is valid.\n */\n public analyzeProblemStatement = (problemStatement: string, taskRegex: RegExp, exerciseTestCases: string[], exerciseHints: ExerciseHint[]) => {\n // Look for task regex matches in the problem statement including their line numbers.\n const tasksFromProblemStatement = matchRegexWithLineNumbers(problemStatement, taskRegex);\n\n const { invalidTestCases, missingTestCases, invalidTestCaseAnalysis } = this.analyzeTestCases(tasksFromProblemStatement, exerciseTestCases);\n const { invalidHints, invalidHintAnalysis } = this.analyzeHints(tasksFromProblemStatement, exerciseHints);\n\n const completeAnalysis: ProblemStatementAnalysis = this.mergeAnalysis(invalidTestCaseAnalysis, invalidHintAnalysis);\n return { invalidTestCases, missingTestCases, invalidHints, completeAnalysis };\n };\n\n /**\n * Analyze the test cases for the following criteria:\n * - Are test cases in the problem statement that don't exist for the exercise?\n * - Do test cases exist for this exercise that are not part of the problem statement?\n *\n * Will also set the invalidTestCases & missingTestCases attributes of the component.\n *\n * @param tasksFromProblemStatement to analyze.\n * @param exerciseTestCases to double check the test cases found in the problem statement.\n */\n private analyzeTestCases = (tasksFromProblemStatement: RegExpLineNumberMatchArray, exerciseTestCases: string[]) => {\n // Extract the testCase list from the task matches.\n const testCasesInMarkdown = this.extractRegexFromTasks(tasksFromProblemStatement, this.TEST_CASE_REGEX);\n // Look for test cases that are not part of the test repository. Could e.g. be typos.\n const invalidTestCaseAnalysis = testCasesInMarkdown\n .map(\n ([lineNumber, testCases]) =>\n [\n lineNumber,\n testCases.filter((testCase) => !exerciseTestCases.map((exTestcase) => exTestcase.toLowerCase()).includes(testCase.toLowerCase())),\n ProblemStatementIssue.INVALID_TEST_CASES,\n ] as AnalysisItem,\n )\n .filter(([, testCases]) => testCases.length);\n // Look for test cases that are part of the test repository but not in the problem statement. Probably forgotten to insert.\n const missingTestCases = exerciseTestCases.filter(\n (testCase) => !testCasesInMarkdown.some(([, foundTestCases]) => foundTestCases.map((foundTestCase) => foundTestCase.toLowerCase()).includes(testCase.toLowerCase())),\n );\n\n const invalidTestCases = compose(\n flatten,\n map(([, testCases]) => testCases),\n )(invalidTestCaseAnalysis);\n\n return { missingTestCases, invalidTestCases, invalidTestCaseAnalysis };\n };\n\n /**\n * Analyze the hints for the following criteria:\n * - Are hints in the problem statement that don't exist for the exercise?\n *\n * Will also set the invalidHints attribute of the component.\n *\n * @param tasksFromProblemStatement to check if they contain hints.\n * @param exerciseHints to double check the exercise hints found in the problem statement.\n */\n private analyzeHints = (tasksFromProblemStatement: RegExpLineNumberMatchArray, exerciseHints: ExerciseHint[]) => {\n const hintsInMarkdown = this.extractRegexFromTasks(tasksFromProblemStatement, this.HINT_REGEX);\n const invalidHintAnalysis = hintsInMarkdown\n .map(\n ([lineNumber, hints]): AnalysisItem => [\n lineNumber,\n hints.filter((hint) => !exerciseHints.some((exerciseHint) => exerciseHint.id!.toString(10) === hint)),\n ProblemStatementIssue.INVALID_HINTS,\n ],\n )\n .filter(([, hints]) => !!hints.length);\n\n const invalidHints = compose(\n flatten,\n map(([, testCases]) => testCases),\n )(invalidHintAnalysis);\n\n return { invalidHints, invalidHintAnalysis };\n };\n\n /**\n * Merges multiple AnalyseItem[] into one accumulated ProblemStatementAnalysis.\n *\n * @param analysis arbitrary number of analysis objects to be merged into one.\n */\n private mergeAnalysis = (...analysis: Array<AnalysisItem[]>) => {\n return compose(\n reduce((acc, [lineNumber, values, issueType]) => {\n const lineNumberValues = acc[lineNumber];\n const issueValues = lineNumberValues ? lineNumberValues[issueType] || [] : [];\n return { ...acc, [lineNumber]: { ...lineNumberValues, [issueType]: [...issueValues, ...values] } };\n }, {}),\n map(([lineNumber, values, issueType]: AnalysisItem) => [\n lineNumber,\n values.map((id) => this.translateService.instant(this.getTranslationByIssueType(issueType), { id })),\n issueType,\n ]),\n flatten,\n )(analysis);\n };\n\n /**\n * Matches the issueType to a translation. A given translation should have {{id}} as a parameter.\n *\n * @param issueType for which to retrieve the fitting translation.\n */\n private getTranslationByIssueType = (issueType: ProblemStatementIssue) => {\n switch (issueType) {\n case ProblemStatementIssue.INVALID_TEST_CASES:\n return this.INVALID_TEST_CASE_TRANSLATION;\n case ProblemStatementIssue.INVALID_HINTS:\n return this.INVALID_HINT_TRANSLATION;\n default:\n return '';\n }\n };\n\n /**\n * Extracts the given regex from the task.\n * Value will be null if no match is found!\n *\n * @param tasks that contain the given regex.\n * @param regex to search for in the tasks.\n */\n private extractRegexFromTasks(tasks: [number, string][], regex: RegExp): [number, string[]][] {\n return compose(\n map(([lineNumber, match]) => {\n const cleanedMatches = compose(\n uniq,\n filter((m) => !!m),\n flatten,\n )(match.split(/,(?![^(]*?\\))/).map((m: string) => m.trim()));\n return [lineNumber, cleanedMatches];\n }),\n filter(([, testCases]) => !!testCases),\n map(([lineNumber, task]) => {\n const extractedValue = task.match(regex);\n return extractedValue && extractedValue.length > 1 ? [lineNumber, extractedValue[1]] : [lineNumber, null];\n }),\n filter(([, task]) => !!task),\n )(tasks) as [number, string[]][];\n }\n}\n" }, { "alpha_fraction": 0.7209156155586243, "alphanum_fraction": 0.7242369651794434, "avg_line_length": 53.87684631347656, "blob_id": "27e9398e88c9bdcf52cb9326fb588e6a86473349", "content_id": "1cfeea58e155228b9e7fd718631d79e319af13f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11140, "license_type": "permissive", "max_line_length": 172, "num_lines": 203, "path": "/src/main/java/de/tum/in/www1/artemis/service/ParticipantScoreService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.service.util.RoundingUtil.round;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.stereotype.Service;\nimport org.springframework.web.bind.annotation.RequestParam;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseMode;\nimport de.tum.in.www1.artemis.domain.enumeration.IncludedInOverallScore;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.exam.ExerciseGroup;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreAverageDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ParticipantScoreDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.ScoreDTO;\n\n@Service\npublic class ParticipantScoreService {\n\n private final UserRepository userRepository;\n\n private final StudentScoreRepository studentScoreRepository;\n\n private final TeamScoreRepository teamScoreRepository;\n\n private final ParticipantScoreRepository participantScoreRepository;\n\n public ParticipantScoreService(UserRepository userRepository, StudentScoreRepository studentScoreRepository, TeamScoreRepository teamScoreRepository,\n ParticipantScoreRepository participantScoreRepository) {\n this.userRepository = userRepository;\n this.studentScoreRepository = studentScoreRepository;\n this.teamScoreRepository = teamScoreRepository;\n this.participantScoreRepository = participantScoreRepository;\n }\n\n /**\n * This method represents a server based way to calculate a students achieved points / score in an exam.\n * <p>\n * Currently both this server based calculation method and the traditional client side calculation method is used\n * side-by-side in exam-scores.component.ts.\n * <p>\n * The goal is to switch completely to this much faster server based calculation if the {@link de.tum.in.www1.artemis.service.listeners.ResultListener}\n * has been battle tested enough.\n *\n * @param exam the exam with registered students, exercise groups and exercises for which to calculate the scores\n * @return list of scores for every registered student\n */\n public List<ScoreDTO> calculateExamScores(Exam exam) {\n if (exam == null || exam.getExerciseGroups() == null) {\n throw new IllegalArgumentException();\n }\n Set<Exercise> exercisesOfExam = new HashSet<>();\n exam.getExerciseGroups().stream().map(ExerciseGroup::getExercises).forEach(exercisesOfExam::addAll);\n Set<Exercise> includedExercises = exercisesOfExam.stream().filter(exercise -> !exercise.getIncludedInOverallScore().equals(IncludedInOverallScore.NOT_INCLUDED))\n .collect(Collectors.toSet());\n\n return calculateScores(includedExercises, exam.getRegisteredUsers(), exam.getMaxPoints().doubleValue());\n }\n\n /**\n * This method represents a server based way to calculate a students achieved points / score in a course.\n * <p>\n * Currently both this server based calculation method and the traditional client side calculation method is used\n * side-by-side in course-scores.component.ts.\n * <p>\n * The goal is to switch completely to this much faster server based calculation if the {@link de.tum.in.www1.artemis.service.listeners.ResultListener}\n * has been battle tested enough.\n *\n * @param course the course with exercises for which to calculate the course scores\n * @return list of course scores for every member of the course\n */\n public List<ScoreDTO> calculateCourseScores(Course course) {\n if (course == null || course.getExercises() == null) {\n throw new IllegalArgumentException();\n }\n\n // we want the score for everybody who can perform exercises in the course (students, tutors and instructors)\n Set<User> usersOfCourse = new HashSet<>();\n usersOfCourse.addAll(userRepository.findAllInGroupWithAuthorities(course.getStudentGroupName()));\n usersOfCourse.addAll(userRepository.findAllInGroupWithAuthorities(course.getTeachingAssistantGroupName()));\n usersOfCourse.addAll(userRepository.findAllInGroupWithAuthorities(course.getInstructorGroupName()));\n\n // we only consider released exercises that are not optional\n Set<Exercise> exercisesToConsider = course.getExercises().stream().filter(Exercise::isCourseExercise)\n .filter(exercise -> exercise.getReleaseDate() == null || exercise.getReleaseDate().isBefore(ZonedDateTime.now()))\n .filter(exercise -> exercise.getIncludedInOverallScore() != IncludedInOverallScore.NOT_INCLUDED).collect(Collectors.toSet());\n\n // this is the denominator when we calculate the achieved score of a student\n Double regularAchievablePoints = exercisesToConsider.stream().filter(exercise -> exercise.getIncludedInOverallScore() == IncludedInOverallScore.INCLUDED_COMPLETELY)\n .map(Exercise::getMaxPoints).reduce(0.0, Double::sum);\n\n return calculateScores(exercisesToConsider, usersOfCourse, regularAchievablePoints);\n }\n\n private List<ScoreDTO> calculateScores(Set<Exercise> exercises, Set<User> users, Double scoreCalculationDenominator) {\n // 0.0 means we can not reasonably calculate the achieved points / scores\n if (scoreCalculationDenominator.equals(0.0)) {\n return List.of();\n }\n\n Set<Exercise> individualExercises = exercises.stream().filter(exercise -> !exercise.isTeamMode()).collect(Collectors.toSet());\n Set<Exercise> teamExercises = exercises.stream().filter(Exercise::isTeamMode).collect(Collectors.toSet());\n\n // For every student we want to calculate the score\n Map<Long, ScoreDTO> userIdToScores = users.stream().collect(Collectors.toMap(User::getId, ScoreDTO::new));\n\n // individual exercises\n // [0] -> User\n // [1] -> sum of achieved points in exercises\n List<Object[]> studentAndAchievedPoints = studentScoreRepository.getAchievedPointsOfStudents(individualExercises);\n for (Object[] rawData : studentAndAchievedPoints) {\n User user = (User) rawData[0];\n double achievedPoints = rawData[1] != null ? ((Number) rawData[1]).doubleValue() : 0.0;\n if (userIdToScores.containsKey(user.getId())) {\n userIdToScores.get(user.getId()).pointsAchieved += achievedPoints;\n }\n }\n\n // team exercises\n // [0] -> Team\n // [1] -> sum of achieved points in exercises\n List<Object[]> teamAndAchievedPoints = teamScoreRepository.getAchievedPointsOfTeams(teamExercises);\n for (Object[] rawData : teamAndAchievedPoints) {\n Team team = (Team) rawData[0];\n double achievedPoints = rawData[1] != null ? ((Number) rawData[1]).doubleValue() : 0.0;\n for (User student : team.getStudents()) {\n if (userIdToScores.containsKey(student.getId())) {\n userIdToScores.get(student.getId()).pointsAchieved += achievedPoints;\n }\n }\n }\n\n // calculating achieved score\n for (ScoreDTO scoreDTO : userIdToScores.values()) {\n scoreDTO.scoreAchieved = round((scoreDTO.pointsAchieved / scoreCalculationDenominator) * 100.0);\n // sending this for debugging purposes to find out why the scores calculation could be wrong\n scoreDTO.regularPointsAchievable = scoreCalculationDenominator;\n }\n\n return new ArrayList<>(userIdToScores.values());\n\n }\n\n /**\n * Gets all the participant scores that exist for given exercises and converts them to the corresponding DTOs\n *\n * @param pageable pageable object to specify paging\n * @param exercises exercises for which to get all the participant scores\n * @return all participant scores of the exercises converted to DTOs\n */\n public List<ParticipantScoreDTO> getParticipantScoreDTOs(Pageable pageable, Set<Exercise> exercises) {\n Set<Exercise> individualExercisesOfCourse = exercises.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.INDIVIDUAL)).collect(Collectors.toSet());\n Set<Exercise> teamExercisesOfCourse = exercises.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.TEAM)).collect(Collectors.toSet());\n\n List<ParticipantScoreDTO> resultsIndividualExercises = studentScoreRepository.findAllByExerciseIn(individualExercisesOfCourse, pageable).stream()\n .map(ParticipantScoreDTO::generateFromParticipantScore).collect(Collectors.toList());\n List<ParticipantScoreDTO> resultsTeamExercises = teamScoreRepository.findAllByExerciseIn(teamExercisesOfCourse, pageable).stream()\n .map(ParticipantScoreDTO::generateFromParticipantScore).collect(Collectors.toList());\n return Stream.concat(resultsIndividualExercises.stream(), resultsTeamExercises.stream()).collect(Collectors.toList());\n }\n\n /**\n * Calculates various average statistics for every user / team that participated in the given exercises\n *\n * @param exercises exercises for which to calcualte the statistics\n * @return DTOs containing the statistics for every user / team\n */\n public List<ParticipantScoreAverageDTO> getParticipantScoreAverageDTOs(Set<Exercise> exercises) {\n Set<Exercise> individualExercises = exercises.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.INDIVIDUAL)).collect(Collectors.toSet());\n Set<Exercise> teamExercises = exercises.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.TEAM)).collect(Collectors.toSet());\n\n List<ParticipantScoreAverageDTO> resultsIndividualExercises = studentScoreRepository.getAvgScoreOfStudentsInExercises(individualExercises);\n List<ParticipantScoreAverageDTO> resultsTeamExercises = teamScoreRepository.getAvgScoreOfTeamInExercises(teamExercises);\n\n return Stream.concat(resultsIndividualExercises.stream(), resultsTeamExercises.stream()).collect(Collectors.toList());\n }\n\n /**\n * Calculated the average last score or average last rated score achieved in the given exercises\n *\n * @param onlyConsiderRatedScores consider either the last score or the last rated score\n * @param includedExercises exercises to include in the average calculation\n * @return average last score or average last rated score achieved in the given exercises\n */\n public Double getAverageScore(@RequestParam(defaultValue = \"true\", required = false) boolean onlyConsiderRatedScores, Set<Exercise> includedExercises) {\n Double averageScore;\n if (onlyConsiderRatedScores) {\n averageScore = participantScoreRepository.findAvgRatedScore(includedExercises);\n }\n else {\n averageScore = participantScoreRepository.findAvgScore(includedExercises);\n }\n return averageScore;\n }\n\n}\n" }, { "alpha_fraction": 0.7984693646430969, "alphanum_fraction": 0.8035714030265808, "avg_line_length": 25.133333206176758, "blob_id": "167d19db4374e0f32ffdedf230b6b45a16606fb7", "content_id": "62fa2a65fe9b9be454ba7fbf966813b27ff8ff51", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 392, "license_type": "permissive", "max_line_length": 75, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/DragItemRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.DragItem;\n\n/**\n * Spring Data JPA repository for the DragItem entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface DragItemRepository extends JpaRepository<DragItem, Long> {\n\n}\n" }, { "alpha_fraction": 0.6895787119865417, "alphanum_fraction": 0.6895787119865417, "avg_line_length": 42.36538314819336, "blob_id": "453a2c30e4af3643ea2b302082541300fd51f35f", "content_id": "9e600129f5a4110192673774e9dc06ec9bd6d87f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2255, "license_type": "permissive", "max_line_length": 143, "num_lines": 52, "path": "/src/test/javascript/spec/component/exam/manage/student-exams/students-exam-import-button.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { MockComponent, MockProvider, MockModule } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as sinon from 'sinon';\nimport { Exam } from 'app/entities/exam.model';\nimport { By } from '@angular/platform-browser';\nimport { NgbModal, NgbModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\nimport { StudentsExamImportButtonComponent } from 'app/exam/manage/students/students-exam-import-dialog/students-exam-import-button.component';\nimport { ButtonComponent } from 'app/shared/components/button.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentsExamImportButtonComponent', () => {\n let fixture: ComponentFixture<StudentsExamImportButtonComponent>;\n let comp: StudentsExamImportButtonComponent;\n let modalService: NgbModal;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [MockModule(NgbModule), TranslateModule.forRoot()],\n declarations: [StudentsExamImportButtonComponent, MockComponent(ButtonComponent)],\n providers: [MockProvider(JhiAlertService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(StudentsExamImportButtonComponent);\n comp = fixture.componentInstance;\n modalService = TestBed.inject(NgbModal);\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n const componentInstance = { courseId: Number, exam: Exam };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n comp.openStudentsExamImportDialog(new MouseEvent('click'));\n\n const openStudentsExamImportDialogButton = fixture.debugElement.query(By.css('jhi-button'));\n expect(openStudentsExamImportDialogButton).to.exist;\n expect(modalServiceOpenStub).to.have.been.called;\n modalServiceOpenStub.restore();\n });\n});\n" }, { "alpha_fraction": 0.6891820430755615, "alphanum_fraction": 0.6897097826004028, "avg_line_length": 43.069766998291016, "blob_id": "d9d058929de824813d6a6344cdb0334865ffe769", "content_id": "9a115b701a938dd981172c59f2fe83ba6d540fb9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1895, "license_type": "permissive", "max_line_length": 120, "num_lines": 43, "path": "/src/test/javascript/spec/component/assessment-shared/assessment-locks.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async, ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule, TranslateService } from '@ngx-translate/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { AssessmentLocksComponent } from 'app/assessment/assessment-locks/assessment-locks.component';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\n\ndescribe('AssessmentLocksComponent', () => {\n let component: AssessmentLocksComponent;\n let fixture: ComponentFixture<AssessmentLocksComponent>;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule, ArtemisAssessmentSharedModule],\n declarations: [],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n }).compileComponents();\n }));\n\n beforeEach(() => {\n fixture = TestBed.createComponent(AssessmentLocksComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n });\n\n it('should call getAllLockedSubmissions on init', () => {\n component.ngOnInit();\n\n expect(component.getAllLockedSubmissions).toHaveBeenCalled;\n expect(component.submissions.length).toBe(0);\n });\n});\n" }, { "alpha_fraction": 0.600778341293335, "alphanum_fraction": 0.6069234013557434, "avg_line_length": 37.74603271484375, "blob_id": "b3399b799424b2948ff9509e94101691c70587b7", "content_id": "4a042f107cbcb7954884e9b2b2f7878fea3aa738", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4882, "license_type": "permissive", "max_line_length": 114, "num_lines": 126, "path": "/src/test/javascript/spec/service/student-question.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport * as chai from 'chai';\nimport { take } from 'rxjs/operators';\nimport { StudentQuestionService } from 'app/overview/student-questions/student-question/student-question.service';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { Course } from 'app/entities/course.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { Lecture } from 'app/entities/lecture.model';\n\nconst expect = chai.expect;\n\ndescribe('StudentQuestion Service', () => {\n let injector: TestBed;\n let service: StudentQuestionService;\n let httpMock: HttpTestingController;\n let elemDefault: StudentQuestion;\n let elem2: StudentQuestion;\n let courseDefault: Course;\n let exerciseDefault: TextExercise;\n let lectureDefault: Lecture;\n let studentQuestionList: StudentQuestion[];\n let expectedResult: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n expectedResult = {} as HttpResponse<StudentQuestion>;\n injector = getTestBed();\n service = injector.get(StudentQuestionService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new StudentQuestion();\n elemDefault.id = 0;\n elemDefault.creationDate = undefined;\n elemDefault.questionText = 'This is a test question';\n\n elem2 = new StudentQuestion();\n elem2.id = 1;\n elem2.creationDate = undefined;\n elem2.questionText = 'This is a test question';\n\n courseDefault = new Course();\n courseDefault.id = 1;\n\n exerciseDefault = new TextExercise(courseDefault, undefined);\n exerciseDefault.id = 1;\n exerciseDefault.studentQuestions = [elemDefault];\n\n lectureDefault = new Lecture();\n lectureDefault.id = 1;\n lectureDefault.studentQuestions = [elem2];\n\n courseDefault.exercises = [exerciseDefault];\n courseDefault.lectures = [lectureDefault];\n\n studentQuestionList = [elemDefault, elem2];\n });\n\n describe('Service methods', () => {\n it('should create a StudentQuestion', async () => {\n const returnedFromService = { ...elemDefault, id: 0 };\n const expected = { ...returnedFromService };\n service\n .create(1, new StudentQuestion())\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should update a StudentQuestion', async () => {\n const returnedFromService = { ...elemDefault, questionText: 'This is another test question' };\n\n const expected = { ...returnedFromService };\n service\n .update(1, expected)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should delete a StudentQuestion', async () => {\n service.delete(1, 123).subscribe((resp) => (expectedResult = resp.ok));\n\n const req = httpMock.expectOne({ method: 'DELETE' });\n req.flush({ status: 200 });\n expect(expectedResult).to.be.true;\n });\n\n it('should update the votes of a StudentQuestion', async () => {\n const returnedFromService = { ...elemDefault, votes: 42 };\n\n const expected = { ...returnedFromService };\n service\n .updateVotes(1, expected.id!, 0)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should return all student questions for a course', async () => {\n const returnedFromService = [...studentQuestionList];\n\n const expected = [...studentQuestionList];\n service\n .findQuestionsForCourse(courseDefault.id!)\n .pipe(take(2))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.7908415794372559, "alphanum_fraction": 0.7908415794372559, "avg_line_length": 52.86666488647461, "blob_id": "b472da91bc3b157827597caccdd20bb79d7f1176", "content_id": "75989b47a913fc9b586f657c6039fe1c796f462e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1616, "license_type": "permissive", "max_line_length": 135, "num_lines": 30, "path": "/src/main/webapp/app/exercises/shared/participation/participation.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\n\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module';\nimport { ArtemisParticipationSubmissionModule } from 'app/exercises/shared/participation-submission/participation-submission.module';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { ParticipationComponent } from 'app/exercises/shared/participation/participation.component';\nimport { ProgrammingExerciseUtilsModule } from 'app/exercises/programming/shared/utils/programming-exercise-utils.module';\nimport { ArtemisExerciseScoresModule } from 'app/exercises/shared/exercise-scores/exercise-scores.module';\nimport { ArtemisParticipationRoutingModule } from 'app/exercises/shared/participation/participation-routing.module';\nimport { ArtemisTeamModule } from 'app/exercises/shared/team/team.module';\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n ArtemisParticipationRoutingModule,\n ArtemisExerciseScoresModule,\n ArtemisProgrammingExerciseActionsModule,\n ArtemisParticipationSubmissionModule,\n NgxDatatableModule,\n ArtemisDataTableModule,\n FeatureToggleModule,\n ProgrammingExerciseUtilsModule,\n ArtemisTeamModule,\n ],\n declarations: [ParticipationComponent],\n})\nexport class ArtemisParticipationModule {}\n" }, { "alpha_fraction": 0.6548141241073608, "alphanum_fraction": 0.6575906872749329, "avg_line_length": 31.83823585510254, "blob_id": "05e8ebd6956e33d8a0f270a2c54329660e3a566c", "content_id": "d7fb307b0569fa33af23446aaabc84c61605ae49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11165, "license_type": "permissive", "max_line_length": 177, "num_lines": 340, "path": "/src/main/java/de/tum/in/www1/artemis/domain/Feedback.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport static de.tum.in.www1.artemis.config.Constants.FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS;\n\nimport java.util.*;\n\nimport javax.persistence.*;\nimport javax.validation.constraints.Size;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.enumeration.FeedbackType;\nimport de.tum.in.www1.artemis.domain.enumeration.Visibility;\n\n/**\n * A Feedback.\n */\n@Entity\n@Table(name = \"feedback\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class Feedback extends DomainObject {\n\n public static final int MAX_REFERENCE_LENGTH = 2000;\n\n public static final String STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER = \"SCAFeedbackIdentifier:\";\n\n @Size(max = 500)\n @Column(name = \"text\", length = 500)\n private String text;\n\n @Size(max = FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS) // this ensures that the detail_text can be stored, even for long feedback\n @Column(name = \"detail_text\", length = FEEDBACK_DETAIL_TEXT_MAX_CHARACTERS)\n private String detailText;\n\n /**\n * Reference to the assessed element (e.g. model element id or text element string)\n */\n @Size(max = MAX_REFERENCE_LENGTH)\n @Column(name = \"reference\", length = MAX_REFERENCE_LENGTH)\n private String reference;\n\n /**\n * Absolute score for the assessed element (e.g. +0.5, -1.0, +2.0, etc.)\n */\n @Column(name = \"credits\")\n private Double credits;\n\n @Column(name = \"positive\")\n private Boolean positive;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"type\")\n private FeedbackType type;\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"visibility\")\n private Visibility visibility;\n\n @ManyToOne\n @JsonIgnoreProperties(\"feedbacks\")\n private Result result;\n\n @ManyToOne\n private GradingInstruction gradingInstruction;\n\n // TODO: JP remove these two references as they are not really needed\n @OneToMany(mappedBy = \"firstFeedback\", orphanRemoval = true)\n private List<FeedbackConflict> firstConflicts = new ArrayList<>();\n\n @OneToMany(mappedBy = \"secondFeedback\", orphanRemoval = true)\n private List<FeedbackConflict> secondConflicts = new ArrayList<>();\n\n public String getText() {\n return text;\n }\n\n public Feedback text(String text) {\n this.text = text;\n return this;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getDetailText() {\n return detailText;\n }\n\n public Feedback detailText(String detailText) {\n this.detailText = detailText;\n return this;\n }\n\n public void setDetailText(String detailText) {\n this.detailText = detailText;\n }\n\n public String getReference() {\n return reference;\n }\n\n public Feedback reference(String reference) {\n this.reference = reference;\n return this;\n }\n\n public boolean hasReference() {\n return reference != null && !reference.isEmpty();\n }\n\n public void setReference(String reference) {\n this.reference = reference;\n }\n\n /**\n * For modeling submissions the reference looks like \"<umlElementType>:<jsonElementId>\". This function tries to split the reference string at ':' and returns the second part\n * (i.e. the jsonElementId).\n *\n * @return the jsonElementId for modeling submissions or null if the reference string does not contain ':'\n */\n @JsonIgnore\n public String getReferenceElementId() {\n if (reference == null || !reference.contains(\":\")) {\n return null;\n }\n return reference.split(\":\")[1];\n }\n\n /**\n * For modeling submissions the reference looks like \"<umlElementType>:<jsonElementId>\". This function tries to split the reference string at ':' and returns the first part\n * (i.e. the umlElementType).\n *\n * @return the umlElementType for modeling submissions or null if the reference string does not contain ':'\n */\n @JsonIgnore\n public String getReferenceElementType() {\n if (!reference.contains(\":\")) {\n return null;\n }\n return reference.split(\":\")[0];\n }\n\n public Double getCredits() {\n return credits;\n }\n\n public Feedback credits(Double credits) {\n this.credits = credits;\n return this;\n }\n\n public void setCredits(Double credits) {\n this.credits = credits;\n }\n\n public Boolean isPositive() {\n return positive;\n }\n\n public Feedback positive(Boolean positive) {\n this.positive = positive;\n return this;\n }\n\n public void setPositive(Boolean positive) {\n this.positive = positive;\n }\n\n public FeedbackType getType() {\n return type;\n }\n\n public Feedback type(FeedbackType type) {\n this.type = type;\n return this;\n }\n\n public void setType(FeedbackType type) {\n this.type = type;\n }\n\n public Visibility getVisibility() {\n return visibility;\n }\n\n @JsonIgnore\n public boolean isAfterDueDate() {\n return this.visibility == Visibility.AFTER_DUE_DATE;\n }\n\n @JsonIgnore\n public boolean isInvisible() {\n return this.visibility == Visibility.NEVER;\n }\n\n public Feedback visibility(Visibility visibility) {\n this.visibility = visibility;\n return this;\n }\n\n public void setVisibility(Visibility visibility) {\n this.visibility = visibility;\n }\n\n public Result getResult() {\n return result;\n }\n\n public Feedback result(Result result) {\n this.result = result;\n return this;\n }\n\n /**\n * be careful when using this method as it might result in org.hibernate.HibernateException: null index column for collection: de.tum.in.www1.artemis.domain.Result.feedbacks\n * when saving the result. The result object is the container that owns the feedback and uses CascadeType.ALL and orphanRemoval\n * @param result the result container object that owns the feedback\n */\n public void setResult(Result result) {\n this.result = result;\n }\n // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove\n\n public GradingInstruction getGradingInstruction() {\n return gradingInstruction;\n }\n\n public void setGradingInstruction(GradingInstruction gradingInstruction) {\n this.gradingInstruction = gradingInstruction;\n }\n\n public List<FeedbackConflict> getFirstConflicts() {\n return firstConflicts;\n }\n\n public void setFirstConflicts(List<FeedbackConflict> firstConflicts) {\n this.firstConflicts = firstConflicts;\n }\n\n public List<FeedbackConflict> getSecondConflicts() {\n return secondConflicts;\n }\n\n public void setSecondConflicts(List<FeedbackConflict> secondConflicts) {\n this.secondConflicts = secondConflicts;\n }\n\n /**\n * Checks whether the feedback was created by static code analysis\n * @return true if the it is static code analysis feedback else false\n */\n @JsonIgnore\n public boolean isStaticCodeAnalysisFeedback() {\n return this.text != null && this.text.startsWith(STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER) && this.type == FeedbackType.AUTOMATIC;\n }\n\n /**\n * Returns the Artemis static code analysis category to which this feedback belongs. The method returns an empty\n * String, if the feedback is not static code analysis feedback.\n *\n * @return The Artemis static code analysis category to which this feedback belongs\n */\n @JsonIgnore\n public String getStaticCodeAnalysisCategory() {\n if (isStaticCodeAnalysisFeedback()) {\n return this.getText().substring(Feedback.STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER.length());\n }\n return \"\";\n }\n\n public boolean referenceEquals(Feedback otherFeedback) {\n return reference.equals(otherFeedback.reference);\n }\n\n /**\n * Copies an automatic feedback to be used for the manual result of a programming exercise\n * @return Copy of the automatic feedback without its original ID\n */\n public Feedback copyFeedback() {\n var feedback = new Feedback();\n feedback.setDetailText(getDetailText());\n feedback.setType(getType());\n // For manual result each feedback needs to have a credit. If no credit is set, we set it to 0.0\n feedback.setCredits(Optional.ofNullable(getCredits()).orElse(0.0));\n feedback.setText(getText());\n feedback.setPositive(isPositive());\n feedback.setReference(getReference());\n feedback.setVisibility(visibility);\n return feedback;\n }\n\n @Override\n public String toString() {\n return \"Feedback{\" + \"id=\" + getId() + \", text='\" + getText() + \"'\" + \", detailText='\" + getDetailText() + \"'\" + \", reference='\" + getReference() + \"'\" + \", positive='\"\n + isPositive() + \"'\" + \", type='\" + getType() + \", visibility=\" + getVisibility() + \", gradingInstruction='\" + getGradingInstruction() + \"'\" + \"}\";\n }\n\n /**\n * Calculates the score over all feedback elements that were set using structured grading instructions (SGI)\n * @param inputScore totalScore which is summed up.\n * @param gradingInstructions empty grading instruction Map to collect the used gradingInstructions\n * @return calculated total score from feedback elements set by SGI\n */\n @JsonIgnore\n public double computeTotalScore(double inputScore, Map<Long, Integer> gradingInstructions) {\n double totalScore = inputScore;\n if (gradingInstructions.get(getGradingInstruction().getId()) != null) {\n // We Encountered this grading instruction before\n var maxCount = getGradingInstruction().getUsageCount();\n var encounters = gradingInstructions.get(getGradingInstruction().getId());\n if (maxCount > 0) {\n if (encounters >= maxCount) {\n // the structured grading instruction was applied on assessment models more often that the usageCount limit allows so we don't sum the feedback credit\n gradingInstructions.put(getGradingInstruction().getId(), encounters + 1);\n }\n else {\n // the usageCount limit was not exceeded yet so we add the credit and increase the nrOfEncounters counter\n gradingInstructions.put(getGradingInstruction().getId(), encounters + 1);\n totalScore += getGradingInstruction().getCredits();\n }\n }\n else {\n totalScore += getCredits();\n }\n }\n else {\n // First time encountering the grading instruction\n gradingInstructions.put(getGradingInstruction().getId(), 1);\n totalScore += getCredits();\n }\n return totalScore;\n }\n}\n" }, { "alpha_fraction": 0.6685393452644348, "alphanum_fraction": 0.6724718809127808, "avg_line_length": 36.87234115600586, "blob_id": "f11c3efa667d435490ed235630ace4edc2f626c1", "content_id": "67fe2b0a96e02ac60cc86db99c0d2e0ae3821c2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3560, "license_type": "permissive", "max_line_length": 120, "num_lines": 94, "path": "/src/test/javascript/spec/component/student-questions/student-questions.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { StudentQuestionsComponent } from 'app/overview/student-questions/student-questions.component';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\nimport { Course } from 'app/entities/course.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentQuestionRowComponent', () => {\n let component: StudentQuestionsComponent;\n let componentFixture: ComponentFixture<StudentQuestionsComponent>;\n\n const course = {\n id: 1,\n } as Course;\n\n const unApprovedStudentQuestionAnswer = {\n id: 1,\n answerDate: undefined,\n answerText: 'not approved',\n tutorApproved: false,\n } as StudentQuestionAnswer;\n\n const approvedStudentQuestionAnswer = {\n id: 2,\n answerDate: undefined,\n answerText: 'approved',\n tutorApproved: true,\n } as StudentQuestionAnswer;\n\n const studentQuestion1 = {\n id: 1,\n creationDate: undefined,\n answers: [unApprovedStudentQuestionAnswer, approvedStudentQuestionAnswer],\n } as StudentQuestion;\n\n const studentQuestion2 = {\n id: 2,\n creationDate: undefined,\n answers: [unApprovedStudentQuestionAnswer, approvedStudentQuestionAnswer],\n } as StudentQuestion;\n\n const lectureDefault = {\n id: 1,\n title: 'test',\n description: 'test',\n startDate: undefined,\n endDate: undefined,\n studentQuestions: [studentQuestion1, studentQuestion2],\n isAtLeastInstructor: true,\n course,\n } as Lecture;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n providers: [\n { provide: AccountService, useClass: MockAccountService },\n { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },\n ],\n declarations: [StudentQuestionsComponent],\n })\n .overrideTemplate(StudentQuestionsComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(StudentQuestionsComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('should set student questions correctly', () => {\n component.lecture = lectureDefault;\n component.ngOnInit();\n expect(component.studentQuestions).to.deep.equal([studentQuestion1, studentQuestion2]);\n });\n\n it('should delete studentQuestion from list', () => {\n component.lecture = lectureDefault;\n component.ngOnInit();\n component.deleteQuestionFromList(studentQuestion1);\n expect(component.studentQuestions).to.deep.equal([studentQuestion2]);\n });\n});\n" }, { "alpha_fraction": 0.7339503765106201, "alphanum_fraction": 0.7351370453834534, "avg_line_length": 44.30644989013672, "blob_id": "d84561842e7462c4200656a356909161b842a134", "content_id": "6e2afc1897eb0666c50afccc210b48491de66fd4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8427, "license_type": "permissive", "max_line_length": 174, "num_lines": 186, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise-utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SimpleChanges } from '@angular/core';\nimport { Exercise, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport * as moment from 'moment';\nimport { now } from 'moment';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { hasResults } from 'app/overview/participation-utils';\n\nexport const hasExerciseChanged = (changes: SimpleChanges) => {\n return changes.exercise && changes.exercise.currentValue && (!changes.exercise.previousValue || changes.exercise.previousValue.id !== changes.exercise.currentValue.id);\n};\n\nexport const problemStatementHasChanged = (changes: SimpleChanges) => {\n return (\n changes.exercise &&\n changes.exercise.currentValue &&\n (!changes.exercise.previousValue || changes.exercise.previousValue.problemStatement !== changes.exercise.currentValue.problemStatement)\n );\n};\n\n/**\n * Checks if the due date of a given exercise lies in the past. If there is no due date it evaluates to false.\n *\n * @param exercise\n * @return {boolean}\n */\nexport const hasExerciseDueDatePassed = (exercise: Exercise): boolean => {\n if (exercise.dueDate == undefined) {\n return false;\n }\n return moment(exercise.dueDate).isBefore();\n};\n\n/**\n * Checks if the given exercise has student participations.\n *\n * @param exercise\n * @return {boolean}\n */\nexport const hasStudentParticipations = (exercise: Exercise) => {\n return exercise.studentParticipations && exercise.studentParticipations.length > 0;\n};\n\n/**\n * Handles the evaluation of participation status.\n *\n * @param exercise\n * @return {ParticipationStatus}\n */\nexport const participationStatus = (exercise: Exercise): ParticipationStatus => {\n // For team exercises check whether the student has been assigned to a team yet\n if (exercise.teamMode && exercise.studentAssignedTeamIdComputed && !exercise.studentAssignedTeamId) {\n return ParticipationStatus.NO_TEAM_ASSIGNED;\n }\n\n // Evaluate the participation status for quiz exercises.\n if (exercise.type === ExerciseType.QUIZ) {\n return participationStatusForQuizExercise(exercise);\n }\n\n // Evaluate the participation status for modeling, text and file upload exercises if the exercise has participations.\n if (exercise.type && [ExerciseType.MODELING, ExerciseType.TEXT, ExerciseType.FILE_UPLOAD].includes(exercise.type) && hasStudentParticipations(exercise)) {\n return participationStatusForModelingTextFileUploadExercise(exercise);\n }\n\n const programmingExerciseStates = [\n InitializationState.UNINITIALIZED,\n InitializationState.REPO_COPIED,\n InitializationState.REPO_CONFIGURED,\n InitializationState.BUILD_PLAN_COPIED,\n InitializationState.BUILD_PLAN_CONFIGURED,\n ];\n\n // The following evaluations are relevant for programming exercises in general and for modeling, text and file upload exercises that don't have participations.\n if (!hasStudentParticipations(exercise) || programmingExerciseStates.includes(exercise.studentParticipations![0].initializationState!)) {\n if (exercise.type === ExerciseType.PROGRAMMING && !isStartExerciseAvailable(exercise as ProgrammingExercise)) {\n return ParticipationStatus.EXERCISE_MISSED;\n } else {\n return ParticipationStatus.UNINITIALIZED;\n }\n } else if (exercise.studentParticipations![0].initializationState === InitializationState.INITIALIZED) {\n return ParticipationStatus.INITIALIZED;\n }\n return ParticipationStatus.INACTIVE;\n};\n\n/**\n * The start exercise button should be available for programming exercises when\n * - there is no due date\n * - now is before the due date\n * - test run after due date is deactivated and manual grading is deactivated\n */\nexport const isStartExerciseAvailable = (exercise: ProgrammingExercise): boolean => {\n return (\n exercise.dueDate == undefined ||\n moment() <= exercise.dueDate! ||\n (exercise.buildAndTestStudentSubmissionsAfterDueDate == undefined && exercise.assessmentType === AssessmentType.AUTOMATIC)\n );\n};\n\n/**\n * Handles the evaluation of participation status for quiz exercises.\n *\n * @param exercise\n * @return {ParticipationStatus}\n */\nconst participationStatusForQuizExercise = (exercise: Exercise): ParticipationStatus => {\n const quizExercise = exercise as QuizExercise;\n if ((!quizExercise.isPlannedToStart || moment(quizExercise.releaseDate!).isAfter(moment())) && quizExercise.visibleToStudents) {\n return ParticipationStatus.QUIZ_NOT_STARTED;\n } else if (!hasStudentParticipations(exercise) && (!quizExercise.isPlannedToStart || moment(quizExercise.dueDate!).isAfter(moment())) && quizExercise.visibleToStudents) {\n return ParticipationStatus.QUIZ_UNINITIALIZED;\n } else if (!hasStudentParticipations(exercise)) {\n return ParticipationStatus.QUIZ_NOT_PARTICIPATED;\n } else if (exercise.studentParticipations![0].initializationState === InitializationState.INITIALIZED && moment(exercise.dueDate!).isAfter(moment())) {\n return ParticipationStatus.QUIZ_ACTIVE;\n } else if (exercise.studentParticipations![0].initializationState === InitializationState.FINISHED && moment(exercise.dueDate!).isAfter(moment())) {\n return ParticipationStatus.QUIZ_SUBMITTED;\n } else {\n return !hasResults(exercise.studentParticipations![0]) ? ParticipationStatus.QUIZ_NOT_PARTICIPATED : ParticipationStatus.QUIZ_FINISHED;\n }\n};\n\n/**\n * Handles the evaluation of participation status for modeling, text and file upload exercises if the exercise has participations.\n *\n * @param exercise\n * @return {ParticipationStatus}\n */\nconst participationStatusForModelingTextFileUploadExercise = (exercise: Exercise): ParticipationStatus => {\n const participation = exercise.studentParticipations![0];\n\n // An exercise is active (EXERCISE_ACTIVE) if it is initialized and has not passed its due date.\n // A more detailed evaluation of active exercises takes place in the result component.\n // An exercise was missed (EXERCISE_MISSED) if it is initialized and has passed its due date (due date lies in the past).\n if (participation.initializationState === InitializationState.INITIALIZED) {\n return hasExerciseDueDatePassed(exercise) ? ParticipationStatus.EXERCISE_MISSED : ParticipationStatus.EXERCISE_ACTIVE;\n } else if (participation.initializationState === InitializationState.FINISHED) {\n // An exercise was submitted (EXERCISE_SUBMITTED) if the corresponding InitializationState is set to FINISHED\n return ParticipationStatus.EXERCISE_SUBMITTED;\n } else {\n return ParticipationStatus.UNINITIALIZED;\n }\n};\n\n/**\n * Checks whether the given exercise is eligible for receiving manual results.\n * This is the case if the user is at least a tutor and the exercise itself is a programming\n * exercise for which manual reviews have been enabled. The due date also has to be in the past.\n *\n * @param exercise\n */\nexport const areManualResultsAllowed = (exercise: Exercise) => {\n if (exercise.type !== ExerciseType.PROGRAMMING) {\n return false;\n }\n // Only allow new results if manual reviews are activated and the due date/after due date has passed\n const progEx = exercise as ProgrammingExercise;\n const relevantDueDate = progEx.buildAndTestStudentSubmissionsAfterDueDate ?? progEx.dueDate;\n return (\n (!!progEx.isAtLeastTutor || !!progEx.isAtLeastInstructor) &&\n progEx.assessmentType === AssessmentType.SEMI_AUTOMATIC &&\n (!relevantDueDate || moment(relevantDueDate).isBefore(now()))\n );\n};\n\n/**\n * Gets the positive and capped to maximum points which is fixed at two decimal numbers\n *\n * @param totalScore the calculated score of a student\n * @param maxPoints the maximal points (including bonus points) of an exercise\n */\nexport const getPositiveAndCappedTotalScore = (totalScore: number, maxPoints: number): number => {\n // Do not allow negative score\n if (totalScore < 0) {\n totalScore = 0;\n }\n // Cap totalScore to maxPoints\n if (totalScore > maxPoints) {\n totalScore = maxPoints;\n }\n\n return +totalScore.toFixed(2);\n};\n" }, { "alpha_fraction": 0.7995495200157166, "alphanum_fraction": 0.7995495200157166, "avg_line_length": 43.400001525878906, "blob_id": "f6ccce18f53c67c5916b103b4644e7f855097f5f", "content_id": "6bbe5433c50f7f095dcb7a6a1bc8dc500bd2955d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 444, "license_type": "permissive", "max_line_length": 132, "num_lines": 10, "path": "/src/main/webapp/app/shared/notification/connection-notification/connection-notification.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ConnectionNotificationComponent } from 'app/shared/notification/connection-notification/connection-notification.component';\n\n@NgModule({\n imports: [ArtemisSharedModule],\n declarations: [ConnectionNotificationComponent],\n exports: [ConnectionNotificationComponent],\n})\nexport class ArtemisConnectionNotificationModule {}\n" }, { "alpha_fraction": 0.7639824151992798, "alphanum_fraction": 0.7666178345680237, "avg_line_length": 40.64634323120117, "blob_id": "1307b9ee4c952aabff97cf53292f468fe94a2e1b", "content_id": "dd0d62b7aacafa5ce8285acbc822f73cb1294410", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3415, "license_type": "permissive", "max_line_length": 148, "num_lines": 82, "path": "/src/main/java/de/tum/in/www1/artemis/service/plagiarism/PlagiarismService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.plagiarism;\n\nimport java.util.Optional;\n\nimport javax.transaction.Transactional;\n\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.plagiarism.PlagiarismComparison;\nimport de.tum.in.www1.artemis.domain.plagiarism.PlagiarismResult;\nimport de.tum.in.www1.artemis.domain.plagiarism.PlagiarismStatus;\nimport de.tum.in.www1.artemis.domain.plagiarism.modeling.ModelingPlagiarismResult;\nimport de.tum.in.www1.artemis.domain.plagiarism.text.TextPlagiarismResult;\nimport de.tum.in.www1.artemis.repository.PlagiarismComparisonRepository;\nimport de.tum.in.www1.artemis.repository.PlagiarismResultRepository;\n\n@Service\npublic class PlagiarismService {\n\n private final PlagiarismComparisonRepository plagiarismComparisonRepository;\n\n private final PlagiarismResultRepository plagiarismResultRepository;\n\n public PlagiarismService(PlagiarismComparisonRepository plagiarismComparisonRepository, PlagiarismResultRepository plagiarismResultRepository) {\n this.plagiarismComparisonRepository = plagiarismComparisonRepository;\n this.plagiarismResultRepository = plagiarismResultRepository;\n }\n\n /**\n * Return an Optional of the latest PlagiarismResult for the given Exercise or empty, if no\n * plagiarism was detected yet.\n *\n * @param exercise Exercise to get the latest plagiarism result for.\n * @return the latest plagiarism result for the given exercise.\n */\n public Optional<PlagiarismResult<?>> getPlagiarismResult(Exercise exercise) {\n return plagiarismResultRepository.findFirstByExerciseIdOrderByLastModifiedDateDesc(exercise.getId());\n }\n\n /**\n * Delete the given plagiarism result.\n * @param result the result to delete.\n */\n public void deletePlagiarismResult(PlagiarismResult<?> result) {\n plagiarismResultRepository.delete(result);\n }\n\n /**\n * Update the status of the given plagiarism comparison.\n *\n * @param comparison Plagiarism comparison to update.\n * @param status The new status of the plagiarism comparison.\n */\n // TODO: move to Repository\n @Transactional // ok because of modifying query\n public void updateStatusOfComparison(PlagiarismComparison<?> comparison, PlagiarismStatus status) {\n plagiarismComparisonRepository.updatePlagiarismComparisonStatus(comparison.getId(), status);\n }\n\n /**\n * Store the given TextPlagiarismResult in the database.\n *\n * @param result TextPlagiarismResult to store in the database.\n */\n public void savePlagiarismResultAndRemovePrevious(TextPlagiarismResult result) {\n Optional<PlagiarismResult<?>> optionalPreviousResult = this.getPlagiarismResult(result.getExercise());\n plagiarismResultRepository.save(result);\n optionalPreviousResult.ifPresent(this::deletePlagiarismResult);\n }\n\n /**\n * Store the given ModelingPlagiarismResult in the database.\n *\n * @param result ModelingPlagiarismResult to store in the database.\n */\n public void savePlagiarismResultAndRemovePrevious(ModelingPlagiarismResult result) {\n Optional<PlagiarismResult<?>> optionalPreviousResult = this.getPlagiarismResult(result.getExercise());\n plagiarismResultRepository.save(result);\n optionalPreviousResult.ifPresent(this::deletePlagiarismResult);\n }\n}\n" }, { "alpha_fraction": 0.5702299475669861, "alphanum_fraction": 0.570540726184845, "avg_line_length": 32.17525863647461, "blob_id": "b5b6bf0c9675e852e34f8790ba6cacdb43c82d6a", "content_id": "ab64feea34c1120f6adffbf02b88377602955b0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3218, "license_type": "permissive", "max_line_length": 162, "num_lines": 97, "path": "/src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, ElementRef, EventEmitter, forwardRef, Input, Output, ViewChild } from '@angular/core';\nimport { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';\nimport * as moment from 'moment';\nimport { isMoment, Moment } from 'moment';\n\n@Component({\n selector: 'jhi-date-time-picker',\n template: `\n <label class=\"form-control-label\" *ngIf=\"labelName\">\n {{ labelName }}\n </label>\n <div class=\"d-flex\">\n <input\n #dateInput=\"ngModel\"\n class=\"form-control position-relative pl-5\"\n [ngClass]=\"{ 'is-invalid': error }\"\n [ngModel]=\"value\"\n [disabled]=\"disabled\"\n [min]=\"min?.isValid() ? min.toDate() : null\"\n [max]=\"max?.isValid() ? max.toDate() : null\"\n (ngModelChange)=\"updateField($event)\"\n [owlDateTime]=\"dt\"\n name=\"datePicker\"\n />\n <button [owlDateTimeTrigger]=\"dt\" class=\"btn position-absolute\" type=\"button\">\n <fa-icon [icon]=\"'calendar-alt'\"></fa-icon>\n </button>\n <owl-date-time [startAt]=\"startAt?.isValid() ? startAt.toDate() : null\" #dt></owl-date-time>\n </div>\n `,\n providers: [\n {\n provide: NG_VALUE_ACCESSOR,\n multi: true,\n useExisting: forwardRef(() => FormDateTimePickerComponent),\n },\n ],\n})\nexport class FormDateTimePickerComponent implements ControlValueAccessor {\n @ViewChild('dateInput', { static: false }) dateInput: ElementRef;\n @Input() labelName: string;\n @Input() value: any;\n @Input() disabled: boolean;\n @Input() error: boolean;\n @Input() startAt: Moment = moment().startOf('minutes'); // Default selected date. By default this sets it to the current time without seconds or milliseconds;\n @Input() min: Moment; // Dates before this date are not selectable.\n @Input() max: Moment; // Dates after this date are not selectable.\n @Output() valueChange = new EventEmitter();\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n _onChange = (val: Moment) => {};\n\n /**\n * Emits the value change from component.\n */\n valueChanged() {\n this.valueChange.emit();\n }\n\n /**\n * Function that writes the value safely.\n * @param value as moment or date\n */\n writeValue(value: any) {\n // convert moment to date, because owl-date-time only works correctly with date objects\n if (isMoment(value)) {\n this.value = (value as Moment).toDate();\n } else {\n this.value = value;\n }\n }\n\n /**\n * Registers a callback function is called by the forms API on initialization to update the form model on blur.\n * @param fn\n */\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n registerOnTouched(fn: any) {}\n\n /**\n *\n * @param fn\n */\n registerOnChange(fn: any) {\n this._onChange = fn;\n }\n\n /**\n *\n * @param newValue\n */\n updateField(newValue: Moment) {\n this.value = newValue;\n this._onChange(moment(this.value));\n this.valueChanged();\n }\n}\n" }, { "alpha_fraction": 0.7188106179237366, "alphanum_fraction": 0.7356173396110535, "avg_line_length": 44.5, "blob_id": "94fbe65762ad5a0ec2aced2dfb5fbf66c55c64ae", "content_id": "77b561d9db3c4d60ab866331ca6a7c7fddec679c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 1547, "license_type": "permissive", "max_line_length": 176, "num_lines": 34, "path": "/src/main/docker/bamboo/swift/Dockerfile", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "FROM atlassian/bamboo-server:7.1.2\n\nLABEL description=\"Bamboo pre-configured for Artemis, pre-installed with Swift\"\n\nUSER root\nENV DEBIAN_FRONTEND noninteractive\n\nRUN apt-get update && apt-get install -y --no-install-recommends \\\n software-properties-common \\\n apt-utils \\\n maven=3.6.0*\nRUN add-apt-repository -y ppa:linuxuprising/java\nRUN echo debconf shared/accepted-oracle-license-v1-2 select true | debconf-set-selections && echo debconf shared/accepted-oracle-license-v1-2 seen true | debconf-set-selections\nRUN apt-get install -y oracle-java15-installer\nRUN update-alternatives --install /usr/bin/java java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1\nRUN update-alternatives --set java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java\n# Add file in /artemis/bin/mvn that uses the correct java version and passes all arguments to mvn\nRUN mkdir /artemis && mkdir /artemis/bin && printf '#!/bin/bash\\nJAVA_HOME=/usr/lib/jvm/java-15-oracle /usr/bin/mvn \"$@\"\\n' > /artemis/bin/mvn && chmod 777 /artemis/bin/mvn\n\n# Install Swift by copying relevant files\nCOPY --from=swift:latest /usr /usr\n\n# Install SwiftLint\nRUN apt-get install -y --no-install-recommends \\\n libcurl4-openssl-dev \\\n libxml2-dev\nRUN git clone --branch master https://github.com/realm/SwiftLint.git && \\\n cd SwiftLint && \\\n swift build --configuration release -Xswiftc -static-stdlib && \\\n mv $(swift build --configuration release -Xswiftc -static-stdlib --show-bin-path)/swiftlint /usr/bin && \\\n cd .. && \\\n rm -rf SwiftLint\n\nUSER ${BAMBOO_USER}\n" }, { "alpha_fraction": 0.6990705728530884, "alphanum_fraction": 0.7008289098739624, "avg_line_length": 47.54878234863281, "blob_id": "ae7c57783af9cd9002ace2d56bb5fbe9ee38b6a9", "content_id": "60a5746d37a90be3bbd28073d4846f43291eafa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7962, "license_type": "permissive", "max_line_length": 145, "num_lines": 164, "path": "/src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\n\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport { OrionConnectorService } from 'app/shared/orion/orion-connector.service';\nimport { CourseExerciseService } from 'app/course/manage/course-management.service';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { BehaviorSubject, Subject } from 'rxjs';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockComponent } from 'ng-mocks';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { ProgrammingExerciseStudentIdeActionsComponent } from 'app/overview/exercise-details/programming-exercise-student-ide-actions.component';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { MockFeatureToggleService } from '../../../helpers/mocks/service/mock-feature-toggle.service';\nimport { Exercise, ParticipationStatus } from 'app/entities/exercise.model';\nimport { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service';\nimport { ExerciseActionButtonComponent } from 'app/shared/components/exercise-action-button.component';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { MockAlertService } from '../../../helpers/mocks/service/mock-alert.service';\nimport { MockOrionConnectorService } from '../../../helpers/mocks/service/mock-orion-connector.service';\nimport { ArtemisOrionConnector, OrionState } from 'app/shared/orion/orion';\nimport { OrionModule } from 'app/shared/orion/orion.module';\nimport { MockIdeBuildAndTestService } from '../../../helpers/mocks/service/mock-ide-build-and-test.service';\nimport { OrionBuildAndTestService } from 'app/shared/orion/orion-build-and-test.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseStudentIdeActionsComponent', () => {\n let comp: ProgrammingExerciseStudentIdeActionsComponent;\n let fixture: ComponentFixture<ProgrammingExerciseStudentIdeActionsComponent>;\n let debugElement: DebugElement;\n let orionConnector: ArtemisOrionConnector;\n let courseExerciseService: CourseExerciseService;\n let ideBuildService: OrionBuildAndTestService;\n\n let startExerciseStub: SinonStub;\n let ideStateStub: SinonStub;\n let cloneSpy: SinonSpy;\n let submitSpy: SinonSpy;\n let forwardBuildSpy: SinonSpy;\n\n const exercise = { id: 42 } as Exercise;\n const ideState = { opened: 40, building: false, cloning: false } as OrionState;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), NgbModule, OrionModule, ArtemisSharedModule, FeatureToggleModule],\n declarations: [ProgrammingExerciseStudentIdeActionsComponent, MockComponent(ExerciseActionButtonComponent)],\n providers: [\n { provide: OrionBuildAndTestService, useClass: MockIdeBuildAndTestService },\n { provide: OrionConnectorService, useClass: MockOrionConnectorService },\n { provide: CourseExerciseService, useClass: MockCourseExerciseService },\n { provide: JhiAlertService, useClass: MockAlertService },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseStudentIdeActionsComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n orionConnector = debugElement.injector.get(OrionConnectorService);\n ideBuildService = debugElement.injector.get(OrionBuildAndTestService);\n courseExerciseService = debugElement.injector.get(CourseExerciseService);\n startExerciseStub = stub(courseExerciseService, 'startExercise');\n forwardBuildSpy = spy(ideBuildService, 'listenOnBuildOutputAndForwardChanges');\n cloneSpy = spy(orionConnector, 'importParticipation');\n submitSpy = spy(orionConnector, 'submit');\n ideStateStub = stub(orionConnector, 'state');\n });\n });\n\n afterEach(() => {\n startExerciseStub.restore();\n cloneSpy.restore();\n submitSpy.restore();\n });\n\n it('should not reflect that the represented exercise is opened if another exercise has been opened', fakeAsync(() => {\n const stateObservable = new BehaviorSubject(ideState);\n comp.exercise = exercise;\n ideStateStub.returns(stateObservable);\n\n comp.ngOnInit();\n fixture.detectChanges();\n tick();\n\n expect(comp.ideState.opened).to.not.equal(exercise.id);\n\n fixture.destroy();\n flush();\n }));\n\n it('should reflect that the represented exercise is opened if the same exercise is open in the IDE', fakeAsync(() => {\n const stateObservable = new BehaviorSubject({ opened: exercise.id });\n comp.exercise = exercise;\n ideStateStub.returns(stateObservable);\n\n comp.ngOnInit();\n fixture.detectChanges();\n tick();\n\n expect(comp.ideState.opened).to.equal(exercise.id);\n\n fixture.destroy();\n flush();\n }));\n\n it('should reflect the correct participation state', fakeAsync(() => {\n const inactivePart = { id: 2, initializationState: InitializationState.INACTIVE } as StudentParticipation;\n const initPart = { id: 2, initializationState: InitializationState.INITIALIZED } as StudentParticipation;\n const participationSubject = new Subject<StudentParticipation>();\n const stateObservable = new BehaviorSubject(ideState);\n comp.exercise = exercise;\n startExerciseStub.returns(participationSubject);\n ideStateStub.returns(stateObservable);\n comp.startExercise();\n participationSubject.next(inactivePart);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatus(comp.exercise)).to.be.equal(ParticipationStatus.INACTIVE);\n expect(startExerciseStub).to.have.been.calledOnce;\n participationSubject.next(initPart);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatus(comp.exercise)).to.be.equal(ParticipationStatus.INITIALIZED);\n\n fixture.destroy();\n flush();\n }));\n\n it('should clone the correct repository in the IDE', () => {\n const participation = { id: 123, repositoryUrl: 'testUrl' } as ProgrammingExerciseStudentParticipation;\n const progExercise = { id: 42, title: 'Test Title' } as Exercise;\n progExercise.studentParticipations = [participation];\n comp.exercise = progExercise;\n comp.courseId = 456;\n\n comp.importIntoIDE();\n expect(cloneSpy).to.have.been.calledOnceWithExactly('testUrl', progExercise);\n });\n\n it('should submit the changes and then forward the build results on submit', () => {\n comp.exercise = exercise;\n comp.submitChanges();\n\n expect(submitSpy).to.have.been.calledOnce;\n expect(forwardBuildSpy).to.have.been.calledOnce;\n expect(forwardBuildSpy).to.have.been.calledImmediatelyAfter(submitSpy);\n });\n});\n" }, { "alpha_fraction": 0.6690090298652649, "alphanum_fraction": 0.6750322580337524, "avg_line_length": 43.6987190246582, "blob_id": "2417b904e17536b0a70a7e64994511c94468d4f4", "content_id": "f13bab5dd8e3fa1aa7918bb0adc21216606c804e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6973, "license_type": "permissive", "max_line_length": 170, "num_lines": 156, "path": "/src/test/javascript/spec/component/quiz-exercise/quiz-re-evaluate.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { of } from 'rxjs';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { Course } from 'app/entities/course.model';\nimport { QuizReEvaluateComponent } from 'app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate.component';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { QuizExercisePopupService } from 'app/exercises/quiz/manage/quiz-exercise-popup.service';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { restore, SinonStub, spy, stub } from 'sinon';\nimport { ReEvaluateMultipleChoiceQuestionComponent } from 'app/exercises/quiz/manage/re-evaluate/multiple-choice-question/re-evaluate-multiple-choice-question.component';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { ReEvaluateDragAndDropQuestionComponent } from 'app/exercises/quiz/manage/re-evaluate/drag-and-drop-question/re-evaluate-drag-and-drop-question.component';\nimport { ReEvaluateShortAnswerQuestionComponent } from 'app/exercises/quiz/manage/re-evaluate/short-answer-question/re-evaluate-short-answer-question.component';\nimport { MockTranslateValuesDirective } from '../course/course-scores/course-scores.component.spec';\nimport { NgModel } from '@angular/forms';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { Duration } from 'app/exercises/quiz/manage/quiz-exercise-interfaces';\nimport { QuizQuestionType } from 'app/entities/quiz/quiz-question.model';\nimport { SimpleChange } from '@angular/core';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('QuizExercise Re-evaluate Component', () => {\n let comp: QuizReEvaluateComponent;\n let fixture: ComponentFixture<QuizReEvaluateComponent>;\n let quizService: QuizExerciseService;\n let quizServiceFindSpy: SinonStub;\n\n const course = { id: 123 } as Course;\n const quizExercise = new QuizExercise(course, undefined);\n quizExercise.id = 456;\n quizExercise.title = 'MyQuiz';\n\n const route = ({ params: of({ exerciseId: 123 }) } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [\n NgModel,\n QuizReEvaluateComponent,\n MockComponent(ReEvaluateMultipleChoiceQuestionComponent),\n MockComponent(ReEvaluateDragAndDropQuestionComponent),\n MockComponent(ReEvaluateShortAnswerQuestionComponent),\n MockTranslateValuesDirective,\n MockDirective(JhiTranslateDirective),\n MockPipe(ArtemisDatePipe),\n ],\n providers: [\n NgbModal,\n QuizExercisePopupService,\n { provide: ActivatedRoute, useValue: route },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: Router, useClass: MockRouter },\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(QuizReEvaluateComponent);\n comp = fixture.componentInstance;\n quizService = fixture.debugElement.injector.get(QuizExerciseService);\n const quizQuestion1 = new MultipleChoiceQuestion();\n const quizQuestion2 = new DragAndDropQuestion();\n quizExercise.quizQuestions = [quizQuestion1, quizQuestion2];\n quizServiceFindSpy = stub(quizService, 'find').returns(of(new HttpResponse({ body: quizExercise })));\n });\n\n afterEach(() => {\n restore();\n });\n\n it('Should initialize quiz exercise', () => {\n comp.ngOnInit();\n expect(comp.validQuiz()).to.be.true;\n expect(comp.quizExercise).to.equal(quizExercise);\n expect(quizServiceFindSpy).to.have.been.calledOnce;\n });\n\n it('Should create correct duration strings', () => {\n comp.duration = new Duration(1, 0);\n expect(comp.durationString()).to.equal('1:00');\n\n comp.duration = new Duration(1, 9);\n expect(comp.durationString()).to.equal('1:09');\n\n comp.duration = new Duration(1, 10);\n expect(comp.durationString()).to.equal('1:10');\n });\n\n it('Should delete quiz question', () => {\n comp.ngOnInit();\n expect(comp.quizExercise.quizQuestions!.length).to.equal(2);\n comp.deleteQuestion(comp.quizExercise.quizQuestions![0]);\n expect(comp.quizExercise.quizQuestions!.length).to.equal(1);\n });\n\n it('Should update and reset quiz questions', () => {\n comp.ngOnInit();\n comp.quizExercise.title = 'New Title';\n comp.quizExercise.quizQuestions![0].points = 5;\n // update question\n comp.onQuestionUpdated();\n expect(comp.quizExercise).to.equal(quizExercise);\n // reset title\n comp.resetQuizTitle();\n expect(comp.quizExercise.title).to.equal(comp.backupQuiz.title);\n // reset all\n comp.resetAll();\n expect(comp.quizExercise).to.deep.equal(comp.backupQuiz);\n });\n\n it('Should have pending changes', () => {\n comp.ngOnInit();\n comp.quizExercise.quizQuestions![0].points = 5;\n expect(comp.pendingChanges()).to.be.true;\n });\n\n it('Should move down the quiz question', () => {\n comp.ngOnInit();\n expect(comp.quizExercise.quizQuestions![0].type).to.equal(QuizQuestionType.MULTIPLE_CHOICE);\n comp.moveDown(comp.quizExercise.quizQuestions![0]);\n expect(comp.quizExercise.quizQuestions![1].type).to.equal(QuizQuestionType.MULTIPLE_CHOICE);\n });\n\n it('Should move up the quiz question', () => {\n comp.ngOnInit();\n expect(comp.quizExercise.quizQuestions![1].type).to.equal(QuizQuestionType.DRAG_AND_DROP);\n comp.moveUp(comp.quizExercise.quizQuestions![1]);\n expect(comp.quizExercise.quizQuestions![0].type).to.equal(QuizQuestionType.DRAG_AND_DROP);\n });\n\n it('Updates quiz on changes', () => {\n const prepareEntitySpy = spy(comp, 'prepareEntity');\n comp.ngOnInit();\n comp.ngOnChanges({\n quizExercise: { currentValue: quizExercise } as SimpleChange,\n });\n\n expect(prepareEntitySpy).to.have.been.called;\n });\n\n it('Should save a quiz', () => {\n comp.ngOnInit();\n });\n});\n" }, { "alpha_fraction": 0.6693606376647949, "alphanum_fraction": 0.6699379682540894, "avg_line_length": 42.85443115234375, "blob_id": "4ef8e22b5e89d1c9205b7c5a9501c732794a9921", "content_id": "11b6dd591b9776b379e7cced8d6f65f772e5242f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6929, "license_type": "permissive", "max_line_length": 179, "num_lines": 158, "path": "/src/main/webapp/app/overview/exercise-details/programming-exercise-student-ide-actions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, HostBinding, Input, OnInit } from '@angular/core';\nimport { CourseExerciseService } from 'app/course/manage/course-management.service';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { ParticipationStatus } from 'app/entities/exercise.model';\nimport { isStartExerciseAvailable, participationStatus } from 'app/exercises/shared/exercise/exercise-utils';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { OrionState } from 'app/shared/orion/orion';\nimport { OrionConnectorService } from 'app/shared/orion/orion-connector.service';\nimport { OrionBuildAndTestService } from 'app/shared/orion/orion-build-and-test.service';\nimport { catchError, filter, tap } from 'rxjs/operators';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\n\n@Component({\n selector: 'jhi-programming-exercise-student-ide-actions',\n templateUrl: './programming-exercise-student-ide-actions.component.html',\n styleUrls: ['../course-overview.scss'],\n providers: [SourceTreeService],\n})\nexport class ProgrammingExerciseStudentIdeActionsComponent implements OnInit {\n readonly UNINITIALIZED = ParticipationStatus.UNINITIALIZED;\n readonly INITIALIZED = ParticipationStatus.INITIALIZED;\n readonly INACTIVE = ParticipationStatus.INACTIVE;\n readonly participationStatus = participationStatus;\n ideState: OrionState;\n FeatureToggle = FeatureToggle;\n\n @Input() @HostBinding('class.col') equalColumns = true;\n @Input() @HostBinding('class.col-auto') smallColumns = false;\n\n @Input() exercise: ProgrammingExercise;\n @Input() courseId: number;\n\n @Input() smallButtons: boolean;\n\n constructor(\n private jhiAlertService: JhiAlertService,\n private courseExerciseService: CourseExerciseService,\n private javaBridge: OrionConnectorService,\n private ideBuildAndTestService: OrionBuildAndTestService,\n private route: ActivatedRoute,\n ) {}\n\n /**\n * get ideState and submit changes if withIdeSubmit set in route query\n */\n ngOnInit(): void {\n this.javaBridge.state().subscribe((ideState: OrionState) => (this.ideState = ideState));\n this.route.queryParams.subscribe((params) => {\n if (params['withIdeSubmit']) {\n this.submitChanges();\n }\n });\n }\n\n /**\n * see exercise-utils -> isStartExerciseAvailable\n */\n isStartExerciseAvailable(): boolean {\n return isStartExerciseAvailable(this.exercise as ProgrammingExercise);\n }\n\n /**\n * Get the repo URL of a participation. Can be used to clone from the repo or push to it.\n *\n * @param participation The participation for which to get the repository URL\n * @return The URL of the remote repository in which the user's code referring the the current exercise is stored.\n */\n repositoryUrl(participation?: Participation) {\n return (participation as ProgrammingExerciseStudentParticipation)?.repositoryUrl;\n }\n\n /**\n * Starts the exercise by initializing a new participation and creating a new personal repository.\n */\n startExercise() {\n this.exercise.loading = true;\n\n this.courseExerciseService\n .startExercise(this.courseId, this.exercise.id!)\n .finally(() => (this.exercise.loading = false))\n .subscribe(\n (participation: StudentParticipation) => {\n if (participation) {\n this.exercise.studentParticipations = [participation];\n this.exercise.participationStatus = this.participationStatus(this.exercise);\n }\n if (this.exercise.allowOfflineIde) {\n this.jhiAlertService.success('artemisApp.exercise.personalRepositoryClone');\n } else {\n this.jhiAlertService.success('artemisApp.exercise.personalRepositoryOnline');\n }\n },\n () => {\n this.jhiAlertService.warning('artemisApp.exercise.startError');\n },\n );\n }\n\n /**\n * Imports the current exercise in the user's IDE and triggers the opening of the new project in the IDE\n */\n importIntoIDE() {\n const repo = this.repositoryUrl(this.exercise.studentParticipations![0])!;\n this.javaBridge.importParticipation(repo, this.exercise as ProgrammingExercise);\n }\n\n /**\n * Submits the changes made in the IDE by staging everything, committing the changes and pushing them to master.\n */\n submitChanges() {\n this.javaBridge.submit();\n this.ideBuildAndTestService.listenOnBuildOutputAndForwardChanges(this.exercise as ProgrammingExercise);\n }\n\n get canImport(): boolean {\n const notOpenedOrInstructor = this.ideState.inInstructorView || this.ideState.opened !== this.exercise.id;\n\n return this.hasInitializedParticipation() && notOpenedOrInstructor;\n }\n\n get canSubmit(): boolean {\n const openedAndNotInstructor = !this.ideState.inInstructorView && this.ideState.opened === this.exercise.id;\n\n return this.hasInitializedParticipation() && openedAndNotInstructor;\n }\n\n private hasInitializedParticipation(): boolean {\n return this.exercise.studentParticipations !== undefined && this.participationStatus(this.exercise) === this.INITIALIZED && this.exercise.studentParticipations.length > 0;\n }\n\n /**\n * resume programming exercise\n */\n resumeProgrammingExercise() {\n this.exercise.loading = true;\n this.courseExerciseService\n .resumeProgrammingExercise(this.courseId, this.exercise.id!)\n .pipe(\n filter(Boolean),\n tap((participation: StudentParticipation) => {\n participation.results = this.exercise.studentParticipations![0] ? this.exercise.studentParticipations![0].results : [];\n this.exercise.studentParticipations = [participation];\n this.exercise.participationStatus = participationStatus(this.exercise);\n }),\n catchError((error) => {\n this.jhiAlertService.error('artemisApp.exerciseActions.resumeExercise', { error });\n return error;\n }),\n )\n .finally(() => (this.exercise.loading = false))\n .subscribe();\n }\n}\n" }, { "alpha_fraction": 0.6577200293540955, "alphanum_fraction": 0.6577200293540955, "avg_line_length": 37.93258285522461, "blob_id": "0d244b1474f5e224919bf3dd07dd1b199491a35f", "content_id": "81f4fbc3d6c56c63778a8ae911fd382402c59b85", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6930, "license_type": "permissive", "max_line_length": 164, "num_lines": 178, "path": "/src/main/webapp/app/overview/student-questions/student-question-row/student-question-row.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { User } from 'app/core/user/user.model';\nimport * as moment from 'moment';\nimport { HttpResponse } from '@angular/common/http';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestionService } from 'app/overview/student-questions/student-question/student-question.service';\nimport { StudentQuestionAnswerService } from 'app/overview/student-questions/student-question-answer/student-question-answer.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { QuestionAnswerActionName, StudentQuestionAnswerAction } from 'app/overview/student-questions/student-question-answer/student-question-answer.component';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { QuestionActionName, StudentQuestionAction } from 'app/overview/student-questions/student-question/student-question.component';\n\nexport interface StudentQuestionRowAction {\n name: QuestionRowActionName;\n studentQuestion: StudentQuestion;\n}\n\nexport enum QuestionRowActionName {\n DELETE,\n VOTE_CHANGE,\n}\n\n@Component({\n selector: 'jhi-student-question-row',\n templateUrl: './student-question-row.component.html',\n styleUrls: ['./../student-questions.scss'],\n})\nexport class StudentQuestionRowComponent implements OnInit {\n @Input() studentQuestion: StudentQuestion;\n @Input() selectedStudentQuestion: StudentQuestion;\n @Input() user: User;\n @Input() isAtLeastTutorInCourse: boolean;\n @Output() interactQuestionRow = new EventEmitter<StudentQuestionRowAction>();\n isExpanded = true;\n isAnswerMode: boolean;\n showOtherAnswers = false;\n questionAnswerText?: string;\n sortedQuestionAnswers: StudentQuestionAnswer[];\n approvedQuestionAnswers: StudentQuestionAnswer[];\n EditorMode = EditorMode;\n courseId: number;\n\n constructor(\n private studentQuestionAnswerService: StudentQuestionAnswerService,\n private studentQuestionService: StudentQuestionService,\n private localStorage: LocalStorageService,\n private route: ActivatedRoute,\n ) {}\n\n /**\n * sort answers when component is initialized\n */\n ngOnInit(): void {\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n this.sortQuestionAnswers();\n }\n\n /**\n * interact with asnwer component\n * @param {StudentQuestionAnswerAction} action\n */\n interactAnswer(action: StudentQuestionAnswerAction) {\n switch (action.name) {\n case QuestionAnswerActionName.DELETE:\n this.deleteAnswerFromList(action.studentQuestionAnswer);\n break;\n case QuestionAnswerActionName.ADD:\n this.addAnswerToList(action.studentQuestionAnswer);\n break;\n case QuestionAnswerActionName.APPROVE:\n this.sortQuestionAnswers();\n break;\n }\n }\n\n /**\n * interact with question component\n * @param {StudentQuestionAction} action\n */\n interactQuestion(action: StudentQuestionAction): void {\n switch (action.name) {\n case QuestionActionName.DELETE:\n this.deleteQuestion();\n break;\n case QuestionActionName.EXPAND:\n this.isExpanded = !this.isExpanded;\n break;\n case QuestionActionName.VOTE_CHANGE:\n this.interactQuestionRow.emit({\n name: QuestionRowActionName.VOTE_CHANGE,\n studentQuestion: action.studentQuestion,\n });\n break;\n }\n }\n\n /**\n * sorts the answers of a question into approved and not approved and then by date\n */\n sortQuestionAnswers(): void {\n if (!this.studentQuestion.answers) {\n this.sortedQuestionAnswers = [];\n this.approvedQuestionAnswers = [];\n return;\n }\n this.approvedQuestionAnswers = this.studentQuestion.answers\n .filter((ans) => ans.tutorApproved)\n .sort((a, b) => {\n const aValue = moment(a.answerDate!).valueOf();\n const bValue = moment(b.answerDate!).valueOf();\n\n return aValue - bValue;\n });\n this.sortedQuestionAnswers = this.studentQuestion.answers\n .filter((ans) => !ans.tutorApproved)\n .sort((a, b) => {\n const aValue = moment(a.answerDate!).valueOf();\n const bValue = moment(b.answerDate!).valueOf();\n\n return aValue - bValue;\n });\n }\n\n /**\n * deletes the studentQuestion\n */\n deleteQuestion(): void {\n this.studentQuestionService.delete(this.courseId, this.studentQuestion.id!).subscribe(() => {\n this.localStorage.clear(`q${this.studentQuestion.id}u${this.user.id}`);\n this.interactQuestionRow.emit({\n name: QuestionRowActionName.DELETE,\n studentQuestion: this.studentQuestion,\n });\n });\n }\n\n /**\n * Creates a new studentAnswer\n */\n addAnswer(): void {\n const studentQuestionAnswer = new StudentQuestionAnswer();\n studentQuestionAnswer.answerText = this.questionAnswerText;\n studentQuestionAnswer.author = this.user;\n studentQuestionAnswer.verified = true;\n studentQuestionAnswer.question = this.studentQuestion;\n studentQuestionAnswer.tutorApproved = false;\n studentQuestionAnswer.answerDate = moment();\n this.studentQuestionAnswerService.create(this.courseId, studentQuestionAnswer).subscribe((studentQuestionResponse: HttpResponse<StudentQuestionAnswer>) => {\n if (!this.studentQuestion.answers) {\n this.studentQuestion.answers = [];\n }\n this.studentQuestion.answers.push(studentQuestionResponse.body!);\n this.sortQuestionAnswers();\n this.questionAnswerText = undefined;\n this.isAnswerMode = false;\n });\n }\n\n /**\n * Takes a studentAnswer and deletes it\n * @param {studentQuestionAnswer} studentQuestionAnswer\n */\n deleteAnswerFromList(studentQuestionAnswer: StudentQuestionAnswer): void {\n this.studentQuestion.answers = this.studentQuestion.answers?.filter((el: StudentQuestionAnswer) => el.id !== studentQuestionAnswer.id);\n this.sortQuestionAnswers();\n }\n\n /**\n * Takes a studentAnswer and adds it to the others\n * @param {StudentQuestionAnswer} studentQuestionAnswer\n */\n addAnswerToList(studentQuestionAnswer: StudentQuestionAnswer): void {\n this.studentQuestion.answers!.push(studentQuestionAnswer);\n this.sortQuestionAnswers();\n }\n}\n" }, { "alpha_fraction": 0.6372296214103699, "alphanum_fraction": 0.6376200318336487, "avg_line_length": 41.689998626708984, "blob_id": "9af4884fba0fe7a16ce8244f16b4270c980c51de", "content_id": "7b61c5e2e703d88ea44c46920a671c2ca23a148f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12807, "license_type": "permissive", "max_line_length": 153, "num_lines": 300, "path": "/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { JhiAlertService, JhiEventManager } from 'ng-jhipster';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Subscription } from 'rxjs';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { HttpResponse } from '@angular/common/http';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { getLatestSubmissionResult, setLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nimport { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { getLinkToSubmissionAssessment } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-assessment-dashboard',\n templateUrl: './modeling-assessment-dashboard.component.html',\n providers: [],\n})\nexport class ModelingAssessmentDashboardComponent implements OnInit, OnDestroy {\n // make constants available to html for comparison\n ExerciseType = ExerciseType;\n AssessmentType = AssessmentType;\n\n course: Course;\n exercise: ModelingExercise;\n paramSub: Subscription;\n predicate: string;\n reverse: boolean;\n nextOptimalSubmissionIds: number[] = [];\n courseId: number;\n examId: number;\n exerciseId: number;\n exerciseGroupId: number;\n numberOfCorrectionrounds = 1;\n\n private cancelConfirmationText: string;\n\n // all available submissions\n submissions: ModelingSubmission[];\n filteredSubmissions: ModelingSubmission[];\n optimalSubmissions: ModelingSubmission[];\n // non optimal submissions\n otherSubmissions: ModelingSubmission[];\n\n eventSubscriber: Subscription;\n assessedSubmissions: number;\n allSubmissionsVisible: boolean;\n busy: boolean;\n userId: number;\n canOverrideAssessments: boolean;\n\n constructor(\n private route: ActivatedRoute,\n private jhiAlertService: JhiAlertService,\n private router: Router,\n private courseService: CourseManagementService,\n private exerciseService: ExerciseService,\n private resultService: ResultService,\n private modelingSubmissionService: ModelingSubmissionService,\n private modelingAssessmentService: ModelingAssessmentService,\n private modalService: NgbModal,\n private eventManager: JhiEventManager,\n private accountService: AccountService,\n private translateService: TranslateService,\n private sortService: SortService,\n ) {\n this.reverse = false;\n this.predicate = 'id';\n this.submissions = [];\n this.filteredSubmissions = [];\n this.optimalSubmissions = [];\n this.otherSubmissions = [];\n this.canOverrideAssessments = this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR]);\n translateService.get('modelingAssessmentEditor.messages.confirmCancel').subscribe((text) => (this.cancelConfirmationText = text));\n }\n\n ngOnInit() {\n this.accountService.identity().then((user) => {\n this.userId = user!.id!;\n });\n this.paramSub = this.route.params.subscribe((params) => {\n this.courseId = params['courseId'];\n this.courseService.find(this.courseId).subscribe((res: HttpResponse<Course>) => {\n this.course = res.body!;\n });\n this.exerciseId = params['exerciseId'];\n this.exerciseService.find(this.exerciseId).subscribe((res: HttpResponse<Exercise>) => {\n if (res.body!.type === ExerciseType.MODELING) {\n this.exercise = res.body as ModelingExercise;\n this.courseId = this.exercise.course ? this.exercise.course.id! : this.exercise.exerciseGroup!.exam!.course!.id!;\n this.getSubmissions(true);\n this.numberOfCorrectionrounds = this.exercise.exerciseGroup ? this.exercise!.exerciseGroup.exam!.numberOfCorrectionRoundsInExam! : 1;\n this.setPermissions();\n } else {\n // TODO: error message if this is not a modeling exercise\n }\n });\n\n this.examId = params['examId'];\n this.exerciseGroupId = params['exerciseGroupId'];\n });\n this.registerChangeInResults();\n }\n\n registerChangeInResults() {\n this.eventSubscriber = this.eventManager.subscribe('resultListModification', () => this.getSubmissions(true));\n }\n\n /**\n * Get all results for the current modeling exercise, this includes information about all submitted models ( = submissions)\n *\n * @param {boolean} forceReload force REST call to update nextOptimalSubmissionIds\n */\n getSubmissions(forceReload: boolean) {\n this.modelingSubmissionService\n .getModelingSubmissionsForExerciseByCorrectionRound(this.exercise.id!, { submittedOnly: true })\n .subscribe((res: HttpResponse<ModelingSubmission[]>) => {\n // only use submissions that have already been submitted (this makes sure that unsubmitted submissions are not shown\n // the server should have filtered these submissions already\n this.submissions = res.body!.filter((submission) => submission.submitted);\n this.submissions.forEach((submission) => {\n const tmpResult = getLatestSubmissionResult(submission);\n if (tmpResult) {\n // reconnect some associations\n submission.latestResult = tmpResult;\n tmpResult!.submission = submission;\n tmpResult!.participation = submission.participation;\n if (submission.participation) {\n submission.participation.results = [tmpResult!];\n }\n }\n });\n this.filteredSubmissions = this.submissions;\n this.filterSubmissions(forceReload);\n this.assessedSubmissions = this.submissions.filter((submission) => {\n const result = getLatestSubmissionResult(submission);\n setLatestSubmissionResult(submission, result);\n return !!result;\n }).length;\n });\n }\n\n updateFilteredSubmissions(filteredSubmissions: Submission[]) {\n this.filteredSubmissions = filteredSubmissions as ModelingSubmission[];\n this.applyFilter();\n }\n\n /**\n * Check if nextOptimalSubmissionIds are needed then applyFilter\n *\n * @param {boolean} forceReload force REST call to update nextOptimalSubmissionIds\n */\n filterSubmissions(forceReload: boolean) {\n if (this.exercise.assessmentType === AssessmentType.SEMI_AUTOMATIC && (this.nextOptimalSubmissionIds.length < 3 || forceReload)) {\n this.modelingAssessmentService.getOptimalSubmissions(this.exercise.id!).subscribe(\n (optimal: number[]) => {\n this.nextOptimalSubmissionIds = optimal;\n this.applyFilter();\n },\n () => {\n this.applyFilter();\n },\n );\n } else {\n this.applyFilter();\n }\n }\n\n /**\n * Mark results as optimal and split them up in all, optimal and not optimal sets\n */\n applyFilter() {\n // A submission is optimal if it is part of nextOptimalSubmissionIds and (nobody is currently assessing it or you are currently assessing it)\n this.submissions.forEach((submission) => {\n const tmpResult = getLatestSubmissionResult(submission);\n submission.optimal =\n this.nextOptimalSubmissionIds.includes(submission.id!) &&\n (!(tmpResult && tmpResult!.assessor) || (tmpResult && tmpResult!.assessor && tmpResult!.assessor!.id === this.userId));\n });\n this.optimalSubmissions = this.filteredSubmissions.filter((submission) => {\n return submission.optimal;\n });\n this.otherSubmissions = this.filteredSubmissions.filter((submission) => {\n return !submission.optimal;\n });\n }\n\n refresh() {\n this.getSubmissions(true);\n }\n\n /**\n * Reset optimality attribute of models\n */\n resetOptimality() {\n if (this.exercise.assessmentType === AssessmentType.SEMI_AUTOMATIC) {\n this.modelingAssessmentService.resetOptimality(this.exercise.id!).subscribe(() => {\n this.filterSubmissions(true);\n });\n }\n }\n\n makeAllSubmissionsVisible() {\n if (!this.busy) {\n this.allSubmissionsVisible = true;\n }\n }\n\n /**\n * Select the next optimal submission to assess or otherwise trigger the REST call\n */\n assessNextOptimal(): void {\n this.busy = true;\n if (this.nextOptimalSubmissionIds.length === 0) {\n this.modelingAssessmentService.getOptimalSubmissions(this.exercise.id!).subscribe(\n (optimal: number[]) => {\n this.busy = false;\n if (optimal.length === 0) {\n this.jhiAlertService.clear();\n this.jhiAlertService.info('artemisApp.assessmentDashboard.noSubmissionFound');\n } else {\n this.nextOptimalSubmissionIds = optimal;\n this.navigateToNextRandomOptimalSubmission();\n }\n },\n () => {\n this.busy = false;\n this.jhiAlertService.clear();\n this.jhiAlertService.info('artemisApp.assessmentDashboard.noSubmissionFound');\n },\n );\n } else {\n this.navigateToNextRandomOptimalSubmission();\n }\n }\n\n getAssessmentRouterLink(submissionId: number): string[] {\n return getLinkToSubmissionAssessment(ExerciseType.MODELING, this.courseId, this.exerciseId, submissionId, this.examId, this.exerciseGroupId);\n }\n\n private navigateToNextRandomOptimalSubmission(): void {\n const randomInt = Math.floor(Math.random() * this.nextOptimalSubmissionIds.length);\n const url = getLinkToSubmissionAssessment(\n ExerciseType.MODELING,\n this.courseId,\n this.exerciseId,\n this.nextOptimalSubmissionIds[randomInt],\n this.examId,\n this.exerciseGroupId,\n );\n this.router.onSameUrlNavigation = 'reload';\n this.router.navigate(url);\n }\n\n private setPermissions() {\n if (this.exercise.course) {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.course!);\n } else {\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.exerciseGroup?.exam?.course!);\n }\n }\n\n /**\n * Cancel the current assessment and reload the submissions to reflect the change.\n */\n cancelAssessment(submission: Submission) {\n const confirmCancel = window.confirm(this.cancelConfirmationText);\n if (confirmCancel) {\n this.modelingAssessmentService.cancelAssessment(submission.id!).subscribe(() => {\n this.refresh();\n });\n }\n }\n\n ngOnDestroy() {\n this.paramSub.unsubscribe();\n this.eventManager.destroy(this.eventSubscriber);\n }\n\n public sortRows() {\n this.sortService.sortByProperty(this.otherSubmissions, this.predicate, this.reverse);\n }\n\n /**\n * get the link for the assessment of a specific submission of the current exercise\n */\n getAssessmentLink(submissionId: number): string[] {\n return getLinkToSubmissionAssessment(this.exercise.type!, this.courseId, this.exerciseId, submissionId, this.examId, this.exerciseGroupId);\n }\n}\n" }, { "alpha_fraction": 0.6955445408821106, "alphanum_fraction": 0.6955445408821106, "avg_line_length": 41.52631759643555, "blob_id": "4922810830958a14a669aef2293292b5a843882b", "content_id": "ded6d2cebcbb34dc17a89a214e63baf829cdfe3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1616, "license_type": "permissive", "max_line_length": 141, "num_lines": 38, "path": "/src/test/javascript/spec/component/lecture-unit/unit-creation-card.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { UnitCreationCardComponent } from 'app/lecture/lecture-unit/lecture-unit-management/unit-creation-card/unit-creation-card.component';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { RouterTestingModule } from '@angular/router/testing';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('UnitCreationCardComponent', () => {\n let unitCreationCardComponentFixture: ComponentFixture<UnitCreationCardComponent>;\n let unitCreationCardComponent: UnitCreationCardComponent;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule],\n declarations: [UnitCreationCardComponent, MockPipe(ArtemisTranslatePipe), MockComponent(FaIconComponent)],\n providers: [],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n unitCreationCardComponentFixture = TestBed.createComponent(UnitCreationCardComponent);\n unitCreationCardComponent = unitCreationCardComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n unitCreationCardComponentFixture.detectChanges();\n expect(unitCreationCardComponent).to.be.ok;\n });\n});\n" }, { "alpha_fraction": 0.7305818200111389, "alphanum_fraction": 0.7324448227882385, "avg_line_length": 49.565216064453125, "blob_id": "2bddb98b62ea7f4608a62891d8c20fb1680cdefd", "content_id": "ea9b674a5f201b4fb9635758ef3e7aae164ca282", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6978, "license_type": "permissive", "max_line_length": 180, "num_lines": 138, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/AbstractVersionControlService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors;\n\nimport static de.tum.in.www1.artemis.config.Constants.*;\n\nimport java.io.IOException;\nimport java.nio.file.Path;\nimport java.util.Optional;\n\nimport org.apache.commons.io.FileUtils;\nimport org.eclipse.jgit.api.errors.GitAPIException;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.ApplicationContext;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.Repository;\nimport de.tum.in.www1.artemis.domain.VcsRepositoryUrl;\nimport de.tum.in.www1.artemis.domain.enumeration.InitializationState;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.exception.VersionControlException;\nimport de.tum.in.www1.artemis.service.UrlService;\n\npublic abstract class AbstractVersionControlService implements VersionControlService {\n\n private final Logger log = LoggerFactory.getLogger(AbstractVersionControlService.class);\n\n @Value(\"${server.url}\")\n protected String ARTEMIS_SERVER_URL;\n\n @Value(\"${artemis.lti.user-prefix-edx:#{null}}\")\n protected Optional<String> userPrefixEdx;\n\n @Value(\"${artemis.lti.user-prefix-u4i:#{null}}\")\n protected Optional<String> userPrefixU4I;\n\n private final ApplicationContext applicationContext;\n\n protected final UrlService urlService;\n\n private final GitService gitService;\n\n public AbstractVersionControlService(ApplicationContext applicationContext, UrlService urlService, GitService gitService) {\n this.applicationContext = applicationContext;\n this.urlService = urlService;\n this.gitService = gitService;\n }\n\n /**\n * Adds a webhook for the specified repository to the given notification URL.\n *\n * @param repositoryUrl The repository to which the webhook should get added to\n * @param notificationUrl The URL the hook should notify\n * @param webHookName Any arbitrary name for the webhook\n */\n protected abstract void addWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName);\n\n /**\n * Adds an authenticated webhook for the specified repository to the given notification URL.\n *\n * @param repositoryUrl The repository to which the webhook should get added to\n * @param notificationUrl The URL the hook should notify\n * @param webHookName Any arbitrary name for the webhook\n * @param secretToken A secret token that authenticates the webhook against the system behind the notification URL\n */\n protected abstract void addAuthenticatedWebHook(VcsRepositoryUrl repositoryUrl, String notificationUrl, String webHookName, String secretToken);\n\n protected ContinuousIntegrationService getContinuousIntegrationService() {\n // We need to get the CI service from the context, because Bamboo and Bitbucket would end up in a circular dependency otherwise\n return applicationContext.getBean(ContinuousIntegrationService.class);\n }\n\n @Override\n public void addWebHooksForExercise(ProgrammingExercise exercise) {\n final var artemisTemplateHookPath = ARTEMIS_SERVER_URL + PROGRAMMING_SUBMISSION_RESOURCE_API_PATH + exercise.getTemplateParticipation().getId();\n final var artemisSolutionHookPath = ARTEMIS_SERVER_URL + PROGRAMMING_SUBMISSION_RESOURCE_API_PATH + exercise.getSolutionParticipation().getId();\n final var artemisTestsHookPath = ARTEMIS_SERVER_URL + TEST_CASE_CHANGED_API_PATH + exercise.getId();\n // first add web hooks from the version control service to Artemis, so that Artemis is notified and can create ProgrammingSubmission when instructors push their template or\n // solution code\n addWebHook(exercise.getVcsTemplateRepositoryUrl(), artemisTemplateHookPath, \"Artemis WebHook\");\n addWebHook(exercise.getVcsSolutionRepositoryUrl(), artemisSolutionHookPath, \"Artemis WebHook\");\n addWebHook(exercise.getVcsTestRepositoryUrl(), artemisTestsHookPath, \"Artemis WebHook\");\n }\n\n @Override\n public void addWebHookForParticipation(ProgrammingExerciseParticipation participation) {\n if (!participation.getInitializationState().hasCompletedState(InitializationState.INITIALIZED)) {\n // first add a web hook from the version control service to Artemis, so that Artemis is notified can create a ProgrammingSubmission when students push their code\n addWebHook(participation.getVcsRepositoryUrl(), ARTEMIS_SERVER_URL + PROGRAMMING_SUBMISSION_RESOURCE_API_PATH + participation.getId(), \"Artemis WebHook\");\n }\n }\n\n @Override\n public VcsRepositoryUrl copyRepository(String sourceProjectKey, String sourceRepositoryName, String targetProjectKey, String targetRepositoryName)\n throws VersionControlException {\n sourceRepositoryName = sourceRepositoryName.toLowerCase();\n targetRepositoryName = targetRepositoryName.toLowerCase();\n final String targetRepoSlug = targetProjectKey.toLowerCase() + \"-\" + targetRepositoryName;\n // get the remote url of the source repo\n final var sourceRepoUrl = getCloneRepositoryUrl(sourceProjectKey, sourceRepositoryName);\n // get the remote url of the target repo\n final var targetRepoUrl = getCloneRepositoryUrl(targetProjectKey, targetRepoSlug);\n Repository targetRepo = null;\n try {\n // create the new target repo\n createRepository(targetProjectKey, targetRepoSlug, null);\n // clone the source repo to the target directory\n targetRepo = gitService.getOrCheckoutRepositoryIntoTargetDirectory(sourceRepoUrl, targetRepoUrl, true);\n // copy by pushing the source's content to the target's repo\n gitService.pushSourceToTargetRepo(targetRepo, targetRepoUrl);\n }\n catch (InterruptedException | GitAPIException e) {\n Path localPath = gitService.getDefaultLocalPathOfRepo(targetRepoUrl);\n try {\n if (targetRepo != null) {\n // delete the target repo if an error occurs\n gitService.deleteLocalRepository(targetRepo);\n }\n else {\n // or delete the folder if it exists\n FileUtils.deleteDirectory(localPath.toFile());\n }\n }\n catch (IOException ex) {\n // ignore\n log.error(\"Could not delete directory of the failed cloned repository in: {}\", localPath);\n }\n throw new VersionControlException(\"Could not copy repository \" + sourceRepositoryName + \" to the target repository \" + targetRepositoryName, e);\n }\n\n return targetRepoUrl;\n }\n\n @Override\n public String getRepositoryName(VcsRepositoryUrl repositoryUrl) {\n return urlService.getRepositorySlugFromRepositoryUrl(repositoryUrl);\n }\n}\n" }, { "alpha_fraction": 0.7410788536071777, "alphanum_fraction": 0.7410788536071777, "avg_line_length": 39.16666793823242, "blob_id": "dd68b58d4adbc6d64fe9f086ad02880a6d362ac1", "content_id": "f6aead110716752f81b3c637874a9c511b28aaa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1205, "license_type": "permissive", "max_line_length": 100, "num_lines": 30, "path": "/src/main/webapp/app/course/dashboards/assessment-dashboard/assessment-dashboard-information.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\n\n@Component({\n selector: 'jhi-assessment-dashboard-information',\n templateUrl: './assessment-dashboard-information.component.html',\n})\nexport class AssessmentDashboardInformationComponent {\n @Input() isExamMode: boolean;\n @Input() numberOfTutorAssessments: number;\n @Input() courseId: number;\n @Input() complaintsEnabled: boolean;\n @Input() feedbackRequestEnabled: boolean;\n @Input() tutorId: number;\n @Input() numberOfTutorComplaints: number;\n @Input() numberOfTutorMoreFeedbackRequests: number;\n @Input() numberOfAssessmentLocks: number;\n @Input() totalNumberOfAssessmentLocks: number;\n\n @Input() examId?: number;\n\n @Input() totalNumberOfAssessments: DueDateStat;\n @Input() numberOfSubmissions: DueDateStat;\n @Input() numberOfCorrectionRounds: number;\n @Input() totalAssessmentPercentage: number;\n @Input() numberOfAssessmentsOfCorrectionRounds: DueDateStat[];\n @Input() isAtLeastInstructor: boolean;\n @Input() numberOfComplaints: number;\n @Input() numberOfMoreFeedbackRequests: number;\n}\n" }, { "alpha_fraction": 0.6508232355117798, "alphanum_fraction": 0.6541552543640137, "avg_line_length": 39.97991943359375, "blob_id": "4bfa5b6df95d6cdc87173aa8c03476db969dfc5c", "content_id": "8a9af087a3fb900f036024a3f9c43ff957105344", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10204, "license_type": "permissive", "max_line_length": 156, "num_lines": 249, "path": "/src/test/javascript/spec/component/exam/manage/exam-exercise-row-buttons.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { Router, RouterModule } from '@angular/router';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { Course } from 'app/entities/course.model';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { HttpResponse } from '@angular/common/http';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamExerciseRowButtonsComponent } from 'app/exercises/shared/exam-exercise-row-buttons/exam-exercise-row-buttons.component';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { ExerciseGroupsComponent } from 'app/exam/manage/exercise-groups/exercise-groups.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport * as moment from 'moment';\nimport { of } from 'rxjs';\nimport { TranslateTestingModule } from '../../../helpers/mocks/service/mock-translate.service';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { MockRouter } from '../../../helpers/mocks/service/mock-route.service';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { FileUploadExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/file-upload-exercise-cell/file-upload-exercise-group-cell.component';\nimport { ModelingExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/modeling-exercise-cell/modeling-exercise-group-cell.component';\nimport { ProgrammingExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/programming-exercise-cell/programming-exercise-group-cell.component';\nimport { QuizExerciseGroupCellComponent } from 'app/exam/manage/exercise-groups/quiz-exercise-cell/quiz-exercise-group-cell.component';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Exam Exercise Row Buttons Component', () => {\n const course = new Course();\n course.id = 456;\n course.isAtLeastInstructor = true;\n\n const exam = new Exam();\n exam.course = course;\n exam.id = 123;\n\n const dueDateStat = { inTime: 0, late: 0 } as DueDateStat;\n\n const quizQuestions = [\n {\n id: 1,\n text: 'text1',\n },\n {\n id: 2,\n text: 'text2',\n },\n ];\n\n const fileExercise = {\n id: 1,\n type: ExerciseType.FILE_UPLOAD,\n maxPoints: 100,\n secondCorrectionEnabled: false,\n studentAssignedTeamIdComputed: false,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat],\n };\n const programmingExercise = {\n id: 2,\n type: ExerciseType.PROGRAMMING,\n maxPoints: 100,\n secondCorrectionEnabled: false,\n studentAssignedTeamIdComputed: false,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat],\n };\n const modelingExercise = {\n id: 3,\n type: ExerciseType.MODELING,\n maxPoints: 100,\n secondCorrectionEnabled: false,\n studentAssignedTeamIdComputed: false,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat],\n };\n const textExercise = {\n id: 4,\n type: ExerciseType.TEXT,\n maxPoints: 100,\n secondCorrectionEnabled: false,\n studentAssignedTeamIdComputed: false,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat],\n };\n const quizExercise = {\n id: 5,\n type: ExerciseType.QUIZ,\n maxPoints: 100,\n secondCorrectionEnabled: false,\n studentAssignedTeamIdComputed: false,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat],\n quizQuestions,\n };\n\n let comp: ExamExerciseRowButtonsComponent;\n let fixture: ComponentFixture<ExamExerciseRowButtonsComponent>;\n let textExerciseService: TextExerciseService;\n let modelingExerciseService: ModelingExerciseService;\n let fileUploadExerciseService: FileUploadExerciseService;\n let quizExerciseService: QuizExerciseService;\n let programmingExerciseService: ProgrammingExerciseService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateTestingModule, RouterModule],\n declarations: [\n ExerciseGroupsComponent,\n ExamExerciseRowButtonsComponent,\n MockComponent(AlertComponent),\n MockDirective(DeleteButtonDirective),\n MockDirective(HasAnyAuthorityDirective),\n MockDirective(NgbTooltip),\n MockPipe(ArtemisTranslatePipe),\n MockComponent(ProgrammingExerciseGroupCellComponent),\n MockComponent(QuizExerciseGroupCellComponent),\n MockComponent(FileUploadExerciseGroupCellComponent),\n MockComponent(ModelingExerciseGroupCellComponent),\n ],\n providers: [{ provide: Router, useClass: MockRouter }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(ExamExerciseRowButtonsComponent);\n comp = fixture.componentInstance;\n\n textExerciseService = TestBed.inject(TextExerciseService);\n modelingExerciseService = TestBed.inject(ModelingExerciseService);\n fileUploadExerciseService = TestBed.inject(FileUploadExerciseService);\n quizExerciseService = TestBed.inject(QuizExerciseService);\n programmingExerciseService = TestBed.inject(ProgrammingExerciseService);\n });\n\n beforeEach(() => {\n comp.course = course;\n comp.exam = exam;\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n describe('check exam is over', () => {\n it('should check exam is over is true', () => {\n comp.latestIndividualEndDate = moment().subtract(1, 'days');\n\n const isExamOver = comp.isExamOver();\n\n expect(isExamOver).to.be.true;\n });\n\n it('should check exam is over is false', () => {\n comp.latestIndividualEndDate = moment().add(1, 'days');\n\n const isExamOver = comp.isExamOver();\n\n expect(isExamOver).to.be.false;\n });\n });\n\n describe('check exercise deletion', () => {\n it('should delete textExercise', () => {\n comp.exercise = textExercise;\n const textExerciseServiceDeleteStub = sinon.stub(textExerciseService, 'delete').returns(\n of(\n new HttpResponse<{}>({ body: [] }),\n ),\n );\n\n comp.deleteExercise();\n\n expect(textExerciseServiceDeleteStub).to.have.been.calledOnceWith(textExercise.id);\n });\n\n it('should delete modelingExercise', () => {\n comp.exercise = modelingExercise;\n const modelingExerciseServiceDeleteStub = sinon.stub(modelingExerciseService, 'delete').returns(\n of(\n new HttpResponse<{}>({ body: [] }),\n ),\n );\n\n comp.deleteExercise();\n\n expect(modelingExerciseServiceDeleteStub).to.have.been.calledOnceWith(modelingExercise.id);\n });\n\n it('should delete fileExercise', () => {\n comp.exercise = fileExercise;\n const fileExerciseServiceDeleteStub = sinon.stub(fileUploadExerciseService, 'delete').returns(\n of(\n new HttpResponse<{}>({ body: [] }),\n ),\n );\n\n comp.deleteExercise();\n\n expect(fileExerciseServiceDeleteStub).to.have.been.calledOnceWith(fileExercise.id);\n });\n\n it('should delete quizExercise', () => {\n comp.exercise = quizExercise;\n const quizExerciseServiceDeleteStub = sinon.stub(quizExerciseService, 'delete').returns(\n of(\n new HttpResponse<{}>({ body: [] }),\n ),\n );\n\n comp.deleteExercise();\n\n expect(quizExerciseServiceDeleteStub).to.have.been.calledOnceWith(quizExercise.id);\n });\n\n it('should delete programmingExercise', () => {\n comp.exercise = programmingExercise;\n const programmingExerciseServiceDeleteStub = sinon.stub(programmingExerciseService, 'delete').returns(\n of(\n new HttpResponse<{}>({ body: [] }),\n ),\n );\n\n comp.deleteProgrammingExercise({ deleteStudentReposBuildPlans: true, deleteBaseReposBuildPlans: false });\n\n expect(programmingExerciseServiceDeleteStub).to.have.been.calledOnceWith(programmingExercise.id, true, false);\n });\n });\n\n describe('check quiz is being exported', () => {\n it('should export quiz exercise by id', () => {\n comp.exercise = quizExercise;\n const quizExerciseServiceFindStub = sinon.stub(quizExerciseService, 'find').returns(\n of(\n new HttpResponse<QuizExercise>({ body: quizExercise }),\n ),\n );\n const quizExerciseServiceExportQuizStub = sinon.stub(quizExerciseService, 'exportQuiz');\n\n comp.exportQuizById(true);\n\n expect(quizExerciseServiceFindStub).to.have.been.calledOnceWith(quizExercise.id);\n expect(quizExerciseServiceExportQuizStub).to.have.been.calledOnceWith(quizQuestions, true);\n });\n });\n});\n" }, { "alpha_fraction": 0.8052738308906555, "alphanum_fraction": 0.8052738308906555, "avg_line_length": 48.29999923706055, "blob_id": "a9dbede68810139badb77fb089fc8d6721fc9c10", "content_id": "fb1c8cfcc1bca3cb22a060b20b0e1d5d949a627f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 493, "license_type": "permissive", "max_line_length": 105, "num_lines": 10, "path": "/src/main/webapp/app/course/course-participant-scores/course-participant-scores.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { CourseParticipantScoresComponent } from './course-participant-scores.component';\nimport { ArtemisParticipantScoresModule } from 'app/shared/participant-scores/participant-scores.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, ArtemisParticipantScoresModule],\n declarations: [CourseParticipantScoresComponent],\n})\nexport class ArtemisCourseParticipantScoresModule {}\n" }, { "alpha_fraction": 0.7148514986038208, "alphanum_fraction": 0.7148514986038208, "avg_line_length": 32.66666793823242, "blob_id": "801e8d717690038dee76ab7dd594e29c7d5bb82f", "content_id": "cd1c9512399badac4907282d8f88182671a92e02", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 505, "license_type": "permissive", "max_line_length": 74, "num_lines": 15, "path": "/src/main/webapp/app/entities/learningGoal.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { Course } from 'app/entities/course.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { LectureUnit } from 'app/entities/lecture-unit/lectureUnit.model';\n\nexport class LearningGoal implements BaseEntity {\n public id?: number;\n public title?: string;\n public description?: string;\n public course?: Course;\n public exercises?: Exercise[];\n public lectureUnits?: LectureUnit[];\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.6700301170349121, "alphanum_fraction": 0.6755995154380798, "avg_line_length": 39.91688919067383, "blob_id": "81ce1b27bf74196e47e4edeed39c8d8090a3f1f1", "content_id": "7056b144d6a6cae988e823c0a3d26d59d1322e53", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 15262, "license_type": "permissive", "max_line_length": 437, "num_lines": 373, "path": "/docs/dev/guidelines/client.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "******\nClient\n******\n\nWORK IN PROGRESS\n\n0. General\n==========\n\nThe Artemis client is an Angular project. Keep https://angular.io/guide/styleguide in mind.\n\nSome general aspects:\n\n* Never invoke methods from the html template. The automatic change tracking in Angular will kill the application performance\n* The Artemis client uses lazy loading to keep the initial bundle size below 2 MB.\n* Code quality and test coverage are important. Try to reuse code and avoid code duplication. Write meaningful tests!\n\n1. Names\n========\n\n1. Use PascalCase for type names.\n2. Do not use \"I\" as a prefix for interface names.\n3. Use PascalCase for enum values.\n4. Use camelCase for function names.\n5. Use camelCase for property names and local variables.\n6. Do not use \"_\" as a prefix for private properties.\n7. Use whole words in names when possible.\n\n2. Components\n=============\n\n1. 1 file per logical component (e.g. parser, scanner, emitter, checker).\n2. Do not add new files. :)\n3. files with \".generated.*\" suffix are auto-generated, do not hand-edit them.\n\n3. Types\n========\n\n1. Do not export types/functions unless you need to share it across multiple components.\n2. Do not introduce new types/values to the global namespace.\n3. Shared types should be defined in 'types.ts'.\n4. Within a file, type definitions should come first.\n\n4. ``null`` and ``undefined``\n=============================\n\n1. Use **undefined**. Do not use null.\n\n5. General Assumptions\n======================\n\n1. Consider objects like Nodes, Symbols, etc. as immutable outside the component that created them. Do not change them.\n2. Consider arrays as immutable by default after creation.\n\n6. Comments\n============\n\n1. Use JSDoc style comments for functions, interfaces, enums, and classes.\n\n7. Strings\n============\n\n1. Use single quotes for strings.\n2. All strings visible to the user need to be localized (make an entry in the corresponding ``*.json`` file).\n\n8. Style\n========\n\n1. Use arrow functions over anonymous function expressions.\n2. Always surround arrow function parameters.\n For example, ``x => x + x`` is wrong but the following are correct:\n\n 1. ``(x) => x + x``\n 2. ``(x,y) => x + y``\n 3. ``<T>(x: T, y: T) => x === y``\n\n3. Always surround loop and conditional bodies with curly braces. Statements on the same line are allowed to omit braces.\n4. Open curly braces always go on the same line as whatever necessitates them.\n5. Parenthesized constructs should have no surrounding whitespace.\n A single space follows commas, colons, and semicolons in those constructs. For example:\n\n 1. ``for (var i = 0, n = str.length; i < 10; i++) { }``\n 2. ``if (x < 10) { }``\n 3. ``function f(x: number, y: string): void { }``\n\n6. Use a single declaration per variable statement (i.e. use ``var x = 1; var y = 2;`` over ``var x = 1, y = 2;``).\n7. ``else`` goes on the same line from the closing curly brace.\n8. Use 4 spaces per indentation.\n\nWe use ``prettier`` to style code automatically and ``eslint`` to find additional issues.\nYou can find the corresponding commands to invoked those tools in ``package.json``.\n\n9. Testing\n===========\n\n**If you are new to client testing, it is highly recommended that you work through the testing part of the angular tutorial:** https://angular.io/guide/testing\n\nWe use Jest (https://jestjs.io/) as our client testing framework.\n\nThere are different tools available to support client testing. A common combination you can see in our codebase is:\n\n- Sinon (https://sinonjs.org/) for creating test spies, stubs and mocks\n- Chai (https://www.chaijs.com/) with Sinon Chai (https://github.com/domenic/sinon-chai) for assertions.\n- NgMocks (https://www.npmjs.com/package/ng-mocks) for mocking the dependencies of an angular component.\n\nThe most basic test looks similar to this:\n\n .. code:: ts\n\n import * as chai from 'chai';\n import * as sinonChai from 'sinon-chai';\n import * as sinon from 'sinon';\n import { ComponentFixture, TestBed } from '@angular/core/testing';\n\n chai.use(sinonChai);\n const expect = chai.expect;\n\n describe('SomeComponent', () => {\n let someComponentFixture: ComponentFixture<SomeComponent>;\n let someComponent: SomeComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [\n SomeComponent,\n MockPipe(SomePipeUsedInTemplate),\n MockComponent(SomeComponentUsedInTemplate),\n MockDirective(SomeDirectiveUsedInTemplate),\n ],\n providers: [\n MockProvider(SomeServiceUsedInComponent),\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n someComponentFixture = TestBed.createComponent(SomeComponent);\n someComponent = someComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n someComponentFixture.detectChanges();\n expect(SomeComponent).to.be.ok;\n });\n });\n\nSome guidelines:\n\n1. A component should be tested in isolation without any dependencies if possible. Do not simply import the whole production module. Only import real dependencies if it is essential for the test\n that the real dependency is used. Instead mock pipes, directives and components that the component under test depends upon. A very useful technique is writing stubs for child components: https://angular.io/guide/testing-components-scenarios#stubbing-unneeded-components.\n This has the benefit of being able to test the interaction with the child components.\n\n * Services should be mocked if they simply return some data from the server. However, if the service has some form of logic included (for exampling converting dates to moments),\n and this logic is important for the component, do not mock the service methods, but mock the http requests and responses from the api. This allows us to test the interaction\n of the component with the service and in addition test that the service logic works correctly. A good explanation can be found in the official angular documentation: https://angular.io/guide/http#testing-http-requests\n\n .. code:: ts\n\n import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\n describe('SomeComponent', () => {\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n\n ...\n httpMock = injector.get(HttpTestingController);\n });\n\n afterEach(() => {\n ...\n httpMock.verify();\n });\n\n it('should make get request', async () => {\n const returnedFromApi = {some: 'data'};\n\n component.callServiceMethod()\n .subscribe((data) => expect(data).toMatchObject({body: returnedFromApi}));\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromApi));\n });\n });\n\n\n\n\n\n\n2. Do not overuse ``NO_ERRORS_SCHEMA`` (https://angular.io/guide/testing-components-scenarios#no_errors_schema).\n This tells angular to ignore the attributes and unrecognized elements, prefer to use component stubs as mentioned above.\n\n3. When using sinon, use sandboxes (https://sinonjs.org/releases/latest/sandbox/).\n Sandboxes remove the need to keep track of every fake created, which greatly simplifies cleanup and improves readability.\n Since ``[email protected]``, the sinon object is a default sandbox. Unless you have a very advanced setup or need a special configuration, you probably want to only use that one.\n\n4. Make sure to have at least 80% test coverage. Running ``yarn test --coverage`` to create a coverage report. You can also simply run the tests in IntelliJ IDEA with coverage activated.\n\n5. It is preferable to test a component through the interaction of the user with the template. This decouples the test from the concrete implementation used in the component.\n For example if you have a component that loads and displays some data when the user clicks a button, you should query for that button, simulate a click and then assert that the data has been loaded and that the expected\n template changes have occurred.\n\n6. Do not remove the template during tests. The template is a crucial part of a component and should not be removed during test. Do not do this:\n\n\n .. code:: ts\n\n import * as chai from 'chai';\n import * as sinonChai from 'sinon-chai';\n import * as sinon from 'sinon';\n\n chai.use(sinonChai);\n const expect = chai.expect;\n\n describe('SomeComponent', () => {\n let someComponentFixture: ComponentFixture<SomeComponent>;\n let someComponent: SomeComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [\n SomeComponent,\n ],\n providers: [\n ],\n schemas: [],\n })\n .overrideTemplate(SomeComponent, '') // DO NOT DO THIS\n .compileComponents()\n .then(() => {\n someComponentFixture = TestBed.createComponent(SomeComponent);\n someComponent = someComponentFixture.componentInstance;\n });\n });\n });\n\n10. Preventing Memory Leaks\n===========================\n\nIt is crucial that you try to prevent memory leaks in both your components and your tests.\n\nWhat are memory leaks?\n**********************\n\nA very good explanation that you should definitely read to understand the problem: https://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/\n\nIn essence:\n\n* JS is a garbage collected language\n* Modern garbage collectors improve on this algorithm in different ways, but the essence is the same: **reachable pieces of memory are marked as such and the rest is considered garbage.**\n* Unwanted references are references to pieces of memory that the developer knows he or she won't be needing\n anymore but that for some reason are kept inside the tree of an active root. **In the context of JavaScript, unwanted references are variables kept somewhere in the code that will not be used anymore and point to a piece of memory that could otherwise be freed.**\n\nWhat are common reasons for memory leaks?\n*****************************************\nhttps://auth0.com/blog/four-types-of-leaks-in-your-javascript-code-and-how-to-get-rid-of-them/:\n\n* Accidental global variables\n* Forgotten timers or callbacks\n* Out of DOM references\n* Closures\n\nhttps://making.close.com/posts/finding-the-cause-of-a-memory-leak-in-jest\nMocks not being restored after the end of a test, especially when it involves global objects.\n\nhttps://www.twilio.com/blog/prevent-memory-leaks-angular-observable-ngondestroy\nRXJS subscriptions not being unsubscribed.\n\nWhat are ways to identify memory leaks?\n*****************************************\n**Number 1:** Manually checking the heap usage and identifying heap dumps for causes of memory leaks\nhttps://chanind.github.io/javascript/2019/10/12/jest-tests-memory-leak.html\n\nCorresponding commands from the article for our project (enter in the root directory of the project):\n\n.. code-block:: text\n\n node --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage --config ./src/test/javascript/jest.config.js --env=jsdom\n\n.. code-block:: text\n\n node --inspect-brk --expose-gc ./node_modules/.bin/jest --runInBand --logHeapUsage --config ./src/test/javascript/jest.config.js --env=jsdom\n\nA live demonstration of this technique to find the reason for memory leaks in the GitLab repository: https://www.youtube.com/watch?v=GOYmouFrGrE\n\n**Number 2:** Using the experimental leak detection feature from jest\n\n\n.. code-block:: text\n\n --detectLeaks **EXPERIMENTAL**: Detect memory leaks in tests.\n After executing a test, it will try to garbage collect the global object used,\n and fail if it was leaked [boolean] [default: false]\n\n --runInBand, -i Run all tests serially in the current process\n (rather than creating a worker pool of child processes that run tests). This is sometimes useful for debugging, but such use cases are pretty rare.\n\n\n\nNavigate into src/test/javascript and run either\n\n.. code-block:: text\n\n jest --detectLeaks --runInBand\n\nor\n\n.. code-block:: text\n\n jest --detectLeaks\n\n\n11. Defining Routes and Breadcrumbs\n===================================\n\nThe ideal schema for routes is that every variable in a path is preceeded by a unique path segment: ``\\entityA\\:entityIDA\\entityB\\:entityIDB`` \n\nFor example, ``\\courses\\:courseId\\:exerciseId`` is not a good path and should be written as ``\\courses\\:courseId\\exercises\\:exerciseId``.\nDoubling textual segments like ``\\lectures\\statistics\\:lectureId`` should be avoided and instead formulated as ``\\lectures\\:lectureId\\statistics``.\n\nWhen creating a completely new route you will have to register the new paths in ``navbar.ts``. A static/textual url segment gets a translation string assigned in the ``mapping`` table. Due to our code-style guidelines any ``-`` in the segment has to be replaced by a ``_``. If your path includes a variable, you will have to add the preceeding path segment to the ``switch`` statement inside the ``addBreadcrumbForNumberSegment`` method.\n\n.. code-block:: ts\n\n\tconst mapping = {\n\t\tcourses: 'artemisApp.course.home.title',\n\t\tlectures: 'artemisApp.lecture.home.title',\n\t\t// put your new directly translated url segments here\n\t\t// the index is the path segment in which '-' have to be replaced by '_'\n\t\t// the value is the translation string\n\t\tyour_case: 'artemisApp.cases.title',\n\t};\n\n\taddBreadcrumbForNumberSegment(currentPath: string, segment: string): void {\n\t\tswitch (this.lastRouteUrlSegment) {\n\t\t\tcase 'course-management':\n\t\t\t\t// handles :courseId\n\t\t\t\tbreak;\n\t\t\tcase 'lectures':\n\t\t\t\t// handles :lectureId\n\t\t\t\tbreak;\n\t\t\tcase 'your-case':\n\t\t\t\t// add a case here for your :variable which is preceeded in the path by 'your-case'\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n12. Strict Template Check\n=========================\n\nTo prevent errors for strict template rule in TypeScript, Artemis uses following approaches.\n\nUse ArtemisTranslatePipe instead of TranslatePipe\n*************************************************\nDo not use ``placeholder=\"{{ 'global.form.newpassword.placeholder' | translate }}\"``\n\nUse ``placeholder=\"{{ 'global.form.newpassword.placeholder' | artemisTranslate }}\"``\n\nUse ArtemisTimeAgoPipe instead of TimeAgoPipe\n*********************************************\nDo not use ``<span [ngbTooltip]=\"submittedDate | artemisDate\">{{ submittedDate | amTimeAgo }}</span>``\n\nUse ``<span [ngbTooltip]=\"submittedDate | artemisDate\">{{ submittedDate | artemisTimeAgo }}</span>``\n\nSome parts of these guidelines are adapted from https://github.com/microsoft/TypeScript-wiki/blob/master/Coding-guidelines.md\n" }, { "alpha_fraction": 0.7911714911460876, "alphanum_fraction": 0.7911714911460876, "avg_line_length": 33.64706039428711, "blob_id": "fd49cc1e32f5c7b46e9f5617b3ee4cad24215cf9", "content_id": "10f632265307237ce052e5ffb235c8bb24378859", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 589, "license_type": "permissive", "max_line_length": 76, "num_lines": 17, "path": "/src/main/webapp/app/entities/submission-sync-payload.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { User } from 'app/core/user/user.model';\nimport { Submission } from 'app/entities/submission.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\n\nexport class SubmissionSyncPayload {\n public submission: Submission;\n public sender: User;\n}\n\nexport class TextSubmissionSyncPayload extends SubmissionSyncPayload {\n public submission: TextSubmission;\n}\n\nexport class ModelingSubmissionSyncPayload extends SubmissionSyncPayload {\n public submission: ModelingSubmission;\n}\n" }, { "alpha_fraction": 0.679861843585968, "alphanum_fraction": 0.6865922808647156, "avg_line_length": 49.63677215576172, "blob_id": "af7c9a9d9ded32abdf896527952791a74ee7076b", "content_id": "70d04ab193ecf705204d3b41324d2896328b7cbf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11292, "license_type": "permissive", "max_line_length": 164, "num_lines": 223, "path": "/src/test/javascript/spec/component/drag-and-drop-question/drag-and-drop-question.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { NgbCollapse, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap';\nimport { AngularFittextModule } from 'angular-fittext';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { DragItem } from 'app/entities/quiz/drag-item.model';\nimport { DropLocation } from 'app/entities/quiz/drop-location.model';\nimport { DragAndDropQuestionUtil } from 'app/exercises/quiz/shared/drag-and-drop-question-util.service';\nimport { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component';\nimport { DragItemComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-item.component';\nimport { QuizScoringInfoStudentModalComponent } from 'app/exercises/quiz/shared/questions/quiz-scoring-infostudent-modal/quiz-scoring-info-student-modal.component';\nimport { SecuredImageComponent } from 'app/shared/image/secured-image.component';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { DndModule } from 'ng2-dnd';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('DragAndDropQuestionComponent', () => {\n let fixture: ComponentFixture<DragAndDropQuestionComponent>;\n let comp: DragAndDropQuestionComponent;\n let markdownService: ArtemisMarkdownService;\n let dragAndDropQuestionUtil: DragAndDropQuestionUtil;\n const reset = () => {\n const question = new DragAndDropQuestion();\n question.id = 1;\n question.backgroundFilePath = '';\n comp.question = question;\n };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [NgbPopoverModule, ArtemisTestModule, DndModule.forRoot(), AngularFittextModule],\n declarations: [\n DragAndDropQuestionComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(MarkdownEditorComponent),\n MockComponent(SecuredImageComponent),\n MockComponent(DragAndDropQuestionComponent),\n MockDirective(NgbCollapse),\n MockComponent(QuizScoringInfoStudentModalComponent),\n DragItemComponent,\n ],\n providers: [MockProvider(DragAndDropQuestionUtil)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(DragAndDropQuestionComponent);\n comp = fixture.componentInstance;\n reset();\n markdownService = TestBed.inject(ArtemisMarkdownService);\n dragAndDropQuestionUtil = fixture.debugElement.injector.get(DragAndDropQuestionUtil);\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should update html when question changes', () => {\n const question = new DragAndDropQuestion();\n question.text = 'Test text';\n question.hint = 'Test hint';\n question.explanation = 'Test explanation';\n const markdownStub = stub(markdownService, 'safeHtmlForMarkdown').callsFake((arg) => `${arg}markdown`);\n comp.question = question;\n expect(markdownStub).to.have.been.calledWith(question.text);\n expect(markdownStub).to.have.been.calledWith(question.text);\n expect(markdownStub).to.have.been.calledWith(question.text);\n expect(comp.renderedQuestion).to.exist;\n expect(comp.renderedQuestion.text).to.equal(`${question.text}markdown`);\n expect(comp.renderedQuestion.hint).to.equal(`${question.hint}markdown`);\n expect(comp.renderedQuestion.explanation).to.equal(`${question.explanation}markdown`);\n });\n\n it('should count correct mappings as zero if no correct mappings', () => {\n const { dropLocation } = getDropLocationMappingAndItem();\n comp.question.dropLocations = [dropLocation];\n comp.ngOnChanges();\n expect(comp.correctAnswer).to.equal(0);\n });\n\n it('should count correct mappings on changes', () => {\n const { dropLocation: dropLocation1, mapping: correctMapping1 } = getDropLocationMappingAndItem();\n const { dropLocation: dropLocation2, mapping: correctMapping2 } = getDropLocationMappingAndItem();\n const { dropLocation: dropLocation3, mapping: correctMapping3 } = getDropLocationMappingAndItem();\n const { mapping: correctMapping4 } = getDropLocationMappingAndItem();\n const { dropLocation: dropLocation5 } = getDropLocationMappingAndItem();\n comp.question.dropLocations = [dropLocation1, dropLocation2, dropLocation3];\n // Mappings do not have any of drop locations so no selected item\n comp.mappings = [correctMapping4];\n comp.question.correctMappings = [correctMapping1, correctMapping2, correctMapping4];\n comp.ngOnChanges();\n // without selected items it should set correct answers to drop locations without valid drag item\n expect(comp.correctAnswer).to.equal(1);\n\n // if there is a selected item should count drop locations that has the selected items drag item\n // dropLocation1 and dropLocation3 is selected\n // dropLocation1 is both correct and selected\n // dropLocation2 is correct but not selected\n // dropLocation3 is not correct but selected\n // dropLocation4 is not one of the drop locations\n // dropLocation5 is neither correct nor selected\n // Hence 2 because of dropLocation1 and dropLocation5\n comp.mappings = [correctMapping1, correctMapping3];\n comp.question.dropLocations = [dropLocation1, dropLocation2, dropLocation3, dropLocation5];\n comp.ngOnChanges();\n expect(comp.correctAnswer).to.equal(2);\n });\n\n it('should return correct drag item for drop location', () => {\n const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();\n const { dropLocation: falseDropLocation } = getDropLocationMappingAndItem();\n comp.sampleSolutionMappings = [mapping];\n expect(comp.correctDragItemForDropLocation(dropLocation)).to.deep.equal(dragItem);\n expect(comp.correctDragItemForDropLocation(falseDropLocation)).to.null;\n });\n\n it('should show sample solution if force sample solution is set to true', () => {\n const { mapping } = getDropLocationMappingAndItem();\n const solveStub = stub(dragAndDropQuestionUtil, 'solve').returnsArg(1);\n const mappings = [mapping];\n comp.mappings = mappings;\n comp.forceSampleSolution = true;\n expect(comp.forceSampleSolution).to.equal(true);\n expect(solveStub).to.have.been.calledWithExactly(comp.question, mappings);\n expect(comp.sampleSolutionMappings).to.deep.equal(mappings);\n expect(comp.showingSampleSolution).to.equal(true);\n });\n\n it('should hide sample solutions', () => {\n comp.showingSampleSolution = true;\n comp.hideSampleSolution();\n expect(comp.showingSampleSolution).to.equal(false);\n });\n\n it('should return unassigned drag items', () => {\n const { mapping: mapping1, dragItem: dragItem1 } = getDropLocationMappingAndItem();\n const { dragItem: dragItem2 } = getDropLocationMappingAndItem();\n comp.mappings = [mapping1];\n comp.question.dragItems = [dragItem1, dragItem2];\n expect(comp.getUnassignedDragItems()).to.deep.equal([dragItem2]);\n });\n\n it('should return invalid dragItem for location', () => {\n const { dropLocation: dropLocation1, mapping: mapping1 } = getDropLocationMappingAndItem();\n const { dropLocation: dropLocation2, mapping: mapping2, dragItem: dragItem2 } = getDropLocationMappingAndItem();\n comp.mappings = [mapping1, mapping2];\n expect(comp.invalidDragItemForDropLocation(dropLocation1)).to.equal(false);\n dragItem2.invalid = true;\n expect(comp.invalidDragItemForDropLocation(dropLocation2)).to.equal(true);\n });\n\n it('should return no drag item if there is no mapping', () => {\n const { dropLocation } = getDropLocationMappingAndItem();\n expect(comp.dragItemForDropLocation(dropLocation)).to.null;\n });\n\n it('should remove existing mappings when there is no drop location', () => {\n const { mapping, dragItem } = getDropLocationMappingAndItem();\n const { mapping: mapping1 } = getDropLocationMappingAndItem();\n const { mapping: mapping2 } = getDropLocationMappingAndItem();\n checkDragDrop(undefined, dragItem, [mapping, mapping1], [mapping1], 1);\n\n // should not call update if mappings did not change\n checkDragDrop(undefined, dragItem, [mapping1, mapping2], [mapping1, mapping2], 0);\n });\n\n it('should not do anything if given droplocation and dragEvent dragData is mapped', () => {\n const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();\n checkDragDrop(dropLocation, dragItem, [mapping], [mapping], 0);\n });\n\n it('should map dragItem to new drop location', () => {\n const { dropLocation, mapping, dragItem } = getDropLocationMappingAndItem();\n const { dropLocation: dropLocation1, mapping: mapping1, dragItem: dragItem1 } = getDropLocationMappingAndItem();\n const { mapping: mapping2 } = getDropLocationMappingAndItem();\n const newMappings = [mapping2, new DragAndDropMapping(dragItem1, dropLocation), new DragAndDropMapping(dragItem, dropLocation1)];\n checkDragDrop(dropLocation, dragItem1, [mapping, mapping1, mapping2], newMappings, 1);\n });\n\n const checkDragDrop = (\n dropLocation: DropLocation | undefined,\n dragItem: DragItem,\n mappings: DragAndDropMapping[],\n expectedMappings: DragAndDropMapping[],\n callCount: number,\n ) => {\n comp.mappings = mappings;\n const dragEvent = { dragData: dragItem };\n const fnOnMappingUpdate = sinon.fake();\n comp.fnOnMappingUpdate = fnOnMappingUpdate;\n comp.onDragDrop(dropLocation, dragEvent);\n expect(comp.mappings).to.deep.equal(expectedMappings);\n expect(fnOnMappingUpdate.callCount).to.equal(callCount);\n };\n\n it('should change loading with given value', () => {\n comp.changeLoading('loading');\n expect(comp.loadingState).to.equal('loading');\n });\n\n it('should set drop allowed to true when dragged', () => {\n comp.dropAllowed = false;\n comp.drag();\n expect(comp.dropAllowed).to.equal(true);\n });\n\n const getDropLocationMappingAndItem = () => {\n const dropLocation = new DropLocation();\n const dragItem = new DragItem();\n const mapping = new DragAndDropMapping(dragItem, dropLocation);\n return { dropLocation, mapping, dragItem };\n };\n});\n" }, { "alpha_fraction": 0.818599283695221, "alphanum_fraction": 0.818599283695221, "avg_line_length": 57.06666564941406, "blob_id": "5e9af7d05e1c6b7463ef22ea53f81fababa67c22", "content_id": "9dfafe519f72f0cc7fcc741984ca8932b4a0e215", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 871, "license_type": "permissive", "max_line_length": 147, "num_lines": 15, "path": "/src/main/webapp/app/shared/dashboards/dashboards.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisAssessmentDashboardModule } from 'app/course/dashboards/assessment-dashboard/assessment-dashboard.module';\nimport { ArtemisExerciseAssessmentDashboardModule } from 'app/exercises/shared/dashboards/tutor/exercise-assessment-dashboard.module';\nimport { ArtemisInstructorCourseStatsDashboardModule } from 'app/course/dashboards/instructor-course-dashboard/instructor-course-dashboard.module';\nimport { ArtemisInstructorExerciseStatsDashboardModule } from 'app/exercises/shared/dashboards/instructor/instructor-exercise-dashboard.module';\n\n@NgModule({\n imports: [\n ArtemisAssessmentDashboardModule,\n ArtemisExerciseAssessmentDashboardModule,\n ArtemisInstructorCourseStatsDashboardModule,\n ArtemisInstructorExerciseStatsDashboardModule,\n ],\n})\nexport class ArtemisDashboardsModule {}\n" }, { "alpha_fraction": 0.8056768774986267, "alphanum_fraction": 0.8056768774986267, "avg_line_length": 49.88888931274414, "blob_id": "c5fdf0fcd51ef76816c8931c0d8e99bd139e9870", "content_id": "5e737fa3988527c52fc6ac8aaa05de21466fc263", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 458, "license_type": "permissive", "max_line_length": 110, "num_lines": 9, "path": "/src/main/webapp/app/exercises/programming/shared/utils/programming-exercise-utils.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { BuildPlanLinkDirective } from 'app/exercises/programming/shared/utils/build-plan-link.directive';\nimport { BuildPlanButtonDirective } from 'app/exercises/programming/shared/utils/build-plan-button.directive';\n\n@NgModule({\n declarations: [BuildPlanLinkDirective, BuildPlanButtonDirective],\n exports: [BuildPlanLinkDirective, BuildPlanButtonDirective],\n})\nexport class ProgrammingExerciseUtilsModule {}\n" }, { "alpha_fraction": 0.6729211211204529, "alphanum_fraction": 0.6762274503707886, "avg_line_length": 46.818180084228516, "blob_id": "f194d3ae48e9b898056216a0bc81e85017b428b1", "content_id": "8001255694e9ebfd86f3f8d3eb52ae9afcc54e2d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12098, "license_type": "permissive", "max_line_length": 175, "num_lines": 253, "path": "/src/test/javascript/spec/component/participation/participation.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute, Params } from '@angular/router';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { ParticipationComponent } from 'app/exercises/shared/participation/participation.component';\nimport { Course } from 'app/entities/course.model';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { of } from 'rxjs';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport * as sinon from 'sinon';\nimport { SinonStub, stub } from 'sinon';\nimport * as moment from 'moment';\nimport { User } from 'app/core/user/user.model';\nimport { Team } from 'app/entities/team.model';\nimport { formatTeamAsSearchResult } from 'app/exercises/shared/team/team.utils';\nimport { ProgrammingSubmissionService, ProgrammingSubmissionState, ProgrammingSubmissionStateObj } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockProvider } from 'ng-mocks';\nimport { defaultLongDateTimeFormat } from 'app/shared/pipes/artemis-date.pipe';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ParticipationComponent', () => {\n let component: ParticipationComponent;\n let componentFixture: ComponentFixture<ParticipationComponent>;\n let participationService: ParticipationService;\n let exerciseService: ExerciseService;\n let submissionService: ProgrammingSubmissionService;\n\n const exercise: Exercise = { numberOfAssessmentsOfCorrectionRounds: [], studentAssignedTeamIdComputed: false, id: 1, secondCorrectionEnabled: true };\n\n const route = { params: of({ exerciseId: 1 } as Params) } as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule],\n declarations: [ParticipationComponent],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n MockProvider(TranslateService),\n ],\n })\n .overrideTemplate(ParticipationComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(ParticipationComponent);\n component = componentFixture.componentInstance;\n participationService = TestBed.inject(ParticipationService);\n exerciseService = TestBed.inject(ExerciseService);\n submissionService = TestBed.inject(ProgrammingSubmissionService);\n component.exercise = exercise;\n });\n });\n\n afterEach(function () {\n // completely restore all fakes created through the sandbox\n sinon.restore();\n });\n\n it('should initialize for non programming exercise', fakeAsync(() => {\n const theExercise = { ...exercise, type: ExerciseType.FILE_UPLOAD };\n sinon.replace(exerciseService, 'find', sinon.fake.returns(of({ body: theExercise })));\n\n const student: User = { guidedTourSettings: [], id: 1, login: 'student', name: 'Max' };\n const participation: StudentParticipation = { id: 1, student };\n sinon.replace(participationService, 'findAllParticipationsByExercise', sinon.fake.returns(of({ body: [participation] })));\n\n component.ngOnInit();\n tick();\n\n expect(component.isLoading).to.be.false;\n expect(component.participations.length).to.equal(1);\n expect(component.participations[0].id).to.equal(participation.id);\n expect(component.newManualResultAllowed).to.be.false;\n expect(component.presentationScoreEnabled).to.be.false;\n }));\n\n it('should initialize for programming exercise', fakeAsync(() => {\n const theExercise = { ...exercise, type: ExerciseType.PROGRAMMING };\n sinon.replace(exerciseService, 'find', sinon.fake.returns(of({ body: theExercise })));\n\n const student: User = { guidedTourSettings: [], id: 1, login: 'student', name: 'Max' };\n const participation: StudentParticipation = { id: 1, student };\n sinon.replace(participationService, 'findAllParticipationsByExercise', sinon.fake.returns(of({ body: [participation] })));\n\n const submissionState: ProgrammingSubmissionStateObj = { participationId: participation.id!, submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION };\n sinon.replace(submissionService, 'getSubmissionStateOfExercise', sinon.fake.returns(of(submissionState)));\n\n component.ngOnInit();\n tick();\n\n expect(component.isLoading).to.be.false;\n expect(component.participations.length).to.equal(1);\n expect(component.participations[0].id).to.equal(participation.id);\n expect(component.newManualResultAllowed).to.be.false;\n expect(component.presentationScoreEnabled).to.be.false;\n expect(component.exerciseSubmissionState).to.equal(submissionState);\n }));\n\n it('should format a dates correctly', () => {\n expect(component.formatDate(undefined)).to.equal('');\n\n const momentDate = moment();\n expect(component.formatDate(momentDate)).to.equal(momentDate.format(defaultLongDateTimeFormat));\n\n const date = new Date();\n const momentFromDate = moment(date);\n expect(component.formatDate(date)).to.equal(momentFromDate.format(defaultLongDateTimeFormat));\n });\n\n it('should format student login or team name from participation', () => {\n const student: User = { guidedTourSettings: [], id: 1, login: 'student', name: 'Max' };\n const participation: StudentParticipation = { student };\n expect(component.searchResultFormatter(participation)).to.equal(`${student.login} (${student.name})`);\n\n const team: Team = { name: 'Team', shortName: 'T', students: [student] };\n participation.student = undefined;\n participation.team = team;\n expect(component.searchResultFormatter(participation)).to.equal(formatTeamAsSearchResult(team));\n\n // Returns undefined for no student and no team\n participation.student = undefined;\n participation.team = undefined;\n expect(component.searchResultFormatter(participation)).to.be.undefined;\n });\n\n it('should return student login, team short name, or empty from participation', () => {\n const student: User = { guidedTourSettings: [], id: 1, login: 'student', name: 'Max' };\n const team: Team = { name: 'Team', shortName: 'T', students: [student] };\n const participation: StudentParticipation = { student, team };\n\n expect(component.searchTextFromParticipation(participation)).to.be.equal(student.login);\n\n participation.student = undefined;\n expect(component.searchTextFromParticipation(participation)).to.be.equal(team.shortName);\n\n participation.team = undefined;\n expect(component.searchTextFromParticipation(participation)).to.be.empty;\n });\n\n it('should filter participation by prop', () => {\n const student: User = { guidedTourSettings: [], id: 1, login: 'student', name: 'Max' };\n const team: Team = { name: 'Team', shortName: 'T', students: [student] };\n const participation: StudentParticipation = { id: 1, student, team };\n\n component.participationCriteria.filterProp = component.FilterProp.ALL;\n expect(component.filterParticipationByProp(participation)).to.be.true;\n\n // Returns true only if submission count is 0\n component.participationCriteria.filterProp = component.FilterProp.NO_SUBMISSIONS;\n expect(component.filterParticipationByProp(participation)).to.be.false;\n participation.submissionCount = 0;\n expect(component.filterParticipationByProp(participation)).to.be.true;\n participation.submissionCount = 1;\n expect(component.filterParticipationByProp(participation)).to.be.false;\n\n component.exerciseSubmissionState = {};\n component.participationCriteria.filterProp = component.FilterProp.FAILED;\n expect(component.filterParticipationByProp(participation)).to.be.false;\n\n // Test different submission states\n Object.values(ProgrammingSubmissionState).forEach((programmingSubmissionState) => {\n const submissionState: ProgrammingSubmissionStateObj = { participationId: participation.id!, submissionState: programmingSubmissionState };\n component.exerciseSubmissionState = { 1: submissionState };\n const expectedBoolean = programmingSubmissionState === ProgrammingSubmissionState.HAS_FAILED_SUBMISSION;\n expect(component.filterParticipationByProp(participation)).to.equal(expectedBoolean);\n });\n });\n\n describe('Presentation Score', () => {\n let updateSpy: SinonStub;\n\n beforeEach(() => {\n updateSpy = stub(participationService, 'update').returns(of());\n });\n\n const courseWithPresentationScore = {\n id: 1,\n title: 'Presentation Score',\n presentationScore: 2,\n } as Course;\n\n const courseWithoutPresentationScore = {\n id: 2,\n title: 'No Presentation Score',\n presentationScore: 0,\n } as Course;\n\n const exercise1 = {\n id: 1,\n title: 'Exercise 1',\n course: courseWithPresentationScore,\n presentationScoreEnabled: true,\n isAtLeastTutor: true,\n } as Exercise;\n\n const exercise2 = {\n id: 2,\n title: 'Exercise 2',\n course: courseWithoutPresentationScore,\n presentationScoreEnabled: false,\n isAtLeastTutor: true,\n } as Exercise;\n\n const participation = {\n student: { id: 1 },\n exercise: exercise1,\n } as StudentParticipation;\n\n it('should add a presentation score if the feature is enabled', () => {\n component.exercise = exercise1;\n component.presentationScoreEnabled = component.checkPresentationScoreConfig();\n component.addPresentation(participation);\n expect(updateSpy.callCount).to.equal(1);\n updateSpy.resetHistory();\n\n component.exercise = exercise2;\n component.presentationScoreEnabled = component.checkPresentationScoreConfig();\n component.addPresentation(participation);\n expect(updateSpy.callCount).to.equal(0);\n });\n\n it('should remove a presentation score if the feature is enabled', () => {\n component.exercise = exercise1;\n component.presentationScoreEnabled = component.checkPresentationScoreConfig();\n component.removePresentation(participation);\n expect(updateSpy.callCount).to.equal(1);\n updateSpy.resetHistory();\n\n component.exercise = exercise2;\n component.presentationScoreEnabled = component.checkPresentationScoreConfig();\n component.removePresentation(participation);\n expect(updateSpy.callCount).to.equal(0);\n });\n\n it('should check if the presentation score actions should be displayed', () => {\n component.exercise = exercise1;\n expect(component.checkPresentationScoreConfig()).to.be.true;\n\n component.exercise = exercise2;\n expect(component.checkPresentationScoreConfig()).to.be.false;\n });\n });\n});\n" }, { "alpha_fraction": 0.8066977262496948, "alphanum_fraction": 0.8095709681510925, "avg_line_length": 61.302467346191406, "blob_id": "22c8318113584933589e0bf2249377c846a852df", "content_id": "f2ddae99a992d49f7acf52b281c705d134c31ad1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 10093, "license_type": "permissive", "max_line_length": 179, "num_lines": 162, "path": "/src/main/java/de/tum/in/www1/artemis/service/programming/ProgrammingExerciseSimulationService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.programming;\n\nimport static de.tum.in.www1.artemis.domain.enumeration.BuildPlanType.*;\n\nimport java.util.Optional;\n\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.ProgrammingSubmission;\nimport de.tum.in.www1.artemis.domain.Result;\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\nimport de.tum.in.www1.artemis.domain.enumeration.RepositoryType;\nimport de.tum.in.www1.artemis.domain.enumeration.SubmissionType;\nimport de.tum.in.www1.artemis.domain.participation.SolutionProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.domain.participation.TemplateProgrammingExerciseParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.GroupNotificationService;\nimport de.tum.in.www1.artemis.service.messaging.InstanceMessageSendService;\nimport de.tum.in.www1.artemis.service.util.VCSSimulationUtils;\n\n/**\n * Only for local development\n * This class simulates a programming exercises without a connection to a vcs and ci server\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n\n@Profile(\"dev\")\n@Service\npublic class ProgrammingExerciseSimulationService {\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final GroupNotificationService groupNotificationService;\n\n private final ProgrammingExerciseService programmingExerciseService;\n\n private final TemplateProgrammingExerciseParticipationRepository templateProgrammingExerciseParticipationRepository;\n\n private final SolutionProgrammingExerciseParticipationRepository solutionProgrammingExerciseParticipationRepository;\n\n private final ProgrammingSubmissionRepository programmingSubmissionRepository;\n\n private final ResultRepository resultRepository;\n\n public final String domain = \"artemislocalhost:7990/scm/\";\n\n private final InstanceMessageSendService instanceMessageSendService;\n\n public ProgrammingExerciseSimulationService(ProgrammingExerciseRepository programmingExerciseRepository, GroupNotificationService groupNotificationService,\n ProgrammingExerciseService programmingExerciseService, TemplateProgrammingExerciseParticipationRepository templateProgrammingExerciseParticipationRepository,\n SolutionProgrammingExerciseParticipationRepository solutionProgrammingExerciseParticipationRepository, ProgrammingSubmissionRepository programmingSubmissionRepository,\n ResultRepository resultRepository, InstanceMessageSendService instanceMessageSendService) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.groupNotificationService = groupNotificationService;\n this.programmingExerciseService = programmingExerciseService;\n this.templateProgrammingExerciseParticipationRepository = templateProgrammingExerciseParticipationRepository;\n this.solutionProgrammingExerciseParticipationRepository = solutionProgrammingExerciseParticipationRepository;\n this.programmingSubmissionRepository = programmingSubmissionRepository;\n this.resultRepository = resultRepository;\n this.instanceMessageSendService = instanceMessageSendService;\n }\n\n /**\n * Setups the context of a new programming exercise.\n * @param programmingExercise the exercise which should be stored in the database\n * @return returns the modified and stored programming exercise\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n @Transactional // ok because we create many objects in a rather complex way and need a rollback in case of exceptions\n public ProgrammingExercise createProgrammingExerciseWithoutVersionControlAndContinuousIntegrationAvailable(ProgrammingExercise programmingExercise) {\n programmingExercise.generateAndSetProjectKey();\n\n programmingExerciseService.initParticipations(programmingExercise);\n setURLsAndBuildPlanIDsForNewExerciseWithoutVersionControlAndContinuousIntegrationAvailable(programmingExercise);\n\n programmingExerciseService.connectBaseParticipationsToExerciseAndSave(programmingExercise);\n programmingExercise = programmingExerciseRepository.save(programmingExercise);\n\n // The creation of the webhooks must occur after the initial push, because the participation is\n // not yet saved in the database, so we cannot save the submission accordingly (see ProgrammingSubmissionService.notifyPush)\n instanceMessageSendService.sendProgrammingExerciseSchedule(programmingExercise.getId());\n groupNotificationService.notifyTutorGroupAboutExerciseCreated(programmingExercise);\n\n return programmingExercise;\n }\n\n /**\n * Sets the url and buildplan ids for the new exercise\n * @param programmingExercise the new exercise\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n private void setURLsAndBuildPlanIDsForNewExerciseWithoutVersionControlAndContinuousIntegrationAvailable(ProgrammingExercise programmingExercise) {\n final var exerciseRepoName = programmingExercise.generateRepositoryName(RepositoryType.TEMPLATE);\n final var solutionRepoName = programmingExercise.generateRepositoryName(RepositoryType.SOLUTION);\n final var testRepoName = programmingExercise.generateRepositoryName(RepositoryType.TESTS);\n\n final var projectKey = programmingExercise.getProjectKey();\n final var templateParticipation = programmingExercise.getTemplateParticipation();\n final var solutionParticipation = programmingExercise.getSolutionParticipation();\n final var exerciseRepoUrl = \"http://\" + domain + projectKey + \"/\" + exerciseRepoName + \".git\";\n final var testsRepoUrl = \"http://\" + domain + projectKey + \"/\" + testRepoName + \".git\";\n final var solutionRepoUrl = \"http://\" + domain + projectKey + \"/\" + solutionRepoName + \".git\";\n templateParticipation.setBuildPlanId(programmingExercise.generateBuildPlanId(TEMPLATE));\n templateParticipation.setRepositoryUrl(exerciseRepoUrl);\n solutionParticipation.setBuildPlanId(programmingExercise.generateBuildPlanId(SOLUTION));\n solutionParticipation.setRepositoryUrl(solutionRepoUrl);\n programmingExercise.setTestRepositoryUrl(testsRepoUrl);\n }\n\n /**\n * This method creates the template and solution submissions and results for the new exercise\n * These submissions and results are SIMULATIONS for the testing of programming exercises without a connection to\n * the VCS and Continuous Integration server\n * @param programmingExercise the new exercise\n * This functionality is only for testing purposes (noVersionControlAndContinuousIntegrationAvailable)\n */\n public void setupInitialSubmissionsAndResults(ProgrammingExercise programmingExercise) {\n Optional<TemplateProgrammingExerciseParticipation> templateProgrammingExerciseParticipation = this.templateProgrammingExerciseParticipationRepository\n .findByProgrammingExerciseId(programmingExercise.getId());\n Optional<SolutionProgrammingExerciseParticipation> solutionProgrammingExerciseParticipation = this.solutionProgrammingExerciseParticipationRepository\n .findByProgrammingExerciseId(programmingExercise.getId());\n String commitHashBase = VCSSimulationUtils.simulateCommitHash();\n ProgrammingSubmission templateProgrammingSubmission = new ProgrammingSubmission();\n templateProgrammingSubmission.setParticipation(templateProgrammingExerciseParticipation.get());\n templateProgrammingSubmission.setSubmitted(true);\n templateProgrammingSubmission.setType(SubmissionType.MANUAL);\n templateProgrammingSubmission.setCommitHash(commitHashBase);\n templateProgrammingSubmission.setSubmissionDate(templateProgrammingExerciseParticipation.get().getInitializationDate());\n programmingSubmissionRepository.save(templateProgrammingSubmission);\n Result templateResult = new Result();\n templateResult.setParticipation(templateProgrammingExerciseParticipation.get());\n templateResult.setSubmission(templateProgrammingSubmission);\n templateResult.setRated(true);\n templateResult.resultString(\"0 of 13 passed\");\n templateResult.setAssessmentType(AssessmentType.AUTOMATIC);\n templateResult.setScore(0D);\n templateResult.setCompletionDate(templateProgrammingExerciseParticipation.get().getInitializationDate());\n resultRepository.save(templateResult);\n\n ProgrammingSubmission solutionProgrammingSubmission = new ProgrammingSubmission();\n String commitHashSolution = VCSSimulationUtils.simulateCommitHash();\n solutionProgrammingSubmission.setParticipation(solutionProgrammingExerciseParticipation.get());\n solutionProgrammingSubmission.setSubmitted(true);\n solutionProgrammingSubmission.setType(SubmissionType.MANUAL);\n solutionProgrammingSubmission.setCommitHash(commitHashSolution);\n solutionProgrammingSubmission.setSubmissionDate(solutionProgrammingExerciseParticipation.get().getInitializationDate());\n programmingSubmissionRepository.save(solutionProgrammingSubmission);\n Result solutionResult = new Result();\n solutionResult.setParticipation(solutionProgrammingExerciseParticipation.get());\n solutionResult.setSubmission(solutionProgrammingSubmission);\n solutionResult.setRated(true);\n solutionResult.resultString(\"13 of 13 passed\");\n solutionResult.setScore(100D);\n solutionResult.setAssessmentType(AssessmentType.AUTOMATIC);\n solutionResult.setCompletionDate(solutionProgrammingExerciseParticipation.get().getInitializationDate());\n resultRepository.save(solutionResult);\n }\n\n}\n" }, { "alpha_fraction": 0.621059238910675, "alphanum_fraction": 0.627364456653595, "avg_line_length": 47.06060791015625, "blob_id": "9647f5d40bd981c2abcfdf900e113c87cf2e7da5", "content_id": "c2dcfd0a6d54b5d8e20b33eeb3bb90cb1a223cc2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1586, "license_type": "permissive", "max_line_length": 159, "num_lines": 33, "path": "/src/main/webapp/app/core/interceptor/artemis-version.interceptor.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';\nimport { Observable, Subject } from 'rxjs';\nimport { tap, throttleTime } from 'rxjs/operators';\nimport { ARTEMIS_VERSION_HEADER, VERSION } from 'app/app.constants';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\n\n@Injectable()\nexport class ArtemisVersionInterceptor implements HttpInterceptor {\n private showAlert = new Subject();\n\n constructor(alertService: JhiAlertService, private serverDateService: ArtemisServerDateService) {\n this.showAlert.pipe(throttleTime(10000)).subscribe(() => alertService.addAlert({ type: 'info', msg: 'artemisApp.outdatedAlert', timeout: 30000 }, []));\n }\n\n intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n return next.handle(req).pipe(\n tap((response) => {\n if (response instanceof HttpResponse) {\n const serverVersion = response.headers.get(ARTEMIS_VERSION_HEADER);\n if (VERSION && serverVersion && VERSION !== serverVersion) {\n this.showAlert.next();\n }\n // only invoke the time call if the call was not already the time call to prevent recursion here\n if (!req.url.includes('time')) {\n this.serverDateService.updateTime();\n }\n }\n }),\n );\n }\n}\n" }, { "alpha_fraction": 0.7917981147766113, "alphanum_fraction": 0.7917981147766113, "avg_line_length": 47.769229888916016, "blob_id": "47bdc6e8c2b696b33493707e7e3f2eba743cdbda", "content_id": "39ad0f3f400ddacccf41766edd6035ccf75edc62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 634, "license_type": "permissive", "max_line_length": 101, "num_lines": 13, "path": "/src/main/webapp/app/shared/shared-common.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\n\nimport { FindLanguageFromKeyPipe } from 'app/shared/language/find-language-from-key.pipe';\nimport { ArtemisSharedLibsModule } from 'app/shared/shared-libs.module';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\n\n@NgModule({\n imports: [ArtemisSharedLibsModule],\n declarations: [FindLanguageFromKeyPipe, AlertComponent, AlertErrorComponent],\n exports: [ArtemisSharedLibsModule, FindLanguageFromKeyPipe, AlertComponent, AlertErrorComponent],\n})\nexport class ArtemisSharedCommonModule {}\n" }, { "alpha_fraction": 0.549332320690155, "alphanum_fraction": 0.5560473203659058, "avg_line_length": 33.9466667175293, "blob_id": "2e7a5fe0c9a2afe8f8b8dc858cf60cba47fea7f5", "content_id": "34a7c015571db86f37ec26c3101e37ba81220d6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13105, "license_type": "permissive", "max_line_length": 141, "num_lines": 375, "path": "/src/main/webapp/app/core/websocket/websocket.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable, OnDestroy } from '@angular/core';\nimport { Router } from '@angular/router';\nimport { Observable, Observer, Subscription } from 'rxjs/Rx';\n\nimport { AuthServerProvider } from 'app/core/auth/auth-jwt.service';\n\nimport { Client, ConnectionHeaders, over, Subscription as StompSubscription } from 'webstomp-client';\nimport * as SockJS from 'sockjs-client';\n\nexport interface IWebsocketService {\n /**\n * Callback function managing the amount of failed connection attempts and the timeout until the next reconnect attempt.\n */\n stompFailureCallback(): void;\n\n /**\n * Setup the websocket connection.\n */\n connect(): void;\n\n /**\n * Close the connection to the websocket and unsubscribe als listeners.\n */\n disconnect(): void;\n\n /**\n * Add a new listener.\n * @param channel The channel the listener listens on\n */\n receive(channel: string): Observable<any>;\n\n /**\n * Subscribe to a channel.\n * @param channel\n */\n subscribe(channel: string): void;\n\n /**\n * Unsubscribe a channel.\n * @param channel\n */\n unsubscribe(channel: string): void;\n\n /**\n * Bind the given callback function to the given event\n *\n * @param event {string} the event to be notified of\n * @param callback {function} the function to call when the event is triggered\n */\n bind(event: string, callback: () => void): void;\n\n /**\n * Unbind the given callback function from the given event\n *\n * @param event {string} the event to no longer be notified of\n * @param callback {function} the function to no longer call when the event is triggered\n */\n unbind(event: string, callback: () => void): void;\n\n /**\n * Enable automatic reconnect\n */\n enableReconnect(): void;\n\n /**\n * Disable automatic reconnect\n */\n disableReconnect(): void;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class JhiWebsocketService implements IWebsocketService, OnDestroy {\n stompClient: Client | null;\n connection: Promise<void>;\n connectedPromise: Function;\n subscribers = new Map<string, StompSubscription>();\n myListeners = new Map<string, Observable<any>>();\n listenerObservers = new Map<string, Observer<any>>();\n alreadyConnectedOnce = false;\n private subscription: Subscription | null;\n shouldReconnect = false;\n connectListeners: { (): void }[] = [];\n disconnectListeners: { (): void }[] = [];\n consecutiveFailedAttempts = 0;\n connecting = false;\n\n private socket: any = undefined;\n private subscriptionCounter = 0;\n\n constructor(private router: Router, private authServerProvider: AuthServerProvider) {\n this.connection = this.createConnection();\n }\n\n /**\n * Callback function managing the amount of failed connection attempts to the websocket and the timeout until the next reconnect attempt.\n *\n * Wait 5 seconds before reconnecting in case the connection does not work or the client is disconnected,\n * after 2 failed attempts in row, increase the timeout to 10 seconds,\n * after 4 failed attempts in row, increase the timeout to 20 seconds\n * after 8 failed attempts in row, increase the timeout to 60 seconds\n * after 12 failed attempts in row, increase the timeout to 120 seconds\n * after 16 failed attempts in row, increase the timeout to 300 seconds\n * after 20 failed attempts in row, increase the timeout to 600 seconds\n */\n stompFailureCallback() {\n this.connecting = false;\n this.consecutiveFailedAttempts++;\n this.disconnectListeners.forEach((listener) => {\n listener();\n });\n if (this.shouldReconnect) {\n let waitUntilReconnectAttempt;\n if (this.consecutiveFailedAttempts > 20) {\n // NOTE: normally a user would reload here anyway\n waitUntilReconnectAttempt = 600;\n } else if (this.consecutiveFailedAttempts > 16) {\n // NOTE: normally a user would reload here anyway\n waitUntilReconnectAttempt = 300;\n } else if (this.consecutiveFailedAttempts > 12) {\n waitUntilReconnectAttempt = 120;\n } else if (this.consecutiveFailedAttempts > 8) {\n waitUntilReconnectAttempt = 60;\n } else if (this.consecutiveFailedAttempts > 4) {\n waitUntilReconnectAttempt = 20;\n } else if (this.consecutiveFailedAttempts > 2) {\n waitUntilReconnectAttempt = 10;\n } else {\n waitUntilReconnectAttempt = 5;\n }\n setTimeout(this.connect.bind(this), waitUntilReconnectAttempt * 1000);\n }\n }\n\n /**\n * Setup the websocket connection.\n */\n connect() {\n if ((this.stompClient && this.stompClient.connected) || this.connecting) {\n return; // don't connect, if already connected or connecting\n }\n this.connecting = true;\n if (!this.connectedPromise) {\n this.connection = this.createConnection();\n }\n let url = `//${window.location.host}/websocket/tracker`;\n const authToken = this.authServerProvider.getToken();\n if (authToken) {\n url += '?access_token=' + authToken;\n }\n // NOTE: only support real websockets transports and disable http poll, http stream and other exotic workarounds.\n // nowadays all modern browsers support websockets and workarounds are not necessary any more and might only lead to problems\n this.socket = new SockJS(url, undefined, { transports: 'websocket' });\n const options = {\n heartbeat: { outgoing: 10000, incoming: 10000 },\n debug: false,\n protocols: ['v12.stomp'],\n };\n this.stompClient = over(this.socket, options);\n // Note: at the moment, debugging is deactivated to prevent console log statements\n this.stompClient.debug = function () {};\n const headers = <ConnectionHeaders>{};\n\n this.stompClient.connect(\n headers,\n () => {\n this.connectedPromise('success');\n this.connecting = false;\n this.connectListeners.forEach((listener) => {\n listener();\n });\n this.consecutiveFailedAttempts = 0;\n if (this.alreadyConnectedOnce) {\n // (re)connect to all existing channels\n if (this.myListeners.size !== 0) {\n this.myListeners.forEach((listener, channel) => {\n this.subscribers.set(\n channel,\n this.stompClient!.subscribe(\n channel,\n (data) => {\n if (this.listenerObservers.has(channel)) {\n this.listenerObservers.get(channel)!.next(JSON.parse(data.body));\n }\n },\n {\n id: this.getSessionId() + '-' + this.subscriptionCounter++,\n },\n ),\n );\n });\n }\n } else {\n this.alreadyConnectedOnce = true;\n }\n },\n this.stompFailureCallback.bind(this),\n );\n }\n\n /**\n * Close the connection to the websocket and unsubscribe als listeners.\n */\n disconnect() {\n this.connection = this.createConnection();\n Object.keys(this.myListeners).forEach((listener) => this.unsubscribe(listener), this);\n if (this.stompClient) {\n this.stompClient.disconnect();\n this.stompClient = null;\n }\n if (this.subscription) {\n this.subscription.unsubscribe();\n this.subscription = null;\n }\n this.alreadyConnectedOnce = false;\n }\n\n /**\n * Add a new listener.\n * @param channel The channel the listener listens on\n */\n receive(channel: string): Observable<any> {\n if (channel != undefined && (this.myListeners.size === 0 || !this.myListeners.has(channel))) {\n this.myListeners.set(channel, this.createListener(channel));\n }\n return this.myListeners.get(channel)!;\n }\n\n /**\n * Send data through the websocket connection\n * @param path {string} the path for the websocket connection\n * @param data {object} the data to send through the websocket connection\n */\n send(path: string, data: any) {\n if (this.stompClient !== null && this.stompClient.connected) {\n this.stompClient.send(path, JSON.stringify(data), {});\n }\n }\n\n /**\n * Subscribe to a channel.\n * @param channel\n */\n subscribe(channel: string) {\n this.connection.then(() => {\n if (channel != undefined && (this.myListeners.size === 0 || !this.myListeners.has(channel))) {\n this.myListeners.set(channel, this.createListener(channel));\n }\n this.subscribers.set(\n channel,\n this.stompClient!.subscribe(\n channel,\n (data) => {\n if (this.listenerObservers.has(channel)) {\n this.listenerObservers.get(channel)!.next(this.parseJSON(data.body));\n }\n },\n {\n id: this.getSessionId() + '-' + this.subscriptionCounter++,\n },\n ),\n );\n });\n }\n\n /**\n * Unsubscribe a channel.\n * @param channel\n */\n unsubscribe(channel: string) {\n if (this && this.subscribers && this.subscribers.has(channel)) {\n this.subscribers.get(channel)!.unsubscribe();\n this.subscribers.delete(channel);\n this.myListeners.delete(channel);\n this.listenerObservers.delete(channel);\n }\n }\n\n /**\n * Create a new listener.\n * @param channel The channel to listen on.\n */\n private createListener<T>(channel: string): Observable<T> {\n return new Observable((observer: Observer<T>) => {\n this.listenerObservers.set(channel, observer);\n });\n }\n\n /**\n * Create a new connection.\n */\n private createConnection(): Promise<void> {\n return new Promise((resolve: Function) => (this.connectedPromise = resolve));\n }\n\n /**\n * Bind the given callback function to the given event\n *\n * @param event {string} the event to be notified of\n * @param callback {function} the function to call when the event is triggered\n */\n bind(event: string, callback: () => void) {\n if (this.stompClient) {\n if (event === 'connect') {\n this.connectListeners.push(callback);\n if (this.stompClient.connected) {\n callback();\n }\n } else if (event === 'disconnect') {\n this.disconnectListeners.push(callback);\n if (!this.stompClient.connected) {\n callback();\n }\n }\n }\n }\n\n /**\n * Unbind the given callback function from the given event\n *\n * @param event {string} the event to no longer be notified of\n * @param callback {function} the function to no longer call when the event is triggered\n */\n unbind(event: string, callback: () => void) {\n if (event === 'connect') {\n this.connectListeners = this.connectListeners.filter((listener) => {\n return listener !== callback;\n });\n } else if (event === 'disconnect') {\n this.disconnectListeners = this.disconnectListeners.filter((listener) => {\n return listener !== callback;\n });\n }\n }\n\n /**\n * Enable automatic reconnect\n */\n enableReconnect() {\n if (this.stompClient && !this.stompClient.connected) {\n this.connect();\n }\n this.shouldReconnect = true;\n }\n\n /**\n * Disable automatic reconnect\n */\n disableReconnect() {\n this.shouldReconnect = false;\n }\n\n /**\n * On destroy disconnect.\n */\n ngOnDestroy(): void {\n this.disconnect();\n }\n\n private parseJSON(response: any): any {\n try {\n return JSON.parse(response);\n } catch {\n return response;\n }\n }\n\n // https://stackoverflow.com/a/35651029/3802758\n private getSessionId(): string {\n if (this.socket && this.socket._transport && this.socket._transport.url) {\n return this.socket._transport.url.match('.*\\\\/websocket\\\\/tracker\\\\/\\\\d*\\\\/(.*)\\\\/websocket.*')[1];\n } else {\n return 'unsubscribed';\n }\n }\n}\n" }, { "alpha_fraction": 0.6758434772491455, "alphanum_fraction": 0.6766531467437744, "avg_line_length": 44.182926177978516, "blob_id": "94ff473c396639906478b8989506df377018c45f", "content_id": "f4408220c65445e30e2e84f835eeea22ec57a756", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3705, "license_type": "permissive", "max_line_length": 133, "num_lines": 82, "path": "/src/main/java/de/tum/in/www1/artemis/service/ZipFileService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.List;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipOutputStream;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\n@Service\npublic class ZipFileService {\n\n private final Logger log = LoggerFactory.getLogger(ZipFileService.class);\n\n /**\n * Create a zip file of the given paths and save it in the zipFilePath\n *\n * @param zipFilePath path where the zip file should be saved\n * @param paths multiple paths that should be zipped\n * @param createDirsInZipFile if set to true, the zip file will contain all directories included in the paths.\n * @throws IOException if an error occurred while zipping\n */\n public void createZipFile(Path zipFilePath, List<Path> paths, boolean createDirsInZipFile) throws IOException {\n try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {\n paths.stream().filter(path -> !Files.isDirectory(path) && Files.exists(path)).forEach(path -> {\n var zipPath = createDirsInZipFile ? path : path.getFileName();\n ZipEntry zipEntry = new ZipEntry(zipPath.toString());\n copyToZipFile(zipOutputStream, path, zipEntry);\n });\n }\n }\n\n /**\n * Create a zip file of the given paths and save it in the zipFilePath\n *\n * @param zipFilePath path where the zip file should be saved\n * @param paths multiple paths that should be zipped\n * @param pathsRoot the root path relative to <code>paths</code>\n * @throws IOException if an error occurred while zipping\n */\n public void createZipFile(Path zipFilePath, List<Path> paths, Path pathsRoot) throws IOException {\n try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {\n paths.stream().filter(path -> !Files.isDirectory(path) && Files.exists(path)).forEach(path -> {\n ZipEntry zipEntry = new ZipEntry(pathsRoot.relativize(path).toString());\n copyToZipFile(zipOutputStream, path, zipEntry);\n });\n }\n }\n\n /**\n * Recursively include all files in contentRootPath and create a zip file 'zipFileName' in the folder 'zipFileFolderName'\n *\n * @param zipFilePath path where the zip file should be saved\n * @param contentRootPath a path to a folder: all content in this folder (and in any subfolders) will be included in the zip file\n * @return the path of the newly created zip file for further processing\n * @throws IOException if an error occurred while zipping\n */\n public Path createZipFileWithFolderContent(Path zipFilePath, Path contentRootPath) throws IOException {\n try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipFilePath))) {\n Files.walk(contentRootPath).filter(path -> !Files.isDirectory(path) && Files.exists(path)).forEach(path -> {\n ZipEntry zipEntry = new ZipEntry(contentRootPath.relativize(path).toString());\n copyToZipFile(zipOutputStream, path, zipEntry);\n });\n }\n return zipFilePath;\n }\n\n private void copyToZipFile(ZipOutputStream zipOutputStream, Path path, ZipEntry zipEntry) {\n try {\n zipOutputStream.putNextEntry(zipEntry);\n Files.copy(path, zipOutputStream);\n zipOutputStream.closeEntry();\n }\n catch (IOException e) {\n log.error(\"Create zip file error\", e);\n }\n }\n}\n" }, { "alpha_fraction": 0.7086677551269531, "alphanum_fraction": 0.7239165306091309, "avg_line_length": 51.64788818359375, "blob_id": "780e96967923c9a077c8dbd248227e0807eef738", "content_id": "2e4d57fe1d06fe5711715d9dbd051143dfefebea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3738, "license_type": "permissive", "max_line_length": 139, "num_lines": 71, "path": "/src/test/javascript/spec/component/instructor-dashboard/instructor-exercise-dashboard.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockComponent } from 'ng-mocks';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { RouterModule } from '@angular/router';\nimport { SidePanelComponent } from 'app/shared/side-panel/side-panel.component';\nimport { TutorLeaderboardComponent } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.component';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { ChartsModule } from 'ng2-charts';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { HeaderExercisePageWithDetailsComponent } from 'app/exercises/shared/exercise-headers/header-exercise-page-with-details.component';\nimport { InstructorExerciseDashboardComponent } from 'app/exercises/shared/dashboards/instructor/instructor-exercise-dashboard.component';\nimport { HeaderParticipationPageComponent } from 'app/exercises/shared/exercise-headers/header-participation-page.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('InstructorExerciseDashboardComponent', () => {\n let comp: InstructorExerciseDashboardComponent;\n let fixture: ComponentFixture<InstructorExerciseDashboardComponent>;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, RouterModule, ChartsModule, TranslateModule.forRoot()],\n declarations: [\n InstructorExerciseDashboardComponent,\n MockComponent(HeaderExercisePageWithDetailsComponent),\n MockComponent(HeaderParticipationPageComponent),\n MockComponent(SidePanelComponent),\n MockComponent(TutorLeaderboardComponent),\n ],\n providers: [],\n });\n fixture = TestBed.createComponent(InstructorExerciseDashboardComponent);\n comp = fixture.componentInstance;\n });\n\n it('Statistics are calculated correctly', () => {\n const stats = new StatsForDashboard();\n stats.numberOfSubmissions.inTime = 420;\n stats.numberOfSubmissions.late = 110;\n stats.totalNumberOfAssessments.inTime = 333;\n stats.totalNumberOfAssessments.late = 55;\n stats.numberOfAutomaticAssistedAssessments.inTime = 42;\n stats.numberOfAutomaticAssistedAssessments.late = 15;\n comp.stats = stats;\n comp.setStatistics();\n expect(comp.totalManualAssessmentPercentage.inTime).equal(69);\n expect(comp.totalManualAssessmentPercentage.late).equal(36);\n expect(comp.totalAutomaticAssessmentPercentage.inTime).equal(10);\n expect(comp.totalAutomaticAssessmentPercentage.late).equal(13);\n expect(comp.dataForAssessmentPieChart[0]).equal(142);\n expect(comp.dataForAssessmentPieChart[1]).equal(331);\n expect(comp.dataForAssessmentPieChart[2]).equal(57);\n });\n\n it('Statistics are calculated, and rounded towards zero correctly', () => {\n const stats = new StatsForDashboard();\n stats.numberOfSubmissions.inTime = 2162;\n stats.totalNumberOfAssessments.inTime = 2152;\n stats.numberOfAutomaticAssistedAssessments.inTime = 4;\n comp.stats = stats;\n comp.setStatistics();\n expect(comp.totalManualAssessmentPercentage.inTime).equal(99);\n expect(comp.totalAutomaticAssessmentPercentage.inTime).equal(0);\n expect(comp.dataForAssessmentPieChart[0]).equal(10);\n expect(comp.dataForAssessmentPieChart[1]).equal(2148);\n expect(comp.dataForAssessmentPieChart[2]).equal(4);\n });\n});\n" }, { "alpha_fraction": 0.6720085740089417, "alphanum_fraction": 0.6720085740089417, "avg_line_length": 40.05263137817383, "blob_id": "42f1458a39dfd3dbdc4e8fccd59ae71112369736", "content_id": "14c197928a463984fdecfb9399e4ae10c57f2c29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4680, "license_type": "permissive", "max_line_length": 165, "num_lines": 114, "path": "/src/main/webapp/app/overview/student-questions/student-question/student-question.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport * as moment from 'moment';\nimport { map } from 'rxjs/operators';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { StudentQuestion } from 'app/entities/student-question.model';\n\ntype EntityResponseType = HttpResponse<StudentQuestion>;\ntype EntityArrayResponseType = HttpResponse<StudentQuestion[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class StudentQuestionService {\n public resourceUrl = SERVER_API_URL + 'api/courses/';\n\n constructor(protected http: HttpClient) {}\n\n /**\n * create a studentQuestion\n * @param {number} courseId\n * @param {StudentQuestion} studentQuestion\n * @return {Observable<EntityResponseType>}\n */\n create(courseId: number, studentQuestion: StudentQuestion): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(studentQuestion);\n return this.http\n .post<StudentQuestion>(`${this.resourceUrl}${courseId}/student-questions`, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * update the studentQuestion\n * @param {number} courseId\n * @param {StudentQuestion} studentQuestion\n * @return {Observable<EntityResponseType>}\n */\n update(courseId: number, studentQuestion: StudentQuestion): Observable<EntityResponseType> {\n const copy = this.convertDateFromClient(studentQuestion);\n return this.http\n .put<StudentQuestion>(`${this.resourceUrl}${courseId}/student-questions`, copy, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * update the votes of a studentQuestion\n * @param {number} courseId\n * @param {number} questionId\n * @param {number} voteChange\n * @return {Observable<EntityResponseType>}\n */\n updateVotes(courseId: number, questionId: number, voteChange: number): Observable<EntityResponseType> {\n return this.http\n .put(`${this.resourceUrl}${courseId}/student-questions/${questionId}/votes`, voteChange, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res)));\n }\n\n /**\n * find all questions for id of course\n * @param {number} courseId\n * @return {Observable<EntityArrayResponseType>}\n */\n findQuestionsForCourse(courseId: number): Observable<EntityArrayResponseType> {\n return this.http\n .get<StudentQuestion[]>(`api/courses/${courseId}/student-questions`, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)));\n }\n\n /**\n * delete studentQuestion by id\n * @param {number} courseId\n * @param {number} studentQuestionId\n * @return {Observable<HttpResponse<any>>}\n */\n delete(courseId: number, studentQuestionId: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}${courseId}/student-questions/${studentQuestionId}`, { observe: 'response' });\n }\n\n /**\n * Takes a studentQuestion and converts the date from the client\n * @param {StudentQuestion} studentQuestion\n * @return {StudentQuestion}\n */\n protected convertDateFromClient(studentQuestion: StudentQuestion): StudentQuestion {\n return Object.assign({}, studentQuestion, {\n creationDate: studentQuestion.creationDate && moment(studentQuestion.creationDate).isValid() ? moment(studentQuestion.creationDate).toJSON() : undefined,\n });\n }\n\n /**\n * Takes a studentQuestion and converts the date from the server\n * @param {EntityResponseType} res\n * @return {StudentQuestion}\n */\n protected convertDateFromServer(res: EntityResponseType): EntityResponseType {\n if (res.body) {\n res.body.creationDate = res.body.creationDate ? moment(res.body.creationDate) : undefined;\n }\n return res;\n }\n\n /**\n * Takes an array of studentQuestions and converts the date from the server\n * @param {EntityArrayResponseType} res\n * @return {EntityArrayResponseType}\n */\n protected convertDateArrayFromServer(res: EntityArrayResponseType): EntityArrayResponseType {\n if (res.body) {\n res.body.forEach((studentQuestion: StudentQuestion) => {\n studentQuestion.creationDate = studentQuestion.creationDate ? moment(studentQuestion.creationDate) : undefined;\n });\n }\n return res;\n }\n}\n" }, { "alpha_fraction": 0.6141952276229858, "alphanum_fraction": 0.6158058643341064, "avg_line_length": 43.347618103027344, "blob_id": "cab429fb132bf982f6c81aad9bc4ae4c62aac075", "content_id": "d72e1126763f189e4b72e9129f96ec7b558425d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9313, "license_type": "permissive", "max_line_length": 115, "num_lines": 210, "path": "/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { of } from 'rxjs';\nimport { ActivatedRoute, UrlSegment } from '@angular/router';\n\nimport { ArtemisTestModule } from '../../test.module';\nimport { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { Exam } from 'app/entities/exam.model';\nimport * as moment from 'moment';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockProvider } from 'ng-mocks';\n\ndescribe('ModelingExercise Management Update Component', () => {\n let comp: ModelingExerciseUpdateComponent;\n let fixture: ComponentFixture<ModelingExerciseUpdateComponent>;\n let service: ModelingExerciseService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [ModelingExerciseUpdateComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: ActivatedRoute, useValue: new MockActivatedRoute() },\n MockProvider(TranslateService),\n ],\n })\n .overrideTemplate(ModelingExerciseUpdateComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(ModelingExerciseUpdateComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(ModelingExerciseService);\n });\n\n describe('save', () => {\n it('Should call update service on save for existing entity', fakeAsync(() => {\n // GIVEN\n const entity = new ModelingExercise(UMLDiagramType.ActivityDiagram, undefined, undefined);\n entity.id = 123;\n spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.modelingExercise = entity;\n comp.modelingExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.update).toHaveBeenCalledWith(entity, {});\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should call create service on save for new entity', fakeAsync(() => {\n // GIVEN\n const entity = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.modelingExercise = entity;\n comp.modelingExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should trim the exercise title before saving', fakeAsync(() => {\n // GIVEN\n const entity = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, undefined);\n entity.title = 'My Exercise ';\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.modelingExercise = entity;\n comp.modelingExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(entity.title).toEqual('My Exercise');\n }));\n });\n\n describe('ngOnInit in import mode: Course to Course', () => {\n const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, new Course(), undefined);\n modelingExercise.id = 1;\n modelingExercise.releaseDate = moment();\n modelingExercise.dueDate = moment();\n modelingExercise.assessmentDueDate = moment();\n const courseId = 1;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId });\n route.url = of([{ path: 'import' } as UrlSegment]);\n route.data = of({ modelingExercise });\n });\n\n it('Should set isImport and remove all dates', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isImport).toEqual(true);\n expect(comp.isExamMode).toEqual(false);\n expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);\n expect(comp.modelingExercise.releaseDate).toEqual(undefined);\n expect(comp.modelingExercise.dueDate).toEqual(undefined);\n }));\n });\n\n describe('ngOnInit in import mode: Exam to Course', () => {\n const exerciseGroup = new ExerciseGroup();\n exerciseGroup.exam = new Exam();\n exerciseGroup.exam.course = new Course();\n exerciseGroup.exam.course.id = 1;\n const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, exerciseGroup);\n modelingExercise.id = 1;\n modelingExercise.releaseDate = moment();\n modelingExercise.dueDate = moment();\n modelingExercise.assessmentDueDate = moment();\n const courseId = 1;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId });\n route.url = of([{ path: 'import' } as UrlSegment]);\n route.data = of({ modelingExercise });\n });\n\n it('Should set isImport and remove all dates', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isImport).toEqual(true);\n expect(comp.isExamMode).toEqual(false);\n expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);\n expect(comp.modelingExercise.releaseDate).toEqual(undefined);\n expect(comp.modelingExercise.dueDate).toEqual(undefined);\n }));\n });\n\n describe('ngOnInit in import mode: Course to Exam', () => {\n const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, new Course(), undefined);\n modelingExercise.id = 1;\n modelingExercise.releaseDate = moment();\n modelingExercise.dueDate = moment();\n modelingExercise.assessmentDueDate = moment();\n const groupId = 1;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ groupId });\n route.url = of([{ path: 'exercise-groups' } as UrlSegment, { path: 'import' } as UrlSegment]);\n route.data = of({ modelingExercise });\n });\n\n it('Should set isImport and isExamMode and remove all dates', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isImport).toEqual(true);\n expect(comp.isExamMode).toEqual(true);\n expect(comp.modelingExercise.course).toEqual(undefined);\n expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);\n expect(comp.modelingExercise.releaseDate).toEqual(undefined);\n expect(comp.modelingExercise.dueDate).toEqual(undefined);\n }));\n });\n\n describe('ngOnInit in import mode: Exam to Exam', () => {\n const exerciseGroup = new ExerciseGroup();\n const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, undefined, exerciseGroup);\n modelingExercise.id = 1;\n modelingExercise.releaseDate = moment();\n modelingExercise.dueDate = moment();\n modelingExercise.assessmentDueDate = moment();\n const groupId = 1;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ groupId });\n route.url = of([{ path: 'exercise-groups' } as UrlSegment, { path: 'import' } as UrlSegment]);\n route.data = of({ modelingExercise });\n });\n\n it('Should set isImport and isExamMode and remove all dates', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isImport).toEqual(true);\n expect(comp.isExamMode).toEqual(true);\n expect(comp.modelingExercise.assessmentDueDate).toEqual(undefined);\n expect(comp.modelingExercise.releaseDate).toEqual(undefined);\n expect(comp.modelingExercise.dueDate).toEqual(undefined);\n }));\n });\n});\n" }, { "alpha_fraction": 0.6173120737075806, "alphanum_fraction": 0.6199696063995361, "avg_line_length": 38.90909194946289, "blob_id": "c2caa269917f3dd7a30ac41b5a6b1fe7d66e62ed", "content_id": "0870fb41bf3b4730528add6a2a44045c92a285bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2634, "license_type": "permissive", "max_line_length": 119, "num_lines": 66, "path": "/src/test/javascript/spec/component/exercise-hint/exercise-hint-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { FormBuilder } from '@angular/forms';\nimport { of } from 'rxjs';\n\nimport { ExerciseHintUpdateComponent } from 'app/exercises/shared/exercise-hint/manage/exercise-hint-update.component';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { ArtemisTestModule } from '../../test.module';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockProvider } from 'ng-mocks';\n\ndescribe('ExerciseHint Management Update Component', () => {\n let comp: ExerciseHintUpdateComponent;\n let fixture: ComponentFixture<ExerciseHintUpdateComponent>;\n let service: ExerciseHintService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [ExerciseHintUpdateComponent],\n providers: [FormBuilder, MockProvider(TranslateService)],\n })\n .overrideTemplate(ExerciseHintUpdateComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(ExerciseHintUpdateComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(ExerciseHintService);\n });\n\n describe('save', () => {\n it('Should call update service on save for existing entity', fakeAsync(() => {\n // GIVEN\n const entity = new ExerciseHint();\n entity.id = 123;\n spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.exerciseHint = entity;\n comp.courseId = 1;\n comp.exerciseId = 2;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.update).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should call create service on save for new entity', fakeAsync(() => {\n // GIVEN\n const entity = new ExerciseHint();\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.exerciseHint = entity;\n comp.courseId = 1;\n comp.exerciseId = 2;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n });\n});\n" }, { "alpha_fraction": 0.6653992533683777, "alphanum_fraction": 0.6658745408058167, "avg_line_length": 34.66101837158203, "blob_id": "301ec11350de1f0da84142901d82b5196d1a51e6", "content_id": "d4f42da7ef3a3d6d8695228f767df5c37ef18609", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2104, "license_type": "permissive", "max_line_length": 137, "num_lines": 59, "path": "/src/main/webapp/app/exercises/programming/shared/utils/build-plan-button.directive.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Directive, HostBinding, HostListener, Input, OnInit } from '@angular/core';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { take, tap } from 'rxjs/operators';\nimport { createBuildPlanUrl } from 'app/exercises/programming/shared/utils/build-plan-link.directive';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\n\n@Directive({ selector: 'button[jhiBuildPlanButton], jhi-button[jhiBuildPlanButton]' })\nexport class BuildPlanButtonDirective implements OnInit {\n @HostBinding('style.visibility')\n visibility = 'hidden';\n\n private participationBuildPlanId: string;\n private exerciseProjectKey: string;\n private buildPlanLink?: string;\n private templateLink: string;\n\n constructor(private profileService: ProfileService) {}\n\n /**\n * Life cycle hook called by Angular to indicate that Angular is done creating the component\n */\n ngOnInit(): void {\n this.profileService\n .getProfileInfo()\n .pipe(\n take(1),\n tap((info: ProfileInfo) => {\n this.templateLink = info.buildPlanURLTemplate;\n this.linkToBuildPlan = createBuildPlanUrl(this.templateLink, this.exerciseProjectKey, this.participationBuildPlanId);\n }),\n )\n .subscribe();\n }\n\n /**\n * Action on click.\n */\n @HostListener('click')\n onClick() {\n window.open(this.buildPlanLink!);\n }\n\n @Input()\n set projectKey(key: string) {\n this.exerciseProjectKey = key;\n this.linkToBuildPlan = createBuildPlanUrl(this.templateLink, this.exerciseProjectKey, this.participationBuildPlanId);\n }\n\n @Input()\n set buildPlanId(planId: string) {\n this.participationBuildPlanId = planId;\n this.linkToBuildPlan = createBuildPlanUrl(this.templateLink, this.exerciseProjectKey, this.participationBuildPlanId);\n }\n\n set linkToBuildPlan(link: string | undefined) {\n this.buildPlanLink = link;\n this.visibility = link ? 'visible' : 'hidden';\n }\n}\n" }, { "alpha_fraction": 0.5741525292396545, "alphanum_fraction": 0.5741525292396545, "avg_line_length": 31.55172348022461, "blob_id": "0ea11ffe561b087b51d8033465b14d26f1654e42", "content_id": "644a8bf6ac90e6cc8e2ac2c8e0e0637ec315204e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 944, "license_type": "permissive", "max_line_length": 72, "num_lines": 29, "path": "/src/test/javascript/jest-global-mocks.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "const mock = () => {\n let storage = {};\n return {\n getItem: (key: any) => (key in storage ? storage[key] : null),\n setItem: (key: any, value: any) => (storage[key] = value || ''),\n removeItem: (key: any) => delete storage[key],\n clear: () => (storage = {}),\n };\n};\n\nObject.defineProperty(window, 'localStorage', { value: mock() });\nObject.defineProperty(window, 'sessionStorage', { value: mock() });\nObject.defineProperty(window, 'getComputedStyle', {\n value: () => ['-webkit-appearance'],\n});\n\nObject.defineProperty(window, 'matchMedia', {\n writable: true,\n value: jest.fn().mockImplementation((query) => ({\n matches: false,\n media: query,\n onchange: null,\n addListener: jest.fn(), // deprecated\n removeListener: jest.fn(), // deprecated\n addEventListener: jest.fn(),\n removeEventListener: jest.fn(),\n dispatchEvent: jest.fn(),\n })),\n});\n" }, { "alpha_fraction": 0.7157408595085144, "alphanum_fraction": 0.7227289080619812, "avg_line_length": 49.708709716796875, "blob_id": "27ef4d4e868cfa7a07d4a3563efc14c282b3328f", "content_id": "f5d1afa6bac578dbf73260ee6ad3067116af22a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 16886, "license_type": "permissive", "max_line_length": 168, "num_lines": 333, "path": "/src/test/java/de/tum/in/www1/artemis/LectureIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.AttachmentType;\nimport de.tum.in.www1.artemis.domain.lecture.*;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class LectureIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private LectureRepository lectureRepository;\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private TextExerciseRepository textExerciseRepository;\n\n @Autowired\n private AttachmentRepository attachmentRepository;\n\n private Attachment attachmentDirectOfLecture;\n\n private Attachment attachmentOfAttachmentUnit;\n\n private TextExercise textExercise;\n\n private Course course1;\n\n private Lecture lecture1;\n\n @BeforeEach\n public void initTestCase() throws Exception {\n this.database.addUsers(10, 10, 10);\n List<Course> courses = this.database.createCoursesWithExercisesAndLectures(true);\n this.course1 = this.courseRepository.findByIdWithExercisesAndLecturesElseThrow(courses.get(0).getId());\n this.lecture1 = this.course1.getLectures().stream().findFirst().get();\n this.textExercise = textExerciseRepository.findByCourseId(course1.getId()).stream().findFirst().get();\n // Add users that are not in the course\n userRepository.save(ModelFactory.generateActivatedUser(\"student42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"tutor42\"));\n userRepository.save(ModelFactory.generateActivatedUser(\"instructor42\"));\n\n // Setting up a lecture with various kinds of content\n ExerciseUnit exerciseUnit = database.createExerciseUnit(textExercise);\n AttachmentUnit attachmentUnit = database.createAttachmentUnit();\n this.attachmentOfAttachmentUnit = attachmentUnit.getAttachment();\n VideoUnit videoUnit = database.createVideoUnit();\n TextUnit textUnit = database.createTextUnit();\n addAttachmentToLecture();\n\n this.lecture1 = database.addLectureUnitsToLecture(this.lecture1, Set.of(exerciseUnit, attachmentUnit, videoUnit, textUnit));\n }\n\n private void addAttachmentToLecture() {\n this.attachmentDirectOfLecture = new Attachment().attachmentType(AttachmentType.FILE).link(\"files/temp/example2.txt\").name(\"example2\");\n this.attachmentDirectOfLecture.setLecture(this.lecture1);\n this.attachmentDirectOfLecture = attachmentRepository.save(this.attachmentDirectOfLecture);\n this.lecture1.addAttachments(this.attachmentDirectOfLecture);\n this.lecture1 = lectureRepository.save(this.lecture1);\n }\n\n private void testAllPreAuthorize() throws Exception {\n request.postWithResponseBody(\"/api/lectures\", new Lecture(), Lecture.class, HttpStatus.FORBIDDEN);\n request.putWithResponseBody(\"/api/lectures\", new Lecture(), Lecture.class, HttpStatus.FORBIDDEN);\n request.getList(\"/api/courses/\" + course1.getId() + \"/lectures\", HttpStatus.FORBIDDEN, Lecture.class);\n request.delete(\"/api/lectures/\" + lecture1.getId(), HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testAll_asTutor() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testAll_asStudent() throws Exception {\n this.testAllPreAuthorize();\n }\n\n @AfterEach\n public void resetDatabase() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createLecture_correctRequestBody_shouldCreateLecture() throws Exception {\n Course course = courseRepository.findByIdElseThrow(this.course1.getId());\n\n Lecture lecture = new Lecture();\n lecture.title(\"loremIpsum\");\n lecture.setCourse(course);\n lecture.setDescription(\"loremIpsum\");\n Lecture returnedLecture = request.postWithResponseBody(\"/api/lectures\", lecture, Lecture.class, HttpStatus.CREATED);\n\n assertThat(returnedLecture).isNotNull();\n assertThat(returnedLecture.getId()).isNotNull();\n assertThat(returnedLecture.getTitle()).isEqualTo(lecture.getTitle());\n assertThat(returnedLecture.getCourse().getId()).isEqualTo(lecture.getCourse().getId());\n assertThat(returnedLecture.getDescription()).isEqualTo(lecture.getDescription());\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createLecture_alreadyId_shouldReturnBadRequest() throws Exception {\n Lecture lecture = new Lecture();\n lecture.setId(1L);\n request.postWithResponseBody(\"/api/lectures\", lecture, Lecture.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateLecture_correctRequestBody_shouldUpdateLecture() throws Exception {\n Lecture originalLecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n originalLecture.setTitle(\"Updated\");\n originalLecture.setDescription(\"Updated\");\n Lecture updatedLecture = request.putWithResponseBody(\"/api/lectures\", originalLecture, Lecture.class, HttpStatus.OK);\n assertThat(updatedLecture.getTitle()).isEqualTo(\"Updated\");\n assertThat(updatedLecture.getDescription()).isEqualTo(\"Updated\");\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateLecture_NoId_shouldReturnBadRequest() throws Exception {\n Lecture originalLecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoals(lecture1.getId()).get();\n originalLecture.setId(null);\n request.putWithResponseBody(\"/api/lectures\", originalLecture, Lecture.class, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getLectureForCourse_withOutLectureUnits_shouldGetLecturesWithOutLectureUnits() throws Exception {\n List<Lecture> returnedLectures = request.getList(\"/api/courses/\" + course1.getId() + \"/lectures\", HttpStatus.OK, Lecture.class);\n assertThat(returnedLectures.size()).isEqualTo(2);\n Lecture lecture = returnedLectures.stream().filter(l -> l.getId().equals(lecture1.getId())).findFirst().get();\n assertThat(lecture.getLectureUnits().size()).isEqualTo(0);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getLectureForCourse_withLectureUnits_shouldGetLecturesWithLectureUnits() throws Exception {\n List<Lecture> returnedLectures = request.getList(\"/api/courses/\" + course1.getId() + \"/lectures?withLectureUnits=true\", HttpStatus.OK, Lecture.class);\n assertThat(returnedLectures.size()).isEqualTo(2);\n Lecture lecture = returnedLectures.stream().filter(l -> l.getId().equals(lecture1.getId())).findFirst().get();\n assertThat(lecture.getLectureUnits().size()).isEqualTo(4);\n }\n\n @Test\n @WithMockUser(username = \"student42\", roles = \"USER\")\n public void getLecture_asStudentNotInCourse_shouldReturnForbidden() throws Exception {\n request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.FORBIDDEN, Lecture.class);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getLecture_ExerciseAndAttachmentReleased_shouldGetLectureWithAllLectureUnits() throws Exception {\n Lecture receivedLecture = request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK, Lecture.class);\n assertThat(receivedLecture.getId()).isEqualTo(lecture1.getId());\n assertThat(receivedLecture.getLectureUnits().size()).isEqualTo(4);\n assertThat(receivedLecture.getAttachments().size()).isEqualTo(2);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getLecture_ExerciseNotReleased_shouldGetLectureWithoutExerciseUnit() throws Exception {\n TextExercise exercise = textExerciseRepository.findByIdElseThrow(textExercise.getId());\n exercise.setReleaseDate(ZonedDateTime.now().plusDays(10));\n textExerciseRepository.saveAndFlush(exercise);\n\n Lecture receivedLecture = request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK, Lecture.class);\n assertThat(receivedLecture.getId()).isEqualTo(lecture1.getId());\n assertThat(receivedLecture.getLectureUnits().size()).isEqualTo(3);\n assertThat(receivedLecture.getLectureUnits().stream().filter(lectureUnit -> lectureUnit instanceof ExerciseUnit).collect(Collectors.toList())).isEmpty();\n\n // now we test that it is included when the user is at least a teaching assistant\n database.changeUser(\"tutor1\");\n receivedLecture = request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK, Lecture.class);\n assertThat(receivedLecture.getId()).isEqualTo(lecture1.getId());\n assertThat(receivedLecture.getLectureUnits().size()).isEqualTo(4);\n assertThat(receivedLecture.getLectureUnits().stream().filter(lectureUnit -> lectureUnit instanceof ExerciseUnit).collect(Collectors.toList())).isNotEmpty();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getLecture_AttachmentNotReleased_shouldGetLectureWithoutAttachmentUnitAndAttachment() throws Exception {\n Attachment unitAttachment = attachmentRepository.findById(attachmentOfAttachmentUnit.getId()).get();\n unitAttachment.setReleaseDate(ZonedDateTime.now().plusDays(10));\n Attachment lectureAttachment = attachmentRepository.findById(attachmentDirectOfLecture.getId()).get();\n lectureAttachment.setReleaseDate(ZonedDateTime.now().plusDays(10));\n attachmentRepository.saveAll(Set.of(unitAttachment, lectureAttachment));\n\n Lecture receivedLecture = request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK, Lecture.class);\n assertThat(receivedLecture.getId()).isEqualTo(lecture1.getId());\n assertThat(receivedLecture.getAttachments().stream().filter(attachment -> attachment.getId().equals(lectureAttachment.getId())).findFirst().isEmpty()).isTrue();\n assertThat(receivedLecture.getLectureUnits().size()).isEqualTo(3);\n assertThat(receivedLecture.getLectureUnits().stream().filter(lectureUnit -> lectureUnit instanceof AttachmentUnit).collect(Collectors.toList())).isEmpty();\n\n // now we test that it is included when the user is at least a teaching assistant\n database.changeUser(\"tutor1\");\n receivedLecture = request.get(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK, Lecture.class);\n assertThat(receivedLecture.getId()).isEqualTo(lecture1.getId());\n assertThat(receivedLecture.getAttachments().stream().anyMatch(attachment -> attachment.getId().equals(lectureAttachment.getId()))).isTrue();\n assertThat(receivedLecture.getLectureUnits().size()).isEqualTo(4);\n assertThat(receivedLecture.getLectureUnits().stream().filter(lectureUnit -> lectureUnit instanceof AttachmentUnit).collect(Collectors.toList())).isNotEmpty();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteLecture_lectureExists_shouldDeleteLecture() throws Exception {\n request.delete(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK);\n Optional<Lecture> lectureOptional = lectureRepository.findById(lecture1.getId());\n assertThat(lectureOptional.isEmpty()).isTrue();\n }\n\n /**\n * Hibernates sometimes adds null to the list of lecture units to keep the order after a lecture unit has been deleted.\n * This should not happen any more as we have refactored the way lecture units are deleted, nevertheless we want to\n * check here that this case not causes any errors as null values could still exist in the database\n */\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteLecture_NullInListOfLectureUnits_shouldDeleteLecture() throws Exception {\n Lecture lecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoalsElseThrow(lecture1.getId());\n List<LectureUnit> lectureUnits = lecture.getLectureUnits();\n assertThat(lectureUnits.size()).isEqualTo(4);\n ArrayList<LectureUnit> lectureUnitsWithNulls = new ArrayList<>();\n for (LectureUnit lectureUnit : lectureUnits) {\n lectureUnitsWithNulls.add(null);\n lectureUnitsWithNulls.add(lectureUnit);\n }\n lecture.getLectureUnits().clear();\n lecture.getLectureUnits().addAll(lectureUnitsWithNulls);\n lectureRepository.saveAndFlush(lecture);\n lecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoalsElseThrow(lecture1.getId());\n lectureUnits = lecture.getLectureUnits();\n assertThat(lectureUnits.size()).isEqualTo(8);\n request.delete(\"/api/lectures/\" + lecture1.getId(), HttpStatus.OK);\n Optional<Lecture> lectureOptional = lectureRepository.findById(lecture1.getId());\n assertThat(lectureOptional.isEmpty()).isTrue();\n }\n\n /**\n * We have to make sure to reorder the list of lecture units when we delete a lecture unit to prevent hibernate\n * from entering nulls into the list to keep the order of lecture units\n */\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteLectureUnit_FirstLectureUnit_ShouldReorderList() throws Exception {\n Lecture lecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoalsElseThrow(lecture1.getId());\n assertThat(lecture.getLectureUnits().size()).isEqualTo(4);\n LectureUnit firstLectureUnit = lecture.getLectureUnits().stream().findFirst().get();\n request.delete(\"/api/lectures/\" + lecture1.getId() + \"/lecture-units/\" + firstLectureUnit.getId(), HttpStatus.OK);\n lecture = lectureRepository.findByIdWithStudentQuestionsAndLectureUnitsAndLearningGoalsElseThrow(lecture1.getId());\n assertThat(lecture.getLectureUnits().size()).isEqualTo(3);\n boolean nullFound = false;\n for (LectureUnit lectureUnit : lecture.getLectureUnits()) {\n if (Objects.isNull(lectureUnit)) {\n nullFound = true;\n break;\n }\n }\n assertThat(nullFound).isFalse();\n\n }\n\n @Test\n @WithMockUser(username = \"instructor42\", roles = \"INSTRUCTOR\")\n public void deleteLecture_asInstructorNotInCourse_shouldReturnForbidden() throws Exception {\n request.delete(\"/api/lectures/\" + lecture1.getId(), HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteLecture_lectureDoesNot_shouldReturnNotFound() throws Exception {\n request.delete(\"/api/lectures/\" + 0, HttpStatus.NOT_FOUND);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetLectureTitleAsInstuctor() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetLectureTitle();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetLectureTitleAsTeachingAssistant() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetLectureTitle();\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetLectureTitleAsUser() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetLectureTitle();\n }\n\n private void testGetLectureTitle() throws Exception {\n Lecture lecture = new Lecture();\n lecture.title(\"Test Lecture\");\n lectureRepository.save(lecture);\n\n final var title = request.get(\"/api/lectures/\" + lecture.getId() + \"/title\", HttpStatus.OK, String.class);\n assertThat(title).isEqualTo(lecture.getTitle());\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetLectureTitleForNonExistingLecture() throws Exception {\n // No lecture with id 1337 was created\n request.get(\"/api/lectures/1337/title\", HttpStatus.NOT_FOUND, String.class);\n }\n}\n" }, { "alpha_fraction": 0.70098876953125, "alphanum_fraction": 0.7020115852355957, "avg_line_length": 33.505882263183594, "blob_id": "b22db37d23ce11a00138edf7c5924fff4d0bff0e", "content_id": "1c524adda9b801b526e41a95b9e8178ddc338879", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2933, "license_type": "permissive", "max_line_length": 138, "num_lines": 85, "path": "/src/main/java/de/tum/in/www1/artemis/domain/notification/SingleUserNotification.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.notification;\n\nimport java.time.ZonedDateTime;\n\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\nimport javax.persistence.ManyToOne;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.google.gson.JsonObject;\n\nimport de.tum.in.www1.artemis.domain.StudentQuestionAnswer;\nimport de.tum.in.www1.artemis.domain.User;\n\n/**\n * A SingleUserNotification.\n */\n@Entity\n@DiscriminatorValue(value = \"U\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class SingleUserNotification extends Notification {\n\n @ManyToOne\n private User recipient;\n\n public User getRecipient() {\n return recipient;\n }\n\n public void setRecipient(User user) {\n this.recipient = user;\n }\n\n public String getTopic() {\n return \"/topic/user/\" + getRecipient().getId() + \"/notifications\";\n }\n\n public SingleUserNotification() {\n }\n\n public SingleUserNotification(User recipient, User author, String title, String text) {\n this.setRecipient(recipient);\n this.setAuthor(author);\n this.setNotificationDate(ZonedDateTime.now());\n this.setTitle(title);\n this.setText(text);\n }\n\n /**\n * Set the target JSON string for an exercise notification\n *\n * @param studentQuestionAnswer a question that was posted for an exercise\n * @return JSON string with all properties for the notification target field\n */\n public String studentQuestionAnswerTargetForExercise(StudentQuestionAnswer studentQuestionAnswer) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", \"newAnswer\");\n target.addProperty(\"id\", studentQuestionAnswer.getQuestion().getExercise().getId());\n target.addProperty(\"entity\", \"exercises\");\n target.addProperty(\"course\", studentQuestionAnswer.getQuestion().getExercise().getCourseViaExerciseGroupOrCourseMember().getId());\n target.addProperty(\"mainPage\", \"courses\");\n return target.toString();\n }\n\n /**\n * Set the target JSON string for a lecture notification\n *\n * @param studentQuestionAnswer a question that was posted for a lecture\n * @return JSON string with all properties for the notification target field\n */\n public String studentQuestionAnswerTargetForLecture(StudentQuestionAnswer studentQuestionAnswer) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", \"newAnswer\");\n target.addProperty(\"id\", studentQuestionAnswer.getQuestion().getLecture().getId());\n target.addProperty(\"entity\", \"lectures\");\n target.addProperty(\"course\", studentQuestionAnswer.getQuestion().getLecture().getCourse().getId());\n target.addProperty(\"mainPage\", \"courses\");\n return target.toString();\n }\n\n @Override\n public String toString() {\n return \"SingleUserNotification{\" + \"id=\" + getId() + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.6170058250427246, "alphanum_fraction": 0.6186409592628479, "avg_line_length": 42, "blob_id": "d1fec981b2d74ba5377d1175dfbccd2dcf339136", "content_id": "5b6d7fb0580f55528eef4121c582b09d3bc635e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5504, "license_type": "permissive", "max_line_length": 123, "num_lines": 128, "path": "/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\n\nimport { ArtemisTestModule } from '../../test.module';\nimport { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component';\nimport { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service';\nimport { FileUploadExercise } from 'app/entities/file-upload-exercise.model';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockFileUploadExerciseService } from '../../helpers/mocks/service/mock-file-upload-exercise.service';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { Course } from 'app/entities/course.model';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockProvider } from 'ng-mocks';\n\ndescribe('FileUploadExercise Management Update Component', () => {\n let comp: FileUploadExerciseUpdateComponent;\n let fixture: ComponentFixture<FileUploadExerciseUpdateComponent>;\n let service: FileUploadExerciseService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [FileUploadExerciseUpdateComponent],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: FileUploadExerciseService, useClass: MockFileUploadExerciseService },\n { provide: ActivatedRoute, useValue: new MockActivatedRoute() },\n MockProvider(TranslateService),\n ],\n })\n .overrideTemplate(FileUploadExerciseUpdateComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(FileUploadExerciseUpdateComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(FileUploadExerciseService);\n });\n\n describe('save', () => {\n it('Should call update service on save for existing entity', fakeAsync(() => {\n // GIVEN\n const entity = new FileUploadExercise(undefined, undefined);\n entity.id = 123;\n spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.fileUploadExercise = entity;\n comp.fileUploadExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.update).toHaveBeenCalledWith(entity, 123);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should call create service on save for new entity', fakeAsync(() => {\n // GIVEN\n const entity = new FileUploadExercise(undefined, undefined);\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.fileUploadExercise = entity;\n comp.fileUploadExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should trim the exercise title before saving', fakeAsync(() => {\n // GIVEN\n const entity = new FileUploadExercise(undefined, undefined);\n entity.title = 'My Exercise ';\n spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.fileUploadExercise = entity;\n comp.fileUploadExercise.course = { id: 1 } as Course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(service.create).toHaveBeenCalledWith(entity);\n expect(entity.title).toEqual('My Exercise');\n }));\n });\n\n describe('ngOnInit with given exerciseGroup', () => {\n const fileUploadExercise = new FileUploadExercise(undefined, new ExerciseGroup());\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.data = of({ fileUploadExercise });\n });\n\n it('Should be in exam mode', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isExamMode).toEqual(true);\n expect(comp.fileUploadExercise).toEqual(fileUploadExercise);\n }));\n });\n\n describe('ngOnInit without given exerciseGroup', () => {\n const fileUploadExercise = new FileUploadExercise(new Course(), undefined);\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.data = of({ fileUploadExercise });\n });\n\n it('Should not be in exam mode', fakeAsync(() => {\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n // THEN\n expect(comp.isExamMode).toEqual(false);\n expect(comp.fileUploadExercise).toEqual(fileUploadExercise);\n }));\n });\n});\n" }, { "alpha_fraction": 0.6301604509353638, "alphanum_fraction": 0.6308021545410156, "avg_line_length": 41.11711883544922, "blob_id": "93f47f2f506b493cb6080337af89eaca64d6c1ef", "content_id": "f5599b8cebefd5bc03b47242f71e050a4829de96", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4675, "license_type": "permissive", "max_line_length": 164, "num_lines": 111, "path": "/src/main/webapp/app/shared/notification/system-notification/system-notification.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport * as moment from 'moment';\nimport { SystemNotification, SystemNotificationType } from 'app/entities/system-notification.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { User } from 'app/core/user/user.model';\nimport { SystemNotificationService } from 'app/shared/notification/system-notification/system-notification.service';\nimport { IconProp } from '@fortawesome/fontawesome-svg-core';\n\n@Component({\n selector: 'jhi-system-notification',\n templateUrl: './system-notification.component.html',\n styleUrls: ['system-notification.scss'],\n})\nexport class SystemNotificationComponent implements OnInit {\n readonly INFO = SystemNotificationType.INFO;\n readonly WARNING = SystemNotificationType.WARNING;\n notification: SystemNotification | undefined;\n alertClass: string;\n alertIcon: IconProp;\n websocketChannel: string;\n\n constructor(\n private route: ActivatedRoute,\n private accountService: AccountService,\n private jhiWebsocketService: JhiWebsocketService,\n private systemNotificationService: SystemNotificationService,\n ) {}\n\n ngOnInit() {\n this.loadActiveNotification();\n this.accountService.getAuthenticationState().subscribe((user: User | undefined) => {\n if (user) {\n // maybe use connectedPromise as a set function\n setTimeout(() => {\n this.jhiWebsocketService.bind('connect', () => {\n this.subscribeSocket();\n });\n }, 500);\n }\n });\n }\n\n private loadActiveNotification() {\n this.systemNotificationService.getActiveNotification().subscribe((notification: SystemNotification) => {\n if (notification) {\n this.notification = notification;\n this.setAlertClass();\n this.setAlertIcon();\n } else {\n this.notification = undefined;\n }\n });\n }\n\n private subscribeSocket() {\n this.websocketChannel = '/topic/system-notification';\n this.jhiWebsocketService.subscribe(this.websocketChannel);\n this.jhiWebsocketService.receive(this.websocketChannel).subscribe((systemNotification: SystemNotification | string) => {\n // as we cannot send null as websocket payload (this is not supported), we send a string 'deleted' in case the system notification was deleted\n if (systemNotification === 'deleted') {\n this.loadActiveNotification();\n return;\n }\n systemNotification = systemNotification as SystemNotification;\n systemNotification.notificationDate = systemNotification.notificationDate ? moment(systemNotification.notificationDate) : undefined;\n systemNotification.expireDate = systemNotification.expireDate ? moment(systemNotification.expireDate) : undefined;\n if (!this.notification) {\n this.checkNotificationDates(systemNotification);\n } else {\n if (this.notification.id === systemNotification.id) {\n this.checkNotificationDates(systemNotification);\n } else if (systemNotification.notificationDate!.isBefore(this.notification.notificationDate!) && systemNotification.expireDate!.isAfter(moment())) {\n this.checkNotificationDates(systemNotification);\n }\n }\n });\n }\n\n private checkNotificationDates(systemNotification: SystemNotification) {\n if (systemNotification.expireDate!.isAfter(moment()) && systemNotification.notificationDate!.isBefore(moment())) {\n this.notification = systemNotification;\n this.setAlertClass();\n this.setAlertIcon();\n } else {\n this.loadActiveNotification();\n return;\n }\n }\n\n private setAlertClass(): void {\n if (this.notification) {\n if (this.notification.type === SystemNotificationType.WARNING) {\n this.alertClass = 'alert-warning';\n } else {\n this.alertClass = 'alert-info';\n }\n }\n }\n\n private setAlertIcon(): void {\n if (this.notification) {\n if (this.notification.type === SystemNotificationType.WARNING) {\n this.alertIcon = 'exclamation-triangle';\n } else {\n this.alertIcon = 'info-circle';\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6466370820999146, "alphanum_fraction": 0.6466370820999146, "avg_line_length": 37.03895950317383, "blob_id": "9d8f472845cbf224244a97886fb5f14dd667b4a4", "content_id": "0948acf9e06e68ddb505aa0f6056649bdee58c63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2929, "license_type": "permissive", "max_line_length": 169, "num_lines": 77, "path": "/src/main/webapp/app/admin/system-notification-management/system-notification-management-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { UserService } from 'app/core/user/user.service';\nimport { SystemNotification, SystemNotificationType } from 'app/entities/system-notification.model';\nimport { SystemNotificationService } from 'app/shared/notification/system-notification/system-notification.service';\nimport { navigateBack } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-system-notification-management-update',\n templateUrl: './system-notification-management-update.component.html',\n})\nexport class SystemNotificationManagementUpdateComponent implements OnInit {\n notification: SystemNotification;\n isSaving: boolean;\n\n systemNotificationTypes = [\n { name: 'INFO', value: SystemNotificationType.INFO },\n { name: 'WARNING', value: SystemNotificationType.WARNING },\n ];\n\n constructor(private userService: UserService, private systemNotificationService: SystemNotificationService, private route: ActivatedRoute, private router: Router) {}\n\n /**\n * Loads notification from route data\n */\n ngOnInit() {\n this.isSaving = false;\n // create a new notification, and only overwrite it if we fetch a notification to edit\n this.notification = new SystemNotification();\n this.route.parent!.data.subscribe(({ notification }) => {\n if (notification) {\n this.notification = notification.body ? notification.body : notification;\n }\n });\n }\n\n /**\n * Returns to previous state (same as back button in the browser)\n * Returns to the detail page if there is no previous state and we edited an existing notification\n * Returns to the overview page if there is no previous state and we created a new notification\n */\n previousState() {\n // Newly created notifications don't have an id yet\n if (!this.notification.id) {\n navigateBack(this.router, ['admin', 'system-notification-management']);\n } else {\n navigateBack(this.router, ['admin', 'system-notification-management', this.notification.id!.toString()]);\n }\n }\n\n /**\n * Either creates or updates the notification, when the form is submitted\n */\n save() {\n this.isSaving = true;\n if (this.notification.id) {\n this.systemNotificationService.update(this.notification).subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n } else {\n this.systemNotificationService.create(this.notification).subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n }\n }\n\n private onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n private onSaveError() {\n this.isSaving = false;\n }\n}\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 19, "blob_id": "76672e579bf068be4854c8fbacd18b8c2c455d62", "content_id": "3011fbfe69a4fb5cc752ea53e6bf8e75236b55ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 100, "license_type": "permissive", "max_line_length": 47, "num_lines": 5, "path": "/src/main/java/de/tum/in/www1/artemis/service/feature/Feature.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.feature;\n\npublic enum Feature {\n PROGRAMMING_EXERCISES;\n}\n" }, { "alpha_fraction": 0.5695496201515198, "alphanum_fraction": 0.5836986899375916, "avg_line_length": 35.36231994628906, "blob_id": "b9f06edae3ffcb00fee9352f85cfd3b94ebba43f", "content_id": "7f76e9c0064b709a85e21971208900e32c173ada", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5018, "license_type": "permissive", "max_line_length": 114, "num_lines": 138, "path": "/src/test/javascript/spec/service/text-submission.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { take } from 'rxjs/operators';\nimport { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport * as sinonChai from 'sinon-chai';\nimport * as chai from 'chai';\n\nchai.use(sinonChai);\n\nconst expect = chai.expect;\n\ndescribe('TextSubmission Service', () => {\n let injector: TestBed;\n let service: TextSubmissionService;\n let httpMock: HttpTestingController;\n let elemDefault: TextSubmission;\n let mockResponse: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n });\n injector = getTestBed();\n service = injector.get(TextSubmissionService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new TextSubmission();\n mockResponse = {\n submissionExerciseType: 'text',\n id: 1,\n submitted: true,\n type: 'MANUAL',\n participation: {\n type: 'student',\n id: 1,\n initializationState: 'FINISHED',\n initializationDate: '2020-07-07T14:34:18.067248+02:00',\n exercise: {\n type: 'text',\n id: 1,\n },\n participantIdentifier: 'ga27der',\n participantName: 'Jonas Petry',\n },\n result: {\n id: 5,\n assessmentType: 'MANUAL',\n },\n submissionDate: '2020-07-07T14:34:25.194518+02:00',\n durationInMinutes: 0,\n text: 'Test\\n\\nTest\\n\\nTest',\n };\n });\n\n it('should create a TextSubmission', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n const expected = Object.assign({}, returnedFromService);\n service\n .create(new TextSubmission(), 1)\n .pipe(take(1))\n .subscribe((resp: any) => expect(resp).to.deep.equal({ body: expected }));\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should update a TextSubmission', async () => {\n const returnedFromService = Object.assign(\n {\n text: 'BBBBBB',\n },\n elemDefault,\n );\n\n const expected = Object.assign({}, returnedFromService);\n service\n .update(expected, 1)\n .pipe(take(1))\n .subscribe((resp: any) => expect(resp).to.deep.equal({ body: expected }));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should not parse jwt from header', async () => {\n service.getTextSubmissionForExerciseForCorrectionRoundWithoutAssessment(1).subscribe((textSubmission) => {\n expect(textSubmission.atheneTextAssessmentTrackingToken).to.be.null;\n });\n\n const mockRequest = httpMock.expectOne({ method: 'GET' });\n mockRequest.flush(mockResponse);\n });\n\n it('should parse jwt from header', async () => {\n service.getTextSubmissionForExerciseForCorrectionRoundWithoutAssessment(1).subscribe((textSubmission) => {\n expect(textSubmission.atheneTextAssessmentTrackingToken).to.equal('12345');\n });\n\n const mockRequest = httpMock.expectOne({ method: 'GET' });\n mockRequest.flush(mockResponse, { headers: { 'x-athene-tracking-authorization': '12345' } });\n });\n it('should get textSubmission for exercise', async () => {\n const exerciseId = 1;\n elemDefault = new TextSubmission();\n elemDefault.latestResult = undefined;\n const returnedFromService = [elemDefault];\n const expected = returnedFromService;\n service\n .getTextSubmissionsForExerciseByCorrectionRound(exerciseId, {})\n .pipe(take(1))\n .subscribe((resp) => (mockResponse = resp));\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(mockResponse.body).to.deep.equal(expected);\n });\n\n it('should get textSubmission', async () => {\n const exerciseId = 1;\n elemDefault = new TextSubmission();\n const returnedFromService = { body: elemDefault };\n const expected = returnedFromService.body;\n service\n .getTextSubmission(exerciseId)\n .pipe(take(1))\n .subscribe((resp) => (mockResponse = resp));\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(returnedFromService);\n expect(mockResponse.body).to.deep.equal(expected);\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.7240398526191711, "alphanum_fraction": 0.7254623174667358, "avg_line_length": 45.86666488647461, "blob_id": "a308994a1f82404c25b84282948ce81460cc3a1a", "content_id": "9643262cfba1f51d2e999510953369e06be3df13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1406, "license_type": "permissive", "max_line_length": 131, "num_lines": 30, "path": "/src/main/webapp/app/shared/util/markdown-util.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "/**\n * adds the passed text into the editor of the passed ace editor component at the current curser by focusing, clearing a selection,\n * moving the cursor to the end of the line, and finally inserting the given text.\n * After that the new test will be selected\n *\n * @param text the text that will be added into the editor of the passed ace editor component\n * @param aceEditor the editor in which the text will be added at the current curser position\n */\nexport function addTextAtCursor(text: String, aceEditor: any) {\n aceEditor.focus();\n aceEditor.clearSelection();\n aceEditor.moveCursorTo(aceEditor.getCursorPosition().row, Number.POSITIVE_INFINITY);\n aceEditor.insert(text);\n const range = aceEditor.selection.getRange();\n const commandIdentifier = text.split(']');\n const offsetRange = commandIdentifier[0].length + 1;\n range.setStart(range.start.row, offsetRange);\n aceEditor.selection.setRange(range);\n}\n\n/**\n * Remove the text at the specified range.\n * @param from = col & row from which to start\n * @param to = col & row at which to end\n * @param aceEditor the editor in which text should be removed\n */\nexport function removeTextRange(from: { col: number; row: number }, to: { col: number; row: number }, aceEditor: any) {\n aceEditor.focus();\n aceEditor.getSession().remove({ startRow: from.row, startColumn: from.col, endRow: to.row, endColumn: to.col });\n}\n" }, { "alpha_fraction": 0.5392067432403564, "alphanum_fraction": 0.5711683630943298, "avg_line_length": 51.2813835144043, "blob_id": "d9f5b53fc65b77d4101eb42dd89f5fd3a72b6eb6", "content_id": "256bdf5122d33304ea55478db852f53a6308fca0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12077, "license_type": "permissive", "max_line_length": 116, "num_lines": 231, "path": "/src/test/javascript/spec/pipe/artemis-date.pipe.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { TestBed } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as moment from 'moment';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ArtemisDatePipe', () => {\n let pipe: ArtemisDatePipe;\n let translateService: TranslateService;\n const dateTime = moment({\n year: 2020,\n month: 3,\n day: 14,\n hour: 9,\n minute: 27,\n seconds: 3,\n }); // 2020-04-14 09:27:03\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n declarations: [ArtemisDatePipe],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n });\n translateService = TestBed.inject(TranslateService);\n pipe = new ArtemisDatePipe(translateService);\n });\n\n it('Return empty string if given date time is null', () => {\n let localizedDateTime = pipe.transform(null);\n expect(localizedDateTime).to.be.equal('');\n localizedDateTime = pipe.transform(moment(null));\n expect(localizedDateTime).to.be.equal('');\n });\n\n it('Return empty string if given date time is invalid moment object', () => {\n const invalidMoment = moment({\n year: 2019,\n month: 2,\n day: 333,\n }); // 2019-02-333\n const localizedDateTime = pipe.transform(invalidMoment);\n expect(localizedDateTime).to.be.equal('');\n });\n\n describe('en locale', () => {\n beforeEach(() => {\n dateTime.locale('en');\n translateService.currentLang = 'en';\n });\n\n describe('without seconds', () => {\n it('Should return format equal to \"2020-04-14 09:27\" with format parameter set to \"short\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short');\n const format = 'YYYY-MM-DD HH:mm';\n expect(ArtemisDatePipe.format('en', 'short')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('2020-04-14 09:27');\n });\n\n it('Should return format equal to \"Apr 14, 2020 09:27\" with format parameter set to \"long\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long');\n const format = 'll HH:mm';\n expect(ArtemisDatePipe.format('en', 'long')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('Apr 14, 2020 09:27');\n });\n\n it('Should return format equal to \"2020-04-14\" with format parameter set to \"short-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short-date');\n const format = 'YYYY-MM-DD';\n expect(ArtemisDatePipe.format('en', 'short-date')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('2020-04-14');\n });\n\n it('Should return format equal to \"Apr 14, 2020\" with format parameter set to \"long-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long-date');\n const format = 'll';\n expect(ArtemisDatePipe.format('en', 'long-date')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('Apr 14, 2020');\n });\n\n it('Should return format equal to \"09:27\" with format parameter set to \"time\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'time');\n const format = 'HH:mm';\n expect(ArtemisDatePipe.format('en', 'time')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('09:27');\n });\n });\n\n describe('with seconds', () => {\n it('Should return format equal to \"2020-04-14 09:27:03\" with format parameter set to \"short\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short', true);\n const format = 'YYYY-MM-DD HH:mm:ss';\n expect(ArtemisDatePipe.format('en', 'short', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('2020-04-14 09:27:03');\n });\n\n it('Should return format equal to \"Apr 14, 2020 09:27:03\" with format parameter set to \"long\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long', true);\n const format = 'll HH:mm:ss';\n expect(ArtemisDatePipe.format('en', 'long', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('Apr 14, 2020 09:27:03');\n });\n\n it('Should return format equal to \"2020-04-14\" with format parameter set to \"short-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short-date', true);\n const format = 'YYYY-MM-DD';\n expect(ArtemisDatePipe.format('en', 'short-date', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('2020-04-14');\n });\n\n it('Should return format equal to \"Apr 14, 2020\" with format parameter set to \"long-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long-date', true);\n const format = 'll';\n expect(ArtemisDatePipe.format('en', 'long-date', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('Apr 14, 2020');\n });\n\n it('Should return format equal to \"09:27:03\" with format parameter set to \"time\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'time', true);\n const format = 'HH:mm:ss';\n expect(ArtemisDatePipe.format('en', 'time', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('09:27:03');\n });\n });\n });\n\n describe('de locale', () => {\n beforeEach(() => {\n dateTime.locale('de');\n translateService.currentLang = 'de';\n });\n\n describe('without seconds', () => {\n it('Should return format equal to \"14.04.2020 09:27\" with format parameter set to \"short\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short');\n const format = 'DD.MM.YYYY HH:mm';\n expect(ArtemisDatePipe.format('de', 'short')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14.04.2020 09:27');\n });\n\n it('Should return format equal to \"14. Apr. 2020 09:27\" with format parameter set to \"long\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long');\n const format = 'll HH:mm';\n expect(ArtemisDatePipe.format('de', 'long')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14. Apr. 2020 09:27');\n });\n\n it('Should return format equal to \"14.04.2020\" with format parameter set to \"short-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short-date');\n const format = 'DD.MM.YYYY';\n expect(ArtemisDatePipe.format('de', 'short-date')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14.04.2020');\n });\n\n it('Should return format equal to \"14. Apr. 2020\" with format parameter set to \"long-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long-date');\n const format = 'll';\n expect(ArtemisDatePipe.format('de', 'long-date')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14. Apr. 2020');\n });\n\n it('Should return format equal to \"09:27\" with format parameter set to \"time\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'time');\n const format = 'HH:mm';\n expect(ArtemisDatePipe.format('de', 'time')).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('09:27');\n });\n });\n\n describe('with seconds', () => {\n it('Should return format equal to \"14.04.2020 09:27:03\" with format parameter set to \"short\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short', true);\n const format = 'DD.MM.YYYY HH:mm:ss';\n expect(ArtemisDatePipe.format('de', 'short', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14.04.2020 09:27:03');\n });\n\n it('Should return format equal to \"14. Apr. 2020 09:27:03\" with format parameter set to \"long\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long', true);\n const format = 'll HH:mm:ss';\n expect(ArtemisDatePipe.format('de', 'long', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14. Apr. 2020 09:27:03');\n });\n\n it('Should return format equal to \"14.04.2020\" with format parameter set to \"short-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'short-date', true);\n const format = 'DD.MM.YYYY';\n expect(ArtemisDatePipe.format('de', 'short-date', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14.04.2020');\n });\n\n it('Should return format equal to \"14. Apr. 2020\" with format parameter set to \"long-date\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'long-date', true);\n const format = 'll';\n expect(ArtemisDatePipe.format('de', 'long-date', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('14. Apr. 2020');\n });\n\n it('Should return format equal to \"09:27:03\" with format parameter set to \"time\"', () => {\n const localizedDateTime = pipe.transform(dateTime, 'time', true);\n const format = 'HH:mm:ss';\n expect(ArtemisDatePipe.format('de', 'time', true)).to.be.equal(format);\n expect(localizedDateTime).to.be.equal(dateTime.format(format));\n expect(localizedDateTime).to.be.equal('09:27:03');\n });\n });\n });\n});\n" }, { "alpha_fraction": 0.6145086288452148, "alphanum_fraction": 0.6197806596755981, "avg_line_length": 38.84873962402344, "blob_id": "cb86b9bc82a168e11e0c772415fa9f1f1b3ed7bc", "content_id": "1b6b13fa462e07c08a230f56724e3278d3504e97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4742, "license_type": "permissive", "max_line_length": 119, "num_lines": 119, "path": "/src/test/javascript/InlineHtmlStripStylesTransformer.js", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "'use strict';\n// Copied from: https://github.com/thymikee/jest-preset-angular\n/*\n * Code is inspired by\n * https://github.com/kulshekhar/ts-jest/blob/25e1c63dd3797793b0f46fa52fdee580b46f66ae/src/transformers/hoist-jest.ts\n *\n */\nObject.defineProperty(exports, '__esModule', { value: true });\n/** Angular component decorator TemplateUrl property name */\nvar TEMPLATE_URL = 'templateUrl';\n/** Angular component decorator StyleUrls property name */\nvar STYLE_URLS = 'styleUrls';\n/** Angular component decorator Styles property name */\nvar STYLES = 'styles';\n/** Angular component decorator Template property name */\nvar TEMPLATE = 'template';\n/** Node require function name */\nvar REQUIRE = 'require';\n/**\n * Property names inside the decorator argument to transform\n */\nvar TRANSFORM_PROPS = [TEMPLATE_URL, STYLES, STYLE_URLS];\n/**\n * Transformer ID\n * @internal\n */\nexports.name = 'angular-component-inline-template-strip-styles';\n// increment this each time the code is modified\n/**\n * Transformer Version\n * @internal\n */\nexports.version = 1;\n/**\n * The factory of hoisting transformer factory\n * @internal\n */\nfunction factory(cs) {\n /**\n * Our compiler (typescript, or a module with typescript-like interface)\n */\n var ts = cs.compilerModule;\n /**\n * Traverses the AST down to the relevant assignments in the decorator\n * argument and returns them in an array.\n */\n function isPropertyAssignmentToTransform(node) {\n return ts.isPropertyAssignment(node) && ts.isIdentifier(node.name) && TRANSFORM_PROPS.includes(node.name.text);\n }\n /**\n * Clones the assignment and manipulates it depending on its name.\n * @param node the property assignment to change\n */\n function transfromPropertyAssignmentForJest(node) {\n var mutableAssignment = ts.getMutableClone(node);\n var assignmentNameText = mutableAssignment.name.text;\n switch (assignmentNameText) {\n case TEMPLATE_URL:\n // reuse the right-hand-side literal from the assignment\n var templatePathLiteral = mutableAssignment.initializer;\n // fix templatePathLiteral if it was a non-relative path\n if (ts.isStringLiteral(mutableAssignment.initializer)) {\n var templatePathStringLiteral = mutableAssignment.initializer;\n // match if it starts with ./ or ../ or /\n if (templatePathStringLiteral.text && !templatePathStringLiteral.text.match(/^(\\.\\/|\\.\\.\\/|\\/)/)) {\n // make path relative by appending './'\n templatePathLiteral = ts.createStringLiteral('./' + templatePathStringLiteral.text);\n }\n }\n // replace 'templateUrl' with 'template'\n mutableAssignment.name = ts.createIdentifier(TEMPLATE);\n // replace current initializer with require(path)\n mutableAssignment.initializer = ts.createCall(\n /* expression */ ts.createIdentifier(REQUIRE),\n /* type arguments */ undefined,\n /* arguments array */ [templatePathLiteral],\n );\n break;\n case STYLES:\n case STYLE_URLS:\n // replace initializer array with empty array\n mutableAssignment.initializer = ts.createArrayLiteral();\n break;\n }\n return mutableAssignment;\n }\n /**\n * Create a source file visitor which will visit all nodes in a source file\n * @param ctx The typescript transformation context\n * @param _ The owning source file\n */\n function createVisitor(ctx, _) {\n /**\n * Our main visitor, which will be called recursively for each node in the source file's AST\n * @param node The node to be visited\n */\n var visitor = function (node) {\n var resultNode;\n // before we create a deep clone to modify, we make sure that\n // this is an assignment which we want to transform\n if (isPropertyAssignmentToTransform(node)) {\n // get transformed node with changed properties\n resultNode = transfromPropertyAssignmentForJest(node);\n } else {\n // look for interesting assignments inside this node\n resultNode = ts.visitEachChild(node, visitor, ctx);\n }\n // finally return the currently visited node\n return resultNode;\n };\n return visitor;\n }\n return function (ctx) {\n return function (sf) {\n return ts.visitNode(sf, createVisitor(ctx, sf));\n };\n };\n}\nexports.factory = factory;\n" }, { "alpha_fraction": 0.6595744490623474, "alphanum_fraction": 0.6675877571105957, "avg_line_length": 38.769229888916016, "blob_id": "cb4922ba13c853c52783e908d01a66802829922a", "content_id": "cc64bd2eb87d52e2d2414b5daa112eccf8e252ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3619, "license_type": "permissive", "max_line_length": 121, "num_lines": 91, "path": "/src/main/webapp/app/shared/category-selector/category-selector.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnChanges, Output, ViewChild, ViewEncapsulation } from '@angular/core';\nimport { ExerciseCategory } from 'app/entities/exercise.model';\nimport { ColorSelectorComponent } from 'app/shared/color-selector/color-selector.component';\nimport { TagModel } from 'ngx-chips/core/accessor';\n\nconst DEFAULT_COLORS = ['#6ae8ac', '#9dca53', '#94a11c', '#691b0b', '#ad5658', '#1b97ca', '#0d3cc2', '#0ab84f'];\n\n@Component({\n selector: 'jhi-category-selector',\n templateUrl: './category-selector.component.html',\n styleUrls: ['./category-selector.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class CategorySelectorComponent implements OnChanges {\n @ViewChild(ColorSelectorComponent, { static: false }) colorSelector: ColorSelectorComponent;\n categoryColors = DEFAULT_COLORS;\n selectedCategory: ExerciseCategory;\n @Input() exerciseCategories: ExerciseCategory[];\n @Input() existingCategories: ExerciseCategory[];\n @Output() selectedCategories = new EventEmitter<ExerciseCategory[]>();\n uniqueCategories: ExerciseCategory[] = [];\n private readonly colorSelectorHeight = 150;\n\n /**\n * set unique categories on changes\n */\n ngOnChanges() {\n if (!this.existingCategories) {\n return;\n }\n this.existingCategories.forEach((category) => {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const categoryIsInArray = (el: ExerciseCategory, index: number, categories: ExerciseCategory[]): boolean => {\n return el.category === category.category;\n };\n if (!this.uniqueCategories.find(categoryIsInArray)) {\n this.uniqueCategories.push(category);\n }\n });\n }\n\n /**\n * open colorSelector for tagItem\n * @param {MouseEvent} event\n * @param {ExerciseCategory} tagItem\n */\n openColorSelector(event: MouseEvent, tagItem: ExerciseCategory) {\n this.selectedCategory = tagItem;\n this.colorSelector.openColorSelector(event, undefined, this.colorSelectorHeight);\n }\n\n /**\n * set color of selected category\n * @param {string} selectedColor\n */\n onSelectedColor(selectedColor: string) {\n this.selectedCategory.color = selectedColor;\n this.exerciseCategories = this.exerciseCategories.map((el) => {\n if (el.category === this.selectedCategory.category) {\n return this.selectedCategory;\n }\n return el;\n });\n this.selectedCategories.emit(this.exerciseCategories);\n }\n\n /**\n * set color if not selected and add exerciseCategory\n * @param categoryTag the tag of the exercise category\n */\n onItemAdded(categoryTag: TagModel) {\n const exerciseCategory = categoryTag as ExerciseCategory;\n if (!exerciseCategory.color) {\n const randomIndex = Math.floor(Math.random() * this.categoryColors.length);\n exerciseCategory.color = this.categoryColors[randomIndex];\n }\n this.exerciseCategories.push(exerciseCategory);\n this.selectedCategories.emit(this.exerciseCategories);\n }\n\n /**\n * cancel colorSelector and remove exerciseCategory\n * @param {ExerciseCategory} tagItem\n */\n onItemRemove(tagItem: TagModel) {\n const categoryToRemove = tagItem as ExerciseCategory;\n this.colorSelector.cancelColorSelector();\n this.exerciseCategories = this.exerciseCategories.filter((category) => category !== categoryToRemove);\n this.selectedCategories.emit(this.exerciseCategories);\n }\n}\n" }, { "alpha_fraction": 0.812199056148529, "alphanum_fraction": 0.812199056148529, "avg_line_length": 35.64706039428711, "blob_id": "65e94607b4c03ff3b92874f916ec3969c9acb5a1", "content_id": "6377a5550d0360e5909e2174860f556b91ed3f19", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 623, "license_type": "permissive", "max_line_length": 65, "num_lines": 17, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-course-progress.dtos.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class CourseLearningGoalProgress {\n public courseId: number;\n public learningGoalId: number;\n public learningGoalTitle: string;\n public averagePointsAchievedByStudentInLearningGoal: number;\n public totalPointsAchievableByStudentsInLearningGoal: number;\n\n public progressInLectureUnits: CourseLectureUnitProgress[];\n}\n\nexport class CourseLectureUnitProgress {\n public lectureUnitId: number;\n public averageScoreAchievedByStudentInLectureUnit: number;\n public totalPointsAchievableByStudentsInLectureUnit: number;\n public noOfParticipants: number;\n public participationRate: number;\n}\n" }, { "alpha_fraction": 0.6206554770469666, "alphanum_fraction": 0.630258321762085, "avg_line_length": 41.5883903503418, "blob_id": "1e5a9be6b812c3d33643b5b50242f136a2767f85", "content_id": "356c134d6dfc8f083660ed279ca944dea4e5eb2b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16141, "license_type": "permissive", "max_line_length": 169, "num_lines": 379, "path": "/src/test/javascript/spec/component/shared/result-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { of, throwError } from 'rxjs';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Feedback, FeedbackType, STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER } from 'app/entities/feedback.model';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { FeedbackItem, FeedbackItemType, ResultDetailComponent } from 'app/exercises/shared/result/result-detail.component';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { Result } from 'app/entities/result.model';\nimport { BuildLogService } from 'app/exercises/programming/shared/service/build-log.service';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ChartComponent } from 'app/shared/chart/chart.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ResultDetailComponent', () => {\n let comp: ResultDetailComponent;\n let fixture: ComponentFixture<ResultDetailComponent>;\n let debugElement: DebugElement;\n\n let exercise: ProgrammingExercise;\n let buildLogService: BuildLogService;\n let resultService: ResultService;\n let buildlogsStub: SinonStub;\n let getFeedbackDetailsForResultStub: SinonStub;\n\n const makeFeedback = (fb: Feedback) => {\n return Object.assign({ type: FeedbackType.AUTOMATIC, text: '', detailText: '', credits: 0 } as Feedback, fb);\n };\n\n const makeFeedbackItem = (item: FeedbackItem) => {\n return Object.assign({ type: FeedbackItemType.Feedback, credits: 0, title: undefined, positive: undefined } as FeedbackItem, item);\n };\n\n const generateSCAFeedbackPair = (\n showDetails: boolean,\n category: string,\n credits: number,\n penalty: number,\n { line = 1, column = undefined }: { line?: number; column?: number } = {},\n ) => {\n return {\n fb: makeFeedback({\n text: STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER + category,\n detailText: JSON.stringify({\n filePath: 'www/packet/File.java',\n startLine: line,\n startColumn: column,\n rule: 'Rule',\n message: 'This is a code issue',\n penalty,\n }),\n credits,\n positive: false,\n }),\n item: makeFeedbackItem({\n type: FeedbackItemType.Issue,\n category: 'Code Issue',\n title: category + ' Issue in file www/packet/File.java at line ' + line + (column != undefined ? ' column ' + column : ''),\n text: showDetails ? 'Rule: This is a code issue' : 'This is a code issue',\n credits: -penalty,\n appliedCredits: credits,\n positive: false,\n }),\n };\n };\n\n const generateTestCaseFeedbackPair = (showDetails: boolean, name: string, message: string | undefined, credits = 0) => {\n return {\n fb: makeFeedback({\n text: name,\n detailText: message,\n credits,\n positive: credits > 0,\n }),\n item: makeFeedbackItem({\n type: FeedbackItemType.Test,\n category: showDetails ? 'Test Case' : 'Feedback',\n text: message,\n credits,\n positive: credits > 0,\n title: showDetails ? `Test ${name} ${credits > 0 ? 'passed' : 'failed'}` : undefined,\n }),\n };\n };\n\n const generateManualFeedbackPair = (showDetails: boolean, title: string, text: string, credits = 0) => {\n return {\n fb: makeFeedback({\n type: FeedbackType.MANUAL,\n text: title,\n detailText: text,\n credits,\n positive: credits > 0,\n }),\n item: makeFeedbackItem({\n type: FeedbackItemType.Feedback,\n category: showDetails ? 'Tutor' : 'Feedback',\n title,\n text,\n credits,\n positive: credits > 0,\n }),\n };\n };\n\n const generateFeedbacksAndExpectedItems = (showTestDetails = false) => {\n const feedbacks: Feedback[] = [];\n const expectedItems: FeedbackItem[] = [];\n const addPair = (pair: { fb: Feedback; item: FeedbackItem }) => {\n feedbacks.push(pair.fb);\n expectedItems.push(pair.item);\n };\n addPair(generateSCAFeedbackPair(showTestDetails, 'Bad Practice', -2, 2));\n addPair(generateSCAFeedbackPair(showTestDetails, 'Styling', -0.5, 1, { column: 10 }));\n addPair(generateSCAFeedbackPair(showTestDetails, 'Styling', -0.5, 1, { line: 2, column: 1 }));\n addPair(generateManualFeedbackPair(showTestDetails, 'Positive', 'This is good', 4));\n addPair(generateManualFeedbackPair(showTestDetails, 'Negative', 'This is bad', -2));\n addPair(generateManualFeedbackPair(showTestDetails, 'Neutral', 'This is neutral', 0));\n addPair(generateTestCaseFeedbackPair(showTestDetails, 'TestCase1', 'This failed.'));\n addPair(generateTestCaseFeedbackPair(showTestDetails, 'TestCase2', 'This passed.', 3));\n addPair(generateTestCaseFeedbackPair(showTestDetails, 'TestCase3', undefined, 3));\n\n if (!showTestDetails) {\n expectedItems.pop();\n expectedItems.unshift(makeFeedbackItem({ type: FeedbackItemType.Test, category: 'Feedback', title: '1 passed test', positive: true, credits: 3 }));\n }\n\n return { feedbacks, expectedItems };\n };\n\n const generateProgrammingSubmission = (buildFailed: boolean) => {\n const programmingSubmission = new ProgrammingSubmission();\n programmingSubmission.buildFailed = buildFailed;\n return programmingSubmission;\n };\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisResultModule],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ResultDetailComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n\n exercise = {\n maxPoints: 100,\n bonusPoints: 0,\n type: ExerciseType.PROGRAMMING,\n staticCodeAnalysisEnabled: true,\n maxStaticCodeAnalysisPenalty: 20,\n } as ProgrammingExercise;\n\n comp.result = {\n id: 89,\n participation: {\n id: 55,\n exercise,\n },\n } as Result;\n\n buildLogService = debugElement.injector.get(BuildLogService);\n resultService = debugElement.injector.get(ResultService);\n\n buildlogsStub = stub(buildLogService, 'getBuildLogs').returns(of([]));\n getFeedbackDetailsForResultStub = stub(resultService, 'getFeedbackDetailsForResult').returns(of({ body: [] as Feedback[] } as HttpResponse<Feedback[]>));\n });\n });\n\n it('should not try to retrieve the feedbacks from the server if provided result has feedbacks', () => {\n const { feedbacks, expectedItems } = generateFeedbacksAndExpectedItems();\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.result.feedbacks = feedbacks;\n\n comp.ngOnInit();\n\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems);\n expect(comp.isLoading).to.be.false;\n });\n\n it('should try to retrieve the feedbacks from the server if provided result does not have feedbacks', () => {\n const { feedbacks, expectedItems } = generateFeedbacksAndExpectedItems();\n comp.exerciseType = ExerciseType.PROGRAMMING;\n getFeedbackDetailsForResultStub.returns(of({ body: feedbacks } as HttpResponse<Feedback[]>));\n\n comp.ngOnInit();\n\n expect(getFeedbackDetailsForResultStub).to.have.been.calledOnceWithExactly(comp.result.id);\n expect(comp.filteredFeedbackList).to.have.same.deep.members(expectedItems);\n expect(comp.isLoading).to.be.false;\n });\n\n it('should try to retrieve build logs if the exercise type is PROGRAMMING and no submission was provided.', () => {\n comp.exerciseType = ExerciseType.PROGRAMMING;\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.have.been.calledOnceWithExactly(comp.result.participation!.id);\n expect(comp.buildLogs).to.deep.equal([]);\n expect(comp.isLoading).to.be.false;\n });\n\n it('should try to retrieve build logs if the exercise type is PROGRAMMING and a submission was provided which was marked with build failed.', () => {\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.result.submission = generateProgrammingSubmission(true);\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.have.been.calledOnceWithExactly(comp.result.participation!.id);\n expect(comp.buildLogs).to.deep.equal([]);\n expect(comp.isLoading).to.be.false;\n });\n\n it('should not try to retrieve build logs if the exercise type is not PROGRAMMING', () => {\n comp.exerciseType = ExerciseType.MODELING;\n comp.result.submission = new ModelingSubmission();\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.not.have.been.called;\n expect(comp.feedbackList).to.be.undefined;\n expect(comp.isLoading).to.be.false;\n });\n\n it('should not try to retrieve build logs if submission was not marked with build failed', () => {\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.result.submission = generateProgrammingSubmission(false);\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.not.have.been.called;\n expect(comp.buildLogs).to.be.undefined;\n expect(comp.isLoading).to.be.false;\n });\n\n it('fetchBuildLogs should suppress 403 error', () => {\n comp.exerciseType = ExerciseType.PROGRAMMING;\n const response = new HttpErrorResponse({ status: 403 });\n buildlogsStub.returns(throwError(response));\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.have.been.calledOnceWithExactly(comp.result.participation!.id);\n expect(comp.loadingFailed).to.be.false;\n expect(comp.isLoading).to.be.false;\n });\n\n it('fetchBuildLogs should not suppress errors with status other than 403', () => {\n comp.exerciseType = ExerciseType.PROGRAMMING;\n const response = new HttpErrorResponse({ status: 500 });\n buildlogsStub.returns(throwError(response));\n\n comp.ngOnInit();\n\n expect(buildlogsStub).to.have.been.calledOnceWithExactly(comp.result.participation!.id);\n expect(comp.loadingFailed).to.be.true;\n expect(comp.isLoading).to.be.false;\n });\n\n it('should show test names if showTestDetails is set to true', () => {\n const { feedbacks, expectedItems } = generateFeedbacksAndExpectedItems(true);\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.result.feedbacks = feedbacks;\n comp.showTestDetails = true;\n\n comp.ngOnInit();\n\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems);\n expect(comp.isLoading).to.be.false;\n });\n\n it('should filter the correct feedbacks when a filter is set', () => {\n const { feedbacks, expectedItems } = generateFeedbacksAndExpectedItems();\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.result.feedbacks = feedbacks;\n comp.feedbackFilter = ['TestCase1', 'TestCase2', 'TestCase3'];\n\n comp.ngOnInit();\n\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems.filter((item) => item.type === FeedbackItemType.Test));\n expect(comp.isLoading).to.be.false;\n });\n\n it('should generate correct class names for feedback items', () => {\n const { expectedItems } = generateFeedbacksAndExpectedItems();\n\n const expectedClasses = [\n 'alert-success', // test case 1\n 'alert-warning', // sca\n 'alert-warning', // sca\n 'alert-warning', // sca\n 'alert-success', // manual 1\n 'alert-danger', // manual 2\n 'alert-warning', // manual 3\n 'alert-danger', // test case 2\n 'alert-success', // test case 3\n ];\n\n expectedItems.forEach((item, index) => expect(comp.getClassNameForFeedbackItem(item)).to.equal(expectedClasses[index]));\n });\n\n it('should calculate the correct chart values and update the score chart', () => {\n const { feedbacks, expectedItems } = generateFeedbacksAndExpectedItems(true);\n comp.exerciseType = ExerciseType.PROGRAMMING;\n comp.showScoreChart = true;\n comp.showTestDetails = true;\n comp.result.feedbacks = feedbacks;\n\n comp.scoreChartPreset.applyTo(new ChartComponent());\n const chartSetValuesSpy = spy(comp.scoreChartPreset, 'setValues');\n\n comp.ngOnInit();\n\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems);\n expect(comp.showScoreChartTooltip).to.equal(true);\n\n expect(chartSetValuesSpy).to.have.been.calledOnceWithExactly(10, 5, 6, 100, 100);\n checkChartPreset(5, 5, '10', '5 of 6');\n expect(comp.isLoading).to.be.false;\n\n // test score exceeding exercise maxpoints\n\n const feedbackPair1 = generateTestCaseFeedbackPair(true, '', '', 120);\n feedbacks.push(feedbackPair1.fb);\n expectedItems.push(feedbackPair1.item);\n\n chartSetValuesSpy.resetHistory();\n comp.ngOnInit();\n\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems);\n expect(chartSetValuesSpy).to.have.been.calledOnceWithExactly(104, 5, 6, 100, 100);\n checkChartPreset(99, 1, '100 of 104', '1 of 6');\n\n // test negative > positive, limit at 0\n\n feedbacks.pop();\n expectedItems.pop();\n const feedbackPair2 = generateSCAFeedbackPair(true, 'Tohuwabohu', -200, 200);\n feedbacks.push(feedbackPair2.fb);\n expectedItems.push(feedbackPair2.item);\n\n chartSetValuesSpy.resetHistory();\n comp.ngOnInit();\n\n expect(comp.filteredFeedbackList).to.have.deep.members(expectedItems);\n expect(chartSetValuesSpy).to.have.been.calledOnceWithExactly(10, 22, 206, 100, 100);\n checkChartPreset(0, 10, '10', '10 of 206');\n });\n\n const checkChartPreset = (d1: number, d2: number, l1: string, l2: string) => {\n // @ts-ignore\n expect(comp.scoreChartPreset.datasets.length).to.equal(2);\n // @ts-ignore\n expect(comp.scoreChartPreset.datasets[0].data[0]).to.equal(d1);\n // @ts-ignore\n expect(comp.scoreChartPreset.valueLabels[0]).to.equal(l1);\n // @ts-ignore\n expect(comp.scoreChartPreset.datasets[1].data[0]).to.equal(d2);\n // @ts-ignore\n expect(comp.scoreChartPreset.valueLabels[1]).to.equal(l2);\n };\n});\n" }, { "alpha_fraction": 0.7128547430038452, "alphanum_fraction": 0.7145242094993591, "avg_line_length": 33.228572845458984, "blob_id": "70ccbddd408a7f66d546a8295c5221a93cd2f430", "content_id": "105bdeb5de77707847d8766b8b1b7a974adfab20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 109, "num_lines": 35, "path": "/src/main/java/de/tum/in/www1/artemis/repository/LectureUnitRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.Optional;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.lecture.LectureUnit;\n\n/**\n * Spring Data JPA repository for the Lecture Unit entity.\n */\n@Repository\npublic interface LectureUnitRepository extends JpaRepository<LectureUnit, Long> {\n\n @Query(\"\"\"\n SELECT lectureUnit\n FROM LectureUnit lectureUnit\n LEFT JOIN FETCH lectureUnit.learningGoals\n WHERE lectureUnit.id = :#{#lectureUnitId}\n \"\"\")\n Optional<LectureUnit> findByIdWithLearningGoals(@Param(\"lectureUnitId\") Long lectureUnitId);\n\n @Query(\"\"\"\n SELECT lectureUnit\n FROM LectureUnit lectureUnit\n LEFT JOIN FETCH lectureUnit.learningGoals lg\n LEFT JOIN FETCH lg.lectureUnits\n WHERE lectureUnit.id = :#{#lectureUnitId}\n \"\"\")\n Optional<LectureUnit> findByIdWithLearningGoalsBidirectional(@Param(\"lectureUnitId\") Long lectureUnitId);\n\n}\n" }, { "alpha_fraction": 0.6765327453613281, "alphanum_fraction": 0.6765327453613281, "avg_line_length": 35.38461685180664, "blob_id": "aace6d6e96bde2dae39c3155608868170330e35b", "content_id": "48ae6240259e2c32cc109a987773efdbd4ed6dfb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 473, "license_type": "permissive", "max_line_length": 84, "num_lines": 13, "path": "/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-query-param-map.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Provider } from '@angular/core';\nimport { ActivatedRoute, convertToParamMap } from '@angular/router';\nimport { BehaviorSubject } from 'rxjs';\n\nexport function mockedActivatedRoute(params: any, queryParams: any = {}): Provider {\n return {\n provide: ActivatedRoute,\n useValue: {\n paramMap: new BehaviorSubject(convertToParamMap(params)),\n queryParamMap: new BehaviorSubject(convertToParamMap(queryParams)),\n },\n };\n}\n" }, { "alpha_fraction": 0.6743044257164001, "alphanum_fraction": 0.6759411096572876, "avg_line_length": 19.366666793823242, "blob_id": "7b88546f3725a5ef29bdf3b59458c64bac317b7a", "content_id": "8381af9ec6e5e01ced00d20cb8e429216e6cb2de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 611, "license_type": "permissive", "max_line_length": 59, "num_lines": 30, "path": "/src/main/java/de/tum/in/www1/artemis/domain/assessment/dashboard/ExerciseMapEntry.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.assessment.dashboard;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n// Custom object for sql query\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ExerciseMapEntry {\n\n private final long exerciseId;\n\n private final long value;\n\n public long getExerciseId() {\n return exerciseId;\n }\n\n public long getValue() {\n return value;\n }\n\n public ExerciseMapEntry(long exerciseId, long value) {\n this.exerciseId = exerciseId;\n this.value = value;\n }\n\n public Long getKey() {\n return exerciseId;\n }\n\n}\n" }, { "alpha_fraction": 0.6730037927627563, "alphanum_fraction": 0.6730037927627563, "avg_line_length": 25.299999237060547, "blob_id": "e5290357a900b734794ed3f0c792ccc9b60f9820", "content_id": "53397f5cbd3e3037c9c7dbc65953e033e9db20a5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 789, "license_type": "permissive", "max_line_length": 85, "num_lines": 30, "path": "/src/test/javascript/spec/helpers/mocks/service/mock-language.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SpyObject } from '../../spyobject';\nimport { JhiLanguageService } from 'ng-jhipster';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { of } from 'rxjs';\nimport { SinonStub } from 'sinon';\n\nexport class MockLanguageService extends SpyObject {\n getCurrentLanguageSpy: SinonStub;\n\n constructor() {\n super(JhiLanguageService);\n\n this.getCurrentLanguageSpy = this.spy('getCurrentLanguage').andReturn('en');\n }\n}\n\nexport class MockLanguageHelper extends SpyObject {\n getAllSpy: SinonStub;\n fakeResponse: 'en';\n\n constructor() {\n super(JhiLanguageHelper);\n\n this.getAllSpy = this.spy('getAll').andReturn(Promise.resolve(['en', 'fr']));\n }\n\n get language() {\n return of(this.fakeResponse);\n }\n}\n" }, { "alpha_fraction": 0.6655075550079346, "alphanum_fraction": 0.6655075550079346, "avg_line_length": 48.09756088256836, "blob_id": "67d9f8a020b376c8c8321238710aea194e2c38a6", "content_id": "906ab78db914276663eb7ff3d150887ade8a6779", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6039, "license_type": "permissive", "max_line_length": 171, "num_lines": 123, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-management/learning-goal-management.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { finalize } from 'rxjs/operators';\nimport { onError } from 'app/shared/util/global.utils';\nimport { forkJoin, Subject } from 'rxjs';\nimport { CourseLearningGoalProgress } from 'app/course/learning-goals/learning-goal-course-progress.dtos.model';\nimport * as _ from 'lodash';\nimport * as Sentry from '@sentry/browser';\n\n@Component({\n selector: 'jhi-learning-goal-management',\n templateUrl: './learning-goal-management.component.html',\n styleUrls: ['./learning-goal-management.component.scss'],\n})\nexport class LearningGoalManagementComponent implements OnInit, OnDestroy {\n courseId: number;\n isLoading = false;\n learningGoals: LearningGoal[] = [];\n learningGoalIdToLearningGoalCourseProgress = new Map<number, CourseLearningGoalProgress>();\n // this is calculated using the participant scores table on the server instead of going participation -> submission -> result\n // we calculate it here to find out if the participant scores table is robust enough to replace the classic way of finding the last result\n learningGoalIdToLearningGoalCourseProgressUsingParticipantScoresTables = new Map<number, CourseLearningGoalProgress>();\n\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(private activatedRoute: ActivatedRoute, private router: Router, private learningGoalService: LearningGoalService, private alertService: JhiAlertService) {}\n\n ngOnDestroy(): void {\n this.dialogErrorSource.unsubscribe();\n }\n\n ngOnInit(): void {\n this.activatedRoute.parent!.params.subscribe((params) => {\n this.courseId = +params['courseId'];\n if (this.courseId) {\n this.loadData();\n }\n });\n }\n\n identify(index: number, learningGoal: LearningGoal) {\n return `${index}-${learningGoal.id}`;\n }\n\n deleteLearningGoal(learningGoalId: number) {\n this.learningGoalService.delete(learningGoalId, this.courseId).subscribe(\n () => {\n this.dialogErrorSource.next('');\n this.loadData();\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n\n getLearningGoalCourseProgress(learningGoal: LearningGoal) {\n return this.learningGoalIdToLearningGoalCourseProgress.get(learningGoal.id!);\n }\n\n loadData() {\n this.isLoading = true;\n this.learningGoalService\n .getAllForCourse(this.courseId)\n .switchMap((res) => {\n this.learningGoals = res.body!;\n\n const progressObservable = this.learningGoals.map((lg) => {\n return this.learningGoalService.getCourseProgress(lg.id!, this.courseId, false);\n });\n\n const progressObservableUsingParticipantScore = this.learningGoals.map((lg) => {\n return this.learningGoalService.getCourseProgress(lg.id!, this.courseId, true);\n });\n\n return forkJoin([forkJoin(progressObservable), forkJoin(progressObservableUsingParticipantScore)]);\n })\n .pipe(\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n ([learningGoalProgressResponses, learningGoalProgressResponsesUsingParticipantScores]) => {\n for (const learningGoalProgressResponse of learningGoalProgressResponses) {\n const learningGoalProgress = learningGoalProgressResponse.body!;\n this.learningGoalIdToLearningGoalCourseProgress.set(learningGoalProgress.learningGoalId, learningGoalProgress);\n }\n for (const learningGoalProgressResponse of learningGoalProgressResponsesUsingParticipantScores) {\n const learningGoalProgress = learningGoalProgressResponse.body!;\n this.learningGoalIdToLearningGoalCourseProgressUsingParticipantScoresTables.set(learningGoalProgress.learningGoalId, learningGoalProgress);\n }\n this.testIfScoreUsingParticipantScoresTableDiffers();\n },\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n\n /**\n * Using this test we want to find out if the progress calculation using the participant scores table leads to the same\n * result as going through participation -> submission -> result\n */\n private testIfScoreUsingParticipantScoresTableDiffers() {\n this.learningGoalIdToLearningGoalCourseProgress.forEach((learningGoalProgress, learningGoalId) => {\n const learningGoalProgressParticipantScoresTable = this.learningGoalIdToLearningGoalCourseProgressUsingParticipantScoresTables.get(learningGoalId);\n if (\n !_.isEqual(\n learningGoalProgress.averagePointsAchievedByStudentInLearningGoal,\n learningGoalProgressParticipantScoresTable!.averagePointsAchievedByStudentInLearningGoal,\n )\n ) {\n const message = `Warning: Learning Goal(id=${learningGoalProgress.learningGoalId}) Course Progress different using participant scores for course ${\n this.courseId\n }! Original: ${JSON.stringify(learningGoalProgress)} | Using ParticipantScores: ${JSON.stringify(learningGoalProgressParticipantScoresTable)}!`;\n console.log(message);\n Sentry.captureException(new Error(message));\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.7001304030418396, "alphanum_fraction": 0.7418513894081116, "avg_line_length": 41.61111068725586, "blob_id": "b9dbe75e116e2d5a14c919629f66f570c24ccfdd", "content_id": "4db9164875dc3bf10f6d7e191fe14466f5d6c34b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 2301, "license_type": "permissive", "max_line_length": 216, "num_lines": 54, "path": "/src/main/docker/jenkins/Dockerfile", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "FROM jenkins/jenkins:lts\n\nLABEL description=\"Jenkins with maven, python3.6 and gcc libraries pre-installed for Artemis\"\n\nUSER root\n\nRUN apt update\n\n# Install Java and Maven dependencies\nRUN apt-get install -y maven\nRUN cd /usr/lib/jvm && \\\n wget https://github.com/AdoptOpenJDK/openjdk16-binaries/releases/download/jdk-16%2B36/OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz && \\\n tar -zxf OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz \\\n && mv jdk-16+36 java-16-openjdk-amd64 \\\n && rm OpenJDK16-jdk_x64_linux_hotspot_16_36.tar.gz\nRUN chown -R root:root /usr/lib/jvm/java-16-openjdk-amd64\nRUN JAVA_HOME=\"/usr/lib/jvm/java-16-openjdk-amd64\" && export JAVA_HOME\nENV JAVA_HOME /usr/lib/jvm/java-16-openjdk-amd64\n\n# Install C dependencies\nRUN apt install -y gcc gdb make libubsan0 liblsan0 libtsan0\n\n# Some packages need to be installed to avoid some known problems for python3.6, see: https://github.com/pyenv/pyenv/wiki/Common-build-problems\nRUN apt install -y make build-essential libssl-dev zlib1g-dev libbz2-dev \\\n libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \\\n xz-utils tk-dev libffi-dev liblzma-dev\n\n # Install Python3.8\nRUN wget https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tgz && \\\n tar xvf Python-3.8.6.tgz \\\n && cd Python-3.8.6 \\\n && ./configure --enable-shared \\\n && make -j8 \\\n && make altinstall\nRUN apt install -y python3 python3-pip\nRUN cd ..\nRUN rm -r -f Python3.8.6/ && rm -f Python-3.8.6.tgz\n\n# Install pytest for python exercises\nRUN pip3 install -U pytest\n\n# Install third-party plugins required by Artemis\nCOPY plugins.yml /usr/share/jenkins/ref/plugins.yml\nRUN jenkins-plugin-cli --plugin-file /usr/share/jenkins/ref/plugins.yml\n\n# Install docker client (if you want a local build agent)\n# (Uncomment this line if you want to use a local docker build agent e.g for development purposes)\n#RUN curl https://download.docker.com/linux/static/stable/x86_64/docker-19.03.8.tgz | tar xvz --directory /tmp && mv -v /tmp/docker/docker /usr/local/bin/docker && chmod +x /usr/local/bin/docker && rm -rf /tmp/docker\n\n# Disables the first-time setup wizard of Jenkins\n# (Uncomment this line if you're using jenknis-casc-config.yml for auto-configuration)\n#ENV JAVA_OPTS -Djenkins.install.runSetupWizard=false\n\nUSER jenkins\n" }, { "alpha_fraction": 0.6749295592308044, "alphanum_fraction": 0.6749295592308044, "avg_line_length": 39.34090805053711, "blob_id": "f7f7815be1f1c2180439214634e1dae4830a2c5d", "content_id": "3f79fe0413a808fdd22362fd97c2b4f11d2e204c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1775, "license_type": "permissive", "max_line_length": 165, "num_lines": 44, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise-lti-configuration.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit } from '@angular/core';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ActivatedRoute } from '@angular/router';\n\nimport { Subscription } from 'rxjs/Subscription';\nimport { LtiConfiguration } from 'app/entities/lti-configuration.model';\nimport { ExerciseLtiConfigurationService, ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { HttpResponse } from '@angular/common/http';\n\n@Component({\n selector: 'jhi-exercise-lti-configuration',\n templateUrl: './exercise-lti-configuration.component.html',\n})\nexport class ExerciseLtiConfigurationComponent implements OnInit, OnDestroy {\n routeSub: Subscription;\n exercise: Exercise;\n ltiConfiguration: LtiConfiguration;\n\n constructor(private route: ActivatedRoute, private exerciseService: ExerciseService, private exerciseLtiConfigurationService: ExerciseLtiConfigurationService) {}\n\n /**\n * Opens the configuration for the exercise encoded in the route\n */\n ngOnInit() {\n this.routeSub = this.route.params.subscribe((params) => {\n const exerciseId = params['exerciseId'];\n if (exerciseId) {\n this.exerciseService.find(exerciseId).subscribe((exerciseResponse: HttpResponse<Exercise>) => {\n this.exerciseLtiConfigurationService.find(exerciseId).subscribe((ltiConfigurationResponse: HttpResponse<any>) => {\n this.exercise = exerciseResponse.body!;\n this.ltiConfiguration = ltiConfigurationResponse.body!;\n });\n });\n }\n });\n }\n\n /**\n * Unsubscribes from the route subscription\n */\n ngOnDestroy() {\n this.routeSub.unsubscribe();\n }\n}\n" }, { "alpha_fraction": 0.8321048617362976, "alphanum_fraction": 0.8321048617362976, "avg_line_length": 75.3125, "blob_id": "9389286926fa38bdfa579e7dd4861f68e8af88a9", "content_id": "4a88a3d5071fbeaea1fe7ba8de1e217b22441c48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1221, "license_type": "permissive", "max_line_length": 150, "num_lines": 16, "path": "/src/main/webapp/app/exercises/shared/exercise-headers/exercise-headers.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { HeaderExercisePageWithDetailsComponent } from './header-exercise-page-with-details.component';\nimport { HeaderParticipationPageComponent } from 'app/exercises/shared/exercise-headers/header-participation-page.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { DifficultyBadgeComponent } from './difficulty-badge.component';\nimport { MomentModule } from 'ngx-moment';\nimport { ArtemisResultModule } from 'app/exercises/shared/result/result.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { IncludedInScoreBadgeComponent } from 'app/exercises/shared/exercise-headers/included-in-score-badge.component';\n\n@NgModule({\n imports: [MomentModule, ArtemisSharedModule, ArtemisResultModule, ArtemisSharedComponentModule],\n declarations: [HeaderExercisePageWithDetailsComponent, HeaderParticipationPageComponent, DifficultyBadgeComponent, IncludedInScoreBadgeComponent],\n exports: [HeaderExercisePageWithDetailsComponent, HeaderParticipationPageComponent, DifficultyBadgeComponent, IncludedInScoreBadgeComponent],\n})\nexport class ArtemisHeaderExercisePageWithDetailsModule {}\n" }, { "alpha_fraction": 0.6181545853614807, "alphanum_fraction": 0.6205317974090576, "avg_line_length": 37.11409378051758, "blob_id": "d06c0e0ff909df597064546df27f18d80939cfaf", "content_id": "67b28274eb4879fa750547caa692ea061b87b41f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11358, "license_type": "permissive", "max_line_length": 125, "num_lines": 298, "path": "/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-point-statistic/quiz-point-statistic.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ChartOptions, ChartType } from 'chart.js';\nimport { calculateHeightOfChart, createOptions, DataSet, DataSetProvider } from '../quiz-statistic/quiz-statistic.component';\nimport { Subscription } from 'rxjs/Subscription';\nimport * as moment from 'moment';\nimport { QuizStatisticUtil } from 'app/exercises/quiz/shared/quiz-statistic-util.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { PointCounter } from 'app/entities/quiz/point-counter.model';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { QuizPointStatistic } from 'app/entities/quiz/quiz-point-statistic.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { blueColor } from 'app/exercises/quiz/manage/statistics/question-statistic.component';\nimport { BaseChartDirective, Color } from 'ng2-charts';\n\n@Component({\n selector: 'jhi-quiz-point-statistic',\n templateUrl: './quiz-point-statistic.component.html',\n})\nexport class QuizPointStatisticComponent implements OnInit, OnDestroy, DataSetProvider {\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n quizExercise: QuizExercise;\n quizPointStatistic: QuizPointStatistic;\n private sub: Subscription;\n\n labels: string[] = [];\n data: number[] = [];\n colors: Color[] = [];\n chartType: ChartType = 'bar';\n datasets: DataSet[] = [];\n\n label: string[] = [];\n ratedData: number[] = [];\n unratedData: number[] = [];\n backgroundColor: string[] = [];\n\n maxScore: number;\n rated = true;\n participants: number;\n websocketChannelForData: string;\n quizExerciseChannel: string;\n\n // options for chart.js style\n options: ChartOptions;\n\n // timer\n waitingForQuizStart = false;\n remainingTimeText = '?';\n remainingTimeSeconds = 0;\n interval: any;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n private accountService: AccountService,\n private translateService: TranslateService,\n private quizExerciseService: QuizExerciseService,\n private quizStatisticUtil: QuizStatisticUtil,\n private jhiWebsocketService: JhiWebsocketService,\n ) {}\n\n ngOnInit() {\n this.sub = this.route.params.subscribe((params) => {\n // use different REST-call if the User is a Student\n if (this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.quizExerciseService.find(params['exerciseId']).subscribe((res) => {\n this.loadQuizSuccess(res.body!);\n });\n }\n\n // subscribe websocket for new statistical data\n this.websocketChannelForData = '/topic/statistic/' + params['exerciseId'];\n this.jhiWebsocketService.subscribe(this.websocketChannelForData);\n\n if (!this.quizExerciseChannel) {\n this.quizExerciseChannel = '/topic/courses/' + params['courseId'] + '/quizExercises';\n\n // quizExercise channel => react to changes made to quizExercise (e.g. start date)\n this.jhiWebsocketService.subscribe(this.quizExerciseChannel);\n this.jhiWebsocketService.receive(this.quizExerciseChannel).subscribe(\n (quiz) => {\n if (this.waitingForQuizStart && params['exerciseId'] === quiz.id) {\n this.loadQuizSuccess(quiz);\n }\n },\n () => {},\n );\n }\n\n // ask for new Data if the websocket for new statistical data was notified\n this.jhiWebsocketService.receive(this.websocketChannelForData).subscribe((quiz) => {\n this.loadNewData(quiz.quizPointStatistic);\n });\n });\n\n // update displayed times in UI regularly\n this.interval = setInterval(() => {\n this.updateDisplayedTimes();\n }, 200);\n }\n\n /**\n * updates all displayed (relative) times in the UI\n */\n updateDisplayedTimes() {\n const translationBasePath = 'showStatistic.';\n // update remaining time\n if (this.quizExercise && this.quizExercise.adjustedDueDate) {\n const endDate = this.quizExercise.adjustedDueDate;\n if (endDate.isAfter(moment())) {\n // quiz is still running => calculate remaining seconds and generate text based on that\n this.remainingTimeSeconds = endDate.diff(moment(), 'seconds');\n this.remainingTimeText = this.relativeTimeText(this.remainingTimeSeconds);\n } else {\n // quiz is over => set remaining seconds to negative, to deactivate 'Submit' button\n this.remainingTimeSeconds = -1;\n this.remainingTimeText = this.translateService.instant(translationBasePath + 'quizhasEnded');\n }\n } else {\n // remaining time is unknown => Set remaining seconds to 0, to keep 'Submit' button enabled\n this.remainingTimeSeconds = 0;\n this.remainingTimeText = '?';\n }\n }\n\n /**\n * Express the given timespan as humanized text\n *\n * @param remainingTimeSeconds {number} the amount of seconds to display\n * @return {string} humanized text for the given amount of seconds\n */\n relativeTimeText(remainingTimeSeconds: number) {\n if (remainingTimeSeconds > 210) {\n return Math.ceil(remainingTimeSeconds / 60) + ' min';\n } else if (remainingTimeSeconds > 59) {\n return Math.floor(remainingTimeSeconds / 60) + ' min ' + (remainingTimeSeconds % 60) + ' s';\n } else {\n return remainingTimeSeconds + ' s';\n }\n }\n\n ngOnDestroy() {\n clearInterval(this.interval);\n this.jhiWebsocketService.unsubscribe(this.websocketChannelForData);\n }\n\n getDataSets() {\n return this.datasets;\n }\n\n getParticipants() {\n return this.participants;\n }\n\n /**\n * load the new quizPointStatistic from the server if the Websocket has been notified\n *\n * @param {QuizPointStatistic} statistic: the new quizPointStatistic\n * from the server with the new Data.\n */\n loadNewData(statistic: QuizPointStatistic) {\n // if the Student finds a way to the Website\n // -> the Student will be send back to Courses\n if (!this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.router.navigate(['courses']);\n }\n this.quizPointStatistic = statistic;\n this.loadData();\n }\n\n /**\n * This functions loads the Quiz, which is necessary to build the Web-Template\n *\n * @param {QuizExercise} quizExercise: the quizExercise,\n * which the this quiz-point-statistic presents.\n */\n loadQuizSuccess(quizExercise: QuizExercise) {\n // if the Student finds a way to the Website\n // -> the Student will be send back to Courses\n if (!this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.router.navigate(['courses']);\n }\n this.quizExercise = quizExercise;\n this.quizExercise.adjustedDueDate = moment().add(this.quizExercise.remainingTime, 'seconds');\n this.waitingForQuizStart = !this.quizExercise.started;\n this.quizPointStatistic = this.quizExercise.quizPointStatistic!;\n this.maxScore = this.calculateMaxScore();\n\n this.loadData();\n }\n\n /**\n * calculate the maximal possible Score for the quiz\n *\n * @return (number): sum over the Scores of all questions\n */\n calculateMaxScore() {\n let result = 0;\n\n this.quizExercise.quizQuestions!.forEach((question) => {\n result = result + question.points!;\n });\n return result;\n }\n\n /**\n * load the Data from the Json-entity to the chart: myChart\n */\n loadData() {\n // reset old data\n this.label = [];\n this.backgroundColor = [];\n this.ratedData = [];\n this.unratedData = [];\n // set data based on the pointCounters\n this.order(this.quizPointStatistic.pointCounters!).forEach((pointCounter) => {\n this.label.push(pointCounter.points!.toString());\n this.ratedData.push(pointCounter.ratedCounter!);\n this.unratedData.push(pointCounter.unRatedCounter!);\n this.backgroundColor.push(blueColor);\n });\n\n this.labels = this.label;\n this.colors = this.backgroundColor.map((backgroundColor) => ({ backgroundColor }));\n\n // load data into the chart\n this.loadDataInDiagram();\n }\n\n /**\n * check if the rated or unrated\n * load the rated or unrated data into the diagram\n */\n loadDataInDiagram() {\n if (this.rated) {\n this.participants = this.quizPointStatistic.participantsRated!;\n this.data = this.ratedData;\n } else {\n // load the unrated data\n this.participants = this.quizPointStatistic.participantsUnrated!;\n this.data = this.unratedData;\n }\n\n this.datasets = [{ data: this.data, backgroundColor: this.colors.map((color) => color.backgroundColor as string) }];\n // recalculate the height of the chart because rated/unrated might have changed or new results might have appeared\n const height = calculateHeightOfChart(this);\n\n // add Axes-labels based on selected language\n const xLabel = this.translateService.instant('showStatistic.quizPointStatistic.xAxes');\n const yLabel = this.translateService.instant('showStatistic.quizPointStatistic.yAxes');\n this.options = createOptions(this, height, height / 5, xLabel, yLabel);\n if (this.chart) {\n this.chart.update(0);\n }\n }\n\n /**\n *\n * Recalculate the complete statistic on the server in case something went wrong with it\n *\n */\n recalculate() {\n this.quizExerciseService.recalculate(this.quizExercise.id!).subscribe((res) => {\n this.loadQuizSuccess(res.body!);\n });\n }\n\n /**\n * switch between showing and hiding the solution in the chart\n * 1. change the amount of participants\n * 2. change the bar-Data\n */\n switchRated() {\n this.rated = !this.rated;\n this.loadDataInDiagram();\n }\n\n /**\n * order the point cursors ascending\n */\n order(pointCursors: Array<PointCounter>) {\n // TODO: use sorting service\n return pointCursors.sort((a: PointCounter, b: PointCounter) => {\n if (a.points! < b.points!) {\n return -1;\n }\n if (a.points! > b.points!) {\n return 1;\n }\n // a must be equal to b\n return 0;\n });\n }\n}\n" }, { "alpha_fraction": 0.6742919683456421, "alphanum_fraction": 0.6759259104728699, "avg_line_length": 38.91304397583008, "blob_id": "9f6257d05094088913d01f3876366c73e927db20", "content_id": "6a3588aacc1f9b932d24a7e9ba9d17524f5865bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1836, "license_type": "permissive", "max_line_length": 118, "num_lines": 46, "path": "/src/test/javascript/spec/component/exam/manage/student-exams/student-exam-summary.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute } from '@angular/router';\nimport { MockDirective } from 'ng-mocks';\nimport { Course } from 'app/entities/course.model';\nimport { of } from 'rxjs';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport * as sinon from 'sinon';\nimport { Exam } from 'app/entities/exam.model';\nimport { StudentExamSummaryComponent } from 'app/exam/manage/student-exams/student-exam-summary.component';\nimport { ExamParticipationSummaryComponent } from 'app/exam/participate/summary/exam-participation-summary.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentExamSummaryComponent', () => {\n let fixture: ComponentFixture<StudentExamSummaryComponent>;\n let component: StudentExamSummaryComponent;\n\n const courseValue = { id: 1 } as Course;\n const examValue = { course: courseValue, id: 2 } as Exam;\n const studentExamValue = { exam: examValue, id: 3 } as StudentExam;\n\n beforeEach(() => {\n return TestBed.configureTestingModule({\n declarations: [StudentExamSummaryComponent, MockDirective(ExamParticipationSummaryComponent)],\n providers: [{ provide: ActivatedRoute, useValue: { data: of({ studentExam: studentExamValue }) } }],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(StudentExamSummaryComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n expect(component.studentExam).to.deep.equal(studentExamValue);\n });\n});\n" }, { "alpha_fraction": 0.7114955186843872, "alphanum_fraction": 0.7137276530265808, "avg_line_length": 26.15151596069336, "blob_id": "f034d1c2caa2b243138d982acb639532b8ef8005", "content_id": "4bcc904bbcea2e9f96281e1d13d9d0b5231f9889", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1792, "license_type": "permissive", "max_line_length": 153, "num_lines": 66, "path": "/src/main/java/de/tum/in/www1/artemis/domain/TeamAssignmentConfig.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport javax.persistence.*;\nimport javax.validation.constraints.Min;\nimport javax.validation.constraints.NotNull;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.validation.constraints.TeamAssignmentConfigConstraints;\n\n/**\n * A team assignment configuration.\n */\n@Entity\n@Table(name = \"team_assignment_config\")\n@TeamAssignmentConfigConstraints\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class TeamAssignmentConfig extends DomainObject {\n\n @OneToOne(mappedBy = \"teamAssignmentConfig\", fetch = FetchType.LAZY)\n @JsonIgnoreProperties(\"teamAssignmentConfig\")\n private Exercise exercise;\n\n @Min(1)\n @NotNull\n @Column(name = \"min_team_size\")\n private Integer minTeamSize;\n\n @Min(1)\n @Column(name = \"max_team_size\")\n private Integer maxTeamSize;\n\n public Exercise getExercise() {\n return exercise;\n }\n\n public void setExercise(Exercise exercise) {\n this.exercise = exercise;\n }\n\n public Integer getMinTeamSize() {\n return minTeamSize;\n }\n\n public void setMinTeamSize(Integer minTeamSize) {\n this.minTeamSize = minTeamSize;\n }\n\n public Integer getMaxTeamSize() {\n return maxTeamSize;\n }\n\n public void setMaxTeamSize(Integer maxTeamSize) {\n this.maxTeamSize = maxTeamSize;\n }\n\n @Override\n public String toString() {\n return \"TeamAssignmentConfig{\" + \"id=\" + getId() + \", minTeamSize='\" + getMinTeamSize() + \"'\" + \", maxTeamSize='\" + getMaxTeamSize() + \"'\" + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.68052738904953, "alphanum_fraction": 0.6818796396255493, "avg_line_length": 39.52054977416992, "blob_id": "e11cdaadad07ecb0ff5f301055e738e405cfa512", "content_id": "74e22e09609122a8202f0850f810bbc0b169f32d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2958, "license_type": "permissive", "max_line_length": 129, "num_lines": 73, "path": "/src/test/javascript/spec/component/text/manual-text-selection.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { TestBed, ComponentFixture } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ManualTextSelectionComponent } from 'app/exercises/text/shared/manual-text-selection/manual-text-selection.component';\nimport { SelectionRectangle, TextSelectEvent } from 'app/exercises/text/shared/text-select.directive';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ManualTextSelectionComponent', () => {\n let component: ManualTextSelectionComponent;\n let fixture: ComponentFixture<ManualTextSelectionComponent>;\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisConfirmIconModule],\n declarations: [ManualTextSelectionComponent],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents();\n });\n\n beforeEach(() => {\n fixture = TestBed.createComponent(ManualTextSelectionComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should select text and assess the text', () => {\n const rectangle = { left: 0, top: 0, width: 0, height: 0 } as SelectionRectangle;\n const event = { text: 'This is a text\\n another line', viewportRectangle: null, hostRectangle: null } as TextSelectEvent;\n\n component.disabled = true;\n\n // catch edge case\n component.didSelectSolutionText(event);\n\n component.disabled = false;\n\n component.didSelectSolutionText(event);\n\n expect(component.hostRectangle).to.be.undefined;\n expect(component.selectedText).to.be.undefined;\n\n event.hostRectangle = rectangle;\n\n component.didSelectSolutionText(event);\n\n expect(component.hostRectangle).to.deep.equal(rectangle);\n expect(component.selectedText).to.equal('This is a text<br> another line');\n\n const spy = sinon.spy(component.assess, 'emit');\n component.assessAction();\n\n expect(spy).to.have.been.calledOnce;\n expect(component.selectedText).to.be.undefined;\n expect(component.hostRectangle).to.be.undefined;\n });\n});\n" }, { "alpha_fraction": 0.6935203671455383, "alphanum_fraction": 0.6963753700256348, "avg_line_length": 49.03726577758789, "blob_id": "926f618046c20f4353cd6424e374d07fd32648ac", "content_id": "b7771d78ee606202553abac5ac029fbad99fdea8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8056, "license_type": "permissive", "max_line_length": 171, "num_lines": 161, "path": "/src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit-form.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { TranslateService } from '@ngx-translate/core';\nimport { AttachmentUnitFormComponent, AttachmentUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/attachment-unit-form/attachment-unit-form.component';\nimport { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { MockComponent, MockPipe, MockProviders } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('AttachmentUnitFormComponent', () => {\n const sandbox = sinon.createSandbox();\n let attachmentUnitFormComponentFixture: ComponentFixture<AttachmentUnitFormComponent>;\n let attachmentUnitFormComponent: AttachmentUnitFormComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ReactiveFormsModule, FormsModule],\n declarations: [AttachmentUnitFormComponent, MockPipe(ArtemisTranslatePipe), MockComponent(FormDateTimePickerComponent)],\n providers: [MockProviders(TranslateService)],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n attachmentUnitFormComponentFixture = TestBed.createComponent(AttachmentUnitFormComponent);\n attachmentUnitFormComponent = attachmentUnitFormComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n attachmentUnitFormComponentFixture.detectChanges();\n expect(attachmentUnitFormComponent).to.be.ok;\n });\n\n it('should correctly set form values in edit mode', () => {\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n\n attachmentUnitFormComponent.isEditMode = true;\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: 'test',\n description: 'lorem ipsum',\n releaseDate: moment({ years: 2010, months: 3, date: 5 }),\n version: 2,\n updateNotificationText: 'lorem ipsum',\n },\n fileProperties: {\n file: fakeBlob,\n fileName: 'lorem ipsum',\n },\n };\n attachmentUnitFormComponentFixture.detectChanges();\n\n attachmentUnitFormComponent.formData = formData;\n attachmentUnitFormComponent.ngOnChanges();\n\n expect(attachmentUnitFormComponent.nameControl?.value).to.equal(formData.formProperties.name);\n expect(attachmentUnitFormComponent.releaseDateControl?.value).to.equal(formData.formProperties.releaseDate);\n expect(attachmentUnitFormComponent.descriptionControl?.value).to.equal(formData.formProperties.description);\n expect(attachmentUnitFormComponent.versionControl?.value).to.equal(formData.formProperties.version);\n expect(attachmentUnitFormComponent.updateNotificationTextControl?.value).to.equal(formData.formProperties.updateNotificationText);\n expect(attachmentUnitFormComponent.fileName).to.equal(formData.fileProperties.fileName);\n expect(attachmentUnitFormComponent.file).to.equal(formData.fileProperties.file);\n });\n it('should submit valid form', () => {\n attachmentUnitFormComponentFixture.detectChanges();\n const exampleName = 'test';\n attachmentUnitFormComponent.nameControl!.setValue(exampleName);\n const exampleReleaseDate = moment({ years: 2010, months: 3, date: 5 });\n attachmentUnitFormComponent.releaseDateControl!.setValue(exampleReleaseDate);\n const exampleDescription = 'lorem ipsum';\n attachmentUnitFormComponent.descriptionControl!.setValue(exampleDescription);\n const exampleVersion = 42;\n attachmentUnitFormComponent.versionControl!.setValue(exampleVersion);\n const exampleUpdateNotificationText = 'updated';\n attachmentUnitFormComponent.updateNotificationTextControl!.setValue(exampleUpdateNotificationText);\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n attachmentUnitFormComponent.file = fakeBlob;\n const exampleFileName = 'lorem Ipsum';\n attachmentUnitFormComponent.fileName = exampleFileName;\n\n attachmentUnitFormComponentFixture.detectChanges();\n expect(attachmentUnitFormComponent.form.valid).to.be.true;\n\n const submitFormSpy = sinon.spy(attachmentUnitFormComponent, 'submitForm');\n const submitFormEventSpy = sinon.spy(attachmentUnitFormComponent.formSubmitted, 'emit');\n\n const submitButton = attachmentUnitFormComponentFixture.debugElement.nativeElement.querySelector('#submitButton');\n submitButton.click();\n\n expect(submitFormSpy).to.have.been.called;\n expect(submitFormEventSpy).to.have.been.calledWith({\n formProperties: {\n name: exampleName,\n description: exampleDescription,\n releaseDate: exampleReleaseDate,\n version: exampleVersion,\n updateNotificationText: exampleUpdateNotificationText,\n },\n fileProperties: {\n file: fakeBlob,\n fileName: exampleFileName,\n },\n });\n\n submitFormSpy.restore();\n submitFormEventSpy.restore();\n });\n it('should not submit a form when name is missing', () => {\n attachmentUnitFormComponentFixture.detectChanges();\n const exampleReleaseDate = moment({ years: 2010, months: 3, date: 5 });\n attachmentUnitFormComponent.releaseDateControl!.setValue(exampleReleaseDate);\n const exampleDescription = 'lorem ipsum';\n attachmentUnitFormComponent.descriptionControl!.setValue(exampleDescription);\n const exampleVersion = 42;\n attachmentUnitFormComponent.versionControl!.setValue(exampleVersion);\n const exampleUpdateNotificationText = 'updated';\n attachmentUnitFormComponent.updateNotificationTextControl!.setValue(exampleUpdateNotificationText);\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n attachmentUnitFormComponent.file = fakeBlob;\n const exampleFileName = 'lorem Ipsum';\n attachmentUnitFormComponent.fileName = exampleFileName;\n\n expect(attachmentUnitFormComponent.form.invalid).to.be.true;\n const submitFormSpy = sinon.spy(attachmentUnitFormComponent, 'submitForm');\n const submitFormEventSpy = sinon.spy(attachmentUnitFormComponent.formSubmitted, 'emit');\n\n const submitButton = attachmentUnitFormComponentFixture.debugElement.nativeElement.querySelector('#submitButton');\n submitButton.click();\n\n expect(submitFormSpy).to.not.have.been.called;\n expect(submitFormEventSpy).to.not.have.been.called;\n });\n\n it('calls on file change on changed file', () => {\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n const onFileChangeStub = sandbox.stub(attachmentUnitFormComponent, 'onFileChange');\n attachmentUnitFormComponentFixture.detectChanges();\n const fileInput = attachmentUnitFormComponentFixture.debugElement.nativeElement.querySelector('#fileInput');\n fileInput.dispatchEvent(new Event('change'));\n expect(onFileChangeStub).to.have.been.calledOnce;\n });\n\n it('sets file upload error correctly', () => {\n attachmentUnitFormComponentFixture.detectChanges();\n attachmentUnitFormComponent.setFileUploadError('lorem ipsum');\n expect(attachmentUnitFormComponent.fileUploadErrorMessage).to.equal('lorem ipsum');\n });\n});\n" }, { "alpha_fraction": 0.7691280841827393, "alphanum_fraction": 0.7744662165641785, "avg_line_length": 43.959999084472656, "blob_id": "a85cad2b322a1b73152380c56721b1890ee8c195", "content_id": "82ca998c5034c22175b8eb390a1491e3ecb45629", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2248, "license_type": "permissive", "max_line_length": 153, "num_lines": 50, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/PlagiarismResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.repository.PlagiarismComparisonRepository;\nimport de.tum.in.www1.artemis.service.plagiarism.PlagiarismService;\nimport de.tum.in.www1.artemis.web.rest.dto.PlagiarismComparisonStatusDTO;\n\n/**\n * REST controller for managing TextExercise.\n */\n@RestController\n@RequestMapping(\"/api\")\npublic class PlagiarismResource {\n\n private final Logger log = LoggerFactory.getLogger(PlagiarismResource.class);\n\n private final PlagiarismService plagiarismService;\n\n private final PlagiarismComparisonRepository plagiarismComparisonRepository;\n\n public PlagiarismResource(PlagiarismService plagiarismService, PlagiarismComparisonRepository plagiarismComparisonRepository) {\n this.plagiarismService = plagiarismService;\n this.plagiarismComparisonRepository = plagiarismComparisonRepository;\n }\n\n /**\n * PUT /plagiarism-comparisons/{comparisonId}/status\n * <p>\n * Update the status of the plagiarism comparison with the given ID.\n *\n * @param comparisonId ID of the plagiarism comparison to update the status of\n * @param statusDTO new status for the given comparison\n * @return The ResponseEntity with status 200 (Ok) or with status 400 (Bad Request) if the\n * parameters are invalid\n */\n @PutMapping(\"/plagiarism-comparisons/{comparisonId}/status\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> updatePlagiarismComparisonStatus(@PathVariable long comparisonId, @RequestBody PlagiarismComparisonStatusDTO statusDTO) {\n // TODO: check that the instructor has access to the corresponding course (add the exerciseId to the URL)\n log.debug(\"REST request to update the status of the plagiarism comparison with id: {}\", comparisonId);\n var comparison = plagiarismComparisonRepository.findByIdElseThrow(comparisonId);\n plagiarismService.updateStatusOfComparison(comparison, statusDTO.getStatus());\n return ResponseEntity.ok().body(null);\n }\n}\n" }, { "alpha_fraction": 0.6511827111244202, "alphanum_fraction": 0.6519319415092468, "avg_line_length": 49.50270080566406, "blob_id": "7824d692fa2bf382137cf3114bb4923a63ca162d", "content_id": "b37b5b741372b98496feaa13051be3e2bfd74518", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 18686, "license_type": "permissive", "max_line_length": 159, "num_lines": 370, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport { HttpResponse } from '@angular/common/http';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport { ActivatedRoute, UrlSegment } from '@angular/router';\nimport { of } from 'rxjs';\nimport { stub } from 'sinon';\nimport * as moment from 'moment';\n\nimport { ArtemisTestModule } from '../../test.module';\nimport { ProgrammingExerciseUpdateComponent } from 'app/exercises/programming/manage/update/programming-exercise-update.component';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { ProgrammingExercise, ProgrammingLanguage, ProjectType } from 'app/entities/programming-exercise.model';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Course } from 'app/entities/course.model';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { ExerciseGroupService } from 'app/exam/manage/exercise-groups/exercise-group.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport {\n ProgrammingLanguageFeature,\n ProgrammingLanguageFeatureService,\n} from 'app/exercises/programming/shared/service/programming-language-feature/programming-language-feature.service';\nimport { ArtemisProgrammingExerciseUpdateModule } from 'app/exercises/programming/manage/update/programming-exercise-update.module';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\n\ndescribe('ProgrammingExercise Management Update Component', () => {\n const courseId = 1;\n const course = { id: courseId } as Course;\n\n let comp: ProgrammingExerciseUpdateComponent;\n let fixture: ComponentFixture<ProgrammingExerciseUpdateComponent>;\n let debugElement: DebugElement;\n let programmingExerciseService: ProgrammingExerciseService;\n let courseService: CourseManagementService;\n let exerciseGroupService: ExerciseGroupService;\n let programmingExerciseFeatureService: ProgrammingLanguageFeatureService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, BrowserAnimationsModule, ArtemisProgrammingExerciseUpdateModule, FormDateTimePickerModule],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: new MockActivatedRoute() },\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(ProgrammingExerciseUpdateComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n programmingExerciseService = debugElement.injector.get(ProgrammingExerciseService);\n courseService = debugElement.injector.get(CourseManagementService);\n exerciseGroupService = debugElement.injector.get(ExerciseGroupService);\n programmingExerciseFeatureService = debugElement.injector.get(ProgrammingLanguageFeatureService);\n });\n\n describe('save', () => {\n it('Should call update service on save for existing entity', fakeAsync(() => {\n // GIVEN\n const entity = new ProgrammingExercise(new Course(), undefined);\n entity.id = 123;\n entity.releaseDate = moment(); // We will get a warning if we do not set a release date\n spyOn(programmingExerciseService, 'update').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.programmingExercise = entity;\n comp.programmingExercise.course = course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(programmingExerciseService.update).toHaveBeenCalledWith(entity, {});\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should call create service on save for new entity', fakeAsync(() => {\n // GIVEN\n const entity = new ProgrammingExercise(undefined, undefined);\n entity.releaseDate = moment(); // We will get a warning if we do not set a release date\n spyOn(programmingExerciseService, 'automaticSetup').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.programmingExercise = entity;\n comp.programmingExercise.course = course;\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(programmingExerciseService.automaticSetup).toHaveBeenCalledWith(entity);\n expect(comp.isSaving).toEqual(false);\n }));\n\n it('Should trim the exercise title before saving', fakeAsync(() => {\n // GIVEN\n const entity = new ProgrammingExercise(undefined, undefined);\n entity.releaseDate = moment(); // We will get a warning if we do not set a release date\n entity.title = 'My Exercise ';\n spyOn(programmingExerciseService, 'automaticSetup').and.returnValue(of(new HttpResponse({ body: entity })));\n comp.programmingExercise = entity;\n comp.programmingExercise.course = course;\n\n // WHEN\n comp.save();\n tick(); // simulate async\n\n // THEN\n expect(programmingExerciseService.automaticSetup).toHaveBeenCalledWith(entity);\n expect(entity.title).toEqual('My Exercise');\n }));\n });\n\n describe('exam mode', () => {\n const examId = 1;\n const groupId = 1;\n const exerciseGroup = new ExerciseGroup();\n exerciseGroup.id = groupId;\n const expectedExamProgrammingExercise = new ProgrammingExercise(undefined, undefined);\n expectedExamProgrammingExercise.exerciseGroup = exerciseGroup;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId, examId, groupId });\n route.url = of([{ path: 'new' } as UrlSegment]);\n route.data = of({ programmingExercise: new ProgrammingExercise(undefined, undefined) });\n });\n\n it('Should be in exam mode after onInit', fakeAsync(() => {\n // GIVEN\n spyOn(exerciseGroupService, 'find').and.returnValue(of(new HttpResponse({ body: exerciseGroup })));\n spyOn(programmingExerciseFeatureService, 'getProgrammingLanguageFeature').and.returnValue(getProgrammingLanguageFeature(ProgrammingLanguage.JAVA));\n\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n\n // THEN\n expect(exerciseGroupService.find).toHaveBeenCalledWith(courseId, examId, groupId);\n expect(comp.isSaving).toEqual(false);\n expect(comp.programmingExercise).toEqual(expectedExamProgrammingExercise);\n expect(comp.isExamMode).toBeTruthy();\n }));\n });\n\n describe('course mode', () => {\n const expectedProgrammingExercise = new ProgrammingExercise(undefined, undefined);\n expectedProgrammingExercise.course = course;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId });\n route.url = of([{ path: 'new' } as UrlSegment]);\n route.data = of({ programmingExercise: new ProgrammingExercise(undefined, undefined) });\n });\n\n it('Should not be in exam mode after onInit', fakeAsync(() => {\n // GIVEN\n spyOn(courseService, 'find').and.returnValue(of(new HttpResponse({ body: course })));\n spyOn(programmingExerciseFeatureService, 'getProgrammingLanguageFeature').and.returnValue(getProgrammingLanguageFeature(ProgrammingLanguage.JAVA));\n\n // WHEN\n comp.ngOnInit();\n tick(); // simulate async\n\n // THEN\n expect(courseService.find).toHaveBeenCalledWith(courseId);\n expect(comp.isSaving).toEqual(false);\n expect(comp.programmingExercise).toEqual(expectedProgrammingExercise);\n expect(comp.isExamMode).toBeFalsy();\n }));\n });\n\n describe('programming language change and features', () => {\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId });\n route.url = of([{ path: 'new' } as UrlSegment]);\n route.data = of({ programmingExercise: new ProgrammingExercise(undefined, undefined) });\n spyOn(courseService, 'find').and.returnValue(of(new HttpResponse({ body: course })));\n spyOn(programmingExerciseFeatureService, 'supportsProgrammingLanguage').and.returnValue(true);\n const getFeaturesStub = stub(programmingExerciseFeatureService, 'getProgrammingLanguageFeature');\n getFeaturesStub.withArgs(ProgrammingLanguage.JAVA).returns(getProgrammingLanguageFeature(ProgrammingLanguage.JAVA));\n getFeaturesStub.withArgs(ProgrammingLanguage.HASKELL).returns(getProgrammingLanguageFeature(ProgrammingLanguage.HASKELL));\n getFeaturesStub.withArgs(ProgrammingLanguage.SWIFT).returns(getProgrammingLanguageFeature(ProgrammingLanguage.SWIFT));\n });\n\n it('Should reset sca settings if new programming language does not support sca', fakeAsync(() => {\n comp.ngOnInit();\n fixture.detectChanges();\n tick();\n\n // Activate sca\n let scaCheckbox = fixture.nativeElement.querySelector('#field_staticCodeAnalysisEnabled');\n scaCheckbox.click();\n scaCheckbox.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n tick();\n\n // Set a max penalty\n const maxPenaltyInput = fixture.nativeElement.querySelector('#field_maxPenalty');\n maxPenaltyInput.value = 50;\n maxPenaltyInput.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n tick();\n\n expect(scaCheckbox.checked).toBeTruthy();\n expect(comp.programmingExercise.staticCodeAnalysisEnabled).toBeTruthy();\n expect(comp.programmingExercise.maxStaticCodeAnalysisPenalty).toBe(50);\n\n // Switch to another programming language not supporting sca\n const languageInput = fixture.nativeElement.querySelector('#field_programmingLanguage');\n languageInput.value = ProgrammingLanguage.HASKELL;\n languageInput.dispatchEvent(new Event('change'));\n fixture.detectChanges();\n tick();\n scaCheckbox = fixture.nativeElement.querySelector('#field_staticCodeAnalysisEnabled');\n\n expect(scaCheckbox).toBeFalsy();\n expect(comp.programmingExercise.staticCodeAnalysisEnabled).toBeFalsy();\n expect(comp.programmingExercise.maxStaticCodeAnalysisPenalty).toBeUndefined();\n expect(comp.programmingExercise.programmingLanguage).toBe(ProgrammingLanguage.HASKELL);\n }));\n\n it('Should activate SCA for Swift', fakeAsync(() => {\n // WHEN\n fixture.detectChanges();\n tick();\n comp.onProgrammingLanguageChange(ProgrammingLanguage.SWIFT);\n\n // THEN\n expect(courseService.find).toHaveBeenCalledWith(courseId);\n expect(comp.selectedProgrammingLanguage).toEqual(ProgrammingLanguage.SWIFT);\n expect(comp.staticCodeAnalysisAllowed).toEqual(true);\n expect(comp.packageNamePattern).toEqual(comp.packageNamePatternForSwift);\n }));\n\n it('Should activate SCA for Java', fakeAsync(() => {\n // WHEN\n fixture.detectChanges();\n tick();\n comp.onProgrammingLanguageChange(ProgrammingLanguage.JAVA);\n\n // THEN\n expect(comp.selectedProgrammingLanguage).toEqual(ProgrammingLanguage.JAVA);\n expect(comp.staticCodeAnalysisAllowed).toEqual(true);\n expect(comp.packageNamePattern).toEqual(comp.packageNamePatternForJavaKotlin);\n }));\n });\n\n describe('import with static code analysis', () => {\n let route: ActivatedRoute;\n\n beforeEach(() => {\n spyOn(courseService, 'find').and.returnValue(of(new HttpResponse({ body: course })));\n spyOn(programmingExerciseFeatureService, 'getProgrammingLanguageFeature').and.returnValue(getProgrammingLanguageFeature(ProgrammingLanguage.JAVA));\n\n route = TestBed.inject(ActivatedRoute);\n route.params = of({ courseId });\n route.url = of([{ path: 'import' } as UrlSegment]);\n });\n\n it.each([\n [true, 80],\n [false, undefined],\n ])(\n 'Should activate recreate build plans and update template when sca changes',\n fakeAsync((scaActivatedOriginal: boolean, maxPenalty: number | undefined) => {\n const newMaxPenalty = 50;\n const programmingExercise = new ProgrammingExercise(undefined, undefined);\n programmingExercise.programmingLanguage = ProgrammingLanguage.JAVA;\n programmingExercise.staticCodeAnalysisEnabled = scaActivatedOriginal;\n programmingExercise.maxStaticCodeAnalysisPenalty = maxPenalty;\n route.data = of({ programmingExercise });\n comp.ngOnInit();\n fixture.detectChanges();\n tick();\n\n let scaCheckbox = fixture.nativeElement.querySelector('#field_staticCodeAnalysisEnabled');\n let maxPenaltyInput = fixture.nativeElement.querySelector('#field_maxPenalty');\n const recreateBuildPlanCheckbox = fixture.nativeElement.querySelector('#field_recreateBuildPlans');\n const updateTemplateCheckbox = fixture.nativeElement.querySelector('#field_updateTemplateFiles');\n\n expect(comp.isImport).toBeTruthy();\n expect(comp.originalStaticCodeAnalysisEnabled).toBe(scaActivatedOriginal);\n expect(comp.programmingExercise.staticCodeAnalysisEnabled).toBe(scaActivatedOriginal);\n expect(comp.programmingExercise.maxStaticCodeAnalysisPenalty).toBe(maxPenalty);\n expect(scaCheckbox.checked).toBe(scaActivatedOriginal);\n expect(!!maxPenaltyInput).toBe(scaActivatedOriginal);\n expect(recreateBuildPlanCheckbox.checked).toBeFalsy();\n expect(updateTemplateCheckbox.checked).toBeFalsy();\n expect(comp.programmingExercise).toEqual(programmingExercise);\n expect(courseService.find).toHaveBeenCalledWith(courseId);\n\n // Activate SCA and set a max penalty\n scaCheckbox.click();\n scaCheckbox.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n tick();\n scaCheckbox = fixture.nativeElement.querySelector('#field_staticCodeAnalysisEnabled');\n\n // SCA penalty field disappears or appears after the sca checkbox click\n maxPenaltyInput = fixture.nativeElement.querySelector('#field_maxPenalty');\n if (scaActivatedOriginal) {\n expect(maxPenaltyInput).toBeFalsy();\n } else {\n maxPenaltyInput.value = newMaxPenalty;\n maxPenaltyInput.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n tick();\n }\n\n // Recreate build plan and template update should be automatically selected\n expect(scaCheckbox.checked).toBe(!scaActivatedOriginal);\n expect(comp.programmingExercise.staticCodeAnalysisEnabled).toBe(!scaActivatedOriginal);\n expect(comp.programmingExercise.maxStaticCodeAnalysisPenalty).toEqual(scaActivatedOriginal ? undefined : newMaxPenalty);\n expect(comp.recreateBuildPlans).toBeTruthy();\n expect(comp.updateTemplate).toBeTruthy();\n\n // Deactivate recreation of build plans\n recreateBuildPlanCheckbox.click();\n recreateBuildPlanCheckbox.dispatchEvent(new Event('input'));\n fixture.detectChanges();\n tick();\n\n // SCA should revert to the state of the original exercise, maxPenalty will revert to undefined\n expect(comp.programmingExercise.staticCodeAnalysisEnabled).toEqual(comp.originalStaticCodeAnalysisEnabled);\n expect(comp.programmingExercise.maxStaticCodeAnalysisPenalty).toBeUndefined();\n }),\n );\n });\n});\n\nconst getProgrammingLanguageFeature = (programmingLanguage: ProgrammingLanguage) => {\n switch (programmingLanguage) {\n case ProgrammingLanguage.SWIFT:\n return {\n programmingLanguage: ProgrammingLanguage.SWIFT,\n sequentialTestRuns: false,\n staticCodeAnalysis: true,\n plagiarismCheckSupported: false,\n packageNameRequired: true,\n checkoutSolutionRepositoryAllowed: false,\n projectTypes: [],\n } as ProgrammingLanguageFeature;\n case ProgrammingLanguage.JAVA:\n return {\n programmingLanguage: ProgrammingLanguage.JAVA,\n sequentialTestRuns: true,\n staticCodeAnalysis: true,\n plagiarismCheckSupported: true,\n packageNameRequired: true,\n checkoutSolutionRepositoryAllowed: true,\n projectTypes: [ProjectType.ECLIPSE, ProjectType.MAVEN],\n } as ProgrammingLanguageFeature;\n case ProgrammingLanguage.HASKELL:\n return {\n programmingLanguage: ProgrammingLanguage.HASKELL,\n sequentialTestRuns: false,\n staticCodeAnalysis: false,\n plagiarismCheckSupported: false,\n packageNameRequired: false,\n checkoutSolutionRepositoryAllowed: true,\n projectTypes: [],\n } as ProgrammingLanguageFeature;\n default:\n throw new Error();\n }\n};\n" }, { "alpha_fraction": 0.6344950795173645, "alphanum_fraction": 0.6407506465911865, "avg_line_length": 32.402984619140625, "blob_id": "a781bc3cd3bfc8dac36097ce898ab5e13a5e2838", "content_id": "50d46d5c86cc7f1af6f8a77dd57491f65bfd52f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2238, "license_type": "permissive", "max_line_length": 94, "num_lines": 67, "path": "/src/test/javascript/spec/component/overview/result-history/result-history.component-spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { Result } from 'app/entities/result.model';\nimport * as sinonChai from 'sinon-chai';\nimport { ResultHistoryComponent } from 'app/overview/result-history/result-history.component';\nimport { MockModule } from 'ng-mocks';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport * as sinon from 'sinon';\nimport * as chai from 'chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ResultHistoryComponent', () => {\n let component: ResultHistoryComponent;\n let fixture: ComponentFixture<ResultHistoryComponent>;\n let result: Result;\n\n beforeEach(() => {\n result = new Result();\n\n return TestBed.configureTestingModule({\n imports: [MockModule(ArtemisSharedModule)],\n declarations: [ResultHistoryComponent],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ResultHistoryComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should return the right values for result score', () => {\n fixture.detectChanges();\n result.score = 85;\n expect(component.resultIcon(result)).to.equal('check');\n expect(component.resultClass(result)).to.equal('success');\n\n result.score = 50;\n expect(component.resultIcon(result)).to.equal('times');\n expect(component.resultClass(result)).to.equal('warning');\n\n result.score = 30;\n expect(component.resultClass(result)).to.equal('danger');\n });\n\n it('should test absolute result', () => {\n fixture.detectChanges();\n\n expect(component.absoluteResult(result)).to.equal(0);\n\n result.resultString = 'failed';\n expect(component.absoluteResult(result)).to.equal(null);\n\n result.resultString = 'passed';\n expect(component.absoluteResult(result)).to.equal(null);\n\n result.resultString = 'no_right_value';\n expect(component.absoluteResult(result)).to.equal(0);\n\n result.resultString = '100 points';\n expect(component.absoluteResult(result)).to.equal(100);\n });\n});\n" }, { "alpha_fraction": 0.69591224193573, "alphanum_fraction": 0.6979062557220459, "avg_line_length": 24.075000762939453, "blob_id": "4c6f900967114e3573c778f4c5c8494bb0bf2dc8", "content_id": "1991eea844738ffd754cc972f24b91ef90b72647", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1003, "license_type": "permissive", "max_line_length": 80, "num_lines": 40, "path": "/src/main/java/de/tum/in/www1/artemis/domain/lecture/ExerciseUnit.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.lecture;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\n\n@Entity\n@DiscriminatorValue(\"E\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ExerciseUnit extends LectureUnit {\n\n // Note: Name and Release Date will always be taken from associated exercise\n @ManyToOne\n @JoinColumn(name = \"exercise_id\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Exercise exercise;\n\n public Exercise getExercise() {\n return exercise;\n }\n\n public void setExercise(Exercise exercise) {\n this.exercise = exercise;\n }\n\n @Override\n public boolean isVisibleToStudents() {\n if (exercise == null) {\n return true;\n }\n else {\n return exercise.isVisibleToStudents();\n }\n }\n}\n" }, { "alpha_fraction": 0.605832576751709, "alphanum_fraction": 0.61696457862854, "avg_line_length": 38.37036895751953, "blob_id": "0805493cd5e368978b0e0bbe91a6334bc3935bb0", "content_id": "f1dd7b181d46ceddfb5a074dc20f9e3a2981ac50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6378, "license_type": "permissive", "max_line_length": 138, "num_lines": 162, "path": "/src/test/javascript/spec/component/text-result/text-result.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { MockHasAnyAuthorityDirective } from '../../helpers/mocks/directive/mock-has-any-authority.directive';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { TextResultComponent } from 'app/exercises/text/participate/text-result/text-result.component';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { Result } from 'app/entities/result.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { TextResultBlock } from 'app/exercises/text/participate/text-result/text-result-block';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('TextResultComponent', () => {\n let fixture: ComponentFixture<TextResultComponent>;\n let component: TextResultComponent;\n\n const feedbacks = [\n {\n id: 1,\n detailText: 'feedback1',\n credits: 1.5,\n reference: 'ed462aaf735fe740a260660cbbbfbcc0ee66f98f',\n } as Feedback,\n {\n id: 3,\n detailText: 'feedback3',\n credits: 1,\n reference: 'exercise',\n } as Feedback,\n {\n id: 2,\n detailText: 'feedback2',\n credits: 0,\n reference: 'ed462aaf735fe740a260660cbcbfbcc0ee66f98a',\n } as Feedback,\n ];\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [TextResultComponent, MockDirective(MockHasAnyAuthorityDirective), MockPipe(ArtemisTranslatePipe)],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(TextResultComponent);\n component = fixture.componentInstance;\n });\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should convert text to result blocks', () => {\n const result = new Result();\n const submission = new TextSubmission();\n submission.text = 'submission text for a text exercise';\n const blocks = [\n {\n id: 'ed462aaf735fe740a260660cbbbfbcc0ee66f98f',\n text: 'submission',\n startIndex: 0,\n endIndex: 10,\n } as TextBlock,\n {\n id: 'ed462aaf735fe740a260660cbcbfbcc0ee66f98a',\n text: ' text',\n startIndex: 10,\n endIndex: 15,\n } as TextBlock,\n {\n id: 'ed462aaf735fe740a260660cbbbfbcc0ee66f98GGG',\n text: ' for a',\n startIndex: 15,\n endIndex: 21,\n } as TextBlock,\n {\n id: 'ed462aaf735fe740a260660cbbbfbcc0ee66f98GGH',\n text: ' exercise',\n startIndex: 21,\n endIndex: 29,\n } as TextBlock,\n ];\n submission.blocks = blocks;\n result.submission = submission;\n result.feedbacks = feedbacks;\n\n component.result = result;\n\n expect(component.textResults.length).to.equal(4);\n });\n\n it('should repeat steps for each credit', () => {\n const textBlock = new TextBlock();\n textBlock.text = 'this is a text block';\n const textResultBlock = new TextResultBlock(textBlock, feedbacks[0]);\n\n expect(component.repeatForEachCredit(textResultBlock)).to.deep.equal([1, 1]);\n });\n\n it('should translate credits', () => {\n const textBlock = new TextBlock();\n textBlock.text = 'this is a text block';\n let textResultBlock = new TextResultBlock(textBlock, feedbacks[0]);\n\n expect(component.creditsTranslationForTextResultBlock(textResultBlock)).to.equal('artemisApp.textAssessment.detail.credits.many');\n\n textResultBlock = new TextResultBlock(textBlock, feedbacks[1]);\n\n expect(component.creditsTranslationForTextResultBlock(textResultBlock)).to.equal('artemisApp.textAssessment.detail.credits.one');\n });\n\n it('should test result block methods', () => {\n const textBlock = new TextBlock();\n textBlock.text = 'this is a text block';\n textBlock.startIndex = 0;\n textBlock.endIndex = 5;\n let textResultBlock = new TextResultBlock(textBlock, feedbacks[0]);\n\n expect(textResultBlock.length).to.equal(5);\n expect(textResultBlock.cssClass).to.equal('text-with-feedback positive-feedback');\n expect(textResultBlock.icon).to.equal('check');\n expect(textResultBlock.iconCssClass).to.equal('feedback-icon positive-feedback');\n expect(textResultBlock.feedbackCssClass).to.equal('alert alert-success');\n\n textResultBlock = new TextResultBlock(textBlock, feedbacks[2]);\n\n expect(textResultBlock.cssClass).to.equal('text-with-feedback neutral-feedback');\n expect(textResultBlock.icon).to.equal('dot');\n expect(textResultBlock.iconCssClass).to.equal('feedback-icon neutral-feedback');\n expect(textResultBlock.feedbackCssClass).to.equal('alert alert-secondary');\n\n const feedback = {\n id: 3,\n detailText: 'feedback5',\n credits: -1,\n reference: 'exercise',\n } as Feedback;\n\n textResultBlock = new TextResultBlock(textBlock, feedback);\n\n expect(textResultBlock.cssClass).to.equal('text-with-feedback negative-feedback');\n expect(textResultBlock.icon).to.equal('times');\n expect(textResultBlock.iconCssClass).to.equal('feedback-icon negative-feedback');\n expect(textResultBlock.feedbackCssClass).to.equal('alert alert-danger');\n });\n});\n" }, { "alpha_fraction": 0.705612301826477, "alphanum_fraction": 0.7071883678436279, "avg_line_length": 53.24906921386719, "blob_id": "c18bc857bab428f12c471497a21932f315c336bf", "content_id": "f75a4d58f34056f46be2795f072e686ee39ae7ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14593, "license_type": "permissive", "max_line_length": 154, "num_lines": 269, "path": "/src/test/javascript/spec/component/overview/exercise-details/course-exercise-details.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { Directive, HostListener, Input } from '@angular/core';\nimport { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ActivatedRoute, Router, RouterOutlet } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ComplaintInteractionsComponent } from 'app/complaints/complaint-interactions.component';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { CourseExerciseSubmissionResultSimulationService } from 'app/course/manage/course-exercise-submission-result-simulation.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { Exercise, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport { Participation, ParticipationType } from 'app/entities/participation/participation.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { TeamAssignmentPayload } from 'app/entities/team.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { ProgrammingExerciseSimulationService } from 'app/exercises/programming/manage/services/programming-exercise-simulation.service';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ProgrammingExerciseInstructionComponent } from 'app/exercises/programming/shared/instructions-render/programming-exercise-instruction.component';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { BuildPlanButtonDirective } from 'app/exercises/programming/shared/utils/build-plan-button.directive';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { HeaderExercisePageWithDetailsComponent } from 'app/exercises/shared/exercise-headers/header-exercise-page-with-details.component';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { ParticipationService } from 'app/exercises/shared/participation/participation.service';\nimport { RatingComponent } from 'app/exercises/shared/rating/rating.component';\nimport { ResultComponent } from 'app/exercises/shared/result/result.component';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { CourseExerciseDetailsComponent } from 'app/overview/exercise-details/course-exercise-details.component';\nimport { ExerciseDetailsStudentActionsComponent } from 'app/overview/exercise-details/exercise-details-student-actions.component';\nimport { ProgrammingExerciseStudentIdeActionsComponent } from 'app/overview/exercise-details/programming-exercise-student-ide-actions.component';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { ResultHistoryComponent } from 'app/overview/result-history/result-history.component';\nimport { SubmissionResultStatusComponent } from 'app/overview/submission-result-status.component';\nimport { ExerciseActionButtonComponent } from 'app/shared/components/exercise-action-button.component';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { OrionFilterDirective } from 'app/shared/orion/orion-filter.directive';\nimport { ArtemisTimeAgoPipe } from 'app/shared/pipes/artemis-time-ago.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport * as chai from 'chai';\nimport { cloneDeep } from 'lodash';\nimport * as moment from 'moment';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { BehaviorSubject, of } from 'rxjs';\nimport { restore, SinonStub, stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { MockParticipationWebsocketService } from '../../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockProfileService } from '../../../helpers/mocks/service/mock-profile.service';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Directive({\n // tslint:disable-next-line:directive-selector\n selector: '[routerLink]',\n})\n// tslint:disable-next-line:directive-class-suffix\nclass RouterLinkSpy {\n @Input()\n routerLink = '';\n\n constructor(private router: Router) {}\n\n @HostListener('click')\n onClick() {\n this.router.navigateByUrl(this.routerLink);\n }\n}\n\ndescribe('CourseExerciseDetailsComponent', () => {\n let comp: CourseExerciseDetailsComponent;\n let fixture: ComponentFixture<CourseExerciseDetailsComponent>;\n let profileService: ProfileService;\n let exerciseService: ExerciseService;\n let teamService: TeamService;\n let participationService: ParticipationService;\n let participationWebsocketService: ParticipationWebsocketService;\n let getProfileInfoStub: SinonStub;\n let getExerciseDetailsStub: SinonStub;\n let getTeamPayloadStub: SinonStub;\n let mergeStudentParticipationStub: SinonStub;\n let subscribeForParticipationChangesStub: SinonStub;\n const exercise = ({ id: 42, type: ExerciseType.TEXT, studentParticipations: [] } as unknown) as Exercise;\n const route = { params: of({ courseId: 1, exerciseId: exercise.id }), queryParams: of({ welcome: '' }) };\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisSharedModule],\n declarations: [\n CourseExerciseDetailsComponent,\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisTimeAgoPipe),\n MockPipe(HtmlForMarkdownPipe),\n MockDirective(OrionFilterDirective),\n MockDirective(BuildPlanButtonDirective),\n MockDirective(RouterOutlet),\n MockComponent(HeaderExercisePageWithDetailsComponent),\n MockComponent(ProgrammingExerciseStudentIdeActionsComponent),\n MockComponent(ExerciseDetailsStudentActionsComponent),\n MockComponent(SubmissionResultStatusComponent),\n MockComponent(ExerciseActionButtonComponent),\n MockComponent(ProgrammingExerciseInstructionComponent),\n MockComponent(ResultHistoryComponent),\n MockComponent(ResultComponent),\n MockComponent(ComplaintInteractionsComponent),\n MockComponent(RatingComponent),\n RouterLinkSpy,\n ],\n providers: [\n { provide: ActivatedRoute, useValue: route },\n { provide: ProfileService, useClass: MockProfileService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n MockProvider(ExerciseService),\n MockProvider(CourseManagementService),\n MockProvider(JhiWebsocketService),\n MockProvider(CourseScoreCalculationService),\n MockProvider(ParticipationService),\n MockProvider(SourceTreeService),\n MockProvider(GuidedTourService),\n MockProvider(CourseExerciseSubmissionResultSimulationService),\n MockProvider(ProgrammingExerciseSimulationService),\n MockProvider(TeamService),\n MockProvider(QuizExerciseService),\n MockProvider(ProgrammingSubmissionService),\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseExerciseDetailsComponent);\n comp = fixture.componentInstance;\n\n // stub profileService\n profileService = fixture.debugElement.injector.get(ProfileService);\n getProfileInfoStub = stub(profileService, 'getProfileInfo');\n const profileInfo = { inProduction: false } as ProfileInfo;\n const profileInfoSubject = new BehaviorSubject<ProfileInfo | null>(profileInfo);\n getProfileInfoStub.returns(profileInfoSubject);\n\n // stub exerciseService\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n getExerciseDetailsStub = stub(exerciseService, 'getExerciseDetails');\n getExerciseDetailsStub.returns(of({ body: exercise }));\n\n // stub teamService, needed for team assignment\n teamService = fixture.debugElement.injector.get(TeamService);\n getTeamPayloadStub = stub(teamService, 'teamAssignmentUpdates');\n const teamAssignmentPayload = { exerciseId: 2, teamId: 2, studentParticipations: [] } as TeamAssignmentPayload;\n getTeamPayloadStub.get(() => Promise.resolve(of(teamAssignmentPayload)));\n\n // stub participationService, needed for team assignment\n participationService = fixture.debugElement.injector.get(ParticipationService);\n mergeStudentParticipationStub = stub(participationService, 'mergeStudentParticipations');\n\n // stub participationService, needed for team assignment\n participationWebsocketService = fixture.debugElement.injector.get(ParticipationWebsocketService);\n subscribeForParticipationChangesStub = stub(participationWebsocketService, 'subscribeForParticipationChanges');\n subscribeForParticipationChangesStub.returns(new BehaviorSubject<Participation | undefined>(undefined));\n });\n }));\n\n afterEach(() => {\n restore();\n });\n\n it('should initialize', fakeAsync(() => {\n fixture.detectChanges();\n tick(500);\n expect(comp).to.be.ok;\n expect(comp.showWelcomeAlert).to.be.true;\n expect(comp.inProductionEnvironment).to.be.false;\n expect(comp.courseId).to.equal(1);\n expect(comp.exercise).to.deep.equal(exercise);\n expect(comp.hasMoreResults).to.be.false;\n }));\n\n it('should have student participations', fakeAsync(() => {\n const studentParticipation = new StudentParticipation();\n studentParticipation.student = new User(99);\n studentParticipation.submissions = [new TextSubmission()];\n studentParticipation.type = ParticipationType.STUDENT;\n const result = new Result();\n result.id = 1;\n result.completionDate = moment();\n studentParticipation.results = [result];\n studentParticipation.exercise = exercise;\n\n const exerciseDetail = { ...exercise, studentParticipations: [studentParticipation] };\n const exerciseDetailReponse = of({ body: exerciseDetail });\n\n // return initial participation for websocketService\n stub(participationWebsocketService, 'getParticipationForExercise').returns(studentParticipation);\n\n mergeStudentParticipationStub.returns(studentParticipation);\n const changedParticipation = cloneDeep(studentParticipation);\n const changedResult = { ...result, id: 2 };\n changedParticipation.results = [changedResult];\n subscribeForParticipationChangesStub.returns(new BehaviorSubject<Participation | undefined>(changedParticipation));\n\n fixture.detectChanges();\n tick(500);\n expect(comp).to.be.ok;\n\n // override stub to return exercise with participation\n getExerciseDetailsStub.returns(exerciseDetailReponse);\n comp.loadExercise();\n fixture.detectChanges();\n expect(comp.courseId).to.equal(1);\n expect(comp.studentParticipation?.exercise?.id).to.equal(exerciseDetail.id);\n expect(comp.exercise!.studentParticipations![0].results![0]).to.deep.equal(changedResult);\n expect(comp.hasMoreResults).to.be.false;\n expect(comp.exerciseRatedBadge(result)).to.equal('badge-info');\n\n // has correct router link\n expect(comp.exerciseRouterLink).to.equal(`/course-management/1/text-exercises/42/assessment`);\n }));\n\n it('should not allow to publish a build plan for text exercises', () => {\n comp.exercise = { ...exercise };\n expect(comp.publishBuildPlanUrl()).to.be.undefined;\n expect(comp.projectKey()).to.be.undefined;\n expect(comp.buildPlanId(new StudentParticipation())).to.be.undefined;\n });\n\n it('should not be a quiz exercise', () => {\n comp.exercise = { ...exercise };\n expect(comp.quizExerciseStatus).to.be.undefined;\n });\n\n it('should simulate a submission', () => {\n const courseExerciseSubmissionResultSimulationService = fixture.debugElement.injector.get(CourseExerciseSubmissionResultSimulationService);\n stub(courseExerciseSubmissionResultSimulationService, 'simulateSubmission').returns(\n of(\n new HttpResponse({\n body: new ProgrammingSubmission(),\n }),\n ),\n );\n comp.simulateSubmission();\n\n expect(comp.wasSubmissionSimulated).to.be.true;\n });\n\n it('should simulate a result', () => {\n comp.exercise = { id: 2 } as Exercise;\n const courseExerciseSubmissionResultSimulationService = fixture.debugElement.injector.get(CourseExerciseSubmissionResultSimulationService);\n stub(courseExerciseSubmissionResultSimulationService, 'simulateResult').returns(\n of(\n new HttpResponse({\n body: new Result(),\n }),\n ),\n );\n comp.simulateResult();\n\n expect(comp.wasSubmissionSimulated).to.be.false;\n expect(comp.exercise?.participationStatus).to.equal(ParticipationStatus.EXERCISE_SUBMITTED);\n });\n});\n" }, { "alpha_fraction": 0.6454625725746155, "alphanum_fraction": 0.6497418880462646, "avg_line_length": 48.736488342285156, "blob_id": "b2519323885a63d36959a303639ea9f0d1f1449e", "content_id": "fdf9559449bcb4ac1a69b82f4f7c3b6fa140060a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 29444, "license_type": "permissive", "max_line_length": 178, "num_lines": 592, "path": "/src/test/javascript/spec/component/exam/manage/student-exams/student-exams.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ActivatedRoute, convertToParamMap, Params } from '@angular/router';\nimport { StudentExamsComponent } from 'app/exam/manage/student-exams/student-exams.component';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { MockComponent, MockDirective, MockPipe, MockProvider, MockModule } from 'ng-mocks';\nimport { StudentExamService } from 'app/exam/manage/student-exams/student-exam.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { StudentExamStatusComponent } from 'app/exam/manage/student-exams/student-exam-status.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { FontAwesomeTestingModule } from '@fortawesome/angular-fontawesome/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ArtemisDurationFromSecondsPipe } from 'app/shared/pipes/artemis-duration-from-seconds.pipe';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { MockLocalStorageService } from '../../../../helpers/mocks/service/mock-local-storage.service';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { Course } from 'app/entities/course.model';\nimport { of, throwError } from 'rxjs';\nimport { HttpResponse, HttpErrorResponse } from '@angular/common/http';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport * as sinon from 'sinon';\nimport { Exam } from 'app/entities/exam.model';\nimport { User } from 'app/core/user/user.model';\nimport * as moment from 'moment';\nimport { By } from '@angular/platform-browser';\nimport { NgbModal, NgbModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StudentExamsComponent', () => {\n let studentExamsComponentFixture: ComponentFixture<StudentExamsComponent>;\n let studentExamsComponent: StudentExamsComponent;\n let studentExams: StudentExam[] = [];\n let course: Course;\n let studentOne: User;\n let studentTwo: User;\n let studentExamOne: StudentExam | undefined;\n let studentExamTwo: StudentExam | undefined;\n let exam: Exam;\n let modalService: NgbModal;\n let examManagementService: ExamManagementService;\n\n beforeEach(() => {\n course = new Course();\n course.id = 1;\n\n studentOne = new User();\n studentOne.id = 1;\n\n studentTwo = new User();\n studentTwo.id = 2;\n\n exam = new Exam();\n exam.course = course;\n exam.id = 1;\n exam.registeredUsers = [studentOne, studentTwo];\n exam.endDate = moment();\n exam.startDate = exam.endDate.subtract(60, 'seconds');\n\n studentExamOne = new StudentExam();\n studentExamOne.exam = exam;\n studentExamOne.id = 1;\n studentExamOne.workingTime = 70;\n studentExamOne.user = studentOne;\n\n studentExamTwo = new StudentExam();\n studentExamTwo.exam = exam;\n studentExamTwo.id = 1;\n studentExamTwo.workingTime = 70;\n studentExamTwo.user = studentOne;\n\n studentExams = [studentExamOne, studentExamTwo];\n\n return TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([]), ArtemisDataTableModule, MockModule(NgbModule), NgxDatatableModule, FontAwesomeTestingModule, TranslateModule.forRoot()],\n declarations: [\n StudentExamsComponent,\n MockComponent(StudentExamStatusComponent),\n MockComponent(AlertComponent),\n MockPipe(ArtemisDurationFromSecondsPipe),\n MockPipe(ArtemisDatePipe),\n MockPipe(ArtemisTranslatePipe),\n ],\n providers: [\n MockProvider(ExamManagementService, {\n find: () => {\n return of(\n new HttpResponse({\n body: exam,\n status: 200,\n }),\n );\n },\n assessUnsubmittedExamModelingAndTextParticipations: () => {\n return of(\n new HttpResponse({\n body: 1,\n status: 200,\n }),\n );\n },\n generateStudentExams: () => {\n return of(\n new HttpResponse({\n body: [studentExamOne!, studentExamTwo!],\n status: 200,\n }),\n );\n },\n generateMissingStudentExams: () => {\n return of(\n new HttpResponse({\n body: studentExamTwo ? [studentExamTwo] : [],\n status: 200,\n }),\n );\n },\n startExercises: () => {\n return of(\n new HttpResponse({\n body: 2,\n status: 200,\n }),\n );\n },\n unlockAllRepositories: () => {\n return of(\n new HttpResponse({\n body: 2,\n status: 200,\n }),\n );\n },\n lockAllRepositories: () => {\n return of(\n new HttpResponse({\n body: 2,\n status: 200,\n }),\n );\n },\n evaluateQuizExercises: () => {\n return of(\n new HttpResponse({\n body: 1,\n status: 200,\n }),\n );\n },\n }),\n MockProvider(StudentExamService, {\n findAllForExam: () => {\n return of(\n new HttpResponse({\n body: studentExams,\n status: 200,\n }),\n );\n },\n }),\n MockProvider(CourseManagementService, {\n find: () => {\n return of(\n new HttpResponse({\n body: course,\n status: 200,\n }),\n );\n },\n }),\n MockProvider(JhiAlertService),\n MockDirective(JhiTranslateDirective),\n {\n provide: LocalStorageService,\n useClass: MockLocalStorageService,\n },\n {\n provide: ActivatedRoute,\n useValue: {\n params: {\n subscribe: (fn: (value: Params) => void) =>\n fn({\n courseId: 1,\n }),\n },\n snapshot: {\n paramMap: convertToParamMap({\n courseId: '1',\n examId: '1',\n }),\n },\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n studentExamsComponentFixture = TestBed.createComponent(StudentExamsComponent);\n studentExamsComponent = studentExamsComponentFixture.componentInstance;\n modalService = TestBed.inject(NgbModal);\n examManagementService = TestBed.inject(ExamManagementService);\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n const courseManagementService = TestBed.inject(CourseManagementService);\n\n const studentExamService = TestBed.inject(StudentExamService);\n const findCourseSpy = sinon.spy(courseManagementService, 'find');\n const findExamSpy = sinon.spy(examManagementService, 'find');\n const findAllStudentExamsSpy = sinon.spy(studentExamService, 'findAllForExam');\n studentExamsComponentFixture.detectChanges();\n\n expect(studentExamsComponentFixture).to.be.ok;\n expect(findCourseSpy).to.have.been.calledOnce;\n expect(findExamSpy).to.have.been.calledOnce;\n expect(findAllStudentExamsSpy).to.have.been.calledOnce;\n expect(studentExamsComponent.course).to.deep.equal(course);\n expect(studentExamsComponent.studentExams).to.deep.equal(studentExams);\n expect(studentExamsComponent.exam).to.deep.equal(exam);\n expect(studentExamsComponent.hasStudentsWithoutExam).to.equal(false);\n expect(studentExamsComponent.longestWorkingTime).to.equal(studentExamOne!.workingTime);\n expect(studentExamsComponent.isExamOver).to.equal(false);\n expect(studentExamsComponent.isLoading).to.equal(false);\n });\n\n it('should not show assess unsubmitted student exam modeling and text participations', () => {\n // user is not an instructor\n studentExamsComponentFixture.detectChanges();\n const assessButton = studentExamsComponentFixture.debugElement.query(By.css('#assessUnsubmittedExamModelingAndTextParticipationsButton'));\n expect(assessButton).to.not.exist;\n });\n\n it('should disable show assess unsubmitted student exam modeling and text participations', () => {\n course.isAtLeastInstructor = true;\n\n // exam is not over\n studentExamsComponentFixture.detectChanges();\n const assessButton = studentExamsComponentFixture.debugElement.query(By.css('#assessUnsubmittedExamModelingAndTextParticipationsButton'));\n expect(assessButton).to.exist;\n expect(assessButton.nativeElement.disabled).to.equal(true);\n });\n\n it('should automatically assess modeling and text exercises of unsubmitted student exams', () => {\n studentExamOne!.workingTime = 10;\n exam.startDate = moment().subtract(200, 'seconds');\n exam.endDate = moment().subtract(100, 'seconds');\n exam.gracePeriod = 0;\n course.isAtLeastInstructor = true;\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamOver).to.equal(true);\n expect(course).to.exist;\n const assessSpy = sinon.spy(examManagementService, 'assessUnsubmittedExamModelingAndTextParticipations');\n const assessButton = studentExamsComponentFixture.debugElement.query(By.css('#assessUnsubmittedExamModelingAndTextParticipationsButton'));\n expect(assessButton).to.exist;\n assessButton.nativeElement.click();\n expect(assessSpy).to.have.been.calledOnce;\n });\n\n it('should correctly catch HTTPError when assessing unsubmitted exams', () => {\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n studentExamOne!.workingTime = 10;\n exam.startDate = moment().subtract(200, 'seconds');\n exam.endDate = moment().subtract(100, 'seconds');\n exam.gracePeriod = 0;\n course.isAtLeastInstructor = true;\n\n studentExamsComponentFixture.detectChanges();\n const alertServiceSpy = sinon.spy(alertService, 'error');\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamOver).to.equal(true);\n expect(course).to.exist;\n const assessStub = sinon.stub(examManagementService, 'assessUnsubmittedExamModelingAndTextParticipations').returns(throwError(httpError));\n const assessButton = studentExamsComponentFixture.debugElement.query(By.css('#assessUnsubmittedExamModelingAndTextParticipationsButton'));\n expect(assessButton).to.exist;\n assessButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n assessStub.restore();\n });\n\n it('should generate student exams if there are none', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n\n studentExams = [];\n studentExamsComponentFixture.detectChanges();\n\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamStarted).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n\n studentExams = [studentExamOne!, studentExamTwo!];\n\n const generateStudentExamsSpy = sinon.spy(examManagementService, 'generateStudentExams');\n const generateStudentExamsButton = studentExamsComponentFixture.debugElement.query(By.css('#generateStudentExamsButton'));\n expect(generateStudentExamsButton).to.exist;\n expect(generateStudentExamsButton.nativeElement.disabled).to.equal(false);\n expect(!!studentExamsComponent.studentExams && !!studentExamsComponent.studentExams.length).to.equal(false);\n generateStudentExamsButton.nativeElement.click();\n expect(generateStudentExamsSpy).to.have.been.calledOnce;\n expect(studentExamsComponent.studentExams.length).to.equal(2);\n });\n\n it('should correctly catch HTTPError when generating student exams', () => {\n examManagementService = TestBed.inject(ExamManagementService);\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n\n studentExams = [];\n const generateStudentExamsStub = sinon.stub(examManagementService, 'generateStudentExams').returns(throwError(httpError));\n\n studentExamsComponentFixture.detectChanges();\n\n expect(!!studentExamsComponent.studentExams && !!studentExamsComponent.studentExams.length).to.equal(false);\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const generateStudentExamsButton = studentExamsComponentFixture.debugElement.query(By.css('#generateStudentExamsButton'));\n expect(generateStudentExamsButton).to.exist;\n expect(generateStudentExamsButton.nativeElement.disabled).to.equal(false);\n generateStudentExamsButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n generateStudentExamsStub.restore();\n });\n\n it('should generate student exams after warning the user that the existing are deleted', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n\n studentExamsComponentFixture.detectChanges();\n const componentInstance = { title: String, text: String };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamStarted).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n const generateStudentExamsSpy = sinon.spy(examManagementService, 'generateStudentExams');\n const generateStudentExamsButton = studentExamsComponentFixture.debugElement.query(By.css('#generateStudentExamsButton'));\n expect(generateStudentExamsButton).to.exist;\n expect(generateStudentExamsButton.nativeElement.disabled).to.equal(false);\n expect(!!studentExamsComponent.studentExams && !!studentExamsComponent.studentExams.length).to.equal(true);\n generateStudentExamsButton.nativeElement.click();\n expect(modalServiceOpenStub).to.have.been.called;\n expect(generateStudentExamsSpy).to.have.been.calledOnce;\n expect(studentExamsComponent.studentExams.length).to.equal(2);\n modalServiceOpenStub.restore();\n });\n\n it('should generate missing student exams', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n studentExams = [studentExamOne!];\n studentExamsComponentFixture.detectChanges();\n studentExams = [studentExamOne!, studentExamTwo!];\n\n expect(studentExamsComponent.hasStudentsWithoutExam).to.equal(true);\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamStarted).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(studentExamsComponent.studentExams.length).to.equal(1);\n expect(course).to.exist;\n const generateStudentExamsSpy = sinon.spy(examManagementService, 'generateMissingStudentExams');\n const generateMissingStudentExamsButton = studentExamsComponentFixture.debugElement.query(By.css('#generateMissingStudentExamsButton'));\n expect(generateMissingStudentExamsButton).to.exist;\n expect(generateMissingStudentExamsButton.nativeElement.disabled).to.equal(false);\n expect(!!studentExamsComponent.studentExams && !!studentExamsComponent.studentExams.length).to.equal(true);\n generateMissingStudentExamsButton.nativeElement.click();\n expect(generateStudentExamsSpy).to.have.been.calledOnce;\n expect(studentExamsComponent.studentExams.length).to.equal(2);\n });\n\n it('should correctly catch HTTPError when generating missing student exams', () => {\n examManagementService = TestBed.inject(ExamManagementService);\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n\n const generateMissingStudentExamsStub = sinon.stub(examManagementService, 'generateMissingStudentExams').returns(throwError(httpError));\n studentExams = [studentExamOne!];\n studentExamsComponentFixture.detectChanges();\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n expect(studentExamsComponent.hasStudentsWithoutExam).to.equal(true);\n const generateMissingStudentExamsButton = studentExamsComponentFixture.debugElement.query(By.css('#generateMissingStudentExamsButton'));\n expect(generateMissingStudentExamsButton).to.exist;\n expect(generateMissingStudentExamsButton.nativeElement.disabled).to.equal(false);\n generateMissingStudentExamsButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n generateMissingStudentExamsStub.restore();\n });\n\n it('should start the exercises of students', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n studentExamsComponentFixture.detectChanges();\n\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamStarted).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n\n const startExercisesSpy = sinon.spy(examManagementService, 'startExercises');\n const startExercisesButton = studentExamsComponentFixture.debugElement.query(By.css('#startExercisesButton'));\n expect(startExercisesButton).to.exist;\n expect(startExercisesButton.nativeElement.disabled).to.equal(false);\n\n startExercisesButton.nativeElement.click();\n expect(startExercisesSpy).to.have.been.calledOnce;\n });\n\n it('should correctly catch HTTPError when starting the exercises of the students', () => {\n examManagementService = TestBed.inject(ExamManagementService);\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n course.isAtLeastInstructor = true;\n exam.startDate = moment().add(120, 'seconds');\n\n const startExercisesStub = sinon.stub(examManagementService, 'startExercises').returns(throwError(httpError));\n studentExamsComponentFixture.detectChanges();\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const startExercisesButton = studentExamsComponentFixture.debugElement.query(By.css('#startExercisesButton'));\n expect(startExercisesButton).to.exist;\n expect(startExercisesButton.nativeElement.disabled).to.equal(false);\n startExercisesButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n startExercisesStub.restore();\n });\n\n it('should unlock all repositories of the students', () => {\n const componentInstance = { title: String, text: String };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n course.isAtLeastInstructor = true;\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n const unlockAllRepositories = sinon.spy(examManagementService, 'unlockAllRepositories');\n const unlockAllRepositoriesButton = studentExamsComponentFixture.debugElement.query(By.css('#handleUnlockAllRepositoriesButton'));\n expect(unlockAllRepositoriesButton).to.exist;\n expect(unlockAllRepositoriesButton.nativeElement.disabled).to.equal(false);\n unlockAllRepositoriesButton.nativeElement.click();\n expect(modalServiceOpenStub).to.have.been.called;\n expect(unlockAllRepositories).to.have.been.calledOnce;\n\n modalServiceOpenStub.restore();\n });\n\n it('should correctly catch HTTPError when unlocking all repositories', () => {\n const componentInstance = { title: String, text: String };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n const alertService = TestBed.inject(JhiAlertService);\n course.isAtLeastInstructor = true;\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n const unlockRepoStub = sinon.stub(examManagementService, 'unlockAllRepositories').returns(throwError(httpError));\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const unlockAllRepositoriesButton = studentExamsComponentFixture.debugElement.query(By.css('#handleUnlockAllRepositoriesButton'));\n expect(unlockAllRepositoriesButton).to.exist;\n expect(unlockAllRepositoriesButton.nativeElement.disabled).to.equal(false);\n unlockAllRepositoriesButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n modalServiceOpenStub.restore();\n unlockRepoStub.restore();\n });\n\n it('should lock all repositories of the students', () => {\n const componentInstance = { title: String, text: String };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n course.isAtLeastInstructor = true;\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n const lockAllRepositories = sinon.spy(examManagementService, 'lockAllRepositories');\n const lockAllRepositoriesButton = studentExamsComponentFixture.debugElement.query(By.css('#lockAllRepositoriesButton'));\n expect(lockAllRepositoriesButton).to.exist;\n expect(lockAllRepositoriesButton.nativeElement.disabled).to.equal(false);\n lockAllRepositoriesButton.nativeElement.click();\n expect(modalServiceOpenStub).to.have.been.called;\n expect(lockAllRepositories).to.have.been.calledOnce;\n\n modalServiceOpenStub.restore();\n });\n\n it('should correctly catch HTTPError when locking all repositories', () => {\n const componentInstance = { title: String, text: String };\n const result = new Promise((resolve) => resolve(true));\n const modalServiceOpenStub = sinon.stub(modalService, 'open').returns(<NgbModalRef>{ componentInstance, result });\n\n const alertService = TestBed.inject(JhiAlertService);\n course.isAtLeastInstructor = true;\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n const lockRepoStub = sinon.stub(examManagementService, 'lockAllRepositories').returns(throwError(httpError));\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const lockAllRepositoriesButton = studentExamsComponentFixture.debugElement.query(By.css('#lockAllRepositoriesButton'));\n expect(lockAllRepositoriesButton).to.exist;\n expect(lockAllRepositoriesButton.nativeElement.disabled).to.equal(false);\n lockAllRepositoriesButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n modalServiceOpenStub.restore();\n lockRepoStub.restore();\n });\n\n it('should evaluate Quiz exercises', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().subtract(200, 'seconds');\n exam.endDate = moment().subtract(100, 'seconds');\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamOver).to.equal(true);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n const evaluateQuizExercises = sinon.spy(examManagementService, 'evaluateQuizExercises');\n const evaluateQuizExercisesButton = studentExamsComponentFixture.debugElement.query(By.css('#evaluateQuizExercisesButton'));\n\n expect(evaluateQuizExercisesButton).to.exist;\n expect(evaluateQuizExercisesButton.nativeElement.disabled).to.equal(false);\n evaluateQuizExercisesButton.nativeElement.click();\n expect(evaluateQuizExercises).to.have.been.calledOnce;\n });\n\n it('should correctly catch HTTPError when evaluating quiz exercises', () => {\n course.isAtLeastInstructor = true;\n exam.startDate = moment().subtract(200, 'seconds');\n exam.endDate = moment().subtract(100, 'seconds');\n const alertService = TestBed.inject(JhiAlertService);\n\n studentExamsComponentFixture.detectChanges();\n expect(studentExamsComponent.isLoading).to.equal(false);\n expect(studentExamsComponent.isExamOver).to.equal(true);\n expect(studentExamsComponent.course.isAtLeastInstructor).to.equal(true);\n expect(course).to.exist;\n\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n const evaluateQuizExercisesStub = sinon.stub(examManagementService, 'evaluateQuizExercises').returns(throwError(httpError));\n studentExamsComponentFixture.detectChanges();\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const evaluateQuizExercisesButton = studentExamsComponentFixture.debugElement.query(By.css('#evaluateQuizExercisesButton'));\n expect(evaluateQuizExercisesButton).to.exist;\n expect(evaluateQuizExercisesButton.nativeElement.disabled).to.equal(false);\n evaluateQuizExercisesButton.nativeElement.click();\n expect(alertServiceSpy).to.have.been.calledOnce;\n\n evaluateQuizExercisesStub.restore();\n });\n});\n" }, { "alpha_fraction": 0.578321099281311, "alphanum_fraction": 0.5826482176780701, "avg_line_length": 43.019046783447266, "blob_id": "3e304995aeb5282db8b253fab8a429ab19036454", "content_id": "a770036c2ae068ef81e3881926373639284c114f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4622, "license_type": "permissive", "max_line_length": 140, "num_lines": 105, "path": "/src/main/webapp/app/shared/http/file-uploader.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClient } from '@angular/common/http';\nimport { Injectable } from '@angular/core';\nimport { MAX_FILE_SIZE } from 'app/shared/constants/input.constants';\n\nexport interface FileUploadResponse {\n path?: string;\n}\n\ntype Options = {\n keepFileName: boolean;\n};\n\n@Injectable({ providedIn: 'root' })\nexport class FileUploaderService {\n // NOTE: this list has to be the same as in FileResource.java\n acceptedFileExtensions = 'png,jpg,jpeg,svg,pdf,zip';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Function which uploads a file. It checks for supported file extensions and file size.\n * Options must be passed as a dictionary. E.g: { keepFileName: true }\n * @param {Blob | File} file\n * @param {string} fileName\n * @param options\n */\n uploadFile(file: Blob | File, fileName?: string, options?: Options): Promise<FileUploadResponse> {\n /** Check file extension **/\n const fileExtension = fileName ? fileName.split('.').pop()!.toLocaleLowerCase() : file['name'].split('.').pop().toLocaleLowerCase();\n if (this.acceptedFileExtensions.split(',').indexOf(fileExtension) === -1) {\n return Promise.reject(\n new Error(\n 'Unsupported file type! Only files of type ' +\n this.acceptedFileExtensions\n .split(',')\n .map((extension) => `\".${extension}\"`)\n .join(', ') +\n ' allowed.',\n ),\n );\n }\n\n /** Check file size **/\n if (file.size > MAX_FILE_SIZE) {\n return Promise.reject(new Error('File is too big! Maximum allowed file size: ' + MAX_FILE_SIZE / (1024 * 1024) + ' MB.'));\n }\n\n const formData = new FormData();\n formData.append('file', file, fileName);\n const keepFileName: boolean = !!options && options.keepFileName;\n const url = `/api/fileUpload?keepFileName=${keepFileName}`;\n return this.http.post<FileUploadResponse>(url, formData).toPromise();\n }\n\n /**\n * Function which uploads a file. It checks for supported file extensions and file size.\n * Options must be passed as a dictionary. E.g: { keepFileName: true }\n * @param {Blob | File} file\n * @param {string} fileName\n * @param options\n */\n uploadMarkdownFile(file: Blob | File, fileName?: string, options?: Options): Promise<FileUploadResponse> {\n /** Check file extension **/\n const fileExtension = fileName ? fileName.split('.').pop()!.toLocaleLowerCase() : file['name'].split('.').pop().toLocaleLowerCase();\n if (this.acceptedFileExtensions.split(',').indexOf(fileExtension) === -1) {\n return Promise.reject(\n new Error(\n 'Unsupported file type! Only files of type ' +\n this.acceptedFileExtensions\n .split(',')\n .map((extension) => `\".${extension}\"`)\n .join(', ') +\n ' allowed.',\n ),\n );\n }\n\n /** Check file size **/\n if (file.size > MAX_FILE_SIZE) {\n return Promise.reject(new Error('File is too big! Maximum allowed file size: ' + MAX_FILE_SIZE / (1024 * 1024) + ' MB.'));\n }\n\n const formData = new FormData();\n formData.append('file', file, fileName);\n const keepFileName: boolean = !!options && options.keepFileName;\n const url = `/api/markdown-file-upload?keepFileName=${keepFileName}`;\n return this.http.post<FileUploadResponse>(url, formData).toPromise();\n }\n\n /**\n * Duplicates file in the server.\n * @param filePath Path of the file which needs to be duplicated\n */\n async duplicateFile(filePath: string): Promise<FileUploadResponse> {\n // Get file from the server using filePath,\n const file = await this.http.get(filePath, { responseType: 'blob' }).toPromise();\n // Generate a temp file name with extension. File extension is necessary as server stores only specific kind of files,\n const tempFilename = 'temp' + filePath.split('/').pop()!.split('#')[0].split('?')[0];\n const formData = new FormData();\n formData.append('file', file, tempFilename);\n // Upload the file to server. This will make a new file in the server in the temp folder\n // and will return path of the file,\n return await this.http.post<FileUploadResponse>(`/api/fileUpload?keepFileName=${false}`, formData).toPromise();\n }\n}\n" }, { "alpha_fraction": 0.6304985284805298, "alphanum_fraction": 0.6304985284805298, "avg_line_length": 21, "blob_id": "91c815ed51e292e032aefcb6158105d10505d159", "content_id": "ed3f9004c828ddd8c4bb5f914fcba1a5a528c679", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 682, "license_type": "permissive", "max_line_length": 58, "num_lines": 31, "path": "/src/main/webapp/app/entities/tutor-group.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { User } from 'app/core/user/user.model';\nimport { Course } from 'app/entities/course.model';\n\nexport const enum Weekday {\n MONDAY = 'MONDAY',\n TUESDAY = 'TUESDAY',\n WEDNESDAY = 'WEDNESDAY',\n THURSDAY = 'THURSDAY',\n FRIDAY = 'FRIDAY',\n}\n\nexport const enum Language {\n ENGLISH = 'ENGLISH',\n GERMAN = 'GERMAN',\n}\n\nexport class TutorGroup implements BaseEntity {\n id?: number;\n name?: string;\n capacity?: number;\n weekday?: Weekday;\n timeSlot?: string;\n language?: Language;\n room?: string;\n tutor?: User;\n students?: User[];\n course?: Course;\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.7827298045158386, "alphanum_fraction": 0.7827298045158386, "avg_line_length": 46.86666488647461, "blob_id": "7e284858150c64495d9a590bee5e876c81a544fb", "content_id": "a18efce2b78e6036cf9471d6b8db901c88df3240", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 718, "license_type": "permissive", "max_line_length": 85, "num_lines": 15, "path": "/src/main/webapp/app/complaints/complaints-for-tutor/complaints-for-tutor.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { MomentModule } from 'ngx-moment';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ComplaintsForTutorComponent } from './complaints-for-tutor.component';\nimport { ComplaintResponseService } from 'app/complaints/complaint-response.service';\nimport { ComplaintService } from 'app/complaints/complaint.service';\n\n@NgModule({\n imports: [ArtemisSharedModule, MomentModule, ClipboardModule],\n declarations: [ComplaintsForTutorComponent],\n exports: [ComplaintsForTutorComponent],\n providers: [ComplaintService, ComplaintResponseService],\n})\nexport class ArtemisComplaintsForTutorModule {}\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 13, "blob_id": "ff1a09b6cf6b2fa5c40bd1539c4637cafd3ed674", "content_id": "a8e177bfbf05288f668a5aefccb91aad3ece3ef2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 28, "license_type": "permissive", "max_line_length": 13, "num_lines": 2, "path": "/docs/user/exercises/quiz.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Quiz exercise\n=============\n" }, { "alpha_fraction": 0.7524949908256531, "alphanum_fraction": 0.7524949908256531, "avg_line_length": 54.66666793823242, "blob_id": "c93dd5733004750b4813712b88e46f08af3b63b1", "content_id": "3507d6ff6d91ab8a69179ed0a7b7aa97b4e45814", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2505, "license_type": "permissive", "max_line_length": 166, "num_lines": 45, "path": "/src/main/webapp/app/exercises/programming/manage/services/programming-exercise-participation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Result } from 'app/entities/result.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { addUserIndependentRepositoryUrl } from 'app/overview/participation-utils';\n\nexport interface IProgrammingExerciseParticipationService {\n getLatestResultWithFeedback: (participationId: number, withSubmission: boolean) => Observable<Result | undefined>;\n getStudentParticipationWithLatestResult: (participationId: number) => Observable<ProgrammingExerciseStudentParticipation>;\n checkIfParticipationHasResult: (participationId: number) => Observable<boolean>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ProgrammingExerciseParticipationService implements IProgrammingExerciseParticipationService {\n public resourceUrl = SERVER_API_URL + 'api/programming-exercise-participations/';\n\n constructor(private http: HttpClient) {}\n\n getLatestResultWithFeedback(participationId: number, withSubmission = false): Observable<Result | undefined> {\n const options = createRequestOption({ withSubmission });\n return this.http.get<Result | undefined>(this.resourceUrl + participationId + '/latest-result-with-feedbacks', { params: options });\n }\n\n getStudentParticipationWithLatestResult(participationId: number) {\n return this.http.get<ProgrammingExerciseStudentParticipation>(this.resourceUrl + participationId + '/student-participation-with-latest-result-and-feedbacks');\n }\n\n getStudentParticipationWithResultOfCorrectionRound(participationId: number, correctionRound: number) {\n return this.http\n .get<ProgrammingExerciseStudentParticipation>(\n this.resourceUrl + participationId + '/student-participation-with-result-and-feedbacks-for/' + correctionRound + '/correction-round',\n )\n .map((participation: ProgrammingExerciseStudentParticipation) => {\n addUserIndependentRepositoryUrl(participation);\n return participation;\n });\n }\n\n checkIfParticipationHasResult(participationId: number): Observable<boolean> {\n return this.http.get<boolean>(this.resourceUrl + participationId + '/has-result');\n }\n}\n" }, { "alpha_fraction": 0.7050074338912964, "alphanum_fraction": 0.7077342867851257, "avg_line_length": 48.802467346191406, "blob_id": "e29ff2e01f71f311bbd96962b03e2f498c1c8f91", "content_id": "11b74d2d2dccdce40198c481782fe9c4e34884ff", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4034, "license_type": "permissive", "max_line_length": 148, "num_lines": 81, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-import.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ProgrammingExercisePagingService } from 'app/exercises/programming/manage/services/programming-exercise-paging.service';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { SinonStub, stub } from 'sinon';\nimport { Subject } from 'rxjs';\nimport { DifferencePipe } from 'ngx-moment';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service';\nimport { ProgrammingExerciseImportComponent } from 'app/exercises/programming/manage/programming-exercise-import.component';\nimport { ArtemisSharedCommonModule } from 'app/shared/shared-common.module';\nimport { ProgrammingExercise, ProgrammingLanguage } from 'app/entities/programming-exercise.model';\nimport { SearchResult } from 'app/shared/table/pageable-table';\nimport { ButtonComponent } from 'app/shared/components/button.component';\nimport { MockProgrammingExercisePagingService } from '../../helpers/mocks/service/mock-programming-exercise-paging.service';\nimport { ArtemisSharedPipesModule } from 'app/shared/pipes/shared-pipes.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseImportComponent', () => {\n let comp: ProgrammingExerciseImportComponent;\n let fixture: ComponentFixture<ProgrammingExerciseImportComponent>;\n let debugElement: DebugElement;\n let pagingService: ProgrammingExercisePagingService;\n\n let pagingStub: SinonStub;\n\n const basicCourse = { id: 12, title: 'Random course title' } as Course;\n const exercise = { id: 42, title: 'Exercise title', programmingLanguage: ProgrammingLanguage.JAVA, course: basicCourse } as ProgrammingExercise;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedCommonModule, FeatureToggleModule, ArtemisSharedPipesModule],\n declarations: [ProgrammingExerciseImportComponent, ButtonComponent],\n providers: [\n DifferencePipe,\n { provide: ProgrammingExercisePagingService, useClass: MockProgrammingExercisePagingService },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseImportComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n pagingService = debugElement.injector.get(ProgrammingExercisePagingService);\n pagingStub = stub(pagingService, 'searchForExercises');\n });\n });\n\n afterEach(() => {\n pagingStub.restore();\n });\n\n it('should parse the pageable search result into the correct state', fakeAsync(() => {\n const searchResult = { resultsOnPage: [exercise], numberOfPages: 3 } as SearchResult<ProgrammingExercise>;\n const searchObservable = new Subject<SearchResult<ProgrammingExercise>>();\n pagingStub.returns(searchObservable);\n\n fixture.detectChanges();\n tick();\n\n expect(pagingStub).to.have.been.calledOnce;\n searchObservable.next(searchResult);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.content.numberOfPages).to.be.eq(3);\n expect(comp.content.resultsOnPage[0].id).to.be.eq(42);\n expect(comp.total).to.be.eq(30);\n expect(comp.loading).to.be.false;\n }));\n});\n" }, { "alpha_fraction": 0.6100665330886841, "alphanum_fraction": 0.6120914220809937, "avg_line_length": 36.17204284667969, "blob_id": "c3d1dc4af7a6fd6025d2de7eaa6b417c5cf654c3", "content_id": "af0dac3f8e114c4abc17a957eceb7d49d3fc961b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3457, "license_type": "permissive", "max_line_length": 175, "num_lines": 93, "path": "/src/main/webapp/app/utils/navigation.utils.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Router } from '@angular/router';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\n\nexport const navigateBack = (router: Router, fallbackUrl: string[]): void => {\n if (window.history.length > 1) {\n window.history.back();\n } else {\n router.navigate(fallbackUrl);\n }\n};\n\nexport const navigateBackFromExerciseUpdate = (router: Router, exercise: Exercise): void => {\n if (window.history.length > 1) {\n window.history.back();\n return;\n }\n\n // If an exercise group is set we are in exam mode\n if (exercise.exerciseGroup) {\n router.navigate(['course-management', exercise.exerciseGroup!.exam!.course!.id!.toString(), 'exams', exercise.exerciseGroup!.exam!.id!.toString(), 'exercise-groups']);\n return;\n }\n\n if (exercise.id) {\n router.navigate(['course-management', exercise.course!.id!.toString(), exercise.type! + '-exercises', exercise.id!.toString()]);\n } else {\n router.navigate(['course-management', exercise.course!.id!.toString(), exercise.type! + '-exercises']);\n }\n};\n\nexport const getLinkToSubmissionAssessment = (\n exerciseType: ExerciseType,\n courseId: number,\n exerciseId: number,\n submissionId: number | 'new',\n examId: number,\n exerciseGroupId: number,\n resultId?: number,\n): string[] => {\n // Special case: If we're dealing with programming exercises use 'code-editor' instead of 'submissions'\n const submissionsURL = exerciseType === ExerciseType.PROGRAMMING ? 'code-editor' : 'submissions';\n\n if (examId > 0) {\n const route = [\n '/course-management',\n courseId.toString(),\n 'exams',\n examId.toString(),\n 'exercise-groups',\n exerciseGroupId.toString(),\n exerciseType + '-exercises',\n exerciseId.toString(),\n submissionsURL,\n submissionId.toString(),\n 'assessment',\n ];\n if (resultId) {\n route[route.length - 1] += 's';\n route.push(resultId.toString());\n }\n return route;\n } else {\n return ['/course-management', courseId.toString(), exerciseType + '-exercises', exerciseId.toString(), submissionsURL, submissionId.toString(), 'assessment'];\n }\n};\n\nexport const getExerciseDashboardLink = (courseId: number, exerciseId: number, examId = 0, isTestRun = false): string[] => {\n if (isTestRun) {\n return ['/course-management', courseId.toString(), 'exams', examId.toString(), 'test-runs', 'assess'];\n }\n\n return examId > 0\n ? ['/course-management', courseId.toString(), 'exams', examId.toString(), 'assessment-dashboard', exerciseId.toString()]\n : ['/course-management', courseId.toString(), 'assessment-dashboard', exerciseId.toString()];\n};\n\nexport const getExerciseSubmissionsLink = (exerciseType: ExerciseType, courseId: number, exerciseId: number, examId: number, exerciseGroupId: number): string[] => {\n if (examId > 0) {\n return [\n '/course-management',\n courseId.toString(),\n 'exams',\n examId.toString(),\n 'exercise-groups',\n exerciseGroupId.toString(),\n exerciseType + '-exercises',\n exerciseId.toString(),\n 'assessment',\n ];\n }\n\n return ['/course-management', courseId.toString(), exerciseType + '-exercises', exerciseId.toString(), 'assessment'];\n};\n" }, { "alpha_fraction": 0.6780728697776794, "alphanum_fraction": 0.678583562374115, "avg_line_length": 32.75862121582031, "blob_id": "88ea9518d8475bdbdc22ff1910fd2d6b30467a79", "content_id": "f3b5a997909a3de5f50d23bd3562c8b5819a42f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5874, "license_type": "permissive", "max_line_length": 138, "num_lines": 174, "path": "/src/main/java/de/tum/in/www1/artemis/domain/notification/GroupNotification.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.notification;\n\nimport java.time.ZonedDateTime;\n\nimport javax.persistence.*;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.google.gson.JsonObject;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.GroupNotificationType;\n\n/**\n * A GroupNotification.\n */\n@Entity\n@DiscriminatorValue(value = \"G\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class GroupNotification extends Notification {\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"jhi_type\")\n private GroupNotificationType type;\n\n @ManyToOne\n @JsonIgnoreProperties(\"groupNotifications\")\n private Course course;\n\n // jhipster-needle-entity-add-field - JHipster will add fields here, do not remove\n\n public GroupNotificationType getType() {\n return type;\n }\n\n public GroupNotification type(GroupNotificationType type) {\n this.type = type;\n return this;\n }\n\n public void setType(GroupNotificationType type) {\n this.type = type;\n }\n\n public Course getCourse() {\n return course;\n }\n\n public GroupNotification course(Course course) {\n this.course = course;\n return this;\n }\n\n public GroupNotification() {\n }\n\n public GroupNotification(Course course, String title, String notificationText, User user, GroupNotificationType type) {\n this.setCourse(course);\n this.setType(type);\n this.setNotificationDate(ZonedDateTime.now());\n this.setTitle(title);\n this.setText(notificationText);\n this.setAuthor(user);\n }\n\n public void setCourse(Course course) {\n this.course = course;\n }\n\n public String getExerciseCreatedTarget(Exercise exercise) {\n return getExerciseTarget(exercise, \"exerciseCreated\");\n }\n\n public String getExerciseUpdatedTarget(Exercise exercise) {\n return getExerciseTarget(exercise, \"exerciseUpdated\");\n }\n\n public String getExerciseAnswerTarget(Exercise exercise) {\n return getExerciseTarget(exercise, \"newAnswer\");\n }\n\n public String getExerciseQuestionTarget(Exercise exercise) {\n return getExerciseTarget(exercise, \"newQuestion\");\n }\n\n public String getLectureQuestionTarget(Lecture lecture) {\n return getLectureTarget(lecture, \"newQuestion\");\n }\n\n public String getLectureAnswerTarget(Lecture lecture) {\n return getLectureTarget(lecture, \"newAnswer\");\n }\n\n public String getAttachmentUpdated(Lecture lecture) {\n return getLectureTarget(lecture, \"attachmentUpdated\");\n }\n\n /**\n * Create JSON representation for a GroupNotification for an ProgrammingExercise in an Exam or if duplicated test cases were detected.\n *\n * @param programmingExercise for which to create the notification.\n * @param message to use for the notification.\n * @return the stringified JSON of the target.\n */\n public String getExamProgrammingExerciseOrTestCaseTarget(ProgrammingExercise programmingExercise, String message) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", message);\n target.addProperty(\"id\", programmingExercise.getId());\n target.addProperty(\"entity\", \"programming-exercises\");\n target.addProperty(\"course\", programmingExercise.getCourseViaExerciseGroupOrCourseMember().getId());\n target.addProperty(\"mainPage\", \"course-management\");\n return target.toString();\n }\n\n /**\n * Create JSON representation for a GroupNotification for an Exercise.\n *\n * @param exercise for which to create the notification.\n * @param message to use for the notification.\n * @return the stringified JSON of the target.\n */\n public String getExerciseTarget(Exercise exercise, String message) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", message);\n target.addProperty(\"id\", exercise.getId());\n target.addProperty(\"entity\", \"exercises\");\n target.addProperty(\"course\", exercise.getCourseViaExerciseGroupOrCourseMember().getId());\n target.addProperty(\"mainPage\", \"courses\");\n return target.toString();\n }\n\n /**\n * Create JSON representation for a GroupNotification for a Lecture.\n *\n * @param lecture for which to create the notification.\n * @param message to use for the notification.\n * @return the stringified JSON of the target.\n */\n public String getLectureTarget(Lecture lecture, String message) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", message);\n target.addProperty(\"id\", lecture.getId());\n target.addProperty(\"entity\", \"lectures\");\n target.addProperty(\"course\", lecture.getCourse().getId());\n target.addProperty(\"mainPage\", \"courses\");\n return target.toString();\n }\n\n /**\n * Create JSON representation for a GroupNotification for a Course.\n *\n * @param course for which to create the notification.\n * @param message to use for the notification.\n * @return the stringified JSON of the target.\n */\n public String getCourseTarget(Course course, String message) {\n JsonObject target = new JsonObject();\n target.addProperty(\"message\", message);\n target.addProperty(\"id\", course.getId());\n target.addProperty(\"entity\", \"courses\");\n target.addProperty(\"course\", course.getId());\n target.addProperty(\"mainPage\", \"courses\");\n return target.toString();\n }\n\n public String getTopic() {\n return \"/topic/course/\" + getCourse().getId() + \"/\" + getType();\n }\n\n @Override\n public String toString() {\n return \"GroupNotification{\" + \"id=\" + getId() + \", type='\" + getType() + \"'\" + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.608450710773468, "alphanum_fraction": 0.6140844821929932, "avg_line_length": 41.11864471435547, "blob_id": "7e0b67ea1a63b351cca94fe3641a29ac6de9c862", "content_id": "b7915231b2f397ff651fba31aede2fac65a7a128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2485, "license_type": "permissive", "max_line_length": 129, "num_lines": 59, "path": "/src/main/webapp/app/shared/markdown-editor/commands/orderedListCommand.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Command } from './command';\n\nexport class OrderedListCommand extends Command {\n buttonIcon = 'list-ol';\n buttonTranslationString = 'artemisApp.multipleChoiceQuestion.editor.orderedList';\n\n /**\n * @function execute\n * @desc Use the markdown language for creating/removing an ordered list\n */\n execute(): void {\n const selectedText = this.getSelectedText();\n this.splitText(selectedText);\n }\n\n /**\n * @function splitText\n * @desc 1. Split the text at the line break into an array\n * 2. Assign each line the position it has in the array\n * 3. Call for each textLine the replaceText method\n * @param selectedText the selected text by the cursor\n */\n splitText(selectedText: string): void {\n const parseArray = selectedText.split('\\n');\n let addAmount = parseArray.length - 1;\n for (const element of parseArray) {\n this.replaceText(element, parseArray.length - addAmount);\n addAmount--;\n }\n }\n\n /**\n * @function replaceText\n * @desc 1. Check if the selected text includes (.) because the ordered counting includes always a number followed by a dot\n * 2. If included, reduce the selected text by 3 (number, dot, whitespace) and replace the selected text by textToAdd\n * 3. If not included, place the position {number} before the selected text {string} and add them to the editor\n * 4. An ordered list in markdown language appears\n * @param element textLine {string}\n * @param position {number} it has in the overall selectedText{array}\n */\n replaceText(element: string, position: number): void {\n /** case 1: text is formed in as an ordered list and the list should be unformed by deleting number + (.) + whitespace */\n if (element.includes('.')) {\n const textToAdd = element.slice(3);\n const text = `${textToAdd}\\n`;\n this.insertText(text);\n /** case 2: start a new ordered list from scratch */\n } else if (element === '') {\n const range = this.getRange();\n element = `1. ${element}`;\n this.replace(range, element);\n this.focus();\n } else {\n /** case 3: formate existing text into an ordered list by inserting the position of the array before the text*/\n element = `${position}. ${element}\\n`;\n this.insertText(element);\n }\n }\n}\n" }, { "alpha_fraction": 0.4929485619068146, "alphanum_fraction": 0.5269613862037659, "avg_line_length": 44.24396896362305, "blob_id": "15c414205641921aaccb73d132df4198c60e2405", "content_id": "4d92b9f41ee5cedf83902151d7586c544a1d78bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16876, "license_type": "permissive", "max_line_length": 165, "num_lines": 373, "path": "/src/test/javascript/spec/component/overview/course-statistics/course-statistics.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport * as moment from 'moment';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ChartsModule } from 'ng2-charts';\nimport { TreeviewModule } from 'ngx-treeview';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockComponent } from 'ng-mocks';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { ActivatedRoute } from '@angular/router';\nimport { By } from '@angular/platform-browser';\nimport { Course } from 'app/entities/course.model';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { CourseStatisticsComponent } from 'app/overview/course-statistics/course-statistics.component';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { CourseLearningGoalsComponent } from 'app/overview/course-learning-goals/course-learning-goals.component';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { IncludedInOverallScore } from 'app/entities/exercise.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseStatisticsComponent', () => {\n let comp: CourseStatisticsComponent;\n let fixture: ComponentFixture<CourseStatisticsComponent>;\n let courseScoreCalculationService: CourseScoreCalculationService;\n\n const modelingExercises = [\n {\n type: 'modeling',\n id: 192,\n title: 'test 17.06. 1',\n dueDate: moment('2019-06-17T09:47:12+02:00'),\n assessmentDueDate: moment('2019-06-17T09:55:17+02:00'),\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n maxPoints: 12.0,\n studentParticipations: [\n {\n id: 248,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-17T09:29:34.908+02:00'),\n presentationScore: 2,\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n presentationScoreEnabled: true,\n },\n {\n type: 'modeling',\n id: 193,\n title: 'test 17.06. 2',\n dueDate: moment('2019-06-17T17:50:08+02:00'),\n assessmentDueDate: moment('2019-06-17T17:51:13+02:00'),\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n maxPoints: 12.0,\n studentParticipations: [\n {\n id: 249,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-18T10:53:27.997+02:00'),\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n },\n {\n type: 'modeling',\n id: 194,\n title: 'test 18.06. 1',\n dueDate: moment('2019-06-18T07:56:41+02:00'),\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n maxPoints: 12.0,\n studentParticipations: [],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n },\n {\n type: 'modeling',\n id: 191,\n title: 'Until 18:20',\n dueDate: moment('2019-06-16T18:15:03+02:00'),\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n assessmentDueDate: moment('2019-06-16T18:30:57+02:00'),\n maxPoints: 12.0,\n studentParticipations: [\n {\n id: 246,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-16T18:10:28.293+02:00'),\n results: [\n {\n id: 231,\n resultString: '11 of 12 points',\n completionDate: moment('2019-06-17T09:30:17.761+02:00'),\n successful: false,\n score: 92,\n rated: true,\n hasFeedback: false,\n assessmentType: 'MANUAL',\n hasComplaint: false,\n },\n ],\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n },\n {\n type: 'modeling',\n id: 195,\n title: 'Until 18:20 too',\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n dueDate: moment('2019-06-16T18:15:03+02:00'),\n assessmentDueDate: moment('2019-06-16T18:30:57+02:00'),\n maxPoints: 12.0,\n studentParticipations: [\n {\n id: 249,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-16T18:10:28.293+02:00'),\n results: [\n {\n id: 230,\n resultString: '9 of 12 points',\n completionDate: moment('2019-06-17T09:30:17.761+02:00'),\n successful: false,\n score: 75,\n rated: true,\n hasFeedback: false,\n assessmentType: 'MANUAL',\n hasComplaint: false,\n },\n ],\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n },\n ] as ModelingExercise[];\n\n const course = new Course();\n course.id = 64;\n course.title = 'Checking statistics';\n course.description = 'Testing the statistics view';\n course.shortName = 'CHS';\n course.studentGroupName = 'jira-users';\n course.teachingAssistantGroupName = 'artemis-dev';\n course.instructorGroupName = 'artemis-dev';\n course.onlineCourse = false;\n course.registrationEnabled = false;\n course.exercises = [];\n course.presentationScore = 1;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, TreeviewModule.forRoot(), RouterTestingModule.withRoutes([]), ArtemisSharedModule, ChartsModule],\n declarations: [CourseStatisticsComponent, MockComponent(CourseLearningGoalsComponent)],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n params: {\n subscribe: (fn: (value: any) => void) => fn(1),\n },\n },\n },\n },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseStatisticsComponent);\n comp = fixture.componentInstance;\n courseScoreCalculationService = TestBed.inject(CourseScoreCalculationService);\n });\n });\n\n afterEach(function () {\n // has to be done so the component can cleanup properly\n spyOn(comp, 'ngOnDestroy').and.callFake(() => {});\n fixture.destroy();\n });\n\n it('should group all exercises', () => {\n const courseToAdd = { ...course };\n courseToAdd.exercises = [...modelingExercises];\n spyOn(courseScoreCalculationService, 'getCourse').and.returnValue(courseToAdd);\n fixture.detectChanges();\n comp.ngOnInit();\n fixture.detectChanges();\n expect(comp.groupedExercises.length).to.equal(1);\n const modelingWrapper = fixture.debugElement.query(By.css('#modeling-wrapper'));\n expect(modelingWrapper.query(By.css('h2')).nativeElement.textContent).to.exist;\n expect(modelingWrapper.query(By.css('#absolute-score')).nativeElement.textContent).to.exist;\n expect(modelingWrapper.query(By.css('#reachable-score')).nativeElement.textContent).to.exist;\n expect(modelingWrapper.query(By.css('#max-score')).nativeElement.textContent).to.exist;\n expect(fixture.debugElement.query(By.css('#presentation-score')).nativeElement.textContent).to.exist;\n const exercise: any = comp.groupedExercises[0];\n expect(exercise.presentationScore).to.equal(2);\n expect(exercise.notGraded.tooltips).to.include.members(['artemisApp.courseOverview.statistics.exerciseNotGraded']);\n expect(exercise.scores.tooltips).to.include.members(['artemisApp.courseOverview.statistics.exerciseAchievedScore']);\n expect(exercise.missedScores.tooltips).to.include.members(['artemisApp.courseOverview.statistics.exerciseParticipatedAfterDueDate']);\n expect(exercise.missedScores.tooltips).to.include.members(['artemisApp.courseOverview.statistics.exerciseNotParticipated']);\n expect(exercise.missedScores.tooltips).to.include.members(['artemisApp.courseOverview.statistics.exerciseMissedScore']);\n });\n\n it('should calculate scores correctly', () => {\n const courseToAdd = { ...course };\n courseToAdd.exercises = [...modelingExercises];\n spyOn(courseScoreCalculationService, 'getCourse').and.returnValue(courseToAdd);\n fixture.detectChanges();\n comp.ngOnInit();\n fixture.detectChanges();\n expect(comp.groupedExercises.length).to.equal(1);\n let exercise: any = comp.groupedExercises[0];\n expect(exercise.absoluteScore).to.equal(20);\n expect(exercise.reachableScore).to.equal(60);\n expect(exercise.overallMaxPoints).to.equal(60);\n\n const newExercise = [\n ({\n type: 'text',\n id: 200,\n title: 'Until 18:20 too',\n dueDate: moment('2019-06-16T18:15:03+02:00'),\n assessmentDueDate: moment('2019-06-16T18:30:57+02:00'),\n maxPoints: 10.0,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n studentParticipations: [\n {\n id: 289,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-16T18:10:28.293+02:00'),\n results: [\n {\n id: 222,\n resultString: '5.5 of 10 points',\n completionDate: moment('2019-06-17T09:30:17.761+02:00'),\n successful: false,\n score: 55,\n rated: true,\n hasFeedback: false,\n assessmentType: 'MANUAL',\n hasComplaint: false,\n },\n ],\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n } as unknown) as TextExercise,\n ({\n type: 'text',\n id: 999,\n title: 'Until 18:20 tooo',\n dueDate: moment('2019-06-16T18:15:03+02:00'),\n assessmentDueDate: moment().add(1, 'days'),\n maxPoints: 10.0,\n includedInOverallScore: IncludedInOverallScore.INCLUDED_COMPLETELY,\n studentParticipations: [\n {\n id: 888,\n initializationState: 'FINISHED',\n initializationDate: moment('2019-06-16T18:10:28.293+02:00'),\n student: {\n id: 9,\n login: 'artemis_test_user_1',\n firstName: 'Artemis Test User 1',\n email: '[email protected]',\n activated: true,\n langKey: 'en',\n },\n },\n ],\n diagramType: 'ClassDiagram',\n numberOfSubmissions: new DueDateStat(),\n totalNumberOfAssessments: new DueDateStat(),\n numberOfComplaints: 0,\n } as unknown) as TextExercise,\n ];\n courseToAdd.exercises = [...modelingExercises, ...newExercise];\n fixture.detectChanges();\n comp.ngOnInit();\n fixture.detectChanges();\n\n // check that exerciseGroup scores are untouched\n exercise = comp.groupedExercises[0];\n expect(exercise.absoluteScore).to.equal(20);\n expect(exercise.reachableScore).to.equal(60);\n expect(exercise.overallMaxPoints).to.equal(60);\n\n // check that overall course score is adapted accordingly -> one exercise after assessment, one before\n expect(comp.overallPoints).to.equal(25.5);\n expect(comp.reachablePoints).to.equal(70);\n expect(comp.overallMaxPoints).to.equal(80);\n\n // check that html file displays the correct elements\n let debugElement = fixture.debugElement.query(By.css('#absolute-course-score'));\n expect(debugElement.nativeElement.textContent).to.equal('artemisApp.courseOverview.statistics.yourPoints');\n debugElement = fixture.debugElement.query(By.css('#reachable-course-score'));\n expect(debugElement.nativeElement.textContent).to.equal(' artemisApp.courseOverview.statistics.reachablePoints ');\n debugElement = fixture.debugElement.query(By.css('#max-course-score'));\n expect(debugElement.nativeElement.textContent).to.equal(' artemisApp.courseOverview.statistics.totalPoints ');\n });\n});\n" }, { "alpha_fraction": 0.6711452603340149, "alphanum_fraction": 0.6737043857574463, "avg_line_length": 40.1315803527832, "blob_id": "b21fa1a63aee38a2dadb0169b08a80fb287fef6f", "content_id": "271c5243d45ff85dc9d25863d5d3cc4db0fc578e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1563, "license_type": "permissive", "max_line_length": 114, "num_lines": 38, "path": "/src/test/javascript/spec/component/markdown-editor/katex-command.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\n\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport { ArtemisTestModule } from '../../test.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('KatexCommand', () => {\n let comp: MarkdownEditorComponent;\n let fixture: ComponentFixture<MarkdownEditorComponent>;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), AceEditorModule, ArtemisMarkdownEditorModule],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(MarkdownEditorComponent);\n comp = fixture.componentInstance;\n });\n });\n it('should add insert the sample e-function into the editor on execute', () => {\n const katexCommand = new KatexCommand();\n comp.domainCommands = [katexCommand];\n fixture.detectChanges();\n comp.ngAfterViewInit();\n\n katexCommand.execute();\n expect(comp.aceEditorContainer.getEditor().getValue()).to.equal('$$ e^{\\\\frac{1}{4} y^2} $$');\n });\n});\n" }, { "alpha_fraction": 0.7767133116722107, "alphanum_fraction": 0.784819483757019, "avg_line_length": 66.8499984741211, "blob_id": "e0a4b6b5f7de7fb5fd7a0c78fca085512d2ffc94", "content_id": "c8b3a8cde187e7408adc1bba9bbd7a8fc40a2f47", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2714, "license_type": "permissive", "max_line_length": 198, "num_lines": 40, "path": "/src/main/java/de/tum/in/www1/artemis/repository/FeedbackConflictRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.FeedbackConflict;\n\n/**\n * Spring Data JPA repository for the FeedbackConflict entity.\n */\n@Repository\npublic interface FeedbackConflictRepository extends JpaRepository<FeedbackConflict, Long> {\n\n @Query(\"select distinct conflict from FeedbackConflict conflict \"\n + \"left join fetch conflict.firstFeedback f1 left join fetch f1.result r1 left join fetch r1.submission left join fetch r1.feedbacks left join fetch r1.assessor \"\n + \"left join fetch conflict.secondFeedback f2 left join fetch f2.result r2 left join fetch r2.submission left join fetch r2.feedbacks left join fetch r2.assessor \"\n + \"where conflict.conflict = true and (conflict.firstFeedback.id = :feedbackId or conflict.secondFeedback.id = :feedbackId)\")\n List<FeedbackConflict> findAllWithEagerFeedbackResultAndSubmissionByFeedbackId(@Param(\"feedbackId\") Long feedbackId);\n\n @Query(\"select distinct conflict from FeedbackConflict conflict where conflict.conflict = true and (conflict.firstFeedback.id in (:feedbackIds) or conflict.secondFeedback.id in (:feedbackIds))\")\n List<FeedbackConflict> findAllConflictsByFeedbackList(@Param(\"feedbackIds\") List<Long> feedbackIds);\n\n List<FeedbackConflict> findByFirstFeedbackIdAndConflict(Long id, Boolean conflict);\n\n List<FeedbackConflict> findBySecondFeedbackIdAndConflict(Long id, Boolean conflict);\n\n @Query(\"select distinct conflict from FeedbackConflict conflict where (conflict.conflict = true or conflict.discard = true) and \"\n + \"((conflict.firstFeedback.id = :firstFeedbackId and conflict.secondFeedback.id = :secondFeedbackId) or \"\n + \"(conflict.secondFeedback.id = :firstFeedbackId and conflict.firstFeedback.id = :secondFeedbackId))\")\n List<FeedbackConflict> findConflictsOrDiscardedOnesByFirstAndSecondFeedback(@Param(\"firstFeedbackId\") Long firstFeedbackId, @Param(\"secondFeedbackId\") Long secondFeedbackId);\n\n @Query(\"select distinct conflict from FeedbackConflict conflict \" + \"left join fetch conflict.firstFeedback f1 left join fetch f1.result r1 left join fetch r1.assessor \"\n + \"left join fetch conflict.secondFeedback f2 left join fetch f2.result r2 left join fetch r2.assessor \" + \"where conflict.id = :feedbackConflictId\")\n Optional<FeedbackConflict> findByFeedbackConflictId(@Param(\"feedbackConflictId\") Long feedbackConflictId);\n}\n" }, { "alpha_fraction": 0.6286096572875977, "alphanum_fraction": 0.6293109059333801, "avg_line_length": 43.064605712890625, "blob_id": "13fda15e60b30a4257b6a2cb34716a063bef5b59", "content_id": "9e93a9bfa4cd43e415cb9f3f0648bd6630846f52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 15687, "license_type": "permissive", "max_line_length": 180, "num_lines": 356, "path": "/src/main/webapp/app/exercises/shared/exercise-scores/exercise-scores.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core';\nimport { Subscription } from 'rxjs/Subscription';\nimport { ActivatedRoute } from '@angular/router';\nimport { DifferencePipe } from 'ngx-moment';\nimport { HttpResponse } from '@angular/common/http';\nimport * as moment from 'moment';\nimport { Moment } from 'moment';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { SourceTreeService } from 'app/exercises/programming/shared/service/sourceTree.service';\nimport { take, tap } from 'rxjs/operators';\nimport { of, zip, forkJoin } from 'rxjs';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { areManualResultsAllowed } from 'app/exercises/shared/exercise/exercise-utils';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { AssessmentType } from 'app/entities/assessment-type.model';\nimport { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { SubmissionExerciseType } from 'app/entities/submission.model';\nimport { formatTeamAsSearchResult } from 'app/exercises/shared/team/team.utils';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { defaultLongDateTimeFormat } from 'app/shared/pipes/artemis-date.pipe';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { addUserIndependentRepositoryUrl } from 'app/overview/participation-utils';\nimport { round } from 'app/shared/util/utils';\n\n/**\n * Filter properties for a result\n */\nenum FilterProp {\n ALL = 'all',\n SUCCESSFUL = 'successful',\n UNSUCCESSFUL = 'unsuccessful',\n BUILD_FAILED = 'build-failed',\n MANUAL = 'manual',\n AUTOMATIC = 'automatic',\n}\n\n@Component({\n selector: 'jhi-exercise-scores',\n styleUrls: ['./exercise-scores.component.scss'],\n templateUrl: './exercise-scores.component.html',\n providers: [ModelingAssessmentService, SourceTreeService],\n encapsulation: ViewEncapsulation.None,\n})\nexport class ExerciseScoresComponent implements OnInit, OnDestroy {\n // make constants available to html for comparison\n readonly FilterProp = FilterProp;\n readonly ExerciseType = ExerciseType;\n readonly FeatureToggle = FeatureToggle;\n\n course: Course;\n exercise: Exercise;\n paramSub: Subscription;\n reverse: boolean;\n results: Result[];\n filteredResultsSize: number;\n eventSubscriber: Subscription;\n newManualResultAllowed: boolean;\n\n resultCriteria: {\n filterProp: FilterProp;\n };\n\n isLoading: boolean;\n\n constructor(\n private route: ActivatedRoute,\n private momentDiff: DifferencePipe,\n private courseService: CourseManagementService,\n private exerciseService: ExerciseService,\n private accountService: AccountService,\n private resultService: ResultService,\n private profileService: ProfileService,\n private programmingSubmissionService: ProgrammingSubmissionService,\n ) {\n this.resultCriteria = {\n filterProp: FilterProp.ALL,\n };\n this.results = [];\n this.filteredResultsSize = 0;\n }\n\n /**\n * Fetches the course and exercise from the server\n */\n ngOnInit() {\n this.paramSub = this.route.params.subscribe((params) => {\n this.isLoading = true;\n const findCourse = this.courseService.find(params['courseId']);\n const findExercise = this.exerciseService.find(params['exerciseId']);\n\n forkJoin(findCourse, findExercise).subscribe(([courseRes, exerciseRes]) => {\n this.course = courseRes.body!;\n this.exercise = exerciseRes.body!;\n // After both calls are done, the loading flag is removed. If the exercise is not a programming exercise, only the result call is needed.\n zip(this.getResults(), this.loadAndCacheProgrammingExerciseSubmissionState())\n .pipe(take(1))\n .subscribe(() => (this.isLoading = false));\n this.exercise.isAtLeastTutor = this.accountService.isAtLeastTutorInCourse(this.course || this.exercise.exerciseGroup!.exam!.course);\n this.exercise.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.course || this.exercise.exerciseGroup!.exam!.course);\n this.newManualResultAllowed = areManualResultsAllowed(this.exercise);\n });\n });\n }\n\n getExerciseParticipationsLink(participationId: number): string[] {\n return !!this.exercise.exerciseGroup\n ? [\n '/course-management',\n this.course.id!.toString(),\n 'exams',\n this.exercise.exerciseGroup!.exam!.id!.toString(),\n 'exercise-groups',\n this.exercise.exerciseGroup!.id!.toString(),\n 'exercises',\n this.exercise.id!.toString(),\n 'participations',\n participationId.toString(),\n ]\n : ['/course-management', this.course.id!.toString(), 'exercises', this.exercise.id!.toString(), 'participations', participationId.toString(), 'submissions'];\n }\n\n /**\n * We need to preload the pending submissions here, otherwise every updating-result would trigger a single REST call.\n * Will return immediately if the exercise is not of type PROGRAMMING.\n */\n private loadAndCacheProgrammingExerciseSubmissionState() {\n // TODO: this is deactivated because of performance reasons as it would lead quickly to thousands of subscribed websocket topics\n // return this.exercise.type === ExerciseType.PROGRAMMING ? this.programmingSubmissionService.getSubmissionStateOfExercise(this.exercise.id) : of(undefined);\n return of(undefined);\n }\n\n /**\n * Fetches all results for an exercise and assigns them to the results in this component\n */\n getResults() {\n return this.resultService\n .getResultsForExercise(this.exercise.id!, {\n withSubmissions: this.exercise.type === ExerciseType.MODELING,\n })\n .pipe(\n tap((res: HttpResponse<Result[]>) => {\n this.results = res.body!.map((result) => {\n result.participation!.results = [result];\n (result.participation! as StudentParticipation).exercise = this.exercise;\n if (result.participation!.type === ParticipationType.PROGRAMMING) {\n addUserIndependentRepositoryUrl(result.participation!);\n }\n result.durationInMinutes = this.durationInMinutes(\n result.completionDate!,\n result.participation!.initializationDate ? result.participation!.initializationDate : this.exercise.releaseDate!,\n );\n // Nest submission into participation so that it is available for the result component\n if (result.participation && result.submission) {\n result.participation.submissions = [result.submission];\n }\n return result;\n });\n }),\n );\n }\n\n /**\n * Updates the criteria by which to filter results\n * @param newValue New filter prop value\n */\n updateResultFilter(newValue: FilterProp) {\n this.isLoading = true;\n setTimeout(() => {\n this.resultCriteria.filterProp = newValue;\n this.isLoading = false;\n });\n }\n\n /**\n * Predicate used to filter results by the current filter prop setting\n * @param result Result for which to evaluate the predicate\n */\n filterResultByProp = (result: Result) => {\n switch (this.resultCriteria.filterProp) {\n case FilterProp.SUCCESSFUL:\n return result.successful;\n case FilterProp.UNSUCCESSFUL:\n return !result.successful;\n case FilterProp.BUILD_FAILED:\n return (\n result.submission && result.submission.submissionExerciseType === SubmissionExerciseType.PROGRAMMING && (result.submission as ProgrammingSubmission).buildFailed\n );\n case FilterProp.MANUAL:\n return Result.isManualResult(result);\n case FilterProp.AUTOMATIC:\n return result.assessmentType === AssessmentType.AUTOMATIC;\n default:\n return true;\n }\n };\n\n /**\n * Update the number of filtered results\n *\n * @param filteredResultsSize Total number of results after filters have been applied\n */\n handleResultsSizeChange = (filteredResultsSize: number) => {\n this.filteredResultsSize = filteredResultsSize;\n };\n\n private durationInMinutes(completionDate: Moment, initializationDate: Moment) {\n return this.momentDiff.transform(completionDate, initializationDate, 'minutes');\n }\n\n /**\n * Returns the build plan id for a result\n * @param result Result for which to return the build plan id\n */\n buildPlanId(result: Result) {\n return (result.participation as ProgrammingExerciseStudentParticipation)?.buildPlanId;\n }\n\n /**\n * Returns the project key of the exercise\n */\n projectKey(): string {\n return (this.exercise as ProgrammingExercise).projectKey!;\n }\n\n /**\n * Returns the link to the repository of a result\n * @param result Result for which to get the link for\n */\n getRepositoryLink(result: Result) {\n return (result.participation! as ProgrammingExerciseStudentParticipation).userIndependentRepositoryUrl;\n }\n\n /**\n * Exports the names of exercise participants as a csv file\n */\n exportNames() {\n if (this.results.length > 0) {\n const rows: string[] = [];\n this.results.forEach((result, index) => {\n const studentParticipation = result.participation! as StudentParticipation;\n const { participantName } = studentParticipation;\n if (studentParticipation.team) {\n if (index === 0) {\n rows.push('data:text/csv;charset=utf-8,Team Name,Team Short Name,Students');\n }\n const { name, shortName, students } = studentParticipation.team;\n rows.push(`${name},${shortName},\"${students?.map((s) => s.name).join(', ')}\"`);\n } else {\n rows.push(index === 0 ? `data:text/csv;charset=utf-8,${participantName}` : participantName!);\n }\n });\n const csvContent = rows.join('\\n');\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement('a');\n link.setAttribute('href', encodedUri);\n link.setAttribute('download', 'results-names.csv');\n document.body.appendChild(link); // Required for FF\n link.click();\n }\n }\n\n /**\n * Exports the exercise results as a csv file\n */\n exportResults() {\n if (this.results.length > 0) {\n const rows: string[] = [];\n this.results.forEach((result, index) => {\n const studentParticipation = result.participation! as StudentParticipation;\n const { participantName, participantIdentifier } = studentParticipation;\n const score = round(result.score);\n\n if (index === 0) {\n const nameAndUserNameColumnHeaders = studentParticipation.team ? 'Team Name,Team Short Name' : 'Name,Username';\n const optionalStudentsColumnHeader = studentParticipation.team ? ',Students' : '';\n if (this.exercise.type !== ExerciseType.PROGRAMMING) {\n rows.push(`data:text/csv;charset=utf-8,${nameAndUserNameColumnHeaders},Score${optionalStudentsColumnHeader}`);\n } else {\n rows.push(`data:text/csv;charset=utf-8,${nameAndUserNameColumnHeaders},Score,Repo Link${optionalStudentsColumnHeader}`);\n }\n }\n const optionalStudentsColumnValue = studentParticipation.team ? `,\"${studentParticipation.team?.students?.map((s) => s.name).join(', ')}\"` : '';\n if (this.exercise.type !== ExerciseType.PROGRAMMING) {\n rows.push(`${participantName},${participantIdentifier},${score}${optionalStudentsColumnValue}`);\n } else {\n const repoLink = (studentParticipation as ProgrammingExerciseStudentParticipation).repositoryUrl;\n rows.push(`${participantName},${participantIdentifier},${score},${repoLink}${optionalStudentsColumnValue}`);\n }\n });\n const csvContent = rows.join('\\n');\n const encodedUri = encodeURI(csvContent);\n const link = document.createElement('a');\n link.setAttribute('href', encodedUri);\n link.setAttribute('download', 'results-scores.csv');\n document.body.appendChild(link); // Required for FF\n link.click();\n }\n }\n\n /**\n * Formats the results in the autocomplete overlay.\n *\n * @param result\n */\n searchResultFormatter = (result: Result) => {\n const participation = result.participation as StudentParticipation;\n if (participation.student) {\n const { login, name } = participation.student;\n return `${login} (${name})`;\n } else if (participation.team) {\n return formatTeamAsSearchResult(participation.team);\n }\n };\n\n /**\n * Converts a result object to a string that can be searched for. This is\n * used by the autocomplete select inside the data table.\n *\n * @param result\n */\n searchTextFromResult = (result: Result): string => {\n return (result.participation as StudentParticipation).participantIdentifier || '';\n };\n\n /**\n * Triggers a re-fetch of the results from the server\n */\n refresh() {\n this.isLoading = true;\n this.results = [];\n this.getResults().subscribe(() => (this.isLoading = false));\n }\n\n /**\n * Unsubscribes from all subscriptions\n */\n ngOnDestroy() {\n this.paramSub.unsubscribe();\n this.programmingSubmissionService.unsubscribeAllWebsocketTopics(this.exercise);\n }\n\n formatDate(date: Moment | Date | undefined) {\n // TODO: we should try to use the artemis date pipe here\n return date ? moment(date).format(defaultLongDateTimeFormat) : '';\n }\n}\n" }, { "alpha_fraction": 0.7130158543586731, "alphanum_fraction": 0.7149206399917603, "avg_line_length": 49, "blob_id": "80b4e276dccc1d3e8419bb18ff624378f3788643", "content_id": "fe81c981fc63852fc39c31562fc01bdb59727a5f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3150, "license_type": "permissive", "max_line_length": 167, "num_lines": 63, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as moment from 'moment';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockComponent } from 'ng-mocks';\nimport { ProgrammingExerciseLifecycleComponent } from 'app/exercises/programming/manage/update/programming-exercise-lifecycle.component';\nimport { HelpIconComponent } from 'app/shared/components/help-icon.component';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseTestScheduleDatePickerComponent } from 'app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseTestSchedulePickerComponent', () => {\n let comp: ProgrammingExerciseLifecycleComponent;\n let fixture: ComponentFixture<ProgrammingExerciseLifecycleComponent>;\n\n const nextDueDate = moment().add(5, 'days');\n const afterDueDate = moment().add(7, 'days');\n const exercise = { id: 42, dueDate: nextDueDate, buildAndTestStudentSubmissionsAfterDueDate: afterDueDate } as ProgrammingExercise;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule],\n declarations: [ProgrammingExerciseLifecycleComponent, MockComponent(ProgrammingExerciseTestScheduleDatePickerComponent), MockComponent(HelpIconComponent)],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseLifecycleComponent);\n comp = fixture.componentInstance;\n });\n });\n\n it('should do nothing if the release date is set to null', () => {\n comp.exercise = exercise;\n comp.updateReleaseDate(undefined);\n\n expect(comp.exercise.dueDate).to.be.equal(nextDueDate);\n expect(comp.exercise.buildAndTestStudentSubmissionsAfterDueDate).to.be.equal(afterDueDate);\n });\n\n it('should only reset the due date if the release date is between the due date and the after due date', () => {\n comp.exercise = exercise;\n const newRelease = moment().add(6, 'days');\n comp.updateReleaseDate(newRelease);\n\n expect(comp.exercise.dueDate).to.be.equal(newRelease);\n expect(comp.exercise.buildAndTestStudentSubmissionsAfterDueDate).to.be.equal(afterDueDate);\n });\n\n it('should reset both the due date and the after due date if the new release is after both dates', () => {\n comp.exercise = exercise;\n const newRelease = moment().add(8, 'days');\n comp.updateReleaseDate(newRelease);\n\n expect(comp.exercise.dueDate).to.be.equal(newRelease);\n expect(comp.exercise.buildAndTestStudentSubmissionsAfterDueDate).to.be.equal(newRelease);\n });\n});\n" }, { "alpha_fraction": 0.6736842393875122, "alphanum_fraction": 0.6736842393875122, "avg_line_length": 24, "blob_id": "8e66ff14db6e4c8183679aea58175beb7358bbc4", "content_id": "90d1cabbaf2752f13e98367847a78ac944b4907d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 475, "license_type": "permissive", "max_line_length": 88, "num_lines": 19, "path": "/src/main/webapp/app/shared/markdown-editor/domainCommands/domainMultiOptionCommand.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { DomainCommand } from 'app/shared/markdown-editor/domainCommands/domainCommand';\n\nexport type ValueItem = {\n id: string;\n value: string;\n};\n\n/**\n * This domain command will be used as a dropdown in the markdown editor.\n */\nexport abstract class DomainMultiOptionCommand extends DomainCommand {\n protected values: ValueItem[] = [];\n setValues(values: ValueItem[]) {\n this.values = values;\n }\n getValues() {\n return this.values;\n }\n}\n" }, { "alpha_fraction": 0.5997161269187927, "alphanum_fraction": 0.6014904379844666, "avg_line_length": 38.69013977050781, "blob_id": "a9c04aac7e7bb22991e8163ec60f4c9688dab36b", "content_id": "9f78c25ca9047f8829f6e51e3a9554780fcb8dcb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2818, "license_type": "permissive", "max_line_length": 125, "num_lines": 71, "path": "/src/test/javascript/spec/component/overview/course-exams/course-exams.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { CourseExamsComponent } from 'app/overview/course-exams/course-exams.component';\nimport { Exam } from 'app/entities/exam.model';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport * as moment from 'moment';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseExamsComponent', () => {\n let component: CourseExamsComponent;\n let componentFixture: ComponentFixture<CourseExamsComponent>;\n\n const visibleExam = {\n id: 1,\n visibleDate: moment().subtract(2, 'days'),\n } as Exam;\n\n const notVisibleExam = {\n id: 2,\n visibleDate: moment().add(2, 'days'),\n } as Exam;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule, RouterTestingModule.withRoutes([])],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n params: {\n subscribe: (fn: (value: any) => void) => fn(1),\n },\n },\n },\n },\n { provide: AccountService, useClass: MockAccountService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n ],\n declarations: [CourseExamsComponent],\n })\n .overrideTemplate(CourseExamsComponent, '')\n .compileComponents()\n .then(() => {\n componentFixture = TestBed.createComponent(CourseExamsComponent);\n component = componentFixture.componentInstance;\n });\n });\n\n it('exam should be visible', () => {\n componentFixture.detectChanges();\n expect(component.isVisible(visibleExam)).to.be.true;\n });\n\n it('exam should not be visible', () => {\n componentFixture.detectChanges();\n expect(component.isVisible(notVisibleExam)).to.false;\n });\n});\n" }, { "alpha_fraction": 0.6764705777168274, "alphanum_fraction": 0.7352941036224365, "avg_line_length": 33, "blob_id": "7a80aafd108f27cfae900a784db4e5720005a95e", "content_id": "575ab2b04af70f76944f196918eefab6a6e07c5c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 34, "license_type": "permissive", "max_line_length": 33, "num_lines": 1, "path": "/src/main/webapp/app/shared/constants/pagination.constants.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export const ITEMS_PER_PAGE = 50;\n" }, { "alpha_fraction": 0.7199417948722839, "alphanum_fraction": 0.7289665341377258, "avg_line_length": 47.38028335571289, "blob_id": "2392ef45b5886653efd1ee708684b0f8bffca89f", "content_id": "4f442a79b30ed6d21edc1f27e15ce606b8ce2a4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3435, "license_type": "permissive", "max_line_length": 179, "num_lines": 71, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/StatisticsResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.enumeration.GraphType;\nimport de.tum.in.www1.artemis.domain.enumeration.SpanType;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseManagementStatisticsDTO;\n\n/**\n * REST controller for managing statistics.\n */\n@RestController\n@RequestMapping(\"/api\")\n@PreAuthorize(\"hasRole('TA')\")\npublic class StatisticsResource {\n\n private final Logger log = LoggerFactory.getLogger(StatisticsResource.class);\n\n private final StatisticsService service;\n\n public StatisticsResource(StatisticsService service) {\n this.service = service;\n }\n\n /**\n * GET management/statistics/data : get the graph data in the last \"span\" days in the given period.\n *\n * @param span the spantime of which the amount should be calculated\n * @param periodIndex an index indicating which time period, 0 is current week, -1 is one week in the past, -2 is two weeks in the past ...\n * @param graphType the type of graph the data should be fetched\n * @return the ResponseEntity with status 200 (OK) and the data in body, or status 404 (Not Found)\n */\n @GetMapping(\"management/statistics/data\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<Integer[]> getChartData(@RequestParam SpanType span, @RequestParam Integer periodIndex, @RequestParam GraphType graphType) {\n log.debug(\"REST request to get graph data\");\n return ResponseEntity.ok(this.service.getChartData(span, periodIndex, graphType, null));\n }\n\n /**\n * GET management/statistics/data-for-course : get the graph data in the last \"span\" days in the given period for a specific course.\n *\n * @param span the spantime of which the amount should be calculated\n * @param periodIndex an index indicating which time period, 0 is current week, -1 is one week in the past, -2 is two weeks in the past ...\n * @param graphType the type of graph the data should be fetched\n * @param courseId the id of the course for which the data should be fetched\n * @return the ResponseEntity with status 200 (OK) and the data in body, or status 404 (Not Found)\n */\n @GetMapping(\"management/statistics/data-for-course\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Integer[]> getChartData(@RequestParam SpanType span, @RequestParam Integer periodIndex, @RequestParam GraphType graphType, @RequestParam Long courseId) {\n return ResponseEntity.ok(this.service.getChartData(span, periodIndex, graphType, courseId));\n }\n\n /**\n * GET management/statistics/course-statistics : get the data for the doughnut graphs in the course statistics\n *\n * @param courseId the id of the course for which the data should be fetched\n * @return the ResponseEntity with status 200 (OK) and the data in body, or status 404 (Not Found)\n */\n @GetMapping(\"management/statistics/course-statistics\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<CourseManagementStatisticsDTO> getCourseStatistics(@RequestParam Long courseId) {\n return ResponseEntity.ok(this.service.getCourseStatistics(courseId));\n }\n}\n" }, { "alpha_fraction": 0.6957707405090332, "alphanum_fraction": 0.6982749104499817, "avg_line_length": 39.382022857666016, "blob_id": "33256e28024f7862b97cfe634cdcb179a4f6fd79", "content_id": "27497b993620a8dc625f3a92fa640e57b3b612a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 17970, "license_type": "permissive", "max_line_length": 172, "num_lines": 445, "path": "/src/test/java/de/tum/in/www1/artemis/util/UserTestService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.util;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.io.IOException;\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cache.CacheManager;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.LinkedMultiValueMap;\n\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.programmingexercise.MockDelegate;\nimport de.tum.in.www1.artemis.repository.AuthorityRepository;\nimport de.tum.in.www1.artemis.repository.CourseRepository;\nimport de.tum.in.www1.artemis.repository.UserRepository;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.dto.UserDTO;\nimport de.tum.in.www1.artemis.service.user.PasswordService;\nimport de.tum.in.www1.artemis.web.rest.vm.ManagedUserVM;\n\n/**\n * Note: this class should be independent of the actual VCS and CIS and contains common test logic for both scenarios:\n * 1) Bamboo + Bitbucket\n * 2) Jenkins + Gitlab\n */\n@Service\npublic class UserTestService {\n\n @Autowired\n private DatabaseUtilService database;\n\n @Autowired\n private AuthorityRepository authorityRepository;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n PasswordService passwordService;\n\n @Autowired\n private CacheManager cacheManager;\n\n @Autowired\n private CourseRepository courseRepository;\n\n @Autowired\n protected RequestUtilService request;\n\n private MockDelegate mockDelegate;\n\n private User student;\n\n private final int numberOfStudents = 50;\n\n private final int numberOfTutors = 1;\n\n private final int numberOfInstructors = 1;\n\n public void setup(MockDelegate mockDelegate) throws Exception {\n this.mockDelegate = mockDelegate;\n\n List<User> users = database.addUsers(numberOfStudents, numberOfTutors, numberOfInstructors);\n student = users.get(0);\n users.forEach(user -> cacheManager.getCache(UserRepository.USERS_CACHE).evict(user.getLogin()));\n }\n\n public void tearDown() throws IOException {\n database.resetDatabase();\n }\n\n public User getStudent() {\n return student;\n }\n\n // Test\n public void deleteUser_isSuccessful() throws Exception {\n mockDelegate.mockDeleteUserInUserManagement(student, true, false, false);\n\n request.delete(\"/api/users/\" + student.getLogin(), HttpStatus.OK);\n\n var deletedUser = userRepository.findById(student.getId());\n assertThat(deletedUser).isEmpty();\n }\n\n // Test\n public void deleteUser_doesntExistInUserManagement_isSuccessful() throws Exception {\n mockDelegate.mockDeleteUserInUserManagement(student, false, false, false);\n\n request.delete(\"/api/users/\" + student.getLogin(), HttpStatus.OK);\n\n var deletedUser = userRepository.findById(student.getId());\n assertThat(deletedUser).isEmpty();\n }\n\n // Test\n public void deleteUser_FailsInExternalCiUserManagement_isNotSuccessful() throws Exception {\n mockDelegate.mockDeleteUserInUserManagement(student, true, false, true);\n\n request.delete(\"/api/users/\" + student.getLogin(), HttpStatus.INTERNAL_SERVER_ERROR);\n\n var deletedUser = userRepository.findById(student.getId());\n assertThat(deletedUser).isNotEmpty();\n }\n\n // Test\n public void deleteUser_FailsInExternalVcsUserManagement_isNotSuccessful() throws Exception {\n mockDelegate.mockDeleteUserInUserManagement(student, false, true, false);\n\n request.delete(\"/api/users/\" + student.getLogin(), HttpStatus.INTERNAL_SERVER_ERROR);\n\n var deletedUser = userRepository.findById(student.getId());\n assertThat(deletedUser).isNotEmpty();\n }\n\n // Test\n public void updateUser_asAdmin_isSuccessful() throws Exception {\n final var newPassword = \"bonobo42\";\n final var newEmail = \"[email protected]\";\n final var newFirstName = \"Bruce\";\n final var newGroups = Set.of(\"foo\", \"bar\");\n final var newLastName = \"Wayne\";\n final var newImageUrl = \"foobar.png\";\n final var newLangKey = \"DE\";\n final var newAuthorities = Set.of(Role.TEACHING_ASSISTANT.getAuthority()).stream().map(authorityRepository::findById).filter(Optional::isPresent).map(Optional::get)\n .collect(Collectors.toSet());\n final var oldGroups = student.getGroups();\n student.setAuthorities(newAuthorities);\n student.setEmail(newEmail);\n student.setFirstName(newFirstName);\n student.setGroups(newGroups);\n student.setLastName(newLastName);\n student.setImageUrl(newImageUrl);\n student.setLangKey(newLangKey);\n\n student.setPassword(newPassword);\n mockDelegate.mockUpdateUserInUserManagement(student.getLogin(), student, oldGroups);\n\n var managedUserVM = new ManagedUserVM(student);\n managedUserVM.setPassword(newPassword);\n final var response = request.putWithResponseBody(\"/api/users\", managedUserVM, User.class, HttpStatus.OK);\n final var updatedUserIndDB = userRepository.findOneWithGroupsAndAuthoritiesByLogin(student.getLogin()).get();\n updatedUserIndDB.setPassword(passwordService.decryptPasswordByLogin(updatedUserIndDB.getLogin()).get());\n\n assertThat(response).isNotNull();\n response.setPassword(passwordService.decryptPasswordByLogin(response.getLogin()).get());\n assertThat(student).as(\"Returned user is equal to sent update\").isEqualTo(response);\n assertThat(student).as(\"Updated user in DB is equal to sent update\").isEqualTo(updatedUserIndDB);\n }\n\n // Test\n public void updateUser_withNullPassword_oldPasswordNotChanged() throws Exception {\n student.setPassword(null);\n final var oldPassword = userRepository.findById(student.getId()).get().getPassword();\n mockDelegate.mockUpdateUserInUserManagement(student.getLogin(), student, student.getGroups());\n\n request.put(\"/api/users\", new ManagedUserVM(student), HttpStatus.OK);\n final var userInDB = userRepository.findById(student.getId()).get();\n\n assertThat(oldPassword).as(\"Password did not change\").isEqualTo(userInDB.getPassword());\n }\n\n // Test\n public void updateUserLogin() throws Exception {\n var oldLogin = student.getLogin();\n student.setLogin(\"new-login\");\n mockDelegate.mockUpdateUserInUserManagement(oldLogin, student, student.getGroups());\n\n request.put(\"/api/users\", new ManagedUserVM(student), HttpStatus.OK);\n final var userInDB = userRepository.findById(student.getId()).get();\n\n assertThat(userInDB.getLogin()).isEqualTo(student.getLogin());\n assertThat(userInDB.getId()).isEqualTo(student.getId());\n }\n\n // Test\n public void updateUser_withExternalUserManagement() throws Exception {\n student.setFirstName(\"changed\");\n mockDelegate.mockUpdateUserInUserManagement(student.getLogin(), student, student.getGroups());\n\n request.put(\"/api/users\", new ManagedUserVM(student), HttpStatus.OK);\n\n var updatedUser = userRepository.findById(student.getId());\n assertThat(updatedUser).isPresent();\n assertThat(updatedUser.get().getFirstName()).isEqualTo(\"changed\");\n }\n\n // Test\n public void updateUserGroups() throws Exception {\n var course = database.addEmptyCourse();\n database.addProgrammingExerciseToCourse(course, false);\n courseRepository.save(course);\n\n // First we create a new user with group\n student.setGroups(Set.of(\"instructor\"));\n student = userRepository.save(student);\n\n // We will then update the user by modifying the groups\n var updatedUser = student;\n updatedUser.setGroups(Set.of(\"tutor\"));\n mockDelegate.mockUpdateUserInUserManagement(student.getLogin(), updatedUser, student.getGroups());\n request.put(\"/api/users\", new ManagedUserVM(updatedUser), HttpStatus.OK);\n\n var updatedUserOrEmpty = userRepository.findOneWithGroupsAndAuthoritiesByLogin(updatedUser.getLogin());\n assertThat(updatedUserOrEmpty).isPresent();\n\n updatedUser = updatedUserOrEmpty.get();\n assertThat(updatedUser.getId()).isEqualTo(student.getId());\n assertThat(updatedUser.getGroups().size()).isEqualTo(1);\n assertThat(updatedUser.getGroups()).contains(\"tutor\");\n }\n\n // Test\n public void createUser_asAdmin_isSuccessful() throws Exception {\n student.setId(null);\n student.setLogin(\"batman\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockCreateUserInUserManagement(student, false);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.CREATED);\n assertThat(response).isNotNull();\n final var userInDB = userRepository.findById(response.getId()).get();\n userInDB.setPassword(passwordService.decryptPasswordByLogin(userInDB.getLogin()).get());\n student.setId(response.getId());\n response.setPassword(\"foobar\");\n\n assertThat(student).as(\"New user is equal to request response\").isEqualTo(response);\n assertThat(student).as(\"New user is equal to new user in DB\").isEqualTo(userInDB);\n }\n\n // Test\n public void createUser_asAdmin_existsInCi_internalError() throws Exception {\n student.setId(null);\n student.setLogin(\"batman\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockCreateUserInUserManagement(student, true);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.INTERNAL_SERVER_ERROR);\n assertThat(response).isNull();\n }\n\n // Test\n public void createUser_asAdmin_illegalLogin_internalError() throws Exception {\n student.setId(null);\n student.setLogin(\"@someusername\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockCreateUserInUserManagement(student, false);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.INTERNAL_SERVER_ERROR);\n assertThat(response).isNull();\n }\n\n // Test\n public void createUser_asAdmin_failInExternalCiUserManagement_internalError() throws Exception {\n student.setId(null);\n student.setLogin(\"batman\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockFailToCreateUserInExernalUserManagement(student, false, true, false);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.INTERNAL_SERVER_ERROR);\n assertThat(response).isNull();\n }\n\n // Test\n public void createUser_asAdmin_failInExternalCiUserManagement_cannotGetCiUser_internalError() throws Exception {\n student.setId(null);\n student.setLogin(\"batman\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockFailToCreateUserInExernalUserManagement(student, false, false, true);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.INTERNAL_SERVER_ERROR);\n assertThat(response).isNull();\n }\n\n // Test\n public void createUser_asAdmin_failInExternalVcsUserManagement_internalError() throws Exception {\n student.setId(null);\n student.setLogin(\"batman\");\n student.setPassword(\"foobar\");\n student.setEmail(\"[email protected]\");\n\n mockDelegate.mockFailToCreateUserInExernalUserManagement(student, true, false, false);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.INTERNAL_SERVER_ERROR);\n assertThat(response).isNull();\n }\n\n // Test\n public void createUser_withNullAsPassword_generatesRandomPassword() throws Exception {\n student.setId(null);\n student.setEmail(\"[email protected]\");\n student.setLogin(\"batman\");\n student.setPassword(null);\n\n mockDelegate.mockCreateUserInUserManagement(student, false);\n\n final var response = request.postWithResponseBody(\"/api/users\", new ManagedUserVM(student), User.class, HttpStatus.CREATED);\n assertThat(response).isNotNull();\n final var userInDB = userRepository.findById(response.getId()).get();\n\n assertThat(userInDB.getPassword()).isNotBlank();\n }\n\n // Test\n public void createUser_withExternalUserManagement() throws Exception {\n var newUser = student;\n newUser.setId(null);\n newUser.setLogin(\"batman\");\n newUser.setEmail(\"[email protected]\");\n\n mockDelegate.mockCreateUserInUserManagement(newUser, false);\n\n request.post(\"/api/users\", new ManagedUserVM(newUser), HttpStatus.CREATED);\n\n var createdUser = userRepository.findOneByEmailIgnoreCase(newUser.getEmail());\n assertThat(createdUser).isPresent();\n assertThat(createdUser.get().getId()).isNotNull();\n }\n\n // Test\n public void createUserWithGroups() throws Exception {\n var course = database.addEmptyCourse();\n database.addProgrammingExerciseToCourse(course, false);\n courseRepository.save(course);\n\n var newUser = student;\n newUser.setId(null);\n newUser.setLogin(\"batman\");\n newUser.setEmail(\"[email protected]\");\n newUser.setGroups(Set.of(\"tutor\", \"instructor\"));\n\n mockDelegate.mockCreateUserInUserManagement(newUser, false);\n\n request.post(\"/api/users\", new ManagedUserVM(newUser), HttpStatus.CREATED);\n\n var createdUserOrEmpty = userRepository.findOneWithGroupsAndAuthoritiesByLogin(newUser.getLogin());\n assertThat(createdUserOrEmpty).isPresent();\n\n var createdUser = createdUserOrEmpty.get();\n assertThat(createdUser.getId()).isNotNull();\n assertThat(createdUser.getGroups().size()).isEqualTo(2);\n assertThat(createdUser.getGroups()).isEqualTo(newUser.getGroups());\n }\n\n // Test\n public void getUsers_asAdmin_isSuccessful() throws Exception {\n final var params = new LinkedMultiValueMap<String, String>();\n params.add(\"page\", \"0\");\n params.add(\"pageSize\", \"100\");\n params.add(\"searchTerm\", \"\");\n params.add(\"sortingOrder\", \"ASCENDING\");\n params.add(\"sortedColumn\", \"id\");\n List<UserDTO> users = request.getList(\"/api/users\", HttpStatus.OK, UserDTO.class, params);\n assertThat(users).hasSize(numberOfStudents + numberOfTutors + numberOfInstructors + 1); // +1 for admin user himself\n }\n\n // Test\n public void searchUsers_asInstructor_isSuccessful() throws Exception {\n final String loginOrName = \"student1\";\n List<UserDTO> users = request.getList(\"/api/users/search?loginOrName=\" + loginOrName, HttpStatus.OK, UserDTO.class);\n assertThat(users).hasSize(11); // size([student1, student10, ... student19]) = 11\n }\n\n // Test\n public void searchUsers_asAdmin_badRequest() throws Exception {\n final String loginOrName = \"ab\"; // too short (needs at least 3 characters)\n request.getList(\"/api/users/search?loginOrName=\" + loginOrName, HttpStatus.BAD_REQUEST, UserDTO.class);\n }\n\n // Test\n public void searchUsers_asTutor_forbidden() throws Exception {\n final String loginOrName = \"student\";\n request.getList(\"/api/users/search?loginOrName=\" + loginOrName, HttpStatus.FORBIDDEN, UserDTO.class);\n }\n\n // Test\n public void getUserViaFilter_asAdmin_isSuccessful() throws Exception {\n final var params = new LinkedMultiValueMap<String, String>();\n params.add(\"page\", \"0\");\n params.add(\"pageSize\", \"100\");\n params.add(\"searchTerm\", \"[email protected]\");\n params.add(\"sortingOrder\", \"ASCENDING\");\n params.add(\"sortedColumn\", \"id\");\n List<User> users = request.getList(\"/api/users\", HttpStatus.OK, User.class, params);\n assertThat(users).hasSize(1);\n assertThat(users.get(0).getEmail()).isEqualTo(\"[email protected]\");\n }\n\n // Test\n public void getAuthorities_asAdmin_isSuccessful() throws Exception {\n List<String> authorities = request.getList(\"/api/users/authorities\", HttpStatus.OK, String.class);\n assertThat(authorities).isEqualTo(List.of(\"ROLE_ADMIN\", \"ROLE_INSTRUCTOR\", \"ROLE_TA\", \"ROLE_USER\"));\n }\n\n // Test\n public void getUsersOrAuthorities_asInstructor_forbidden() throws Exception {\n getUsersOrAuthorities_forbidden();\n }\n\n // Test\n public void getUsersOrAuthorities_asTutor_forbidden() throws Exception {\n getUsersOrAuthorities_forbidden();\n }\n\n // Test\n public void getUsersOrAuthorities_asStudent_forbidden() throws Exception {\n getUsersOrAuthorities_forbidden();\n }\n\n private void getUsersOrAuthorities_forbidden() throws Exception {\n request.getList(\"/api/users\", HttpStatus.FORBIDDEN, User.class);\n request.getList(\"/api/users/authorities\", HttpStatus.FORBIDDEN, String.class);\n }\n\n // Test\n public void getUser_asAdmin_isSuccessful() throws Exception {\n final String userLogin = \"student1\";\n UserDTO userDTO = request.get(\"/api/users/\" + userLogin, HttpStatus.OK, UserDTO.class);\n assertThat(userDTO.getLogin()).isEqualTo(userLogin);\n }\n\n // Test\n public void updateUserNotificationDate_asStudent_isSuccessful() throws Exception {\n request.put(\"/api/users/notification-date\", null, HttpStatus.OK);\n User userInDB = userRepository.findOneByLogin(\"student1\").get();\n assertThat(userInDB.getLastNotificationRead()).isAfterOrEqualTo(ZonedDateTime.now().minusSeconds(1));\n }\n}\n" }, { "alpha_fraction": 0.6750437021255493, "alphanum_fraction": 0.679632842540741, "avg_line_length": 41.766353607177734, "blob_id": "ec33f8f0f24590027718b79a57a22702c1af4ffa", "content_id": "a51203bc6eef3de94a9f2fa8d71f9e500179fdb3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4576, "license_type": "permissive", "max_line_length": 163, "num_lines": 107, "path": "/src/test/javascript/spec/component/course/course-participant-scores.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { CourseParticipantScoresComponent } from 'app/course/course-participant-scores/course-participant-scores.component';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslatePipe } from '@ngx-translate/core';\nimport { MockComponent, MockPipe, MockProvider } from 'ng-mocks';\nimport { of } from 'rxjs';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ActivatedRoute } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ParticipantScoreAverageDTO, ParticipantScoreDTO, ParticipantScoresService } from 'app/shared/participant-scores/participant-scores.service';\nimport * as chai from 'chai';\nimport { HttpResponse } from '@angular/common/http';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-participant-scores-tables-container', template: '<div></div>' })\nclass ParticipantScoresTableContainerStubComponent {\n @Input()\n isLoading: boolean;\n @Input()\n participantScores: ParticipantScoreDTO[] = [];\n @Input()\n participantScoresAverage: ParticipantScoreAverageDTO[] = [];\n @Input()\n avgScore = 0;\n @Input()\n avgRatedScore = 0;\n @Output()\n reload = new EventEmitter<void>();\n}\n\ndescribe('CourseParticipantScores', () => {\n let fixture: ComponentFixture<CourseParticipantScoresComponent>;\n let component: CourseParticipantScoresComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n declarations: [CourseParticipantScoresComponent, ParticipantScoresTableContainerStubComponent, MockPipe(TranslatePipe), MockComponent(AlertComponent)],\n providers: [\n MockProvider(ParticipantScoresService),\n MockProvider(JhiAlertService),\n {\n provide: ActivatedRoute,\n useValue: { params: of({ courseId: 1 }) },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseParticipantScoresComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should load date when initialized', () => {\n const participantScoreService = TestBed.inject(ParticipantScoresService);\n\n // stub find all of course\n const participantScoreDTO = new ParticipantScoreDTO();\n participantScoreDTO.id = 1;\n participantScoreDTO.userName = 'test';\n const findAllOfCourseResponse: HttpResponse<ParticipantScoreDTO[]> = new HttpResponse({\n body: [participantScoreDTO],\n status: 200,\n });\n const findAllOfCourseStub = sinon.stub(participantScoreService, 'findAllOfCourse').returns(of(findAllOfCourseResponse));\n // stub find average of course\n const participantScoreAverageDTO = new ParticipantScoreAverageDTO();\n participantScoreAverageDTO.userName = 'test';\n participantScoreAverageDTO.averageScore = 10;\n const findAverageOfCoursePerParticipantResponse: HttpResponse<ParticipantScoreAverageDTO[]> = new HttpResponse({\n body: [participantScoreAverageDTO],\n status: 200,\n });\n const findAverageOfCoursePerParticipantStub = sinon\n .stub(participantScoreService, 'findAverageOfCoursePerParticipant')\n .returns(of(findAverageOfCoursePerParticipantResponse));\n // stub find average of course\n const findAverageOfCourseResponse: HttpResponse<number> = new HttpResponse({\n body: 99,\n status: 200,\n });\n const findAverageOfCourseStub = sinon.stub(participantScoreService, 'findAverageOfCourse').returns(of(findAverageOfCourseResponse));\n\n fixture.detectChanges();\n\n expect(component.participantScores).to.deep.equal([participantScoreDTO]);\n expect(component.participantScoresAverage).to.deep.equal([participantScoreAverageDTO]);\n expect(component.avgScore).to.equal(99);\n expect(component.avgRatedScore).to.equal(99);\n expect(findAllOfCourseStub).to.have.been.called;\n expect(findAverageOfCoursePerParticipantStub).to.have.been.called;\n expect(findAverageOfCourseStub).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.6467409729957581, "alphanum_fraction": 0.649442732334137, "avg_line_length": 42.54411697387695, "blob_id": "a54af69f7d7ede0278992ef709e72300359a3696", "content_id": "88fef6f6599373889a71acadc30c578c0dbabd3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2961, "license_type": "permissive", "max_line_length": 113, "num_lines": 68, "path": "/src/test/javascript/spec/component/complaints/complaints.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport { By } from '@angular/platform-browser';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { MockComplaintResponse, MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service';\n\nimport { MomentModule } from 'ngx-moment';\nimport { DebugElement } from '@angular/core';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { ComplaintsComponent } from 'app/complaints/complaints.component';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { Exercise } from 'app/entities/exercise.model';\n\nconst expect = chai.expect;\ndescribe('ComplaintsComponent', () => {\n const exercise: Exercise = { id: 1, teamMode: false } as Exercise;\n let comp: ComplaintsComponent;\n let fixture: ComponentFixture<ComplaintsComponent>;\n let debugElement: DebugElement;\n\n beforeEach(async(() => {\n TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule, MomentModule],\n declarations: [ComplaintsComponent],\n providers: [\n {\n provide: ComplaintService,\n useClass: MockComplaintService,\n },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ComplaintsComponent);\n comp = fixture.componentInstance;\n comp.exercise = exercise;\n debugElement = fixture.debugElement;\n });\n }));\n\n it('should initialize with correct values for complaints service', fakeAsync(() => {\n fixture.detectChanges();\n expect(comp.complaintText).to.be.equal(MockComplaintResponse.body.complaintText);\n expect(comp.alreadySubmitted).to.be.true;\n expect(comp.submittedDate).to.be.undefined;\n expect(comp.accepted).to.be.undefined;\n expect(comp.handled).to.be.false;\n tick(1000);\n const textarea = debugElement.query(By.css('#complainTextArea')).nativeElement;\n expect(textarea.disabled).to.be.true;\n expect(textarea.value).to.be.equal(MockComplaintResponse.body.complaintText);\n expect(textarea.readOnly).to.be.true;\n }));\n\n it('should show accepted message when complaint is accepted', () => {\n comp.resultId = 111;\n comp.ngOnInit();\n fixture.detectChanges();\n expect(comp.alreadySubmitted).to.be.true;\n expect(comp.submittedDate).to.be.undefined;\n expect(comp.accepted).to.be.true;\n expect(comp.handled).to.be.true;\n\n expect(debugElement.query(By.css('.text-light.bg-success'))).to.be.not.null;\n });\n});\n" }, { "alpha_fraction": 0.738095223903656, "alphanum_fraction": 0.7422824501991272, "avg_line_length": 46.952754974365234, "blob_id": "3e14f8c349a0fe60998235bf7b9918eede1460a4", "content_id": "6844bfbbd36bd577eb2704c57b37effe0409d9c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 12180, "license_type": "permissive", "max_line_length": 179, "num_lines": 254, "path": "/src/test/java/de/tum/in/www1/artemis/service/connectors/LtiServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.junit.jupiter.api.Assertions.assertThrows;\nimport static org.mockito.ArgumentMatchers.anyString;\nimport static org.mockito.Mockito.*;\n\nimport java.util.*;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport org.apache.commons.lang3.tuple.Pair;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.springframework.security.authentication.InternalAuthenticationServiceException;\nimport org.springframework.security.authentication.UsernamePasswordAuthenticationToken;\nimport org.springframework.security.core.context.SecurityContextHolder;\nimport org.springframework.test.util.ReflectionTestUtils;\n\nimport de.tum.in.www1.artemis.authentication.AuthenticationIntegrationTestHelper;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.ArtemisAuthenticationProvider;\nimport de.tum.in.www1.artemis.service.user.UserCreationService;\nimport de.tum.in.www1.artemis.web.rest.dto.LtiLaunchRequestDTO;\n\npublic class LtiServiceTest {\n\n @Mock\n private UserCreationService userCreationService;\n\n @Mock\n private UserRepository userRepository;\n\n @Mock\n private LtiOutcomeUrlRepository ltiOutcomeUrlRepository;\n\n @Mock\n private ResultRepository resultRepository;\n\n @Mock\n private ArtemisAuthenticationProvider artemisAuthenticationProvider;\n\n @Mock\n private LtiUserIdRepository ltiUserIdRepository;\n\n @Mock\n private HttpServletResponse response;\n\n private Exercise exercise;\n\n private LtiService ltiService;\n\n private LtiLaunchRequestDTO launchRequest;\n\n private User user;\n\n private LtiUserId ltiUserId;\n\n private final String courseStudentGroupName = \"courseStudentGroupName\";\n\n private LtiOutcomeUrl ltiOutcomeUrl;\n\n @BeforeEach\n public void init() {\n MockitoAnnotations.openMocks(this);\n SecurityContextHolder.clearContext();\n ltiService = new LtiService(userCreationService, userRepository, ltiOutcomeUrlRepository, resultRepository, artemisAuthenticationProvider, ltiUserIdRepository, response);\n Course course = new Course();\n course.setStudentGroupName(courseStudentGroupName);\n exercise = new TextExercise();\n exercise.setCourse(course);\n launchRequest = AuthenticationIntegrationTestHelper.setupDefaultLtiLaunchRequest();\n user = new User();\n user.setLogin(\"login\");\n user.setPassword(\"password\");\n user.setGroups(new HashSet<>());\n ltiUserId = new LtiUserId();\n ltiUserId.setUser(user);\n ltiOutcomeUrl = new LtiOutcomeUrl();\n\n ReflectionTestUtils.setField(ltiService, \"USER_GROUP_NAME_EDX\", Optional.of(\"\"));\n ReflectionTestUtils.setField(ltiService, \"USER_GROUP_NAME_U4I\", Optional.of(\"\"));\n ReflectionTestUtils.setField(ltiService, \"USER_PREFIX_EDX\", Optional.of(\"\"));\n ReflectionTestUtils.setField(ltiService, \"USER_PREFIX_U4I\", Optional.of(\"\"));\n }\n\n @Test\n public void handleLaunchRequest_LTILaunchFromEdx() {\n launchRequest.setUser_id(\"student\");\n var exception = assertThrows(InternalAuthenticationServiceException.class, () -> ltiService.handleLaunchRequest(launchRequest, exercise));\n String expectedMessage = \"Invalid username sent by launch request. Please do not launch the exercise from edX studio. Use 'Preview' instead.\";\n assertThat(exception.getMessage()).isEqualTo(expectedMessage);\n }\n\n @Test\n public void handleLaunchRequest_InvalidContextLabel() {\n launchRequest.setContext_label(\"randomLabel\");\n var exception = assertThrows(InternalAuthenticationServiceException.class, () -> ltiService.handleLaunchRequest(launchRequest, exercise));\n String expectedMessage = \"Unknown context_label sent in LTI Launch Request: \" + launchRequest.toString();\n assertThat(exception.getMessage()).isEqualTo(expectedMessage);\n }\n\n @Test\n public void handleLaunchRequest_existingMappingForLtiUserId() {\n when(ltiUserIdRepository.findByLtiUserId(launchRequest.getUser_id())).thenReturn(Optional.of(ltiUserId));\n when(userRepository.getUserWithGroupsAndAuthorities()).thenReturn(user);\n onSuccessfulAuthenticationSetup(user, ltiUserId);\n ltiService.handleLaunchRequest(launchRequest, exercise);\n onSuccessfulAuthenticationAssertions(user, ltiUserId);\n }\n\n @Test\n public void handleLaunchRequest_lookupWithLtiEmailAddress() {\n String username = \"username\";\n String email = launchRequest.getLis_person_contact_email_primary();\n launchRequest.setCustom_lookup_user_by_email(true);\n when(ltiUserIdRepository.findByLtiUserId(launchRequest.getUser_id())).thenReturn(Optional.empty());\n when(artemisAuthenticationProvider.getUsernameForEmail(email)).thenReturn(Optional.of(username));\n when(artemisAuthenticationProvider.getOrCreateUser(new UsernamePasswordAuthenticationToken(username, \"\"), \"\", launchRequest.getLis_person_sourcedid(), email, true))\n .thenReturn(user);\n\n onSuccessfulAuthenticationSetup(user, ltiUserId);\n ltiService.handleLaunchRequest(launchRequest, exercise);\n onSuccessfulAuthenticationAssertions(user, ltiUserId);\n }\n\n @Test\n public void handleLaunchRequest_newUserIsNotRequired() {\n String username = launchRequest.getLis_person_sourcedid();\n Set<String> groups = new HashSet<>();\n groups.add(\"\");\n user.setActivated(false);\n when(ltiUserIdRepository.findByLtiUserId(launchRequest.getUser_id())).thenReturn(Optional.empty());\n when(userRepository.findOneByLogin(username)).thenReturn(Optional.empty());\n when(userCreationService.createInternalUser(username, null, groups, \"\", launchRequest.getLis_person_sourcedid(), launchRequest.getLis_person_contact_email_primary(), null,\n null, \"en\")).thenReturn(user);\n\n onSuccessfulAuthenticationSetup(user, ltiUserId);\n ltiService.handleLaunchRequest(launchRequest, exercise);\n onSuccessfulAuthenticationAssertions(user, ltiUserId);\n verify(userCreationService).activateUser(user);\n\n SecurityContextHolder.clearContext();\n launchRequest.setContext_label(\"randomLabel\");\n var exception = assertThrows(InternalAuthenticationServiceException.class, () -> ltiService.handleLaunchRequest(launchRequest, exercise));\n String expectedMessage = \"Unknown context_label sent in LTI Launch Request: \" + launchRequest.toString();\n assertThat(exception.getMessage()).isEqualTo(expectedMessage);\n }\n\n @Test\n public void handleLaunchRequest_noAuthenticationWasSuccessful() {\n launchRequest.setCustom_require_existing_user(true);\n when(ltiUserIdRepository.findByLtiUserId(launchRequest.getUser_id())).thenReturn(Optional.empty());\n when(response.containsHeader(\"Set-Cookie\")).thenReturn(true);\n List<String> headers = new ArrayList<>();\n headers.add(\"JSESSIONID=(123);\");\n when(response.getHeaders(\"Set-Cookie\")).thenReturn(headers);\n when(response.getHeader(\"Set-Cookie\")).thenReturn(headers.get(0));\n String sessionId = \"(123)\";\n ltiService.handleLaunchRequest(launchRequest, exercise);\n\n assertThat(ltiService.launchRequestForSession).containsKey(sessionId);\n assertThat(ltiService.launchRequestForSession).containsValue(Pair.of(launchRequest, exercise));\n assertThat(ltiService.launchRequestForSession.get(sessionId)).isEqualTo(Pair.of(launchRequest, exercise));\n }\n\n @Test\n public void onSuccessfulLtiAuthentication() {\n ltiUserId.setLtiUserId(\"oldStudentId\");\n onSuccessfulAuthenticationSetup(user, ltiUserId);\n ltiService.onSuccessfulLtiAuthentication(launchRequest, exercise);\n onSuccessfulAuthenticationAssertions(user, ltiUserId);\n }\n\n private void onSuccessfulAuthenticationSetup(User user, LtiUserId ltiUserId) {\n when(userRepository.getUserWithGroupsAndAuthorities()).thenReturn(user);\n when(ltiUserIdRepository.findByUser(user)).thenReturn(Optional.of(ltiUserId));\n ltiOutcomeUrlRepositorySetup(user);\n }\n\n private void ltiOutcomeUrlRepositorySetup(User user) {\n when(ltiOutcomeUrlRepository.findByUserAndExercise(user, exercise)).thenReturn(Optional.of(ltiOutcomeUrl));\n }\n\n private void onSuccessfulAuthenticationAssertions(User user, LtiUserId ltiUserId) {\n assertThat(user.getGroups()).contains(courseStudentGroupName);\n assertThat(\"ff30145d6884eeb2c1cef50298939383\").isEqualTo(ltiUserId.getLtiUserId());\n assertThat(\"some.outcome.service.url.com\").isEqualTo(ltiOutcomeUrl.getUrl());\n assertThat(\"someResultSourceId\").isEqualTo(ltiOutcomeUrl.getSourcedId());\n verify(userCreationService, times(1)).saveUser(user);\n verify(artemisAuthenticationProvider, times(1)).addUserToGroup(user, courseStudentGroupName);\n verify(ltiOutcomeUrlRepository, times(1)).save(ltiOutcomeUrl);\n }\n\n @Test\n public void verifyRequest_oauthSecretNotSpecified() {\n ReflectionTestUtils.setField(ltiService, \"OAUTH_SECRET\", Optional.empty());\n HttpServletRequest request = mock(HttpServletRequest.class);\n String message = ltiService.verifyRequest(request);\n assertThat(\"verifyRequest for LTI is not supported on this Artemis instance, artemis.lti.oauth-secret was not specified in the yml configuration\").isEqualTo(message);\n }\n\n @Test\n public void verifyRequest_unsuccessfulVerification() {\n ReflectionTestUtils.setField(ltiService, \"OAUTH_SECRET\", Optional.of(\"secret\"));\n String url = \"http://some.url.com\";\n HttpServletRequest request = mock(HttpServletRequest.class);\n when(request.getHeader(anyString())).thenReturn(null);\n when(request.getRequestURL()).thenReturn(new StringBuffer(url));\n when(request.getMethod()).thenReturn(\"GET\");\n when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());\n when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration());\n String message = ltiService.verifyRequest(request);\n assertThat(\"LTI signature verification failed with message: Failed to validate: parameter_absent; error: bad_request, launch result: null\").isEqualTo(message);\n }\n\n @Test\n public void onNewResult() {\n ReflectionTestUtils.setField(ltiService, \"OAUTH_KEY\", Optional.of(\"oauthKey\"));\n ReflectionTestUtils.setField(ltiService, \"OAUTH_SECRET\", Optional.of(\"oauthSecret\"));\n\n StudentParticipation participation = new StudentParticipation();\n User user = new User();\n participation.setParticipant(user);\n participation.setExercise(exercise);\n participation.setId(27L);\n Result result = new Result();\n result.setScore(3D);\n LtiOutcomeUrl ltiOutcomeUrl = new LtiOutcomeUrl();\n ltiOutcomeUrl.setUrl(\"https://some.url.com/\");\n ltiOutcomeUrl.setSourcedId(\"sourceId\");\n ltiOutcomeUrl.setExercise(exercise);\n ltiOutcomeUrl.setUser(user);\n ltiOutcomeUrlRepositorySetup(user);\n when(resultRepository.findFirstByParticipationIdOrderByCompletionDateDesc(27L)).thenReturn(Optional.of(result));\n ltiService.onNewResult(participation);\n verify(resultRepository, times(1)).findFirstByParticipationIdOrderByCompletionDateDesc(27L);\n }\n\n @Test\n public void handleLaunchRequestForSession() {\n String sessionId = \"sessionId\";\n ltiService.launchRequestForSession.put(sessionId, Pair.of(launchRequest, exercise));\n onSuccessfulAuthenticationSetup(user, ltiUserId);\n ltiService.handleLaunchRequestForSession(sessionId);\n onSuccessfulAuthenticationAssertions(user, ltiUserId);\n assertThat(ltiService.launchRequestForSession).isEmpty();\n }\n}\n" }, { "alpha_fraction": 0.7505773901939392, "alphanum_fraction": 0.7505773901939392, "avg_line_length": 32.30769348144531, "blob_id": "e846f0a756787b6648d0a2c600d605c4bcdd0a5d", "content_id": "ef65e339a30bdf928bd4ef57d602e003c0e6e011", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 433, "license_type": "permissive", "max_line_length": 53, "num_lines": 13, "path": "/src/main/webapp/app/exercises/shared/exercise/exercise-statistics-dto.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class CourseExerciseStatisticsDTO {\n public exerciseId?: number;\n public exerciseTitle?: string;\n public exerciseMode?: string;\n public exerciseMaxPoints?: number;\n public averageScoreInPercent?: number;\n public noOfParticipatingStudentsOrTeams?: number;\n public noOfStudentsInCourse?: number;\n public noOfTeamsInCourse?: number;\n public participationRateInPercent?: number;\n\n constructor() {}\n}\n" }, { "alpha_fraction": 0.6615815758705139, "alphanum_fraction": 0.6615815758705139, "avg_line_length": 32.1134033203125, "blob_id": "13cfe7950d1b611d8883ce00260813b90ec6f78f", "content_id": "74ada5ed749cc139ec3d8fd89435f6d8d2fa1f9f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3212, "license_type": "permissive", "max_line_length": 124, "num_lines": 97, "path": "/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\n\nexport type ExerciseHintResponse = HttpResponse<ExerciseHint>;\n\nexport interface IExerciseHintService {\n /**\n * Creates an exercise hint\n * @param exerciseHint Exercise hint to create\n */\n create(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse>;\n\n /**\n * Updates an exercise hint\n * @param exerciseHint Exercise hint to update\n */\n update(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse>;\n\n /**\n * Finds an exercise hint\n * @param id Id of exercise hint to find\n */\n find(id: number): Observable<ExerciseHintResponse>;\n\n /**\n * Finds all exercise hints by exercise id\n * @param exerciseId Id of exercise\n */\n findByExerciseId(exerciseId: number): Observable<HttpResponse<ExerciseHint[]>>;\n\n /**\n * Deletes an exercise hint\n * @param id Id of exercise hint to delete\n */\n delete(id: number): Observable<HttpResponse<any>>;\n}\n\n@Injectable({ providedIn: 'root' })\nexport class ExerciseHintService implements IExerciseHintService {\n public resourceUrl = SERVER_API_URL + 'api/exercise-hints';\n\n constructor(protected http: HttpClient) {}\n\n /**\n * Creates an exercise hint\n * @param exerciseHint Exercise hint to create\n */\n create(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse> {\n return this.http.post<ExerciseHint>(this.resourceUrl, exerciseHint, { observe: 'response' });\n }\n\n /**\n * Updates an exercise hint\n * @param exerciseHint Exercise hint to update\n */\n update(exerciseHint: ExerciseHint): Observable<ExerciseHintResponse> {\n return this.http.put<ExerciseHint>(`${this.resourceUrl}/${exerciseHint.id}`, exerciseHint, { observe: 'response' });\n }\n\n /**\n * Finds an exercise hint\n * @param id Id of exercise hint to find\n */\n find(id: number): Observable<ExerciseHintResponse> {\n return this.http.get<ExerciseHint>(`${this.resourceUrl}/${id}`, { observe: 'response' });\n }\n\n /**\n * Finds all exercise hints by exercise id\n * @param exerciseId Id of exercise\n */\n findByExerciseId(exerciseId: number): Observable<HttpResponse<ExerciseHint[]>> {\n return this.http.get<ExerciseHint[]>(`api/exercises/${exerciseId}/hints`, { observe: 'response' });\n }\n\n /**\n * Fetches the title of the hint with the given id\n *\n * @param hintId the id of the hint\n * @return the title of the hint in an HttpResponse, or an HttpErrorResponse on error\n */\n getTitle(hintId: number): Observable<HttpResponse<string>> {\n return this.http.get(`${this.resourceUrl}/${hintId}/title`, { observe: 'response', responseType: 'text' });\n }\n\n /**\n * Deletes an exercise hint\n * @param id Id of exercise hint to delete\n */\n delete(id: number): Observable<HttpResponse<any>> {\n return this.http.delete<any>(`${this.resourceUrl}/${id}`, { observe: 'response' });\n }\n}\n" }, { "alpha_fraction": 0.7563775777816772, "alphanum_fraction": 0.7614796161651611, "avg_line_length": 28.037036895751953, "blob_id": "a72031f84d2ec6e69677316738f9573cd41d82ba", "content_id": "f8010eb450046e8f231fba5ed75d623db6b9a7c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 784, "license_type": "permissive", "max_line_length": 73, "num_lines": 27, "path": "/src/main/java/de/tum/in/www1/artemis/service/dto/AbstractBuildResultNotificationDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.dto;\n\nimport java.time.ZonedDateTime;\nimport java.util.Optional;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic abstract class AbstractBuildResultNotificationDTO {\n\n public abstract ZonedDateTime getBuildRunDate();\n\n public abstract Optional<String> getCommitHashFromAssignmentRepo();\n\n public abstract Optional<String> getCommitHashFromTestsRepo();\n\n public abstract boolean isBuildSuccessful();\n\n public abstract Double getBuildScore();\n\n /**\n * Returns a string stating how much tests passed:\n * Example: \"1 of 10 passed\"\n * @return string stating how much tests passes out of a total amount\n */\n public abstract String getTestsPassedString();\n}\n" }, { "alpha_fraction": 0.7943887114524841, "alphanum_fraction": 0.7952078580856323, "avg_line_length": 56.447059631347656, "blob_id": "37e5093804b665eed58b07246b6683ff484aea97", "content_id": "aa01d129bd534608267acb814dd1a0ad7fc98f63", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4883, "license_type": "permissive", "max_line_length": 491, "num_lines": 85, "path": "/src/main/java/de/tum/in/www1/artemis/repository/TextExerciseRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.time.ZonedDateTime;\nimport java.util.List;\nimport java.util.Optional;\nimport java.util.Set;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.domain.Page;\nimport org.springframework.data.domain.Pageable;\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.TextExercise;\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data JPA repository for the TextExercise entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface TextExerciseRepository extends JpaRepository<TextExercise, Long> {\n\n @Query(\"SELECT e FROM TextExercise e WHERE e.course.id = :#{#courseId}\")\n List<TextExercise> findByCourseId(@Param(\"courseId\") Long courseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"teamAssignmentConfig\", \"categories\" })\n Optional<TextExercise> findWithEagerTeamAssignmentConfigAndCategoriesById(Long exerciseId);\n\n List<TextExercise> findByAssessmentTypeAndDueDateIsAfter(AssessmentType assessmentType, ZonedDateTime dueDate);\n\n /**\n * Query which fetches all the text exercises for which the user is instructor in the course and matching the search criteria.\n * As JPQL doesn't support unions, the distinction for course exercises and exam exercises is made with sub queries.\n *\n * @param partialTitle exercise title search term\n * @param partialCourseTitle course title search term\n * @param groups user groups\n * @param pageable Pageable\n * @return Page with search results\n */\n @Query(\"select te from TextExercise te where (te.id in (select courseTe.id from TextExercise courseTe where courseTe.course.instructorGroupName in :groups and (courseTe.title like %:partialTitle% or courseTe.course.title like %:partialCourseTitle%)) or te.id in (select examTe.id from TextExercise examTe where examTe.exerciseGroup.exam.course.instructorGroupName in :groups and (examTe.title like %:partialTitle% or examTe.exerciseGroup.exam.course.title like %:partialCourseTitle%)))\")\n Page<TextExercise> findByTitleInExerciseOrCourseAndUserHasAccessToCourse(@Param(\"partialTitle\") String partialTitle, @Param(\"partialCourseTitle\") String partialCourseTitle,\n @Param(\"groups\") Set<String> groups, Pageable pageable);\n\n Page<TextExercise> findByTitleIgnoreCaseContainingOrCourse_TitleIgnoreCaseContainingOrExerciseGroup_Exam_TitleIgnoreCaseContainingOrExerciseGroup_Exam_Course_TitleIgnoreCaseContaining(\n String partialTitle, String partialCourseTitle, String partialExamTitle, String partialExamCourseTitle, Pageable pageable);\n\n @Query(\"select textExercise from TextExercise textExercise left join fetch textExercise.exampleSubmissions exampleSubmissions left join fetch exampleSubmissions.submission submission left join fetch submission.results result left join fetch result.feedbacks left join fetch submission.blocks left join fetch result.assessor left join fetch textExercise.teamAssignmentConfig where textExercise.id = :#{#exerciseId}\")\n Optional<TextExercise> findByIdWithExampleSubmissionsAndResults(@Param(\"exerciseId\") Long exerciseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"studentParticipations\", \"studentParticipations.submissions\", \"studentParticipations.submissions.results\" })\n Optional<TextExercise> findWithStudentParticipationsAndSubmissionsById(Long exerciseId);\n\n @NotNull\n default TextExercise findByIdElseThrow(long exerciseId) {\n return findById(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Text Exercise\", exerciseId));\n }\n\n @NotNull\n default TextExercise findByIdWithExampleSubmissionsAndResultsElseThrow(long exerciseId) {\n return findByIdWithExampleSubmissionsAndResults(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Text Exercise\", exerciseId));\n }\n\n @NotNull\n default TextExercise findByIdWithStudentParticipationsAndSubmissionsElseThrow(long exerciseId) {\n return findWithStudentParticipationsAndSubmissionsById(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Text Exercise\", exerciseId));\n }\n\n /**\n * Find all exercises with *Due Date* in the future.\n *\n * @return List of Text Exercises\n */\n default List<TextExercise> findAllAutomaticAssessmentTextExercisesWithFutureDueDate() {\n return findByAssessmentTypeAndDueDateIsAfter(AssessmentType.SEMI_AUTOMATIC, ZonedDateTime.now());\n }\n}\n" }, { "alpha_fraction": 0.6827425360679626, "alphanum_fraction": 0.7028558850288391, "avg_line_length": 51.319766998291016, "blob_id": "a458ca581d816438ac5b09bf8ba13321ec14bbf0", "content_id": "730060590ffb3d7ee367a6fa8df2121ffee4a968", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8999, "license_type": "permissive", "max_line_length": 176, "num_lines": 172, "path": "/src/test/javascript/spec/service/course-score-calculation.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ABSOLUTE_SCORE, CourseScoreCalculationService, MAX_POINTS, PRESENTATION_SCORE, REACHABLE_POINTS, RELATIVE_SCORE } from 'app/overview/course-score-calculation.service';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { Course } from 'app/entities/course.model';\nimport { Exercise, IncludedInOverallScore } from 'app/entities/exercise.model';\nimport * as moment from 'moment';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { Result } from 'app/entities/result.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseScoreCalculationService', () => {\n let courseScoreCalculationService: CourseScoreCalculationService;\n\n beforeEach(() => {\n courseScoreCalculationService = new CourseScoreCalculationService();\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should return the correctly calculate the course score for all normal exercise', () => {\n const course = new Course();\n course.exercises = [];\n const exercise1 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n const exercise2 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n const exercise3 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n const exercise4 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n addParticipationAndResultToExercise(exercise1, true, 200, true);\n addParticipationAndResultToExercise(exercise2, true, 0, true);\n addParticipationAndResultToExercise(exercise3, true, 100, true);\n addParticipationAndResultToExercise(exercise4, true, 50, true);\n const result = courseScoreCalculationService.calculateTotalScores(course.exercises);\n expectCalculationResult(result, 35, 87.5, 87.5, 40, 0, 40);\n });\n\n it('should return the correctly calculate the course score for all bonus exercise', () => {\n const course = new Course();\n course.exercises = [];\n const exercise1 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.INCLUDED_AS_BONUS, true);\n const exercise2 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.INCLUDED_AS_BONUS, true);\n const exercise3 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.INCLUDED_AS_BONUS, true);\n const exercise4 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.INCLUDED_AS_BONUS, true);\n addParticipationAndResultToExercise(exercise1, true, 100, true);\n addParticipationAndResultToExercise(exercise2, true, 0, true);\n addParticipationAndResultToExercise(exercise3, true, 100, true);\n addParticipationAndResultToExercise(exercise4, true, 50, true);\n const result = courseScoreCalculationService.calculateTotalScores(course.exercises);\n expectCalculationResult(result, 25, 0, 0, 0, 0, 0);\n });\n\n it('should return the correctly calculate the course score for all not included exercise', () => {\n const course = new Course();\n course.exercises = [];\n const exercise1 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.NOT_INCLUDED, true);\n const exercise2 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.NOT_INCLUDED, true);\n const exercise3 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.NOT_INCLUDED, true);\n const exercise4 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.NOT_INCLUDED, true);\n addParticipationAndResultToExercise(exercise1, true, 100, true);\n addParticipationAndResultToExercise(exercise2, true, 0, true);\n addParticipationAndResultToExercise(exercise3, true, 100, true);\n addParticipationAndResultToExercise(exercise4, true, 50, true);\n const result = courseScoreCalculationService.calculateTotalScores(course.exercises);\n expectCalculationResult(result, 0, 0, 0, 0, 0, 0);\n });\n\n it('should return the correctly calculate the course score for a mixture of calculation types', () => {\n const course = new Course();\n course.exercises = [];\n const exercise1 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n const exercise2 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.INCLUDED_AS_BONUS, true);\n const exercise3 = addTextExerciseToCourse(course, 10, 0, IncludedInOverallScore.NOT_INCLUDED, true);\n addParticipationAndResultToExercise(exercise1, true, 200, true);\n addParticipationAndResultToExercise(exercise2, true, 100, true);\n addParticipationAndResultToExercise(exercise3, true, 100, true);\n const result = courseScoreCalculationService.calculateTotalScores(course.exercises);\n expectCalculationResult(result, 30, 300, 300, 10, 0, 10);\n });\n\n it('should pick the last result for calculation of the course score if multiple exits', () => {\n const course = new Course();\n course.exercises = [];\n const exercise1 = addTextExerciseToCourse(course, 10, 10, IncludedInOverallScore.INCLUDED_COMPLETELY, true);\n const participation = new StudentParticipation(ParticipationType.STUDENT);\n participation.exercise = exercise1;\n participation.initializationDate = moment();\n participation.results = [];\n exercise1.studentParticipations!.push(participation);\n\n const oldResult = new Result();\n oldResult.completionDate = moment(exercise1.dueDate!).subtract(1, 'days');\n oldResult.participation = participation;\n oldResult.score = 200;\n oldResult.rated = true;\n participation.results.push(oldResult);\n\n const newResult = new Result();\n newResult.completionDate = moment(oldResult.completionDate).add(1, 'hours');\n newResult.participation = participation;\n newResult.score = 0;\n newResult.rated = true;\n participation.results.push(newResult);\n\n const result = courseScoreCalculationService.calculateTotalScores(course.exercises);\n expectCalculationResult(result, 0, 0, 0, 10, 0, 10);\n });\n\n function addParticipationAndResultToExercise(exercise: Exercise, finishedInTime: boolean, scoreAwarded: number, rated: boolean) {\n const participation = new StudentParticipation(ParticipationType.STUDENT);\n participation.exercise = exercise;\n participation.initializationDate = moment();\n participation.results = [];\n exercise.studentParticipations!.push(participation);\n\n const result = new Result();\n if (finishedInTime) {\n result.completionDate = moment(exercise.dueDate!).subtract(1, 'days');\n } else {\n result.completionDate = moment(exercise.dueDate!).add(1, 'days');\n }\n result.participation = participation;\n result.score = scoreAwarded;\n result.rated = rated;\n participation.results.push(result);\n }\n\n function addTextExerciseToCourse(course: Course, maxPoints: number, bonusPoints: number, includedInOverallScore: IncludedInOverallScore, isFinished: boolean) {\n const exercise = new TextExercise(course, undefined);\n exercise.includedInOverallScore = includedInOverallScore;\n exercise.maxPoints = maxPoints;\n exercise.bonusPoints = bonusPoints;\n exercise.studentParticipations = [];\n if (isFinished) {\n exercise.dueDate = moment().subtract(1, 'days');\n } else {\n exercise.dueDate = moment().add(1, 'days');\n }\n course.exercises!.push(exercise);\n return exercise;\n }\n\n function expectCalculationResult(\n resultMap: Map<String, number>,\n expectedAbsoluteScore?: number,\n expectedRelativeScore?: number,\n expectedCurrentRelativeScore?: number,\n expectedMaxPoints?: number,\n expectedPresentationScore?: number,\n expectedReachableScore?: number,\n ) {\n if (expectedAbsoluteScore) {\n expect(resultMap.get(ABSOLUTE_SCORE)).to.equal(expectedAbsoluteScore);\n }\n if (expectedRelativeScore) {\n expect(resultMap.get(RELATIVE_SCORE)).to.equal(expectedRelativeScore);\n }\n if (expectedCurrentRelativeScore) {\n expect(resultMap.get(MAX_POINTS)).to.equal(expectedMaxPoints);\n }\n if (expectedPresentationScore) {\n expect(resultMap.get(PRESENTATION_SCORE)).to.equal(expectedPresentationScore);\n }\n if (expectedReachableScore) {\n expect(resultMap.get(REACHABLE_POINTS)).to.equal(expectedReachableScore);\n }\n }\n});\n" }, { "alpha_fraction": 0.7870778441429138, "alphanum_fraction": 0.7900146842002869, "avg_line_length": 29.954545974731445, "blob_id": "690930f3cf29610f7401242cd154ffbadb02b94c", "content_id": "940fa09951e96f42b9051b2299af2483884eed42", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 681, "license_type": "permissive", "max_line_length": 79, "num_lines": 22, "path": "/src/main/java/de/tum/in/www1/artemis/repository/AttachmentRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.List;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.Attachment;\n\n/**\n * Spring Data repository for the Attachment entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface AttachmentRepository extends JpaRepository<Attachment, Long> {\n\n @Query(\"select a FROM Attachment a WHERE a.lecture.id = :#{#lectureId}\")\n List<Attachment> findAllByLectureId(@Param(\"lectureId\") Long lectureId);\n\n}\n" }, { "alpha_fraction": 0.6145475506782532, "alphanum_fraction": 0.6145475506782532, "avg_line_length": 40.57143020629883, "blob_id": "18052632b8af11c5cc9ef84e824dc1fcc94ba542", "content_id": "97e9e54f1381bbb4c0cc613ed3de79c0432240bd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1746, "license_type": "permissive", "max_line_length": 121, "num_lines": 42, "path": "/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-popup.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Injectable } from '@angular/core';\nimport { Router } from '@angular/router';\nimport { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';\n\n@Injectable({ providedIn: 'root' })\nexport class ParticipationSubmissionPopupService {\n private ngbModalRef: NgbModalRef | null;\n\n constructor(private modalService: NgbModal, private router: Router) {\n this.ngbModalRef = null;\n }\n\n open(component: Component, participationId?: number | any, submissionId?: number | any): Promise<NgbModalRef> {\n return new Promise<NgbModalRef>((resolve) => {\n if (this.ngbModalRef != undefined) {\n resolve(this.ngbModalRef);\n }\n\n if (participationId && submissionId) {\n this.ngbModalRef = this.participationModalRef(component, participationId, submissionId);\n resolve(this.ngbModalRef);\n }\n });\n }\n\n participationModalRef(component: Component, participationId: number, submissionId: number): NgbModalRef {\n const modalRef: NgbModalRef = this.modalService.open(component, { size: 'lg', backdrop: 'static' });\n modalRef.componentInstance.participationId = participationId;\n modalRef.componentInstance.submissionId = submissionId;\n modalRef.result.then(\n () => {\n this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' });\n this.ngbModalRef = null;\n },\n () => {\n this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' });\n this.ngbModalRef = null;\n },\n );\n return modalRef;\n }\n}\n" }, { "alpha_fraction": 0.6802634596824646, "alphanum_fraction": 0.6900361180305481, "avg_line_length": 51.494422912597656, "blob_id": "2302f1bc8a48f34f9b1f0bd282bca476820288b8", "content_id": "82ed3215d2209e27f66923b90ca081a0598cd80d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14121, "license_type": "permissive", "max_line_length": 142, "num_lines": 269, "path": "/src/test/javascript/spec/component/code-editor/code-editor-build-output.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { CookieService } from 'ngx-cookie-service';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { By } from '@angular/platform-browser';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { AceEditorModule } from 'ng2-ace-editor';\nimport { SinonStub, stub } from 'sinon';\nimport { Observable, of } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { CodeEditorBuildOutputComponent } from 'app/exercises/programming/shared/code-editor/build-output/code-editor-build-output.component';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { BuildLogEntryArray } from 'app/entities/build-log.model';\nimport { CodeEditorBuildLogService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { MockResultService } from '../../helpers/mocks/service/mock-result.service';\nimport { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { StaticCodeAnalysisIssue } from 'app/entities/static-code-analysis-issue.model';\nimport { Feedback, FeedbackType, STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER } from 'app/entities/feedback.model';\nimport { Annotation } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component';\nimport { ProgrammingLanguage } from 'app/entities/programming-exercise.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorBuildOutputComponent', () => {\n let comp: CodeEditorBuildOutputComponent;\n let fixture: ComponentFixture<CodeEditorBuildOutputComponent>;\n let debugElement: DebugElement;\n let codeEditorBuildLogService: CodeEditorBuildLogService;\n let participationWebsocketService: ParticipationWebsocketService;\n let resultService: ResultService;\n let subscribeForLatestResultOfParticipationStub: SinonStub;\n let getBuildLogsStub: SinonStub;\n let getFeedbackDetailsForResultStub: SinonStub;\n\n const buildLogs = [\n {\n time: '2019-05-15T10:32:11+02:00',\n log: '[ERROR] COMPILATION ERROR : ',\n },\n {\n time: '2019-05-15T10:32:11+02:00',\n log:\n '[ERROR] /var/atlassian/application-data/bamboo/xml-data/build-dir/COURSEPROGSHORT-BASE-JOB1/' +\n 'assignment/src/todo/main/BubbleSort.java:[8,12] cannot find symbol',\n },\n {\n time: '2019-05-15T10:32:11+02:00',\n log: '&nbsp; symbol:&nbsp; &nbsp;class voi',\n },\n {\n time: '2019-05-15T10:32:11+02:00',\n log: '&nbsp; location: class todo.main.BubbleSort',\n },\n {\n time: '2019-05-15T10:32:11+02:00',\n log: '[INFO] 1 error',\n },\n ];\n const expectedBuildLogErrors = [\n {\n fileName: 'src/todo/main/BubbleSort.java',\n type: 'error',\n row: 7,\n column: 11,\n text: 'cannot find symbol',\n timestamp: 1557909131000,\n },\n ];\n\n const staticCodeAnalysisIssue = {\n filePath: 'path',\n startLine: 2,\n endLine: 3,\n startColumn: 1,\n endColumn: 2,\n message: 'Issue',\n category: 'Misc',\n rule: 'Best rule',\n priority: '1',\n } as StaticCodeAnalysisIssue;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, AceEditorModule, ArtemisSharedModule],\n declarations: [CodeEditorBuildOutputComponent],\n providers: [\n { provide: ResultService, useClass: MockResultService },\n { provide: CodeEditorBuildLogService, useClass: MockCodeEditorBuildLogService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CodeEditorBuildOutputComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n codeEditorBuildLogService = debugElement.injector.get(CodeEditorBuildLogService);\n participationWebsocketService = debugElement.injector.get(ParticipationWebsocketService);\n resultService = debugElement.injector.get(ResultService);\n subscribeForLatestResultOfParticipationStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation');\n getBuildLogsStub = stub(codeEditorBuildLogService, 'getBuildLogs');\n getFeedbackDetailsForResultStub = stub(resultService, 'getFeedbackDetailsForResult');\n });\n });\n\n afterEach(() => {\n subscribeForLatestResultOfParticipationStub.restore();\n getBuildLogsStub.restore();\n getFeedbackDetailsForResultStub.restore();\n });\n\n it('should setup result websocket, fetch result details and build logs on participation change', () => {\n const result = { id: 1 };\n const participation = { id: 1, results: [result] } as Participation;\n\n subscribeForLatestResultOfParticipationStub.returns(Observable.of(null));\n getFeedbackDetailsForResultStub.returns(of({ body: [] }));\n getBuildLogsStub.returns(of(buildLogs));\n\n comp.participation = participation;\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n fixture.detectChanges();\n\n expect(getFeedbackDetailsForResultStub).to.have.been.calledOnceWithExactly(result.id);\n expect(getBuildLogsStub).to.have.been.calledOnce;\n expect(subscribeForLatestResultOfParticipationStub).to.have.been.calledOnceWithExactly(participation.id, true);\n expect(comp.rawBuildLogs).to.deep.equal(BuildLogEntryArray.fromBuildLogs(buildLogs));\n expect(comp.rawBuildLogs.extractErrors(ProgrammingLanguage.JAVA)).to.deep.equal(expectedBuildLogErrors);\n\n const buildLogIsBuildingHtml = debugElement.query(By.css('.is-building'));\n expect(buildLogIsBuildingHtml).not.to.exist;\n const buildLogNoResultHtml = debugElement.query(By.css('.no-buildoutput'));\n expect(buildLogNoResultHtml).not.to.exist;\n const buildLogHtmlEntries = debugElement.queryAll(By.css('.build-output__entry'));\n expect(buildLogHtmlEntries).to.have.lengthOf(buildLogs.length);\n });\n\n it('should not retrieve build logs after participation change, if no result is available', () => {\n const participation = { id: 1 } as Participation;\n comp.participation = participation;\n subscribeForLatestResultOfParticipationStub.returns(Observable.of(null));\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n fixture.detectChanges();\n expect(getBuildLogsStub).to.not.have.been.called;\n expect(comp.rawBuildLogs).to.deep.equal(new BuildLogEntryArray());\n\n const buildLogIsBuildingHtml = debugElement.query(By.css('.is-building'));\n expect(buildLogIsBuildingHtml).not.to.exist;\n const buildLogNoResultHtml = debugElement.query(By.css('.no-buildoutput'));\n expect(buildLogNoResultHtml).to.exist;\n const buildLogHtmlEntries = debugElement.queryAll(By.css('.buildoutput__entry'));\n expect(buildLogHtmlEntries).to.have.lengthOf(0);\n });\n\n it('should not retrieve build logs after participation change, if submission could be built', () => {\n const submission = { id: 1, buildFailed: false } as ProgrammingSubmission;\n const result = { id: 1, successful: true } as Result;\n result.submission = submission;\n const participation = { id: 1, results: [result] } as Participation;\n comp.participation = participation;\n subscribeForLatestResultOfParticipationStub.returns(Observable.of(null));\n getFeedbackDetailsForResultStub.returns(of({ ...result, feedbacks: [] }));\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n fixture.detectChanges();\n expect(getFeedbackDetailsForResultStub).to.have.been.calledOnceWithExactly(result.id);\n expect(getBuildLogsStub).to.not.have.been.called;\n expect(comp.rawBuildLogs).to.deep.equal(new BuildLogEntryArray());\n\n const buildLogIsBuildingHtml = debugElement.query(By.css('.is-building'));\n expect(buildLogIsBuildingHtml).not.to.exist;\n const buildLogNoResultHtml = debugElement.query(By.css('.no-buildoutput'));\n expect(buildLogNoResultHtml).to.exist;\n const buildLogHtmlEntries = debugElement.queryAll(By.css('.buildoutput__entry'));\n expect(buildLogHtmlEntries).to.have.lengthOf(0);\n });\n\n it('should retrieve build logs if no result submission is available', () => {\n const result = { id: 1, successful: false };\n const participation = { id: 1 } as Participation;\n\n getBuildLogsStub.returns(of(buildLogs));\n subscribeForLatestResultOfParticipationStub.returns(of(result));\n\n comp.participation = participation;\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n fixture.detectChanges();\n\n expect(getBuildLogsStub).to.have.been.calledOnceWithExactly();\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(comp.rawBuildLogs).to.deep.equal(BuildLogEntryArray.fromBuildLogs(buildLogs));\n expect(comp.rawBuildLogs.extractErrors(ProgrammingLanguage.JAVA)).to.deep.equal(expectedBuildLogErrors);\n\n const buildLogIsBuildingHtml = debugElement.query(By.css('.is-building'));\n expect(buildLogIsBuildingHtml).not.to.exist;\n const buildLogNoResultHtml = debugElement.query(By.css('.no-buildoutput'));\n expect(buildLogNoResultHtml).not.to.exist;\n const buildLogHtmlEntries = debugElement.queryAll(By.css('.build-output__entry'));\n expect(buildLogHtmlEntries).to.have.lengthOf(buildLogs.length);\n });\n\n it('should retrieve build logs if result submission could not be built', () => {\n const submission = { id: 1, buildFailed: true } as ProgrammingSubmission;\n const result = { id: 1, successful: true } as Result;\n result.submission = submission;\n const participation = { id: 1 } as Participation;\n\n getBuildLogsStub.returns(of(buildLogs));\n subscribeForLatestResultOfParticipationStub.returns(of(result));\n\n comp.participation = participation;\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n fixture.detectChanges();\n\n expect(getBuildLogsStub).to.have.been.calledOnceWithExactly();\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(comp.rawBuildLogs).to.deep.equal(BuildLogEntryArray.fromBuildLogs(buildLogs));\n expect(comp.rawBuildLogs.extractErrors(ProgrammingLanguage.JAVA)).to.deep.equal(expectedBuildLogErrors);\n\n const buildLogIsBuildingHtml = debugElement.query(By.css('.is-building'));\n expect(buildLogIsBuildingHtml).not.to.exist;\n const buildLogNoResultHtml = debugElement.query(By.css('.no-buildoutput'));\n expect(buildLogNoResultHtml).not.to.exist;\n const buildLogHtmlEntries = debugElement.queryAll(By.css('.build-output__entry'));\n expect(buildLogHtmlEntries).to.have.lengthOf(buildLogs.length);\n });\n\n it('should create annotation from static code analysis feedback', () => {\n const submission = { id: 1, buildFailed: false } as ProgrammingSubmission;\n const result = { id: 1, successful: true } as Result;\n result.submission = submission;\n const participation = { id: 1, results: [result] } as Participation;\n comp.participation = participation;\n const feedback = {\n id: 1,\n type: FeedbackType.AUTOMATIC,\n text: STATIC_CODE_ANALYSIS_FEEDBACK_IDENTIFIER,\n detailText: JSON.stringify(staticCodeAnalysisIssue),\n } as Feedback;\n subscribeForLatestResultOfParticipationStub.returns(Observable.of(null));\n getFeedbackDetailsForResultStub.returns(of({ body: [feedback] }));\n let emittedAnnotations: Annotation[] = [];\n comp.onAnnotations.subscribe((emitted: any) => {\n emittedAnnotations = emitted;\n });\n triggerChanges(comp, { property: 'participation', currentValue: participation });\n\n expect(emittedAnnotations).to.have.length(1);\n const annotation = emittedAnnotations[0];\n expect(annotation.fileName).to.equal(staticCodeAnalysisIssue.filePath);\n expect(annotation.row).to.equal(staticCodeAnalysisIssue.startLine - 1);\n expect(annotation.column).to.equal(staticCodeAnalysisIssue.startColumn! - 1);\n });\n});\n" }, { "alpha_fraction": 0.6366666555404663, "alphanum_fraction": 0.6366666555404663, "avg_line_length": 35.14457702636719, "blob_id": "4368d296f7ff7d39aca47cd74c438b15a1440489", "content_id": "f4feca76fc79850f96cfe39f6d7a3d6e5e1ad063", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3000, "license_type": "permissive", "max_line_length": 119, "num_lines": 83, "path": "/src/main/webapp/app/core/user/user.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\nimport { createRequestOption } from 'app/shared/util/request-util';\nimport { User } from 'app/core/user/user.model';\nimport { SERVER_API_URL } from 'app/app.constants';\n\n@Injectable({ providedIn: 'root' })\nexport class UserService {\n public resourceUrl = SERVER_API_URL + 'api/users';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Create a user on the server.\n * @param user The user to create.\n * @return Observable<HttpResponse<User>> with the created user as body.\n */\n create(user: User): Observable<HttpResponse<User>> {\n return this.http.post<User>(this.resourceUrl, user, { observe: 'response' });\n }\n\n /**\n * Update a user on the server.\n * @param user The user to update.\n * @return Observable<HttpResponse<User>> with the updated user as body.\n */\n update(user: User): Observable<HttpResponse<User>> {\n return this.http.put<User>(this.resourceUrl, user, { observe: 'response' });\n }\n\n /**\n * Find a user on the server.\n * @param login The login of the user to find.\n * @return Observable<HttpResponse<User>> with the found user as body.\n */\n find(login: string): Observable<HttpResponse<User>> {\n return this.http.get<User>(`${this.resourceUrl}/${login}`, { observe: 'response' });\n }\n\n /**\n * Submit a query for a given request.\n * @param req The query request\n * @return Observable<HttpResponse<User[]>> with the list of users that match the query as body.\n */\n query(req?: any): Observable<HttpResponse<User[]>> {\n const options = createRequestOption(req);\n return this.http.get<User[]>(this.resourceUrl, { params: options, observe: 'response' });\n }\n\n /**\n * Search for a user on the server by login or name.\n * @param loginOrName The login or name to search for.\n * @return Observable<HttpResponse<User[]>> with the list of found users as body.\n */\n search(loginOrName: string): Observable<HttpResponse<User[]>> {\n return this.http.get<User[]>(`${this.resourceUrl}/search?loginOrName=${loginOrName}`, { observe: 'response' });\n }\n\n /**\n * Delete a user on the server.\n * @param login The login of the user to delete.\n * @return Observable<HttpResponse<void>>\n */\n delete(login: string): Observable<HttpResponse<void>> {\n return this.http.delete<void>(`${this.resourceUrl}/${login}`, { observe: 'response' });\n }\n\n /**\n * Update the user notification date.\n */\n updateLastNotificationRead(): Observable<HttpResponse<void>> {\n return this.http.put<void>(`${this.resourceUrl}/notification-date`, null, { observe: 'response' });\n }\n\n /**\n * Get the authorities.\n */\n authorities(): Observable<string[]> {\n return this.http.get<string[]>(SERVER_API_URL + 'api/users/authorities');\n }\n}\n" }, { "alpha_fraction": 0.7061144113540649, "alphanum_fraction": 0.7084812521934509, "avg_line_length": 46.3831787109375, "blob_id": "b66e924847a6b3fffcb4bb5c36eaeb9fc83ce205", "content_id": "a5b68b87869da3f6c1afa54276aa87a67b32757b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10140, "license_type": "permissive", "max_line_length": 180, "num_lines": 214, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { By } from '@angular/platform-browser';\nimport { MockComponent } from 'ng-mocks';\nimport { Subject } from 'rxjs';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonSpy, SinonStub, spy, stub } from 'sinon';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { MockResultService } from '../../helpers/mocks/service/mock-result.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { MockProgrammingExerciseGradingService } from '../../helpers/mocks/service/mock-programming-exercise-grading.service';\nimport { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-instructions-editor.module';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { TemplateProgrammingExerciseParticipation } from 'app/entities/participation/template-programming-exercise-participation.model';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { ProgrammingExerciseGradingService, IProgrammingExerciseGradingService } from 'app/exercises/programming/manage/services/programming-exercise-grading.service';\nimport { Result } from 'app/entities/result.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProgrammingExerciseInstructionAnalysisComponent } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.component';\nimport { ProgrammingExerciseEditableInstructionComponent } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-editable-instruction.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseEditableInstructionComponent', () => {\n let comp: ProgrammingExerciseEditableInstructionComponent;\n let fixture: ComponentFixture<ProgrammingExerciseEditableInstructionComponent>;\n let debugElement: DebugElement;\n let gradingService: IProgrammingExerciseGradingService;\n let programmingExerciseParticipationService: ProgrammingExerciseParticipationService;\n\n let subscribeForTestCaseSpy: SinonSpy;\n let getLatestResultWithFeedbacksStub: SinonStub;\n let generateHtmlSubjectStub: SinonStub;\n\n const templateParticipation = new TemplateProgrammingExerciseParticipation();\n templateParticipation.id = 99;\n\n const exercise = { id: 30, templateParticipation } as ProgrammingExercise;\n const participation = { id: 1, results: [{ id: 10, feedbacks: [{ id: 20 }, { id: 21 }] }] } as Participation;\n const testCases = [\n { testName: 'test1', active: true },\n { testName: 'test2', active: true },\n { testName: 'test3', active: false },\n ];\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, NgbModule, ArtemisProgrammingExerciseInstructionsEditorModule],\n declarations: [MockComponent(ProgrammingExerciseInstructionAnalysisComponent), MockComponent(MarkdownEditorComponent)],\n providers: [\n { provide: ResultService, useClass: MockResultService },\n { provide: ProgrammingExerciseGradingService, useClass: MockProgrammingExerciseGradingService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseEditableInstructionComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n gradingService = debugElement.injector.get(ProgrammingExerciseGradingService);\n (gradingService as MockProgrammingExerciseGradingService).initSubject([]);\n programmingExerciseParticipationService = debugElement.injector.get(ProgrammingExerciseParticipationService);\n subscribeForTestCaseSpy = spy(gradingService, 'subscribeForTestCases');\n getLatestResultWithFeedbacksStub = stub(programmingExerciseParticipationService, 'getLatestResultWithFeedback');\n generateHtmlSubjectStub = stub(comp.generateHtmlSubject, 'next');\n });\n });\n\n afterEach(() => {\n (gradingService as MockProgrammingExerciseGradingService).initSubject([]);\n subscribeForTestCaseSpy.restore();\n getLatestResultWithFeedbacksStub.restore();\n generateHtmlSubjectStub.restore();\n });\n\n it('should not have any test cases if the test case service emits an empty array', fakeAsync(() => {\n comp.exercise = exercise;\n comp.participation = participation;\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n fixture.detectChanges();\n tick();\n\n expect(subscribeForTestCaseSpy).to.have.been.calledOnceWithExactly(exercise.id);\n expect(comp.exerciseTestCases).to.have.lengthOf(0);\n\n fixture.destroy();\n flush();\n }));\n\n it('should have test cases according to the result of the test case service if it does not return an empty array', fakeAsync(() => {\n comp.exercise = exercise;\n comp.participation = participation;\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n\n (gradingService as MockProgrammingExerciseGradingService).nextTestCases(testCases);\n\n fixture.detectChanges();\n tick();\n\n expect(subscribeForTestCaseSpy).to.have.been.calledOnceWithExactly(exercise.id);\n expect(comp.exerciseTestCases).to.have.lengthOf(2);\n expect(comp.exerciseTestCases).to.deep.equal(['test1', 'test2']);\n\n fixture.destroy();\n flush();\n }));\n\n it('should update test cases if a new test case result comes in', fakeAsync(() => {\n comp.exercise = exercise;\n comp.participation = participation;\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n\n (gradingService as MockProgrammingExerciseGradingService).nextTestCases(testCases);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.exerciseTestCases).to.have.lengthOf(2);\n expect(comp.exerciseTestCases).to.deep.equal(['test1', 'test2']);\n\n (gradingService as MockProgrammingExerciseGradingService).nextTestCases([{ testName: 'testX' }]);\n fixture.detectChanges();\n tick();\n\n expect(comp.exerciseTestCases).to.be.empty;\n\n expect(subscribeForTestCaseSpy).to.have.been.calledOnceWithExactly(exercise.id);\n\n fixture.destroy();\n flush();\n }));\n\n it('should try to retrieve the test case values from the solution repos last build result if there are no testCases (empty result)', fakeAsync(() => {\n comp.exercise = exercise;\n comp.participation = participation;\n const subject = new Subject<Result>();\n getLatestResultWithFeedbacksStub.returns(subject);\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n\n // No test cases available, might be that the solution build never ran to create tests...\n (gradingService as MockProgrammingExerciseGradingService).nextTestCases(undefined);\n\n fixture.detectChanges();\n\n expect(comp.exerciseTestCases).to.have.lengthOf(0);\n expect(getLatestResultWithFeedbacksStub).to.have.been.calledOnceWithExactly(exercise.templateParticipation!.id!);\n\n subject.next({ feedbacks: [{ text: 'testY' }, { text: 'testX' }] } as Result);\n tick();\n\n expect(comp.exerciseTestCases).to.have.lengthOf(2);\n expect(comp.exerciseTestCases).to.deep.equal(['testX', 'testY']);\n\n fixture.destroy();\n flush();\n }));\n\n it('should not try to query test cases or solution participation results if the exercise is being created (there can be no test cases yet)', fakeAsync(() => {\n comp.exercise = exercise;\n comp.participation = participation;\n comp.editMode = false;\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n\n fixture.detectChanges();\n tick();\n\n expect(comp.exerciseTestCases).to.have.lengthOf(0);\n expect(comp.exerciseTestCases).to.be.empty;\n\n expect(comp.testCaseSubscription).to.be.undefined;\n expect(subscribeForTestCaseSpy).not.to.have.been.called;\n expect(getLatestResultWithFeedbacksStub).not.to.have.been.called;\n\n const saveProblemStatementButton = debugElement.query(By.css('#save-instructions-button'));\n expect(saveProblemStatementButton).not.to.exist;\n\n fixture.destroy();\n flush();\n }));\n\n it('should re-render the preview html when forceRender has emitted', fakeAsync(() => {\n const forceRenderSubject = new Subject<void>();\n comp.exercise = exercise;\n comp.participation = participation;\n comp.forceRender = forceRenderSubject.asObservable();\n\n triggerChanges(comp, { property: 'exercise', currentValue: exercise });\n\n fixture.detectChanges();\n tick();\n\n forceRenderSubject.next();\n\n expect(generateHtmlSubjectStub).to.have.been.calledOnce;\n\n fixture.destroy();\n flush();\n }));\n});\n" }, { "alpha_fraction": 0.8063725233078003, "alphanum_fraction": 0.811274528503418, "avg_line_length": 26.200000762939453, "blob_id": "10dcc61878abea2bd183373e00ddc4032f18b814", "content_id": "ac6eadac27d6702cd2fcb6bb1006142ed016ce54", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 408, "license_type": "permissive", "max_line_length": 83, "num_lines": 15, "path": "/src/main/java/de/tum/in/www1/artemis/repository/AnswerOptionRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.quiz.AnswerOption;\n\n/**\n * Spring Data JPA repository for the AnswerOption entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface AnswerOptionRepository extends JpaRepository<AnswerOption, Long> {\n\n}\n" }, { "alpha_fraction": 0.6896404027938843, "alphanum_fraction": 0.690496563911438, "avg_line_length": 36.07936477661133, "blob_id": "cdd929bb152285a5b5648bccbd4b3819f580a457", "content_id": "a4c8516a5084e55b31afb725cea86a584da54d3a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2336, "license_type": "permissive", "max_line_length": 133, "num_lines": 63, "path": "/src/main/webapp/app/overview/course-exams/course-exams.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, OnDestroy } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport { ActivatedRoute } from '@angular/router';\nimport { Subscription } from 'rxjs/Subscription';\nimport { Exam } from 'app/entities/exam.model';\nimport * as moment from 'moment';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\n\n@Component({\n selector: 'jhi-course-exams',\n templateUrl: './course-exams.component.html',\n})\nexport class CourseExamsComponent implements OnInit, OnDestroy {\n courseId: number;\n public course?: Course;\n private paramSubscription?: Subscription;\n private courseUpdatesSubscription?: Subscription;\n\n constructor(\n private route: ActivatedRoute,\n private courseCalculationService: CourseScoreCalculationService,\n private courseManagementService: CourseManagementService,\n private serverDateService: ArtemisServerDateService,\n ) {}\n\n /**\n * subscribe to changes in the course and fetch course by the path parameter\n */\n ngOnInit(): void {\n this.paramSubscription = this.route.parent!.params.subscribe((params) => {\n this.courseId = parseInt(params['courseId'], 10);\n });\n\n this.course = this.courseCalculationService.getCourse(this.courseId);\n\n this.courseUpdatesSubscription = this.courseManagementService.getCourseUpdates(this.courseId).subscribe((course: Course) => {\n this.courseCalculationService.updateCourse(course);\n this.course = this.courseCalculationService.getCourse(this.courseId);\n });\n }\n\n /**\n * unsubscribe from all unsubscriptions\n */\n ngOnDestroy(): void {\n if (this.paramSubscription) {\n this.paramSubscription.unsubscribe();\n }\n if (this.courseUpdatesSubscription) {\n this.courseUpdatesSubscription.unsubscribe();\n }\n }\n\n /**\n * check for given exam if it is visible\n * @param {Exam} exam\n */\n isVisible(exam: Exam): boolean {\n return exam.visibleDate ? moment(exam.visibleDate).isBefore(this.serverDateService.now()) : false;\n }\n}\n" }, { "alpha_fraction": 0.6717692017555237, "alphanum_fraction": 0.6729466915130615, "avg_line_length": 38.96470642089844, "blob_id": "a8c971461aec4f997dc9c9aa4e9933ab9feb9f7c", "content_id": "a3295967b93c0697c72e6a547250310b5477d1cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3397, "license_type": "permissive", "max_line_length": 109, "num_lines": 85, "path": "/src/test/javascript/spec/component/lecture-unit/video-unit/video-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport * as chai from 'chai';\n\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbCollapse, NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport { VideoUnitComponent } from 'app/overview/course-lectures/video-unit/video-unit.component';\nimport { SafeResourceUrlPipe } from 'app/shared/pipes/safe-resource-url.pipe';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { BrowserModule } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('VideoUnitComponent', () => {\n const sandbox = sinon.createSandbox();\n const exampleName = 'Test';\n const exampleDescription = 'Lorem Ipsum';\n const exampleSource = 'https://www.youtube.com/embed/8iU8LPEa4o0';\n let videoUnitComponentFixture: ComponentFixture<VideoUnitComponent>;\n let videoUnitComponent: VideoUnitComponent;\n let videoUnit: VideoUnit;\n\n beforeEach(() => {\n videoUnit = new VideoUnit();\n videoUnit.name = exampleName;\n videoUnit.description = exampleDescription;\n videoUnit.source = exampleSource;\n\n TestBed.configureTestingModule({\n imports: [BrowserModule],\n declarations: [\n VideoUnitComponent,\n MockComponent(FaIconComponent),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockDirective(NgbCollapse),\n MockDirective(NgbTooltip),\n ],\n providers: [{ provide: SafeResourceUrlPipe, useClass: SafeResourceUrlPipe }],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n videoUnitComponentFixture = TestBed.createComponent(VideoUnitComponent);\n videoUnitComponent = videoUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n videoUnitComponentFixture.detectChanges();\n expect(videoUnitComponent).to.be.ok;\n });\n\n it('should iFrame correctly', () => {\n videoUnitComponent.videoUnit = videoUnit;\n videoUnitComponentFixture.detectChanges(); // ngInit\n const iFrame = videoUnitComponentFixture.debugElement.nativeElement.querySelector('#videoFrame');\n expect(iFrame.src).to.equal(videoUnit.source);\n });\n\n it('should collapse when clicked', () => {\n videoUnitComponent.videoUnit = videoUnit;\n videoUnitComponentFixture.detectChanges(); // ngInit\n expect(videoUnitComponent.isCollapsed).to.be.true;\n const handleCollapseSpy = sinon.spy(videoUnitComponent, 'handleCollapse');\n\n const container = videoUnitComponentFixture.debugElement.nativeElement.querySelector('.card-header');\n expect(container).to.be.ok;\n container.click();\n\n expect(handleCollapseSpy).to.have.been.called;\n expect(videoUnitComponent.isCollapsed).to.be.false;\n\n handleCollapseSpy.restore();\n });\n});\n" }, { "alpha_fraction": 0.7157057523727417, "alphanum_fraction": 0.7176938652992249, "avg_line_length": 24.149999618530273, "blob_id": "3ed7c7e9fd6ed26e637d9af32948e51d0f069da7", "content_id": "95d53c6b518e34ebcf43d0334869c410d0a54798", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 503, "license_type": "permissive", "max_line_length": 62, "num_lines": 20, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/TimeResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport java.time.Instant;\n\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.GetMapping;\nimport org.springframework.web.bind.annotation.RestController;\n\n@RestController\npublic class TimeResource {\n\n /**\n * {@code GET /time}:\n * @return the current server time as Instant\n */\n @GetMapping(\"/time\")\n public ResponseEntity<Instant> time() {\n return ResponseEntity.ok(Instant.now());\n }\n}\n" }, { "alpha_fraction": 0.6532805562019348, "alphanum_fraction": 0.6532805562019348, "avg_line_length": 45.52631759643555, "blob_id": "d7d8690bb9535433528cad7ff95022616ca33634", "content_id": "6903220f260b844ac98a31d9eb89716f2b0eb7a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3536, "license_type": "permissive", "max_line_length": 177, "num_lines": 76, "path": "/src/main/webapp/app/exam/manage/student-exams/student-exam.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Router } from '@angular/router';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { ParticipationType } from 'app/entities/participation/participation.model';\nimport { addUserIndependentRepositoryUrl } from 'app/overview/participation-utils';\nimport { ExerciseType } from 'app/entities/exercise.model';\n\ntype EntityResponseType = HttpResponse<StudentExam>;\ntype EntityArrayResponseType = HttpResponse<StudentExam[]>;\n\n@Injectable({ providedIn: 'root' })\nexport class StudentExamService {\n public resourceUrl = SERVER_API_URL + 'api/courses';\n\n constructor(private router: Router, private http: HttpClient) {}\n\n /**\n * Find a student exam on the server using a GET request.\n * @param courseId The course id.\n * @param examId The exam id.\n * @param studentExamId The id of the student exam to get.\n */\n find(courseId: number, examId: number, studentExamId: number): Observable<EntityResponseType> {\n return this.http\n .get<StudentExam>(`${this.resourceUrl}/${courseId}/exams/${examId}/student-exams/${studentExamId}`, { observe: 'response' })\n .pipe(map((res: EntityResponseType) => this.adjustRepositoryUrlsForProgrammingExercises(res)));\n }\n\n /**\n * Find all student exams for the given exam.\n * @param courseId The course id.\n * @param examId The exam id.\n */\n findAllForExam(courseId: number, examId: number): Observable<EntityArrayResponseType> {\n return this.http.get<StudentExam[]>(`${this.resourceUrl}/${courseId}/exams/${examId}/student-exams`, { observe: 'response' });\n }\n\n /**\n * Update the working time of the given student exam.\n * @param courseId The course id.\n * @param examId The exam id.\n * @param studentExamId The id of the student exam to get.\n * @param workingTime The working time in seconds.\n */\n updateWorkingTime(courseId: number, examId: number, studentExamId: number, workingTime: number): Observable<EntityResponseType> {\n return this.http.patch<StudentExam>(`${this.resourceUrl}/${courseId}/exams/${examId}/student-exams/${studentExamId}/working-time`, workingTime, { observe: 'response' });\n }\n\n toggleSubmittedState(courseId: number, examId: number, studentExamId: number, unsubmit: boolean): Observable<EntityResponseType> {\n const url = `${this.resourceUrl}/${courseId}/exams/${examId}/student-exams/${studentExamId}/toggle-to-`;\n if (unsubmit) {\n return this.http.put<StudentExam>(url + `unsubmitted`, {}, { observe: 'response' });\n } else {\n return this.http.put<StudentExam>(url + `submitted`, {}, { observe: 'response' });\n }\n }\n\n protected adjustRepositoryUrlsForProgrammingExercises(res: EntityResponseType): EntityResponseType {\n if (res.body && res.body.exercises) {\n res.body.exercises!.forEach((ex) => {\n if (ex.type === ExerciseType.PROGRAMMING && ex.studentParticipations) {\n ex.studentParticipations!.forEach((sp) => {\n if (sp.type === ParticipationType.PROGRAMMING) {\n addUserIndependentRepositoryUrl(sp);\n }\n });\n }\n });\n }\n return res;\n }\n}\n" }, { "alpha_fraction": 0.6718849539756775, "alphanum_fraction": 0.6793941855430603, "avg_line_length": 56.77206039428711, "blob_id": "aafb1d41e859128c7e773e16bec83948e006b781", "content_id": "6b0429aa02159f4c9bf03591785794424ac7ff64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7857, "license_type": "permissive", "max_line_length": 186, "num_lines": 136, "path": "/src/test/javascript/spec/component/exam/manage/exams/exam-checklist-exercisegroup-table.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { Component } from '@angular/core';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { ExamChecklistCheckComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-check/exam-checklist-check.component';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport { ProgressBarComponent } from 'app/shared/dashboards/tutor-participation-graph/progress-bar/progress-bar.component';\nimport { ExamChecklistExerciseGroupTableComponent } from 'app/exam/manage/exams/exam-checklist-component/exam-checklist-exercisegroup-table/exam-checklist-exercisegroup-table.component';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({\n template: '',\n})\nclass DummyComponent {}\n\ndescribe('ExamChecklistExerciseGroupTableComponent', () => {\n let examChecklistComponentFixture: ComponentFixture<ExamChecklistExerciseGroupTableComponent>;\n let examChecklistExerciseGroupTableComponent: ExamChecklistExerciseGroupTableComponent;\n\n const dueDateStatArray = [{ inTime: 0, late: 0, total: 0 }];\n function getExerciseGroups(equalPoints: boolean) {\n const exerciseGroups = [\n {\n id: 1,\n exercises: [\n {\n id: 3,\n title: 'A',\n maxPoints: 101,\n numberOfAssessmentsOfCorrectionRounds: dueDateStatArray,\n studentAssignedTeamIdComputed: false,\n secondCorrectionEnabled: false,\n numberOfParticipations: 23,\n },\n {\n id: 2,\n title: 'B',\n maxPoints: 101,\n numberOfAssessmentsOfCorrectionRounds: dueDateStatArray,\n studentAssignedTeamIdComputed: false,\n secondCorrectionEnabled: false,\n numberOfParticipations: 22,\n },\n ],\n },\n ];\n if (!equalPoints) {\n exerciseGroups[0].exercises[0].maxPoints = 50;\n }\n return exerciseGroups;\n }\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule.withRoutes([\n { path: 'course-management/:courseId/exams/:examId/edit', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/exercise-groups', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/assessment-dashboard', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/scores', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/student-exams', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/test-runs', component: DummyComponent },\n { path: 'course-management/:courseId/exams/:examId/students', component: DummyComponent },\n ]),\n HttpClientTestingModule,\n ],\n declarations: [\n DummyComponent,\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockDirective(JhiTranslateDirective),\n MockDirective(HasAnyAuthorityDirective),\n ExamChecklistCheckComponent,\n ExamChecklistExerciseGroupTableComponent,\n ProgressBarComponent,\n MockDirective(NgbTooltip),\n MockComponent(FaIconComponent),\n ],\n providers: [],\n })\n .compileComponents()\n .then(() => {\n examChecklistComponentFixture = TestBed.createComponent(ExamChecklistExerciseGroupTableComponent);\n examChecklistExerciseGroupTableComponent = examChecklistComponentFixture.componentInstance;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n describe('test onChanges', () => {\n it('should set properties false', () => {\n examChecklistExerciseGroupTableComponent.ngOnChanges();\n examChecklistExerciseGroupTableComponent.exerciseGroups = getExerciseGroups(false);\n examChecklistExerciseGroupTableComponent.ngOnChanges();\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns.length).to.equal(2);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].indexExerciseGroup).to.equal(1);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].indexExercise).to.equal(1);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseGroupPointsEqual).to.equal(false);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseTitle).to.equal('A');\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseMaxPoints).to.equal(50);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseNumberOfParticipations).to.equal(23);\n\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].indexExerciseGroup).to.equal(undefined);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].indexExercise).to.equal(2);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].exerciseGroupPointsEqual).to.equal(undefined);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].exerciseTitle).to.equal('B');\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].exerciseMaxPoints).to.equal(101);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[1].exerciseNumberOfParticipations).to.equal(22);\n });\n\n it('should set properties true', () => {\n examChecklistExerciseGroupTableComponent.exerciseGroups = getExerciseGroups(true);\n examChecklistExerciseGroupTableComponent.ngOnChanges();\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns.length).to.not.equal(0);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].indexExerciseGroup).to.equal(1);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].indexExercise).to.equal(1);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseGroupPointsEqual).to.equal(true);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseTitle).to.equal('A');\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseMaxPoints).to.equal(101);\n expect(examChecklistExerciseGroupTableComponent.exerciseGroupVariantColumns[0].exerciseNumberOfParticipations).to.equal(23);\n });\n });\n});\n" }, { "alpha_fraction": 0.6123827695846558, "alphanum_fraction": 0.6143697500228882, "avg_line_length": 44.58695602416992, "blob_id": "bbf3d9a3cb94d63d06f07b87d41f43494c857d81", "content_id": "17e3b8dbc02983aa3d713aafb05611c3f66a2460", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12582, "license_type": "permissive", "max_line_length": 147, "num_lines": 276, "path": "/src/test/javascript/spec/component/lecture-unit/attachment-unit/edit-attachment-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';\nimport { MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable, of } from 'rxjs';\nimport { AttachmentUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/attachment-unit-form/attachment-unit-form.component';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { AttachmentUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/attachmentUnit.service';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { EditAttachmentUnitComponent } from 'app/lecture/lecture-unit/lecture-unit-management/edit-attachment-unit/edit-attachment-unit.component';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-attachment-unit-form', template: '' })\nclass AttachmentUnitFormStubComponent {\n errorMessage: string;\n @Input() isEditMode = false;\n @Input() formData: AttachmentUnitFormData;\n @Output() formSubmitted: EventEmitter<AttachmentUnitFormData> = new EventEmitter<AttachmentUnitFormData>();\n\n setFileUploadError(errorMessage: string) {\n this.errorMessage = errorMessage;\n }\n}\n\n@Component({ selector: 'jhi-lecture-unit-layout', template: '<ng-content></ng-content>' })\nclass LectureUnitLayoutStubComponent {\n @Input()\n isLoading = false;\n}\n\ndescribe('EditAttachmentUnitComponent', () => {\n let editAttachmentUnitComponentFixture: ComponentFixture<EditAttachmentUnitComponent>;\n let editAttachmentUnitComponent: EditAttachmentUnitComponent;\n const sandbox = sinon.createSandbox();\n let fileUploadService;\n let attachmentService;\n let attachmentUnitService;\n let router: Router;\n let uploadFileStub: sinon.SinonStub;\n let updateAttachmentStub: sinon.SinonStub;\n let updateAttachmentUnitStub: sinon.SinonStub;\n let attachment: Attachment;\n let attachmentUnit: AttachmentUnit;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [AttachmentUnitFormStubComponent, LectureUnitLayoutStubComponent, EditAttachmentUnitComponent],\n providers: [\n MockProvider(AttachmentService),\n MockProvider(AttachmentUnitService),\n MockProvider(FileUploaderService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'attachmentUnitId':\n return 1;\n }\n },\n }),\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'lectureId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n editAttachmentUnitComponentFixture = TestBed.createComponent(EditAttachmentUnitComponent);\n editAttachmentUnitComponent = editAttachmentUnitComponentFixture.componentInstance;\n router = TestBed.inject(Router);\n fileUploadService = TestBed.inject(FileUploaderService);\n attachmentService = TestBed.inject(AttachmentService);\n attachmentUnitService = TestBed.inject(AttachmentUnitService);\n\n attachment = new Attachment();\n attachment.id = 1;\n attachment.version = 1;\n attachment.attachmentType = AttachmentType.FILE;\n attachment.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n attachment.uploadDate = moment({ years: 2010, months: 3, date: 5 });\n attachment.name = 'test';\n attachment.link = '/path/to/file';\n\n attachmentUnit = new AttachmentUnit();\n attachmentUnit.id = 1;\n attachmentUnit.description = 'lorem ipsum';\n attachmentUnit.attachment = attachment;\n sandbox.stub(attachmentUnitService, 'findById').returns(\n of(\n new HttpResponse({\n body: attachmentUnit,\n status: 200,\n }),\n ),\n );\n uploadFileStub = sandbox.stub(fileUploadService, 'uploadFile');\n updateAttachmentUnitStub = sandbox.stub(attachmentUnitService, 'update');\n updateAttachmentStub = sandbox.stub(attachmentService, 'update');\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n editAttachmentUnitComponentFixture.detectChanges();\n expect(editAttachmentUnitComponent).to.be.ok;\n });\n\n it('should set form data correctly', () => {\n editAttachmentUnitComponentFixture.detectChanges();\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = editAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n\n expect(attachmentUnitFormStubComponent.formData.formProperties.name).to.equal(attachment.name);\n expect(attachmentUnitFormStubComponent.formData.formProperties.releaseDate).to.equal(attachment.releaseDate);\n expect(attachmentUnitFormStubComponent.formData.formProperties.updateNotificationText).to.be.undefined;\n expect(attachmentUnitFormStubComponent.formData.formProperties.version).to.equal(1);\n expect(attachmentUnitFormStubComponent.formData.formProperties.description).to.equal(attachmentUnit.description);\n expect(attachmentUnitFormStubComponent.formData.fileProperties.fileName).to.equal(attachment.link);\n expect(attachmentUnitFormStubComponent.formData.fileProperties.file).to.be.undefined;\n });\n\n it('should upload file before performing update when file HAS changed', () => {\n editAttachmentUnitComponentFixture.detectChanges();\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = editAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: attachment.name,\n description: attachmentUnit.description,\n releaseDate: attachment.releaseDate,\n version: 1,\n updateNotificationText: 'UPDATED FILE',\n },\n fileProperties: {\n file: fakeBlob,\n fileName: 'updated file',\n },\n };\n\n uploadFileStub.resolves({ path: '/path/to/new/file' });\n attachmentUnitFormStubComponent.formSubmitted.emit(formData);\n expect(uploadFileStub).to.have.been.calledWith(fakeBlob, formData.fileProperties.fileName, { keepFileName: true });\n });\n\n it('should not update file before performing update when file HAS NOT changed', () => {\n editAttachmentUnitComponentFixture.detectChanges();\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = editAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: attachment.name,\n description: attachmentUnit.description,\n releaseDate: attachment.releaseDate,\n version: 1,\n updateNotificationText: 'UPDATED FILE',\n },\n fileProperties: {\n file: undefined,\n fileName: undefined,\n },\n };\n\n attachmentUnitFormStubComponent.formSubmitted.emit(formData);\n expect(uploadFileStub).to.not.have.been.called;\n });\n\n it('should set file file upload error on form', fakeAsync(() => {\n editAttachmentUnitComponentFixture.detectChanges();\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = editAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: attachment.name,\n description: attachmentUnit.description,\n releaseDate: attachment.releaseDate,\n version: 1,\n updateNotificationText: 'UPDATED FILE',\n },\n fileProperties: {\n file: fakeBlob,\n fileName: 'updated filename',\n },\n };\n\n const performUpdateSpy = sinon.spy(editAttachmentUnitComponent, 'performUpdate');\n uploadFileStub.rejects(new Error('some error'));\n attachmentUnitFormStubComponent.formSubmitted.emit(formData);\n editAttachmentUnitComponentFixture.whenStable().then(() => {\n expect(attachmentUnitFormStubComponent.errorMessage).to.equal('some error');\n expect(performUpdateSpy).to.not.have.been.called;\n performUpdateSpy.restore();\n });\n }));\n\n it('should send PUT request for attachment and attachment unit upon form submission and navigate', fakeAsync(() => {\n editAttachmentUnitComponentFixture.detectChanges();\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = editAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: attachment.name,\n description: attachmentUnit.description,\n releaseDate: attachment.releaseDate,\n version: 1,\n updateNotificationText: 'UPDATED FILE',\n },\n fileProperties: {\n file: fakeBlob,\n fileName: 'updated filename',\n },\n };\n\n uploadFileStub.resolves({ path: '/path/to/new/file' });\n updateAttachmentStub.returns(of(new Attachment()));\n updateAttachmentUnitStub.returns(of(new AttachmentUnit()));\n const navigateSpy = sinon.spy(router, 'navigate');\n\n attachmentUnitFormStubComponent.formSubmitted.emit(formData);\n\n editAttachmentUnitComponentFixture.whenStable().then(() => {\n expect(navigateSpy).to.have.been.calledOnce;\n expect(updateAttachmentUnitStub).to.have.been.calledOnce;\n expect(updateAttachmentStub).to.have.been.calledOnce;\n navigateSpy.restore();\n });\n }));\n});\n" }, { "alpha_fraction": 0.6794992089271545, "alphanum_fraction": 0.6801251769065857, "avg_line_length": 45.985294342041016, "blob_id": "8477db31a3af2dc5b1710a30343b82c960a35e9d", "content_id": "a8f9e271e6f9b48470b7c715ab5ae0013a1d6337", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3195, "license_type": "permissive", "max_line_length": 159, "num_lines": 68, "path": "/src/test/javascript/spec/component/text-submission-assessment/text-assessment-area.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { TestBed, ComponentFixture } from '@angular/core/testing';\nimport { TextAssessmentAreaComponent } from 'app/exercises/text/assess/text-assessment-area/text-assessment-area.component';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { TextblockAssessmentCardComponent } from 'app/exercises/text/assess/textblock-assessment-card/textblock-assessment-card.component';\nimport { TextblockFeedbackEditorComponent } from 'app/exercises/text/assess/textblock-feedback-editor/textblock-feedback-editor.component';\nimport { TextBlockRef } from 'app/entities/text-block-ref.model';\nimport { By } from '@angular/platform-browser';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { MockComponent } from 'ng-mocks';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ManualTextblockSelectionComponent } from 'app/exercises/text/assess/manual-textblock-selection/manual-textblock-selection.component';\nimport { TextSharedModule } from 'app/exercises/text/shared/text-shared.module';\n\ndescribe('TextAssessmentAreaComponent', () => {\n let component: TextAssessmentAreaComponent;\n let fixture: ComponentFixture<TextAssessmentAreaComponent>;\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisConfirmIconModule, TextSharedModule],\n declarations: [TextAssessmentAreaComponent, TextblockAssessmentCardComponent, TextblockFeedbackEditorComponent, ManualTextblockSelectionComponent],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n })\n .overrideModule(ArtemisTestModule, {\n remove: {\n declarations: [MockComponent(FaIconComponent)],\n exports: [MockComponent(FaIconComponent)],\n },\n })\n .compileComponents();\n });\n\n beforeEach(() => {\n fixture = TestBed.createComponent(TextAssessmentAreaComponent);\n component = fixture.componentInstance;\n fixture.detectChanges();\n });\n\n it('should create', () => {\n expect(component).toBeTruthy();\n });\n\n it('should add a TextblockAssessmentCardComponent for each TextBlockRef', () => {\n const textBlockRefs = [\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n TextBlockRef.new(),\n ];\n\n for (let i = 0; i < textBlockRefs.length; i++) {\n component.textBlockRefs = textBlockRefs.slice(0, i);\n fixture.detectChanges();\n\n const all = fixture.debugElement.queryAll(By.directive(TextblockAssessmentCardComponent));\n expect(all.length).toBe(i);\n }\n });\n});\n" }, { "alpha_fraction": 0.6395532488822937, "alphanum_fraction": 0.6402816772460938, "avg_line_length": 42.352630615234375, "blob_id": "6f63b25bb90afa216b8006962a0c137f8bdeeb86", "content_id": "57eaea11344df490ad2dd09ddfa380ec151e420a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8237, "license_type": "permissive", "max_line_length": 175, "num_lines": 190, "path": "/src/main/webapp/app/complaints/complaint-interactions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit } from '@angular/core';\nimport { Exercise } from 'app/entities/exercise.model';\nimport * as moment from 'moment';\nimport { ComplaintType } from 'app/entities/complaint.model';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { Result } from 'app/entities/result.model';\nimport { ActivatedRoute } from '@angular/router';\nimport { Course } from 'app/entities/course.model';\nimport { ArtemisServerDateService } from 'app/shared/server-date.service';\nimport { Exam } from 'app/entities/exam.model';\nimport { AccountService } from 'app/core/auth/account.service';\n\n@Component({\n selector: 'jhi-complaint-interactions',\n templateUrl: './complaint-interactions.component.html',\n})\nexport class ComplaintInteractionsComponent implements OnInit {\n @Input() exercise: Exercise;\n @Input() participation: StudentParticipation;\n @Input() result: Result;\n @Input() exam: Exam;\n // flag to indicate exam test run. Default set to false.\n @Input() testRun = false;\n isCurrentUserSubmissionAuthor: boolean;\n\n get isExamMode() {\n return this.exam != undefined;\n }\n\n showRequestMoreFeedbackForm = false;\n // indicates if there is a complaint for the result of the submission\n hasComplaint = false;\n // indicates if more feedback was requested already\n hasRequestMoreFeedback = false;\n // the number of complaints that the student is still allowed to submit in the course. this is used for disabling the complain button.\n numberOfAllowedComplaints: number;\n showComplaintForm = false;\n ComplaintType = ComplaintType;\n\n constructor(\n private complaintService: ComplaintService,\n private activatedRoute: ActivatedRoute,\n private serverDateService: ArtemisServerDateService,\n private accountService: AccountService,\n ) {}\n\n /**\n * Loads the number of allowed complaints and feedback requests\n */\n ngOnInit(): void {\n if (this.isExamMode) {\n if (this.participation && this.participation.id && this.exercise) {\n if (this.participation.results && this.participation.results.length > 0) {\n // Make sure result and participation are connected\n this.result = this.participation.results[0];\n this.result.participation = this.participation;\n }\n }\n } else {\n if (this.course) {\n // for normal exercises we track the number of allowed complaints\n if (this.course.complaintsEnabled) {\n this.complaintService.getNumberOfAllowedComplaintsInCourse(this.course.id!, this.exercise.teamMode).subscribe((allowedComplaints: number) => {\n this.numberOfAllowedComplaints = allowedComplaints;\n });\n } else {\n this.numberOfAllowedComplaints = 0;\n }\n }\n }\n if (this.participation.submissions && this.participation.submissions.length > 0) {\n if (this.result && this.result.completionDate) {\n this.complaintService.findByResultId(this.result.id!).subscribe((res) => {\n if (res.body) {\n if (res.body.complaintType == undefined || res.body.complaintType === ComplaintType.COMPLAINT) {\n this.hasComplaint = true;\n } else {\n this.hasRequestMoreFeedback = true;\n }\n }\n });\n }\n }\n this.accountService.identity().then((user) => {\n if (this.participation && this.participation.student && user && user.id) {\n this.isCurrentUserSubmissionAuthor = this.participation.student.id === user.id;\n }\n });\n }\n\n get course(): Course | undefined {\n return this.exercise.course;\n }\n\n /**\n * We disable the component, if no complaint has been made by the user during the Student Review period, for exam exercises.\n */\n get noValidComplaintWasSubmittedWithinTheStudentReviewPeriod() {\n if (this.testRun) {\n return false;\n }\n return !this.isTimeOfComplaintValid && !this.hasComplaint;\n }\n\n /**\n * This function is used to check whether the student is allowed to submit a complaint or not.\n * For exams, submitting a complaint is allowed within the Student Review Period, see {@link isWithinStudentReviewPeriod}.\n *\n * For normal course exercises, submitting a complaint is allowed within one week after the student received the\n * result. If the result was submitted after the assessment due date or the assessment due date is not set, the completion date of the result is checked. If the result was\n * submitted before the assessment due date, the assessment due date is checked, as the student can only see the result after the assessment due date.\n */\n get isTimeOfComplaintValid(): boolean {\n if (this.isExamMode) {\n if (this.testRun) {\n return !!this.result && !!this.result.completionDate;\n }\n return this.isWithinStudentReviewPeriod() && !!this.result && !!this.result.completionDate;\n } else if (this.result && this.result.completionDate) {\n const resultCompletionDate = moment(this.result.completionDate!);\n if (!this.exercise.assessmentDueDate || resultCompletionDate.isAfter(this.exercise.assessmentDueDate)) {\n return resultCompletionDate.isAfter(moment().subtract(this.course?.maxComplaintTimeDays, 'day'));\n }\n return moment(this.exercise.assessmentDueDate).isAfter(moment().subtract(this.course?.maxComplaintTimeDays, 'day'));\n } else {\n return false;\n }\n }\n\n /**\n * Analogous to isTimeOfComplaintValid but exams cannot have more feedback requests.\n */\n get isTimeOfFeedbackRequestValid(): boolean {\n if (this.isExamMode) {\n return false;\n } else if (this.result && this.result.completionDate) {\n const resultCompletionDate = moment(this.result.completionDate!);\n if (!this.exercise.assessmentDueDate || resultCompletionDate.isAfter(this.exercise.assessmentDueDate)) {\n return resultCompletionDate.isAfter(moment().subtract(this.course?.maxRequestMoreFeedbackTimeDays, 'day'));\n }\n return moment(this.exercise.assessmentDueDate).isAfter(moment().subtract(this.course?.maxRequestMoreFeedbackTimeDays, 'day'));\n } else {\n return false;\n }\n }\n\n /**\n * A guard function used to indicate whether complaint submissions are valid.\n * These are only allowed if they are submitted within the student review period.\n */\n private isWithinStudentReviewPeriod(): boolean {\n if (this.testRun) {\n return true;\n }\n if (this.exam.examStudentReviewStart && this.exam.examStudentReviewEnd) {\n return this.serverDateService.now().isBetween(this.exam.examStudentReviewStart, this.exam.examStudentReviewEnd);\n } else {\n return false;\n }\n }\n\n /**\n * toggles between showing the complaint form\n */\n toggleComplaintForm() {\n this.showRequestMoreFeedbackForm = false;\n this.showComplaintForm = !this.showComplaintForm;\n }\n\n /**\n * toggles between showing the feedback request form\n */\n toggleRequestMoreFeedbackForm() {\n this.showComplaintForm = false;\n this.showRequestMoreFeedbackForm = !this.showRequestMoreFeedbackForm;\n }\n\n /**\n * Calculates the maximum number of complaints allowed for the exercise.\n * In case of exams, it returns an arbitrary number > 0, as we do not limit the number of complaints for exams\n */\n calculateMaxComplaints() {\n if (this.course) {\n return this.exercise.teamMode ? this.course.maxTeamComplaints! : this.course.maxComplaints!;\n } else {\n return 1;\n }\n }\n}\n" }, { "alpha_fraction": 0.7245155572891235, "alphanum_fraction": 0.7379949688911438, "avg_line_length": 41.39285659790039, "blob_id": "f34b674173d53e072a5dafa0626f4f40eff496d1", "content_id": "901ef70f4eabf44b6674a6353c6e4b10c8d3162a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1187, "license_type": "permissive", "max_line_length": 191, "num_lines": 28, "path": "/src/main/resources/templates/ocaml/test/run.sh", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nOUTPUT_FOLDER=\"test-reports\"\nOUTPUT_FILE=\"$OUTPUT_FOLDER/results.xml\"\nERROR_LOG=\"build_errors.txt\"\nTIMEOUT=\"5m\" # Timeout for running all tests\nVERBOSE=false # Set to true to print out compile errors. Be aware that compile errors might show test code.\n\neval $(opam env)\n\n# Run the test\n# If there are build failures, the compiler sometimes prints source code of tests to stderr by default, which is shown to the participant.\n# Therefore, hide stderr output by rederecting it to a file.\ntimeout -s SIGTERM $TIMEOUT dune runtest --build-dir=$OUTPUT_FOLDER 2>$ERROR_LOG\n\nif [ $? = 124 ]; then # timeout exits with 124 if it had to kill the tests.\n echo -e \"Testing your submission resulted in a timeout.\" 1>&2\n# Warn the participant in case no output file could be generated\nelif [ ! -f \"$OUTPUT_FILE\" ]; then\n echo -e \"Your submission could not be built.\\nPlease check whether your submission compiles and whether all functions and constants have the type specified in the problem statement.\" 1>&2\n\n if $VERBOSE ; then\n cat $ERROR_LOG 1>&2\n fi\nfi\n\n# We always exit this script with error code 0, so that the following steps on Bamboo are performed.\nexit 0\n" }, { "alpha_fraction": 0.7131719589233398, "alphanum_fraction": 0.7141977548599243, "avg_line_length": 41.75438690185547, "blob_id": "0ec60c30bb0e7c346582f743cbcd7e1d0764a115", "content_id": "c1fcf2eb7e834b40727304c7d3581a5b2d17ac73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4874, "license_type": "permissive", "max_line_length": 151, "num_lines": 114, "path": "/src/main/java/de/tum/in/www1/artemis/service/exam/ExamDateService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.exam;\n\nimport java.time.ZonedDateTime;\nimport java.util.Set;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.repository.ExamRepository;\nimport de.tum.in.www1.artemis.repository.StudentExamRepository;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n@Service\npublic class ExamDateService {\n\n private final ExamRepository examRepository;\n\n private final StudentExamRepository studentExamRepository;\n\n public ExamDateService(ExamRepository examRepository, StudentExamRepository studentExamRepository) {\n this.examRepository = examRepository;\n this.studentExamRepository = studentExamRepository;\n }\n\n /**\n * Returns if the exam is over by checking if the latest individual exam end date plus grace period has passed.\n * See {@link ExamDateService#getLatestIndividualExamEndDate}\n * <p>\n *\n * @param examId the id of the exam\n * @return true if the exam is over and the students cannot submit anymore\n * @throws EntityNotFoundException if no exam with the given examId can be found\n */\n public boolean isExamWithGracePeriodOver(Long examId) {\n final var exam = examRepository.findByIdElseThrow(examId);\n return isExamWithGracePeriodOver(exam);\n }\n\n /**\n * Returns if the exam is over by checking if the latest individual exam end date plus grace period has passed.\n * See {@link ExamDateService#getLatestIndividualExamEndDate}\n * <p>\n *\n * @param exam the exam\n * @return true if the exam is over and the students cannot submit anymore\n * @throws EntityNotFoundException if no exam with the given examId can be found\n */\n public boolean isExamWithGracePeriodOver(Exam exam) {\n var now = ZonedDateTime.now();\n return getLatestIndividualExamEndDate(exam).plusSeconds(exam.getGracePeriod()).isBefore(now);\n }\n\n /**\n * Returns the latest individual exam end date as determined by the working time of the student exams.\n * <p>\n * If no student exams are available, the exam end date is returned.\n *\n * @param examId the id of the exam\n * @return the latest end date or the exam end date if no student exams are found. May return <code>null</code>, if the exam has no start/end date.\n * @throws EntityNotFoundException if no exam with the given examId can be found\n */\n @NotNull\n public ZonedDateTime getLatestIndividualExamEndDate(Long examId) {\n final var exam = examRepository.findByIdElseThrow(examId);\n return getLatestIndividualExamEndDate(exam);\n }\n\n /**\n * Returns the latest individual exam end date as determined by the working time of the student exams.\n * <p>\n * If no student exams are available, the exam end date is returned.\n *\n * @param exam the exam\n * @return the latest end date or the exam end date if no student exams are found. May return <code>null</code>, if the exam has no start/end date.\n */\n @NotNull\n public ZonedDateTime getLatestIndividualExamEndDate(Exam exam) {\n var maxWorkingTime = studentExamRepository.findMaxWorkingTimeByExamId(exam.getId());\n return maxWorkingTime.map(timeInSeconds -> exam.getStartDate().plusSeconds(timeInSeconds)).orElse(exam.getEndDate());\n }\n\n /**\n * Returns all individual exam end dates as determined by the working time of the student exams.\n * <p>\n * If no student exams are available, an empty set returned.\n *\n * @param examId the id of the exam\n * @return a set of all end dates. May return an empty set, if the exam has no start/end date or student exams cannot be found.\n * @throws EntityNotFoundException if no exam with the given examId can be found\n */\n public Set<ZonedDateTime> getAllIndividualExamEndDates(Long examId) {\n final var exam = examRepository.findByIdElseThrow(examId);\n return getAllIndividualExamEndDates(exam);\n }\n\n /**\n * Returns all individual exam end dates as determined by the working time of the student exams.\n * <p>\n * If no student exams are available, an empty set returned.\n *\n * @param exam the exam\n * @return a set of all end dates. May return an empty set, if the exam has no start/end date or student exams cannot be found.\n */\n public Set<ZonedDateTime> getAllIndividualExamEndDates(Exam exam) {\n if (exam.getStartDate() == null) {\n return null;\n }\n var workingTimes = studentExamRepository.findAllDistinctWorkingTimesByExamId(exam.getId());\n return workingTimes.stream().map(timeInSeconds -> exam.getStartDate().plusSeconds(timeInSeconds)).collect(Collectors.toSet());\n }\n}\n" }, { "alpha_fraction": 0.6902777552604675, "alphanum_fraction": 0.6936728358268738, "avg_line_length": 48.846153259277344, "blob_id": "59183ce122b8e46f90c7e27c47b8b50ef3efa619", "content_id": "6f963f20bdeb3460495dc8bdfaff7e34c772d8bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6480, "license_type": "permissive", "max_line_length": 140, "num_lines": 130, "path": "/src/test/javascript/spec/component/learning-goals/learning-goal-management.component.spect.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { of } from 'rxjs';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { LearningGoalManagementComponent } from 'app/course/learning-goals/learning-goal-management/learning-goal-management.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ActivatedRoute } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Component, Input } from '@angular/core';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\nimport { CourseLearningGoalProgress, CourseLectureUnitProgress } from 'app/course/learning-goals/learning-goal-course-progress.dtos.model';\nimport * as Sentry from '@sentry/browser';\nimport * as _ from 'lodash';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-learning-goal-card', template: '<div><ng-content></ng-content></div>' })\nclass LearningGoalCardStubComponent {\n @Input() learningGoal: LearningGoal;\n @Input() learningGoalProgress: CourseLearningGoalProgress;\n}\n\ndescribe('LearningGoalManagementComponent', () => {\n let learningGoalManagementComponentFixture: ComponentFixture<LearningGoalManagementComponent>;\n let learningGoalManagementComponent: LearningGoalManagementComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([])],\n declarations: [\n LearningGoalManagementComponent,\n LearningGoalCardStubComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(AlertComponent),\n MockComponent(FaIconComponent),\n MockDirective(DeleteButtonDirective),\n MockDirective(HasAnyAuthorityDirective),\n ],\n providers: [\n MockProvider(JhiAlertService),\n MockProvider(LearningGoalService),\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n params: of({\n courseId: 1,\n }),\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n learningGoalManagementComponentFixture = TestBed.createComponent(LearningGoalManagementComponent);\n learningGoalManagementComponent = learningGoalManagementComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n learningGoalManagementComponentFixture.detectChanges();\n expect(learningGoalManagementComponent).to.be.ok;\n });\n\n it('should load learning goal and associated progress and display a card for each of them', () => {\n const learningGoalService = TestBed.inject(LearningGoalService);\n const learningGoal = new LearningGoal();\n const textUnit = new TextUnit();\n learningGoal.id = 1;\n learningGoal.description = 'test';\n learningGoal.lectureUnits = [textUnit];\n const courseLectureUnitProgress = new CourseLectureUnitProgress();\n courseLectureUnitProgress.lectureUnitId = 1;\n courseLectureUnitProgress.totalPointsAchievableByStudentsInLectureUnit = 10;\n const courseLearningGoalProgress = new CourseLearningGoalProgress();\n courseLearningGoalProgress.courseId = 1;\n courseLearningGoalProgress.learningGoalId = 1;\n courseLearningGoalProgress.learningGoalTitle = 'test';\n courseLearningGoalProgress.averagePointsAchievedByStudentInLearningGoal = 5;\n courseLearningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 10;\n courseLearningGoalProgress.progressInLectureUnits = [courseLectureUnitProgress];\n\n const learningGoalsOfCourseResponse: HttpResponse<LearningGoal[]> = new HttpResponse({\n body: [learningGoal, new LearningGoal()],\n status: 200,\n });\n const learningGoalProgressResponse: HttpResponse<CourseLearningGoalProgress> = new HttpResponse({\n body: courseLearningGoalProgress,\n status: 200,\n });\n const courseProgressParticipantScores = _.cloneDeep(courseLearningGoalProgress);\n courseProgressParticipantScores.averagePointsAchievedByStudentInLearningGoal = 1;\n const learningGoalProgressParticipantScoreResponse: HttpResponse<CourseLearningGoalProgress> = new HttpResponse({\n body: courseProgressParticipantScores,\n status: 200,\n });\n const getAllForCourseStub = sinon.stub(learningGoalService, 'getAllForCourse').returns(of(learningGoalsOfCourseResponse));\n const getProgressStub = sinon.stub(learningGoalService, 'getCourseProgress');\n getProgressStub.withArgs(sinon.match.any, sinon.match.any, false).returns(of(learningGoalProgressResponse));\n getProgressStub.withArgs(sinon.match.any, sinon.match.any, true).returns(of(learningGoalProgressParticipantScoreResponse));\n\n const captureExceptionSpy = sinon.spy(Sentry, 'captureException');\n\n learningGoalManagementComponentFixture.detectChanges();\n\n const learningGoalCards = learningGoalManagementComponentFixture.debugElement.queryAll(By.directive(LearningGoalCardStubComponent));\n expect(learningGoalCards).to.have.lengthOf(2);\n expect(getAllForCourseStub).to.have.been.calledOnce;\n expect(getProgressStub).to.have.callCount(4);\n expect(captureExceptionSpy).to.have.been.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.6746442317962646, "alphanum_fraction": 0.6746442317962646, "avg_line_length": 29.3137264251709, "blob_id": "c81da5ef3d8f25e65a6c4c7c32d32839976d9c77", "content_id": "f4abbd7ac817574b18e76acf0d66e96498be6896", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1546, "license_type": "permissive", "max_line_length": 125, "num_lines": 51, "path": "/src/main/webapp/app/assessment/assessment-filters/assessment-filters.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { getLatestSubmissionResult, Submission } from 'app/entities/submission.model';\n\n/**\n * filters for all or only locked submissions\n */\nenum FilterProp {\n ALL = 'all',\n LOCKED = 'locked',\n}\n\n@Component({\n selector: 'jhi-assessment-filters',\n templateUrl: './assessment-filters.component.html',\n})\nexport class AssessmentFiltersComponent {\n FilterProp = FilterProp;\n\n filterProp: FilterProp = FilterProp.ALL;\n\n @Input() submissions: Submission[] = [];\n\n @Output() filterChange = new EventEmitter<Submission[]>();\n\n /**\n * Updates filter to either filtering for locked or all assessments\n * @param {FilterProp} filterProp - filter type\n */\n public updateFilter(filterProp: FilterProp) {\n this.filterProp = filterProp;\n this.updateFilteredSubmissions();\n }\n\n private updateFilteredSubmissions() {\n this.filterChange.emit(this.submissions.filter(this.filterSubmissionByProp));\n }\n\n private filterSubmissionByProp = (submission: Submission) => {\n switch (this.filterProp) {\n case FilterProp.LOCKED:\n return AssessmentFiltersComponent.isSubmissionLocked(submission);\n case FilterProp.ALL:\n default:\n return true;\n }\n };\n\n private static isSubmissionLocked(submission: Submission) {\n return submission && getLatestSubmissionResult(submission) && !getLatestSubmissionResult(submission)!.completionDate;\n }\n}\n" }, { "alpha_fraction": 0.7396699786186218, "alphanum_fraction": 0.7405500411987305, "avg_line_length": 63.194915771484375, "blob_id": "c9b804575408551f5217bce99b90ae83b5438272", "content_id": "0faf09408b42d95247657c806d9912c4755594fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 22725, "license_type": "permissive", "max_line_length": 180, "num_lines": 354, "path": "/src/test/java/de/tum/in/www1/artemis/connector/bitbucket/BitbucketRequestMockProvider.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.connector.bitbucket;\n\nimport static org.hamcrest.text.MatchesPattern.matchesPattern;\nimport static org.springframework.test.web.client.match.MockRestRequestMatchers.*;\nimport static org.springframework.test.web.client.response.MockRestResponseCreators.*;\n\nimport java.io.IOException;\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.net.URL;\nimport java.util.*;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.http.HttpMethod;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.MediaType;\nimport org.springframework.stereotype.Component;\nimport org.springframework.test.web.client.ExpectedCount;\nimport org.springframework.test.web.client.MockRestServiceServer;\nimport org.springframework.web.client.RestTemplate;\nimport org.springframework.web.util.UriComponentsBuilder;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport com.fasterxml.jackson.databind.JsonNode;\nimport com.fasterxml.jackson.databind.ObjectMapper;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.User;\nimport de.tum.in.www1.artemis.domain.VcsRepositoryUrl;\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.service.UrlService;\nimport de.tum.in.www1.artemis.service.connectors.bitbucket.dto.*;\nimport de.tum.in.www1.artemis.service.user.PasswordService;\n\n@Component\n@Profile(\"bitbucket\")\npublic class BitbucketRequestMockProvider {\n\n @Value(\"${artemis.version-control.url}\")\n private URL bitbucketServerUrl;\n\n @Value(\"${artemis.user-management.external.admin-group-name}\")\n private String adminGroupName;\n\n @Value(\"${artemis.lti.user-prefix-edx:#{null}}\")\n private Optional<String> userPrefixEdx;\n\n @Value(\"${artemis.lti.user-prefix-u4i:#{null}}\")\n private Optional<String> userPrefixU4I;\n\n private final RestTemplate restTemplate;\n\n private final RestTemplate shortTimeoutRestTemplate;\n\n private final ObjectMapper mapper = new ObjectMapper();\n\n @Autowired\n private UrlService urlService;\n\n private MockRestServiceServer mockServer;\n\n private MockRestServiceServer mockServerShortTimeout;\n\n private final PasswordService passwordService;\n\n public BitbucketRequestMockProvider(PasswordService passwordService, @Qualifier(\"bitbucketRestTemplate\") RestTemplate restTemplate,\n @Qualifier(\"shortTimeoutBitbucketRestTemplate\") RestTemplate shortTimeoutRestTemplate) {\n this.passwordService = passwordService;\n this.restTemplate = restTemplate;\n this.shortTimeoutRestTemplate = shortTimeoutRestTemplate;\n }\n\n public void enableMockingOfRequests() {\n enableMockingOfRequests(false);\n }\n\n public void enableMockingOfRequests(boolean ignoreExpectOrder) {\n MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate);\n builder.ignoreExpectOrder(ignoreExpectOrder);\n mockServer = builder.build();\n\n MockRestServiceServer.MockRestServiceServerBuilder builderShortTimeout = MockRestServiceServer.bindTo(shortTimeoutRestTemplate);\n builderShortTimeout.ignoreExpectOrder(ignoreExpectOrder);\n mockServerShortTimeout = builderShortTimeout.build();\n }\n\n public void reset() {\n if (mockServer != null) {\n mockServer.reset();\n }\n }\n\n public void mockCreateProjectForExercise(ProgrammingExercise exercise) throws IOException, URISyntaxException {\n final var projectKey = exercise.getProjectKey();\n final var projectName = exercise.getProjectName();\n final var body = new BitbucketProjectDTO(projectKey, projectName);\n\n mockServer.expect(ExpectedCount.once(), requestTo(bitbucketServerUrl + \"/rest/api/latest/projects\")).andExpect(method(HttpMethod.POST))\n .andExpect(content().json(mapper.writeValueAsString(body))).andRespond(withStatus(HttpStatus.OK));\n\n mockGrantGroupPermissionToProject(exercise, adminGroupName, \"PROJECT_ADMIN\");\n mockGrantGroupPermissionToProject(exercise, exercise.getCourseViaExerciseGroupOrCourseMember().getInstructorGroupName(), \"PROJECT_ADMIN\");\n if (exercise.getCourseViaExerciseGroupOrCourseMember().getTeachingAssistantGroupName() != null) {\n mockGrantGroupPermissionToProject(exercise, exercise.getCourseViaExerciseGroupOrCourseMember().getTeachingAssistantGroupName(), \"PROJECT_WRITE\");\n }\n }\n\n public void mockGrantGroupPermissionToProject(ProgrammingExercise exercise, String groupName, String permission) throws URISyntaxException {\n final var projectKey = exercise.getProjectKey();\n final var permissionPath = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(projectKey).path(\"/permissions/groups/\")\n .queryParam(\"name\", groupName).queryParam(\"permission\", permission);\n\n mockServer.expect(ExpectedCount.once(), requestTo(permissionPath.build().toUri())).andExpect(method(HttpMethod.PUT)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockCreateRepository(ProgrammingExercise exercise, String repositoryName) throws URISyntaxException, IOException {\n final var projectKey = exercise.getProjectKey();\n final var body = new BitbucketRepositoryDTO(repositoryName);\n final var createRepoPath = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(projectKey).path(\"/repos\");\n\n mockServer.expect(requestTo(createRepoPath.build().toUri())).andExpect(method(HttpMethod.POST)).andExpect(content().json(mapper.writeValueAsString(body)))\n .andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockAddWebHooks(ProgrammingExercise exercise) throws IOException {\n final var projectKey = exercise.getProjectKey();\n final var searchResult = new BitbucketSearchDTO<BitbucketWebHookDTO>();\n searchResult.setSize(0);\n searchResult.setSearchResults(new ArrayList<>());\n\n mockServer.expect(ExpectedCount.manyTimes(), requestTo(matchesPattern(bitbucketServerUrl + \"/rest/api/latest/projects/\" + projectKey + \"/repos/.*/webhooks\")))\n .andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.OK).body(mapper.writeValueAsString(searchResult)).contentType(MediaType.APPLICATION_JSON));\n mockServer.expect(ExpectedCount.manyTimes(), requestTo(matchesPattern(bitbucketServerUrl + \"/rest/api/latest/projects/\" + projectKey + \"/repos/.*/webhooks\")))\n .andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockCopyRepositoryForParticipation(ProgrammingExercise exercise, String username) throws URISyntaxException, IOException {\n final var projectKey = exercise.getProjectKey();\n final var clonedRepoName = projectKey.toLowerCase() + \"-\" + username.toLowerCase();\n mockCreateRepository(exercise, clonedRepoName);\n }\n\n public void mockGetBitbucketRepository(ProgrammingExercise exercise, String bitbucketRepoName, BitbucketRepositoryDTO bitbucketRepository)\n throws URISyntaxException, JsonProcessingException {\n URI uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(exercise.getProjectKey()).pathSegment(\"repos\")\n .pathSegment(bitbucketRepoName).build().toUri();\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(mapper.writeValueAsString(bitbucketRepository)));\n }\n\n public void mockConfigureRepository(ProgrammingExercise exercise, String username, Set<User> users, boolean ltiUserExists) throws URISyntaxException, IOException {\n final var projectKey = exercise.getProjectKey();\n final var repoName = projectKey.toLowerCase() + \"-\" + username.toLowerCase();\n for (User user : users) {\n if (exercise.isCourseExercise()) {\n // add mock for userExists() check, if the username contains edx_ or u4i_\n String loginName = user.getLogin();\n if (userPrefixEdx.isPresent() && loginName.startsWith(userPrefixEdx.get()) || userPrefixU4I.isPresent() && loginName.startsWith(userPrefixU4I.get())) {\n if (ltiUserExists) {\n mockUserExists(loginName);\n }\n else {\n mockUserDoesNotExist(loginName);\n String displayName = (user.getFirstName() + \" \" + user.getLastName()).trim();\n mockCreateUser(loginName, passwordService.decryptPassword(user.getPassword()), user.getEmail(), displayName);\n mockAddUserToGroups();\n }\n }\n mockGiveWritePermission(exercise, repoName, user.getLogin(), HttpStatus.OK);\n }\n // exam exercises receive write permissions when the exam starts\n }\n mockProtectBranches(exercise, repoName);\n }\n\n public void mockUserExists(String userName) throws URISyntaxException {\n final var path = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/users/\").path(userName).build().toUri();\n mockServer.expect(requestTo(path)).andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockUserDoesNotExist(String userName) throws URISyntaxException {\n final var path = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/users/\").path(userName).build().toUri();\n mockServer.expect(requestTo(path)).andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND));\n }\n\n public void mockCreateUser(String userName, String password, String emailAddress, String displayName) {\n final var path = UriComponentsBuilder.fromHttpUrl(bitbucketServerUrl + \"/rest/api/latest/admin/users\").queryParam(\"name\", userName).queryParam(\"email\", emailAddress)\n .queryParam(\"emailAddress\", emailAddress).queryParam(\"password\", password).queryParam(\"displayName\", displayName).queryParam(\"addToDefaultGroup\", \"true\")\n .queryParam(\"notify\", \"false\").build().toUri();\n mockServer.expect(requestTo(path)).andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockAddUserToGroups() throws URISyntaxException {\n final var path = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/admin/users/add-groups\").build().toUri();\n mockServer.expect(requestTo(path)).andExpect(method(HttpMethod.POST)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockGiveWritePermission(ProgrammingExercise exercise, String repositoryName, String username, HttpStatus status) throws URISyntaxException {\n final var projectKey = exercise.getProjectKey();\n final var permissionPath = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(projectKey).path(\"/repos/\")\n .pathSegment(repositoryName).path(\"/permissions/users\").queryParam(\"name\", username).queryParam(\"permission\", \"REPO_WRITE\").build().toUri();\n\n mockServer.expect(requestTo(permissionPath)).andExpect(method(HttpMethod.PUT)).andRespond(withStatus(status));\n }\n\n public void mockProtectBranches(ProgrammingExercise exercise, String repositoryName) throws IOException, URISyntaxException {\n final var projectKey = exercise.getProjectKey();\n final var type = new BitbucketBranchProtectionDTO.TypeDTO(\"PATTERN\", \"Pattern\");\n // A wildcard (*) ist used to protect all branches\n final var matcher = new BitbucketBranchProtectionDTO.MatcherDTO(\"*\", \"*\", type, true);\n // Prevent force-pushes\n final var fastForwardOnlyProtection = new BitbucketBranchProtectionDTO(\"fast-forward-only\", matcher);\n // Prevent deletion of branches\n final var noDeletesProtection = new BitbucketBranchProtectionDTO(\"no-deletes\", matcher);\n final var body = List.of(fastForwardOnlyProtection, noDeletesProtection);\n final var protectBranchPath = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/branch-permissions/2.0/projects/\").pathSegment(projectKey)\n .path(\"/repos/\").pathSegment(repositoryName).path(\"/restrictions\").build().toUri();\n\n mockServer.expect(requestTo(protectBranchPath)).andExpect(method(HttpMethod.POST)).andExpect(content().json(mapper.writeValueAsString(body)))\n .andExpect(content().contentType(\"application/vnd.atl.bitbucket.bulk+json\")).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockRepositoryUrlIsValid(final VcsRepositoryUrl repositoryUrl, final String projectKey, final boolean isValid) throws URISyntaxException {\n final var repositoryName = urlService.getRepositorySlugFromRepositoryUrl(repositoryUrl);\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(projectKey).pathSegment(\"repos\")\n .pathSegment(repositoryName).build().toUri();\n\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.GET)).andRespond(withStatus(isValid ? HttpStatus.OK : HttpStatus.BAD_REQUEST));\n }\n\n /**\n * This method mocks that the programming exercise with the same project key (based on the course + programming exercise short name) already exists\n *\n * @param exercise the programming exercise that already exists\n */\n public void mockProjectKeyExists(ProgrammingExercise exercise) throws URISyntaxException, JsonProcessingException {\n final var existsUri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(exercise.getProjectKey()).build().toUri();\n var existingProject = new BitbucketProjectDTO(exercise.getProjectKey());\n existingProject.setName(\"existingProject\");\n mockServer.expect(requestTo(existsUri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(mapper.writeValueAsString(existingProject)));\n }\n\n /**\n * This method mocks that the programming exercise with the same project name already exists (depending on the boolean input exists), based on the programming exercise title\n *\n * @param exercise the programming exercise that might already exist\n * @param exists whether the programming exercise with the same title exists\n * @throws JsonProcessingException exception in the processing of json files\n * @throws URISyntaxException exception in the processing of uris\n */\n public void mockCheckIfProjectExists(final ProgrammingExercise exercise, final boolean exists) throws JsonProcessingException, URISyntaxException {\n final var existsUri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").pathSegment(exercise.getProjectKey()).build().toUri();\n final var uniqueUri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").queryParam(\"name\", exercise.getProjectName()).build()\n .toUri();\n final var searchResults = new BitbucketSearchDTO<BitbucketProjectDTO>();\n final var foundProject = new BitbucketProjectDTO();\n foundProject.setName(exercise.getProjectName() + (exists ? \"\" : \"abc\"));\n searchResults.setSearchResults(List.of(foundProject));\n searchResults.setSize(1);\n\n mockServer.expect(requestTo(existsUri)).andExpect(method(HttpMethod.GET)).andRespond(withStatus(HttpStatus.NOT_FOUND));\n mockServer.expect(requestTo(uniqueUri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(mapper.writeValueAsString(searchResults)));\n }\n\n public void mockGetExistingWebhooks(String projectKey, String repositoryName) throws URISyntaxException, JsonProcessingException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).path(\"repos\").pathSegment(repositoryName)\n .path(\"webhooks\").build().toUri();\n final var searchResult = new BitbucketSearchDTO<BitbucketWebHookDTO>();\n searchResult.setSize(0);\n searchResult.setSearchResults(new ArrayList<>());\n\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(HttpStatus.OK).body(mapper.writeValueAsString(searchResult)).contentType(MediaType.APPLICATION_JSON));\n }\n\n public void mockAddWebhook(String projectKey, String repositoryName, String url) throws JsonProcessingException, URISyntaxException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).path(\"repos\").pathSegment(repositoryName)\n .path(\"webhooks\").build().toUri();\n final var body = new BitbucketWebHookDTO(\"Artemis WebHook\", url, List.of(\"repo:refs_changed\"));\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.POST)).andExpect(content().contentType(MediaType.APPLICATION_JSON))\n .andExpect(content().json(mapper.writeValueAsString(body))).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockDeleteProject(String projectKey, boolean shouldFail) throws URISyntaxException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).build().toUri();\n var status = shouldFail ? HttpStatus.BAD_REQUEST : HttpStatus.OK;\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.DELETE)).andRespond(withStatus(status));\n }\n\n public void mockDeleteRepository(String projectKey, String repositoryName, boolean shouldFail) throws URISyntaxException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).path(\"repos\").pathSegment(repositoryName)\n .build().toUri();\n var status = shouldFail ? HttpStatus.BAD_REQUEST : HttpStatus.OK;\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.DELETE)).andRespond(withStatus(status));\n }\n\n public void mockSetRepositoryPermissionsToReadOnly(String repositorySlug, String projectKey, Set<User> users) throws URISyntaxException {\n for (User user : users) {\n mockSetStudentRepositoryPermission(repositorySlug, projectKey, user.getLogin());\n }\n }\n\n private void mockSetStudentRepositoryPermission(String repositorySlug, String projectKey, String username) throws URISyntaxException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).path(\"repos\").pathSegment(repositorySlug)\n .path(\"permissions/users\").queryParam(\"name\", username).queryParam(\"permission\", \"REPO_READ\").build().toUri();\n\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.PUT)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockRemoveMemberFromRepository(String repositorySlug, String projectKey, User user) throws URISyntaxException {\n mockRemoveStudentRepositoryAccess(repositorySlug, projectKey, user.getLogin());\n }\n\n private void mockRemoveStudentRepositoryAccess(String repositorySlug, String projectKey, String username) throws URISyntaxException {\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects\").pathSegment(projectKey).path(\"repos\").pathSegment(repositorySlug)\n .path(\"permissions/users\").queryParam(\"name\", username).build().toUri();\n\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.DELETE)).andRespond(withStatus(HttpStatus.OK));\n }\n\n public void mockHealth(String state, HttpStatus httpStatus) throws URISyntaxException, JsonProcessingException {\n var response = Map.of(\"state\", state);\n var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/status\").build().toUri();\n mockServerShortTimeout.expect(requestTo(uri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(httpStatus).contentType(MediaType.APPLICATION_JSON).body(mapper.writeValueAsString(response)));\n }\n\n public void mockFetchCommitInfo(String projectKey, String repositorySlug, String hash) throws URISyntaxException, JsonProcessingException {\n String json = \"{ \\\"message\\\" : \\\"Merge branch 'develop' into master\\\", \\\"author\\\": { \\\"name\\\" : \\\"admin\\\", \\\"emailAddress\\\" : \\\"[email protected]\\\" } } \";\n ObjectMapper objectMapper = new ObjectMapper();\n JsonNode response = objectMapper.readTree(json);\n final var uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/1.0/projects\").pathSegment(projectKey, \"repos\", repositorySlug, \"commits\", hash)\n .build().toUri();\n\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.GET))\n .andRespond(withStatus(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON).body(mapper.writeValueAsString(response)));\n }\n\n public void mockGetBitbucketRepository(String projectKey, String repositorySlug) throws URISyntaxException, JsonProcessingException {\n BitbucketRepositoryDTO mockResponse = new BitbucketRepositoryDTO(\"asd\", repositorySlug, projectKey, \"ssh:cloneUrl\");\n String body = mapper.writeValueAsString(mockResponse);\n URI uri = UriComponentsBuilder.fromUri(bitbucketServerUrl.toURI()).path(\"/rest/api/latest/projects/\").path(projectKey).path(\"/repos/\").path(repositorySlug).build().toUri();\n mockServer.expect(requestTo(uri)).andExpect(method(HttpMethod.GET)).andRespond(withSuccess().body(body).contentType(MediaType.APPLICATION_JSON));\n }\n\n public static String repositorySlugOf(ProgrammingExerciseStudentParticipation participation) {\n return (participation.getProgrammingExercise().getProjectKey() + \"-\" + participation.getParticipantIdentifier()).toLowerCase();\n }\n}\n" }, { "alpha_fraction": 0.767336368560791, "alphanum_fraction": 0.7699286937713623, "avg_line_length": 31.82978630065918, "blob_id": "c08275126b8b4c2a36a9f0c1de96a6e9a9bf240a", "content_id": "cecc79adca1bff1c409454f952d7fb1ec6c51a03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1543, "license_type": "permissive", "max_line_length": 97, "num_lines": 47, "path": "/src/test/java/de/tum/in/www1/artemis/service/connectors/AtheneHealthIndicatorTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.actuate.health.Health;\nimport org.springframework.boot.actuate.health.Status;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.connector.athene.AtheneRequestMockProvider;\nimport de.tum.in.www1.artemis.service.connectors.athene.AtheneHealthIndicator;\n\npublic class AtheneHealthIndicatorTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private AtheneRequestMockProvider atheneRequestMockProvider;\n\n @Autowired\n private AtheneHealthIndicator atheneHealthIndicator;\n\n @BeforeEach\n public void initTestCase() {\n atheneRequestMockProvider.enableMockingOfRequests();\n }\n\n @AfterEach\n public void tearDown() {\n atheneRequestMockProvider.reset();\n }\n\n @Test\n void healthUp() {\n atheneRequestMockProvider.mockQueueStatus(true);\n final Health health = atheneHealthIndicator.health();\n assertThat(health.getStatus()).isEqualTo(Status.UP);\n }\n\n @Test\n void healthDown() {\n atheneRequestMockProvider.mockQueueStatus(false);\n final Health health = atheneHealthIndicator.health();\n assertThat(health.getStatus()).isEqualTo(Status.DOWN);\n }\n}\n" }, { "alpha_fraction": 0.7210590839385986, "alphanum_fraction": 0.7222906351089478, "avg_line_length": 44.11111068725586, "blob_id": "475ff681ab419f46c7118e0c4ecf0fd16ac976b0", "content_id": "eb87625da641af779f1a1dc4be2e2cadfb74f6ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1624, "license_type": "permissive", "max_line_length": 154, "num_lines": 36, "path": "/src/main/webapp/app/overview/submission-result-status.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\n\n@Component({\n selector: 'jhi-submission-result-status',\n templateUrl: './submission-result-status.component.html',\n})\nexport class SubmissionResultStatusComponent {\n readonly ExerciseType = ExerciseType;\n\n /**\n * @property exercise Exercise to which the submission's participation belongs\n * @property studentParticipation Participation to which the submission belongs (optional, used for updating-result)\n * @property updatingResultClass Class(es) that will be applied to the updating-result component\n * @property showGradedBadge Flag whether a colored badge (saying e.g. \"Graded\") should be shown\n * @property short Flag whether the short version of the result text should be used\n */\n @Input() exercise: Exercise;\n @Input() studentParticipation?: StudentParticipation;\n @Input() updatingResultClass: string;\n @Input() showGradedBadge = false;\n @Input() short = false;\n @Input() triggerLastGraded = true;\n\n /**\n * If a student participation is supplied explicitly, use that one.\n * Otherwise, use the first student participation on the exercise.\n */\n get participation() {\n if (this.studentParticipation) {\n return this.studentParticipation;\n }\n return this.exercise.studentParticipations && this.exercise.studentParticipations.length > 0 ? this.exercise.studentParticipations[0] : undefined;\n }\n}\n" }, { "alpha_fraction": 0.7380560040473938, "alphanum_fraction": 0.7414962649345398, "avg_line_length": 37.289424896240234, "blob_id": "93dc49bb9fbf6ca0b4d1e4b9ed57c37ae2ba8d22", "content_id": "c8c47ef138461c6f518e80be9d0bc99856364719", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 20638, "license_type": "permissive", "max_line_length": 120, "num_lines": 539, "path": "/src/test/java/de/tum/in/www1/artemis/CourseGitlabJenkinsIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.mockito.Mockito.verifyNoInteractions;\n\nimport java.util.HashSet;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.util.CourseTestService;\nimport de.tum.in.www1.artemis.util.ModelFactory;\n\npublic class CourseGitlabJenkinsIntegrationTest extends AbstractSpringIntegrationJenkinsGitlabTest {\n\n @Autowired\n CourseTestService courseTestService;\n\n @BeforeEach\n public void setup() {\n courseTestService.setup(this, this.groupNotificationService);\n gitlabRequestMockProvider.enableMockingOfRequests();\n jenkinsRequestMockProvider.enableMockingOfRequests(jenkinsServer);\n }\n\n @AfterEach\n public void teardown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithPermission() throws Exception {\n courseTestService.testCreateCourseWithPermission();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithSameShortName() throws Exception {\n courseTestService.testCreateCourseWithSameShortName();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithNegativeMaxComplainNumber() throws Exception {\n courseTestService.testCreateCourseWithNegativeMaxComplainNumber();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithNegativeMaxComplainTimeDays() throws Exception {\n courseTestService.testCreateCourseWithNegativeMaxComplainTimeDays();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithNegativeMaxTeamComplainNumber() throws Exception {\n courseTestService.testCreateCourseWithNegativeMaxTeamComplainNumber();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithModifiedMaxComplainTimeDaysAndMaxComplains() throws Exception {\n courseTestService.testCreateCourseWithModifiedMaxComplainTimeDaysAndMaxComplains();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithCustomNonExistingGroupNames() throws Exception {\n courseTestService.testCreateCourseWithCustomNonExistingGroupNames();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithOptions() throws Exception {\n courseTestService.testCreateCourseWithOptions();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDeleteCourseWithPermission() throws Exception {\n courseTestService.testDeleteCourseWithPermission();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testDeleteNotExistingCourse() throws Exception {\n courseTestService.testDeleteNotExistingCourse();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCreateCourseWithoutPermission() throws Exception {\n courseTestService.testCreateCourseWithoutPermission();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testCreateCourseWithWrongShortName() throws Exception {\n courseTestService.testCreateCourseWithWrongShortName();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseWithWrongShortName() throws Exception {\n courseTestService.testUpdateCourseWithWrongShortName();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseWithoutId() throws Exception {\n courseTestService.testUpdateCourseWithoutId();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseIsEmpty() throws Exception {\n courseTestService.testUpdateCourseIsEmpty();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testEditCourseWithPermission() throws Exception {\n courseTestService.testEditCourseWithPermission();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseGroups() throws Exception {\n courseTestService.testUpdateCourseGroups();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseGroups_InExternalCiUserManagement_failToRemoveUser() throws Exception {\n courseTestService.testUpdateCourseGroups_InExternalCiUserManagement_failToRemoveUser();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourseGroups_InExternalCiUserManagement_failToAddUser() throws Exception {\n courseTestService.testUpdateCourseGroups_InExternalCiUserManagement_failToAddUser();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetCourseWithoutPermission() throws Exception {\n courseTestService.testGetCourseWithoutPermission();\n }\n\n @Test\n @WithMockUser(username = \"tutor6\", roles = \"TA\")\n public void testGetCourse_tutorNotInCourse() throws Exception {\n courseTestService.testGetCourse_tutorNotInCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor2\", roles = \"INSTRUCTOR\")\n public void testGetCourseWithExercisesAndRelevantParticipationsWithoutPermissions() throws Exception {\n courseTestService.testGetCourseWithExercisesAndRelevantParticipationsWithoutPermissions();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCoursesWithPermission() throws Exception {\n courseTestService.testGetCoursesWithPermission();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCoursesWithQuizExercises() throws Exception {\n courseTestService.testGetCoursesWithQuizExercises();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetCourseForDashboard() throws Exception {\n courseTestService.testGetCourseForDashboard();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetAllCoursesForDashboard() throws Exception {\n courseTestService.testGetAllCoursesForDashboard();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetCoursesWithoutActiveExercises() throws Exception {\n courseTestService.testGetCoursesWithoutActiveExercises();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetCoursesAccurateTimezoneEvaluation() throws Exception {\n courseTestService.testGetCoursesAccurateTimezoneEvaluation();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetAllCoursesWithUserStats() throws Exception {\n courseTestService.testGetAllCoursesWithUserStats();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCourseWithOrganizations() throws Exception {\n courseTestService.testGetCourseWithOrganizations();\n }\n\n @Test\n @WithMockUser(username = \"student1\")\n public void testGetCoursesToRegisterAndAccurateTimeZoneEvaluation() throws Exception {\n courseTestService.testGetCoursesToRegisterAndAccurateTimeZoneEvaluation();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetCourseForAssessmentDashboardWithStats() throws Exception {\n courseTestService.testGetCourseForAssessmentDashboardWithStats();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCourseForInstructorDashboardWithStats() throws Exception {\n courseTestService.testGetCourseForInstructorDashboardWithStats();\n }\n\n @Test\n @WithMockUser(username = \"instructor2\", roles = \"INSTRUCTOR\")\n public void testGetCourseForInstructorDashboardWithStats_instructorNotInCourse() throws Exception {\n courseTestService.testGetCourseForInstructorDashboardWithStats_instructorNotInCourse();\n }\n\n @Test\n @WithMockUser(username = \"tutor6\", roles = \"TA\")\n public void testGetCourseForAssessmentDashboardWithStats_tutorNotInCourse() throws Exception {\n courseTestService.testGetCourseForAssessmentDashboardWithStats_tutorNotInCourse();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withoutAssessments() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withoutAssessments();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessments() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessments();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaints() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessmentsAndComplaints();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessmentsAndFeedbackRequests() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessmentsAndFeedbackRequests();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessmentsAndFeedBackRequestsAndResponses() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessmentsAndFeedBackRequestsAndResponses();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses_Large() throws Exception {\n courseTestService.testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses_Large();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCourse() throws Exception {\n courseTestService.testGetCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCategoriesInCourse() throws Exception {\n courseTestService.testGetCategoriesInCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor2\", roles = \"INSTRUCTOR\")\n public void testGetCategoriesInCourse_instructorNotInCourse() throws Exception {\n courseTestService.testGetCategoriesInCourse_instructorNotInCourse();\n }\n\n @Test\n @WithMockUser(username = \"ab12cde\")\n public void testRegisterForCourse() throws Exception {\n courseTestService.testRegisterForCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testAddTutorAndInstructorToCourse_failsToAddUserToGroup() throws Exception {\n courseTestService.testAddTutorAndInstructorToCourse_failsToAddUserToGroup(HttpStatus.INTERNAL_SERVER_ERROR);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testRemoveTutorFromCourse_failsToRemoveUserFromGroup() throws Exception {\n courseTestService.testRemoveTutorFromCourse_failsToRemoveUserFromGroup();\n }\n\n @Test\n @WithMockUser(username = \"ab12cde\")\n public void testRegisterForCourse_notMeetsDate() throws Exception {\n courseTestService.testRegisterForCourse_notMeetsDate();\n }\n\n @Test\n @WithMockUser(username = \"admin\", roles = \"ADMIN\")\n public void testUpdateCourse_withExternalUserManagement_vcsUserManagementHasNotBeenCalled() throws Exception {\n var course = ModelFactory.generateCourse(1L, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseTestService.getCourseRepo().save(course);\n\n request.put(\"/api/courses\", course, HttpStatus.OK);\n\n verifyNoInteractions(versionControlService);\n }\n\n @Test\n @WithMockUser(username = \"instructor2\", roles = \"INSTRUCTOR\")\n public void testUpdateCourse_instructorNotInCourse() throws Exception {\n courseTestService.testUpdateCourse_instructorNotInCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse() throws Exception {\n courseTestService.testGetAllStudentsOrTutorsOrInstructorsInCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n courseTestService.testGetAllStudentsOrTutorsOrInstructorsInCourse_AsInstructorOfOtherCourse_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse_AsTutor_forbidden() throws Exception {\n courseTestService.testGetAllStudentsOrTutorsOrInstructorsInCourse_AsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testAddStudentOrTutorOrInstructorToCourse() throws Exception {\n courseTestService.testAddStudentOrTutorOrInstructorToCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testAddStudentOrTutorOrInstructorToCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n courseTestService.testAddStudentOrTutorOrInstructorToCourse_AsInstructorOfOtherCourse_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testAddStudentOrTutorOrInstructorToCourse_AsTutor_forbidden() throws Exception {\n courseTestService.testAddStudentOrTutorOrInstructorToCourse_AsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testAddStudentOrTutorOrInstructorToCourse_WithNonExistingUser() throws Exception {\n courseTestService.testAddStudentOrTutorOrInstructorToCourse_WithNonExistingUser();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testRemoveStudentOrTutorOrInstructorFromCourse() throws Exception {\n courseTestService.testRemoveStudentOrTutorOrInstructorFromCourse();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testRemoveStudentOrTutorOrInstructorFromCourse_WithNonExistingUser() throws Exception {\n courseTestService.testRemoveStudentOrTutorOrInstructorFromCourse_WithNonExistingUser();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testRemoveStudentOrTutorOrInstructorFromCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n courseTestService.testRemoveStudentOrTutorOrInstructorFromCourse_AsInstructorOfOtherCourse_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testRemoveStudentOrTutorOrInstructorFromCourse_AsTutor_forbidden() throws Exception {\n courseTestService.testRemoveStudentOrTutorOrInstructorFromCourse_AsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetLockedSubmissionsForCourseAsTutor() throws Exception {\n courseTestService.testGetLockedSubmissionsForCourseAsTutor();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testGetLockedSubmissionsForCourseAsStudent() throws Exception {\n courseTestService.testGetLockedSubmissionsForCourseAsStudent();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testArchiveCourseAsStudent_forbidden() throws Exception {\n courseTestService.testArchiveCourseAsStudent_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testArchiveCourseAsTutor_forbidden() throws Exception {\n courseTestService.testArchiveCourseAsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testArchiveCourseWithTestModelingAndFileUploadExercises() throws Exception {\n courseTestService.testArchiveCourseWithTestModelingAndFileUploadExercises();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testDownloadCourseArchiveAsStudent_forbidden() throws Exception {\n courseTestService.testDownloadCourseArchiveAsStudent_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testDownloadCourseArchiveAsTutor_forbidden() throws Exception {\n courseTestService.testDownloadCourseArchiveAsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testDownloadCourseArchiveAsInstructor_not_found() throws Exception {\n courseTestService.testDownloadCourseArchiveAsInstructor_not_found();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testDownloadCourseArchiveAsInstructor() throws Exception {\n courseTestService.testDownloadCourseArchiveAsInstructor();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void testCleanupCourseAsStudent_forbidden() throws Exception {\n courseTestService.testCleanupCourseAsStudent_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testCleanupCourseAsTutor_forbidden() throws Exception {\n courseTestService.testCleanupCourseAsTutor_forbidden();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCleanupCourseAsInstructor_no_Archive() throws Exception {\n courseTestService.testCleanupCourseAsInstructor_no_Archive();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testCleanupCourseAsInstructor() throws Exception {\n courseTestService.testCleanupCourseAsInstructor();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetCourseTitle() throws Exception {\n // Only user and role matter, so we can re-use the logic\n courseTestService.testGetCourseTitle();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetCourseTitleAsTeachingAssistant() throws Exception {\n // Only user and role matter, so we can re-use the logic\n courseTestService.testGetCourseTitle();\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetCourseTitleAsUser() throws Exception {\n // Only user and role matter, so we can re-use the logic\n courseTestService.testGetCourseTitle();\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetCourseTitleForNonExistingCourse() throws Exception {\n courseTestService.testGetCourseTitleForNonExistingCourse();\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetAllCoursesForManagementOverview() throws Exception {\n courseTestService.testGetAllCoursesForManagementOverview();\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetExercisesForCourseOverview() throws Exception {\n courseTestService.testGetExercisesForCourseOverview();\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetExerciseStatsForCourseOverview() throws Exception {\n courseTestService.testGetExerciseStatsForCourseOverview();\n }\n\n @Test\n @WithMockUser(value = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetExerciseStatsForCourseOverviewWithPastExercises() throws Exception {\n courseTestService.testGetExerciseStatsForCourseOverviewWithPastExercises();\n }\n}\n" }, { "alpha_fraction": 0.6957821249961853, "alphanum_fraction": 0.6964463591575623, "avg_line_length": 28.233009338378906, "blob_id": "d89f5310fc491f1fbd0379a0608f4e8e6561185c", "content_id": "a9fbb39fa51aee71f7e8d4a2fb557f6795379432", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3011, "license_type": "permissive", "max_line_length": 223, "num_lines": 103, "path": "/src/main/java/de/tum/in/www1/artemis/domain/LearningGoal.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\n\nimport de.tum.in.www1.artemis.domain.lecture.LectureUnit;\n\n@Entity\n@Table(name = \"learning_goal\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\npublic class LearningGoal extends DomainObject {\n\n @Column(name = \"title\", nullable = false)\n private String title;\n\n @Column(name = \"description\")\n @Lob\n private String description;\n\n @ManyToOne\n @JoinColumn(name = \"course_id\")\n @JsonIgnoreProperties(\"learningGoals\")\n private Course course;\n\n @ManyToMany\n @JoinTable(name = \"learning_goal_exercise\", joinColumns = @JoinColumn(name = \"learning_goal_id\", referencedColumnName = \"id\"), inverseJoinColumns = @JoinColumn(name = \"exercise_id\", referencedColumnName = \"id\"))\n @JsonIgnoreProperties(\"learningGoals\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Set<Exercise> exercises = new HashSet<>();\n\n @ManyToMany\n @JoinTable(name = \"learning_goal_lecture_unit\", joinColumns = @JoinColumn(name = \"learning_goal_id\", referencedColumnName = \"id\"), inverseJoinColumns = @JoinColumn(name = \"lecture_unit_id\", referencedColumnName = \"id\"))\n @JsonIgnoreProperties(\"learningGoals\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Set<LectureUnit> lectureUnits = new HashSet<>();\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public Course getCourse() {\n return course;\n }\n\n public void setCourse(Course course) {\n this.course = course;\n }\n\n public Set<Exercise> getExercises() {\n return exercises;\n }\n\n public void setExercises(Set<Exercise> exercises) {\n this.exercises = exercises;\n }\n\n public void addExercise(Exercise exercise) {\n this.exercises.add(exercise);\n exercise.getLearningGoals().add(this);\n }\n\n public void removeExercise(Exercise exercise) {\n this.exercises.remove(exercise);\n exercise.getLearningGoals().remove(this);\n }\n\n public Set<LectureUnit> getLectureUnits() {\n return lectureUnits;\n }\n\n public void setLectureUnits(Set<LectureUnit> lectureUnits) {\n this.lectureUnits = lectureUnits;\n }\n\n public void addLectureUnit(LectureUnit lectureUnit) {\n this.lectureUnits.add(lectureUnit);\n lectureUnit.getLearningGoals().add(this);\n }\n\n public void removeLectureUnit(LectureUnit lectureUnit) {\n this.lectureUnits.remove(lectureUnit);\n lectureUnit.getLearningGoals().remove(this);\n }\n}\n" }, { "alpha_fraction": 0.8197135925292969, "alphanum_fraction": 0.822240948677063, "avg_line_length": 41.39285659790039, "blob_id": "7ca4ae59a28f5903e820d8209ad78dc2908ac011", "content_id": "92fcb374afccf07b9f62cce451eaaa6ae8d3bd4b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1187, "license_type": "permissive", "max_line_length": 167, "num_lines": 28, "path": "/src/test/java/de/tum/in/www1/artemis/AbstractSpringDevelopmentTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static io.github.jhipster.config.JHipsterConstants.SPRING_PROFILE_TEST;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;\nimport org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.ActiveProfiles;\nimport org.springframework.test.context.TestPropertySource;\n\nimport de.tum.in.www1.artemis.util.DatabaseUtilService;\nimport de.tum.in.www1.artemis.util.RequestUtilService;\n\n@SpringBootTest\n@AutoConfigureMockMvc\n@AutoConfigureTestDatabase\n@ActiveProfiles({ SPRING_PROFILE_TEST, \"artemis\", \"dev\", \"scheduling\" })\n@TestPropertySource(properties = { \"artemis.user-management.use-external=false\", \"artemis.version-control.ssh-private-key-folder-path=./src/test/resources/sshtestkey\",\n \"artemis.version-control.ssh-private-key-password=test1234\" })\npublic abstract class AbstractSpringDevelopmentTest {\n\n @Autowired\n protected DatabaseUtilService database;\n\n @Autowired\n protected RequestUtilService request;\n}\n" }, { "alpha_fraction": 0.711456298828125, "alphanum_fraction": 0.7146278023719788, "avg_line_length": 49.655738830566406, "blob_id": "2d5e6731e7c04b37274a24146d1773c235d5c69f", "content_id": "2ddb4f5dd3f11ead5aa44c60e7f7e3049231c2ab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 15450, "license_type": "permissive", "max_line_length": 175, "num_lines": 305, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/StudentQuestionResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.forbidden;\n\nimport java.net.URI;\nimport java.net.URISyntaxException;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.AuthorizationCheckService;\nimport de.tum.in.www1.artemis.service.GroupNotificationService;\nimport de.tum.in.www1.artemis.web.rest.errors.BadRequestAlertException;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\n\n/**\n * REST controller for managing StudentQuestion.\n */\n@RestController\n@RequestMapping(\"/api\")\npublic class StudentQuestionResource {\n\n private final Logger log = LoggerFactory.getLogger(StudentQuestionResource.class);\n\n private static final String ENTITY_NAME = \"studentQuestion\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final StudentQuestionRepository studentQuestionRepository;\n\n private final ExerciseRepository exerciseRepository;\n\n private final LectureRepository lectureRepository;\n\n private final CourseRepository courseRepository;\n\n private final AuthorizationCheckService authorizationCheckService;\n\n private final UserRepository userRepository;\n\n private final GroupNotificationService groupNotificationService;\n\n public StudentQuestionResource(StudentQuestionRepository studentQuestionRepository, GroupNotificationService groupNotificationService, LectureRepository lectureRepository,\n AuthorizationCheckService authorizationCheckService, UserRepository userRepository, ExerciseRepository exerciseRepository, CourseRepository courseRepository) {\n this.studentQuestionRepository = studentQuestionRepository;\n this.groupNotificationService = groupNotificationService;\n this.authorizationCheckService = authorizationCheckService;\n this.userRepository = userRepository;\n this.exerciseRepository = exerciseRepository;\n this.lectureRepository = lectureRepository;\n this.courseRepository = courseRepository;\n }\n\n /**\n * POST /courses/{courseId}/student-questions : Create a new studentQuestion.\n *\n * @param courseId course the question belongs to\n * @param studentQuestion the studentQuestion to create\n * @return the ResponseEntity with status 201 (Created) and with body the new studentQuestion, or with status 400 (Bad Request) if the studentQuestion has already an ID\n * @throws URISyntaxException if the Location URI syntax is incorrect\n */\n @PostMapping(\"courses/{courseId}/student-questions\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentQuestion> createStudentQuestion(@PathVariable Long courseId, @RequestBody StudentQuestion studentQuestion) throws URISyntaxException {\n log.debug(\"REST request to save StudentQuestion : {}\", studentQuestion);\n User user = this.userRepository.getUserWithGroupsAndAuthorities();\n if (studentQuestion.getId() != null) {\n throw new BadRequestAlertException(\"A new studentQuestion cannot already have an ID\", ENTITY_NAME, \"idexists\");\n }\n final var course = courseRepository.findByIdElseThrow(courseId);\n if (!this.authorizationCheckService.isAtLeastStudentInCourse(course, user)) {\n return forbidden();\n }\n if (!studentQuestion.getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n StudentQuestion question = studentQuestionRepository.save(studentQuestion);\n if (question.getExercise() != null) {\n groupNotificationService.notifyTutorAndInstructorGroupAboutNewQuestionForExercise(question);\n }\n if (question.getLecture() != null) {\n groupNotificationService.notifyTutorAndInstructorGroupAboutNewQuestionForLecture(question);\n }\n return ResponseEntity.created(new URI(\"/api/courses/\" + courseId + \"/student-questions/\" + question.getId()))\n .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, question.getId().toString())).body(question);\n }\n\n /**\n * PUT /courses/{courseId}/student-questions : Updates an existing studentQuestion.\n *\n * @param courseId course the question belongs to\n * @param studentQuestion the studentQuestion to update\n * @return the ResponseEntity with status 200 (OK) and with body the updated studentQuestion, or with status 400 (Bad Request) if the studentQuestion is not valid, or with\n * status 500 (Internal Server Error) if the studentQuestion couldn't be updated\n */\n @PutMapping(\"courses/{courseId}/student-questions\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentQuestion> updateStudentQuestion(@PathVariable Long courseId, @RequestBody StudentQuestion studentQuestion) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n log.debug(\"REST request to update StudentQuestion : {}\", studentQuestion);\n if (studentQuestion.getId() == null) {\n throw new BadRequestAlertException(\"Invalid id\", ENTITY_NAME, \"idnull\");\n }\n courseRepository.findByIdElseThrow(courseId);\n var existingStudentQuestion = studentQuestionRepository.findByIdElseThrow(studentQuestion.getId());\n if (!existingStudentQuestion.getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n if (mayUpdateOrDeleteStudentQuestion(existingStudentQuestion, user)) {\n existingStudentQuestion.setQuestionText(studentQuestion.getQuestionText());\n existingStudentQuestion.setVisibleForStudents(studentQuestion.isVisibleForStudents());\n StudentQuestion result = studentQuestionRepository.save(existingStudentQuestion);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, studentQuestion.getId().toString())).body(result);\n }\n else {\n return forbidden();\n }\n }\n\n /**\n * PUT /courses/{courseId}/student-questions/{questionId}/votes : Updates votes for a studentQuestion.\n *\n * @param courseId course the question belongs to\n * @param questionId the ID of the question to update\n * @param voteChange value by which votes are increased / decreased\n * @return the ResponseEntity with status 200 (OK) and with body the updated studentQuestion, or with status 400 (Bad Request) if the studentQuestion is not valid, or with\n * status 500 (Internal Server Error) if the studentQuestion couldn't be updated\n */\n @PutMapping(\"courses/{courseId}/student-questions/{questionId}/votes\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<StudentQuestion> updateStudentQuestionVotes(@PathVariable Long courseId, @PathVariable Long questionId, @RequestBody Integer voteChange) {\n if (voteChange < -2 || voteChange > 2) {\n return forbidden();\n }\n final User user = userRepository.getUserWithGroupsAndAuthorities();\n Optional<StudentQuestion> optionalStudentQuestion = studentQuestionRepository.findById(questionId);\n if (optionalStudentQuestion.isEmpty()) {\n return ResponseEntity.notFound().build();\n }\n courseRepository.findByIdElseThrow(courseId);\n if (!optionalStudentQuestion.get().getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n if (mayUpdateStudentQuestionVotes(optionalStudentQuestion.get(), user)) {\n StudentQuestion updatedStudentQuestion = optionalStudentQuestion.get();\n Integer newVotes = updatedStudentQuestion.getVotes() + voteChange;\n updatedStudentQuestion.setVotes(newVotes);\n StudentQuestion result = studentQuestionRepository.save(updatedStudentQuestion);\n return ResponseEntity.ok().body(result);\n }\n else {\n return forbidden();\n }\n }\n\n /**\n * GET /courses/{courseId}/exercises/{exerciseId}/student-questions : get all student questions for exercise.\n *\n * @param courseId course the question belongs to\n * @param exerciseId the exercise that the student questions belong to\n * @return the ResponseEntity with status 200 (OK) and with body all student questions for exercise\n */\n @GetMapping(\"courses/{courseId}/exercises/{exerciseId}/student-questions\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<List<StudentQuestion>> getAllQuestionsForExercise(@PathVariable Long courseId, @PathVariable Long exerciseId) {\n final User user = userRepository.getUserWithGroupsAndAuthorities();\n Optional<Exercise> exercise = exerciseRepository.findById(exerciseId);\n if (exercise.isEmpty()) {\n throw new EntityNotFoundException(\"Exercise with exerciseId \" + exerciseId + \" does not exist!\");\n }\n courseRepository.findByIdElseThrow(courseId);\n if (!authorizationCheckService.isAtLeastStudentForExercise(exercise.get(), user)) {\n return forbidden();\n }\n if (!exercise.get().getCourseViaExerciseGroupOrCourseMember().getId().equals(courseId)) {\n return forbidden();\n }\n List<StudentQuestion> studentQuestions = studentQuestionRepository.findStudentQuestionsForExercise(exerciseId);\n hideSensitiveInformation(studentQuestions);\n\n return new ResponseEntity<>(studentQuestions, null, HttpStatus.OK);\n }\n\n /**\n * GET /courses/{courseId}/lectures/{lectureId}/student-questions : get all student questions for lecture.\n *\n * @param courseId course the question belongs to\n * @param lectureId the lecture that the student questions belong to\n * @return the ResponseEntity with status 200 (OK) and with body all student questions for lecture\n */\n @GetMapping(\"courses/{courseId}/lectures/{lectureId}/student-questions\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<List<StudentQuestion>> getAllQuestionsForLecture(@PathVariable Long courseId, @PathVariable Long lectureId) {\n Optional<Lecture> lecture = lectureRepository.findById(lectureId);\n if (lecture.isEmpty()) {\n throw new EntityNotFoundException(\"Lecture with lectureId \" + lectureId + \" does not exist!\");\n }\n courseRepository.findByIdElseThrow(courseId);\n final User user = userRepository.getUserWithGroupsAndAuthorities();\n if (!authorizationCheckService.isAtLeastStudentInCourse(lecture.get().getCourse(), user)) {\n return forbidden();\n }\n if (!lecture.get().getCourse().getId().equals(courseId)) {\n return forbidden();\n }\n List<StudentQuestion> studentQuestions = studentQuestionRepository.findStudentQuestionsForLecture(lectureId);\n hideSensitiveInformation(studentQuestions);\n\n return new ResponseEntity<>(studentQuestions, null, HttpStatus.OK);\n }\n\n /**\n *\n * GET /courses/{courseId}/student-questions : get all student questions for course\n * @param courseId the course that the student questions belong to\n * @return the ResponseEntity with status 200 (OK) and with body all student questions for course\n */\n @GetMapping(\"courses/{courseId}/student-questions\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<List<StudentQuestion>> getAllQuestionsForCourse(@PathVariable Long courseId) {\n final User user = userRepository.getUserWithGroupsAndAuthorities();\n var course = courseRepository.findByIdElseThrow(courseId);\n if (!authorizationCheckService.isAtLeastTeachingAssistantInCourse(course, user)) {\n return forbidden();\n }\n List<StudentQuestion> studentQuestions = studentQuestionRepository.findStudentQuestionsForCourse(courseId);\n\n return new ResponseEntity<>(studentQuestions, null, HttpStatus.OK);\n }\n\n private void hideSensitiveInformation(List<StudentQuestion> studentQuestions) {\n for (StudentQuestion question : studentQuestions) {\n question.setExercise(null);\n question.setLecture(null);\n question.setAuthor(question.getAuthor().copyBasicUser());\n for (StudentQuestionAnswer answer : question.getAnswers()) {\n answer.setAuthor(answer.getAuthor().copyBasicUser());\n }\n }\n }\n\n /**\n * DELETE /courses/{courseId}/student-questions/:id : delete the \"id\" studentQuestion.\n *\n * @param courseId course the question belongs to\n * @param studentQuestionId the id of the studentQuestion to delete\n * @return the ResponseEntity with status 200 (OK)\n */\n @DeleteMapping(\"courses/{courseId}/student-questions/{studentQuestionId}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<Void> deleteStudentQuestion(@PathVariable Long courseId, @PathVariable Long studentQuestionId) {\n User user = userRepository.getUserWithGroupsAndAuthorities();\n courseRepository.findByIdElseThrow(courseId);\n var studentQuestion = studentQuestionRepository.findByIdElseThrow(studentQuestionId);\n String entity = \"\";\n if (studentQuestion.getLecture() != null) {\n entity = \"lecture with id: \" + studentQuestion.getLecture().getId();\n }\n else if (studentQuestion.getExercise() != null) {\n entity = \"exercise with id: \" + studentQuestion.getExercise().getId();\n }\n if (studentQuestion.getCourse() == null) {\n return ResponseEntity.badRequest().build();\n }\n if (mayUpdateOrDeleteStudentQuestion(studentQuestion, user)) {\n log.info(\"StudentQuestion deleted by {}. Question: {} for {}\", user.getLogin(), studentQuestion.getQuestionText(), entity);\n studentQuestionRepository.deleteById(studentQuestionId);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, studentQuestionId.toString())).build();\n }\n else {\n return forbidden();\n }\n }\n\n private boolean mayUpdateOrDeleteStudentQuestion(StudentQuestion studentQuestion, User user) {\n Boolean hasCourseTAAccess = authorizationCheckService.isAtLeastTeachingAssistantInCourse(studentQuestion.getCourse(), user);\n Boolean isUserAuthor = user.getId().equals(studentQuestion.getAuthor().getId());\n return hasCourseTAAccess || isUserAuthor;\n }\n\n private boolean mayUpdateStudentQuestionVotes(StudentQuestion studentQuestion, User user) {\n Course course = studentQuestion.getCourse();\n Exercise exercise = studentQuestion.getExercise();\n if (course != null) {\n return authorizationCheckService.isAtLeastStudentInCourse(course, user);\n }\n else if (exercise != null) {\n return authorizationCheckService.isAtLeastStudentForExercise(exercise, user);\n }\n else {\n return false;\n }\n }\n}\n" }, { "alpha_fraction": 0.6727374196052551, "alphanum_fraction": 0.6732949018478394, "avg_line_length": 41.70634841918945, "blob_id": "0c0c09b012cae2808045eb922168b61c4508cfcf", "content_id": "9da2adfacb501d2548ae6d23d79c3db6da74d8b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5381, "license_type": "permissive", "max_line_length": 159, "num_lines": 126, "path": "/src/main/java/de/tum/in/www1/artemis/service/ResourceLoaderService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.apache.commons.lang.StringUtils;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.core.io.Resource;\nimport org.springframework.core.io.ResourceLoader;\nimport org.springframework.core.io.support.ResourcePatternUtils;\nimport org.springframework.stereotype.Service;\n\n/**\n * Service class to load resources from the file system (if possible) and the classpath (as fallback).\n */\n@Service\npublic class ResourceLoaderService {\n\n private final ResourceLoader resourceLoader;\n\n @Value(\"${artemis.template-path:#{null}}\")\n private Optional<String> templateFileSystemPath;\n\n // Files that start with a prefix that is included in this list can be overwritten from the file system\n private final List<String> allowedOverridePrefixes = new ArrayList<>();\n\n public ResourceLoaderService(ResourceLoader resourceLoader) {\n this.resourceLoader = resourceLoader;\n\n allowedOverridePrefixes.add(\"templates/jenkins/\");\n }\n\n /**\n * Load the resource from the specified path. The path MUST NOT start with a '/', it is appended automatically if needed.\n * File will be loaded from the relative path, if it exists, from the classpath otherwise.\n * @param path the path to load the file from. Must not start with a '/'.\n * @return the loaded resource, which might not exist ({@link Resource#exists()}.\n */\n public Resource getResource(String path) {\n Resource resource = null;\n // Try to load from filesystem if override is allowed for path\n if (isOverrideAllowed(path)) {\n resource = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResource(\"file:\" + getTemplateFileSystemPath() + path);\n }\n // If loading from filesystem is not allowed or was not successful, load from classpath\n if (resource == null || !resource.exists()) {\n resource = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResource(\"classpath:/\" + path);\n }\n\n return resource;\n }\n\n /**\n * Load the resource from the specified path.\n * File will be loaded from the relative path, if it exists, from the classpath otherwise.\n * @param pathSegments the segments of the path (e.g. [\"templates\", \"java\", \"pom.xml\"]). Will automatically be joined with '/'.\n * @return the loaded resource, which might not exist ({@link Resource#exists()}.\n */\n public Resource getResource(String... pathSegments) {\n return getResource(StringUtils.join(pathSegments, \"/\"));\n }\n\n /**\n * Load the resources from the specified path. The path MUST NOT start with a '/', it is appended automatically if needed.\n * Files will be loaded from the relative path, it is non-empty (at least one resource), from the classpath otherwise.\n * @param path the path to load the file from. Must not start with a '/'.\n * @return the loaded resources, which might be an empty array\n */\n public Resource[] getResources(String path) {\n Resource[] resources = null;\n // Try to load from filesystem if override is allowed for path\n if (isOverrideAllowed(path)) {\n try {\n resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(\"file:\" + getTemplateFileSystemPath() + path);\n }\n catch (IOException ignored) {\n }\n }\n\n // If loading from filesystem is not allowed or was not successful, load from classpath\n if (resources == null || resources.length == 0) {\n try {\n resources = ResourcePatternUtils.getResourcePatternResolver(resourceLoader).getResources(\"classpath:/\" + path);\n }\n catch (IOException ignored) {\n }\n }\n\n return resources != null ? resources : new Resource[0];\n }\n\n /**\n * Load the resources from the specified path.\n * Files will be loaded from the relative path, it is non-empty (at least one resource), from the classpath otherwise.\n * @param pathSegments the segments of the path (e.g. [\"templates\", \"java\"]). Will automatically be joined with '/'.\n * @return the loaded resources, which might be an empty array\n */\n public Resource[] getResources(String... pathSegments) {\n return getResources(StringUtils.join(pathSegments, \"/\"));\n }\n\n /**\n * Return the file system path were templates are stored.\n * If no template path is defined, the current directory where Artemis was started from is used (e.g. the `templates` folder next to the Artemis.war file).\n * If a template path is defined, it is used.\n * @return the template system path if defined (with a trailing '/') or \"\" if is not set\n */\n private String getTemplateFileSystemPath() {\n if (templateFileSystemPath.isEmpty()) {\n return \"\";\n }\n\n if (templateFileSystemPath.get().endsWith(\"/\")) {\n return templateFileSystemPath.get();\n }\n else {\n return templateFileSystemPath.get() + \"/\";\n }\n }\n\n private boolean isOverrideAllowed(String path) {\n return allowedOverridePrefixes.stream().anyMatch(path::startsWith);\n }\n}\n" }, { "alpha_fraction": 0.8182807564735413, "alphanum_fraction": 0.8182807564735413, "avg_line_length": 67.92500305175781, "blob_id": "7cc617ad6514e55bf9375845d9f86059225dfbc3", "content_id": "9ec41e3d4645b4bb2f7cd9ff7e2a936334c9dbc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2757, "license_type": "permissive", "max_line_length": 176, "num_lines": 40, "path": "/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ProgrammingExerciseUpdateComponent } from 'app/exercises/programming/manage/update/programming-exercise-update.component';\nimport { ProgrammingExerciseLifecycleComponent } from 'app/exercises/programming/manage/update/programming-exercise-lifecycle.component';\nimport { ProgrammingExerciseTestScheduleDatePickerComponent } from 'app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { OwlDateTimeModule } from 'ng-pick-datetime';\nimport { ProgrammingExercisePlansAndRepositoriesPreviewComponent } from 'app/exercises/programming/manage/update/programming-exercise-plans-and-repositories-preview.component';\nimport { ArtemisTeamConfigFormGroupModule } from 'app/exercises/shared/team-config-form-group/team-config-form-group.module';\nimport { ArtemisDifficultyPickerModule } from 'app/exercises/shared/difficulty-picker/difficulty-picker.module';\nimport { ArtemisPresentationScoreModule } from 'app/exercises/shared/presentation-score/presentation-score.module';\nimport { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-instructions-editor.module';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\nimport { ArtemisCategorySelectorModule } from 'app/shared/category-selector/category-selector.module';\nimport { StructuredGradingCriterionModule } from 'app/exercises/shared/structured-grading-criterion/structured-grading-criterion.module';\nimport { ArtemisIncludedInOverallScorePickerModule } from 'app/exercises/shared/included-in-overall-score-picker/included-in-overall-score-picker.module';\n\n@NgModule({\n imports: [\n ArtemisSharedModule,\n ArtemisSharedComponentModule,\n OwlDateTimeModule,\n ArtemisTeamConfigFormGroupModule,\n ArtemisIncludedInOverallScorePickerModule,\n ArtemisDifficultyPickerModule,\n ArtemisPresentationScoreModule,\n ArtemisProgrammingExerciseInstructionsEditorModule,\n ArtemisMarkdownEditorModule,\n ArtemisCategorySelectorModule,\n StructuredGradingCriterionModule,\n ],\n declarations: [\n ProgrammingExerciseLifecycleComponent,\n ProgrammingExerciseTestScheduleDatePickerComponent,\n ProgrammingExercisePlansAndRepositoriesPreviewComponent,\n ProgrammingExerciseUpdateComponent,\n ],\n exports: [ProgrammingExerciseUpdateComponent, ProgrammingExerciseLifecycleComponent],\n})\nexport class ArtemisProgrammingExerciseUpdateModule {}\n" }, { "alpha_fraction": 0.6872340440750122, "alphanum_fraction": 0.6882978677749634, "avg_line_length": 37.367347717285156, "blob_id": "7d87107e2d94d866e378382ce26c2c2fc00c5d6c", "content_id": "6f47c68953757383ad26784afec2137cf78432f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3760, "license_type": "permissive", "max_line_length": 177, "num_lines": 98, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/ParticipantScoreDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.scores.ParticipantScore;\nimport de.tum.in.www1.artemis.domain.scores.StudentScore;\nimport de.tum.in.www1.artemis.domain.scores.TeamScore;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ParticipantScoreDTO {\n\n public Long id;\n\n public Long userId;\n\n public String userName;\n\n public Long teamId;\n\n public String teamName;\n\n public Long exerciseId;\n\n public String exerciseTitle;\n\n public Long lastResultId;\n\n public Double lastResultScore;\n\n public Double lastPoints;\n\n public Long lastRatedResultId;\n\n public Double lastRatedResultScore;\n\n public Double lastRatedPoints;\n\n public ParticipantScoreDTO(Long id, Long userId, String userName, Long teamId, String teamName, Long exerciseId, String exerciseTitle, Long lastResultId,\n Double lastResultScore, Long lastRatedResultId, Double lastRatedResultScore, Double lastPoints, Double lastRatedPoints) {\n this.id = id;\n this.userId = userId;\n this.userName = userName;\n this.teamId = teamId;\n this.teamName = teamName;\n this.exerciseId = exerciseId;\n this.exerciseTitle = exerciseTitle;\n this.lastResultId = lastResultId;\n this.lastResultScore = lastResultScore;\n this.lastRatedResultId = lastRatedResultId;\n this.lastRatedResultScore = lastRatedResultScore;\n this.lastPoints = lastPoints;\n this.lastRatedPoints = lastRatedPoints;\n }\n\n public ParticipantScoreDTO() {\n // for jackson\n }\n\n /**\n * Generates a {@link ParticipantScoreDTO} from a {@link ParticipantScore}\n *\n * @param participantScore ParticipantScore input\n * @return {@link ParticipantScoreDTO}\n */\n public static ParticipantScoreDTO generateFromParticipantScore(ParticipantScore participantScore) {\n String userName = null;\n Long userId = null;\n String teamName = null;\n Long teamId = null;\n\n if (participantScore.getClass().equals(StudentScore.class)) {\n StudentScore studentScore = (StudentScore) participantScore;\n if (studentScore.getUser() != null) {\n userName = studentScore.getUser().getLogin();\n userId = studentScore.getUser().getId();\n }\n }\n else {\n TeamScore teamScore = (TeamScore) participantScore;\n if (teamScore.getTeam() != null) {\n teamName = teamScore.getTeam().getName();\n teamId = teamScore.getTeam().getId();\n }\n }\n Long id = participantScore.getId();\n String exerciseTitle = participantScore.getExercise() != null && participantScore.getExercise().getTitle() != null ? participantScore.getExercise().getTitle() : null;\n Long exerciseId = participantScore.getExercise() != null ? participantScore.getExercise().getId() : null;\n Long lastResultId = participantScore.getLastResult() != null ? participantScore.getLastResult().getId() : null;\n Double lastResultScore = participantScore.getLastScore();\n Long lastRatedResultId = participantScore.getLastRatedResult() != null ? participantScore.getLastRatedResult().getId() : null;\n Double lastRatedResultScore = participantScore.getLastRatedScore();\n Double lastPoints = participantScore.getLastPoints();\n Double lastRatedPoints = participantScore.getLastRatedPoints();\n\n return new ParticipantScoreDTO(id, userId, userName, teamId, teamName, exerciseId, exerciseTitle, lastResultId, lastResultScore, lastRatedResultId, lastRatedResultScore,\n lastPoints, lastRatedPoints);\n }\n}\n" }, { "alpha_fraction": 0.7046218514442444, "alphanum_fraction": 0.7046218514442444, "avg_line_length": 43.90565872192383, "blob_id": "516dffc86c21f26f95d64d7699892f90a5fbe7d5", "content_id": "a21c7a71dec4845be5abdf4d9f422ce9c8d5cd89", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2380, "license_type": "permissive", "max_line_length": 112, "num_lines": 53, "path": "/src/main/webapp/app/exercises/quiz/participate/quiz-participation.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';\nimport { Result } from 'app/entities/result.model';\n\nexport type EntityResponseType = HttpResponse<QuizSubmission>;\nexport type ResultResponseType = HttpResponse<Result>;\n\n@Injectable({ providedIn: 'root' })\nexport class QuizParticipationService {\n constructor(private http: HttpClient) {}\n\n submitForPractice(quizSubmission: QuizSubmission, exerciseId: number): Observable<ResultResponseType> {\n const copy = QuizParticipationService.convert(quizSubmission);\n return this.http\n .post<Result>(`api/exercises/${exerciseId}/submissions/practice`, copy, { observe: 'response' })\n .map((res: ResultResponseType) => QuizParticipationService.convertResponse(res));\n }\n\n submitForPreview(quizSubmission: QuizSubmission, exerciseId: number): Observable<ResultResponseType> {\n const copy = QuizParticipationService.convert(quizSubmission);\n return this.http\n .post<Result>(`api/exercises/${exerciseId}/submissions/preview`, copy, { observe: 'response' })\n .map((res: ResultResponseType) => QuizParticipationService.convertResponse(res));\n }\n\n submitForLiveMode(quizSubmission: QuizSubmission, exerciseId: number): Observable<EntityResponseType> {\n const copy = QuizParticipationService.convert(quizSubmission);\n return this.http\n .post<QuizSubmission>(`api/exercises/${exerciseId}/submissions/live`, copy, { observe: 'response' })\n .map((res: EntityResponseType) => QuizParticipationService.convertResponse(res));\n }\n\n private static convertResponse<T>(res: HttpResponse<T>): HttpResponse<T> {\n const body: T = QuizParticipationService.convertItemFromServer(res.body!);\n return res.clone({ body });\n }\n\n /**\n * Convert a returned JSON object to QuizSubmission.\n */\n private static convertItemFromServer<T>(object: T): T {\n return Object.assign({}, object);\n }\n\n /**\n * Convert a QuizSubmission to a JSON which can be sent to the server.\n */\n private static convert(quizSubmission: QuizSubmission): QuizSubmission {\n return Object.assign({}, quizSubmission);\n }\n}\n" }, { "alpha_fraction": 0.7038139700889587, "alphanum_fraction": 0.705073893070221, "avg_line_length": 48.60795593261719, "blob_id": "34cd4fe7850770f606392095e7f0f866676c6f23", "content_id": "9144c71e585dd480ad69b80f2cfb6a413c204bc7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8731, "license_type": "permissive", "max_line_length": 158, "num_lines": 176, "path": "/src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\n\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';\nimport { DebugElement } from '@angular/core';\nimport { CourseExerciseService } from 'app/course/manage/course-management.service';\nimport { SinonStub, stub } from 'sinon';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { Subject, of } from 'rxjs';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { MockComponent } from 'ng-mocks';\nimport { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { InitializationState } from 'app/entities/participation/participation.model';\nimport { MockFeatureToggleService } from '../../../helpers/mocks/service/mock-feature-toggle.service';\nimport { ExerciseMode, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model';\nimport { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service';\nimport { ExerciseActionButtonComponent } from 'app/shared/components/exercise-action-button.component';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { MockAlertService } from '../../../helpers/mocks/service/mock-alert.service';\nimport { ExerciseDetailsStudentActionsComponent } from 'app/overview/exercise-details/exercise-details-student-actions.component';\nimport { Team } from 'app/entities/team.model';\nimport { RouterModule } from '@angular/router';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { MockAccountService } from '../../../helpers/mocks/service/mock-account.service';\nimport { User } from 'app/core/user/user.model';\nimport { By } from '@angular/platform-browser';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { MockProfileService } from '../../../helpers/mocks/service/mock-profile.service';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\nimport { CloneRepoButtonComponent } from 'app/shared/components/clone-repo-button/clone-repo-button.component';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ExerciseDetailsStudentActionsComponent', () => {\n let comp: ExerciseDetailsStudentActionsComponent;\n let fixture: ComponentFixture<ExerciseDetailsStudentActionsComponent>;\n let debugElement: DebugElement;\n let courseExerciseService: CourseExerciseService;\n let profileService: ProfileService;\n let startExerciseStub: SinonStub;\n let getProfileInfoSub: SinonStub;\n\n const team = { id: 1, students: [{ id: 99 } as User] } as Team;\n const teamExerciseWithoutTeamAssigned = ({\n id: 42,\n type: ExerciseType.PROGRAMMING,\n mode: ExerciseMode.TEAM,\n teamMode: true,\n studentAssignedTeamIdComputed: true,\n studentParticipations: [],\n } as unknown) as ProgrammingExercise;\n const teamExerciseWithTeamAssigned = { ...teamExerciseWithoutTeamAssigned, studentAssignedTeamId: team.id, allowOfflineIde: true } as ProgrammingExercise;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [ArtemisTestModule, TranslateModule.forRoot(), NgbModule, ArtemisSharedModule, FeatureToggleModule, RouterModule, ClipboardModule],\n declarations: [ExerciseDetailsStudentActionsComponent, MockComponent(ExerciseActionButtonComponent), MockComponent(CloneRepoButtonComponent)],\n providers: [\n { provide: CourseExerciseService, useClass: MockCourseExerciseService },\n { provide: JhiAlertService, useClass: MockAlertService },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n { provide: AccountService, useClass: MockAccountService },\n { provide: ProfileService, useClass: MockProfileService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExerciseDetailsStudentActionsComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n courseExerciseService = debugElement.injector.get(CourseExerciseService);\n profileService = debugElement.injector.get(ProfileService);\n\n getProfileInfoSub = stub(profileService, 'getProfileInfo');\n getProfileInfoSub.returns(of({ inProduction: false, sshCloneURLTemplate: 'ssh://[email protected]:1234/' } as ProfileInfo));\n startExerciseStub = stub(courseExerciseService, 'startExercise');\n });\n });\n\n afterEach(() => {\n startExerciseStub.restore();\n getProfileInfoSub.restore();\n });\n\n it('should not show the buttons \"Team\" and \"Start exercise\" for a team exercise when not assigned to a team yet', fakeAsync(() => {\n comp.exercise = teamExerciseWithoutTeamAssigned;\n\n fixture.detectChanges();\n tick();\n\n const viewTeamButton = fixture.debugElement.query(By.css('.view-team'));\n expect(viewTeamButton).to.not.exist;\n\n const startExerciseButton = fixture.debugElement.query(By.css('.start-exercise'));\n expect(startExerciseButton).to.not.exist;\n }));\n\n it('should reflect the correct participation state when a team was assigned to the student', fakeAsync(() => {\n comp.exercise = teamExerciseWithoutTeamAssigned;\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatusWrapper()).to.be.equal(ParticipationStatus.NO_TEAM_ASSIGNED);\n\n comp.exercise.studentAssignedTeamId = team.id;\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatusWrapper()).to.be.equal(ParticipationStatus.UNINITIALIZED);\n }));\n\n it('should show the button \"Team\" for a team exercise for a student to view his team when assigned to a team', fakeAsync(() => {\n comp.exercise = teamExerciseWithTeamAssigned;\n\n fixture.detectChanges();\n tick();\n\n const viewTeamButton = fixture.debugElement.query(By.css('.view-team'));\n expect(viewTeamButton).to.exist;\n }));\n\n it('should show the button \"Start exercise\" for a team exercise when assigned to a team', fakeAsync(() => {\n comp.exercise = teamExerciseWithTeamAssigned;\n\n fixture.detectChanges();\n tick();\n\n const startExerciseButton = fixture.debugElement.query(By.css('.start-exercise'));\n expect(startExerciseButton).to.exist;\n }));\n\n it('should reflect the correct participation state when team exercise was started', fakeAsync(() => {\n const inactivePart = { id: 2, initializationState: InitializationState.UNINITIALIZED } as StudentParticipation;\n const initPart = { id: 2, initializationState: InitializationState.INITIALIZED } as StudentParticipation;\n const participationSubject = new Subject<StudentParticipation>();\n\n comp.exercise = teamExerciseWithTeamAssigned;\n startExerciseStub.returns(participationSubject);\n comp.startExercise();\n participationSubject.next(inactivePart);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatusWrapper()).to.be.equal(ParticipationStatus.UNINITIALIZED);\n expect(startExerciseStub).to.have.been.calledOnce;\n participationSubject.next(initPart);\n\n fixture.detectChanges();\n tick();\n\n expect(comp.participationStatusWrapper()).to.be.equal(ParticipationStatus.INITIALIZED);\n\n // Check that button \"Start exercise\" is no longer shown\n const startExerciseButton = fixture.debugElement.query(By.css('.start-exercise'));\n expect(startExerciseButton).to.not.exist;\n\n // Check that button \"Clone repository\" is shown\n const cloneRepositoryButton = fixture.debugElement.query(By.css('jhi-clone-repo-button'));\n expect(cloneRepositoryButton).to.exist;\n\n fixture.destroy();\n flush();\n }));\n});\n" }, { "alpha_fraction": 0.6945337653160095, "alphanum_fraction": 0.6945337653160095, "avg_line_length": 31.736841201782227, "blob_id": "4d039aab9c3c378268436ba770c3c4b52c31a12b", "content_id": "aac8eb14ce3705f85dcad3dad4c25b3ec7d3c3bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 622, "license_type": "permissive", "max_line_length": 70, "num_lines": 19, "path": "/src/main/webapp/app/entities/student-question-answer.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\nimport { BaseEntity } from 'app/shared/model/base-entity';\nimport { User } from 'app/core/user/user.model';\nimport { StudentQuestion } from 'app/entities/student-question.model';\n\nexport class StudentQuestionAnswer implements BaseEntity {\n public id?: number;\n public answerText?: string;\n public answerDate?: Moment;\n public verified?: boolean;\n public tutorApproved?: boolean;\n public author?: User;\n public question?: StudentQuestion;\n\n constructor() {\n this.verified = false; // default value\n this.tutorApproved = false; // default value\n }\n}\n" }, { "alpha_fraction": 0.6026522517204285, "alphanum_fraction": 0.6031433939933777, "avg_line_length": 29.388059616088867, "blob_id": "09e719280d018b3b7d4ae933de29b134e5207240", "content_id": "5f7f76952d95dc14b8d9b956a0090de9368143eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2036, "license_type": "permissive", "max_line_length": 118, "num_lines": 67, "path": "/src/main/webapp/app/shared/components/button.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';\n\n/**\n * enum for button types\n * @enum {string}\n */\nexport enum ButtonType {\n PRIMARY = 'btn-primary',\n SECONDARY = 'btn-secondary',\n SUCCESS = 'btn-success',\n WARNING = 'btn-warning',\n ERROR = 'btn-danger',\n INFO = 'btn-info',\n}\n\n/**\n * enum for button sizes\n * @enum {string}\n */\nexport enum ButtonSize {\n SMALL = 'btn-sm',\n MEDIUM = 'btn-md',\n LARGE = 'btn-lg',\n}\n\n/**\n * A generic button component that has a disabled & loading state.\n * The only event output is the click.\n *\n * Can be used as a button with text and/or icon.\n */\n@Component({\n selector: 'jhi-button',\n template: `\n <button\n [ngClass]=\"['jhi-btn', 'btn', btnType, btnSize]\"\n [type]=\"shouldSubmit ? 'submit' : 'button'\"\n ngbTooltip=\"{{ tooltip | translate }}\"\n container=\"body\"\n (click)=\"onClick.emit($event)\"\n [jhiFeatureToggle]=\"featureToggle\"\n [overwriteDisabled]=\"disabled || isLoading\"\n >\n <fa-icon class=\"jhi-btn__loading\" *ngIf=\"isLoading\" icon=\"circle-notch\" [spin]=\"true\" size=\"sm\"></fa-icon>\n <fa-icon class=\"jhi-btn__icon\" *ngIf=\"icon && !isLoading\" [icon]=\"icon\" size=\"sm\"></fa-icon>\n <span class=\"jhi-btn__title\" [class.ml-1]=\"icon || isLoading\" *ngIf=\"title\" [jhiTranslate]=\"title\"></span>\n </button>\n `,\n})\nexport class ButtonComponent {\n @Input() btnType = ButtonType.PRIMARY;\n @Input() btnSize = ButtonSize.MEDIUM;\n // Fa-icon name.\n @Input() icon: string;\n // Translation placeholders, will be translated in the component.\n @Input() title: string;\n @Input() tooltip: string;\n\n @Input() disabled = false;\n @Input() isLoading = false;\n @Input() featureToggle: FeatureToggle; // Disable by feature toggle.\n\n @Input() shouldSubmit = true;\n\n @Output() onClick = new EventEmitter<MouseEvent>();\n}\n" }, { "alpha_fraction": 0.704937756061554, "alphanum_fraction": 0.7065435647964478, "avg_line_length": 32.66216278076172, "blob_id": "d2cf2d189488b957a4c7cf3976f7220b2aef1972", "content_id": "36d7a222a7b64754cd10edf99ef86cbd0d9f7376", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2491, "license_type": "permissive", "max_line_length": 171, "num_lines": 74, "path": "/src/main/java/de/tum/in/www1/artemis/domain/participation/ProgrammingExerciseStudentParticipation.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.participation;\n\nimport javax.persistence.Column;\nimport javax.persistence.DiscriminatorValue;\nimport javax.persistence.Entity;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\nimport com.fasterxml.jackson.annotation.JsonInclude;\nimport com.fasterxml.jackson.annotation.JsonView;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\nimport de.tum.in.www1.artemis.domain.view.QuizView;\n\n@Entity\n@DiscriminatorValue(value = \"PESP\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ProgrammingExerciseStudentParticipation extends StudentParticipation implements ProgrammingExerciseParticipation {\n\n @Column(name = \"repository_url\")\n @JsonView(QuizView.Before.class)\n private String repositoryUrl;\n\n @Column(name = \"build_plan_id\")\n @JsonView(QuizView.Before.class)\n private String buildPlanId;\n\n public String getRepositoryUrl() {\n return repositoryUrl;\n }\n\n public void setRepositoryUrl(String repositoryUrl) {\n this.repositoryUrl = repositoryUrl;\n }\n\n public String getBuildPlanId() {\n return buildPlanId;\n }\n\n public void setBuildPlanId(String buildPlanId) {\n this.buildPlanId = buildPlanId;\n }\n\n @Override\n @JsonIgnore\n // NOTE: this is a helper method to avoid casts in other classes that want to access the underlying exercise\n public ProgrammingExercise getProgrammingExercise() {\n Exercise exercise = getExercise();\n if (exercise instanceof ProgrammingExercise) { // this should always be the case except exercise is null\n return (ProgrammingExercise) exercise;\n }\n else {\n return null;\n }\n }\n\n @Override\n public void setProgrammingExercise(ProgrammingExercise programmingExercise) {\n setExercise(programmingExercise);\n }\n\n @Override\n public String toString() {\n return \"Participation{\" + \"id=\" + getId() + \", repositoryUrl='\" + getRepositoryUrl() + \"'\" + \", buildPlanId='\" + getBuildPlanId() + \"'\" + \", initializationState='\"\n + getInitializationState() + \"'\" + \", initializationDate='\" + getInitializationDate() + \"'\" + \", presentationScore=\" + getPresentationScore() + \"}\";\n }\n\n @Override\n public Participation copyParticipationId() {\n var participation = new ProgrammingExerciseStudentParticipation();\n participation.setId(getId());\n return participation;\n }\n}\n" }, { "alpha_fraction": 0.6324324607849121, "alphanum_fraction": 0.6351351141929626, "avg_line_length": 31.647058486938477, "blob_id": "a57011a9e04cf2d1f825322cc3a21f13b17a70cb", "content_id": "74ef2cf6c54319e4828e8def19332e56aca4fce3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 117, "num_lines": 34, "path": "/src/main/webapp/app/assessment/assessment-warning/assessment-warning.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges } from '@angular/core';\nimport * as moment from 'moment';\nimport { Exercise } from 'app/entities/exercise.model';\n\n/*\nWarn instructors in the assessment and submission page\nif the due date is not over yet as they are allowed to assess submissions there\n */\n@Component({\n selector: 'jhi-assessment-warning',\n template: `\n <h6>\n <div class=\"card-header\" *ngIf=\"this.isBeforeDueDate\">\n <fa-icon [icon]=\"'exclamation-triangle'\" size=\"2x\" class=\"text-warning\" placement=\"bottom\"></fa-icon>\n {{ 'artemisApp.assessment.dashboard.warning' | translate }}\n </div>\n </h6>\n `,\n})\nexport class AssessmentWarningComponent implements OnChanges {\n @Input() exercise: Exercise;\n currentDate: moment.MomentInput;\n isBeforeDueDate = false;\n\n /**\n * Checks if the due date of the exercise is over\n */\n ngOnChanges(): void {\n const dueDate = this.exercise.dueDate;\n if (dueDate != undefined) {\n this.isBeforeDueDate = dueDate.isAfter(this.currentDate);\n }\n }\n}\n" }, { "alpha_fraction": 0.73581463098526, "alphanum_fraction": 0.7370049953460693, "avg_line_length": 59.581729888916016, "blob_id": "2547c1cb31f64fe3fd7d66efa089033c508bd35a", "content_id": "d718b57df5b4db6fbb7a39626aa2c18452a599fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12601, "license_type": "permissive", "max_line_length": 171, "num_lines": 208, "path": "/src/test/javascript/spec/integration/code-editor/code-editor-student.integration.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as moment from 'moment';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { ChangeDetectorRef, DebugElement } from '@angular/core';\nimport { ActivatedRoute, Params } from '@angular/router';\nimport { SinonStub, stub } from 'sinon';\nimport { BehaviorSubject, Subject } from 'rxjs';\nimport * as ace from 'brace';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\nimport { CommitState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { MockAccountService } from '../../helpers/mocks/service/mock-account.service';\nimport { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service';\nimport { ProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service';\nimport { MockProgrammingSubmissionService } from '../../helpers/mocks/service/mock-programming-submission.service';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { getElement } from '../../helpers/utils/general.utils';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { MockWebsocketService } from '../../helpers/mocks/service/mock-websocket.service';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { Result } from 'app/entities/result.model';\nimport {\n CodeEditorBuildLogService,\n CodeEditorRepositoryFileService,\n CodeEditorRepositoryService,\n} from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { CodeEditorStudentContainerComponent } from 'app/exercises/programming/participate/code-editor-student-container.component';\nimport { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockResultService } from '../../helpers/mocks/service/mock-result.service';\nimport { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service';\nimport { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service';\nimport { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service';\nimport { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service';\nimport { ArtemisProgrammingParticipationModule } from 'app/exercises/programming/participate/programming-participation.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CodeEditorStudentIntegration', () => {\n // needed to make sure ace is defined\n ace.acequire('ace/ext/modelist');\n let container: CodeEditorStudentContainerComponent;\n let containerFixture: ComponentFixture<CodeEditorStudentContainerComponent>;\n let containerDebugElement: DebugElement;\n let codeEditorRepositoryService: CodeEditorRepositoryService;\n let participationWebsocketService: ParticipationWebsocketService;\n let resultService: ResultService;\n let programmingExerciseParticipationService: ProgrammingExerciseParticipationService;\n let route: ActivatedRoute;\n\n let checkIfRepositoryIsCleanStub: SinonStub;\n let subscribeForLatestResultOfParticipationStub: SinonStub;\n let getFeedbackDetailsForResultStub: SinonStub;\n let getStudentParticipationWithLatestResultStub: SinonStub;\n\n let subscribeForLatestResultOfParticipationSubject: BehaviorSubject<Result | undefined>;\n let routeSubject: Subject<Params>;\n\n const result = { id: 3, successful: false, completionDate: moment().subtract(2, 'days') };\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisProgrammingParticipationModule],\n declarations: [],\n providers: [\n JhiLanguageHelper,\n ChangeDetectorRef,\n DeviceDetectorService,\n CodeEditorConflictStateService,\n { provide: AccountService, useClass: MockAccountService },\n { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects },\n { provide: JhiWebsocketService, useClass: MockWebsocketService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: ProgrammingExerciseParticipationService, useClass: MockProgrammingExerciseParticipationService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: ResultService, useClass: MockResultService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: CodeEditorRepositoryService, useClass: MockCodeEditorRepositoryService },\n { provide: CodeEditorRepositoryFileService, useClass: MockCodeEditorRepositoryFileService },\n { provide: CodeEditorBuildLogService, useClass: MockCodeEditorBuildLogService },\n { provide: ResultService, useClass: MockResultService },\n { provide: ProgrammingSubmissionService, useClass: MockProgrammingSubmissionService },\n { provide: ExerciseHintService, useClass: MockExerciseHintService },\n ],\n })\n .compileComponents()\n .then(() => {\n containerFixture = TestBed.createComponent(CodeEditorStudentContainerComponent);\n container = containerFixture.componentInstance;\n containerDebugElement = containerFixture.debugElement;\n\n codeEditorRepositoryService = containerDebugElement.injector.get(CodeEditorRepositoryService);\n participationWebsocketService = containerDebugElement.injector.get(ParticipationWebsocketService);\n resultService = containerDebugElement.injector.get(ResultService);\n programmingExerciseParticipationService = containerDebugElement.injector.get(ProgrammingExerciseParticipationService);\n route = containerDebugElement.injector.get(ActivatedRoute);\n\n subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | undefined>(undefined);\n\n routeSubject = new Subject<Params>();\n // @ts-ignore\n (route as MockActivatedRouteWithSubjects).setSubject(routeSubject);\n\n checkIfRepositoryIsCleanStub = stub(codeEditorRepositoryService, 'getStatus');\n subscribeForLatestResultOfParticipationStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation').returns(\n subscribeForLatestResultOfParticipationSubject,\n );\n getFeedbackDetailsForResultStub = stub(resultService, 'getFeedbackDetailsForResult');\n getStudentParticipationWithLatestResultStub = stub(programmingExerciseParticipationService, 'getStudentParticipationWithLatestResult');\n });\n });\n\n afterEach(() => {\n checkIfRepositoryIsCleanStub.restore();\n subscribeForLatestResultOfParticipationStub.restore();\n getFeedbackDetailsForResultStub.restore();\n getStudentParticipationWithLatestResultStub.restore();\n\n subscribeForLatestResultOfParticipationSubject = new BehaviorSubject<Result | undefined>(undefined);\n subscribeForLatestResultOfParticipationStub.returns(subscribeForLatestResultOfParticipationSubject);\n\n routeSubject = new Subject<Params>();\n // @ts-ignore\n (route as MockActivatedRouteWithSubjects).setSubject(routeSubject);\n });\n\n it('should initialize correctly on route change if participation can be retrieved', () => {\n container.ngOnInit();\n const participation = { id: 1, results: [result], exercise: { id: 99 } } as Participation;\n const feedbacks = [{ id: 2 }] as Feedback[];\n const findWithLatestResultSubject = new Subject<Participation>();\n const getFeedbackDetailsForResultSubject = new Subject<{ body: Feedback[] }>();\n getStudentParticipationWithLatestResultStub.returns(findWithLatestResultSubject);\n getFeedbackDetailsForResultStub.returns(getFeedbackDetailsForResultSubject);\n\n routeSubject.next({ participationId: 1 });\n\n expect(container.loadingParticipation).to.be.true;\n\n findWithLatestResultSubject.next(participation);\n getFeedbackDetailsForResultSubject.next({ body: feedbacks });\n\n expect(getStudentParticipationWithLatestResultStub).to.have.been.calledOnceWithExactly(participation.id);\n expect(getFeedbackDetailsForResultStub).to.have.been.calledOnceWithExactly(result.id);\n expect(container.loadingParticipation).to.be.false;\n expect(container.participationCouldNotBeFetched).to.be.false;\n expect(container.participation).to.deep.equal({ ...participation, results: [{ ...result, feedbacks }] });\n });\n\n it('should show the repository locked badge and disable the editor actions if the exercises buildAndTestAfterDueDate is set and the due date has passed', () => {\n container.ngOnInit();\n const participation = {\n id: 1,\n results: [result],\n exercise: { id: 99, buildAndTestStudentSubmissionsAfterDueDate: moment().subtract(1, 'hours'), dueDate: moment().subtract(2, 'hours') } as ProgrammingExercise,\n } as any;\n const feedbacks = [{ id: 2 }] as Feedback[];\n const findWithLatestResultSubject = new Subject<Participation>();\n const getFeedbackDetailsForResultSubject = new Subject<{ body: Feedback[] }>();\n const isCleanSubject = new Subject();\n getStudentParticipationWithLatestResultStub.returns(findWithLatestResultSubject);\n getFeedbackDetailsForResultStub.returns(getFeedbackDetailsForResultSubject);\n checkIfRepositoryIsCleanStub.returns(isCleanSubject);\n\n routeSubject.next({ participationId: 1 });\n findWithLatestResultSubject.next(participation);\n getFeedbackDetailsForResultSubject.next({ body: feedbacks });\n\n containerFixture.detectChanges();\n isCleanSubject.next({ repositoryStatus: CommitState.CLEAN });\n\n // Repository should be locked, the student can't write into it anymore.\n expect(container.repositoryIsLocked).to.be.true;\n expect(getElement(containerDebugElement, '.locked-container')).to.exist;\n expect(container.codeEditorContainer.fileBrowser.disableActions).to.be.true;\n expect(container.codeEditorContainer.actions.disableActions).to.be.true;\n });\n\n it('should abort initialization and show error state if participation cannot be retrieved', () => {\n container.ngOnInit();\n const findWithLatestResultSubject = new Subject<{ body: Participation }>();\n getStudentParticipationWithLatestResultStub.returns(findWithLatestResultSubject);\n\n routeSubject.next({ participationId: 1 });\n\n expect(container.loadingParticipation).to.be.true;\n\n findWithLatestResultSubject.error('fatal error');\n\n expect(container.loadingParticipation).to.be.false;\n expect(container.participationCouldNotBeFetched).to.be.true;\n expect(getFeedbackDetailsForResultStub).to.not.have.been.called;\n expect(container.participation).to.be.undefined;\n });\n});\n" }, { "alpha_fraction": 0.6026511192321777, "alphanum_fraction": 0.6029744744300842, "avg_line_length": 44.15328598022461, "blob_id": "c8658731fcd98c631d08c4e66ea26f202e7a0df1", "content_id": "c1602c1498c3a3cbbe1e968c1b9d33cfa607a557", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6186, "license_type": "permissive", "max_line_length": 171, "num_lines": 137, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/edit-attachment-unit/edit-attachment-unit.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, ViewChild } from '@angular/core';\nimport { onError } from 'app/shared/util/global.utils';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { finalize, switchMap, take } from 'rxjs/operators';\nimport { AttachmentUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/attachmentUnit.service';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { AttachmentUnitFormComponent, AttachmentUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/attachment-unit-form/attachment-unit-form.component';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { forkJoin, combineLatest } from 'rxjs';\nimport * as moment from 'moment';\n\n@Component({\n selector: 'jhi-edit-attachment-unit',\n templateUrl: './edit-attachment-unit.component.html',\n styles: [],\n})\nexport class EditAttachmentUnitComponent implements OnInit {\n @ViewChild('attachmentUnitForm')\n attachmentUnitForm: AttachmentUnitFormComponent;\n isLoading = false;\n attachmentUnit: AttachmentUnit;\n attachment: Attachment;\n formData: AttachmentUnitFormData;\n lectureId: number;\n notificationText: string;\n\n constructor(\n private activatedRoute: ActivatedRoute,\n private router: Router,\n private attachmentUnitService: AttachmentUnitService,\n private attachmentService: AttachmentService,\n private alertService: JhiAlertService,\n private fileUploaderService: FileUploaderService,\n ) {}\n\n ngOnInit(): void {\n this.isLoading = true;\n const lectureRoute = this.activatedRoute.parent!.parent!;\n combineLatest(this.activatedRoute.paramMap, lectureRoute.paramMap)\n .pipe(\n take(1),\n switchMap(([params, parentParams]) => {\n const attachmentUnitId = Number(params.get('attachmentUnitId'));\n this.lectureId = Number(parentParams.get('lectureId'));\n return this.attachmentUnitService.findById(attachmentUnitId, this.lectureId);\n }),\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n (attachmentUnitResponse: HttpResponse<AttachmentUnit>) => {\n this.attachmentUnit = attachmentUnitResponse.body!;\n this.attachment = this.attachmentUnit.attachment!;\n // breaking the connection to prevent errors in deserialization. will be reconnected on the server side\n this.attachmentUnit.attachment = undefined;\n this.attachment.attachmentUnit = undefined;\n\n this.formData = {\n formProperties: {\n name: this.attachment.name,\n description: this.attachmentUnit.description,\n releaseDate: this.attachment.releaseDate,\n version: this.attachment.version,\n },\n fileProperties: {\n fileName: this.attachment.link,\n },\n };\n },\n (res: HttpErrorResponse) => onError(this.alertService, res),\n );\n }\n\n updateAttachmentUnit(formData: AttachmentUnitFormData) {\n const { description, name, releaseDate, updateNotificationText } = formData.formProperties;\n const { file, fileName } = formData.fileProperties;\n\n // optional update notification text for students\n if (updateNotificationText) {\n this.notificationText = updateNotificationText;\n }\n\n // === Setting attachment ===\n this.attachment.name = name;\n this.attachment.releaseDate = releaseDate;\n this.attachment.attachmentType = AttachmentType.FILE;\n // === Setting attachmentUnit ===\n this.attachmentUnit.description = description;\n\n this.isLoading = true;\n // when the file has changed the new file needs to be uploaded first before making the put request\n if (file) {\n this.fileUploaderService.uploadFile(file, fileName, { keepFileName: true }).then(\n (result) => {\n // we only update the version when the underlying file has changed\n this.attachment.version = this.attachment.version! + 1;\n this.attachment.uploadDate = moment();\n // update link to the path provided by the server\n this.attachment.link = result.path;\n this.performUpdate();\n },\n (error) => {\n // displaying the file upload error in the form but not resetting the form]\n this.attachmentUnitForm.setFileUploadError(error.message);\n this.isLoading = false;\n },\n );\n } else {\n this.performUpdate();\n }\n }\n\n performUpdate() {\n const attachmentUnitObservable = this.attachmentUnitService.update(this.attachmentUnit, this.lectureId);\n const requestOptions = {} as any;\n if (this.notificationText) {\n requestOptions.notificationText = this.notificationText;\n }\n const attachmentObservable = this.attachmentService.update(this.attachment, requestOptions);\n forkJoin([attachmentUnitObservable, attachmentObservable])\n .pipe(\n finalize(() => {\n this.isLoading = false;\n this.router.navigate(['../../../'], { relativeTo: this.activatedRoute });\n }),\n )\n .subscribe(\n () => {},\n (res: HttpErrorResponse) => onError(this.alertService, res),\n );\n }\n}\n" }, { "alpha_fraction": 0.6801007390022278, "alphanum_fraction": 0.6901763081550598, "avg_line_length": 22.352941513061523, "blob_id": "e29944a776209f4eb9bf3b1f1e6c4e6c79f893b5", "content_id": "92869af0501aebd96913d0c61b573a3bb2503409", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 794, "license_type": "permissive", "max_line_length": 106, "num_lines": 34, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/ScoreDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.User;\n\n/**\n * Wrapper Class to send achieved points and achieved scores of a student to the client for courses / exam\n */\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ScoreDTO {\n\n public Long studentId;\n\n public String studentLogin;\n\n public Double pointsAchieved;\n\n public Double scoreAchieved;\n\n public Double regularPointsAchievable;\n\n public ScoreDTO(User user) {\n this.studentId = user.getId();\n this.studentLogin = user.getLogin();\n this.pointsAchieved = 0.0;\n this.scoreAchieved = 0.0;\n this.regularPointsAchievable = 0.0;\n }\n\n public ScoreDTO() {\n // for jackson\n }\n}\n" }, { "alpha_fraction": 0.6653565168380737, "alphanum_fraction": 0.6895002722740173, "avg_line_length": 32.60377502441406, "blob_id": "a6d134ac1b7d6a1d446224dc47475a8cc8f88e1f", "content_id": "aafa877a8ac0f5173fd0cf848831bdf61cb95344", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 1781, "license_type": "permissive", "max_line_length": 227, "num_lines": 53, "path": "/docker-compose.yml", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "version: '3'\n\n# NOTE: this docker compose file starts the artemis-server (as jar file) and the artemis-client in separate containers. This setup is aimed for development.\n# If you want to start the whole Artemis application (server and client) in the same container, you need to specify a different service and\n# you have to execute the command './gradlew -Pprod -Pwar clean bootWar && java -jar build/libs/*.war --spring.profiles.active=dev,artemis,bamboo,bitbucket,jira'\n\nservices:\n artemis-server:\n command: sh -c \"./gradlew buildJarForDocker && java -jar build/libs/Artemis-*.jar\"\n depends_on:\n - artemis-mysql\n image: openjdk:15-jdk-alpine\n environment:\n - SPRING_DATASOURCE_URL=jdbc:mysql://artemis-mysql:3306/Artemis?createDatabaseIfNotExist=true&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC\n - SPRING_PROFILES_ACTIVE=dev,bamboo,bitbucket,jira,artemis,scheduling\n networks:\n - artemis\n ports:\n - 8080:8080\n volumes:\n - ./:/server/\n working_dir: /server\n\n artemis-client:\n command: sh -c \"yarn install && yarn start-docker\"\n depends_on:\n - artemis-server\n image: node:15.6.0-alpine\n networks:\n - artemis\n ports:\n - 9000:9000\n volumes:\n - ./:/client/\n working_dir: /client\n\n artemis-mysql:\n command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp\n environment:\n - MYSQL_USER=root\n - MYSQL_ALLOW_EMPTY_PASSWORD=yes\n - MYSQL_DATABASE=Artemis\n image: mysql:8.0.23\n networks:\n - artemis\n ports:\n - 3306:3306\n volumes:\n - ./data/.db:/var/lib/mysql\n\nnetworks:\n artemis:\n driver: bridge\n" }, { "alpha_fraction": 0.6354166865348816, "alphanum_fraction": 0.644345223903656, "avg_line_length": 31.780487060546875, "blob_id": "0fb1f63495cfb65fb21b51789af8a746c8c48ffa", "content_id": "d7bf20323aabbdb3d12749c38a87397bb24d5aae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2688, "license_type": "permissive", "max_line_length": 125, "num_lines": 82, "path": "/src/test/javascript/spec/component/plagiarism/plagiarism-sidebar.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockTranslateService, TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service';\nimport { ArtemisPlagiarismModule } from 'app/exercises/shared/plagiarism/plagiarism.module';\nimport { PlagiarismSidebarComponent } from 'app/exercises/shared/plagiarism/plagiarism-sidebar/plagiarism-sidebar.component';\n\ndescribe('Plagiarism Sidebar Component', () => {\n let comp: PlagiarismSidebarComponent;\n let fixture: ComponentFixture<PlagiarismSidebarComponent>;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisPlagiarismModule, TranslateTestingModule],\n providers: [{ provide: TranslateService, useClass: MockTranslateService }],\n }).compileComponents();\n\n fixture = TestBed.createComponent(PlagiarismSidebarComponent);\n comp = fixture.componentInstance;\n\n comp.pageSize = 10;\n });\n\n it('displays the run details', () => {\n spyOn(comp.showRunDetailsChange, 'emit');\n\n comp.displayRunDetails();\n expect(comp.showRunDetailsChange.emit).toHaveBeenCalledWith(true);\n });\n\n it('computes the number of pages with multiple comparisons', () => {\n const numberOfPages = comp.computeNumberOfPages(12);\n expect(numberOfPages).toEqual(1);\n });\n\n it('computes the number of pages with 0 comparisons', () => {\n const numberOfPages = comp.computeNumberOfPages(0);\n expect(numberOfPages).toEqual(0);\n });\n\n it('computes the number of pages with one comparison', () => {\n const numberOfPages = comp.computeNumberOfPages(1);\n expect(numberOfPages).toEqual(0);\n });\n\n it('computes the paged index', () => {\n comp.currentPage = 2;\n const pagedIndex = comp.getPagedIndex(1);\n\n expect(pagedIndex).toEqual(21);\n });\n\n it('pages left', () => {\n comp.currentPage = 2;\n comp.handlePageLeft();\n\n expect(comp.currentPage).toEqual(1);\n });\n\n it('does not page left', () => {\n comp.currentPage = 0;\n comp.handlePageLeft();\n\n expect(comp.currentPage).toEqual(0);\n });\n\n it('pages right', () => {\n comp.currentPage = 2;\n comp.numberOfPages = 3;\n comp.handlePageRight();\n\n expect(comp.currentPage).toEqual(3);\n });\n\n it('does not pages right', () => {\n comp.currentPage = 3;\n comp.numberOfPages = 3;\n comp.handlePageRight();\n\n expect(comp.currentPage).toEqual(3);\n });\n});\n" }, { "alpha_fraction": 0.653352677822113, "alphanum_fraction": 0.6569837927818298, "avg_line_length": 42.48421096801758, "blob_id": "11d78d9d5482945035a1d529989cc3722c7bad6e", "content_id": "975560f46cc93b0ed6880b0e6fcbc4239b531519", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4131, "license_type": "permissive", "max_line_length": 122, "num_lines": 95, "path": "/src/test/javascript/spec/component/lecture-unit/attachment-unit/attachment-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\n\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbCollapse, NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { AttachmentUnitComponent } from 'app/overview/course-lectures/attachment-unit/attachment-unit.component';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { FileService } from 'app/shared/http/file.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('AttachmentUnitComponent', () => {\n const sandbox = sinon.createSandbox();\n let attachmentUnit: AttachmentUnit;\n let attachment: Attachment;\n\n let attachmentUnitComponentFixture: ComponentFixture<AttachmentUnitComponent>;\n let attachmentUnitComponent: AttachmentUnitComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [\n AttachmentUnitComponent,\n MockDirective(NgbCollapse),\n MockComponent(FaIconComponent),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockDirective(NgbTooltip),\n ],\n providers: [MockProvider(FileService)],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n attachmentUnitComponentFixture = TestBed.createComponent(AttachmentUnitComponent);\n attachmentUnitComponent = attachmentUnitComponentFixture.componentInstance;\n\n attachment = new Attachment();\n attachment.id = 1;\n attachment.version = 1;\n attachment.attachmentType = AttachmentType.FILE;\n attachment.releaseDate = moment({ years: 2010, months: 3, date: 5 });\n attachment.uploadDate = moment({ years: 2010, months: 3, date: 5 });\n attachment.name = 'test';\n attachment.link = '/path/to/file/test.pdf';\n\n attachmentUnit = new AttachmentUnit();\n attachmentUnit.id = 1;\n attachmentUnit.description = 'lorem ipsum';\n attachmentUnit.attachment = attachment;\n attachmentUnitComponent.attachmentUnit = attachmentUnit;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n attachmentUnitComponentFixture.detectChanges();\n attachment.link = '/path/to/file/test.jpg';\n attachmentUnitComponentFixture.detectChanges();\n attachment.link = '/path/to/file/test.svg';\n attachmentUnitComponentFixture.detectChanges();\n attachment.link = '/path/to/file/test.zip';\n attachmentUnitComponentFixture.detectChanges();\n attachment.link = '/path/to/file/test.something';\n expect(attachmentUnitComponent).to.be.ok;\n });\n\n it('should calculate correct fileName', () => {\n const getFileNameSpy = sinon.spy(attachmentUnitComponent, 'getFileName');\n attachmentUnitComponentFixture.detectChanges();\n expect(getFileNameSpy).to.have.returned('test.pdf');\n getFileNameSpy.restore();\n });\n\n it('should download attachment when clicked', () => {\n const fileService = TestBed.inject(FileService);\n const downloadFileStub = sandbox.stub(fileService, 'downloadFileWithAccessToken');\n const downloadButton = attachmentUnitComponentFixture.debugElement.nativeElement.querySelector('#downloadButton');\n expect(downloadButton).to.be.ok;\n downloadButton.click();\n expect(downloadFileStub).to.have.been.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.7009757161140442, "alphanum_fraction": 0.7069252729415894, "avg_line_length": 41.23115539550781, "blob_id": "bc301690e0cd861180b62807f468f380e0a3d16f", "content_id": "42905233aa091f7700ec06a3b82b3ccd2ac097ed", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 8404, "license_type": "permissive", "max_line_length": 117, "num_lines": 199, "path": "/src/test/java/de/tum/in/www1/artemis/ExerciseHintIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis;\n\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.List;\nimport java.util.Optional;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.ExerciseHint;\nimport de.tum.in.www1.artemis.repository.ExerciseHintRepository;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\n\npublic class ExerciseHintIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ExerciseHintRepository exerciseHintRepository;\n\n @Autowired\n private ProgrammingExerciseRepository exerciseRepository;\n\n private Exercise exercise;\n\n @BeforeEach\n public void initTestCase() {\n database.addCourseWithOneProgrammingExerciseAndTestCases();\n database.addUsers(2, 2, 2);\n\n exercise = exerciseRepository.findAll().get(0);\n database.addHintsToExercise(exercise);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void queryAllHintsForAnExerciseAsAStudent() throws Exception {\n request.getList(\"/api/exercises/\" + exercise.getId() + \"/hints\", HttpStatus.OK, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void queryAllHintsForAnExerciseAsATutor() throws Exception {\n request.getList(\"/api/exercises/\" + exercise.getId() + \"/hints\", HttpStatus.OK, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void queryAllHintsForAnExerciseAsAnInstructor() throws Exception {\n request.getList(\"/api/exercises/\" + exercise.getId() + \"/hints\", HttpStatus.OK, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void getHintForAnExerciseAsAStudentShouldReturnForbidden() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n request.get(\"/api/exercise-hints/\" + exerciseHint.getId(), HttpStatus.FORBIDDEN, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void getHintForAnExerciseAsATutor() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n request.get(\"/api/exercise-hints/\" + exerciseHint.getId(), HttpStatus.OK, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void getHintForAnExerciseAsAnInstructor() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n request.get(\"/api/exercise-hints/\" + exerciseHint.getId(), HttpStatus.OK, ExerciseHint.class);\n request.get(\"/api/exercise-hints/\" + 0L, HttpStatus.NOT_FOUND, ExerciseHint.class);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void createHintAsAStudentShouldReturnForbidden() throws Exception {\n ExerciseHint exerciseHint = new ExerciseHint().title(\"title 4\").content(\"content 4\").exercise(exercise);\n request.post(\"/api/exercise-hints/\", exerciseHint, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void createHintAsTutor() throws Exception {\n ExerciseHint exerciseHint = new ExerciseHint().title(\"title 4\").content(\"content 4\").exercise(exercise);\n request.post(\"/api/exercise-hints/\", exerciseHint, HttpStatus.CREATED);\n\n List<ExerciseHint> exerciseHints = exerciseHintRepository.findAll();\n assertThat(exerciseHints).hasSize(4);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void createHintAsInstructor() throws Exception {\n ExerciseHint exerciseHint = new ExerciseHint().title(\"title 4\").content(\"content 4\").exercise(exercise);\n request.post(\"/api/exercise-hints/\", exerciseHint, HttpStatus.CREATED);\n List<ExerciseHint> exerciseHints = exerciseHintRepository.findAll();\n assertThat(exerciseHints).hasSize(4);\n\n exerciseHint.setExercise(null);\n request.post(\"/api/exercise-hints/\", exerciseHint, HttpStatus.BAD_REQUEST);\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n public void updateHintAsAStudentShouldReturnForbidden() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n String newContent = \"new content value!\";\n String contentBefore = exerciseHint.getContent();\n\n exerciseHint.setContent(newContent);\n request.put(\"/api/exercise-hints/\" + exerciseHint.getId(), exerciseHint, HttpStatus.FORBIDDEN);\n\n Optional<ExerciseHint> hintAfterSave = exerciseHintRepository.findById(exerciseHint.getId());\n assertThat(hintAfterSave.get().getContent()).isEqualTo(contentBefore);\n\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void updateHintAsTutor() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n String newContent = \"new content value!\";\n\n exerciseHint.setContent(newContent);\n request.put(\"/api/exercise-hints/\" + exerciseHint.getId(), exerciseHint, HttpStatus.OK);\n request.put(\"/api/exercise-hints/\" + 0L, exerciseHint, HttpStatus.BAD_REQUEST);\n Optional<ExerciseHint> hintAfterSave = exerciseHintRepository.findById(exerciseHint.getId());\n assertThat(hintAfterSave.get().getContent()).isEqualTo(newContent);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void updateHintAsInstructor() throws Exception {\n ExerciseHint exerciseHint = exerciseHintRepository.findAll().get(0);\n String newContent = \"new content value!\";\n\n exerciseHint.setContent(newContent);\n request.put(\"/api/exercise-hints/\" + exerciseHint.getId(), exerciseHint, HttpStatus.OK);\n\n Optional<ExerciseHint> hintAfterSave = exerciseHintRepository.findById(exerciseHint.getId());\n assertThat(hintAfterSave.get().getContent()).isEqualTo(newContent);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void deleteHintAsInstructor() throws Exception {\n ExerciseHint exerciseHint = new ExerciseHint().title(\"title 4\").content(\"content 4\").exercise(exercise);\n request.delete(\"/api/exercise-hints/\" + 0L, HttpStatus.NOT_FOUND);\n request.post(\"/api/exercise-hints\", exerciseHint, HttpStatus.CREATED);\n List<ExerciseHint> exerciseHints = exerciseHintRepository.findAll();\n request.delete(\"/api/exercise-hints/\" + exerciseHints.get(0).getId(), HttpStatus.NO_CONTENT);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testGetHintTitleAsInstuctor() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetHintTitle();\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void testGetHintTitleAsTeachingAssistant() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetHintTitle();\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetHintTitleAsUser() throws Exception {\n // Only user and role matter, so we can re-use the logic\n testGetHintTitle();\n }\n\n private void testGetHintTitle() throws Exception {\n final var hint = new ExerciseHint().title(\"Test Hint\").exercise(exercise);\n exerciseHintRepository.save(hint);\n\n final var title = request.get(\"/api/exercise-hints/\" + hint.getId() + \"/title\", HttpStatus.OK, String.class);\n assertThat(title).isEqualTo(hint.getTitle());\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void testGetHintTitleForNonExistingHint() throws Exception {\n // No hint with id 10 was created\n request.get(\"/api/exercise-hints/10/title\", HttpStatus.NOT_FOUND, String.class);\n }\n}\n" }, { "alpha_fraction": 0.6330578327178955, "alphanum_fraction": 0.6371901035308838, "avg_line_length": 33.57143020629883, "blob_id": "4fed9a19e60b7348ae65dcd844396d7d138eaff0", "content_id": "acd87adb0bb2cffc1eca22428f05abe7a08ec2f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1210, "license_type": "permissive", "max_line_length": 80, "num_lines": 35, "path": "/src/main/webapp/app/exercises/programming/manage/grading/programming-exercise-grading-table-actions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\n\n/**\n * The actions of the test case table:\n * - Save the test cases with the updated values.\n * - Reset all weights to 1.\n */\n@Component({\n selector: 'jhi-programming-exercise-grading-table-actions',\n template: `\n <button\n id=\"save-table-button\"\n class=\"btn btn-primary ml-3 my-1\"\n jhiTranslate=\"artemisApp.programmingExercise.configureGrading.save\"\n (click)=\"onSave.emit()\"\n [disabled]=\"isSaving || !hasUnsavedChanges\"\n ></button>\n <button\n id=\"reset-table-button\"\n class=\"btn btn-secondary ml-3 my-1\"\n (click)=\"onReset.emit()\"\n [disabled]=\"isSaving\"\n jhiTranslate=\"artemisApp.programmingExercise.configureGrading.reset\"\n ></button>\n `,\n})\nexport class ProgrammingExerciseGradingTableActionsComponent {\n @Input() exercise: ProgrammingExercise;\n @Input() hasUnsavedChanges: boolean;\n @Input() isSaving: boolean;\n\n @Output() onSave = new EventEmitter();\n @Output() onReset = new EventEmitter();\n}\n" }, { "alpha_fraction": 0.6490113139152527, "alphanum_fraction": 0.6504237055778503, "avg_line_length": 34.400001525878906, "blob_id": "50b40834ac1bc1eeb5d2a34a32db1d5dd05565e9", "content_id": "90bb77993c1ded5e4940456ef7caffc79b4e5a15", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1417, "license_type": "permissive", "max_line_length": 149, "num_lines": 40, "path": "/src/main/webapp/app/core/legal/privacy/privacy.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { StaticContentService } from 'app/shared/service/static-content.service';\n\nconst privacyStatementFile = 'privacy_statement.html';\n\n@Component({\n selector: 'jhi-privacy',\n template: `\n <h3 jhiTranslate=\"legal.privacy.title\">Datenschutzerklärung</h3>\n <div [innerHTML]=\"privacyStatement\"></div>\n `,\n})\nexport class PrivacyComponent implements AfterViewInit, OnInit {\n privacyStatement: SafeHtml;\n\n constructor(private route: ActivatedRoute, private staticContentService: StaticContentService) {}\n\n /**\n * On init get the privacy statement file from the Artemis server and save it.\n */\n ngOnInit(): void {\n this.staticContentService.getStaticHtmlFromArtemisServer(privacyStatementFile).subscribe((statement) => (this.privacyStatement = statement));\n }\n\n /**\n * After view initialization scroll the fragment of the current route into view.\n */\n ngAfterViewInit(): void {\n this.route.params.subscribe((params) => {\n try {\n const fragment = document.querySelector('#' + params['fragment']);\n if (fragment !== null) {\n fragment.scrollIntoView();\n }\n } catch (e) {}\n });\n }\n}\n" }, { "alpha_fraction": 0.7251198887825012, "alphanum_fraction": 0.7279577255249023, "avg_line_length": 49.589107513427734, "blob_id": "88fcd85083bcd88aea365dc72dc65f3d4ddb130d", "content_id": "d15aa5239f74db2f2469df9618a7615b3eb91ace", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10219, "license_type": "permissive", "max_line_length": 134, "num_lines": 202, "path": "/src/test/javascript/spec/component/exam/participate/exercises/quiz-exam-submission.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { Course } from 'app/entities/course.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { AnswerOption } from 'app/entities/quiz/answer-option.model';\nimport { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport { DragAndDropSubmittedAnswer } from 'app/entities/quiz/drag-and-drop-submitted-answer.model';\nimport { DragItem } from 'app/entities/quiz/drag-item.model';\nimport { DropLocation } from 'app/entities/quiz/drop-location.model';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { MultipleChoiceSubmittedAnswer } from 'app/entities/quiz/multiple-choice-submitted-answer.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { ShortAnswerSubmittedAnswer } from 'app/entities/quiz/short-answer-submitted-answer.model';\nimport { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model';\nimport { QuizExamSubmissionComponent } from 'app/exam/participate/exercises/quiz/quiz-exam-submission.component';\nimport { ArtemisQuizQuestionTypesModule } from 'app/exercises/quiz/shared/questions/artemis-quiz-question-types.module';\nimport { IncludedInScoreBadgeComponent } from 'app/exercises/shared/exercise-headers/included-in-score-badge.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ArtemisQuizService } from 'app/shared/quiz/quiz.service';\nimport * as chai from 'chai';\nimport { MockComponent, MockModule, MockPipe, MockProvider } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('QuizExamSubmissionComponent', () => {\n let fixture: ComponentFixture<QuizExamSubmissionComponent>;\n let component: QuizExamSubmissionComponent;\n\n let quizSubmission: QuizSubmission;\n let exercise: QuizExercise;\n let multipleChoiceQuestion: MultipleChoiceQuestion;\n let dragAndDropQuestion: DragAndDropQuestion;\n let shortAnswerQuestion: ShortAnswerQuestion;\n\n let quizService: any;\n\n beforeEach(() => {\n quizSubmission = new QuizSubmission();\n exercise = new QuizExercise(new Course(), new ExerciseGroup());\n multipleChoiceQuestion = new MultipleChoiceQuestion();\n multipleChoiceQuestion.id = 1;\n dragAndDropQuestion = new DragAndDropQuestion();\n dragAndDropQuestion.id = 2;\n shortAnswerQuestion = new ShortAnswerQuestion();\n shortAnswerQuestion.id = 3;\n\n return TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([]), MockModule(ArtemisQuizQuestionTypesModule), MockModule(NgbModule)],\n declarations: [QuizExamSubmissionComponent, MockPipe(ArtemisTranslatePipe), MockComponent(IncludedInScoreBadgeComponent)],\n providers: [MockProvider(ArtemisQuizService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(QuizExamSubmissionComponent);\n component = fixture.componentInstance;\n quizService = TestBed.inject(ArtemisQuizService);\n });\n });\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n const quizServiceSpy = sinon.spy(quizService, 'randomizeOrder');\n\n exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion];\n component.exercise = exercise;\n fixture.detectChanges();\n\n expect(fixture).to.be.ok;\n expect(quizServiceSpy.calledOnce);\n expect(component.selectedAnswerOptions.has(1)).to.equal(true);\n expect(component.selectedAnswerOptions.size).to.equal(1);\n expect(component.dragAndDropMappings.has(2)).to.equal(true);\n expect(component.dragAndDropMappings.size).to.equal(1);\n expect(component.shortAnswerSubmittedTexts.size).to.equal(0);\n });\n\n it('should update view from submission and fill the dictionary accordingly when submitted answer', () => {\n exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion];\n component.exercise = exercise;\n\n const multipleChoiceSubmittedAnswer = new MultipleChoiceSubmittedAnswer();\n const multipleChoiceSelectedOptions = new AnswerOption();\n multipleChoiceSelectedOptions.id = 1;\n multipleChoiceSubmittedAnswer.id = 1;\n multipleChoiceSubmittedAnswer.quizQuestion = multipleChoiceQuestion;\n multipleChoiceSubmittedAnswer.selectedOptions = [multipleChoiceSelectedOptions];\n\n const dragAndDropSubmittedAnswer = new DragAndDropSubmittedAnswer();\n const dragAndDropMapping = new DragAndDropMapping(new DragItem(), new DropLocation());\n dragAndDropMapping.id = 2;\n dragAndDropSubmittedAnswer.id = 2;\n dragAndDropSubmittedAnswer.quizQuestion = dragAndDropQuestion;\n dragAndDropSubmittedAnswer.mappings = [dragAndDropMapping];\n quizSubmission.submittedAnswers = [multipleChoiceSubmittedAnswer, dragAndDropSubmittedAnswer];\n component.studentSubmission = quizSubmission;\n\n component.updateViewFromSubmission();\n fixture.detectChanges();\n\n expect(JSON.stringify(component.selectedAnswerOptions.get(1))).to.equal(JSON.stringify([multipleChoiceSelectedOptions]));\n expect(JSON.stringify(component.dragAndDropMappings.get(2))).to.equal(JSON.stringify([dragAndDropMapping]));\n expect(component.shortAnswerSubmittedTexts.size).to.equal(0);\n\n /**\n * Test the return value of the getSubmission and getExercise\n */\n expect(component.getSubmission()).to.equal(quizSubmission);\n expect(component.getExercise()).to.equal(exercise);\n\n /**\n * Change the isSynced value of studentSubmission to false when selection changed\n */\n component.onSelectionChanged();\n expect(component.studentSubmission.isSynced).to.equal(false);\n /**\n * Return the negated value of isSynced when there are unsaved changes\n */\n expect(component.hasUnsavedChanges()).to.equal(true);\n });\n\n it('should set answerOptions/mappings/submitted texts to empty array when not submitted answer', () => {\n exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion, shortAnswerQuestion];\n component.exercise = exercise;\n\n component.updateViewFromSubmission();\n fixture.detectChanges();\n\n expect(JSON.stringify(component.selectedAnswerOptions.get(1))).to.equal(JSON.stringify([]));\n expect(component.selectedAnswerOptions.has(1)).to.equal(true);\n expect(JSON.stringify(component.dragAndDropMappings.get(2))).to.equal(JSON.stringify([]));\n expect(component.dragAndDropMappings.has(2)).to.equal(true);\n\n expect(component.shortAnswerSubmittedTexts.size).to.equal(1);\n expect(component.shortAnswerSubmittedTexts.has(3)).to.equal(true);\n });\n\n it('should trigger navigation towards the corrensponding question of the quiz', () => {\n const element = document.createElement('exam-navigation-bar');\n const getNavigationStub = stub(document, 'getElementById').returns(element);\n\n const yOffsetRect = element.getBoundingClientRect() as DOMRect;\n const yOffsetStub = stub(element, 'getBoundingClientRect').returns(yOffsetRect);\n\n const windowSpy = sinon.spy(window, 'scrollTo');\n\n component.navigateToQuestion(1);\n component.exercise = exercise;\n fixture.detectChanges();\n expect(getNavigationStub).to.have.been.called;\n expect(yOffsetStub).to.have.been.called;\n expect(windowSpy).to.have.been.called;\n });\n\n it('should create multiple choice submission from users selection ', () => {\n exercise.quizQuestions = [multipleChoiceQuestion, dragAndDropQuestion, shortAnswerQuestion];\n component.studentSubmission = new QuizSubmission();\n component.exercise = exercise;\n\n const multipleChoiceSelectedOptions = new AnswerOption();\n multipleChoiceSelectedOptions.id = 1;\n component.selectedAnswerOptions.set(1, [multipleChoiceSelectedOptions]);\n\n const dragAndDropMapping = new DragAndDropMapping(new DragItem(), new DropLocation());\n dragAndDropMapping.id = 2;\n component.dragAndDropMappings.set(2, [dragAndDropMapping]);\n\n const shortAnswerSubmittedText = new ShortAnswerSubmittedText();\n shortAnswerSubmittedText.id = 3;\n component.shortAnswerSubmittedTexts.set(3, [shortAnswerSubmittedText]);\n\n const multipleChoiceSubmittedAnswer = new MultipleChoiceSubmittedAnswer();\n multipleChoiceSubmittedAnswer.quizQuestion = multipleChoiceQuestion;\n multipleChoiceSubmittedAnswer.selectedOptions = [multipleChoiceSelectedOptions];\n\n const dragAndDropSubmittedAnswer = new DragAndDropSubmittedAnswer();\n dragAndDropSubmittedAnswer.quizQuestion = dragAndDropQuestion;\n dragAndDropSubmittedAnswer.mappings = [dragAndDropMapping];\n dragAndDropQuestion.correctMappings = [dragAndDropMapping];\n\n const shortAnswerSubmittedAnswer = new ShortAnswerSubmittedAnswer();\n shortAnswerSubmittedAnswer.quizQuestion = shortAnswerQuestion;\n shortAnswerSubmittedAnswer.submittedTexts = [shortAnswerSubmittedText];\n\n component.updateSubmissionFromView();\n fixture.detectChanges();\n\n expect(component.studentSubmission.submittedAnswers?.length).to.equal(3);\n expect(JSON.stringify(component.studentSubmission.submittedAnswers)).to.equal(\n JSON.stringify([multipleChoiceSubmittedAnswer, dragAndDropSubmittedAnswer, shortAnswerSubmittedAnswer]),\n );\n });\n});\n" }, { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.4545454680919647, "avg_line_length": 16, "blob_id": "df0b83d9ac34c9f7ba5991d13f630cb7909f450c", "content_id": "3e7e995dea4ae5c634189682315ac18e629a8c1f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 33, "license_type": "permissive", "max_line_length": 16, "num_lines": 2, "path": "/docs/user/exercises/textual.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "Textual exercise\n================" }, { "alpha_fraction": 0.6492525935173035, "alphanum_fraction": 0.6509477496147156, "avg_line_length": 40.86451721191406, "blob_id": "b06655b535a44d3422c3cc987231754d8f0e9540", "content_id": "74c3eb7556354362de8ceea2ba7fd6de350fd49a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6489, "license_type": "permissive", "max_line_length": 149, "num_lines": 155, "path": "/src/main/webapp/app/overview/student-questions/student-questions.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, Input, OnInit } from '@angular/core';\nimport { User } from 'app/core/user/user.model';\nimport * as moment from 'moment';\nimport { HttpResponse } from '@angular/common/http';\nimport { QuestionRowActionName, StudentQuestionRowAction } from 'app/overview/student-questions/student-question-row/student-question-row.component';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { StudentQuestion } from 'app/entities/student-question.model';\nimport { StudentQuestionService } from 'app/overview/student-questions/student-question/student-question.service';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command';\nimport interact from 'interactjs';\nimport { ActivatedRoute } from '@angular/router';\n\n@Component({\n selector: 'jhi-student-questions',\n templateUrl: './student-questions.component.html',\n styleUrls: ['./student-questions.scss'],\n})\nexport class StudentQuestionsComponent implements OnInit, AfterViewInit {\n @Input() exercise: Exercise;\n @Input() lecture: Lecture;\n\n studentQuestions: StudentQuestion[];\n isEditMode: boolean;\n collapsed = false;\n studentQuestionText?: string;\n selectedStudentQuestion?: StudentQuestion;\n currentUser: User;\n isAtLeastTutorInCourse: boolean;\n EditorMode = EditorMode;\n domainCommands = [new KatexCommand()];\n courseId: number;\n\n constructor(\n private route: ActivatedRoute,\n private accountService: AccountService,\n private studentQuestionService: StudentQuestionService,\n private exerciseService: ExerciseService,\n ) {}\n\n /**\n * get the current user and check if he is at least a tutor for this course\n */\n ngOnInit(): void {\n this.accountService.identity().then((user: User) => {\n this.currentUser = user;\n });\n this.loadQuestions();\n }\n\n loadQuestions() {\n if (this.exercise) {\n // in this case the student questions are preloaded\n this.studentQuestions = StudentQuestionsComponent.sortStudentQuestionsByVote(this.exercise.studentQuestions!);\n this.isAtLeastTutorInCourse = this.accountService.isAtLeastTutorInCourse(this.exercise.course!);\n this.courseId = this.exercise.course!.id!;\n } else if (this.lecture) {\n // in this case the student questions are preloaded\n this.studentQuestions = StudentQuestionsComponent.sortStudentQuestionsByVote(this.lecture.studentQuestions!);\n this.isAtLeastTutorInCourse = this.accountService.isAtLeastTutorInCourse(this.lecture.course!);\n this.courseId = this.lecture.course!.id!;\n }\n }\n\n /**\n * Configures interact to make instructions expandable\n */\n ngAfterViewInit(): void {\n interact('.expanded-questions')\n .resizable({\n edges: { left: '.draggable-left', right: false, bottom: false, top: false },\n modifiers: [\n // Set maximum width\n interact.modifiers!.restrictSize({\n min: { width: 300, height: 0 },\n max: { width: 600, height: 4000 },\n }),\n ],\n inertia: true,\n })\n .on('resizestart', function (event: any) {\n event.target.classList.add('card-resizable');\n })\n .on('resizeend', function (event: any) {\n event.target.classList.remove('card-resizable');\n })\n .on('resizemove', function (event: any) {\n const target = event.target;\n target.style.width = event.rect.width + 'px';\n });\n }\n\n /**\n * interact with actions send from studentQuestionRow\n * @param {StudentQuestionRowAction} action\n */\n interactQuestion(action: StudentQuestionRowAction) {\n switch (action.name) {\n case QuestionRowActionName.DELETE:\n this.deleteQuestionFromList(action.studentQuestion);\n break;\n case QuestionRowActionName.VOTE_CHANGE:\n this.updateQuestionAfterVoteChange(action.studentQuestion);\n break;\n }\n }\n\n /**\n * takes a studentQuestion and removes it from the list\n * @param {StudentQuestion} studentQuestion\n */\n deleteQuestionFromList(studentQuestion: StudentQuestion): void {\n this.studentQuestions = this.studentQuestions.filter((el) => el.id !== studentQuestion.id);\n }\n\n /**\n * create a new studentQuestion\n */\n addQuestion(): void {\n const studentQuestion = new StudentQuestion();\n studentQuestion.questionText = this.studentQuestionText;\n studentQuestion.author = this.currentUser;\n studentQuestion.visibleForStudents = true;\n if (this.exercise) {\n studentQuestion.exercise = Object.assign({}, this.exerciseService.convertExerciseForServer(this.exercise), {});\n } else {\n studentQuestion.lecture = Object.assign({}, this.lecture, {});\n delete studentQuestion.lecture.attachments;\n delete studentQuestion.lecture.lectureUnits;\n }\n studentQuestion.creationDate = moment();\n this.studentQuestionService.create(this.courseId, studentQuestion).subscribe((studentQuestionResponse: HttpResponse<StudentQuestion>) => {\n this.studentQuestions.push(studentQuestionResponse.body!);\n this.studentQuestionText = undefined;\n this.isEditMode = false;\n });\n }\n\n private static sortStudentQuestionsByVote(studentQuestions: StudentQuestion[]): StudentQuestion[] {\n return studentQuestions.sort((a, b) => {\n return b.votes! - a.votes!;\n });\n }\n\n private updateQuestionAfterVoteChange(studentQuestion: StudentQuestion): void {\n const indexToUpdate = this.studentQuestions.findIndex((question) => {\n return question.id === studentQuestion.id;\n });\n this.studentQuestions[indexToUpdate] = studentQuestion;\n this.studentQuestions = StudentQuestionsComponent.sortStudentQuestionsByVote(this.studentQuestions);\n }\n}\n" }, { "alpha_fraction": 0.7180248498916626, "alphanum_fraction": 0.7209941744804382, "avg_line_length": 54.109092712402344, "blob_id": "4c19deb610b0ef751a49f124be1de22934ecf143", "content_id": "ef7b3f35a6291b652540968dee8609e755b3866d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 9093, "license_type": "permissive", "max_line_length": 154, "num_lines": 165, "path": "/src/test/javascript/spec/component/exam/participate/summary/exam-participation-summary.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinon from 'sinon';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ExamParticipationSummaryComponent } from 'app/exam/participate/summary/exam-participation-summary.component';\nimport { MockComponent, MockDirective, MockModule, MockPipe } from 'ng-mocks';\nimport { TestRunRibbonComponent } from 'app/exam/manage/test-runs/test-run-ribbon.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { FontAwesomeTestingModule } from '@fortawesome/angular-fontawesome/testing';\nimport { ExamInformationComponent } from 'app/exam/participate/information/exam-information.component';\nimport { ExamPointsSummaryComponent } from 'app/exam/participate/summary/points-summary/exam-points-summary.component';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport { ResultComponent } from 'app/exercises/shared/result/result.component';\nimport { ComplaintInteractionsComponent } from 'app/complaints/complaint-interactions.component';\nimport { ProgrammingExamSummaryComponent } from 'app/exam/participate/summary/exercises/programming-exam-summary/programming-exam-summary.component';\nimport { FileUploadExamSummaryComponent } from 'app/exam/participate/summary/exercises/file-upload-exam-summary/file-upload-exam-summary.component';\nimport { QuizExamSummaryComponent } from 'app/exam/participate/summary/exercises/quiz-exam-summary/quiz-exam-summary.component';\nimport { ModelingExamSummaryComponent } from 'app/exam/participate/summary/exercises/modeling-exam-summary/modeling-exam-summary.component';\nimport { TextExamSummaryComponent } from 'app/exam/participate/summary/exercises/text-exam-summary/text-exam-summary.component';\nimport { ProgrammingExerciseInstructionComponent } from 'app/exercises/programming/shared/instructions-render/programming-exercise-instruction.component';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { HttpClientModule } from '@angular/common/http';\nimport { Exam } from 'app/entities/exam.model';\nimport { StudentExam } from 'app/entities/student-exam.model';\nimport { User } from 'app/core/user/user.model';\nimport { ActivatedRoute, convertToParamMap } from '@angular/router';\nimport { By } from '@angular/platform-browser';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { QuizSubmission } from 'app/entities/quiz/quiz-submission.model';\nimport { ModelingSubmission } from 'app/entities/modeling-submission.model';\nimport { ProgrammingSubmission } from 'app/entities/programming-submission.model';\nimport { IncludedInScoreBadgeComponent } from 'app/exercises/shared/exercise-headers/included-in-score-badge.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\nlet fixture: ComponentFixture<ExamParticipationSummaryComponent>;\nlet component: ExamParticipationSummaryComponent;\n\nconst user = { id: 1, name: 'Test User' } as User;\n\nconst visibleDate = moment().subtract(6, 'hours');\nconst startDate = moment().subtract(5, 'hours');\nconst endDate = moment().subtract(4, 'hours');\nconst publishResultsDate = moment().subtract(3, 'hours');\nconst reviewStartDate = moment().subtract(2, 'hours');\nconst reviewEndDate = moment().add(1, 'hours');\n\nconst exam = {\n id: 1,\n title: 'Test Exam',\n visibleDate,\n startDate,\n endDate,\n publishResultsDate,\n reviewStartDate,\n reviewEndDate,\n} as Exam;\n\nconst textSubmission = { id: 1, submitted: true } as TextSubmission;\nconst quizSubmission = { id: 1 } as QuizSubmission;\nconst modelingSubmission = { id: 1 } as ModelingSubmission;\nconst programmingSubmission = { id: 1 } as ProgrammingSubmission;\n\nconst textParticipation = { id: 1, student: user, submissions: [textSubmission] } as StudentParticipation;\nconst quizParticipation = { id: 2, student: user, submissions: [quizSubmission] } as StudentParticipation;\nconst modelingParticipation = { id: 3, student: user, submissions: [modelingSubmission] } as StudentParticipation;\nconst programmingParticipation = { id: 4, student: user, submissions: [programmingSubmission] } as StudentParticipation;\n\nconst textExercise = { id: 1, type: ExerciseType.TEXT, studentParticipations: [textParticipation] } as TextExercise;\nconst quizExercise = { id: 2, type: ExerciseType.QUIZ, studentParticipations: [quizParticipation] } as QuizExercise;\nconst modelingExercise = { id: 3, type: ExerciseType.MODELING, studentParticipations: [modelingParticipation] } as ModelingExercise;\nconst programmingExercise = { id: 4, type: ExerciseType.PROGRAMMING, studentParticipations: [programmingParticipation] } as ProgrammingExercise;\nconst exercises = [textExercise, quizExercise, modelingExercise, programmingExercise];\n\nconst studentExam = { id: 1, exam, user, exercises } as StudentExam;\n\nfunction sharedSetup(url: string[]) {\n beforeEach(() => {\n return TestBed.configureTestingModule({\n imports: [RouterTestingModule.withRoutes([]), FontAwesomeTestingModule, MockModule(NgbModule), HttpClientModule],\n declarations: [\n ExamParticipationSummaryComponent,\n MockComponent(TestRunRibbonComponent),\n MockComponent(ExamPointsSummaryComponent),\n MockComponent(ExamInformationComponent),\n MockComponent(ResultComponent),\n MockComponent(ProgrammingExerciseInstructionComponent),\n MockComponent(ProgrammingExamSummaryComponent),\n MockComponent(QuizExamSummaryComponent),\n MockComponent(ModelingExamSummaryComponent),\n MockComponent(TextExamSummaryComponent),\n MockComponent(FileUploadExamSummaryComponent),\n MockComponent(ComplaintInteractionsComponent),\n MockDirective(JhiTranslateDirective),\n MockPipe(ArtemisTranslatePipe),\n MockPipe(HtmlForMarkdownPipe),\n MockComponent(IncludedInScoreBadgeComponent),\n ],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n snapshot: {\n url,\n paramMap: convertToParamMap({\n courseId: '1',\n }),\n },\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ExamParticipationSummaryComponent);\n component = fixture.componentInstance;\n component.studentExam = studentExam;\n });\n });\n\n afterEach(() => {\n sinon.restore();\n });\n}\n\ndescribe('ExamParticipationSummaryComponent', () => {\n sharedSetup(['', '']);\n\n it('should expand all exercises and call print when Export PDF is clicked', fakeAsync(() => {\n const printWindowStub = sinon.stub(global.window, 'print').returns();\n fixture.detectChanges();\n const exportToPDFButton = fixture.debugElement.query(By.css('#exportToPDFButton'));\n const toggleCollapseExerciseButtonOne = fixture.debugElement.query(By.css('#toggleCollapseExerciseButton-0'));\n const toggleCollapseExerciseButtonTwo = fixture.debugElement.query(By.css('#toggleCollapseExerciseButton-1'));\n const toggleCollapseExerciseButtonThree = fixture.debugElement.query(By.css('#toggleCollapseExerciseButton-2'));\n const toggleCollapseExerciseButtonFour = fixture.debugElement.query(By.css('#toggleCollapseExerciseButton-3'));\n expect(exportToPDFButton).to.exist;\n expect(toggleCollapseExerciseButtonOne).to.exist;\n expect(toggleCollapseExerciseButtonTwo).to.exist;\n expect(toggleCollapseExerciseButtonThree).to.exist;\n expect(toggleCollapseExerciseButtonFour).to.exist;\n\n toggleCollapseExerciseButtonOne.nativeElement.click();\n toggleCollapseExerciseButtonTwo.nativeElement.click();\n toggleCollapseExerciseButtonThree.nativeElement.click();\n toggleCollapseExerciseButtonFour.nativeElement.click();\n expect(component.collapsedExerciseIds.length).to.equal(4);\n\n exportToPDFButton.nativeElement.click();\n expect(component.collapsedExerciseIds).to.be.empty;\n tick();\n sinon.assert.called(printWindowStub);\n printWindowStub.restore();\n }));\n});\n" }, { "alpha_fraction": 0.6135844588279724, "alphanum_fraction": 0.6135844588279724, "avg_line_length": 31.245399475097656, "blob_id": "fa0529a11a0db231ee1a83c95453fe62fe63782c", "content_id": "22d8f275351215f86b0e69cdfa06ace64ba28dfb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5256, "license_type": "permissive", "max_line_length": 99, "num_lines": 163, "path": "/src/test/javascript/spec/component/shared/button.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { DebugElement } from '@angular/core';\nimport { SinonSpy, spy } from 'sinon';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service';\nimport { ButtonComponent } from 'app/shared/components/button.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ButtonComponent', () => {\n let comp: ButtonComponent;\n let fixture: ComponentFixture<ButtonComponent>;\n let debugElement: DebugElement;\n\n let clickSpy: SinonSpy;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedComponentModule],\n providers: [\n JhiLanguageHelper,\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ButtonComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n\n clickSpy = spy(comp.onClick, 'emit');\n });\n });\n\n const getButton = () => {\n const button = debugElement.query(By.css(`.jhi-btn`));\n return button ? button.nativeElement : null;\n };\n\n const getTitle = () => {\n const title = debugElement.query(By.css(`.jhi-btn > .jhi-btn__title`));\n return title ? title.nativeElement : null;\n };\n\n const getIcon = () => {\n const icon = debugElement.query(By.css('.jhi-btn > .jhi-btn__icon'));\n return icon ? icon.nativeElement : null;\n };\n\n const getLoading = () => {\n const loadingIcon = debugElement.query(By.css('.jhi-btn > .jhi-btn__loading'));\n return loadingIcon ? loadingIcon.nativeElement : null;\n };\n\n it('should render button with icon and title', () => {\n comp.title = 'artemisApp.title.test';\n comp.icon = 'redo';\n\n fixture.detectChanges();\n\n const title = getTitle();\n expect(title).to.exist;\n\n const icon = getIcon();\n expect(icon).to.exist;\n\n const loadingIcon = getLoading();\n expect(loadingIcon).not.to.exist;\n });\n\n it('should render button without icon and with title', () => {\n comp.title = 'artemisApp.title.test';\n\n fixture.detectChanges();\n\n const title = getTitle();\n expect(title).to.exist;\n\n const icon = getIcon();\n expect(icon).not.to.exist;\n\n const loadingIcon = getLoading();\n expect(loadingIcon).not.to.exist;\n });\n\n it('should render button with icon and without title', () => {\n comp.icon = 'redo';\n\n fixture.detectChanges();\n\n const title = getTitle();\n expect(title).not.to.exist;\n\n const icon = getIcon();\n expect(icon).to.exist;\n\n const loadingIcon = getLoading();\n expect(loadingIcon).not.to.exist;\n });\n\n it('should disable complete button if disabled is set', async () => {\n comp.title = 'artemisApp.title.test';\n comp.icon = 'redo';\n comp.disabled = true;\n\n fixture.detectChanges();\n\n const button = getButton();\n expect(button).to.exist;\n expect(button.disabled).to.be.true;\n button.click();\n await fixture.whenStable();\n\n expect(clickSpy).to.not.have.been.called;\n });\n\n it('should enable complete button if disabled is set to false', async () => {\n comp.title = 'artemisApp.title.test';\n comp.icon = 'redo';\n comp.disabled = false;\n\n fixture.detectChanges();\n\n const button = getButton();\n expect(button).to.exist;\n expect(button.disabled).to.be.false;\n button.click();\n await fixture.whenStable();\n\n expect(clickSpy).to.have.been.called;\n });\n\n it('should show loading indicator when loading is set', async () => {\n comp.title = 'artemisApp.title.test';\n comp.icon = 'redo';\n comp.isLoading = true;\n\n fixture.detectChanges();\n\n const button = getButton();\n expect(button).to.exist;\n expect(button.disabled).to.be.true;\n const loadingIcon = getLoading();\n expect(loadingIcon).to.exist;\n\n button.click();\n await fixture.whenStable();\n\n expect(clickSpy).to.not.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.7343671917915344, "alphanum_fraction": 0.7348674535751343, "avg_line_length": 24.96103858947754, "blob_id": "dfd1068a3a8ca4292b04c8d82b4a5bb7f66291d5", "content_id": "2b6c9b7acc1024925f1419d36a503feca0b99722", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1999, "license_type": "permissive", "max_line_length": 95, "num_lines": 77, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/dto/CourseExerciseStatisticsDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest.dto;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class CourseExerciseStatisticsDTO {\n\n private Long exerciseId;\n\n private String exerciseTitle;\n\n private String exerciseMode;\n\n private Double exerciseMaxPoints;\n\n private Double averageScoreInPercent;\n\n private Integer noOfParticipatingStudentsOrTeams;\n\n private Double participationRateInPercent;\n\n public Long getExerciseId() {\n return exerciseId;\n }\n\n public void setExerciseId(Long exerciseId) {\n this.exerciseId = exerciseId;\n }\n\n public String getExerciseTitle() {\n return exerciseTitle;\n }\n\n public void setExerciseTitle(String exerciseTitle) {\n this.exerciseTitle = exerciseTitle;\n }\n\n public String getExerciseMode() {\n return exerciseMode;\n }\n\n public void setExerciseMode(String exerciseMode) {\n this.exerciseMode = exerciseMode;\n }\n\n public Double getExerciseMaxPoints() {\n return exerciseMaxPoints;\n }\n\n public void setExerciseMaxPoints(Double exerciseMaxPoints) {\n this.exerciseMaxPoints = exerciseMaxPoints;\n }\n\n public Double getAverageScoreInPercent() {\n return averageScoreInPercent;\n }\n\n public void setAverageScoreInPercent(Double averageScoreInPercent) {\n this.averageScoreInPercent = averageScoreInPercent;\n }\n\n public Integer getNoOfParticipatingStudentsOrTeams() {\n return noOfParticipatingStudentsOrTeams;\n }\n\n public void setNoOfParticipatingStudentsOrTeams(Integer noOfParticipatingStudentsOrTeams) {\n this.noOfParticipatingStudentsOrTeams = noOfParticipatingStudentsOrTeams;\n }\n\n public Double getParticipationRateInPercent() {\n return participationRateInPercent;\n }\n\n public void setParticipationRateInPercent(Double participationRateInPercent) {\n this.participationRateInPercent = participationRateInPercent;\n }\n}\n" }, { "alpha_fraction": 0.7143147587776184, "alphanum_fraction": 0.7217243313789368, "avg_line_length": 60.72703170776367, "blob_id": "820c9af6f71d3ae800ed624aa0e26b7cfaa45309", "content_id": "dcdacf5b68dac90b40057f49bfd4b18049e09bad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 93393, "license_type": "permissive", "max_line_length": 180, "num_lines": 1513, "path": "/src/test/java/de/tum/in/www1/artemis/util/CourseTestService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.util;\n\nimport static de.tum.in.www1.artemis.config.Constants.ARTEMIS_GROUP_DEFAULT_PREFIX;\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.awaitility.Awaitility.await;\n\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.time.Instant;\nimport java.time.ZonedDateTime;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.actuate.audit.AuditEvent;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.stereotype.Service;\nimport org.springframework.util.LinkedMultiValueMap;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingSubmission;\nimport de.tum.in.www1.artemis.domain.participation.*;\nimport de.tum.in.www1.artemis.domain.quiz.QuizExercise;\nimport de.tum.in.www1.artemis.programmingexercise.MockDelegate;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.GroupNotificationService;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseManagementOverviewStatisticsDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.StatsForDashboardDTO;\n\n@Service\npublic class CourseTestService {\n\n @Autowired\n private DatabaseUtilService database;\n\n @Autowired\n private CourseRepository courseRepo;\n\n @Autowired\n private ExerciseRepository exerciseRepo;\n\n @Autowired\n private LectureRepository lectureRepo;\n\n @Autowired\n private ResultRepository resultRepo;\n\n @Autowired\n private CustomAuditEventRepository auditEventRepo;\n\n @Autowired\n private UserRepository userRepo;\n\n @Autowired\n private NotificationRepository notificationRepo;\n\n @Autowired\n private ExamRepository examRepo;\n\n @Autowired\n private ProgrammingExerciseRepository programmingExerciseRepository;\n\n @Autowired\n private RequestUtilService request;\n\n @Autowired\n private ZipFileTestUtilService zipFileTestUtilService;\n\n @Autowired\n private SubmissionRepository submissionRepository;\n\n private final int numberOfStudents = 8;\n\n private final int numberOfTutors = 5;\n\n private final int numberOfInstructors = 1;\n\n private MockDelegate mockDelegate;\n\n private GroupNotificationService groupNotificationService;\n\n public void setup(MockDelegate mockDelegate, GroupNotificationService groupNotificationService) {\n this.mockDelegate = mockDelegate;\n this.groupNotificationService = groupNotificationService;\n\n database.addUsers(numberOfStudents, numberOfTutors, numberOfInstructors);\n\n // Add users that are not in the course\n userRepo.save(ModelFactory.generateActivatedUser(\"tutor6\"));\n userRepo.save(ModelFactory.generateActivatedUser(\"instructor2\"));\n }\n\n public void tearDown() {\n database.resetDatabase();\n }\n\n public CourseRepository getCourseRepo() {\n return courseRepo;\n }\n\n // Test\n public void testCreateCourseWithPermission() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n\n request.post(\"/api/courses\", course, HttpStatus.CREATED);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course got stored\").isEqualTo(1);\n\n course = ModelFactory.generateCourse(1L, null, null, new HashSet<>());\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n assertThat(courseRepo.findAll()).as(\"Course has not been stored\").contains(repoContent.toArray(new Course[0]));\n }\n\n // Test\n public void testCreateCourseWithSameShortName() throws Exception {\n Course course1 = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n course1.setShortName(\"shortName\");\n mockDelegate.mockCreateGroupInUserManagement(course1.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course1.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course1.getDefaultInstructorGroupName());\n\n request.post(\"/api/courses\", course1, HttpStatus.CREATED);\n assertThat(courseRepo.findAll().size()).as(\"Course got stored\").isEqualTo(1);\n\n Course course2 = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course2.setShortName(\"shortName\");\n request.post(\"/api/courses\", course2, HttpStatus.BAD_REQUEST);\n assertThat(courseRepo.findAll().size()).as(\"Course has not been stored\").isEqualTo(1);\n }\n\n // Test\n public void testCreateCourseWithNegativeMaxComplainNumber() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n course.setMaxComplaints(-1);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n }\n\n // Test\n public void testCreateCourseWithNegativeMaxComplainTimeDays() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n course.setMaxComplaintTimeDays(-1);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n }\n\n // Test\n public void testCreateCourseWithNegativeMaxTeamComplainNumber() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n course.setMaxTeamComplaints(-1);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n }\n\n // Test\n public void testCreateCourseWithModifiedMaxComplainTimeDaysAndMaxComplains() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n course.setMaxComplaintTimeDays(0);\n course.setMaxComplaints(1);\n course.setMaxTeamComplaints(0);\n course.setMaxRequestMoreFeedbackTimeDays(0);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n\n // change configuration\n course.setMaxComplaintTimeDays(1);\n course.setMaxComplaints(0);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n\n // change configuration again\n course.setMaxComplaintTimeDays(0);\n course.setMaxRequestMoreFeedbackTimeDays(-1);\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course has not been stored\").isEqualTo(0);\n }\n\n // Test\n public void testCreateCourseWithCustomNonExistingGroupNames() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n course.setStudentGroupName(\"StudentGroupName\");\n course.setTeachingAssistantGroupName(\"TeachingAssistantGroupName\");\n course.setInstructorGroupName(\"InstructorGroupName\");\n request.post(\"/api/courses\", course, HttpStatus.CREATED);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course got stored\").isEqualTo(1);\n }\n\n // Test\n public void testCreateCourseWithOptions() throws Exception {\n // Generate POST Request Body with maxComplaints = 5, maxComplaintTimeDays = 14, studentQuestionsEnabled = false\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), null, null, null, 5, 5, 14, false, 0);\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n course = request.postWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.CREATED);\n // Because the courseId is automatically generated we cannot use the findById method to retrieve the saved course.\n Course getFromRepo = courseRepo.findAll().get(0);\n assertThat(getFromRepo.getMaxComplaints()).as(\"Course has right maxComplaints Value\").isEqualTo(5);\n assertThat(getFromRepo.getMaxComplaintTimeDays()).as(\"Course has right maxComplaintTimeDays Value\").isEqualTo(14);\n assertThat(getFromRepo.getStudentQuestionsEnabled()).as(\"Course has right studentQuestionsEnabled Value\").isFalse();\n assertThat(getFromRepo.getRequestMoreFeedbackEnabled()).as(\"Course has right requestMoreFeedbackEnabled Value\").isFalse();\n\n // Test edit course\n course.setId(getFromRepo.getId());\n course.setMaxComplaints(1);\n course.setMaxComplaintTimeDays(7);\n course.setStudentQuestionsEnabled(true);\n course.setMaxRequestMoreFeedbackTimeDays(7);\n Course updatedCourse = request.putWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.OK);\n assertThat(updatedCourse.getMaxComplaints()).as(\"maxComplaints Value updated successfully\").isEqualTo(course.getMaxComplaints());\n assertThat(updatedCourse.getMaxComplaintTimeDays()).as(\"maxComplaintTimeDays Value updated successfully\").isEqualTo(course.getMaxComplaintTimeDays());\n assertThat(updatedCourse.getStudentQuestionsEnabled()).as(\"studentQuestionsEnabled Value updated successfully\").isTrue();\n assertThat(updatedCourse.getRequestMoreFeedbackEnabled()).as(\"Course has right requestMoreFeedbackEnabled Value\").isTrue();\n }\n\n // Test\n public void testDeleteCourseWithPermission() throws Exception {\n // add to new list so that we can add another course with ARTEMIS_GROUP_DEFAULT_PREFIX so that delete group will be tested properly\n List<Course> courses = new ArrayList<>(database.createCoursesWithExercisesAndLectures(true));\n Course course3 = ModelFactory.generateCourse(null, ZonedDateTime.now().minusDays(8), ZonedDateTime.now().minusDays(4), new HashSet<>(), null, null, null);\n course3.setStudentGroupName(course3.getDefaultStudentGroupName());\n course3.setTeachingAssistantGroupName(course3.getDefaultTeachingAssistantGroupName());\n course3.setInstructorGroupName(course3.getDefaultInstructorGroupName());\n course3 = courseRepo.save(course3);\n courses.add(course3);\n database.addExamWithExerciseGroup(courses.get(0), true);\n // mock certain requests to JIRA Bitbucket and Bamboo\n for (Course course : courses) {\n if (course.getStudentGroupName().startsWith(ARTEMIS_GROUP_DEFAULT_PREFIX)) {\n mockDelegate.mockDeleteGroupInUserManagement(course.getStudentGroupName());\n }\n if (course.getTeachingAssistantGroupName().startsWith(ARTEMIS_GROUP_DEFAULT_PREFIX)) {\n mockDelegate.mockDeleteGroupInUserManagement(course.getTeachingAssistantGroupName());\n }\n if (course.getInstructorGroupName().startsWith(ARTEMIS_GROUP_DEFAULT_PREFIX)) {\n mockDelegate.mockDeleteGroupInUserManagement(course.getInstructorGroupName());\n }\n for (Exercise exercise : course.getExercises()) {\n if (exercise instanceof ProgrammingExercise) {\n final var programmingExercise = (ProgrammingExercise) exercise;\n final String projectKey = programmingExercise.getProjectKey();\n final var templateRepoName = programmingExercise.generateRepositoryName(RepositoryType.TEMPLATE);\n final var solutionRepoName = programmingExercise.generateRepositoryName(RepositoryType.SOLUTION);\n final var testsRepoName = programmingExercise.generateRepositoryName(RepositoryType.TESTS);\n database.addSolutionParticipationForProgrammingExercise(programmingExercise);\n database.addTemplateParticipationForProgrammingExercise(programmingExercise);\n mockDelegate.mockDeleteBuildPlan(projectKey, programmingExercise.getTemplateBuildPlanId(), false);\n mockDelegate.mockDeleteBuildPlan(projectKey, programmingExercise.getSolutionBuildPlanId(), false);\n mockDelegate.mockDeleteBuildPlanProject(projectKey, false);\n mockDelegate.mockDeleteRepository(projectKey, templateRepoName, false);\n mockDelegate.mockDeleteRepository(projectKey, solutionRepoName, false);\n mockDelegate.mockDeleteRepository(projectKey, testsRepoName, false);\n mockDelegate.mockDeleteProjectInVcs(projectKey, false);\n }\n }\n }\n\n for (Course course : courses) {\n if (!course.getExercises().isEmpty()) {\n groupNotificationService.notifyStudentGroupAboutExerciseUpdate(course.getExercises().iterator().next(), \"notify\");\n }\n request.delete(\"/api/courses/\" + course.getId(), HttpStatus.OK);\n }\n assertThat(courseRepo.findAll()).as(\"All courses deleted\").hasSize(0);\n assertThat(notificationRepo.findAll()).as(\"All notifications are deleted\").isEmpty();\n assertThat(examRepo.findAll()).as(\"All exams are deleted\").isEmpty();\n assertThat(exerciseRepo.findAll()).as(\"All Exercises are deleted\").isEmpty();\n assertThat(lectureRepo.findAll()).as(\"All Lectures are deleted\").isEmpty();\n }\n\n // Test\n public void testDeleteNotExistingCourse() throws Exception {\n request.delete(\"/api/courses/1\", HttpStatus.NOT_FOUND);\n }\n\n // Test\n public void testCreateCourseWithoutPermission() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n request.post(\"/api/courses\", course, HttpStatus.FORBIDDEN);\n assertThat(courseRepo.findAll().size()).as(\"Course got stored\").isEqualTo(0);\n }\n\n // Test\n public void testCreateCourseWithWrongShortName() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n course.setShortName(\"`badName~\");\n request.post(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n }\n\n // Test\n public void testUpdateCourseWithWrongShortName() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n course.setShortName(\"`badName~\");\n courseRepo.save(course);\n request.put(\"/api/courses\", course, HttpStatus.BAD_REQUEST);\n }\n\n // Test\n public void testUpdateCourseWithoutId() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>());\n\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultStudentGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultTeachingAssistantGroupName());\n mockDelegate.mockCreateGroupInUserManagement(course.getDefaultInstructorGroupName());\n request.put(\"/api/courses\", course, HttpStatus.CREATED);\n List<Course> repoContent = courseRepo.findAll();\n assertThat(repoContent.size()).as(\"Course got stored\").isEqualTo(1);\n }\n\n // Test\n public void testUpdateCourseIsEmpty() throws Exception {\n Course course = ModelFactory.generateCourse(1L, null, null, new HashSet<>());\n request.put(\"/api/courses\", course, HttpStatus.NOT_FOUND);\n }\n\n // Test\n public void testEditCourseWithPermission() throws Exception {\n\n Course course = ModelFactory.generateCourse(1L, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n\n course.setTitle(\"Test Course\");\n course.setStartDate(ZonedDateTime.now().minusDays(5));\n course.setEndDate(ZonedDateTime.now().plusDays(5));\n Course updatedCourse = request.putWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.OK);\n assertThat(updatedCourse.getShortName()).as(\"short name was changed correctly\").isEqualTo(course.getShortName());\n assertThat(updatedCourse.getTitle()).as(\"title was changed correctly\").isEqualTo(course.getTitle());\n assertThat(updatedCourse.getStartDate()).as(\"start date was changed correctly\").isEqualTo(course.getStartDate());\n assertThat(updatedCourse.getEndDate()).as(\"end date was changed correctly\").isEqualTo(course.getEndDate());\n }\n\n // Test\n public void testUpdateCourseGroups() throws Exception {\n Course course = database.addCourseWithOneProgrammingExercise();\n var oldInstructorGroup = course.getInstructorGroupName();\n var oldTeachingAssistantGroup = course.getTeachingAssistantGroupName();\n\n course.setInstructorGroupName(\"new-instructor-group\");\n course.setTeachingAssistantGroupName(\"new-ta-group\");\n\n mockDelegate.mockUpdateCoursePermissions(course, oldInstructorGroup, oldTeachingAssistantGroup);\n Course updatedCourse = request.putWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.OK);\n\n assertThat(updatedCourse.getInstructorGroupName()).isEqualTo(\"new-instructor-group\");\n assertThat(updatedCourse.getTeachingAssistantGroupName()).isEqualTo(\"new-ta-group\");\n }\n\n // Test\n public void testUpdateCourseGroups_InExternalCiUserManagement_failToRemoveUser() throws Exception {\n Course course = database.addCourseWithOneProgrammingExercise();\n var oldInstructorGroup = course.getInstructorGroupName();\n var oldTeachingAssistantGroup = course.getTeachingAssistantGroupName();\n\n course.setInstructorGroupName(\"new-instructor-group\");\n course.setTeachingAssistantGroupName(\"new-ta-group\");\n\n mockDelegate.mockFailUpdateCoursePermissionsInCi(course, oldInstructorGroup, oldTeachingAssistantGroup, false, true);\n Course updatedCourse = request.putWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.INTERNAL_SERVER_ERROR);\n\n assertThat(updatedCourse).isNull();\n }\n\n // Test\n public void testUpdateCourseGroups_InExternalCiUserManagement_failToAddUser() throws Exception {\n Course course = database.addCourseWithOneProgrammingExercise();\n var oldInstructorGroup = course.getInstructorGroupName();\n var oldTeachingAssistantGroup = course.getTeachingAssistantGroupName();\n\n course.setInstructorGroupName(\"new-instructor-group\");\n course.setTeachingAssistantGroupName(\"new-ta-group\");\n\n mockDelegate.mockFailUpdateCoursePermissionsInCi(course, oldInstructorGroup, oldTeachingAssistantGroup, true, false);\n Course updatedCourse = request.putWithResponseBody(\"/api/courses\", course, Course.class, HttpStatus.INTERNAL_SERVER_ERROR);\n\n assertThat(updatedCourse).isNull();\n }\n\n // Test\n public void testGetCourseWithoutPermission() throws Exception {\n request.getList(\"/api/courses\", HttpStatus.FORBIDDEN, Course.class);\n }\n\n // Test\n public void testGetCourse_tutorNotInCourse() throws Exception {\n var courses = database.createCoursesWithExercisesAndLectures(true);\n request.getList(\"/api/courses/\" + courses.get(0).getId(), HttpStatus.FORBIDDEN, Course.class);\n request.get(\"/api/courses/\" + courses.get(0).getId() + \"/with-exercises\", HttpStatus.FORBIDDEN, Course.class);\n }\n\n // Test\n public void testGetCourseWithExercisesAndRelevantParticipationsWithoutPermissions() throws Exception {\n var courses = database.createCoursesWithExercisesAndLectures(true);\n request.get(\"/api/courses/\" + courses.get(0).getId() + \"/with-exercises-and-relevant-participations\", HttpStatus.FORBIDDEN, Course.class);\n }\n\n // Test\n public void testGetCoursesWithPermission() throws Exception {\n database.createCoursesWithExercisesAndLectures(true);\n List<Course> courses = request.getList(\"/api/courses\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).as(\"All courses are available\").isEqualTo(2);\n for (Exercise exercise : courses.get(0).getExercises()) {\n assertThat(exercise.getGradingInstructions()).as(\"Grading instructions are not filtered out\").isNotNull();\n assertThat(exercise.getProblemStatement()).as(\"Problem statements are not filtered out\").isNotNull();\n }\n }\n\n // Test\n public void testGetCoursesWithQuizExercises() throws Exception {\n database.createCoursesWithExercisesAndLectures(true);\n List<Course> courses = request.getList(\"/api/courses/courses-with-quiz\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).as(\"All courses are available\").isEqualTo(1);\n for (Exercise exercise : courses.get(0).getExercises()) {\n assertThat(exercise.getGradingInstructions()).as(\"Grading instructions are filtered out\").isNull();\n assertThat(exercise.getProblemStatement()).as(\"Problem statements are filtered out\").isNull();\n }\n }\n\n // Test\n public void testGetCourseForDashboard() throws Exception {\n List<Course> courses = database.createCoursesWithExercisesAndLecturesAndLectureUnits(true);\n Course receivedCourse = request.get(\"/api/courses/\" + courses.get(0).getId() + \"/for-dashboard\", HttpStatus.OK, Course.class);\n\n // Test that the received course has five exercises\n assertThat(receivedCourse.getExercises().size()).as(\"Five exercises are returned\").isEqualTo(5);\n // Test that the received course has two lectures\n assertThat(receivedCourse.getLectures().size()).as(\"Two lectures are returned\").isEqualTo(2);\n\n // Iterate over all exercises of the remaining course\n for (Exercise exercise : courses.get(0).getExercises()) {\n // Test that the exercise does not have more than one participation.\n assertThat(exercise.getStudentParticipations().size()).as(\"At most one participation for exercise\").isLessThanOrEqualTo(1);\n if (exercise.getStudentParticipations().size() > 0) {\n // Buffer participation so that null checking is easier.\n Participation participation = exercise.getStudentParticipations().iterator().next();\n if (participation.getSubmissions().size() > 0) {\n // The call filters participations by submissions and their result. After the call each participation shouldn't have more than one submission.\n assertThat(participation.getSubmissions().size()).as(\"At most one submission for participation\").isLessThanOrEqualTo(1);\n Submission submission = participation.getSubmissions().iterator().next();\n if (submission != null) {\n // Test that the correct text submission was filtered.\n if (submission instanceof TextSubmission) {\n TextSubmission textSubmission = (TextSubmission) submission;\n assertThat(textSubmission.getText()).as(\"Correct text submission\").isEqualTo(\"text\");\n }\n // Test that the correct modeling submission was filtered.\n if (submission instanceof ModelingSubmission) {\n ModelingSubmission modelingSubmission = (ModelingSubmission) submission;\n assertThat(modelingSubmission.getModel()).as(\"Correct modeling submission\").isEqualTo(\"model1\");\n }\n }\n }\n }\n }\n }\n\n // Test\n public void testGetAllCoursesForDashboard() throws Exception {\n database.createCoursesWithExercisesAndLecturesAndLectureUnits(true);\n\n // Perform the request that is being tested here\n List<Course> courses = request.getList(\"/api/courses/for-dashboard\", HttpStatus.OK, Course.class);\n\n // Test that the prepared inactive course was filtered out\n assertThat(courses.size()).as(\"Inactive course was filtered out\").isEqualTo(1);\n\n // Test that the remaining course has five exercises\n assertThat(courses.get(0).getExercises().size()).as(\"Five exercises are returned\").isEqualTo(5);\n\n // Iterate over all exercises of the remaining course\n for (Exercise exercise : courses.get(0).getExercises()) {\n // Test that the exercise does not have more than one participation.\n assertThat(exercise.getStudentParticipations().size()).as(\"At most one participation for exercise\").isLessThanOrEqualTo(1);\n if (exercise.getStudentParticipations().size() > 0) {\n // Buffer participation so that null checking is easier.\n Participation participation = exercise.getStudentParticipations().iterator().next();\n if (participation.getSubmissions().size() > 0) {\n // The call filters participations by submissions and their result. After the call each participation shouldn't have more than one submission.\n assertThat(participation.getSubmissions().size()).as(\"At most one submission for participation\").isLessThanOrEqualTo(1);\n Submission submission = participation.getSubmissions().iterator().next();\n if (submission != null) {\n // Test that the correct text submission was filtered.\n if (submission instanceof TextSubmission) {\n TextSubmission textSubmission = (TextSubmission) submission;\n assertThat(textSubmission.getText()).as(\"Correct text submission\").isEqualTo(\"text\");\n }\n // Test that the correct modeling submission was filtered.\n if (submission instanceof ModelingSubmission) {\n ModelingSubmission modelingSubmission = (ModelingSubmission) submission;\n assertThat(modelingSubmission.getModel()).as(\"Correct modeling submission\").isEqualTo(\"model1\");\n }\n }\n }\n }\n }\n }\n\n // Test\n public void testGetCoursesWithoutActiveExercises() throws Exception {\n Course course = ModelFactory.generateCourse(1L, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n courseRepo.save(course);\n List<Course> courses = request.getList(\"/api/courses/for-dashboard\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).as(\"Only one course is returned\").isEqualTo(1);\n assertThat(courses.stream().findFirst().get().getExercises().size()).as(\"Course doesn't have any exercises\").isEqualTo(0);\n }\n\n // Test\n public void testGetCoursesAccurateTimezoneEvaluation() throws Exception {\n Course courseActive = ModelFactory.generateCourse(1L, ZonedDateTime.now().minusMinutes(25), ZonedDateTime.now().plusMinutes(25), new HashSet<>(), \"tumuser\", \"tutor\",\n \"instructor\");\n Course courseNotActivePast = ModelFactory.generateCourse(2L, ZonedDateTime.now().minusDays(5), ZonedDateTime.now().minusMinutes(25), new HashSet<>(), \"tumuser\", \"tutor\",\n \"instructor\");\n Course courseNotActiveFuture = ModelFactory.generateCourse(3L, ZonedDateTime.now().plusMinutes(25), ZonedDateTime.now().plusDays(5), new HashSet<>(), \"tumuser\", \"tutor\",\n \"instructor\");\n courseActive = courseRepo.save(courseActive);\n courseRepo.save(courseNotActivePast);\n courseRepo.save(courseNotActiveFuture);\n List<Course> courses = request.getList(\"/api/courses/for-dashboard\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).as(\"Exactly one course is returned\").isEqualTo(1);\n assertThat(courses.get(0)).as(\"Active course is returned\").isEqualTo(courseActive);\n List<Course> coursesForNotifications = request.getList(\"/api/courses/for-notifications\", HttpStatus.OK, Course.class);\n assertThat(coursesForNotifications.size()).as(\"Exactly one course is returned\").isEqualTo(1);\n assertThat(coursesForNotifications.get(0)).as(\"Active course is returned\").isEqualTo(courseActive);\n }\n\n // Test\n public void testGetCourseWithOrganizations() throws Exception {\n Course courseWithOrganization = database.createCourseWithOrganizations();\n Course course = request.get(\"/api/courses/\" + courseWithOrganization.getId() + \"/with-organizations\", HttpStatus.OK, Course.class);\n assertThat(course.getOrganizations()).isEqualTo(courseWithOrganization.getOrganizations());\n assertThat(course.getOrganizations()).isNotEmpty();\n }\n\n // Test\n public void testGetAllCoursesWithUserStats() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n List<Course> receivedCourse = request.getList(\"/api/courses/with-user-stats\", HttpStatus.OK, Course.class);\n assertThat(testCourses).isEqualTo(receivedCourse);\n assertThat(receivedCourse.get(0).getNumberOfStudents()).isEqualTo(numberOfStudents);\n assertThat(receivedCourse.get(0).getNumberOfTeachingAssistants()).isEqualTo(numberOfTutors);\n assertThat(receivedCourse.get(0).getNumberOfInstructors()).isEqualTo(numberOfInstructors);\n }\n\n // Test\n public void testGetCoursesToRegisterAndAccurateTimeZoneEvaluation() throws Exception {\n Course courseActiveRegistrationEnabled = ModelFactory.generateCourse(1L, ZonedDateTime.now().minusMinutes(25), ZonedDateTime.now().plusMinutes(25), new HashSet<>(),\n \"tumuser\", \"tutor\", \"instructor\");\n courseActiveRegistrationEnabled.setRegistrationEnabled(true);\n Course courseActiveRegistrationDisabled = ModelFactory.generateCourse(2L, ZonedDateTime.now().minusMinutes(25), ZonedDateTime.now().plusMinutes(25), new HashSet<>(),\n \"tumuser\", \"tutor\", \"instructor\");\n courseActiveRegistrationDisabled.setRegistrationEnabled(false);\n Course courseNotActivePast = ModelFactory.generateCourse(3L, ZonedDateTime.now().minusDays(5), ZonedDateTime.now().minusMinutes(25), new HashSet<>(), \"tumuser\", \"tutor\",\n \"instructor\");\n Course courseNotActiveFuture = ModelFactory.generateCourse(4L, ZonedDateTime.now().plusMinutes(25), ZonedDateTime.now().plusDays(5), new HashSet<>(), \"tumuser\", \"tutor\",\n \"instructor\");\n courseRepo.save(courseActiveRegistrationEnabled);\n courseRepo.save(courseActiveRegistrationDisabled);\n courseRepo.save(courseNotActivePast);\n courseRepo.save(courseNotActiveFuture);\n\n List<Course> courses = request.getList(\"/api/courses/to-register\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).as(\"Exactly one course is available to register\").isEqualTo(1);\n courses.get(0).setId(courseActiveRegistrationEnabled.getId());\n assertThat(courses.get(0)).as(\"Only active course is returned\").isEqualTo(courseActiveRegistrationEnabled);\n }\n\n private void getCourseForDashboardWithStats(boolean isInstructor) throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n for (Course testCourse : testCourses) {\n Course course = request.get(\"/api/courses/\" + testCourse.getId() + \"/for-assessment-dashboard\", HttpStatus.OK, Course.class);\n for (Exercise exercise : course.getExercises()) {\n assertThat(exercise.getTotalNumberOfAssessments().getInTime()).as(\"Number of in-time assessments is correct\").isZero();\n assertThat(exercise.getTotalNumberOfAssessments().getLate()).as(\"Number of late assessments is correct\").isZero();\n assertThat(exercise.getTutorParticipations().size()).as(\"Tutor participation was created\").isEqualTo(1);\n // Mock data contains exactly two submissions for the modeling exercise\n if (exercise instanceof ModelingExercise) {\n assertThat(exercise.getNumberOfSubmissions().getInTime()).as(\"Number of in-time submissions is correct\").isEqualTo(2);\n }\n // Mock data contains exactly one submission for the text exercise\n if (exercise instanceof TextExercise) {\n assertThat(exercise.getNumberOfSubmissions().getInTime()).as(\"Number of in-time submissions is correct\").isEqualTo(1);\n }\n // Mock data contains no submissions for the file upload and programming exercise\n if (exercise instanceof FileUploadExercise || exercise instanceof ProgrammingExercise) {\n assertThat(exercise.getNumberOfSubmissions().getInTime()).as(\"Number of in-time submissions is correct\").isEqualTo(0);\n }\n\n assertThat(exercise.getNumberOfSubmissions().getLate()).as(\"Number of late submissions is correct\").isEqualTo(0);\n assertThat(exercise.getNumberOfAssessmentsOfCorrectionRounds().length).isEqualTo(1L);\n assertThat(exercise.getNumberOfAssessmentsOfCorrectionRounds()[0].getInTime()).isEqualTo(0L);\n // Check tutor participation\n if (exercise.getTutorParticipations().size() > 0) {\n TutorParticipation tutorParticipation = exercise.getTutorParticipations().iterator().next();\n assertThat(tutorParticipation.getStatus()).as(\"Tutor participation status is correctly initialized\").isEqualTo(TutorParticipationStatus.NOT_PARTICIPATED);\n }\n }\n\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n long numberOfInTimeSubmissions = course.getId().equals(testCourses.get(0).getId()) ? 3 : 0; // course 1 has 3 submissions, course 2 has 0 submissions\n assertThat(stats.getNumberOfSubmissions().getInTime()).as(\"Number of in-time submissions is correct\").isEqualTo(numberOfInTimeSubmissions);\n assertThat(stats.getNumberOfSubmissions().getLate()).as(\"Number of latte submissions is correct\").isEqualTo(0);\n assertThat(stats.getTotalNumberOfAssessments().getInTime()).as(\"Number of in-time assessments is correct\").isEqualTo(0);\n assertThat(stats.getTotalNumberOfAssessments().getLate()).as(\"Number of late assessments is correct\").isEqualTo(0);\n assertThat(stats.getNumberOfAssessmentsOfCorrectionRounds().length).isEqualTo(1L);\n assertThat(stats.getNumberOfAssessmentsOfCorrectionRounds()[0].getInTime()).isEqualTo(0L);\n assertThat(stats.getTutorLeaderboardEntries().size()).as(\"Number of tutor leaderboard entries is correct\").isEqualTo(5);\n\n StatsForDashboardDTO stats2 = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-instructor-dashboard\", isInstructor ? HttpStatus.OK : HttpStatus.FORBIDDEN,\n StatsForDashboardDTO.class);\n\n if (!isInstructor) {\n assertThat(stats2).as(\"Stats for instructor are not available to tutor\").isNull();\n }\n else {\n assertThat(stats2).as(\"Stats are available for instructor\").isNotNull();\n assertThat(stats2.getNumberOfSubmissions()).as(\"Submission stats for instructor are correct.\").usingRecursiveComparison().isEqualTo(stats.getNumberOfSubmissions());\n assertThat(stats2.getTotalNumberOfAssessments()).as(\"Assessment stats for instructor are correct.\").usingRecursiveComparison()\n .isEqualTo(stats.getTotalNumberOfAssessments());\n }\n }\n }\n\n // Test\n public void testGetCourseForAssessmentDashboardWithStats() throws Exception {\n getCourseForDashboardWithStats(false);\n }\n\n // Test\n public void testGetCourseForInstructorDashboardWithStats() throws Exception {\n getCourseForDashboardWithStats(true);\n }\n\n // Test\n public void testGetCourseForInstructorDashboardWithStats_instructorNotInCourse() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n request.get(\"/api/courses/\" + testCourses.get(0).getId() + \"/for-assessment-dashboard\", HttpStatus.FORBIDDEN, Course.class);\n request.get(\"/api/courses/\" + testCourses.get(0).getId() + \"/stats-for-instructor-dashboard\", HttpStatus.FORBIDDEN, StatsForDashboardDTO.class);\n }\n\n // Test\n public void testGetCourseForAssessmentDashboardWithStats_tutorNotInCourse() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n request.get(\"/api/courses/\" + testCourses.get(0).getId() + \"/for-assessment-dashboard\", HttpStatus.FORBIDDEN, Course.class);\n request.get(\"/api/courses/\" + testCourses.get(0).getId() + \"/stats-for-assessment-dashboard\", HttpStatus.FORBIDDEN, StatsForDashboardDTO.class);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withoutAssessments() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n // create 6 * 4 = 24 submissions\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 0, 0, true, 0, validModel);\n\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n\n var currentTutorLeaderboard = stats.getTutorLeaderboardEntries().get(0);\n assertThat(currentTutorLeaderboard.getNumberOfTutorComplaints()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfAcceptedComplaints()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfTutorMoreFeedbackRequests()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getNumberOfAssessments()).isEqualTo(0);\n assertThat(currentTutorLeaderboard.getPoints()).isEqualTo(0);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessments() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 2, 0, true, 0, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 2 submissions in 2 exercises. The second two only 2 in one exercise.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(2);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaints() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 4, 2, true, 0, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 2 submissions in 2 exercises. The second two only 2 in one exercise.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(4);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfTutorComplaints()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfTutorComplaints()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfTutorComplaints()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfTutorComplaints()).isEqualTo(2);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessmentsAndFeedbackRequests() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 4, 2, false, 0, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 2 submissions in 2 exercises. The second two only 2 in one exercise.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(4);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfTutorComplaints()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfTutorComplaints()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfTutorComplaints()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfTutorComplaints()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(2);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 4, 2, true, 1, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 2 submissions in 2 exercises. The second two only 2 in one exercise.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAssessments()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfTutorComplaints()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfTutorComplaints()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfTutorComplaints()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfTutorComplaints()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfTutorComplaints()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAcceptedComplaints()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAcceptedComplaints()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAcceptedComplaints()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAcceptedComplaints()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAcceptedComplaints()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfComplaintResponses()).isEqualTo(6);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessmentsAndFeedBackRequestsAndResponses() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(6, 4, 4, 2, false, 1, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 2 submissions in 2 exercises. The second two only 2 in one exercise.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(8);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAssessments()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfTutorMoreFeedbackRequests()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfTutorMoreFeedbackRequests()).isEqualTo(4);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfTutorMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfTutorMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfTutorMoreFeedbackRequests()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfNotAnsweredMoreFeedbackRequests()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(2);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(1);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAnsweredMoreFeedbackRequests()).isEqualTo(0);\n }\n\n // Test\n public void testGetAssessmentDashboardStats_withAssessmentsAndComplaintsAndResponses_Large() throws Exception {\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n Course testCourse = database.addCourseWithExercisesAndSubmissions(9, 8, 8, 5, true, 5, validModel);\n StatsForDashboardDTO stats = request.get(\"/api/courses/\" + testCourse.getId() + \"/stats-for-assessment-dashboard\", HttpStatus.OK, StatsForDashboardDTO.class);\n // the first two tutors did assess 8 submissions of 3 exercises. The rest two only 8 of two exercises.\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAssessments()).isEqualTo(3 * 8);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAssessments()).isEqualTo(2 * 8);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAssessments()).isEqualTo(2 * 8);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAssessments()).isEqualTo(2 * 8);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAssessments()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfTutorComplaints()).isEqualTo(3 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfTutorComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfTutorComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfTutorComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfTutorComplaints()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfAcceptedComplaints()).isEqualTo(3 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfAcceptedComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfAcceptedComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfAcceptedComplaints()).isEqualTo(2 * 5);\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfAcceptedComplaints()).isEqualTo(0);\n\n assertThat(stats.getTutorLeaderboardEntries().get(0).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(1).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(2).getNumberOfComplaintResponses()).isEqualTo(0);\n assertThat(stats.getTutorLeaderboardEntries().get(3).getNumberOfComplaintResponses()).isEqualTo(0);\n // 9 exercises, for each one there are 5 complaintResponese\n assertThat(stats.getTutorLeaderboardEntries().get(4).getNumberOfComplaintResponses()).isEqualTo(9 * 5);\n }\n\n // Test\n public void testGetCourse() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n for (Course testCourse : testCourses) {\n Course courseWithExercisesAndRelevantParticipations = request.get(\"/api/courses/\" + testCourse.getId() + \"/with-exercises-and-relevant-participations\", HttpStatus.OK,\n Course.class);\n Course courseWithExercises = request.get(\"/api/courses/\" + testCourse.getId() + \"/with-exercises\", HttpStatus.OK, Course.class);\n Course courseOnly = request.get(\"/api/courses/\" + testCourse.getId(), HttpStatus.OK, Course.class);\n\n // Check course properties on courseOnly\n assertThat(courseOnly.getStudentGroupName()).as(\"Student group name is correct\").isEqualTo(\"tumuser\");\n assertThat(courseOnly.getTeachingAssistantGroupName()).as(\"Teaching assistant group name is correct\").isEqualTo(\"tutor\");\n assertThat(courseOnly.getInstructorGroupName()).as(\"Instructor group name is correct\").isEqualTo(\"instructor\");\n assertThat(courseOnly.getEndDate()).as(\"End date is after start date\").isAfter(courseOnly.getStartDate());\n assertThat(courseOnly.getMaxComplaints()).as(\"Max complaints is correct\").isEqualTo(3);\n assertThat(courseOnly.getPresentationScore()).as(\"Presentation score is correct\").isEqualTo(2);\n assertThat(courseOnly.getExercises().size()).as(\"Course without exercises contains no exercises\").isZero();\n assertThat(courseOnly.getNumberOfStudents()).as(\"Amount of students is correct\").isEqualTo(8);\n assertThat(courseOnly.getNumberOfTeachingAssistants()).as(\"Amount of teaching assistants is correct\").isEqualTo(5);\n assertThat(courseOnly.getNumberOfInstructors()).as(\"Amount of instructors is correct\").isEqualTo(1);\n\n // Assert that course properties on courseWithExercises and courseWithExercisesAndRelevantParticipations match those of courseOnly\n String[] ignoringFields = { \"exercises\", \"tutorGroups\", \"lectures\", \"exams\", \"fileService\", \"numberOfInstructorsTransient\", \"numberOfStudentsTransient\",\n \"numberOfTeachingAssistantsTransient\" };\n assertThat(courseWithExercises).as(\"courseWithExercises same as courseOnly\").usingRecursiveComparison().ignoringFields(ignoringFields).isEqualTo(courseOnly);\n assertThat(courseWithExercisesAndRelevantParticipations).as(\"courseWithExercisesAndRelevantParticipations same as courseOnly\").usingRecursiveComparison()\n .ignoringFields(ignoringFields).isEqualTo(courseOnly);\n\n // Verify presence of exercises in mock courses\n // - Course 1 has 5 exercises in total, 4 exercises with relevant participations\n // - Course 2 has 0 exercises in total, 0 exercises with relevant participations\n boolean isFirstCourse = courseOnly.getId().equals(testCourses.get(0).getId());\n long numberOfExercises = isFirstCourse ? 5 : 0;\n long numberOfInterestingExercises = isFirstCourse ? 4 : 0;\n assertThat(courseWithExercises.getExercises().size()).as(\"Course contains correct number of exercises\").isEqualTo(numberOfExercises);\n assertThat(courseWithExercisesAndRelevantParticipations.getExercises().size()).as(\"Course contains correct number of exercises\")\n .isEqualTo(numberOfInterestingExercises);\n }\n }\n\n // Test\n public void testGetCategoriesInCourse() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n Course course1 = testCourses.get(0);\n Course course2 = testCourses.get(1);\n List<String> categories1 = request.getList(\"/api/courses/\" + course1.getId() + \"/categories\", HttpStatus.OK, String.class);\n assertThat(categories1).as(\"Correct categories in course1\").containsExactlyInAnyOrder(\"Category\", \"Modeling\", \"Quiz\", \"File\", \"Text\", \"Programming\");\n List<String> categories2 = request.getList(\"/api/courses/\" + course2.getId() + \"/categories\", HttpStatus.OK, String.class);\n assertThat(categories2).as(\"No categories in course2\").isEmpty();\n }\n\n // Test\n public void testGetCategoriesInCourse_instructorNotInCourse() throws Exception {\n List<Course> testCourses = database.createCoursesWithExercisesAndLectures(true);\n request.get(\"/api/courses/\" + testCourses.get(0).getId() + \"/categories\", HttpStatus.FORBIDDEN, Set.class);\n }\n\n // Test\n public void testRegisterForCourse() throws Exception {\n User student = ModelFactory.generateActivatedUser(\"ab12cde\");\n userRepo.save(student);\n\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n ZonedDateTime futureTimestamp = ZonedDateTime.now().plusDays(5);\n Course course1 = ModelFactory.generateCourse(null, pastTimestamp, futureTimestamp, new HashSet<>(), \"testcourse1\", \"tutor\", \"instructor\");\n Course course2 = ModelFactory.generateCourse(null, pastTimestamp, futureTimestamp, new HashSet<>(), \"testcourse2\", \"tutor\", \"instructor\");\n course1.setRegistrationEnabled(true);\n\n course1 = courseRepo.save(course1);\n course2 = courseRepo.save(course2);\n\n mockDelegate.mockAddUserToGroupInUserManagement(student, course1.getStudentGroupName(), false);\n mockDelegate.mockAddUserToGroupInUserManagement(student, course2.getStudentGroupName(), false);\n\n User updatedStudent = request.postWithResponseBody(\"/api/courses/\" + course1.getId() + \"/register\", null, User.class, HttpStatus.OK);\n assertThat(updatedStudent.getGroups()).as(\"User is registered for course\").contains(course1.getStudentGroupName());\n\n List<AuditEvent> auditEvents = auditEventRepo.find(\"ab12cde\", Instant.now().minusSeconds(20), Constants.REGISTER_FOR_COURSE);\n assertThat(auditEvents).as(\"Audit Event for course registration added\").hasSize(1);\n AuditEvent auditEvent = auditEvents.get(0);\n assertThat(auditEvent.getData().get(\"course\")).as(\"Correct Event Data\").isEqualTo(course1.getTitle());\n\n request.postWithResponseBody(\"/api/courses/\" + course2.getId() + \"/register\", null, User.class, HttpStatus.BAD_REQUEST);\n }\n\n // Test\n public void testRegisterForCourse_notMeetsDate() throws Exception {\n User student = ModelFactory.generateActivatedUser(\"ab12cde\");\n userRepo.save(student);\n\n ZonedDateTime pastTimestamp = ZonedDateTime.now().minusDays(5);\n ZonedDateTime futureTimestamp = ZonedDateTime.now().plusDays(5);\n Course notYetStartedCourse = ModelFactory.generateCourse(null, futureTimestamp, futureTimestamp, new HashSet<>(), \"testcourse1\", \"tutor\", \"instructor\");\n Course finishedCourse = ModelFactory.generateCourse(null, pastTimestamp, pastTimestamp, new HashSet<>(), \"testcourse2\", \"tutor\", \"instructor\");\n notYetStartedCourse.setRegistrationEnabled(true);\n\n notYetStartedCourse = courseRepo.save(notYetStartedCourse);\n finishedCourse = courseRepo.save(finishedCourse);\n\n mockDelegate.mockAddUserToGroupInUserManagement(student, notYetStartedCourse.getStudentGroupName(), false);\n mockDelegate.mockAddUserToGroupInUserManagement(student, finishedCourse.getStudentGroupName(), false);\n\n request.post(\"/api/courses/\" + notYetStartedCourse.getId() + \"/register\", User.class, HttpStatus.BAD_REQUEST);\n request.post(\"/api/courses/\" + finishedCourse.getId() + \"/register\", User.class, HttpStatus.BAD_REQUEST);\n }\n\n // Test\n public void testUpdateCourse_instructorNotInCourse() throws Exception {\n var course = ModelFactory.generateCourse(1L, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n\n request.put(\"/api/courses\", course, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n\n // Get all students for course\n List<User> students = request.getList(\"/api/courses/\" + course.getId() + \"/students\", HttpStatus.OK, User.class);\n assertThat(students).as(\"All students in course found\").hasSize(numberOfStudents);\n\n // Get all tutors for course\n List<User> tutors = request.getList(\"/api/courses/\" + course.getId() + \"/tutors\", HttpStatus.OK, User.class);\n assertThat(tutors).as(\"All tutors in course found\").hasSize(numberOfTutors);\n\n // Get all instructors for course\n List<User> instructors = request.getList(\"/api/courses/\" + course.getId() + \"/instructors\", HttpStatus.OK, User.class);\n assertThat(instructors).as(\"All instructors in course found\").hasSize(numberOfInstructors);\n }\n\n // Test\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"other-tumuser\", \"other-tutor\", \"other-instructor\");\n course = courseRepo.save(course);\n testGetAllStudentsOrTutorsOrInstructorsInCourse__forbidden(course);\n }\n\n // Test\n public void testGetAllStudentsOrTutorsOrInstructorsInCourse_AsTutor_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n testGetAllStudentsOrTutorsOrInstructorsInCourse__forbidden(course);\n }\n\n private void testGetAllStudentsOrTutorsOrInstructorsInCourse__forbidden(Course course) throws Exception {\n request.getList(\"/api/courses/\" + course.getId() + \"/students\", HttpStatus.FORBIDDEN, User.class);\n request.getList(\"/api/courses/\" + course.getId() + \"/tutors\", HttpStatus.FORBIDDEN, User.class);\n request.getList(\"/api/courses/\" + course.getId() + \"/instructors\", HttpStatus.FORBIDDEN, User.class);\n }\n\n // Test\n public void testAddStudentOrTutorOrInstructorToCourse() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n testAddStudentOrTutorOrInstructorToCourse(course, HttpStatus.OK);\n\n // TODO check that the roles have changed accordingly\n }\n\n // Test\n public void testAddStudentOrTutorOrInstructorToCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"other-tumuser\", \"other-tutor\", \"other-instructor\");\n course = courseRepo.save(course);\n testAddStudentOrTutorOrInstructorToCourse(course, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testAddStudentOrTutorOrInstructorToCourse_AsTutor_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n testAddStudentOrTutorOrInstructorToCourse(course, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testAddStudentOrTutorOrInstructorToCourse_WithNonExistingUser() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/students/maxMustermann\", null, HttpStatus.NOT_FOUND, null);\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/tutors/maxMustermann\", null, HttpStatus.NOT_FOUND, null);\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/instructors/maxMustermann\", null, HttpStatus.NOT_FOUND, null);\n }\n\n private void testAddStudentOrTutorOrInstructorToCourse(Course course, HttpStatus httpStatus) throws Exception {\n var student = userRepo.findOneWithGroupsAndAuthoritiesByLogin(\"student1\").get();\n var tutor1 = userRepo.findOneWithGroupsAndAuthoritiesByLogin(\"tutor1\").get();\n var instructor1 = userRepo.findOneWithGroupsAndAuthoritiesByLogin(\"instructor1\").get();\n\n mockDelegate.mockAddUserToGroupInUserManagement(student, course.getStudentGroupName(), false);\n mockDelegate.mockAddUserToGroupInUserManagement(tutor1, course.getTeachingAssistantGroupName(), false);\n mockDelegate.mockAddUserToGroupInUserManagement(instructor1, course.getInstructorGroupName(), false);\n\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/students/student1\", null, httpStatus, null);\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/tutors/tutor1\", null, httpStatus, null);\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/instructors/instructor1\", null, httpStatus, null);\n }\n\n // Test\n public void testAddTutorAndInstructorToCourse_failsToAddUserToGroup(HttpStatus expectedFailureCode) throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n database.addProgrammingExerciseToCourse(course, false);\n course = courseRepo.save(course);\n\n var tutor1 = userRepo.findOneWithGroupsAndAuthoritiesByLogin(\"tutor1\").get();\n var instructor1 = userRepo.findOneWithGroupsAndAuthoritiesByLogin(\"instructor1\").get();\n\n mockDelegate.mockAddUserToGroupInUserManagement(tutor1, course.getTeachingAssistantGroupName(), true);\n mockDelegate.mockAddUserToGroupInUserManagement(instructor1, course.getInstructorGroupName(), true);\n\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/tutors/tutor1\", null, expectedFailureCode, null);\n request.postWithoutLocation(\"/api/courses/\" + course.getId() + \"/instructors/instructor1\", null, expectedFailureCode, null);\n }\n\n // Test\n public void testRemoveTutorFromCourse_failsToRemoveUserFromGroup() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n database.addProgrammingExerciseToCourse(course, false);\n course = courseRepo.save(course);\n\n User tutor = userRepo.findOneWithGroupsByLogin(\"tutor1\").get();\n mockDelegate.mockRemoveUserFromGroup(tutor, course.getTeachingAssistantGroupName(), true);\n request.delete(\"/api/courses/\" + course.getId() + \"/tutors/\" + tutor.getLogin(), HttpStatus.INTERNAL_SERVER_ERROR);\n }\n\n // Test\n public void testRemoveStudentOrTutorOrInstructorFromCourse() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n testRemoveStudentOrTutorOrInstructorFromCourse_forbidden(course, HttpStatus.OK);\n // TODO check that the roles have changed accordingly\n }\n\n // Test\n public void testRemoveStudentOrTutorOrInstructorFromCourse_WithNonExistingUser() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n request.delete(\"/api/courses/\" + course.getId() + \"/students/maxMustermann\", HttpStatus.NOT_FOUND);\n request.delete(\"/api/courses/\" + course.getId() + \"/tutors/maxMustermann\", HttpStatus.NOT_FOUND);\n request.delete(\"/api/courses/\" + course.getId() + \"/instructors/maxMustermann\", HttpStatus.NOT_FOUND);\n }\n\n // Test\n public void testRemoveStudentOrTutorOrInstructorFromCourse_AsInstructorOfOtherCourse_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"other-tumuser\", \"other-tutor\", \"other-instructor\");\n course = courseRepo.save(course);\n testRemoveStudentOrTutorOrInstructorFromCourse_forbidden(course, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testRemoveStudentOrTutorOrInstructorFromCourse_AsTutor_forbidden() throws Exception {\n Course course = ModelFactory.generateCourse(null, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n testRemoveStudentOrTutorOrInstructorFromCourse_forbidden(course, HttpStatus.FORBIDDEN);\n }\n\n private void testRemoveStudentOrTutorOrInstructorFromCourse_forbidden(Course course, HttpStatus httpStatus) throws Exception {\n // Retrieve users from whom to remove groups\n User student = userRepo.findOneWithGroupsByLogin(\"student1\").get();\n User tutor = userRepo.findOneWithGroupsByLogin(\"tutor1\").get();\n User instructor = userRepo.findOneWithGroupsByLogin(\"instructor1\").get();\n\n // Mock remove requests\n mockDelegate.mockRemoveUserFromGroup(student, course.getStudentGroupName(), false);\n mockDelegate.mockRemoveUserFromGroup(tutor, course.getTeachingAssistantGroupName(), false);\n mockDelegate.mockRemoveUserFromGroup(instructor, course.getInstructorGroupName(), false);\n\n // Remove users from their group\n request.delete(\"/api/courses/\" + course.getId() + \"/students/\" + student.getLogin(), httpStatus);\n request.delete(\"/api/courses/\" + course.getId() + \"/tutors/\" + tutor.getLogin(), httpStatus);\n request.delete(\"/api/courses/\" + course.getId() + \"/instructors/\" + instructor.getLogin(), httpStatus);\n }\n\n // Test\n public void testGetLockedSubmissionsForCourseAsTutor() throws Exception {\n Course course = database.addCourseWithDifferentModelingExercises();\n ModelingExercise classExercise = database.findModelingExerciseWithTitle(course.getExercises(), \"ClassDiagram\");\n\n List<Submission> lockedSubmissions = request.get(\"/api/courses/\" + course.getId() + \"/lockedSubmissions\", HttpStatus.OK, List.class);\n assertThat(lockedSubmissions).as(\"Locked Submissions is not null\").isNotNull();\n assertThat(lockedSubmissions).as(\"Locked Submissions length is 0\").hasSize(0);\n\n String validModel = FileUtils.loadFileFromResources(\"test-data/model-submission/model.54727.json\");\n\n ModelingSubmission submission = ModelFactory.generateModelingSubmission(validModel, true);\n database.addModelingSubmissionWithResultAndAssessor(classExercise, submission, \"student1\", \"tutor1\");\n\n submission = ModelFactory.generateModelingSubmission(validModel, true);\n database.addModelingSubmissionWithResultAndAssessor(classExercise, submission, \"student2\", \"tutor1\");\n\n submission = ModelFactory.generateModelingSubmission(validModel, true);\n database.addModelingSubmissionWithResultAndAssessor(classExercise, submission, \"student3\", \"tutor1\");\n\n lockedSubmissions = request.get(\"/api/courses/\" + course.getId() + \"/lockedSubmissions\", HttpStatus.OK, List.class);\n assertThat(lockedSubmissions).as(\"Locked Submissions is not null\").isNotNull();\n assertThat(lockedSubmissions).as(\"Locked Submissions length is 3\").hasSize(3);\n }\n\n // Test\n public void testGetLockedSubmissionsForCourseAsStudent() throws Exception {\n List<Submission> lockedSubmissions = request.get(\"/api/courses/1/lockedSubmissions\", HttpStatus.FORBIDDEN, List.class);\n assertThat(lockedSubmissions).as(\"Locked Submissions is null\").isNull();\n }\n\n // Test\n public void testArchiveCourseAsStudent_forbidden() throws Exception {\n request.put(\"/api/courses/\" + 1 + \"/archive\", null, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testArchiveCourseAsTutor_forbidden() throws Exception {\n request.put(\"/api/courses/\" + 1 + \"/archive\", null, HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testArchiveCourseWithTestModelingAndFileUploadExercises() throws Exception {\n var course = database.createCourseWithTestModelingAndFileUploadExercisesAndSubmissions();\n\n request.put(\"/api/courses/\" + course.getId() + \"/archive\", null, HttpStatus.OK);\n\n await().until(() -> courseRepo.findById(course.getId()).get().getCourseArchivePath() != null);\n\n var updatedCourse = courseRepo.findById(course.getId()).get();\n assertThat(updatedCourse.getCourseArchivePath()).isNotEmpty();\n }\n\n // Test\n public void testDownloadCourseArchiveAsStudent_forbidden() throws Exception {\n request.get(\"/api/courses/\" + 1 + \"/download-archive\", HttpStatus.FORBIDDEN, String.class);\n }\n\n // Test\n public void testDownloadCourseArchiveAsTutor_forbidden() throws Exception {\n request.get(\"/api/courses/\" + 1 + \"/download-archive\", HttpStatus.FORBIDDEN, String.class);\n }\n\n // Test\n public void testDownloadCourseArchiveAsInstructor_not_found() throws Exception {\n // Generate a course that has no archive and assert that an 404 status is thrown\n Course course = ModelFactory.generateCourse(1L, null, null, new HashSet<>(), \"tumuser\", \"tutor\", \"instructor\");\n course = courseRepo.save(course);\n\n var downloadedArchive = request.get(\"/api/courses/\" + course.getId() + \"/download-archive\", HttpStatus.NOT_FOUND, String.class);\n assertThat(downloadedArchive).isNull();\n }\n\n // Test\n public void testDownloadCourseArchiveAsInstructor() throws Exception {\n submissionRepository.deleteAll();\n\n // Archive the course and wait until it's complete\n testArchiveCourseWithTestModelingAndFileUploadExercises();\n\n var optCourse = courseRepo.findAll().stream().findFirst();\n assertThat(optCourse).isPresent();\n var course = optCourse.get();\n\n // Download the archive\n var archive = request.getFile(\"/api/courses/\" + course.getId() + \"/download-archive\", HttpStatus.OK, new LinkedMultiValueMap<>());\n assertThat(archive).isNotNull();\n assertThat(archive).exists();\n assertThat(archive.getPath().length()).isGreaterThanOrEqualTo(4);\n\n // Extract the archive\n zipFileTestUtilService.extractZipFileRecursively(archive.getAbsolutePath());\n String extractedArchiveDir = archive.getPath().substring(0, archive.getPath().length() - 4);\n\n // We test for the filenames of the submissions since it's the easiest way.\n // We don't test the directory structure\n var filenames = Files.walk(Path.of(extractedArchiveDir)).filter(Files::isRegularFile).map(Path::getFileName).collect(Collectors.toList());\n\n var submissions = submissionRepository.findAll();\n\n var fileUploadSubmissionId = submissions.stream().filter(submission -> submission instanceof FileUploadSubmission).findFirst().get().getId();\n assertThat(filenames).contains(Path.of(\"FileUpload-student1-\" + fileUploadSubmissionId + \".png\"));\n\n var textSubmissionId = submissions.stream().filter(submission -> submission instanceof TextSubmission).findFirst().get().getId();\n assertThat(filenames).contains(Path.of(\"Text-student1-\" + textSubmissionId + \".txt\"));\n\n var modelingSubmission = submissions.stream().filter(submission -> submission instanceof ModelingSubmission).findFirst().get().getId();\n assertThat(filenames).contains(Path.of(\"Modeling-student1-\" + modelingSubmission + \".json\"));\n }\n\n // Test\n public void testCleanupCourseAsStudent_forbidden() throws Exception {\n request.delete(\"/api/courses/\" + 1 + \"/cleanup\", HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testCleanupCourseAsTutor_forbidden() throws Exception {\n request.delete(\"/api/courses/\" + 1 + \"/cleanup\", HttpStatus.FORBIDDEN);\n }\n\n // Test\n public void testCleanupCourseAsInstructor_no_Archive() throws Exception {\n // Generate a course that has an archive\n Course course = courseRepo.save(database.createCourse());\n\n request.delete(\"/api/courses/\" + course.getId() + \"/cleanup\", HttpStatus.BAD_REQUEST);\n }\n\n // Test\n public void testCleanupCourseAsInstructor() throws Exception {\n // Generate a course that has an archive\n var course = database.addCourseWithOneProgrammingExercise(false, ProgrammingLanguage.JAVA);\n course.setCourseArchivePath(\"some-archive-path\");\n courseRepo.save(course);\n\n var programmingExercise = programmingExerciseRepository.findAllWithEagerTemplateAndSolutionParticipations().get(0);\n database.addStudentParticipationForProgrammingExercise(programmingExercise, \"student1\");\n database.addStudentParticipationForProgrammingExercise(programmingExercise, \"student1\");\n\n mockDelegate.mockDeleteRepository(programmingExercise.getProjectKey(), (programmingExercise.getProjectKey()).toLowerCase() + \"-student1\", false);\n var buildPlanId = (programmingExercise.getProjectKey() + \"-student1\").toUpperCase();\n mockDelegate.mockDeleteBuildPlan(programmingExercise.getProjectKey(), buildPlanId, false);\n request.delete(\"/api/courses/\" + course.getId() + \"/cleanup\", HttpStatus.OK);\n\n course.getExercises().forEach(exercise -> {\n var exerciseWithParticipations = exerciseRepo.findWithEagerStudentParticipationsStudentAndSubmissionsById(exercise.getId()).get();\n if (exercise instanceof ProgrammingExercise) {\n for (StudentParticipation participation : exerciseWithParticipations.getStudentParticipations()) {\n ProgrammingExerciseStudentParticipation programmingExerciseParticipation = (ProgrammingExerciseStudentParticipation) participation;\n assertThat(programmingExerciseParticipation.getBuildPlanId()).as(\"Build plan id has been removed\").isNull();\n }\n }\n\n // TODO: Assert the other exercises after it's implemented\n });\n }\n\n // Test\n public void testGetCourseTitle() throws Exception {\n Course course = database.createCourse();\n course.setTitle(\"Test Course\");\n course = courseRepo.save(course);\n\n final var title = request.get(\"/api/courses/\" + course.getId() + \"/title\", HttpStatus.OK, String.class);\n assertThat(title).isEqualTo(course.getTitle());\n }\n\n // Test\n public void testGetCourseTitleForNonExistingCourse() throws Exception {\n // No course with id 10 was created\n request.get(\"/api/courses/10/title\", HttpStatus.NOT_FOUND, String.class);\n }\n\n // Test\n public void testGetAllCoursesForManagementOverview() throws Exception {\n // Add two courses, containing one not belonging to the instructor\n var testCourses = database.createCoursesWithExercisesAndLectures(true);\n var instructorsCourse = testCourses.get(0);\n instructorsCourse.setInstructorGroupName(\"test-instructors\");\n courseRepo.save(instructorsCourse);\n\n var instructor = database.getUserByLogin(\"instructor1\");\n var groups = new HashSet<String>();\n groups.add(\"test-instructors\");\n instructor.setGroups(groups);\n userRepo.save(instructor);\n\n var courses = request.getList(\"/api/courses/course-management-overview\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).isEqualTo(1);\n\n var course = courses.get(0);\n assertThat(course.getId()).isEqualTo(instructorsCourse.getId());\n }\n\n // Test\n public void testGetExercisesForCourseOverview() throws Exception {\n // Add two courses, containing one not belonging to the instructor\n var testCourses = database.createCoursesWithExercisesAndLectures(true);\n var instructorsCourse = testCourses.get(0);\n instructorsCourse.setInstructorGroupName(\"test-instructors\");\n courseRepo.save(instructorsCourse);\n\n var instructor = database.getUserByLogin(\"instructor1\");\n var groups = new HashSet<String>();\n groups.add(\"test-instructors\");\n instructor.setGroups(groups);\n userRepo.save(instructor);\n\n var courses = request.getList(\"/api/courses/exercises-for-management-overview\", HttpStatus.OK, Course.class);\n assertThat(courses.size()).isEqualTo(1);\n\n var course = courses.get(0);\n assertThat(course.getId()).isEqualTo(instructorsCourse.getId());\n\n var exerciseDetails = course.getExercises();\n assertThat(exerciseDetails).isNotNull();\n assertThat(exerciseDetails.size()).isEqualTo(5);\n\n var quizDetailsOptional = exerciseDetails.stream().filter(e -> e instanceof QuizExercise).findFirst();\n assertThat(quizDetailsOptional.isPresent()).isTrue();\n\n var quizExerciseOptional = instructorsCourse.getExercises().stream().filter(e -> e instanceof QuizExercise).findFirst();\n assertThat(quizExerciseOptional.isPresent()).isTrue();\n\n var quizDetails = quizDetailsOptional.get();\n var quizExercise = quizExerciseOptional.get();\n assertThat(quizDetails.getCategories().size()).isEqualTo(quizExercise.getCategories().size());\n\n var detailsCategories = quizDetails.getCategories().stream().findFirst();\n var exerciseCategories = quizExercise.getCategories().stream().findFirst();\n assertThat(detailsCategories.isPresent()).isTrue();\n assertThat(exerciseCategories.isPresent()).isTrue();\n assertThat(detailsCategories.get()).isEqualTo(exerciseCategories.get());\n }\n\n // Test\n public void testGetExerciseStatsForCourseOverview() throws Exception {\n // Add a course and set the instructor group name\n var instructorsCourse = database.createCourse();\n instructorsCourse.setInstructorGroupName(\"test-instructors\");\n\n // Fetch and update an instructor\n var instructor = database.getUserByLogin(\"instructor1\");\n var groups = new HashSet<String>();\n groups.add(\"test-instructors\");\n instructor.setGroups(groups);\n userRepo.save(instructor);\n\n // Get a student\n var student = ModelFactory.generateActivatedUser(\"user1\");\n userRepo.save(student);\n\n // Add a team exercise which was just released but not due\n var releaseDate = ZonedDateTime.now().minusDays(4);\n var futureDueDate = ZonedDateTime.now().plusDays(2);\n var futureAssessmentDueDate = ZonedDateTime.now().plusDays(4);\n var teamExerciseNotEnded = database.createTeamTextExercise(instructorsCourse, releaseDate, futureDueDate, futureAssessmentDueDate);\n teamExerciseNotEnded = exerciseRepo.save(teamExerciseNotEnded);\n\n // Add a team with a participation to the exercise\n final var teamExerciseId = teamExerciseNotEnded.getId();\n var teamStudents = new HashSet<User>();\n teamStudents.add(student);\n var team = database.createTeam(teamStudents, instructor, teamExerciseNotEnded);\n database.addTeamParticipationForExercise(teamExerciseNotEnded, team.getId());\n\n instructorsCourse.addExercises(teamExerciseNotEnded);\n\n // Create an exercise which has passed the due and assessment due date\n var dueDate = ZonedDateTime.now().minusDays(2);\n var passedAssessmentDueDate = ZonedDateTime.now().minusDays(1);\n var exerciseAssessmentDone = ModelFactory.generateTextExercise(releaseDate, dueDate, passedAssessmentDueDate, instructorsCourse);\n exerciseAssessmentDone.setMaxPoints(5.0);\n exerciseAssessmentDone = exerciseRepo.save(exerciseAssessmentDone);\n\n // Add a single participation to that exercise\n final var exerciseId = exerciseAssessmentDone.getId();\n database.createParticipationSubmissionAndResult(exerciseId, student, 5.0, 0.0, 60, true);\n\n instructorsCourse.addExercises(exerciseAssessmentDone);\n\n // Create an exercise which is currently in assessment\n var exerciseInAssessment = ModelFactory.generateTextExercise(releaseDate, dueDate, futureAssessmentDueDate, instructorsCourse);\n exerciseInAssessment.setMaxPoints(15.0);\n exerciseInAssessment = exerciseRepo.save(exerciseInAssessment);\n\n // Add a single participation to that exercise\n final var exerciseIdInAssessment = exerciseInAssessment.getId();\n var resultToSetAssessorFor = database.createParticipationSubmissionAndResult(exerciseIdInAssessment, student, 15.0, 0.0, 30, true);\n resultToSetAssessorFor.setAssessor(instructor);\n resultRepo.saveAndFlush(resultToSetAssessorFor);\n\n instructorsCourse.addExercises(exerciseInAssessment);\n\n courseRepo.save(instructorsCourse);\n\n // We only added one course, so expect one dto\n var courseDtos = request.getList(\"/api/courses/stats-for-management-overview\", HttpStatus.OK, CourseManagementOverviewStatisticsDTO.class);\n assertThat(courseDtos.size()).isEqualTo(1);\n var dto = courseDtos.get(0);\n assertThat(dto.getCourseId()).isEqualTo(instructorsCourse.getId());\n\n // Expect our three created exercises\n var exerciseDTOS = dto.getExerciseDTOS();\n assertThat(exerciseDTOS.size()).isEqualTo(3);\n\n // Get the statistics of the exercise with a passed assessment due date\n var statisticsOptional = exerciseDTOS.stream().filter(exercise -> exercise.getExerciseId().equals(exerciseId)).findFirst();\n assertThat(statisticsOptional.isPresent()).isTrue();\n\n // Since the exercise is a \"past exercise\", the average score are the only statistics we set\n var statisticsDTO = statisticsOptional.get();\n assertThat(statisticsDTO.getAverageScoreInPercent()).isEqualTo(60.0);\n assertThat(statisticsDTO.getExerciseMaxPoints()).isEqualTo(5.0);\n assertThat(statisticsDTO.getNoOfParticipatingStudentsOrTeams()).isEqualTo(0);\n assertThat(statisticsDTO.getParticipationRateInPercent()).isEqualTo(0.0);\n assertThat(statisticsDTO.getNoOfStudentsInCourse()).isEqualTo(8);\n assertThat(statisticsDTO.getNoOfRatedAssessments()).isEqualTo(0);\n assertThat(statisticsDTO.getNoOfAssessmentsDoneInPercent()).isEqualTo(0.0);\n assertThat(statisticsDTO.getNoOfSubmissionsInTime()).isEqualTo(0L);\n\n // Get the statistics of the team exercise\n var teamStatisticsOptional = exerciseDTOS.stream().filter(exercise -> exercise.getExerciseId().equals(teamExerciseId)).findFirst();\n assertThat(teamStatisticsOptional.isPresent()).isTrue();\n\n // Since that exercise is still \"currently in progress\", the participations are the only statistics we set\n var teamStatisticsDTO = teamStatisticsOptional.get();\n assertThat(teamStatisticsDTO.getAverageScoreInPercent()).isEqualTo(0.0);\n assertThat(teamStatisticsDTO.getExerciseMaxPoints()).isEqualTo(10.0);\n assertThat(teamStatisticsDTO.getNoOfParticipatingStudentsOrTeams()).isEqualTo(1);\n assertThat(teamStatisticsDTO.getParticipationRateInPercent()).isEqualTo(100D);\n assertThat(teamStatisticsDTO.getNoOfStudentsInCourse()).isEqualTo(8);\n assertThat(teamStatisticsDTO.getNoOfTeamsInCourse()).isEqualTo(1);\n assertThat(teamStatisticsDTO.getNoOfRatedAssessments()).isEqualTo(0);\n assertThat(teamStatisticsDTO.getNoOfAssessmentsDoneInPercent()).isEqualTo(0.0);\n assertThat(teamStatisticsDTO.getNoOfSubmissionsInTime()).isEqualTo(1L);\n\n // Get the statistics of the exercise in assessment\n var exerciseInAssessmentStatisticsOptional = exerciseDTOS.stream().filter(exercise -> exercise.getExerciseId().equals(exerciseIdInAssessment)).findFirst();\n assertThat(exerciseInAssessmentStatisticsOptional.isPresent()).isTrue();\n\n // Since that exercise is \"currently in assessment\", we need the numberOfRatedAssessment, assessmentsDoneInPercent and the numberOfSubmissionsInTime\n var exerciseInAssessmentStatisticsDTO = exerciseInAssessmentStatisticsOptional.get();\n assertThat(exerciseInAssessmentStatisticsDTO.getAverageScoreInPercent()).isEqualTo(0.0);\n assertThat(exerciseInAssessmentStatisticsDTO.getExerciseMaxPoints()).isEqualTo(15.0);\n assertThat(exerciseInAssessmentStatisticsDTO.getNoOfParticipatingStudentsOrTeams()).isEqualTo(0);\n assertThat(exerciseInAssessmentStatisticsDTO.getParticipationRateInPercent()).isEqualTo(0D);\n assertThat(exerciseInAssessmentStatisticsDTO.getNoOfStudentsInCourse()).isEqualTo(8);\n assertThat(exerciseInAssessmentStatisticsDTO.getNoOfRatedAssessments()).isEqualTo(1);\n assertThat(exerciseInAssessmentStatisticsDTO.getNoOfAssessmentsDoneInPercent()).isEqualTo(100.0);\n assertThat(exerciseInAssessmentStatisticsDTO.getNoOfSubmissionsInTime()).isEqualTo(1L);\n }\n\n // Test\n public void testGetExerciseStatsForCourseOverviewWithPastExercises() throws Exception {\n // Add a single course with six past exercises, from which only five are returned\n var instructorsCourse = database.createCourse();\n var releaseDate = ZonedDateTime.now().minusDays(7);\n var dueDate = ZonedDateTime.now().minusDays(4);\n var olderDueDate = ZonedDateTime.now().minusDays(4);\n var assessmentDueDate = ZonedDateTime.now().minusDays(2);\n var olderAssessmentDueDate = ZonedDateTime.now().minusDays(3);\n var oldestAssessmentDueDate = ZonedDateTime.now().minusDays(6);\n\n // Add five exercises with different combinations of due dates and assessment due dates\n instructorsCourse.addExercises(exerciseRepo.save(ModelFactory.generateTextExercise(releaseDate, dueDate, assessmentDueDate, instructorsCourse)));\n instructorsCourse.addExercises(exerciseRepo.save(ModelFactory.generateTextExercise(releaseDate, null, assessmentDueDate, instructorsCourse)));\n instructorsCourse.addExercises(exerciseRepo.save(ModelFactory.generateTextExercise(releaseDate, olderDueDate, assessmentDueDate, instructorsCourse)));\n instructorsCourse.addExercises(exerciseRepo.save(ModelFactory.generateTextExercise(releaseDate, olderDueDate, olderAssessmentDueDate, instructorsCourse)));\n instructorsCourse.addExercises(exerciseRepo.save(ModelFactory.generateTextExercise(releaseDate, null, olderAssessmentDueDate, instructorsCourse)));\n\n // Add one exercise which will be sorted last due to the oldest assessment due date\n var exerciseNotReturned = ModelFactory.generateTextExercise(releaseDate, dueDate, oldestAssessmentDueDate, instructorsCourse);\n exerciseNotReturned = exerciseRepo.save(exerciseNotReturned);\n final var exerciseId = exerciseNotReturned.getId();\n instructorsCourse.addExercises(exerciseNotReturned);\n courseRepo.save(instructorsCourse);\n\n // We only added one course, so expect one dto\n var courseDtos = request.getList(\"/api/courses/stats-for-management-overview\", HttpStatus.OK, CourseManagementOverviewStatisticsDTO.class);\n assertThat(courseDtos.size()).isEqualTo(1);\n var dto = courseDtos.get(0);\n assertThat(dto.getCourseId()).isEqualTo(instructorsCourse.getId());\n\n // Only five exercises should be returned\n var exerciseDTOS = dto.getExerciseDTOS();\n assertThat(exerciseDTOS.size()).isEqualTo(5);\n\n // The one specific exercise should not be included\n var statisticsOptional = exerciseDTOS.stream().filter(exercise -> exercise.getExerciseId().equals(exerciseId)).findFirst();\n assertThat(statisticsOptional.isEmpty()).isTrue();\n }\n}\n" }, { "alpha_fraction": 0.6963503360748291, "alphanum_fraction": 0.6978102326393127, "avg_line_length": 28.35714340209961, "blob_id": "8f6a57f3790258e6aea6c38345b77ed06e9ad4e9", "content_id": "f2f0189ad12299b081c267ffcab3348404f24354", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2055, "license_type": "permissive", "max_line_length": 166, "num_lines": 70, "path": "/src/main/java/de/tum/in/www1/artemis/domain/modeling/ModelingExercise.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.modeling;\n\nimport javax.persistence.*;\n\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.DiagramType;\n\n/**\n * A ModelingExercise.\n */\n@Entity\n@DiscriminatorValue(value = \"M\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ModelingExercise extends Exercise {\n\n @Enumerated(EnumType.STRING)\n @Column(name = \"diagram_type\")\n private DiagramType diagramType;\n\n @Column(name = \"sample_solution_model\")\n @Lob\n private String sampleSolutionModel;\n\n @Column(name = \"sample_solution_explanation\")\n @Lob\n private String sampleSolutionExplanation;\n\n public DiagramType getDiagramType() {\n return diagramType;\n }\n\n public void setDiagramType(DiagramType diagramType) {\n this.diagramType = diagramType;\n }\n\n public String getSampleSolutionModel() {\n return sampleSolutionModel;\n }\n\n public void setSampleSolutionModel(String sampleSolutionModel) {\n this.sampleSolutionModel = sampleSolutionModel;\n }\n\n public String getSampleSolutionExplanation() {\n return sampleSolutionExplanation;\n }\n\n public void setSampleSolutionExplanation(String sampleSolutionExplanation) {\n this.sampleSolutionExplanation = sampleSolutionExplanation;\n }\n\n /**\n * set all sensitive information to null, so no info with respect to the solution gets leaked to students through json\n */\n @Override\n public void filterSensitiveInformation() {\n setSampleSolutionModel(null);\n setSampleSolutionExplanation(null);\n super.filterSensitiveInformation();\n }\n\n @Override\n public String toString() {\n return \"ModelingExercise{\" + \"id=\" + getId() + \", maxPoints='\" + getMaxPoints() + \"'\" + \", diagramType='\" + getDiagramType() + \"'\" + \", sampleSolutionModel='\"\n + getSampleSolutionModel() + \"'\" + \", sampleSolutionExplanation='\" + getSampleSolutionExplanation() + \"'\" + \"}\";\n }\n\n}\n" }, { "alpha_fraction": 0.6646026968955994, "alphanum_fraction": 0.6646026968955994, "avg_line_length": 39.375, "blob_id": "65e4a86d03f031bbe5748a4b5ea79ebcd321d787", "content_id": "e23f5e29e0a17657983eede0fa184630dee90aa3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 969, "license_type": "permissive", "max_line_length": 150, "num_lines": 24, "path": "/src/main/webapp/app/exercises/shared/slide-toggle/slide-toggle.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Output, EventEmitter } from '@angular/core';\n\n@Component({\n selector: 'jhi-slide-toggle',\n template: `\n <!-- Default switch -->\n <div class=\"custom-control custom-switch\">\n <input type=\"checkbox\" class=\"custom-control-input\" id=\"customSwitches\" [(ngModel)]=\"checked\" (change)=\"getCheckedFlag()\" />\n <label class=\"custom-control-label\" for=\"customSwitches\"></label>\n </div>\n <label *ngIf=\"checked === false || checked === undefined\" jhiTranslate=\"artemisApp.exercise.gradingInstructions\"> Grading Instructions</label>\n <label *ngIf=\"checked === true\" jhiTranslate=\"artemisApp.exercise.structuredGradingInstructions\"> Structured Grading Instructions</label>\n `,\n})\nexport class SlideToggleComponent {\n @Output() checkedEmitter = new EventEmitter<boolean>();\n checked: boolean;\n\n constructor() {}\n\n getCheckedFlag() {\n this.checkedEmitter.emit(this.checked);\n }\n}\n" }, { "alpha_fraction": 0.7903226017951965, "alphanum_fraction": 0.7983871102333069, "avg_line_length": 23.799999237060547, "blob_id": "9b9e88d37a239914efa23d9bbd3c1d4b1357f753", "content_id": "efb74aef953e0e9d2a5616b45038d9852ae823ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 124, "license_type": "permissive", "max_line_length": 50, "num_lines": 5, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/VersionControlRepositoryPermission.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors;\n\npublic enum VersionControlRepositoryPermission {\n READ_ONLY, WRITE\n}\n" }, { "alpha_fraction": 0.6221585869789124, "alphanum_fraction": 0.6232324838638306, "avg_line_length": 37.531036376953125, "blob_id": "c1c696c439268cb192fe9e6443c43303a32dc5c8", "content_id": "4e08a434e828028bd111c376651efec0d9128fbe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5587, "license_type": "permissive", "max_line_length": 135, "num_lines": 145, "path": "/src/main/webapp/app/exercises/shared/plagiarism/plagiarism-split-view/text-submission-viewer/text-submission-viewer.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges, SimpleChanges, ViewEncapsulation } from '@angular/core';\nimport { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service';\nimport { PlagiarismSubmission } from 'app/exercises/shared/plagiarism/types/PlagiarismSubmission';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { DomainType, FileType } from 'app/exercises/programming/shared/code-editor/model/code-editor.model';\nimport { CodeEditorRepositoryFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service';\n\n@Component({\n selector: 'jhi-text-submission-viewer',\n styleUrls: ['./text-submission-viewer.component.scss'],\n templateUrl: './text-submission-viewer.component.html',\n encapsulation: ViewEncapsulation.None,\n})\nexport class TextSubmissionViewerComponent implements OnChanges {\n @Input() exercise: ProgrammingExercise | TextExercise;\n @Input() matches: Map<string, { from: TextSubmissionElement; to: TextSubmissionElement }[]>;\n @Input() plagiarismSubmission: PlagiarismSubmission<TextSubmissionElement>;\n\n /**\n * Name of the currently selected file.\n */\n public currentFile: string;\n\n /**\n * Content of the currently selected file.\n */\n public fileContent: string;\n\n /**\n * List of files the given submission consists of.\n * `null` for text exercises.\n */\n public files: string[];\n\n /**\n * True, if the given exercise is of type 'programming'.\n */\n public isProgrammingExercise: boolean;\n\n /**\n * True, if the file content for the given submission is being loaded.\n */\n public loading: boolean;\n\n /**\n * Token that marks the beginning of a highlighted match.\n */\n public tokenStart = '<span class=\"plagiarism-match\">';\n\n /**\n * Token that marks the end of a highlighted match.\n */\n public tokenEnd = '</span>';\n\n constructor(private repositoryService: CodeEditorRepositoryFileService, private textSubmissionService: TextSubmissionService) {}\n\n ngOnChanges(changes: SimpleChanges): void {\n if (changes.plagiarismSubmission) {\n const currentPlagiarismSubmission: PlagiarismSubmission<TextSubmissionElement> = changes.plagiarismSubmission.currentValue;\n this.loading = true;\n\n if (this.exercise.type === ExerciseType.PROGRAMMING) {\n this.isProgrammingExercise = true;\n\n this.repositoryService.setDomain([DomainType.PARTICIPATION, { id: currentPlagiarismSubmission.submissionId }]);\n this.repositoryService.getRepositoryContent().subscribe(\n (files) => {\n this.loading = false;\n this.files = this.filterFiles(files);\n },\n () => {\n this.loading = false;\n },\n );\n } else {\n this.isProgrammingExercise = false;\n\n this.textSubmissionService.getTextSubmission(currentPlagiarismSubmission.submissionId).subscribe(\n (submission: TextSubmission) => {\n this.loading = false;\n this.fileContent = this.insertMatchTokens(submission.text || '');\n },\n () => {\n this.loading = false;\n },\n );\n }\n }\n }\n\n filterFiles(files: { [p: string]: FileType }) {\n return Object.keys(files).filter((fileName) => files[fileName] === FileType.FILE);\n }\n\n handleFileSelect(file: string) {\n this.currentFile = file;\n this.loading = true;\n\n this.repositoryService.setDomain([DomainType.PARTICIPATION, { id: this.plagiarismSubmission.submissionId }]);\n this.repositoryService.getFile(file).subscribe(\n ({ fileContent }) => {\n this.loading = false;\n this.fileContent = this.insertMatchTokens(fileContent);\n },\n () => {\n this.loading = false;\n },\n );\n }\n\n getMatchesForCurrentFile() {\n return this.matches.get(this.currentFile || 'none') || [];\n }\n\n insertToken(text: string, token: string, position: number) {\n return [text.slice(0, position), token, text.slice(position)].join('');\n }\n\n insertMatchTokens(fileContent: string) {\n const rows = fileContent.split('\\n');\n const matches = this.getMatchesForCurrentFile();\n const offsets = new Array(rows.length).fill(0);\n\n matches.forEach(({ from, to }) => {\n const idxLineFrom = from.line - 1;\n const idxLineTo = to.line - 1;\n\n const idxColumnFrom = from.column - 1 + offsets[idxLineFrom];\n\n rows[idxLineFrom] = this.insertToken(rows[idxLineFrom], this.tokenStart, idxColumnFrom);\n offsets[idxLineFrom] += this.tokenStart.length;\n\n const idxColumnTo = to.column + to.length - 1 + offsets[idxLineTo];\n\n rows[idxLineTo] = this.insertToken(rows[idxLineTo], this.tokenEnd, idxColumnTo);\n offsets[idxLineTo] += this.tokenEnd.length;\n });\n\n return rows.join('\\n');\n }\n}\n" }, { "alpha_fraction": 0.7453585863113403, "alphanum_fraction": 0.7459449172019958, "avg_line_length": 50.68687057495117, "blob_id": "61b8219780e7a4a1572fd3163a5711b31caad2f6", "content_id": "fb81a38a98223e1329f374703eef2e2d9ceb41c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 5117, "license_type": "permissive", "max_line_length": 189, "num_lines": 99, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ProgrammingExerciseStudentParticipationRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.time.ZonedDateTime;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.Optional;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.participation.ProgrammingExerciseStudentParticipation;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data JPA repository for the Participation entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ProgrammingExerciseStudentParticipationRepository extends JpaRepository<ProgrammingExerciseStudentParticipation, Long> {\n\n @Query(\"\"\"\n select p from ProgrammingExerciseStudentParticipation p\n left join fetch p.results pr\n left join fetch pr.feedbacks\n left join fetch pr.submission\n where p.id = :participationId\n and (pr.id = (select max(prr.id) from p.results prr\n left join prr.submission prrs\n where (prrs.type <> 'ILLEGAL' or prrs.type is null)\n and (prr.assessmentType = 'AUTOMATIC'\n or (prr.completionDate IS NOT NULL\n and (p.exercise.assessmentDueDate IS NULL\n OR p.exercise.assessmentDueDate < :#{#dateTime}))))\n or pr.id IS NULL)\n \"\"\")\n Optional<ProgrammingExerciseStudentParticipation> findByIdWithLatestResultAndFeedbacksAndRelatedLegalSubmissions(@Param(\"participationId\") Long participationId,\n @Param(\"dateTime\") ZonedDateTime dateTime);\n\n /**\n * Will return the participation with the provided participationId. The participation will come with all it's manual results, submissions, feedbacks and assessors\n *\n * @param participationId the participation id\n * @return a participation with all it's manual results.\n */\n @Query(\"\"\"\n select p from ProgrammingExerciseStudentParticipation p\n left join fetch p.results pr\n left join fetch pr.feedbacks\n left join fetch pr.submission\n left join fetch pr.assessor\n where p.id = :participationId\n and pr.id in (select prr.id from p.results prr\n where prr.assessmentType = 'MANUAL' or prr.assessmentType = 'SEMI_AUTOMATIC')\n \"\"\")\n Optional<ProgrammingExerciseStudentParticipation> findByIdWithAllManualOrSemiAutomaticResultsAndFeedbacksAndRelatedSubmissionAndAssessor(\n @Param(\"participationId\") Long participationId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"results\", \"exercise\" })\n List<ProgrammingExerciseStudentParticipation> findByBuildPlanId(String buildPlanId);\n\n @Query(\"select distinct p from ProgrammingExerciseStudentParticipation p left join fetch p.results where p.buildPlanId is not null and (p.student is not null or p.team is not null)\")\n List<ProgrammingExerciseStudentParticipation> findAllWithBuildPlanIdWithResults();\n\n Optional<ProgrammingExerciseStudentParticipation> findByExerciseIdAndStudentLogin(Long exerciseId, String username);\n\n Optional<ProgrammingExerciseStudentParticipation> findByExerciseIdAndTeamId(Long exerciseId, Long teamId);\n\n List<ProgrammingExerciseStudentParticipation> findByExerciseId(Long exerciseId);\n\n /**\n * Will return the participations matching the provided participation ids, but only if they belong to the given exercise.\n *\n * @param exerciseId is used as a filter for the found participations.\n * @param participationIds the participations to retrieve.\n * @return filtered list of participations.\n */\n @Query(\"select participation from ProgrammingExerciseStudentParticipation participation where participation.exercise.id = :#{#exerciseId} and participation.id in :#{#participationIds}\")\n List<ProgrammingExerciseStudentParticipation> findByExerciseIdAndParticipationIds(@Param(\"exerciseId\") Long exerciseId,\n @Param(\"participationIds\") Collection<Long> participationIds);\n\n @EntityGraph(type = LOAD, attributePaths = \"student\")\n Optional<ProgrammingExerciseStudentParticipation> findWithStudentById(Long participationId);\n\n @NotNull\n default ProgrammingExerciseStudentParticipation findByIdElseThrow(Long participationId) {\n return findById(participationId).orElseThrow(() -> new EntityNotFoundException(\"Programming Exercise Student Participation\", participationId));\n }\n\n default Optional<ProgrammingExerciseStudentParticipation> findStudentParticipationWithLatestResultAndFeedbacksAndRelatedLegalSubmissions(Long participationId) {\n return findByIdWithLatestResultAndFeedbacksAndRelatedLegalSubmissions(participationId, ZonedDateTime.now());\n }\n}\n" }, { "alpha_fraction": 0.6332539319992065, "alphanum_fraction": 0.6389346718788147, "avg_line_length": 44.474998474121094, "blob_id": "a246597b70e049db5077e2fe687400f8dc484d65", "content_id": "e1aefaa835093727b7975be0b1fbf6b9d72b95f9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 16371, "license_type": "permissive", "max_line_length": 112, "num_lines": 360, "path": "/src/test/javascript/spec/component/guided-tour/guided-tour.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { NO_ERRORS_SCHEMA } from '@angular/core';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { CookieService } from 'ngx-cookie-service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service';\nimport { TextTourStep } from 'app/guided-tour/guided-tour-step.model';\nimport { GuidedTour } from 'app/guided-tour/guided-tour.model';\nimport { GuidedTourComponent } from 'app/guided-tour/guided-tour.component';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { Orientation, OverlayPosition, ResetParticipation } from 'app/guided-tour/guided-tour.constants';\nimport { DeviceDetectorService } from 'ngx-device-detector';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { By } from '@angular/platform-browser';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { Authority } from 'app/shared/constants/authority.constants';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('GuidedTourComponent', () => {\n const tourStep = new TextTourStep({\n headlineTranslateKey: '',\n contentTranslateKey: '',\n });\n\n const tourStepWithPermission = new TextTourStep({\n headlineTranslateKey: '',\n contentTranslateKey: '',\n highlightPadding: 10,\n permission: [Authority.ADMIN],\n });\n\n const tourStepWithHighlightPadding = new TextTourStep({\n headlineTranslateKey: '',\n contentTranslateKey: '',\n highlightPadding: 10,\n });\n\n const courseOverviewTour: GuidedTour = {\n settingsKey: 'course_overview_tour',\n resetParticipation: ResetParticipation.EXERCISE_PARTICIPATION,\n steps: [\n tourStep,\n tourStepWithHighlightPadding,\n tourStepWithPermission,\n tourStep,\n tourStepWithHighlightPadding,\n tourStepWithPermission,\n tourStep,\n tourStepWithHighlightPadding,\n tourStepWithPermission,\n ],\n };\n\n let guidedTourComponent: GuidedTourComponent;\n let guidedTourComponentFixture: ComponentFixture<GuidedTourComponent>;\n let guidedTourService: GuidedTourService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n ArtemisTestModule,\n ArtemisSharedModule,\n RouterTestingModule.withRoutes([\n {\n path: 'courses',\n component: GuidedTourComponent,\n },\n ]),\n ],\n declarations: [GuidedTourComponent],\n schemas: [NO_ERRORS_SCHEMA],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: CookieService, useClass: MockCookieService },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: DeviceDetectorService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n guidedTourComponentFixture = TestBed.createComponent(GuidedTourComponent);\n guidedTourComponent = guidedTourComponentFixture.componentInstance;\n guidedTourService = TestBed.inject(GuidedTourService);\n });\n });\n\n it('should subscribe to events on after init', () => {\n const currentStepSpy = spyOn<any>(guidedTourComponent, 'subscribeToGuidedTourCurrentStepStream');\n const resizeEventSpy = spyOn<any>(guidedTourComponent, 'subscribeToResizeEvent');\n const scrollEventSpy = spyOn<any>(guidedTourComponent, 'subscribeToScrollEvent');\n const dotNavigationSpy = spyOn<any>(guidedTourComponent, 'subscribeToDotChanges').and.returnValue(of());\n const guidedTourInitSpy = spyOn(guidedTourService, 'init').and.returnValue(of());\n\n guidedTourComponent.ngAfterViewInit();\n\n expect(currentStepSpy.calls.count()).to.equal(1);\n expect(resizeEventSpy.calls.count()).to.equal(1);\n expect(scrollEventSpy.calls.count()).to.equal(1);\n expect(dotNavigationSpy.calls.count()).to.equal(1);\n expect(guidedTourInitSpy.calls.count()).to.equal(1);\n });\n\n it('should handle user permissions', () => {\n guidedTourComponent.currentTourStep = tourStep;\n const permission = guidedTourComponent['hasUserPermissionForCurrentTourStep']();\n expect(permission).to.be.true;\n });\n\n describe('Keydown Element', () => {\n beforeEach(async () => {\n // Prepare guided tour service\n spyOn(guidedTourService, 'init').and.returnValue(of());\n spyOn(guidedTourService, 'getLastSeenTourStepIndex').and.returnValue(0);\n spyOn<any>(guidedTourService, 'updateGuidedTourSettings');\n spyOn<any>(guidedTourService, 'enableTour').and.callFake(() => {\n guidedTourService['availableTourForComponent'] = courseOverviewTour;\n guidedTourService.currentTour = courseOverviewTour;\n });\n spyOn<any>(guidedTourComponent, 'subscribeToDotChanges').and.returnValue(of());\n\n // Prepare guided tour component\n guidedTourComponent.ngAfterViewInit();\n\n // Start course overview tour\n expect(guidedTourComponent.currentTourStep).to.not.exist;\n guidedTourService['enableTour'](courseOverviewTour, true);\n guidedTourService['startTour']();\n expect(guidedTourComponent.currentTourStep).to.exist;\n\n // Check highlight (current) dot and small dot\n guidedTourComponentFixture.detectChanges();\n const highlightDot = guidedTourComponentFixture.debugElement.query(By.css('.current'));\n expect(highlightDot).to.exist;\n const nSmallDot = guidedTourComponentFixture.debugElement.queryAll(By.css('.n-small'));\n expect(nSmallDot).to.exist;\n });\n\n it('should not trigger the guided tour with the right arrow key', () => {\n guidedTourComponent.currentTourStep = null;\n const nextStep = spyOn(guidedTourService, 'nextStep');\n const eventMock = new KeyboardEvent('keydown', { code: 'ArrowRight' });\n guidedTourComponent.handleKeyboardEvent(eventMock);\n expect(nextStep.calls.count()).to.equal(0);\n nextStep.calls.reset();\n });\n\n it('should navigate next with the right arrow key', () => {\n guidedTourComponent['currentStepIndex'] = guidedTourService.currentTourStepIndex;\n guidedTourComponent['nextStepIndex'] = guidedTourService.currentTourStepIndex + 1;\n const nextStep = spyOn(guidedTourService, 'nextStep');\n const eventMock = new KeyboardEvent('keydown', { code: 'ArrowRight' });\n guidedTourComponent.handleKeyboardEvent(eventMock);\n expect(nextStep.calls.count()).to.equal(1);\n nextStep.calls.reset();\n });\n\n it('should navigate back with the left arrow key', () => {\n const backStep = spyOn(guidedTourService, 'backStep').and.returnValue(of());\n const nextStep = spyOn(guidedTourService, 'nextStep').and.callThrough();\n const eventMockRight = new KeyboardEvent('keydown', { code: 'ArrowRight' });\n const eventMockLeft = new KeyboardEvent('keydown', { code: 'ArrowLeft' });\n\n guidedTourComponent.handleKeyboardEvent(eventMockLeft);\n expect(backStep.calls.count()).to.equal(0);\n\n guidedTourComponent.handleKeyboardEvent(eventMockRight);\n\n guidedTourComponent.handleKeyboardEvent(eventMockLeft);\n expect(backStep.calls.count()).to.equal(1);\n\n nextStep.calls.reset();\n backStep.calls.reset();\n });\n\n it('should skip the tour with the escape key', () => {\n const skipTour = spyOn(guidedTourService, 'skipTour');\n spyOn<any>(guidedTourService, 'isCurrentTour').and.returnValue(false);\n const eventMock = new KeyboardEvent('keydown', { code: 'Escape' });\n\n guidedTourComponent.handleKeyboardEvent(eventMock);\n expect(skipTour.calls.count()).to.equal(1);\n\n // Reset component\n skipTour.calls.reset();\n guidedTourComponent.currentTourStep = null;\n\n // Skip tour with ESC key should not be possible when the component is not active\n guidedTourComponent.handleKeyboardEvent(eventMock);\n expect(skipTour.calls.count()).to.equal(0);\n });\n\n it('should not skip but finish the cancel tour with the escape key', () => {\n const skipTour = spyOn(guidedTourService, 'skipTour');\n const finishTour = spyOn(guidedTourService, 'finishGuidedTour');\n spyOn<any>(guidedTourService, 'isCurrentTour').and.returnValue(true);\n const eventMock = new KeyboardEvent('keydown', { code: 'Escape' });\n\n while (!guidedTourService.isOnLastStep) {\n guidedTourService.nextStep();\n }\n\n guidedTourComponent.handleKeyboardEvent(eventMock);\n expect(skipTour.calls.count()).to.equal(0);\n expect(finishTour.calls.count()).to.equal(1);\n\n // Reset component\n skipTour.calls.reset();\n finishTour.calls.reset();\n guidedTourComponent.currentTourStep = null;\n });\n });\n\n describe('Guided Tour Step', () => {\n let selectedElement: Element;\n let selectedElementRect: DOMRect;\n\n function setOrientation(orientation: Orientation) {\n guidedTourComponent.orientation = orientation;\n guidedTourComponent.currentTourStep.orientation = orientation;\n }\n\n beforeAll(() => {\n selectedElement = document.createElement('div') as Element;\n selectedElement.id = 'overview-menu';\n selectedElementRect = selectedElement.getBoundingClientRect() as DOMRect;\n selectedElementRect.height = 50;\n selectedElementRect.width = 200;\n });\n\n beforeEach(() => {\n guidedTourComponent.currentTourStep = tourStep;\n guidedTourComponent.selectedElementRect = selectedElementRect;\n guidedTourComponent.tourStepWidth = 500;\n });\n\n afterEach(() => {\n if (guidedTourComponent.currentTourStep) {\n guidedTourComponent.currentTourStep.orientation = undefined;\n }\n });\n\n it('should determine if the tour step has bottom orientation', () => {\n expect(guidedTourComponent['isBottom']()).to.be.false;\n\n guidedTourComponent.currentTourStep!.orientation = Orientation.BOTTOM;\n expect(guidedTourComponent['isBottom']()).to.be.true;\n });\n\n it('should determine the highlight padding of the tour step', () => {\n expect(guidedTourComponent['getHighlightPadding']()).to.equal(0);\n\n guidedTourComponent.currentTourStep = tourStepWithHighlightPadding;\n expect(guidedTourComponent['getHighlightPadding']()).to.equal(10);\n });\n\n it('should calculate the top position of the tour step', () => {\n expect(guidedTourComponent.topPosition).to.equal(0);\n\n setOrientation(Orientation.BOTTOM);\n expect(guidedTourComponent.topPosition).to.equal(50);\n });\n\n it('should calculate the left position of the tour step', () => {\n expect(guidedTourComponent.leftPosition).to.equal(-350);\n });\n\n it('should calculate the width of the tour step', () => {\n expect(guidedTourComponent.calculatedTourStepWidth).to.equal(500);\n });\n\n it('should apply the right transformation', () => {\n setOrientation(Orientation.TOP);\n expect(guidedTourComponent.transform).to.equal('translateY(-100%)');\n\n guidedTourComponent.currentTourStep!.orientation = Orientation.BOTTOM;\n expect(guidedTourComponent.transform).to.equal('');\n });\n\n it('should calculate the right max width adjustment', () => {\n guidedTourComponent.tourStepWidth = 500;\n guidedTourComponent.minimalTourStepWidth = 400;\n expect(guidedTourComponent['maxWidthAdjustmentForTourStep']).to.equal(100);\n });\n\n it('should calculate the left position of the highlighted element', () => {\n guidedTourComponent.currentTourStep = tourStepWithHighlightPadding;\n expect(guidedTourComponent['calculatedHighlightLeftPosition']).to.equal(-350);\n\n setOrientation(Orientation.TOPRIGHT);\n expect(guidedTourComponent['calculatedHighlightLeftPosition']).to.equal(-500);\n\n setOrientation(Orientation.TOPLEFT);\n expect(guidedTourComponent['calculatedHighlightLeftPosition']).to.equal(0);\n\n setOrientation(Orientation.LEFT);\n expect(guidedTourComponent['calculatedHighlightLeftPosition']).to.equal(-510);\n\n setOrientation(Orientation.RIGHT);\n expect(guidedTourComponent['calculatedHighlightLeftPosition']).to.equal(210);\n });\n\n it('should adjust the width for screen bound', () => {\n guidedTourComponent.currentTourStep = tourStepWithHighlightPadding;\n expect(guidedTourComponent['widthAdjustmentForScreenBound']).to.equal(0);\n\n guidedTourComponent.tourStepWidth = 1000;\n expect(guidedTourComponent['widthAdjustmentForScreenBound']).to.equal(500);\n });\n\n it('should calculate the right style for the overlays', () => {\n // Define expected objects\n const topStyle = { 'top.px': 0, 'left.px': 0, 'height.px': 0 };\n const bottomStyle = { 'top.px': 50 };\n const leftStyle = { 'top.px': 0, 'left.px': 0, 'height.px': 50, 'width.px': 0 };\n const rightStyle = { 'top.px': 0, 'left.px': 200, 'height.px': 50 };\n\n let style = guidedTourComponent.getOverlayStyle(OverlayPosition.TOP);\n expect(JSON.stringify(style)).to.equal(JSON.stringify(topStyle));\n style = guidedTourComponent.getOverlayStyle(OverlayPosition.BOTTOM);\n expect(JSON.stringify(style)).to.equal(JSON.stringify(bottomStyle));\n style = guidedTourComponent.getOverlayStyle(OverlayPosition.LEFT);\n expect(JSON.stringify(style)).to.equal(JSON.stringify(leftStyle));\n style = guidedTourComponent.getOverlayStyle(OverlayPosition.RIGHT);\n expect(JSON.stringify(style)).to.equal(JSON.stringify(rightStyle));\n });\n\n it('should initiate flip orientation', () => {\n window.scrollTo = () => {};\n jest.useFakeTimers();\n spyOn<any>(guidedTourComponent, 'isTourOnScreen').and.returnValue(false);\n const flipOrientationSpy = spyOn<any>(guidedTourComponent, 'flipOrientation').and.returnValue(of());\n guidedTourComponent['scrollToAndSetElement']();\n expect(flipOrientationSpy.calls.count()).to.equal(0);\n\n jest.advanceTimersByTime(300);\n guidedTourComponent['scrollToAndSetElement']();\n expect(flipOrientationSpy.calls.count()).to.equal(1);\n });\n\n it('should flip orientation', () => {\n setOrientation(Orientation.BOTTOMLEFT);\n guidedTourComponent['flipOrientation']();\n expect(guidedTourComponent.orientation).to.equal(Orientation.BOTTOMRIGHT);\n\n setOrientation(Orientation.TOPRIGHT);\n guidedTourComponent['flipOrientation']();\n expect(guidedTourComponent.orientation).to.equal(Orientation.TOPLEFT);\n });\n });\n});\n" }, { "alpha_fraction": 0.6797658801078796, "alphanum_fraction": 0.681438148021698, "avg_line_length": 34.17647171020508, "blob_id": "8f8eaa3ec5d9bd33fa55b1fd14cf773012ddfa84", "content_id": "b3fafa9fa88b5132df0b7999dbb402cf7eaadc7d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1196, "license_type": "permissive", "max_line_length": 72, "num_lines": 34, "path": "/src/main/webapp/app/exercises/text/assess/conflicts/conflicts-header/text-feedback-conflicts-header.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, Output, EventEmitter } from '@angular/core';\n\n@Component({\n selector: 'jhi-text-feedback-conflicts-header',\n templateUrl: './text-feedback-conflicts-header.component.html',\n styleUrls: ['./text-feedback-conflicts-header.component.scss'],\n})\nexport class TextFeedbackConflictsHeaderComponent {\n @Input() numberOfConflicts: number;\n @Input() haveRights: boolean;\n @Input() overrideBusy: boolean;\n @Input() markBusy: boolean;\n @Input() isOverrideDisabled: boolean;\n @Input() isMarkingDisabled: boolean;\n @Output() didChangeConflictIndex = new EventEmitter<number>();\n @Output() overrideLeftSubmission = new EventEmitter<void>();\n @Output() discardConflict = new EventEmitter<void>();\n\n currentConflictIndex = 1;\n\n onNextConflict() {\n if (this.currentConflictIndex < this.numberOfConflicts) {\n this.currentConflictIndex++;\n this.didChangeConflictIndex.emit(this.currentConflictIndex);\n }\n }\n\n onPrevConflict() {\n if (this.currentConflictIndex > 1) {\n this.currentConflictIndex--;\n this.didChangeConflictIndex.emit(this.currentConflictIndex);\n }\n }\n}\n" }, { "alpha_fraction": 0.6448651552200317, "alphanum_fraction": 0.6467775702476501, "avg_line_length": 35.823944091796875, "blob_id": "956f4c53f8f0b56f5b7fa1d1d27b3940127da4ae", "content_id": "d0db374858148ebedcda6741522ae5d1e023c135", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5229, "license_type": "permissive", "max_line_length": 175, "num_lines": 142, "path": "/src/main/webapp/app/course/dashboards/instructor-course-dashboard/instructor-course-dashboard.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { JhiAlertService } from 'ng-jhipster';\nimport { Component, OnInit } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from '../../manage/course-management.service';\nimport { catchError, map, tap } from 'rxjs/operators';\nimport { of, zip } from 'rxjs';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { StatsForDashboard } from 'app/course/dashboards/instructor-course-dashboard/stats-for-dashboard.model';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { getIcon, getIconTooltip, ExerciseType } from 'app/entities/exercise.model';\nimport { User } from 'app/core/user/user.model';\nimport { AccountService } from 'app/core/auth/account.service';\n\n@Component({\n selector: 'jhi-instructor-course-dashboard',\n templateUrl: './instructor-course-dashboard.component.html',\n providers: [],\n})\nexport class InstructorCourseDashboardComponent implements OnInit {\n course: Course;\n instructor: User;\n\n getIcon = getIcon;\n getIconTooltip = getIconTooltip;\n\n isLoading = true;\n exercisesSortingPredicate = 'assessmentDueDate';\n exercisesReverseOrder = false;\n\n stats = new StatsForDashboard();\n dataForAssessmentPieChart: number[];\n\n readonly MIN_POINTS_GREEN = 100;\n readonly MIN_POINTS_ORANGE = 50;\n\n readonly ExerciseType = ExerciseType;\n\n constructor(\n private courseService: CourseManagementService,\n private resultService: ResultService,\n private route: ActivatedRoute,\n private jhiAlertService: JhiAlertService,\n private sortService: SortService,\n private accountService: AccountService,\n ) {}\n\n /**\n * On init fetch the course from the server.\n */\n ngOnInit(): void {\n this.isLoading = true;\n this.loadCourse(Number(this.route.snapshot.paramMap.get('courseId')));\n this.accountService.identity().then((user) => {\n if (user) {\n this.instructor = user;\n }\n });\n }\n\n /**\n * Load the course and statistics relevant for instructors for a course.\n * @param courseId ID of the course to load.\n */\n private loadCourse(courseId: number) {\n // Load the course.\n const loadCourseObservable = this.courseService.findWithExercisesAndParticipations(courseId).pipe(\n map((res: HttpResponse<Course>) => res.body!),\n tap((course: Course) => {\n this.course = Course.from(course);\n }),\n catchError((response: HttpErrorResponse) => {\n this.onError(response.message);\n return of(null);\n }),\n );\n\n // Load course stats.\n const loadStatsObservable = this.courseService.getStatsForInstructors(courseId).pipe(\n map((res: HttpResponse<StatsForDashboard>) => Object.assign({}, this.stats, res.body)),\n tap((stats) => {\n this.stats = StatsForDashboard.from(stats);\n this.sortService.sortByProperty(this.stats.tutorLeaderboardEntries, 'points', false);\n this.dataForAssessmentPieChart = [this.stats.numberOfSubmissions.total - this.stats.totalNumberOfAssessments.total, this.stats.totalNumberOfAssessments.total];\n }),\n catchError((response: string) => {\n this.onError(response);\n return of(null);\n }),\n );\n\n // After both calls are done, the loading flag is removed.\n zip(loadCourseObservable, loadStatsObservable).subscribe(() => {\n this.isLoading = false;\n });\n }\n\n /**\n * Calculate rounded towards zero percentage for given numerator and denominator.\n * @param numerator\n * @param denominator\n * @return {number} percentage for given numerator and denominator that is rounded towards zero\n */\n calculatePercentage(numerator: number, denominator: number): number {\n if (denominator === 0) {\n return 0;\n }\n\n return Math.floor((numerator / denominator) * 100);\n }\n\n /**\n * Return class of assessment progress.\n * @param numberOfAssessments Number of assessed submissions.\n * @param length Total number of participations.\n * @return {string} 'bg-danger', 'bg-warning' or 'bg-success' depending on percentage of assessed submissions.\n */\n calculateClass(numberOfAssessments: number, length: number): string {\n const percentage = this.calculatePercentage(numberOfAssessments, length);\n\n if (percentage < this.MIN_POINTS_ORANGE) {\n return 'bg-danger';\n } else if (percentage < this.MIN_POINTS_GREEN) {\n return 'bg-warning';\n }\n\n return 'bg-success';\n }\n\n sortRows() {\n this.sortService.sortByProperty(this.course.exercises!, this.exercisesSortingPredicate, this.exercisesReverseOrder);\n }\n\n /**\n * Pass an error to the jhiAlertService.\n * @param error\n */\n private onError(error: string) {\n this.jhiAlertService.error(error);\n }\n}\n" }, { "alpha_fraction": 0.6637998223304749, "alphanum_fraction": 0.6637998223304749, "avg_line_length": 38.96875, "blob_id": "d66bea1c3fd793e068290d237dbf283c9c72a23c", "content_id": "e7b5729586a0362dc76fbe4b6599faaf6c116c4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1279, "license_type": "permissive", "max_line_length": 107, "num_lines": 32, "path": "/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise-row-buttons.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input } from '@angular/core';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport { Subject } from 'rxjs';\nimport { JhiEventManager } from 'ng-jhipster';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { TextExercise } from 'app/entities/text-exercise.model';\n\n@Component({\n selector: 'jhi-text-exercise-row-buttons',\n templateUrl: './text-exercise-row-buttons.component.html',\n})\nexport class TextExerciseRowButtonsComponent {\n @Input() courseId: number;\n @Input() exercise: TextExercise;\n private dialogErrorSource = new Subject<string>();\n dialogError$ = this.dialogErrorSource.asObservable();\n\n constructor(private textExerciseService: TextExerciseService, private eventManager: JhiEventManager) {}\n\n deleteExercise() {\n this.textExerciseService.delete(this.exercise.id!).subscribe(\n () => {\n this.eventManager.broadcast({\n name: 'textExerciseListModification',\n content: 'Deleted a textExercise',\n });\n this.dialogErrorSource.next('');\n },\n (error: HttpErrorResponse) => this.dialogErrorSource.next(error.message),\n );\n }\n}\n" }, { "alpha_fraction": 0.5885205268859863, "alphanum_fraction": 0.5959933400154114, "avg_line_length": 35.2507209777832, "blob_id": "9f66702cd27d4c628f969ce8e06b4ae52c02c995", "content_id": "587b2b453253f0e501483b7698a50fc4341db56e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 12579, "license_type": "permissive", "max_line_length": 168, "num_lines": 347, "path": "/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-statistic/quiz-statistic.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { HttpResponse } from '@angular/common/http';\nimport { Chart, ChartAnimationOptions, ChartOptions, ChartType, LinearTickOptions } from 'chart.js';\nimport { Subscription } from 'rxjs/Subscription';\nimport { QuizStatisticUtil } from 'app/exercises/quiz/shared/quiz-statistic-util.service';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service';\nimport { Authority } from 'app/shared/constants/authority.constants';\nimport { BaseChartDirective, Color } from 'ng2-charts';\n\n/**\n * this interface is adapted from chart.js\n */\nexport interface DataSet {\n data: number[];\n backgroundColor: string[];\n}\n\nexport interface ChartElement {\n chart: Chart;\n}\n\n// this code is reused in 4 different statistic components\nexport function createOptions(dataSetProvider: DataSetProvider, max: number, stepSize: number, xLabel: string, yLabel: string): ChartOptions {\n return {\n layout: {\n padding: {\n left: 0,\n right: 0,\n top: 0,\n bottom: 30,\n },\n },\n legend: {\n display: false,\n },\n title: {\n display: false,\n text: '',\n position: 'top',\n fontSize: 16,\n padding: 20,\n },\n tooltips: {\n enabled: false,\n },\n scales: {\n yAxes: [\n {\n display: true,\n scaleLabel: {\n labelString: xLabel,\n display: true,\n },\n ticks: {\n beginAtZero: true,\n stepSize,\n max,\n min: 0,\n } as LinearTickOptions,\n },\n ],\n xAxes: [\n {\n scaleLabel: {\n labelString: yLabel,\n display: true,\n },\n },\n ],\n },\n hover: { animationDuration: 0 },\n animation: createAnimation(dataSetProvider),\n };\n}\n\n// this code is reused in 4 different statistic components\nexport function createAnimation(dataSetProvider: DataSetProvider): ChartAnimationOptions {\n return {\n duration: 500,\n onComplete: (chartElement: ChartElement) => {\n const chartInstance = chartElement.chart;\n const ctx = chartInstance.ctx!;\n\n ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);\n ctx.textAlign = 'center';\n ctx.textBaseline = 'bottom';\n const participants = dataSetProvider.getParticipants();\n\n dataSetProvider.getDataSets().forEach((dataset: DataSet, datasetIndex: number) => {\n const meta = chartInstance.getDatasetMeta(datasetIndex);\n meta.data.forEach((bar: any, dataIndex: number) => {\n const data = (Math.round(dataset.data[dataIndex] * 100) / 100).toString();\n const dataPercentage = Math.round((dataset.data[dataIndex] / participants) * 1000) / 10 || 0;\n ctx.fillText(data, bar._model.x, bar._model.y - 20);\n ctx.fillText(`(${dataPercentage}%)`, bar._model.x, bar._model.y - 5);\n });\n });\n },\n };\n}\n\nexport interface DataSetProvider {\n getDataSets(): DataSet[];\n getParticipants(): number;\n\n /**\n * check if the rated or unrated\n * load the rated or unrated data into the diagram\n */\n loadDataInDiagram(): void;\n}\n\nexport function calculateHeightOfChart(dataSetProvider: DataSetProvider) {\n const data = dataSetProvider.getDataSets().map((dataset) => {\n return dataset.data;\n });\n const flattened = ([] as number[]).concat(...data);\n const max = Math.max(...flattened);\n // we provide 300 as buffer at the top to display labels\n const height = Math.ceil((max + 1) / 10) * 10;\n if (height < 10) {\n return height + 3;\n } else if (height < 1000) {\n // add 25%, round to the next 10\n return Math.ceil(height * 0.125) * 10;\n } else {\n // add 25%, round to the next 100\n return Math.ceil(height * 0.0125) * 100;\n }\n}\n\n@Component({\n selector: 'jhi-quiz-statistic',\n templateUrl: './quiz-statistic.component.html',\n})\nexport class QuizStatisticComponent implements OnInit, OnDestroy, DataSetProvider {\n @ViewChild(BaseChartDirective) chart: BaseChartDirective;\n\n quizExercise: QuizExercise;\n private sub: Subscription;\n\n labels: string[] = [];\n data: number[] = [];\n colors: Color[] = [];\n chartType: ChartType = 'bar';\n datasets: DataSet[] = [];\n\n label: string[] = [];\n ratedData: number[] = [];\n unratedData: number[] = [];\n backgroundColor: string[] = [];\n ratedAverage: number;\n unratedAverage: number;\n\n maxScore: number;\n rated = true;\n participants: number;\n websocketChannelForData: string;\n\n // options for chart.js style\n options: ChartOptions;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n private accountService: AccountService,\n private translateService: TranslateService,\n private quizExerciseService: QuizExerciseService,\n private quizStatisticUtil: QuizStatisticUtil,\n private jhiWebsocketService: JhiWebsocketService,\n ) {}\n\n loadDataInDiagram(): void {\n throw new Error('Method not implemented.');\n }\n\n ngOnInit() {\n this.sub = this.route.params.subscribe((params) => {\n // use different REST-call if the User is a Student\n if (this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.quizExerciseService.find(params['exerciseId']).subscribe((res: HttpResponse<QuizExercise>) => {\n this.loadQuizSuccess(res.body!);\n });\n }\n\n // subscribe websocket for new statistical data\n this.websocketChannelForData = '/topic/statistic/' + params['exerciseId'];\n this.jhiWebsocketService.subscribe(this.websocketChannelForData);\n\n // ask for new Data if the websocket for new statistical data was notified\n this.jhiWebsocketService.receive(this.websocketChannelForData).subscribe(() => {\n if (this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.quizExerciseService.find(params['exerciseId']).subscribe((res) => {\n this.loadQuizSuccess(res.body!);\n });\n }\n });\n });\n }\n\n ngOnDestroy() {\n this.jhiWebsocketService.unsubscribe(this.websocketChannelForData);\n }\n\n getDataSets() {\n return this.datasets;\n }\n\n getParticipants() {\n return this.participants;\n }\n\n /**\n * This functions loads the Quiz, which is necessary to build the Web-Template\n * And it loads the new Data if the Websocket has been notified\n *\n * @param {QuizExercise} quiz: the quizExercise, which the this quiz-statistic presents.\n */\n loadQuizSuccess(quiz: QuizExercise) {\n // if the Student finds a way to the Website -> the Student will be send back to Courses\n if (!this.accountService.hasAnyAuthorityDirect([Authority.ADMIN, Authority.INSTRUCTOR, Authority.TA])) {\n this.router.navigate(['/courses']);\n }\n this.quizExercise = quiz;\n this.maxScore = this.calculateMaxScore();\n this.loadData();\n }\n\n /**\n * calculate the maximal possible Score for the quiz\n *\n * @return (int): sum over the Scores of all questions\n */\n calculateMaxScore() {\n let result = 0;\n\n if (this.quizExercise.quizQuestions) {\n this.quizExercise.quizQuestions.forEach(function (question) {\n result = result + question.points!;\n });\n } else {\n result = this.quizExercise.maxPoints!;\n }\n return result;\n }\n\n /**\n * load the Data from the Json-entity to the chart: myChart\n */\n loadData() {\n // reset old data\n this.label = [];\n this.backgroundColor = [];\n this.ratedData = [];\n this.unratedData = [];\n this.ratedAverage = 0;\n this.unratedAverage = 0;\n\n // set data based on the CorrectCounters in the QuestionStatistics\n for (let i = 0; i < this.quizExercise.quizQuestions!.length; i++) {\n const question = this.quizExercise.quizQuestions![i];\n const statistic = question.quizQuestionStatistic!;\n const ratedCounter = statistic.ratedCorrectCounter!;\n const unratedCounter = statistic.unRatedCorrectCounter!;\n this.label.push(i + 1 + '.');\n this.backgroundColor.push('#5bc0de');\n this.ratedData.push(ratedCounter);\n this.unratedData.push(unratedCounter);\n this.ratedAverage = this.ratedAverage + ratedCounter * question.points!;\n this.unratedAverage = this.unratedAverage + unratedCounter * question.points!;\n }\n\n // set Background for invalid questions = grey\n for (let i = 0; i < this.quizExercise.quizQuestions!.length; i++) {\n if (this.quizExercise.quizQuestions![i].invalid) {\n this.backgroundColor[i] = '#949494';\n }\n }\n\n // add data for the last bar (Average)\n this.backgroundColor.push('#1e3368');\n this.ratedData.push(this.ratedAverage / this.maxScore);\n this.unratedData.push(this.unratedAverage / this.maxScore);\n\n // load data into the chart\n this.labels = this.label;\n this.colors = this.backgroundColor.map((backgroundColor) => ({ backgroundColor }));\n\n // add Text for last label based on the language\n const lastLabel = this.translateService.instant('showStatistic.quizStatistic.average');\n this.label.push(lastLabel);\n\n // if this.rated == true -> load the rated data\n if (this.rated) {\n this.participants = this.quizExercise.quizPointStatistic!.participantsRated!;\n this.data = this.ratedData;\n } else {\n // load the unrated data\n this.participants = this.quizExercise.quizPointStatistic!.participantsUnrated!;\n this.data = this.unratedData;\n }\n\n this.updateChart();\n }\n\n /**\n * switch between showing and hiding the solution in the chart\n * 1. change the amount of participants\n * 2. change the bar-Data\n */\n switchRated() {\n if (this.rated) {\n // load unrated Data\n this.data = this.unratedData;\n this.participants = this.quizExercise.quizPointStatistic!.participantsUnrated!;\n this.rated = false;\n } else {\n // load rated Data\n this.data = this.ratedData;\n this.participants = this.quizExercise.quizPointStatistic!.participantsRated!;\n this.rated = true;\n }\n\n this.updateChart();\n }\n\n /**\n * updates the chart by setting the data set, re-calculating the height and calling update on the chart view child\n */\n updateChart() {\n this.datasets = [{ data: this.data, backgroundColor: this.colors.map((color) => color.backgroundColor as string) }];\n // recalculate the height of the chart because rated/unrated might have changed or new results might have appeared\n const height = calculateHeightOfChart(this);\n // add Axes-labels based on selected language\n const xLabel = this.translateService.instant('showStatistic.quizStatistic.xAxes');\n const yLabel = this.translateService.instant('showStatistic.quizStatistic.yAxes');\n this.options = createOptions(this, height, height / 5, xLabel, yLabel);\n if (this.chart) {\n this.chart.update(0);\n }\n }\n}\n" }, { "alpha_fraction": 0.6162790656089783, "alphanum_fraction": 0.6183013319969177, "avg_line_length": 34.53293228149414, "blob_id": "28618bb1fea68313ef93ef3763d97174b7d0bdf4", "content_id": "4c451bb6b81624a73b723d2039566bd813393606", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5934, "license_type": "permissive", "max_line_length": 165, "num_lines": 167, "path": "/src/main/webapp/app/course/learning-goals/learning-goal-form/learning-goal-form.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core';\nimport { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { of } from 'rxjs';\nimport { catchError, delay, map, switchMap } from 'rxjs/operators';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { LectureUnit } from 'app/entities/lecture-unit/lectureUnit.model';\nimport { TranslateService } from '@ngx-translate/core';\nimport * as _ from 'lodash';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\n\n/**\n * Async Validator to make sure that a learning goal title is unique within a course\n */\nexport const titleUniqueValidator = (learningGoalService: LearningGoalService, courseId: number, initialTitle?: string) => {\n return (learningGoalTitleControl: FormControl) => {\n return of(learningGoalTitleControl.value).pipe(\n delay(250),\n switchMap((title) => {\n if (initialTitle && title === initialTitle) {\n return of(null);\n }\n return learningGoalService.getAllForCourse(courseId).pipe(\n map((res) => {\n let learningGoalTitles: string[] = [];\n if (res.body) {\n learningGoalTitles = res.body.map((learningGoal) => learningGoal.title!);\n }\n if (learningGoalTitles.includes(title)) {\n return {\n titleUnique: { valid: false },\n };\n } else {\n return null;\n }\n }),\n catchError(() => of(null)),\n );\n }),\n );\n };\n};\n\nexport interface LearningGoalFormData {\n title?: string;\n description?: string;\n connectedLectureUnits?: LectureUnit[];\n}\n\n@Component({\n selector: 'jhi-learning-goal-form',\n templateUrl: './learning-goal-form.component.html',\n styleUrls: ['./learning-goal-form.component.scss'],\n})\nexport class LearningGoalFormComponent implements OnInit, OnChanges {\n @Input()\n formData: LearningGoalFormData = {\n title: undefined,\n description: undefined,\n connectedLectureUnits: undefined,\n };\n\n @Input()\n isEditMode = false;\n @Input()\n courseId: number;\n @Input()\n lecturesOfCourseWithLectureUnits: Lecture[] = [];\n\n titleUniqueValidator = titleUniqueValidator;\n\n @Output()\n formSubmitted: EventEmitter<LearningGoalFormData> = new EventEmitter<LearningGoalFormData>();\n\n form: FormGroup;\n selectedLectureInDropdown: Lecture;\n selectedLectureUnitsInTable: LectureUnit[] = [];\n\n constructor(\n private fb: FormBuilder,\n private learningGoalService: LearningGoalService,\n private translateService: TranslateService,\n public lectureUnitService: LectureUnitService,\n ) {}\n\n get titleControl() {\n return this.form.get('title');\n }\n\n get descriptionControl() {\n return this.form.get('description');\n }\n\n ngOnChanges(): void {\n this.initializeForm();\n if (this.isEditMode && this.formData) {\n this.setFormValues(this.formData);\n }\n }\n\n ngOnInit(): void {\n this.initializeForm();\n }\n\n private initializeForm() {\n if (this.form) {\n return;\n }\n let initialTitle: string | undefined = undefined;\n if (this.isEditMode && this.formData && this.formData.title) {\n initialTitle = this.formData.title;\n }\n this.form = this.fb.group({\n title: [undefined, [Validators.required, Validators.maxLength(255)], [this.titleUniqueValidator(this.learningGoalService, this.courseId, initialTitle)]],\n description: [undefined, [Validators.maxLength(10000)]],\n });\n this.selectedLectureUnitsInTable = [];\n }\n\n private setFormValues(formData: LearningGoalFormData) {\n this.form.patchValue(formData);\n if (formData.connectedLectureUnits) {\n this.selectedLectureUnitsInTable = formData.connectedLectureUnits;\n }\n }\n\n submitForm() {\n const learningGoalFormData: LearningGoalFormData = { ...this.form.value };\n learningGoalFormData.connectedLectureUnits = this.selectedLectureUnitsInTable;\n this.formSubmitted.emit(learningGoalFormData);\n }\n\n get isSubmitPossible() {\n return !this.form.invalid;\n }\n\n selectLectureInDropdown(lecture: Lecture) {\n this.selectedLectureInDropdown = lecture;\n }\n\n selectLectureUnitInTable(lectureUnit: LectureUnit) {\n if (this.isLectureUnitAlreadySelectedInTable(lectureUnit)) {\n this.selectedLectureUnitsInTable.forEach((selectedLectureUnit, index) => {\n if (selectedLectureUnit.id === lectureUnit.id) {\n this.selectedLectureUnitsInTable.splice(index, 1);\n }\n });\n } else {\n this.selectedLectureUnitsInTable.push(lectureUnit);\n }\n }\n\n isLectureUnitAlreadySelectedInTable(lectureUnit: LectureUnit) {\n return this.selectedLectureUnitsInTable.map((selectedLectureUnit) => selectedLectureUnit.id).includes(lectureUnit.id);\n }\n\n getLectureTitleForDropdown(lecture: Lecture) {\n const noOfSelectedUnitsInLecture = _.intersection(\n this.selectedLectureUnitsInTable.map((u) => u.id),\n lecture.lectureUnits?.map((u) => u.id),\n ).length;\n return this.translateService.instant('artemisApp.learningGoal.createLearningGoal.dropdown', {\n lectureTitle: lecture.title,\n noOfConnectedUnits: noOfSelectedUnitsInLecture,\n });\n }\n}\n" }, { "alpha_fraction": 0.6618798971176147, "alphanum_fraction": 0.662140965461731, "avg_line_length": 43.022987365722656, "blob_id": "d913ef5a5de5e2c4aa8c5a45c2f215abab719e08", "content_id": "3e67801217bf091f243c4c9a528e4e519250cecd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3830, "license_type": "permissive", "max_line_length": 154, "num_lines": 87, "path": "/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-solution.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, ViewChild } from '@angular/core';\nimport { SafeHtml } from '@angular/platform-browser';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { UMLModel } from '@ls1intum/apollon';\nimport { ArtemisMarkdownService } from 'app/shared/markdown.service';\nimport { ModelingEditorComponent } from 'app/exercises/modeling/shared/modeling-editor.component';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\n\n@Component({\n selector: 'jhi-example-modeling-solution',\n templateUrl: './example-modeling-solution.component.html',\n styleUrls: ['./example-modeling-solution.component.scss'],\n})\nexport class ExampleModelingSolutionComponent implements OnInit {\n @ViewChild(ModelingEditorComponent, { static: false })\n modelingEditor: ModelingEditorComponent;\n\n exercise: ModelingExercise;\n exerciseId: number;\n exampleSolution: UMLModel;\n isAtLeastInstructor = false;\n formattedProblemStatement: SafeHtml | null;\n\n constructor(\n private exerciseService: ModelingExerciseService,\n private jhiAlertService: JhiAlertService,\n private accountService: AccountService,\n private route: ActivatedRoute,\n private router: Router,\n private artemisMarkdown: ArtemisMarkdownService,\n ) {}\n\n ngOnInit(): void {\n this.exerciseId = Number(this.route.snapshot.paramMap.get('exerciseId'));\n\n this.exerciseService.find(this.exerciseId).subscribe((exerciseResponse: HttpResponse<ModelingExercise>) => {\n this.exercise = exerciseResponse.body!;\n if (this.exercise.sampleSolutionModel) {\n this.exampleSolution = JSON.parse(this.exercise.sampleSolutionModel);\n }\n this.isAtLeastInstructor = this.accountService.isAtLeastInstructorInCourse(this.exercise.course || this.exercise.exerciseGroup!.exam!.course);\n this.formattedProblemStatement = this.artemisMarkdown.safeHtmlForMarkdown(this.exercise.problemStatement);\n });\n }\n\n saveExampleSolution(): void {\n if (!this.exercise || !this.modelingEditor.getCurrentModel()) {\n return;\n }\n this.exampleSolution = this.modelingEditor.getCurrentModel();\n this.exercise.sampleSolutionModel = JSON.stringify(this.exampleSolution);\n this.exerciseService.update(this.exercise).subscribe(\n (exerciseResponse: HttpResponse<ModelingExercise>) => {\n this.exercise = exerciseResponse.body!;\n if (this.exercise.sampleSolutionModel) {\n this.exampleSolution = JSON.parse(this.exercise.sampleSolutionModel);\n }\n this.jhiAlertService.success('artemisApp.modelingEditor.saveSuccessful');\n },\n (error: HttpErrorResponse) => {\n this.jhiAlertService.error(error.message);\n },\n );\n }\n\n async back() {\n if (this.exercise.course) {\n await this.router.navigate(['/course-management', this.exercise.course?.id, 'modeling-exercises', this.exerciseId, 'edit']);\n } else {\n await this.router.navigate([\n '/course-management',\n this.exercise.exerciseGroup?.exam?.course?.id,\n 'exams',\n this.exercise.exerciseGroup?.exam?.id,\n 'exercise-groups',\n this.exercise.exerciseGroup?.id,\n 'modeling-exercises',\n this.exerciseId,\n 'edit',\n ]);\n }\n }\n}\n" }, { "alpha_fraction": 0.6056607961654663, "alphanum_fraction": 0.6082144975662231, "avg_line_length": 39.860870361328125, "blob_id": "dbb4f79f43f59cafc60bc43f066a81a8fa2d8ab6", "content_id": "cfabdd193baa42b8ea3d49925c65dec295a23aa5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4699, "license_type": "permissive", "max_line_length": 175, "num_lines": 115, "path": "/src/main/webapp/app/exercises/shared/team/teams-import-dialog/teams-import-from-file-form.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ChangeDetectorRef, Component, EventEmitter, Output } from '@angular/core';\nimport { TranslateService } from '@ngx-translate/core';\nimport { User } from 'app/core/user/user.model';\nimport { StudentWithTeam } from 'app/entities/team.model';\nimport { Team } from 'app/entities/team.model';\nimport { shortNamePattern } from 'app/shared/constants/input.constants';\n\n@Component({\n selector: 'jhi-teams-import-from-file-form',\n templateUrl: './teams-import-from-file-form.component.html',\n styleUrls: ['./teams-import-from-file-form.component.scss'],\n})\nexport class TeamsImportFromFileFormComponent {\n @Output() teamsChanged = new EventEmitter<Team[]>();\n sourceTeams?: Team[];\n importedTeams: StudentWithTeam[] = [];\n importFile?: Blob;\n importFileName: string;\n loading: boolean;\n\n constructor(private changeDetector: ChangeDetectorRef, private translate: TranslateService) {}\n\n /**\n * Move file reader creation to separate function to be able to mock\n * https://fromanegg.com/post/2015/04/22/easy-testing-of-code-involving-native-methods-in-javascript/\n */\n generateFileReader() {\n return new FileReader();\n }\n\n /**\n * Converts teams from file to expected team type\n * @param {FileReader} $fileReader object that is generated by generateFileReader\n */\n onFileLoadImport(fileReader: FileReader) {\n try {\n // Read the file and get list of teams from the file\n this.importedTeams = JSON.parse(fileReader.result as string) as StudentWithTeam[];\n this.sourceTeams = this.convertTeams(this.importedTeams);\n this.teamsChanged.emit(this.sourceTeams);\n this.loading = false;\n // Clearing html elements,\n this.importFile = undefined;\n this.importFileName = '';\n const control = document.getElementById('importFileInput') as HTMLInputElement;\n if (control) {\n control.value = '';\n }\n } catch (e) {\n this.loading = false;\n const message = `${this.translate.instant('artemisApp.team.errors.importFailed')} ${e}`;\n alert(message);\n }\n }\n\n /**\n * Assigns the uploaded import file\n * @param $event object containing the uploaded file\n */\n setImportFile($event: any): void {\n if ($event.target.files.length) {\n const fileList: FileList = $event.target.files;\n this.importFile = fileList[0];\n this.importFileName = this.importFile['name'];\n this.loading = true;\n }\n if (!this.importFile) {\n return;\n }\n const fileReader = this.generateFileReader();\n fileReader.onload = () => this.onFileLoadImport(fileReader);\n fileReader.readAsText(this.importFile);\n this.changeDetector.detectChanges();\n }\n\n /**\n * Convert imported team list to normal teams\n */\n convertTeams(importTeam: StudentWithTeam[]): Team[] {\n const teams: Team[] = [];\n importTeam.forEach((student) => {\n const newStudent = new User();\n newStudent.firstName = student.firstName ?? '';\n newStudent.lastName = student.lastName ?? '';\n newStudent.visibleRegistrationNumber = student.registrationNumber;\n newStudent.login = student.username;\n\n if ((typeof student.username !== 'string' || !student.username.trim()) && (typeof student.registrationNumber !== 'string' || !student.registrationNumber.trim())) {\n throw new Error(this.translate.instant('artemisApp.team.missingUserNameOrId'));\n }\n\n if (typeof student.teamName !== 'string' || !student.teamName.trim()) {\n throw new Error(this.translate.instant('artemisApp.team.teamName.missingTeamName'));\n }\n\n const shortName = student.teamName.replace(/[^0-9a-z]/gi, '').toLowerCase();\n if (!shortName.match(shortNamePattern)) {\n throw new Error(this.translate.instant('artemisApp.team.teamName.pattern'));\n }\n\n newStudent.name = `${newStudent.firstName} ${newStudent.lastName}`.trim();\n const index = teams.findIndex((team) => team.name === student.teamName);\n if (index === -1) {\n const newTeam = new Team();\n newTeam.name = student.teamName;\n newTeam.shortName = shortName;\n newTeam.students = [newStudent];\n teams.push(newTeam);\n } else {\n teams[index].students = [...teams[index].students!, newStudent];\n }\n });\n return teams;\n }\n}\n" }, { "alpha_fraction": 0.6542927622795105, "alphanum_fraction": 0.6565771698951721, "avg_line_length": 37.625, "blob_id": "10dd53c5a28b582a3b7c9e30849f732bbc22213a", "content_id": "c90cd2bc35d12acc6db1b5e38837d9e4e7179c3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5253, "license_type": "permissive", "max_line_length": 153, "num_lines": 136, "path": "/src/test/javascript/spec/component/exam/manage/exam-management.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { HttpResponse } from '@angular/common/http';\nimport { Observable, of } from 'rxjs';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { ArtemisTestModule } from '../../../test.module';\nimport { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockTranslateService } from '../../../helpers/mocks/service/mock-translate.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ActivatedRoute, convertToParamMap, UrlSegment } from '@angular/router';\nimport { Course } from 'app/entities/course.model';\nimport { ExamManagementComponent } from 'app/exam/manage/exam-management.component';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Exam Management Component', () => {\n const course = { id: 456 } as Course;\n const exam = new Exam();\n exam.course = course;\n exam.id = 123;\n\n let comp: ExamManagementComponent;\n let fixture: ComponentFixture<ExamManagementComponent>;\n let service: ExamManagementService;\n let courseManagementService: CourseManagementService;\n\n const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) }, url: new Observable<UrlSegment[]>() } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule],\n declarations: [ExamManagementComponent],\n providers: [\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: route },\n ],\n })\n .overrideTemplate(ExamManagementComponent, '')\n .compileComponents();\n\n fixture = TestBed.createComponent(ExamManagementComponent);\n comp = fixture.componentInstance;\n service = TestBed.inject(ExamManagementService);\n courseManagementService = TestBed.inject(CourseManagementService);\n });\n\n afterEach(function () {\n // completely restore all fakes created through the sandbox\n sinon.restore();\n });\n\n it('Should call findAllExamsForCourse on init', () => {\n // GIVEN\n const responseFakeExams = { body: [exam] } as HttpResponse<Exam[]>;\n const responseFakeCourse = { body: { id: 456 } as Course } as HttpResponse<Course>;\n sinon.replace(courseManagementService, 'find', sinon.fake.returns(of(responseFakeCourse)));\n sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeExams)));\n\n // WHEN\n comp.ngOnInit();\n\n // THEN\n expect(service.findAllExamsForCourse).to.have.been.calledOnce;\n expect(comp.exams[0]).to.eq(exam);\n });\n\n it('Should delete an exam when delete exam is called', () => {\n // GIVEN\n comp.exams = [exam];\n comp.course = course;\n const responseFakeDelete = {} as HttpResponse<any[]>;\n const responseFakeEmptyExamArray = { body: [exam] } as HttpResponse<Exam[]>;\n sinon.replace(service, 'delete', sinon.fake.returns(of(responseFakeDelete)));\n sinon.replace(service, 'findAllExamsForCourse', sinon.fake.returns(of(responseFakeEmptyExamArray)));\n\n // WHEN\n comp.deleteExam(exam.id!);\n\n // THEN\n expect(service.delete).to.have.been.calledOnce;\n });\n\n it('Should return true for examHasFinished when component has no exam information ', () => {\n // GIVEN\n exam.latestIndividualEndDate = undefined;\n\n // WHEN\n const examHasFinished = comp.examHasFinished(exam);\n\n // THEN\n expect(examHasFinished).to.be.false;\n });\n\n it('Should return true for examHasFinished when component has information of other exams', () => {\n // GIVEN\n exam.latestIndividualEndDate = undefined;\n\n // WHEN\n const examHasFinished = comp.examHasFinished(exam);\n\n // THEN\n expect(examHasFinished).to.be.false;\n });\n\n it('Should return true for examHasFinished when exam is in the past ', () => {\n // GIVEN\n exam.latestIndividualEndDate = moment().subtract(1, 'days');\n\n // WHEN\n const examHasFinished = comp.examHasFinished(exam);\n\n // THEN\n expect(examHasFinished).to.be.true;\n });\n\n it('Should return false for examHasFinished when exam is in the future ', () => {\n // GIVEN\n exam.latestIndividualEndDate = moment().add(1, 'minute');\n\n // WHEN\n const examHasFinished = comp.examHasFinished(exam);\n\n // THEN\n expect(examHasFinished).to.be.false;\n });\n});\n" }, { "alpha_fraction": 0.6269716024398804, "alphanum_fraction": 0.6269716024398804, "avg_line_length": 38.216495513916016, "blob_id": "05bf9ce5d705858de5264912c5ab6bc9588d92d3", "content_id": "06513c4bfe9332014367f77152ed8c6688e4e471", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3804, "license_type": "permissive", "max_line_length": 171, "num_lines": 97, "path": "/src/main/webapp/app/overview/course-lectures/course-lecture-details.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { HttpErrorResponse } from '@angular/common/http';\nimport * as moment from 'moment';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { FileService } from 'app/shared/http/file.service';\nimport { Attachment } from 'app/entities/attachment.model';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { LectureUnit, LectureUnitType } from 'app/entities/lecture-unit/lectureUnit.model';\nimport { StudentQuestionsComponent } from 'app/overview/student-questions/student-questions.component';\nimport { onError } from 'app/shared/util/global.utils';\nimport { finalize } from 'rxjs/operators';\nimport { JhiAlertService } from 'ng-jhipster';\n\n@Component({\n selector: 'jhi-course-lecture-details',\n templateUrl: './course-lecture-details.component.html',\n styleUrls: ['../course-overview.scss', './course-lectures.scss'],\n})\nexport class CourseLectureDetailsComponent implements OnInit {\n lectureId?: number;\n isLoading = false;\n lecture?: Lecture;\n isDownloadingLink?: string;\n lectureUnits: LectureUnit[] = [];\n studentQuestions?: StudentQuestionsComponent;\n\n readonly LectureUnitType = LectureUnitType;\n\n constructor(private alertService: JhiAlertService, private lectureService: LectureService, private activatedRoute: ActivatedRoute, private fileService: FileService) {}\n\n ngOnInit(): void {\n this.activatedRoute.params.subscribe((params) => {\n this.lectureId = +params['lectureId'];\n if (this.lectureId) {\n this.loadData();\n }\n });\n }\n\n loadData() {\n this.isLoading = true;\n this.lectureService\n .find(this.lectureId!)\n .pipe(\n finalize(() => {\n this.isLoading = false;\n }),\n )\n .subscribe(\n (findLectureResult) => {\n this.lecture = findLectureResult.body!;\n if (this.lecture?.lectureUnits) {\n this.lectureUnits = this.lecture.lectureUnits;\n }\n if (this.studentQuestions) {\n // We need to manually update the lecture property of the student questions component\n this.studentQuestions.lecture = this.lecture;\n this.studentQuestions.loadQuestions(); // reload the student questions\n }\n },\n (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse),\n );\n }\n attachmentNotReleased(attachment: Attachment): boolean {\n return attachment.releaseDate != undefined && !moment(attachment.releaseDate).isBefore(moment())!;\n }\n\n attachmentExtension(attachment: Attachment): string {\n if (!attachment.link) {\n return 'N/A';\n }\n\n return attachment.link.split('.').pop()!;\n }\n\n downloadAttachment(downloadUrl: string): void {\n if (!this.isDownloadingLink) {\n this.isDownloadingLink = downloadUrl;\n this.fileService.downloadFileWithAccessToken(downloadUrl);\n this.isDownloadingLink = undefined;\n }\n }\n\n /**\n * This function gets called if the router outlet gets activated. This is\n * used only for the StudentQuestionsComponent\n * @param instance The component instance\n */\n onChildActivate(instance: StudentQuestionsComponent) {\n this.studentQuestions = instance; // save the reference to the component instance\n if (this.lecture) {\n instance.lecture = this.lecture;\n instance.loadQuestions(); // reload the student questions\n }\n }\n}\n" }, { "alpha_fraction": 0.6209088563919067, "alphanum_fraction": 0.623028039932251, "avg_line_length": 42.783504486083984, "blob_id": "7e9f59370639eed3a03d09196116dbf2c2c5c28a", "content_id": "75facb56f8d1e03749bd31fdf91b44697666ed92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4247, "license_type": "permissive", "max_line_length": 178, "num_lines": 97, "path": "/src/test/javascript/spec/component/text-exercise/text-exercise-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { ArtemisTestModule } from '../../test.module';\nimport { TextExerciseDetailComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-detail.component';\nimport { Course } from 'app/entities/course.model';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { ExerciseGroup } from 'app/entities/exercise-group.model';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockComponent, MockProvider } from 'ng-mocks';\nimport { NonProgrammingExerciseDetailCommonActionsComponent } from 'app/exercises/shared/exercise-detail-common-actions/non-programming-exercise-detail-common-actions.component';\n\ndescribe('TextExercise Management Detail Component', () => {\n let comp: TextExerciseDetailComponent;\n let fixture: ComponentFixture<TextExerciseDetailComponent>;\n let service: TextExerciseService;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [TextExerciseDetailComponent, MockComponent(NonProgrammingExerciseDetailCommonActionsComponent)],\n providers: [{ provide: ActivatedRoute, useValue: new MockActivatedRoute() }, MockProvider(TranslateService)],\n })\n .overrideTemplate(TextExerciseDetailComponent, '')\n .compileComponents();\n fixture = TestBed.createComponent(TextExerciseDetailComponent);\n comp = fixture.componentInstance;\n service = fixture.debugElement.injector.get(TextExerciseService);\n });\n\n describe('OnInit with course exercise', () => {\n const course: Course = { id: 123 } as Course;\n const textExerciseWithCourse: TextExercise = new TextExercise(course, undefined);\n textExerciseWithCourse.id = 123;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ exerciseId: textExerciseWithCourse.id });\n });\n\n it('Should call load on init and be not in exam mode', () => {\n // GIVEN\n const headers = new HttpHeaders().append('link', 'link;link');\n spyOn(service, 'find').and.returnValue(\n of(\n new HttpResponse({\n body: textExerciseWithCourse,\n headers,\n }),\n ),\n );\n // WHEN\n fixture.detectChanges();\n comp.ngOnInit();\n\n // THEN\n expect(service.find).toHaveBeenCalled();\n expect(comp.isExamExercise).toBeFalsy();\n expect(comp.textExercise).toEqual(textExerciseWithCourse);\n });\n });\n\n describe('OnInit with exam exercise', () => {\n const exerciseGroup: ExerciseGroup = new ExerciseGroup();\n const textExerciseWithExerciseGroup: TextExercise = new TextExercise(undefined, exerciseGroup);\n textExerciseWithExerciseGroup.id = 123;\n\n beforeEach(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.params = of({ exerciseId: textExerciseWithExerciseGroup.id });\n });\n\n it('Should call load on init and be in exam mode', () => {\n // GIVEN\n const headers = new HttpHeaders().append('link', 'link;link');\n spyOn(service, 'find').and.returnValue(\n of(\n new HttpResponse({\n body: textExerciseWithExerciseGroup,\n headers,\n }),\n ),\n );\n // WHEN\n fixture.detectChanges();\n comp.ngOnInit();\n\n // THEN\n expect(service.find).toHaveBeenCalled();\n expect(comp.isExamExercise).toBeTruthy();\n expect(comp.textExercise).toEqual(textExerciseWithExerciseGroup);\n });\n });\n});\n" }, { "alpha_fraction": 0.580008327960968, "alphanum_fraction": 0.5866583585739136, "avg_line_length": 38.442623138427734, "blob_id": "f81cefa98c02ec3931a2f34c7589b6858b42b7d4", "content_id": "2ce0f1fd80281fa06d8d428cfa103b98f599c5cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4812, "license_type": "permissive", "max_line_length": 133, "num_lines": 122, "path": "/src/test/javascript/spec/service/submission.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { SubmissionService } from 'app/exercises/shared/submission/submission.service';\nimport { getTestBed, TestBed } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport { take } from 'rxjs/operators';\nimport { ArtemisTestModule } from '../test.module';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { Result } from 'app/entities/result.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpResponse } from '@angular/common/http';\nimport { getLatestSubmissionResult, Submission } from 'app/entities/submission.model';\nconst expect = chai.expect;\n\ndescribe('Submission Service', () => {\n let injector: TestBed;\n let service: SubmissionService;\n let httpMock: HttpTestingController;\n let expectedResult: any;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, HttpClientTestingModule],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n });\n injector = getTestBed();\n service = injector.get(SubmissionService);\n httpMock = injector.get(HttpTestingController);\n expectedResult = {} as HttpResponse<Submission[]>;\n });\n\n it('should delete an existing submission', async () => {\n service.delete(187).subscribe((resp) => (expectedResult = resp.ok));\n const req = httpMock.expectOne({ method: 'DELETE' });\n req.flush({ status: 200 });\n expect(expectedResult).to.be.true;\n });\n\n it('should find all submissions of a given participation', async () => {\n const participationId = 1;\n const submission = ({\n id: 1,\n submitted: true,\n type: 'AUTOMATIC',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as TextSubmission;\n submission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n } as unknown) as Result,\n ];\n getLatestSubmissionResult(submission)!.feedbacks = [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ];\n const returnedFromService = [...[submission]];\n const expected = [...[submission]];\n service\n .findAllSubmissionsOfParticipation(participationId)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ url: `${SERVER_API_URL}api/participations/${participationId}/submissions`, method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n it('should get test run submission for a given exercise', async () => {\n const exerciseId = 1;\n const submission = ({\n id: 1,\n submitted: true,\n type: 'AUTOMATIC',\n text: 'Test\\n\\nTest\\n\\nTest',\n } as unknown) as TextSubmission;\n submission.results = [\n ({\n id: 2374,\n resultString: '1 of 12 points',\n score: 8,\n rated: true,\n hasFeedback: true,\n hasComplaint: false,\n } as unknown) as Result,\n ];\n getLatestSubmissionResult(submission)!.feedbacks = [\n {\n id: 2,\n detailText: 'Feedback',\n credits: 1,\n } as Feedback,\n ];\n const returnedFromService = [...[submission]];\n const expected = [...[submission]];\n service\n .getTestRunSubmissionsForExercise(exerciseId)\n .pipe(take(1))\n .subscribe((resp) => (expectedResult = resp));\n const req = httpMock.expectOne({ url: `api/exercises/${exerciseId}/test-run-submissions`, method: 'GET' });\n req.flush(returnedFromService);\n expect(expectedResult.body).to.deep.equal(expected);\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.714194655418396, "alphanum_fraction": 0.7199320197105408, "avg_line_length": 48.536842346191406, "blob_id": "aa8a18b01053b3911938772c9c9a98bc8af1ac1f", "content_id": "1542e2d1f9d15a7a6c687a0c1b29a0e4beadbe65", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4706, "license_type": "permissive", "max_line_length": 163, "num_lines": 95, "path": "/src/test/javascript/spec/component/shared/participant-scores-average-table.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ParticipantScoresAverageTableComponent } from 'app/shared/participant-scores/participant-scores-average-table/participant-scores-average-table.component';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { NgxDatatableModule } from '@swimlane/ngx-datatable';\nimport { TranslateModule, TranslatePipe } from '@ngx-translate/core';\nimport { MockDirective, MockPipe } from 'ng-mocks';\nimport { JhiTranslateDirective } from 'ng-jhipster';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as chai from 'chai';\nimport { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ParticipantScoreAverageDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ParticipantScoresAverageTable', () => {\n let fixture: ComponentFixture<ParticipantScoresAverageTableComponent>;\n let component: ParticipantScoresAverageTableComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisDataTableModule, NgxDatatableModule, NgbTooltipModule, TranslateModule.forRoot()],\n declarations: [ParticipantScoresAverageTableComponent, MockPipe(TranslatePipe), MockDirective(JhiTranslateDirective)],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n {\n provide: SessionStorageService,\n useClass: MockSyncStorage,\n },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ParticipantScoresAverageTableComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n\n it('should render the data in a row', () => {\n const participantScoreAverageDTO = new ParticipantScoreAverageDTO();\n participantScoreAverageDTO.userName = 'testUser';\n participantScoreAverageDTO.averageRatedScore = 10;\n participantScoreAverageDTO.averageScore = 5;\n participantScoreAverageDTO.averagePoints = 8;\n participantScoreAverageDTO.averageRatedPoints = 12;\n\n component.isLoading = false;\n component.participantAverageScores = [participantScoreAverageDTO];\n\n fixture.detectChanges();\n\n const cellElements = fixture.debugElement.queryAll(By.css('.datatable-body-cell-label > span'));\n expect(cellElements.length).to.equal(6);\n expect(cellElements[0].nativeElement.innerHTML).to.contain(participantScoreAverageDTO.userName);\n expect(cellElements[1].nativeElement.innerHTML).to.contain('');\n expect(cellElements[2].nativeElement.innerHTML).to.contain(participantScoreAverageDTO.averageScore);\n expect(cellElements[3].nativeElement.innerHTML).to.contain(participantScoreAverageDTO.averagePoints);\n expect(cellElements[4].nativeElement.innerHTML).to.contain(participantScoreAverageDTO.averageRatedScore);\n expect(cellElements[5].nativeElement.innerHTML).to.contain(participantScoreAverageDTO.averageRatedPoints);\n });\n\n it('should extract participant name correctly', () => {\n let participantScoreAverageDTO = new ParticipantScoreAverageDTO();\n participantScoreAverageDTO.userName = 'testUser';\n participantScoreAverageDTO.averageRatedScore = 10;\n participantScoreAverageDTO.averageScore = 5;\n participantScoreAverageDTO.averagePoints = 12;\n participantScoreAverageDTO.averageRatedPoints = 20;\n\n expect(component.extractParticipantName(participantScoreAverageDTO)).to.equal(participantScoreAverageDTO.userName);\n\n participantScoreAverageDTO = new ParticipantScoreAverageDTO();\n participantScoreAverageDTO.averageRatedScore = 10;\n participantScoreAverageDTO.averageScore = 5;\n participantScoreAverageDTO.teamName = 'testTeam';\n participantScoreAverageDTO.averageRatedPoints = 20;\n participantScoreAverageDTO.averagePoints = 12;\n\n expect(component.extractParticipantName(participantScoreAverageDTO)).to.equal(participantScoreAverageDTO.teamName);\n });\n});\n" }, { "alpha_fraction": 0.626650333404541, "alphanum_fraction": 0.6289136409759521, "avg_line_length": 36.46996307373047, "blob_id": "5e057e04ec486c706cbdfc7568593dc84a73d195", "content_id": "e8478f21b999e4f160ce4afdd936d20a668647d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10604, "license_type": "permissive", "max_line_length": 162, "num_lines": 283, "path": "/src/main/webapp/app/exercises/shared/plagiarism/plagiarism-inspector/plagiarism-inspector.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { HttpResponse } from '@angular/common/http';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { Exercise, ExerciseType } from 'app/entities/exercise.model';\nimport { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service';\nimport { ModelingPlagiarismResult } from 'app/exercises/shared/plagiarism/types/modeling/ModelingPlagiarismResult';\nimport { downloadFile, downloadZipFileFromResponse } from 'app/shared/util/download.util';\nimport { TextPlagiarismResult } from 'app/exercises/shared/plagiarism/types/text/TextPlagiarismResult';\nimport { PlagiarismResult } from 'app/exercises/shared/plagiarism/types/PlagiarismResult';\nimport { ExportToCsv } from 'export-to-csv';\nimport { PlagiarismComparison } from 'app/exercises/shared/plagiarism/types/PlagiarismComparison';\nimport { ModelingSubmissionElement } from 'app/exercises/shared/plagiarism/types/modeling/ModelingSubmissionElement';\nimport { TextSubmissionElement } from 'app/exercises/shared/plagiarism/types/text/TextSubmissionElement';\nimport { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';\nimport { PlagiarismOptions } from 'app/exercises/shared/plagiarism/types/PlagiarismOptions';\n\n@Component({\n selector: 'jhi-plagiarism-inspector',\n styleUrls: ['./plagiarism-inspector.component.scss'],\n templateUrl: './plagiarism-inspector.component.html',\n})\nexport class PlagiarismInspectorComponent implements OnInit {\n /**\n * The modeling exercise for which plagiarism is to be detected.\n */\n exercise: Exercise;\n\n /**\n * Result of the automated plagiarism detection\n */\n plagiarismResult?: TextPlagiarismResult | ModelingPlagiarismResult;\n\n /**\n * True, if an automated plagiarism detection is running; false otherwise.\n */\n detectionInProgress: boolean;\n\n /**\n * Index of the currently selected comparison.\n */\n selectedComparisonIndex: number;\n\n /**\n * True, if the plagiarism details tab is active.\n */\n showRunDetails = false;\n\n /**\n * True, if the plagiarism options should be displayed.\n */\n showOptions = false;\n\n /**\n * If true, the plagiarism detection will return the generated jplag report.\n */\n generateJPlagReport = false;\n\n /**\n * Minimum similarity (%) of the comparisons to return.\n */\n similarityThreshold = 50;\n\n /**\n * Ignore submissions with a score less than `minimumScore` in plagiarism detection.\n */\n minimumScore = 0;\n\n /**\n * Ignore submissions with a size less than `minimumSize` in plagiarism detection.\n */\n minimumSize = 0;\n\n /**\n * The minimumScore option is only configurable, if this value is true.\n */\n enableMinimumScore = false;\n\n /**\n * The minimumSize option is only configurable, if this value is true.\n */\n enableMinimumSize = false;\n\n constructor(\n private route: ActivatedRoute,\n private router: Router,\n private modelingExerciseService: ModelingExerciseService,\n private programmingExerciseService: ProgrammingExerciseService,\n private textExerciseService: TextExerciseService,\n ) {}\n\n ngOnInit() {\n this.route.data.subscribe(({ exercise }) => {\n this.exercise = exercise;\n\n this.getLatestPlagiarismResult();\n });\n }\n\n /**\n * Fetch the latest plagiarism result. There might be no plagiarism result for the given exercise yet.\n */\n getLatestPlagiarismResult() {\n this.detectionInProgress = true;\n\n switch (this.exercise.type) {\n case ExerciseType.MODELING: {\n this.modelingExerciseService.getLatestPlagiarismResult(this.exercise.id!).subscribe(\n (result) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n return;\n }\n case ExerciseType.PROGRAMMING: {\n this.programmingExerciseService.getLatestPlagiarismResult(this.exercise.id!).subscribe(\n (result) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n return;\n }\n case ExerciseType.TEXT: {\n this.textExerciseService.getLatestPlagiarismResult(this.exercise.id!).subscribe(\n (result) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n return;\n }\n default: {\n this.detectionInProgress = false;\n }\n }\n }\n\n checkPlagiarism() {\n const minimumScore = this.enableMinimumScore ? this.minimumScore : 0;\n const minimumSize = this.enableMinimumSize ? this.minimumSize : 0;\n\n const options = new PlagiarismOptions(this.similarityThreshold, minimumScore, minimumSize);\n\n if (this.exercise.type === ExerciseType.MODELING) {\n this.checkPlagiarismModeling(options);\n } else if (this.generateJPlagReport) {\n this.checkPlagiarismJPlagReport(options);\n } else {\n this.checkPlagiarismJPlag(options);\n }\n }\n\n selectComparisonAtIndex(index: number) {\n this.selectedComparisonIndex = index;\n this.showRunDetails = false;\n }\n\n /**\n * This method triggers the plagiarism detection for programming exercises and downloads the zipped report generated by JPlag.\n */\n checkPlagiarismJPlagReport(options?: PlagiarismOptions) {\n this.detectionInProgress = true;\n\n this.programmingExerciseService.checkPlagiarismJPlagReport(this.exercise.id!, options).subscribe(\n (response: HttpResponse<Blob>) => {\n this.detectionInProgress = false;\n downloadZipFileFromResponse(response);\n },\n () => {\n this.detectionInProgress = false;\n },\n );\n }\n\n isProgrammingExercise() {\n return this.exercise?.type === ExerciseType.PROGRAMMING;\n }\n\n /**\n * Trigger the server-side plagiarism detection and fetch its result.\n */\n checkPlagiarismJPlag(options?: PlagiarismOptions) {\n this.detectionInProgress = true;\n\n if (this.exercise.type === ExerciseType.TEXT) {\n this.textExerciseService.checkPlagiarism(this.exercise.id!, options).subscribe(\n (result) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n } else {\n this.programmingExerciseService.checkPlagiarism(this.exercise.id!, options).subscribe(\n (result) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n }\n }\n\n /**\n * Trigger the server-side plagiarism detection and fetch its result.\n */\n checkPlagiarismModeling(options?: PlagiarismOptions) {\n this.detectionInProgress = true;\n\n this.modelingExerciseService.checkPlagiarism(this.exercise.id!, options).subscribe(\n (result: ModelingPlagiarismResult) => this.handlePlagiarismResult(result),\n () => (this.detectionInProgress = false),\n );\n }\n\n handlePlagiarismResult(result: ModelingPlagiarismResult | TextPlagiarismResult) {\n this.detectionInProgress = false;\n\n this.sortComparisonsForResult(result);\n\n this.plagiarismResult = result;\n this.selectedComparisonIndex = 0;\n }\n\n sortComparisonsForResult(result: PlagiarismResult<any>) {\n result.comparisons = result.comparisons.sort((a, b) => b.similarity - a.similarity);\n }\n\n /**\n * Download plagiarism detection results as JSON document.\n */\n downloadPlagiarismResultsJson() {\n const json = JSON.stringify(this.plagiarismResult);\n const blob = new Blob([json], { type: 'application/json' });\n\n downloadFile(blob, `plagiarism-result_${this.exercise.type}-exercise-${this.exercise.id}.json`);\n }\n\n /**\n * Download plagiarism detection results as CSV document.\n */\n downloadPlagiarismResultsCsv() {\n if (this.plagiarismResult && this.plagiarismResult.comparisons.length > 0) {\n const csvExporter = new ExportToCsv({\n fieldSeparator: ';',\n quoteStrings: '\"',\n decimalSeparator: 'locale',\n showLabels: true,\n title: `Plagiarism Check for Exercise ${this.exercise.id}: ${this.exercise.title}`,\n filename: `plagiarism-result_${this.exercise.type}-exercise-${this.exercise.id}`,\n useTextFile: false,\n useBom: true,\n headers: ['Similarity', 'Status', 'Participant 1', 'Submission 1', 'Score 1', 'Size 1', 'Participant 2', 'Submission 2', 'Score 2', 'Size 2'],\n });\n\n const csvData = (this.plagiarismResult.comparisons as PlagiarismComparison<ModelingSubmissionElement | TextSubmissionElement>[]).map((comparison) => {\n return Object.assign({\n Similarity: comparison.similarity,\n Status: comparison.status,\n 'Participant 1': comparison.submissionA.studentLogin,\n 'Submission 1': comparison.submissionA.submissionId,\n 'Score 1': comparison.submissionA.score,\n 'Size 1': comparison.submissionA.size,\n 'Participant 2': comparison.submissionB.studentLogin,\n 'Submission 2': comparison.submissionB.submissionId,\n 'Score 2': comparison.submissionB.score,\n 'Size 2': comparison.submissionB.size,\n });\n });\n\n csvExporter.generateCsv(csvData);\n }\n }\n\n /**\n * Return the translation identifier of the minimum size tooltip for the current exercise type.\n */\n getMinimumSizeTooltip() {\n const tooltip = 'artemisApp.plagiarism.minimum-size-tooltip';\n\n switch (this.exercise.type) {\n case ExerciseType.TEXT: {\n return tooltip + '-text';\n }\n case ExerciseType.MODELING: {\n return tooltip + '-modeling';\n }\n default: {\n return tooltip;\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7300168871879578, "alphanum_fraction": 0.7308362126350403, "avg_line_length": 57.9110107421875, "blob_id": "10e0fcb261b676387d88b1ea8624fb69c000b717", "content_id": "1a75ca6f32afbd7cfaca1ae3ccb8ebf0c6ba4a7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 39058, "license_type": "permissive", "max_line_length": 180, "num_lines": 663, "path": "/src/main/java/de/tum/in/www1/artemis/service/ParticipationService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static de.tum.in.www1.artemis.domain.enumeration.InitializationState.*;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\nimport org.springframework.transaction.annotation.Transactional;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.*;\nimport de.tum.in.www1.artemis.domain.participation.*;\nimport de.tum.in.www1.artemis.domain.quiz.QuizExercise;\nimport de.tum.in.www1.artemis.domain.quiz.QuizSubmission;\nimport de.tum.in.www1.artemis.exception.ContinuousIntegrationException;\nimport de.tum.in.www1.artemis.exception.VersionControlException;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.service.connectors.ContinuousIntegrationService;\nimport de.tum.in.www1.artemis.service.connectors.GitService;\nimport de.tum.in.www1.artemis.service.connectors.VersionControlService;\nimport de.tum.in.www1.artemis.service.scheduled.quiz.QuizScheduleService;\n\n/**\n * Service Implementation for managing Participation.\n */\n@Service\n// TODO: this class is too large. We need to split it into multiple smaller classes with fewer dependencies\npublic class ParticipationService {\n\n private final Logger log = LoggerFactory.getLogger(ParticipationService.class);\n\n private final GitService gitService;\n\n private final Optional<ContinuousIntegrationService> continuousIntegrationService;\n\n private final Optional<VersionControlService> versionControlService;\n\n private final QuizScheduleService quizScheduleService;\n\n private final UrlService urlService;\n\n private final ParticipationRepository participationRepository;\n\n private final StudentParticipationRepository studentParticipationRepository;\n\n private final ProgrammingExerciseStudentParticipationRepository programmingExerciseStudentParticipationRepository;\n\n private final ExerciseRepository exerciseRepository;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final ResultRepository resultRepository;\n\n private final SubmissionRepository submissionRepository;\n\n private final ComplaintResponseRepository complaintResponseRepository;\n\n private final ComplaintRepository complaintRepository;\n\n private final RatingRepository ratingRepository;\n\n private final TeamRepository teamRepository;\n\n private final ParticipantScoreRepository participantScoreRepository;\n\n public ParticipationService(UrlService urlService, ProgrammingExerciseStudentParticipationRepository programmingExerciseStudentParticipationRepository,\n StudentParticipationRepository studentParticipationRepository, ExerciseRepository exerciseRepository, ProgrammingExerciseRepository programmingExerciseRepository,\n ResultRepository resultRepository, SubmissionRepository submissionRepository, ComplaintResponseRepository complaintResponseRepository,\n ComplaintRepository complaintRepository, TeamRepository teamRepository, GitService gitService, QuizScheduleService quizScheduleService,\n ParticipationRepository participationRepository, Optional<ContinuousIntegrationService> continuousIntegrationService,\n Optional<VersionControlService> versionControlService, RatingRepository ratingRepository, ParticipantScoreRepository participantScoreRepository) {\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.participationRepository = participationRepository;\n this.programmingExerciseStudentParticipationRepository = programmingExerciseStudentParticipationRepository;\n this.studentParticipationRepository = studentParticipationRepository;\n this.exerciseRepository = exerciseRepository;\n this.resultRepository = resultRepository;\n this.submissionRepository = submissionRepository;\n this.complaintResponseRepository = complaintResponseRepository;\n this.complaintRepository = complaintRepository;\n this.teamRepository = teamRepository;\n this.gitService = gitService;\n this.continuousIntegrationService = continuousIntegrationService;\n this.versionControlService = versionControlService;\n this.quizScheduleService = quizScheduleService;\n this.ratingRepository = ratingRepository;\n this.urlService = urlService;\n this.participantScoreRepository = participantScoreRepository;\n }\n\n /**\n * This method is triggered when a student starts an exercise. It creates a Participation which connects the corresponding student and exercise. Additionally, it configures\n * repository / build plan related stuff for programming exercises. In the case of modeling or text exercises, it also initializes and stores the corresponding submission.\n *\n * @param exercise the exercise which is started, a programming exercise needs to have the template and solution participation eagerly loaded\n * @param participant the user or team who starts the exercise\n * @param createInitialSubmission whether an initial empty submission should be created for text, modeling, quiz, fileupload or not\n * @return the participation connecting the given exercise and user\n */\n public StudentParticipation startExercise(Exercise exercise, Participant participant, boolean createInitialSubmission) {\n // common for all exercises\n // Check if participation already exists\n Optional<StudentParticipation> optionalStudentParticipation = findOneByExerciseAndParticipantAnyState(exercise, participant);\n StudentParticipation participation;\n if (optionalStudentParticipation.isEmpty()) {\n // create a new participation only if no participation can be found\n if (exercise instanceof ProgrammingExercise) {\n participation = new ProgrammingExerciseStudentParticipation();\n }\n else {\n participation = new StudentParticipation();\n }\n participation.setInitializationState(UNINITIALIZED);\n participation.setExercise(exercise);\n participation.setParticipant(participant);\n participation = studentParticipationRepository.saveAndFlush(participation);\n }\n else {\n // make sure participation and exercise are connected\n participation = optionalStudentParticipation.get();\n participation.setExercise(exercise);\n }\n\n if (exercise instanceof ProgrammingExercise) {\n // fetch again to get additional objects\n var programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationElseThrow(exercise.getId());\n participation = startProgrammingExercise(programmingExercise, (ProgrammingExerciseStudentParticipation) participation);\n }\n else {// for all other exercises: QuizExercise, ModelingExercise, TextExercise, FileUploadExercise\n if (participation.getInitializationState() == null || participation.getInitializationState() == UNINITIALIZED\n || participation.getInitializationState() == FINISHED && !(exercise instanceof QuizExercise)) {\n // in case the participation was finished before, we set it to initialized again so that the user sees the correct button \"Open modeling editor\" on the client side.\n // Only for quiz exercises, the participation status FINISHED should not be overwritten since the user must not change his submission once submitted\n participation.setInitializationState(INITIALIZED);\n }\n\n if (Optional.ofNullable(participation.getInitializationDate()).isEmpty()) {\n participation.setInitializationDate(ZonedDateTime.now());\n }\n // TODO: load submission with exercise for exam edge case:\n // clients creates missing participation for exercise, call on server succeeds, but response to client is lost\n // -> client tries to create participation again. In this case the submission is not loaded from db -> client errors\n if (optionalStudentParticipation.isEmpty() || !submissionRepository.existsByParticipationId(participation.getId())) {\n // initialize a modeling, text, file upload or quiz submission\n if (createInitialSubmission) {\n submissionRepository.initializeSubmission(participation, exercise, null);\n }\n }\n }\n return studentParticipationRepository.saveAndFlush(participation);\n }\n\n /**\n * Start a programming exercise participation (which does not exist yet) by creating and configuring a student git repository (step 1) and a student build plan (step 2)\n * based on the templates in the given programming exercise\n *\n * @param exercise the programming exercise that the currently active user (student) wants to start\n * @param participation inactive participation\n * @return started participation\n */\n private StudentParticipation startProgrammingExercise(ProgrammingExercise exercise, ProgrammingExerciseStudentParticipation participation) {\n // Step 1a) create the student repository (based on the template repository)\n participation = copyRepository(participation);\n // Step 1b) configure the student repository (e.g. access right, etc.)\n participation = configureRepository(exercise, participation);\n // Step 2a) create the build plan (based on the BASE build plan)\n participation = copyBuildPlan(participation);\n // Step 2b) configure the build plan (e.g. access right, hooks, etc.)\n participation = configureBuildPlan(participation);\n // Step 2c) we might need to perform an empty commit (as a workaround, depending on the CI system) here, because it should not trigger a new programming submission\n // (when the web hook was already initialized, see below)\n continuousIntegrationService.get().performEmptySetupCommit(participation);\n // Note: we configure the repository webhook last, so that the potential empty commit does not trigger a new programming submission (see empty-commit-necessary)\n // Step 3) configure the web hook of the student repository\n participation = configureRepositoryWebHook(participation);\n participation.setInitializationState(INITIALIZED);\n participation.setInitializationDate(ZonedDateTime.now());\n // after saving, we need to make sure the object that is used after the if statement is the right one\n return participation;\n }\n\n /**\n * This method checks whether a participation exists for a given exercise and user. If not, it creates such a participation with initialization state FINISHED.\n * If the participation had to be newly created or there were no submissions yet for the existing participation, a new submission is created with the given submission type.\n * For external submissions, the submission is assumed to be submitted immediately upon creation.\n *\n * @param exercise the exercise for which to create a participation and submission\n * @param participant the user/team for which to create a participation and submission\n * @param submissionType the type of submission to create if none exist yet\n * @return the participation connecting the given exercise and user\n */\n public StudentParticipation createParticipationWithEmptySubmissionIfNotExisting(Exercise exercise, Participant participant, SubmissionType submissionType) {\n Optional<StudentParticipation> optionalStudentParticipation = findOneByExerciseAndParticipantAnyState(exercise, participant);\n StudentParticipation participation;\n if (optionalStudentParticipation.isEmpty()) {\n // create a new participation only if no participation can be found\n if (exercise instanceof ProgrammingExercise) {\n participation = new ProgrammingExerciseStudentParticipation();\n }\n else {\n participation = new StudentParticipation();\n }\n participation.setInitializationState(UNINITIALIZED);\n participation.setInitializationDate(ZonedDateTime.now());\n participation.setExercise(exercise);\n participation.setParticipant(participant);\n\n participation = studentParticipationRepository.saveAndFlush(participation);\n }\n else {\n participation = optionalStudentParticipation.get();\n }\n\n // setup repository in case of programming exercise\n if (exercise instanceof ProgrammingExercise) {\n // fetch again to get additional objects\n ProgrammingExercise programmingExercise = programmingExerciseRepository.findByIdWithTemplateAndSolutionParticipationElseThrow(exercise.getId());\n ProgrammingExerciseStudentParticipation programmingParticipation = (ProgrammingExerciseStudentParticipation) participation;\n // Note: we need a repository, otherwise the student would not be possible to click resume (in case he wants to further participate after the deadline)\n programmingParticipation = copyRepository(programmingParticipation);\n programmingParticipation = configureRepository(programmingExercise, programmingParticipation);\n programmingParticipation = configureRepositoryWebHook(programmingParticipation);\n participation = programmingParticipation;\n if (programmingExercise.getBuildAndTestStudentSubmissionsAfterDueDate() != null || programmingExercise.getAssessmentType() != AssessmentType.AUTOMATIC) {\n // restrict access for the student\n try {\n versionControlService.get().setRepositoryPermissionsToReadOnly(programmingParticipation.getVcsRepositoryUrl(), programmingExercise.getProjectKey(),\n programmingParticipation.getStudents());\n }\n catch (VersionControlException e) {\n log.error(\"Removing write permissions failed for programming exercise with id {} for student repository with participation id {}: {}\",\n programmingExercise.getId(), programmingParticipation.getId(), e.getMessage());\n }\n }\n }\n\n participation.setInitializationState(FINISHED);\n participation = studentParticipationRepository.saveAndFlush(participation);\n\n // Take the latest submission or initialize a new empty submission\n var studentParticipation = studentParticipationRepository.findByIdWithLegalSubmissionsElseThrow(participation.getId());\n var submission = studentParticipation.findLatestSubmission().orElseGet(() -> submissionRepository.initializeSubmission(studentParticipation, exercise, submissionType));\n\n // If the submission has not yet been submitted, submit it now\n if (!submission.isSubmitted()) {\n submission.setSubmitted(true);\n submission.setSubmissionDate(ZonedDateTime.now());\n submissionRepository.save(submission);\n }\n\n return studentParticipation;\n }\n\n /**\n * Get a participation for the given quiz and username.\n * If the quiz hasn't ended, participation is constructed from cached submission.\n * If the quiz has ended, we first look in the database for the participation and construct one if none was found\n *\n * @param quizExercise the quiz exercise to attach to the participation\n * @param username the username of the user that the participation belongs to\n * @return the found or created participation with a result\n */\n public StudentParticipation participationForQuizWithResult(QuizExercise quizExercise, String username) {\n if (quizExercise.isEnded()) {\n // try getting participation from database\n Optional<StudentParticipation> optionalParticipation = findOneByExerciseAndStudentLoginAnyState(quizExercise, username);\n\n if (optionalParticipation.isEmpty()) {\n log.error(\"Participation in quiz {} not found for user {}\", quizExercise.getTitle(), username);\n // TODO properly handle this case\n return null;\n }\n StudentParticipation participation = optionalParticipation.get();\n // add exercise\n participation.setExercise(quizExercise);\n\n // add the appropriate result\n Result result = resultRepository.findFirstByParticipationIdAndRatedOrderByCompletionDateDesc(participation.getId(), true).orElse(null);\n participation.setResults(new HashSet<>());\n if (result != null) {\n participation.addResult(result);\n }\n return participation;\n }\n\n // Look for Participation in ParticipationHashMap first\n StudentParticipation participation = quizScheduleService.getParticipation(quizExercise.getId(), username);\n if (participation != null) {\n return participation;\n }\n\n // get submission from HashMap\n QuizSubmission quizSubmission = quizScheduleService.getQuizSubmission(quizExercise.getId(), username);\n\n // construct result\n Result result = new Result().submission(quizSubmission);\n\n // construct participation\n participation = new StudentParticipation();\n participation.setInitializationState(INITIALIZED);\n participation.setExercise(quizExercise);\n participation.addResult(result);\n return participation;\n }\n\n /**\n * Resume an inactive programming exercise participation (with previously deleted build plan) by creating and configuring a student build plan (step 2)\n * based on the template (BASE) in the corresponding programming exercise, also compare {@link #startProgrammingExercise}\n *\n * @param participation inactive participation\n * @return resumed participation\n */\n public ProgrammingExerciseStudentParticipation resumeProgrammingExercise(ProgrammingExerciseStudentParticipation participation) {\n // this method assumes that the student git repository already exists (compare startProgrammingExercise) so steps 1, 2 and 5 are not necessary\n // Step 2a) create the build plan (based on the BASE build plan)\n participation = copyBuildPlan(participation);\n // Step 2b) configure the build plan (e.g. access right, hooks, etc.)\n participation = configureBuildPlan(participation);\n // Note: the repository webhook (step 1c) already exists so we don't need to set it up again, the empty commit hook (step 2c) is also not necessary here\n // and must be handled by the calling method in case it would be necessary\n participation.setInitializationState(INITIALIZED);\n participation = programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n if (participation.getInitializationDate() == null) {\n // only set the date if it was not set before (which should NOT be the case)\n participation.setInitializationDate(ZonedDateTime.now());\n }\n return programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n\n private ProgrammingExerciseStudentParticipation copyRepository(ProgrammingExerciseStudentParticipation participation) {\n // only execute this step if it has not yet been completed yet or if the repository url is missing for some reason\n if (!participation.getInitializationState().hasCompletedState(InitializationState.REPO_COPIED) || participation.getVcsRepositoryUrl() == null) {\n final var programmingExercise = participation.getProgrammingExercise();\n final var projectKey = programmingExercise.getProjectKey();\n final var participantIdentifier = participation.getParticipantIdentifier();\n // NOTE: we have to get the repository slug of the template participation here, because not all exercises (in particular old ones) follow the naming conventions\n final var templateRepoName = urlService.getRepositorySlugFromRepositoryUrl(programmingExercise.getTemplateParticipation().getVcsRepositoryUrl());\n // the next action includes recovery, which means if the repository has already been copied, we simply retrieve the repository url and do not copy it again\n var newRepoUrl = versionControlService.get().copyRepository(projectKey, templateRepoName, projectKey, participantIdentifier);\n // add the userInfo part to the repoURL only if the participation belongs to a single student (and not a team of students)\n if (participation.getStudent().isPresent()) {\n newRepoUrl = newRepoUrl.withUser(participantIdentifier);\n }\n participation.setRepositoryUrl(newRepoUrl.toString());\n participation.setInitializationState(REPO_COPIED);\n\n return programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n else {\n return participation;\n }\n }\n\n private ProgrammingExerciseStudentParticipation configureRepository(ProgrammingExercise exercise, ProgrammingExerciseStudentParticipation participation) {\n if (!participation.getInitializationState().hasCompletedState(InitializationState.REPO_CONFIGURED)) {\n // do not allow the student to access the repository if this is an exam exercise that has not started yet\n boolean allowAccess = !exercise.isExamExercise() || ZonedDateTime.now().isAfter(exercise.getIndividualReleaseDate());\n versionControlService.get().configureRepository(exercise, participation.getVcsRepositoryUrl(), participation.getStudents(), allowAccess);\n participation.setInitializationState(InitializationState.REPO_CONFIGURED);\n return programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n else {\n return participation;\n }\n }\n\n private ProgrammingExerciseStudentParticipation copyBuildPlan(ProgrammingExerciseStudentParticipation participation) {\n // only execute this step if it has not yet been completed yet or if the build plan id is missing for some reason\n if (!participation.getInitializationState().hasCompletedState(InitializationState.BUILD_PLAN_COPIED) || participation.getBuildPlanId() == null) {\n final var projectKey = participation.getProgrammingExercise().getProjectKey();\n final var planName = BuildPlanType.TEMPLATE.getName();\n final var username = participation.getParticipantIdentifier();\n final var buildProjectName = participation.getExercise().getCourseViaExerciseGroupOrCourseMember().getShortName().toUpperCase() + \" \"\n + participation.getExercise().getTitle();\n // the next action includes recovery, which means if the build plan has already been copied, we simply retrieve the build plan id and do not copy it again\n final var buildPlanId = continuousIntegrationService.get().copyBuildPlan(projectKey, planName, projectKey, buildProjectName, username.toUpperCase(), true);\n participation.setBuildPlanId(buildPlanId);\n participation.setInitializationState(InitializationState.BUILD_PLAN_COPIED);\n return programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n else {\n return participation;\n }\n }\n\n private ProgrammingExerciseStudentParticipation configureBuildPlan(ProgrammingExerciseStudentParticipation participation) {\n if (!participation.getInitializationState().hasCompletedState(InitializationState.BUILD_PLAN_CONFIGURED)) {\n try {\n continuousIntegrationService.get().configureBuildPlan(participation);\n }\n catch (ContinuousIntegrationException ex) {\n // this means something with the configuration of the build plan is wrong.\n // we try to recover from typical edge cases by setting the initialization state back, so that the previous action (copy build plan) is tried again, when\n // the user again clicks on the start / resume exercise button.\n participation.setInitializationState(InitializationState.REPO_CONFIGURED);\n programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n // rethrow\n throw ex;\n }\n participation.setInitializationState(InitializationState.BUILD_PLAN_CONFIGURED);\n return programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n else {\n return participation;\n }\n }\n\n private ProgrammingExerciseStudentParticipation configureRepositoryWebHook(ProgrammingExerciseStudentParticipation participation) {\n if (!participation.getInitializationState().hasCompletedState(InitializationState.INITIALIZED)) {\n versionControlService.get().addWebHookForParticipation(participation);\n }\n return participation;\n }\n\n /**\n * Get one participation (in any state) by its student and exercise.\n *\n * @param exercise the exercise for which to find a participation\n * @param username the username of the student\n * @return the participation of the given student and exercise in any state\n */\n public Optional<StudentParticipation> findOneByExerciseAndStudentLoginAnyState(Exercise exercise, String username) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserLogin(exercise.getId(), username);\n return optionalTeam.flatMap(team -> studentParticipationRepository.findWithEagerLegalSubmissionsByExerciseIdAndTeamId(exercise.getId(), team.getId()));\n }\n return studentParticipationRepository.findWithEagerLegalSubmissionsByExerciseIdAndStudentLogin(exercise.getId(), username);\n }\n\n /**\n * Get one participation (in any state) by its participant and exercise.\n *\n * @param exercise the exercise for which to find a participation\n * @param participant the short name of the team\n * @return the participation of the given team and exercise in any state\n */\n public Optional<StudentParticipation> findOneByExerciseAndParticipantAnyState(Exercise exercise, Participant participant) {\n if (participant instanceof User) {\n return findOneByExerciseAndStudentLoginAnyState(exercise, ((User) participant).getLogin());\n }\n else if (participant instanceof Team) {\n return studentParticipationRepository.findWithEagerLegalSubmissionsByExerciseIdAndTeamId(exercise.getId(), ((Team) participant).getId());\n }\n else {\n throw new Error(\"Unknown Participant type\");\n }\n }\n\n /**\n * Get one participation (in any state) by its student and exercise with all its results.\n *\n * @param exercise the exercise for which to find a participation\n * @param username the username of the student\n * @return the participation of the given student and exercise in any state\n */\n public Optional<StudentParticipation> findOneByExerciseAndStudentLoginAnyStateWithEagerResults(Exercise exercise, String username) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserLogin(exercise.getId(), username);\n return optionalTeam.flatMap(team -> studentParticipationRepository.findWithEagerResultsByExerciseIdAndTeamId(exercise.getId(), team.getId()));\n }\n return studentParticipationRepository.findWithEagerResultsByExerciseIdAndStudentLogin(exercise.getId(), username);\n }\n\n /**\n * Get one participation (in any state) by its student and exercise with eager submissions.\n *\n * @param exercise the exercise for which to find a participation\n * @param username the username of the student\n * @return the participation of the given student and exercise with eager submissions in any state\n */\n public Optional<StudentParticipation> findOneByExerciseAndStudentLoginWithEagerSubmissionsAnyState(Exercise exercise, String username) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserLogin(exercise.getId(), username);\n return optionalTeam.flatMap(team -> studentParticipationRepository.findWithEagerLegalSubmissionsByExerciseIdAndTeamId(exercise.getId(), team.getId()));\n }\n return studentParticipationRepository.findWithEagerLegalSubmissionsByExerciseIdAndStudentLogin(exercise.getId(), username);\n }\n\n /**\n * Get all exercise participations belonging to exercise and student.\n *\n * @param exercise the exercise\n * @param studentId the id of student\n * @return the list of exercise participations belonging to exercise and student\n */\n public List<StudentParticipation> findByExerciseAndStudentId(Exercise exercise, Long studentId) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserId(exercise.getId(), studentId);\n return optionalTeam.map(team -> studentParticipationRepository.findByExerciseIdAndTeamId(exercise.getId(), team.getId())).orElse(List.of());\n }\n return studentParticipationRepository.findByExerciseIdAndStudentId(exercise.getId(), studentId);\n }\n\n /**\n * Get all exercise participations belonging to exercise and student with eager submissions.\n *\n * @param exercise the exercise\n * @param studentId the id of student\n * @return the list of exercise participations belonging to exercise and student\n */\n public List<StudentParticipation> findByExerciseAndStudentIdWithEagerSubmissions(Exercise exercise, Long studentId) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserId(exercise.getId(), studentId);\n return optionalTeam.map(team -> studentParticipationRepository.findByExerciseIdAndTeamIdWithEagerLegalSubmissions(exercise.getId(), team.getId())).orElse(List.of());\n }\n return studentParticipationRepository.findByExerciseIdAndStudentIdWithEagerLegalSubmissions(exercise.getId(), studentId);\n }\n\n /**\n * Get all programming exercise participations belonging to exercise and student with eager results and submissions.\n *\n * @param exercise the exercise\n * @param studentId the id of student\n * @return the list of programming exercise participations belonging to exercise and student\n */\n public List<StudentParticipation> findByExerciseAndStudentIdWithEagerResultsAndSubmissions(Exercise exercise, Long studentId) {\n if (exercise.isTeamMode()) {\n Optional<Team> optionalTeam = teamRepository.findOneByExerciseIdAndUserId(exercise.getId(), studentId);\n return optionalTeam.map(team -> studentParticipationRepository.findByExerciseIdAndTeamIdWithEagerResultsAndLegalSubmissions(exercise.getId(), team.getId()))\n .orElse(List.of());\n }\n return studentParticipationRepository.findByExerciseIdAndStudentIdWithEagerResultsAndLegalSubmissions(exercise.getId(), studentId);\n }\n\n /**\n * Deletes the build plan on the continuous integration server and sets the initialization state of the participation to inactive This means the participation can be resumed in\n * the future\n *\n * @param participation that will be set to inactive\n */\n public void cleanupBuildPlan(ProgrammingExerciseStudentParticipation participation) {\n // ignore participations without build plan id\n if (participation.getBuildPlanId() != null) {\n final var projectKey = ((ProgrammingExercise) participation.getExercise()).getProjectKey();\n continuousIntegrationService.get().deleteBuildPlan(projectKey, participation.getBuildPlanId());\n participation.setInitializationState(INACTIVE);\n participation.setBuildPlanId(null);\n programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n }\n\n /**\n * NOTICE: be careful with this method because it deletes the students code on the version control server Deletes the repository on the version control server and sets the\n * initialization state of the participation to finished This means the participation cannot be resumed in the future and would need to be restarted\n *\n * @param participation to be stopped\n */\n public void cleanupRepository(ProgrammingExerciseStudentParticipation participation) {\n // ignore participations without repository URL\n if (participation.getRepositoryUrl() != null) {\n versionControlService.get().deleteRepository(participation.getVcsRepositoryUrl());\n gitService.deleteLocalRepository(participation.getVcsRepositoryUrl());\n participation.setRepositoryUrl(null);\n participation.setInitializationState(InitializationState.FINISHED);\n programmingExerciseStudentParticipationRepository.saveAndFlush(participation);\n }\n }\n\n /**\n * Delete the participation by participationId.\n *\n * @param participationId the participationId of the entity\n * @param deleteBuildPlan determines whether the corresponding build plan should be deleted as well\n * @param deleteRepository determines whether the corresponding repository should be deleted as well\n */\n @Transactional // ok\n public void delete(Long participationId, boolean deleteBuildPlan, boolean deleteRepository) {\n StudentParticipation participation = studentParticipationRepository.findWithEagerLegalSubmissionsResultsFeedbacksById(participationId).get();\n log.info(\"Request to delete Participation : {}\", participation);\n\n if (participation instanceof ProgrammingExerciseStudentParticipation) {\n ProgrammingExerciseStudentParticipation programmingExerciseParticipation = (ProgrammingExerciseStudentParticipation) participation;\n var repositoryUrl = programmingExerciseParticipation.getVcsRepositoryUrl();\n String buildPlanId = programmingExerciseParticipation.getBuildPlanId();\n\n if (deleteBuildPlan && buildPlanId != null) {\n final var projectKey = programmingExerciseParticipation.getProgrammingExercise().getProjectKey();\n continuousIntegrationService.get().deleteBuildPlan(projectKey, buildPlanId);\n }\n if (deleteRepository && programmingExerciseParticipation.getRepositoryUrl() != null) {\n try {\n versionControlService.get().deleteRepository(repositoryUrl);\n }\n catch (Exception ex) {\n log.error(\"Could not delete repository: {}\", ex.getMessage());\n }\n }\n // delete local repository cache\n gitService.deleteLocalRepository(repositoryUrl);\n }\n\n complaintResponseRepository.deleteByComplaint_Result_Participation_Id(participationId);\n complaintRepository.deleteByResult_Participation_Id(participationId);\n ratingRepository.deleteByResult_Participation_Id(participationId);\n\n participation = (StudentParticipation) deleteResultsAndSubmissionsOfParticipation(participation.getId());\n\n Exercise exercise = participation.getExercise();\n exercise.removeParticipation(participation);\n exerciseRepository.save(exercise);\n studentParticipationRepository.delete(participation);\n }\n\n /**\n * Remove all results and submissions of the given participation. Will do nothing if invoked with a participation without results/submissions.\n *\n * @param participationId the id of the participation to delete results/submissions from.\n * @return participation without submissions and results.\n */\n @Transactional // ok\n public Participation deleteResultsAndSubmissionsOfParticipation(Long participationId) {\n log.info(\"Request to delete all results and submissions of participation with id : {}\", participationId);\n Participation participation = participationRepository.getOneWithEagerSubmissionsAndResults(participationId);\n Set<Submission> submissions = participation.getSubmissions();\n List<Result> resultsToBeDeleted = new ArrayList<>();\n\n // The result of the submissions will be deleted via cascade\n submissions.forEach(submission -> {\n resultsToBeDeleted.addAll(Objects.requireNonNull(submission.getResults()));\n submissionRepository.deleteById(submission.getId());\n });\n resultsToBeDeleted.forEach(result -> participantScoreRepository.deleteAllByResultIdTransactional(result.getId()));\n // The results that are only connected to a participation are also deleted\n resultsToBeDeleted.forEach(participation::removeResult);\n participation.getResults().forEach(result -> resultRepository.deleteById(result.getId()));\n return participation;\n }\n\n /**\n * Delete all participations belonging to the given exercise\n *\n * @param exerciseId the id of the exercise\n * @param deleteBuildPlan specify if build plan should be deleted\n * @param deleteRepository specify if repository should be deleted\n */\n @Transactional // ok\n public void deleteAllByExerciseId(Long exerciseId, boolean deleteBuildPlan, boolean deleteRepository) {\n log.info(\"Request to delete all participations of Exercise with id : {}\", exerciseId);\n List<StudentParticipation> participationsToDelete = studentParticipationRepository.findByExerciseId(exerciseId);\n for (StudentParticipation participation : participationsToDelete) {\n delete(participation.getId(), deleteBuildPlan, deleteRepository);\n }\n }\n\n /**\n * Delete all participations belonging to the given team\n *\n * @param teamId the id of the team\n * @param deleteBuildPlan specify if build plan should be deleted\n * @param deleteRepository specify if repository should be deleted\n */\n @Transactional // ok\n public void deleteAllByTeamId(Long teamId, boolean deleteBuildPlan, boolean deleteRepository) {\n log.info(\"Request to delete all participations of Team with id : {}\", teamId);\n List<StudentParticipation> participationsToDelete = studentParticipationRepository.findByTeamId(teamId);\n for (StudentParticipation participation : participationsToDelete) {\n delete(participation.getId(), deleteBuildPlan, deleteRepository);\n }\n }\n}\n" }, { "alpha_fraction": 0.72651606798172, "alphanum_fraction": 0.72651606798172, "avg_line_length": 46.2471923828125, "blob_id": "84c7c14d566ca7ed4ade67602f6f3e7fb59fd9d4", "content_id": "42d53cadcb227c0ed9b8311727eeefecf9226e8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4205, "license_type": "permissive", "max_line_length": 137, "num_lines": 89, "path": "/src/test/javascript/spec/service/login.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { SinonStub, stub } from 'sinon';\nimport { of, throwError } from 'rxjs';\nimport { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service';\nimport { MockRouter } from '../helpers/mocks/mock-router';\nimport { MockAccountService } from '../helpers/mocks/service/mock-account.service';\nimport { MockAuthServerProviderService } from '../helpers/mocks/service/mock-auth-server-provider.service';\nimport { MockAlertService } from '../helpers/mocks/service/mock-alert.service';\nimport { IAccountService } from 'app/core/auth/account.service';\nimport { IWebsocketService } from 'app/core/websocket/websocket.service';\nimport { LoginService } from 'app/core/login/login.service';\nimport { IAuthServerProvider } from 'app/core/auth/auth-jwt.service';\nimport { MockNotificationService } from '../helpers/mocks/service/mock-notification.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('LoginService', () => {\n let accountService: IAccountService;\n let websocketService: IWebsocketService;\n let authServerProvider: IAuthServerProvider;\n let router: MockRouter;\n let alertService: MockAlertService;\n let notificationService: MockNotificationService;\n let loginService: LoginService;\n\n let removeAuthTokenFromCachesStub: SinonStub;\n let authenticateStub: SinonStub;\n // let alertServiceClearStub: SinonStub;\n let notificationServiceCleanUpStub: SinonStub;\n let navigateByUrlStub: SinonStub;\n let alertServiceErrorStub: SinonStub;\n\n // TODO: reimplement this test using the typical TestBed configuration as in other tests\n\n beforeEach(() => {\n accountService = new MockAccountService();\n websocketService = new MockWebsocketService();\n authServerProvider = new MockAuthServerProviderService();\n router = new MockRouter();\n alertService = new MockAlertService();\n notificationService = new MockNotificationService();\n // @ts-ignore\n loginService = new LoginService(accountService, websocketService, authServerProvider, router, alertService, notificationService);\n\n removeAuthTokenFromCachesStub = stub(authServerProvider, 'removeAuthTokenFromCaches');\n authenticateStub = stub(accountService, 'authenticate');\n // alertServiceClearStub = stub(alertService, 'clear');\n notificationServiceCleanUpStub = stub(notificationService, 'cleanUp');\n navigateByUrlStub = stub(router, 'navigateByUrl');\n alertServiceErrorStub = stub(alertService, 'error');\n });\n\n afterEach(() => {\n removeAuthTokenFromCachesStub.restore();\n authenticateStub.restore();\n // alertServiceClearStub.restore();\n notificationServiceCleanUpStub.restore();\n navigateByUrlStub.restore();\n alertServiceErrorStub.restore();\n });\n\n it('should properly log out when every action is successful', () => {\n removeAuthTokenFromCachesStub.returns(of(undefined));\n navigateByUrlStub.returns(Promise.resolve(true));\n loginService.logout(true);\n\n expect(removeAuthTokenFromCachesStub).to.have.been.calledOnceWithExactly();\n expect(authenticateStub).to.have.been.calledOnceWithExactly(undefined);\n // expect(alertServiceClearStub).to.have.been.calledOnceWithExactly();\n expect(notificationServiceCleanUpStub).to.have.been.calledOnceWithExactly();\n expect(navigateByUrlStub).to.have.been.calledOnceWithExactly('/');\n expect(alertServiceErrorStub).not.to.have.been.called;\n });\n\n it('should emit an error when an action fails', () => {\n const error = 'fatal error';\n removeAuthTokenFromCachesStub.returns(of(undefined));\n authenticateStub.throws(throwError(error));\n loginService.logout(true);\n\n expect(removeAuthTokenFromCachesStub).to.have.been.calledOnceWithExactly();\n expect(authenticateStub).to.have.been.calledOnceWithExactly(undefined);\n // expect(alertServiceClearStub).not.to.have.been.called;\n expect(navigateByUrlStub).not.to.have.been.called;\n expect(alertServiceErrorStub).to.have.been.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.7012345790863037, "alphanum_fraction": 0.7024691104888916, "avg_line_length": 34.21739196777344, "blob_id": "72f659eceaf0807fe1ef3bec416c86189a948ec5", "content_id": "1ddac3cee66ccd54badf816ad641beeb82707129", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 810, "license_type": "permissive", "max_line_length": 83, "num_lines": 23, "path": "/src/main/webapp/app/entities/student-question.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\nimport { BaseEntity } from 'app/shared/model/base-entity';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { User } from 'app/core/user/user.model';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\n\nexport class StudentQuestion implements BaseEntity {\n public id?: number;\n public questionText?: string;\n public creationDate?: Moment;\n public visibleForStudents?: boolean;\n public answers?: StudentQuestionAnswer[];\n public author?: User;\n public exercise?: Exercise;\n public lecture?: Lecture;\n public votes?: number;\n\n constructor() {\n this.visibleForStudents = true; // default value\n this.votes = 0; // default value\n }\n}\n" }, { "alpha_fraction": 0.626459538936615, "alphanum_fraction": 0.6278448700904846, "avg_line_length": 39.91497802734375, "blob_id": "a26693fc06c76f341c53b309f93c86b48ba125b7", "content_id": "83237a7f806078024c750fe7d737c606942a8d00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 10106, "license_type": "permissive", "max_line_length": 172, "num_lines": 247, "path": "/src/main/webapp/app/exercises/modeling/shared/modeling-editor.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { AfterViewInit, Component, ElementRef, Input, OnChanges, OnDestroy, Renderer2, SimpleChanges, ViewChild, Output, EventEmitter } from '@angular/core';\nimport { ApollonEditor, ApollonMode, UMLDiagramType, UMLElementType, UMLModel, UMLRelationship, UMLRelationshipType } from '@ls1intum/apollon';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport interact from 'interactjs';\nimport { GuidedTourService } from 'app/guided-tour/guided-tour.service';\nimport { associationUML, personUML, studentUML } from 'app/guided-tour/guided-tour-task.model';\nimport { isFullScreen } from 'app/shared/util/fullscreen.util';\n\n@Component({\n selector: 'jhi-modeling-editor',\n templateUrl: './modeling-editor.component.html',\n styleUrls: ['./modeling-editor.component.scss'],\n})\nexport class ModelingEditorComponent implements AfterViewInit, OnDestroy, OnChanges {\n @ViewChild('editorContainer', { static: false })\n editorContainer: ElementRef;\n @ViewChild('resizeContainer', { static: false })\n resizeContainer: ElementRef;\n @Input()\n umlModel: UMLModel;\n @Input()\n diagramType: UMLDiagramType;\n @Input()\n readOnly = false;\n @Input()\n resizeOptions: { initialWidth: string; maxWidth?: number };\n @Input()\n showHelpButton = true;\n @Input()\n withExplanation = false;\n @Input()\n explanation: string;\n\n @Output()\n private onModelChanged: EventEmitter<UMLModel> = new EventEmitter<UMLModel>();\n\n @Output()\n explanationChange = new EventEmitter();\n\n private apollonEditor?: ApollonEditor;\n private modelSubscription: number;\n\n constructor(private jhiAlertService: JhiAlertService, private renderer: Renderer2, private modalService: NgbModal, private guidedTourService: GuidedTourService) {}\n\n /**\n * Initializes the Apollon editor.\n * If this is a guided tour, than calls assessModelForGuidedTour.\n * If resizeOptions is set to true, resizes the editor according to interactions.\n */\n ngAfterViewInit(): void {\n this.initializeApollonEditor();\n this.guidedTourService.checkModelingComponent().subscribe((key) => {\n if (key) {\n this.assessModelForGuidedTour(key, this.getCurrentModel());\n }\n });\n if (this.resizeOptions) {\n if (this.resizeOptions.initialWidth) {\n this.renderer.setStyle(this.resizeContainer.nativeElement, 'width', this.resizeOptions.initialWidth);\n }\n interact('.resizable')\n .resizable({\n edges: { left: false, right: '.draggable-right', bottom: false, top: false },\n modifiers: [\n interact.modifiers!.restrictSize({\n min: { width: 15, height: 0 },\n max: { width: this.resizeOptions.maxWidth ? this.resizeOptions.maxWidth : 2500, height: 2000 },\n }),\n ],\n inertia: true,\n })\n .on('resizestart', function (event: any) {\n event.target.classList.add('card-resizable');\n })\n .on('resizeend', function (event: any) {\n event.target.classList.remove('card-resizable');\n })\n .on('resizemove', (event: any) => {\n const target = event.target;\n target.style.width = event.rect.width + 'px';\n });\n }\n }\n\n /**\n * This function initializes the Apollon editor in Modeling mode.\n */\n private initializeApollonEditor(): void {\n if (this.apollonEditor) {\n this.apollonEditor.unsubscribeFromModelChange(this.modelSubscription);\n this.apollonEditor.destroy();\n }\n // Apollon doesn't need assessments in Modeling mode\n this.removeAssessments(this.umlModel);\n this.apollonEditor = new ApollonEditor(this.editorContainer.nativeElement, {\n model: this.umlModel,\n mode: ApollonMode.Modelling,\n readonly: this.readOnly,\n type: this.diagramType,\n });\n this.modelSubscription = this.apollonEditor.subscribeToModelChange((model: UMLModel) => {\n this.onModelChanged.emit(model);\n });\n }\n\n get isApollonEditorMounted(): boolean {\n return this.apollonEditor != undefined;\n }\n\n /**\n * Removes the Assessments from a given UMLModel. In modeling mode the assessments are not needed.\n * Also they should not be sent to the server and persisted as part of the model JSON.\n *\n * @param umlModel the model for which the assessments should be removed\n */\n private removeAssessments(umlModel: UMLModel): void {\n if (umlModel) {\n umlModel.assessments = [];\n }\n }\n\n /**\n * Returns the current model of the Apollon editor. It removes the assessment first, as it should not be part\n * of the model outside of Apollon.\n */\n getCurrentModel(): UMLModel {\n const currentModel: UMLModel = this.apollonEditor!.model;\n this.removeAssessments(currentModel);\n return currentModel;\n }\n\n /**\n * This function opens the modal for the help dialog.\n */\n open(content: any): void {\n this.modalService.open(content, { size: 'lg' });\n }\n\n /**\n * If changes are made to the the uml model, update the model and remove assessments\n * @param {simpleChanges} changes - Changes made\n */\n ngOnChanges(changes: SimpleChanges): void {\n if (changes.umlModel && changes.umlModel.currentValue && this.apollonEditor) {\n this.umlModel = changes.umlModel.currentValue;\n // Apollon doesn't need assessments in Modeling mode\n this.removeAssessments(this.umlModel);\n this.apollonEditor.model = this.umlModel;\n }\n }\n\n /**\n * If the apollon editor is not null, destroy it and set it to null, on component destruction\n */\n ngOnDestroy(): void {\n if (this.apollonEditor) {\n if (this.modelSubscription) {\n this.apollonEditor.unsubscribeFromModelChange(this.modelSubscription);\n }\n this.apollonEditor.destroy();\n this.apollonEditor = undefined;\n }\n }\n\n /**\n * Assess the model for the modeling guided tutorial\n * @param umlName the identifier of the UML element that has to be assessed\n * @param umlModel the current UML model in the editor\n */\n assessModelForGuidedTour(umlName: string, umlModel: UMLModel): void {\n // Find the required UML classes\n const personClass = this.elementWithClass(personUML.name, umlModel);\n const studentClass = this.elementWithClass(studentUML.name, umlModel);\n let personStudentAssociation: UMLRelationship | undefined;\n\n switch (umlName) {\n // Check if the Person class is correct\n case personUML.name: {\n const nameAttribute = this.elementWithAttribute(personUML.attribute, umlModel);\n const personClassCorrect = personClass && nameAttribute ? nameAttribute.owner === personClass.id : false;\n this.guidedTourService.updateModelingResult(umlName, personClassCorrect);\n break;\n }\n // Check if the Student class is correct\n case studentUML.name: {\n const majorAttribute = this.elementWithAttribute(studentUML.attribute, umlModel);\n const visitLectureMethod = this.elementWithMethod(studentUML.method, umlModel);\n const studentClassCorrect =\n studentClass && majorAttribute && visitLectureMethod ? majorAttribute.owner === studentClass.id && visitLectureMethod.owner === studentClass.id : false;\n this.guidedTourService.updateModelingResult(umlName, studentClassCorrect);\n break;\n }\n // Check if the Inheritance association is correct\n case associationUML.name: {\n personStudentAssociation = umlModel.relationships.find(\n (relationship) =>\n relationship.source.element === studentClass!.id &&\n relationship.target.element === personClass!.id &&\n relationship.type === UMLRelationshipType.ClassInheritance,\n );\n this.guidedTourService.updateModelingResult(umlName, !!personStudentAssociation);\n break;\n }\n }\n }\n\n /**\n * Return the UMLModelElement of the type class with the @param name\n * @param name class name\n * @param umlModel current model that is assessed\n */\n elementWithClass(name: string, umlModel: UMLModel) {\n return umlModel.elements.find((element) => element.name.trim() === name && element.type === UMLElementType.Class);\n }\n\n /**\n * Return the UMLModelElement of the type ClassAttribute with the @param attribute\n * @param attribute name\n * @param umlModel current model that is assessed\n */\n elementWithAttribute(attribute: string, umlModel: UMLModel) {\n return umlModel.elements.find((element) => element.name.includes(attribute) && element.type === UMLElementType.ClassAttribute);\n }\n\n /**\n * Return the UMLModelElement of the type ClassMethod with the @param method\n * @param method name\n * @param umlModel current model that is assessed\n */\n elementWithMethod(method: string, umlModel: UMLModel) {\n return umlModel.elements.find((element) => element.name.includes(method) && element.type === UMLElementType.ClassMethod);\n }\n\n /**\n * checks if this component is the current fullscreen component\n */\n get isFullScreen() {\n return isFullScreen();\n }\n\n // Emit explanation change when textarea input changes\n onExplanationInput(newValue: string) {\n this.explanationChange.emit(newValue);\n this.explanation = newValue;\n }\n}\n" }, { "alpha_fraction": 0.6650536060333252, "alphanum_fraction": 0.6674731969833374, "avg_line_length": 38.6301383972168, "blob_id": "dcda9b5ebd48d96e6b2c6da6181780590172045a", "content_id": "1bd81a6f7a2bc23578b0e0f41ebd7b1bc1317c9a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2893, "license_type": "permissive", "max_line_length": 162, "num_lines": 73, "path": "/src/main/webapp/app/exam/manage/student-exams/student-exam-detail-table-row/student-exam-detail-table-row.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges } from '@angular/core';\nimport { Exercise, ExerciseType, getIcon } from 'app/entities/exercise.model';\nimport { Submission } from 'app/entities/submission.model';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { getExerciseSubmissionsLink, getLinkToSubmissionAssessment } from 'app/utils/navigation.utils';\nimport { round } from 'app/shared/util/utils';\nimport { Course } from 'app/entities/course.model';\nimport { Result } from 'app/entities/result.model';\nimport { StudentExam } from 'app/entities/student-exam.model';\n\n@Component({\n /* tslint:disable-next-line component-selector */\n selector: '[jhi-student-exam-detail-table-row]',\n templateUrl: './student-exam-detail-table-row.component.html',\n providers: [],\n})\nexport class StudentExamDetailTableRowComponent implements OnChanges {\n @Input() exercise: Exercise;\n @Input() examId: number;\n @Input() isTestRun: boolean;\n @Input() course: Course;\n @Input() busy: boolean;\n @Input() studentExam: StudentExam;\n\n courseId: number;\n studentParticipation: StudentParticipation;\n submission: Submission;\n result: Result;\n openingAssessmentEditorForNewSubmission = false;\n readonly ExerciseType = ExerciseType;\n getIcon = getIcon;\n\n ngOnChanges() {\n if (this.exercise.studentParticipations?.[0]) {\n this.studentParticipation = this.exercise.studentParticipations![0];\n if (this.studentParticipation.submissions?.length! > 0) {\n this.submission = this.studentParticipation.submissions![0];\n }\n if (this.studentParticipation.results?.length! > 0) {\n this.result = this.studentParticipation.results![0];\n }\n }\n if (this.course && this.course.id) {\n this.courseId = this.course.id!;\n }\n }\n\n /**\n * get the link for the assessment of a specific submission of the current exercise\n * @param exercise\n * @param submission\n * @param resultId\n */\n getAssessmentLink(exercise: Exercise, submission?: Submission, resultId?: number) {\n let route;\n if (!exercise || !exercise.type) {\n return;\n }\n\n if (exercise.type === ExerciseType.PROGRAMMING) {\n route = getExerciseSubmissionsLink(exercise.type, this.courseId, exercise.id!, this.examId, exercise.exerciseGroup?.id!);\n } else if (submission) {\n this.openingAssessmentEditorForNewSubmission = true;\n route = getLinkToSubmissionAssessment(exercise.type, this.courseId, exercise.id!, submission.id!, this.examId, exercise.exerciseGroup?.id!, resultId);\n this.openingAssessmentEditorForNewSubmission = false;\n }\n return route;\n }\n\n rounding(number: number) {\n return round(number, 1);\n }\n}\n" }, { "alpha_fraction": 0.5682912468910217, "alphanum_fraction": 0.5715795755386353, "avg_line_length": 38.23963165283203, "blob_id": "75410bc280462e97f76ce12a7ab6d74fb7c89aa6", "content_id": "d40e5508d983ff54b4158accddb13f26bd3790ea", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8515, "license_type": "permissive", "max_line_length": 102, "num_lines": 217, "path": "/src/test/javascript/spec/component/exam/exam-update.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed, tick, fakeAsync } from '@angular/core/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ExamUpdateComponent } from 'app/exam/manage/exams/exam-update.component';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { ActivatedRoute, convertToParamMap, Params } from '@angular/router';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { Exam } from 'app/entities/exam.model';\nimport { HttpResponse, HttpErrorResponse } from '@angular/common/http';\nimport { MockComponent, MockDirective, MockProvider, MockModule, MockPipe } from 'ng-mocks';\nimport { of, throwError } from 'rxjs';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { FormsModule } from '@angular/forms';\nimport { HttpClientModule } from '@angular/common/http';\nimport { FontAwesomeTestingModule } from '@fortawesome/angular-fontawesome/testing';\nimport { Course } from 'app/entities/course.model';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component.ts';\nimport { NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { ArtemisDataTableModule } from 'app/shared/data-table/data-table.module';\nimport { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport * as moment from 'moment';\nimport { Component } from '@angular/core';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({\n template: '',\n})\nclass DummyComponent {}\n\ndescribe('Exam Update Component', function () {\n let component: ExamUpdateComponent;\n let fixture: ComponentFixture<ExamUpdateComponent>;\n let examManagementService: ExamManagementService;\n const exam = { id: 1 } as Exam;\n const course = { id: 1 } as Course;\n const routes = [\n { path: 'course-management/:courseId/exams/:examId', component: DummyComponent },\n { path: 'course-management/:courseId/exams', component: DummyComponent },\n ];\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [\n RouterTestingModule.withRoutes(routes),\n ArtemisDataTableModule,\n MockModule(NgbModule),\n TranslateModule.forRoot(),\n FontAwesomeTestingModule,\n FormsModule,\n HttpClientModule,\n ],\n declarations: [\n ExamUpdateComponent,\n MockComponent(AlertErrorComponent),\n MockComponent(FormDateTimePickerComponent),\n MockComponent(MarkdownEditorComponent),\n DummyComponent,\n MockPipe(ArtemisTranslatePipe),\n ],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n MockProvider(JhiAlertService),\n MockDirective(JhiTranslateDirective),\n {\n provide: ActivatedRoute,\n useValue: {\n data: {\n subscribe: (fn: (value: Params) => void) =>\n fn({\n exam,\n }),\n },\n snapshot: {\n paramMap: convertToParamMap({\n courseId: '1',\n }),\n },\n },\n },\n MockProvider(CourseManagementService, {\n find: () => {\n return of(\n new HttpResponse({\n body: course,\n status: 200,\n }),\n );\n },\n }),\n MockProvider(ExamManagementService, {\n create: () => {\n return of(\n new HttpResponse({\n body: {},\n status: 200,\n }),\n );\n },\n update: () => {\n return of(\n new HttpResponse({\n body: {},\n status: 200,\n }),\n );\n },\n }),\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(ExamUpdateComponent);\n component = fixture.componentInstance;\n examManagementService = fixture.debugElement.injector.get(ExamManagementService);\n });\n\n afterEach(() => {\n sinon.restore();\n });\n\n it('should initialize', () => {\n fixture.detectChanges();\n expect(fixture).to.be.ok;\n expect(component.exam).to.exist;\n expect(component.exam.course).to.deep.equal(course);\n expect(component.exam.gracePeriod).to.equal(180);\n expect(component.exam.numberOfCorrectionRoundsInExam).to.equal(1);\n });\n\n it('should validate the dates correctly', () => {\n exam.visibleDate = moment().add(1, 'hours');\n exam.startDate = moment().add(2, 'hours');\n exam.endDate = moment().add(3, 'hours');\n fixture.detectChanges();\n expect(component.isValidConfiguration).is.true;\n\n exam.publishResultsDate = moment().add(4, 'hours');\n exam.examStudentReviewStart = moment().add(5, 'hours');\n exam.examStudentReviewEnd = moment().add(6, 'hours');\n fixture.detectChanges();\n expect(component.isValidConfiguration).is.true;\n\n exam.visibleDate = undefined;\n exam.startDate = undefined;\n exam.endDate = undefined;\n fixture.detectChanges();\n expect(component.isValidConfiguration).is.false;\n });\n\n it('should update', fakeAsync(() => {\n fixture.detectChanges();\n\n const updateSpy = sinon.spy(examManagementService, 'update');\n\n // trigger save\n component.save();\n tick();\n expect(updateSpy).to.have.been.calledOnce;\n expect(component.isSaving).is.false;\n }));\n\n it('should correctly catch HTTPError when updating the exam', fakeAsync(() => {\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n fixture.detectChanges();\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const updateStub = sinon.stub(examManagementService, 'update').returns(throwError(httpError));\n\n // trigger save\n component.save();\n tick();\n expect(alertServiceSpy).to.have.been.calledOnce;\n expect(component.isSaving).is.false;\n\n updateStub.restore();\n }));\n\n it('should create', fakeAsync(() => {\n exam.id = undefined;\n fixture.detectChanges();\n\n const createSpy = sinon.spy(examManagementService, 'create');\n\n // trigger save\n component.save();\n tick();\n expect(createSpy).to.have.been.calledOnce;\n expect(component.isSaving).is.false;\n }));\n\n it('should correctly catch HTTPError when creating the exam', fakeAsync(() => {\n const alertService = TestBed.inject(JhiAlertService);\n const httpError = new HttpErrorResponse({ error: 'Forbidden', status: 403 });\n fixture.detectChanges();\n\n const alertServiceSpy = sinon.spy(alertService, 'error');\n const createStub = sinon.stub(examManagementService, 'create').returns(throwError(httpError));\n\n // trigger save\n component.save();\n tick();\n expect(alertServiceSpy).to.have.been.calledOnce;\n expect(component.isSaving).is.false;\n\n createStub.restore();\n }));\n});\n" }, { "alpha_fraction": 0.6356545686721802, "alphanum_fraction": 0.6362116932868958, "avg_line_length": 20.117647171020508, "blob_id": "b7ecc11e291f407275122dfc7fd4894231d0bea0", "content_id": "9e6d6fba0e05a760d5e9901ee0d731f81fb25163", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1795, "license_type": "permissive", "max_line_length": 74, "num_lines": 85, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/bamboo/dto/BambooProjectDTO.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.bamboo.dto;\n\nimport java.util.List;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n@JsonIgnoreProperties(ignoreUnknown = true)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class BambooProjectDTO {\n\n private String key;\n\n private String name;\n\n private String description;\n\n private BambooBuildPlansDTO plans;\n\n /**\n * needed for Jackson\n */\n public BambooProjectDTO() {\n }\n\n public BambooProjectDTO(String key, String name, String description) {\n this.key = key;\n this.name = name;\n this.description = description;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public BambooBuildPlansDTO getPlans() {\n return plans;\n }\n\n public void setPlans(BambooBuildPlansDTO plans) {\n this.plans = plans;\n }\n\n @JsonIgnoreProperties(ignoreUnknown = true)\n public static final class BambooBuildPlansDTO {\n\n private List<BambooBuildPlanDTO> plan;\n\n public BambooBuildPlansDTO() {\n }\n\n public BambooBuildPlansDTO(List<BambooBuildPlanDTO> plan) {\n this.plan = plan;\n }\n\n public List<BambooBuildPlanDTO> getPlan() {\n return plan;\n }\n\n public void setPlan(List<BambooBuildPlanDTO> plan) {\n this.plan = plan;\n }\n }\n\n}\n" }, { "alpha_fraction": 0.7192417979240417, "alphanum_fraction": 0.7206723690032959, "avg_line_length": 29.39130401611328, "blob_id": "24988d2c73b3c03dca797aae0fec416f19e25b48", "content_id": "da78b66e92ab2669be96c268ba5ed90b383ba8d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2796, "license_type": "permissive", "max_line_length": 153, "num_lines": 92, "path": "/src/main/java/de/tum/in/www1/artemis/domain/lecture/LectureUnit.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain.lecture;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\nimport org.hibernate.annotations.DiscriminatorOptions;\n\nimport com.fasterxml.jackson.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.DomainObject;\nimport de.tum.in.www1.artemis.domain.LearningGoal;\nimport de.tum.in.www1.artemis.domain.Lecture;\n\n@Entity\n@Table(name = \"lecture_unit\")\n@Inheritance(strategy = InheritanceType.SINGLE_TABLE)\n@DiscriminatorColumn(name = \"discriminator\", discriminatorType = DiscriminatorType.STRING)\n@DiscriminatorValue(\"L\")\n@DiscriminatorOptions(force = true)\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"type\")\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\n// Annotation necessary to distinguish between concrete implementations of lecture-content when deserializing from JSON\n@JsonSubTypes({ @JsonSubTypes.Type(value = AttachmentUnit.class, name = \"attachment\"), @JsonSubTypes.Type(value = ExerciseUnit.class, name = \"exercise\"),\n @JsonSubTypes.Type(value = TextUnit.class, name = \"text\"), @JsonSubTypes.Type(value = VideoUnit.class, name = \"video\"), })\npublic abstract class LectureUnit extends DomainObject {\n\n @Transient\n private boolean visibleToStudents;\n\n @Column(name = \"name\")\n private String name;\n\n @Column(name = \"release_date\")\n private ZonedDateTime releaseDate;\n\n @ManyToOne\n @JoinColumn(name = \"lecture_id\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n private Lecture lecture;\n\n @ManyToMany(mappedBy = \"lectureUnits\")\n @OrderBy(\"title\")\n @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n public Set<LearningGoal> learningGoals = new HashSet<>();\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Lecture getLecture() {\n return lecture;\n }\n\n public void setLecture(Lecture lecture) {\n this.lecture = lecture;\n }\n\n public ZonedDateTime getReleaseDate() {\n return releaseDate;\n }\n\n public void setReleaseDate(ZonedDateTime releaseDate) {\n this.releaseDate = releaseDate;\n }\n\n public Set<LearningGoal> getLearningGoals() {\n return learningGoals;\n }\n\n public void setLearningGoals(Set<LearningGoal> learningGoals) {\n this.learningGoals = learningGoals;\n }\n\n @JsonProperty(\"visibleToStudents\")\n public boolean isVisibleToStudents() {\n if (releaseDate == null) {\n return true;\n }\n return releaseDate.isBefore(ZonedDateTime.now());\n }\n\n}\n" }, { "alpha_fraction": 0.7840440273284912, "alphanum_fraction": 0.7840440273284912, "avg_line_length": 44.4375, "blob_id": "a0cdcb9c3303f4be3d156337dbef660dfe95b754", "content_id": "4b923ecaf82e786617bb6247555bd903e34b0ab5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 727, "license_type": "permissive", "max_line_length": 97, "num_lines": 16, "path": "/src/main/webapp/app/complaints/complaints.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\n\nimport { ComplaintsComponent } from './complaints.component';\nimport { MomentModule } from 'ngx-moment';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { ComplaintInteractionsComponent } from 'app/complaints/complaint-interactions.component';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\n@NgModule({\n imports: [ArtemisSharedModule, MomentModule, ClipboardModule],\n declarations: [ComplaintsComponent, ComplaintInteractionsComponent],\n exports: [ComplaintsComponent, ComplaintInteractionsComponent],\n providers: [ComplaintService],\n})\nexport class ArtemisComplaintsModule {}\n" }, { "alpha_fraction": 0.6546797752380371, "alphanum_fraction": 0.6546797752380371, "avg_line_length": 45.1363639831543, "blob_id": "4ab0e5720f8074595f223b0bb3f671803a19bf4b", "content_id": "94097fd2361668a5cb13014f48b8d3bbc5c8c6b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2030, "license_type": "permissive", "max_line_length": 141, "num_lines": 44, "path": "/src/main/webapp/app/shared/statistics-graph/statistics.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { HttpClient, HttpParams } from '@angular/common/http';\nimport { Observable } from 'rxjs/Observable';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { Graphs, SpanType } from 'app/entities/statistics.model';\nimport { CourseManagementStatisticsDTO } from 'app/course/manage/course-management-statistics-dto';\n\n@Injectable({ providedIn: 'root' })\nexport class StatisticsService {\n private resourceUrl = SERVER_API_URL + 'api/management/statistics/';\n\n constructor(private http: HttpClient) {}\n\n /**\n * Sends a GET request to retrieve the data for a graph based on the graphType in the last *span* days and the given period\n */\n getChartData(span: SpanType, periodIndex: number, graphType: Graphs): Observable<number[]> {\n const params = new HttpParams()\n .set('span', '' + span)\n .set('periodIndex', '' + periodIndex)\n .set('graphType', '' + graphType);\n return this.http.get<number[]>(`${this.resourceUrl}data`, { params });\n }\n\n /**\n * Sends a GET request to retrieve the data for a graph based on the graphType in the last *span* days, the given period and the courseId\n */\n getChartDataForCourse(span: SpanType, periodIndex: number, graphType: Graphs, courseId: number): Observable<number[]> {\n const params = new HttpParams()\n .set('span', '' + span)\n .set('periodIndex', '' + periodIndex)\n .set('graphType', '' + graphType)\n .set('courseId', '' + courseId);\n return this.http.get<number[]>(`${this.resourceUrl}data-for-course`, { params });\n }\n\n /**\n * Sends a GET request to retrieve data needed for the course statistics\n */\n getCourseStatistics(courseId: number): Observable<CourseManagementStatisticsDTO> {\n const params = new HttpParams().set('courseId', '' + courseId);\n return this.http.get<CourseManagementStatisticsDTO>(`${this.resourceUrl}course-statistics`, { params });\n }\n}\n" }, { "alpha_fraction": 0.7297297120094299, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 31.375, "blob_id": "855de3c23e10cf7da094dcb2ea13e701c725ccc7", "content_id": "e271d8a50181ad929df941695071626885341149", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 259, "license_type": "permissive", "max_line_length": 58, "num_lines": 8, "path": "/src/main/webapp/app/entities/exam-session.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { StudentExam } from './student-exam.model';\n\nexport class ExamSession implements BaseEntity {\n public id?: number;\n public studentExam?: StudentExam;\n public sessionToken?: string;\n}\n" }, { "alpha_fraction": 0.7057256698608398, "alphanum_fraction": 0.7057256698608398, "avg_line_length": 33.1363639831543, "blob_id": "a002e95eb598224461b1dff3ccfe3421af424105", "content_id": "1b47b27c7985b42c3239aa7bde657047e2eb6598", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 751, "license_type": "permissive", "max_line_length": 84, "num_lines": 22, "path": "/src/main/webapp/app/entities/quiz/short-answer-spot.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { BaseEntity } from 'app/shared/model/base-entity';\nimport { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model';\nimport { generate } from 'app/exercises/quiz/manage/temp-id';\nimport { CanBecomeInvalid } from 'app/entities/quiz/drop-location.model';\n\nexport class ShortAnswerSpot implements BaseEntity, CanBecomeInvalid {\n public id?: number;\n public width?: number;\n public spotNr?: number;\n public invalid?: boolean;\n public question?: ShortAnswerQuestion;\n public tempID?: number;\n\n // additionally added after database changes with Stephan\n public posX?: number;\n public posY?: number;\n\n constructor() {\n this.tempID = generate();\n this.invalid = false; // default\n }\n}\n" }, { "alpha_fraction": 0.4732181429862976, "alphanum_fraction": 0.48444923758506775, "avg_line_length": 32.30935287475586, "blob_id": "e9b50f4a223d280eeda0c73fb2b45fe1b8f35923", "content_id": "57eb711283ef7c71ffd5be53ab0c97f3ba2fe9d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4630, "license_type": "permissive", "max_line_length": 110, "num_lines": 139, "path": "/src/main/webapp/app/course/manage/overview/course-management-overview-statistics.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnChanges, OnInit } from '@angular/core';\nimport { Graphs } from 'app/entities/statistics.model';\nimport { ChartDataSets, ChartType } from 'chart.js';\nimport { Label } from 'ng2-charts';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ChangeDetectionStrategy } from '@angular/core';\nimport { DataSet } from 'app/exercises/quiz/manage/statistics/quiz-statistic/quiz-statistic.component';\n\n@Component({\n selector: 'jhi-course-management-overview-statistics',\n templateUrl: './course-management-overview-statistics.component.html',\n changeDetection: ChangeDetectionStrategy.OnPush,\n})\nexport class CourseManagementOverviewStatisticsComponent implements OnInit, OnChanges {\n @Input()\n amountOfStudentsInCourse: number;\n\n @Input()\n initialStats: number[] | undefined;\n\n loading = true;\n graphType: Graphs = Graphs.ACTIVE_STUDENTS;\n\n // Chart\n chartName: string;\n\n // Histogram-related properties\n barChartOptions: any = {};\n barChartType: ChartType = 'line';\n amountOfStudents: string;\n barChartLegend = false;\n\n // Data\n barChartLabels: Label[] = [];\n chartData: ChartDataSets[] = [];\n dataForSpanType: number[] = [];\n\n constructor(private translateService: TranslateService) {}\n\n ngOnInit() {\n this.amountOfStudents = this.translateService.instant('artemisApp.courseStatistics.amountOfStudents');\n\n for (let i = 0; i < 4; i++) {\n this.barChartLabels[i] = this.translateService.instant(`overview.${3 - i}_weeks_ago`);\n }\n\n this.createChartData();\n\n // Store a reference for the label function\n const self = this;\n this.barChartOptions = {\n layout: {\n padding: {\n top: 20,\n },\n },\n responsive: true,\n hover: {\n animationDuration: 0,\n },\n animation: {\n duration: 1,\n onComplete() {\n const chartInstance = this.chart,\n ctx = chartInstance.ctx;\n ctx.textAlign = 'center';\n ctx.textBaseline = 'bottom';\n\n this.data.datasets.forEach(function (dataset: DataSet, j: number) {\n const meta = chartInstance.controller.getDatasetMeta(j);\n meta.data.forEach(function (bar: any, index: number) {\n const data = !!self.initialStats ? self.initialStats[index] : 0;\n ctx.fillText(String(data), bar._model.x, bar._model.y - 5);\n });\n });\n },\n },\n scales: {\n yAxes: [\n {\n ticks: {\n beginAtZero: true,\n min: 0,\n max: 100,\n autoSkip: true,\n precision: 0,\n stepSize: 20,\n callback(value: number) {\n return value + '%';\n },\n },\n },\n ],\n },\n tooltips: {\n enabled: true,\n callbacks: {\n label(tooltipItem: any) {\n if (!self.initialStats) {\n return ' 0';\n }\n\n return ' ' + self.initialStats[tooltipItem.index];\n },\n },\n },\n };\n }\n\n ngOnChanges() {\n if (!!this.initialStats) {\n this.loading = false;\n this.createChartData();\n }\n }\n\n private createChartData() {\n if (this.amountOfStudentsInCourse > 0 && !!this.initialStats) {\n this.dataForSpanType = [];\n for (const value of this.initialStats) {\n this.dataForSpanType.push((value * 100) / this.amountOfStudentsInCourse);\n }\n } else {\n this.dataForSpanType = new Array(4).fill(0);\n }\n\n this.chartData = [\n {\n label: this.amountOfStudents,\n data: this.dataForSpanType,\n backgroundColor: 'rgba(53,61,71,1)',\n borderColor: 'rgba(53,61,71,1)',\n fill: false,\n pointBackgroundColor: 'rgba(53,61,71,1)',\n pointHoverBorderColor: 'rgba(53,61,71,1)',\n },\n ];\n }\n}\n" }, { "alpha_fraction": 0.6630378365516663, "alphanum_fraction": 0.6649386286735535, "avg_line_length": 50.439998626708984, "blob_id": "be00aa10779ad99ea8d49c0914d421512d5753a0", "content_id": "25cfd086cc1218459d54e5ef97c9a727e1d01eb3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 11574, "license_type": "permissive", "max_line_length": 161, "num_lines": 225, "path": "/src/test/javascript/spec/component/lecture-unit/lecture-unit-management.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { LectureUnitManagementComponent } from 'app/lecture/lecture-unit/lecture-unit-management/lecture-unit-management.component';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ExerciseUnit } from 'app/entities/lecture-unit/exerciseUnit.model';\nimport * as sinon from 'sinon';\nimport { MockPipe } from 'ng-mocks/dist/lib/mock-pipe/mock-pipe';\nimport { Component, Directive, Input } from '@angular/core';\nimport { ExerciseUnitComponent } from 'app/overview/course-lectures/exercise-unit/exercise-unit.component';\nimport { MockComponent, MockDirective, MockProvider } from 'ng-mocks';\nimport { AttachmentUnitComponent } from 'app/overview/course-lectures/attachment-unit/attachment-unit.component';\nimport { VideoUnitComponent } from 'app/overview/course-lectures/video-unit/video-unit.component';\nimport { TextUnitComponent } from 'app/overview/course-lectures/text-unit/text-unit.component';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { ActivatedRoute, Params, Router, RouterOutlet } from '@angular/router';\nimport { LectureUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service';\nimport { LectureService } from 'app/lecture/lecture.service';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { VideoUnit } from 'app/entities/lecture-unit/videoUnit.model';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { of } from 'rxjs';\nimport { By } from '@angular/platform-browser';\nimport { ActionType } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { UnitCreationCardComponent } from 'app/lecture/lecture-unit/lecture-unit-management/unit-creation-card/unit-creation-card.component';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n// tslint:disable-next-line:directive-selector\n@Directive({ selector: '[routerLink]' })\nexport class MockRouterLinkDirective {\n @Input('routerLink') data: any;\n}\n\n@Component({ selector: 'jhi-learning-goals-popover', template: '' })\nclass LearningGoalsPopoverStubComponent {\n @Input()\n courseId: number;\n @Input()\n learningGoals: LearningGoal[] = [];\n @Input()\n navigateTo: 'learningGoalManagement' | 'courseStatistics' = 'courseStatistics';\n}\ndescribe('LectureUnitManagementComponent', () => {\n let lectureUnitManagementComponent: LectureUnitManagementComponent;\n let lectureUnitManagementComponentFixture: ComponentFixture<LectureUnitManagementComponent>;\n\n let lectureService: LectureService;\n let lectureUnitService: LectureUnitService;\n let findLectureStub: sinon.SinonStub;\n let updateOrderStub: sinon.SinonStub;\n\n let attachmentUnit: AttachmentUnit;\n let exerciseUnit: ExerciseUnit;\n let textUnit: TextUnit;\n let videoUnit: VideoUnit;\n let lecture: Lecture;\n\n beforeEach(() => {\n return TestBed.configureTestingModule({\n imports: [],\n declarations: [\n LectureUnitManagementComponent,\n MockComponent(UnitCreationCardComponent),\n LearningGoalsPopoverStubComponent,\n MockPipe(ArtemisTranslatePipe),\n MockComponent(ExerciseUnitComponent),\n MockComponent(AttachmentUnitComponent),\n MockComponent(VideoUnitComponent),\n MockComponent(TextUnitComponent),\n MockComponent(FaIconComponent),\n MockComponent(AlertComponent),\n MockDirective(DeleteButtonDirective),\n MockDirective(HasAnyAuthorityDirective),\n MockDirective(RouterOutlet),\n MockRouterLinkDirective,\n ],\n providers: [\n MockProvider(LectureUnitService),\n MockProvider(LectureService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n params: {\n subscribe: (fn: (value: Params) => void) =>\n fn({\n lectureId: 1,\n }),\n },\n },\n children: [],\n },\n },\n ],\n })\n .compileComponents()\n .then(() => {\n lectureUnitManagementComponentFixture = TestBed.createComponent(LectureUnitManagementComponent);\n lectureUnitManagementComponent = lectureUnitManagementComponentFixture.componentInstance;\n lectureService = TestBed.inject(LectureService);\n lectureUnitService = TestBed.inject(LectureUnitService);\n\n findLectureStub = sinon.stub(lectureService, 'find');\n updateOrderStub = sinon.stub(lectureUnitService, 'updateOrder');\n\n textUnit = new TextUnit();\n textUnit.id = 0;\n videoUnit = new VideoUnit();\n videoUnit.id = 1;\n exerciseUnit = new ExerciseUnit();\n exerciseUnit.id = 2;\n attachmentUnit = new AttachmentUnit();\n attachmentUnit.id = 3;\n\n lecture = new Lecture();\n lecture.id = 0;\n lecture.lectureUnits = [textUnit, videoUnit, exerciseUnit, attachmentUnit];\n\n findLectureStub.returns(\n of(\n new HttpResponse({\n body: lecture,\n status: 200,\n }),\n ),\n );\n\n updateOrderStub.returns(\n of(\n new HttpResponse({\n body: [],\n status: 200,\n }),\n ),\n );\n\n lectureUnitManagementComponentFixture.detectChanges();\n });\n });\n it('should initialize', () => {\n lectureUnitManagementComponentFixture.detectChanges();\n expect(lectureUnitManagementComponent).to.be.ok;\n });\n\n it('should move down', () => {\n const originalOrder = [...lecture.lectureUnits!];\n lectureUnitManagementComponentFixture.detectChanges();\n const moveDownSpy = sinon.spy(lectureUnitManagementComponent, 'moveDown');\n const moveUpSpy = sinon.spy(lectureUnitManagementComponent, 'moveUp');\n const upButton = lectureUnitManagementComponentFixture.debugElement.query(By.css('#up-0'));\n expect(upButton).to.exist;\n upButton.nativeElement.click();\n expect(moveUpSpy).to.not.have.been.calledOnce;\n // not moved as first one\n expect(lectureUnitManagementComponent.lectureUnits[0].id).to.equal(originalOrder[0].id);\n const downButton = lectureUnitManagementComponentFixture.debugElement.query(By.css('#down-0'));\n expect(downButton).to.exist;\n downButton.nativeElement.click();\n expect(moveDownSpy).to.have.been.calledOnce;\n expect(lectureUnitManagementComponent.lectureUnits[0].id).to.equal(originalOrder[1].id);\n expect(lectureUnitManagementComponent.lectureUnits[1].id).to.equal(originalOrder[0].id);\n });\n\n it('should move up', () => {\n const originalOrder = [...lecture.lectureUnits!];\n lectureUnitManagementComponentFixture.detectChanges();\n const moveDownSpy = sinon.spy(lectureUnitManagementComponent, 'moveDown');\n const moveUpSpy = sinon.spy(lectureUnitManagementComponent, 'moveUp');\n const lastPosition = lectureUnitManagementComponent.lectureUnits.length - 1;\n const downButton = lectureUnitManagementComponentFixture.debugElement.query(By.css(`#down-${lastPosition}`));\n expect(downButton).to.exist;\n downButton.nativeElement.click();\n expect(moveDownSpy).to.not.have.been.calledOnce;\n\n expect(lectureUnitManagementComponent.lectureUnits[lastPosition].id).to.equal(originalOrder[lastPosition].id);\n const upButton = lectureUnitManagementComponentFixture.debugElement.query(By.css(`#up-${lastPosition}`));\n expect(upButton).to.exist;\n upButton.nativeElement.click();\n expect(moveUpSpy).to.have.been.calledOnce;\n expect(lectureUnitManagementComponent.lectureUnits[lastPosition].id).to.equal(originalOrder[lastPosition - 1].id);\n });\n\n it('should navigate to edit attachment unit page', () => {\n const editButtonClickedSpy = sinon.spy(lectureUnitManagementComponent, 'editButtonRouterLink');\n const buttons = lectureUnitManagementComponentFixture.debugElement.queryAll(By.css(`.edit`));\n for (const button of buttons) {\n button.nativeElement.click();\n }\n lectureUnitManagementComponentFixture.detectChanges();\n expect(editButtonClickedSpy).to.have.been.called;\n });\n\n it('should give the correct delete question translation key', () => {\n expect(lectureUnitManagementComponent.getDeleteQuestionKey(new AttachmentUnit())).to.equal('artemisApp.attachmentUnit.delete.question');\n expect(lectureUnitManagementComponent.getDeleteQuestionKey(new ExerciseUnit())).to.equal('artemisApp.exerciseUnit.delete.question');\n expect(lectureUnitManagementComponent.getDeleteQuestionKey(new TextUnit())).to.equal('artemisApp.textUnit.delete.question');\n expect(lectureUnitManagementComponent.getDeleteQuestionKey(new VideoUnit())).to.equal('artemisApp.videoUnit.delete.question');\n });\n\n it('should give the correct confirmation text translation key', () => {\n expect(lectureUnitManagementComponent.getDeleteConfirmationTextKey(new AttachmentUnit())).to.equal('artemisApp.attachmentUnit.delete.typeNameToConfirm');\n expect(lectureUnitManagementComponent.getDeleteConfirmationTextKey(new ExerciseUnit())).to.equal('artemisApp.exerciseUnit.delete.typeNameToConfirm');\n expect(lectureUnitManagementComponent.getDeleteConfirmationTextKey(new VideoUnit())).to.equal('artemisApp.videoUnit.delete.typeNameToConfirm');\n expect(lectureUnitManagementComponent.getDeleteConfirmationTextKey(new TextUnit())).to.equal('artemisApp.textUnit.delete.typeNameToConfirm');\n });\n\n it('should give the correct action type', () => {\n expect(lectureUnitManagementComponent.getActionType(new AttachmentUnit())).to.equal(ActionType.Delete);\n expect(lectureUnitManagementComponent.getActionType(new ExerciseUnit())).to.equal(ActionType.Unlink);\n expect(lectureUnitManagementComponent.getActionType(new TextUnit())).to.equal(ActionType.Delete);\n expect(lectureUnitManagementComponent.getActionType(new VideoUnit())).to.equal(ActionType.Delete);\n });\n});\n" }, { "alpha_fraction": 0.675662636756897, "alphanum_fraction": 0.6775903701782227, "avg_line_length": 39.686275482177734, "blob_id": "c97278de981d7dcb8c2a4b429e51da44e9f50d29", "content_id": "80fa420a3c75e086855f10907f286b64c7221f9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2075, "license_type": "permissive", "max_line_length": 114, "num_lines": 51, "path": "/src/test/javascript/spec/service/delete-dialog.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule } from '@angular/common/http/testing';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisTestModule } from '../test.module';\nimport { DeleteDialogService } from 'app/shared/delete-dialog/delete-dialog.service';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport * as sinon from 'sinon';\nimport { TranslateModule } from '@ngx-translate/core';\n\nimport { ActionType, DeleteDialogData } from 'app/shared/delete-dialog/delete-dialog.model';\nimport { EventEmitter } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { JhiAlertService } from 'ng-jhipster';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Delete Dialog Service', () => {\n let service: DeleteDialogService;\n let modalService: NgbModal;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, ArtemisSharedModule, HttpClientTestingModule, TranslateModule.forRoot()],\n providers: [DeleteDialogService, JhiAlertService],\n });\n\n service = TestBed.inject(DeleteDialogService);\n modalService = TestBed.inject(NgbModal);\n });\n\n it('should open delete dialog', () => {\n expect(service.modalRef).to.be.undefined;\n const data: DeleteDialogData = {\n dialogError: new Observable<string>(),\n entityTitle: 'title',\n deleteQuestion: 'artemisApp.exercise.delete.question',\n deleteConfirmationText: 'artemisApp.exercise.delete.typeNameToConfirm',\n actionType: ActionType.Delete,\n delete: new EventEmitter<any>(),\n };\n const modalSpy = sinon.spy(modalService, 'open');\n service.openDeleteDialog(data);\n expect(modalSpy.callCount).to.be.equal(1);\n const args = modalSpy.getCall(0).args;\n expect(args[0].name).to.be.equal('DeleteDialogComponent');\n expect(args[1]).to.be.not.null;\n });\n});\n" }, { "alpha_fraction": 0.7969782948493958, "alphanum_fraction": 0.798866868019104, "avg_line_length": 57.83333206176758, "blob_id": "b8b653dceff5bdac63e44e52b292b8dc0c7ea330", "content_id": "13c47aaac5c6dbf7c3a9c527ea7ecfc745770de8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1059, "license_type": "permissive", "max_line_length": 165, "num_lines": 18, "path": "/src/test/java/de/tum/in/www1/artemis/repository/ProgrammingExerciseTestRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.ProgrammingExercise;\n\n@Repository\npublic interface ProgrammingExerciseTestRepository extends JpaRepository<ProgrammingExercise, Long> {\n\n @Query(\"select p from ProgrammingExercise p left join fetch p.studentParticipations left join fetch p.attachments left join fetch p.categories \"\n + \"left join fetch p.templateParticipation left join fetch p.solutionParticipation left join fetch p.exampleSubmissions left join fetch p.exerciseHints \"\n + \"left join fetch p.tutorParticipations left join fetch p.studentQuestions left join fetch p.testCases left join fetch p.staticCodeAnalysisCategories \"\n + \"where p.id = :#{#exerciseId}\")\n ProgrammingExercise findOneWithEagerEverything(@Param(\"exerciseId\") Long exerciseId);\n}\n" }, { "alpha_fraction": 0.7087475061416626, "alphanum_fraction": 0.7147117257118225, "avg_line_length": 34.92856979370117, "blob_id": "fd7c09bfd9776847f61daf2d562f225b8c576aaa", "content_id": "210060cbf29c2cd98d588163a125dfa7b88c9e2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1006, "license_type": "permissive", "max_line_length": 115, "num_lines": 28, "path": "/src/main/webapp/app/course/manage/course-management-exercises.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from './course-management.service';\nimport { ActivatedRoute } from '@angular/router';\n\n@Component({\n selector: 'jhi-course-management-exercises',\n templateUrl: './course-management-exercises.component.html',\n})\nexport class CourseManagementExercisesComponent implements OnInit {\n course: Course;\n courseId = 0;\n quizExercisesCount = 0;\n textExercisesCount = 0;\n programmingExercisesCount = 0;\n modelingExercisesCount = 0;\n fileUploadExercisesCount = 0;\n\n constructor(private courseService: CourseManagementService, private route: ActivatedRoute) {}\n\n /**\n * initializes courseId and course\n */\n ngOnInit(): void {\n this.courseId = Number(this.route.parent!.snapshot.paramMap.get('courseId'));\n this.courseService.find(this.courseId).subscribe((courseResponse) => (this.course = courseResponse.body!));\n }\n}\n" }, { "alpha_fraction": 0.638080894947052, "alphanum_fraction": 0.641089916229248, "avg_line_length": 39.41891860961914, "blob_id": "08bb5b34378b63a1c1ebb16bbb3cc26aa3abae86", "content_id": "506c151af7961d260739e2944bf32adc437beade", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5982, "license_type": "permissive", "max_line_length": 146, "num_lines": 148, "path": "/src/test/javascript/spec/service/apollon-diagram.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { fakeAsync, inject, TestBed, tick } from '@angular/core/testing';\nimport { ApollonDiagramService } from 'app/exercises/quiz/manage/apollon-diagrams/apollon-diagram.service';\nimport { ApollonDiagram } from 'app/entities/apollon-diagram.model';\nimport { UMLDiagramType } from 'app/entities/modeling-exercise.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\nconst resourceUrl = SERVER_API_URL + 'api';\n\ndescribe('ApollonDiagramService', () => {\n let courseId: number;\n let apollonDiagram: ApollonDiagram;\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [HttpClientTestingModule],\n providers: [ApollonDiagramService],\n });\n courseId = 1;\n apollonDiagram = new ApollonDiagram(UMLDiagramType.ClassDiagram, courseId);\n });\n\n it('should be initialized', inject([ApollonDiagramService], (apollonDiagramService: ApollonDiagramService) => {\n expect(apollonDiagramService).to.be.ok;\n }));\n\n it('should create a diagram', fakeAsync(\n inject([ApollonDiagramService, HttpTestingController], (apollonDiagramService: ApollonDiagramService, backend: HttpTestingController) => {\n // Set up\n const url = `${resourceUrl}/course/${courseId}/apollon-diagrams`;\n const responseObject = apollonDiagram;\n\n let response: HttpResponse<ApollonDiagram>;\n\n apollonDiagramService.create(apollonDiagram, courseId).subscribe((receivedResponse: HttpResponse<ApollonDiagram>) => {\n response = receivedResponse;\n });\n\n const requestWrapper = backend.expectOne({ url });\n requestWrapper.flush(responseObject);\n\n tick();\n\n expect(requestWrapper.request.method).to.equal('POST');\n expect(response!.body).to.equal(responseObject);\n expect(response!.status).to.equal(200);\n }),\n ));\n\n it('should update a diagram', fakeAsync(\n inject([ApollonDiagramService, HttpTestingController], (apollonDiagramService: ApollonDiagramService, backend: HttpTestingController) => {\n // Set up\n const url = `${resourceUrl}/course/${courseId}/apollon-diagrams`;\n const responseObject = apollonDiagram;\n\n let response: HttpResponse<ApollonDiagram>;\n\n apollonDiagramService.update(apollonDiagram, courseId).subscribe((receivedResponse: HttpResponse<ApollonDiagram>) => {\n response = receivedResponse;\n });\n\n const requestWrapper = backend.expectOne({ url });\n requestWrapper.flush(responseObject);\n\n tick();\n\n expect(requestWrapper.request.method).to.equal('PUT');\n expect(response!.body).to.equal(responseObject);\n expect(response!.status).to.equal(200);\n }),\n ));\n\n it('should find a diagram', fakeAsync(\n inject([ApollonDiagramService, HttpTestingController], (apollonDiagramService: ApollonDiagramService, backend: HttpTestingController) => {\n // Set up\n const diagramId = 1;\n const url = `${resourceUrl}/course/${courseId}/apollon-diagrams/${diagramId}`;\n const responseObject = apollonDiagram;\n\n let response: HttpResponse<ApollonDiagram>;\n\n apollonDiagramService.find(diagramId, courseId).subscribe((receivedResponse: HttpResponse<ApollonDiagram>) => {\n response = receivedResponse;\n });\n\n const requestWrapper = backend.expectOne({ url });\n requestWrapper.flush(responseObject);\n\n tick();\n\n expect(requestWrapper.request.method).to.equal('GET');\n expect(response!.body).to.equal(responseObject);\n expect(response!.status).to.equal(200);\n }),\n ));\n\n it('should delete a diagram', fakeAsync(\n inject([ApollonDiagramService, HttpTestingController], (apollonDiagramService: ApollonDiagramService, backend: HttpTestingController) => {\n // Set up\n const diagramId = 1;\n const url = `${resourceUrl}/course/${courseId}/apollon-diagrams/${diagramId}`;\n const responseObject = apollonDiagram;\n\n let response: HttpResponse<void>;\n\n apollonDiagramService.delete(diagramId, courseId).subscribe((receivedResponse: HttpResponse<void>) => {\n response = receivedResponse;\n });\n\n const requestWrapper = backend.expectOne({ url });\n requestWrapper.flush(responseObject);\n\n tick();\n\n expect(requestWrapper.request.method).to.equal('DELETE');\n expect(response!.body).to.equal(responseObject);\n expect(response!.status).to.equal(200);\n }),\n ));\n\n it('should get diagrams by course', fakeAsync(\n inject([ApollonDiagramService, HttpTestingController], (apollonDiagramService: ApollonDiagramService, backend: HttpTestingController) => {\n // Set up\n const url = `${resourceUrl}/course/${courseId}/apollon-diagrams`;\n const responseObject = [apollonDiagram];\n\n let response: HttpResponse<ApollonDiagram[]>;\n\n apollonDiagramService.getDiagramsByCourse(courseId).subscribe((receivedResponse: HttpResponse<ApollonDiagram[]>) => {\n response = receivedResponse;\n });\n\n const requestWrapper = backend.expectOne({ url });\n requestWrapper.flush(responseObject);\n\n tick();\n\n expect(requestWrapper.request.method).to.equal('GET');\n expect(response!.body).to.equal(responseObject);\n expect(response!.status).to.equal(200);\n }),\n ));\n});\n" }, { "alpha_fraction": 0.7294673323631287, "alphanum_fraction": 0.7313041090965271, "avg_line_length": 42.306819915771484, "blob_id": "3385dc9dfb0e8e2801f09f30977b9732863f130d", "content_id": "eb2cc815db4af93ecd1c5a5d4a2496e2edfbcd4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 3811, "license_type": "permissive", "max_line_length": 124, "num_lines": 88, "path": "/src/main/java/de/tum/in/www1/artemis/service/scheduled/ScheduleService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.scheduled;\n\nimport java.time.ZonedDateTime;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ScheduledFuture;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.stereotype.Service;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseLifecycle;\nimport de.tum.in.www1.artemis.service.ExerciseLifecycleService;\nimport de.tum.in.www1.artemis.service.util.Tuple;\n\n@Service\npublic class ScheduleService {\n\n private final Logger log = LoggerFactory.getLogger(ScheduleService.class);\n\n private final ExerciseLifecycleService exerciseLifecycleService;\n\n private final Map<Tuple<Long, ExerciseLifecycle>, Set<ScheduledFuture<?>>> scheduledTasks = new HashMap<>();\n\n public ScheduleService(ExerciseLifecycleService exerciseLifecycleService) {\n this.exerciseLifecycleService = exerciseLifecycleService;\n }\n\n private void addScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle, Set<ScheduledFuture<?>> futures) {\n Tuple<Long, ExerciseLifecycle> taskId = new Tuple<>(exercise.getId(), lifecycle);\n scheduledTasks.put(taskId, futures);\n }\n\n private void removeScheduledTask(Exercise exercise, ExerciseLifecycle lifecycle) {\n removeScheduledTask(exercise.getId(), lifecycle);\n }\n\n private void removeScheduledTask(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple<Long, ExerciseLifecycle> taskId = new Tuple<>(exerciseId, lifecycle);\n scheduledTasks.remove(taskId);\n }\n\n /**\n * Schedule a task for the given Exercise for the provided ExerciseLifecycle.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param task Runnable task to be executed on the lifecycle hook\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Runnable task) {\n // check if already scheduled for exercise. if so, cancel.\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n ScheduledFuture<?> scheduledTask = exerciseLifecycleService.scheduleTask(exercise, lifecycle, task);\n addScheduledTask(exercise, lifecycle, Set.of(scheduledTask));\n }\n\n /**\n * Schedule a set of tasks for the given Exercise for the provided ExerciseLifecycle at the given times.\n *\n * @param exercise Exercise\n * @param lifecycle ExerciseLifecycle\n * @param tasks Runnable tasks to be executed at the associated ZonedDateTimes\n */\n void scheduleTask(Exercise exercise, ExerciseLifecycle lifecycle, Set<Tuple<ZonedDateTime, Runnable>> tasks) {\n // check if already scheduled for exercise. if so, cancel.\n // no exercise should be scheduled more than once.\n cancelScheduledTaskForLifecycle(exercise.getId(), lifecycle);\n Set<ScheduledFuture<?>> scheduledTasks = exerciseLifecycleService.scheduleMultipleTasks(exercise, lifecycle, tasks);\n addScheduledTask(exercise, lifecycle, scheduledTasks);\n }\n\n /**\n * Cancel possible schedules tasks for a provided exercise.\n * @param exerciseId if of the exercise for which a potential scheduled task is canceled\n */\n void cancelScheduledTaskForLifecycle(Long exerciseId, ExerciseLifecycle lifecycle) {\n Tuple<Long, ExerciseLifecycle> taskId = new Tuple<>(exerciseId, lifecycle);\n Set<ScheduledFuture<?>> futures = scheduledTasks.get(taskId);\n if (futures != null) {\n log.debug(\"Cancelling scheduled task {} for Exercise (#{}).\", lifecycle, exerciseId);\n futures.forEach(future -> future.cancel(false));\n removeScheduledTask(exerciseId, lifecycle);\n }\n }\n}\n" }, { "alpha_fraction": 0.8185185194015503, "alphanum_fraction": 0.8222222328186035, "avg_line_length": 32.75, "blob_id": "d5e5a65f19dfc1650e8fd83899631706d7b5b7a2", "content_id": "faec6eaadd9e034f36823b96702fa05c8d729843", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 540, "license_type": "permissive", "max_line_length": 89, "num_lines": 16, "path": "/src/test/java/de/tum/in/www1/artemis/repository/ParticipationTestRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.List;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.participation.Participation;\n\n@Repository\npublic interface ParticipationTestRepository extends JpaRepository<Participation, Long> {\n\n @Query(\"select distinct p from Participation p left join fetch p.submissions\")\n List<Participation> findAllWithSubmissions();\n}\n" }, { "alpha_fraction": 0.7351535558700562, "alphanum_fraction": 0.7535836100578308, "avg_line_length": 44.78125, "blob_id": "234a6b90aebdb5e6f1cc43c264cb117de0e9ab1b", "content_id": "b998538ef96c721d319736bec1aa825a152f0f5b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 164, "num_lines": 32, "path": "/docs/dev/testservers.rst", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": ".. _testservers:\n\nTest Servers\n============\n\nTest Server 1-3\n---------------\n\nDeployment via Bamboo. Only for branches of the ``ls1intum/Artemis`` repository, no forks.\nGuide available in the Artemis Developer Confluence Space: `Deploying changes to test server`_.\n\n.. _`Deploying changes to test server`: https://confluence.ase.in.tum.de/display/ArTEMiS/Deploying+changes+to+test+server\n\nTest Server 5\n-------------\n\n\nPull requests on GitHub can be deployed to TS5_, including forks.\nTo invoke a deployment, you need to be part of the `ls1intum` GitHub organization.\n\nStart the deployment using the `Test Server Deployment Workflow`_.\n(Refer to the `GitHub documentation \"Manually running a workflow\"`_.)\nSupply the pull request number to initiate the deployment (e.g. ``42`` for PR #42).\nTS5 is locked to a pull request using the `lock:artemistest5`_ label.\nThe workflow applies the lock label automatically on deployment.\nRemove the label from the PR once the test server is free to use by other developers.\n\n\n.. _TS5: https://artemistest5.ase.in.tum.de\n.. _`Test Server Deployment Workflow`: https://github.com/ls1intum/Artemis/actions?query=workflow%3A%22Testserver+Deployment%22\n.. _`GitHub documentation \"Manually running a workflow\"`: https://docs.github.com/en/free-pro-team@latest/actions/managing-workflow-runs/manually-running-a-workflow\n.. _`lock:artemistest5`: https://github.com/ls1intum/Artemis/pulls?q=is%3Aopen+is%3Apr+label%3Alock%3Aartemistest5\n" }, { "alpha_fraction": 0.6614118218421936, "alphanum_fraction": 0.6624627709388733, "avg_line_length": 39.48936080932617, "blob_id": "822b220578eeb66960b8bee7f86319530bef8a4a", "content_id": "f126fcbd708c364046465dea288577013b64813e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5709, "license_type": "permissive", "max_line_length": 146, "num_lines": 141, "path": "/src/main/webapp/app/exam/manage/exams/exam-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Exam } from 'app/entities/exam.model';\nimport { ExamManagementService } from 'app/exam/manage/exam-management.service';\nimport { Observable } from 'rxjs';\nimport { HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { Course } from 'app/entities/course.model';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport * as moment from 'moment';\nimport { navigateBack } from 'app/utils/navigation.utils';\n\n@Component({\n selector: 'jhi-exam-update',\n templateUrl: './exam-update.component.html',\n})\nexport class ExamUpdateComponent implements OnInit {\n exam: Exam;\n course: Course;\n isSaving: boolean;\n\n constructor(\n private route: ActivatedRoute,\n private examManagementService: ExamManagementService,\n private jhiAlertService: JhiAlertService,\n private courseManagementService: CourseManagementService,\n private router: Router,\n ) {}\n\n ngOnInit(): void {\n this.route.data.subscribe(({ exam }) => {\n this.exam = exam;\n this.courseManagementService.find(Number(this.route.snapshot.paramMap.get('courseId'))).subscribe(\n (response: HttpResponse<Course>) => {\n this.exam.course = response.body!;\n this.course = response.body!;\n },\n (err: HttpErrorResponse) => this.onError(err),\n );\n if (!this.exam.gracePeriod) {\n this.exam.gracePeriod = 180;\n }\n if (!this.exam.numberOfCorrectionRoundsInExam) {\n this.exam.numberOfCorrectionRoundsInExam = 1;\n }\n });\n }\n\n /**\n * Revert to the previous state, equivalent with pressing the back button on your browser\n * Returns to the detail page if there is no previous state and we edited an existing exam\n * Returns to the overview page if there is no previous state and we created a new exam\n */\n previousState() {\n if (this.exam.id) {\n navigateBack(this.router, ['course-management', this.course.id!.toString(), 'exams', this.exam.id!.toString()]);\n } else {\n navigateBack(this.router, ['course-management', this.course.id!.toString(), 'exams']);\n }\n }\n\n save() {\n this.isSaving = true;\n if (this.exam.id !== undefined) {\n this.subscribeToSaveResponse(this.examManagementService.update(this.course.id!, this.exam));\n } else {\n this.subscribeToSaveResponse(this.examManagementService.create(this.course.id!, this.exam));\n }\n }\n\n subscribeToSaveResponse(result: Observable<HttpResponse<Exam>>) {\n result.subscribe(\n () => this.onSaveSuccess(),\n (err: HttpErrorResponse) => this.onSaveError(err),\n );\n }\n\n private onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n private onSaveError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n this.isSaving = false;\n }\n\n private onError(error: HttpErrorResponse) {\n this.jhiAlertService.error(error.message);\n }\n\n get isValidConfiguration(): boolean {\n const examConductionDatesValid = this.isValidVisibleDate && this.isValidStartDate && this.isValidEndDate;\n const examReviewDatesValid = this.isValidPublishResultsDate && this.isValidExamStudentReviewStart && this.isValidExamStudentReviewEnd;\n const examNumberOfCorrectionsValid = this.isValidNumberOfCorrectionRounds;\n return examConductionDatesValid && examReviewDatesValid && examNumberOfCorrectionsValid;\n }\n\n get isValidVisibleDate(): boolean {\n return this.exam.visibleDate !== undefined;\n }\n\n get isValidNumberOfCorrectionRounds(): boolean {\n return this.exam?.numberOfCorrectionRoundsInExam! < 3 && this.exam?.numberOfCorrectionRoundsInExam! > 0;\n }\n\n get isValidStartDate(): boolean {\n return this.exam.startDate !== undefined && moment(this.exam.startDate).isAfter(this.exam.visibleDate);\n }\n\n get isValidEndDate(): boolean {\n return this.exam.endDate !== undefined && moment(this.exam.endDate).isAfter(this.exam.startDate);\n }\n\n get isValidPublishResultsDate(): boolean {\n // allow instructors to set publishResultsDate later\n if (!this.exam.publishResultsDate) {\n return true;\n }\n // check for undefined because undefined is otherwise treated as the now moment by moment.js\n return this.exam.endDate !== undefined && moment(this.exam.publishResultsDate).isAfter(this.exam.endDate);\n }\n\n get isValidExamStudentReviewStart(): boolean {\n // allow instructors to set examStudentReviewStart later\n if (!this.exam.examStudentReviewStart) {\n return true;\n }\n // check for undefined because undefined is otherwise treated as the now moment by moment.js\n return this.exam.publishResultsDate !== undefined && moment(this.exam.examStudentReviewStart).isAfter(this.exam.publishResultsDate);\n }\n\n get isValidExamStudentReviewEnd(): boolean {\n // allow instructors to set examStudentReviewEnd later\n if (!this.exam.examStudentReviewEnd) {\n return true;\n }\n // check for undefined because undefined is otherwise treated as the now moment by moment.js\n return this.exam.examStudentReviewStart !== undefined && moment(this.exam.examStudentReviewEnd).isAfter(this.exam.examStudentReviewStart);\n }\n}\n" }, { "alpha_fraction": 0.5829787254333496, "alphanum_fraction": 0.5829787254333496, "avg_line_length": 31.63888931274414, "blob_id": "8286af9a5db317a119272994628655f7de96630f", "content_id": "9ae4e43e5a70fe505e23356d0472dfd4ac158fd8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1175, "license_type": "permissive", "max_line_length": 105, "num_lines": 36, "path": "/src/main/webapp/app/course/learning-goals/learning-goals-popover/learning-goals-popover.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\n\n@Component({\n selector: 'jhi-learning-goals-popover',\n templateUrl: './learning-goals-popover.component.html',\n styleUrls: ['./learning-goals-popover.component.scss'],\n encapsulation: ViewEncapsulation.None,\n})\nexport class LearningGoalsPopoverComponent implements OnInit {\n @Input()\n courseId: number;\n @Input()\n learningGoals: LearningGoal[] = [];\n @Input()\n navigateTo: 'learningGoalManagement' | 'courseStatistics' = 'courseStatistics';\n\n navigationArray: string[] = [];\n\n constructor() {}\n\n ngOnInit(): void {\n if (this.courseId) {\n switch (this.navigateTo) {\n case 'courseStatistics': {\n this.navigationArray = ['/courses', `${this.courseId}`, 'statistics'];\n break;\n }\n case 'learningGoalManagement': {\n this.navigationArray = ['/course-management', `${this.courseId}`, 'goal-management'];\n break;\n }\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.7028226256370544, "alphanum_fraction": 0.7067669034004211, "avg_line_length": 48.469512939453125, "blob_id": "822caa4542dc816cff62cac943a6b505c4be1c94", "content_id": "aac51696ada753bc5d246cbfc0f47aa2826fe2a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 8113, "license_type": "permissive", "max_line_length": 159, "num_lines": 164, "path": "/src/test/javascript/spec/component/lecture-unit/video-unit/video-unit-form.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { VideoUnitFormComponent, VideoUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/video-unit-form/video-unit-form.component';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { FormsModule, ReactiveFormsModule } from '@angular/forms';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockComponent, MockPipe } from 'ng-mocks';\nimport { FormDateTimePickerComponent } from 'app/shared/date-time-picker/date-time-picker.component';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\ndescribe('VideoUnitFormComponent', () => {\n const sandbox = sinon.createSandbox();\n const validYouTubeUrl = 'https://www.youtube.com/watch?v=8iU8LPEa4o0';\n const validYouTubeUrlInEmbeddableFormat = 'https://www.youtube.com/embed/8iU8LPEa4o0';\n let videoUnitFormComponentFixture: ComponentFixture<VideoUnitFormComponent>;\n let videoUnitFormComponent: VideoUnitFormComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ReactiveFormsModule, FormsModule],\n declarations: [VideoUnitFormComponent, MockPipe(ArtemisTranslatePipe), MockComponent(FormDateTimePickerComponent), MockComponent(FaIconComponent)],\n providers: [],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n videoUnitFormComponentFixture = TestBed.createComponent(VideoUnitFormComponent);\n videoUnitFormComponent = videoUnitFormComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n videoUnitFormComponentFixture.detectChanges();\n expect(videoUnitFormComponent).to.be.ok;\n });\n\n it('should not submit a form when name is missing', () => {\n sandbox.stub(videoUnitFormComponent, 'urlValidator').returns(null);\n sandbox.stub(videoUnitFormComponent, 'videoUrlValidator').returns(null);\n videoUnitFormComponentFixture.detectChanges();\n const exampleDescription = 'lorem ipsum';\n videoUnitFormComponent.descriptionControl!.setValue(exampleDescription);\n const exampleReleaseDate = moment({ years: 2010, months: 3, date: 5 });\n videoUnitFormComponent.releaseDateControl!.setValue(exampleReleaseDate);\n videoUnitFormComponent.sourceControl!.setValue(validYouTubeUrlInEmbeddableFormat);\n videoUnitFormComponentFixture.detectChanges();\n expect(videoUnitFormComponent.form.invalid).to.be.true;\n\n const submitFormSpy = sinon.spy(videoUnitFormComponent, 'submitForm');\n const submitFormEventSpy = sinon.spy(videoUnitFormComponent.formSubmitted, 'emit');\n\n const submitButton = videoUnitFormComponentFixture.debugElement.nativeElement.querySelector('#submitButton');\n submitButton.click();\n\n videoUnitFormComponentFixture.whenStable().then(() => {\n expect(submitFormSpy).to.not.have.been.called;\n expect(submitFormEventSpy).to.not.have.been.called;\n });\n });\n\n it('should not submit a form when source is missing', () => {\n sandbox.stub(videoUnitFormComponent, 'urlValidator').returns(null);\n sandbox.stub(videoUnitFormComponent, 'videoUrlValidator').returns(null);\n videoUnitFormComponentFixture.detectChanges();\n const exampleName = 'test';\n videoUnitFormComponent.nameControl!.setValue(exampleName);\n const exampleDescription = 'lorem ipsum';\n videoUnitFormComponent.descriptionControl!.setValue(exampleDescription);\n const exampleReleaseDate = moment({ years: 2010, months: 3, date: 5 });\n videoUnitFormComponent.releaseDateControl!.setValue(exampleReleaseDate);\n videoUnitFormComponentFixture.detectChanges();\n expect(videoUnitFormComponent.form.invalid).to.be.true;\n\n const submitFormSpy = sinon.spy(videoUnitFormComponent, 'submitForm');\n const submitFormEventSpy = sinon.spy(videoUnitFormComponent.formSubmitted, 'emit');\n\n const submitButton = videoUnitFormComponentFixture.debugElement.nativeElement.querySelector('#submitButton');\n submitButton.click();\n\n videoUnitFormComponentFixture.whenStable().then(() => {\n expect(submitFormSpy).to.not.have.been.called;\n expect(submitFormEventSpy).to.not.have.been.called;\n });\n });\n\n it('should submit valid form', () => {\n sandbox.stub(videoUnitFormComponent, 'urlValidator').returns(null);\n sandbox.stub(videoUnitFormComponent, 'videoUrlValidator').returns(null);\n videoUnitFormComponentFixture.detectChanges();\n const exampleName = 'test';\n videoUnitFormComponent.nameControl!.setValue(exampleName);\n const exampleDescription = 'lorem ipsum';\n videoUnitFormComponent.descriptionControl!.setValue(exampleDescription);\n const exampleReleaseDate = moment({ years: 2010, months: 3, date: 5 });\n videoUnitFormComponent.releaseDateControl!.setValue(exampleReleaseDate);\n videoUnitFormComponent.sourceControl!.setValue(validYouTubeUrlInEmbeddableFormat);\n videoUnitFormComponentFixture.detectChanges();\n expect(videoUnitFormComponent.form.valid).to.be.true;\n\n const submitFormSpy = sinon.spy(videoUnitFormComponent, 'submitForm');\n const submitFormEventSpy = sinon.spy(videoUnitFormComponent.formSubmitted, 'emit');\n\n const submitButton = videoUnitFormComponentFixture.debugElement.nativeElement.querySelector('#submitButton');\n submitButton.click();\n\n videoUnitFormComponentFixture.whenStable().then(() => {\n expect(submitFormSpy).to.have.been.called;\n expect(submitFormEventSpy).to.have.been.calledWith({\n name: exampleName,\n description: exampleDescription,\n releaseDate: exampleReleaseDate,\n source: validYouTubeUrlInEmbeddableFormat,\n urlHelper: null,\n });\n\n submitFormSpy.restore();\n submitFormEventSpy.restore();\n });\n });\n\n it('should correctly transform YouTube URL into embeddable format', () => {\n sandbox.stub(videoUnitFormComponent, 'extractEmbeddedUrl').returns(validYouTubeUrlInEmbeddableFormat);\n sandbox.stub(videoUnitFormComponent, 'urlValidator').returns(null);\n sandbox.stub(videoUnitFormComponent, 'videoUrlValidator').returns(null);\n\n videoUnitFormComponentFixture.detectChanges();\n\n videoUnitFormComponent.urlHelperControl!.setValue(validYouTubeUrl);\n videoUnitFormComponentFixture.detectChanges();\n const transformButton = videoUnitFormComponentFixture.debugElement.nativeElement.querySelector('#transformButton');\n transformButton.click();\n\n videoUnitFormComponentFixture.whenStable().then(() => {\n expect(videoUnitFormComponent.sourceControl?.value).to.equal(validYouTubeUrlInEmbeddableFormat);\n });\n });\n\n it('should correctly set form values in edit mode', () => {\n videoUnitFormComponent.isEditMode = true;\n const formData: VideoUnitFormData = {\n name: 'test',\n description: 'lorem ipsum',\n releaseDate: moment({ years: 2010, months: 3, date: 5 }),\n source: validYouTubeUrlInEmbeddableFormat,\n };\n videoUnitFormComponentFixture.detectChanges();\n\n videoUnitFormComponent.formData = formData;\n videoUnitFormComponent.ngOnChanges();\n\n expect(videoUnitFormComponent.nameControl?.value).to.equal(formData.name);\n expect(videoUnitFormComponent.releaseDateControl?.value).to.equal(formData.releaseDate);\n expect(videoUnitFormComponent.descriptionControl?.value).to.equal(formData.description);\n expect(videoUnitFormComponent.sourceControl?.value).to.equal(formData.source);\n });\n});\n" }, { "alpha_fraction": 0.599071204662323, "alphanum_fraction": 0.6015222072601318, "avg_line_length": 45.698795318603516, "blob_id": "9ae339898482e742486b98aba42548f3df764610", "content_id": "a1cc477ce8665991fef780cc5c0f74026e3eff75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7752, "license_type": "permissive", "max_line_length": 153, "num_lines": 166, "path": "/src/test/javascript/spec/component/lecture-unit/attachment-unit/create-attachment-unit.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport * as moment from 'moment';\nimport { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';\nimport { MockProvider } from 'ng-mocks';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { MockRouter } from '../../../helpers/mocks/mock-router';\nimport { Observable, of } from 'rxjs';\nimport { AttachmentUnitFormData } from 'app/lecture/lecture-unit/lecture-unit-management/attachment-unit-form/attachment-unit-form.component';\nimport { CreateAttachmentUnitComponent } from 'app/lecture/lecture-unit/lecture-unit-management/create-attachment-unit/create-attachment-unit.component';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { AttachmentUnitService } from 'app/lecture/lecture-unit/lecture-unit-management/attachmentUnit.service';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { HttpResponse } from '@angular/common/http';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { By } from '@angular/platform-browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-attachment-unit-form', template: '' })\nclass AttachmentUnitFormStubComponent {\n @Input() isEditMode = false;\n @Output() formSubmitted: EventEmitter<AttachmentUnitFormData> = new EventEmitter<AttachmentUnitFormData>();\n}\n\n@Component({ selector: 'jhi-lecture-unit-layout', template: '<ng-content></ng-content>' })\nclass LectureUnitLayoutStubComponent {\n @Input()\n isLoading = false;\n}\n\ndescribe('CreateAttachmentUnitComponent', () => {\n let createAttachmentUnitComponentFixture: ComponentFixture<CreateAttachmentUnitComponent>;\n let createAttachmentUnitComponent: CreateAttachmentUnitComponent;\n const sandbox = sinon.createSandbox();\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [AttachmentUnitFormStubComponent, LectureUnitLayoutStubComponent, CreateAttachmentUnitComponent],\n providers: [\n MockProvider(AttachmentService),\n MockProvider(AttachmentUnitService),\n MockProvider(FileUploaderService),\n MockProvider(JhiAlertService),\n { provide: Router, useClass: MockRouter },\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'lectureId':\n return 1;\n }\n },\n }),\n parent: {\n paramMap: Observable.of({\n get: (key: string) => {\n switch (key) {\n case 'courseId':\n return 1;\n }\n },\n }),\n },\n },\n },\n },\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n createAttachmentUnitComponentFixture = TestBed.createComponent(CreateAttachmentUnitComponent);\n createAttachmentUnitComponent = createAttachmentUnitComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('should initialize', () => {\n createAttachmentUnitComponentFixture.detectChanges();\n expect(createAttachmentUnitComponent).to.be.ok;\n });\n\n it('should upload file, send POST for attachment and post for attachment unit', fakeAsync(() => {\n const router: Router = TestBed.inject(Router);\n const fileUploadService = TestBed.inject(FileUploaderService);\n const attachmentService = TestBed.inject(AttachmentService);\n const attachmentUnitService = TestBed.inject(AttachmentUnitService);\n\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n\n const formData: AttachmentUnitFormData = {\n formProperties: {\n name: 'test',\n description: 'lorem ipsum',\n releaseDate: moment({ years: 2010, months: 3, date: 5 }),\n version: 2,\n updateNotificationText: 'lorem ipsum',\n },\n fileProperties: {\n file: fakeBlob,\n fileName: 'lorem ipsum',\n },\n };\n\n const examplePath = '/path/to/file';\n const uploadFileStub = sandbox.stub(fileUploadService, 'uploadFile').resolves({ path: examplePath });\n\n const attachmentUnit = new AttachmentUnit();\n attachmentUnit.description = formData.formProperties.description;\n\n const attachmentUnitResponse: HttpResponse<AttachmentUnit> = new HttpResponse({\n body: attachmentUnit,\n status: 201,\n });\n const createAttachmentUnitStub = sandbox.stub(attachmentUnitService, 'create').returns(of(attachmentUnitResponse));\n\n const attachment = new Attachment();\n attachment.version = 1;\n attachment.attachmentType = AttachmentType.FILE;\n attachment.releaseDate = formData.formProperties.releaseDate;\n attachment.name = formData.formProperties.name;\n attachment.link = examplePath;\n\n const attachmentResponse: HttpResponse<Attachment> = new HttpResponse({\n body: attachment,\n status: 201,\n });\n const createAttachmentStub = sandbox.stub(attachmentService, 'create').returns(of(attachmentResponse));\n const navigateSpy = sinon.spy(router, 'navigate');\n createAttachmentUnitComponentFixture.detectChanges();\n\n const attachmentUnitFormStubComponent: AttachmentUnitFormStubComponent = createAttachmentUnitComponentFixture.debugElement.query(\n By.directive(AttachmentUnitFormStubComponent),\n ).componentInstance;\n attachmentUnitFormStubComponent.formSubmitted.emit(formData);\n\n createAttachmentUnitComponentFixture.whenStable().then(() => {\n expect(uploadFileStub).to.have.been.calledWith(formData.fileProperties.file, formData.fileProperties.fileName, { keepFileName: true });\n expect(createAttachmentUnitStub).to.have.been.calledWith(attachmentUnit, 1);\n const attachmentArgument: Attachment = createAttachmentStub.getCall(0).args[0];\n expect(attachmentArgument.name).to.equal(attachment.name);\n expect(attachmentArgument.releaseDate).to.equal(attachment.releaseDate);\n expect(attachmentArgument.version).to.equal(attachment.version);\n expect(attachmentArgument.link).to.equal(attachment.link);\n expect(attachmentArgument.attachmentUnit).to.deep.equal(attachmentUnit);\n expect(navigateSpy).to.have.been.calledOnce;\n navigateSpy.restore();\n });\n }));\n});\n" }, { "alpha_fraction": 0.68597811460495, "alphanum_fraction": 0.6907305121421814, "avg_line_length": 53.96019744873047, "blob_id": "a92ed28c14765af6aa899d04e37f105c080d518e", "content_id": "6aca743aea087b0595fd74846fa416688c7681d1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 22094, "license_type": "permissive", "max_line_length": 188, "num_lines": 402, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { By } from '@angular/platform-browser';\nimport { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap';\nimport { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing';\nimport { DebugElement } from '@angular/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as moment from 'moment';\nimport { SinonStub, spy, stub } from 'sinon';\nimport { Observable, of, Subject, Subscription, throwError } from 'rxjs';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { MockResultService } from '../../helpers/mocks/service/mock-result.service';\nimport { MockRepositoryFileService } from '../../helpers/mocks/service/mock-repository-file.service';\nimport { problemStatement, problemStatementBubbleSortFailsHtml, problemStatementBubbleSortNotExecutedHtml } from '../../helpers/sample/problemStatement.json';\nimport { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service';\nimport { ProgrammingExerciseInstructionStepWizardComponent } from 'app/exercises/programming/shared/instructions-render/step-wizard/programming-exercise-instruction-step-wizard.component';\nimport { ProgrammingExerciseInstructionService } from 'app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service';\nimport { ProgrammingExerciseTaskExtensionWrapper } from 'app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension';\nimport { ProgrammingExercisePlantUmlExtensionWrapper } from 'app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension';\nimport { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service';\nimport { ExerciseHint } from 'app/entities/exercise-hint.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { LocalStorageService } from 'ngx-webstorage';\nimport { Participation } from 'app/entities/participation/participation.model';\nimport { ExerciseHintService, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ResultService } from 'app/exercises/shared/result/result.service';\nimport { RepositoryFileService } from 'app/exercises/shared/result/repository.service';\nimport { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service';\n// eslint-disable-next-line @typescript-eslint/tslint/config\nimport { ProgrammingExerciseInstructionTaskStatusComponent } from 'app/exercises/programming/shared/instructions-render/task/programming-exercise-instruction-task-status.component';\nimport { Result } from 'app/entities/result.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { ProgrammingExerciseInstructionComponent } from 'app/exercises/programming/shared/instructions-render/programming-exercise-instruction.component';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\nimport { ResultDetailComponent } from 'app/exercises/shared/result/result-detail.component';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport { TranslatePipeMock } from '../../helpers/mocks/service/mock-translate.service';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseInstructionComponent', () => {\n let comp: ProgrammingExerciseInstructionComponent;\n let fixture: ComponentFixture<ProgrammingExerciseInstructionComponent>;\n let debugElement: DebugElement;\n let participationWebsocketService: ParticipationWebsocketService;\n let repositoryFileService: RepositoryFileService;\n let programmingExerciseParticipationService: ProgrammingExerciseParticipationService;\n let exerciseHintService: IExerciseHintService;\n let modalService: NgbModal;\n\n let subscribeForLatestResultOfParticipationStub: SinonStub;\n let getFileStub: SinonStub;\n let openModalStub: SinonStub;\n let getLatestResultWithFeedbacks: SinonStub;\n let getHintsForExerciseStub: SinonStub;\n\n const exerciseHints = [{ id: 1 }, { id: 2 }];\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisSharedModule, NgbModule],\n declarations: [\n ProgrammingExerciseInstructionComponent,\n ProgrammingExerciseInstructionStepWizardComponent,\n ProgrammingExerciseInstructionTaskStatusComponent,\n TranslatePipeMock,\n ],\n providers: [\n ProgrammingExerciseTaskExtensionWrapper,\n ProgrammingExercisePlantUmlExtensionWrapper,\n ProgrammingExerciseInstructionService,\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: ResultService, useClass: MockResultService },\n { provide: ProgrammingExerciseParticipationService, useClass: MockProgrammingExerciseParticipationService },\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: RepositoryFileService, useClass: MockRepositoryFileService },\n { provide: NgbModal, useClass: MockNgbModalService },\n { provide: ExerciseHintService, useClass: MockExerciseHintService },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .overrideModule(BrowserDynamicTestingModule, { set: { entryComponents: [FaIconComponent, ProgrammingExerciseInstructionTaskStatusComponent] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseInstructionComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n participationWebsocketService = debugElement.injector.get(ParticipationWebsocketService);\n programmingExerciseParticipationService = debugElement.injector.get(ProgrammingExerciseParticipationService);\n repositoryFileService = debugElement.injector.get(RepositoryFileService);\n exerciseHintService = debugElement.injector.get(ExerciseHintService);\n modalService = debugElement.injector.get(NgbModal);\n\n subscribeForLatestResultOfParticipationStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation');\n openModalStub = stub(modalService, 'open');\n getFileStub = stub(repositoryFileService, 'get');\n getLatestResultWithFeedbacks = stub(programmingExerciseParticipationService, 'getLatestResultWithFeedback');\n getHintsForExerciseStub = stub(exerciseHintService, 'findByExerciseId').returns(of({ body: exerciseHints }) as Observable<HttpResponse<ExerciseHint[]>>);\n\n comp.personalParticipation = true;\n });\n });\n\n afterEach(() => {\n subscribeForLatestResultOfParticipationStub.restore();\n openModalStub.restore();\n getFileStub.restore();\n getLatestResultWithFeedbacks.restore();\n });\n\n it('should on participation change clear old subscription for participation results set up new one', () => {\n const exercise = { id: 1 };\n const oldParticipation = { id: 1 } as Participation;\n const result = { id: 1 };\n const participation = { id: 2, results: [result] } as Participation;\n const oldSubscription = new Subscription();\n subscribeForLatestResultOfParticipationStub.returns(of());\n comp.exercise = exercise as ProgrammingExercise;\n comp.participation = participation;\n comp.participationSubscription = oldSubscription;\n\n triggerChanges(comp, { property: 'participation', currentValue: participation, previousValue: oldParticipation, firstChange: false });\n fixture.detectChanges();\n\n expect(subscribeForLatestResultOfParticipationStub).to.have.been.calledOnceWithExactly(participation.id, true, exercise.id);\n expect(comp.participationSubscription).not.to.equal(oldSubscription);\n expect(comp.isInitial).to.be.true;\n expect(getHintsForExerciseStub).to.have.been.calledOnceWithExactly(exercise.id);\n expect(comp.exerciseHints).to.deep.equal(exerciseHints);\n });\n\n it('should try to fetch README.md from assignment repository if no problemStatement was provided', () => {\n const result = { id: 1, feedbacks: [] as Feedback[] } as Result;\n const participation = { id: 2 } as Participation;\n const exercise = { id: 3, course: { id: 4 } } as ProgrammingExercise;\n const getFileSubject = new Subject<{ fileContent: string; fileName: string }>();\n const loadInitialResultStub = stub(comp, 'loadInitialResult').returns(of(result));\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n getFileStub.returns(getFileSubject);\n comp.participation = participation;\n comp.exercise = exercise;\n comp.isInitial = true;\n comp.isLoading = false;\n\n fixture.detectChanges();\n triggerChanges(comp);\n fixture.detectChanges();\n expect(comp.isLoading).to.be.true;\n expect(debugElement.query(By.css('#programming-exercise-instructions-loading'))).to.exist;\n expect(debugElement.query(By.css('#programming-exercise-instructions-content'))).not.to.exist;\n expect(getFileStub).to.have.been.calledOnceWithExactly(participation.id, 'README.md');\n\n getFileSubject.next({ fileContent: 'lorem ipsum', fileName: 'README.md' });\n expect(comp.problemStatement).to.equal('lorem ipsum');\n expect(loadInitialResultStub).to.have.been.calledOnceWithExactly();\n expect(comp.latestResult).to.deep.equal(result);\n expect(updateMarkdownStub).to.have.been.calledOnceWithExactly();\n expect(comp.isInitial).to.be.false;\n expect(comp.isLoading).to.be.false;\n fixture.detectChanges();\n expect(debugElement.query(By.css('#programming-exercise-instructions-loading'))).not.to.exist;\n expect(debugElement.query(By.css('#programming-exercise-instructions-content'))).to.exist;\n });\n\n it('should NOT try to fetch README.md from assignment repository if a problemStatement was provided', () => {\n const result = { id: 1, feedbacks: [] as Feedback[] } as Result;\n const participation = { id: 2 } as Participation;\n const problemstatement = 'lorem ipsum';\n const exercise = { id: 3, course: { id: 4 }, problemStatement: problemstatement } as ProgrammingExercise;\n const loadInitialResultStub = stub(comp, 'loadInitialResult').returns(of(result));\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n comp.participation = participation;\n comp.exercise = exercise;\n comp.isInitial = true;\n comp.isLoading = false;\n\n fixture.detectChanges();\n triggerChanges(comp);\n\n expect(getFileStub).to.not.have.been.called;\n expect(comp.problemStatement).to.equal('lorem ipsum');\n expect(loadInitialResultStub).to.have.been.calledOnceWithExactly();\n expect(comp.latestResult).to.deep.equal(result);\n expect(updateMarkdownStub).to.have.been.calledOnceWithExactly();\n expect(comp.isInitial).to.be.false;\n expect(comp.isLoading).to.be.false;\n fixture.detectChanges();\n expect(debugElement.query(By.css('#programming-exercise-instructions-loading'))).not.to.exist;\n expect(debugElement.query(By.css('#programming-exercise-instructions-content'))).to.exist;\n });\n\n it('should emit that no instructions are available if there is neither a problemStatement provided nor a README.md can be retrieved', () => {\n const result = { id: 1, feedbacks: [] as Feedback[] } as Result;\n const participation = { id: 2 } as Participation;\n const exercise = { id: 3, course: { id: 4 } } as ProgrammingExercise;\n const getFileSubject = new Subject<{ fileContent: string; fileName: string }>();\n const loadInitialResultStub = stub(comp, 'loadInitialResult').returns(of(result));\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n const noInstructionsAvailableSpy = spy(comp.onNoInstructionsAvailable, 'emit');\n getFileStub.returns(getFileSubject);\n comp.participation = participation;\n comp.exercise = exercise;\n comp.isInitial = true;\n comp.isLoading = false;\n\n fixture.detectChanges();\n triggerChanges(comp);\n expect(comp.isLoading).to.be.true;\n expect(getFileStub).to.have.been.calledOnceWithExactly(participation.id, 'README.md');\n\n getFileSubject.error('fatal error');\n expect(comp.problemStatement).to.be.undefined;\n expect(loadInitialResultStub).to.not.have.been.called;\n expect(comp.latestResult).to.be.undefined;\n expect(updateMarkdownStub).to.not.have.been.called;\n expect(noInstructionsAvailableSpy).to.have.been.calledOnceWithExactly();\n expect(comp.isInitial).to.be.false;\n expect(comp.isLoading).to.be.false;\n fixture.detectChanges();\n expect(debugElement.query(By.css('#programming-exercise-instructions-loading'))).not.to.exist;\n expect(debugElement.query(By.css('#programming-exercise-instructions-content'))).to.exist;\n });\n\n it('should NOT update markdown if the problemStatement is changed', () => {\n const participation = { id: 2 } as Participation;\n const exercise = { id: 3, course: { id: 4 } } as ProgrammingExercise;\n const oldProblemStatement = 'lorem ipsum';\n const newProblemStatement = 'new lorem ipsum';\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n const loadInitialResult = stub(comp, 'loadInitialResult');\n fixture.detectChanges();\n comp.exercise = { ...exercise, problemStatement: newProblemStatement };\n comp.participation = participation;\n comp.isInitial = false;\n triggerChanges(comp, {\n property: 'exercise',\n previousValue: { ...exercise, problemStatement: oldProblemStatement },\n currentValue: { ...comp.exercise, problemStatement: newProblemStatement },\n firstChange: false,\n });\n expect(updateMarkdownStub).to.have.been.called;\n expect(loadInitialResult).not.to.have.been.called;\n });\n\n it('should NOT update the markdown if there is no participation and the exercise has changed', () => {\n const participation = { id: 2 } as Participation;\n const exercise = { id: 3, course: { id: 4 } } as ProgrammingExercise;\n const newProblemStatement = 'new lorem ipsum';\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n const loadInitialResult = stub(comp, 'loadInitialResult');\n fixture.detectChanges();\n comp.exercise = { ...exercise, problemStatement: newProblemStatement };\n comp.participation = participation;\n comp.isInitial = false;\n triggerChanges(comp, { property: 'exercise', currentValue: { ...comp.exercise, problemStatement: newProblemStatement }, firstChange: false });\n expect(comp.markdownExtensions).to.have.lengthOf(2);\n expect(updateMarkdownStub).to.have.been.called;\n expect(loadInitialResult).not.to.have.been.called;\n });\n\n it('should still render the instructions if fetching the latest result fails', () => {\n const participation = { id: 2 } as Participation;\n const problemstatement = 'lorem ipsum';\n const exercise = { id: 3, course: { id: 4 }, problemStatement: problemstatement } as ProgrammingExercise;\n const updateMarkdownStub = stub(comp, 'updateMarkdown');\n getLatestResultWithFeedbacks.returns(throwError('fatal error'));\n comp.participation = participation;\n comp.exercise = exercise;\n comp.isInitial = true;\n comp.isLoading = false;\n\n fixture.detectChanges();\n triggerChanges(comp);\n\n expect(comp.markdownExtensions).to.have.lengthOf(2);\n expect(getLatestResultWithFeedbacks).to.have.been.calledOnceWith(participation.id);\n expect(updateMarkdownStub).to.have.been.calledOnce;\n expect(comp.isInitial).to.be.false;\n expect(comp.isLoading).to.be.false;\n });\n\n it('should create the steps task icons for the tasks in problem statement markdown (non legacy case)', fakeAsync(() => {\n const result = {\n id: 1,\n completionDate: moment('2019-06-06T22:15:29.203+02:00'),\n feedbacks: [{ text: 'testMergeSort', detail_text: 'lorem ipsum', positive: true }],\n } as any;\n const exercise = { id: 3, course: { id: 4 }, problemStatement, showTestNamesToStudents: true } as ProgrammingExercise;\n\n comp.problemStatement = exercise.problemStatement!;\n comp.exercise = exercise;\n comp.latestResult = result;\n // @ts-ignore\n comp.setupMarkdownSubscriptions();\n\n comp.updateMarkdown();\n\n expect(comp.tasks).to.have.lengthOf(2);\n expect(comp.tasks[0]).to.deep.equal({\n id: 0,\n completeString: '[task][Implement Bubble Sort](testBubbleSort)',\n taskName: 'Implement Bubble Sort',\n tests: ['testBubbleSort'],\n hints: [],\n });\n expect(comp.tasks[1]).to.deep.equal({\n id: 1,\n completeString: '[task][Implement Merge Sort](testMergeSort){33,44}',\n taskName: 'Implement Merge Sort',\n tests: ['testMergeSort'],\n hints: ['33', '44'],\n });\n fixture.detectChanges();\n\n expect(debugElement.query(By.css('.stepwizard'))).to.exist;\n expect(debugElement.queryAll(By.css('.stepwizard-circle'))).to.have.lengthOf(2);\n tick();\n fixture.detectChanges();\n expect(debugElement.query(By.css('.instructions__content__markdown')).nativeElement.innerHTML).to.equal(problemStatementBubbleSortNotExecutedHtml);\n\n const bubbleSortStep = debugElement.query(By.css('.stepwizard-step--not-executed'));\n const mergeSortStep = debugElement.query(By.css('.stepwizard-step--success'));\n expect(bubbleSortStep).to.exist;\n expect(mergeSortStep).to.exist;\n\n const modalRef = { componentInstance: {} };\n openModalStub.returns(modalRef);\n\n bubbleSortStep.nativeElement.click();\n mergeSortStep.nativeElement.click();\n\n expect(openModalStub).to.have.been.calledOnceWithExactly(ResultDetailComponent, { keyboard: true, size: 'lg' });\n expect(modalRef).to.deep.equal({\n componentInstance: { exerciseType: ExerciseType.PROGRAMMING, feedbackFilter: ['testBubbleSort'], result, showTestDetails: true },\n });\n }));\n\n it('should create the steps task icons for the tasks in problem statement markdown (legacy case)', fakeAsync(() => {\n const result = {\n id: 1,\n completionDate: moment('2019-01-06T22:15:29.203+02:00'),\n feedbacks: [{ text: 'testBubbleSort', detail_text: 'lorem ipsum' }],\n } as any;\n const exercise = { id: 3, course: { id: 4 }, problemStatement } as ProgrammingExercise;\n\n comp.problemStatement = exercise.problemStatement!;\n comp.exercise = exercise;\n comp.latestResult = result;\n // @ts-ignore\n comp.setupMarkdownSubscriptions();\n\n comp.updateMarkdown();\n\n expect(comp.tasks).to.have.lengthOf(2);\n expect(comp.tasks[0]).to.deep.equal({\n id: 0,\n completeString: '[task][Implement Bubble Sort](testBubbleSort)',\n taskName: 'Implement Bubble Sort',\n tests: ['testBubbleSort'],\n hints: [],\n });\n expect(comp.tasks[1]).to.deep.equal({\n id: 1,\n completeString: '[task][Implement Merge Sort](testMergeSort){33,44}',\n taskName: 'Implement Merge Sort',\n tests: ['testMergeSort'],\n hints: ['33', '44'],\n });\n fixture.detectChanges();\n\n expect(debugElement.query(By.css('.stepwizard'))).to.exist;\n expect(debugElement.queryAll(By.css('.stepwizard-circle'))).to.have.lengthOf(2);\n tick();\n fixture.detectChanges();\n expect(debugElement.query(By.css('.instructions__content__markdown')).nativeElement.innerHTML).to.equal(problemStatementBubbleSortFailsHtml);\n\n const bubbleSortStep = debugElement.query(By.css('.stepwizard-step--failed'));\n const mergeSortStep = debugElement.query(By.css('.stepwizard-step--success'));\n expect(bubbleSortStep).to.exist;\n expect(mergeSortStep).to.exist;\n\n const modalRef = { componentInstance: {} };\n openModalStub.returns(modalRef);\n\n bubbleSortStep.nativeElement.click();\n mergeSortStep.nativeElement.click();\n\n expect(openModalStub).to.have.been.calledOnceWithExactly(ResultDetailComponent, { keyboard: true, size: 'lg' });\n expect(modalRef).to.deep.equal({\n componentInstance: { exerciseType: ExerciseType.PROGRAMMING, feedbackFilter: ['testBubbleSort'], result, showTestDetails: false },\n });\n }));\n});\n" }, { "alpha_fraction": 0.6918745040893555, "alphanum_fraction": 0.693081259727478, "avg_line_length": 45.03703689575195, "blob_id": "a04ed8e862211bac18679c44c8a28db5bbef8c12", "content_id": "63895f6e0f1e9ca7928edb2199aba55db8db2b6b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2486, "license_type": "permissive", "max_line_length": 178, "num_lines": 54, "path": "/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute } from '@angular/router';\nimport { of } from 'rxjs';\n\nimport { ArtemisTestModule } from '../../test.module';\nimport { ModelingExerciseDetailComponent } from 'app/exercises/modeling/manage/modeling-exercise-detail.component';\nimport { ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockComponent, MockProvider } from 'ng-mocks';\nimport { NonProgrammingExerciseDetailCommonActionsComponent } from 'app/exercises/shared/exercise-detail-common-actions/non-programming-exercise-detail-common-actions.component';\n\ndescribe('ModelingExercise Management Detail Component', () => {\n let comp: ModelingExerciseDetailComponent;\n let fixture: ComponentFixture<ModelingExerciseDetailComponent>;\n let modelingExerciseService: ModelingExerciseService;\n\n const modelingExercise = { id: 123 } as ModelingExercise;\n const route = ({ params: of({ exerciseId: modelingExercise.id }) } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [ModelingExerciseDetailComponent, MockComponent(NonProgrammingExerciseDetailCommonActionsComponent)],\n providers: [{ provide: ActivatedRoute, useValue: route }, MockProvider(TranslateService)],\n })\n .overrideTemplate(ModelingExerciseDetailComponent, '')\n .compileComponents();\n fixture = TestBed.createComponent(ModelingExerciseDetailComponent);\n comp = fixture.componentInstance;\n modelingExerciseService = fixture.debugElement.injector.get(ModelingExerciseService);\n });\n\n it('Should load exercise on init', () => {\n // GIVEN\n const headers = new HttpHeaders().append('link', 'link;link');\n spyOn(modelingExerciseService, 'find').and.returnValue(\n of(\n new HttpResponse({\n body: modelingExercise,\n headers,\n }),\n ),\n );\n\n // WHEN\n comp.ngOnInit();\n\n // THEN\n expect(modelingExerciseService.find).toHaveBeenCalled();\n expect(comp.modelingExercise).toEqual(modelingExercise);\n });\n});\n" }, { "alpha_fraction": 0.7392945885658264, "alphanum_fraction": 0.7408046722412109, "avg_line_length": 49.93955993652344, "blob_id": "3af68f8abe88d19b8cd08a8b8996e77fbef05f6d", "content_id": "b7e6857db6557531f71bb63ddd6515f41fa8d1c7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 9271, "license_type": "permissive", "max_line_length": 166, "num_lines": 182, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/jenkins/JenkinsBuildPlanCreator.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.jenkins;\n\nimport static de.tum.in.www1.artemis.service.connectors.ContinuousIntegrationService.getDockerImageName;\n\nimport java.io.IOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Paths;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport javax.annotation.PostConstruct;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Component;\nimport org.springframework.util.StreamUtils;\nimport org.w3c.dom.Document;\n\nimport de.tum.in.www1.artemis.config.Constants;\nimport de.tum.in.www1.artemis.domain.VcsRepositoryUrl;\nimport de.tum.in.www1.artemis.domain.enumeration.ProgrammingLanguage;\nimport de.tum.in.www1.artemis.domain.enumeration.StaticCodeAnalysisTool;\nimport de.tum.in.www1.artemis.service.ResourceLoaderService;\nimport de.tum.in.www1.artemis.service.util.XmlFileUtils;\n\n@Profile(\"jenkins\")\n@Component\npublic class JenkinsBuildPlanCreator implements JenkinsXmlConfigBuilder {\n\n private static final Logger LOG = LoggerFactory.getLogger(JenkinsBuildPlanCreator.class);\n\n private static final String STATIC_CODE_ANALYSIS_REPORT_DIR = \"staticCodeAnalysisReports\";\n\n private static final String REPLACE_PIPELINE_SCRIPT = \"#pipelineScript\";\n\n private static final String REPLACE_TEST_REPO = \"#testRepository\";\n\n private static final String REPLACE_ASSIGNMENT_REPO = \"#assignmentRepository\";\n\n private static final String REPLACE_GIT_CREDENTIALS = \"#gitCredentials\";\n\n private static final String REPLACE_ASSIGNMENT_CHECKOUT_PATH = \"#assignmentCheckoutPath\";\n\n private static final String REPLACE_TESTS_CHECKOUT_PATH = \"#testsCheckoutPath\";\n\n private static final String REPLACE_PUSH_TOKEN = \"#secretPushToken\";\n\n private static final String REPLACE_ARTEMIS_NOTIFICATION_URL = \"#notificationsUrl\";\n\n private static final String REPLACE_NOTIFICATIONS_TOKEN = \"#jenkinsNotificationToken\";\n\n private static final String REPLACE_STATIC_CODE_ANALYSIS_SCRIPT = \"#staticCodeAnalysisScript\";\n\n private static final String REPLACE_DOCKER_IMAGE_NAME = \"#dockerImage\";\n\n private static final String REPLACE_JENKINS_TIMEOUT = \"#jenkinsTimeout\";\n\n private String artemisNotificationUrl;\n\n @Value(\"${artemis.continuous-integration.secret-push-token}\")\n private String pushToken;\n\n @Value(\"${artemis.continuous-integration.vcs-credentials}\")\n private String gitCredentialsKey;\n\n @Value(\"${artemis.continuous-integration.build-timeout:#{30}}\")\n private String buildTimeout;\n\n @Value(\"${server.url}\")\n private String ARTEMIS_SERVER_URL;\n\n @Value(\"${artemis.continuous-integration.artemis-authentication-token-key}\")\n private String ARTEMIS_AUTHENTICATION_TOKEN_KEY;\n\n private final ResourceLoaderService resourceLoaderService;\n\n public JenkinsBuildPlanCreator(ResourceLoaderService resourceLoaderService) {\n this.resourceLoaderService = resourceLoaderService;\n }\n\n @PostConstruct\n public void init() {\n this.artemisNotificationUrl = ARTEMIS_SERVER_URL + \"/api\" + Constants.NEW_RESULT_RESOURCE_PATH;\n }\n\n public String getPipelineScript(ProgrammingLanguage programmingLanguage, VcsRepositoryUrl testRepositoryURL, VcsRepositoryUrl assignmentRepositoryURL,\n boolean isStaticCodeAnalysisEnabled) {\n var pipelinePath = getResourcePath(programmingLanguage, isStaticCodeAnalysisEnabled);\n var replacements = getReplacements(programmingLanguage, testRepositoryURL, assignmentRepositoryURL, isStaticCodeAnalysisEnabled);\n return replacePipelineScriptParameters(pipelinePath, replacements);\n }\n\n private Map<String, String> getReplacements(ProgrammingLanguage programmingLanguage, VcsRepositoryUrl testRepositoryURL, VcsRepositoryUrl assignmentRepositoryURL,\n boolean isStaticCodeAnalysisEnabled) {\n Map<String, String> replacements = new HashMap<>();\n replacements.put(REPLACE_TEST_REPO, testRepositoryURL.getURL().toString());\n replacements.put(REPLACE_ASSIGNMENT_REPO, assignmentRepositoryURL.getURL().toString());\n replacements.put(REPLACE_GIT_CREDENTIALS, gitCredentialsKey);\n replacements.put(REPLACE_ASSIGNMENT_CHECKOUT_PATH, Constants.ASSIGNMENT_CHECKOUT_PATH);\n replacements.put(REPLACE_TESTS_CHECKOUT_PATH, Constants.TESTS_CHECKOUT_PATH);\n replacements.put(REPLACE_ARTEMIS_NOTIFICATION_URL, artemisNotificationUrl);\n replacements.put(REPLACE_NOTIFICATIONS_TOKEN, ARTEMIS_AUTHENTICATION_TOKEN_KEY);\n replacements.put(REPLACE_DOCKER_IMAGE_NAME, getDockerImageName(programmingLanguage));\n replacements.put(REPLACE_JENKINS_TIMEOUT, buildTimeout);\n // at the moment, only Java and Swift are supported\n if (isStaticCodeAnalysisEnabled) {\n String staticCodeAnalysisScript = createStaticCodeAnalysisScript(programmingLanguage);\n replacements.put(REPLACE_STATIC_CODE_ANALYSIS_SCRIPT, staticCodeAnalysisScript);\n }\n return replacements;\n }\n\n private String[] getResourcePath(ProgrammingLanguage programmingLanguage, boolean isStaticCodeAnalysisEnabled) {\n final var buildPlan = isStaticCodeAnalysisEnabled ? \"Jenkinsfile-staticCodeAnalysis\" : \"Jenkinsfile\";\n return new String[] { \"templates\", \"jenkins\", programmingLanguage.name().toLowerCase(), buildPlan };\n }\n\n @Override\n public Document buildBasicConfig(ProgrammingLanguage programmingLanguage, VcsRepositoryUrl testRepositoryURL, VcsRepositoryUrl assignmentRepositoryURL,\n boolean isStaticCodeAnalysisEnabled) {\n final var resourcePath = Paths.get(\"templates\", \"jenkins\", \"config.xml\");\n\n String pipeLineScript = getPipelineScript(programmingLanguage, testRepositoryURL, assignmentRepositoryURL, isStaticCodeAnalysisEnabled);\n pipeLineScript = pipeLineScript.replace(\"'\", \"&apos;\");\n pipeLineScript = pipeLineScript.replace(\"<\", \"&lt;\");\n pipeLineScript = pipeLineScript.replace(\">\", \"&gt;\");\n pipeLineScript = pipeLineScript.replace(\"\\\\\", \"\\\\\\\\\");\n\n Map<String, String> replacements = Map.of(REPLACE_PIPELINE_SCRIPT, pipeLineScript, REPLACE_PUSH_TOKEN, pushToken);\n\n final var xmlResource = resourceLoaderService.getResource(resourcePath.toString());\n return XmlFileUtils.readXmlFile(xmlResource, replacements);\n }\n\n private String replacePipelineScriptParameters(String[] pipelineScriptPath, Map<String, String> variablesToReplace) {\n final var resource = resourceLoaderService.getResource(pipelineScriptPath);\n try {\n var pipelineScript = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());\n if (variablesToReplace != null) {\n for (final var replacement : variablesToReplace.entrySet()) {\n pipelineScript = pipelineScript.replace(replacement.getKey(), replacement.getValue());\n }\n }\n\n return pipelineScript;\n }\n catch (IOException e) {\n final var errorMessage = \"Error loading template Jenkins build XML: \" + e.getMessage();\n LOG.error(errorMessage, e);\n throw new IllegalStateException(errorMessage, e);\n }\n }\n\n // at the moment, only Java and Swift are supported\n private String createStaticCodeAnalysisScript(ProgrammingLanguage programmingLanguage) {\n StringBuilder script = new StringBuilder();\n String lineEnding = \"&#xd;\";\n // Delete a possible old directory for generated static code analysis reports and create a new one\n script.append(\"rm -rf \").append(STATIC_CODE_ANALYSIS_REPORT_DIR).append(lineEnding);\n script.append(\"mkdir \").append(STATIC_CODE_ANALYSIS_REPORT_DIR).append(lineEnding);\n if (programmingLanguage == ProgrammingLanguage.JAVA) {\n script.append(\"mvn \");\n // Execute all static code analysis tools for Java\n script.append(StaticCodeAnalysisTool.createBuildPlanCommandForProgrammingLanguage(programmingLanguage)).append(lineEnding);\n // Copy all static code analysis reports to new directory\n for (var tool : StaticCodeAnalysisTool.getToolsForProgrammingLanguage(programmingLanguage)) {\n script.append(\"cp target/\").append(tool.getFilePattern()).append(\" \").append(STATIC_CODE_ANALYSIS_REPORT_DIR).append(lineEnding);\n }\n }\n else if (programmingLanguage == ProgrammingLanguage.SWIFT) {\n StaticCodeAnalysisTool tool = StaticCodeAnalysisTool.getToolsForProgrammingLanguage(programmingLanguage).get(0);\n // Copy swiftlint configuration into student's repository\n script.append(\"cp .swiftlint.yml assignment || true\").append(lineEnding);\n // Execute swiftlint within the student's repository and save the report into the sca directory\n // sh command: swiftlint lint assignment > <scaDir>/<result>.xml\n script.append(\"swiftlint lint assignment > \").append(STATIC_CODE_ANALYSIS_REPORT_DIR).append(\"/\").append(tool.getFilePattern()).append(lineEnding);\n }\n return script.toString();\n }\n}\n" }, { "alpha_fraction": 0.6537462472915649, "alphanum_fraction": 0.6563440561294556, "avg_line_length": 44.499061584472656, "blob_id": "fbd29007d431c072f22b75e35683731ac406b6dc", "content_id": "246c2e0d20cb3d06318e3fbc3f31313fa729592d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 24251, "license_type": "permissive", "max_line_length": 179, "num_lines": 533, "path": "/src/main/java/de/tum/in/www1/artemis/repository/ExerciseRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport static org.springframework.data.jpa.repository.EntityGraph.EntityGraphType.LOAD;\n\nimport java.time.ZonedDateTime;\nimport java.time.temporal.ChronoUnit;\nimport java.util.*;\nimport java.util.stream.Collectors;\n\nimport javax.validation.constraints.NotNull;\n\nimport org.springframework.data.jpa.repository.EntityGraph;\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.data.jpa.repository.Query;\nimport org.springframework.data.repository.query.Param;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.Exercise;\nimport de.tum.in.www1.artemis.domain.enumeration.ExerciseMode;\nimport de.tum.in.www1.artemis.web.rest.dto.CourseExerciseStatisticsDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\n\n/**\n * Spring Data JPA repository for the Exercise entity.\n */\n@SuppressWarnings(\"unused\")\n@Repository\npublic interface ExerciseRepository extends JpaRepository<Exercise, Long> {\n\n @Query(\"\"\"\n SELECT e FROM Exercise e\n LEFT JOIN FETCH e.categories\n WHERE e.course.id = :#{#courseId}\n \"\"\")\n Set<Exercise> findByCourseIdWithCategories(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n SELECT e\n FROM Exercise e LEFT JOIN FETCH e.categories WHERE\n e.id IN :exerciseIds\n \"\"\")\n Set<Exercise> findByExerciseIdWithCategories(@Param(\"exerciseIds\") Set<Long> exerciseIds);\n\n @Query(\"\"\"\n SELECT e FROM Exercise e\n WHERE e.course.id = :#{#courseId}\n \tAND e.mode = 'TEAM'\n \"\"\")\n Set<Exercise> findAllTeamExercisesByCourseId(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n SELECT e FROM Exercise e\n WHERE e.course.testCourse = FALSE\n \tAND e.dueDate >= :#{#now}\n ORDER BY e.dueDate ASC\n \"\"\")\n Set<Exercise> findAllExercisesWithCurrentOrUpcomingDueDate(@Param(\"now\") ZonedDateTime now);\n\n /**\n * Select Exercise for Course ID WHERE there does exist an LtiOutcomeUrl for the current user (-> user has started exercise once using LTI)\n * @param courseId the id of the course\n * @param login the login of the corresponding user\n * @return list of exercises\n */\n @Query(\"\"\"\n SELECT e FROM Exercise e\n WHERE e.course.id = :#{#courseId}\n AND EXISTS (\n \tSELECT l FROM LtiOutcomeUrl l\n \tWHERE e = l.exercise\n \tAND l.user.login = :#{#login})\n \"\"\")\n Set<Exercise> findByCourseIdWhereLtiOutcomeUrlExists(@Param(\"courseId\") Long courseId, @Param(\"login\") String login);\n\n @Query(\"\"\"\n SELECT DISTINCT c FROM Exercise e JOIN e.categories c\n WHERE e.course.id = :#{#courseId}\n \"\"\")\n Set<String> findAllCategoryNames(@Param(\"courseId\") Long courseId);\n\n @Query(\"\"\"\n SELECT DISTINCT e FROM Exercise e\n LEFT JOIN FETCH e.studentParticipations\n WHERE e.id = :#{#exerciseId}\n \"\"\")\n Optional<Exercise> findByIdWithEagerParticipations(@Param(\"exerciseId\") Long exerciseId);\n\n @EntityGraph(type = LOAD, attributePaths = { \"categories\", \"teamAssignmentConfig\" })\n Optional<Exercise> findWithEagerCategoriesAndTeamAssignmentConfigById(Long exerciseId);\n\n @Query(\"\"\"\n SELECT DISTINCT e from Exercise e\n LEFT JOIN FETCH e.exampleSubmissions examplesub\n LEFT JOIN FETCH examplesub.submission exsub\n LEFT JOIN FETCH exsub.results\n WHERE e.id = :#{#exerciseId}\n \"\"\")\n Optional<Exercise> findByIdWithEagerExampleSubmissions(@Param(\"exerciseId\") Long exerciseId);\n\n @Query(\"\"\"\n SELECT DISTINCT e from Exercise e\n LEFT JOIN FETCH e.exerciseHints\n LEFT JOIN FETCH e.studentQuestions\n LEFT JOIN FETCH e.categories\n WHERE e.id = :#{#exerciseId}\n \"\"\")\n Optional<Exercise> findByIdWithDetailsForStudent(@Param(\"exerciseId\") Long exerciseId);\n\n /**\n *\n * @param courseId - course id of the exercises we want to fetch\n * @return all exercise-ids which belong to the course\n */\n @Query(\"\"\"\n SELECT e.id FROM Exercise e LEFT JOIN e.course c\n WHERE c.id = :courseId\n \"\"\")\n Set<Long> findAllIdsByCourseId(@Param(\"courseId\") Long courseId);\n\n /**\n * calculates the average score and the participation rate of students for each given individual course exercise\n * by using the last result (rated or not)\n * @param exerciseIds - exercise ids to count the statistics for\n * @return <code>Object[]</code> where each index corresponds to the column from the db (0 refers to exerciseId and so on)\n */\n @Query(\"\"\"\n SELECT\n e.id,\n AVG(r.score),\n Count(Distinct p.student.id),\n (SELECT count(distinct u.id)\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n FROM Exercise e JOIN e.studentParticipations p JOIN p.submissions s JOIN s.results r\n WHERE e.id IN :exerciseIds\n AND e.course.studentGroupName member of p.student.groups\n AND e.course.teachingAssistantGroupName not member of p.student.groups\n AND e.course.instructorGroupName not member of p.student.groups\n AND r.score IS NOT NULL AND r.completionDate IS NOT NULL\n AND\n s.id = (\n SELECT max(s2.id)\n FROM Submission s2 JOIN s2.results r2\n WHERE s2.participation.id = s.participation.id\n AND r2.score IS NOT NULL AND r2.completionDate IS NOT NULL\n )\n GROUP BY e.id\n \"\"\")\n List<Object[]> calculateStatisticsForIndividualCourseExercises(@Param(\"exerciseIds\") List<Long> exerciseIds);\n\n /**\n * calculates the average score and the participation rate of students for each given individual course exercise\n * by using the last result (rated or not). This query gets the last result from the participation scores table\n *\n * @param exerciseIds - exercise ids to count the statistics for\n * @return <code>Object[]</code> where each index corresponds to the column from the db (0 refers to exerciseId and so on)\n */\n @Query(\"\"\"\n SELECT\n e.id,\n AVG(sc.lastScore),\n Count(Distinct p.student.id),\n (SELECT count(distinct u.id)\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n\n FROM Exercise e JOIN e.studentParticipations p, StudentScore sc\n WHERE e.id IN :exerciseIds\n AND sc.exercise = e AND sc.user = p.student\n AND e.course.studentGroupName member of p.student.groups\n AND e.course.teachingAssistantGroupName not member of p.student.groups\n AND e.course.instructorGroupName not member of p.student.groups\n GROUP BY e.id\n \"\"\")\n List<Object[]> calculateExerciseStatisticsForIndividualCourseUsingParticipationTable(@Param(\"exerciseIds\") List<Long> exerciseIds);\n\n /**\n * calculates the average score and the participation rate of students for each given team course exercise\n * by using the last result (rated or not)\n *\n * @param exerciseIds - exercise ids to count the statistics for\n * @return <code>Object[]</code> where each index corresponds to the column from the db (0 refers to exerciseId and so on)\n */\n @Query(\"\"\"\n SELECT\n e.id,\n AVG(r.score),\n Count(Distinct p.team.id),\n (SELECT count(distinct t.id)\n FROM Team t JOIN t.students st2\n WHERE st2.id IN (\n SELECT DISTINCT u.id\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n )\n FROM Exercise e JOIN e.studentParticipations p JOIN p.submissions s JOIN s.results r JOIN p.team.students st\n WHERE e.id IN :exerciseIds\n AND r.score IS NOT NULL AND r.completionDate IS NOT NULL\n AND\n st.id IN (\n SELECT DISTINCT u.id\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n AND\n s.id = (\n SELECT max(s2.id)\n FROM Submission s2 JOIN s2.results r2\n WHERE s2.participation.id = s.participation.id\n AND r2.score IS NOT NULL AND r2.completionDate IS NOT NULL\n )\n GROUP BY e.id\n \"\"\")\n List<Object[]> calculateStatisticsForTeamCourseExercises(@Param(\"exerciseIds\") List<Long> exerciseIds);\n\n /**\n * calculates the average score and the participation rate of students for each given team course exercise\n * by using the last result (rated or not). This query gets the last result from the participation scores table\n *\n * @param exerciseIds - exercise ids to count the statistics for\n * @return <code>Object[]</code> where each index corresponds to the column from the db (0 refers to exerciseId and so on)\n */\n @Query(\"\"\"\n SELECT\n e.id,\n AVG(ts.lastScore),\n Count(Distinct p.team.id),\n (SELECT count(distinct t.id)\n FROM Team t JOIN t.students st2\n WHERE st2.id IN (\n SELECT DISTINCT u.id\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n )\n FROM Exercise e JOIN e.studentParticipations p JOIN p.team.students st, TeamScore ts\n WHERE e.id IN :exerciseIds\n AND ts.exercise = e AND ts.team = p.team\n AND\n st.id IN (\n SELECT DISTINCT u.id\n FROM User u\n WHERE\n e.course.studentGroupName member of u.groups\n AND e.course.teachingAssistantGroupName not member of u.groups\n AND e.course.instructorGroupName not member of u.groups\n )\n GROUP BY e.id\n \"\"\")\n List<Object[]> calculateExerciseStatisticsForTeamCourseExercisesUsingParticipationTable(@Param(\"exerciseIds\") List<Long> exerciseIds);\n\n @EntityGraph(type = LOAD, attributePaths = { \"studentParticipations\", \"studentParticipations.student\", \"studentParticipations.submissions\" })\n Optional<Exercise> findWithEagerStudentParticipationsStudentAndSubmissionsById(Long exerciseId);\n\n /**\n * Returns the title of the exercise with the given id\n *\n * @param exerciseId the id of the exercise\n * @return the name/title of the exercise or null if the exercise does not exist\n */\n @Query(\"\"\"\n SELECT e.title\n FROM Exercise e\n WHERE e.id = :exerciseId\n \"\"\")\n String getExerciseTitle(@Param(\"exerciseId\") Long exerciseId);\n\n /**\n * Fetches the exercises for a course\n *\n * @param courseId the course to get the exercises for\n * @return a set of exercises with categories\n */\n @Query(\"\"\"\n SELECT DISTINCT e\n FROM Exercise e LEFT JOIN FETCH e.categories\n WHERE e.course.id = :courseId\n \"\"\")\n Set<Exercise> getExercisesForCourseManagementOverview(@Param(\"courseId\") Long courseId);\n\n /**\n * Fetches the exercises for a course with an assessment due date (or due date if without assessment due date) in the future\n *\n * @param courseId the course to get the exercises for\n * @param now the current date time\n * @return a set of exercises\n */\n @Query(\"\"\"\n SELECT DISTINCT e\n FROM Exercise e\n WHERE e.course.id = :courseId\n AND (e.assessmentDueDate IS NULL OR e.assessmentDueDate > :now)\n AND (e.assessmentDueDate IS NOT NULL OR e.dueDate IS NULL OR e.dueDate > :now)\n \"\"\")\n Set<Exercise> getActiveExercisesForCourseManagementOverview(@Param(\"courseId\") Long courseId, @Param(\"now\") ZonedDateTime now);\n\n /**\n * Fetches the exercises for a course with a passed assessment due date (or due date if without assessment due date)\n *\n * @param courseId the course to get the exercises for\n * @param now the current date time\n * @return a set of exercises\n */\n @Query(\"\"\"\n SELECT DISTINCT e\n FROM Exercise e\n WHERE e.course.id = :courseId\n AND (e.assessmentDueDate IS NOT NULL AND e.assessmentDueDate < :now\n OR e.assessmentDueDate IS NULL AND e.dueDate IS NOT NULL AND e.dueDate < :now)\n \"\"\")\n List<Exercise> getPastExercisesForCourseManagementOverview(@Param(\"courseId\") Long courseId, @Param(\"now\") ZonedDateTime now);\n\n /**\n * Fetches the number of student participations in the given exercise\n *\n * @param exerciseId the id of the exercise to get the amount for\n * @return The number of participations as <code>Long</code>\n */\n @Query(\"\"\"\n SELECT COUNT(DISTINCT p.student.id)\n FROM Exercise e JOIN e.studentParticipations p\n WHERE e.id = :exerciseId\n \"\"\")\n Long getStudentParticipationCountById(@Param(\"exerciseId\") Long exerciseId);\n\n /**\n * Fetches the number of team participations in the given exercise\n *\n * @param exerciseId the id of the exercise to get the amount for\n * @return The number of participations as <code>Long</code>\n */\n @Query(\"\"\"\n SELECT COUNT(DISTINCT p.team.id)\n FROM Exercise e JOIN e.studentParticipations p\n WHERE e.id = :exerciseId\n \"\"\")\n Long getTeamParticipationCountById(@Param(\"exerciseId\") Long exerciseId);\n\n /**\n * Fetches exercise ids of exercises of a course\n *\n * @param courseId the id of the course the exercises are part of\n * @return a list of ids of exercises\n */\n @Query(\"\"\"\n SELECT e.id\n FROM Exercise e\n WHERE e.course.id = :courseId\n \"\"\")\n List<Long> getExerciseIdsByCourseId(@Param(\"courseId\") Long courseId);\n\n @NotNull\n default Exercise findByIdElseThrow(Long exerciseId) throws EntityNotFoundException {\n return findById(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Exercise\", exerciseId));\n }\n\n /**\n * Get one exercise by exerciseId with its categories and its team assignment config\n *\n * @param exerciseId the exerciseId of the entity\n * @return the entity\n */\n @NotNull\n default Exercise findByIdWithCategoriesAndTeamAssignmentConfigElseThrow(Long exerciseId) {\n return findWithEagerCategoriesAndTeamAssignmentConfigById(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Exercise\", exerciseId));\n }\n\n /**\n * Finds all exercises where the due date is today or in the future\n * (does not return exercises belonging to test courses).\n *\n * @return set of exercises\n */\n default Set<Exercise> findAllExercisesWithCurrentOrUpcomingDueDate() {\n return findAllExercisesWithCurrentOrUpcomingDueDate(ZonedDateTime.now().truncatedTo(ChronoUnit.DAYS));\n }\n\n /**\n * Find exercise by exerciseId and load participations in this exercise.\n *\n * @param exerciseId the exerciseId of the exercise entity\n * @return the exercise entity\n */\n @NotNull\n default Exercise findByIdWithStudentParticipationsElseThrow(Long exerciseId) {\n return findByIdWithEagerParticipations(exerciseId).orElseThrow(() -> new EntityNotFoundException(\"Exercise\", exerciseId));\n }\n\n /**\n * Gets the {@link CourseExerciseStatisticsDTO} for each exercise proved in <code>exerciseIds</code>.\n * <p>\n * calculates the average score and the participation rate of students for each given course exercise (team or individual)\n * by using the last result (rated or not)\n *\n * @param exerciseIds - list of exercise ids (must be belong to the same course)\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result\n * @return the list of {@link CourseExerciseStatisticsDTO}\n * @throws IllegalArgumentException if exercise is not found in database, exercise is not a course exercise or not all exercises are from the same course\n */\n default List<CourseExerciseStatisticsDTO> calculateExerciseStatistics(List<Long> exerciseIds, boolean useParticipantScoreTable) throws IllegalArgumentException {\n List<Exercise> exercisesFromDb = new ArrayList<>();\n for (Long exerciseId : exerciseIds) {\n Optional<Exercise> exerciseFromDbOptional = this.findById(exerciseId);\n if (exerciseFromDbOptional.isEmpty()) {\n throw new IllegalArgumentException(\"Exercise not found in database\");\n }\n Exercise exerciseFromDb = exerciseFromDbOptional.get();\n\n if (!exerciseFromDb.isCourseExercise()) {\n throw new IllegalArgumentException(\"Exercise is not a course exercise\");\n }\n\n exercisesFromDb.add(exerciseFromDb);\n }\n\n List<Long> uniqueCourseIds = exercisesFromDb.stream().map(exercise -> exercise.getCourseViaExerciseGroupOrCourseMember().getId()).distinct().collect(Collectors.toList());\n if (uniqueCourseIds.size() > 1) {\n throw new IllegalArgumentException(\"Not all exercises are from the same course\");\n }\n\n List<CourseExerciseStatisticsDTO> courseExerciseStatisticsDTOs = new ArrayList<>();\n\n Map<Long, Object[]> exerciseIdToRawStatisticQueryData = this.getRawStatisticQueryData(exercisesFromDb, useParticipantScoreTable);\n exercisesFromDb.forEach((exercise) -> {\n CourseExerciseStatisticsDTO courseExerciseStatisticsDTO = convertRawStatisticQueryDataToDTO(exerciseIdToRawStatisticQueryData, exercise);\n courseExerciseStatisticsDTOs.add(courseExerciseStatisticsDTO);\n });\n\n return courseExerciseStatisticsDTOs;\n }\n\n /**\n * Converts the row data from the exercise statistic query into the corresponding DTO\n * @param exerciseIdToRawStatisticQueryData map from exerciseId to query data\n * @param exercise exercise\n * @return converted DTO\n */\n private CourseExerciseStatisticsDTO convertRawStatisticQueryDataToDTO(Map<Long, Object[]> exerciseIdToRawStatisticQueryData, Exercise exercise) {\n CourseExerciseStatisticsDTO courseExerciseStatisticsDTO = new CourseExerciseStatisticsDTO();\n courseExerciseStatisticsDTO.setExerciseId(exercise.getId());\n courseExerciseStatisticsDTO.setExerciseTitle(exercise.getTitle());\n courseExerciseStatisticsDTO.setExerciseMaxPoints(exercise.getMaxPoints());\n courseExerciseStatisticsDTO.setExerciseMode(exercise.getMode().toString());\n\n if (exerciseIdToRawStatisticQueryData.containsKey(exercise.getId())) {\n Object[] exerciseStatistics = exerciseIdToRawStatisticQueryData.get(exercise.getId());\n courseExerciseStatisticsDTO.setAverageScoreInPercent(exerciseStatistics[1] != null ? ((Number) exerciseStatistics[1]).doubleValue() : 0.0);\n courseExerciseStatisticsDTO.setNoOfParticipatingStudentsOrTeams(exerciseStatistics[2] != null ? ((Number) exerciseStatistics[2]).intValue() : 0);\n int numberOfPossibleParticipants = exerciseStatistics[3] != null ? ((Number) exerciseStatistics[3]).intValue() : 0;\n\n if (numberOfPossibleParticipants != 0) {\n double participationRate = ((courseExerciseStatisticsDTO.getNoOfParticipatingStudentsOrTeams() * 1.0) / (numberOfPossibleParticipants * 1.0)) * 100.0;\n courseExerciseStatisticsDTO.setParticipationRateInPercent(Math.round(participationRate * 100.0) / 100.0);\n }\n else {\n courseExerciseStatisticsDTO.setParticipationRateInPercent(0.0);\n }\n\n }\n else {\n courseExerciseStatisticsDTO.setAverageScoreInPercent(0.0);\n courseExerciseStatisticsDTO.setParticipationRateInPercent(0.0);\n courseExerciseStatisticsDTO.setNoOfParticipatingStudentsOrTeams(0);\n }\n return courseExerciseStatisticsDTO;\n }\n\n /**\n * calculates the average score and the participation rate of students for each given course exercise (team or individual)\n * by using the last result (rated or not)\n *\n * @param exercisesFromDb exercises to calculate the statistics for\n * @param useParticipantScoreTable use the participant score table instead of going through participation -> submission -> result*\n * @return Map which maps from exercise id to statistic query row data\n */\n private Map<Long, Object[]> getRawStatisticQueryData(List<Exercise> exercisesFromDb, boolean useParticipantScoreTable) {\n List<Exercise> individualExercises = exercisesFromDb.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.INDIVIDUAL)).collect(Collectors.toList());\n List<Exercise> teamExercises = exercisesFromDb.stream().filter(exercise -> exercise.getMode().equals(ExerciseMode.TEAM)).collect(Collectors.toList());\n\n List<Object[]> statisticForIndividualExercises;\n List<Object[]> statisticTeamExercises;\n\n if (useParticipantScoreTable) {\n statisticForIndividualExercises = this\n .calculateExerciseStatisticsForIndividualCourseUsingParticipationTable(individualExercises.stream().map(Exercise::getId).collect(Collectors.toList()));\n statisticTeamExercises = this\n .calculateExerciseStatisticsForTeamCourseExercisesUsingParticipationTable(teamExercises.stream().map(Exercise::getId).collect(Collectors.toList()));\n }\n else {\n statisticForIndividualExercises = this.calculateStatisticsForIndividualCourseExercises(individualExercises.stream().map(Exercise::getId).collect(Collectors.toList()));\n statisticTeamExercises = this.calculateStatisticsForTeamCourseExercises(teamExercises.stream().map(Exercise::getId).collect(Collectors.toList()));\n }\n\n List<Object[]> combinedStatistics = new ArrayList<>();\n combinedStatistics.addAll(statisticForIndividualExercises);\n combinedStatistics.addAll(statisticTeamExercises);\n\n Map<Long, Object[]> exerciseIdToStatistic = new HashMap<>();\n for (Object[] exerciseStatistic : combinedStatistics) {\n exerciseIdToStatistic.put(((Number) exerciseStatistic[0]).longValue(), exerciseStatistic);\n }\n return exerciseIdToStatistic;\n }\n\n /**\n * Activates or deactivates the possibility for tutors to assess within the correction round\n *\n * @param exercise - the exercise for which we want to toggle if the second correction round is enabled\n * @return the new state of the second correction\n */\n default boolean toggleSecondCorrection(Exercise exercise) {\n exercise.setSecondCorrectionEnabled(!exercise.getSecondCorrectionEnabled());\n return save(exercise).getSecondCorrectionEnabled();\n }\n}\n" }, { "alpha_fraction": 0.6512048244476318, "alphanum_fraction": 0.6518072485923767, "avg_line_length": 21.73972511291504, "blob_id": "727dda18f7fdba218c870b07a0a040340af9bc47", "content_id": "efa9053a31cd23fe749b341accc0ea9d044d4ab3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1660, "license_type": "permissive", "max_line_length": 125, "num_lines": 73, "path": "/src/main/java/de/tum/in/www1/artemis/domain/ExerciseHint.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.domain;\n\nimport javax.persistence.*;\n\nimport org.hibernate.annotations.Cache;\nimport org.hibernate.annotations.CacheConcurrencyStrategy;\n\nimport com.fasterxml.jackson.annotation.JsonIgnoreProperties;\nimport com.fasterxml.jackson.annotation.JsonInclude;\n\n/**\n * A ExerciseHint.\n */\n@Entity\n@Table(name = \"exercise_hint\")\n@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)\n@JsonInclude(JsonInclude.Include.NON_EMPTY)\npublic class ExerciseHint extends DomainObject {\n\n @Column(name = \"title\")\n private String title;\n\n @Column(name = \"content\")\n private String content;\n\n @ManyToOne\n @JsonIgnoreProperties(\"exerciseHints\")\n private Exercise exercise;\n\n public String getTitle() {\n return title;\n }\n\n public ExerciseHint title(String title) {\n this.title = title;\n return this;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getContent() {\n return content;\n }\n\n public ExerciseHint content(String content) {\n this.content = content;\n return this;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public Exercise getExercise() {\n return exercise;\n }\n\n public ExerciseHint exercise(Exercise exercise) {\n this.exercise = exercise;\n return this;\n }\n\n public void setExercise(Exercise exercise) {\n this.exercise = exercise;\n }\n\n @Override\n public String toString() {\n return \"ExerciseHint{\" + \"id=\" + getId() + \", title='\" + getTitle() + \"'\" + \", content='\" + getContent() + \"'\" + \"}\";\n }\n}\n" }, { "alpha_fraction": 0.5204790830612183, "alphanum_fraction": 0.5404406189918518, "avg_line_length": 43.4934196472168, "blob_id": "a3e05852ab1c4d5b125fd4d29ffa093b2ac5867a", "content_id": "28c94851103fbc0d07cefa98cfe7e0588abe45bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13526, "license_type": "permissive", "max_line_length": 610, "num_lines": 304, "path": "/src/test/javascript/spec/component/lecture/lecture-attachments.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport * as moment from 'moment';\nimport { TranslateModule } from '@ngx-translate/core';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { TreeviewModule } from 'ngx-treeview';\nimport { ArtemisTestModule } from '../../test.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ActivatedRoute } from '@angular/router';\nimport { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module';\nimport { By } from '@angular/platform-browser';\nimport { FileUploaderService } from 'app/shared/http/file-uploader.service';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { Attachment, AttachmentType } from 'app/entities/attachment.model';\nimport { LectureAttachmentsComponent } from 'app/lecture/lecture-attachments.component';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { FileService } from 'app/shared/http/file.service';\nimport { HtmlForMarkdownPipe } from 'app/shared/pipes/html-for-markdown.pipe';\nimport { MockPipe } from 'ng-mocks';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('LectureAttachmentsComponent', () => {\n let comp: LectureAttachmentsComponent;\n let fixture: ComponentFixture<LectureAttachmentsComponent>;\n let fileUploaderService: FileUploaderService;\n\n const lecture = {\n id: 4,\n title: 'Second Test Lecture2',\n description:\n 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',\n startDate: moment('2019-04-15T14:00:19+02:00'),\n endDate: moment('2019-04-15T15:30:20+02:00'),\n course: {\n id: 1,\n title: 'Refactoring CSS',\n description:\n 'Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.',\n shortName: 'RCSS',\n studentGroupName: 'artemis-dev',\n teachingAssistantGroupName: 'tumuser',\n instructorGroupName: 'tumuser',\n startDate: moment('2018-12-15T16:11:00+01:00'),\n endDate: moment('2019-06-15T16:11:14+02:00'),\n onlineCourse: false,\n color: '#691b0b',\n registrationEnabled: false,\n },\n } as Lecture;\n\n const attachments = [\n {\n id: 50,\n name: 'test',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF4.pdf',\n version: 2,\n uploadDate: moment('2019-05-05T10:05:25+02:00'),\n attachmentType: 'FILE',\n },\n {\n id: 52,\n name: 'test2',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF3.pdf',\n version: 1,\n uploadDate: moment('2019-05-07T08:49:59+02:00'),\n attachmentType: 'FILE',\n },\n ] as Attachment[];\n\n const newAttachment = {\n id: 53,\n name: 'TestFile',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF3.pdf',\n version: 1,\n uploadDate: moment('2019-05-07T08:49:59+02:00'),\n attachmentType: 'FILE',\n } as Attachment;\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, TreeviewModule.forRoot(), RouterTestingModule.withRoutes([]), ArtemisSharedModule, FormDateTimePickerModule],\n declarations: [LectureAttachmentsComponent, MockPipe(HtmlForMarkdownPipe)],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: {\n parent: {\n data: {\n subscribe: (fn: (value: any) => void) =>\n fn({\n lecture,\n }),\n },\n },\n },\n },\n {\n provide: AttachmentService,\n useValue: {\n create() {\n return {\n subscribe: (fn: (value: any) => void) =>\n fn({\n body: newAttachment,\n }),\n };\n },\n findAllByLectureId() {\n return {\n subscribe: (fn: (value: any) => void) =>\n fn({\n body: [...attachments],\n }),\n };\n },\n update() {\n return {\n subscribe: (fn: (value: any) => void) =>\n fn({\n body: {\n id: 52,\n name: 'TestFile',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF3.pdf',\n version: 2,\n uploadDate: moment('2019-05-07T08:49:59+02:00'),\n attachmentType: 'FILE',\n } as Attachment,\n }),\n };\n },\n delete() {\n return {\n subscribe: (fn: (value: any) => void) =>\n fn({\n body: newAttachment,\n }),\n };\n },\n },\n },\n {\n provide: FileService,\n useValue: {\n downloadFileWithAccessToken() {\n return {\n subscribe: (fn: (value: any) => void) =>\n fn({\n body: new Window(),\n }),\n };\n },\n },\n },\n ],\n })\n .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(LectureAttachmentsComponent);\n comp = fixture.componentInstance;\n fileUploaderService = TestBed.inject(FileUploaderService);\n });\n });\n\n afterEach(() => {\n comp.attachments = [...attachments];\n });\n\n it('should accept file and add attachment to list', fakeAsync(() => {\n fixture.detectChanges();\n const addAttachmentButton = fixture.debugElement.query(By.css('#add-attachment'));\n expect(comp.attachmentToBeCreated).to.be.undefined;\n expect(addAttachmentButton).to.exist;\n addAttachmentButton.nativeElement.click();\n fixture.detectChanges();\n const fakeBlob = new Blob([''], { type: 'application/pdf' });\n fakeBlob['name'] = 'Test-File.pdf';\n comp.attachmentFile = fakeBlob;\n const uploadAttachmentButton = fixture.debugElement.query(By.css('#upload-attachment'));\n expect(uploadAttachmentButton).to.exist;\n expect(comp.attachmentToBeCreated).to.exist;\n comp.attachmentToBeCreated!.name = 'Test File Name';\n spyOn(fileUploaderService, 'uploadFile').and.returnValue(Promise.resolve({ path: 'test' }));\n uploadAttachmentButton.nativeElement.click();\n\n fixture.detectChanges();\n tick();\n expect(comp.attachments.length).to.equal(3);\n }));\n\n it('should not accept too large file', fakeAsync(() => {\n fixture.detectChanges();\n const addAttachmentButton = fixture.debugElement.query(By.css('#add-attachment'));\n expect(comp.attachmentToBeCreated).to.be.undefined;\n expect(addAttachmentButton).to.exist;\n addAttachmentButton.nativeElement.click();\n fixture.detectChanges();\n const fakeBlob = {};\n fakeBlob['name'] = 'Test-File.pdf';\n fakeBlob['size'] = 100000000000000000;\n comp.attachmentFile = fakeBlob as Blob;\n const uploadAttachmentButton = fixture.debugElement.query(By.css('#upload-attachment'));\n expect(uploadAttachmentButton).to.exist;\n expect(comp.attachmentToBeCreated).to.exist;\n comp.attachmentToBeCreated!.name = 'Test File Name';\n uploadAttachmentButton.nativeElement.click();\n tick();\n fixture.detectChanges();\n const fileAlert = fixture.debugElement.query(By.css('#too-large-file-alert'));\n expect(comp.attachments.length).to.equal(2);\n expect(fileAlert).to.exist;\n }));\n\n it('should exit saveAttachment', fakeAsync(() => {\n fixture.detectChanges();\n comp.attachmentToBeCreated = undefined;\n comp.saveAttachment();\n expect(comp.attachmentToBeCreated).to.deep.equal({\n lecture: comp.lecture,\n attachmentType: AttachmentType.FILE,\n version: 0,\n uploadDate: comp.attachmentToBeCreated!.uploadDate,\n } as Attachment);\n }));\n\n it('should create Attachment', fakeAsync(() => {\n fixture.detectChanges();\n comp.attachmentToBeCreated = {\n id: 1,\n lecture: comp.lecture,\n attachmentType: AttachmentType.FILE,\n version: 1,\n uploadDate: moment(),\n } as Attachment;\n comp.notificationText = 'wow how did i get here';\n comp.saveAttachment();\n expect(comp.attachments[1].version).to.equal(2);\n }));\n\n it('should edit attachment', fakeAsync(() => {\n fixture.detectChanges();\n comp.attachmentToBeCreated = undefined;\n expect(comp.attachmentToBeCreated).to.equal(undefined);\n comp.editAttachment(newAttachment);\n expect(comp.attachmentToBeCreated).to.equal(newAttachment);\n expect(comp.attachmentBackup).to.deep.equal(newAttachment);\n }));\n\n it('should delete attachment', fakeAsync(() => {\n fixture.detectChanges();\n const toDelete = {\n id: 52,\n name: 'test2',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF3.pdf',\n version: 1,\n uploadDate: moment('2019-05-07T08:49:59+02:00'),\n attachmentType: 'FILE',\n } as Attachment;\n comp.deleteAttachment(toDelete);\n expect(comp.attachments.length).to.equal(1);\n }));\n\n it('should call cancel', fakeAsync(() => {\n fixture.detectChanges();\n const toCancel = {\n id: 52,\n name: 'test34',\n link: '/api/files/attachments/lecture/4/Mein_Test_PDF34.pdf',\n version: 5,\n uploadDate: moment('2019-05-07T08:49:59+02:00'),\n attachmentType: 'FILE',\n } as Attachment;\n comp.attachmentBackup = toCancel;\n comp.cancel();\n expect(comp.attachments[1]).to.deep.equal(toCancel);\n }));\n\n it('should download attachment', fakeAsync(() => {\n fixture.detectChanges();\n comp.isDownloadingAttachmentLink = undefined;\n expect(comp.isDownloadingAttachmentLink).to.equal(undefined);\n comp.downloadAttachment('https://my/own/download/url');\n expect(comp.isDownloadingAttachmentLink).to.equal(undefined);\n }));\n\n it('should set lecture attachment', fakeAsync(() => {\n fixture.detectChanges();\n const myBlob1 = { size: 1024, name: '/api/files/attachments/lecture/4/NewTest34.pdf' };\n const myBlob2 = { size: 1024, name: '/api/files/attachments/lecture/4/NewTest100.pdf' };\n const object = {\n target: {\n files: [myBlob1, myBlob2],\n },\n };\n comp.attachmentToBeCreated = newAttachment;\n comp.setLectureAttachment(object);\n\n expect(comp.attachmentFile).to.deep.equal(myBlob1);\n expect(comp.attachmentToBeCreated.link).to.equal(myBlob1.name);\n }));\n});\n" }, { "alpha_fraction": 0.5331599712371826, "alphanum_fraction": 0.5431296229362488, "avg_line_length": 51.037593841552734, "blob_id": "d9d408c93dafcd532a0b58955525dd24d87a0273", "content_id": "4d86ed0e6ef53764649a918ddef4fed6e1d9da0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Maven POM", "length_bytes": 6921, "license_type": "permissive", "max_line_length": 125, "num_lines": 133, "path": "/src/main/resources/templates/java/test/projectTemplate/pom.xml", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>${packageName}</groupId>\n <artifactId>${exerciseNamePomXml}-Tests</artifactId>\n <packaging>${packaging}</packaging>\n <version>1.0</version>\n <name>${exerciseName} Tests</name>\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <!--%static-code-analysis-start%-->\n <scaConfigDirectory>${project.basedir}/staticCodeAnalysisConfig</scaConfigDirectory>\n <analyzeTests>false</analyzeTests>\n <!--%static-code-analysis-stop%-->\n\t</properties>\n <dependencies>\n <dependency>\n <!-- Comes with JUnit 5, AssertJ and Hamcrest. JUnit 4 (JUnit 5 Vintage) or jqwik need to be added explicitly -->\n <groupId>de.tum.in.ase</groupId>\n <artifactId>artemis-java-test-sandbox</artifactId>\n <version>1.5.3</version>\n </dependency>\n </dependencies>\n <build>\n <sourceDirectory>${project.basedir}${studentWorkingDirectory}</sourceDirectory>\n <!--%non-sequential-start%-->\n <testSourceDirectory>${project.basedir}/test</testSourceDirectory>\n <testResources>\n <testResource>\n <directory>${project.basedir}/test</directory>\n </testResource>\n </testResources>\n <!--%non-sequential-stop%-->\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.1</version>\n <configuration>\n <source>16</source>\n <target>16</target>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>3.0.0-M5</version>\n <configuration>\n <argLine>-Dfile.encoding=UTF-8</argLine>\n </configuration>\n </plugin>\n <!--%static-code-analysis-start%-->\n <plugin>\n <groupId>com.github.spotbugs</groupId>\n <artifactId>spotbugs-maven-plugin</artifactId>\n <version>4.1.4</version>\n <configuration>\n <!-- Do not analyze the files in the test directory -->\n <includeTests>${analyzeTests}</includeTests>\n <xmlOutput>true</xmlOutput>\n <!-- Do not report bugs matching the rules defined in this file -->\n <excludeFilterFile>${scaConfigDirectory}/spotbugs-exclusions.xml</excludeFilterFile>\n <!-- Only include bugs matching the rules defined in this file -->\n <includeFilterFile/>\n <!-- Analysis with high effort are more precise and can potentially find more bugs at the cost of\n memory consumption and computation time. See https://spotbugs.readthedocs.io/en/stable/effort.html\n for more information -->\n <effort>Default</effort>\n <!-- Minimum bug severity to report. Low reports all bugs -->\n <threshold>Low</threshold>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-checkstyle-plugin</artifactId>\n <version>3.1.1</version>\n <dependencies>\n <dependency>\n <groupId>com.puppycrawl.tools</groupId>\n <artifactId>checkstyle</artifactId>\n <version>8.36.2</version>\n </dependency>\n </dependencies>\n <configuration>\n <!-- Do not analyze the files in the test directory -->\n <includeTestSourceDirectory>${analyzeTests}</includeTestSourceDirectory>\n <!-- Use the Artemis default configuration. Two other predefined rulesets are available:\n Add sun_checks.xml to check for the official Oracle code conventions or add google_checks.xml to\n check for the Google's Java Style Guide -->\n <configLocation>${scaConfigDirectory}/checkstyle-configuration.xml</configLocation>\n <!-- No documentation and not needed -->\n <enableRSS>false</enableRSS>\n </configuration>\n </plugin>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-pmd-plugin</artifactId>\n <version>3.14.0</version>\n <dependencies>\n <dependency>\n <groupId>net.sourceforge.pmd</groupId>\n <artifactId>pmd-core</artifactId>\n <version>6.29.0</version>\n </dependency>\n <dependency>\n <groupId>net.sourceforge.pmd</groupId>\n <artifactId>pmd-java</artifactId>\n <version>6.29.0</version>\n </dependency>\n </dependencies>\n <configuration>\n <!-- Do not analyze the files in the test directory -->\n <includeTests>${analyzeTests}</includeTests>\n <!-- Bugs reported have at least this priority. 1 is the highest and 5 is the lowest priority -->\n <minimumPriority>5</minimumPriority>\n <!-- Add multiple rulesets for fine-grained control of file exclusions per rule -->\n <rulesets>\n <ruleset>${scaConfigDirectory}/pmd-configuration.xml</ruleset>\n </rulesets>\n <!-- Minimum amount of duplicated tokens triggering the copy-paste detection -->\n <minimumTokens>60</minimumTokens>\n <!-- Ignore literal value differences when evaluating a duplicate block.\n If true, foo=42; and foo=43; will be seen as equivalent -->\n <ignoreLiterals>true</ignoreLiterals>\n <!-- Similar to ignoreLiterals but for identifiers, i.e. variable names, methods names.\n If activated, most tokens will be ignored so minimumTokens must be lowered significantly -->\n <ignoreIdentifiers>false</ignoreIdentifiers>\n </configuration>\n </plugin>\n <!--%static-code-analysis-stop%-->\n </plugins>\n </build>\n</project>\n" }, { "alpha_fraction": 0.6676815152168274, "alphanum_fraction": 0.6687471270561218, "avg_line_length": 44.93706130981445, "blob_id": "11486b28a681727e4423361d7a628031b0ebda4f", "content_id": "58c3fc024a5c1f3f081313c0009034af3b9c23fc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6569, "license_type": "permissive", "max_line_length": 155, "num_lines": 143, "path": "/src/test/javascript/spec/component/course/course-detail.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { ActivatedRoute } from '@angular/router';\nimport { of, throwError } from 'rxjs';\nimport { ArtemisTestModule } from '../../test.module';\nimport { CourseDetailComponent } from 'app/course/manage/course-detail.component';\nimport { TranslateService } from '@ngx-translate/core';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks';\nimport { SecuredImageComponent } from 'app/shared/image/secured-image.component';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport * as moment from 'moment';\nimport { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { JhiAlertService, JhiTranslateDirective } from 'ng-jhipster';\nimport { MockRouterLinkDirective } from '../lecture-unit/lecture-unit-management.component.spec';\nimport { DeleteButtonDirective } from 'app/shared/delete-dialog/delete-button.directive';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { CourseExamArchiveButtonComponent } from 'app/shared/components/course-exam-archive-button/course-exam-archive-button.component';\nimport { HasAnyAuthorityDirective } from 'app/shared/auth/has-any-authority.directive';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { HttpErrorResponse, HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { JhiEventManager } from 'ng-jhipster';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('Course Management Detail Component', () => {\n let comp: CourseDetailComponent;\n let fixture: ComponentFixture<CourseDetailComponent>;\n let courseService: CourseManagementService;\n let eventManager: JhiEventManager;\n let alertService: JhiAlertService;\n const course = { id: 123, title: 'Course Title', isAtLeastInstructor: true, endDate: moment().subtract(5, 'minutes'), courseArchivePath: 'some-path' };\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [\n CourseDetailComponent,\n MockComponent(SecuredImageComponent),\n MockRouterLinkDirective,\n MockPipe(ArtemisTranslatePipe),\n MockDirective(DeleteButtonDirective),\n MockComponent(AlertErrorComponent),\n MockDirective(AlertComponent),\n MockPipe(ArtemisDatePipe),\n MockDirective(JhiTranslateDirective),\n MockComponent(CourseExamArchiveButtonComponent),\n MockDirective(HasAnyAuthorityDirective),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: new MockActivatedRoute() },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n MockProvider(JhiAlertService),\n MockProvider(NgbModal),\n MockProvider(CourseManagementService),\n ],\n }).compileComponents();\n fixture = TestBed.createComponent(CourseDetailComponent);\n comp = fixture.componentInstance;\n courseService = fixture.debugElement.injector.get(CourseManagementService);\n alertService = TestBed.inject(JhiAlertService);\n eventManager = fixture.debugElement.injector.get(JhiEventManager);\n });\n\n beforeEach(fakeAsync(() => {\n const route = TestBed.inject(ActivatedRoute);\n route.data = of({ course });\n\n comp.ngOnInit();\n tick();\n }));\n\n afterEach(function () {\n sinon.restore();\n });\n\n describe('OnInit for course that has an archive', () => {\n it('Should call registerChangeInCourses on init', () => {\n const registerSpy = sinon.spy(comp, 'registerChangeInCourses');\n\n fixture.detectChanges();\n comp.ngOnInit();\n expect(comp.course).to.deep.equal(course);\n expect(registerSpy).to.have.been.called;\n });\n });\n\n describe('Register for course', () => {\n it('should alert user if registration is successful', () => {\n const registerStub = sinon.stub(courseService, 'registerForCourse');\n const alertStub = sinon.stub(alertService, 'info');\n\n registerStub.returns(of(new HttpResponse({ body: { guidedTourSettings: [] } })));\n\n comp.registerForCourse();\n\n expect(registerStub).to.have.been.calledWith(course.id);\n expect(alertStub).to.have.been.calledWith(`Registered user for course ${course.title}`);\n });\n\n it('should alert user if registration fails', () => {\n const registerStub = sinon.stub(courseService, 'registerForCourse');\n const alertStub = sinon.stub(alertService, 'error');\n const headers = new HttpHeaders().append('X-artemisApp-message', 'errorMessage');\n\n registerStub.returns(throwError(new HttpErrorResponse({ headers })));\n\n comp.registerForCourse();\n\n expect(registerStub).to.have.been.calledWith(course.id);\n expect(alertStub).to.have.been.calledWith(`errorMessage`);\n });\n });\n\n it('should destroy event subscriber onDestroy', () => {\n comp.ngOnDestroy();\n expect(eventManager.destroy).to.have.been.called;\n });\n\n it('should broadcast course modification on delete', () => {\n const deleteStub = sinon.stub(courseService, 'delete');\n deleteStub.returns(of(new HttpResponse({})));\n\n const courseId = 444;\n comp.deleteCourse(courseId);\n\n expect(deleteStub).to.have.been.calledWith(courseId);\n expect(eventManager.broadcast).to.have.been.calledWith({\n name: 'courseListModification',\n content: 'Deleted an course',\n });\n });\n});\n" }, { "alpha_fraction": 0.6771210432052612, "alphanum_fraction": 0.6787294149398804, "avg_line_length": 42.6315803527832, "blob_id": "187b5663424d7d6d902112f4be0fa641f2862629", "content_id": "570c99c3f770b7d43aa39b52ffd6c03333b02883", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2487, "license_type": "permissive", "max_line_length": 158, "num_lines": 57, "path": "/src/test/javascript/spec/component/about-us/about-us.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { TranslatePipeMock } from '../../helpers/mocks/service/mock-translate.service';\nimport { ProfileService } from 'app/shared/layouts/profiles/profile.service';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { AboutUsComponent } from 'app/core/about-us/about-us.component';\nimport { ActivatedRoute } from '@angular/router';\nimport { StaticContentService } from 'app/shared/service/static-content.service';\nimport * as sinon from 'sinon';\nimport { AboutUsModel } from 'app/core/about-us/models/about-us-model';\nimport { BehaviorSubject, of } from 'rxjs';\nimport { MockProvider } from 'ng-mocks';\nimport { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('AboutUsComponent', () => {\n let fixture: ComponentFixture<AboutUsComponent>;\n const sandbox = sinon.createSandbox();\n\n const route = ({ snapshot: { url: ['about'] } } as any) as ActivatedRoute;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule],\n declarations: [AboutUsComponent, TranslatePipeMock],\n providers: [{ provide: ActivatedRoute, useValue: route }, MockProvider(ProfileService), MockProvider(StaticContentService)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(AboutUsComponent);\n });\n });\n\n afterEach(function () {\n sandbox.restore();\n });\n\n it('load the json file from resources', fakeAsync(() => {\n const staticContentService = TestBed.inject(StaticContentService);\n const profileService = TestBed.inject(ProfileService);\n\n const getStaticJsonFromArtemisServerStub = sandbox.stub(staticContentService, 'getStaticJsonFromArtemisServer').returns(of(new AboutUsModel([], [])));\n const getProfileInfoSub = sandbox.stub(profileService, 'getProfileInfo');\n getProfileInfoSub.returns(\n new BehaviorSubject<ProfileInfo | undefined>({ inProduction: false, sshCloneURLTemplate: 'ssh://[email protected]:1234/' } as ProfileInfo),\n );\n\n fixture.detectChanges();\n tick();\n fixture.whenStable().then(() => {\n expect(getStaticJsonFromArtemisServerStub).to.have.been.calledOnce;\n });\n }));\n});\n" }, { "alpha_fraction": 0.7149876952171326, "alphanum_fraction": 0.7186732292175293, "avg_line_length": 49.5036506652832, "blob_id": "adcf5f6d59ee4151ee988e6e6d8775f29994183b", "content_id": "b32fe057d03c24ac666540d70e2d78e245251125", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13838, "license_type": "permissive", "max_line_length": 172, "num_lines": 274, "path": "/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { TranslateModule } from '@ngx-translate/core';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { DebugElement } from '@angular/core';\nimport { SinonStub, stub } from 'sinon';\nimport { of, Subject } from 'rxjs';\nimport * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service';\nimport { ParticipationWebsocketService } from 'app/overview/participation-websocket.service';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { ExerciseSubmissionState, ProgrammingSubmissionService, ProgrammingSubmissionState } from 'app/exercises/programming/participate/programming-submission.service';\nimport { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module';\nimport { ProgrammingExerciseInstructorSubmissionStateComponent } from 'app/exercises/programming/shared/actions/programming-exercise-instructor-submission-state.component';\nimport { triggerChanges } from '../../helpers/utils/general.utils';\nimport { BuildRunState, ProgrammingBuildRunService } from 'app/exercises/programming/participate/programming-build-run.service';\nimport { MockProgrammingBuildRunService } from '../../helpers/mocks/service/mock-programming-build-run.service';\nimport { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service';\nimport { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service';\nimport { ProgrammingExercise } from 'app/entities/programming-exercise.model';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('ProgrammingExerciseInstructorSubmissionStateComponent', () => {\n let comp: ProgrammingExerciseInstructorSubmissionStateComponent;\n let fixture: ComponentFixture<ProgrammingExerciseInstructorSubmissionStateComponent>;\n let debugElement: DebugElement;\n let submissionService: ProgrammingSubmissionService;\n let buildRunService: ProgrammingBuildRunService;\n\n let getExerciseSubmissionStateStub: SinonStub;\n let getExerciseSubmissionStateSubject: Subject<ExerciseSubmissionState>;\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n let getBuildRunStateStub: SinonStub;\n let getBuildRunStateSubject: Subject<BuildRunState>;\n\n let triggerAllStub: SinonStub;\n let triggerParticipationsStub: SinonStub;\n\n const exercise = { id: 20 } as Exercise;\n\n const resultEtaId = '#result-eta';\n\n const getResultEtaContainer = () => {\n return debugElement.query(By.css(resultEtaId));\n };\n\n beforeEach(async () => {\n return TestBed.configureTestingModule({\n imports: [TranslateModule.forRoot(), ArtemisTestModule, ArtemisProgrammingExerciseActionsModule],\n providers: [\n JhiLanguageHelper,\n { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService },\n { provide: ProgrammingBuildRunService, useClass: MockProgrammingBuildRunService },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: FeatureToggleService, useClass: MockFeatureToggleService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ProgrammingExerciseInstructorSubmissionStateComponent);\n comp = fixture.componentInstance;\n debugElement = fixture.debugElement;\n\n submissionService = debugElement.injector.get(ProgrammingSubmissionService);\n buildRunService = debugElement.injector.get(ProgrammingBuildRunService);\n\n getExerciseSubmissionStateSubject = new Subject<ExerciseSubmissionState>();\n getExerciseSubmissionStateStub = stub(submissionService, 'getSubmissionStateOfExercise').returns(getExerciseSubmissionStateSubject);\n\n getBuildRunStateSubject = new Subject<BuildRunState>();\n getBuildRunStateStub = stub(buildRunService, 'getBuildRunUpdates').returns(getBuildRunStateSubject);\n\n triggerAllStub = stub(submissionService, 'triggerInstructorBuildForParticipationsOfExercise').returns(of());\n triggerParticipationsStub = stub(submissionService, 'triggerInstructorBuildForAllParticipationsOfExercise').returns(of());\n });\n });\n\n afterEach(() => {\n getExerciseSubmissionStateStub.restore();\n triggerAllStub.restore();\n getBuildRunStateStub.restore();\n triggerParticipationsStub.restore();\n });\n\n const getTriggerAllButton = () => {\n const triggerButton = debugElement.query(By.css('#trigger-all-button button'));\n return triggerButton ? triggerButton.nativeElement : null;\n };\n\n const getTriggerFailedButton = () => {\n const triggerButton = debugElement.query(By.css('#trigger-failed-button button'));\n return triggerButton ? triggerButton.nativeElement : null;\n };\n\n const getBuildState = () => {\n const buildState = debugElement.query(By.css('#build-state'));\n return buildState ? buildState.nativeElement : null;\n };\n\n it('should not show the component before the build summary is retrieved', () => {\n expect(getTriggerAllButton()).to.be.null;\n expect(getTriggerFailedButton()).to.be.null;\n expect(getBuildState()).to.be.null;\n });\n\n it('should show the result eta if there is at least one building submission', fakeAsync(() => {\n const isBuildingSubmissionState = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 },\n 4: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 5 },\n } as ExerciseSubmissionState;\n comp.exercise = exercise as ProgrammingExercise;\n\n triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise });\n getExerciseSubmissionStateSubject.next(isBuildingSubmissionState);\n\n tick(500);\n\n fixture.detectChanges();\n\n const resultEta = getResultEtaContainer();\n expect(resultEta).to.exist;\n }));\n\n it('should not show the result eta if there is no building submission', fakeAsync(() => {\n const isNotBuildingSubmission = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 },\n 4: { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: undefined, participationId: 5 },\n } as ExerciseSubmissionState;\n comp.exercise = exercise as ProgrammingExercise;\n\n triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise });\n getExerciseSubmissionStateSubject.next(isNotBuildingSubmission);\n\n tick(500);\n\n fixture.detectChanges();\n\n const resultEta = getResultEtaContainer();\n expect(resultEta).not.to.exist;\n }));\n\n it('should show & enable the trigger all button and the build state once the build summary is loaded', fakeAsync(() => {\n const noPendingSubmissionState = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 },\n 4: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 5 },\n } as ExerciseSubmissionState;\n const compressedSummary = { [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 2 };\n comp.exercise = exercise as ProgrammingExercise;\n\n triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise });\n getExerciseSubmissionStateSubject.next(noPendingSubmissionState);\n\n // Wait for a second as the view is updated with a debounce.\n tick(500);\n\n fixture.detectChanges();\n\n expect(getExerciseSubmissionStateStub).to.have.been.calledOnceWithExactly(exercise.id);\n\n expect(comp.hasFailedSubmissions).to.be.false;\n expect(comp.isBuildingFailedSubmissions).to.be.false;\n expect(comp.buildingSummary).to.deep.equal(compressedSummary);\n\n expect(getTriggerAllButton()).to.exist;\n expect(getTriggerAllButton().disabled).to.be.false;\n expect(getTriggerFailedButton()).to.exist;\n expect(getTriggerFailedButton().disabled).to.be.true;\n expect(getBuildState()).to.exist;\n }));\n\n it('should show & enable both buttons and the build state once the build summary is loaded when a failed submission exists', fakeAsync(() => {\n const noPendingSubmissionState = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 55 },\n 4: { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: undefined, participationId: 76 },\n 5: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 76 },\n } as ExerciseSubmissionState;\n const compressedSummary = {\n [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 1,\n [ProgrammingSubmissionState.HAS_FAILED_SUBMISSION]: 1,\n [ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION]: 1,\n };\n comp.exercise = exercise as ProgrammingExercise;\n\n triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise });\n getExerciseSubmissionStateSubject.next(noPendingSubmissionState);\n\n // Wait for a second as the view is updated with a debounce.\n tick(500);\n\n fixture.detectChanges();\n\n expect(getExerciseSubmissionStateStub).to.have.been.calledOnceWithExactly(exercise.id);\n\n expect(comp.hasFailedSubmissions).to.be.true;\n expect(comp.isBuildingFailedSubmissions).to.be.false;\n expect(comp.buildingSummary).to.deep.equal(compressedSummary);\n\n expect(getResultEtaContainer()).to.exist;\n expect(getTriggerAllButton()).to.exist;\n expect(getTriggerAllButton().disabled).to.be.false;\n expect(getTriggerFailedButton()).to.exist;\n expect(getTriggerFailedButton().disabled).to.be.false;\n expect(getBuildState()).to.exist;\n }));\n\n it('should trigger the appropriate service method on trigger failed and set the isBuildingFailedSubmissionsState until the request returns a response', () => {\n const failedSubmissionParticipationIds = [333];\n const triggerInstructorBuildForParticipationsOfExerciseSubject = new Subject<void>();\n triggerAllStub.returns(triggerInstructorBuildForParticipationsOfExerciseSubject);\n const getFailedSubmissionParticipationsForExerciseStub = stub(submissionService, 'getSubmissionCountByType').returns(failedSubmissionParticipationIds);\n // Component must have at least one failed submission for the button to be enabled.\n comp.exercise = exercise as ProgrammingExercise;\n comp.buildingSummary = { [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 1, [ProgrammingSubmissionState.HAS_FAILED_SUBMISSION]: 1 };\n comp.hasFailedSubmissions = true;\n\n fixture.detectChanges();\n\n const triggerButton = getTriggerFailedButton();\n expect(triggerButton).to.exist;\n expect(triggerButton.disabled).to.be.false;\n\n // Button is clicked.\n triggerButton.click();\n\n expect(comp.isBuildingFailedSubmissions).to.be.true;\n expect(getFailedSubmissionParticipationsForExerciseStub).to.have.been.calledOnceWithExactly(comp.exercise.id, ProgrammingSubmissionState.HAS_FAILED_SUBMISSION);\n expect(triggerAllStub).to.have.been.calledOnceWithExactly(comp.exercise.id, failedSubmissionParticipationIds);\n\n fixture.detectChanges();\n\n // Now the request returns a response.\n triggerInstructorBuildForParticipationsOfExerciseSubject.next(undefined);\n\n fixture.detectChanges();\n\n expect(comp.isBuildingFailedSubmissions).to.be.false;\n });\n\n it('should disable the trigger all button while a build is running and re-enable it when it is complete', fakeAsync(() => {\n const isBuildingSubmissionState = {\n 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 },\n 4: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 5 },\n } as ExerciseSubmissionState;\n comp.exercise = exercise as ProgrammingExercise;\n\n triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise });\n getExerciseSubmissionStateSubject.next(isBuildingSubmissionState);\n\n // Wait for a second as the view is updated with a debounce.\n tick(500);\n\n fixture.detectChanges();\n\n expect(getTriggerAllButton().disabled).to.be.false;\n\n getBuildRunStateSubject.next(BuildRunState.RUNNING);\n fixture.detectChanges();\n\n expect(getTriggerAllButton().disabled).to.be.true;\n\n getBuildRunStateSubject.next(BuildRunState.COMPLETED);\n fixture.detectChanges();\n\n expect(getTriggerAllButton().disabled).to.be.false;\n }));\n});\n" }, { "alpha_fraction": 0.7677063941955566, "alphanum_fraction": 0.7699082493782043, "avg_line_length": 39.07352828979492, "blob_id": "5d83ffcab0e3f08bf20504a3e286b4fa1b3eba97", "content_id": "eedbd323e2fb93562b8c40a954e53268176d0d4e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2725, "license_type": "permissive", "max_line_length": 174, "num_lines": 68, "path": "/src/main/java/de/tum/in/www1/artemis/service/connectors/athene/TextAssessmentConflictService.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service.connectors.athene;\n\nimport java.util.List;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.context.annotation.Profile;\nimport org.springframework.stereotype.Service;\nimport org.springframework.web.client.RestTemplate;\n\nimport de.tum.in.www1.artemis.exception.NetworkingError;\nimport de.tum.in.www1.artemis.service.dto.FeedbackConflictResponseDTO;\nimport de.tum.in.www1.artemis.service.dto.TextFeedbackConflictRequestDTO;\n\n@Service\n@Profile(\"athene\")\npublic class TextAssessmentConflictService {\n\n private final Logger log = LoggerFactory.getLogger(TextAssessmentConflictService.class);\n\n @Value(\"${artemis.athene.url}\")\n private String atheneUrl;\n\n private final AtheneConnector<Request, Response> connector;\n\n public TextAssessmentConflictService(@Qualifier(\"atheneRestTemplate\") RestTemplate atheneRestTemplate) {\n connector = new AtheneConnector<>(log, atheneRestTemplate, Response.class);\n }\n\n // region Request/Response DTOs\n private static class Request {\n\n public List<TextFeedbackConflictRequestDTO> feedbackWithTextBlock;\n\n public Long exerciseId;\n\n Request(List<TextFeedbackConflictRequestDTO> textFeedbackConflictRequestDTOS, long exerciseId) {\n this.feedbackWithTextBlock = textFeedbackConflictRequestDTOS;\n this.exerciseId = exerciseId;\n }\n }\n\n private static class Response {\n\n public List<FeedbackConflictResponseDTO> feedbackInconsistencies;\n }\n // endregion\n\n /**\n * Calls the remote feedback consistency service to check consistencies between feedback for an automatically assessed text exercise.\n *\n * @param textFeedbackConflictRequestDTOS list of request objects\n * @param exerciseId exercise id that feedback belong to\n * @param maxRetries number of retries before the request will be canceled\n * @return A list of FeedbackConflictResponseDTO objects\n * @throws NetworkingError if the request isn't successful\n */\n public List<FeedbackConflictResponseDTO> checkFeedbackConsistencies(List<TextFeedbackConflictRequestDTO> textFeedbackConflictRequestDTOS, long exerciseId, int maxRetries)\n throws NetworkingError {\n log.info(\"Calling Remote Service to check feedback consistencies.\");\n final Request request = new Request(textFeedbackConflictRequestDTOS, exerciseId);\n final Response response = connector.invokeWithRetry(atheneUrl + \"/feedback_consistency\", request, maxRetries);\n\n return response.feedbackInconsistencies;\n }\n}\n" }, { "alpha_fraction": 0.7815699577331543, "alphanum_fraction": 0.7815699577331543, "avg_line_length": 28.299999237060547, "blob_id": "0843f2f63e2411dd9083e12cd22ff53d4a5cb4a2", "content_id": "2cccd74b3cacf4b9d48a0b63f4e76f2d86474857", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 293, "license_type": "permissive", "max_line_length": 98, "num_lines": 10, "path": "/SECURITY.md", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "# Security Policy\n\n## Supported Versions\n\nCurrently, only the latest version of Artemis is supported. \nWe do **not** provide security patches for older versions.\n\n## Reporting a Vulnerability\n\nPlease contact the Artemis Maintainers via email at [email protected] to report (potential) vulnerabilities.\n" }, { "alpha_fraction": 0.6486780643463135, "alphanum_fraction": 0.6489891409873962, "avg_line_length": 46.27941131591797, "blob_id": "8828363a27f61d9d67253c4b42bef37a0722ac25", "content_id": "a675256b7568801c9c08325d9b58bf4d4df679b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6430, "license_type": "permissive", "max_line_length": 156, "num_lines": 136, "path": "/src/main/webapp/app/lecture/lecture-unit/lecture-unit-management/lectureUnit.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { LectureUnit, LectureUnitType } from 'app/entities/lecture-unit/lectureUnit.model';\nimport { SERVER_API_URL } from 'app/app.constants';\nimport { HttpClient, HttpResponse } from '@angular/common/http';\nimport { Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\nimport * as moment from 'moment';\nimport { Injectable } from '@angular/core';\nimport { AttachmentUnit } from 'app/entities/lecture-unit/attachmentUnit.model';\nimport { AttachmentService } from 'app/lecture/attachment.service';\nimport { ExerciseUnit } from 'app/entities/lecture-unit/exerciseUnit.model';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\n\ntype EntityArrayResponseType = HttpResponse<LectureUnit[]>;\n\n@Injectable({\n providedIn: 'root',\n})\nexport class LectureUnitService {\n private resourceURL = SERVER_API_URL + 'api';\n\n constructor(private httpClient: HttpClient, private attachmentService: AttachmentService, private exerciseService: ExerciseService) {}\n\n updateOrder(lectureId: number, lectureUnits: LectureUnit[]): Observable<HttpResponse<LectureUnit[]>> {\n // need to remove participations from exercise units to prevent circular structure failure\n lectureUnits = lectureUnits.map((lectureUnit) => {\n if (lectureUnit.type === LectureUnitType.EXERCISE && (lectureUnit as ExerciseUnit).exercise) {\n (lectureUnit as ExerciseUnit).exercise!.studentParticipations = undefined;\n (lectureUnit as ExerciseUnit).exercise!.tutorParticipations = undefined;\n }\n return lectureUnit;\n });\n return this.httpClient\n .put<LectureUnit[]>(`${this.resourceURL}/lectures/${lectureId}/lecture-units-order`, lectureUnits, { observe: 'response' })\n .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServerResponse(res)));\n }\n\n delete(lectureUnitId: number, lectureId: number) {\n return this.httpClient.delete(`${this.resourceURL}/lectures/${lectureId}/lecture-units/${lectureUnitId}`, { observe: 'response' });\n }\n\n convertDateFromClient<T extends LectureUnit>(lectureUnit: T): T {\n if (lectureUnit.type === LectureUnitType.ATTACHMENT) {\n if ((<AttachmentUnit>lectureUnit).attachment) {\n (<AttachmentUnit>lectureUnit).attachment = this.attachmentService.convertDateFromClient((<AttachmentUnit>lectureUnit).attachment!);\n return lectureUnit;\n }\n } else if (lectureUnit.type === LectureUnitType.EXERCISE) {\n if ((<ExerciseUnit>lectureUnit).exercise) {\n (<ExerciseUnit>lectureUnit).exercise = this.exerciseService.convertDateFromClient((<ExerciseUnit>lectureUnit).exercise!);\n return lectureUnit;\n }\n }\n return Object.assign({}, lectureUnit, {\n releaseDate: lectureUnit.releaseDate && moment(lectureUnit.releaseDate).isValid() ? lectureUnit.releaseDate.toJSON() : undefined,\n });\n }\n\n convertDateArrayFromClient<T extends LectureUnit>(lectureUnits: T[]): T[] {\n if (lectureUnits && lectureUnits.length > 0) {\n for (let _i = 0; _i < lectureUnits.length; _i++) {\n lectureUnits[_i] = this.convertDateFromClient(lectureUnits[_i]);\n }\n }\n return lectureUnits;\n }\n\n convertDateFromServerResponse<T extends LectureUnit>(res: HttpResponse<T>): HttpResponse<T> {\n if (res.body) {\n if (res.body.type === LectureUnitType.ATTACHMENT) {\n if ((<AttachmentUnit>res.body).attachment) {\n (<AttachmentUnit>res.body).attachment = this.attachmentService.convertAttachmentDateFromServer((<AttachmentUnit>res.body).attachment);\n }\n } else if (res.body.type === LectureUnitType.EXERCISE) {\n if ((<ExerciseUnit>res.body).exercise) {\n (<ExerciseUnit>res.body).exercise = this.exerciseService.convertExerciseDateFromServer((<ExerciseUnit>res.body).exercise);\n }\n } else {\n res.body.releaseDate = res.body.releaseDate ? moment(res.body.releaseDate) : undefined;\n }\n }\n return res;\n }\n\n convertDateFromServerEntity<T extends LectureUnit>(lectureUnit: T): T {\n if (lectureUnit.type === LectureUnitType.ATTACHMENT) {\n if ((<AttachmentUnit>lectureUnit).attachment) {\n (<AttachmentUnit>lectureUnit).attachment = this.attachmentService.convertAttachmentDateFromServer((<AttachmentUnit>lectureUnit).attachment);\n }\n } else if (lectureUnit.type === LectureUnitType.EXERCISE) {\n if ((<ExerciseUnit>lectureUnit).exercise) {\n (<ExerciseUnit>lectureUnit).exercise = this.exerciseService.convertExerciseDateFromServer((<ExerciseUnit>lectureUnit).exercise);\n }\n } else {\n lectureUnit.releaseDate = lectureUnit.releaseDate ? moment(lectureUnit.releaseDate) : undefined;\n }\n return lectureUnit;\n }\n\n convertDateArrayFromServerResponse<T extends LectureUnit>(res: HttpResponse<T[]>): HttpResponse<T[]> {\n if (res.body) {\n res.body.forEach((lectureUnit: LectureUnit) => {\n this.convertDateFromServerEntity(lectureUnit);\n });\n }\n return res;\n }\n\n convertDateArrayFromServerEntity<T extends LectureUnit>(res: T[]): T[] {\n if (res) {\n res.forEach((lectureUnit: LectureUnit) => {\n this.convertDateFromServerEntity(lectureUnit);\n });\n }\n return res;\n }\n\n getLectureUnitName(lectureUnit: LectureUnit) {\n if (lectureUnit.type === LectureUnitType.ATTACHMENT) {\n return (<AttachmentUnit>lectureUnit)?.attachment?.name;\n } else if (lectureUnit.type === LectureUnitType.EXERCISE) {\n return (<ExerciseUnit>lectureUnit)?.exercise?.title;\n } else {\n return lectureUnit.name;\n }\n }\n\n getLectureUnitReleaseDate(lectureUnit: LectureUnit) {\n if (lectureUnit.type === LectureUnitType.ATTACHMENT) {\n return (<AttachmentUnit>lectureUnit)?.attachment?.releaseDate;\n } else if (lectureUnit.type === LectureUnitType.EXERCISE) {\n return (<ExerciseUnit>lectureUnit)?.exercise?.releaseDate;\n } else {\n return lectureUnit.releaseDate;\n }\n }\n}\n" }, { "alpha_fraction": 0.6339989304542542, "alphanum_fraction": 0.6374146342277527, "avg_line_length": 40.369564056396484, "blob_id": "37d4a8a1af5d99005c7905e188c60e0c6e28dcf2", "content_id": "5f0ebd6a7c286eb6605e160ce0a473a785abe3ca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3806, "license_type": "permissive", "max_line_length": 118, "num_lines": 92, "path": "/src/test/javascript/spec/service/modeling-exercise.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';\nimport { take } from 'rxjs/operators';\nimport { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service';\nimport { UMLDiagramType, ModelingExercise } from 'app/entities/modeling-exercise.model';\nimport { TranslateService } from '@ngx-translate/core';\nimport { MockTranslateService } from '../helpers/mocks/service/mock-translate.service';\nimport { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { routes } from 'app/exercises/modeling/manage/modeling-exercise.route';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { ArtemisModelingExerciseModule } from 'app/exercises/modeling/manage/modeling-exercise.module';\n\ndescribe('ModelingExercise Service', () => {\n let injector: TestBed;\n let service: ModelingExerciseService;\n let httpMock: HttpTestingController;\n let elemDefault: ModelingExercise;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisModelingExerciseModule, HttpClientTestingModule, RouterTestingModule.withRoutes(routes)],\n providers: [\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n ],\n });\n injector = getTestBed();\n service = injector.get(ModelingExerciseService);\n httpMock = injector.get(HttpTestingController);\n\n elemDefault = new ModelingExercise(UMLDiagramType.ComponentDiagram, undefined, undefined);\n });\n\n it('should find an element', async () => {\n const returnedFromService = Object.assign({}, elemDefault);\n service\n .find(123)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault }));\n\n const req = httpMock.expectOne({ method: 'GET' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should create a ModelingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n id: 0,\n },\n elemDefault,\n );\n const expected = Object.assign({}, returnedFromService);\n service\n .create(new ModelingExercise(UMLDiagramType.ComponentDiagram, undefined, undefined))\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'POST' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should update a ModelingExercise', async () => {\n const returnedFromService = Object.assign(\n {\n diagramType: 'BBBBBB',\n sampleSolutionModel: 'BBBBBB',\n sampleSolutionExplanation: 'BBBBBB',\n },\n elemDefault,\n );\n\n const expected = Object.assign({}, returnedFromService);\n service\n .update(expected)\n .pipe(take(1))\n .subscribe((resp) => expect(resp).toMatchObject({ body: expected }));\n const req = httpMock.expectOne({ method: 'PUT' });\n req.flush(JSON.stringify(returnedFromService));\n });\n\n it('should delete a ModelingExercise', async () => {\n service.delete(123).subscribe((resp) => expect(resp.ok));\n\n const req = httpMock.expectOne({ method: 'DELETE' });\n req.flush({ status: 200 });\n });\n\n afterEach(() => {\n httpMock.verify();\n });\n});\n" }, { "alpha_fraction": 0.6284998655319214, "alphanum_fraction": 0.6391987204551697, "avg_line_length": 42.49504852294922, "blob_id": "edb78e94e4ebc010b2d6f25b978d5ff61e3b4f8c", "content_id": "4ab2c622cb8eb51447e8b49886f680ce818e5b9d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4393, "license_type": "permissive", "max_line_length": 124, "num_lines": 101, "path": "/src/test/javascript/spec/component/statistics/statistics-average-score-graph.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTestModule } from '../../test.module';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { MomentModule } from 'ngx-moment';\nimport { MockPipe } from 'ng-mocks';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { StatisticsAverageScoreGraphComponent } from 'app/shared/statistics-graph/statistics-average-score-graph.component';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { ChartsModule } from 'ng2-charts';\nimport { TranslateService } from '@ngx-translate/core';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('StatisticsAverageScoreGraphComponent', () => {\n let fixture: ComponentFixture<StatisticsAverageScoreGraphComponent>;\n let component: StatisticsAverageScoreGraphComponent;\n\n const returnValue = [\n { exerciseId: 1, exerciseName: 'BridgePattern', averageScore: 20 },\n { exerciseId: 2, exerciseName: 'AdapterPattern', averageScore: 35 },\n { exerciseId: 3, exerciseName: 'ProxyPattern', averageScore: 40 },\n { exerciseId: 4, exerciseName: 'SingletonPattern', averageScore: 55 },\n { exerciseId: 5, exerciseName: 'ObserverPattern', averageScore: 60 },\n { exerciseId: 6, exerciseName: 'StrategyPattern', averageScore: 75 },\n { exerciseId: 7, exerciseName: 'BuilderPattern', averageScore: 50 },\n { exerciseId: 8, exerciseName: 'StatePattern', averageScore: 100 },\n { exerciseId: 9, exerciseName: 'FarcadePattern', averageScore: 0 },\n { exerciseId: 10, exerciseName: 'VisitorPattern', averageScore: 25 },\n { exerciseId: 11, exerciseName: 'BehaviouralPattern', averageScore: 55 },\n ];\n\n const courseAverageScore = 75;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, RouterTestingModule.withRoutes([]), MomentModule, ChartsModule],\n declarations: [StatisticsAverageScoreGraphComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(StatisticsAverageScoreGraphComponent);\n component = fixture.componentInstance;\n\n component.exerciseAverageScores = returnValue;\n component.courseAverage = courseAverageScore;\n fixture.detectChanges();\n });\n });\n\n it('should initialize', () => {\n const averageScoreCourse = new Array(10).fill(courseAverageScore);\n const averageExerciseScores: number[] = [];\n for (let i = 0; i < 10; i++) {\n averageExerciseScores.push(returnValue[i].averageScore);\n }\n\n // take first 10 exerciseTitles\n expect(component.barChartLabels).to.deep.equal([\n 'BridgePattern',\n 'AdapterPattern',\n 'ProxyPattern',\n 'SingletonPattern',\n 'ObserverPattern',\n 'StrategyPattern',\n 'BuilderPattern',\n 'StatePattern',\n 'FarcadePattern',\n 'VisitorPattern',\n ]);\n expect(component.chartData[0]['data']).to.deep.equal(averageScoreCourse);\n expect(component.chartData[1]['data']).to.deep.equal(averageExerciseScores);\n });\n\n it('should switch time span', () => {\n component.switchTimeSpan(true);\n\n // remove first one and push one to the end\n expect(component.barChartLabels).to.deep.equal([\n 'AdapterPattern',\n 'ProxyPattern',\n 'SingletonPattern',\n 'ObserverPattern',\n 'StrategyPattern',\n 'BuilderPattern',\n 'StatePattern',\n 'FarcadePattern',\n 'VisitorPattern',\n 'BehaviouralPattern',\n ]);\n });\n});\n" }, { "alpha_fraction": 0.801086962223053, "alphanum_fraction": 0.802173912525177, "avg_line_length": 53.117645263671875, "blob_id": "43c7f2e3429af68f5a0894e95a97c2207ea8eacb", "content_id": "437ab060e038d8febc9c75a660de6b2a8b66a6b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 920, "license_type": "permissive", "max_line_length": 149, "num_lines": 17, "path": "/src/main/webapp/app/course/dashboards/instructor-course-dashboard/instructor-course-dashboard.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { RouterModule } from '@angular/router';\nimport { ChartsModule } from 'ng2-charts';\nimport { instructorCourseDashboardRoute } from './instructor-course-dashboard.route';\nimport { InstructorCourseDashboardComponent } from './instructor-course-dashboard.component';\nimport { MomentModule } from 'ngx-moment';\nimport { ClipboardModule } from 'ngx-clipboard';\nimport { ArtemisTutorLeaderboardModule } from 'app/shared/dashboards/tutor-leaderboard/tutor-leaderboard.module';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\n\nconst ENTITY_STATES = instructorCourseDashboardRoute;\n\n@NgModule({\n imports: [ArtemisSharedModule, MomentModule, ClipboardModule, RouterModule.forChild(ENTITY_STATES), ChartsModule, ArtemisTutorLeaderboardModule],\n declarations: [InstructorCourseDashboardComponent],\n})\nexport class ArtemisInstructorCourseStatsDashboardModule {}\n" }, { "alpha_fraction": 0.6561797857284546, "alphanum_fraction": 0.6569288372993469, "avg_line_length": 36.08333206176758, "blob_id": "57a25626a7fe61e5307c812d888ff04d43bd1fac", "content_id": "ec2ed4c273ca997628d033181a604abf97b7913f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1335, "license_type": "permissive", "max_line_length": 107, "num_lines": 36, "path": "/src/main/webapp/app/shared/fingerprint/browser-fingerprint.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { BehaviorSubject } from 'rxjs';\nimport { LocalStorageService } from 'ngx-webstorage';\nconst FingerprintJS = require('@fingerprintjs/fingerprintjs');\nimport { v4 as uuid } from 'uuid';\n\n@Injectable({ providedIn: 'root' })\nexport class BrowserFingerprintService {\n private readonly BROWSER_INSTANCE_KEY = 'instanceIdentifier';\n\n public fingerprint = new BehaviorSubject<string | undefined>(undefined);\n public instanceIdentifier = new BehaviorSubject<string | undefined>(undefined);\n\n constructor(private localStorage: LocalStorageService) {\n this.setFingerprint();\n this.setInstance();\n }\n\n private setFingerprint(): void {\n FingerprintJS.load().then((fp: { get: () => Promise<any> }) => {\n fp.get().then((result) => {\n const visitorId = result.visitorId;\n this.fingerprint.next(visitorId);\n });\n });\n }\n\n private setInstance(): void {\n let instanceIdentifier: string | undefined = this.localStorage.retrieve(this.BROWSER_INSTANCE_KEY);\n if (!instanceIdentifier) {\n instanceIdentifier = uuid();\n this.localStorage.store(this.BROWSER_INSTANCE_KEY, instanceIdentifier);\n }\n this.instanceIdentifier.next(instanceIdentifier);\n }\n}\n" }, { "alpha_fraction": 0.6072383522987366, "alphanum_fraction": 0.6072383522987366, "avg_line_length": 34.4963493347168, "blob_id": "c266ba945cf2650ede954e196d1e7d33c0832deb", "content_id": "881715bcb3c55bdaa826c44a78ebe655bd1b9408", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 4863, "license_type": "permissive", "max_line_length": 147, "num_lines": 137, "path": "/src/main/webapp/app/admin/user-management/user-management-update.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { User } from 'app/core/user/user.model';\nimport { UserService } from 'app/core/user/user.service';\nimport { JhiLanguageHelper } from 'app/core/language/language.helper';\nimport { navigateBack } from 'app/utils/navigation.utils';\nimport { OrganizationManagementService } from 'app/admin/organization-management/organization-management.service';\nimport { OrganizationSelectorComponent } from 'app/shared/organization-selector/organization-selector.component';\nimport { Organization } from 'app/entities/organization.model';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\n\n@Component({\n selector: 'jhi-user-management-update',\n templateUrl: './user-management-update.component.html',\n})\nexport class UserManagementUpdateComponent implements OnInit {\n user: User;\n languages: string[];\n authorities: string[];\n isSaving: boolean;\n\n constructor(\n private languageHelper: JhiLanguageHelper,\n private userService: UserService,\n private route: ActivatedRoute,\n private organizationService: OrganizationManagementService,\n private modalService: NgbModal,\n private router: Router,\n ) {}\n\n /**\n * Enable subscriptions to retrieve the user based on the activated route, all authorities and all languages on init\n */\n ngOnInit() {\n this.isSaving = false;\n\n // create a new user, and only overwrite it if we fetch a user to edit\n this.user = new User();\n this.route.parent!.data.subscribe(({ user }) => {\n if (user) {\n this.user = user.body ? user.body : user;\n this.organizationService.getOrganizationsByUser(this.user.id!).subscribe((organizations) => {\n this.user.organizations = organizations;\n });\n }\n });\n this.authorities = [];\n this.userService.authorities().subscribe((authorities) => {\n this.authorities = authorities;\n });\n this.languages = this.languageHelper.getAll();\n // Empty array for new user\n if (!this.user.id) {\n this.user.groups = [];\n }\n // Set password to undefined. ==> If it still is undefined on save, it won't be changed for existing users. It will be random for new users\n this.user.password = undefined;\n }\n\n /**\n * Navigate to the previous page when the user cancels the update process\n * Returns to the detail page if there is no previous state and we edited an existing user\n * Returns to the overview page if there is no previous state and we created a new user\n */\n previousState() {\n if (this.user.id) {\n navigateBack(this.router, ['admin', 'user-management', this.user.login!.toString()]);\n } else {\n navigateBack(this.router, ['admin', 'user-management']);\n }\n }\n\n /**\n * Update or create user in the user management component\n */\n save() {\n this.isSaving = true;\n if (this.user.id) {\n this.userService.update(this.user).subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n } else {\n this.userService.create(this.user).subscribe(\n () => this.onSaveSuccess(),\n () => this.onSaveError(),\n );\n }\n }\n\n /**\n * Set isSaving to false and navigate to previous page\n */\n private onSaveSuccess() {\n this.isSaving = false;\n this.previousState();\n }\n\n /**\n * Set isSaving to false\n */\n private onSaveError() {\n this.isSaving = false;\n }\n\n shouldRandomizePassword(useRandomPassword: any) {\n if (useRandomPassword) {\n this.user.password = undefined;\n } else {\n this.user.password = '';\n }\n }\n\n /**\n * Opens the organizations modal used to select an organization to add\n */\n openOrganizationsModal() {\n const modalRef = this.modalService.open(OrganizationSelectorComponent, { size: 'xl', backdrop: 'static' });\n modalRef.componentInstance.organizations = this.user.organizations;\n modalRef.closed.subscribe((organization) => {\n if (organization !== undefined) {\n if (this.user.organizations === undefined) {\n this.user.organizations = [];\n }\n this.user.organizations!.push(organization);\n }\n });\n }\n\n /**\n * Removes an organization from the user\n * @param organization to remove\n */\n removeOrganizationFromUser(organization: Organization) {\n this.user.organizations = this.user.organizations!.filter((o) => o.id !== organization.id);\n }\n}\n" }, { "alpha_fraction": 0.7021546363830566, "alphanum_fraction": 0.7021546363830566, "avg_line_length": 34.8636360168457, "blob_id": "ebb328c44d03dbaeaaa9483bec13a8bc2650fb8b", "content_id": "6fdcfa3fd70f42a4f87a01753dfd3e1c542c7240", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 789, "license_type": "permissive", "max_line_length": 114, "num_lines": 22, "path": "/src/main/webapp/app/shared/markdown-editor/commands/fullscreen.command.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Command } from 'app/shared/markdown-editor/commands/command';\nimport { enterFullscreen, exitFullscreen, isFullScreen } from 'app/shared/util/fullscreen.util';\n\n/**\n * Toggles fullscreen on button press.\n * Uses the markdown editor wrapper including tabs as element for fullscreen.\n *\n * The command needs to check different browser implementations of the fullscreen mode so it is handled correctly.\n */\nexport class FullscreenCommand extends Command {\n buttonIcon = 'compress';\n buttonTranslationString = 'artemisApp.markdownEditor.commands.fullscreen';\n\n execute(): void {\n if (isFullScreen()) {\n exitFullscreen();\n } else {\n const element = this.markdownWrapper.nativeElement;\n enterFullscreen(element);\n }\n }\n}\n" }, { "alpha_fraction": 0.49467140436172485, "alphanum_fraction": 0.5004440546035767, "avg_line_length": 28.246753692626953, "blob_id": "d83d55a0d77a016ee592e15dcea184ced51d4e3b", "content_id": "7cbe783f4604bf054abd0372c7aa4e1610989700", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2252, "license_type": "permissive", "max_line_length": 101, "num_lines": 77, "path": "/src/main/webapp/app/shared/service/sort.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport * as moment from 'moment';\n\n@Injectable({\n providedIn: 'root',\n})\nexport class SortService {\n constructor() {}\n\n sortByProperty<T>(array: T[], key: string, asc: boolean): T[] {\n return array.sort((a: T, b: T) => {\n const valueA = this.customGet(a, key, undefined);\n const valueB = this.customGet(b, key, undefined);\n\n if (valueA == undefined || valueB == undefined) {\n return SortService.compareWithUndefinedNull(valueA, valueB);\n }\n\n if (moment.isMoment(valueA) && moment.isMoment(valueB)) {\n return SortService.compareMoments(valueA, valueB, asc);\n }\n\n return SortService.compareBasic(valueA, valueB, asc);\n });\n }\n\n private static compareWithUndefinedNull(valueA: any, valueB: any) {\n if (!valueA && !valueB) {\n return 0;\n } else if (!valueA) {\n return 1;\n } else {\n return -1;\n }\n }\n\n private static compareMoments(valueA: moment.Moment, valueB: moment.Moment, ascending: boolean) {\n if (valueA.isSame(valueB)) {\n return 0;\n } else if (ascending) {\n return valueA.isBefore(valueB) ? -1 : 1;\n } else {\n return valueA.isBefore(valueB) ? 1 : -1;\n }\n }\n\n private static compareBasic(valueA: any, valueB: any, ascending: boolean) {\n if (valueA === valueB) {\n return 0;\n } else if (ascending) {\n return valueA < valueB ? -1 : 1;\n } else {\n return valueA < valueB ? 1 : -1;\n }\n }\n\n private customGet(object: any, path: string, defaultValue: any) {\n const pathArray = path.split('.').filter((key) => key);\n const value = pathArray.reduce((obj, key) => {\n if (!obj) {\n return obj;\n } else {\n if (obj instanceof Map) {\n return obj.get(key);\n } else {\n return obj[key];\n }\n }\n }, object);\n\n if (value === undefined) {\n return defaultValue;\n } else {\n return value;\n }\n }\n}\n" }, { "alpha_fraction": 0.7746745347976685, "alphanum_fraction": 0.7805917263031006, "avg_line_length": 47.0113639831543, "blob_id": "cd146511d52995685c83809976907b58417e587c", "content_id": "931d52e7388da9b9e4f011807bc3cbf681c4c295", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 4225, "license_type": "permissive", "max_line_length": 164, "num_lines": 88, "path": "/src/test/java/de/tum/in/www1/artemis/service/ParticipationTeamWebsocketServiceTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.service;\n\nimport static org.assertj.core.api.Assertions.assertThat;\nimport static org.mockito.Mockito.*;\n\nimport java.util.List;\nimport java.util.UUID;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.mockito.MockitoAnnotations;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.messaging.simp.stomp.StompHeaderAccessor;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.Course;\nimport de.tum.in.www1.artemis.domain.modeling.ModelingExercise;\nimport de.tum.in.www1.artemis.domain.participation.Participation;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.web.websocket.team.ParticipationTeamWebsocketService;\n\nclass ParticipationTeamWebsocketServiceTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n @Autowired\n private ParticipationTeamWebsocketService participationTeamWebsocketService;\n\n private StudentParticipation participation;\n\n private static String websocketTopic(Participation participation) {\n return \"/topic/participations/\" + participation.getId() + \"/team\";\n }\n\n @BeforeEach\n void init() {\n database.addUsers(3, 0, 0);\n Course course = database.addCourseWithOneModelingExercise();\n ModelingExercise modelingExercise = database.findModelingExerciseWithTitle(course.getExercises(), \"ClassDiagram\");\n participation = database.createAndSaveParticipationForExercise(modelingExercise, \"student1\");\n\n MockitoAnnotations.openMocks(this);\n participationTeamWebsocketService.clearDestinationTracker();\n }\n\n @AfterEach\n void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n void testSubscribeToParticipationTeamWebsocketTopic() {\n participationTeamWebsocketService.subscribe(participation.getId(), getStompHeaderAccessorMock());\n verify(messagingTemplate, times(1)).convertAndSend(websocketTopic(participation), List.of());\n assertThat(participationTeamWebsocketService.getDestinationTracker()).as(\"Session was added to destination tracker.\").hasSize(1);\n assertThat(participationTeamWebsocketService.getDestinationTracker()).as(\"Destination in tracker is correct.\").containsValue(websocketTopic(participation));\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n void testTriggerSendOnlineTeamMembers() {\n participationTeamWebsocketService.triggerSendOnlineTeamStudents(participation.getId());\n verify(messagingTemplate, times(1)).convertAndSend(websocketTopic(participation), List.of());\n }\n\n @Test\n @WithMockUser(username = \"student1\", roles = \"USER\")\n void testUnsubscribeFromParticipationTeamWebsocketTopic() {\n StompHeaderAccessor stompHeaderAccessor1 = getStompHeaderAccessorMock();\n StompHeaderAccessor stompHeaderAccessor2 = getStompHeaderAccessorMock();\n\n participationTeamWebsocketService.subscribe(participation.getId(), stompHeaderAccessor1);\n participationTeamWebsocketService.subscribe(participation.getId(), stompHeaderAccessor2);\n participationTeamWebsocketService.unsubscribe(stompHeaderAccessor1.getSessionId());\n\n verify(messagingTemplate, times(3)).convertAndSend(websocketTopic(participation), List.of());\n assertThat(participationTeamWebsocketService.getDestinationTracker()).as(\"Session was removed from destination tracker.\").hasSize(1);\n assertThat(participationTeamWebsocketService.getDestinationTracker()).as(\"Correct session was removed.\").containsKey(stompHeaderAccessor2.getSessionId());\n }\n\n private StompHeaderAccessor getStompHeaderAccessorMock() {\n String fakeSessionId = UUID.randomUUID().toString();\n StompHeaderAccessor stompHeaderAccessor = mock(StompHeaderAccessor.class, RETURNS_MOCKS);\n when(stompHeaderAccessor.getSessionId()).thenReturn(fakeSessionId);\n return stompHeaderAccessor;\n }\n}\n" }, { "alpha_fraction": 0.692319929599762, "alphanum_fraction": 0.6958180665969849, "avg_line_length": 44.90510940551758, "blob_id": "e1a91af5f8206a29ec01d8a625f560415d5c2f4e", "content_id": "2ac8a854aeb431a44ff96cc2a5d86564093b5e76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 6289, "license_type": "permissive", "max_line_length": 151, "num_lines": 137, "path": "/src/test/javascript/spec/component/learning-goals/course-learning-goals.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { MockPipe, MockProvider } from 'ng-mocks';\nimport { LearningGoalService } from 'app/course/learning-goals/learningGoal.service';\nimport { of } from 'rxjs';\nimport { LearningGoal } from 'app/entities/learningGoal.model';\nimport { ActivatedRoute } from '@angular/router';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { IndividualLearningGoalProgress, IndividualLectureUnitProgress } from 'app/course/learning-goals/learning-goal-individual-progress-dtos.model';\nimport { Component, Input } from '@angular/core';\nimport { CourseLearningGoalsComponent } from 'app/overview/course-learning-goals/course-learning-goals.component';\nimport { HttpResponse } from '@angular/common/http';\nimport { By } from '@angular/platform-browser';\nimport { TextUnit } from 'app/entities/lecture-unit/textUnit.model';\nimport { AccountService } from 'app/core/auth/account.service';\nimport { User } from 'app/core/user/user.model';\nimport * as _ from 'lodash';\nimport * as Sentry from '@sentry/browser';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-learning-goal-card', template: '<div><ng-content></ng-content></div>' })\nclass LearningGoalCardStubComponent {\n @Input() learningGoal: LearningGoal;\n @Input() learningGoalProgress: IndividualLearningGoalProgress;\n}\n\nclass MockActivatedRoute {\n parent: any;\n params: any;\n\n constructor(options: { parent?: any; params?: any }) {\n this.parent = options.parent;\n this.params = options.params;\n }\n}\n\nconst mockActivatedRoute = new MockActivatedRoute({\n parent: new MockActivatedRoute({\n params: of({ courseId: '1' }),\n }),\n});\ndescribe('CourseLearningGoals', () => {\n let courseLearningGoalsComponentFixture: ComponentFixture<CourseLearningGoalsComponent>;\n let courseLearningGoalsComponent: CourseLearningGoalsComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [],\n declarations: [CourseLearningGoalsComponent, LearningGoalCardStubComponent, MockPipe(ArtemisTranslatePipe)],\n providers: [\n MockProvider(JhiAlertService),\n MockProvider(LearningGoalService),\n MockProvider(AccountService),\n {\n provide: ActivatedRoute,\n useValue: mockActivatedRoute,\n },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n courseLearningGoalsComponentFixture = TestBed.createComponent(CourseLearningGoalsComponent);\n courseLearningGoalsComponent = courseLearningGoalsComponentFixture.componentInstance;\n const accountService = TestBed.get(AccountService);\n const user = new User();\n user.login = 'testUser';\n sinon.stub(accountService, 'userIdentity').get(function getterFn() {\n return user;\n });\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n courseLearningGoalsComponentFixture.detectChanges();\n expect(courseLearningGoalsComponent).to.be.ok;\n expect(courseLearningGoalsComponent.courseId).to.equal(1);\n });\n\n it('should load learning goal and associated progress and display a card for each of them', () => {\n const learningGoalService = TestBed.inject(LearningGoalService);\n const learningGoal = new LearningGoal();\n const textUnit = new TextUnit();\n learningGoal.id = 1;\n learningGoal.description = 'test';\n learningGoal.lectureUnits = [textUnit];\n const learningUnitProgress = new IndividualLectureUnitProgress();\n learningUnitProgress.lectureUnitId = 1;\n learningUnitProgress.totalPointsAchievableByStudentsInLectureUnit = 10;\n const learningGoalProgress = new IndividualLearningGoalProgress();\n learningGoalProgress.learningGoalId = 1;\n learningGoalProgress.learningGoalTitle = 'test';\n learningGoalProgress.pointsAchievedByStudentInLearningGoal = 5;\n learningGoalProgress.totalPointsAchievableByStudentsInLearningGoal = 10;\n learningGoalProgress.progressInLectureUnits = [learningUnitProgress];\n\n const learningGoalsOfCourseResponse: HttpResponse<LearningGoal[]> = new HttpResponse({\n body: [learningGoal, new LearningGoal()],\n status: 200,\n });\n const learningGoalProgressResponse: HttpResponse<IndividualLearningGoalProgress> = new HttpResponse({\n body: learningGoalProgress,\n status: 200,\n });\n\n const learningGoalProgressParticipantScores = _.cloneDeep(learningGoalProgress);\n learningGoalProgressParticipantScores.pointsAchievedByStudentInLearningGoal = 0;\n const learningGoalProgressParticipantScoreResponse: HttpResponse<IndividualLearningGoalProgress> = new HttpResponse({\n body: learningGoalProgressParticipantScores,\n status: 200,\n });\n\n const getAllForCourseStub = sinon.stub(learningGoalService, 'getAllForCourse').returns(of(learningGoalsOfCourseResponse));\n const getProgressStub = sinon.stub(learningGoalService, 'getProgress');\n getProgressStub.withArgs(sinon.match.any, sinon.match.any, false).returns(of(learningGoalProgressResponse));\n getProgressStub.withArgs(sinon.match.any, sinon.match.any, true).returns(of(learningGoalProgressParticipantScoreResponse));\n\n const captureExceptionSpy = sinon.spy(Sentry, 'captureException');\n\n courseLearningGoalsComponentFixture.detectChanges();\n\n const learningGoalCards = courseLearningGoalsComponentFixture.debugElement.queryAll(By.directive(LearningGoalCardStubComponent));\n expect(learningGoalCards).to.have.lengthOf(2);\n expect(getAllForCourseStub).to.have.been.calledOnce;\n expect(getProgressStub).to.have.callCount(4);\n expect(captureExceptionSpy).to.have.been.calledOnce;\n });\n});\n" }, { "alpha_fraction": 0.6518105864524841, "alphanum_fraction": 0.6518105864524841, "avg_line_length": 26.615385055541992, "blob_id": "1eeee49947e7af0890194c5b7deda3d23cc4f55b", "content_id": "aba66b5cfa7454f8c8e32dd1ffb81df79fe53241", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 359, "license_type": "permissive", "max_line_length": 90, "num_lines": 13, "path": "/src/main/webapp/app/core/about-us/models/contributor-model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export class ContributorModel {\n fullName: string;\n photoDirectory: string;\n role: string;\n website: string;\n\n constructor(fullName: string, photoDirectory: string, role: string, website: string) {\n this.fullName = fullName;\n this.photoDirectory = photoDirectory;\n this.role = role;\n this.website = website;\n }\n}\n" }, { "alpha_fraction": 0.7112461924552917, "alphanum_fraction": 0.7112461924552917, "avg_line_length": 39.403507232666016, "blob_id": "2604e52e9f20586b3e3be9bb6f6c5d742e661c2e", "content_id": "8d0a72b1141a58ae4d57eb6cbf2914848c3ada76", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2303, "license_type": "permissive", "max_line_length": 176, "num_lines": 57, "path": "/src/test/javascript/spec/component/shared/participant-scores-tables-container.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { TranslatePipe } from '@ngx-translate/core';\nimport { MockPipe } from 'ng-mocks';\nimport { Component, Input } from '@angular/core';\nimport { ParticipantScoreAverageDTO, ParticipantScoreDTO } from 'app/shared/participant-scores/participant-scores.service';\nimport * as chai from 'chai';\nimport { ParticipantScoresTablesContainerComponent } from 'app/shared/participant-scores/participant-scores-tables-container/participant-scores-tables-container.component';\nimport { NgbButtonsModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';\nimport { FormsModule } from '@angular/forms';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\n@Component({ selector: 'jhi-participant-scores-table', template: '<div></div>' })\nclass ParticipantScoresTableStubComponent {\n @Input()\n participantScores: ParticipantScoreDTO[] = [];\n @Input()\n isLoading = false;\n}\n\n@Component({ selector: 'jhi-participant-scores-average-table', template: '<div></div>' })\nclass ParticipantScoresAverageTableStubComponent {\n @Input()\n participantAverageScores: ParticipantScoreAverageDTO[] = [];\n @Input()\n isLoading = false;\n}\n\ndescribe('ParticipantScoresTablesContainer', () => {\n let fixture: ComponentFixture<ParticipantScoresTablesContainerComponent>;\n let component: ParticipantScoresTablesContainerComponent;\n\n beforeEach(() => {\n TestBed.configureTestingModule({\n imports: [FormsModule, NgbTooltipModule, NgbButtonsModule],\n declarations: [ParticipantScoresTablesContainerComponent, ParticipantScoresTableStubComponent, ParticipantScoresAverageTableStubComponent, MockPipe(TranslatePipe)],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(ParticipantScoresTablesContainerComponent);\n component = fixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n // this is just a simple container component so we test that the component renders correctly\n fixture.detectChanges();\n expect(component).to.be.ok;\n });\n});\n" }, { "alpha_fraction": 0.6591962575912476, "alphanum_fraction": 0.6607871651649475, "avg_line_length": 49.19791793823242, "blob_id": "ab002712b17e4c1b54d917c94db28da7c8435fe1", "content_id": "1b3a29cf111816ceee9becbd3f11304b7ede3d81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 14457, "license_type": "permissive", "max_line_length": 180, "num_lines": 288, "path": "/src/main/webapp/app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit, Input, ViewChild } from '@angular/core';\nimport { GradingCriterion } from 'app/exercises/shared/structured-grading-criterion/grading-criterion.model';\nimport { UsageCountCommand } from 'app/shared/markdown-editor/domainCommands/usageCount.command';\nimport { CreditsCommand } from 'app/shared/markdown-editor/domainCommands/credits.command';\nimport { FeedbackCommand } from 'app/shared/markdown-editor/domainCommands/feedback.command';\nimport { DomainCommand } from 'app/shared/markdown-editor/domainCommands/domainCommand';\nimport { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component';\nimport { GradingInstruction } from 'app/exercises/shared/structured-grading-criterion/grading-instruction.model';\nimport { GradingScaleCommand } from 'app/shared/markdown-editor/domainCommands/gradingScaleCommand';\nimport { GradingInstructionCommand } from 'app/shared/markdown-editor/domainCommands/gradingInstruction.command';\nimport { InstructionDescriptionCommand } from 'app/shared/markdown-editor/domainCommands/instructionDescription.command';\nimport { GradingCriterionCommand } from 'app/shared/markdown-editor/domainCommands/gradingCriterionCommand';\nimport { Exercise } from 'app/entities/exercise.model';\n@Component({\n selector: 'jhi-grading-instructions-details',\n templateUrl: './grading-instructions-details.component.html',\n})\nexport class GradingInstructionsDetailsComponent implements OnInit {\n /** Ace Editor configuration constants **/\n questionEditorText = '';\n @ViewChild('markdownEditor', { static: false })\n private markdownEditor: MarkdownEditorComponent;\n @Input()\n exercise: Exercise;\n private instructions: GradingInstruction[];\n private criteria: GradingCriterion[];\n\n gradingCriterionCommand = new GradingCriterionCommand();\n gradingInstructionCommand = new GradingInstructionCommand();\n creditsCommand = new CreditsCommand();\n gradingScaleCommand = new GradingScaleCommand();\n instructionDescriptionCommand = new InstructionDescriptionCommand();\n feedbackCommand = new FeedbackCommand();\n usageCountCommand = new UsageCountCommand();\n\n domainCommands: DomainCommand[] = [\n this.creditsCommand,\n this.gradingScaleCommand,\n this.instructionDescriptionCommand,\n this.feedbackCommand,\n this.usageCountCommand,\n this.gradingCriterionCommand,\n this.gradingInstructionCommand,\n ];\n\n constructor() {}\n\n ngOnInit() {\n this.criteria = this.exercise.gradingCriteria || [];\n this.questionEditorText = this.generateMarkdown();\n }\n\n generateMarkdown(): string {\n let markdownText = '';\n if (this.criteria === undefined || this.criteria.length === 0) {\n this.criteria = [];\n const dummyCriterion = new GradingCriterion();\n const exampleCriterion = new GradingCriterion();\n exampleCriterion.title = 'This is an Example criterion';\n const exampleInstr = new GradingInstruction();\n exampleCriterion.structuredGradingInstructions = [];\n exampleCriterion.structuredGradingInstructions.push(exampleInstr);\n exampleCriterion.structuredGradingInstructions.push(exampleInstr); // to showcase that a criterion consists of multiple instructions\n this.criteria.push(dummyCriterion);\n this.criteria.push(exampleCriterion);\n }\n for (const criterion of this.criteria) {\n if (criterion.title === null || criterion.title === undefined) {\n // if it is a dummy criterion, leave out the command identifier\n markdownText += this.generateInstructionsMarkdown(criterion);\n } else {\n markdownText += GradingCriterionCommand.identifier + criterion.title + '\\n' + '\\t' + this.generateInstructionsMarkdown(criterion);\n }\n }\n return markdownText;\n }\n\n /**\n * @function generateMarkdown\n * @desc Generate the markdown text for this grading instruction\n */\n generateInstructionsMarkdown(criterion: GradingCriterion): string {\n let markdownText = '';\n if (criterion.structuredGradingInstructions === undefined || criterion.structuredGradingInstructions.length === 0) {\n this.instructions = [];\n const newInstruction = new GradingInstruction();\n this.instructions.push(newInstruction);\n criterion.structuredGradingInstructions = this.instructions;\n }\n for (const instruction of criterion.structuredGradingInstructions) {\n markdownText +=\n GradingInstructionCommand.identifier +\n '\\n' +\n '\\t' +\n this.generateCreditsText(instruction) +\n '\\n' +\n '\\t' +\n this.generateGradingScaleText(instruction) +\n '\\n' +\n '\\t' +\n this.generateInstructionDescriptionText(instruction) +\n '\\n' +\n '\\t' +\n this.generateInstructionFeedback(instruction) +\n '\\n' +\n '\\t' +\n this.generateUsageCount(instruction) +\n '\\n' +\n '\\n';\n }\n return markdownText;\n }\n\n generateCreditsText(instruction: GradingInstruction): string {\n if (instruction.credits === undefined) {\n instruction.credits = parseFloat(CreditsCommand.text);\n return CreditsCommand.identifier + ' ' + CreditsCommand.text;\n }\n return CreditsCommand.identifier + ' ' + instruction.credits;\n }\n\n generateGradingScaleText(instruction: GradingInstruction): string {\n if (instruction.gradingScale === undefined) {\n instruction.gradingScale = GradingScaleCommand.text;\n return GradingScaleCommand.identifier + ' ' + GradingScaleCommand.text;\n }\n return GradingScaleCommand.identifier + ' ' + instruction.gradingScale;\n }\n\n generateInstructionDescriptionText(instruction: GradingInstruction): string {\n if (instruction.instructionDescription === undefined) {\n instruction.instructionDescription = InstructionDescriptionCommand.text;\n return InstructionDescriptionCommand.identifier + ' ' + InstructionDescriptionCommand.text;\n }\n return InstructionDescriptionCommand.identifier + ' ' + instruction.instructionDescription;\n }\n\n generateInstructionFeedback(instruction: GradingInstruction): string {\n if (instruction.feedback === undefined) {\n instruction.feedback = FeedbackCommand.text;\n return FeedbackCommand.identifier + ' ' + FeedbackCommand.text;\n }\n return FeedbackCommand.identifier + ' ' + instruction.feedback;\n }\n\n generateUsageCount(instruction: GradingInstruction): string {\n if (instruction.usageCount === undefined) {\n instruction.usageCount = parseInt(UsageCountCommand.text, 10);\n return UsageCountCommand.identifier + ' ' + UsageCountCommand.text;\n }\n return UsageCountCommand.identifier + ' ' + instruction.usageCount;\n }\n\n prepareForSave(): void {\n this.markdownEditor.parse();\n }\n\n hasCriterionCommand(domainCommands: [string, DomainCommand | null][]): boolean {\n return domainCommands.some(([, command]) => command instanceof GradingCriterionCommand);\n }\n\n /**\n * @function createSubInstructionCommands\n * @desc 1. divides the input: domainCommands in two subarrays:\n * instructionCommands, which consists of all stand-alone instructions\n * criteriaCommands, which consists of instructions that belong to a criterion\n * 2. for each subarrray a method is called to create the criterion and instruction objects\n * @param domainCommands containing tuples of [text, domainCommandIdentifiers]\n */\n createSubInstructionCommands(domainCommands: [string, DomainCommand | null][]): void {\n let instructionCommands;\n let criteriaCommands;\n let endOfInstructionsCommand = 0;\n if (!this.hasCriterionCommand(domainCommands)) {\n this.setParentForInstructionsWithNoCriterion(domainCommands);\n } else {\n for (const [, command] of domainCommands) {\n endOfInstructionsCommand++;\n if (command instanceof GradingCriterionCommand) {\n instructionCommands = domainCommands.slice(0, endOfInstructionsCommand - 1);\n if (instructionCommands.length !== 0) {\n this.setParentForInstructionsWithNoCriterion(instructionCommands);\n }\n criteriaCommands = domainCommands.slice(endOfInstructionsCommand - 1);\n if (criteriaCommands.length !== 0) {\n this.instructions = []; // resets the instructions array to be filled with the instructions of the criteria\n this.groupInstructionsToCriteria(criteriaCommands); // creates criterion object for each criterion and their corresponding instruction objects\n }\n break;\n }\n }\n }\n }\n\n /**\n * @function setParentForInstructionsWithNoCriterion\n * @desc 1. creates a dummy criterion object for each stand-alone instruction\n * @param domainCommands containing tuples of [text, domainCommandIdentifiers]\n */\n setParentForInstructionsWithNoCriterion(domainCommands: [string, DomainCommand | null][]): void {\n for (const [, command] of domainCommands) {\n if (command instanceof GradingInstructionCommand) {\n const dummyCriterion = new GradingCriterion();\n const newInstruction = new GradingInstruction();\n dummyCriterion.structuredGradingInstructions = [];\n dummyCriterion.structuredGradingInstructions.push(newInstruction);\n this.instructions.push(newInstruction);\n this.criteria.push(dummyCriterion);\n }\n }\n this.exercise.gradingCriteria = this.criteria;\n this.setInstructionParameters(domainCommands);\n }\n\n /**\n * @function groupInstructionsToCriteria\n * @desc 1. creates a criterion for each GradingCriterionCommandIdentifier\n * and creates the instruction objects of this criterion then assigns them to their parent criterion\n * @param domainCommands containing tuples of [text, domainCommandIdentifiers]\n */\n groupInstructionsToCriteria(domainCommands: [string, DomainCommand | null][]): void {\n const initialCriteriaCommands = domainCommands;\n if (this.exercise.gradingCriteria === undefined) {\n this.exercise.gradingCriteria = [];\n }\n for (const [text, command] of domainCommands) {\n if (command instanceof GradingCriterionCommand) {\n const newCriterion = new GradingCriterion();\n newCriterion.title = text;\n this.exercise.gradingCriteria.push(newCriterion);\n newCriterion.structuredGradingInstructions = [];\n const modifiedArray = domainCommands.slice(1); // remove GradingCriterionCommandIdentifier after creating its criterion object\n let endOfCriterion = 0;\n for (const [, instrCommand] of modifiedArray) {\n endOfCriterion++;\n if (instrCommand instanceof GradingInstructionCommand) {\n const newInstruction = new GradingInstruction(); // create instruction objects that belong to the above created criterion\n newCriterion.structuredGradingInstructions.push(newInstruction);\n this.instructions.push(newInstruction);\n }\n if (instrCommand instanceof GradingCriterionCommand) {\n domainCommands = domainCommands.slice(endOfCriterion, domainCommands.length);\n break;\n }\n }\n }\n }\n this.setInstructionParameters(initialCriteriaCommands.filter(([, command]) => !(command instanceof GradingCriterionCommand)));\n }\n\n /**\n * @function setInstructionParameters\n * @desc 1. Gets a tuple of text and domainCommandIdentifiers not including GradingCriterionCommandIdentifiers and assigns text values according to the domainCommandIdentifiers\n * 2. The tupple order is the same as the order of the commands in the markdown text inserted by the user\n * instruction objects must be created before the method gets triggered\n * @param domainCommands containing tuples of [text, domainCommandIdentifiers]\n */\n setInstructionParameters(domainCommands: [string, DomainCommand | null][]): void {\n let index = 0;\n for (const [text, command] of domainCommands) {\n if (command instanceof CreditsCommand) {\n this.instructions[index].credits = parseFloat(text);\n } else if (command instanceof GradingScaleCommand) {\n this.instructions[index].gradingScale = text;\n } else if (command instanceof InstructionDescriptionCommand) {\n this.instructions[index].instructionDescription = text;\n } else if (command instanceof FeedbackCommand) {\n this.instructions[index].feedback = text;\n } else if (command instanceof UsageCountCommand) {\n this.instructions[index].usageCount = parseInt(text, 10);\n index++; // index must be increased after the last parameter of the instruction to continue with the next instruction object\n }\n }\n }\n\n /**\n * @function domainCommandsFound\n * @desc 1. Gets a tuple of text and domainCommandIdentifiers and assigns text values according to the domainCommandIdentifiers\n * 2. The tupple order is the same as the order of the commands in the markdown text inserted by the user\n * @param domainCommands containing tuples of [text, domainCommandIdentifiers]\n */\n domainCommandsFound(domainCommands: [string, DomainCommand | null][]): void {\n this.instructions = [];\n this.criteria = [];\n this.exercise.gradingCriteria = [];\n this.createSubInstructionCommands(domainCommands);\n }\n}\n" }, { "alpha_fraction": 0.8291746377944946, "alphanum_fraction": 0.8330134153366089, "avg_line_length": 29.647058486938477, "blob_id": "2f2dc81f6d67fda999ceca10b1236ea6293775f7", "content_id": "42ddd5a3bd7ea234e4182027f546ca1e9b85b21d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 521, "license_type": "permissive", "max_line_length": 111, "num_lines": 17, "path": "/src/main/java/de/tum/in/www1/artemis/repository/StaticCodeAnalysisCategoryRepository.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.repository;\n\nimport java.util.Set;\n\nimport org.springframework.data.jpa.repository.JpaRepository;\nimport org.springframework.stereotype.Repository;\n\nimport de.tum.in.www1.artemis.domain.StaticCodeAnalysisCategory;\n\n/**\n * Spring Data repository for the StaticCodeAnalysisCategory entity.\n */\n@Repository\npublic interface StaticCodeAnalysisCategoryRepository extends JpaRepository<StaticCodeAnalysisCategory, Long> {\n\n Set<StaticCodeAnalysisCategory> findByExerciseId(Long exerciseId);\n}\n" }, { "alpha_fraction": 0.7180083990097046, "alphanum_fraction": 0.724057674407959, "avg_line_length": 33.66128921508789, "blob_id": "cc3be93e4be37f7d4c1436f7c6502b318b3a1ed1", "content_id": "d153040e0ce69f20b3f6e9d9253057c9cc536571", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2149, "license_type": "permissive", "max_line_length": 117, "num_lines": 62, "path": "/src/main/resources/templates/kotlin/test/testFiles/behavior/SortingExampleBehaviorTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package ${packageName};\n\nimport org.junit.jupiter.api.*;\n\nimport java.lang.reflect.Method;\n\nimport static org.junit.jupiter.api.Assertions.*;\nimport static de.tum.in.test.api.util.ReflectionTestUtils.*;\n\nimport de.tum.in.test.api.BlacklistPath;\nimport de.tum.in.test.api.AddTrustedPackage;\nimport de.tum.in.test.api.PathType;\nimport de.tum.in.test.api.StrictTimeout;\nimport de.tum.in.test.api.WhitelistPath;\nimport de.tum.in.test.api.jupiter.Public;\n\n/**\n * @author Stephan Krusche ([email protected])\n * @version 5.0 (11.11.2020)\n */\n@WhitelistPath(\"target\")\n@BlacklistPath(value = \"**Test*.{java,class}\", type = PathType.GLOB)\n@Public\n// This disables security but allows all Kotlin libraries to work (AJTS Security Error)\n@AddTrustedPackage(\"**\")\npublic class SortingExampleBehaviorTest {\n\n private Context context;\n private Policy policy;\n private Method methodPolicyConfigure;\n\n @BeforeEach\n public void setup() {\n context = (Context) newInstance(Context.class.getName());\n policy = (Policy) newInstance(Policy.class.getName(), context);\n methodPolicyConfigure = getMethod(Policy.class, \"configure\", boolean.class, boolean.class);\n }\n\n @Test\n @StrictTimeout(1)\n public void testMergeSort() {\n invokeMethod(policy, methodPolicyConfigure, true, false);\n Object sortAlgorithm = invokeMethod(context, \"getSortAlgorithm\");\n assertTrue(sortAlgorithm instanceof MergeSort, \"Expected MergeSort when time is important and space is not\");\n }\n\n @Test\n @StrictTimeout(1)\n public void testQuickSort() {\n invokeMethod(policy, methodPolicyConfigure, true, true);\n Object sortAlgorithm = invokeMethod(context, \"getSortAlgorithm\");\n assertTrue(sortAlgorithm instanceof QuickSort, \"Expected QuickSort when time and space are important\");\n }\n\n @Test\n @StrictTimeout(1)\n public void testSimulateRuntimeStrategyChoice() {\n Client.INSTANCE.simulateRuntimeConfigurationChange(policy);\n Object sortAlgorithm = invokeMethod(context, \"getSortAlgorithm\");\n assertNotNull(sortAlgorithm, \"Expected Client to simulate runtime configuration change\");\n }\n}\n" }, { "alpha_fraction": 0.6800765991210938, "alphanum_fraction": 0.6800765991210938, "avg_line_length": 35.540000915527344, "blob_id": "2b2e74b33f9fa133bdedeeec35877277cddace93", "content_id": "8fbcb3dc966eeca10ccde7c68f78fe467634bdb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3654, "license_type": "permissive", "max_line_length": 134, "num_lines": 100, "path": "/src/main/webapp/app/overview/student-questions/student-question-answer/student-question-answer.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';\nimport { ActivatedRoute } from '@angular/router';\nimport { User } from 'app/core/user/user.model';\nimport { StudentQuestionAnswer } from 'app/entities/student-question-answer.model';\nimport { StudentQuestionAnswerService } from 'app/overview/student-questions/student-question-answer/student-question-answer.service';\nimport { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component';\n\nexport interface StudentQuestionAnswerAction {\n name: QuestionAnswerActionName;\n studentQuestionAnswer: StudentQuestionAnswer;\n}\n\nexport enum QuestionAnswerActionName {\n DELETE,\n ADD,\n APPROVE,\n}\n\n@Component({\n selector: 'jhi-student-question-answer',\n templateUrl: './student-question-answer.component.html',\n styleUrls: ['./../student-questions.scss'],\n})\nexport class StudentQuestionAnswerComponent implements OnInit {\n @Input() studentQuestionAnswer: StudentQuestionAnswer;\n @Input() user: User;\n @Input() isAtLeastTutorInCourse: boolean;\n @Output() interactAnswer = new EventEmitter<StudentQuestionAnswerAction>();\n editText?: string;\n isEditMode: boolean;\n EditorMode = EditorMode;\n courseId: number;\n\n // Only allow certain html tags and no attributes\n allowedHtmlTags: string[] = ['a', 'b', 'strong', 'i', 'em', 'mark', 'small', 'del', 'ins', 'sub', 'sup', 'p'];\n allowedHtmlAttributes: string[] = ['href'];\n\n constructor(private studentQuestionAnswerService: StudentQuestionAnswerService, private route: ActivatedRoute) {}\n\n /**\n * Sets the text of the answer as the editor text\n */\n ngOnInit(): void {\n this.editText = this.studentQuestionAnswer.answerText;\n this.courseId = Number(this.route.snapshot.paramMap.get('courseId'));\n }\n\n /**\n * Takes a studentQuestionAnswer and determines if the user is the author of it\n * @param {StudentQuestionAnswer} studentQuestionAnswer\n * @returns {boolean}\n */\n isAuthorOfAnswer(studentQuestionAnswer: StudentQuestionAnswer): boolean {\n return this.user ? studentQuestionAnswer.author!.id === this.user.id : false;\n }\n\n /**\n * Deletes this studentQuestionAnswer\n */\n deleteAnswer(): void {\n this.studentQuestionAnswerService.delete(this.courseId, this.studentQuestionAnswer.id!).subscribe(() => {\n this.interactAnswer.emit({\n name: QuestionAnswerActionName.DELETE,\n studentQuestionAnswer: this.studentQuestionAnswer,\n });\n });\n }\n\n /**\n * Updates the text of the selected studentAnswer\n */\n saveAnswer(): void {\n this.studentQuestionAnswer.answerText = this.editText;\n this.studentQuestionAnswerService.update(this.courseId, this.studentQuestionAnswer).subscribe(() => {\n this.isEditMode = false;\n });\n }\n\n /**\n * Toggles the tutorApproved field for this studentQuestionAnswer\n */\n toggleAnswerTutorApproved(): void {\n this.studentQuestionAnswer.tutorApproved = !this.studentQuestionAnswer.tutorApproved;\n this.studentQuestionAnswerService.update(this.courseId, this.studentQuestionAnswer).subscribe(() => {\n this.interactAnswer.emit({\n name: QuestionAnswerActionName.APPROVE,\n studentQuestionAnswer: this.studentQuestionAnswer,\n });\n });\n }\n\n /**\n * toggles the edit Mode\n * set the editor text to the answer text\n */\n toggleEditMode(): void {\n this.isEditMode = !this.isEditMode;\n this.editText = this.studentQuestionAnswer.answerText;\n }\n}\n" }, { "alpha_fraction": 0.7011770009994507, "alphanum_fraction": 0.7058250308036804, "avg_line_length": 48.40370559692383, "blob_id": "59a9176ad53e08b446b0d3e13b374c3f10be4e3c", "content_id": "096eae7746e719722a28213d3a3361baef9dac93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13339, "license_type": "permissive", "max_line_length": 157, "num_lines": 270, "path": "/src/test/javascript/spec/component/course/course-overview.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import * as chai from 'chai';\nimport * as sinonChai from 'sinon-chai';\nimport * as sinon from 'sinon';\nimport { stub } from 'sinon';\nimport { Subject } from 'rxjs';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { CourseManagementService } from 'app/course/manage/course-management.service';\nimport { ArtemisTestModule } from '../../test.module';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs/internal/observable/of';\nimport { HttpHeaders, HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, Params, Router } from '@angular/router';\nimport { Course } from 'app/entities/course.model';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport { RouterTestingModule } from '@angular/router/testing';\nimport { MockHasAnyAuthorityDirective } from '../../helpers/mocks/directive/mock-has-any-authority.directive';\nimport { JhiAlertService, JhiSortByDirective, JhiSortDirective } from 'ng-jhipster';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { MomentModule } from 'ngx-moment';\nimport { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service';\nimport { TranslateService } from '@ngx-translate/core';\nimport { CourseExerciseRowComponent } from 'app/overview/course-exercises/course-exercise-row.component';\nimport { CourseExercisesComponent } from 'app/overview/course-exercises/course-exercises.component';\nimport { CourseRegistrationSelectorComponent } from 'app/overview/course-registration-selector/course-registration-selector.component';\nimport { CourseOverviewComponent } from 'app/overview/course-overview.component';\nimport { CourseCardComponent } from 'app/overview/course-card.component';\nimport { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service';\nimport * as moment from 'moment';\nimport { MockAlertService } from '../../helpers/mocks/service/mock-alert.service';\nimport { Exercise } from 'app/entities/exercise.model';\nimport { DueDateStat } from 'app/course/dashboards/instructor-course-dashboard/due-date-stat.model';\nimport { MockRouter } from '../../helpers/mocks/mock-router';\nimport { SecuredImageComponent } from 'app/shared/image/secured-image.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { OrionFilterDirective } from 'app/shared/orion/orion-filter.directive';\nimport { AlertErrorComponent } from 'app/shared/alert/alert-error.component';\nimport { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects';\nimport { TeamService } from 'app/exercises/shared/team/team.service';\nimport { JhiWebsocketService } from 'app/core/websocket/websocket.service';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\nconst endDate1 = moment().add(1, 'days');\nconst visibleDate1 = moment().subtract(1, 'days');\nconst dueDateStat1: DueDateStat = { inTime: 1, late: 0, total: 1 };\nconst exercise1: Exercise = {\n id: 5,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat1],\n studentAssignedTeamIdComputed: false,\n dueDate: moment().add(2, 'days'),\n secondCorrectionEnabled: true,\n};\nconst exercise2: Exercise = {\n id: 6,\n numberOfAssessmentsOfCorrectionRounds: [dueDateStat1],\n studentAssignedTeamIdComputed: false,\n dueDate: moment().add(1, 'days'),\n secondCorrectionEnabled: true,\n};\nconst quizExercise: QuizExercise = { id: 7, numberOfAssessmentsOfCorrectionRounds: [], studentAssignedTeamIdComputed: false, secondCorrectionEnabled: true };\n\nconst courseEmpty: Course = {};\n\nconst exam1 = { id: 3, endDate: endDate1, visibleDate: visibleDate1, course: courseEmpty };\nconst exam2 = { id: 4, course: courseEmpty };\nconst exams = [exam1, exam2];\nconst course1 = { id: 1, exams, exercises: [exercise1], description: 'description of course 1' };\nconst course2 = { id: 2, exercises: [exercise2], exams: [exam2], description: 'description of course 2', shortName: 'shortName1' };\n\ndescribe('CourseOverviewComponent', () => {\n let component: CourseOverviewComponent;\n let fixture: ComponentFixture<CourseOverviewComponent>;\n let courseService: CourseManagementService;\n let courseScoreCalculationService: CourseScoreCalculationService;\n let teamService: TeamService;\n let jhiWebsocketService: JhiWebsocketService;\n\n const route: MockActivatedRouteWithSubjects = new MockActivatedRouteWithSubjects();\n const params = new Subject<Params>();\n params.next({ courseId: course1.id });\n route.setSubject(params);\n\n beforeEach(async () => {\n TestBed.configureTestingModule({\n imports: [ArtemisTestModule, RouterTestingModule.withRoutes([]), MomentModule],\n declarations: [\n CourseOverviewComponent,\n MockDirective(MockHasAnyAuthorityDirective),\n MockDirective(OrionFilterDirective),\n MockPipe(ArtemisTranslatePipe),\n MockDirective(JhiSortDirective),\n MockDirective(JhiSortByDirective),\n MockPipe(ArtemisDatePipe),\n MockComponent(CourseExerciseRowComponent),\n MockComponent(CourseExercisesComponent),\n MockComponent(CourseRegistrationSelectorComponent),\n MockComponent(CourseCardComponent),\n MockComponent(SecuredImageComponent),\n MockComponent(AlertComponent),\n MockComponent(AlertErrorComponent),\n ],\n providers: [\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n { provide: TranslateService, useClass: MockTranslateService },\n { provide: ActivatedRoute, useValue: route },\n { provide: CourseExerciseRowComponent },\n { provide: JhiAlertService, useClass: MockAlertService },\n { provide: Router, useClass: MockRouter },\n ],\n })\n .compileComponents()\n .then(() => {\n fixture = TestBed.createComponent(CourseOverviewComponent);\n component = fixture.componentInstance;\n courseService = TestBed.inject(CourseManagementService);\n courseScoreCalculationService = TestBed.inject(CourseScoreCalculationService);\n teamService = TestBed.inject(TeamService);\n jhiWebsocketService = TestBed.inject(JhiWebsocketService);\n fixture.detectChanges();\n });\n });\n\n afterEach(() => {\n component.ngOnDestroy();\n sinon.restore();\n });\n\n it('Should call all methods on init', fakeAsync(() => {\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n const subscribeToTeamAssignmentUpdatesStub = stub(component, 'subscribeToTeamAssignmentUpdates');\n const subscribeForQuizChangesStub = stub(component, 'subscribeForQuizChanges');\n const adjustCourseDescriptionStub = stub(component, 'adjustCourseDescription');\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course1, headers: new HttpHeaders() })));\n getCourseStub.returns(course1);\n\n component.ngOnInit();\n tick(1000);\n\n expect(getCourseStub).to.have.been.called;\n expect(adjustCourseDescriptionStub).to.have.been.called;\n expect(subscribeForQuizChangesStub).to.have.been.called;\n expect(subscribeToTeamAssignmentUpdatesStub).to.have.been.called;\n }));\n\n it('Should call load Course methods on init', fakeAsync(() => {\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n const subscribeToTeamAssignmentUpdatesStub = stub(component, 'subscribeToTeamAssignmentUpdates');\n const subscribeForQuizChangesStub = stub(component, 'subscribeForQuizChanges');\n const adjustCourseDescriptionStub = stub(component, 'adjustCourseDescription');\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course1, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n tick(600);\n\n expect(getCourseStub).to.have.been.called;\n expect(adjustCourseDescriptionStub).to.have.been.called;\n expect(subscribeForQuizChangesStub).to.have.been.called;\n expect(subscribeToTeamAssignmentUpdatesStub).to.have.been.called;\n }));\n\n it('should set Long Description', () => {\n component.longTextShown = false;\n\n component.showLongDescription();\n\n expect(component.courseDescription).to.equal('');\n expect(component.longTextShown).to.equal(true);\n });\n\n it('should set short Description', () => {\n component.longTextShown = true;\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n getCourseStub.returns(course1);\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course1, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n\n component.showShortDescription();\n\n expect(component.courseDescription).to.equal('description of course 1...');\n expect(component.longTextShown).to.equal(false);\n });\n\n it('should have visible exams', () => {\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n getCourseStub.returns(course1);\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course1, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n\n const bool = component.hasVisibleExams();\n\n expect(bool).to.equal(true);\n });\n\n it('should not have visible exams', () => {\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n getCourseStub.returns(course2);\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course2, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n\n const bool = component.hasVisibleExams();\n\n expect(bool).to.equal(false);\n });\n\n it('should subscribeToTeamAssignmentUpdates', () => {\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n const teamAssignmentUpdatesStub = stub(teamService, 'teamAssignmentUpdates');\n getCourseStub.returns(course2);\n teamAssignmentUpdatesStub.returns(Promise.resolve(of({ exerciseId: 6, teamId: 1, studentParticipations: [] })));\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course2, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n\n component.subscribeToTeamAssignmentUpdates();\n });\n\n it('should adjustCourseDescription', () => {\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n getCourseStub.returns(course2);\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course2, headers: new HttpHeaders() })));\n const showLongDescriptionStub = stub(component, 'showLongDescription');\n component.enableShowMore = true;\n\n component.ngOnInit();\n component.adjustCourseDescription();\n\n expect(component.enableShowMore).to.equal(false);\n expect(showLongDescriptionStub).to.have.been.called;\n expect(localStorage.getItem('isDescriptionReadshortName1')).to.equal('true');\n });\n it('should subscribeForQuizChanges', () => {\n const findOneForDashboardStub = stub(courseService, 'findOneForDashboard');\n const getCourseStub = stub(courseScoreCalculationService, 'getCourse');\n const jhiWebsocketServiceReceiveStub = stub(jhiWebsocketService, 'receive');\n jhiWebsocketServiceReceiveStub.returns(of(quizExercise));\n const jhiWebsocketServiceSubscribeStub = stub(jhiWebsocketService, 'subscribe');\n getCourseStub.returns(course2);\n findOneForDashboardStub.returns(of(new HttpResponse({ body: course2, headers: new HttpHeaders() })));\n\n component.ngOnInit();\n component.subscribeForQuizChanges();\n\n expect(jhiWebsocketServiceSubscribeStub).to.have.been.called;\n expect(jhiWebsocketServiceReceiveStub).to.have.been.called;\n });\n\n it('should do ngOnDestroy', () => {\n const jhiWebsocketServiceStub = stub(jhiWebsocketService, 'unsubscribe');\n\n component.ngOnInit();\n component.subscribeForQuizChanges(); // to have quizExercisesChannel set\n component.ngOnDestroy();\n\n expect(jhiWebsocketServiceStub).to.have.been.called;\n });\n});\n" }, { "alpha_fraction": 0.7589372396469116, "alphanum_fraction": 0.7614970207214355, "avg_line_length": 58.62631607055664, "blob_id": "48b2d666a9384854c9ecbcdda2445a041b2b9ffe", "content_id": "6abed65d6504ad33116bea3a238571b3f6be2158", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 11329, "license_type": "permissive", "max_line_length": 179, "num_lines": 190, "path": "/src/test/java/de/tum/in/www1/artemis/programmingexercise/ProgrammingExerciseServiceIntegrationTest.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.programmingexercise;\n\nimport static de.tum.in.www1.artemis.web.rest.ProgrammingExerciseResource.Endpoints.*;\nimport static org.assertj.core.api.Assertions.assertThat;\n\nimport java.util.stream.Collectors;\n\nimport org.junit.jupiter.api.AfterEach;\nimport org.junit.jupiter.api.BeforeEach;\nimport org.junit.jupiter.api.Test;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.security.test.context.support.WithMockUser;\n\nimport de.tum.in.www1.artemis.AbstractSpringIntegrationBambooBitbucketJiraTest;\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.repository.ProgrammingExerciseRepository;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseImportService;\nimport de.tum.in.www1.artemis.service.programming.ProgrammingExerciseService;\nimport de.tum.in.www1.artemis.util.ModelFactory;\nimport de.tum.in.www1.artemis.web.rest.dto.SearchResultPageDTO;\n\npublic class ProgrammingExerciseServiceIntegrationTest extends AbstractSpringIntegrationBambooBitbucketJiraTest {\n\n private static final String BASE_RESOURCE = \"/api/programming-exercises/\";\n\n @Autowired\n ProgrammingExerciseService programmingExerciseService;\n\n @Autowired\n ProgrammingExerciseImportService programmingExerciseImportService;\n\n @Autowired\n ProgrammingExerciseRepository programmingExerciseRepository;\n\n private Course additionalEmptyCourse;\n\n private ProgrammingExercise programmingExercise;\n\n @BeforeEach\n public void setUp() {\n bambooRequestMockProvider.enableMockingOfRequests();\n bitbucketRequestMockProvider.enableMockingOfRequests();\n database.addUsers(1, 1, 1);\n database.addInstructor(\"other-instructors\", \"instructorother\");\n database.addCourseWithOneProgrammingExerciseAndTestCases();\n additionalEmptyCourse = database.addEmptyCourse();\n programmingExercise = programmingExerciseRepository.findAll().get(0);\n database.addHintsToExercise(programmingExercise);\n database.addHintsToProblemStatement(programmingExercise);\n database.addStaticCodeAnalysisCategoriesToProgrammingExercise(programmingExercise);\n\n // Load again to fetch changes to statement and hints while keeping eager refs\n programmingExercise = database.loadProgrammingExerciseWithEagerReferences(programmingExercise);\n }\n\n @AfterEach\n public void tearDown() {\n database.resetDatabase();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void importProgrammingExerciseBasis_baseReferencesGotCloned() {\n final var newlyImported = importExerciseBase();\n\n assertThat(newlyImported.getId()).isNotEqualTo(programmingExercise.getId());\n assertThat(newlyImported != programmingExercise).isTrue();\n assertThat(newlyImported.getTemplateParticipation().getId()).isNotEqualTo(programmingExercise.getTemplateParticipation().getId());\n assertThat(newlyImported.getSolutionParticipation().getId()).isNotEqualTo(programmingExercise.getSolutionParticipation().getId());\n assertThat(newlyImported.getProgrammingLanguage()).isEqualTo(programmingExercise.getProgrammingLanguage());\n assertThat(newlyImported.getProjectKey()).isNotEqualTo(programmingExercise.getProjectKey());\n assertThat(newlyImported.getSolutionBuildPlanId()).isNotEqualTo(programmingExercise.getSolutionBuildPlanId());\n assertThat(newlyImported.getTemplateBuildPlanId()).isNotEqualTo(programmingExercise.getTemplateBuildPlanId());\n assertThat(newlyImported.hasSequentialTestRuns()).isEqualTo(programmingExercise.hasSequentialTestRuns());\n assertThat(newlyImported.isAllowOnlineEditor()).isEqualTo(programmingExercise.isAllowOnlineEditor());\n assertThat(newlyImported.getTotalNumberOfAssessments()).isNull();\n assertThat(newlyImported.getNumberOfComplaints()).isNull();\n assertThat(newlyImported.getNumberOfMoreFeedbackRequests()).isNull();\n assertThat(newlyImported.getNumberOfSubmissions()).isNull();\n assertThat(newlyImported.getAttachments()).isNull();\n assertThat(newlyImported.getTutorParticipations()).isNull();\n assertThat(newlyImported.getExampleSubmissions()).isNull();\n assertThat(newlyImported.getStudentQuestions()).isNull();\n assertThat(newlyImported.getStudentParticipations()).isNull();\n final var newTestCaseIDs = newlyImported.getTestCases().stream().map(ProgrammingExerciseTestCase::getId).collect(Collectors.toSet());\n assertThat(newlyImported.getTestCases().size()).isEqualTo(programmingExercise.getTestCases().size());\n assertThat(programmingExercise.getTestCases()).noneMatch(testCase -> newTestCaseIDs.contains(testCase.getId()));\n assertThat(programmingExercise.getTestCases()).usingElementComparatorIgnoringFields(\"id\", \"exercise\").containsExactlyInAnyOrderElementsOf(newlyImported.getTestCases());\n final var newHintIDs = newlyImported.getExerciseHints().stream().map(ExerciseHint::getId).collect(Collectors.toSet());\n assertThat(newlyImported.getExerciseHints().size()).isEqualTo(programmingExercise.getExerciseHints().size());\n assertThat(programmingExercise.getExerciseHints()).noneMatch(hint -> newHintIDs.contains(hint.getId()));\n final var newStaticCodeAnalysisCategoriesIDs = newlyImported.getStaticCodeAnalysisCategories().stream().map(StaticCodeAnalysisCategory::getId).collect(Collectors.toSet());\n assertThat(newlyImported.getStaticCodeAnalysisCategories().size()).isEqualTo(programmingExercise.getStaticCodeAnalysisCategories().size());\n assertThat(programmingExercise.getStaticCodeAnalysisCategories()).noneMatch(category -> newStaticCodeAnalysisCategoriesIDs.contains(category.getId()));\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void importProgrammingExerciseBasis_hintsGotReplacedInStatement() {\n final var imported = importExerciseBase();\n\n final var oldHintIDs = programmingExercise.getExerciseHints().stream().map(ExerciseHint::getId).collect(Collectors.toSet());\n final var newHintIDs = imported.getExerciseHints().stream().map(ExerciseHint::getId).collect(Collectors.toSet());\n final var matchString = \".*\\\\{[^{}]*%d[^{}]*\\\\}.*\";\n final var importedStatement = imported.getProblemStatement();\n assertThat(oldHintIDs).noneMatch(hint -> importedStatement.matches(String.format(matchString, hint)));\n assertThat(newHintIDs).allMatch(hint -> importedStatement.matches(String.format(matchString, hint)));\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void importProgrammingExerciseBasis_testsAndHintsHoldTheSameInformation() {\n final var imported = importExerciseBase();\n\n // All copied hints/tests have the same content are are referenced to the new exercise\n assertThat(imported.getExerciseHints()).allMatch(hint -> programmingExercise.getExerciseHints().stream().anyMatch(\n oldHint -> oldHint.getContent().equals(hint.getContent()) && oldHint.getTitle().equals(hint.getTitle()) && hint.getExercise().getId().equals(imported.getId())));\n assertThat(imported.getTestCases()).allMatch(test -> programmingExercise.getTestCases().stream().anyMatch(oldTest -> test.getExercise().getId().equals(imported.getId())\n && oldTest.getTestName().equalsIgnoreCase(test.getTestName()) && oldTest.getWeight().equals(test.getWeight())));\n }\n\n @Test\n @WithMockUser(username = \"tutor1\", roles = \"TA\")\n public void importExercise_tutor_forbidden() throws Exception {\n final var toBeImported = createToBeImported();\n request.post(ROOT + IMPORT.replace(\"{sourceExerciseId}\", programmingExercise.getId().toString()), toBeImported, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"user1\", roles = \"USER\")\n public void importExercise_user_forbidden() throws Exception {\n final var toBeImported = createToBeImported();\n request.post(ROOT + IMPORT.replace(\"{sourceExerciseId}\", programmingExercise.getId().toString()), toBeImported, HttpStatus.FORBIDDEN);\n }\n\n @Test\n @WithMockUser(username = \"instructorother1\", roles = \"INSTRUCTOR\")\n public void testInstructorGetsResultsOnlyFromOwningCourses() throws Exception {\n final var search = database.configureSearch(\"\");\n final var result = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(search));\n assertThat(result.getResultsOnPage()).isNullOrEmpty();\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testInstructorGetsResultsFromOwningCoursesNotEmpty() throws Exception {\n final var search = database.configureSearch(\"Programming\");\n final var result = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(search));\n assertThat(result.getResultsOnPage().size()).isEqualTo(1);\n }\n\n @Test\n @WithMockUser(username = \"instructor1\", roles = \"INSTRUCTOR\")\n public void testSearchProgrammingExercisesWithProperSearchTerm() throws Exception {\n database.addCourseWithNamedProgrammingExerciseAndTestCases(\"Java JDK13\");\n database.addCourseWithNamedProgrammingExerciseAndTestCases(\"Python\");\n database.addCourseWithNamedProgrammingExerciseAndTestCases(\"Java JDK12\");\n final var searchPython = database.configureSearch(\"Python\");\n final var resultPython = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(searchPython));\n assertThat(resultPython.getResultsOnPage().size()).isEqualTo(1);\n\n final var searchJava = database.configureSearch(\"Java\");\n final var resultJava = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(searchJava));\n assertThat(resultJava.getResultsOnPage().size()).isEqualTo(2);\n\n final var searchSwift = database.configureSearch(\"Swift\");\n final var resultSwift = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(searchSwift));\n assertThat(resultSwift.getResultsOnPage()).isNullOrEmpty();\n }\n\n @Test\n @WithMockUser(value = \"admin\", roles = \"ADMIN\")\n public void testAdminGetsResultsFromAllCourses() throws Exception {\n database.addCourseInOtherInstructionGroupAndExercise(\"Programming\");\n final var search = database.configureSearch(\"Programming\");\n final var result = request.get(BASE_RESOURCE, HttpStatus.OK, SearchResultPageDTO.class, database.exerciseSearchMapping(search));\n assertThat(result.getResultsOnPage().size()).isEqualTo(2);\n }\n\n private ProgrammingExercise importExerciseBase() {\n final var toBeImported = createToBeImported();\n return programmingExerciseImportService.importProgrammingExerciseBasis(programmingExercise, toBeImported);\n }\n\n private ProgrammingExercise createToBeImported() {\n return ModelFactory.generateToBeImportedProgrammingExercise(\"Test\", \"TST\", programmingExercise, additionalEmptyCourse);\n }\n\n}\n" }, { "alpha_fraction": 0.742222785949707, "alphanum_fraction": 0.7452619075775146, "avg_line_length": 50.953948974609375, "blob_id": "7363d9f096fb82fa65d38cf9f5912275efa890d7", "content_id": "d4db092a46b880b2e2295dba6e3cb0daab0d4553", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 23691, "license_type": "permissive", "max_line_length": 189, "num_lines": 456, "path": "/src/main/java/de/tum/in/www1/artemis/web/rest/ExerciseResource.java", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "package de.tum.in.www1.artemis.web.rest;\n\nimport static de.tum.in.www1.artemis.web.rest.util.ResponseUtil.*;\n\nimport java.time.ZonedDateTime;\nimport java.util.*;\n\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.core.io.Resource;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.security.access.prepost.PreAuthorize;\nimport org.springframework.web.bind.annotation.*;\n\nimport de.tum.in.www1.artemis.domain.*;\nimport de.tum.in.www1.artemis.domain.enumeration.AssessmentType;\nimport de.tum.in.www1.artemis.domain.enumeration.ComplaintType;\nimport de.tum.in.www1.artemis.domain.enumeration.TutorParticipationStatus;\nimport de.tum.in.www1.artemis.domain.exam.Exam;\nimport de.tum.in.www1.artemis.domain.participation.StudentParticipation;\nimport de.tum.in.www1.artemis.domain.participation.TutorParticipation;\nimport de.tum.in.www1.artemis.repository.*;\nimport de.tum.in.www1.artemis.security.Role;\nimport de.tum.in.www1.artemis.service.*;\nimport de.tum.in.www1.artemis.service.exam.ExamDateService;\nimport de.tum.in.www1.artemis.service.feature.Feature;\nimport de.tum.in.www1.artemis.service.feature.FeatureToggle;\nimport de.tum.in.www1.artemis.web.rest.dto.DueDateStat;\nimport de.tum.in.www1.artemis.web.rest.dto.StatsForDashboardDTO;\nimport de.tum.in.www1.artemis.web.rest.dto.TutorLeaderboardDTO;\nimport de.tum.in.www1.artemis.web.rest.errors.EntityNotFoundException;\nimport de.tum.in.www1.artemis.web.rest.util.HeaderUtil;\nimport io.github.jhipster.web.util.ResponseUtil;\n\n/**\n * REST controller for managing Exercise.\n */\n@RestController\n@RequestMapping(\"/api\")\n@PreAuthorize(\"hasRole('ADMIN')\")\npublic class ExerciseResource {\n\n private final Logger log = LoggerFactory.getLogger(ExerciseResource.class);\n\n private static final String ENTITY_NAME = \"exercise\";\n\n @Value(\"${jhipster.clientApp.name}\")\n private String applicationName;\n\n private final ExerciseService exerciseService;\n\n private final ExerciseRepository exerciseRepository;\n\n private final UserRepository userRepository;\n\n private final ParticipationService participationService;\n\n private final AuthorizationCheckService authCheckService;\n\n private final TutorParticipationService tutorParticipationService;\n\n private final SubmissionRepository submissionRepository;\n\n private final ExamDateService examDateService;\n\n private final TutorLeaderboardService tutorLeaderboardService;\n\n private final ProgrammingExerciseRepository programmingExerciseRepository;\n\n private final GradingCriterionRepository gradingCriterionRepository;\n\n private final ComplaintRepository complaintRepository;\n\n private final ComplaintResponseRepository complaintResponseRepository;\n\n private final ExampleSubmissionRepository exampleSubmissionRepository;\n\n private final ResultRepository resultRepository;\n\n public ExerciseResource(ExerciseService exerciseService, ParticipationService participationService, UserRepository userRepository, ExamDateService examDateService,\n AuthorizationCheckService authCheckService, TutorParticipationService tutorParticipationService, ExampleSubmissionRepository exampleSubmissionRepository,\n ComplaintRepository complaintRepository, SubmissionRepository submissionRepository, TutorLeaderboardService tutorLeaderboardService,\n ComplaintResponseRepository complaintResponseRepository, ProgrammingExerciseRepository programmingExerciseRepository,\n GradingCriterionRepository gradingCriterionRepository, ExerciseRepository exerciseRepository, ResultRepository resultRepository) {\n this.exerciseService = exerciseService;\n this.participationService = participationService;\n this.userRepository = userRepository;\n this.authCheckService = authCheckService;\n this.tutorParticipationService = tutorParticipationService;\n this.exampleSubmissionRepository = exampleSubmissionRepository;\n this.complaintRepository = complaintRepository;\n this.submissionRepository = submissionRepository;\n this.complaintResponseRepository = complaintResponseRepository;\n this.tutorLeaderboardService = tutorLeaderboardService;\n this.programmingExerciseRepository = programmingExerciseRepository;\n this.gradingCriterionRepository = gradingCriterionRepository;\n this.examDateService = examDateService;\n this.exerciseRepository = exerciseRepository;\n this.resultRepository = resultRepository;\n }\n\n /**\n * GET /exercises/:exerciseId : get the \"exerciseId\" exercise.\n *\n * @param exerciseId the exerciseId of the exercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the exercise, or with status 404 (Not Found)\n */\n @GetMapping(\"/exercises/{exerciseId}\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<Exercise> getExercise(@PathVariable Long exerciseId) {\n\n log.debug(\"REST request to get Exercise : {}\", exerciseId);\n\n User user = userRepository.getUserWithGroupsAndAuthorities();\n Exercise exercise = exerciseRepository.findByIdWithCategoriesAndTeamAssignmentConfigElseThrow(exerciseId);\n\n // Exam exercise\n if (exercise.isExamExercise()) {\n Exam exam = exercise.getExerciseGroup().getExam();\n if (authCheckService.isAtLeastInstructorForExercise(exercise, user)) {\n // instructors and admins should always be able to see exam exercises\n // continue\n }\n else if (authCheckService.isAtLeastTeachingAssistantForExercise(exercise, user)) {\n // tutors should only be able to see exam exercises when the exercise has finished\n ZonedDateTime latestIndividualExamEndDate = examDateService.getLatestIndividualExamEndDate(exam);\n if (latestIndividualExamEndDate == null || latestIndividualExamEndDate.isAfter(ZonedDateTime.now())) {\n // When there is no due date or the due date is in the future, we return forbidden here\n return forbidden();\n }\n }\n else {\n // Students should never access exercises\n return forbidden();\n }\n }\n // Normal exercise\n else {\n if (!authCheckService.isAllowedToSeeExercise(exercise, user)) {\n return forbidden();\n }\n if (!authCheckService.isAtLeastTeachingAssistantForExercise(exercise, user)) {\n exercise.filterSensitiveInformation();\n }\n }\n\n List<GradingCriterion> gradingCriteria = gradingCriterionRepository.findByExerciseIdWithEagerGradingCriteria(exerciseId);\n exercise.setGradingCriteria(gradingCriteria);\n return ResponseUtil.wrapOrNotFound(Optional.of(exercise));\n }\n\n /**\n * GET /exercises/:exerciseId : get the \"exerciseId\" exercise with data useful for tutors.\n *\n * @param exerciseId the exerciseId of the exercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the exercise, or with status 404 (Not Found)\n */\n @GetMapping(\"/exercises/{exerciseId}/for-assessment-dashboard\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<Exercise> getExerciseForAssessmentDashboard(@PathVariable Long exerciseId) {\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n User user = userRepository.getUserWithGroupsAndAuthorities();\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.TEACHING_ASSISTANT, exercise, user);\n\n // Programming exercises with only automatic assessment should *NOT* be available on the assessment dashboard!\n if (exercise instanceof ProgrammingExercise && exercise.getAssessmentType().equals(AssessmentType.AUTOMATIC)) {\n return badRequest();\n }\n\n Set<ExampleSubmission> exampleSubmissions = this.exampleSubmissionRepository.findAllWithResultByExerciseId(exerciseId);\n // Do not provide example submissions without any assessment\n exampleSubmissions.removeIf(exampleSubmission -> exampleSubmission.getSubmission().getLatestResult() == null);\n exercise.setExampleSubmissions(exampleSubmissions);\n\n List<GradingCriterion> gradingCriteria = gradingCriterionRepository.findByExerciseIdWithEagerGradingCriteria(exerciseId);\n exercise.setGradingCriteria(gradingCriteria);\n\n TutorParticipation tutorParticipation = tutorParticipationService.findByExerciseAndTutor(exercise, user);\n if (exampleSubmissions.size() == 0 && tutorParticipation.getStatus().equals(TutorParticipationStatus.REVIEWED_INSTRUCTIONS)) {\n tutorParticipation.setStatus(TutorParticipationStatus.TRAINED);\n }\n exercise.setTutorParticipations(Collections.singleton(tutorParticipation));\n\n return ResponseUtil.wrapOrNotFound(Optional.of(exercise));\n }\n\n /**\n * GET /exercises/upcoming : Find all exercises that have an upcoming due date.\n *\n * @return the ResponseEntity with status 200 (OK) and a list of exercises.\n */\n @GetMapping(\"/exercises/upcoming\")\n @PreAuthorize(\"hasRole('ADMIN')\")\n public ResponseEntity<Set<Exercise>> getUpcomingExercises() {\n log.debug(\"REST request to get all upcoming exercises\");\n\n if (!authCheckService.isAdmin()) {\n return forbidden();\n }\n\n Set<Exercise> upcomingExercises = exerciseRepository.findAllExercisesWithCurrentOrUpcomingDueDate();\n return ResponseEntity.ok(upcomingExercises);\n }\n\n /**\n * GET /exercises/:exerciseId/title : Returns the title of the exercise with the given id\n *\n * @param exerciseId the id of the exercise\n * @return the title of the exercise wrapped in an ResponseEntity or 404 Not Found if no exercise with that id exists\n */\n @GetMapping(value = \"/exercises/{exerciseId}/title\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<String> getExerciseTitle(@PathVariable Long exerciseId) {\n final var title = exerciseRepository.getExerciseTitle(exerciseId);\n return title == null ? ResponseEntity.notFound().build() : ResponseEntity.ok(title);\n }\n\n /**\n * GET /exercises/:exerciseId/stats-for-assessment-dashboard A collection of useful statistics for the tutor exercise dashboard of the exercise with the given exerciseId\n *\n * @param exerciseId the exerciseId of the exercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the stats, or with status 404 (Not Found)\n */\n @GetMapping(\"/exercises/{exerciseId}/stats-for-assessment-dashboard\")\n @PreAuthorize(\"hasRole('TA')\")\n public ResponseEntity<StatsForDashboardDTO> getStatsForExerciseAssessmentDashboard(@PathVariable Long exerciseId) {\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n\n if (!authCheckService.isAtLeastTeachingAssistantForExercise(exercise)) {\n return forbidden();\n }\n\n StatsForDashboardDTO stats = populateCommonStatistics(exercise, exercise.isExamExercise());\n\n return ResponseEntity.ok(stats);\n }\n\n /**\n * Given an exercise exerciseId, it creates an object node with numberOfSubmissions, totalNumberOfAssessments, numberOfComplaints and numberOfMoreFeedbackRequests, that are used by both\n * stats for assessment dashboard and for instructor dashboard\n * TODO: refactor and improve this method\n *\n * @param exercise - the exercise we are interested in\n * @param examMode - flag to determine if test run submissions should be deducted from the statistics\n * @return a object node with the stats\n */\n private StatsForDashboardDTO populateCommonStatistics(Exercise exercise, boolean examMode) {\n final Long exerciseId = exercise.getId();\n StatsForDashboardDTO stats = new StatsForDashboardDTO();\n\n Course course = exercise.getCourseViaExerciseGroupOrCourseMember();\n\n DueDateStat numberOfSubmissions;\n DueDateStat totalNumberOfAssessments;\n\n if (exercise instanceof ProgrammingExercise) {\n numberOfSubmissions = new DueDateStat(programmingExerciseRepository.countLegalSubmissionsByExerciseIdSubmitted(exerciseId, examMode), 0L);\n totalNumberOfAssessments = new DueDateStat(programmingExerciseRepository.countAssessmentsByExerciseIdSubmitted(exerciseId, examMode), 0L);\n }\n else {\n numberOfSubmissions = submissionRepository.countSubmissionsForExercise(exerciseId, examMode);\n totalNumberOfAssessments = resultRepository.countNumberOfFinishedAssessmentsForExercise(exerciseId, examMode);\n }\n\n stats.setNumberOfSubmissions(numberOfSubmissions);\n stats.setTotalNumberOfAssessments(totalNumberOfAssessments);\n\n final DueDateStat[] numberOfAssessmentsOfCorrectionRounds;\n int numberOfCorrectionRounds = 1;\n if (examMode) {\n // set number of corrections specific to each correction round\n numberOfCorrectionRounds = exercise.getExerciseGroup().getExam().getNumberOfCorrectionRoundsInExam();\n numberOfAssessmentsOfCorrectionRounds = resultRepository.countNumberOfFinishedAssessmentsForExamExerciseForCorrectionRounds(exercise, numberOfCorrectionRounds);\n }\n else {\n // no examMode here, so correction rounds defaults to 1 and is the same as totalNumberOfAssessments\n numberOfAssessmentsOfCorrectionRounds = new DueDateStat[] { totalNumberOfAssessments };\n }\n\n stats.setNumberOfAssessmentsOfCorrectionRounds(numberOfAssessmentsOfCorrectionRounds);\n\n final DueDateStat[] numberOfLockedAssessmentByOtherTutorsOfCorrectionRound;\n numberOfLockedAssessmentByOtherTutorsOfCorrectionRound = resultRepository.countNumberOfLockedAssessmentsByOtherTutorsForExamExerciseForCorrectionRounds(exercise,\n numberOfCorrectionRounds, userRepository.getUserWithGroupsAndAuthorities());\n stats.setNumberOfLockedAssessmentByOtherTutorsOfCorrectionRound(numberOfLockedAssessmentByOtherTutorsOfCorrectionRound);\n\n final DueDateStat numberOfAutomaticAssistedAssessments = resultRepository.countNumberOfAutomaticAssistedAssessmentsForExercise(exerciseId);\n stats.setNumberOfAutomaticAssistedAssessments(numberOfAutomaticAssistedAssessments);\n\n final long numberOfMoreFeedbackRequests = complaintRepository.countComplaintsByExerciseIdAndComplaintType(exerciseId, ComplaintType.MORE_FEEDBACK);\n stats.setNumberOfMoreFeedbackRequests(numberOfMoreFeedbackRequests);\n\n long numberOfComplaints;\n if (examMode) {\n numberOfComplaints = complaintRepository.countByResultParticipationExerciseIdAndComplaintTypeIgnoreTestRuns(exerciseId, ComplaintType.COMPLAINT);\n }\n else {\n numberOfComplaints = complaintRepository.countComplaintsByExerciseIdAndComplaintType(exerciseId, ComplaintType.COMPLAINT);\n }\n stats.setNumberOfComplaints(numberOfComplaints);\n\n long numberOfComplaintResponses = complaintResponseRepository.countComplaintResponseByExerciseIdAndComplaintTypeAndSubmittedTimeIsNotNull(exerciseId,\n ComplaintType.COMPLAINT);\n\n stats.setNumberOfOpenComplaints(numberOfComplaints - numberOfComplaintResponses);\n\n long numberOfMoreFeedbackComplaintResponses = complaintResponseRepository.countComplaintResponseByExerciseIdAndComplaintTypeAndSubmittedTimeIsNotNull(exerciseId,\n ComplaintType.MORE_FEEDBACK);\n\n stats.setNumberOfOpenMoreFeedbackRequests(numberOfMoreFeedbackRequests - numberOfMoreFeedbackComplaintResponses);\n\n List<TutorLeaderboardDTO> leaderboardEntries = tutorLeaderboardService.getExerciseLeaderboard(exercise);\n stats.setTutorLeaderboardEntries(leaderboardEntries);\n final long totalNumberOfAssessmentLocks = submissionRepository.countLockedSubmissionsByExerciseId(exerciseId);\n stats.setTotalNumberOfAssessmentLocks(totalNumberOfAssessmentLocks);\n\n stats.setFeedbackRequestEnabled(course.getComplaintsEnabled());\n stats.setFeedbackRequestEnabled(course.getRequestMoreFeedbackEnabled());\n\n return stats;\n }\n\n /**\n * GET /exercises/:exerciseId/stats-for-instructor-dashboard A collection of useful statistics for the instructor exercise dashboard of the exercise with the given exerciseId\n *\n * @param exerciseId the exerciseId of the exercise to retrieve\n * @return the ResponseEntity with status 200 (OK) and with body the stats, or with status 404 (Not Found)\n */\n @GetMapping(\"/exercises/{exerciseId}/stats-for-instructor-dashboard\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<StatsForDashboardDTO> getStatsForInstructorExerciseDashboard(@PathVariable Long exerciseId) {\n log.debug(\"REST request to get exercise statistics for instructor dashboard : {}\", exerciseId);\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, exercise, null);\n\n StatsForDashboardDTO stats = populateCommonStatistics(exercise, exercise.isExamExercise());\n long numberOfOpenComplaints = complaintRepository.countComplaintsByExerciseIdAndComplaintType(exerciseId, ComplaintType.COMPLAINT);\n stats.setNumberOfOpenComplaints(numberOfOpenComplaints);\n\n long numberOfOpenMoreFeedbackRequests = complaintRepository.countByResult_Participation_Exercise_Course_IdAndComplaintType(exerciseId, ComplaintType.MORE_FEEDBACK);\n stats.setNumberOfOpenMoreFeedbackRequests(numberOfOpenMoreFeedbackRequests);\n return ResponseEntity.ok(stats);\n }\n\n /**\n * Reset the exercise by deleting all its partcipations /exercises/:exerciseId/reset This can be used by all exercise types, however they can also provide custom implementations\n *\n * @param exerciseId exercise to delete\n * @return the ResponseEntity with status 200 (OK)\n */\n @DeleteMapping(value = \"/exercises/{exerciseId}/reset\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Void> reset(@PathVariable Long exerciseId) {\n log.debug(\"REST request to reset Exercise : {}\", exerciseId);\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n authCheckService.checkHasAtLeastRoleForExerciseElseThrow(Role.INSTRUCTOR, exercise, null);\n exerciseService.reset(exercise);\n return ResponseEntity.ok().headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, \"exercise\", exerciseId.toString())).build();\n }\n\n /**\n * DELETE /exercises/:exerciseId/cleanup : delete all build plans (except BASE) of all participations belonging to this exercise. Optionally delete and archive all repositories\n *\n * @param exerciseId exercise to delete build plans for\n * @param deleteRepositories whether repositories should be deleted or not\n * @return ResponseEntity with status\n */\n @DeleteMapping(value = \"/exercises/{exerciseId}/cleanup\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n @FeatureToggle(Feature.PROGRAMMING_EXERCISES)\n public ResponseEntity<Resource> cleanup(@PathVariable Long exerciseId, @RequestParam(defaultValue = \"false\") boolean deleteRepositories) {\n log.info(\"Start to cleanup build plans for Exercise: {}, delete repositories: {}\", exerciseId, deleteRepositories);\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n if (!authCheckService.isAtLeastInstructorForExercise(exercise)) {\n return forbidden();\n }\n exerciseService.cleanup(exerciseId, deleteRepositories);\n log.info(\"Cleanup build plans was successful for Exercise : {}\", exerciseId);\n return ResponseEntity.ok().build();\n }\n\n /**\n * GET /exercises/:exerciseId/details : sends exercise details including all results for the currently logged in user\n *\n * @param exerciseId the exerciseId of the exercise to get the repos from\n * @return the ResponseEntity with status 200 (OK) and with body the exercise, or with status 404 (Not Found)\n */\n @GetMapping(value = \"/exercises/{exerciseId}/details\")\n @PreAuthorize(\"hasRole('USER')\")\n public ResponseEntity<Exercise> getExerciseDetails(@PathVariable Long exerciseId) {\n long start = System.currentTimeMillis();\n User user = userRepository.getUserWithGroupsAndAuthorities();\n log.debug(\"{} requested access for exercise with exerciseId {}\", user.getLogin(), exerciseId);\n\n Exercise exercise = exerciseService.findOneWithDetailsForStudents(exerciseId, user);\n\n // TODO: Create alternative route so that instructors and admins can access the exercise details\n // The users are not allowed to access the exercise details over this route if the exercise belongs to an exam\n if (exercise.isExamExercise()) {\n return forbidden();\n }\n\n // if exercise is not yet released to the students they should not have any access to it\n if (!authCheckService.isAllowedToSeeExercise(exercise, user)) {\n return forbidden();\n }\n\n List<StudentParticipation> participations = participationService.findByExerciseAndStudentIdWithEagerResultsAndSubmissions(exercise, user.getId());\n exercise.setStudentParticipations(new HashSet<>());\n for (StudentParticipation participation : participations) {\n\n participation.setResults(exercise.findResultsFilteredForStudents(participation));\n // By filtering the results available yet, they can become null for the exercise.\n if (participation.getResults() != null) {\n participation.getResults().forEach(r -> r.setAssessor(null));\n }\n exercise.addParticipation(participation);\n }\n\n if (exercise instanceof ProgrammingExercise) {\n ((ProgrammingExercise) exercise).checksAndSetsIfProgrammingExerciseIsLocalSimulation();\n }\n // TODO: we should also check that the submissions do not contain sensitive data\n\n // remove sensitive information for students\n if (!authCheckService.isAtLeastTeachingAssistantForExercise(exercise, user)) {\n exercise.filterSensitiveInformation();\n }\n\n log.debug(\"getResultsForCurrentUser took {}ms\", System.currentTimeMillis() - start);\n\n return ResponseUtil.wrapOrNotFound(Optional.of(exercise));\n }\n\n /**\n * GET /exercises/:exerciseId/toggle-second-correction\n *\n * @param exerciseId the exerciseId of the exercise to get the repos from\n * @return the ResponseEntity with status 200 (OK) and with body the exercise, or with status 404 (Not Found)\n */\n @PutMapping(value = \"/exercises/{exerciseId}/toggle-second-correction\")\n @PreAuthorize(\"hasRole('INSTRUCTOR')\")\n public ResponseEntity<Boolean> toggleSecondCorrectionEnabled(@PathVariable Long exerciseId) {\n log.debug(\"toggleSecondCorrectionEnabled for exercise with id: {}\", exerciseId);\n Exercise exercise = exerciseRepository.findByIdElseThrow(exerciseId);\n if (exercise == null) {\n throw new EntityNotFoundException(\"Exercise not found with id \" + exerciseId);\n }\n if (!authCheckService.isAtLeastInstructorForExercise(exercise)) {\n return forbidden();\n }\n return ResponseEntity.ok(exerciseRepository.toggleSecondCorrection(exercise));\n }\n\n}\n" }, { "alpha_fraction": 0.680736780166626, "alphanum_fraction": 0.6855717301368713, "avg_line_length": 45.87050247192383, "blob_id": "6dc54c4ab6324fc85099777cb74fa81aee0c3fd0", "content_id": "abb28420a3ab1124292faa615d46519c0824b829", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 13030, "license_type": "permissive", "max_line_length": 147, "num_lines": 278, "path": "/src/test/javascript/spec/component/text-exercise/example-text-submission.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { HttpResponse } from '@angular/common/http';\nimport { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';\nimport { FormsModule } from '@angular/forms';\nimport { By } from '@angular/platform-browser';\nimport { ActivatedRoute, ActivatedRouteSnapshot, convertToParamMap } from '@angular/router';\nimport { TranslateService } from '@ngx-translate/core';\nimport { AssessmentInstructionsComponent } from 'app/assessment/assessment-instructions/assessment-instructions/assessment-instructions.component';\nimport { ExampleSubmission } from 'app/entities/example-submission.model';\nimport { Feedback } from 'app/entities/feedback.model';\nimport { Result } from 'app/entities/result.model';\nimport { TextBlock } from 'app/entities/text-block.model';\nimport { TextExercise } from 'app/entities/text-exercise.model';\nimport { TextSubmission } from 'app/entities/text-submission.model';\nimport { TutorParticipationService } from 'app/exercises/shared/dashboards/tutor/tutor-participation.service';\nimport { ExampleSubmissionService } from 'app/exercises/shared/example-submission/example-submission.service';\nimport { ExerciseService } from 'app/exercises/shared/exercise/exercise.service';\nimport { TextAssessmentAreaComponent } from 'app/exercises/text/assess/text-assessment-area/text-assessment-area.component';\nimport { TextAssessmentService } from 'app/exercises/text/assess/text-assessment.service';\nimport { State } from 'app/exercises/text/manage/example-text-submission/example-text-submission-state.model';\nimport { ExampleTextSubmissionComponent } from 'app/exercises/text/manage/example-text-submission/example-text-submission.component';\nimport { AlertComponent } from 'app/shared/alert/alert.component';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport { ResizeableContainerComponent } from 'app/shared/resizeable-container/resizeable-container.component';\nimport { ScoreDisplayComponent } from 'app/shared/score-display/score-display.component';\nimport { MockComponent, MockPipe, MockProvider } from 'ng-mocks';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { of } from 'rxjs';\nimport { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service';\nimport { ArtemisTestModule } from '../../test.module';\n\ndescribe('ExampleTextSubmissionComponent', () => {\n let fixture: ComponentFixture<ExampleTextSubmissionComponent>;\n let comp: ExampleTextSubmissionComponent;\n let exerciseService: ExerciseService;\n let exampleSubmissionService: ExampleSubmissionService;\n let assessmentsService: TextAssessmentService;\n\n const EXERCISE_ID = 1;\n const EXAMPLE_SUBMISSION_ID = 2;\n const SUBMISSION_ID = 3;\n let exercise: TextExercise;\n let exampleSubmission: ExampleSubmission;\n let result: Result;\n let submission: TextSubmission;\n let activatedRouteSnapshot: ActivatedRouteSnapshot;\n\n beforeEach(async () => {\n const route: ActivatedRoute = {\n snapshot: {\n paramMap: convertToParamMap({}),\n queryParamMap: convertToParamMap({}),\n },\n } as any;\n await TestBed.configureTestingModule({\n imports: [ArtemisTestModule, FormsModule],\n declarations: [\n ExampleTextSubmissionComponent,\n MockComponent(ResizeableContainerComponent),\n MockComponent(ScoreDisplayComponent),\n MockComponent(TextAssessmentAreaComponent),\n MockComponent(AssessmentInstructionsComponent),\n MockPipe(ArtemisTranslatePipe),\n MockComponent(AlertComponent),\n ],\n providers: [\n {\n provide: ActivatedRoute,\n useValue: route,\n },\n { provide: LocalStorageService, useClass: MockSyncStorage },\n { provide: SessionStorageService, useClass: MockSyncStorage },\n MockProvider(TranslateService),\n ],\n }).compileComponents();\n\n fixture = TestBed.createComponent(ExampleTextSubmissionComponent);\n comp = fixture.componentInstance;\n activatedRouteSnapshot = fixture.debugElement.injector.get(ActivatedRoute).snapshot;\n exerciseService = fixture.debugElement.injector.get(ExerciseService);\n exampleSubmissionService = fixture.debugElement.injector.get(ExampleSubmissionService);\n assessmentsService = fixture.debugElement.injector.get(TextAssessmentService);\n\n exercise = new TextExercise(undefined, undefined);\n exercise.id = EXERCISE_ID;\n exercise.title = 'Test case exercise';\n exampleSubmission = new ExampleSubmission();\n exampleSubmission.id = EXAMPLE_SUBMISSION_ID;\n result = new Result();\n submission = result.submission = exampleSubmission.submission = new TextSubmission();\n submission.id = SUBMISSION_ID;\n });\n\n it('should fetch example submission with result for existing example submission and switch to edit state', fakeAsync(() => {\n // GIVEN\n // @ts-ignore\n activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };\n spyOn(exerciseService, 'find').and.returnValue(httpResponse(exercise));\n spyOn(exampleSubmissionService, 'get').and.returnValue(httpResponse(exampleSubmission));\n spyOn(assessmentsService, 'getExampleResult').and.returnValue(of(result));\n\n // WHEN\n fixture.detectChanges();\n tick();\n\n // THEN\n expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);\n expect(exampleSubmissionService.get).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID);\n expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);\n expect(comp.state.constructor.name).toEqual('EditState');\n }));\n\n it('should fetch only fetch exercise for new example submission and stay in new state', fakeAsync(() => {\n // GIVEN\n // @ts-ignore\n activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: 'new' };\n spyOn(exerciseService, 'find').and.returnValue(httpResponse(exercise));\n spyOn(exampleSubmissionService, 'get').and.stub();\n spyOn(assessmentsService, 'getExampleResult').and.stub();\n\n // WHEN\n fixture.detectChanges();\n tick();\n\n // THEN\n expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);\n expect(exampleSubmissionService.get).toHaveBeenCalledTimes(0);\n expect(assessmentsService.getExampleResult).toHaveBeenCalledTimes(0);\n expect(comp.state.constructor.name).toEqual('NewState');\n }));\n\n it('should switch state when starting assessment', fakeAsync(() => {\n // GIVEN\n // @ts-ignore\n activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };\n fixture.detectChanges();\n tick();\n comp.isAtLeastInstructor = true;\n comp.exercise = exercise;\n comp.exampleSubmission = exampleSubmission;\n comp.submission = submission;\n spyOn(assessmentsService, 'getExampleResult').and.returnValue(of(result));\n of();\n\n // WHEN\n fixture.detectChanges();\n tick();\n fixture.debugElement.query(By.css('#createNewAssessment')).nativeElement.click();\n tick();\n\n // THEN\n expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);\n expect(comp.state.constructor.name).toEqual('NewAssessmentState');\n }));\n\n it('should save assessment', fakeAsync(() => {\n // GIVEN\n // @ts-ignore\n activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };\n fixture.detectChanges();\n tick();\n comp.isAtLeastInstructor = true;\n comp.exercise = exercise;\n comp.exampleSubmission = exampleSubmission;\n comp.submission = submission;\n const textBlock1 = new TextBlock();\n textBlock1.startIndex = 0;\n textBlock1.endIndex = 4;\n textBlock1.setTextFromSubmission(submission);\n textBlock1.computeId();\n const textBlock2 = new TextBlock();\n textBlock2.startIndex = 5;\n textBlock2.endIndex = 9;\n textBlock2.setTextFromSubmission(submission);\n textBlock2.computeId();\n submission.blocks = [textBlock1, textBlock2];\n comp.result = result;\n const feedback = Feedback.forText(textBlock1, 0, 'Test');\n result.feedbacks = [feedback];\n comp.state.edit();\n comp.state.assess();\n comp['prepareTextBlocksAndFeedbacks']();\n comp.validateFeedback();\n spyOn(assessmentsService, 'saveExampleAssessment').and.returnValue(httpResponse(result));\n\n // WHEN\n fixture.detectChanges();\n tick();\n fixture.debugElement.query(By.css('#saveNewAssessment')).nativeElement.click();\n tick();\n\n // THEN\n expect(assessmentsService.saveExampleAssessment).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID, [feedback], [textBlock1]);\n }));\n\n it('editing submission from assessment state switches state', fakeAsync(() => {\n // GIVEN\n comp.isAtLeastInstructor = true;\n comp.exercise = exercise;\n comp.exampleSubmission = exampleSubmission;\n comp.submission = submission;\n const textBlock1 = new TextBlock();\n textBlock1.startIndex = 0;\n textBlock1.endIndex = 4;\n textBlock1.setTextFromSubmission(submission);\n textBlock1.computeId();\n const textBlock2 = new TextBlock();\n textBlock2.startIndex = 5;\n textBlock2.endIndex = 9;\n textBlock2.setTextFromSubmission(submission);\n textBlock2.computeId();\n submission.blocks = [textBlock1, textBlock2];\n comp.result = result;\n const feedback = Feedback.forText(textBlock1, 0, 'Test');\n result.feedbacks = [feedback];\n comp.state = State.forExistingAssessmentWithContext(comp);\n comp['prepareTextBlocksAndFeedbacks']();\n comp.validateFeedback();\n spyOn(assessmentsService, 'deleteExampleFeedback').and.returnValue(httpResponse(null));\n\n // WHEN\n fixture.detectChanges();\n tick();\n fixture.debugElement.query(By.css('#editSampleSolution')).nativeElement.click();\n tick();\n\n // THEN\n expect(comp.state.constructor.name).toEqual('EditState');\n expect(assessmentsService.deleteExampleFeedback).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID);\n expect(comp.submission?.blocks).toBeUndefined();\n expect(comp.result?.feedbacks).toBeUndefined();\n expect(comp.textBlockRefs).toHaveLength(0);\n expect(comp.unusedTextBlockRefs).toHaveLength(0);\n }));\n\n it('it should verify correct tutorial submission', fakeAsync(() => {\n // GIVEN\n // @ts-ignore\n activatedRouteSnapshot.paramMap.params = { exerciseId: EXERCISE_ID, exampleSubmissionId: EXAMPLE_SUBMISSION_ID };\n // @ts-ignore\n activatedRouteSnapshot.queryParamMap.params = { toComplete: true };\n spyOn(exerciseService, 'find').and.returnValue(httpResponse(exercise));\n spyOn(exampleSubmissionService, 'get').and.returnValue(httpResponse(exampleSubmission));\n const textBlock1 = new TextBlock();\n textBlock1.startIndex = 0;\n textBlock1.endIndex = 4;\n textBlock1.setTextFromSubmission(submission);\n textBlock1.computeId();\n const textBlock2 = new TextBlock();\n textBlock2.startIndex = 5;\n textBlock2.endIndex = 9;\n textBlock2.setTextFromSubmission(submission);\n textBlock2.computeId();\n submission.blocks = [textBlock1, textBlock2];\n spyOn(assessmentsService, 'getExampleResult').and.returnValue(of(result));\n fixture.detectChanges();\n tick();\n\n comp.textBlockRefs[0].initFeedback();\n comp.textBlockRefs[0].feedback!.credits = 2;\n comp.validateFeedback();\n const tutorParticipationService = fixture.debugElement.injector.get(TutorParticipationService);\n spyOn(tutorParticipationService, 'assessExampleSubmission').and.returnValue(httpResponse(null));\n\n // WHEN\n fixture.detectChanges();\n tick();\n fixture.debugElement.query(By.css('#checkAssessment')).nativeElement.click();\n tick();\n\n // THEN\n expect(exerciseService.find).toHaveBeenCalledWith(EXERCISE_ID);\n expect(exampleSubmissionService.get).toHaveBeenCalledWith(EXAMPLE_SUBMISSION_ID);\n expect(assessmentsService.getExampleResult).toHaveBeenCalledWith(EXERCISE_ID, SUBMISSION_ID);\n expect(tutorParticipationService.assessExampleSubmission).toHaveBeenCalled();\n }));\n\n const httpResponse = (body: any) => of(new HttpResponse({ body }));\n});\n" }, { "alpha_fraction": 0.7990372776985168, "alphanum_fraction": 0.7990372776985168, "avg_line_length": 60.55555725097656, "blob_id": "15026bfe16d6053d4ee5e22125c5a238c57e6fd0", "content_id": "fea97e2d5b0b58b3d39ae4985e824e231209c395", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1662, "license_type": "permissive", "max_line_length": 168, "num_lines": 27, "path": "/src/main/webapp/app/overview/student-questions/student-questions.module.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { NgModule } from '@angular/core';\nimport { ArtemisSharedModule } from 'app/shared/shared.module';\nimport { ArtemisSidePanelModule } from 'app/shared/side-panel/side-panel.module';\nimport { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module';\nimport { StudentQuestionsComponent } from 'app/overview/student-questions/student-questions.component';\nimport { StudentQuestionRowComponent } from 'app/overview/student-questions/student-question-row/student-question-row.component';\nimport { StudentQuestionComponent } from 'app/overview/student-questions/student-question/student-question.component';\nimport { StudentQuestionAnswerComponent } from 'app/overview/student-questions/student-question-answer/student-question-answer.component';\nimport { StudentVotesComponent } from 'app/overview/student-questions/student-votes/student-votes.component';\nimport { RouterModule, Routes } from '@angular/router';\nimport { ArtemisMarkdownModule } from 'app/shared/markdown.module';\nimport { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module';\n\nconst routes: Routes = [\n {\n path: '',\n pathMatch: 'full',\n component: StudentQuestionsComponent,\n },\n];\n\n@NgModule({\n imports: [RouterModule.forChild(routes), ArtemisSharedModule, ArtemisSidePanelModule, ArtemisConfirmIconModule, ArtemisMarkdownModule, ArtemisMarkdownEditorModule],\n declarations: [StudentQuestionsComponent, StudentQuestionRowComponent, StudentQuestionComponent, StudentQuestionAnswerComponent, StudentVotesComponent],\n exports: [StudentQuestionsComponent],\n})\nexport class ArtemisStudentQuestionsModule {}\n" }, { "alpha_fraction": 0.6386248469352722, "alphanum_fraction": 0.6395363807678223, "avg_line_length": 40.73369598388672, "blob_id": "0e298fd4ae1eee8dc4e4504f01e23478450049d9", "content_id": "10b9d1d8ac235b80b8b8d89593b910c77fcaf66f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 7679, "license_type": "permissive", "max_line_length": 171, "num_lines": 184, "path": "/src/main/webapp/app/complaints/list-of-complaints/list-of-complaints.component.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Component, OnInit } from '@angular/core';\nimport { Location } from '@angular/common';\nimport { JhiAlertService } from 'ng-jhipster';\nimport { ComplaintService } from 'app/complaints/complaint.service';\nimport { Complaint, ComplaintType } from 'app/entities/complaint.model';\nimport { HttpResponse } from '@angular/common/http';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { Observable } from 'rxjs';\nimport { ExerciseType } from 'app/entities/exercise.model';\nimport * as moment from 'moment';\nimport { StudentParticipation } from 'app/entities/participation/student-participation.model';\nimport { NgbModal } from '@ng-bootstrap/ng-bootstrap';\nimport { SortService } from 'app/shared/service/sort.service';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { TranslateService } from '@ngx-translate/core';\n\n@Component({\n // TODO this selector is used twice which is not good!!!\n selector: 'jhi-complaint-form',\n templateUrl: './list-of-complaints.component.html',\n providers: [],\n})\nexport class ListOfComplaintsComponent implements OnInit {\n public complaints: Complaint[] = [];\n public hasStudentInformation = false;\n public complaintType: ComplaintType;\n ComplaintType = ComplaintType;\n\n private courseId: number;\n private exerciseId: number;\n private tutorId: number;\n private examId?: number;\n private correctionRound?: number;\n complaintsSortingPredicate = 'id';\n complaintsReverseOrder = false;\n complaintsToShow: Complaint[] = [];\n showAddressedComplaints = false;\n\n loading = true;\n\n constructor(\n private complaintService: ComplaintService,\n private jhiAlertService: JhiAlertService,\n private route: ActivatedRoute,\n private router: Router,\n private location: Location,\n private modalService: NgbModal,\n private sortService: SortService,\n private translateService: TranslateService,\n private artemisDatePipe: ArtemisDatePipe,\n ) {}\n\n ngOnInit(): void {\n this.route.params.subscribe((params) => {\n this.courseId = Number(params['courseId']);\n this.exerciseId = Number(params['exerciseId']);\n this.examId = Number(params['examId']);\n });\n this.route.queryParams.subscribe((queryParams) => {\n this.tutorId = Number(queryParams['tutorId']);\n this.correctionRound = Number(queryParams['correctionRound']);\n });\n this.route.data.subscribe((data) => (this.complaintType = data.complaintType));\n this.loadComplaints();\n }\n\n loadComplaints() {\n let complaintResponse: Observable<HttpResponse<Complaint[]>>;\n\n if (this.tutorId) {\n if (this.exerciseId) {\n complaintResponse = this.complaintService.findAllByTutorIdForExerciseId(this.tutorId, this.exerciseId, this.complaintType);\n } else if (this.examId) {\n // TODO make exam complaints visible for tutors too\n complaintResponse = this.complaintService.findAllByTutorIdForCourseId(this.tutorId, this.courseId, this.complaintType);\n } else {\n complaintResponse = this.complaintService.findAllByTutorIdForCourseId(this.tutorId, this.courseId, this.complaintType);\n }\n } else {\n if (this.exerciseId) {\n complaintResponse = this.complaintService.findAllByExerciseId(this.exerciseId, this.complaintType);\n } else if (this.examId) {\n complaintResponse = this.complaintService.findAllByCourseIdAndExamId(this.courseId, this.examId);\n } else {\n complaintResponse = this.complaintService.findAllByCourseId(this.courseId, this.complaintType);\n }\n }\n\n complaintResponse.subscribe(\n (res) => {\n this.complaints = res.body!;\n this.complaintsToShow = this.complaints.filter((complaint) => complaint.accepted === undefined);\n\n if (this.complaints.length > 0 && this.complaints[0].student) {\n this.hasStudentInformation = true;\n }\n },\n () => this.onError(),\n () => (this.loading = false),\n );\n }\n\n openAssessmentEditor(complaint: Complaint) {\n if (!complaint || !complaint.result || !complaint.result.participation || !complaint.result.submission) {\n return;\n }\n\n const studentParticipation = complaint.result.participation as StudentParticipation;\n const exercise = studentParticipation.exercise;\n const submissionId = complaint.result.submission.id;\n if (!exercise || !exercise.type || !submissionId) {\n return;\n }\n if (!this.correctionRound) {\n this.correctionRound = 0;\n }\n\n switch (exercise.type) {\n case ExerciseType.TEXT:\n case ExerciseType.MODELING:\n case ExerciseType.FILE_UPLOAD:\n const url = [`/course-management/${this.courseId}/${exercise.type}-exercises/${exercise.id}/submissions/${submissionId}/assessment`];\n this.router.navigate(url, { queryParams: { 'correction-round': this.correctionRound } });\n return;\n case ExerciseType.PROGRAMMING:\n const urlProgramming = [`/course-management/${this.courseId}/${exercise.type}-exercises/${exercise.id}/code-editor/${studentParticipation.id}/assessment`];\n this.router.navigate(urlProgramming, { queryParams: { 'correction-round': this.correctionRound } });\n return;\n }\n }\n\n private onError() {\n this.jhiAlertService.error('error.http.400');\n }\n\n sortRows() {\n this.sortService.sortByProperty(this.complaintsToShow, this.complaintsSortingPredicate, this.complaintsReverseOrder);\n }\n\n triggerAddressedComplaints() {\n this.showAddressedComplaints = !this.showAddressedComplaints;\n\n if (this.showAddressedComplaints) {\n this.complaintsToShow = this.complaints;\n } else {\n this.complaintsToShow = this.complaints.filter((complaint) => complaint.accepted === undefined);\n }\n }\n\n shouldHighlightComplaint(complaint: Complaint) {\n // Reviewed complaints shouldn't be highlight\n if (complaint.accepted !== undefined) {\n return false;\n }\n\n const complaintSubmittedTime = complaint.submittedTime;\n if (complaintSubmittedTime) {\n return moment().diff(complaintSubmittedTime, 'days') > 7; // We highlight complaints older than a week\n }\n\n return false;\n }\n\n calculateComplaintLockStatus(complaint: Complaint) {\n if (complaint.complaintResponse && this.complaintService.isComplaintLocked(complaint)) {\n if (this.complaintService.isComplaintLockedByLoggedInUser(complaint)) {\n const endDate = this.artemisDatePipe.transform(complaint.complaintResponse?.lockEndDate);\n return this.translateService.instant('artemisApp.locks.lockInformationYou', {\n endDate,\n });\n } else {\n const endDate = this.artemisDatePipe.transform(complaint.complaintResponse?.lockEndDate);\n const user = complaint.complaintResponse?.reviewer?.login;\n\n return this.translateService.instant('artemisApp.locks.lockInformation', {\n endDate,\n user,\n });\n }\n } else {\n return this.translateService.instant('artemisApp.locks.notUnlocked');\n }\n }\n}\n" }, { "alpha_fraction": 0.7309321761131287, "alphanum_fraction": 0.7309321761131287, "avg_line_length": 26.764705657958984, "blob_id": "ab14e2cc475e9cd6f3d2e84f13467d3e8c02482d", "content_id": "45d5ecea635b470a32f02e49c026cc485e582477", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 472, "license_type": "permissive", "max_line_length": 81, "num_lines": 17, "path": "/src/main/webapp/app/shared/notification/connection-notification/connection-notification.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Moment } from 'moment';\nimport { Notification, NotificationType } from 'app/entities/notification.model';\n\nexport const enum ConnectionNotificationType {\n DISCONNECTED = 'DISCONNECTED',\n RECONNECTED = 'RECONNECTED',\n CONNECTED = 'CONNECTED',\n}\n\nexport class ConnectionNotification extends Notification {\n public expireDate: Moment;\n public type?: ConnectionNotificationType;\n\n constructor() {\n super(NotificationType.CONNECTION);\n }\n}\n" }, { "alpha_fraction": 0.6616021990776062, "alphanum_fraction": 0.6616021990776062, "avg_line_length": 42.878787994384766, "blob_id": "c4072fc16244d68be2934a77aa9b1979ba1d1767", "content_id": "e631cb77bfd53bb048adce939634cc1b6249df3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 1448, "license_type": "permissive", "max_line_length": 138, "num_lines": 33, "path": "/src/main/webapp/app/core/interceptor/auth.interceptor.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { Observable } from 'rxjs';\nimport { LocalStorageService, SessionStorageService } from 'ngx-webstorage';\nimport { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';\nimport { isRequestToArtemisServer } from './interceptor.util';\n\n@Injectable()\nexport class AuthInterceptor implements HttpInterceptor {\n constructor(private localStorage: LocalStorageService, private sessionStorage: SessionStorageService) {}\n\n /**\n * Identifies and handles a given HTTP request. If the request is valid, add a authenticationToken from localStorage or sessionStorage\n * and pass on to next.\n * @param request The outgoing request object to handle.\n * @param next The next interceptor in the chain, or the server\n * if no interceptors remain in the chain.\n * @returns An observable of the event stream.\n */\n intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n if (isRequestToArtemisServer(request)) {\n const token = this.localStorage.retrieve('authenticationToken') || this.sessionStorage.retrieve('authenticationToken');\n if (token) {\n request = request.clone({\n setHeaders: {\n Authorization: 'Bearer ' + token,\n },\n });\n }\n }\n\n return next.handle(request);\n }\n}\n" }, { "alpha_fraction": 0.5990836024284363, "alphanum_fraction": 0.6116838455200195, "avg_line_length": 36.956520080566406, "blob_id": "f31053b3b5c2f899cc4e5357a4c125d4244b2efd", "content_id": "9bb82618562bf60a5a2c71e4dc522d3b7e962738", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 873, "license_type": "permissive", "max_line_length": 122, "num_lines": 23, "path": "/src/test/k6/requests/text.js", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { fail } from 'k6';\nimport { nextAlphanumeric } from '../util/utils.js';\nimport { SUBMIT_TEXT_EXAM } from './endpoints.js';\n\nexport function submitRandomTextAnswerExam(artemis, exercise, submissionId) {\n const answer = {\n id: submissionId,\n isSynced: false,\n submissionExerciseType: 'text',\n submitted: true,\n text: 'SOME RANDOM ANSWER ' + nextAlphanumeric(100),\n };\n\n let res = artemis.put(SUBMIT_TEXT_EXAM(exercise.id), answer);\n if (res[0].status !== 200) {\n console.log('ERROR when submitting text (Exam) via REST. Response headers:');\n for (let [key, value] of Object.entries(res[0].headers)) {\n console.log(`${key}: ${value}`);\n }\n fail('FAILTEST: Could not submit text (Exam) via REST (status: ' + res[0].status + ')! response: ' + res[0].body);\n }\n return answer;\n}\n" }, { "alpha_fraction": 0.6587756872177124, "alphanum_fraction": 0.6617347598075867, "avg_line_length": 38.757354736328125, "blob_id": "c6a98f08ac38ded62ae58f96672ac0775fdab10c", "content_id": "5393d27890f0016fe887fd2a89d984a12798ce13", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 5407, "license_type": "permissive", "max_line_length": 117, "num_lines": 136, "path": "/src/test/javascript/spec/component/overview/course-lectures/course-lecture-row.component.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { ComponentFixture, TestBed } from '@angular/core/testing';\nimport { By } from '@angular/platform-browser';\nimport { ActivatedRoute, Router } from '@angular/router';\nimport { FaIconComponent } from '@fortawesome/angular-fontawesome';\nimport { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';\nimport { Course } from 'app/entities/course.model';\nimport { Lecture } from 'app/entities/lecture.model';\nimport { CourseLectureRowComponent } from 'app/overview/course-lectures/course-lecture-row.component';\nimport { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe';\nimport { ArtemisTimeAgoPipe } from 'app/shared/pipes/artemis-time-ago.pipe';\nimport { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe.ts';\nimport * as chai from 'chai';\nimport * as moment from 'moment';\nimport { MockComponent, MockDirective, MockPipe } from 'ng-mocks';\nimport * as sinon from 'sinon';\nimport * as sinonChai from 'sinon-chai';\n\nchai.use(sinonChai);\nconst expect = chai.expect;\n\ndescribe('CourseLectureRow', () => {\n let courseLectureRowComponentFixture: ComponentFixture<CourseLectureRowComponent>;\n let courseLectureRowComponent: CourseLectureRowComponent;\n let mockRouter: any;\n let mockActivatedRoute: any;\n\n beforeEach(() => {\n mockRouter = sinon.createStubInstance(Router);\n mockActivatedRoute = sinon.createStubInstance(ActivatedRoute);\n\n TestBed.configureTestingModule({\n imports: [],\n declarations: [\n CourseLectureRowComponent,\n MockPipe(ArtemisTranslatePipe),\n MockPipe(ArtemisDatePipe),\n MockComponent(FaIconComponent),\n MockDirective(NgbTooltip),\n MockPipe(ArtemisTimeAgoPipe),\n ],\n providers: [\n { provide: ActivatedRoute, useValue: mockActivatedRoute },\n { provide: Router, useValue: mockRouter },\n ],\n schemas: [],\n })\n .compileComponents()\n .then(() => {\n courseLectureRowComponentFixture = TestBed.createComponent(CourseLectureRowComponent);\n courseLectureRowComponent = courseLectureRowComponentFixture.componentInstance;\n });\n });\n\n afterEach(function () {\n sinon.restore();\n });\n\n it('should initialize', () => {\n courseLectureRowComponentFixture.detectChanges();\n expect(courseLectureRowComponent).to.be.ok;\n });\n\n it('should set urgent class to date if remaining days is less than 7 days', () => {\n const lecture = new Lecture();\n lecture.id = 1;\n lecture.title = 'exampleLecture';\n lecture.startDate = moment().add(1, 'd');\n const course = new Course();\n course.id = 1;\n\n courseLectureRowComponent.lecture = lecture;\n courseLectureRowComponent.course = course;\n courseLectureRowComponentFixture.detectChanges();\n\n const dateContainer = courseLectureRowComponentFixture.debugElement.query(By.css('.text-danger'));\n expect(dateContainer).to.be.ok;\n });\n\n it('should not urgent class to date if remaining days is more than 7 days', () => {\n const lecture = new Lecture();\n lecture.id = 1;\n lecture.title = 'exampleLecture';\n lecture.startDate = moment().add(9, 'd');\n const course = new Course();\n course.id = 1;\n\n courseLectureRowComponent.lecture = lecture;\n courseLectureRowComponent.course = course;\n courseLectureRowComponentFixture.detectChanges();\n\n const dateContainer = courseLectureRowComponentFixture.debugElement.query(By.css('.text-danger'));\n expect(dateContainer).to.not.exist;\n });\n\n it('navigate to details page if row is clicked and extendedLink is activated', () => {\n const lecture = new Lecture();\n lecture.id = 1;\n lecture.title = 'exampleLecture';\n const course = new Course();\n course.id = 1;\n\n courseLectureRowComponent.lecture = lecture;\n courseLectureRowComponent.course = course;\n courseLectureRowComponent.extendedLink = true;\n\n courseLectureRowComponentFixture.detectChanges();\n\n const icon = courseLectureRowComponentFixture.debugElement.nativeElement.querySelector('.exercise-row-icon');\n icon.click();\n\n expect(mockRouter.navigate).to.have.been.calledOnce;\n const navigationArray = mockRouter.navigate.getCall(0).args[0];\n expect(navigationArray).to.deep.equal(['courses', course.id, 'lectures', lecture.id]);\n });\n\n it('navigate to details page if row is clicked and extendedLink is deactivated', () => {\n const lecture = new Lecture();\n lecture.id = 1;\n lecture.title = 'exampleLecture';\n const course = new Course();\n course.id = 1;\n\n courseLectureRowComponent.lecture = lecture;\n courseLectureRowComponent.course = course;\n courseLectureRowComponent.extendedLink = false;\n\n courseLectureRowComponentFixture.detectChanges();\n\n const icon = courseLectureRowComponentFixture.debugElement.nativeElement.querySelector('.exercise-row-icon');\n icon.click();\n\n expect(mockRouter.navigate).to.have.been.calledOnce;\n const navigationArray = mockRouter.navigate.getCall(0).args[0];\n expect(navigationArray).to.deep.equal([lecture.id]);\n });\n});\n" }, { "alpha_fraction": 0.5773889422416687, "alphanum_fraction": 0.590847909450531, "avg_line_length": 29.95833396911621, "blob_id": "1156f61f6c510035532a5be90743e8ff55429e19", "content_id": "1fb9d8457840653c9262d22ecad65129f0c05fb2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 743, "license_type": "permissive", "max_line_length": 70, "num_lines": 24, "path": "/src/main/webapp/app/shared/pipes/artemis-duration-from-seconds.pipe.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({ name: 'artemisDurationFromSeconds' })\nexport class ArtemisDurationFromSecondsPipe implements PipeTransform {\n /**\n * Convert seconds to a human-readable duration format (mm:ss).\n * @param seconds {number}\n */\n transform(seconds: number): string {\n const minutes = Math.floor(seconds / 60);\n seconds = seconds - minutes * 60;\n\n let minutesOut = minutes.toString();\n if (minutes < 10) {\n minutesOut = '0' + minutes.toString();\n }\n let secondsOut = seconds.toString();\n if (seconds < 10) {\n secondsOut = '0' + seconds.toString();\n }\n\n return minutesOut + ':' + secondsOut;\n }\n}\n" }, { "alpha_fraction": 0.7433155179023743, "alphanum_fraction": 0.7433155179023743, "avg_line_length": 61.33333206176758, "blob_id": "7bb3b81e2dcad105b4d2861b3cf515003c09bec3", "content_id": "c0dfa7f6e88dd1fafa05042f3943454999d9cde3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 187, "license_type": "permissive", "max_line_length": 85, "num_lines": 3, "path": "/src/test/javascript/spec/helpers/jest.fix.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "// male sure that jest except is available and preferred to prevent TypeScript errors\n// type JestExpect = <T>(actual: T) => jest.Matchers<T>;\n// export declare const expect: JestExpect;\n" }, { "alpha_fraction": 0.4034244418144226, "alphanum_fraction": 0.430759996175766, "avg_line_length": 26.974790573120117, "blob_id": "d793994fddf63ac30b8cc1fa9527a709dc906346", "content_id": "f39f10eae7fd49b6a7c7bee480b811192fc5cf39", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 3329, "license_type": "permissive", "max_line_length": 103, "num_lines": 119, "path": "/src/test/javascript/spec/service/sort.service.spec.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { getTestBed, TestBed } from '@angular/core/testing';\nimport * as moment from 'moment';\nimport { SortService } from 'app/shared/service/sort.service';\n\ntype TestObject = {\n a: number;\n b: string;\n c: moment.Moment;\n d?: number | null;\n e: Map<string, number>;\n};\n\ndescribe('Sort Service', () => {\n let injector: TestBed;\n let service: SortService;\n let e1: TestObject, e2: TestObject, e3: TestObject, e4: TestObject, e5: TestObject, e6: TestObject;\n\n beforeEach(() => {\n TestBed.configureTestingModule({});\n injector = getTestBed();\n service = injector.get(SortService);\n\n e1 = {\n a: 10,\n b: 'dog',\n c: moment().subtract(1, 'days'),\n d: 2,\n e: new Map().set('f', 4),\n };\n e2 = {\n a: 18,\n b: 'cat',\n c: moment().subtract(20, 'hours'),\n d: 5,\n e: new Map().set('f', 8),\n };\n e3 = {\n a: 4,\n b: 'snake',\n c: moment().add(3, 'minutes'),\n d: null,\n e: new Map().set('f', 29),\n };\n e4 = {\n a: 28,\n b: 'panda',\n c: moment().subtract(4, 'years'),\n d: 1,\n e: new Map().set('f', 43),\n };\n e5 = {\n a: 15,\n b: 'giraffe',\n c: moment().add(2, 'hours'),\n d: 4,\n e: new Map().set('f', 6),\n };\n e6 = {\n a: 7,\n b: 'tiger',\n c: moment().subtract(5, 'minutes'),\n e: new Map().set('f', 16),\n };\n });\n\n describe('Service methods', () => {\n it(\n 'should sort basic array ascending',\n repeatWithRandomArray(10, (arr) => {\n service.sortByProperty(arr, 'a', true);\n expect(arr).toEqual([e3, e6, e1, e5, e2, e4]);\n }),\n );\n\n it(\n 'should sort basic array descending',\n repeatWithRandomArray(10, (arr) => {\n service.sortByProperty(arr, 'b', false);\n expect(arr).toEqual([e6, e3, e4, e5, e1, e2]);\n }),\n );\n\n it(\n 'should sort array with moment properties',\n repeatWithRandomArray(10, (arr) => {\n service.sortByProperty(arr, 'c', true);\n expect(arr).toEqual([e4, e1, e2, e6, e3, e5]);\n }),\n );\n\n it(\n 'should sort array with null properties',\n repeatWithRandomArray(10, (arr) => {\n service.sortByProperty(arr, 'd', true);\n expect(arr.slice(0, 4)).toEqual([e4, e1, e5, e2]);\n }),\n );\n\n it(\n 'should sort array of nested maps',\n repeatWithRandomArray(10, (arr) => {\n service.sortByProperty(arr, 'e.f', true);\n expect(arr).toEqual([e1, e5, e2, e6, e3, e4]);\n }),\n );\n });\n\n function repeatWithRandomArray(times: number, fn: (arr: TestObject[]) => void) {\n return () => {\n while (times-- > 0) {\n fn(shuffle([e1, e2, e3, e4, e5, e6]));\n }\n };\n }\n\n function shuffle(array: TestObject[]) {\n return array.sort(() => Math.random() - 0.5);\n }\n});\n" }, { "alpha_fraction": 0.5916013121604919, "alphanum_fraction": 0.5929856896400452, "avg_line_length": 40.67307662963867, "blob_id": "e96e998385ac0570236cb310ec7aeba707a11c17", "content_id": "468e252444445e289088e5b61f76b8bed64cbc73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 2167, "license_type": "permissive", "max_line_length": 97, "num_lines": 52, "path": "/src/main/webapp/app/shared/quiz/quiz.service.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "import { Injectable } from '@angular/core';\nimport { QuizExercise } from 'app/entities/quiz/quiz-exercise.model';\nimport { QuizQuestionType } from 'app/entities/quiz/quiz-question.model';\nimport { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model';\nimport { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model';\nimport * as Sentry from '@sentry/browser';\n\n@Injectable({ providedIn: 'root' })\nexport class ArtemisQuizService {\n /**\n * Randomize the order of the questions\n * (and answerOptions or dragItems within each question)\n * if randomizeOrder is true\n *\n * @param quizExercise {object} the quizExercise to randomize elements in\n */\n randomizeOrder(quizExercise: QuizExercise) {\n if (quizExercise.quizQuestions) {\n // shuffle questions\n if (quizExercise.randomizeQuestionOrder) {\n this.shuffle(quizExercise.quizQuestions);\n }\n\n // shuffle answerOptions / dragItems within questions\n quizExercise.quizQuestions.forEach((question) => {\n if (question.randomizeOrder) {\n if (question.type === QuizQuestionType.MULTIPLE_CHOICE) {\n this.shuffle((question as MultipleChoiceQuestion).answerOptions!);\n } else if (question.type === QuizQuestionType.DRAG_AND_DROP) {\n this.shuffle((question as DragAndDropQuestion).dragItems!);\n } else if (question.type === QuizQuestionType.SHORT_ANSWER) {\n } else {\n Sentry.captureException(new Error('Unknown question type: ' + question));\n }\n }\n }, this);\n }\n }\n\n /**\n * Shuffles array in place.\n * @param {Array} items An array containing the items.\n */\n shuffle<T>(items: T[]) {\n for (let i = items.length - 1; i > 0; i--) {\n const pickedIndex = Math.floor(Math.random() * (i + 1));\n const picked = items[pickedIndex];\n items[pickedIndex] = items[i];\n items[i] = picked;\n }\n }\n}\n" }, { "alpha_fraction": 0.7002096176147461, "alphanum_fraction": 0.7002096176147461, "avg_line_length": 22.850000381469727, "blob_id": "504f29d9b87343fcf90388001fea9e12818df36d", "content_id": "cd2fed453f90dae4945da1c8513a0223b8c2f7c5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "TypeScript", "length_bytes": 477, "license_type": "permissive", "max_line_length": 63, "num_lines": 20, "path": "/src/main/webapp/app/entities/modeling-statistic.model.ts", "repo_name": "moritzhertler/Artemis", "src_encoding": "UTF-8", "text": "export interface UniqueElementStatistic {\n name: string;\n apollonId: string;\n conflict: boolean;\n}\n\nexport interface ModelStatistic {\n confidence: number;\n coverage: number;\n conflicts: number;\n}\n\nexport interface ModelingStatistic {\n numberModels: number;\n numberConflicts: number;\n totalConfidence: number;\n totalCoverage: number;\n uniqueElements: [{ [id: string]: UniqueElementStatistic }];\n models: [{ [id: string]: ModelStatistic }];\n}\n" } ]
702
mpetruzelli/new_relic
https://github.com/mpetruzelli/new_relic
e9c385545317b6e71e0e364c3017e404c239f6a4
d429bfec9ba9fbbba7a80470a91d21f599419d70
0d2fd08dfdf5458a448a019ff63bca928d1f6c3a
refs/heads/master
2020-04-05T06:34:26.567460
2018-11-09T17:57:27
2018-11-09T17:57:27
156,642,391
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6219974756240845, "alphanum_fraction": 0.6270543336868286, "avg_line_length": 24.516128540039062, "blob_id": "593a5288b3ff1850a83ab78e3599bb451e4292a9", "content_id": "c836c3efad8a76d5d0ccb713d89123d0719bab37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 70, "num_lines": 31, "path": "/setup.py", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport codecs\nimport os\nimport re\n\nfrom setuptools import setup\n\nfile_path = os.path.abspath(os.path.dirname(__file__))\n\n\ndef readfile(*parts):\n return codecs.open(os.path.join(file_path, *parts), 'r').read()\n\n\ndef find_version(*file_paths):\n version_file = readfile(*file_paths)\n version_match = re.search(\n r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError('Unable to find version string')\n\n\nsetup(name='phrases',\n version=find_version('src', 'phrases', '__init__.py'),\n description='Print top 10, most common 3 word phrases in input',\n packages=['phrases'],\n package_dir={'': 'src'},\n scripts=['bin/phrases'],\n zip_safe=False)\n" }, { "alpha_fraction": 0.5463435649871826, "alphanum_fraction": 0.5497449040412903, "avg_line_length": 35.75, "blob_id": "5019f5ecbd8cb7bf6963912a8850ce65c1b6d8ae", "content_id": "9bffefe53b2d5c708d8ed5caa521150d0da265af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2352, "license_type": "no_license", "max_line_length": 66, "num_lines": 64, "path": "/src/phrases/test_top_ten.py", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "import unittest\nimport subprocess\nimport os\nfrom phrases import top_ten\n\n\nclass TestTopTen(unittest.TestCase):\n\n def setUp(self):\n self.pass_list = [\"a b c\", \"A B C\", \"a B c\", \"$a %B !C\"]\n self.fail_list = [\"a b c\", \"D E F\", \"G i j\", \"$H &E !Y\"]\n\n for index, item in enumerate(self.pass_list):\n with open(str(index) + '_pass.txt', 'w') as text_file:\n text_file.write(item)\n for index, item in enumerate(self.fail_list):\n with open(str(index) + '_fail.txt', 'w') as text_file:\n text_file.write(item)\n\n def test_top_ten_files(self):\n test_results = list()\n for index, item in enumerate(self.pass_list):\n test_results.append(subprocess.check_output(\n \"phrases %s_pass.txt\" % index, shell=True))\n if len(test_results) > 2:\n self.assertEqual(\n test_results[index], test_results[1])\n\n def test_top_ten_stdin(self):\n test_results = list()\n for index, item in enumerate(self.pass_list):\n test_results.append(subprocess.check_output(\n \"cat %s_pass.txt | phrases\" % index, shell=True))\n if len(test_results) > 2:\n self.assertEqual(\n test_results[index], test_results[1])\n\n def test_fail_top_ten_files(self):\n test_results = list()\n for index, item in enumerate(self.fail_list):\n test_results.append(subprocess.check_output(\n \"phrases %s_fail.txt\" % index, shell=True))\n if len(test_results) > 2:\n self.assertNotEqual(\n test_results[index], test_results[1])\n\n def test_fail_top_ten_stdin(self):\n test_results = list()\n for index, item in enumerate(self.fail_list):\n test_results.append(subprocess.check_output(\n \"cat %s_fail.txt | phrases\" % index, shell=True))\n if len(test_results) > 2:\n self.assertNotEqual(\n test_results[index], test_results[1])\n\n def tearDown(self):\n for index, item in enumerate(self.pass_list):\n os.remove(str(index) + '_pass.txt')\n for index, item in enumerate(self.fail_list):\n os.remove(str(index) + '_fail.txt')\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6788793206214905, "alphanum_fraction": 0.6982758641242981, "avg_line_length": 15.571428298950195, "blob_id": "2eac9af1c7704bb39bc72feb99a095fc5b9b5421", "content_id": "1827fb18025da5b65e3a02db65be16e15ebaa2ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 464, "license_type": "no_license", "max_line_length": 89, "num_lines": 28, "path": "/Dockerfile", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "FROM ubuntu:18.04 AS builder\n\n\n\nRUN mkdir -p /build/src && \\\n mkdir -p /build/bin && \\\n apt-get update && \\\n apt-get install python3-dev python3 python3-venv python-pip -y\n\nCOPY src /build/src\nCOPY bin /build/bin\nCOPY setup.py /build/setup.py\n\nWORKDIR /build\n\nRUN pip install -e .\n\nFROM builder\n\nWORKDIR /build/src\n\nRUN python */test_*.py\n\nFROM builder\n\nWORKDIR /\n\nCMD echo 'Usage: mount volumes with desired files, and run \"phrases file1.txt file2.txt\"'\n" }, { "alpha_fraction": 0.5263158082962036, "alphanum_fraction": 0.535469114780426, "avg_line_length": 20.850000381469727, "blob_id": "47420bea63c5dfa28a1355474e10a22f8707f5a1", "content_id": "7f18abd80b0808ae2f777eb909911a82a553a101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 48, "num_lines": 20, "path": "/src/phrases/__main__.py", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "import sys\nfrom phrases import top_ten\n\n\ndef main():\n try:\n if sys.stdin.isatty():\n if not sys.argv[1]:\n raise IndexError\n except IndexError:\n print(\"no stdin or file paths supplied\")\n print(\"Usages: \")\n print(\" phrases file1.txt file2.txt\")\n print(\" cat file2.txt | phrases\")\n else:\n print(\"{}\".format(top_ten.main()))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6210067868232727, "alphanum_fraction": 0.6282671689987183, "avg_line_length": 31.793651580810547, "blob_id": "170b77dbe6b42ae695c41f320e24f08f15e413c1", "content_id": "46987e5df6106c0097b3214330e1a1949e75f5e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2066, "license_type": "no_license", "max_line_length": 82, "num_lines": 63, "path": "/src/phrases/top_ten.py", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport fileinput\nimport collections\nimport re\nimport sys\n\n\nclass Comparitor(object):\n\n \"\"\"\n This function will accept cpace separated file paths:\n ./solution file.txt file2.txt\n or accept stdin:\n cat file1.txt | ./solution\n and output the top 10 three word phrases in each.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize 2 empty lists. \n The choice here is that all inputs will be considered one input request\n fileinput is used to read any file or stdin, but it operates on lines\n to cover edge cases of split lines, well waste some cycles and mem \n construct a single split string, then combine into all possible triples\n collections will tell us the most used, but it returns the whole list\n in the interest of simple verification, limit to 10 results\n \"\"\"\n self.entire_file = list()\n self.phrases = list()\n\n def _create_single_string(self):\n for line in fileinput.input():\n self.entire_file.append(line)\n self.one_string = ''.join(self.entire_file).lower()\n\n def _clean_special_chars(self):\n self.clean_string = re.sub('\\W+', ' ', self.one_string)\n\n def _split_words_to_list(self):\n self.split_string = self.clean_string.split()\n\n def _create_triple_word_phrases(self):\n for index, word in enumerate(self.split_string):\n if index < len(self.split_string)-2:\n self.phrases.append(\"{0} {1} {2}\".format(\n word, self.split_string[index+1], self.split_string[index+2]))\n\n def _find_most_common(self):\n self.most_common = collections.Counter(self.phrases).most_common(10)\n\n def run(self):\n self._create_single_string()\n self._clean_special_chars()\n self._split_words_to_list()\n self._create_triple_word_phrases()\n self._find_most_common()\n return self.most_common\n\n\ndef main():\n runner = Comparitor()\n return runner.run()\n # print(\"{}\".format(most_common))\n" }, { "alpha_fraction": 0.7095709443092346, "alphanum_fraction": 0.7161716222763062, "avg_line_length": 30.947368621826172, "blob_id": "fb9cc2ff01fa50828d2790725f4c59571e31a16d", "content_id": "1dc335569e768e8ff12e3b726510ec3fa4045b49", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 606, "license_type": "no_license", "max_line_length": 180, "num_lines": 19, "path": "/README.md", "repo_name": "mpetruzelli/new_relic", "src_encoding": "UTF-8", "text": "# Usage\n## Local install (python >=3.6)\n\n(optional) Create and activate venv:\n - `python -m venv env`\n - `source env/bin/activate`\n\nPip install `phrases`\n - `pip install -e .`\n - `cat file1.txt | phrases` or `phrases file1.txt`\n\nA test has been provided `src/phrases/test_top_ten.py`\n - `python src/phrases/test_top_ten.py`\n\n## Dockerfile\nA dockerfile has been provided that operates in three stages. My favorite part about docker multi-stage builds is no artifact is produced if any stage fails (build-time testing!!).\n\nBuild docker container\n - `docker build --rm -f Dockerfile -t phrases:latest .`" } ]
6
vpeddu/CMV-NIPT
https://github.com/vpeddu/CMV-NIPT
1c3b7ff292a38132390abd9384a2facf22d78f45
a46d7a47e3fa42d368150698e0f41b9bb038d4d8
315767bebf595b302bca7bb7cb9db1b9e9e1dc75
refs/heads/master
2020-06-22T04:49:29.508402
2020-01-28T22:41:09
2020-01-28T22:41:09
197,637,434
0
2
null
null
null
null
null
[ { "alpha_fraction": 0.6540229916572571, "alphanum_fraction": 0.665517270565033, "avg_line_length": 28.03333282470703, "blob_id": "fb0021011ce6f9869f5a7a69338383032f0d4d74", "content_id": "925b14d8abdfdf4597d508b814e570856b059a86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 870, "license_type": "no_license", "max_line_length": 122, "num_lines": 30, "path": "/reproducibility/HHV-6/verified_bam.py", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "import sys \nimport glob\nimport csv\nimport subprocess \nblast_hits_file = sys.argv[1]\nsuffix = sys.argv[2]\n\n#suffix = \"*\" + suffix\n\nfile_list = glob.glob( \"*\" + suffix)\n\nduplicate_list=[]\n\nwith open(blast_hits_file, 'r') as hitsfile:\n\treader = csv.reader(hitsfile)\n\tfor row in reader:\n\t\t#print(row)\n\t\tread_id = row[0].split('-')[1]\n\t\tsample = row[0].split('-')[0].split('.')[0]\n\t\thit_count = int(row[1])\n\t\tcheck= sample + read_id\n\t\t#print(duplicate_list)\n\t\tif hit_count > 5 and check not in duplicate_list: \n\t\t\ttemp_filename = sample + suffix \n\t\t\t#print(temp_filename)\n\t\t\tgrep_cmd = \"samtools view \" + temp_filename + \" | grep \" + read_id + \" >> \" + sample + \".filtered.sam\"\n\t\t\tduplicate_list.append(check)\n\t\t\tsubprocess.run(grep_cmd, shell = True)\n\nsubprocess.call('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/append_sam_header.sh', shell=True)" }, { "alpha_fraction": 0.6658097505569458, "alphanum_fraction": 0.7005141377449036, "avg_line_length": 30.15999984741211, "blob_id": "62cc040fb82f4cc04bbf39809e765fb4dd3c6150", "content_id": "182ce7c513613a5058ec00e70cf6e3c734bc6c3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 778, "license_type": "no_license", "max_line_length": 120, "num_lines": 25, "path": "/scratch/34M.sh", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "cd /Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/resequenced_sample\nfor i in *.bam; do echo $i; samtools view -H $i >> $i.filtered.sam ; samtools view $i | grep '37M' >> $i.filtered.sam \nsamtools view $i | grep '36M' >> $i.filtered.sam\nsamtools view $i | grep '35M' >> $i.filtered.sam\nsamtools view $i | grep '34M' >> $i.filtered.sam\n done\n\nmkdir ../filtered_sams\nmv *.sam ../filtered_sams\ncd ../filtered_sams\nmkdir ../filtered_bams\nfor i in *.sam \ndo\n\tsamtools view -Sb -@8 $i > $i.bam\ndone\n\nmv *.bam ../filtered_bams\ncd ..\n\nrscript --vanilla /Users/gerbix/Documents/vikas/NIPT/31119_download/mismatch_testing/makefastasfromsams.r filtered_bams/\ncd filtered_bams\n\nfind . -name \"*.fasta\" | xargs -n 100 -P 8 cat >> resequenced_combined.txt\n\necho '34 finished'" }, { "alpha_fraction": 0.646974503993988, "alphanum_fraction": 0.6861915588378906, "avg_line_length": 30.614513397216797, "blob_id": "6feec9b24da418267c4fe232630c9ec3a09361fb", "content_id": "c89a857bb66f97fbb06390606ee8670a40fd440b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 13948, "license_type": "no_license", "max_line_length": 211, "num_lines": 441, "path": "/scratch/filitered_bam_fragment_histograms.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/filtered_bams')\n#read_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/blast_hits.csv', header = FALSE, col.names = c('full_ID','count'))\nfilenames = list.files('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/original_bams',pattern = '.bam$')\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\nblast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\nblast_hits_file<-blast_hits_file[blast_hits_file$count>75,]\nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\nfor(i in 1:length(filenames)){ \n #print(i)\n temp_bam<-scanBam(filenames[i])\n if((identical(temp_bam[[1]]$qname, character(0)))){ \n print(i)\n next\n }\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n #progress(j)\n for(k in 1:length(all_bam_read_IDs)){\n if(grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, filenames[i])\n }\n }\n }\n }\ncombined<-data.frame(sample, read_id, isize)\ncombined<-combined[combined$isize>0,]\ncombined<-combined[complete.cases(combined$isize),]\ncmv_plot<-ggplot(combined, aes( x=combined$isize)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('fragment length')+\n annotate(\"text\", x = 400, y = 18 , label = paste0('mean=', mean(combined$isize))) + \n annotate(\"text\", x = 400, y = 15, label = paste0('median=', median(combined$isize))) +\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\ncmv_plot\n\n\nggsave('combined_cmv_plot.pdf',cmv_plot)\n\n\n\n\n\n#####human stuff######\n\n\nsetwd('/Volumes/Seagate8Tb1/nipt/bams/bams_realigned_to_hg38')\nread_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nfilenames = list.files(pattern = '*.bam.results.txt$')\nplotslist<-c()\n\nsavePlot <- function(myPlot, plotname) {\n pdf(plotname, width = 8.5, height = 11)\n print(myPlot)\n dev.off()\n}\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(filenames)){ \n print(i)\n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'length'\n colnames(histo)[1]<-'occurences'\n histo$type<-strsplit(filenames[i],\".sam\")[[1]][1]\n histo<-histo[histo$length>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 900)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$length)\n totaloccurences =append(totaloccurences,histo$occurences)\n dflist[[i]]<-histo\n }\n }\n}\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches')\n\ncombineddf <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nread_counts$sample<-as.character(read_counts$sample)\n\ncount = 0 \nfor(i in 1:nrow(combineddf)){ \n temp = combineddf$occurences[i] * combineddf$length[i]\n count = count + temp\n }\nhuman_mean = count/ sum(combineddf$occurences)\n\nmedian_list<-c()\nfor(i in 1:nrow(combineddf)){ \n progress(i, nrow(combineddf))\n median_list<-append(median_list,rep(combineddf$length[i],combineddf$occurences[i]))\n }\nhuman_median<-median(median_list)\n\nhuman_plot<-ggplot(combineddf, aes( x=combineddf$length, y = combineddf$occurences, color = combineddf$type)) + \n geom_point() + \n #geom_histogram(binwidth = 5) + \n # geom_histogram(binwidth = 5) +\n geom_vline(xintercept = human_median) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"none\") +\n annotate(\"text\", x = 400, y = 1500000 , label = paste0('mean=', mean(human_mean))) +\n annotate(\"text\", x = 400, y = 1300000, label = paste0('median=', median(human_median))) + \n ggtitle('Human median fragment length')\n\nhuman_plot\n\nggsave('human_plot.pdf', human_plot)\n\n\n\n\n#overlaying plots\n\nhuman_plot<-ggplot(combineddf, aes( x=combineddf$length, y = combineddf$occurences, color = combineddf$type)) + \n geom_point(aes = ) + \n #geom_histogram(binwidth = 5) + \n # geom_histogram(binwidth = 5) +\n #geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"none\") \n#annotate(\"text\", x = 400, y = max(histo$occurences)-5, label = paste0('mean=', mean(combineddf$length))) + \n#annotate(\"text\", x = 400, y = max(histo$occurences)-7, label = paste0('median=', median(combineddf$length)))\nhuman_plot\n\n\n\n\n\n\n\n###121R04 original plot\nR04_original<-combined[combined$sample=='121R04_D01_CFFv1_NA0144.sam.bam',]\nr04_original_plot<-ggplot(R04_original, aes( x=R04_original$isize)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(R04_original$isize)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('fragment length')+\n annotate(\"text\", x = 400, y = 18 , label = paste0('mean=', mean(R04_original$isize))) + \n annotate(\"text\", x = 400, y = 15, label = paste0('median=', median(R04_original$isize))) +\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\") + \n ggtitle('121R04 original')\nr04_original_plot\nggsave('121R04_original.pdf', r04_original_plot)\n\n\n\n\n\n\n###12104 resequenced \nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/resequenced_sample')\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/resequenced_sample/resequenced_cmv_vs_full_nt.txt_blast_hits.csv', header = FALSE, col.names = c('full_ID','count','x'))\nr04_resequenced_BamFile<-scanBam('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/resequenced_sample/resequenced_local_cmv_aligned.bam')\nduplicated_file_data<-read.csv('positions_with_read_ids.csv')\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\n progress(i,nrow(blast_hits_file))\n blast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\n#blast_hits_file<-blast_hits_file[blast_hits_file$count>75,]\nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\n all_bam_read_IDs<-r04_resequenced_BamFile[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n progress(j,nrow(blast_hits_file))\n for(k in 1:length(all_bam_read_IDs)){\n #print(grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) \n \n if(grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n # print ('ok')\n isize<-append(isize, r04_resequenced_BamFile[[1]]$isize[k])\n #print(isize)\n read_id<-append(read_id, paste(r04_resequenced_BamFile[[1]]$qname[k],'.1'))\n sample<-append(sample, '121r04_resequenced')\n }\n }\n }\nr04_resequenced_combined<-data.frame(sample, read_id, isize)\nr04_resequenced_combined<-r04_resequenced_combined[r04_resequenced_combined$isize>0,]\nr04_resequenced_combined<-r04_resequenced_combined[complete.cases(r04_resequenced_combined$isize),]\nr04_resequenced_plot<-ggplot(r04_resequenced_combined, aes( x=combined$isize)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(r04_resequenced_combined$isize)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('fragment length')+\n annotate(\"text\", x = 400, y = 100 , label = paste0('mean=', mean(r04_resequenced_combined$isize))) + \n annotate(\"text\", x = 400, y = 90, label = paste0('median=', median(r04_resequenced_combined$isize))) +\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\") + \n ggtitle('121R04 resequenced')\nr04_resequenced_plot\n\n\nggsave('121r04_resequenced_plot.pdf',r04_resequenced_plot)\n\n\nwrite.csv(combined,'121r04_resequenced.csv')\n\n\nnot_unique<-which(duplicated(duplicated_file_data$positions_list))\nduplicated_file_data<-duplicated_file_data[-not_unique,]\n#duplicated_file_data<-duplicated_file_data[complete.cases(duplicated_file_data$positions_list),]\n\nduplicates_to_keep<-c()\n#non_paired<-duplicated_file_data$read_id_list[duplicated_file_data$paired==TRUE]\nfor(i in 1:nrow(duplicated_file_data)){ \n if(duplicated_file_data$paired[i]==TRUE){ \n for(j in 1:nrow(r04_resequenced_combined)){ \n if(grepl(as.character(duplicated_file_data$read_id_list[i]), as.character(r04_resequenced_combined$read_id[j]))){ \n #print(as.character(duplicated_file_data$read_id_list[i]))\n #print(as.character(r04_resequenced_combined$read_id[j]))\n duplicates_to_keep<-append(duplicates_to_keep, j)\n }\n }\n }\n }\n\nr04_resequenced_combined<-r04_resequenced_combined[duplicates_to_keep,]\n\n\n\nr04_isizes<-r04_resequenced_combined$isize\nr04_sample<-c(rep('121r04_resequenced',length(r04_isizes)))\ntemp_table<-table(r04_isizes)\nr04_freq_df<-data.frame(temp_table)\ncolnames(r04_freq_df)[1]<-'isize'\ncolnames(r04_freq_df)[2]<-'freq'\nr04_freq_df$sample<-('121r04_resequenced')\nr04_freq_df$percent<-100*r04_freq_df$freq/sum(r04_freq_df$freq)\n\nhuman_isizes<-median_list\nhuman_sample<-c(rep('Human',length(median_list)))\ntemp_table<-table(median_list)\nhuman_freq_df<-data.frame(temp_table)\n#human_freq_df<-data.frame(human_isizes,human_sample)\ncolnames(human_freq_df)[1]<-'isize'\ncolnames(human_freq_df)[2]<-'freq'\nhuman_freq_df$sample<-('Human')\nhuman_freq_df$percent<-100*human_freq_df$freq/sum(human_freq_df$freq)\n\nfreq_df<-rbind(human_freq_df,r04_freq_df)\nfreq_df$isize<-as.numeric(freq_df$isize)\nfreq_df$freq<-as.numeric(freq_df$freq)\n\nhead_freq_df<-freq_df[1:100000,]\n\n####\n#human_freq_df<-freq_df[freq_df$sample=='Human',]\npercent_plot<-ggplot(human_freq_df, aes(x= human_freq_df$isize, y=human_freq_df$percent, color = human_freq_df$sample)) + \n geom_point() + \n xlab('Fragment length') + \n ylab('percent of mapped reads in the sample') + \n #xlim(c(0,500)) + \n geom_vline(xintercept = 130) + \n theme_classic()\npercent_plot\nggsave(plot = percent_plot,'human_small.pdf')\n\n\ntest<-c()\nd2 <- rep(human_freq_df$isize, human_freq_df$freq)\nfor(i in 1:nrow(human_freq_df)){ \n d2 <- rep(d$Score, d$Frequency)\n\n }\n\n\n####\n\n\npercent_plot<-ggplot(head_freq_df, aes(x= head_freq_df$isize, y=head_freq_df$percent, color = head_freq_df$sample)) + \n geom_line() + \n xlab('Fragment length') + \n ylab('percent of mapped reads in the sample') + \n xlim(c(50,400)) + \n ylim(c(0,2.5)) + \n geom_vline(xintercept = 167) +\n theme_classic()\npercent_plot\n\n\n\npercent_plot<-ggplot(freq_df, aes(x= freq_df$isize, y=freq_df$percent, color = freq_df$sample)) + \n geom_line() + \n xlab('Fragment length') + \n ylab('% of mapped reads in the sample') +\n xlim(c(0,500))+\n ylim(c(0,2.5)) + \n #geom_vline(xintercept = 168) + \n theme_classic() + \n theme(legend.position = 'none')\npercent_plot\n\nggsave('121_r04_only_realigned_human_vs_resequenced_frequency_plot.pdf', percent_plot, height = 3 , width = 3)\n\n\n#data for percent plot\nwrite.csv(freq_df,'121_r04_only_realigned_human_vs_resequenced_frequency_plot_data.csv')\n\n\n\n\n###calculating true human mean fragment length from resequenced sample \nresequenced_isizes<-read.csv('/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/human_fragment_lengths.txt')\nmean_resequenced_human_fragment_length<-mean(resequenced_isizes$X0)\nmedian_resequenced_human_fragment_length<-median(resequenced_isizes$X0)\n\nmean_resequenced_cmv_fragment_length<-mean(r04_resequenced_combined$isize)\nmedian_resequenced_cmv_fragment_length<-median(r04_resequenced_combined$isize)\n\n\npvalues<-c()\nfor(i in 1:50000){ \n progress(i,50000)\n temp_cmv<-sample(r04_resequenced_combined$isize,3000)\n temp_human<-sample(resequenced_isizes$X0,3000)\n #result<-cor.test(temp_cmv,temp_human, method = \"pearson\")\n result<-wilcox.test(temp_human,temp_cmv)\n pvalues<-append(result$p.value,pvalues)\n }\nplot(pvalues)\n\n\n\n#p value on insert sizes \nt.test(human_isizes,r04_isizes, alternative = \"two.sided\")\n\ntests<-c()\nfor(i in 1:100000){ \n progress(i,100000)\n temp<-(sample(human_isizes, length(r04_isizes)))\n #print((temp))\n ttest<-(t.test(temp,r04_isizes, paired = TRUE))\n tests<-append(tests,ttest$p.value)\n }\n\ntestsdf<-data.frame(tests)\n\nttest_graph<-ggplot(testsdf, aes(x = testsdf$tests)) + \n geom_freqpoly(bins = 1000) +\n xlim(c(0,summary(testsdf$tests)[5]))+\n geom_vline(xintercept = 0) + \n geom_hline(yintercept = 0) + \n ylim(0,2000) + \n xlab('p-value') + \n ylab('frequency (100000 iterations)') + \n theme_classic() + \n theme(axis.text.x = element_text(angle = 90, hjust = 1)) \n # ylim(c(0,8))\nttest_graph\nggsave(plot =ttest_graph, 'insert_size_p-value_distribution.pdf')\n\n#library('dyplr')\n#boxplot(tests)\n\n\nhuman_percentile<-ecdf(human_isizes)\ncmv_med_percentile<-human_percentile(median(r04_isizes))\n\n\ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isizes, length(r04_isizes)))\n #print((temp))\n fktest<-(fligner.test(temp,r04_isizes, paired = TRUE))\n tests<-append(tests,fktest$p.value)\n}\n\nfk_df<-data.frame(tests)\n\nfktest_graph<-ggplot(fk_df, aes(x = fk_df$tests)) + \n geom_freqpoly(bins = 1000) +\n xlim(c(0,summary(fk_df$tests)[5]))+\n geom_vline(xintercept = 0) + \n geom_hline(yintercept = 0) + \n ylim(0,2000) + \n xlab('p-value') + \n ylab('frequency (100000 iterations)') + \n theme_classic() + \n theme(axisw.text.x = element_text(angle = 90, hjust = 1)) \n# ylim(c(0,8))\nfktest_graph \nggsave(plot =fktest_graph, 'insert_size_variance_distribution.pdf')\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7341115474700928, "alphanum_fraction": 0.7522698044776917, "avg_line_length": 47.1875, "blob_id": "bcb0c9ce491e5dfc913b20669ee6f243c7ea26e6", "content_id": "829cbce61cf32782a618d49f4ec7d7613df3553c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1542, "license_type": "no_license", "max_line_length": 137, "num_lines": 32, "path": "/reproducibility/CMV/maternal/current_version/strong_positive_r04_removed_insert_stats.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "setwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/fragment_patch')\n\nstrong_positive_sample_names<-df_for_graph$sample[df_for_graph$classification == 'strong positive']\n\nbam_folder<-'/Users/gerbix/Documents/vikas/NIPT/all_deduplicated/original_bams_deduplicated/'\n\nblasted_reads<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/blast_positive_sequence_info.csv')\n\nall_sample_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/all_sample_data.csv')\n\nblasted_reads$sample<-NA\nblasted_reads$unique_id<-NA\nfor(i in 1:nrow(blasted_reads)){ \n blasted_reads$sample[i]<-strsplit(as.character(blasted_reads$nameslist[i]),'[.]')[[1]][1]\n blasted_reads$unique_id[i]<-strsplit(as.character(blasted_reads$nameslist[i]),'-')[[1]][2]\n}\n\nto_keep<-as.character(all_sample_data$sample[all_sample_data$classification=='strong positive'])\nblasted_reads<-blasted_reads[which(blasted_reads$sample %in% to_keep),]\n\n\nblasted_reads$isize<-NA\nfor(i in 1:nrow(blasted_reads)){ \n print(i)\n temp_dir<-paste0(bam_folder,'/',blasted_reads$sample[i], '.sam.bam.sorted.bam_dedup.bam')\n temp_bam<-scanBam(temp_dir)\n blasted_reads$isize[i]<-abs(temp_bam[[1]]$isize[which(grepl(blasted_reads$unique_id[i],temp_bam[[1]]$qname))])\n}\nblasted_reads<-blasted_reads[complete.cases(blasted_reads$isize),]\nr04_removed<-blasted_reads[-which(blasted_reads$sample == '121R04_D01_CFFv1_NA0144'),]\n\nsummary(r04_removed$isize[blasted_reads$isize < 500], na.omit= TRUE)\n" }, { "alpha_fraction": 0.6728558540344238, "alphanum_fraction": 0.6885499358177185, "avg_line_length": 35.75609588623047, "blob_id": "e22a902ae7731e1aac85ba8c24537bc34ba1beb5", "content_id": "8a63581b83f486a76858f0d228402b5e5dfec933", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4524, "license_type": "no_license", "max_line_length": 144, "num_lines": 123, "path": "/scratch/new_cmv_samples/new_cmv_cumulative_dist.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\nlibrary(wesanderson)\nlibrary(RColorBrewer)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/new_samples')\n#read_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/blast_hits.csv', header = FALSE, col.names = c('full_ID','count'))\nfilenames = list.files('/Users/gerbix/Documents/vikas/NIPT/new_samples',pattern = '.bam$')\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\n blast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\nblast_hits_file<-blast_hits_file[blast_hits_file$count>75,]\nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\nfor(i in 1:length(filenames)){ \n #print(i)\n temp_bam<-scanBam(filenames[i])\n if((identical(temp_bam[[1]]$qname, character(0)))){ \n print(i)\n next\n }\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n #progress(j)\n for(k in 1:length(all_bam_read_IDs)){\n print(blast_hits_file$read_ID[j])\n if( !(is.na(blast_hits_file$read_ID[j])) & grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, filenames[i])\n }\n }\n }\n}\ncombined<-data.frame(sample, read_id, isize)\ncombined<-combined[combined$isize>0,]\ncombined<-combined[complete.cases(combined$isize),]\ncmv_plot<-ggplot(combined, aes( x=combined$isize)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('fragment length')+\n #annotate(\"text\", x = 400, y = 18 , label = paste0('mean=', mean(combined$isize))) + \n annotate(\"text\", x = 400, y = 15, label = paste0('median=', median(combined$isize))) +\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\ncmv_plot\n\ncombined_trimmed<-combined[combined$isize<501,]\n\ncmv_cumulative_frequency<-ggplot(combined_trimmed, aes(x = combined_trimmed$isize, color = combined_trimmed$sample)) + \n stat_ecdf(geom = 'step', size =.5 ) +\n theme_classic() + \n scale_fill_manual(values = getPalette(colourCount)) +\n theme(legend.position='bottom') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') \n #scale_colour_brewer(palette = 'Set2') + \ncmv_cumulative_frequency\n\n#pulling human from sample 244P16_H02_CFFv2_NB0289\nhuman<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/p16.results.txt', sep = '', header = FALSE, col.names = c('frequency', 'isize'))\nhuman<-human[human$isize>0,]\n\nhuman_isizes<-rep(human$isize, human$frequency)\nhuman_df<-as.data.frame(human_isizes)\ncolnames(human_df)[1]<-'isize'\nhuman_df$sample<-'P16_Human'\nhuman_df$read_id<-'eh'\n\n\n\nhuman_cmv_combined<-rbind(human_df,combined_trimmed)\nlibrary(RColorBrewer)\ngetPalette = colorRampPalette(brewer.pal(8, \"Set3\"))\ncolourCount = length(unique(human_cmv_combined$sample))\n\n\ncmv_cumulative_frequency<-ggplot(combined_trimmed, aes(x = isize, color = sample)) + \n stat_ecdf(geom = 'step', size =.5 )+\n scale_color_manual(values = getPalette(colourCount)) + \n theme_classic() + \n theme(legend.position='bottom') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') \ncmv_cumulative_frequency\n\n\ncumulative_freq_with_human<-ggplot(human_cmv_combined, aes(x = human_cmv_combined$isize, color = human_cmv_combined$sample)) + \n theme_classic() + \n theme(legend.position='none') + \n scale_color_manual(values = getPalette(colourCount)) + \n xlab('Insert size') + \n ylab ('Cumulative frequency') + \n stat_ecdf(geom = 'step', size =.5 ) \n #scale_fill_manual(values = x)\ncumulative_freq_with_human\nggsave(plot = cumulative_freq_with_human, 'cmv_cum_freq_with_human_recolored.pdf', height = 3, width = 3)\n\n\n\nhuman_cdf<-as.data.frame(Ecdf(human_cmv_combined$isize[human_cmv_combined$sample=='P16_Human']), col.names =(c('size','proportion')))\ncmv_cdf<-as.data.frame(Ecdf(human_cmv_combined$isize[human_cmv_combined$sample!='P16_Human']), col.names =(c('size','proportion')))\ncdf_combined<-merge(human_cdf, cmv_cdf, by=\"size\", all = T)\nwrite.csv(cdf_combined, 'new_cmv_cdf.csv')\n\nplot(ecdf(human_cmv_combined$isize[human_cmv_combined$sample=='P16_Human']), col.names =(c('size','proportion')))\n\n\n\n" }, { "alpha_fraction": 0.7112832069396973, "alphanum_fraction": 0.7308259606361389, "avg_line_length": 44.099998474121094, "blob_id": "b83ddd4ab1473f2373ca5ba6860f0ac4104dd07e", "content_id": "c04c225a9dc176d9a3af61f4490cb2b95386202f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2712, "license_type": "no_license", "max_line_length": 256, "num_lines": 60, "path": "/scratch/resequenced_original_compare.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\n\n\nresequenced_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/resequenced_human_insert_sizes.csv')\nresequenced_data$run<-'resequenced'\noriginal_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/original_human_insert_sizes.csv')\noriginal_data$run<-'original'\n\nall_reads<-rbind(resequenced_data[resequenced_data$type=='with_duplicates',], original_data[original_data$type=='with_duplicates',])\ndeduplicated_reads<-rbind(resequenced_data[resequenced_data$type=='deduplicated',], original_data[original_data$type=='deduplicated',])\nduplicate_reads<-rbind(resequenced_data[resequenced_data$type=='extracted_duplicates',], original_data[original_data$type=='extracted_duplicates',])\n\n#all of the reads\nall_reads_plot<-ggplot(all_reads, aes( x = all_reads$isize , y = all_reads$percent, color = all_reads$run)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line(aes(alpha=0.4)) \nall_reads_plot\nggsave(plot = all_reads_plot, 'all_reads_overlayed.pdf', height = 8, width = 8)\n\n\n\n#deduplicated reads\ndeduplicated_reads_plot<-ggplot(all_reads, aes( x = deduplicated_reads$isize , y = deduplicated_reads$percent, color = deduplicated_reads$run)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line(aes(alpha=0.4)) \ndeduplicated_reads_plot\nggsave(plot = deduplicated_reads_plot, 'deduplicated_overlayed.pdf', height = 8, width = 8)\n\n#duplicate reads\nduplicate_reads_plot<-ggplot(duplicate_reads, aes( x = duplicate_reads$isize , y = duplicate_reads$percent, color = duplicate_reads$run)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line(aes(alpha=0.4)) \nduplicate_reads_plot\nggsave(plot = duplicate_reads_plot, 'duplicates_overlayed.pdf', height = 8, width = 8)\n\n\n\n\nduplicate_vs_non_duplicate_resequenced<-rbind(resequenced_data[resequenced_data$run=='resequenced' & resequenced_data$type=='extracted_duplicates',], resequenced_data[resequenced_data$run=='resequenced' & resequenced_data$type=='deduplicated',])\n\nduplicate_vs_non_duplicate_resequenced_plot<-ggplot(duplicate_vs_non_duplicate_resequenced, aes( x = duplicate_vs_non_duplicate_resequenced$isize , y = duplicate_vs_non_duplicate_resequenced$percent, color = duplicate_vs_non_duplicate_resequenced$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line(aes(alpha=0.4)) \nduplicate_vs_non_duplicate_resequenced_plot\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.668988823890686, "alphanum_fraction": 0.7036098837852478, "avg_line_length": 29.954248428344727, "blob_id": "154ca3169fc45b112eec2a981999eb8b865524f4", "content_id": "051e98200dcccb42460404a443e367bc69a207fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4737, "license_type": "no_license", "max_line_length": 119, "num_lines": 153, "path": "/reproducibility/HHV-6/figure_5C.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\n\n#pulled human insert sizes from NIPT CMV sample 3P13\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6')\nfilenames = '/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/3P13_read_lengths.txt'\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(filenames)){ \n print(i)\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'Human'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nhuman_frequencies <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\n\nhuman_frequencies$percent<-(100 * human_frequencies$freq) / (sum(human_frequencies$freq))\n\n#human median calculation\nhuman_isize_expanded<-rep(human_frequencies$isize, human_frequencies$freq) \nhuman_isize_expanded_below250<-human_isize_expanded[human_isize_expanded < 500]\nhuman_median<-median(as.numeric(as.character(human_isize_expanded_below250)))\n\n\nhuman_frequencies$isize<-as.numeric(as.character(human_frequencies$isize))\n\n\n###hhv6 isizes\nhhv_6_combined<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/hhv6_isizes_all.csv')\n\nhhv6_combined<-hhv_6_combined[hhv_6_combined$lengthlist<500,]\n\nhhv6_ks_test<-ks.test(human_isize_expanded,hhv_6_combined$lengthlist)\nhhv6_ks_test\n\n\nhhv_6_isize<-data.frame(hhv_6_combined$lengthlist)\ncolnames(hhv_6_isize)[1]<-'length'\nhhv_6_isize$type<-'hhv6'\n\nhuman_isize<-data.frame(human_isize_expanded)\ncolnames(human_isize)[1]<-'length'\nhuman_isize$type<-'Human'\n\nhuman_hhv6_combined<-rbind(human_isize,hhv_6_isize)\n\n\ncum_frequency<-ggplot(human_hhv6_combined, aes(x = human_hhv6_combined$length, color = human_hhv6_combined$type)) + \n theme_classic() + \n theme(legend.position='none') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') + \n stat_ecdf(geom = 'step', size =1 ) \ncum_frequency\n\n\nplot(ecdf(combined$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\nplot(ecdf(cmv))\n\nfor(i in 1:nrow(human_hhv6_combined)){ \n if(human_hhv6_combined$type=='H')\n}\n\nuniques<-unique(combineddf$sample)\n\nfor(i in 1:length(uniques)){ \n print(uniques[i])\n print( nrow(combineddf[combineddf$sample==uniques[i],]))\n}\n\nto_remove<-c('99P03_C01','120R22_F03','104P04_D01','98P11','97P10_B02','93R20_D03')\n\nlowclusterremoved<-combineddf[-which(grepl(paste(to_remove,collapse=\"|\"),combineddf$sample)),]\n\nplot(ecdf(lowclusterremoved$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\n\n\nlowclusteronly<-combineddf[which(grepl(paste(to_remove,collapse=\"|\"),combineddf$sample)),]\n\nplot(ecdf(lowclusterremoved$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\nplot(ecdf(lowclusteronly$length), add = TRUE, col = 3 )\n\n\nks.test(human_isize_expanded, combineddf$length)\n\nhhv6_isizes_all<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/hhv6_isizes_all.csv')\nhhv6_isizes_all<-hhv6_isizes_all[hhv6_isizes_all$lengthlist<500,]\n\nhuman_isizes_all<-data.frame(human_isize$length)\ncolnames(human_isizes_all)[1]<-'lengthlist'\nhuman_isizes_all$X<-NA\nhuman_isizes_all$samplelist<-'Human'\nhuman_isizes_all$sample_trimmed<-'Human'\nhuman_isizes_all$cluster<-'Human'\n\n\n\nall_combined<-rbind(human_isizes_all, hhv6_isizes_all)\n\ncum_frequency<-ggplot(all_combined, aes(x = all_combined$lengthlist, color = all_combined$cluster)) + \n stat_ecdf(geom = 'step', size =1 , show.legend = TRUE, pad = FALSE) + \n theme_classic() +\n theme(legend.title = element_blank()) +\n theme(text = element_text(size=10)) +\n theme(legend.position = c(0.8, 0.3)) + \n theme(legend.title=element_blank()) +\n xlim(0,500) + \n scale_color_manual(values = c( '#FF4500','#077524','#436EEE')) + \n xlab('Fragment size') + \n ylab ('Cumulative frequency') \ncum_frequency\n\n# saving plot crashes R \n# ggsave(cum_frequency, 'figure_5C.pdf', height = 3 , width = 3)\n\n\n\ncum_frequency<-ggplot(x, aes(x = x$lengthlist, color = x$cluster)) + \n stat_ecdf(geom = 'step', size =1 , show.legend = TRUE, pad = FALSE) + \n theme_classic() +\n theme(legend.title = element_blank()) +\n theme(text = element_text(size=8)) +\n theme(legend.position = c(0.8, 0.3)) + \n theme(legend.title=element_blank()) +\n xlim(0,500) + \n scale_color_manual(values = c('#077524', '#FF4500','#436EEE')) + \n xlab('Fragment size') + \n ylab ('Cumulative frequency') \ncum_frequency\n\n\nsave.image(file= 'figure_5C.Rdata')\n\n" }, { "alpha_fraction": 0.6448163390159607, "alphanum_fraction": 0.6820083856582642, "avg_line_length": 32.53125, "blob_id": "ddae17331f1463b00d4b7d8444b2dd3b5c6916a4", "content_id": "ccac980a36b296ca7a1c3d566fddf49b194adb4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2151, "license_type": "no_license", "max_line_length": 121, "num_lines": 64, "path": "/scratch/makefastasfromsams.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "args = commandArgs(trailingOnly=TRUE)\n\nlibrary(Rsamtools)\nlibrary(seqinr)\nlibrary(svMisc)\n\nfilenames <- list.files(args[1], pattern ='.bam$')\n#print(filenames)\nsetwd(args[1])\nsequence= c()\nidentifier= c()\nheader=c()\n#print('reading bams')\nfor (i in 1:length(filenames)){ \n lengthfilenames= length(filenames)\n #print (100*i/lengthfilenames)\n #progress(i)\n tempbam=scanBam(filenames[i])\n if(length(tempbam[[1]]$seq)>0){\n for(j in 1:length(tempbam[[1]]$seq)){ \n #if(tempbam[[1]]$pos > 11000 && tempbam[[1]]$pos<120000) {\n sequence = append(sequence,as.character(tempbam[[1]]$seq[j]))\n tempfilename = paste0(filenames[i],'.',j)\n header=append(header, as.character(tempbam[[1]]$qname[j]))\n# print(tempfilename)\n identifier = append(identifier,tempfilename)\n #}\n }\n }\n }\n#print('done making bams')\nfastadf <- data.frame(identifier, sequence, header)\nfastadf$header<-as.character(fastadf$header)\nfastadf$identifier<-as.character(fastadf$identifier)\n\n\n#repeatmasker limits header names to 50 characters so this deletes the non-unique regions of the header\nfor(i in 1:nrow(fastadf)){\n progress(i, nrow(fastadf))\n if(grepl('NB502000', fastadf$header[i])) {\n fastadf$header[i]<-gsub(pattern = 'NB502000', replacement = '', fastadf$header[i])\n }\n if(grepl('NS500359', fastadf$header[i])) {\n fastadf$header[i]<-gsub(pattern = 'NS500359', replacement = '', fastadf$header[i])\n }\n fastadf$identifier[i]<-gsub('.sam.bam','',fastadf$identifier[i])\n fastadf$header[i]<-substr(fastadf$header[i], 17, stop = nchar(fastadf$header[i]))\n}\n\n\nx<-c()\nprint('making fastas')\nfor ( i in 1:nrow(fastadf)){\n lengthvar=nrow(fastadf)\n #print(100*i/lengthvar)\n tempfilename = paste0(fastadf$identifier[i],'.fasta')\n write.fasta(sequences= fastadf$sequence[i], names = paste0(tempfilename,'-',fastadf$header[i]), file.out= tempfilename)\n if(nchar(paste0(tempfilename,'-',fastadf$header[i]))>50){ \n x<-append(x,i)\n }\n } \n#tempbam = scanBam('121R04_D01_CFFv1_NA0144.sam.removed.sam.bam')\n\n#run find . -name \"*.fasta\" | xargs -n 100 -P 8 cat >> combined.txt from terminal. Doesn't work when called from system \n\n\n\n\n" }, { "alpha_fraction": 0.61562180519104, "alphanum_fraction": 0.6955292820930481, "avg_line_length": 37.117645263671875, "blob_id": "09c5a81cedca35e683b5804836a94c8adb8a2395", "content_id": "5c1b0e957e306372d2e2a1b33006461ee8f2d768", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3892, "license_type": "no_license", "max_line_length": 165, "num_lines": 102, "path": "/scratch/new_cmv_samples/new_cmv_standard_curve.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#matching container IDs to sequencing IDs and creating standard curves for cmv samples \nlibrary(\"ggplot2\")\nlibrary(\"xlsx\")\n\n\ncmv_ids<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/new_cmv_pulled_ids.csv', sep = '\\t', header = FALSE, col.names = c('sequencing_id', 'bid', 'lmid'))\ncmv_ids$bid<-as.character(cmv_ids$bid)\nfor(i in 1:nrow(cmv_ids)){ \n cmv_ids$bid[i]<-strsplit(as.character(cmv_ids$bid[i]), 'P')[[1]][2]\n}\n\n<<<<<<< HEAD\n<<<<<<< HEAD\nrpkm_values<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/deduplicated/all_sample_data.csv')\n=======\nrpkm_values<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/all_sample_data.csv')\n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n=======\nrpkm_values<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/all_sample_data.csv')\n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\nrpkm_values$sample<-as.character(rpkm_values$sample)\nrpkm_values$rpm<-as.numeric(as.character(rpkm_values$rpm))\ncmv_quants<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/new_samples/CMVPulled.xlsx', sheetIndex = 1)\n\nrpkm_values$quant<-NA\nrpkm_values$sample<-as.character(rpkm_values$sample)\nfor(i in 1:nrow(cmv_ids)){ \n temp<-which(grepl(cmv_ids$sequencing_id[i],rpkm_values$sample))\n print(rpkm_values$sample[temp])\n temp_quant<-which(grepl(cmv_ids$bid[i], as.character(cmv_quants$Barcode.ID.)))\n rpkm_values$quant[temp]<-cmv_quants$result_num[temp_quant]\n}\n\nrpkm_values$quant_adjusted<-rpkm_values$quant * 4\ncurve<-ggplot(rpkm_values, aes(x = rpm, y = quant)) + \n geom_point() +\n# scale_x_log10() + \n ylim(c(0,20000)) +\n #xlim(c(0,3)) + \n geom_smooth(method = \"lm\", se = FALSE, alpha = .5) + \n theme_classic() + \n geom_vline(xintercept = .3, linetype = 'dotted')\ncurve\nggsave( plot = curve, 'cmv_quants.pdf', height = 4, width = 4)\n\nwrite.csv(rpkm_values, 'rpkm_values_with_quants.csv')\n<<<<<<< HEAD\n<<<<<<< HEAD\n=======\n=======\n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n \n\n\n\n\n\n\n#Original CMV samples with qCPR data \n<<<<<<< HEAD\n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n=======\n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n\noriginal_cmv<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update/6131_cmv_percent_vs_qpcr_load.xlsx', sheetIndex = 1)\noriginal_reformatted<- original_cmv[,c(1,4,11,12,13,14,15)]\ncolnames(original_reformatted)<-c('sample','quant','count','rpkm','read_counts','rpm','classification')\noriginal_reformatted$time<-'original'\noriginal_reformatted$quant_adjusted<-original_reformatted$quant\n\nrpkm_values$X<-NULL\nrpkm_values$time<-'new'\n\noriginal_new_combined<-rbind(original_reformatted,rpkm_values)\noriginal_new_combined$time<-as.character(original_new_combined$time)\n\nlibrary(RColorBrewer)\ngetPalette = colorRampPalette(brewer.pal(8, \"Set3\"))\ncolourCount = length(unique(original_new_combined$time))\n\nplot<-ggplot(original_new_combined, aes(x = rpm, y = quant_adjusted, color= time)) + \n geom_point() +\n scale_y_log10(breaks = c( 1, 10, 100, 1000, 10000,100000))+ \n scale_x_log10(limits = c(.01, 100)) + \n #geom_hline(yintercept = 68000) + \n geom_smooth(method = \"lm\", se = FALSE, alpha = .5, aes(group=1), color = 'black') + \n<<<<<<< HEAD\n<<<<<<< HEAD\n scale_color_manual(values = c(\"#729AF2\",\"#BF6FF7\")) + \n=======\n scale_color_manual(values = c( \"#BEBADA\", \"#FB8072\", \"#80B1D3\", \"#FDB462\", \"#B3DE69\", \"#FCCDE5\")) + \n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n=======\n scale_color_manual(values = c( \"#BEBADA\", \"#FB8072\", \"#80B1D3\", \"#FDB462\", \"#B3DE69\", \"#FCCDE5\")) + \n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n theme_classic() + \n theme(legend.title=element_blank(), legend.position = 'none') \n #geom_vline(xintercept = .3, linetype = 'dotted')\nplot\nggsave(plot = plot, 'cmv_original_new_quant_rpm_recolored_quant_adjusted_v2.pdf', height = 3, width = 3)\n\nsummary(lm(rpm ~ quant_adjusted, data=original_new_combined))\n\n\n\n\n" }, { "alpha_fraction": 0.6572290658950806, "alphanum_fraction": 0.683685302734375, "avg_line_length": 36.11206817626953, "blob_id": "929f7ceea7f904a7b463d197e1685159e06bfa7c", "content_id": "31e26449b060b7972935d9c4564ae58f53d846a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4309, "license_type": "no_license", "max_line_length": 144, "num_lines": 116, "path": "/reproducibility/CMV/SOT/previous_version/figure_4C.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\nlibrary(wesanderson)\nlibrary(RColorBrewer)\nlibrary(Hmisc)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT')\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/blast_hits.csv', header = FALSE, col.names = c('full_ID','count'))\nfilenames = list.files('/Users/gerbix/Documents/vikas/NIPT/new_samples',pattern = '.bam$', full.names = TRUE)\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\n blast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\nblast_hits_file<-blast_hits_file[blast_hits_file$count>75,]\nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\nfor(i in 1:length(filenames)){ \n temp_bam<-scanBam(filenames[i])\n if((identical(temp_bam[[1]]$qname, character(0)))){ \n print(i)\n next\n }\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n for(k in 1:length(all_bam_read_IDs)){\n print(blast_hits_file$read_ID[j])\n if( !(is.na(blast_hits_file$read_ID[j])) & grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, filenames[i])\n }\n }\n }\n}\ncombined<-data.frame(sample, read_id, isize)\ncombined<-combined[combined$isize>0,]\ncombined<-combined[complete.cases(combined$isize),]\ncmv_plot<-ggplot(combined, aes( x=combined$isize)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('fragment length')+\n annotate(\"text\", x = 400, y = 15, label = paste0('median=', median(combined$isize))) +\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\ncmv_plot\n\ncombined_trimmed<-combined[combined$isize<501,]\n\ncmv_cumulative_frequency<-ggplot(combined_trimmed, aes(x = combined_trimmed$isize, color = combined_trimmed$sample)) + \n stat_ecdf(geom = 'step', size =.5 ) +\n theme_classic() + \n scale_fill_manual(values = getPalette(colourCount)) +\n theme(legend.position='bottom') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') \ncmv_cumulative_frequency\n\n#pulling human insert sizes from sample 244P16_H02_CFFv2_NB0289\nhuman<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/p16.results.txt', sep = '', header = FALSE, col.names = c('frequency', 'isize'))\nhuman<-human[human$isize>1,]\n\nhuman_isizes<-rep(human$isize, human$frequency)\nhuman_df<-as.data.frame(human_isizes)\ncolnames(human_df)[1]<-'isize'\nhuman_df$sample<-'P16_Human'\nhuman_df$read_id<-'eh'\n\n\nhuman_df<-human_df[human_df$isize < 500,]\nhuman_cmv_combined<-rbind(human_df,combined_trimmed)\nlibrary(RColorBrewer)\ngetPalette = colorRampPalette(brewer.pal(8, \"Set3\"))\ncolourCount = length(unique(human_cmv_combined$sample))\n\n\ncmv_cumulative_frequency<-ggplot(combined_trimmed, aes(x = isize, color = sample)) + \n stat_ecdf(geom = 'step', size =.5 )+\n scale_color_manual(values = getPalette(colourCount)) + \n theme_classic() + \n theme(legend.position='bottom') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') \ncmv_cumulative_frequency\n\n\ncolors<-c(\"#8DD3C7\", \"#F4EB42\" ,\"#BEBADA\" ,\"#FB8072\", \"#80B1D3\" ,\"#FDB462\" ,\"#B3DE69\" ,\"#05188B\")\ncumulative_freq_with_human<-ggplot(human_cmv_combined, aes(x = human_cmv_combined$isize, color = human_cmv_combined$sample)) + \n theme_classic() + \n scale_color_manual(values = colors, labels= c('P12','P13','P14','P15','P16','P17','P18','P16 (Human)')) + \n xlab('Fragment size') + \n theme(legend.title=element_blank()) + \n theme(text = element_text(size=8)) +\n theme(legend.text=element_text(size=6)) +\n xlim(c(0,500)) +\n #geom_vline(xintercept = 500) +\n theme(legend.position = c(0.8, 0.3)) + \n ylab ('Cumulative frequency') + \n theme(legend.key.size = unit(.3, \"cm\")) + \n stat_ecdf(geom = 'step', size =.5, pad = FALSE) \ncumulative_freq_with_human\nggsave(plot = cumulative_freq_with_human, 'figure_4c.pdf', height = 3, width = 3)\nsave.image(\"~/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/figure_4c.rdata\")\n\n\n\n\n" }, { "alpha_fraction": 0.6737089157104492, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 20.299999237060547, "blob_id": "a307cdcdbef11aca0585e99a934cdac841a8faef", "content_id": "45afb0ee83ec0b696d4f21d6bee46b843b8dbb73", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 426, "license_type": "no_license", "max_line_length": 57, "num_lines": 20, "path": "/reproducibility/HHV-6/append_sam_header.sh", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "for i in *.bam\ndo\n\tfile=$(echo $i | cut -d . -f1)\n\ttemp_filename=$file.filtered.sam\n\tsam_header=$(samtools view -H $i)\n\techo $temp_filename\n\techo \"$sam_header$(cat $temp_filename)\" > $temp_filename\n\t#echo $sam_header\n\t# echo \"task goes here\n\t# $(cat $tepm_filename)\" > $temp_filename\ndone\n\nmkdir verified_sams \nmv *.sam verified_sams\ncd verified_sams\nmkdir bams \nfor i in *.sam\ndo\n\tsamtools view -Sb $i > $i.bam\nmv *.bam bams\n" }, { "alpha_fraction": 0.8104496002197266, "alphanum_fraction": 0.819562554359436, "avg_line_length": 163.39999389648438, "blob_id": "cfa4537288343dae43eeec2c5122a7ca947292c2", "content_id": "83decda6d78a11f5c3b1c52cb7755dda042a937f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1646, "license_type": "no_license", "max_line_length": 442, "num_lines": 10, "path": "/README.MD", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "# High-resolution profiling of human cytomegalovirus cell-free DNA in human plasma highlights its exceptionally fragmented nature\n\n## Congenital CMV is one of the most common causes of birth defects yet is not screened for in the United States.\nCMV is the leading cause of newborn deafness via congenital infections. Despite this, it is unscreened for in routine prenatal screenings. The current 'gold standard' of congenital CMV diagnostics PCR on amniotic fluid. Amniocentesis is an invasive procedure with a non-zero risk of complications occurring. Here, we attempt to detect CMV/HHV-6 reads using cell-free DNA sequence from a cohort of 2,208 pregnant women.\n\n## We aligned cell-free DNA sequence to the CMV and HHV-6 reference genomes and extracted blast-verified CMV reads\nAfter aligning to the CMV Merlin reference genome (NC_006273.2) all aligned reads were extracted, repeatmasked, and run through blast. The scripts containing more information regarding these pipelines are available at `reproducibility/CMV_reproducibility.sh` and `reproducibility/HHV-6_reproducibility.sh`\n\n## CMV DNA is detectable in cfDNA sequence, and circulates at a smaller fragment size than human chromosomal DNA \nWe show that approximately 5% of samples sent for NIPT had detectable CMV-specific reads, which routinely outstripped the analytical sensitivity of our CMV qPCR assay when performed on cfDNA. We also discovered that CMV cfDNA exists in circulation at a smaller fragment size than human chromosomally-derived cfDNA. We confirmed the highly fragmented nature of CMV in cfDNA in seven CMV-positive specimens from solid organ transplant patients. \n\n" }, { "alpha_fraction": 0.6827785968780518, "alphanum_fraction": 0.7179932594299316, "avg_line_length": 32.514564514160156, "blob_id": "8bc30dd9830853b3277d2f0c53f77554df89cdc5", "content_id": "c5b9746dcbb9b01b44a672ce8ce923da8ed424d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 10365, "license_type": "no_license", "max_line_length": 143, "num_lines": 309, "path": "/scratch/HHV6/nipt_cfDNA_average_coverage_ratio.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#make sure to include hhv6 aligned to betaglobin, edar, and rpp30\n#NEED TO FILL IN START/STOP FOR EACH GENE\nlibrary(Biostrings)\nlibrary(Rsamtools)\nlibrary(GenomicAlignments)\nlibrary(edgeR)\nlibrary(rtracklayer)\nlibrary(openxlsx)\nlibrary(ggplot2)\nlibrary(gtools)\nlibrary(plotrix)\nlibrary(foreach)\nlibrary(doParallel)\nlibrary(seqinr)\nlibrary(scales)\nlibrary(wesanderson)\nlibrary(RColorBrewer)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6')\ndata <- read.csv(\"/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/read_counts_all.csv\")\n\n#update for deduplication\ndata<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/read_counts_all_deduplicated.csv')\n\n# data <- read.xlsx(\"gtex_icihhv6_hhv6b_positives.xlsx\", sheetIndex = 2)\n# datatrimmed <- data[, -c(5:9),(12:13)]\n# data<-data[complete.cases(data$Run), ]\n# data<-data[data$LibrarySelection=='cDNA',]\n# #reads z29 gff3, trims out repeats\n# gff3<-readGFF('hhv6areference.gff3',version=3,columns=NULL, tags=NULL, filter=NULL, nrows=-1, raw_data=FALSE)\n\nedarpath<-'/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/edar'\nrpp30path<-'rpp30'\nbetaglobinpath<-'/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/bglobin'\nhhv6apath<-'/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/hhv6a'\nhhv6bpath<-'/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/hhv6b'\n\n\ndepthcounter<-function(paths,start,stop) {\n list<-c()\n filenames<-list.files(path=paths, pattern='*.bam$')\n for( i in 1:length(filenames)) {\n count<-0\n tempbam<-scanBam(paste0(paths,'/',filenames[i]))\n for( j in 1:length(tempbam[[1]]$pos)){ \n if(tempbam[[1]]$pos[j]>start & tempbam[[1]]$pos[j]<stop) { \n count<-count+1\n }\n }\n print(count)\n list[i]<-count\n print(100*(i/length(filenames)))\n }\n combined<-c()\n combined[[1]]<-list\n combined[[2]]<-filenames\n return(combined)\n}\nbglobinstart<-1545\nbglobinstop<-3871\nbglobin<-depthcounter(betaglobinpath,bglobinstart,bglobinstop)\nbglobincounts<-bglobin[1]\nbglobinnames<-bglobin[2]\nbglobindf<-data.frame(bglobincounts,bglobinnames)\nbglobindf$type<-'Beta globin'\ncolnames(bglobindf)[1]<-'counts'\ncolnames(bglobindf)[2]<-'names'\nbglobindf$depth<-(bglobindf$counts * 76)/(bglobinstop-bglobinstart)\n#bglobindf$total_reads<-0\nbglobindf$read_counts<-NA\nfor ( i in 1:nrow(bglobindf)){ \n tempname<-strsplit(as.character(bglobindf$names[i]), '_bglobin')[[1]][1]\n print(tempname)\n bglobindf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nbglobindf$length<-bglobinstop-bglobinstart\n\nedarstart<-8390\nedarstop<-10900\nedar<-depthcounter(edarpath,edarstart,edarstop)\nedarcounts<-edar[1]\nedarnames<-edar[2]\nedardf<-data.frame(edarcounts,edarnames)\nedardf$type<-'EDAR'\ncolnames(edardf)[1]<-'counts'\ncolnames(edardf)[2]<-'names'\nedardf$depth<-(edardf$counts * 76)/(edarstop-edarstart)\nedardf$read_counts<-NA\nfor ( i in 1:nrow(edardf)){ \n tempname<-strsplit(as.character(edardf$names[i]), '_edar')[[1]][1]\n print(tempname)\n edardf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nedardf$length<- edarstop - edarstart\n\nhhv6astart<-42000\nhhv6astop<-90000\nhhv6a<-depthcounter(hhv6apath,hhv6astart,hhv6astop)\nhhv6acounts<-hhv6a[1]\nhhv6anames<-hhv6a[2]\nhhv6adf<-data.frame(hhv6acounts,hhv6anames)\nhhv6adf$type<-'HHV-6A'\ncolnames(hhv6adf)[1]<-'counts'\ncolnames(hhv6adf)[2]<-'names'\nhhv6adf$depth<-(hhv6adf$counts * 76)/(hhv6astop-hhv6astart)\nhhv6adf$read_counts<-NA\nfor ( i in 1:nrow(hhv6adf)){ \n tempname<-strsplit(as.character(hhv6adf$names[i]), '.sam')[[1]][1]\n print(tempname)\n hhv6adf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nhhv6adf$length<- hhv6astop - hhv6astart\n\n\nhhv6bstart<-42000\nhhv6bstop<-90000\nhhv6b<-depthcounter(hhv6bpath,hhv6bstart,hhv6bstop)\nhhv6bcounts<-hhv6b[1]\nhhv6bnames<-hhv6b[2]\nhhv6bdf<-data.frame(hhv6bcounts,hhv6bnames)\nhhv6bdf$type<-'HHV-6B'\ncolnames(hhv6bdf)[1]<-'counts'\ncolnames(hhv6bdf)[2]<-'names'\nhhv6bdf$depth<-(hhv6bdf$counts * 76)/(hhv6bstop-hhv6bstart)\nhhv6bdf$read_counts<-NA\nfor ( i in 1:nrow(hhv6bdf)){ \n tempname<-strsplit(as.character(hhv6bdf$names[i]), '.sam')[[1]][1]\n print(tempname)\n hhv6bdf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nhhv6bdf$length<- hhv6bstop - hhv6bstart\n\n#allcombined<-rbind(bglobindf,edardf,rpp30df,hhv6adf,hhv6bdf)\nallcombined<-rbind(bglobindf,edardf,hhv6adf,hhv6bdf)\n#allcombined$total_reads<-allcombined$total_reads*1000000\nallcombined$normalized<-allcombined$depth/allcombined$read_counts\nallcombined$normalized_adjusted<-100*(allcombined$normalized/max(allcombined$normalized))\n#allcombined$normalized<-allcombined$depth/allcombined$total_reads\n#allcombined$normalized<-allcombined$normalized*300000000000\n#allcombined[nrow(allcombined)+1,] <- NA\n#allcombined[nrow(allcombined),3]<-'negative'\n#allcombined[nrow(allcombined),4:6]<-0\n\nallcombined$rpkm<-(allcombined$counts * 1e6 * 1e3) / (allcombined$read_counts * (allcombined$length)) \n\npal <- wes.palette(name = \"Zissou\", type = \"continuous\")\n\ngraph<-ggplot(allcombined,aes(x=names, y=depth, color=as.factor(type))) + geom_point()\ngraph + scale_color_brewer(palette=\"Dark2\") + theme_minimal() +\n labs(x = \"Gene\")\n\n#not normalized depth\np2 <- ggplot(allcombined, aes(x=factor(type),y=depth, color=allcombined$read_counts))+\n geom_point() + labs(title=\"Average Coverage\") + \n theme_bw() +\n expand_limits(x = 0, y = 0)\n\np2\n\nggsave('nipt_cfdna_average_coverage.pdf', p2)\n\n\n\n\n#normalized depth\np3 <- ggplot(allcombined, aes(x=factor(type),y=normalized_adjusted, color=allcombined$type))+\n geom_jitter(width = .3, size = .1) +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') +\n theme(legend.position = 'none')\np3\nggsave('nipt_cfdna_average_coverage_normalized.pdf', height = 3, width = 3)\n\np4 <- ggplot(allcombined, aes(x=factor(type),y=normalized_adjusted, color=allcombined$read_counts))+\n geom_point() +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') \np4\nggsave('nipt_cfdna_average_coverage_colored.pdf', p4)\n\nallcombined$fraction<-allcombined$counts/allcombined$read_counts\nwrite.csv(allcombined, 'hhv6_cfdna_info.csv')\n\n\n#with rpkm \nallcombined$rpkm_adjusted<-allcombined$rpkm / max(allcombined$rpkm)\np5 <- ggplot(allcombined, aes(x=factor(type),y=rpkm_adjusted, color=allcombined$type))+\n geom_jitter(width = .3, size = 1) +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n theme(legend.position = 'none') + \n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') \np5\nggsave('hhv6_nipt_cfdna_average_coverage_rpkm_deduplicated.pdf', p5, width = 3, height = 3)\n\n allcombined$sample<-NA\nfor(i in 1:nrow(allcombined)){\n if(grepl('bglobin',allcombined$names[i])){\n allcombined$sample[i]<-strsplit(as.character(allcombined$names[i]), '_bglobin*')[[1]][1]\n }\n else if (grepl('edar',allcombined$names[i])){\n allcombined$sample[i]<-strsplit(as.character(allcombined$names[i]), '_edar*')[[1]][1]\n }\n else { \n allcombined$sample[i]<-strsplit(as.character(allcombined$names[i]), '.sam*')[[1]][1]\n \n }\n }\nto_change_shape<-c()\nfor(i in 1:nrow(allcombined)){ \n if(allcombined$rpkm[i] < .2) { \n to_change_shape<-append(to_change_shape,allcombined$sample[i])\n }\n}\nto_change_shape<-unique(to_change_shape)\nallcombined$shape<-'hhv6b rpkm > .2'\n\nfor(i in 1:nrow(allcombined)){\n for(j in 1:length(to_change_shape)){ \n if(to_change_shape[j] == allcombined$sample[i]){ \n allcombined$shape[i]<-'hhv6b rpkm < .2'\n }\n }\n }\n\np6 <- ggplot(allcombined, aes(x=factor(type),y=rpkm, color=allcombined$type, shape = allcombined$shape))+\n geom_jitter(width = .3) +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') \np6\nggsave('nipt_cfdna_average_coverage_rpkm_by_shape.pdf', p6)\n\n\nno_hhv6a<-allcombined[allcombined$type!='HHV-6A',]\n\np7 <- ggplot(no_hhv6a, aes(x=factor(type),y=rpkm))+\n geom_jitter(width = .3, size = .5) +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') \np7\nggsave('nipt_cfdna_average_coverage_rpkm.pdf', p5)\n\n\n\n\n\n\n\n#fetal fraction data \nwrite.csv(just_hhv6b,'just_icihhv-6b.csv')\nfetal_fraction<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/icihhv6_cellfreefetal_added.xlsx')\njust_hhv6b<-allcombined[allcombined$type=='HHV-6B',]\njust_hhv6b$sample<-as.character(just_hhv6b$sample)\njust_hhv6b$fraction<-NA\njust_hhv6b$sample<-as.character(just_hhv6b$sample)\nfetal_fraction$X1<-as.character(fetal_fraction$X1)\nfor(i in 1:nrow(just_hhv6b)){ \n for(j in 1:nrow(fetal_fraction)){ \n if(grepl(just_hhv6b$sample[i],fetal_fraction$X1[j])){ \n just_hhv6b$fraction[i]<-fetal_fraction$Predicted_Fetal_Fraction[j]\n }\n }\n }\n\n\nfetal_fraction_plot<-ggplot(just_hhv6b, aes(x = just_hhv6b$fraction, y= just_hhv6b$rpkm, group = just_hhv6b$shape)) + \n geom_point() + \n geom_smooth(method = 'lm', se = FALSE) + \n theme_classic() + \n ylab('RPKM') + \n xlab('Predicted fetal fraction')\nfetal_fraction_plot\nggsave(plot = fetal_fraction_plot,'icihHV-6_cfdna_fetalfractions.pdf', height = 3, width = 3)\n\nmale_fetal_fraction<-fetal_fraction[fetal_fraction$Sex_Classification=='XY',]\njust_hhv6b_male<-allcombined[allcombined$type=='HHV-6B',]\njust_hhv6b_male$sample<-as.character(just_hhv6b_male$sample)\njust_hhv6b_male$fraction<-NA\njust_hhv6b_male$sample<-as.character(just_hhv6b_male$sample)\nmale_fetal_fraction$X1<-as.character(male_fetal_fraction$X1)\nfor(i in 1:nrow(just_hhv6b_male)){ \n for(j in 1:nrow(male_fetal_fraction)){ \n if(grepl(just_hhv6b_male$sample[i],male_fetal_fraction$X1[j])){ \n just_hhv6b_male$fraction[i]<-male_fetal_fraction$Predicted_Fetal_Fraction[j]\n }\n }\n}\nmale_fetal_fraction_plot<-ggplot(just_hhv6b_male, aes(x = just_hhv6b_male$fraction, y= just_hhv6b_male$rpkm, group = just_hhv6b_male$shape)) + \n geom_point() + \n geom_smooth(method = 'lm', se = FALSE) + \n theme_classic() + \n ylab('RPKM') + \n xlab('Predicted fetal fraction')\nmale_fetal_fraction_plot\nggsave(plot = male_fetal_fraction_plot,'male_icihHV-6_cfdna_fetalfractions.pdf', height = 3, width = 3)\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7391012907028198, "alphanum_fraction": 0.7484909296035767, "avg_line_length": 37.230770111083984, "blob_id": "48bbf59d868ba1b1187d8eb38572b032af6db3d0", "content_id": "82428c9f2f82986ba7c6030347770f051eb02f5b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1491, "license_type": "no_license", "max_line_length": 137, "num_lines": 39, "path": "/reproducibility/CMV/maternal/previous_version/intermediate_positive_insert_stats.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal')\n\nbam_folder<-'/Users/gerbix/Documents/vikas/NIPT/all_deduplicated/original_bams_deduplicated/'\n\nblasted_reads<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/blast_positive_sequence_info.csv')\n\nall_sample_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/all_sample_data.csv')\n\nblasted_reads$sample<-NA\nblasted_reads$unique_id<-NA\nfor(i in 1:nrow(blasted_reads)){ \n blasted_reads$sample[i]<-strsplit(as.character(blasted_reads$nameslist[i]),'[.]')[[1]][1]\n blasted_reads$unique_id[i]<-strsplit(as.character(blasted_reads$nameslist[i]),'-')[[1]][2]\n }\n\nto_remove<-as.character(all_sample_data$sample[all_sample_data$classification=='strong positive'])\nblasted_reads<-blasted_reads[-which(blasted_reads$sample %in% to_remove),]\n\n\nblasted_reads$isize<-NA\nfor(i in 1:nrow(blasted_reads)){ \n print(i)\n temp_dir<-paste0(bam_folder,'/',blasted_reads$sample[i], '.sam.bam.sorted.bam_dedup.bam')\n temp_bam<-scanBam(temp_dir)\n blasted_reads$isize[i]<-abs(temp_bam[[1]]$isize[which(grepl(blasted_reads$unique_id[i],temp_bam[[1]]$qname))])\n}\nblasted_reads<-blasted_reads[complete.cases(blasted_reads$isize),]\n\nsummary(blasted_reads$isize[blasted_reads$isize < 500])\n\nlength(unique(blasted_reads$unique_id))\n" }, { "alpha_fraction": 0.6310679316520691, "alphanum_fraction": 0.6474341154098511, "avg_line_length": 23.114093780517578, "blob_id": "6104a424db417d88ecf0996ec8611c57ac7f5174", "content_id": "4eda26b574f6efa5a2a66879fe73b7d999770886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3605, "license_type": "no_license", "max_line_length": 83, "num_lines": 149, "path": "/scratch/blast_hits.py", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n####MODIFIED FOR LOCAL BLAST#### \n#args[1] = blast file\n#args[2] = virus identifier\n\nimport sys \nimport csv\nimport re\n\nblastfile = open(sys.argv[1], \"r\").readlines()\n#print blastfile\n\n#deletelines=[]\nprint(sys.argv[2])\ncount = 0 \nfor i in range(1, len(blastfile)): \n\t#print(type(blastfile[i]))\n\tif(re.search('-$', blastfile[i])): \n\t\tcount +=1\n\t\t#print(blastfile[i].rstrip(\"\\n\"))\n\t\tblastfile[i] = blastfile[i].rstrip(\"\\n\") + blastfile[i+1].rstrip()\n\t\t#print(blastfile[i])\n\t\t#i +=1\n\t\t#deletelines.append((i+1))\n\t\t# print(blastfile[i])\n\t\t#print(blastfile[i + 1])\n\t\t#print(blastfile[i+1])\n#print(count)\n\n\nquerylist= []\ncount_start=14\nmatches_start=0\nmatches_end=0\nalignments_start=[]\nalignments_end=[]\nnames=[]\nfor i in range(1,len(blastfile)):\n\tnumlines=0\n\tif \"Query=\" in blastfile[i]:\n\t\t#print(blastfile[i])\n\t\t# should use a single if not statement here \n\t\t# if blastfile[i+6][0] == '*':\n\t\t# \tprint ('fuck')\n\t\tif blastfile[i+5][0]!='*' and blastfile[i+6][0]!='*':\n\t\t\t#print(blastfile[i])\n\t\t\t#print(blastfile[i+6])\n\n\t\t\t# default argument of split is whitespace \n\t\t\ttemp_name=blastfile[i].split(\" \")[1]\n\t\t\t#print (temp_name.rstrip())\n\t\t\tnames.append(temp_name.rstrip())\n\t\t\t#print(temp_name)\n\t\t\tcontinue\n\t\t\t#print(temp_name.rstrip())\n\t\t#print(temp_name)\n\n\tif \"alignments:\" in blastfile[i]:\n\t\tmatches_start=(i+3)\n\t\talignments_start.append(matches_start)\n\t\tcontinue\n\t\t#print(matches_start)\n\t\t#print('ok')\n\t\t#print(matches_start)\n\tif blastfile[i][0] == \">\" and \"\\n\" in blastfile[i-1] and (blastfile[i-3][0]!='S'):\n\t\t#print(blastfile[0])\n\t\t#print (blastfile[i])\n\t\tmatches_end=(i-2)\n\t\talignments_end.append(matches_end)\n\t\tcontinue\n\tif(len(alignments_end) > len(alignments_start)): \n\t\tprint(i)\n\t\tprint('fuck')\n\t\t#print(matches_end)\n\t\t#print (temp_name)\n\t\t#print ('\\n')\n\t\t# print ('new')\n\t\t# print(blastfile[i-3])\n\t\t# print(blastfile[i-2])\n\t\t# print(blastfile[i-1])\n\t\t# print(blastfile[i])\n\t\t#print ('ok')\n\t#print (\"\\n\")\n\t\t#print(matches_end)\n\t#print(range(matches_end,matches_start))\n\t#hhv6_count=0\n\t# for j in range(matches_end,matches_start): \n\t# \tif ('Herpesvirus 6') in blastfile[j]:\n\t# \t\thhv6_count+=1\n\t# \tif(hhv6_count>1):\n\t# \t\tprint(hhv6_count)\n\t\t# count_end=i\n\t\t# #print(blastfile[count_end])\n\t\t# numlines=count_end-count_start\n\t\t# print(numlines)\n\n\t\t#count_start=count_end\n#print(blastfile[11])\n#print(len(names))\ndata=[]\nperc_total=[]\n\n\nfor i in range(len(alignments_start)):\n\t#print (len(alignments_start))\n\t#print (len(alignments_end))\n\t#print('\\n')\n\tcount=0\n\ttemp=[]\n\t# if (alignments_start[i]==alignments_end[i]):\n\t# \tprint (\"ok\")\n\t#print(alignments_start[i])\n\t#print(alignments_end[i])\n\tfor j in range(alignments_start[i],alignments_end[i]):\n\t\tif sys.argv[2] in blastfile[j]:\n\t\t\tcount+=1\n\t\t\t# print(blastfile[j])\n\t\t\t# print(names[i])\n\t\t\t# print(j+1)\n\t\t\t# print(alignments_start[i])\n\t\t\t# print(alignments_end[i])\n\t\t\t# print('\\n')\n\t\t\t# print(blastfile[j])\n\t#temp_perc = 100* (count/(alignments_end[i] - alignments_start[i]))\n\t#perc_total.append(temp_perc)\n\ttemp=[names[i].strip(),count]\n\t#print (names[i].strip())\n\t#print(temp)\n\tdata.append(temp)\n#print(data)\nmyFile = open('blast_hits.csv', 'w')\nwith myFile:\n writer = csv.writer(myFile)\n writer.writerows(data)\nprint(\"file written as blast_hits.csv\")\n\t#print(i)\t\t\n\t# \t\thhv6_count+=1\n\t# \tif(hhv6_count>1):\n\t# \t\tprint(hhv6_count)\n#print(len(names))\nprint(len(alignments_start))\nprint(len(alignments_end))\nprint(len(names))\n\n#print(names)\n\n###make a temp list of lines between alignment_end and alignment_start \n###take that list and grep for herpesvirus 6 \n###count that and put in a line with the name in a .csv\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6205711364746094, "alphanum_fraction": 0.6483342051506042, "avg_line_length": 31.869565963745117, "blob_id": "9e77250058ef108688fa332b07d4203baad749c2", "content_id": "cb05b374ec4cb11575537ac312a94c2001e72bba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3782, "license_type": "no_license", "max_line_length": 132, "num_lines": 115, "path": "/reproducibility/HHV-6/figure_5B.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(svMisc)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5b/6a_verified_sams/bams')\n\nread_counts <- read.csv(\"/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5b/read_counts_all_deduplicated.csv\")\nsystem(\"for i in *.bam ; do echo processing $i ; samtools view -@ 8 $i | awk '{print $9}' | sort | uniq -c > $i.results.txt ; done\")\nfilenames = list.files(pattern = '*.bam.results.txt$')\nplotslist<-c()\n\nsavePlot <- function(myPlot, plotname) {\n pdf(plotname, width = 8.5, height = 11)\n print(myPlot)\n dev.off()\n}\n\ntotallengths<-c()\ntotaloccurences<-c()\ndflist<-c()\ntoremove<-c()\nstatslist<-c()\nstatslistremove<-c()\nfor (i in 1:length(filenames)){ \n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'length'\n colnames(histo)[1]<-'occurences'\n histo$type<-strsplit(filenames[i],\".sam\")[[1]][1]\n histo<-histo[histo$length>0,]\n if(nrow(histo)>0){\n for(j in 1:length(histo$occurences)){ \n for(k in 1:histo$occurences[j]){ \n #print(histo$length[i])\n statslist<-append(statslist, histo$length[j]) \n }\n }\n statslistremove<-which(statslist>900)\n if(length(statslistremove)>0){ \n statslist<-statslist[-statslistremove]\n }\n toremove<-which(histo[,2]> 900)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$length)\n totaloccurences =append(totaloccurences,histo$occurences)\n plot<-ggplot(histo, aes(y=histo$occurences, x=histo$length)) + \n geom_point() + \n geom_vline(xintercept = median(statslist)) +\n ylab('occurences')+\n xlab('length') +\n annotate(\"text\", x = 400, y = max(histo$occurences)-5, label = paste0('mean=', mean(statslist))) + \n annotate(\"text\", x = 400, y = max(histo$occurences)-6, label = paste0('median=', median(statslist)))\n \n print(plot)\n #print(mean(statslist))\n plotname = paste0(filenames[i],'.plot.pdf')\n print(filenames[1])\n print(i)\n #ggsave(filename=plotname, device = pdf)\n #savePlot(plot, plotname)\n dflist[[i]]<-histo\n }\n }\n}\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6')\n\n\ncombined <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nfor(i in 1:nrow(combined)){\n for(j in 1:combined$occurences[i]){\n lengthlist<-append(lengthlist,combined$length[i])\n samplelist<-append(samplelist,combined$type[i])\n }\n}\n\n\ncombined_expanded<-data.frame(lengthlist,samplelist)\n\nfor(i in 1:nrow(combined_expanded)){ \n progress(i,nrow(combined_expanded))\ncombined_expanded$sample_trimmed<-strsplit(as.character(combined_expanded$samplelist),'_')[[i]][1]\n}\n\nlow_cluster<-c('99P03_C01','120R22_F03','104P04_D01','98P11','97P10_B02','93R20_D03')\n\ncombined_expanded$cluster<-\"High HHV-6\"\nfor(i in 1:nrow(combined_expanded)){ \n if(grepl(paste(low_cluster,collapse=\"|\"),combined_expanded$samplelist[i])){ \n combined_expanded$cluster[i]<-\"Low HHV-6\"\n }\n }\n\nplot<-ggplot(combined_expanded, aes( x=combined_expanded$lengthlist)) + \n geom_histogram(binwidth = 5, aes(fill = combined_expanded$cluster, y=(100 * ..count../sum(..count..)))) + \n scale_fill_manual(values=c(\"orangered\", \"royalblue2\")) + \n xlim(0,500) + \n ylab('Percent within each alignment')+\n xlab('Fragment size')+\n labs(colour=\"file\") +\n theme_classic() +\n #theme(legend.position = 'bottom') +\n labs(fill=\"\") +\n theme(text = element_text(size=8)) +\n theme(legend.position = c(0.8, 0.3)) + \n theme(legend.title=element_blank())\nplot\nggsave(plot=plot, 'figure_5B.pdf', height = 3, width = 3)\n\nwrite.csv(combined_expanded, 'hhv6_isizes_all.csv')\n\nsave.image(file = 'figure_5B.rdata')\n\n\n" }, { "alpha_fraction": 0.7469512224197388, "alphanum_fraction": 0.7625339031219482, "avg_line_length": 43.044776916503906, "blob_id": "32d51224f73840fe740d037eae956691d98df442", "content_id": "6873ce560aedc10e224ddc27b6c750c972e133e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2952, "license_type": "no_license", "max_line_length": 187, "num_lines": 67, "path": "/scratch/low_positive_read_extract.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(svMisc)\nlibrary(seqinr)\nlibrary(Rsamtools)\nlibrary(ggplot2)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download')\n\nblast_positive<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/blast_positive_sequence_info.csv')\nall_samples<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/all_sample_data.csv')\n\n\nintermediates<-all_samples[all_samples$classification=='intermediate positive',]\n\nblast_positive$sample<-NA\nfor(i in 1:nrow(blast_positive)){ \n progress(i) \n blast_positive$sample[i]<-strsplit(as.character(blast_positive$nameslist[i]),'[.]')[[1]][1]\n}\n\nintermediates_with_sequences<-setNames(data.frame(matrix(ncol = ncol(blast_positive), nrow = 0)), colnames(blast_positive))\nfor(i in 1:nrow(intermediates)){ \n temp<-which(intermediates$sample[i]==blast_positive$sample)\n print(temp)\n for(j in 1:length(temp)){ \n intermediates_with_sequences<-rbind(intermediates_with_sequences, blast_positive[temp[j],])\n }\n}\nintermediates_with_sequences$nameslist<-as.character(intermediates_with_sequences$nameslist)\nfor(i in 1:nrow(intermediates_with_sequences)){ \n #print(as.character(strsplit(as.character(intermediates_with_sequences$nameslist[i]),'-')[[1]][2]))\n intermediates_with_sequences$nameslist[i]<-as.character(strsplit(as.character(intermediates_with_sequences$nameslist[i]),'-')[[1]][2])\n }\n\nwrite.csv(intermediates_with_sequences,'intermediate_positive_sequences_deduplicated.csv')\n\nsystem('mkdir intermediate_positive_fastas_deduplicated')\nsetwd('intermediate_positive_fastas_deduplicated/')\n\nfor(i in 1:nrow(intermediates_with_sequences)){ \n temp_header<-paste0(intermediates_with_sequences$sample[i],intermediates_with_sequences$nameslist[i])\n temp_seq<-intermediates_with_sequences$seqslist[i]\n print(temp_header)\n temp_file_name<-paste(i,'.tempfa')\n write.fasta(sequences = temp_seq, names = temp_header, file.out = temp_file_name)\n}\nsystem('cat *.tempfa > intermediate_sequences.fasta')\nsystem('rm *.tempfa')\n\nintermediates_with_sequences$isize<-NA\nfor(i in 1:nrow(intermediates_with_sequences)){ \n #progress(i,nrow(intermediates_with_sequences))\n tempbamname<-paste0('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/original_bams_deduplicated/',intermediates_with_sequences$sample[i],'.sam.bam.sorted.bam_dedup.bam')\n tempbam<-scanBam(tempbamname)\n read<-which(grepl(intermediates_with_sequences$nameslist[i], tempbam[[1]]$qname))\n temp_isize<-((tempbam[[1]]$isize[read]))\n if( any(is.na(temp_isize))) {\n temp_isize<-0\n }\n temp_isize<-abs(temp_isize[1])\n print(temp_isize)\n intermediates_with_sequences$isize[i]<-temp_isize\n}\nintermediates_with_sequences<-intermediates_with_sequences[complete.cases(intermediates_with_sequences$isize),]\nintermediates_median<-median(intermediates_with_sequences$isize)\nggplot(intermediates_with_sequences, aes(x = intermediates_with_sequences$isize)) + \n geom_freqpoly() + \n theme_classic() \n" }, { "alpha_fraction": 0.6383838653564453, "alphanum_fraction": 0.6684623956680298, "avg_line_length": 34.062992095947266, "blob_id": "d27d992bfa5749eb1951fe832c2413710c4672fa", "content_id": "9833844197ed780789fc428a488ee0c3fc0e792e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4455, "license_type": "no_license", "max_line_length": 183, "num_lines": 127, "path": "/scratch/new_cmv_samples/median_fragment_length_new_samples.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/new_samples')\n#read_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/blast_hits.csv', header = FALSE, col.names = c('full_ID','count'))\nfilenames = list.files('/Users/gerbix/Documents/vikas/NIPT/new_samples',pattern = '.bam$')\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\n blast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\nblast_hits_file<-blast_hits_file[blast_hits_file$count>75,] \nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\nfor(i in 1:length(filenames)){ \n #print(100 * (i / length(filenames)))\n #print(i)\n temp_bam<-scanBam(filenames[i])\n if((identical(temp_bam[[1]]$qname, character(0)))){ \n #print(i)\n next\n }\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n print(100 * (j/nrow(blast_hits_file)))\n for(k in 1:length(all_bam_read_IDs)){\n # print(blast_hits_file$read_ID[j])\n if( !(is.na(blast_hits_file$read_ID[j])) & grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, filenames[i])\n }\n }\n }\n}\ncombined<-data.frame(sample, read_id, isize)\ncombined<-combined[combined$isize>0,]\ncombined<-combined[complete.cases(combined$isize),]\ncmv_plot<-ggplot(combined, aes( x=combined$isize, fill = sample)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('fragment length')+\n #annotate(\"text\", x = 400, y = 18 , label = paste0('mean=', mean(combined$isize))) + \n annotate(\"text\", x = 400, y = 600, label = paste0('median=', median(combined$isize[combined$isize<500]))) +\n labs(colour=\"file\") +\n scale_y_continuous(expand = c(0,0)) +\n theme_classic() + \n theme(legend.position=\"right\")\ncmv_plot\nggsave(plot = cmv_plot, 'new_cmv_insert_size_colored.pdf', height = 5, width = 5)\n\n\n#overlaying human \nhuman<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/p16.results.txt', sep = '', header = FALSE, col.names = c('frequency', 'isize'))\nhuman<-human[human$isize>0,]\nhuman_isizes<-rep(human$isize, human$frequency)\nhuman_df<-as.data.frame(human_isizes)\ncolnames(human_df)[1]<-'isize'\nhuman_df$sample<-'P16_Human'\nhuman_df$read_id<-'eh'\n\n\ncmv_df<-as.data.frame(table(combined$isize[combined$isize<500]))\ncmv_df$percent<-NA\nfor(i in 1:nrow(cmv_df)){ \n cmv_df$percent[i] <- 100 * (cmv_df$Freq[i] / sum(cmv_df$Freq))\n }\ncmv_df$type<-'CMV'\n\nhuman_isize_df<-as.data.frame(table(human_df$isize[human_df$isize<500]))\nhuman_isize_df$percent<-NA\nfor(i in 1:nrow(human_isize_df)){ \n human_isize_df$percent[i] <- 100 * (human_isize_df$Freq[i] / sum(human_isize_df$Freq))\n}\nhuman_isize_df$type<-'Human'\n\ncombined_isize_df<-rbind(human_isize_df, cmv_df)\n\n\ncmv_plot<-ggplot(combined_isize_df, aes( x=as.numeric(as.character(combined_isize_df$Var1)), y = as.numeric(as.character(combined_isize_df$percent)),color = combined_isize_df$type)) +\n geom_line() + \n #geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n ylim(0,2.5) + \n ylab('percent')+\n xlab('insert size')+\n #annotate(\"text\", x = 400, y = 18 , label = paste0('mean=', mean(combined$isize))) + \n #annotate(\"text\", x = 400, y = 600, label = paste0('median=', median(combined$isize[combined$isize<500]))) +\n #labs(colour=\"file\") +\n #scale_y_continuous(expand = c(0,0)) +\n #theme(legend.title =\"\") + \n theme_classic() +\n #theme(legend.title = element_blank()) \n theme(legend.position = 'none') \ncmv_plot\n\nggsave(plot = cmv_plot, 'new_cmv_isize_distribution.pdf', height = 3, width = 3)\n\n######\nfor(i in (unique(combined$sample))){ \n print(i)\n print(median(combined$isize[combined$sample==i & combined$isize < 500]))\n print('')\n }\n\n\nP17<-combined[combined$sample=='244P17_A03_CFFv2_NB0289.sam.bam' & combined$isize < 500,]\nmedian(P17$isize[P17$isize<500])\n\n#finding size of the two peaks \nmedian(combined$isize[combined$isize < 100])\n\nmedian(combined$isize[combined$isize < 250 & combined$isize > 100])\n\n\n" }, { "alpha_fraction": 0.6779234409332275, "alphanum_fraction": 0.7128857374191284, "avg_line_length": 31.399141311645508, "blob_id": "a7655b1f4ac2b2b0e7a8f7e878cc580b961ca8e5", "content_id": "d9f9a8ac37c41bea5f54a76f48afbdee79324b59", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 7551, "license_type": "no_license", "max_line_length": 105, "num_lines": 233, "path": "/reproducibility/HHV-6/figure_5A.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#make sure to include hhv6 aligned to betaglobin, edar, and rpp30\n#NEED TO FILL IN START/STOP FOR EACH GENE\nlibrary(Biostrings)\nlibrary(Rsamtools)\nlibrary(GenomicAlignments)\nlibrary(edgeR)\nlibrary(rtracklayer)\nlibrary(openxlsx)\nlibrary(ggplot2)\nlibrary(gtools)\nlibrary(plotrix)\nlibrary(foreach)\nlibrary(doParallel)\nlibrary(seqinr)\nlibrary(scales)\nlibrary(wesanderson)\nlibrary(RColorBrewer)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6')\n\ndata<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/read_counts_all_deduplicated.csv')\n\nedarpath<-'/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5a/edar/bams/sorted/deduplicated'\nbetaglobinpath<-'/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5a/bglobin/bams/sorted/deduplicated'\nhhv6apath<-'/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5a/6a_verified_sams/bams'\nhhv6bpath<-'/Users/gerbix/Documents/vikas/NIPT/hhv6/figure_5a/6b_verified_sams/bams'\n\n\ndepthcounter<-function(paths,start,stop) {\n list<-c()\n filenames<-list.files(path=paths, pattern='*.bam$')\n for( i in 1:length(filenames)) {\n count<-0\n tempbam<-scanBam(paste0(paths,'/',filenames[i]))\n for( j in 1:length(tempbam[[1]]$pos)){ \n if(tempbam[[1]]$pos[j]>start & tempbam[[1]]$pos[j]<stop) { \n count<-count+1\n }\n }\n print(count)\n list[i]<-count\n print(100*(i/length(filenames)))\n }\n combined<-c()\n combined[[1]]<-list\n combined[[2]]<-filenames\n return(combined)\n}\nbglobinstart<-1545\nbglobinstop<-3871\nbglobin<-depthcounter(betaglobinpath,bglobinstart,bglobinstop)\nbglobincounts<-bglobin[1]\nbglobinnames<-bglobin[2]\nbglobindf<-data.frame(bglobincounts,bglobinnames)\nbglobindf$type<-'Beta-globin'\ncolnames(bglobindf)[1]<-'counts'\ncolnames(bglobindf)[2]<-'names'\nbglobindf$depth<-(bglobindf$counts * 76)/(bglobinstop-bglobinstart)\n#bglobindf$total_reads<-0\nbglobindf$read_counts<-NA\nfor ( i in 1:nrow(bglobindf)){ \n tempname<-strsplit(as.character(bglobindf$names[i]), '_bglobin')[[1]][1]\n print(tempname)\n bglobindf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nbglobindf$length<-bglobinstop-bglobinstart\n\nedarstart<-8390\nedarstop<-10900\nedar<-depthcounter(edarpath,edarstart,edarstop)\nedarcounts<-edar[1]\nedarnames<-edar[2]\nedardf<-data.frame(edarcounts,edarnames)\nedardf$type<-'EDAR'\ncolnames(edardf)[1]<-'counts'\ncolnames(edardf)[2]<-'names'\nedardf$depth<-(edardf$counts * 76)/(edarstop-edarstart)\nedardf$read_counts<-NA\nfor ( i in 1:nrow(edardf)){ \n tempname<-strsplit(as.character(edardf$names[i]), '_edar')[[1]][1]\n print(tempname)\n edardf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nedardf$length<- edarstop - edarstart\n\nhhv6astart<-0\nhhv6astop<-159000\nhhv6a<-depthcounter(hhv6apath,hhv6astart,hhv6astop)\nhhv6acounts<-hhv6a[1]\nhhv6anames<-hhv6a[2]\nhhv6adf<-data.frame(hhv6acounts,hhv6anames)\nhhv6adf$type<-'HHV-6A'\ncolnames(hhv6adf)[1]<-'counts'\ncolnames(hhv6adf)[2]<-'names'\nhhv6adf$depth<-(hhv6adf$counts * 76)/(hhv6astop-hhv6astart)\nhhv6adf$read_counts<-NA\nfor ( i in 1:nrow(hhv6adf)){ \n tempname<-strsplit(as.character(hhv6adf$names[i]), '.filtered')[[1]][1]\n print(tempname)\n hhv6adf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nhhv6adf$length<- hhv6astop - hhv6astart\n\n\nhhv6bstart<-0\nhhv6bstop<-162000\nhhv6b<-depthcounter(hhv6bpath,hhv6bstart,hhv6bstop)\nhhv6bcounts<-hhv6b[1]\nhhv6bnames<-hhv6b[2]\nhhv6bdf<-data.frame(hhv6bcounts,hhv6bnames)\nhhv6bdf$type<-'HHV-6B'\ncolnames(hhv6bdf)[1]<-'counts'\ncolnames(hhv6bdf)[2]<-'names'\nhhv6bdf$depth<-(hhv6bdf$counts * 76)/(hhv6bstop-hhv6bstart)\nhhv6bdf$read_counts<-NA\nfor ( i in 1:nrow(hhv6bdf)){ \n tempname<-strsplit(as.character(hhv6bdf$names[i]), '.filtered')[[1]][1]\n print(tempname)\n hhv6bdf$read_counts[i]<-data$count[which(grepl(tempname,data$sample))]\n}\nhhv6bdf$length<- hhv6bstop - hhv6bstart\n\n\nallcombined<-rbind(bglobindf,edardf,hhv6adf,hhv6bdf)\n\nallcombined$normalized<-allcombined$depth/allcombined$read_counts\nallcombined$normalized_adjusted<-100*(allcombined$normalized/max(allcombined$normalized))\n\nallcombined$rpkm<-(allcombined$counts * 1e6 * 1e3) / (allcombined$read_counts * (allcombined$length)) \n\n#not normalized depth\np2 <- ggplot(allcombined, aes(x=factor(type),y=depth, color=allcombined$read_counts))+\n geom_point() + labs(title=\"Average Coverage\") + \n theme_bw() +\n expand_limits(x = 0, y = 0)\n\np2\n\n#normalized depth\np3 <- ggplot(allcombined, aes(x=factor(type),y=normalized_adjusted, color=allcombined$type))+\n geom_jitter(width = .3, size = .1) +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') +\n theme(legend.position = 'none')\np3\n\np4 <- ggplot(allcombined, aes(x=factor(type),y=normalized_adjusted, color=allcombined$read_counts))+\n geom_point() +\n labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n xlab('gene') +\n ylab('normalized depth') +\n scale_y_continuous(trans='log10') \np4\n\nallcombined$fraction<-allcombined$counts/allcombined$read_counts\nwrite.csv(allcombined, 'hhv6_cfdna_info.csv')\n\n\n#with rpkm \nallcombined$rpkm_adjusted<-allcombined$rpkm / max(allcombined$rpkm)\nallcombined$color<-NA\nallcombined$color[allcombined$rpkm_adjusted < .1] = 'blue'\nallcombined$color[allcombined$rpkm_adjusted > .1 & allcombined$rpkm_adjusted < .8] = 'red'\nallcombined$color[allcombined$type==\"Beta-globin\" | allcombined$type==\"EDAR\"]<-'green'\n\n\np5 <- ggplot(allcombined, aes(x=factor(type),y=rpkm_adjusted, color=allcombined$color))+\n scale_color_manual(values = c( '#436EEE','#077524', '#FF4500')) + \n geom_jitter(width = .3, size = 1) +\n #labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n theme(legend.position = 'none') + \n #xlab('') +\n ylab('normalized depth') +\n theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),axis.title.x=element_blank())+ \n scale_y_continuous(trans='log10') +\n theme(text = element_text(size=8)) \np5\nggsave('figure_5A_full_hhv6_genome.pdf', p5, width = 3, height = 3)\n\n\n\n## EDITS\n\nab_combined<-allcombined\nab_combined$shape<-'circle'\nfor(i in 1:nrow(ab_combined)){ \n if(ab_combined$type[i] == 'HHV-6B'){ \n ab_combined$shape[i]<-'HHV-6B'\n }\n if(ab_combined$type[i] == 'HHV-6A'){ \n ab_combined$shape[i]<-'HHV-6A'\n }\n}\nab_combined$type[ab_combined$type == 'HHV-6A' | ab_combined$type == 'HHV-6B'] <-'HHV-6'\n\nto_remove<-c()\nab_combined$type<-as.character(ab_combined$type)\nab_combined$names<-as.character(ab_combined$names)\nhhv6_unique<-unique(ab_combined$names[ab_combined$type == 'HHV-6'])\n\nfor(i in 1:length(hhv6_unique)){ \n temp<-which(ab_combined$names == hhv6_unique[i] & ab_combined$type == 'HHV-6')\n if(ab_combined$rpkm[temp[1]] > ab_combined$rpkm[temp[2]]){ \n to_remove<-append(to_remove, temp [2])\n }\n else{ \n to_remove<-append(to_remove, temp[1])\n }\n }\nab_combined<-ab_combined[-to_remove,]\n\n\np6 <- ggplot(ab_combined, aes(x=factor(type),y=rpkm_adjusted, color=ab_combined$color))+\n scale_color_manual(values = c( '#436EEE','#077524', '#FF4500')) + \n geom_jitter(width = .3, size = 1, aes(shape = ab_combined$shape)) +\n #labs(title=\"Average Coverage\", color = 'Target') + \n theme_bw() +\n theme(legend.position = 'none') + \n #xlab('') +\n ylab('normalized depth') +\n theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1),axis.title.x=element_blank())+ \n scale_y_continuous(trans='log10') +\n theme(text = element_text(size=8)) \np6\nggsave('figure_5A_full_hhv6_shape_combined.pdf', p6, width = 3, height = 3)\n\n\nsave.image(file = 'figure_5A.rdata')\n\n\n" }, { "alpha_fraction": 0.7397388219833374, "alphanum_fraction": 0.7602611780166626, "avg_line_length": 38.72222137451172, "blob_id": "25502dc0edcaa38026ca19cb2aa95f49a68321d2", "content_id": "0a74936125bede9abba257a550468d8bd222a009", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2144, "license_type": "no_license", "max_line_length": 160, "num_lines": 54, "path": "/reproducibility/CMV_reproducibility.sh", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#Workflow for generating CMV figures \n\n#Bowtie2 alignment to CMV Merlin genome (NC_006273.2)\nbowtie2 -x <cmv_merlin_reference> -1 <r1.fastq> -2 <r2.fastq> --local --no-unal -p <cores> -S <aligned.sam> \n\n#Convert SAM to BAM \nsamtools view -@ <cores> -Sb <aligned.sam> -o <aligned.bam> \n\n#sort BAM for picard\nsamtools sort <aligned.bam> -o <sorted.bam> \n\n#Deduplicate aligned bam file \npicard MarkDuplicates I=<sorted.bam> O=<deduplicated.bam> M=<metrics.txt> REMOVE_DUPLICATES= TRUE ASSUME_SORTED=TRUE VALIDATION_STRINGENCY= SILENT\n\n#Only keep reads with 34 or more matches and extract reads for repeatmasking and BLAST later.\n./34m.sh <deduplicated_bam_folder> \n\n#Repeatmask output of previous command\nRepeatmasker -int -pa <cores> cmv_combined.txt\nmv cmv_combined.txt.masked cmv_combined_masked.fasta \n\n#remove all repeat masked lines with NNNNN in it \nfor file in cmv_combined_masked.fasta\ndo\nsed '$!N;/NNNNN/!P;D' \"$file\"\ndone > cmv_combined_masked_n_removed.fasta\n\n#Local BLAST against NT (requires blast NT database)\nblastn -query cmv_combined_masked_n_removed.fasta -db /db/blast_db/nt -num_threads 42 -perc_identity 97 -evalue 1e-5 -out cmv_vs_full_nt.txt\n\n#Creates count table of BLAST hits to \"Human hepesvirus 5\" from the BLAST results.\npython blast_hits.py cmv_masked_blastn_out.txt 'Human herpesvirus 5'\n\n#creates all_sample_data.csv- A table of sample name, FPM, FPKM, read counts, and classification (strong vs intermediate positive based on the FPM cutoff of .3)\n#file paths inside the script require editing based on how the above commands were run\nrscript --vanilla fpm_calculate.R\n\n#figure 1B\nrscript --vanilla figure_1b.r\n\n#run the first script to create a frequency table of insert sizes \nsamtools view -@ 40 <deduplicated_121r04_resequenced.bam> | awk '{print $9}' | sort | uniq -c > duplicates_removed_read_lengths.txt\n\n#for the scripts below file paths will have to be changed from the ones used on our local machine\n#figure 3\nrscript --vanilla figure_3.r\n\n#figure 4 individual scripts\nrscript --vanilla figure_4A.r\nrscript --vanilla figure_4B.r\nrscript --vanilla figure_4C.r\n\n#figure 4 panel\nrscript --vanilla figure_4.r" }, { "alpha_fraction": 0.6082621216773987, "alphanum_fraction": 0.7060778737068176, "avg_line_length": 40.97999954223633, "blob_id": "aa9e3471d1dddd60605c590b3dbb1e410d8aad16", "content_id": "b88393735635bbd13953fac2c9e271fe17027679", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 118, "num_lines": 50, "path": "/reproducibility/cmv_simulation/CMV_fragment_qPCR_simulation_violin_plot.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(grid)\nlibrary(nplr)\nlibrary(scales)\nlibrary(gridExtra)\nlibrary(RColorBrewer)\nlibrary(cowplot)\nlibrary(tidyverse)\nlibrary(ggpubr)\n\nsetwd(\"~/Documents/Manuscripts/CMV_cfDNA/newversion/simulation/\")\nSamplefrag <- read.csv(\"Sample_frag.csv\",stringsAsFactors=F)\nMultifrag <- read.csv(\"Multi_frag.csv\",stringsAsFactors=F)\n\nplayfrag <- gather(Samplefrag,\"X50\",\"X100\",\"X150\",\"X200\",\"X250\",\"X300\",\"X350\",key=\"amplicon\",value=\"counts\")\nplayfrag[playfrag==\"X50\"] <- 50\nplayfrag[playfrag==\"X100\"] <- 100\nplayfrag[playfrag==\"X150\"] <- 150\nplayfrag[playfrag==\"X200\"] <- 200\nplayfrag[playfrag==\"X250\"] <- 250\nplayfrag[playfrag==\"X300\"] <- 300\nplayfrag[playfrag==\"X350\"] <- 350\n\nplayfragMulti <- gather(Multifrag,\"X50\",\"X100\",\"X150\",\"X200\",\"X250\",\"X300\",\"X350\",key=\"amplicon\",value=\"counts\")\nplayfragMulti[playfragMulti==\"X50\"] <- 50\nplayfragMulti[playfragMulti==\"X100\"] <- 100\nplayfragMulti[playfragMulti==\"X150\"] <- 150\nplayfragMulti[playfragMulti==\"X200\"] <- 200\nplayfragMulti[playfragMulti==\"X250\"] <- 250\nplayfragMulti[playfragMulti==\"X300\"] <- 300\nplayfragMulti[playfragMulti==\"X350\"] <- 350\n\nplayfrag$amplicon <- as.factor(playfrag$amplicon)\nplayfrag$amplicon <- factor(playfrag$amplicon, levels = c(50,100,150,200,250,300,350))\nplayfragMulti$amplicon <- factor(playfragMulti$amplicon, levels = c(50,100,150,200,250,300,350))\n\n\nSample_plot <- ggplot(playfrag, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark blue\") + \n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + \n scale_y_continuous(breaks=c(0,100,200,300,400,500),limits=c(0, 560))\n\nMulti_plot <- ggplot(playfragMulti, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark green\") + \n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + \n scale_y_continuous(breaks=c(0,100,200,300,400,500),limits=c(0, 560)) \n\nfigure <- ggarrange(Sample_plot, Multi_plot,\n labels = c(\"A\", \"B\"),\n ncol = 2, nrow = 1)\nfigure\nggsave(\"Figure_violinplot.pdf\",plot=figure,width=6.2,height=3) \n\n\n" }, { "alpha_fraction": 0.7044278383255005, "alphanum_fraction": 0.7297297120094299, "avg_line_length": 35.16666793823242, "blob_id": "1f826aacee125936891b83edff35293bf403f7fe", "content_id": "54824b7821174defc07916062fbf021898ed75f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1739, "license_type": "no_license", "max_line_length": 173, "num_lines": 48, "path": "/scratch/HHV6/contamination_check.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(svMisc)\nlibrary(seqinr)\nlibrary(Rsamtools)\nlibrary(ggplot2)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download')\n\nblast_positive<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/blast_positive_sequence_info.csv')\nall_samples<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/all_sample_data.csv')\n\nblast_positive$sample<-NA\nfor(i in 1:nrow(blast_positive)){ \n progress(i) \n blast_positive$sample[i]<-strsplit(as.character(blast_positive$nameslist[i]),'[.]')[[1]][1]\n}\n\n\nblast_positive$nameslist<-as.character(blast_positive$nameslist)\nfor(i in 1:nrow(blast_positive)){ \n #print(as.character(strsplit(as.character(intermediates_with_sequences$nameslist[i]),'-')[[1]][2]))\n blast_positive$nameslist[i]<-as.character(strsplit(as.character(blast_positive$nameslist[i]),'-')[[1]][2])\n}\n\n#filling in insert sizes\nblast_positive$pos<-NA\nfor(i in 1:nrow(blast_positive)){ \n #progress(i,nrow(intermediates_with_sequences))\n tempbamname<-paste0('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/original_bams_deduplicated/',blast_positive$sample[i],'.sam.bam.sorted.bam_dedup.bam')\n tempbam<-scanBam(tempbamname)\n read<-which(grepl(blast_positive$nameslist[i], tempbam[[1]]$qname))\n temp_pos<-((tempbam[[1]]$pos[read]))\n if( any(is.na(temp_pos))) {\n temp_pos<-0\n }\n temp_pos<-abs(temp_pos[1])\n print(temp_pos)\n blast_positive$pos[i]<-temp_pos\n}\nblast_positive<-blast_positive[complete.cases(blast_positive$pos),]\n\nsorted_blast_positive<-blast_positive[order(blast_positive$seqslist),]\n\n\nfor(i in 1:nrow(sorted_blast_positive)){ \n if(i +1 < nrow(blast_positive) & blast_positive$seqslist[i]==blast_positive$seqslist[i+1]){ \n print(i)\n }\n }\n\n\n\n" }, { "alpha_fraction": 0.658893883228302, "alphanum_fraction": 0.695067286491394, "avg_line_length": 28.94925308227539, "blob_id": "dd34283945aed3e070940ba8dfafc3d7ec9a0a12", "content_id": "930a85f13669fc41e709035225a8b18e0ee807a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 10035, "license_type": "no_license", "max_line_length": 202, "num_lines": 335, "path": "/scratch/figure_3_deduplicated.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating')\n#read_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nfilenames = '/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/aligned_to_hg38/duplicates_removed_read_lengths.txt'\nplotslist<-c()\n\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(filenames)){ \n print(i)\n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'Human'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nhuman_frequencies <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nread_counts$sample<-as.character(read_counts$sample)\n\nhuman_frequencies$percent<-(100 * human_frequencies$freq) / (sum(human_frequencies$freq))\n\n#human median calculation\nhuman_isize_expanded<-rep(human_frequencies$isize, human_frequencies$freq) \nhuman_isize_expanded_below250<-human_isize_expanded[human_isize_expanded < 500]\nhuman_median<-median(as.numeric(as.character(human_isize_expanded_below250)))\n\n\nhuman_frequencies$isize<-as.numeric(as.character(human_frequencies$isize))\nx<-human_frequencies[order(human_frequencies$isize),]\n\nx<-x[x$isize < 500 ,]\n\ncount = 1 \nsum = 0 \nx$percent<- (100 * x$freq)/ sum(x$freq)\nwhile( sum < 50) { \n print(sum)\n print(x$isize[count])\n sum = sum + x$percent[count]\n count = count + 1 \n }\n\n\nhuman_plot<-ggplot(human_frequencies, aes( x = human_frequencies$isize , y = human_frequencies$percent)) + \n geom_vline(xintercept = human_median) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\nggsave(plot = human_plot, 'Resequenced_human_fragment_length.pdf')\n\n\n\n\n\n#reading in CMV BAM\n\n#CMV_blast_hits<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/figure_2_final/resequenced_combined_blast_out.txt_blast_hits.csv', header = FALSE, col.names = c('full_ID','count','sample'))\n#CMV_blast_hits$full_ID<-as.character(CMV_blast_hits$full_ID)\n#CMV_blast_hits<-CMV_blast_hits[CMV_blast_hits$count>75,]\n\nrepeatmasked_fasta<-read.fasta('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/resequenced_repeatmasked_7_removed.fasta')\nfasta_IDs<-names(repeatmasked_fasta)\n\nfasta_IDs_trimmed<-c()\nfor( i in 1:length(fasta_IDs)){\n progress(i,length(fasta_IDs))\n fasta_IDs_trimmed<-append(fasta_IDs_trimmed,strsplit(fasta_IDs, '/')[[i]][1])\n} \nfasta_IDs_deduplicated<-fasta_IDs_trimmed[-(which(duplicated(fasta_IDs_trimmed)))]\n\n#CMV_blast_hits_deduplicated<-CMV_blast_hits[-(which(duplicated(CMV_blast_hits$read_ID))),]\n\n\nisize<-c()\nread_id<-c()\nsample<-c()\n\ntemp_bam<-scanBam('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/cmv_duplicates_removed.bam')\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:length(fasta_IDs_deduplicated)){ \n print(100 * j / length(fasta_IDs_deduplicated))\n for(k in 1:length(all_bam_read_IDs)){\n if(grepl( fasta_IDs_deduplicated[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, 'CMV')\n }\n }\n }\n\nCMV_matched<-data.frame(sample, read_id, isize)\nCMV_matched<-CMV_matched[CMV_matched$isize>0,]\nCMV_matched<-CMV_matched[CMV_matched$isize<500,]\n\nCMV_matched<-CMV_matched[complete.cases(CMV_matched$isize),]\n\nCMV_frequencies<-data.frame(table(CMV_matched$isize))\ncolnames(CMV_frequencies)<-(c('isize','freq'))\nCMV_frequencies$percent<- 100 * ( as.numeric(as.character(CMV_frequencies$freq)) / (sum(CMV_frequencies$freq))) \nCMV_frequencies$type<-'CMV'\n\n#calculating CMV median\nCMV_isize_exanded<-rep(CMV_frequencies$isize, CMV_frequencies$freq) \nCMV_isize_exanded<-CMV_isize_exanded[as.numeric(as.character(CMV_isize_exanded)) < 500]\nCMV_median<-median(as.numeric(as.character(CMV_isize_exanded)))\n\n\n\nCMV_plot<-ggplot(CMV_frequencies, aes( x = as.numeric(as.character(CMV_frequencies$isize)) , y = CMV_frequencies$percent)) + \n geom_vline(xintercept = 143, color = 'blue') + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nCMV_plot\nggsave(plot = CMV_plot, 'cmv_duplicates_removed_fragment_length.pdf')\nwrite.csv(CMV_matched, 'cmv_duplicates_removed_read_data.csv')\nwrite.csv(CMV_frequencies,'cmv_duplicates_removed_insert_sizes.csv')\n#combining human and CMV graphs \n\ncombined<-rbind(human_frequencies,CMV_frequencies)\n\n#red: ED6464\n#blue: 05188B\n\ncombined_plot <- ggplot(combined, aes ( x = as.numeric(as.character(combined$isize)), y = as.numeric(as.character(combined$percent)), color = combined$type)) + \n theme_classic() + \n theme(legend.position = \"none\") + \n #theme_classic() + \n xlim(c(0,500)) +\n ylim(c(0,2.5)) +\n scale_color_manual(values=c(\"#ED6464\", \"#05188B\")) +\n #geom_vline(xintercept = 168) + \n #geom_vline(xintercept = 125) + \n xlab('Insert size') + \n ylab('Percent within each alignment') + \n geom_line(size = .75) \ncombined_plot\nggsave(plot = combined_plot, 'deduplicated_figure_3a_500bp_1026.pdf', height = 3, width = 3 )\n\n\n\n\n\n\n#p-value calculations \nCMV_isize_exanded<-as.numeric(as.character(CMV_isize_exanded))\nhuman_isize_expanded<-as.numeric(as.character(human_isize_expanded))\n\n\n#two sided t test on insert sizes \nt.test(human_isize_expanded,CMV_isize_exanded, alternative = \"two.sided\")\n\n#running t tests 10000 iterations \ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n ttest<-(t.test(temp,CMV_isize_exanded, paired = TRUE))\n tests<-append(tests,ttest$p.value)\n}\n\ntestsdf<-data.frame(tests)\n\n#plot of p values\nttest_graph<-ggplot(testsdf, aes(x = testsdf$tests)) + \n geom_freqpoly(bins = 1000) +\n # xlim(c(0,summary(testsdf$tests)[5]))+\n #geom_vline(xintercept = 0, color = 'blue') + \n #geom_hline(yintercept = 0, color = 'blue') + \n# ylim(0,2000) + \n #xlim(0,8.5e-49) + \n xlab('p-value') + \n ylab('frequency (100000 iterations)') + \n theme_classic() + \n theme(axis.text.x = element_text(angle = 90, hjust = 1)) \n# ylim(c(0,8))\nttest_graph\nggsave(plot =ttest_graph, 'insert_size_p-value_distribution.pdf')\n\n#library('dyplr')\n#boxplot(tests)\n\n#CMV is in 14th percentile of human insert size distribution\nhuman_percentile<-ecdf(human_isize_expanded)\ncmv_med_percentile<-human_percentile(median(CMV_isize_exanded)) * 100\n\n#fligner-killeen test for homogeneity of variances between samples\ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n fktest<-(fligner.test(temp,CMV_isize_exanded, paired = TRUE))\n tests<-append(tests,fktest$p.value)\n}\n\nfk_df<-data.frame(tests)\n\nfktest_graph<-ggplot(fk_df, aes(x = fk_df$tests)) + \n geom_freqpoly(bins = 1000) +\n xlim(c(0,summary(fk_df$tests)[5]))+\n #geom_vline(xintercept = 0) + \n #geom_hline(yintercept = 0) + \n ylim(0,2000) + \n xlab('p-value') + \n ylab('frequency (100000 iterations)') + \n theme_classic() \n #theme(axisw.text.x = element_text(angle = 90, hjust = 1)) \n# ylim(c(0,8))\n fktest_graph \nggsave(plot =fktest_graph, 'insert_size_variance_distribution.pdf')\n\n\n#Kolmogorov-Smirnov test\n\ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n kstest<-(ks.test(temp,CMV_isize_exanded))\n tests<-append(tests,kstest$p.value)\n}\n\nks_df<-data.frame(tests)\n\nmedian(ks_df$tests)\n\nkstest_graph<-ggplot(ks_df, aes(x = ks_df$tests)) + \n geom_freqpoly(bins = 1000) +\n xlim(c(0,summary(ks_df$tests)[5]))+\n #geom_vline(xintercept = 0) + \n #geom_hline(yintercept = 0) + \n ylim(0,2000) + \n xlab('p-value') + \n ylab('frequency (100000 iterations)') + \n theme_classic() \n#theme(axisw.text.x = element_text(angle = 90, hjust = 1)) \n# ylim(c(0,8))\nkstest_graph \nggsave(plot =fktest_graph, 'insert_size_variance_distribution.pdf')\n\n\nplot(ecdf(CMV_isize_exanded))\nplot(ecdf(human_isize_expanded))\n\n\n\n\nCMV_cdf <- ecdf(CMV_isize_exanded)\nhuman_cdf <- ecdf(human_isize_expanded)\n\nCMV_cdf\nks<-ks.test(CMV_isize_exanded,human_isize_expanded)\n\nhuman_isize_df<-data.frame(human_isize_expanded)\ncmv_isize_df<-data.frame(CMV_isize_exanded)\n\nplot(ecdf(CMV_isize_exanded)) \n\nplot(ecdf(human_isize_expanded),add = TRUE, col = 2 )\n\n\nhuman_cdf_df<-data.frame()\n\nhuman_subsampled<-data.frame(sample(human_isize_expanded, length(CMV_isize_exanded)))\ncolnames(human_subsampled)[1]<-'isizes'\nhuman_subsampled$type = 'human'\n\ncmv_isize_df$type = 'cmv'\ncolnames(cmv_isize_df)[1]<-'isizes'\n\nsubsampled_df<-rbind(human_subsampled, cmv_isize_df)\n\n\n\ncum_frequency<-ggplot(subsampled_df, aes(x = subsampled_df$isizes, color = subsampled_df$type)) + \n theme_classic() + \n scale_color_manual(values=c(\"#ED6464\", \"#05188B\")) +\n theme(legend.position='none') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') + \n<<<<<<< HEAD\n<<<<<<< HEAD\n stat_ecdf(geom = 'step', size =.75 ) + \n=======\n stat_ecdf(geom = 'step', size =1 ) + \n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n=======\n stat_ecdf(geom = 'step', size =1 ) + \n>>>>>>> fc8ed0222b2c2448d148e1835a033131476adb6a\n xlim(c(0,500))\ncum_frequency\nggsave(plot = cum_frequency, 'cmv_deduplicated_cum_frequency_1026.pdf',width = 3, height = 3 )\n\n\nshapiro.test(subsampled_df$isizes[subsampled_df$type=='human'])\n\n\n#combined plot #cum_frequency\n#red: ED6464\n#blue: 05188B\nplot_grid(combined_plot, cum_frequency, labels = c('A','B'))\nggsave(plot = last_plot(), height = 3, width = 6, filename = 'figure_3_grid.pdf')\n\n\n" }, { "alpha_fraction": 0.7016431093215942, "alphanum_fraction": 0.7289933562278748, "avg_line_length": 33.32143020629883, "blob_id": "ad749506f6898bbfa9ed9d631104e10568310657", "content_id": "c3dd4b25dfc60f348b6c5460e733a78ebecb54d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 9616, "license_type": "no_license", "max_line_length": 146, "num_lines": 280, "path": "/reproducibility/CMV/maternal/current_version/fpm_calculate.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(seqinr)\nlibrary(svMisc)\nlibrary(Biostrings)\nlibrary(svMisc)\nlibrary(ggplot2)\nlibrary(xlsx)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/fragment_patch')\n\n#Provide the blast hit count table here \nblasthitsfile<-read.csv('/Users/gerbix/Documents/vikas/NIPT/all_deduplicated/blast_hits.csv')\n\n#provide the repeatmaskedmasked fasta here\nfastafile<-readDNAStringSet('/Users/gerbix/Documents/vikas/NIPT/all_deduplicated/original_bams_deduplicated/cmv_combined_masked.fasta')\ncolnames(blasthitsfile)[1]<-'readname'\ncolnames(blasthitsfile)[2]<-'count'\n\n#provide a csv of all read counts in the original FASTQ files here (column1=name, column2=read_count)\nread_counts_all<-read.csv2('/Users/gerbix/Documents/vikas/NIPT/31119_download/read_counts_all_deduplicated.csv', sep = ',')\n\n#Creating a lookup table for later on \nread_counts_all$sample<-as.character(read_counts_all$sample)\nfor(i in 1:length(read_counts_all$sample)){ \n read_counts_all$sample[i]<-strsplit(read_counts_all$sample[i],'[.]')[[1]][1]\n}\n\nblasthitsfile$readname<-as.character(blasthitsfile$readname)\nblasthitsfile$unique_identifier<-NA\nblasthitsfile$full_readname<-blasthitsfile$readname\nblasthitsfile$sample_id<-NA\nfor(i in 1:nrow(blasthitsfile)){\n blasthitsfile$unique_identifier[i]<-strsplit(blasthitsfile$readname[i],'[-]')[[1]][2]\n blasthitsfile$readname[i]<-strsplit(blasthitsfile$readname[i],'[-]')[[1]][1]\n }\nfor(i in 1:nrow(blasthitsfile)){\n blasthitsfile$sample_id[i]<-strsplit(blasthitsfile$readname[i],'[.]')[[1]][1]\n }\nblasthitsfile$fragments<-1\n# fragment_indexes<-which(duplicated(blasthitsfile$unique_identifier))\n# for(i in 1:length(fragment_indexes)){ \n# blasthitsfile$fragments[fragment_indexes[i]]<-0\n# }\n# \n\n\n\n#blank list for file in blast that have > 5 reads\npositivefiles <- c() \nblasthitsfile$blast_pass<-FALSE\nfor( i in 1:nrow(blasthitsfile)){ \n if(blasthitsfile$count[i] > 5) { \n #print(blasthitsfile$readname[i])\n positivefiles<-append(positivefiles, as.character(blasthitsfile$full_readname[i]))\n blasthitsfile$blast_pass[i]<-TRUE\n }\n}\n\n#makes csv of all blast verified reads\nnameslist<-c()\nlengthslist<- c()\nseqslist<-c()\n\n\nfor(i in 1:length(positivefiles)){ \n progress(i, length(positivefiles))\n index=which(positivefiles[i]==names(fastafile))\n lengthslist = append(lengthslist, nchar(paste(fastafile[index])))\n nameslist<-append(nameslist,names(fastafile[index]))\n seqslist<-append(seqslist,paste(fastafile[index]))\n }\nseqdata<-data.frame(nameslist,seqslist,lengthslist)\nwrite.csv(seqdata,'blast_positive_sequence_info.csv')\n\n\npositivestrimmed <- c()\nfor (word in positivefiles) { \n word <- strsplit(word, '.sam')[[1]][1]\n positivestrimmed <- append(positivestrimmed, word )\n}\nunique_positivestrimmed<-unique(positivestrimmed)\n\nuniquefiles = c()\npositvereads= c()\nintermediatepositives = c()\nintermediatepositives_reads = c()\npositives<-c()\npositivereads<-c()\nweak_positives<-c()\nweak_positives_reads<-c()\n\n\n\nx<-blasthitsfile\nblasthitsfile<-x\n\n#convert reads to fragments based on unique identifiers in the blast file\n#blasthitsfile<-blasthitsfile[which(!(duplicated(blasthitsfile$unique_identifier))),]\n\n#23502:18556:14889\n#:22401:26501:2671\n# \n# to_remove<-c()\n# duplicated<-which(duplicated(blasthitsfile$unique_identifier))\n# for(i in 1:length(duplicated)){ \n# duplicates<-which(blasthitsfile$unique_identifier == blasthitsfile$unique_identifier[duplicated[i]])\n# first = duplicates[1]\n# second = duplicates[2]\n# #print(length(duplicates))\n# #print(length(duplicates))\n# #print(duplicates)\n# if( length( duplicates == 2)){\n# #print(i)\n# }\n# if(blasthitsfile$count[first] >= blasthitsfile$count[second]){ \n# to_remove<-append(to_remove, second)\n# }\n# else{ \n# to_remove<-append(to_remove,first)\n# \n# }\n# }\n# \n# blasthitsfile<-blasthitsfile[-to_remove,]\n\nfor(i in 1:nrow(blasthitsfile)){ \n if(blasthitsfile$blast_pass[i]==FALSE){ \n temp_id<-blasthitsfile$unique_identifier[i]\n if(temp_id %in% blasthitsfile$unique_identifier[which(duplicated(blasthitsfile$unique_identifier))]){ \n temp_indexes<-which(blasthitsfile$unique_identifier==temp_id)\n first<-temp_indexes[1]\n second<-temp_indexes[2]\n if(blasthitsfile$blast_pass[first] == TRUE | blasthitsfile$blast_pass[second]== TRUE){ \n blasthitsfile$blast_pass[first] <-TRUE\n blasthitsfile$blast_pass[second] <-TRUE\n }\n }\n \n }\n }\n#tf 13112:10034:9920 , 13610:3061:1660\n#ff 21401:15559:5891 , 21509:19330:6011\n\n\nblasthitsfile<-blasthitsfile[which(!(duplicated(blasthitsfile$unique_identifier))),]\nblasthitsfile<-blasthitsfile[-c(which(blasthitsfile$sample_id=='121R27_C04_CFFv1_NA0147')),]\n\n\n\n\n\n#matches read IDs back to their original SAM files \nunique_file_list<-unique(blasthitsfile$sample_id)\nfor (i in 1:length(unique_file_list)) { \n print(100*i/length(unique_file_list))\n count = 0\n identifier = unique_file_list[i]\n for ( j in 1:length(blasthitsfile$sample_id)) { \n if(blasthitsfile$sample_id[j] == unique_file_list[i] && blasthitsfile$blast_pass[j]==TRUE) { \n count = count + blasthitsfile$fragments[j]\n tempidentifier<-blasthitsfile$sample_id[j]\n }\n }\n if( count > 2) { \n uniquefiles = append(uniquefiles,tempidentifier)\n }\n if(count < 15 && count >1) { \n intermediatepositives = append(intermediatepositives , tempidentifier)\n intermediatepositives_reads = append(intermediatepositives_reads , count)\n }\n if(count > 15) { \n positives = append(positives , tempidentifier)\n positivereads = append(positivereads , count)\n }\n if(count==1){ \n weak_positives = append(weak_positives, tempidentifier)\n weak_positives_reads= append(weak_positives_reads, count)\n }\n}\n\n\n\n\n\n\n#fpkm and fpm calculation for weak positives (1 read)\nweakpositivesdf<-data.frame(weak_positives,weak_positives_reads)\nweakpositivesdf <- weakpositivesdf[!duplicated(weakpositivesdf$weak_positives), ]\nweakpositivesdf$fpkm<-NA\nweakpositivesdf$read_counts<-NA\nweakpositivesdf$fpm<-NA\nfor(i in 1:nrow(weakpositivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if(read_counts_all$sample[j]==as.character(weakpositivesdf$weak_positives[i])){ \n weakpositivesdf$fpkm[i]<-(weakpositivesdf$weak_positives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1000000))\n print((weakpositivesdf$weak_positives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n weakpositivesdf$read_counts[i]<-read_counts_all$count[j]\n weakpositivesdf$fpm[i]<-((weakpositivesdf$weak_positives_reads[i])*1e6)/(read_counts_all$count[j])\n\n }\n }\n}\n\n#fpkm and fpm calculation for intermediate positives (between 2-15 reads)\nintermediatepositivesdf <- data.frame(intermediatepositives, intermediatepositives_reads)\nintermediatepositivesdf <- intermediatepositivesdf[!duplicated(intermediatepositivesdf$intermediatepositives), ]\nintermediatepositivesdf$fpkm<-NA\nintermediatepositivesdf$read_counts<-NA\nintermediatepositivesdf$fpm<-NA\nread_counts_all$sample<-as.character(read_counts_all$sample)\nfor(i in 1:nrow(intermediatepositivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if(read_counts_all$sample[j]==as.character(intermediatepositivesdf$intermediatepositives[i])){ \n intermediatepositivesdf$fpkm[i]<-(intermediatepositivesdf$intermediatepositives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1000000))\n print((intermediatepositivesdf$intermediatepositives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n intermediatepositivesdf$read_counts[i]<-read_counts_all$count[j]\n intermediatepositivesdf$fpm[i]<-((intermediatepositivesdf$intermediatepositives_reads[i])*1e6)/(read_counts_all$count[j])\n \n }\n }\n}\n\n\n\n\n#fpkm and fpm calculation for strong positives (over 15 reads)\npositivesdf<-data.frame(positives,positivereads)\npositivesdf <- positivesdf[!duplicated(positivesdf$positives), ]\npositivesdf$fpkm<-NA\npositivesdf$read_counts<-NA\npositivesdf$fpm<-NA\nfor(i in 1:nrow(positivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if((strsplit(read_counts_all$sample[j],'[.]')[[1]][1])==as.character(positivesdf$positives[i])){ \n positivesdf$fpkm[i]<-((positivesdf$positivereads[i])/((235646/1000)*(read_counts_all$count[j]/1000000)))\n print((positivesdf$positivereads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n positivesdf$read_counts[i]<-read_counts_all$count[j]\n positivesdf$fpm[i]<-((positivesdf$positivereads[i])*1e6)/(read_counts_all$count[j])\n }\n }\n}\n\nactuallyunique <- unique(uniquefiles)\ncmv_all_positives_table<-rbind(positivesdf,intermediatepositivesdf,weakpositivesdf)\n\n\n\n\n\n#graph to find a nice arbitrary fpkm cutoff\npositivesdf$classification<-'strong positives'\nintermediatepositivesdf$classification<-'intermediate positives'\nweakpositivesdf$classification<-'weak positives'\n\ngraph_weakdf<-weakpositivesdf\ncolnames(graph_weakdf)[1]<-'sample'\ncolnames(graph_weakdf)[2]<-'count'\n\ngraph_positivesdf<-positivesdf\ncolnames(graph_positivesdf)[1]<-'sample'\ncolnames(graph_positivesdf)[2]<-'count'\n\ngraph_intermediatesdf<-intermediatepositivesdf\ncolnames(graph_intermediatesdf)[1]<-'sample'\ncolnames(graph_intermediatesdf)[2]<-'count'\n\n\ndf_for_graph<-rbind(graph_positivesdf,graph_intermediatesdf,graph_weakdf)\n\n\nfor(i in 1:nrow(df_for_graph)){ \n if(df_for_graph$fpm[i] > .3){ \n df_for_graph$classification[i]<-'strong positive'\n }\n if(df_for_graph$fpm[i] < .3){ \n df_for_graph$classification[i]<-'intermediate positive'\n }\n }\n\nwrite.csv(df_for_graph,'all_sample_data.csv')\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6673948764801025, "alphanum_fraction": 0.6925177574157715, "avg_line_length": 33.433963775634766, "blob_id": "4e4099c23355808b47885490654e11238defe1ac", "content_id": "cead6ff94c139cb72fb445d89a5305fea7f8eaa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1831, "license_type": "no_license", "max_line_length": 121, "num_lines": 53, "path": "/reproducibility/HHV-6/makefastasfromsams.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "# Arg 1 is the path to the folder containing the deduplicated BAMs\nargs = commandArgs(trailingOnly=TRUE)\n\nlibrary(Rsamtools)\nlibrary(seqinr)\nlibrary(svMisc)\n\nfilenames <- list.files(args[1], pattern ='.bam$')\nsetwd(args[1])\nsequence= c()\nidentifier= c()\nheader=c()\nfor (i in 1:length(filenames)){ \n lengthfilenames= length(filenames)\n tempbam=scanBam(filenames[i])\n if(length(tempbam[[1]]$seq)>0){\n for(j in 1:length(tempbam[[1]]$seq)){ \n sequence = append(sequence,as.character(tempbam[[1]]$seq[j]))\n tempfilename = paste0(filenames[i],'.',j)\n header=append(header, as.character(tempbam[[1]]$qname[j]))\n identifier = append(identifier,tempfilename)\n }\n }\n }\nfastadf <- data.frame(identifier, sequence, header)\nfastadf$header<-as.character(fastadf$header)\nfastadf$identifier<-as.character(fastadf$identifier)\n\n\n# repeatmasker limits header names to 50 characters so this deletes the non-unique regions of the header\nfor(i in 1:nrow(fastadf)){\n progress(i, nrow(fastadf))\n if(grepl('NB502000', fastadf$header[i])) {\n fastadf$header[i]<-gsub(pattern = 'NB502000', replacement = '', fastadf$header[i])\n }\n if(grepl('NS500359', fastadf$header[i])) {\n fastadf$header[i]<-gsub(pattern = 'NS500359', replacement = '', fastadf$header[i])\n }\n fastadf$identifier[i]<-gsub('.sam.bam.sorted.deduplicated.bam','',fastadf$identifier[i])\n fastadf$header[i]<-substr(fastadf$header[i], 17, stop = nchar(fastadf$header[i]))\n}\n\n# writes fastas\nx<-c()\nprint('making fastas')\nfor ( i in 1:nrow(fastadf)){\n lengthvar=nrow(fastadf)\n tempfilename = paste0(fastadf$identifier[i],'.fasta')\n write.fasta(sequences= fastadf$sequence[i], names = paste0(tempfilename,'-',fastadf$header[i]), file.out= tempfilename)\n if(nchar(paste0(tempfilename,'-',fastadf$header[i]))>50){ \n x<-append(x,i)\n }\n } \n\n\n\n\n\n" }, { "alpha_fraction": 0.658349335193634, "alphanum_fraction": 0.6880998015403748, "avg_line_length": 40.63999938964844, "blob_id": "a05cb4a5ab0f4e51ee6aa2e9e077ed4f4e85e379", "content_id": "ac541260224e6d5c9eb042954e75d80ea4c2d966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 1042, "license_type": "no_license", "max_line_length": 141, "num_lines": 25, "path": "/reproducibility/CMV/maternal/previous_version/figure_1b.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(xlsx)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal')\n\nint_breaks <- function(x, n = 5) pretty(x, n)[pretty(x, n) %% 1 == 0] \n\n#Modify for your own all_sample_data.csv \ndf_for_graph<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/fragment_patch/all_sample_data_og.csv')\nfigure_1b_plot_fpm<-ggplot(df_for_graph, aes(x=fpm, fill = classification)) + \n geom_histogram(bins = 45, color = 'black') + \n scale_x_log10() + \n theme_classic() +\n scale_fill_manual(labels = c( \"FPM < 0.3\", \"FPM > 0.3\"),values = c('#BEBADA',\"#E27184\")) +\n theme(legend.title=element_blank())+ \n theme(legend.position = c(0.8, 0.8))+\n xlab('FPM') + \n ylab('Number of samples') + \n theme(text = element_text(size=10))+ \n scale_y_continuous(expand = c(0,0), breaks = int_breaks)\nfigure_1b_plot_fpm\nggsave(plot=figure_1b_plot_fpm, filename = 'figure_1b.pdf', height= 4, width = 4, useDingbats=FALSE)\n\n" }, { "alpha_fraction": 0.6390302181243896, "alphanum_fraction": 0.6655040383338928, "avg_line_length": 30.903284072875977, "blob_id": "63aa9a5486441bd85369e3af760f0ffc0cedadd1", "content_id": "2a95f7df5664641d2db83eb2bd6fbe2c44266f4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 17489, "license_type": "no_license", "max_line_length": 179, "num_lines": 548, "path": "/scratch/HHV6/hhv6a_bam_fragment_histograms.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#for icihhv6 in cfdna insert sizes\n\nlibrary(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\n\nsetwd('/Volumes/Seagate8Tb1/nipt/bams/bams_for_vikas/')\nread_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nfilenames = list.files(pattern = '*.bam.results.txt$')\nplotslist<-c()\n\nsavePlot <- function(myPlot, plotname) {\n pdf(plotname, width = 8.5, height = 11)\n print(myPlot)\n dev.off()\n}\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(filenames)){ \n print(i)\n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'length'\n colnames(histo)[1]<-'occurences'\n histo$type<-strsplit(filenames[i],\".sam\")[[1]][1]\n histo<-histo[histo$length>0,]\n if(nrow(histo)>0){\n # for(j in 1:length(histo$occurences)){ \n # for(k in 1:histo$occurences[j]){ \n # #print(histo$length[i])\n # statslist<-append(statslist, histo$length[j]) \n # }\n # }\n # statslistremove<-which(statslist>900)\n # if(length(statslistremove)>0){ \n # statslist<-statslist[-statslistremove]\n # }\n toremove<-which(histo[,2]> 900)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$length)\n totaloccurences =append(totaloccurences,histo$occurences)\n # plot<-ggplot(histo, aes(y=histo$occurences, x=histo$length)) + \n # geom_point() + \n # geom_vline(xintercept = median(statslist)) +\n # ylab('occurences')+\n # xlab('length') +\n # annotate(\"text\", x = 400, y = max(histo$occurences)-5, label = paste0('mean=', mean(statslist))) + \n # annotate(\"text\", x = 400, y = max(histo$occurences)-6, label = paste0('median=', median(statslist)))\n # \n # print(plot)\n # #print(mean(statslist))\n # plotname = paste0(filenames[i],'.plot.pdf')\n # print(filenames[1])\n # print(i)\n # #ggsave(filename=plotname, device = pdf)\n # savePlot(plot, plotname)\n dflist[[i]]<-histo\n }\n }\n}\n\n########revised 3/04/19#################\ncombineddf <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nread_counts$sample<-as.character(read_counts$sample)\n#combineddf<-combineddf[combineddf$length>74,]\nplot<-ggplot(combineddf, aes( x=combineddf$length, y = combineddf$occurences, color = combineddf$type)) + \n geom_point() + \n #geom_histogram(binwidth = 5) + \n # geom_histogram(binwidth = 5) +\n #geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\") \n #annotate(\"text\", x = 400, y = max(histo$occurences)-5, label = paste0('mean=', mean(combineddf$length))) + \n #annotate(\"text\", x = 400, y = max(histo$occurences)-7, label = paste0('median=', median(combineddf$length)))\nplot\nggsave('30219_revised_mean_median_human_bam_fragments.pdf', plot = last_plot())\n\n#calculating mean human read length\ntemp_sum<-0\nfor(i in 1:nrow(combineddf)){ \n temp_sum = temp_sum + (combineddf$occurences[i] * combineddf$length[i])\n }\nmean_human_read_length <- temp_sum / (sum(combineddf$occurences))\n\n\n##############end revision##############\n\n#calculating mean and median for human fragments\ncombineddf$totals<-NA\nfor(i in 1:nrow(combineddf)){ \n combineddf$totals[i]<-combineddf$occurences[i]*combineddf$length[i]\n }\nmean(combineddf$totals)\n\nplot<-ggplot(combineddf, aes(y=combineddf$occurences, x=combineddf$length)) + \n geom_point(aes(color = combineddf$type), size = .5) + \n geom_vline(xintercept = mean(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n #labs(colour=\"file\") + \n theme_classic() + \n theme(legend.position = 'none')\n #theme(legend.position=\"bottom\")\nplot\nggsave('occurences_all_bams_average_length.pdf',plot, ,height = 3, width = 3, useDingbats = FALSE)\n\nsavePlot(plot, 'all_bams_average_length.pdf')\n\n\ncombineddf$denominator_adjusted<-NA \n\n\nfor (i in 1:length(read_counts$sample)){ \n for( j in 1:length(combineddf$type)) { \n temp<-strsplit(as.character(read_counts$sample[i]), split = 'final') [[1]][1]\n if( temp == combineddf$type[j]) { \n combineddf$denominator_adjusted[j]= combineddf$occurences[j] / read_counts$count[i] \n }\n }\n }\n\n\n\n\ndenominator_adjusted_plot<-ggplot(combineddf, aes(y=combineddf$denominator_adjusted, x=combineddf$length)) + \n geom_point(aes(color = combineddf$type), size = 1) + \n geom_vline(xintercept = mean(combineddf$length)) +\n xlim(0,500) + \n ylab('occurrences/total read count of sample')+\n xlab('length')+\n labs(colour=\"file\") + \n theme_classic() +\n theme(legend.position=\"none\")\n\ndenominator_adjusted_plot\nggsave('denominator_adjusted_all_bams_average_length.pdf',denominator_adjusted_plot, ,height = 3, width = 3, useDingbats = FALSE)\nsavePlot(denominator_adjusted_plot, 'denominator_adjusted_all_bams_average_length.pdf')\n\n\n#for rpkm\ncombineddf$rpkm<-NA\nfor (i in 1:length(read_counts$sample)){ \n for( j in 1:length(combineddf$type)) { \n temp<-strsplit(as.character(read_counts$sample[i]), split = 'final') [[1]][1]\n if( temp == combineddf$type[j]) { \n #combineddf$rpkm[j]= (10e9*combineddf$occurences[j]) / (read_counts$count[i] * 3088286401) \n combineddf$rpkm[j] =(combineddf$occurences[j])/((3088286401/1000)*(read_counts$count[i]/1e9))\n }\n }\n}\n\nrpkm_plot<-ggplot(combineddf, aes(y=combineddf$rpkm, x=combineddf$length)) + \n geom_point(aes(color = combineddf$type), size = 1) + \n geom_vline(xintercept = mean(combineddf$length)) +\n xlim(0,500) + \n ylab('rpkm')+\n xlab('length')+\n labs(colour=\"file\") + \n theme_classic() +\n theme(legend.position=\"none\")\n\nrpkm_plot\n\n\n\n\n#############################\n#####HHV-6 positive files######\n#############################\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/host_filtered_hhv6/fastqs/paired/hhv6a/bams')\nsystem('$PWD')\nread_counts <- read.csv(\"/Users/gerbix/Documents/vikas/NIPT/31119_download/hhv6/read_counts_all.csv\")\nsystem(\"for i in *.bam ; do echo processing $i ; samtools view -@ 8 $i | awk '{print $9}' | sort | uniq -c > $i.results.txt ; done\")\nsystem('')\nfilenames = list.files(pattern = '*.bam.results.txt$')\nplotslist<-c()\n\nsavePlot <- function(myPlot, plotname) {\n pdf(plotname, width = 8.5, height = 11)\n print(myPlot)\n dev.off()\n}\n\ntotallengths<-c()\ntotaloccurences<-c()\ndflist<-c()\ntoremove<-c()\nstatslist<-c()\nstatslistremove<-c()\nfor (i in 1:length(filenames)){ \n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'length'\n colnames(histo)[1]<-'occurences'\n histo$type<-strsplit(filenames[i],\".sam\")[[1]][1]\n histo<-histo[histo$length>0,]\n if(nrow(histo)>0){\n for(j in 1:length(histo$occurences)){ \n for(k in 1:histo$occurences[j]){ \n #print(histo$length[i])\n statslist<-append(statslist, histo$length[j]) \n }\n }\n statslistremove<-which(statslist>900)\n if(length(statslistremove)>0){ \n statslist<-statslist[-statslistremove]\n }\n toremove<-which(histo[,2]> 900)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$length)\n totaloccurences =append(totaloccurences,histo$occurences)\n plot<-ggplot(histo, aes(y=histo$occurences, x=histo$length)) + \n geom_point() + \n geom_vline(xintercept = median(statslist)) +\n ylab('occurences')+\n xlab('length') +\n annotate(\"text\", x = 400, y = max(histo$occurences)-5, label = paste0('mean=', mean(statslist))) + \n annotate(\"text\", x = 400, y = max(histo$occurences)-6, label = paste0('median=', median(statslist)))\n \n print(plot)\n #print(mean(statslist))\n plotname = paste0(filenames[i],'.plot.pdf')\n print(filenames[1])\n print(i)\n #ggsave(filename=plotname, device = pdf)\n savePlot(plot, plotname)\n dflist[[i]]<-histo\n }\n }\n}\n\n\n# combined<-data.frame(totaloccurences, totallengths)\n# \n# plot<-ggplot(combined, aes(y=combined$totaloccurences, x=combined$totallengths)) + \n# geom_point() + \n# geom_vline(xintercept = mean(combined$totallengths)) +\n# xlim(0,250) + \n# ylab('occurences')+\n# xlab('length') \n\n####revised code as of 3/34/19######\ncombined <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nfor(i in 1:nrow(combined)){ \n for(j in 1:combined$occurences[i]){ \n lengthlist<-append(lengthlist,combined$length[i])\n samplelist<-append(samplelist,combined$type[i])\n }\n}\ncombineddf<-data.frame(lengthlist,samplelist)\ncolnames(combineddf)[1]<-'length'\ncolnames(combineddf)[2]<-'sample'\n#read_counts$sample<-as.character(read_counts$sample)\n#combineddf<-combineddf[combineddf$length>74,]\nplot<-ggplot(combineddf, aes( x=combineddf$length)) + \n geom_histogram(binwidth = 5) + \n # geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\") + \n annotate(\"text\", x = 400, y = 400, label = paste0('mean=', mean(combineddf$length))) + \n annotate(\"text\", x = 400, y = 300, label = paste0('median=', median(combineddf$length)))\nplot\nggsave('30219_revised_mean_median_cmv_bam_fragments.pdf', plot = last_plot())\n########end revision#########\n\n\nread_counts$sample<-as.character(read_counts$sample)\nfor (i in 1:length(read_counts$sample)) {\n print(i)\n read_counts$sample[i]=print(strsplit(as.character(read_counts$sample[i]),split='.fastq.gz')[[1]][1])\n}\n\nread_counts$percentage<-NA\nread_counts$summed<-NA\nfor(i in 1:length(read_counts$sample)){ \n tempcount<-0\n for(j in 1:nrow(combineddf)){ \n if(read_counts$sample[i]==combineddf$type[j]){ \n print('ok')\n tempcount= tempcount + combineddf$occurences[j]\n }\n }\n read_counts$percentage[i] <-100*tempcount/(read_counts$count[i])\n read_counts$summed[i]<-tempcount\n # print(read_counts$percentage[i])\n }\n\n#####\ncombineddf$denominator_adjusted<-NA \n\nfor (i in 1:length(read_counts$sample)){ \n for( j in 1:length(combineddf$type)) { \n temp<-strsplit(as.character(read_counts$sample[i]), split = 'final') [[1]][1]\n if( temp == combineddf$type[j]) { \n combineddf$denominator_adjusted[j]= combineddf$occurences[j] / read_counts$count[i] \n }\n }\n}\n\ncombineddf$percent<-0\nfor(i in 1:nrow(combineddf)){ \n print(i)\n for(j in 1:nrow(frequencies)){ \n if(combineddf$length[i] == frequencies$Var1[j]){ \n combineddf$percent[i] <- frequencies$percent[j]\n }\n }\n }\n\n\nplot<-ggplot(combineddf, aes( x=combineddf$length, y= combineddf$percent)) + \n geom_histogram(binwidth = 5, aes(fill = combineddf$sample, y=(100 * ..count../sum(..count..)))) + \n\n #geom_histogram(binwidth = 5, aes(fill=combineddf$sample)) + \n# geom_histogram(binwidth = 5) +\n #geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('percent')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\n\nplot\nggsave(plot = plot, 'hhv6_isizes_stacked.pdf', width = 8.5, height = 11)\n#ggsave('all_cmv_positives_average_length.pdf',plot, height = 3, width = 3,useDingbats = FALSE)\n\nwrite.csv(combined,'hhv_6_isizes.csv')\n\n\n\n\n\nhhv6_low_cluster<-c('98P11_C02_CFFv1_NB0120','93R20_D03_CFFv1_NA0087','97P10_B02_CFFv1_NB0119','99P03_C01_CFFv1_NB0121','120R22_F03_CFFv1_NA0137','104P04_D01_CFFv1_NA0266')\nhhv6_low_cluster<-as.character(hhv6_low_cluster)\ncombineddf$sample<-as.character(combineddf$sample)\ncombineddf$cluster<-'high cluster'\nfor(i in 1:nrow(combineddf)){ \n for(j in 1:length(hhv6_low_cluster)){ \n if(hhv6_low_cluster[j] %in% combineddf$sample[i]) { \n combineddf$cluster[i]<-'low cluster'\n }\n }\n }\n\nplot<-ggplot(combineddf, aes( x=combineddf$length)) + \n geom_histogram(binwidth = 5, aes(fill=combineddf$cluster)) + \n # geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\n\nplot\n\n\nggsave('filled_all_cmv_positives_average_length.pdf',plot, height = 3, width = 3,useDingbats = FALSE)\n\nsavePlot(plot, 'all_cmv_positives_average_length.pdf')\n\n\n\nggplot(combineddf, aes(y=combineddf$denominator_adjusted, x=combineddf$length)) + \n geom_point() + \n geom_vline(xintercept = mean(combineddf$length)) +\n xlim(0,500) + \n ylab('occurrences/total read count of sample')+\n xlab('length')+\n labs(colour=\"file\") + \n theme_classic() +\n theme(legend.position=\"none\")\n\n\n\n#for rpkm\ncombineddf$rpkm<-NA\nfor (i in 1:length(read_counts$sample)){ \n for( j in 1:length(combineddf$type)) { \n temp<-strsplit(as.character(read_counts$sample[i]), split = 'final') [[1]][1]\n if( temp == combineddf$type[j]) { \n combineddf$rpkm[j]= (10e9*combineddf$occurences[j]) / (read_counts$count[i] * 3088286401) \n }\n }\n}\n\ncmv_rpkm_plot<-ggplot(combineddf, aes( x=combineddf$length)) + \n geom_histogram(binwidth = 5, aes()) + \n # geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combineddf$length)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\n\ncmv_rpkm_plot\n\nggplot(combineddf, aes(y=combineddf$rpkm, x=combineddf$length)) + \n geom_point() + \n geom_vline(xintercept = mean(combineddf$length)) +\n xlim(0,500) + \n ylab('occurrences/total read count of sample')+\n xlab('length')+\n labs(colour=\"file\") + \n theme_classic() +\n theme(legend.position=\"none\")\n######\nbinned_occurences<-c()\nbinned_lengths<-c()\nfor( i in 1:nrow(combineddf)){ \n if(i%%5==0) {\n tempcount=0\n tempcount<-sum(combineddf$occurences[i],combineddf$occurences[i-1],combineddf$occurences[i-2],combineddf$occurences[i-3],combineddf$occurences[i-4],combineddf$occurences[i-5])\n binned_occurences<-append(binned_occurences,tempcount)\n binned_lengths<-append(binned_lengths,i)\n }\n}\n#binned_lengths<-as.character(binned_lengths)\n#binned_lengths<-as.character(binned_occurences)\nbinned_df<-cbind.data.frame(binned_occurences,binned_lengths)\n\n\n\n\n######\n##########\nfor(i in 1:nrow(read_counts)) { \n if(read_counts$cmv_ct[i]==0) { \n read_counts$cmv_ct[i]=NA\n }\n }\nfmt_dcimals <- function(decimals=0){\n # return a function responpsible for formatting the \n # axis labels with a given number of decimals \n function(x) as.character(round(x,decimals))\n}\nread_counts$cmvnorm = 100*(read_counts$cmv_quant*250000)/(read_counts$bglobin_quant*3000000000)\npercentvspercent<-ggplot(read_counts, aes( x=read_counts$cmvnorm,y= read_counts$percentage, color= read_counts$sample)) + \n geom_point(size=6) + \n scale_y_continuous(labels=function(x){sprintf(\"%.4f\", x)}) +\n scale_x_continuous(labels=function(x){sprintf(\"%.6f\", x)}) +\n ylab('Percent of cfDNA reads mapping to CMV ') +\n xlab('expected CMV percentage based on qPCR')+\n labs(colour=\"file\") +\n theme(legend.position=\"right\")\npercentvspercent\nsavePlot(percentvspercent, 'normalized_cmv_and_genome_by_ct.pdf')\n\n\n\n\n\ncmvctbysum<-ggplot(read_counts, aes( x=read_counts$cmv_ct,y= read_counts$summed, color= read_counts$sample)) + \n geom_point(size=6) + \n ylab('number of verified reads')+\n xlab('cmv ct')+\n labs(colour=\"file\") +\n theme(legend.position=\"right\")\ncmvctbysum\n\nsavePlot(cmvctbysum, 'cmv_by_ct_vs_sum.pdf')\n\npercentcmvbysum<-ggplot(read_counts, aes( x=read_counts$cmv_ct,y= read_counts$percentage, color= read_counts$sample)) + \n geom_point(size=6) + \n xlab('cmv ct')+\n ylab('percent of cmv total reads going to cmv ')+\n scale_y_continuous(labels=function(x){sprintf(\"%.4f\", x)}) +\n labs(colour=\"file\") +\n theme(legend.position=\"right\")\npercentcmvbysum\nsavePlot(percentcmvbysum, 'cmv_by_ct_vs_percent.pdf')\n\n\n\n\n#cmv and bglobin quants in copies/ml\nqpcr_results<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/qpcr_results.xls', sheetIndex = 3, header = TRUE)\n\nread_counts$cmv_bglobin_ratio_ml<-NA\nfor(i in 1:nrow(qpcr_results)){ \n for(j in 1:nrow(read_counts)){\n if(grepl(as.character(qpcr_results$Sample.Name[i]), as.character(read_counts$sample[j]))){ \n read_counts$cmv_bglobin_ratio_ml[j]<-qpcr_results$CMv_quantity.ml_plasma[i]/qpcr_results$bglobin_quantity.ml_plasma[i]\n \n }\n }\n}\n\nfigure1b<-ggplot(read_counts, aes(x=read_counts$cmv_bglobin_ratio_ml,y=read_counts$percentage,color = read_counts$sample)) + \n theme_classic() + \n #xlim(c(0,.4)) + \n theme(legend.position=\"none\") +\n xlab('CMV copies/mL Beta-globin copies/mL') + \n ylab('Percentage of reads mapping to CMV per sample') +\n scale_x_continuous(limits = c(0, .4))+ \n scale_y_log10() + \n geom_point(size = 3)\nfigure1b \nggsave(\"figure1b_final.pdf\", plot = figure1b, width = 4, height = 4, useDingbats= FALSE)\n\n\n####resequenced sample####\nresequenced<-read.table('/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/read_length_counts.txt')\n\nplot<-ggplot(resequenced, aes( x=resequenced$V2, y= resequenced$V1)) + \n geom_point() + \n # geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(resequenced$V2)) +\n xlim(0,500) + \n #ylim(0,200) + \n ylab('occurences')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\nplot\n\n\n\nresequenced_bam<-scanBam('/Users/gerbix/Documents/vikas/NIPT/21419_download/resequenced_121R04_D01_CFFv1_NB0222.bam')\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7417503595352173, "alphanum_fraction": 0.763271152973175, "avg_line_length": 39.98039245605469, "blob_id": "b89f321e78238b7a1b23887ef0450098345aa188", "content_id": "483ea2be5280056629864a4a8128d0da79677423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2091, "license_type": "no_license", "max_line_length": 146, "num_lines": 51, "path": "/reproducibility/HHV-6_reproducibility.sh", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#Workflow for generating CMV figures \n\n#Bowtie2 alignment to CMV Merlin genome (NC_006273.2)\nbowtie2 -x <hhv-6a/b_reference> -1 <r1.fastq> -2 <r2.fastq> --local --no-unal -p <cores> -S <aligned.sam> \n\n#Convert SAM to BAM \nsamtools view -@ <cores> -Sb <aligned.sam> -o <aligned.bam> \n\n#sort BAM for picard\nsamtools sort <aligned.bam> <sorted.bam> \n\n#Deduplicate aligned bam file \npicard MarkDuplicates I=<sorted.bam> O=<deduplicated.bam> M=<metrics.txt> REMOVE_DUPLICATES= TRUE ASSUME_SORTED=TRUE VALIDATION_STRINGENCY= SILENT\n\n#Only keep reads with 34 or more matches and extract reads for repeatmasking and BLAST later.\n./34m.sh <deduplicated_bam_folder> \n\n#Repeatmask output of previous command\nRepeatmasker -int -pa <cores> hhv6_combined.txt\nmv hhv6_combined.txt.masked hhv6_combined_masked.fasta \n\n#remove all repeat masked lines with NNNNN in it \nfor file in hhv6_combined_masked.fasta\ndo\nsed '$!N;/NNNNN/!P;D' \"$file\"\ndone > hhv6_combined_masked_n_removed.fasta\n\n#Local BLAST against NT (requires blast NT database)\nblastn -query hhv6_combined_masked_n_removed.fasta -db /db/blast_db/nt -num_threads 42 -perc_identity 97 -evalue 1e-5 -out hhv6_vs_full_nt.txt\n\n#Creates count table of BLAST hits to \"Human hepesvirus 5\" from the BLAST results.\npython blast_hits.py hhv6_masked_blastn_out.txt '<Human herpesvirus 6>'\n\n#Creates BAMs with just the verified reads \n#run from within folder of filtered bams for both HHV-6A and HHV-6B (./34m.sh step)\nuw-virongs-vikas:verified_sams gerbix$ python verified_bam.py blast_hits<HHV6a/b>.csv <suffix for filtered bams> \n\n\n#creates all_sample_data.csv- A table of sample name, FPM, FPKM and read counts\n#file paths inside the script require editing based on how the above commands were run\nrscript --vanilla fpm_calculate.R\n\n#for the scripts below file paths will have to be changed from the ones used on our local machine\n#figure 5 inidividual figures\n#path to any bams should be from the verified bams folder\nrscript --vanilla figure_5A.r\nrscript --vanilla figure_5B.r\nrscript --vanilla figure_5C.r\n\n#figure 5 panel\nrscript --vanilla figure_5.r\n\n" }, { "alpha_fraction": 0.6507096886634827, "alphanum_fraction": 0.6752017736434937, "avg_line_length": 34.93000030517578, "blob_id": "1eea2dc2fd76fbaf6385220d98db44669a7348c3", "content_id": "232ee3c2b2e64b8e283467baafc43e87d9e7f461", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3593, "license_type": "no_license", "max_line_length": 186, "num_lines": 100, "path": "/reproducibility/CMV/SOT/previous_version/figure_4B.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT')\nblast_hits_file<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/blast_hits.csv', header = FALSE, col.names = c('full_ID','count'))\nfilenames = list.files('/Users/gerbix/Documents/vikas/NIPT/new_samples',pattern = '.bam$', full.names = TRUE)\nplotslist<-c()\n\n\nblast_hits_file$full_ID<-as.character(blast_hits_file$full_ID)\nfor( i in 1:nrow(blast_hits_file)){\n blast_hits_file$read_ID[i]<-strsplit(blast_hits_file$full_ID, '-')[[i]][2]\n} \n\nblast_hits_file<-blast_hits_file[blast_hits_file$count>75,] \nblast_hits_file<-blast_hits_file[-(which(duplicated(blast_hits_file$read_ID))),]\n\nisize<-c()\nread_id<-c()\nsample<-c()\nfor(i in 1:length(filenames)){ \n temp_bam<-scanBam(filenames[i])\n if((identical(temp_bam[[1]]$qname, character(0)))){ \n next\n }\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:nrow(blast_hits_file)){ \n print(100 * (j/nrow(blast_hits_file)))\n for(k in 1:length(all_bam_read_IDs)){\n if( !(is.na(blast_hits_file$read_ID[j])) & grepl( blast_hits_file$read_ID[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, filenames[i])\n }\n }\n }\n}\ncombined<-data.frame(sample, read_id, isize)\ncombined<-combined[combined$isize>0,]\ncombined<-combined[complete.cases(combined$isize),]\ncmv_plot<-ggplot(combined, aes( x=combined$isize, fill = sample)) + \n geom_histogram(binwidth = 5) +\n geom_vline(xintercept = median(combined$isize)) +\n xlim(0,500) + \n ylab('occurences')+\n xlab('fragment length')+\n annotate(\"text\", x = 400, y = 600, label = paste0('median=', median(combined$isize[combined$isize<500]))) +\n labs(colour=\"file\") +\n scale_y_continuous(expand = c(0,0)) +\n theme_classic() + \n theme(legend.position=\"right\")\ncmv_plot\n\n\n#overlaying human \nhuman<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/p16.results.txt', sep = '', header = FALSE, col.names = c('frequency', 'isize'))\nhuman<-human[human$isize>0,]\nhuman_isizes<-rep(human$isize, human$frequency)\nhuman_df<-as.data.frame(human_isizes)\ncolnames(human_df)[1]<-'isize'\nhuman_df$sample<-'P16_Human'\nhuman_df$read_id<-'eh'\n\n\ncmv_df<-as.data.frame(table(combined$isize[combined$isize<500]))\ncmv_df$percent<-NA\nfor(i in 1:nrow(cmv_df)){ \n cmv_df$percent[i] <- 100 * (cmv_df$Freq[i] / sum(cmv_df$Freq))\n }\ncmv_df$type<-'CMV'\n\nhuman_isize_df<-as.data.frame(table(human_df$isize[human_df$isize<500]))\nhuman_isize_df$percent<-NA\nfor(i in 1:nrow(human_isize_df)){ \n human_isize_df$percent[i] <- 100 * (human_isize_df$Freq[i] / sum(human_isize_df$Freq))\n}\nhuman_isize_df$type<-'Human'\n\ncombined_isize_df<-rbind(human_isize_df, cmv_df)\n\ncmv_plot_4b<-ggplot(combined_isize_df, aes( x=as.numeric(as.character(combined_isize_df$Var1)), y = as.numeric(as.character(combined_isize_df$percent)),color = combined_isize_df$type)) +\n geom_line() + \n xlim(0,500) + \n ylim(0,2.5) + \n scale_color_manual(values=c(\"#ED6464\", \"#05188B\"), labels = c(\"CMV\", \"Human\")) +\n theme(legend.position = c(0.8, 0.6)) + \n ylab('percent')+\n xlab('Fragment size')+\n theme_classic() +\n theme(text = element_text(size=8)) +\n theme(legend.position = c(0.8, 0.6)) + \n theme(legend.title=element_blank())\n cmv_plot_4b\n\nggsave(plot = cmv_plot_4b, 'figure_4B.pdf', height = 3, width = 3)\nsave.image(\"~/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/figure_4B.Rdata\")\n" }, { "alpha_fraction": 0.6518051028251648, "alphanum_fraction": 0.6938251852989197, "avg_line_length": 25.103092193603516, "blob_id": "8d685e7b7a5e05bba899e0a9bb209395bbbea1c5", "content_id": "8745b5b5f38cb7378c166ed48f5843f6937edbd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 5069, "license_type": "no_license", "max_line_length": 119, "num_lines": 194, "path": "/scratch/HHV6/hhv_6_121r04_human_compare.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\n\n###121r04 human \nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/figure_2_final/71719')\n#read_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\nfilenames = '/Volumes/Seagate8Tb1/nipt/bams/bams_for_vikas/3P13_E02_CFFv1_NB0015.final.bam.read_length_counts.txt'\nplotslist<-c()\n\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(filenames)){ \n print(i)\n #print(filenames[i])\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'Human'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nhuman_frequencies <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\nread_counts$sample<-as.character(read_counts$sample)\n\nhuman_frequencies$percent<-(100 * human_frequencies$freq) / (sum(human_frequencies$freq))\n\n#human median calculation\nhuman_isize_expanded<-rep(human_frequencies$isize, human_frequencies$freq) \nhuman_isize_expanded_below250<-human_isize_expanded[human_isize_expanded < 500]\nhuman_median<-median(as.numeric(as.character(human_isize_expanded_below250)))\n\n\nhuman_frequencies$isize<-as.numeric(as.character(human_frequencies$isize))\nx<-human_frequencies[order(human_frequencies$isize),]\n\nx<-x[x$isize < 250 ,]\n\ncount = 1 \nsum = 0 \nx$percent<- (100 * x$freq)/ sum(x$freq)\nwhile( sum < 50) { \n print(sum)\n print(x$isize[count])\n sum = sum + x$percent[count]\n count = count + 1 \n}\n\n\nhuman_plot<-ggplot(human_frequencies, aes( x = human_frequencies$isize , y = human_frequencies$percent)) + \n geom_vline(xintercept = human_median) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\nggsave(plot = human_plot, 'Resequenced_human_fragment_length.pdf')\n\n\n###hhv6 isizes\nhhv_6_combined<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/figure_2_final/71719/hhv6_isizes_all.csv')\n\n\n\nplot<-ggplot(hhv_6_combined, aes( x=hhv_6_combined$length, y= hhv_6_combined$percent)) + \n geom_histogram(binwidth = 5, aes(fill = combineddf$sample, y=(100 * ..count../sum(..count..)))) + \n geom_line(data = , aes(x = A, y = B), col = \"red\") +\n xlim(0,500) + \n ylab('percent')+\n xlab('length')+\n labs(colour=\"file\") +\n theme_classic() + \n theme(legend.position=\"bottom\")\n \nplot\n\n\n\nhhv6_ks_test<-ks.test(human_isize_expanded,hhv_6_combined$lengthlist)\nhhv6_ks_test\n\n\nhhv_6_isize<-data.frame(hhv_6_combined$lengthlist)\ncolnames(hhv_6_isize)[1]<-'length'\nhhv_6_isize$type<-'hhv6'\n\nhuman_isize<-data.frame(human_isize_expanded)\ncolnames(human_isize)[1]<-'length'\nhuman_isize$type<-'Human'\n\nhuman_hhv6_combined<-rbind(human_isize,hhv_6_isize)\n\n\n\ncum_frequency<-ggplot(human_hhv6_combined, aes(x = human_hhv6_combined$length, color = human_hhv6_combined$type)) + \n theme_classic() + \n theme(legend.position='none') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') + \n stat_ecdf(geom = 'step', size =1 ) \ncum_frequency\n\n\nplot(ecdf(combined$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\nplot(ecdf(cmv))\n\n\n\nfor(i in 1:nrow(human_hhv6_combined)){ \n if(human_hhv6_combined$type=='H')\n }\n\n\n\n###########\n\nuniques<-unique(combineddf$sample)\n\nfor(i in 1:length(uniques)){ \n print(uniques[i])\n print( nrow(combineddf[combineddf$sample==uniques[i],]))\n }\n\n#99P03_C01\n#120R22_F03\n#104P04_D01\n#98p11\n#97P10_B02\n#93R20_D03\n\nto_remove<-c('99P03_C01','120R22_F03','104P04_D01','98P11','97P10_B02','93R20_D03')\n\n\nlowclusterremoved<-combineddf[-which(grepl(paste(to_remove,collapse=\"|\"),combineddf$sample)),]\n\nplot(ecdf(lowclusterremoved$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\n\n\nlowclusteronly<-combineddf[which(grepl(paste(to_remove,collapse=\"|\"),combineddf$sample)),]\n\nplot(ecdf(lowclusterremoved$length))\nplot(ecdf(human_isize_expanded), add = TRUE, col = 2 )\nplot(ecdf(lowclusteronly$length), add = TRUE, col = 3 )\n\n\nks.test(human_isize_expanded, combineddf$length)\n\n\n\n\nhhv6_isizes_all<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/figure_2_final/71719/hhv6_isizes_all.csv')\n\n\n\n\n\n\n\nhuman_isizes_all<-data.frame(human_isize$length)\ncolnames(human_isizes_all)[1]<-'lengthlist'\nhuman_isizes_all$X<-NA\nhuman_isizes_all$samplelist<-'Human'\nhuman_isizes_all$sample_trimmed<-'Human'\nhuman_isizes_all$cluster<-'Human'\n\nall_combined<-rbind(human_isizes_all, hhv6_isizes_all)\n\n\ncum_frequency<-ggplot(all_combined, aes(x = all_combined$lengthlist, color = all_combined$cluster)) + \n theme_classic() + \n xlim(0,500) + \n theme(legend.position='none') + \n xlab('Insert size') + \n ylab ('Cumulative frequency') + \n stat_ecdf(geom = 'step', size =1 ) \ncum_frequency\nggsave(cum_frequency, 'cumulative_frequency_500_max.pdf', height = 3 , width = 3)\n\n\n\n\n\n" }, { "alpha_fraction": 0.7278798222541809, "alphanum_fraction": 0.7445743083953857, "avg_line_length": 38.79999923706055, "blob_id": "a8f4d3bc134c9bbebaa9de154757dd3ed2ee1b2b", "content_id": "9b8f9610f95e36caa41b24e4df1d9ac40477f27e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 599, "license_type": "no_license", "max_line_length": 104, "num_lines": 15, "path": "/reproducibility/CMV/SOT/previous_version/figure_4.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\n\n\nload(file = '/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/figure_4A.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/figure_4B.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/figure_4C.rdata')\n\nplot_grid(plot,cmv_plot_4b, cumulative_freq_with_human ,labels = c('A','B','C'), ncol = 3, align = 'hv')\nggsave(plot = last_plot(), height = 3, width = 8, filename = 'figure_4.pdf')\n " }, { "alpha_fraction": 0.6730343103408813, "alphanum_fraction": 0.7037652134895325, "avg_line_length": 43.543209075927734, "blob_id": "54a136afcbf398dbd79952ec55297c39c9504f5c", "content_id": "04482f5f9a3a9577971c8d8c594ad001bb36405d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3612, "license_type": "no_license", "max_line_length": 165, "num_lines": 81, "path": "/reproducibility/CMV/SOT/current_version/figure_4A.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#matching container IDs to sequencing IDs and creating standard curves for cmv samples \nlibrary(\"ggplot2\")\nlibrary(\"xlsx\")\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch')\n\n#matching qpcr values to fpm values for SOT cmv samples\ncmv_ids<-read.csv('/Users/gerbix/Documents/vikas/NIPT/new_samples/new_cmv_pulled_ids.csv', sep = '\\t', header = FALSE, col.names = c('sequencing_id', 'bid', 'lmid'))\ncmv_ids$bid<-as.character(cmv_ids$bid)\nfor(i in 1:nrow(cmv_ids)){ \n cmv_ids$bid[i]<-strsplit(as.character(cmv_ids$bid[i]), 'P')[[1]][2]\n}\n\nrpkm_values<-read.csv('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch/all_sample_data.csv')\nrpkm_values$sample<-as.character(rpkm_values$sample)\nrpkm_values$rpm<-as.numeric(as.character(rpkm_values$rpm))\ncmv_quants<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/new_samples/CMVPulled.xlsx', sheetIndex = 1)\n\nrpkm_values$quant<-NA\nrpkm_values$sample<-as.character(rpkm_values$sample)\nfor(i in 1:nrow(cmv_ids)){ \n temp<-which(grepl(cmv_ids$sequencing_id[i],rpkm_values$sample))\n print(rpkm_values$sample[temp])\n temp_quant<-which(grepl(cmv_ids$bid[i], as.character(cmv_quants$Barcode.ID.)))\n rpkm_values$quant[temp]<-cmv_quants$result_num[temp_quant]\n}\n\nrpkm_values$quant_adjusted<-rpkm_values$quant * 4\ncurve<-ggplot(rpkm_values, aes(x = rpm, y = quant)) + \n geom_point() +\n ylim(c(0,20000)) +\n geom_smooth(method = \"lm\", se = FALSE, alpha = .5) + \n theme_classic() + \n geom_vline(xintercept = .3, linetype = 'dotted')\ncurve\n\n\nwrite.csv(rpkm_values, 'fpm_values_with_quants.csv')\n\n#matching qpcr values to fpm values for NIPT samples\noriginal_cmv<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update/6131_cmv_percent_vs_qpcr_load.xlsx', sheetIndex = 1)\noriginal_reformatted<- original_cmv[,c(1,4,11,12,13,14,15)]\ncolnames(original_reformatted)<-c('sample','quant','count','rpkm','read_counts','rpm','classification')\noriginal_reformatted$time<-'original'\noriginal_reformatted$quant_adjusted<-original_reformatted$quant\n\nrpkm_values$X<-NULL\nrpkm_values$time<-'new'\n\noriginal_new_combined<-rbind(original_reformatted,rpkm_values)\noriginal_new_combined$time<-as.character(original_new_combined$time)\n\nlibrary(RColorBrewer)\ngetPalette = colorRampPalette(brewer.pal(8, \"Set3\"))\ncolourCount = length(unique(original_new_combined$time))\n\n\nscientific_10 <- function(x) {\n parse(text=gsub(\"e\", \" %*% 10^\", scales::scientific_format()(x)))\n}\n\nr2=summary(lm(rpm ~ quant_adjusted, data=original_new_combined))\nlb1 <- paste0(\"r^2= \", signif(r2$adj.r.squared, digits = 2))\nplot<-ggplot(original_new_combined, aes(x = rpm, y = quant_adjusted, color= time)) + \n geom_point() +\n scale_y_log10(breaks = c( 1, 10, 100, 1000, 10000,100000), labels = trans_format(\"log10\", math_format(10^.x)))+ \n scale_x_log10(limits = c(.01, 100), labels = trans_format(\"log10\", math_format(10^.x)))+ \n ylab('CMV copies/mL') + \n xlab('CMV FPM') + \n geom_smooth(method = \"lm\", se = FALSE, alpha = .5, aes(group=1), color = 'black') + \n scale_color_manual(values = c(\"#729AF2\",\"#BF6FF7\"), labels = c(\"Maternal\", \"Transplant\")) + \n theme_classic() + \n annotate(\"text\", x = 25 , y =.5, label = lb1, parse = FALSE, vjust =1, size = 3 ) +\n theme(text = element_text(size=8),\n legend.title=element_blank(),\n legend.position = c(.8,.2),\n legend.spacing.y = unit(0.01, 'cm')) \nplot\nggsave(plot = plot, 'figure_4a_modified.pdf', height = 3, width = 3)\n\nsave.image(\"~/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch/figure_4A.rdata\")\n\n\n\n\n" }, { "alpha_fraction": 0.7476383447647095, "alphanum_fraction": 0.76113361120224, "avg_line_length": 45.1875, "blob_id": "70cb4ce094bf9766654d5f67ce26df3e8caf815c", "content_id": "7e78f0c27e70ae1153d3f3a01403f4f6b94f1aed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 741, "license_type": "no_license", "max_line_length": 118, "num_lines": 16, "path": "/reproducibility/CMV/SOT/current_version/figure_4.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch')\n\n\nload(file = '/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch/figure_4A.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch/figure_4B.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT/fragment_patch/figure_4C.rdata')\n\nplot_grid(plot,cmv_plot_4b, cumulative_freq_with_human ,labels = c('A','B','C'), ncol = 3, align = 'hv')\nggsave(plot = last_plot(), height = 3, width = 8, filename = 'figure_4.pdf')\n " }, { "alpha_fraction": 0.7441860437393188, "alphanum_fraction": 0.760465145111084, "avg_line_length": 32.07692337036133, "blob_id": "9d11b4f83235edac7e3fcbf602945f37007aaca3", "content_id": "f09385b5830d73b5a2c9792f32484dc63ba72676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 430, "license_type": "no_license", "max_line_length": 86, "num_lines": 13, "path": "/reproducibility/CMV/cumulative_dist.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#load fig 3 data\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal')\n\ncmv<-combined[combined$type==\"CMV\",]\ncmv$isize<-as.numeric(cmv$isize)\n\nwrite.csv(cmv,'121r04_cmv_cumulative_dist.csv')\n\n#load 4b data\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/SOT')\n\ncmv_sot<-combined_isize_df[combined_isize_df$type=='CMV',]\nwrite.csv(cmv_sot,'SOT_cmv_cumulative_dist.csv')\n" }, { "alpha_fraction": 0.6819647550582886, "alphanum_fraction": 0.7092533111572266, "avg_line_length": 30.119691848754883, "blob_id": "2b8d54eede8dfd9cadf878e5eb1ea8a30b68395d", "content_id": "59def8f463b7f5e41f274abf40af0a051b70c742", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 8062, "license_type": "no_license", "max_line_length": 160, "num_lines": 259, "path": "/reproducibility/CMV/maternal/current_version/figure_3.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/CMV/maternal/fragment_patch')\n\n# modify to include the resequenced 121r04 frequency table\nfilenames = '/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/aligned_to_hg38/duplicates_removed_read_lengths.txt'\nplotslist<-c()\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\n\n#extracts all insert sizes below 500\nfor (i in 1:length(filenames)){ \n print(i)\n if (file.size(filenames[i]) != 0) {\n histo<- read.table(filenames[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'Human'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nhuman_frequencies <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\n\nhuman_frequencies$percent<-(100 * human_frequencies$freq) / (sum(human_frequencies$freq))\n\n#human median calculation\nhuman_isize_expanded<-rep(human_frequencies$isize, human_frequencies$freq) \nhuman_isize_expanded_below250<-human_isize_expanded[human_isize_expanded < 500]\nhuman_median<-median(as.numeric(as.character(human_isize_expanded_below250)))\n\n\nhuman_frequencies$isize<-as.numeric(as.character(human_frequencies$isize))\n\n#plot of just human insert sizes\nhuman_plot<-ggplot(human_frequencies, aes( x = human_frequencies$isize , y = human_frequencies$percent)) + \n geom_vline(xintercept = human_median) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\n\n\n#reading in CMV BAMs\n\n#provide repeatmasked fasta for 121r04 resequenced\nrepeatmasked_fasta<-read.fasta('/Users/gerbix/Documents/vikas/NIPT/121r04_resequenced/resequenced_repeatmasked_7_removed.fasta')\nfasta_IDs<-names(repeatmasked_fasta)\n\nfasta_IDs_trimmed<-c()\nfor( i in 1:length(fasta_IDs)){\n progress(i,length(fasta_IDs))\n fasta_IDs_trimmed<-append(fasta_IDs_trimmed,strsplit(fasta_IDs, '/')[[i]][1])\n} \n\n#converts reads to fragments\nfasta_IDs_deduplicated<-fasta_IDs_trimmed[-(which(duplicated(fasta_IDs_trimmed)))]\n\nisize<-c()\nread_id<-c()\nsample<-c()\n\n#reads in bam to find insert sizes matched by read ID from fasta\ntemp_bam<-scanBam('/Users/gerbix/Documents/vikas/NIPT/121r04_resequenced/deduplicating/cmv_duplicates_removed.bam')\n all_bam_read_IDs<-temp_bam[[1]]$qname \n matches<-c()\n for(j in 1:length(fasta_IDs_deduplicated)){ \n print(100 * j / length(fasta_IDs_deduplicated))\n for(k in 1:length(all_bam_read_IDs)){\n if(grepl( fasta_IDs_deduplicated[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, 'CMV')\n }\n }\n }\n\nCMV_matched<-data.frame(sample, read_id, isize)\nCMV_matched<-CMV_matched[CMV_matched$isize>0,]\nCMV_matched<-CMV_matched[CMV_matched$isize<500,]\n\nCMV_matched<-CMV_matched[complete.cases(CMV_matched$isize),]\n\nCMV_frequencies<-data.frame(table(CMV_matched$isize))\ncolnames(CMV_frequencies)<-(c('isize','freq'))\nCMV_frequencies$percent<- 100 * ( as.numeric(as.character(CMV_frequencies$freq)) / (sum(CMV_frequencies$freq))) \nCMV_frequencies$type<-'CMV'\n\n#calculating CMV median\nCMV_isize_exanded<-rep(CMV_frequencies$isize, CMV_frequencies$freq) \nCMV_isize_exanded<-CMV_isize_exanded[as.numeric(as.character(CMV_isize_exanded)) < 500]\nCMV_median<-median(as.numeric(as.character(CMV_isize_exanded)))\n\n\n# plot of just resequenced CMV insert sizes\nCMV_plot<-ggplot(CMV_frequencies, aes( x = as.numeric(as.character(CMV_frequencies$isize)) , y = CMV_frequencies$percent)) + \n geom_vline(xintercept = 143, color = 'blue') + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nCMV_plot\n\nwrite.csv(CMV_matched, 'cmv_duplicates_removed_read_data.csv')\nwrite.csv(CMV_frequencies,'cmv_duplicates_removed_insert_sizes.csv')\n\n#combining human and CMV graphs \ncombined<-rbind(human_frequencies,CMV_frequencies)\n\n#red: ED6464\n#blue: 05188B\n\ncombined_plot <- ggplot(combined, aes ( x = as.numeric(as.character(combined$isize)), y = as.numeric(as.character(combined$percent)), color = combined$type)) + \n theme_classic() + \n xlim(c(0,500)) +\n ylim(c(0,2.5)) +\n scale_color_manual(values=c(\"#ED6464\", \"#05188B\")) +\n theme(legend.title=element_blank())+ \n theme(legend.position = c(.8,.6)) + \n xlab('Fragment size') + \n theme(legend.position = c(0.8, 0.6)) + \n ylab('Percent') + \n theme(text = element_text(size=8)) +\n theme(legend.title=element_blank(),legend.key.size = unit(1, 'lines'))+\n geom_line(size = .5) \ncombined_plot\n\n#p-value calculations \nCMV_isize_exanded<-as.numeric(as.character(CMV_isize_exanded))\nhuman_isize_expanded<-as.numeric(as.character(human_isize_expanded))\n\n\n#two sided t test on insert sizes \nt.test(human_isize_expanded,CMV_isize_exanded, alternative = \"two.sided\")\n\n#running t tests 10000 iterations \ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n ttest<-(t.test(temp,CMV_isize_exanded, paired = TRUE))\n tests<-append(tests,ttest$p.value)\n}\n\ntestsdf<-data.frame(tests)\n\n#CMVpercentile of human insert size distribution\nhuman_percentile<-ecdf(human_isize_expanded)\ncmv_med_percentile<-human_percentile(median(CMV_isize_exanded)) * 100\n\n#fligner-killeen test for homogeneity of variances between samples\ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n fktest<-(fligner.test(temp,CMV_isize_exanded, paired = TRUE))\n tests<-append(tests,fktest$p.value)\n}\n\nfk_df<-data.frame(tests)\n\n#Kolmogorov-Smirnov test\n\ntests<-c()\nfor(i in 1:10000){ \n progress(i,10000)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n kstest<-(ks.test(temp,CMV_isize_exanded))\n tests<-append(tests,kstest$p.value)\n}\n\nks_df<-data.frame(tests)\n\nmedian(ks_df$tests)\n\nplot(ecdf(CMV_isize_exanded))\nplot(ecdf(human_isize_expanded))\n\nCMV_cdf <- ecdf(CMV_isize_exanded)\nhuman_cdf <- ecdf(human_isize_expanded)\n\nCMV_cdf\nks<-ks.test(CMV_isize_exanded,human_isize_expanded)\n\nhuman_isize_df<-data.frame(human_isize_expanded)\ncmv_isize_df<-data.frame(CMV_isize_exanded)\n\nplot(ecdf(CMV_isize_exanded)) \n\nplot(ecdf(human_isize_expanded),add = TRUE, col = 2 )\n\nhuman_cdf_df<-data.frame()\n\nhuman_subsampled<-data.frame(sample(human_isize_expanded, length(CMV_isize_exanded)))\ncolnames(human_subsampled)[1]<-'isizes'\nhuman_subsampled$type = 'human'\n\ncmv_isize_df$type = 'cmv'\ncolnames(cmv_isize_df)[1]<-'isizes'\n\nsubsampled_df<-rbind(human_subsampled, cmv_isize_df)\n\ncum_frequency<-ggplot(subsampled_df, aes(x = subsampled_df$isizes, color = subsampled_df$type)) + \n theme_classic() + \n scale_color_manual(values=c(\"#ED6464\", \"#05188B\"), labels = c(\"CMV\", \"Human\")) +\n theme(legend.position='bottom') + \n xlab('Fragment size') + \n theme(legend.position = c(0.8, 0.6)) + \n ylab ('Cumulative frequency') + \n theme(legend.title=element_blank(),legend.key.size = unit(1, 'lines'))+ \n stat_ecdf(geom = 'step', size =.5, pad = FALSE) + \n theme(text = element_text(size=8)) +\n xlim(c(0,500))\ncum_frequency\nggsave(plot = cum_frequency, 'cmv_deduplicated_cum_frequency_1026.pdf',width = 3, height = 3 )\n\n\nshapiro.test(subsampled_df$isizes[subsampled_df$type=='human'])\n\n#Panel\n#red: ED6464\n#blue: 05188B\nplot_grid(combined_plot, cum_frequency, labels = c('A','B'))\nggsave(plot = last_plot(), height = 3, width = 6, filename = 'figure_3_modified.pdf')\n\n\n#wilcox test\ntests<-c()\nfor(i in 1:100){ \n progress(i,100)\n temp<-(sample(human_isize_expanded, length(CMV_isize_exanded)))\n #print((temp))\n wctest<-(wilcox.test(temp,CMV_isize_exanded))\n tests<-append(tests,wctest$p.value)\n}\n\n\n" }, { "alpha_fraction": 0.6937342882156372, "alphanum_fraction": 0.7167854309082031, "avg_line_length": 29.292062759399414, "blob_id": "e12117853428472cd7ea04f1ef48d4661e316a4b", "content_id": "6e1d01d80a9a2a3aa16c718f00a4230e1efd92cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 9544, "license_type": "no_license", "max_line_length": 218, "num_lines": 315, "path": "/scratch/human_resequenced_deduplication_compare.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\n#comparing human with and without duplicates \n\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating')\ndeduplicated_human = '/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/aligned_to_hg38/duplicates_removed_read_lengths.txt'\nplotslist<-c()\n\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(deduplicated_human)){ \n print(i)\n #print(filenames[i])\n if (file.size(deduplicated_human[i]) != 0) {\n histo<- read.table(deduplicated_human[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'deduplicated'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\ndeduplicated_human_frequencies <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\n\ndeduplicated_human_frequencies$percent<-(100 * deduplicated_human_frequencies$freq) / (sum(deduplicated_human_frequencies$freq))\n\n#human median calculation\nhuman_isize_expanded_deduplicated<-rep(deduplicated_human_frequencies$isize, deduplicated_human_frequencies$freq) \nhuman_isize_expanded_below500<-human_isize_expanded_deduplicated[human_isize_expanded_deduplicated < 500]\nhuman_median_deduplicated<-median(as.numeric(as.character(human_isize_expanded_below500)))\n\n\ndeduplicated_human_frequencies$isize<-as.numeric(as.character(deduplicated_human_frequencies$isize))\nx<-deduplicated_human_frequencies[order(deduplicated_human_frequencies$isize),]\n\nx<-x[x$isize < 250 ,]\n\ncount = 1 \nsum = 0 \nx$percent<- (100 * x$freq)/ sum(x$freq)\nwhile( sum < 50) { \n print(sum)\n print(x$isize[count])\n sum = sum + x$percent[count]\n count = count + 1 \n}\n\n\nhuman_plot<-ggplot(deduplicated_human_frequencies, aes( x = deduplicated_human_frequencies$isize , y = deduplicated_human_frequencies$percent)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\nggsave(plot = human_plot, 'Resequenced_human_fragment_length.pdf')\n\n\n\n\n\n\n\n\n\n#Human with duplicates\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating')\nhuman_with_duplicates = '/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/aligned_to_hg38/read_lengths_duplicates_marked.txt'\nplotslist<-c()\n\n\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(human_with_duplicates)){ \n print(i)\n #print(filenames[i])\n if (file.size(human_with_duplicates[i]) != 0) {\n histo<- read.table(human_with_duplicates[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'with_duplicates'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nhuman_with_duplicates <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\n\nhuman_with_duplicates$percent<-(100 * human_with_duplicates$freq) / (sum(human_with_duplicates$freq))\n\n#human median calculation\nhuman_isize_expanded_duplicates<-rep(human_with_duplicates$isize, human_with_duplicates$freq) \nhuman_isize_expanded_below500<-human_isize_expanded_duplicates[human_isize_expanded_duplicates < 500]\nhuman_median_duplicates<-median(as.numeric(as.character(human_isize_expanded_below500)))\n\n\nhuman_with_duplicates$isize<-as.numeric(as.character(human_with_duplicates$isize))\nx<-human_with_duplicates[order(human_with_duplicates$isize),]\n\nx<-x[x$isize < 250 ,]\n\ncount = 1 \nsum = 0 \nx$percent<- (100 * x$freq)/ sum(x$freq)\nwhile( sum < 50) { \n print(sum)\n print(x$isize[count])\n sum = sum + x$percent[count]\n count = count + 1 \n}\n\n\nhuman_plot<-ggplot(human_with_duplicates, aes( x = human_with_duplicates$isize , y = human_with_duplicates$percent)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\nggsave(plot = human_plot, 'Resequenced_human_fragment_length.pdf')\n\n\n\n####only the removed duplicates\nextracted_duplicates<-'/Volumes/Seagate8Tb1/resquenced_121R04_D01_CFFv1_NB0222/aligned_to_hg38/duplicates_only_read_lengths.txt'\nplotslist<-c()\ndflist<-c()\nstatslist<-c()\ntotallengths<-c()\ntotaloccurences<-c()\nfor (i in 1:length(extracted_duplicates)){ \n print(i)\n #print(filenames[i])\n if (file.size(extracted_duplicates[i]) != 0) {\n histo<- read.table(extracted_duplicates[i], quote=\"\\\"\", comment.char=\"\")\n colnames(histo)[2]<-'isize'\n colnames(histo)[1]<-'freq'\n histo$type<-'extracted_duplicates'\n histo<-histo[histo$isize>0,]\n if(nrow(histo)>0){\n toremove<-which(histo[,2]> 500)\n if(length(toremove)>0){ \n histo<-histo[-toremove,]\n }\n totallengths= append(totallengths,histo$isize)\n totaloccurences =append(totaloccurences,histo$freq)\n dflist[[i]]<-histo\n }\n }\n}\n\nextracted_duplicates <- do.call(\"rbind\", dflist)\nlengthlist<-c()\nsamplelist<-c()\n\nextracted_duplicates$percent<-(100 * extracted_duplicates$freq) / (sum(extracted_duplicates$freq))\n\n#human median calculation\nextractedduplicates_expanded<-rep(extracted_duplicates$isize, extracted_duplicates$freq) \nextractedduplicates_expanded_below500<-extractedduplicates_expanded[extractedduplicates_expanded < 500]\nextractedduplicates_expanded_median<-median(as.numeric(as.character(extractedduplicates_expanded_below500)))\n\n\nextracted_duplicates$isize<-as.numeric(as.character(extracted_duplicates$isize))\nx<-extracted_duplicates[order(extracted_duplicates$isize),]\n\nx<-x[x$isize < 250 ,]\n\ncount = 1 \nsum = 0 \nx$percent<- (100 * x$freq)/ sum(x$freq)\nwhile( sum < 50) { \n print(sum)\n print(x$isize[count])\n sum = sum + x$percent[count]\n count = count + 1 \n}\n\n\nhuman_plot<-ggplot(extracted_duplicates, aes( x = extracted_duplicates$isize , y = extracted_duplicates$percent)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_plot\n\n\n\n\n\n\n\n\n\n\n\n#combining duplicated and deduplicated\n#human_with_duplicates$type<-'with duplicates'\n#deduplicated_human_frequencie$type<-'without duplicates'\n\nduplicated_deduplicated_combined<-rbind(deduplicated_human_frequencies, human_with_duplicates, extracted_duplicates)\nwrite.csv(duplicated_deduplicated_combined,'resequenced_human_insert_sizes.csv')\n\nduplication_distribution_plot<-ggplot(duplicated_deduplicated_combined, aes( x = duplicated_deduplicated_combined$isize , y = duplicated_deduplicated_combined$percent, color = duplicated_deduplicated_combined$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line(aes(alpha=0.4)) \nduplication_distribution_plot\n\ndeduplicated_human_frequencies_plot<-ggplot(deduplicated_human_frequencies, aes( x = deduplicated_human_frequencies$isize , y = deduplicated_human_frequencies$percent, color = deduplicated_human_frequencies$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \ndeduplicated_human_frequencies_plot\n\n\nhuman_with_duplicates_plot<-ggplot(human_with_duplicates, aes( x = human_with_duplicates$isize , y = human_with_duplicates$percent, color = human_with_duplicates$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nhuman_with_duplicates_plot\n\nextracted_duplicates_plot<-ggplot(extracted_duplicates, aes( x = extracted_duplicates$isize , y = extracted_duplicates$percent, color = extracted_duplicates$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nextracted_duplicates_plot\n\n \ndeduplicated_extracted<-rbind(deduplicated_human_frequencies, extracted_duplicates)\n\ndeduplicated_extracted_plot<-ggplot(deduplicated_extracted, aes( x = deduplicated_extracted$isize , y = deduplicated_extracted$percent, color = deduplicated_extracted$type)) + \n geom_vline(xintercept = 168) + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \ndeduplicated_extracted_plot\n\n\n\n\n\n\n\n\nduplicated_expaned<-data.frame(human_isize_expanded_duplicates)\nduplicated_expaned$type<-'duplicated'\ncolnames(duplicated_expaned)<-c('isizes', 'type')\n\n\n\ndeduplicated_expanded<-data.frame(human_isize_expanded_deduplicated)\ndeduplicated_expanded$type<-'deduplicated'\ncolnames(deduplicated_expanded)<-c('isizes', 'type')\n\n\nextracted_duplicates_expanded_df<-data.frame(extractedduplicates_expanded)\nextracted_duplicates_expanded_df$type<-'extracted_duplicates'\ncolnames(extracted_duplicates_expanded_df)<-c('isizes', 'type')\n\n\n\nexpanded_combined<-rbind(duplicated_expaned, deduplicated_expanded,(extracted_duplicates_expanded_df))\n\nduplication_distribution_histogram<-ggplot(expanded_combined, aes(x=expanded_combined$isizes, color =expanded_combined$type)) +\n geom_freqpoly(binwidth = 5 ) + \n theme_classic() + \n xlab('Insert sizes')\n\n#duplication_distribution_histogram\n\n\n" }, { "alpha_fraction": 0.6662379503250122, "alphanum_fraction": 0.6994640827178955, "avg_line_length": 37.48760223388672, "blob_id": "305a44f2a01efcd27b120ac38b9ccf110e518668", "content_id": "7d2c454ae35c79b37dbc131d1b22959a5f604011", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4665, "license_type": "no_license", "max_line_length": 218, "num_lines": 121, "path": "/scratch/qpcr_graphs_updated.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(xlsx)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update')\nqpcr_results<-read.xlsx2('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update/qpcr_results.xlsx', sheetIndex = 3)\n#read_counts <- read.csv(\"/Users/gerbix/Documents/vikas/NIPT/21419_download/bam_fragment_read_counts.csv\")\ncmv_all_positives<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/all_sample_data.csv', colClasses=c('character', 'character', 'character','character', 'character', 'character','character')) \n\n\n\nqpcrplot_copies_microliter<-ggplot(qpcr_results, aes(x=qpcr_results$BGLOBIN_Quantity.10UL.DNA., y=qpcr_results$CMV_Quantity.10UL.DNA., color=qpcr_results$classification)) + \n theme_classic() +\n theme(legend.position= \"bottom\")+\n xlab('Beta-globin copies per reaction') +\n ylab('CMV copies per reaction') +\n ylim(c(0,100))+\n xlim(c(0,2500))+\n# scale_y_continuous(expand = c(0,0)) + \n# scale_x_continuous(expand = c(0,0)) + \n labs(color = 'Classification by RPM and number of reads') +\n geom_point(size = qpcr_results$size)\nqpcrplot_copies_microliter\n\nggsave(plot = qpcrplot_copies_microliter, filename = 'qpcr_graphs/qpcr_cmv_bglobin_quants_per_10ul.pdf', height = 7, width = 7, useDingbats=FALSE)\n\n\nqpcrplot_copies_ml_plasma<-ggplot(qpcr_results, aes(x=qpcr_results$bglobin_quantity.ml_plasma, y=qpcr_results$CMv_quantity.ml_plasma, color=qpcr_results$classification)) + \n theme_classic() +\n theme(legend.position= \"bottom\")+\n xlab('Beta-globin copies per mL Plasma') +\n ylab('CMV copies per mL plasma') +\n #ylim(c(0,100))+\n #xlim(c(0,100))+\n scale_y_log10() + \n scale_x_log10() + \n labs(color = 'Classification by RPM and number of reads') +\n geom_point(size = 3 )\nqpcrplot_copies_ml_plasma\n\nggsave(plot = qpcrplot_copies_ml_plasma, filename = 'qpcr_cmv_bglobin_quants_per_ml_plasma.pdf', height = 7, width = 7, useDingbats=FALSE)\n\nread_counts <- read.csv(\"~/Documents/vikas/NIPT/clip_removed/cmv_full/read_counts.csv\")\n\n\nread_counts$cmv_bglobin_ratio_ml<-NA\nfor(i in 1:nrow(qpcr_results)){ \n for(j in 1:nrow(read_counts)){\n if(grepl(as.character(qpcr_results$Sample.Name[i]), as.character(read_counts$sample[j]))){ \n read_counts$cmv_bglobin_ratio_ml[j]<-qpcr_results$CMv_quantity.ml_plasma[i]/qpcr_results$bglobin_quantity.ml_plasma[i]\n \n }\n }\n }\n\n\n\n\n\nggplot(cmv_all_positives, aes(x=cmv_all_positives$read_counts) + \n geom_histogram() + \n scale_x_log10(breaks=c(1,2,3,4,5,6,10,20,50,100,200,500,1000))) + \n geom_vline(aes(xintercept=15),color=\"blue\", linetype=\"dashed\", size=1) + \n theme(panel.background = element_blank())\n\n\n\n\n\n\n#figure 1b \n\n#controls<-(read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/controls_list.csv'))\n#to_remove<-which(controls$x %in% df_for_graph$sample)\n\n\nfigure_1b_plot<-ggplot(cmv_all_positives, aes(x=read_counts)) + \n geom_histogram(bins = 20, color= 'black') + \n scale_x_log10() + \n theme_classic() +\n xlab('number of reads') + \n ylab('Number of samples containing this many reads')+ \n scale_y_continuous(expand = c(0,0))\n #geom_vline(aes(xintercept=15),color=\"blue\", linetype=\"dashed\", size=1) \nfigure_1b_plot\nggsave(plot = figure_1b_plot, filename = 'qpcr_graphs/figure_1b_plot.pdf', height = 4, width = 4, useDingbats = FALSE)\n\n\nint_breaks <- function(x, n = 5) pretty(x, n)[pretty(x, n) %% 1 == 0] \n\n\ndf_for_graph<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/all_sample_data.csv')\nfigure_1b_plot_rpm<-ggplot(df_for_graph, aes(x=rpm, fill = classification)) + \n geom_histogram(bins = 45, color = 'black') + \n scale_x_log10() + \n #stat_bin(geom=\"text\", colour=\"white\", size=3.5, aes(label=)) +\n theme_classic() +\n theme(legend.position='none') + \n xlab('RPM of Fragments') + \n ylab('Number of samples containing this RPM') + \n scale_y_continuous(expand = c(0,0), breaks = int_breaks)\nfigure_1b_plot_rpm\nggsave(plot=figure_1b_plot_rpm, filename = 'figure_1b_fragment_rpm_plot.pdf', height= 4, width = 4, useDingbats=FALSE)\n\n\n\n\nfigure_1b_plot_rpm<-ggplot(df_for_graph, aes(x=count, fill = classification)) + \n geom_histogram(bins = 45, color='black') + \n scale_x_log10() + \n #scale_y_log10() +\n #stat_bin(geom=\"text\", colour=\"white\", size=3.5, aes(label=)) +\n theme_classic() +\n #theme(legend.position='none') + \n xlab('Number of fragments') + \n ylab('Number of samples containing this RPM') \n #scale_y_continuous(expand = c(0,0))\nfigure_1b_plot_rpm\nggsave(plot=figure_1b_plot_rpm, filename = 'qpcr_graphs/number_of_fragments.pdf', height= 4, width = 4, useDingbats=FALSE)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6830929517745972, "alphanum_fraction": 0.7051281929016113, "avg_line_length": 32.46308898925781, "blob_id": "9d5fa480d66ad0ffae9b4a8aceed42adfc65a3c8", "content_id": "2853cd23dee7ca6968d1985086cbe809fe437fd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 4992, "license_type": "no_license", "max_line_length": 143, "num_lines": 149, "path": "/scratch/cmv_coverage_graphs.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\n\nReadFasta<-function(file) {\n # Read the file line by line\n fasta<-readLines(file)\n # Identify header lines\n ind<-grep(\">\", fasta)\n # Identify the sequence lines\n s<-data.frame(ind=ind, from=ind+1, to=c((ind-1)[-1], length(fasta)))\n # Process sequence lines\n seqs<-rep(NA, length(ind))\n for(i in 1:length(ind)) {\n seqs[i]<-paste(fasta[s$from[i]:s$to[i]], collapse=\"\")\n }\n # Create a data frame \n DF<-data.frame(name=gsub(\">\", \"\", fasta[ind]), sequence=seqs)\n # Return the data frame as a result object from the function\n return(DF)\n}\n\nresequenced_verified_reads<-ReadFasta('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/resequenced_repeatmasked_7_removed.fasta')\n\n#coverage graph: \n\nresequenced_bam<-scanBam('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/cmv_duplicates_removed.bam')\n\nresequenced_verified_reads$name_trimmed<-NA\nfor(i in 1:nrow(resequenced_verified_reads)){ \n progress(i,nrow(resequenced_verified_reads))\n resequenced_verified_reads$name_trimmed[i]<-strsplit(as.character(resequenced_verified_reads$name[i]),'/')[[1]][1]\n}\n\n#shouldn't be making this unique values, pairs count as coverage \nto_remove<- which(duplicated(as.character(resequenced_verified_reads$name_trimmed)))\nunique_resequenced_verified_reads<-resequenced_verified_reads[-to_remove,]\n\n#resequenced_bam_names<-resequenced_bam[[1]]$qname\n# resequenced_bam_names_trimmed<-c()\n# for(i in 1:length(resequenced_bam_names)){ \n# progress(i,nrow(verified_reads))\n# resequenced_bam_names_trimmed <-append(resequenced_bam_names_trimmed,strsplit(as.character(resequenced_bam_names[i]),'/')[[1]][1])\n# }\n# \n\nresequenced_verified_reads$pos<-NA\n\n\nunique_resequenced_verified_reads$paired<-NA\nfor(i in 1:nrow(unique_resequenced_verified_reads)){ \n tempindex<-which(as.character(unique_resequenced_verified_reads$name_trimmed[i]) == resequenced_bam[[1]]$qname)\n if(is.na(tempindex[2])){ \n #print(index)\n unique_resequenced_verified_reads$paired[i]<-FALSE\n }\n else{\n print(tempindex)\n unique_resequenced_verified_reads$paired[i]<-TRUE\n }\n}\n\n\n\n\n\npositions_list<-c()\nread_id_list<-c()\nfor(i in 1:length(unique_resequenced_verified_reads$name_trimmed)){\n index<- which(as.character(unique_resequenced_verified_reads$name_trimmed[i]) == resequenced_bam[[1]]$qname)\n if(unique_resequenced_verified_reads$paired[i]==FALSE){ \n # print((index))\n positions_list<-append(positions_list,resequenced_bam[[1]]$pos[index])\n read_id_list<-append(read_id_list,resequenced_bam[[1]]$qname[index])\n }\n else{\n #print(index)\n # if(resequenced_bam[[1]]$isize[index[1]] > 0 ){ \n positions_list<-append(positions_list,resequenced_bam[[1]]$pos[index[1]])\n read_id_list<-append(read_id_list,resequenced_bam[[1]]$qname[index[1]])\n \n positions_list<-append(positions_list,resequenced_bam[[1]]$pos[index[2]])\n read_id_list<-append(read_id_list,resequenced_bam[[1]]$qname[index[2]])\n \n #}\n }\n \n}\n\npositions_with_read_ids<-data.frame(positions_list,read_id_list)\n\n\n\n# for(i in 1:nrow(resequenced_verified_reads)){ \n# resequenced_verified_reads$pos[i]<-resequenced_bam[[1]]$pos[match_indices[i]]\n# }\n# \nall_positions_covered<-c()\nall_positions_covered_readid<-c()\n\nfor(i in 1:length(positions_with_read_ids$positions_list)){ \n print(i)\n for(j in 1:36){\n temp<-(positions_with_read_ids$positions_list[i] + j)\n all_positions_covered<-append(all_positions_covered, temp)\n all_positions_covered_readid<-append(all_positions_covered_readid, as.character(positions_with_read_ids$read_id_list[i]))\n }\n}\n\n\n\n\nall_positions_covered_df<-data.frame(all_positions_covered, all_positions_covered_readid)\n\ncoverage_plot<-ggplot(all_positions_covered_df, aes(x = all_positions_covered_df$all_positions_covered)) + \n geom_freqpoly( bins = 50) + \n theme_classic() \ncoverage_plot\n\nggsave('cmv_coverage_plot.pdf', coverage_plot,width = 3, height = 3)\n\ncoverage_freq_table<-data.frame(table(all_positions_covered_df$all_positions_covered))\n\n\npositions_covered_by_freq<-ggplot(coverage_freq_table, aes(x = coverage_freq_table$Var1, y = coverage_freq_table$Freq, group = 1 )) + \n geom_line() + \n theme_classic() \n\npositions_covered_by_freq\n\n\ncoverage_plot<-ggplot(coverage_freq_table, aes(x = coverage_freq_table$Var1, y = coverage_freq_table$Freq, group = 1 )) + \n geom_freqpoly(bins = 50, stat = 'identity') + \n theme_classic() \ncoverage_plot\n\n#mapping = aes(x = x, y = y), stat = \"identity\"\n\nx<-ggplot(all_positions_covered_df) + \n geom_freqpoly(aes(x = all_positions_covered_df$all_positions_covered), binwidth = 1) + \n xlab('position') + \n ylab('depth') + \n scale_x_continuous(expand = c(0, 0), limits = c(0,235000), breaks = c(0,47000,94000,141000,188000,235000)) + \n theme_classic() +\n theme(axis.text.x = element_text(angle = 90, vjust = .1)) + \n scale_y_continuous(expand = c(0, 0)) \n #xlim(0,250000) + \nx\nggsave(plot=x, \"test.pdf\", height = 3, width = 5)\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.729520857334137, "alphanum_fraction": 0.7511591911315918, "avg_line_length": 42.13333511352539, "blob_id": "11ff0df6ddfac8cc849c58c6a804158cdde37278", "content_id": "abea9cec4df644df4b84c9d21a3a3fae2b5810ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 647, "license_type": "no_license", "max_line_length": 99, "num_lines": 15, "path": "/reproducibility/HHV-6/figure_5.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\nlibrary(Rsamtools)\nlibrary(svMisc)\nlibrary(seqinr)\nlibrary(reshape2)\nlibrary(cowplot)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6')\n\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/figure_5A.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/figure_5B.rdata')\nload(file='/Users/gerbix/Documents/vikas/NIPT/nipt_git_repo/reproducibility/HHV-6/figure_5C.rdata')\n\nplot_grid(p6,plot, cum_frequency ,labels = c('A','B','C'), ncol = 3, align = 'vh') \nggsave(plot = last_plot(), height = 3, width = 8, filename = 'figure_5.pdf')\n" }, { "alpha_fraction": 0.5743842124938965, "alphanum_fraction": 0.6719211935997009, "avg_line_length": 42.67647171020508, "blob_id": "52b5b6ebca6cd1923d377fcd818150572d01b15e", "content_id": "de90536877eec9e9fe1700df3aae425e69e27145", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3045, "license_type": "no_license", "max_line_length": 147, "num_lines": 68, "path": "/scratch/cmv_simulation/CMV_fragment_qPCR_simulation_v3.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\r\nlibrary(grid)\r\nlibrary(nplr)\r\nlibrary(scales)\r\nlibrary(gridExtra)\r\nlibrary(RColorBrewer)\r\nlibrary(cowplot)\r\ninstall.packages(\"tidyverse\")\r\nlibrary(tidyverse)\r\ninstall.packages(\"ggpubr\")\r\nlibrary(\"ggpubr\")\r\n\r\nsetwd(\"~/Documents/Manuscripts/CMV_cfDNA/newversion/simulation/\")\r\nSamplefrag <- read.csv(\"Sample_frag.csv\",stringsAsFactors=F)\r\nMultifrag <- read.csv(\"Multi_frag.csv\",stringsAsFactors=F)\r\n\r\nplayfrag <- gather(Samplefrag,\"X50\",\"X100\",\"X150\",\"X200\",\"X250\",\"X300\",\"X350\",key=\"amplicon\",value=\"counts\")\r\nplayfrag[playfrag==\"X50\"] <- 50\r\nplayfrag[playfrag==\"X100\"] <- 100\r\nplayfrag[playfrag==\"X150\"] <- 150\r\nplayfrag[playfrag==\"X200\"] <- 200\r\nplayfrag[playfrag==\"X250\"] <- 250\r\nplayfrag[playfrag==\"X300\"] <- 300\r\nplayfrag[playfrag==\"X350\"] <- 350\r\n\r\nplayfragMulti <- gather(Multifrag,\"X50\",\"X100\",\"X150\",\"X200\",\"X250\",\"X300\",\"X350\",key=\"amplicon\",value=\"counts\")\r\nplayfragMulti[playfragMulti==\"X50\"] <- 50\r\nplayfragMulti[playfragMulti==\"X100\"] <- 100\r\nplayfragMulti[playfragMulti==\"X150\"] <- 150\r\nplayfragMulti[playfragMulti==\"X200\"] <- 200\r\nplayfragMulti[playfragMulti==\"X250\"] <- 250\r\nplayfragMulti[playfragMulti==\"X300\"] <- 300\r\nplayfragMulti[playfragMulti==\"X350\"] <- 350\r\n\r\nplayfrag$amplicon <- as.factor(playfrag$amplicon)\r\nplayfrag$amplicon <- factor(playfrag$amplicon, levels = c(50,100,150,200,250,300,350))\r\nplayfragMulti$amplicon <- factor(playfragMulti$amplicon, levels = c(50,100,150,200,250,300,350))\r\n\r\n\r\nSample_plot <- ggplot(playfrag, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark blue\") + \r\n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + \r\n scale_y_continuous(breaks=c(0,100,200,300,400,500),limits=c(0, 560))\r\n\r\nMulti_plot <- ggplot(playfragMulti, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark green\") + \r\n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + \r\n scale_y_continuous(breaks=c(0,100,200,300,400,500),limits=c(0, 560)) \r\n\r\nfigure <- ggarrange(Sample_plot, Multi_plot,\r\n labels = c(\"A\", \"B\"),\r\n ncol = 2, nrow = 1)\r\nfigure\r\nggsave(\"Figure5_violinplot.pdf\",plot=figure,width=6.2,height=3) \r\n\r\n\r\nMulti_plot <- ggplot(playfragMulti, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark green\") + \r\n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + #scale_y_log10()\r\n scale_y_log10(breaks=c(10,30,100,300,1000),limits=c(5, 1000)) \r\n\r\nggplot(playfragMulti, aes(x=amplicon, y=counts),show.legend = FALSE) + geom_violin(fill=\"dark green\") + \r\n xlab(label=\"Amplicon length\") + ylab(label=\"Measured qPCR copies\") + theme_classic() + theme(aspect.ratio=1) +\r\n scale_y_log10(breaks=c(3,10,30,100,300,1000,3000,10000),labels=c(\"-2.00\",\"-1.50\",\"-1.00\",\"-0.50\",\"0.00\",\"0.50\",\"1.00\",\"1.50\"),limits=c(1, 10000))\r\n\r\n\r\n\r\nscale_x_discrete(labels=c(\"0.5\" = \"Dose 0.5\", \"1\" = \"Dose 1\",\r\n \"2\" = \"Dose 2\")\r\n\r\nggsave(\"logplot.pdf\",width=3,height=3) \r\n\r\n" }, { "alpha_fraction": 0.6116504669189453, "alphanum_fraction": 0.6278316974639893, "avg_line_length": 24.75, "blob_id": "540f2ce53a94683d8489dfc842e05400cac1bcb0", "content_id": "24acd067d49f91828f1835acda089601af486962", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 927, "license_type": "no_license", "max_line_length": 90, "num_lines": 36, "path": "/reproducibility/HHV-6/verified_bam.sh", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "suffix=$2\necho $suffix\niter=0\nwhile read line \ndo\n\tread_id=$(echo $line | cut -d , -f1 | cut -d - -f2)\n\thit_count=$(echo $line | cut -d , -f2)\n\tsample_name=$(echo $line | cut -d . -f1)\n\thit_count_trimmed=${hit_count%$'\\r'}\n\tif (( \"$hit_count_trimmed\"> \"10\")); then\n\t\ttemp_filename=$sample_name.$suffix\n\t\t#echo $temp_filename\n\t\t#if ((\"$iter\" == \"0\" )); then\n\t\t#\tsamtools view -H $temp_filename >> $sample_name.filtered.sam\n\t\t#fi\n\t#iter=$(expr $iter + 1)\n\t#USCOUNTER=$(expr $USCOUNTER + 1)\n\tsamtools view $temp_filename | grep -m 1 $read_id | head -n1 >> $sample_name.filtered.sam\n\tfi\ndone < $1 \n\nfor i in *.bam\ndo\n\tfile=$(echo $i | cut -d . -f1)\n\ttemp_filename=$file.filtered.sam\n\tsam_header=$(samtools view -H $i)\n\techo $temp_filename\n\techo -e \"$sam_header$(cat $temp_filename)\" > $temp_filename\n\t#echo $sam_header\n\t# echo \"task goes here\n\t# $(cat $tepm_filename)\" > $temp_filename\ndone\n\nmkdir sams \nmv *.sam sams/\nmv sams/ .. " }, { "alpha_fraction": 0.7059201598167419, "alphanum_fraction": 0.7235922813415527, "avg_line_length": 35.599998474121094, "blob_id": "b02e814ee3fbc03f98bdb0594877d8fbd33cd04a", "content_id": "413e44b43636a9d97c2c33dc42b444e39e1723f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 12449, "license_type": "no_license", "max_line_length": 146, "num_lines": 340, "path": "/scratch/blast_positive_parse.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "#rebuild\n#running after including full NT in blast db \n\nlibrary(Rsamtools)\nlibrary(seqinr)\nlibrary(svMisc)\nlibrary(Biostrings)\nlibrary(svMisc)\nlibrary(ggplot2)\nlibrary(xlsx)\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches')\nblasthitsfile<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/blast_hits.csv')\n#human_blasthitsfile<-read.csv('human_filtered_blast_hits.csv')\n#blasthitsfile<-read.csv('cmv_blast_hits.csv')\n#fastafile<-readDNAStringSet('/Users/gerbix/Documents/vikas/NIPT/21419_download/cmv_combined_masked.fasta')\nfastafile<-readDNAStringSet('/Users/gerbix/Documents/vikas/NIPT/31119_download/34_mismatches/cmv_combined_masked_n_removed.fasta')\ncolnames(blasthitsfile)[1]<-'readname'\ncolnames(blasthitsfile)[2]<-'count'\n\nread_counts_all<-read.csv2('/Users/gerbix/Documents/vikas/NIPT/31119_download/read_counts_all.csv', sep = ',')\nread_counts_all$sample<-as.character(read_counts_all$sample)\nfor(i in 1:length(read_counts_all$sample)){ \n read_counts_all$sample[i]<-strsplit(read_counts_all$sample[i],'[.]')[[1]][1]\n}\n#####\n\n\nblasthitsfile$readname<-as.character(blasthitsfile$readname)\nblasthitsfile$unique_identifier<-NA\nblasthitsfile$full_readname<-blasthitsfile$readname\nblasthitsfile$sample_id<-NA\nfor(i in 1:nrow(blasthitsfile)){\n blasthitsfile$unique_identifier[i]<-strsplit(blasthitsfile$readname[i],'[-]')[[1]][2]\n blasthitsfile$readname[i]<-strsplit(blasthitsfile$readname[i],'[-]')[[1]][1]\n }\nfor(i in 1:nrow(blasthitsfile)){\n blasthitsfile$sample_id[i]<-strsplit(blasthitsfile$readname[i],'[.]')[[1]][1]\n }\nblasthitsfile$fragments<-1\nfragment_indexes<-which(duplicated(blasthitsfile$unique_identifier))\nfor(i in 1:length(fragment_indexes)){ \n blasthitsfile$fragments[fragment_indexes[i]]<-0\n }\n\n\n\n#####\n\n#blank list for file in blast that have > 5 reads\npositivefiles <- c() \nblasthitsfile$blast_pass<-FALSE\nfor( i in 1:nrow(blasthitsfile)){ \n if(blasthitsfile$count[i] > 5) { \n #print(blasthitsfile$readname[i])\n positivefiles<-append(positivefiles, as.character(blasthitsfile$full_readname[i]))\n blasthitsfile$blast_pass[i]<-TRUE\n }\n}\n\n#makes csv of all blast verified reads\nnameslist<-c()\nlengthslist<- c()\nseqslist<-c()\n\n\nfor(i in 1:length(positivefiles)){ \n progress(i, length(positivefiles))\n index=which(positivefiles[i]==names(fastafile))\n lengthslist = append(lengthslist, nchar(paste(fastafile[index])))\n nameslist<-append(nameslist,names(fastafile[index]))\n seqslist<-append(seqslist,paste(fastafile[index]))\n }\nseqdata<-data.frame(nameslist,seqslist,lengthslist)\nwrite.csv(seqdata,'blast_positive_sequence_info.csv')\n\n\npositivestrimmed <- c()\nfor (word in positivefiles) { \n word <- strsplit(word, '.sam')[[1]][1]\n positivestrimmed <- append(positivestrimmed, word )\n}\nunique_positivestrimmed<-unique(positivestrimmed)\n\n######################\nuniquefiles = c()\npositvereads= c()\nintermediatepositives = c()\nintermediatepositives_reads = c()\npositives<-c()\npositivereads<-c()\nweak_positives<-c()\nweak_positives_reads<-c()\n\n\n\n\nunique_file_list<-unique(blasthitsfile$sample_id)\nfor (i in 1:length(unique_file_list)) { \n print(100*i/length(unique_file_list))\n count = 0\n identifier = unique_file_list[i]\n for ( j in 1:length(blasthitsfile$sample_id)) { \n if(blasthitsfile$sample_id[j] == unique_file_list[i] && blasthitsfile$blast_pass[j]==TRUE) { \n #print(i)\n #count = count + 1 \n count = count + blasthitsfile$fragments[j]\n #count = count + 1 + blasthitsfile$fragments[tempfragmentcount]\n #count = count + 1\n #print(blasthitsfile$fragments[tempfragmentcount])\n #print(tempfragmentcount)\n #print(identifier)\n tempidentifier<-blasthitsfile$sample_id[j]\n }\n }\n #print(identifier)\n # if( count > 15){ \n # print('whatthefuck')\n # }\n if( count > 2) { \n uniquefiles = append(uniquefiles,tempidentifier)\n }\n if(count < 15 && count >1) { \n #print(identifier)\n intermediatepositives = append(intermediatepositives , tempidentifier)\n intermediatepositives_reads = append(intermediatepositives_reads , count)\n }\n if(count > 15) { \n #print(identifier)\n positives = append(positives , tempidentifier)\n positivereads = append(positivereads , count)\n }\n if(count==1){ \n weak_positives = append(weak_positives, tempidentifier)\n weak_positives_reads= append(weak_positives_reads, count)\n }\n}\n\n\n\n\n\n\n#######################\n#rpkm and rpm calculation for weak positives (1 read)\nweakpositivesdf<-data.frame(weak_positives,weak_positives_reads)\nweakpositivesdf <- weakpositivesdf[!duplicated(weakpositivesdf$weak_positives), ]\nweakpositivesdf$rpkm<-NA\nweakpositivesdf$read_counts<-NA\nweakpositivesdf$rpm<-NA\nfor(i in 1:nrow(weakpositivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if(read_counts_all$sample[j]==as.character(weakpositivesdf$weak_positives[i])){ \n weakpositivesdf$rpkm[i]<-(weakpositivesdf$weak_positives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1000000))\n print((weakpositivesdf$weak_positives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n weakpositivesdf$read_counts[i]<-read_counts_all$count[j]\n weakpositivesdf$rpm[i]<-((weakpositivesdf$weak_positives_reads[i])*1e6)/(read_counts_all$count[j])\n\n }\n }\n}\n\n#rpkm and rpm calculation for intermediate positives (between 2-15 reads)\nintermediatepositivesdf <- data.frame(intermediatepositives, intermediatepositives_reads)\nintermediatepositivesdf <- intermediatepositivesdf[!duplicated(intermediatepositivesdf$intermediatepositives), ]\nintermediatepositivesdf$rpkm<-NA\nintermediatepositivesdf$read_counts<-NA\nintermediatepositivesdf$rpm<-NA\nread_counts_all$sample<-as.character(read_counts_all$sample)\nfor(i in 1:nrow(intermediatepositivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if(read_counts_all$sample[j]==as.character(intermediatepositivesdf$intermediatepositives[i])){ \n intermediatepositivesdf$rpkm[i]<-(intermediatepositivesdf$intermediatepositives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1000000))\n print((intermediatepositivesdf$intermediatepositives_reads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n intermediatepositivesdf$read_counts[i]<-read_counts_all$count[j]\n intermediatepositivesdf$rpm[i]<-((intermediatepositivesdf$intermediatepositives_reads[i])*1e6)/(read_counts_all$count[j])\n \n }\n }\n}\n\n\n\n\n#rpkm and rpm calculation for strong positives (over 15 reads)\npositivesdf<-data.frame(positives,positivereads)\npositivesdf <- positivesdf[!duplicated(positivesdf$positives), ]\npositivesdf$rpkm<-NA\npositivesdf$read_counts<-NA\npositivesdf$rpm<-NA\nfor(i in 1:nrow(positivesdf)){ \n for( j in 1:nrow(read_counts_all)){ \n if((strsplit(read_counts_all$sample[j],'[.]')[[1]][1])==as.character(positivesdf$positives[i])){ \n positivesdf$rpkm[i]<-((positivesdf$positivereads[i])/((235646/1000)*(read_counts_all$count[j]/1000000)))\n print((positivesdf$positivereads[i])/((235646/1000)*(read_counts_all$count[j]/1e9)))\n positivesdf$read_counts[i]<-read_counts_all$count[j]\n positivesdf$rpm[i]<-((positivesdf$positivereads[i])*1e6)/(read_counts_all$count[j])\n }\n }\n}\n\nactuallyunique <- unique(uniquefiles)\nwrite.csv(actuallyunique, 'other_cmv_positives.csv')\nwrite.csv(weakpositivesdf,'cmv_weak_positives_table.csv')\nwrite.csv(intermediatepositivesdf, 'cmv_intermediate_positives_table.csv')\nwrite.csv(positivesdf, 'cmv_strong_positives_table.csv')\n#cmv_all_positives_table<-rbind(positivesdf,intermediatepositivesdf,weakpositivesdf)\n\n\n\n\n\n#graph to find a nice arbitrary rpkm cutoff\npositivesdf$classification<-'strong positives'\nintermediatepositivesdf$classification<-'intermediate positives'\nweakpositivesdf$classification<-'weak positives'\n\ngraph_weakdf<-weakpositivesdf\ncolnames(graph_weakdf)[1]<-'sample'\ncolnames(graph_weakdf)[2]<-'count'\n\ngraph_positivesdf<-positivesdf\ncolnames(graph_positivesdf)[1]<-'sample'\ncolnames(graph_positivesdf)[2]<-'count'\n\ngraph_intermediatesdf<-intermediatepositivesdf\ncolnames(graph_intermediatesdf)[1]<-'sample'\ncolnames(graph_intermediatesdf)[2]<-'count'\n\n\ndf_for_graph<-rbind(graph_positivesdf,graph_intermediatesdf,graph_weakdf)\n#df_for_graph<-mapply(c,positivesdf,intermediatepositivesdf)\n\nfor(i in 1:nrow(df_for_graph)){ \n if(df_for_graph$rpm[i] > .3){ \n df_for_graph$classification[i]<-'strong positive'\n }\n if(df_for_graph$rpm[i] < .3){ \n df_for_graph$classification[i]<-'intermediate positive'\n }\n }\n\nwrite.csv(df_for_graph,'all_sample_data.csv')\n\n\n\nrpkm_plot<-ggplot(df_for_graph, aes(x=classification, y=rpkm)) + \n geom_hline(yintercept = min(df_for_graph$rpkm[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$rpkm[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n geom_point()\nrpkm_plot\nggsave('CMV_logrpkm_by_classification.pdf', plot = last_plot())\n\nreads_plot<-ggplot(df_for_graph, aes(x=classification, y=count)) + \n geom_point() + \n geom_hline(yintercept = min(df_for_graph$count[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$count[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n ylab('# reads mapping to CMV')\nreads_plot\nggsave('CMV_logcounts_by_classification.pdf', plot = last_plot())\n\nwrite.xlsx(df_for_graph,'rpkm_values.xlsx')\n\nrpkm_by_number_of_reads_plot<-ggplot(df_for_graph, aes(x=read_counts, y=rpkm, color=classification)) + \n geom_hline(yintercept = min(df_for_graph$rpkm[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$rpkm[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n xlab('number of reads in sample') +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n geom_point()\nrpkm_by_number_of_reads_plot\nggsave('CMV_logrpkm_by_number_of_reads.pdf', plot = last_plot())\n\n\n\n\n##same graphs but now using rpm\n\n\nrpm_plot<-ggplot(df_for_graph, aes(x=classification, y=rpm)) + \n geom_hline(yintercept = min(df_for_graph$rpm[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$rpm[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n ylab('rpm of reads mapping to CMV') +\n geom_point()\nrpm_plot\nggsave('CMV_logrpm_by_classification.pdf', plot = last_plot())\n\nreads_plot<-ggplot(df_for_graph, aes(x=classification, y=count)) + \n geom_point() + \n geom_hline(yintercept = min(df_for_graph$count[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$count[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n ylab('# reads mapping to CMV')\nreads_plot\nggsave('CMV_logcounts_by_classification.pdf', plot = last_plot())\n\nwrite.xlsx(df_for_graph,'rpkm_values.xlsx')\n\nrpm_by_number_of_reads_plot<-ggplot(df_for_graph, aes(x=read_counts, y=rpm, color=classification)) + \n geom_hline(yintercept = min(df_for_graph$rpm[df_for_graph$classification=='strong positives'])) + \n geom_hline(yintercept = max(df_for_graph$rpm[df_for_graph$classification=='intermediate positives']), linetype = 'dashed') + \n scale_y_continuous(trans = 'log10') +\n xlab('number of reads in sample') +\n ylab('rpm of reads mapping to CMV') +\n theme(axis.text.x = element_text(angle = 90, hjust = 1)) +\n geom_point()\nrpm_by_number_of_reads_plot\nggsave('CMV_logrpm_by_number_of_reads.pdf', plot = last_plot())\n\n\n\n\n\n\n\n\n\n\n\n##filling in qpcr data for the all_data spreadsheet\n\nedited_all_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/21419_download/all_sample_data.csv', header = TRUE)\nedited_all_data$sample<-as.character(edited_all_data$sample)\nqpcr_results<-read_excel(\"qpcr_results.xls\", skip = 1)\nqpcr_results$`Sample Name`<-gsub(pattern = '-',replacement = '',x=qpcr_results$`Sample Name`)\n\nfor(i in 1:nrow(qpcr_results)){ \n for(j in 1:nrow(edited_all_data)){ \n if(grepl(qpcr_results$`Sample Name`[i],edited_all_data$sample[j])){\n edited_all_data$cmv.quant[j]<-qpcr_results$`Quantity(10UL DNA)`[i]\n edited_all_data$bglobin.quant[j]<-qpcr_results$`Quantity(10UL DNA)__1`[i]\n }\n \n }\n }\n\nwrite.csv(edited_all_data, 'all_data_combined.csv')\n\n\n\n\n\n" }, { "alpha_fraction": 0.7262784242630005, "alphanum_fraction": 0.7434229850769043, "avg_line_length": 37.375, "blob_id": "b439ace1b1e1d2cc013586952e95c02dc1fef01f", "content_id": "cb84ed6575ce14f71aad7e023bb4a6ffd76486a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3383, "license_type": "no_license", "max_line_length": 152, "num_lines": 88, "path": "/scratch/cmv_duplication_compare.r", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(ggplot2)\n\n\n\nrepeatmasked_fasta<-read.fasta('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/resequenced_repeatmasked_7_removed.fasta')\nfasta_IDs<-names(repeatmasked_fasta)\n\nfasta_IDs_trimmed<-c()\nfor( i in 1:length(fasta_IDs)){\n progress(i,length(fasta_IDs))\n fasta_IDs_trimmed<-append(fasta_IDs_trimmed,strsplit(fasta_IDs, '/')[[i]][1])\n} \nfasta_IDs_deduplicated<-fasta_IDs_trimmed[-(which(duplicated(fasta_IDs_trimmed)))]\n\n#CMV_blast_hits_deduplicated<-CMV_blast_hits[-(which(duplicated(CMV_blast_hits$read_ID))),]\n\n\nisize<-c()\nread_id<-c()\nsample<-c()\n\ntemp_bam<-scanBam('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/cmv_just_duplicates.bam')\nall_bam_read_IDs<-temp_bam[[1]]$qname \nmatches<-c()\nfor(j in 1:length(fasta_IDs_deduplicated)){ \n print(100 * j / length(fasta_IDs_deduplicated))\n for(k in 1:length(all_bam_read_IDs)){\n if(grepl( fasta_IDs_deduplicated[j], all_bam_read_IDs[k])) { \n isize<-append(isize, temp_bam[[1]]$isize[k])\n read_id<-append(read_id, paste(temp_bam[[1]]$qname[k],'.1'))\n sample<-append(sample, 'CMV')\n }\n }\n}\n\nCMV_matched<-data.frame(sample, read_id, isize)\nCMV_matched<-CMV_matched[CMV_matched$isize>0,]\nCMV_matched<-CMV_matched[CMV_matched$isize<500,]\n\nCMV_matched<-CMV_matched[complete.cases(CMV_matched$isize),]\n\nCMV_frequencies<-data.frame(table(CMV_matched$isize))\ncolnames(CMV_frequencies)<-(c('isize','freq'))\nCMV_frequencies$percent<- 100 * ( as.numeric(as.character(CMV_frequencies$freq)) / (sum(CMV_frequencies$freq))) \nCMV_frequencies$type<-'CMV'\n\n#calculating CMV median\nCMV_isize_exanded<-rep(CMV_frequencies$isize, CMV_frequencies$freq) \nCMV_isize_exanded<-CMV_isize_exanded[as.numeric(as.character(CMV_isize_exanded)) < 500]\nCMV_median<-median(as.numeric(as.character(CMV_isize_exanded)))\nCMV_frequencies$type<-'duplicates_only'\n\n\n\nwrite.csv(CMV_matched,('cmv_duplicates_read_data.csv'))\n\ncmv_deduplicated_read_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/cmv_duplicates_removed_read_data.csv')\ncmv_deduplicated<-read.csv('/Users/gerbix/Documents/vikas/NIPT/31119_download/resequenced/deduplicating/cmv_duplicates_removed_insert_sizes.csv')\ncmv_deduplicated$type<-'deduplicated'\ncmv_just_duplicates<-CMV_frequencies\n\n\ncmv_deduplicated$X<-NULL\nall_cmv<-rbind(cmv_deduplicated, CMV_frequencies)\n\n\n\nCMV_plot<-ggplot(all_cmv, aes( x = as.numeric(all_cmv$isize) , y = all_cmv$percent, color = all_cmv$type)) + \n geom_vline(xintercept = 143, color = 'blue') + \n theme_classic() + \n xlim(c(0,500)) +\n xlab('insert size') + \n ylab('percent') +\n geom_line() \nCMV_plot\nggsave(plot = CMV_plot, 'cmv_deduplicated_vs_duplicates.pdf', width = 8, height =8)\n\n#median calculations\n#deduplicated cmv\nCMV_deduplicated_isize_exanded<-rep(cmv_deduplicated$isize, cmv_deduplicated$freq) \nCMV_deduplicated_isize_exanded<-CMV_deduplicated_isize_exanded[as.numeric(as.character(CMV_deduplicated_isize_exanded)) < 500]\nCMV_deduplicated_median<-median(as.numeric(as.character(CMV_deduplicated_isize_exanded)))\n\n#cmv duplicate reads \n\nCMV_duplicates_isize_exanded<-rep(CMV_frequencies$isize, CMV_frequencies$freq) \nCMV_duplicates_isize_exanded<-CMV_duplicates_isize_exanded[as.numeric(as.character(CMV_duplicates_isize_exanded)) < 500]\nCMV_duplicates_median<-median(as.numeric(as.character(CMV_duplicates_isize_exanded)))\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6754139065742493, "alphanum_fraction": 0.6988441348075867, "avg_line_length": 34.522220611572266, "blob_id": "76668a96daec85fbca15533cb4bc24ffc89647a3", "content_id": "294f73ba4ab48b6eff80bc0d371b1b952fe475b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 3201, "license_type": "no_license", "max_line_length": 151, "num_lines": 90, "path": "/scratch/cmv_percent_vs_qpcr_cmv_load_updated.R", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "library(Rsamtools)\nlibrary(Biostrings)\nlibrary(seqinr)\nlibrary(ggplot2)\nlibrary(svMisc)\nlibrary(xlsx)\nlibrary(Rsamtools)\n\n\nsetwd('/Users/gerbix/Documents/vikas/NIPT/31119_download')\n\nqpcr_results<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_results.xls', sheetIndex =3)\nsample_read_data<-read.csv('/Users/gerbix/Documents/vikas/NIPT/all_deduplicated/all_sample_data.csv')\n\ncombined<-qpcr_results[qpcr_results$CMV_Quantity.10UL.DNA.>0,]\ncombined_names<-as.character(combined$Sample.Name)\n\n\nfor(i in 1:length(combined_names)){ \n if(grepl('-', combined_names[i])){ \n combined_names[i]<-strsplit(combined_names[i], '-')[[1]][1]\n }\n }\n\nfor(i in 1:length(combined_names)) { \n for(j in 1:length(sample_read_data)){ \n if( grepl(combined_names[i], sample_read_data$sample[j])){ \n print(combined_names[i])\n }\n }\n}\n\n\ndata<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update/6131_cmv_percent_vs_qpcr_load.xlsx', sheetIndex = 1)\n\n#deduplicated read counts version\ndata<-read.xlsx('/Users/gerbix/Documents/vikas/NIPT/31119_download/qpcr_graph_update/82419_deduplicated_cmv_percent_vs_qpcr_load.xlsx', sheetIndex = 1)\n\n\ndata$percent<-data$count/data$read_counts\n\ncmv_percent_vs_viral_laod<-ggplot(data, aes(x = data$CMv_quantity.ml_plasma, y= data$percent, color = data$classification.1)) + \n geom_point() + \n theme_classic() + \n theme(legend.position=\"none\") + \n scale_y_log10() + \n scale_x_log10() + \n xlab('CMV copies/ml by qPCR') + \n ylab('Percent of total reads mapping to CMV') \ncmv_percent_vs_viral_laod\n\nggsave('cmv_percent_vs_viral_load.pdf', cmv_percent_vs_viral_laod, width = 3, height = 3)\n\n\n#testing\n\ncmv_percent_vs_viral_laod_regression<-ggplot(data, aes(x = data$CMv_quantity.ml_plasma, y= data$percent)) + \n geom_point(aes( color = data$classification.1)) + \n theme_classic() + \n theme(legend.position=\"none\") + \n scale_y_log10() + \n scale_x_log10() + \n xlab('CMV copies/ml by qPCR') + \n ylab('Percent of total reads mapping to CMV') + \n geom_smooth(method = \"lm\", se = FALSE)\ncmv_percent_vs_viral_laod_regression\nggsave('percent reads mapping to cmv with regression line.pdf' ,cmv_percent_vs_viral_laod_regression, width = 3, height = 3)\n\nfit1 <- lm(data$percent ~ data$CMv_quantity.ml_plasma)\n\n\nfit1 <- lm((data$CMv_quantity.ml_plasma) ~ (data$rpm ), data = data)\nlibrary(ggpmisc)\n\n#with rpm\ncmv_percent_vs_viral_laod_regression<-ggplot(data, aes(x = data$CMv_quantity.ml_plasma, y= data$rpm)) + \n geom_point(aes( color = data$classification.1)) + \n theme_classic() + \n theme(legend.position=\"none\") + \n scale_y_log10() + \n scale_x_log10(limits = c(NA, 1000)) +\n xlab('CMV copies/ml by qPCR') + \n ylab('RPM of total reads mapping to CMV') + \n geom_smooth(method = \"lm\", se = FALSE) + \n stat_poly_eq(aes(label = paste(..rr.label.., sep = \"~~~\")), formula = fit1, parse = TRUE, size = 5) \n\n #geom_abline(slope = fit1$coefficients[2], intercept = fit1$coefficients[1])\ncmv_percent_vs_viral_laod_regression\nsetwd('/Users/gerbix/Documents/vikas/NIPT/all_deduplicated')\nggsave('rpm reads mapping to cmv with regression line_v2.pdf' ,cmv_percent_vs_viral_laod_regression, width = 3, height = 3)\n\n\n\n\n" }, { "alpha_fraction": 0.42162615060806274, "alphanum_fraction": 0.457669734954834, "avg_line_length": 29.13157844543457, "blob_id": "578579f74243c64ba6cb0c1a5467b22e1e20d298", "content_id": "7ecace920551074bb6f5d0779fa617aa01d62f53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1193, "license_type": "no_license", "max_line_length": 103, "num_lines": 38, "path": "/reproducibility/cmv_simulation/Simulation.py", "repo_name": "vpeddu/CMV-NIPT", "src_encoding": "UTF-8", "text": "import random\r\noutput = open(\"MultiSampleRead3Probe350_alex.txt\", \"w\")\r\n\r\nprobelen = 350\r\nprobestart = random.randint(1, 235149 - probelen)\r\nprobestop = probestart + probelen - 1\r\n\r\nfor a in range (0, 100):\r\n print(str(a))\r\n input1 = open(\"Sample2Read3_alex.txt\", \"r\") #1st column read length, 2nd colum number of reads\r\n\r\n readstart = []\r\n readstop = []\r\n readcount = 0\r\n\r\n for line in input1:\r\n line = line.strip()\r\n line = line.split(\"\\t\")\r\n count = int(line[1])\r\n for x in range (0, count):\r\n z = 235149 - int(line[0])\r\n y = random.randint(1, z)\r\n readstart.append(y)\r\n y = y + int(line[0]) - 1\r\n readstop.append(y)\r\n readcount = readcount + 1\r\n\r\n input1.close()\r\n\r\n load = 0 \r\n\r\n for x in range (0, readcount):\r\n if probestart >= readstart[x] and probestop <= readstop[x]:\r\n load = load + 1\r\n output.write(str(load))\r\n output.write(\"\\n\")\r\n\r\noutput.close() \r\n" } ]
45
rogerzadi/Unsupervised_client_clustering
https://github.com/rogerzadi/Unsupervised_client_clustering
448926272c8d288a347f298ac3b51dc610e9bfa2
6ac36fe9fdd71e037a3e0e95e4a0108d3752cd45
17210227fcce3776896b6b257d48ce1402ccf320
refs/heads/master
2020-11-25T03:22:14.594301
2019-12-27T22:44:04
2019-12-27T22:44:04
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7900616526603699, "alphanum_fraction": 0.7935284972190857, "avg_line_length": 62.26829147338867, "blob_id": "e787649e5d405dfb6a3d389e1b8ca51e8aff60e1", "content_id": "f094c374edb2a80325cc21607c9ac3711da4c75e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2617, "license_type": "no_license", "max_line_length": 439, "num_lines": 41, "path": "/README.md", "repo_name": "rogerzadi/Unsupervised_client_clustering", "src_encoding": "UTF-8", "text": "![Iron Hack](https://github.com/rogerzadi/ModeloSupervivencia/blob/master/images/ironhack.png)\n# Clusterización de clientes Retail\nEste es un modelo que se utiliza para alimentar Crece la cual es un proyecto sobre una plataforma la cual ayuda a generar insights básicos así como basados en machine learning para tiendas. **Este es el apartado de Machine Learning para la plataforma**\n\n### Intro \nSe creo un modelo de clusterización no supervisado, basandonos en las ventas de una tienda se crearon diferentes clusters con diferentes caracteristicas, esto para generar una estrategia de ventas mas solida.\n\n### Modelo Utilizado\n- K-Means\n- Se utiliza PCA para disminuir dimensiones \n\n### Modelo\n\nEl modelo tiene como entrada:\n- Registro de ventas de una tienda\n\nLa cual contiene Timestamp, Transacción, Item, Categoria, Precio\n\nSe limpia y transforma los tipos de datos, observamos cuales son las variables categoricas para sacar one-hot-code (dummies) para asi poder manegar estos datos, esto se hace en base a la columna de categorías y a la suma de los Items pertenecientes a cada categoría, atravez de la libreria sklearn utilizamos el metodo K-means el cual se le indica que seran 3 clusters *en el ejemplo se ven 4 clusters pero en la plataforma se utilizan 3* \n\nel resultado se puede apreciar gráficamente así, sin embargo, los outputs del sistema serían datos los cuales utiliza el Web developer para dibujar sus gráficas:\n\n### Tabla día\n\n![Gráfica por día](https://github.com/rogerzadi/Clusterizacion_no_supervisada_clientes/blob/master/images/cluster_hora.JPG)\n\nEn esta tabla podemos ver a que dia van mas los diferentes tipos de clientes, podemos observar que en general los sabados son los mas visitados o por ejemplo los clientes que van mas los viernes son los del primer cluster \n\n### Tabla Hora\n\n![Gráfica por día](https://github.com/rogerzadi/Clusterizacion_no_supervisada_clientes/blob/master/images/cluster_dia.JPG)\n\nPodemos ver a que hora van mas los distintos tipos de clientes, por ejemplo podemos enfocar o personalizar todas nuestras estratégias de venta a los clientes tipo 2 a las 10 am ya que son mas del 90% de los clientes los que van a esa hora \n\n### Items más comprados\n\n![Gráfica por día](https://github.com/rogerzadi/Clusterizacion_no_supervisada_clientes/blob/master/images/mas_compra.JPG)\n\nEstos son los Items que mas compran los distintos tipos de clientes, por ejemplo, podemos dar un descuento a la Frittata a los clientes tipo 1 en la compra de un café.\n\nPodemos ver la Plataforma creada por Eduardo Chavez Colorado en este [link.](http://crecemass.herokuapp.com/metricas)\n\n\n" }, { "alpha_fraction": 0.6354116797447205, "alphanum_fraction": 0.639695405960083, "avg_line_length": 42.79166793823242, "blob_id": "b9646817011bfe677de77c40cfe247111dbb97f8", "content_id": "b192550f15a971c9c623af0e258f9eb56ff23c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2101, "license_type": "no_license", "max_line_length": 120, "num_lines": 48, "path": "/Pipeline.py", "repo_name": "rogerzadi/Unsupervised_client_clustering", "src_encoding": "UTF-8", "text": "import pandas as pd\nclass clusterization:\n\n def __init__(self, data):\n self.data = data\n self.groupdum(data)\n\n def groupdum(self, data):\n data['DateTime'] = pd.to_datetime(data['DateTime'], format='%Y-%m-%d %H:%M:%S')\n dummies = pd.get_dummies(data.category, drop_first=False)\n piped = pd.concat([data, dummies], axis=1)\n self.group(piped)\n\n def group(self, piped):\n self.piped_group = piped.groupby(['DateTime', 'Transaction']).sum()\n self.piped_group.reset_index(level='DateTime', inplace=True)\n self.piped_group['day'] = self.piped_group.DateTime.dt.day_name()\n self.piped_group['hour'] = self.piped_group.DateTime.dt.hour\n piped_dummy = pd.get_dummies(data=self.piped_group, columns=['day']).drop('DateTime', axis=1)\n self.pca(piped_dummy)\n\n def pca(self, piped_dummy):\n from sklearn.decomposition import PCA\n pca = PCA(n_components=4).fit_transform(piped_dummy)\n pc_df = pd.DataFrame(pca, columns=[f'pc_{i + 1}' for i in range(4)])\n self.pc_df = pc_df\n self.cluster(pc_df)\n\n def cluster(self, pc_df):\n from sklearn.cluster import KMeans\n kmeans = KMeans(n_clusters=4).fit(pc_df)\n self.outputgroup(kmeans, pc_df)\n\n def outputgroup(self, kmeans, pc_df):\n import seaborn as sns\n cm = sns.light_palette('green', as_cmap=True)\n self.piped_group['label'] = kmeans.predict(pc_df)\n piped_merge = pipe.merge(self.piped_group.reset_index()[['label', 'Transaction']], on='Transaction', how='left')\n print(pd.crosstab(self.piped_group.hour, self.piped_group.label).style.background_gradient(cmap=cm))\n print(pd.crosstab(self.piped_group.day, self.piped_group.label).style.background_gradient(cmap=cm))\n self.outputbest(piped_merge)\n\n def outputbest(self, piped_merge):\n print(piped_merge.groupby('label')['Item'].value_counts().to_frame('counts').reset_index().set_index(\n 'Item').groupby('label')['counts'].nlargest(10))\n\npipe=pd.read_csv(\"muestra6dias.csv\")\nclusterization(pipe)" } ]
2
aarcher/python-general
https://github.com/aarcher/python-general
87c149469bac37a7933bf6dab4e3a90b42834954
c7cce650310266c0fae761ee619b69b8c74c3ded
dfefa27301c67deb7d4f8b19c66ad96f73ac2305
refs/heads/master
2018-03-07T13:41:34.401339
2016-09-11T00:16:26
2016-09-11T00:16:26
65,872,785
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.589090883731842, "alphanum_fraction": 0.6218181848526001, "avg_line_length": 21.91666603088379, "blob_id": "223afab054530e7d98aaa945c0d43af0dd89c6e1", "content_id": "9a6847345cc89010db2c63f7251855aa4f43fff5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 57, "num_lines": 24, "path": "/Common/MultiListComp/Unittest_MListComp.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Unit test framework for the MultiListcomp.py module'''\n\nimport unittest\n\n#Own imports:\nfrom MultiListComp import dot_product\n\nclass TestDotProduct(unittest.TestCase):\n '''Test for the dot product'''\n def setUp(self):\n '''Set up for this test group'''\n self.v1 = [1,2,3,4,5]\n self.v2 = [6,7,8,9,10]\n\n def tearDown(self):\n '''Tear down'''\n pass\n\n def test_dot_product(self):\n '''Simple dot product test'''\n self.assertEqual(130, dot_product(self.v1,self.v2))\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6906779408454895, "alphanum_fraction": 0.6906779408454895, "avg_line_length": 22.600000381469727, "blob_id": "6beb5dd3ece61735589ceee9fa769ea85c8f9276", "content_id": "e2ab344e69fc0e9be8183f1279893f9f8472d573", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 236, "license_type": "no_license", "max_line_length": 46, "num_lines": 10, "path": "/Inheritance/DerivedClass.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "from BaseClass import BaseClass\n\nclass DerivedClass(BaseClass):\n\n def __init__(self):\n BaseClass.__init__(self) \n super(DerivedClass, self)._construction()\n\n def _construction(self):\n print\"Constructing derived class.\"\n" }, { "alpha_fraction": 0.45121949911117554, "alphanum_fraction": 0.5162601470947266, "avg_line_length": 26.33333396911621, "blob_id": "bd48f6219726f542ced263a9943d34f90567386b", "content_id": "954ccccc11398fd0241df5664cfe62d41cd5f433", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 492, "license_type": "no_license", "max_line_length": 68, "num_lines": 18, "path": "/Perceptron/Driver_Perceptron.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Driver for the perceptron class. This module handles all the file\n input and output.'''\n\n\nfrom Perceptron import Perceptron\ndef main():\n '''Main driver module.'''\n training_data = [ ( (1.0,0.0,0.0), 1.0),\\\n ( (1.0,1.0,0.0), 1.0),\\\n ( (1.0,0.0,1.0), 1.0),\\\n ( (1.0,1.0,1.0), 0.0) ] \n\n perceptron = Perceptron(training_data)\n perceptron.retrieve_training_data() \n perceptron.run()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6739130616188049, "alphanum_fraction": 0.6778656244277954, "avg_line_length": 24.299999237060547, "blob_id": "18788e18a69c8f1b80326f095cb7ce499c80f5a2", "content_id": "367feb0f7fd9f0bb606d0a1f5f51be3b9f5e81e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1012, "license_type": "no_license", "max_line_length": 65, "num_lines": 40, "path": "/ThreadLocks/ThreadLocks.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import threading\n\nclass FetchUrls(threading.Thread):\n '''\n Simple example of a class which uses a simple\n lock for thread control.\n The point of this example is to show how the lock must be out\n of the scope of the calling function.\n '''\n\n\n# Note that the lock is taken from outside the scope of the class\n# and so it will not be released when the class is destroyed.\n def __init__(self, lock):\n threading.Thread.__init__(self)\n self.lock = lock\n\n def run(self):\n self.lock.acquire()\n print 'hello'\n# Comment out the following line in order to\n# block the second thread from running.\n self.lock.release()\n\ndef main():\n '''\n main() function generates the lock and passes it on to the \n threads.\n '''\n# Lock at this scope will work\n# Remember that reference semantics are the rule in Python \n# This means that the lock is in the right scope.\n lock = threading.Lock()\n t1 = FetchUrls(lock)\n t1.start()\n t2 = FetchUrls(lock)\n t2.start()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6146993041038513, "alphanum_fraction": 0.6169264912605286, "avg_line_length": 15.55555534362793, "blob_id": "4afc23071b1ab32ca814e843e0e80e90a206b39d", "content_id": "7999f54b208727d2999801ec28b7425a00949d20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 449, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/ThreadTest/ThreadTest.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import Tkinter\nimport threading\n\n\nclass ThreadTest():\n '''\n Class used to test threading in python.\n '''\n\n def __init__(self,anArgument):\n self.arg = anArgument\n self.start()\n \n def start(self):\n print 'In ThreadTest.start():'\n print 'Argument: '\n print self.arg\n\n\n\ndef main():\n aThread = threading.Thread(group=None, target=ThreadTest, args=[3])\n aThread.start()\n aThread.join()\n\nif __name__ == \"__main__\":\n main()\n\n\n" }, { "alpha_fraction": 0.6227351427078247, "alphanum_fraction": 0.6322260499000549, "avg_line_length": 38.623931884765625, "blob_id": "bbf82641a1713113373c5b995e1739c438fdfb1f", "content_id": "febed6f2282e8da41fb24c92051c9637daa1ead8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4636, "license_type": "no_license", "max_line_length": 87, "num_lines": 117, "path": "/Perceptron/Unittest_Perceptron.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Unit test for the perceptron class'''\nimport unittest\n\n#Own imports\nfrom Perceptron import Perceptron \n\nclass TestPerceptron(unittest.TestCase):\n '''Main class for testing the perceptron'''\n\n def setUp(self):\n '''Data initialization common to this test group.'''\n\n # Initialize the training data for this\n # The general format for all training data is \n # the following: \n # [ (training_elem), (training_elem), ...] \n # where the tuple (training_elem) is actually\n # ( (x0, x1, x2), d )\n # Here, the x's are inputs and d is the desired input\n # This means that the complete training data set looks like:\n # [ ( (x0, x1, x2,), d ),\n # ( (x0, x1, x2,), d ),\n # ( (x0, x1, x2,), d ) ]\n # Training data is for NAND logic\n\n self.training_data = [ ( (1,0,0), 1),\\\n ( (1,1,0), 1),\\\n ( (1,0,1), 1),\\\n ( (1,1,1), 0) ] \n\n # Initialize the perceptron class \n self.perceptron = Perceptron(self.training_data) \n\n def tearDown(self): \n '''tearDown for this group. Currently, just a placeholder.'''\n pass\n\n def test_perceptron_data_once(self):\n '''Check the complete training data set. \n We check the actual function of the \n circular buffer elsewhere. \n '''\n# Check all of the data elements\n# For some reason, the unit test framework does not\n# allow multiple iterations\n# for tr_elem in self.training_data:\n# perceptron_elem = next(self.perceptron.data_generator)\n# if tr_elem != perceptron_elem:\n# self.assertTrue(true) \n tr_elem = self.training_data[0]\n perceptron_elem = next(self.perceptron.data_generator)\n self.assertEqual(tr_elem, perceptron_elem)\n\n def test_generate_sum(self):\n '''Generate a sum based on the first element training data'''\n# Assume that the tests are independent, and so we look for\n# for the first training datum\n self.perceptron.retrieve_training_data()\n# Assume the inital weight values, and compute as needed \n self.perceptron.generate_sum() \n# Below is the sum of w0*x0+w1*x1+w2*x2 = 0.5+0+0\n# Keep in mind that x0 is always one, so that w0*x0 is a \n# bias term\n expected_value = 0.5 \n self.assertEqual(self.perceptron.input_sum, expected_value) \n\n def test_calculate_error(self):\n '''Test the perceptron error calculation.'''\n# I assume that the tests are independent.\n# So, we perform all the preceding steps. \n# TODO: Find a better to design test suite.\n# Perhaps reorganizing this into separate\n# separate test classes. \n self.perceptron.retrieve_training_data()\n self.perceptron.generate_sum() \n self.perceptron.calculate_error()\n# Assume that the same expected value is generated \n expected_error = self.perceptron.actual_output - self.perceptron.desired_output \n self.assertEqual(self.perceptron.error, expected_error)\n\n\n def test_update_weights(self):\n '''Test the weight updates'''\n self.perceptron.retrieve_training_data()\n self.perceptron.generate_sum() \n self.perceptron.calculate_error()\n# Compare to the actual calculation \n test_weights = [w + self.perceptron.learning_rate*\\\n self.perceptron.error*x for w, x in \\\n zip(self.perceptron.weights, self.perceptron.inputs) ] \n# Actual computation\n self.perceptron.update_weights()\n self.assertEqual(test_weights, self.perceptron.weights)\n\n def test_forward(self):\n '''Test the forward propagation method once'''\n# At the end of the forward propagation, we should have an \n# updated error\n self.perceptron.forward()\n expected_error = self.perceptron.actual_output - self.perceptron.desired_output \n self.assertEqual(self.perceptron.error, expected_error)\n\n def test_backward(self):\n '''Test the backward propagation method once'''\n# The backward propagation method assumes that the forward() method\n# has been executed already.\n self.perceptron.forward()\n# Test for the weights since they should have been updated at the end\n# of the backward() propagation\n test_weights = [w + self.perceptron.learning_rate*\\\n self.perceptron.error*x for w, x in \\\n zip(self.perceptron.weights, self.perceptron.inputs) ] \n self.perceptron.backward()\n self.assertEqual(test_weights, self.perceptron.weights)\n\nif __name__ == '__main__': \n unittest.main()\n" }, { "alpha_fraction": 0.6815415620803833, "alphanum_fraction": 0.6815415620803833, "avg_line_length": 36.92307662963867, "blob_id": "cac0fddfb2f17172932abc468d590c7d55be3eb6", "content_id": "e708280d44197c2cfe69d071146883c0e14ed4ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 493, "license_type": "no_license", "max_line_length": 80, "num_lines": 13, "path": "/py-Octave/pyOctave.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef load(filename): \n '''Load a data set and place it in a numpy array.''' \n '''Modelled to behave in a way analogous to the octave load command.'''\n fo = open(filename,'r') \n#The following will load as a list of strings with a carriage return at the end \n raw_data = fo.readlines()\n# strip the carriage return \n stripped_data = [x.strip() for x in raw_data]\n num_data = [float(x) for x in stripped_data]\n data_array = np.array(num_data)\n return data_array\n" }, { "alpha_fraction": 0.6443349719047546, "alphanum_fraction": 0.6443349719047546, "avg_line_length": 39.599998474121094, "blob_id": "32981a48c4237736476961584678d00c2c9ef22b", "content_id": "f9a31cc3c4d8f5598ac0edf09e87962bfaba2ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 77, "num_lines": 25, "path": "/README.txt", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "Basic description of the contents of this subdirectory.\n\nPythonTemplate\n-This is a very basic python template. It generates a basic main() module and\nplaces an __init__ tag which can be used to run this as a module\n\nMultiWindowsTest\nA test of multiwindow capability. In the end, I would like to run separate\nwindows\n\nImageProcessing\nA sample of the functionality available through the Python Imaging Library\n(PIL). Refer to the README inside this directory for more details.\n\npy-Octave\nA series of python-based functions which are meant to look like Octave\nfunctions in order to make the translation a little easier.\n----------------------------------------------------------------------\nNeuralNet\nVarious explorations of neural net computation, eventually, hopefully leading\nultimately to a concurrent system.\n----------------------------------------------------------------------\nInheritance\nShowcases some of the Python inheritance classes.\n----------------------------------------------------------------------\n" }, { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6894736886024475, "avg_line_length": 26.14285659790039, "blob_id": "1670ff71219ef4de4847a6552afe02af247bfcdc", "content_id": "78afc4d432caf34ae44712dc8e8d548f9ea0a26f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 52, "num_lines": 7, "path": "/NumpyExamples/numpyExamples.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import numpy as np\n\ndef matMultiply(mat1, mat2):\n '''Take two numpy matrices and multipy them\n they can be either rank1 or rank2 matrices.'''\n res = np.dot(mat1,mat2)\n return res\n" }, { "alpha_fraction": 0.8823529481887817, "alphanum_fraction": 0.8823529481887817, "avg_line_length": 34, "blob_id": "2a7affb018688addcab7bef40ef4dc9268fe276c", "content_id": "4465e7cb0a1f069378adec21ca63bc5c5d75f1c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 34, "license_type": "no_license", "max_line_length": 34, "num_lines": 1, "path": "/Common/CircularBuffer.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "./CircularBuffer/CircularBuffer.py" }, { "alpha_fraction": 0.641121506690979, "alphanum_fraction": 0.641121506690979, "avg_line_length": 22.130434036254883, "blob_id": "f808c3b7d7b8fbb097a969f557c2d09a5544be84", "content_id": "8bd056cce55c0698c70712421e366257e4e15be9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 535, "license_type": "no_license", "max_line_length": 60, "num_lines": 23, "path": "/TwoWindows/TwoWindows.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import Tkinter as TK\n\nclass MyWindow:\n '''\n This class contains a second python window.\n The point of the container is to make it threadable\n in other examples. I am not sure that this is necessary.\n '''\n def __init__(self):\n self.window = TK.Toplevel()\n self.window.title('Hello, there')\n\n \ndef main():\n root = TK.Tk()\n button = TK.Button(root, text = \"Hello\")\n button.pack()\n# Create the second window and start the event queue\n aWindow = MyWindow()\n root.mainloop()\n \nif __name__ == \"__main__\":\n main()\n \n" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 32, "blob_id": "7577fcdeacfadbc989d7b333c02b5c787f7bedad", "content_id": "0f821a1c84408752d12c4d5792c2028f5d0ab080", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 32, "license_type": "no_license", "max_line_length": 32, "num_lines": 1, "path": "/Common/MultiListComp.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "./MultiListComp/MultiListComp.py" }, { "alpha_fraction": 0.6607692241668701, "alphanum_fraction": 0.6611538529396057, "avg_line_length": 33.21052551269531, "blob_id": "e231f43be29bbb98e6f60ab2d655b9d3e3fa0dcd", "content_id": "fae2b2580d12b2ba227e5a24c8e3fcc294a16850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2600, "license_type": "no_license", "max_line_length": 80, "num_lines": 76, "path": "/NeuralNet/InputNode.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Local imports\nfrom Node import Node\nimport NeuralNetGlobals as Globals\n\n#External imports\nimport random\n\nclass InputNode(Node):\n\n def __init__(self, identifier):\n '''\n Initialization function for an input node. Initialize the base node first.\n '''\n\n# Base class identifier \n Node.__init__(self,identifier) \n\n# Output to the next nodes. This is the weighted response for\n# each node which takes input from this node.\n# key: Node id, an integer one of the next nodes connecting to this\n# value: a tuple which is made of a [weight, signal] pair as a list.\n# It is assumed that the network has already initialized all weights and\n# signals for the network.\n self.next_node_data={}\n\n# Signals from an input buffer are collected here\n# Each input node can only take one signal. The input signal\n# is initially set by the network.\n self.input_signal=0\n\n# For now, the learning rate is the same for all nodes\n# TODO: Consider node specific learning rates \n# self._alpha may not be needed for input nodes \n self._alpha = Globals.DEFAULT_LEARNING_RATE \n\n# Random seed, given here for testability\n self.seed = None\n\n# Use the following flag in order to decide to use random numbers\n self.use_random = False \n\n def forward(self):\n '''\n For the input node, this means capturing the next set of inputs and\n setting the properties of the next nodes.\n We are assuming that the input is the response for an input node.\n '''\n self._response = self.input_signal\n self._set_output_signals() \n\n def initialize_weights(self):\n '''Initialize the weights of the next nodes.'''\n for key in self.next_node_data:\n weight = self._retrieve_weight_value()\n self.next_node_data[key][Globals.WEIGHT_IDX] = weight \n\n def _set_output_signals(self):\n '''Use the response to set the output signals.'''\n# Set the output signals based on threshold value\n for key in self.next_node_data:\n value = self._response*self.next_node_data[key][Globals.WEIGHT_IDX]\n self.next_node_data[key][Globals.SIGNAL_IDX] = value \n\n def _retrieve_weight_value(self):\n '''Retrieve a weight value. Currently, this value is zero. Eventually, \n this may be replaced by a random number between zero and one.\n '''\n if self.use_random is True:\n if self.seed is not None:\n random.seed(self.seed)\n\n weight = random.random()\n else: \n weight = Globals.DEFAULT_WEIGHT_VALUE\n\n return weight\n" }, { "alpha_fraction": 0.6104046106338501, "alphanum_fraction": 0.6369942426681519, "avg_line_length": 27.799999237060547, "blob_id": "99aaf9d7879848c48f176193485008908e2af15d", "content_id": "e9d9f70714f4062600782bc2d748bc5df96591f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 865, "license_type": "no_license", "max_line_length": 89, "num_lines": 30, "path": "/Generator/Generator.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Generator example. Create a series of functions to test the generator.\n For an excellent discussion on generators:\nhttps://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/\n'''\n \ndef main():\n '''Main function driver, used to do some basic testing.'''\n# Begin with index -1, so that at 'next' we will actually begin at \n# index 0\n a_generator = generator_from_list(-1)\n value = 0\n while value < 20:\n print(next(a_generator))\n value += 1\n\ndef generator_from_list(index):\n '''Generate a generator from a list. This is a circular buffer.'''\n test_list = [1,2 ,3,4,5]\n# In order to keep the generator active, we\n# we keep it running.\n while True:\n if index == len(test_list)-1:\n index = 0\n else:\n index += 1\n yield test_list[index]\n\n\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.6581827998161316, "alphanum_fraction": 0.6584565043449402, "avg_line_length": 34.07692337036133, "blob_id": "cfbdf0e2facd4e2ca9b5bbdd1575bb2c7c434e39", "content_id": "328771e371bbe87288f78a2cac87f96a6f2666bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3654, "license_type": "no_license", "max_line_length": 77, "num_lines": 104, "path": "/NeuralNet/Node_orig.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Local modules\nimport NeuralNetGlobals as Globals\n\n\nclass Node (object):\n '''Base class for the basic component of the neural net.'''\n\n def __init__(self, identifier):\n '''\n The unique identifier for this node is an integer set by the network.\n at initialization.\n '''\n# The node identifier, and integer\n self.ident = identifier \n\n# The output signal, computed from the input signals and the \n# threshold function. Used to calculate the output signal\n self._response = 0\n\n# Dictionaries of input and output signals\n# In the input nodes, the structure is:\n# key: Node id, an integer\n# value: a reference to the node itself\n self.prev_node_data={}\n\n# Output to the next nodes. This is the weighted response for\n# each node which takes input from this node.\n# key: Node id, an integer one of the next nodes connecting to this\n# value: a tuple which is made of a (weight, signal) pair \n self.next_node_data={}\n\n# Signals from the previous nodes are collected here.\n self._input_signals=[]\n\n# List of nodes 'forward' of the current node:\n# These may be redefined by the derived clases, depending on whether\n# they are input or output nodes\n# These are just list of identifiers\n\n# Input or back nodes\n# This is a list of indices of nodes which provide input to this node\n# May not be necessary\n# self._input_nodes=[]\n\n# Output or forward nodes\n# This is a list of indices of nodes for which this node provides output \n#\n# self._output_nodes=[]\n\n# Use the expected output to compute the error\n def _compute_errors(self):\n '''Compute the errors based on the actual and desired outputs.'''\n pass\n \n def _compute_and_set_output_signals(self):\n '''\n Compute the output signal of this node based on the output of the input\n nodes.\n '''\n self._collect_input_signals()\n self._compute_threshold_value()\n\n# Set the output signals based on threshold value\n for key,val in self.next_node_data:\n value = self._response*self.next_node_data[key][Globals.WEIGHT_IDX]\n self.next_node_data[key][Globals.SIGNAL_IDX] = value \n\n def _collect_input_signals(self):\n# An input node would not have this function defined\n '''Collect the input signals, based on the output of the input nodes.\n The signals are assumed to be weighted by the previous node.\n '''\n for key in self.prev_node_data:\n prev_node = self.prev_node_data[key]\n value = prev_node.next_node_data[self.ident][Globals.SIGNAL_IDX]\n\n# Obtain the output of the previous node for this node\n self._input_signals.append(value) \n\n def _compute_threshold_value(self):\n '''Compute the output value based on a threshold function'''\n total = sum(self._input_signals)\n# Compute the response based on the threshold function\n self._response = self._threshold(total)\n\n def _back_propagate_weights(self):\n '''Use the computed error to update the weight values.'''\n for key in self.prev_node_data:\n node = self.prev_node_data[key]\n weight = node.next_node_data[self.ident][WEIGHT_IDX]\n weight = weight + self.error\n node.next_node_data[self.ident][WEIGHT_IDX] = weight \n\n def forward(self):\n '''\n Computes the output and returns a list of the output nodes.\n '''\n self._compute_and_set_output_signals()\n return self._output_nodes\n\n def backward(self):\n '''This is the back propagation function.'''\n self._compute_error()\n self._back_propagate_weights() \n" }, { "alpha_fraction": 0.6192017197608948, "alphanum_fraction": 0.6305285692214966, "avg_line_length": 30.423728942871094, "blob_id": "191c0c7265ff71d0fc4ff7523afca2a522b190c9", "content_id": "15f6a051610daa638d2b59e13045ab1a0143725b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1854, "license_type": "no_license", "max_line_length": 64, "num_lines": 59, "path": "/BinaryTree/BinaryTree_unittest.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Unit test framework for the binary tree'''\n\nimport unittest\nimport BinaryTree\n\nclass TestBinaryTree(unittest.TestCase):\n '''Tests related to the binary tree execution'''\n\n def setUp(self):\n '''Generic set up for this test'''\n self.create_binary_tree()\n\n def create_binary_tree(self):\n '''Auxiliary method used to create a simple binary tree'''\n #TODO: create a variant which allows you to choose\n #tree elements from an array\n node_left = BinaryTree.Node(4)\n node_right = BinaryTree.Node(5)\n self._root = BinaryTree.Node(3, node_left, node_right) \n\n def test_single_node(self):\n '''Create and check the value of a single node.'''\n targetVal = 3 #Arbitrary value\n aNode = BinaryTree.Node(3)\n self.assertEqual(aNode.val, targetVal)\n\n def test_three_node_traversal(self):\n '''Test a three node tree''' \n test_val = [3,4,5]\n res = BinaryTree.traverse(self._root)\n self.assertEqual(test_val, res)\n\n def test_insert_node_left(self):\n '''Insert a left child to a given node'''\n test_val = 3\n parent_val = 4\n test_node = BinaryTree.Node(4)\n BinaryTree.insert_node(test_node,test_val)\n self.assertEqual(test_val, test_node.left.val)\n\n def test_insert_node_right(self):\n '''Insert a child to a given node'''\n test_val = 3\n parent_val = 4\n test_node = BinaryTree.Node(4)\n BinaryTree.insert_node(test_node,test_val,False)\n self.assertEqual(test_val, test_node.right.val)\n\n def test_insert_from_arr(self):\n '''Insert the values of an array into a binary\n tree.''' \n arr = [1,2,3,4,5,6,7] \n root = BinaryTree.construct_from_array(arr) \n Res = [] \n Res = BinaryTree.traverse(root, [])\n self.assertEqual(sorted(Res), arr)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5361701846122742, "alphanum_fraction": 0.5574468374252319, "avg_line_length": 22.5, "blob_id": "b337315e1e8ddd5d24e64b3625e67360bd9f07d6", "content_id": "a87768a84cddde5cd5042af1d104c839abf51052", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 235, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/Fibonacci/Fibonacci.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''A container for the Fibonacci sequence'''\ndef fib(n):\n '''Simple, recursive fibonacci sequence'''\n if n == 1 or n == 0:\n return n\n else:\n return fib(n-1)+fib(n-2)\n\nif __name__ == '__main__':\n fib(int(sys.argv[1]))\n" }, { "alpha_fraction": 0.6875489354133606, "alphanum_fraction": 0.6922474503517151, "avg_line_length": 25.39583396911621, "blob_id": "461a36055d60f7bf07f6edb2bb34eebcbdb09c70", "content_id": "946de5737e7390888ab26dbd9e88eb16bf4af48b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1277, "license_type": "no_license", "max_line_length": 80, "num_lines": 48, "path": "/ThreadWindows_NonWorking/ThreadWindows.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import threading\nimport Tkinter\n\n# The purpose of this script was to show a series of multithreaded windows.\n# the lesson learned from all this is that there can only be one mainloop()\n# it is possible to have multiple top level windows running as separate threads.\n# This Python script is not meant to work in its present form.\n\nclass ThreadedWindow(threading.Thread):\n '''\n Simple example of a class which uses creates two separate windows\n as threads.\n '''\n\n def __init__(self,master):\n threading.Thread.__init__(self)\n self.master = master\n self.aButton = Tkinter.Button(self.master)\n\n def run(self):\n self.aButton.pack()\n\ndef main():\n '''\n Main program module creates two Threaded windows.\n This is effectively the controller loop.\n '''\n# Starting two root level windows via Tkinter is not really workable. \n# I assume that this is\n master = Tkinter.Tk()\n master2 = Tkinter.Tk()\n tw1 = ThreadedWindow(master)\n tw2 = ThreadedWindow(master2)\n tw1.start()\n tw2.start()\n master.mainloop()\n\n#def aWindow():\n# master = Tkinter.Tk()\n# aButton = Tkinter.Button(master, text='Hello')\n# aButton.pack()\n# master.mainloop()\n#\n#def main():\n# threading.Thread(group=None, target=aWindow).start()\n \nif __name__ == \"__main__\":\n main()\n\n \n\n \n" }, { "alpha_fraction": 0.6198083162307739, "alphanum_fraction": 0.6485623121261597, "avg_line_length": 13.809523582458496, "blob_id": "b1f0f6779370cfdf2ab147746dab55c2c10927e6", "content_id": "78adcc2a82f5f39937d725ab06b8067ea6eae39f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "no_license", "max_line_length": 52, "num_lines": 21, "path": "/If_ThenEx.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n#vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\nmylogical=1\nif mylogical:\n print 'myLogical 1'\n\n\nx = int(raw_input(\"Please enter an integer:\"))\n\n\n\nif x<0:\n x=0\n print 'Negative changed to zero'\nelif x==0:\n print 'Zero'\nelif x==1:\n print 'Single'\nelse:\n print 'More'\n\n\n" }, { "alpha_fraction": 0.6138211488723755, "alphanum_fraction": 0.6382113695144653, "avg_line_length": 14.375, "blob_id": "392dfd2ef9ceea9da6e6edd830dba35cf544ba7d", "content_id": "1583a14e7c01a4895bbae24397cf4b559ec3c096", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 246, "license_type": "no_license", "max_line_length": 35, "num_lines": 16, "path": "/OpenGLPygame/OpenGLPygame.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import pygame\nimport gutil\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\ndef main():\n pygame.init()\n gutil.initializeDisplay(800,600)\n\n done = False\n \n while not done:\n pygame.display.flip()\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.47218453884124756, "alphanum_fraction": 0.5029398202896118, "avg_line_length": 22.521276473999023, "blob_id": "f6e7837290135a87af4006ff916725fc21638ff1", "content_id": "a9f53e08ba9e0a8393a535203e6dbdca151f153b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2211, "license_type": "no_license", "max_line_length": 62, "num_lines": 94, "path": "/QuickSort/QuickSort.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "def main():\n print \"Main module\"\n L = [1,4,3,2,5]\n (R,q) = pivot(L,0, len(L) ) \n print R\n# Swap the last and first element in the array\n#L = swap(L, 0, len(L) -1) \n# print L\n# L = [2, 6, 7, 9, 3] \n# (R,p) = pivot(L) \n# print L[p]\n\ndef pivot_test():\n '''Test a single pivot on a number of lists'''\n #Rightmost position is largest\n L = [1,4,3,2,5]\n (R,p,q) = pivot(L,0, len(L)-1) \n print R, p, q\n L = [2, 6, 7, 9, 3] \n (R,p,q) = pivot(L,0, len(L)-1) \n print R, p, q\n #Rightmost position is smallest\n L = [8, 6, 7, 9, 2] \n (R,p,q) = pivot(L,0, len(L)-1) \n print R, p, q\n\ndef quick_sort_test():\n '''Perform quick sort tests for a number of lists'''\n# L = [1,4,3,2,5]\n# R = quick_sort(L,0, len(L)-1) \n# print R\n L = [2, 6, 7, 9, 3] \n R = quick_sort(L,0, len(L)-1) \n print R\n #Rightmost position is smallest\n# L = [8, 6, 7, 9, 2] \n# R = quick_sort(L,0, len(L)-1) \n# print R\nimport time \ndef quick_sort(L,left, right):\n '''Returns the array with the pivot in the main position'''\n time.sleep(5)\n#if q <= p: \n# return L\n# else:\n (L,p,q)=pivot(L,left,right)\n print L, p, q\n if left<q-1:\n #Pass the entire list...\n #Otherwise, L is just a sublist\n L = quick_sort(L,0,q-1) \n if right>q+1:\n L = quick_sort(L,q+1,len(L)-1)\n\n return L \n \ndef pivot(L,p,q): \n '''(L, q) = pivot(L) \n Inputs: \n L: original list\n Returns:\n L: resulting list with correctly positioned pivot\n p: pivot index \n '''\n #Perform two swap operations \n #p is the index to the left of the pivot\n #q is the index to the right of the pivot\n while (p<q): \n if (L[p] > L[q] ):\n L = swap(L, p, q-1) \n#print L, p, q\n L = swap(L, q-1, q)\n q -= 1 \n#print L, p, q \n else:\n p+=1\n# print L, p, q\n return (L,p,q)\n\ndef swap(L, p, q):\n '''swap(L,p,q):\n Swaps elements at index p and q in array L\n returns the array with the swapped elements'''\n if (p == len(L)) or (q == len(L)) or (p==q) \\\n or (p < 0) or (q<0):\n return L\n else:\n tmp = L[p]\n L[p] = L[q]\n L[q] = tmp\n return L\n \nif __name__ == \"main\":\n main()\n" }, { "alpha_fraction": 0.6472080945968628, "alphanum_fraction": 0.6522842645645142, "avg_line_length": 19.736841201782227, "blob_id": "b44c512e28c1c7c8928f09b1cfceb73544588fa5", "content_id": "efc20c0560c4c4e91159c67e8a31250edd05f717", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 788, "license_type": "no_license", "max_line_length": 62, "num_lines": 38, "path": "/ThreadLocksOut/ThreadLocksOut.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import threading\n\nclass FetchUrls(threading.Thread):\n '''\n Simple example of a class which using a simple\n lock for thread control.\n '''\n\n#lock = threading.Lock()\n\n def __init__(self):\n threading.Thread.__init__(self)\n# self.lock = lock\n\n def run(self):\n# lock in this scope should release\n# lock may not work at all\n lock = threading.Lock()\n lock.acquire()\n print 'hello'\n# release is not necessary\n#self.lock.release()\n\ndef main():\n '''\n main() function generates the lock and passes it on to the \n threads.\n '''\n# Lock at this scope will work\n# Remember that reference semantics are the rule in Python \n# This means that the lock is in the right scope.\n t1 = FetchUrls()\n t1.start()\n t2 = FetchUrls()\n t2.start()\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.5627802610397339, "alphanum_fraction": 0.6165919303894043, "avg_line_length": 21.299999237060547, "blob_id": "d98e3819492e50c4ee437c01445ade07e3aa6d74", "content_id": "c7fcf55b152d20eb4276e144f635bbbc00af6088", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 892, "license_type": "no_license", "max_line_length": 63, "num_lines": 40, "path": "/OpenGLPygame/example1b.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import gutil\nimport pygame\nimport time\nfrom pygame.locals import*\nfrom OpenGL.GL import *\n\ndef main():\n pygame.init()\n gutil.initializeDisplay(800,600)\n\n glColor4f(1.0, 1.0, 1.0, 1.0)\n\n done = False\n alpha = 0.0\n while not done:\n glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT)\n alpha = alpha + 0.1\n#Note the sequence of operations\n glPushMatrix()\n#glTranslate(20,20, 0)\n glRotate(alpha,0,0,20)\n#The actual image is generated here\n#Between glBegin() and glEnd()\n glBegin(GL_TRIANGLES)\n glVertex2f(10,400)\n glVertex2f(400,400)\n glVertex2f(400,200)\n glEnd()\n glPopMatrix()\n\n pygame.display.flip()\n\n eventlist = pygame.event.get()\n for event in eventlist:\n if event.type == QUIT \\\n or event.type == KEYDOWN and event.key == K_ESCAPE:\n done = True\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.7625820636749268, "alphanum_fraction": 0.7713347673416138, "avg_line_length": 26.66666603088379, "blob_id": "db67f5fcfe3ca80182f9c554a74dc0841815baf5", "content_id": "b18f90f8954e9d8d5954960bcb642a35719551bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 914, "license_type": "no_license", "max_line_length": 59, "num_lines": 33, "path": "/DomParsers/DomParser.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\n#open an existing xml file, parse for the top level element\n#change its name attribute\n\nfrom xml.dom.minidom import parse, parseString\n\ndom1=parse('build.xml')\n#Capture the top level element\nprojectRoot = dom1.documentElement\n\nresult = projectRoot.hasAttribute(\"name\")\nprint \"Attribute name available: \",result\n\n#Set the attribute name \nprojectRoot.setAttribute(\"name\", \"testProject\")\n\n#show the xml file before writing it back out to file\n#print(dom1.toprettyxml() )\n\n#print the description of the data and then modify it\nelement = dom1.getElementsByTagName('description')[0]\n\n#Assume that the data is text, but we should verify this\n#The following will capture the information between the \n#<description> tags\nprint element.childNodes[0].data\n\nelement.childNodes[0].data='Description goes here'\n\n#rewrite the xml back to file\nxmlFile = open('build.new.xml','w');\ndom1.writexml(xmlFile);\n\n" }, { "alpha_fraction": 0.6894451975822449, "alphanum_fraction": 0.6962110996246338, "avg_line_length": 34.16666793823242, "blob_id": "d9e79fb6fd43bba45bc2a5e121604abb6f52ab28", "content_id": "5cdfde019ef2988a2e79e5c9ce9f587295db7982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 91, "num_lines": 42, "path": "/NeuralNet/NodeDataGenerator.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#External madules\nimport pickle\n\n#Local modules\nimport NeuralNetGlobals as Globals\n\ndef main():\n '''\n Node data generator main module. This module generates the node data which is then \n used to generate the neural network. This file is meant to be modified as noted below.\n The data it generates is a dictionary in which the key is the node number and the value\n is the layer type (input, output, hidden). \n A simple three node network would have a dictionary which would look like this:\n {1:'input',2:'input',3:'hidden'}\n By default the file created is called Node.dat.\n Inputs: None\n Outputs: Node.dat, output file containing node data. \n '''\n \n# Modify the following dictionary in order to denote the network \n node_data = {1:'input',\n 2:'input',\n 3:'output'} \n\n# Modify the following list in order to denote the connections of the network\n# The association list shows the relationship between 'previous' and 'next' nodes.\n# The general format of the tuple is (prev, next)\n association_list = [ (0,2) , (1,2) ]\n\n\n#TODO: Consider data checking to make sure that both the association list and the node data\n# refer to the same nodes. This may be actually fairly elaborate than it firts appears.\n\n# Pack all structures into a single container\n\n container = [node_data, association_list]\n\n with open(Globals.NODE_FILENAME,'w') as f:\n pickle.dump(container,f) \n \nif __name__ == '__main__':\n main() \n" }, { "alpha_fraction": 0.5838509202003479, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 22, "blob_id": "da14e9bc84e4df22314f0aea33e922c1b50e4d71", "content_id": "8c4d01479b5e80ab2b05fd4ab96313245c0c8ddb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 161, "license_type": "no_license", "max_line_length": 55, "num_lines": 7, "path": "/py-Octave/parserExample.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "print 'Example of parsing numbers from a string'\na = ' 1 2 3 4 '\nb = a.split(' ')\nnums = [int(y) for y in [x for x in b if x.isdigit()] ]\n\nprint a\nprint nums\n" }, { "alpha_fraction": 0.6804123520851135, "alphanum_fraction": 0.6818851232528687, "avg_line_length": 31.33333396911621, "blob_id": "42285a2185f214fd4c29886c4ac59ba28163cdbf", "content_id": "6a4e0f7116e69abc6abec2c3c0157a78acb132fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "no_license", "max_line_length": 75, "num_lines": 21, "path": "/NeuralNet/Node.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Local modules\nimport NeuralNetGlobals as Globals\n\n\nclass Node (object):\n '''Base class for the basic component of the neural net.'''\n\n def __init__(self, identifier):\n '''\n Initialization of the base node.\n This node is not meant to be used by itself. It has the functionality\n common to input, hidden and output nodes.\n The unique identifier for this node is an integer set by the network\n at initialization.\n '''\n# The node identifier, and integer\n self.ident = identifier \n\n# The output signal, computed from the input signals and the \n# threshold function. Used to calculate the output signal\n self._response = 0\n" }, { "alpha_fraction": 0.4819401502609253, "alphanum_fraction": 0.511867880821228, "avg_line_length": 22.071428298950195, "blob_id": "f137182739de2319c01700ad26a9c26c431650b6", "content_id": "ddedb9d934c6576fc0a764458381c2cc70c8df60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 969, "license_type": "no_license", "max_line_length": 66, "num_lines": 42, "path": "/MergeSort/MergeSort.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#This script attempts a simple merge sort algorithm \ndef main():\n '''The main module runs the merge sort algorithm.'''\n print \"The main module\"\n#R = merge([1,3,5],0, [2,4,6], 0)\n# print R\n R = merge_sort([5,4,3])\n print R\n R = merge_sort([1,1,1,1,12,8,1,1,1])\n print R\n\ndef merge(A,p,B,q):\n '''Accepts two sorted lists, produces a merged, sorted list.'''\n if p == len(A): \n return B\n elif q == len(B):\n return A\n elif p == len(A) and q == len(B):\n return \n else:\n a = A[p]\n b = B[q]\n if a<b:\n return [A[p]]+merge(A, p+1, B, q) \n else:\n return [B[q]]+merge(A, p, B, q+1)\n\ndef merge_sort(L):\n '''Sort arrays recursively using the merge-sort algorithm'''\n if len(L) == 1:\n return L\n else:\n A = L[0:len(L)/2] \n B = L[len(L)/2:len(L)] \n print A\n print B\n C = merge_sort(A)\n D = merge_sort(B)\n return merge(C,0,D,0)\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.625, "avg_line_length": 23, "blob_id": "9d230b13617fe85b942864c8c175f0c4052b1429", "content_id": "6c825d74b82f07b8571e86f795d10807ab6c4004", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 39, "num_lines": 18, "path": "/AnimatedPlot/AnimatedPlot.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\nimport matplotlib.pylab as pylab\nimport time\ndef main():\n pylab.ion()\n fig1 = plt.figure()\n ax1 = fig1.add_subplot(111)\n x = pylab.arange(0,2*pylab.pi,0.01)\n line, = ax1.plot(x,pylab.sin(x))\n for i in pylab.arange(1,200):\n line.set_ydata(pylab.sin(x+i/10.0))\n xlims = ax1.get_xlim()\n ax1.set_xlim(0, xlims[1]+0.2)\n time.sleep(0.5) \n plt.draw()\n\nif __name__==\"__main__\":\n main()\n" }, { "alpha_fraction": 0.6024172902107239, "alphanum_fraction": 0.6068702340126038, "avg_line_length": 29.52427101135254, "blob_id": "e4b69a881b1a874efa41389e596496db3b92740d", "content_id": "6420f5607c7ea62261f9fd8a67773f6678c58454", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3144, "license_type": "no_license", "max_line_length": 64, "num_lines": 103, "path": "/BinaryTree/BinaryTree.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''This module attempts to implement a binary tree class. One \n possible use for this are to gain a better understanding of \n the heap sort algorithm'''\n\ndef main():\n '''Main module. Quick tests here, otherwise\n use the test suite.'''\n pass\n\ndef construct_from_array(arr):\n '''Construct a balanced binary tree from an array.\n Input: arr -- array of elements usually implemented\n as a list.\n Output: root -- root of the completed tree\n '''\n #Array begins at index zero, but the tree is \n #easier to manage with index 1\n idx = 1\n root = None\n if len(arr) is not 0:\n root = Node(arr[idx-1])\n root.left = insert_from_arr(arr, 2*idx, 'left')\n root.right = insert_from_arr(arr, 2*(idx)+1, 'right') \n return root\n\ndef insert_from_arr(arr, idx, child):\n '''Insert elements from an array into a binary tree.\n Function is recursive.\n Input: arr -- input array\n idx -- index from the array\n child -- a tag, 'left' or 'right' tag\n '''\n\n if idx > len(arr): \n return None\n\n #Binary tree arrays begin at 1 \n if idx < 1:\n return None \n\n if child == 'left':\n node = Node(arr[idx-1])\n else:\n node = Node(arr[idx-1]) \n\n# Worth noting that we pass the new nodes by value \n# constructing the tree by reference, that is,\n# via the parameter list, will not work.\n# Python makes a local copy, even though in the\n# command shell it appears to assign by reference.\n# I guess that this means that assignment is by \n# reference, but parameter passing is by value\n\n node.left = insert_from_arr(arr, 2*idx,'left')\n node.right = insert_from_arr(arr, 2*idx+1,'right')\n\n return node\n\ndef traverse(node = None, Res=[]):\n '''Traverse a tree beginning at node and place \n the results in a list'''\n if node is None:\n return Res\n\n Res.append(node.val)\n Res = traverse(node.left, Res) \n Res = traverse(node.right, Res)\n return Res\n\ndef insert_node(parent, value = 'NaN', left=True, node = None): \n '''Insert a value into a node. Keep in mind that\n elements are not sorted in any particular order.\n Inputs: \n parent --- node to which we will attach the node\n keep in mind that a tree is a node\n value --- value associated with this node\n left --- left or right child (left=True) \n node --- the root of the tree in which \n we will insert the value\n '''\n#Nothing to do if no tree is provided\n if parent is not None:\n if node is None:\n #Node is binary tree, creating node \n node = Node(value) \n if left is True: \n parent.left = node \n else: \n parent.right = node \n\n return parent \n\nclass Node:\n def __init__(self, val= None, left=None, right=None):\n '''Initialization routine. Input is the intrinsic value\n of the binary tree.\n Inputs: val -- value associated with this node\n left, right -- left and right nodes\n Outputs: none\n '''\n self.val = val\n self.left = left\n self.right = right\n" }, { "alpha_fraction": 0.6942148804664612, "alphanum_fraction": 0.7355371713638306, "avg_line_length": 23.200000762939453, "blob_id": "3e39f8f5f50cc5667164b19e63746ffafb01358c", "content_id": "dfa069deef76a9c3e6b591450af99c102772fc75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 32, "num_lines": 10, "path": "/NeuralNet/NeuralNetGlobals.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "NODE_FILENAME = 'Node.dat'\nASSOC_FILENAME = 'NodeAssoc.dat'\nWEIGHT_IDX = 0\nSIGNAL_IDX = 1\nDEFAULT_LEARNING_RATE = 0.1\nDEFAULT_WEIGHT_VALUE = 0\nDEFAULT_RANDOM_SEED = 3\nDEFAULT_INITIAL_RESPONSE = 0\nDEFAULT_TEST_ID = 0\nNUMBER_OF_TEST_NODES = 10\n" }, { "alpha_fraction": 0.6251660585403442, "alphanum_fraction": 0.6333270072937012, "avg_line_length": 34.3624153137207, "blob_id": "0f43c95cb693422767d3992bf79579588a4d9afe", "content_id": "257be7d48f8285b547f130bbbcc8f286adf1d6ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5269, "license_type": "no_license", "max_line_length": 76, "num_lines": 149, "path": "/Perceptron/Perceptron.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#own imports \nfrom CircularBuffer import CircularBuffer\nfrom MultiListComp import dot_product \nimport time\n\nclass Perceptron(object):\n '''Basic perceptron class.\n Creates a simple no-hidden layer perceptron.'''\n\n def __init__(self, trainingData):\n '''Basic initialization routine.\n Assume at least a three element input, with a\n bias input always set to 1.\n The training data should behave like a circular\n buffer.\n Assumes that the training data has the form:\n [ ((1,0,0),1), (1,1,0),1), ...]\n In other words:\n [ (training_data), (training_data), ... ]\n Where (training_data) is \n ((input), expected_output)\n ''' \n # Construct a circular buffer from the training data \n # Here for diagnostic purposes\n self.circ_buffer = CircularBuffer(trainingData) \n \n # TODO: Make these configurable\n self.init_val_weights = [0.0,0.0,0.0]\n self.weights = self.init_val_weights\n self.learning_rate = 0.1\n self.threshold = 0.5\n# Epsilon is the value below which the error becomes acceptable, and \n# we have reached the end of the computation.\n self.epsilon = 0.0 \n# Calculated error for each training data instance\n# Note that this is different from the accumulated error\n# which looks at the error for all the training data\n# elements\n self.error = 0.0\n\n# Collect the errors for each individual training element \n# data set. \n# Deliberately set all errors to a maximum (1) in order\n# to start with the maximal error\n self.error_set = [1.0 for x in range( len(trainingData) ) ] \n\n# The error set index is increased whever the error_set is \n# updated\n self.error_set_index = 0\n\n# The average error is calculated for all elements in \n# the training set\n self.average_error = 0.0\n\n# The number of training elements in the set. \n self.num_training_elements = len(trainingData) \n\n# sum of the input node values\n self.input_sum = 0.0\n\n def forward(self):\n '''Forward propagation.\n Calculate for the entire training set.\n '''\n self.retrieve_training_data()\n self.generate_sum() \n self.calculate_error()\n self.calculate_average_error()\n self.forward_data()\n \n def backward(self):\n '''Backward propagation. Update the \n the weights only if the error is larger\n than expected'''\n self.update_weights()\n\n def retrieve_training_data(self):\n '''Retrieve the training data. It is \n assumed that the format is given as \n shown in previous comments'''\n training_elem = self.circ_buffer.retrieve() \n self.inputs =training_elem[0]\n self.desired_output = training_elem[1]\n \n def generate_sum(self):\n '''Given weights and inputs, generate the sum'''\n# Let us indulge in a bit of functional programming\n# Convenience variables\n self.input_sum = dot_product(self.inputs,self.weights)\n\n def calculate_error(self):\n '''Calculate the error, based on the threshold.\n This method ''' \n# Simple activation function\n if self.input_sum > self.threshold:\n self.actual_output = 1\n else:\n self.actual_output = 0\n\n self.error = self.desired_output-self.actual_output \n\n def calculate_average_error(self):\n '''Calculate the average error for each element in the training set'''\n self.error_set[self.error_set_index] = abs(self.error) \n if self.error_set_index+1 == self.num_training_elements:\n self.error_set_index = 0\n else:\n self.error_set_index += 1\n\n self.average_error = sum(self.error_set)/self.num_training_elements \n\n def update_weights(self):\n '''Update the weights with the new delta''' \n\n# Weight update calculation\n# We use the method of steepest descent in order\n# to calculate the change in the weight \n# Error = 1/2(actual_output-expected_output)^2\n# d(Err)/dw_n=(actual_output-expected_output)*x_n\n# The total change in the weights is:\n# delta_w = learning_rate*d(Err)/dw_n\n \n self.weights = [w + self.learning_rate*self.error*x for w, x in \\\n zip(self.weights, self.inputs) ] \n\n def run(self):\n '''Run the perceptron to completion. We do this in two steps:\n (1) Run through the complete training data set and compute\n the accumulated error.\n (2) While the accumulated error is larger than a given limit\n (epsilon), continue to exercise the forward and backward\n propagation.\n '''\n \n self.forward()\n while abs(self.average_error)>self.epsilon:\n self.backward()\n self.forward()\n\n def forward_data(self):\n '''Print the data after the forward propagation step.'''\n print 'self.inputs: ',self.inputs\n print 'self.weights: ',self.weights \n# print 'self.desired_output: ',self.desired_output\n# print 'self.input_sum: ', self.input_sum\n# print 'self.actual_output: ', self.actual_output\n print 'self.error: ', self.error\n print 'self.error_set: ', self.error_set\n print 'self.average_error: ',self.average_error\n" }, { "alpha_fraction": 0.5943517088890076, "alphanum_fraction": 0.6084724068641663, "avg_line_length": 26.75, "blob_id": "73c976413668e7bb1e56801fe3301462d6feeaec", "content_id": "74548098ae8d20a44bb929006f1e853d733e8492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 779, "license_type": "no_license", "max_line_length": 64, "num_lines": 28, "path": "/ListCopy/ListCopy.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Copy the contents of one or more lists to a third list\n test various list functions.'''\n\ndef main():\n '''The test module, at least for now'''\n Src = [1,2,3,4]\n Dest = [0 for x in range (len(Src) )] \n listCopy(Src,0, Dest, 0)\n\ndef listCopy(Src,p, Dest, q):\n '''Index-based recursive list copy. Leaves the original list \n unchanged. Traverses using an incremented list index.\n '''\n if p == len(Src):\n print Dest\n return Dest\n else:\n Dest[q] = Src[p]\n listCopy(Src, p+1, Dest, q+1) \n\ndef listCopy(Src,p):\n '''Index-based recursive list copy. Leaves the original list \n unchanged. Traverses using an incremented list index.\n '''\n if p == len(Src)-1:\n return [Src[p]]\n else:\n return [Src[p]] + listCopy(Src,p+1) \n" }, { "alpha_fraction": 0.6332454085350037, "alphanum_fraction": 0.6365435123443604, "avg_line_length": 30.58333396911621, "blob_id": "2cee88a3e6cd526fb6ad130f6a9aadc73590ff3b", "content_id": "3832d5e95e0b015827c0b38c539473577e1c3487", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1516, "license_type": "no_license", "max_line_length": 62, "num_lines": 48, "path": "/DisplayUtils/DisplayUtils.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''DisplayUtils -- generic utilities to display information on\n (non-graphically) on a screen. '''\n\ndef main():\n '''Main function, used to test the utilities'''\n print_at(40, '*')\n\n#print len('* * * * * * * * * *')\n print_at(40, '* * * * * * * * * *')\n\ndef print_at(col_number, elem):\n '''Print an element beginning at a given position.\n Inputs: \n col_number: column number at which to begin printing\n elem: element to be printed\n Outputs: Formatted string for printout \n Notes:\n Only supports center justification.\n The API will attempt to center the string element based \n on its length. \n It is the responsibiity of the calling program to \n provide a well formatted string which can be printed.\n The API will not modifiy the structure of the string\n in any way.\n '''\n # Construct the spacing based on the column number\n # and the length of the string\n # the default spacing element is one space\n sp = ' '\n # Use the following to construct the spacers\n spacer=''\n # Use the following to print the complete string\n complete = ''\n # The actual number of spacers is a function of\n # the column number and the lenght of the string \n total_num_spacers = col_number-len(elem)/2\n# print total_num_spacers\n for i in range(total_num_spacers):\n spacer+=' '\n\n #Construct the final string \n complete+=spacer+elem\n print complete \n return complete \n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6416465044021606, "alphanum_fraction": 0.6416465044021606, "avg_line_length": 30.769229888916016, "blob_id": "5ecaa44c250a86a54af77268890021946fe6f7e9", "content_id": "65dd9056b34c7e4f5c4c54624c6570b3b02c49db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 64, "num_lines": 13, "path": "/Common/MultiListComp/MultiListComp.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''This module is used to test the use of the list comprehension\n in Python using more than one list.\n'''\n\ndef dot_product(A, B):\n '''Simulates a vector dot product.\n Inputs: A,B \n -- lists, assumed to be of the same length from which\n the dot product would be computed.\n '''\n product_list = [a*b for a,b in zip(A,B)] \n result = reduce(lambda x,y: x+y, product_list)\n return result\n" }, { "alpha_fraction": 0.6584821343421936, "alphanum_fraction": 0.6607142686843872, "avg_line_length": 31.780487060546875, "blob_id": "4c3d78f86cea128a8e406f5eefc7dba5dd33f4d5", "content_id": "7aab2345f872cc5a24aa82ebe1bc2fdad31f5979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1344, "license_type": "no_license", "max_line_length": 65, "num_lines": 41, "path": "/Common/CircularBuffer/Unittest_CircBuff.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Unit test framework for CircularBuffer class'''\nimport unittest\n\n# Own imports\nfrom CircularBuffer import CircularBuffer\nclass TestCircularBufferBasic(unittest.TestCase):\n '''Basic test suite for the circular buffer class'''\n\n def setUp(self): \n '''Setup for all classes. Uses default container'''\n self.circularBuffer = CircularBuffer() \n\n# Reference to the circular buffer's internal data, for\n# convenience:\n self.thisBuffer = self.circularBuffer.circ_data\n \n def test_first_value(self):\n '''Return a single value from the circular buffer.\n Keep in mind that we are using a generator for this. \n '''\n index = 0\n# Convenience variables\n circBuffer = self.circularBuffer\n data = self.thisBuffer \n# End convenience variables\n self.assertEqual(circBuffer.retrieve(),data[index]) \n\n def test_periodicity(self):\n '''Test the circular buffer by retrieving values \n beyond the length of the buffer\n '''\n# Convenience variables\n data = self.circularBuffer.circ_data\n circBuffer = self.circularBuffer\n# Use the default data iterate n-times (for now n = 2) \n for n in range(2):\n for value in data:\n self.assertEqual(circBuffer.retrieve(), value) \n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6721925139427185, "alphanum_fraction": 0.6732620596885681, "avg_line_length": 38.3684196472168, "blob_id": "4ea66971ebedb9ca1699763ea6f6671d1993de12", "content_id": "7405bf597fb6bb0220ef00a446e5e455cbc3c768", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3740, "license_type": "no_license", "max_line_length": 96, "num_lines": 95, "path": "/NeuralNet/NeuralNet_unittest.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Local imports\nimport Node\nimport InputNode\nimport NeuralNetGlobals as Globals\n\n#External imports\nimport unittest\nimport random\n\nclass TestBaseNode(unittest.TestCase):\n\n def setUp(self):\n '''Set up a default Id to construct the base node.'''\n self._id = Globals.DEFAULT_TEST_ID \n self._test_node = Node.Node(Globals.DEFAULT_TEST_ID) \n self._expected_initial_response = 0\n\n def test_node_construction(self):\n '''Verify that the node constructor behaves as expected.'''\n\n #\\Test identifier is expected value\n #\\Result: no exception thrown\n self.assertEqual(self._test_node.ident, Globals.DEFAULT_TEST_ID)\n \n def test_response_val_at_initialization(self): \n '''Verify the initial response value.'''\n self.assertEqual(self._test_node._response, \\\n self._expected_initial_response)\n \n def test_exception_at_construction(self):\n '''Verify that the constructor throws an exception when no ID''' \n self.assertRaises(TypeError,Node.Node)\n \nclass TestInputNode(TestBaseNode):\n '''InputNode test cases''' \n \n def setUp(self):\n '''Set up for the input node.''' \n self._id = Globals.DEFAULT_TEST_ID \n self._test_node = InputNode.InputNode(Globals.DEFAULT_TEST_ID) \n self._expected_initial_response = Globals.DEFAULT_INITIAL_RESPONSE \n self._test_random_seed = Globals.DEFAULT_RANDOM_SEED \n# Create nex_node_data to be used for some of the tests\n for key in range(Globals.NUMBER_OF_TEST_NODES):\n self._test_node.next_node_data[key]=[0,0]\n \n\n def test_node_has_node_dictionary(self):\n '''Tests that the input node has a self._next_node\n dictionary.'''\n self.assertIsInstance(self._test_node.next_node_data,dict)\n \n def test_input_signal_at_initialization(self):\n '''Test the value of the input signal at initialization.\n Default value of the input signal is zero.'''\n self.assertEqual(self._test_node.input_signal, 0)\n\n def test_random_weight_initialization(self):\n '''Test the weight initialization function. Use a specific random\n seed to generate random weights and compare them to those generated by\n the node.'''\n self._test_node.seed = self._test_random_seed\n self._test_node.use_random = True\n random.seed(self._test_random_seed)\n weight = random.random()\n #\\Test: generated random weight is the same\n #\\Result: number generated by unittest and by the node should \n #\\be the same \n self.assertEqual(self._test_node._retrieve_weight_value(), weight)\n\n def test_non_random_weight_initialization(self):\n '''Test the weight initialization function. This tests specifically \n the case where a single default weight is used.'''\n self._test_node.use_random = False\n #\\Test: generated random weight is the same\n #\\Result: should not throw an exception.\n self.assertEqual(self._test_node._retrieve_weight_value(), Globals.DEFAULT_WEIGHT_VALUE) \n\n def test_initialize_weights(self):\n '''Test the complete weight initialization sequence. Use simulated \n data which is part of the setup. We use random weight values.'''\n self._test_node.use_random = True\n self._test_node.initialize_weights() \n #TODO: Create a logging utility instead of stdout.\n #print(self._test_node.next_node_data)\n #\\Test: make sure that each of the initialized values is not none.\n for key in self._test_node.next_node_data:\n self.assertIsNotNone(\\\n self._test_node.next_node_data[key][Globals.WEIGHT_IDX])\n \n def test_node_forward(self):\n '''Test the node forward method.'''\n \nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5625879168510437, "alphanum_fraction": 0.5773558616638184, "avg_line_length": 34.525001525878906, "blob_id": "2122b679a9bd9b3076d166e55a43d063307cbc84", "content_id": "48735a1d9c034cf290266e8018019cdc73405df2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1422, "license_type": "no_license", "max_line_length": 74, "num_lines": 40, "path": "/Common/CircularBuffer/CircularBuffer.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''Implements functionality for a circular buffer container of any kind'''\n\nclass CircularBuffer(object):\n '''Generic circular buffer class'''\n\n def __init__(self,circ_data=[34,10,5,77,9,45,23,98],\\\n index=0):\n '''Initialization\n Input: circ_data -- data to be managed by the buffer\n by default the series of numbers.\n Useful for testing.\n '''\n self.circ_data = circ_data \n self.index = index\n self.generator = self._generate_data(self.index-1)\n \n def retrieve(self):\n '''Retrieve the next value from the circular buffer. \n Hide the implementation detail from the client.\n '''\n return next(self.generator)\n\n def _generate_data(self, index):\n '''Yield the next value in the circular buffer\n Inputs: index -- index of the desired value,\n offset by -1.\n\n Notes: We deliberately set the offset by -1\n so that the invocation of the generator function\n using 'next' will actually yield the zero index \n function.\n Note that this is essentially a coroutine. The function\n is keep as an infinite loop, and the index is persistent.\n '''\n while True: \n if index == len(self.circ_data)-1:\n index = 0\n else:\n index += 1\n yield self.circ_data[index]\n\n" }, { "alpha_fraction": 0.5986260771751404, "alphanum_fraction": 0.6000981330871582, "avg_line_length": 32.685951232910156, "blob_id": "a626219ff7ece9290e53f48869a31b02bc03d15a", "content_id": "c3335281e736dd0a1ed937d3bddcdd7b8e93d762", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4076, "license_type": "no_license", "max_line_length": 89, "num_lines": 121, "path": "/NeuralNet/Network.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#External imports\nimport pickle\n\n#Local inputs\nimport NeuralNetGlobals as Globals\n\nclass Network(object):\n '''Keeps track of all the weights and all the nodes in a neural net.\n Manages both forward and back propagation.\n '''\n\n def __init__(self):\n '''\n Initialize the network by creating the nodes and associating them according to the \n association list.\n Inputs: \n association_list -- a list of tuples which \n node_list -- a list of lists of nodes. It can also be construed as a \n two-dimensional array \n '''\n\n# The node dictionary \n# has the following format\n# key: Node id, an integer\n# value: Node itself \n# The node dictionary is used when associating the nodes according\n# to the association list.\n self._node_dict = {} \n self._assoc_list=[]\n\n# The following three lists hold the id's of each node\n# Use these to drive the network using the forward(self) method\n# Keep in mind that the netword is an ordered acyclic graph\n self._input_layer_data =[]\n self._hidden_layer_data=[]\n self._output_layer_data=[]\n\n# Load and unpack the node list and the association list \n file_handle = open(Globals.NODE_FILENAME) \n# The container is a two element list, a dictionary and an association list\n container = pickle.load(file_handle)\n self._node_dict = container[0]\n self._assoc_list = container[1]\n\n# The following actually control the network \n self._create_nodes()\n self._associate_nodes()\n self._initialize_weights() \n\n def _create_nodes(self):\n '''\n Create the nodes based on the list provided.\n The list is 'unpickled.' \n '''\n# Capture and iterate through the keys\n node_ids = node_dict.keys() \n for id_el in node_ids:\n# Construct a node assigning it a number and a type\n# type is 'input', 'output', or 'hidden'\n node_type = self.node_dict[id_el]\n# Group the node id's by layer\n switch(node_type)\n {\n case 'input':\n self._input_layer_data.append(node_type)\n aNode = InputNode(id_el)\n break\n case 'hidden':\n self._hidden_layer_data.append(node_type)\n aNode = HiddenNode(id_el)\n break\n case 'output':\n self._output_layer_data.append(node_type)\n aNode = OutputNode(id_el)\n break\n default:\n# TODO: maybe throw an exception\n break\n } \n\n def _associate_nodes(self):\n '''\n Use the association list to connect the input, hidden and \n output nodes. \n '''\n# Initialize weight and signal values\n# TODO: This should probalby be randomized \n weight_value = 0.0\n signal_value = 0.0\n for elem in self._assoc_list\n prev_id = elem[Globals.PREVIOUS]\n next_id = elem[Globals.NEXT]\n prev_node = self._node_list[prev_id]\n next_node = self._node_list[next_id]\n prev_node.next_node_data[next_id] = (weight_value, signal_value) \n next_node.prev_node_data[prev_id] = prev_node \n\n def _execute_loop(self):\n '''Main execution loop. For both forward and back propagation.'''\n pass\n\n def _initialize_weights(self):\n '''Use the association list to create the weights.\n It will iterate through the input and hidden nodes and\n initializes the weights.\n This operation should only be performed once at network initialization.\n '''\n# Input layer initialization\n for item in self._input_layer_data:\n node = self._node_dict[item]\n node.initialize_weights()\n\n# Hidden layer initialization\n for item in self.__layer_data:\n node = self._node_dict[item]\n node.initialize_weights()\n\n# Output layer initialization \n for item in self._layer_data:\n node=self._node_dict[item]\n node.initialize_weights()\n" }, { "alpha_fraction": 0.682584285736084, "alphanum_fraction": 0.7134831547737122, "avg_line_length": 24.428571701049805, "blob_id": "a418306490c07939b12b358d053eebf9269b9177", "content_id": "fbca67d65e53568af5cfd5186cad2ac006810e02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 356, "license_type": "no_license", "max_line_length": 65, "num_lines": 14, "path": "/OpenGLTorus/gutil.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import pygame\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\ndef initializeDisplay(w, h):\n pygame.display.set_mode((w,h), pygame.OPENGL|pygame.DOUBLEBUF)\n\n glClearColor(0.0, 0.0, 0.0, 1.0)\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n gluOrtho2D(0, w, 0, h)\n glMatrixMode(GL_MODELVIEW)\n" }, { "alpha_fraction": 0.6686182618141174, "alphanum_fraction": 0.682084321975708, "avg_line_length": 27, "blob_id": "63acf2e67943447cfdde28997e1ddc900190fb6d", "content_id": "1223b9582fff371d382ccce3f9d72ed75aac51d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1708, "license_type": "no_license", "max_line_length": 69, "num_lines": 61, "path": "/CellularAutomata/Rule30.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Starting from an initial configuration, print a celular automata\n\nfrom math import pow\n\ndef computeHash(sequence, start, end):\n '''\n Compute the hash of a binary triplet.\n The hash function in this case is just the equivalent\n decimal value.\n We avail ourselves of the mystifying power of list \n comprehensions.\n '''\n triplet = list(sequence[start:end])\n tmp.reverse()\n hash = int(sum([tmp[i]*pow(2,i) for i in range(len(triplet))]))\n return hash\n\ndef applyRule(hash, triplet, originalIndex):\n '''\n Apply the rule to the existing triplet.\n Inputs:\n hash - computed for the given triplet\n triplet - triplet consisting of a cell and its neighbors\n originalIndex - index in the original configuration\n '''\n triplet[originalIndex] = rulesTable[hash] \n \ndef runConfiguration(initConfig):\n '''\n Run a celular automata configuration through a given number \n of generation.\n '''\n# Break the pattern into sets of three and shift as needed \n# initialIndex = 0 \n# index = initialIndex\n# inc= 3\n# while index < len(initConfig):\n# print the triplets\n# print initConfig[index:index+inc]\n# apply the rule\n# index += 3\n\n triplets = [initConfig[i:i+3] for i in range(0,len(initConfig),3) ]\n print triplets\n\n# Test the ever so complicated hashing function\n print computeHash(triplets[0])\n print computeHash(triplets[1])\n print computeHash(triplets[2])\n\n# Unwrap the list here\n finalConfig = []\n for i in range(0,len(triplets),1):\n for j in range(0,len(triplets[i]),1):\n finalConfig.append(triplets[i][j])\n\n print finalConfig\n\nif __name__ == '__main__':\n initConfig = [0,0,0,0,1,0,0,0,0]\n runConfiguration(initConfig)\n" }, { "alpha_fraction": 0.6437111496925354, "alphanum_fraction": 0.6561453938484192, "avg_line_length": 31.169231414794922, "blob_id": "2450f318e50a3e1eafc11eabae4ae65ec4e0a8fd", "content_id": "e1d4d44d26dfc0f380d7f26847a28321d462864a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2091, "license_type": "no_license", "max_line_length": 72, "num_lines": 65, "path": "/HeapSort/HeapSort.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "'''This function implements a simple heap sort algorithm. It begins by\n generating a heap data structure from an array ans then arranging the\n elements of the heap. '''\n\nimport random\nimport math\n#add DisplayUtils to the path. Assume that the library is built\nimport sys\nsys.path.append('/home/allan/WorkingCopy/DisplayUtils')\nimport DisplayUtils\n\ndef main():\n '''Main driver function for the heap sort algorithm. All testing \n done here.'''\n #Generate a random set of 20 numbers between 0 and 20\n L = []\n for i in range(10):\n L.append(random.randrange(20))\n\n print \"Initial array: \", L\n print \"List from array: \", list_to_string(L) \n #Assuming you have at least two levels, show all the \n #elements in level 2:\n print \"Elems in level 2:\", elems_in_level(2,L)\n\ndef list_to_string(L):\n '''Given a list, generate a string of the elements of the list\n separated by a space'''\n\n M = ''.join([str(x)+' ' for x in L])\n return M\n\ndef generate_heap(L):\n '''Traverse an array and report back the parent,\n left and right elements of the array. Display\n these as a tree'''\n pass \n\ndef display_as_tree(L):\n '''Take a list and display its contents as a binary\n tree based on the heap indices, for lack of a better\n term.\n '''\n #Compute the number of levels in the tree\n num_levels = int(math.ceil(math.log(len(L),2)) ) \n\n #To display correctly, you should do a zero fill to \n #the nearest power of two \n for i in range(num_levels):\n DisplayUtils.print_at(40, list_to_string(elems_in_level(i, L) ) )\n\ndef elems_in_level(level_num, L):\n '''Assuming that an array can be cast as a binary tree, \n return that portion of the array which would correspond to \n level in the tree.\n '''\n #2^level_num -- will not work\n first_idx = int(math.ldexp(1,level_num) ) \n last_idx = int( min( math.ldexp(1, level_num+1) -1, len(L)-1 ) )\n #min(2^(level_num+1)-1, len(L) -1) -- will not work \n print level_num, first_idx, last_idx\n return L[first_idx:last_idx+1] \n \nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6601479649543762, "alphanum_fraction": 0.6686046719551086, "avg_line_length": 27.65151596069336, "blob_id": "1a4463b5fc0dbee7d6dbeaa7bd88520324925470", "content_id": "98dd169892e745b7cdc04c5260deb5f9f1d77113", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1892, "license_type": "no_license", "max_line_length": 74, "num_lines": 66, "path": "/ImageProcessing/ImageProcessing.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import Image\n\ndef main():\n '''Main module'''\n with open('texture.raw','rb') as f:\n im = Image.fromstring('RGB',(256,256),f.read())\n im.show()\n\n# Convert the data to string\n# TODO: find a better way to do this, so that the string\n# structure is bypassed altogether\n rawDataString = im.tostring()\n rawDataList = list(rawDataString)\n# Pick a single channel (channels are interleaved (RGBRGBRGB))\n filteredDataList = rawDataList[0::3]\n# Convert the filtered data to a string and reconstruct the image\n filteredString = ''.join(filteredDataList)\n# 'L' encoding is gray scale\n filteredIm = Image.fromstring('L',(256,256), filteredString)\n filteredIm.show()\n# Close the file\n f.close()\n# Save the image as a jpg\n im.save('texture.jpg')\n\n# Open a jpg image and convert it to raw output\n jpg_im=Image.open('Earth_tilt_sample.jpg')\n jpg_im.show()\n\n\n# Size is a tuple\n# print jpg_im.size\n#print jpg_im.info\n\n# Convert the data to buffer and then to a list\n jpg_list = list(jpg_im.tostring())\n filtered_jpg_list = jpg_list[0::3]\n filtered_jpg_string = ''.join(filtered_jpg_list)\n filtered_jpg_im = Image.fromstring('L',jpg_im.size,filtered_jpg_string)\n filtered_jpg_im.show()\n\n# Save the raw single channel data\n with open('Earth_tilt_sample_gray.raw', 'wb') as f:\n f.write(filtered_jpg_string)\n f.close()\n\n# Reopen the raw single channel data and redisplay\n with open('Earth_tilt_sample_gray.raw','rb') as f:\n readIm = Image.fromstring( 'L',jpg_im.size,f.read() )\n readIm.show()\n f.close()\n\n# Save the raw three channel data\n with open('Earth_tilt_sample.raw', 'wb') as f:\n f.write(jpg_im.tostring() )\n f.close()\n\n# Reopen the raw data and redisplay\n with open('Earth_tilt_sample.raw','rb') as f:\n readIm = Image.fromstring( 'RGB',jpg_im.size,f.read() )\n\n f.close()\n readIm.show()\n\nif __name__ == '__main__':\n main()\n\n" }, { "alpha_fraction": 0.7516778707504272, "alphanum_fraction": 0.7718120813369751, "avg_line_length": 28.799999237060547, "blob_id": "1743dcceacafe0e21579b860157807bf6bde6077", "content_id": "daea77e559f39e29bed39ddb19803f3691db7403", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 149, "license_type": "no_license", "max_line_length": 59, "num_lines": 5, "path": "/QuickSort/README.txt", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "My implementation of the quick sort algorithm using python.\nIn short:\n(1) Find the pivot point\n(2) Partition on the pivot point\n(3) Apply quick sort\n" }, { "alpha_fraction": 0.8142856955528259, "alphanum_fraction": 0.8142856955528259, "avg_line_length": 34, "blob_id": "01c94e5a7c4c0e3474336a278e7c42c2c17f2b97", "content_id": "650ef3d763c5ddbfa003fd8bab75ef5de5cd173f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 140, "license_type": "no_license", "max_line_length": 72, "num_lines": 4, "path": "/MergeSort/README.txt", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "This directory contains an implementation of the merge sort algorithm in\npython. \n\nOne of many attempts to elucidate the use of algorithms.\n" }, { "alpha_fraction": 0.6074380278587341, "alphanum_fraction": 0.6074380278587341, "avg_line_length": 25.22222137451172, "blob_id": "884249e932d52ba22f18bf3372d40e494a38b151", "content_id": "5e552639a721fe3f499cc07f37579fe5932ef512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 41, "num_lines": 9, "path": "/Inheritance/BaseClass.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "class BaseClass(object):\n \n def __init__(self, color='green'):\n self.color = color \n# May be overriden in the base class\"\n self._construction()\n \n def _construction(self):\n print \"Constructing the base class\"\n \n" }, { "alpha_fraction": 0.6389011740684509, "alphanum_fraction": 0.6389011740684509, "avg_line_length": 30.760562896728516, "blob_id": "96307788501d6273137bbcd19abd148fd0c3a4a0", "content_id": "48d84f0a51ccc2b9aa5ab1a9dd521ac67f5ff669", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 75, "num_lines": 71, "path": "/NeuralNet/OutputNode.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "#Local imports\nfrom Node import Node\nimport NeuralNetGlobals as Globals\n\nclass OutputNode(Node):\n\n def __init__(self, identifier):\n '''Initialization function for output nodes.\n Initialize the base node first.\n Keep in mind that OutputNodes do not have \n next_node_data\n '''\n\n Node.__init__(self, identifier)\n\n# Dictionaries of input and output signals\n# In the input nodes, the structure is:\n# key: Node id, an integer\n# value: a reference to the node itself\n self.prev_node_data={}\n\n# Signals from the previous nodes are collected here.\n self._input_signals=[]\n\n\n def forward(self):\n '''Collects the input signals.\n Computes the response.\n '''\n self._collect_input_signals()\n self._compute_response()\n \n def _collect_input_signals(self):\n '''Collect the input signals, based on the output of the input nodes.\n The signals are assumed to be weighted by the previous node.\n '''\n for key in self.prev_node_data:\n prev_node = self.prev_node_data[key]\n value = prev_node.next_node_data[self.ident][Globals.SIGNAL_IDX]\n\n# Obtain the output of the previous node for this node\n self._input_signals.append(value) \n\n def _compute_response(self):\n '''Compute the output value based on a threshold function'''\n total = sum(self._input_signals)\n\n# Compute the response based on the threshold function\n self._response = self._threshold(total)\n\n def backward(self):\n '''Computes the error.\n Back propagates the weights.\n '''\n self._compute_errors()\n self._back_propagate_weights()\n\n# Use the expected output to compute the error\n def _compute_errors(self):\n '''Compute the errors based on the actual and desired outputs.\n\n '''\n self._error = abs(self.desired_output - self._response) \n\n def _back_propagate_weights(self):\n '''Use the computed error to update the weight values.'''\n for key in self.prev_node_data:\n node = self.prev_node_data[key]\n weight = node.next_node_data[self.ident][WEIGHT_IDX]\n weight = weight + self._error\n node.next_node_data[self.ident][WEIGHT_IDX] = weight \n\n" }, { "alpha_fraction": 0.5729702115058899, "alphanum_fraction": 0.631723165512085, "avg_line_length": 29.24870491027832, "blob_id": "36723954fab69a5625514fa440fc9d1f28ed05f3", "content_id": "cd05a40343df010e9da48564c4672d8815728c4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5838, "license_type": "no_license", "max_line_length": 115, "num_lines": 193, "path": "/OpenGLTorus/OpenGLTorus.py", "repo_name": "aarcher/python-general", "src_encoding": "UTF-8", "text": "import gutil\nimport pygame\nfrom pygame.locals import *\nfrom OpenGL.GL import *\nfrom OpenGL.GLUT import *\nfrom math import *\n\n\ndef main():\n displayWidth = 800\n displayHeight = 600\n pygame.init()\n \n done = False\n \n init(displayWidth, displayHeight)\n\n glColor4f(1.0,1.0,1.0,1.0)\n\n while not done:\n render(displayWidth, displayHeight)\n pygame.display.flip()\n eventlist = pygame.event.get()\n for event in eventlist:\n if event.type == QUIT\\\n or event.type == KEYDOWN and event.key == K_ESCAPE:\n done = True\n\ndef render(w,h):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n glClearColor(.3, .5, .8, 1.0)\n glLoadIdentity()\n glPushMatrix()\n glTranslatef(w/2.0, h/2.0, 0.0);\n drawTorus(10, 200, 15, 15)\n glPopMatrix()\n \n glBegin(GL_QUADS)\n glVertex2i(-50, -50)\n glVertex2i(50, -50)\n glVertex2i(50, 50)\n glVertex2i(-50, 50)\n glEnd()\n#glPopMatrix()\n\n# Java code\n# float frot = rot;\n# \t\tGL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);\n# \t\tGL11.glClearColor(.3f, .5f, .8f, 1.0f);\n# \t\tGL11.glLoadIdentity();\n# \t\tGL11.glPushMatrix();\n# \t\t/*Use the following with orthographic mode*/\n# \t\tGL11.glTranslatef(Display.getDisplayMode().getWidth() / 2, Display.getDisplayMode().getHeight() / 2, 10*frot);\n# \t\t/*END <use orthographic*/\n# \t\t \n# \t\t/*Use the following in perspective mode*/\n# \t\t//GL11.glTranslatef(0.0f,0.0f,-(float)rot*2.0f);\n# \t\t/*END <use perspective.*/\n# \t\t\n# \n# \t\tGL11.glRotatef(0.15f * rot, 2.0f * frot, 10.0f * frot, 1.0f);\n# \t\tGL11.glRotatef(0.3f * rot, 3.0f * frot, 1.0f * frot, 1.0f);\n# \t\tGL11.glRotatef(0.3f*rot,0.0f,0.0f,1.0f);\n# \t\trot++;\n# \t\tGL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);\n# \t\tGL11.glColor3f(0.9f, 0.9f, 0.9f);\n# \t\tdrawTorus(10, 20, 15, 15);\n# \t\t//drawTorus(5f+((float) Math.sin((0.004f * frot))), 5f+((float) Math.sin((0.004f * frot))), 15, 15);\n# \t\t\n# \t\t/*GL11.glBegin(GL11.GL_QUADS);\n# \t\tGL11.glVertex2i(-50, -50);\n# \t\tGL11.glVertex2i(50, -50);\n# \t\tGL11.glVertex2i(50, 50);\n# \t\tGL11.glVertex2i(-50, 50);\n# \t\tGL11.glEnd();*/\n# \t\tGL11.glPopMatrix();\n \n\ndef drawTorus(r, R, nsides, rings): \n ringDelta = 2.0 * pi/rings\n sideDelta = 2.0 * pi/nsides\n theta = 0.0 \n cosTheta = 1.0 \n sinTheta = 0.0\n i = rings - 1\n\n theta1 = theta + ringDelta\n cosTheta1 = cos(theta1)\n sinTheta1 = sin(theta1)\n glBegin(GL_QUAD_STRIP)\n\n phi = 0.0\n j = nsides\n while (j >= 0):\n phi += sideDelta\n cosPhi = cos(phi)\n sinPhi = cos(phi)\n dist = R + r * cosPhi\n\n glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi)\n glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi)\n glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi)\n glVertex3f(cosTheta * dist, -sinTheta * dist, r * sinPhi)\n j = j -1\n\n glEnd()\n\ndef init(w,h):\n\n pygame.display.set_mode((w,h), pygame.OPENGL|pygame.DOUBLEBUF)\n\n glClearColor(0.0, 0.0, 0.0, 1.0)\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n glEnable(GL_TEXTURE_2D)\n glEnable(GL_CULL_FACE)\n glEnable(GL_DEPTH_TEST)\n glDepthFunc(GL_LEQUAL)\n glShadeModel(GL_SMOOTH)\n glViewport(0, 0, w, h) \n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glOrtho(0, w, 0, w, -800, 800);\n glMatrixMode(GL_MODELVIEW)\n glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)\n glLoadIdentity()\n#\n#Java code\n#\t\t\n#private static void init(boolean fullscreen) throws Exception {\n#\t\t// Create a fullscreen window with 1:1 orthographic 2D projection (default)\n#\t\tDisplay.setTitle(GAME_TITLE);\n#\t\tDisplay.setFullscreen(fullscreen);\n#\n#\t\t// Enable vsync if we can (due to how OpenGL works, it cannot be guarenteed to always work)\n#\t\tDisplay.setVSyncEnabled(true);\n#\n#\t\t// Create default display of 640x480\n#\t\tDisplay.create();\n#\t\t// run through some based OpenGL capability settings. Textures\n#\t\t// enabled, back face culling enabled, depth testing is on,\n#\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\n#\t\tGL11.glEnable(GL11.GL_CULL_FACE);\n#\t\tGL11.glEnable(GL11.GL_DEPTH_TEST);\n#\t\tGL11.glDepthFunc(GL11.GL_LEQUAL);\n#\t\tGL11.glShadeModel(GL11.GL_SMOOTH); \n#\t\t\t\n#\t\tfloat fAspect = Display.getDisplayMode().getWidth()/Display.getDisplayMode().getHeight();\n#\t\t// define the properties for the perspective of the scene\n#\t\tSystem.out.println(fAspect);\n#\t\tGL11.glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());\n#\t\tGL11.glMatrixMode(GL11.GL_PROJECTION);\n#\t\tGL11.glLoadIdentity();\t\n#\t\t//GL11.glOrtho(0, Display.getDisplayMode().getWidth(), 0, Display.getDisplayMode().getHeight(), -800, 800);\n#\t\t\n#\t\tGLU.gluPerspective(\n#\t 30.0f, // Field Of View\n#\t fAspect, // aspect ratio\n#\t 1f, // near Z clipping plane\n#\t 800.0f); // far Z clipping plane\n#\t\t\n#\t\tGL11.glMatrixMode(GL11.GL_MODELVIEW);\n#\t\tGL11.glHint(GL11.GL_PERSPECTIVE_CORRECTION_HINT, GL11.GL_NICEST);\n#\t\tGL11.glLoadIdentity();\n\n\n\n#Java code\n#\tfor (int i = rings - 1; i >= 0; i--) {\n#\t\t\tfloat theta1 = theta + ringDelta;\n#\t\t\tfloat cosTheta1 = (float) Math.cos(theta1);\n#\t\t\tfloat sinTheta1 = (float) Math.sin(theta1);\n#\t\t\tGL11.glBegin(GL11.GL_QUAD_STRIP);\n#\t\t\tfloat phi = 0.0f;\n#\t\t\tfor (int j = nsides; j >= 0; j--) {\n#\t\t\t\tphi += sideDelta;\n#\t\t\t\tfloat cosPhi = (float) Math.cos(phi);\n#\t\t\t\tfloat sinPhi = (float) Math.sin(phi);\n#\t\t\t\tfloat dist = R + r * cosPhi;\n#\t\t\t\tGL11.glNormal3f(cosTheta1 * cosPhi, -sinTheta1 * cosPhi, sinPhi);\n#\t\t\t\tGL11.glVertex3f(cosTheta1 * dist, -sinTheta1 * dist, r * sinPhi);\n#\t\t\t\tGL11.glNormal3f(cosTheta * cosPhi, -sinTheta * cosPhi, sinPhi);\n#\t\t\t\tGL11.glVertex3f(cosTheta * dist, -sinTheta * dist, r * sinPhi);\n#\t\t\t}\n#\t\t\tGL11.glEnd();\n#\t\t\ttheta = theta1;\n#\t\t\tcosTheta = cosTheta1;\n#\t\t\tsinTheta = sinTheta1;\n#\t\t}\n#\t}/*END static void drawTorus*/\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
48
trichimtrich/testrtc2
https://github.com/trichimtrich/testrtc2
c0856b561ab8463f63108250762dfd1584f474ec
67b4d03c74ec416b6fd723ecec5b7ada7e53a30e
747cc1b483f4827f82b3c4a05e5efc6dd84bea1d
refs/heads/master
2022-04-27T07:43:33.035507
2020-04-26T13:46:57
2020-04-26T13:46:57
259,023,539
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5568862557411194, "alphanum_fraction": 0.5568862557411194, "avg_line_length": 8.823529243469238, "blob_id": "79858afa2e346a59eeb309557a855e91db94cde3", "content_id": "d9c52c56f053e2a1e9ce0bf22c81b80e09ce6541", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 167, "license_type": "no_license", "max_line_length": 24, "num_lines": 17, "path": "/go/screen/misc.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package screen\n\n// maximum\nfunc Max(a, b int) int {\n\tif a >= b {\n\t\treturn a\n\t}\n\treturn b\n}\n\n// minimum\nfunc Min(a, b int) int {\n\tif a <= b {\n\t\treturn a\n\t}\n\treturn b\n}\n" }, { "alpha_fraction": 0.7318246960639954, "alphanum_fraction": 0.7423592209815979, "avg_line_length": 37.838382720947266, "blob_id": "f691f1ad984d6fc3792abee4788a40ca32abf4b1", "content_id": "6cadebee8ff2f460d594823ee03ce9b297e342b4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7719, "license_type": "no_license", "max_line_length": 203, "num_lines": 198, "path": "/README.md", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "# testrtc2\n\n**ToC**\n\n- [Intro](#intro)\n- [Features](#features)\n- [Components](#components)\n - [Signal server](#signal-server)\n - [Web client](#web-client)\n - [Golang client](#golang-client)\n - [Flutter/dart client](#flutterdart-client)\n- [Usage](#usage)\n- [Notes](#notes)\n- [TODO](#todo)\n\n## Intro\n\nAnother test clients for [WebRTC](https://webrtc.org/), included multiple clients implemented in\n- Vanila JS - works on all modern browsers (Chromium + Firefox + Safari)\n- Golang with [pion](https://github.com/pion/webrtc) library - works on any Desktop OS\n- Flutter/Dart lang with [Flutter-WebRTC](https://pub.dev/packages/flutter_webrtc) wrapper - works on Mobile (iOS + Android) + Chromium\n\nThe old repo [testrtc](https://github.com/trichimtrich/testrtc) was made to do blackbox connectivity test/experiment between nodes (behide NAT, dockerize environment, other locations, ...)\n\nWith this repo, we aim to experiment the compatibility/functionality between clients.\n\n\n\n## Features\n\nCan break down each clients to parts:\n- Connectivity:\n - Signaling (via websocket)\n - Init / close peer connection\n- Transceiver (transport unit): [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTransceiver)\n - Add on kinds: audio / video\n - Add on directions: sendrecv / sendonly / recvonly\n- SDP role:\n - CreateOffer -> local SDP: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createOffer)\n - Options for CreateOffer\n - CreateAnswer -> local SDP: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createAnswer)\n - Send local SDP to peer (-> set remote SDP)\n- ICE gathering:\n - Capture ICE Candidate from STUN / TURN: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/onicecandidate)\n - Send local ICE Candidate to peer (via signal)\n - Receive remote ICE Candidate from peer (via signal)\n - Add remote ICE Candidate from peer: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addIceCandidate)\n - Restart ICE: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/restartIce)\n- Media stream:\n - Add sample video track: [Link1](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack) [Link2](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream)\n - Add sample audio track: [Link1](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack) [Link2](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream)\n - Add webcam track: [Link1](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack) [Link2](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)\n - Add microphone track: [Link1](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/addTrack) [Link2](https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia)\n - Remove all added tracks: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/removeTrack)\n- Data channel:\n - Add data channel: [Link](https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel)\n - Close all data channels\n\nWith these breakdown parts we can do blackbox test to watch behavior of each clients:\n- What if we set local and remote SDP but don't add ICE\n- What if we set remote SDP twice\n- What if we send tracks to peer without transceiver\n- What if we add media track before createOffer\n- What if we add media track after createAnswer\n- What if we close data channel\n- ...\n\n## Components\n\n```\n.\n├── README.md\n├── flutter --> flutter client\n├── go --> golang client\n├── signal.py --> signal server\n├── web.html --> web client\n```\n\n### Signal server\n\nVery simple websocket implementation in Python\n- Assign an ID for each connection (use as userID, peerID in client)\n- Forward message between IDs\n\nInstall\n```bash\n$ pip install websocket_server\n```\n\nRun\n```bash\n$ python signal.py HOST PORT\n$ python signal.py 127.0.0.1 6789\n```\n\n### Web client\n\nFull features, can run `web.html` directly in browser on multiple platforms. Or you can serve it via a webserver (some browsers might need a web origin)\n\nExample:\n```bash\n$ python -m http.server PORT --bind HOST\n```\n\n### Golang client\n\nGolang version works in interactive terminal graphic, and only implemented some parts\n- connectivity\n- create and send offer\n- automatic answer from remote SDP\n- media tracks (gststreamer)\n- data channel\n\nNeeds to install `gststreamer` dependency first for this to work.\n\n```bash\n# Debian / Ubuntu\n$ sudo apt-get install libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev gstreamer1.0-plugins-good\n\n# Windows MinGW64/MSYS2\n$ pacman -S mingw-w64-x86_64-gstreamer mingw-w64-x86_64-gst-libav mingw-w64-x86_64-gst-plugins-good mingw-w64-x86_64-gst-plugins-bad mingw-w64-x86_64-gst-plugins-ugly\n\n# macOS\n$ brew install gst-plugins-good gst-plugins-ugly pkg-config && export PKG_CONFIG_PATH=\"/usr/local/opt/libffi/lib/pkgconfig\"\n```\n\nRun\n```bash\n$ cd go\n$ go run . -addr SIGNALSV\n\n# example\n$ go run . -addr 127.0.0.1:6789\n```\n\nIf this somehow `panic`, please use `reset` command to reset terminal graphic\n\n### Flutter/dart client\n\nFlutter/dart version only acts as receiver, no added media track support\n\n- Install flutter SDK first depends on your platform : [Link](https://flutter.dev/docs/get-started/install)\n\n- Run flutter\n - iOS/Android:\n ```bash\n $ cd flutter\n $ flutter run\n ```\n - Chromium: \n ```bash\n $ cd flutter\n $ flutter run -d chrome\n ```\n\nFlutter is supposed to be `write once, compile and run anywhere`. You can compile this source code to standalone app easily with flutter -> [Link](https://flutter.dev/docs/testing/build-modes)\n\nThis client uses a wrapper for WebRTC\n- iOS/Android: binding for libWebRTC -> compile to native app\n- Web: binding for WebRTC JS API -> compile to web app\n\nIf you are facing the problem run in Firefox or Safari with this flutter web app, because there is an issue with `dart:html` (by the commit timestamp of this README)\n- https://github.com/dart-lang/sdk/issues/38787\n\n## Usage\n\n1. Run Signal server first\n2. Connect 2 peers to Signal server\n3. From 1 peer ping to other peer (by their IDs), so both parties know each others\n4. In Web client, you have to create PeerConnection manually (intended)\n5. Do whatever test you want to...\n\n## Notes\n\nThis repo is used for blackbox testing between clients, not to claim and disclaim anything. Here is my personal results:\n- First call of CreateOffer and CreateAnswer will immediately create lots of local ICE candidates (from STUN/TURN).\n- Remote ICE candidates should be added only after remote SDP is set.\n- ICE candidates should be transfer at least from 1 peer to another to make successful connection. But very stable when both parties exchange their local ICE candidates.\n- Add transreceiver is not neccessary needed to send/recv tracks.\n- After successful connection between parties, any party can createOffer to other.\n- `offerToReceiveVideo` and `offerToReceiveAudio` work as expected.\n- Media provider should be the one createOffer.\n- Media track should be added before createOffer.\n- Added media tracks will not send immediately, need renegotiation (createOffer -> createAnswer).\n- Same thing with DataChannel\n- Restart Ice does not work, and asks for renegotiation.\n\nThis result was conducted between Web - Go Client in Chrome/Safari/Firefox on MacOS.\n\n## TODO\n\n- setConfiguration for peerConnection\n- DataChannel with name\n- send message via DataChannel\n- replaceTrack\n- codec(?)\n- view and edit SDP(?)\n- stats" }, { "alpha_fraction": 0.6826156377792358, "alphanum_fraction": 0.6985645890235901, "avg_line_length": 18, "blob_id": "80840838679f5842b0ab560f5d07e397e5ffa7e3", "content_id": "0383d6e6fcd6ba3818ad47d1800d1fb9e8acf16b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 627, "license_type": "no_license", "max_line_length": 57, "num_lines": 33, "path": "/go/network/misc.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package network\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n)\n\n// Encode encodes the input in base64\n// It can optionally zip the input before encoding\nfunc Encode(obj interface{}) (result string, err error) {\n\tb, err := json.Marshal(obj)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = base64.StdEncoding.EncodeToString(b)\n\treturn\n}\n\n// Decode decodes the input from base64\n// It can optionally unzip the input after decoding\nfunc Decode(in string, obj interface{}) error {\n\tb, err := base64.StdEncoding.DecodeString(in)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = json.Unmarshal(b, obj)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n" }, { "alpha_fraction": 0.6460626721382141, "alphanum_fraction": 0.6613039970397949, "avg_line_length": 20.472726821899414, "blob_id": "c0a477cf9923f059f2b0c15949d44e619911bfd3", "content_id": "7707ada97e64a4e62b6dd611785010a9c59a1e27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1181, "license_type": "no_license", "max_line_length": 77, "num_lines": 55, "path": "/go/main.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package main\n\nimport (\n\t\"flag\"\n\t\"strings\"\n\n\t\"testrtc2/network\"\n\t\"testrtc2/screen\"\n)\n\nfunc main() {\n\taddr := flag.String(\"addr\", \"192.168.1.104:6789\", \"websocket signal server\")\n\tflag.Parse()\n\n\tquit := make(chan struct{})\n\n\t// terminal\n\tscreen := screen.NewScreen()\n\tscreen.Init()\n\tscreen.SetTitle(\"Enter command ...\")\n\tscreen.Log(\"[System] Welcome to WebRTC Demo - Pion2 Golang\")\n\tscreen.Show()\n\tgo screen.RenderLoop(quit)\n\tgo screen.EventLoop(quit)\n\n\t// create websocket + webrtc\n\tws := network.NewWebSocket(screen)\n\trtc := network.NewWebRTC(screen)\n\tws.SetWebRTC(rtc)\n\trtc.SetWebSocket(ws)\n\n\t// register createOffer callback\n\tscreen.RegisterCallback(func(data string) {\n\t\tif data == \"/new\" {\n\t\t\t// run in routine, dial might take long time\n\t\t\t// also init webrtc when establishing ws connection\n\t\t\tgo ws.Connect(*addr)\n\t\t} else if strings.HasPrefix(data, \"/peer \") {\n\t\t\tpeerID := data[6:]\n\t\t\tws.SetPeer(peerID)\n\t\t} else if data == \"/media\" {\n\t\t\trtc.AddMedia()\n\t\t} else if data == \"/data\" {\n\t\t\trtc.CreateDataChannel()\n\t\t} else if data == \"/offer\" {\n\t\t\trtc.CreateOffer()\n\t\t} else {\n\t\t\tscreen.Log(\"[System] Unknown command\")\n\t\t}\n\t\tscreen.SetBuffer(\"\")\n\t})\n\n\t<-quit\n\tscreen.Fini()\n}\n" }, { "alpha_fraction": 0.6695467233657837, "alphanum_fraction": 0.6736789345741272, "avg_line_length": 23.80124282836914, "blob_id": "064300073152cf56033ae3e7446478671caee4dc", "content_id": "83339d938982782ce3b0170c10feb960645cf772", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 7986, "license_type": "no_license", "max_line_length": 100, "num_lines": 322, "path": "/go/network/webrtc.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package network\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\n\t\"testrtc2/gst\"\n\t\"testrtc2/screen\"\n\n\t\"github.com/pion/webrtc/v2\"\n)\n\ntype WebRTC struct {\n\tscreen *screen.Screen\n\tws *WebSocket\n\tconn *webrtc.PeerConnection\n\tisOffering bool\n\tisPeered bool\n\tpipes []*gst.Pipeline\n}\n\nfunc NewWebRTC(screen *screen.Screen) *WebRTC {\n\treturn &WebRTC{screen, nil, nil, false, false, nil}\n}\n\nfunc (rtc *WebRTC) SetWebSocket(ws *WebSocket) {\n\trtc.ws = ws\n}\n\nfunc (rtc *WebRTC) StopPipe() {\n\t// stop pipe\n\tfor _, pipe := range rtc.pipes {\n\t\tpipe.Stop()\n\t\trtc.screen.Log(\"[Track] Stop a pipe\")\n\t}\n\trtc.pipes = nil\n}\n\nfunc (rtc *WebRTC) Reset() {\n\trtc.StopPipe()\n\trtc.isOffering = false\n\trtc.isPeered = false\n\n\tif rtc.conn != nil {\n\t\trtc.conn.Close()\n\t\trtc.screen.Log(\"[System] Close previous peer connection\")\n\t\trtc.conn = nil\n\t}\n}\n\nfunc (rtc *WebRTC) registerDataCallback(channel *webrtc.DataChannel) {\n\tchannel.OnOpen(func() {\n\t\trtc.screen.Log(\"[DataChannel] OnOpen\")\n\t\tchannel.SendText(\"ping\")\n\t})\n\n\tchannel.OnError(func(err error) {\n\t\trtc.screen.Log(\"[DataChannel] OnError: \" + err.Error())\n\t})\n\n\tchannel.OnClose(func() {\n\t\trtc.screen.Log(\"[DataChannel] OnClose\")\n\t})\n\n\tchannel.OnMessage(func(msg webrtc.DataChannelMessage) {\n\t\tif msg.IsString {\n\t\t\tst := string(msg.Data)\n\t\t\trtc.screen.Log(\"[DataChannel] OnMessage: \" + st)\n\t\t\tif st == \"ping\" {\n\t\t\t\tchannel.SendText(\"pong\")\n\t\t\t}\n\t\t} else {\n\t\t\t// pass\n\t\t}\n\t})\n\n\trtc.screen.Log(\"[DataChannel] Register callbacks\")\n}\n\nfunc (rtc *WebRTC) CreateDataChannel() {\n\tif rtc.conn == nil {\n\t\trtc.screen.Log(\"[System] No peer connection to create data channel\")\n\t\treturn\n\t}\n\n\t// DataChannel\n\tchannel, err := rtc.conn.CreateDataChannel(\"data\", nil)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create data channel failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] Create Data Channel\")\n\n\trtc.registerDataCallback(channel)\n}\n\nfunc (rtc *WebRTC) AddMedia() {\n\tif rtc.conn == nil {\n\t\trtc.screen.Log(\"[System] No peer connection to add media\")\n\t\treturn\n\t}\n\n\t// stop pipelines\n\trtc.StopPipe()\n\n\t// remove all media sender\n\tfor _, sender := range rtc.conn.GetSenders() {\n\t\trtc.screen.Log(\"[WebRTC] Remove track - \" + sender.Track().Label())\n\t\trtc.conn.RemoveTrack(sender)\n\t}\n\n\t// Audio Track\n\topusTrack, err := rtc.conn.NewTrack(webrtc.DefaultPayloadTypeOpus, rand.Uint32(), \"audio\", \"pion1\")\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create new audio track failed: \" + err.Error())\n\t\treturn\n\t}\n\n\trtc.screen.Log(\"[WebRTC] create new audio track\")\n\n\t_, err = rtc.conn.AddTrack(opusTrack)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] add new audio track failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] add new audio track\")\n\n\t// Video Track\n\tvp8Track, err := rtc.conn.NewTrack(webrtc.DefaultPayloadTypeVP8, rand.Uint32(), \"video\", \"pion2\")\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create new video track failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] create new video track\")\n\n\t_, err = rtc.conn.AddTrack(vp8Track)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] add new video track failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] add new video track\")\n\n\t// build pipelines\n\taudioSrc := \"audiotestsrc ! audioconvert ! queue\"\n\tvideoSrc := \"videotestsrc pattern=snow ! video/x-raw,width=320,height=240 ! queue\"\n\n\tpipe1 := gst.CreatePipeline(webrtc.Opus, []*webrtc.Track{opusTrack}, audioSrc)\n\tpipe2 := gst.CreatePipeline(webrtc.VP8, []*webrtc.Track{vp8Track}, videoSrc)\n\trtc.pipes = append(rtc.pipes, pipe1, pipe2) // lazy, have to remove pipes first\n\n\t// starting...\n\tpipe1.Start()\n\tpipe2.Start()\n\n\t// if rtc.isPeered {\n\t// \t// already in connection, re-offer?\n\t// \trtc.CreateOffer()\n\t// }\n}\n\nfunc (rtc *WebRTC) CreateOffer() {\n\tif rtc.conn == nil {\n\t\trtc.screen.Log(\"[System] No peer connection to make offer\")\n\t\treturn\n\t}\n\n\tif rtc.ws.GetPeer() == \"\" {\n\t\trtc.screen.Log(\"[System] Need to set peer ID first\")\n\t\treturn\n\t}\n\n\trtc.isOffering = true\n\n\t// Create Offer\n\toffer, err := rtc.conn.CreateOffer(nil)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create offer failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] create offer\")\n\n\trtc.setLocalSDP(offer)\n}\n\nfunc (rtc *WebRTC) setLocalSDP(desc webrtc.SessionDescription) {\n\terr := rtc.conn.SetLocalDescription(desc)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] set local sdp failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] local sdp set\")\n\n\tsdp, err := Encode(desc)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] sdp encode failed: \" + err.Error())\n\t\treturn\n\t}\n\n\trtc.ws.SendMessage(Message{\"sdp\", sdp})\n}\n\nfunc (rtc *WebRTC) createAnswer() {\n\tanswer, err := rtc.conn.CreateAnswer(nil)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create answer failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] answer created\")\n\n\trtc.setLocalSDP(answer)\n}\n\nfunc (rtc *WebRTC) SetRemoteSDP(sdp string) {\n\tdesc := webrtc.SessionDescription{}\n\terr := Decode(sdp, &desc)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] sdp decode failed: \" + err.Error())\n\t\treturn\n\t}\n\n\terr = rtc.conn.SetRemoteDescription(desc)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] set remote sdp failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] remote sdp set\")\n\n\tif rtc.isOffering {\n\t\trtc.isOffering = false\n\t} else {\n\t\t// suppose to answer if not in offering mode\n\t\trtc.createAnswer()\n\t}\n}\n\nfunc (rtc *WebRTC) SetCandidate(data string) {\n\tvar ice webrtc.ICECandidateInit\n\terr := Decode(data, &ice)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] decode IceCandidate failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] decoded IceCandidate: \" + ice.Candidate)\n\n\terr = rtc.conn.AddICECandidate(ice)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] add IceCandidate failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.screen.Log(\"[WebRTC] add IceCandidate from peer\")\n}\n\nfunc (rtc *WebRTC) Init() {\n\trtc.Reset()\n\n\tconfig := webrtc.Configuration{\n\t\tICEServers: []webrtc.ICEServer{\n\t\t\t{\n\t\t\t\tURLs: []string{\"stun:stun.l.google.com:19302\"},\n\t\t\t},\n\t\t},\n\t}\n\n\trr, err := webrtc.NewPeerConnection(config)\n\tif err != nil {\n\t\trtc.screen.Log(\"[WebRTC] create peer connection failed: \" + err.Error())\n\t\treturn\n\t}\n\trtc.conn = rr\n\n\t// // Allow us to receive 1 audio track, and 1 video track\n\t// if _, err = rtc.conn.AddTransceiver(webrtc.RTPCodecTypeAudio); err != nil {\n\t// \trtc.screen.Log(\"[WebRTC] AddTransceiver Audio failed\")\n\t// }\n\t// if _, err = rtc.conn.AddTransceiver(webrtc.RTPCodecTypeVideo); err != nil {\n\t// \trtc.screen.Log(\"[WebRTC] AddTransceiver Video failed\")\n\t// }\n\n\trtc.screen.Log(\"[WebRTC] peer connection created\")\n\n\trtc.conn.OnSignalingStateChange(func(state webrtc.SignalingState) {\n\t\trtc.screen.Log(\"[WebRTC] OnSignalingStateChange -> \" + state.String())\n\t})\n\n\trtc.conn.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {\n\t\trtc.screen.Log(\"[WebRTC] OnICEConnectionStateChange -> \" + state.String())\n\t})\n\n\trtc.conn.OnICEGatheringStateChange(func(state webrtc.ICEGathererState) {\n\t\trtc.screen.Log(\"[WebRTC] OnICEGatheringStateChange -> \" + state.String())\n\t})\n\n\trtc.conn.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {\n\t\trtc.screen.Log(\"[WebRTC] OnConnectionStateChange -> \" + state.String())\n\t\tif state == webrtc.PeerConnectionStateConnected {\n\t\t\t// peer established\n\t\t\trtc.isPeered = true\n\t\t}\n\t})\n\n\trtc.conn.OnTrack(func(track *webrtc.Track, rec *webrtc.RTPReceiver) {\n\t\trtc.screen.Log(fmt.Sprintf(\"[WebRTC] OnTrack -> %s - %s\", track.Kind().String(), track.ID()))\n\t})\n\n\trtc.conn.OnDataChannel(func(channel *webrtc.DataChannel) {\n\t\trtc.screen.Log(\"[WebRTC] OnDataChannel: \" + channel.Label())\n\t\trtc.registerDataCallback(channel)\n\t})\n\n\trtc.conn.OnICECandidate(func(candidate *webrtc.ICECandidate) {\n\t\t// TODO: send via websocket\n\t\tif candidate != nil {\n\t\t\trtc.screen.Log(\"[WebRTC] OnICECandidate: \" + candidate.String())\n\t\t\tbody, err := Encode(candidate.ToJSON())\n\t\t\tif err != nil {\n\t\t\t\trtc.screen.Log(\"[WebRTC] encode IceCandidate failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trtc.ws.SendMessage(Message{\"candidate\", string(body)})\n\t\t}\n\t})\n}\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.7444444298744202, "avg_line_length": 17, "blob_id": "5ef8a73195b27259a2605698d4f0056c884e2159", "content_id": "759c17e5604690087baaae6607260d34a76bc87d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go Module", "length_bytes": 180, "license_type": "no_license", "max_line_length": 37, "num_lines": 10, "path": "/go/go.mod", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "module testrtc2\n\ngo 1.13\n\nrequire (\n\tgithub.com/gdamore/tcell v1.3.0\n\tgithub.com/gorilla/websocket v1.4.2\n\tgithub.com/mattn/go-runewidth v0.0.4\n\tgithub.com/pion/webrtc/v2 v2.2.5\n)\n" }, { "alpha_fraction": 0.5905329585075378, "alphanum_fraction": 0.6041045784950256, "avg_line_length": 18.24203872680664, "blob_id": "9e40247a6d6f812325b86a656dbefcb8ee298c69", "content_id": "97653effccdc3914c653f7d295873e8da6166c6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3021, "license_type": "no_license", "max_line_length": 78, "num_lines": 157, "path": "/go/screen/textbox.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package screen\n\nimport (\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gdamore/tcell\"\n\trunewidth \"github.com/mattn/go-runewidth\"\n)\n\ntype TextBox struct {\n\tscreen tcell.Screen\n\tx, y, width, height int // no height, only 2 lines\n\tstyle tcell.Style\n\ttitle string\n\tbuffer string\n\n\tsnapshotMutex sync.Mutex\n\treRender bool\n}\n\nfunc NewTextBox(s tcell.Screen, x, y, width int, style tcell.Style) *TextBox {\n\treturn &TextBox{s, x, y, width, 2, style, \"\", \"\", sync.Mutex{}, true}\n}\n\n// relative position\nfunc (tb *TextBox) puts(x, y int, str string, bold bool) {\n\ts := tb.screen\n\tstyle := tb.style.Bold(bold)\n\t// reposition\n\tx += tb.x\n\ty += tb.y\n\t// overflow\n\tif len(str) > tb.width {\n\t\tstr = str[:tb.width]\n\t}\n\n\ti := 0\n\tvar deferred []rune\n\tdwidth := 0\n\tzwj := false\n\tfor _, r := range str {\n\t\tif r == '\\u200d' {\n\t\t\tif len(deferred) == 0 {\n\t\t\t\tdeferred = append(deferred, ' ')\n\t\t\t\tdwidth = 1\n\t\t\t}\n\t\t\tdeferred = append(deferred, r)\n\t\t\tzwj = true\n\t\t\tcontinue\n\t\t}\n\t\tif zwj {\n\t\t\tdeferred = append(deferred, r)\n\t\t\tzwj = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch runewidth.RuneWidth(r) {\n\t\tcase 0:\n\t\t\tif len(deferred) == 0 {\n\t\t\t\tdeferred = append(deferred, ' ')\n\t\t\t\tdwidth = 1\n\t\t\t}\n\t\tcase 1:\n\t\t\tif len(deferred) != 0 {\n\t\t\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\t\t\ti += dwidth\n\t\t\t}\n\t\t\tdeferred = nil\n\t\t\tdwidth = 1\n\t\tcase 2:\n\t\t\tif len(deferred) != 0 {\n\t\t\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\t\t\ti += dwidth\n\t\t\t}\n\t\t\tdeferred = nil\n\t\t\tdwidth = 2\n\t\t}\n\t\tdeferred = append(deferred, r)\n\t}\n\tif len(deferred) != 0 {\n\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\ti += dwidth\n\t}\n}\n\nfunc (tb *TextBox) Render() {\n\tif !tb.reRender {\n\t\treturn\n\t}\n\n\ttb.snapshotMutex.Lock()\n\ttitle := tb.title\n\tnewBuffer := tb.buffer\n\ttb.reRender = false\n\ttb.snapshotMutex.Unlock()\n\n\t// clear screen\n\tfor x := 0; x < tb.width; x++ {\n\t\tfor y := 0; y < tb.height; y++ {\n\t\t\ttb.puts(x, y, \" \", false)\n\t\t}\n\t}\n\n\tif len(title) > tb.width-20 {\n\t\ttitle = title[:tb.width-20] + \"...\"\n\t}\n\ttitle = \"[ \" + title + \" ]\"\n\tnewTitle := strings.Repeat(\"-\", (tb.width-len(title))/2)\n\tnewTitle += title\n\tnewTitle += strings.Repeat(\"-\", tb.width-len(newTitle))\n\n\tif len(newBuffer) > tb.width-1 {\n\t\tnewBuffer = newBuffer[len(newBuffer)-tb.width+1:]\n\t}\n\n\ttb.puts(0, 0, newTitle, true)\n\ttb.puts(0, 1, newBuffer, false)\n\n\ttb.screen.ShowCursor(tb.x+len(newBuffer), tb.y+1)\n\n\ttb.screen.Sync()\n}\n\nfunc (tb *TextBox) SetTitle(str string) {\n\ttb.snapshotMutex.Lock()\n\ttb.title = str\n\ttb.reRender = true\n\ttb.snapshotMutex.Unlock()\n}\n\nfunc (tb *TextBox) GetBuffer() string {\n\treturn tb.buffer\n}\n\nfunc (tb *TextBox) SetBuffer(str string) {\n\ttb.snapshotMutex.Lock()\n\ttb.buffer = str\n\ttb.reRender = true\n\ttb.snapshotMutex.Unlock()\n}\n\nfunc (tb *TextBox) Add(str string) {\n\ttb.SetBuffer(tb.buffer + str)\n}\n\nfunc (tb *TextBox) Backspace() {\n\tif len(tb.buffer) > 0 {\n\t\ttb.SetBuffer(tb.buffer[:len(tb.buffer)-1])\n\t}\n}\n\nfunc (tb *TextBox) Resize(x, y, width int) {\n\ttb.x = x\n\ttb.y = y\n\ttb.width = width\n\ttb.reRender = true\n}\n" }, { "alpha_fraction": 0.6350210905075073, "alphanum_fraction": 0.6377637386322021, "avg_line_length": 19, "blob_id": "59e9de08c833e322a45330cbc514ea37a6921228", "content_id": "e6306f9a64dc1bf73b76ce92ae4e750fb7bbc3e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 4740, "license_type": "no_license", "max_line_length": 121, "num_lines": 237, "path": "/go/network/websocket.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package network\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/url\"\n\t\"sync\"\n\t\"time\"\n\n\t\"testrtc2/screen\"\n\n\t\"github.com/gorilla/websocket\"\n)\n\ntype WebSocket struct {\n\tscreen *screen.Screen\n\trtc *WebRTC\n\tconn *websocket.Conn\n\tuserID string\n\tpeerID string\n\tmu sync.Mutex // write mutex\n}\n\ntype ActionPacket struct {\n\tAction string `json:\"action\"`\n}\n\ntype InitPacket struct {\n\tActionPacket\n\tID string `json:\"id\"`\n}\n\ntype Message struct {\n\tTopic string `json:\"topic\"`\n\tBody string `json:\"body\"`\n}\n\ntype ErrorPacket struct {\n\tActionPacket\n\tMsg string `json:\"msg\"`\n}\n\ntype RecvPacket struct {\n\tActionPacket\n\tFrom string `json:\"from\"`\n\tMsg Message `json:\"msg\"`\n}\n\ntype SendPacket struct {\n\tActionPacket\n\tTo string `json:\"to\"`\n\tMsg Message `json:\"msg\"`\n}\n\nfunc NewWebSocket(screen *screen.Screen) *WebSocket {\n\treturn &WebSocket{screen, nil, nil, \"\", \"\", sync.Mutex{}}\n}\n\nfunc (ws *WebSocket) SetWebRTC(rtc *WebRTC) {\n\tws.rtc = rtc\n}\n\nfunc (ws *WebSocket) Reset() {\n\tws.userID = \"\"\n\tws.peerID = \"\"\n\n\tif ws.conn != nil {\n\t\tws.conn.Close()\n\t\tws.screen.Log(\"[System] Close previous web socket\")\n\t\tws.conn = nil\n\t}\n}\n\nfunc (ws *WebSocket) GetPeer() string {\n\treturn ws.peerID\n}\n\nfunc (ws *WebSocket) SetPeer(id string) {\n\tws.screen.Log(\"[System] Set Peer ID: \" + id)\n\tws.peerID = id\n}\n\nfunc (ws *WebSocket) sendSafePacket(data []byte) error {\n\tws.mu.Lock()\n\tdefer ws.mu.Unlock()\n\treturn ws.conn.WriteMessage(websocket.TextMessage, data)\n}\n\nfunc (ws *WebSocket) SendMessage(msg Message) {\n\tsp := SendPacket{ActionPacket{\"send\"}, ws.peerID, msg}\n\tpacket, err := json.Marshal(sp)\n\tif err != nil {\n\t\tws.screen.Log(\"[WebSocket] json encode packet failed: \" + err.Error())\n\t\treturn\n\t}\n\terr = ws.sendSafePacket(packet)\n\tif err != nil {\n\t\tws.screen.Log(\"[WebSocket] write message failed: \" + err.Error())\n\t}\n\n\tws.screen.Log(fmt.Sprintf(\"[WebSocket] sent mail to %s: <%s> %d bytes\", ws.peerID, msg.Topic, len(msg.Body)))\n}\n\nfunc (ws *WebSocket) handleMessage(message []byte) (err error) {\n\tvar ap ActionPacket\n\terr = json.Unmarshal(message, &ap)\n\tif err != nil {\n\t\treturn\n\t}\n\tswitch ap.Action {\n\tcase \"init\": // identity\n\t\tvar ip InitPacket\n\t\terr = json.Unmarshal(message, &ip)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tws.userID = ip.ID\n\t\tws.screen.Log(\"[WebSocket] my new ID: \" + ip.ID)\n\t\tws.screen.SetTitle(fmt.Sprintf(\"My ID = %s. Enter command ...\", ip.ID))\n\n\tcase \"error\": // error\n\t\tvar ep ErrorPacket\n\t\terr = json.Unmarshal(message, &ep)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tws.screen.Log(\"[WebSocket] error: \" + ep.Msg)\n\n\tcase \"recv\": // letter from other peer\n\t\tvar rp RecvPacket\n\t\terr = json.Unmarshal(message, &rp)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tws.peerID = rp.From\n\t\tws.screen.Log(fmt.Sprintf(\"[WebSocket] got mail from %s: <%s> %d bytes\", rp.From, rp.Msg.Topic, len(rp.Msg.Body)))\n\n\t\tswitch rp.Msg.Topic {\n\t\tcase \"ping\":\n\t\t\tws.SendMessage(Message{\"pong\", \"\"})\n\n\t\tcase \"sdp\":\n\t\t\tws.rtc.SetRemoteSDP(rp.Msg.Body)\n\n\t\tcase \"candidate\":\n\t\t\tws.rtc.SetCandidate(rp.Msg.Body)\n\t\t}\n\n\t}\n\treturn\n}\n\nfunc (ws *WebSocket) LoopMessage() {\n\tdefer ws.conn.Close()\n\tfor {\n\t\t_, message, err := ws.conn.ReadMessage()\n\t\tif err != nil {\n\t\t\tws.screen.Log(\"[WebSocket] read failed: \" + err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tws.screen.Log(fmt.Sprintf(\"[WebSocket] read: %d bytes\", len(message)))\n\n\t\terr = ws.handleMessage(message)\n\t\tif err != nil {\n\t\t\tws.screen.Log(\"[WebSocket] handle message failed: \" + err.Error())\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc (ws *WebSocket) Connect(addr string) {\n\tws.Reset()\n\n\tu := url.URL{Scheme: \"ws\", Host: addr, Path: \"/\"}\n\tws.screen.Log(\"[WebSocket] connecting to \" + u.String())\n\n\tdialer := websocket.Dialer{\n\t\tReadBufferSize: 65535,\n\t\tWriteBufferSize: 65535,\n\t\tNetDial: (&net.Dialer{\n\t\t\tTimeout: 5 * time.Second,\n\t\t}).Dial,\n\t}\n\n\tc, _, err := dialer.Dial(u.String(), nil)\n\tif err != nil {\n\t\tws.screen.Log(\"[WebSocket] dial failed: \" + err.Error())\n\t\treturn\n\t}\n\tws.conn = c\n\n\t// handle incoming signal\n\tgo ws.LoopMessage()\n\tws.rtc.Init()\n}\n\n// func (ws *WebSocket) Loop(quit chan struct{}) {\n// \tinterrupt := make(chan os.Signal, 1)\n// \tsignal.Notify(interrupt, os.Interrupt)\n\n// \tdefer ws.conn.Close()\n\n// \tdone := make(chan struct{})\n\n// \tgo ws.loopMessage(done)\n\n// \tticker := time.NewTicker(time.Second)\n// \tdefer ticker.Stop()\n\n// \tfor {\n// \t\tselect {\n// \t\tcase <-quit:\n// \t\t\treturn\n\n// \t\tcase <-done:\n// \t\t\treturn\n\n// \t\tcase <-interrupt:\n// \t\t\tws.screen.Log(\"[WebSocket] got interrupt signal\")\n\n// \t\t\terr := ws.conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, \"\"))\n// \t\t\tif err != nil {\n// \t\t\t\tws.screen.Log(\"[WebSocket] write close failed:\" + err.Error())\n// \t\t\t\treturn\n// \t\t\t}\n// \t\t\tselect {\n// \t\t\tcase <-done:\n// \t\t\tcase <-time.After(time.Second):\n// \t\t\t}\n// \t\t\treturn\n// \t\t}\n// \t}\n\n// }\n" }, { "alpha_fraction": 0.5375183820724487, "alphanum_fraction": 0.5414418578147888, "avg_line_length": 26.945205688476562, "blob_id": "789f05ac51580fc69c9be1b97f53cd6d071268b2", "content_id": "43d43311e20a77393563fe5530008e0d6e11d635", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2039, "license_type": "no_license", "max_line_length": 68, "num_lines": 73, "path": "/signal.py", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "from websocket_server import WebsocketServer\nimport json\nimport sys\n\nusers = {}\nidx_map = {}\ncount = 0\n\n# Called for every client connecting (after handshake)\ndef new_client(client, server):\n global count, users, idx_map\n idx = str(count + 1)\n count += 1\n print('New user: {}'.format(idx))\n users[idx] = client\n server.send_message(client, json.dumps({\n 'action': 'init',\n 'id': idx,\n }))\n\ndef get_client_idx(client):\n global users\n for k, cl in users.items():\n if cl == client:\n return k\n\n# Called for every client disconnecting\ndef client_left(client, server):\n global users\n k = get_client_idx(client)\n del users[k]\n print('Client {} disconnected'.format(k))\n\n# Called when a client sends a message\ndef message_received(client, server, message):\n data = json.loads(message)\n if data['action'] == 'send':\n from_id = get_client_idx(client)\n to_id = data['to']\n if to_id not in users:\n print(\"Client {} sent bad request\".format(from_id))\n server.send_message(\n client,\n json.dumps({\n 'action': 'error',\n 'msg': 'Cannot find peer {}'.format(repr(to_id))\n })\n )\n else:\n server.send_message(\n users[to_id],\n json.dumps({\n 'action': 'recv',\n 'from': from_id,\n 'msg': data['msg'],\n })\n )\n else:\n print(\"unsupported event: {}\", data)\n\nif __name__ == '__main__':\n if len(sys.argv) < 3:\n print('Usage: python {} HOST PORT'.format(sys.argv[0]))\n sys.exit(1)\n\n HOST = sys.argv[1]\n PORT = int(sys.argv[2])\n server = WebsocketServer(PORT, host=HOST)\n server.set_fn_new_client(new_client)\n server.set_fn_client_left(client_left)\n server.set_fn_message_received(message_received)\n print('Server is running at {}:{}'.format(HOST, PORT))\n server.run_forever()" }, { "alpha_fraction": 0.635407567024231, "alphanum_fraction": 0.6456325054168701, "avg_line_length": 19.745454788208008, "blob_id": "612d946cdc100ade65e7b2ff8a4ff9f426c1a158", "content_id": "3523133a2e0f8593e63f08fea6eeebfc1a682a94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3423, "license_type": "no_license", "max_line_length": 124, "num_lines": 165, "path": "/go/screen/screen.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package screen\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"github.com/gdamore/tcell\"\n)\n\ntype Screen struct {\n\tscreen tcell.Screen\n\ttxtLog *Memo\n\ttxtInput *TextBox\n\ttxtHelp *Memo\n\tcallback ScreenCB\n}\n\ntype ScreenCB func(string)\n\nfunc NewScreen() *Screen {\n\treturn &Screen{nil, nil, nil, nil, nil}\n}\n\nfunc (s *Screen) Log(rline string) {\n\t// fmt.Println(rline)\n\ts.txtLog.Println(rline)\n}\n\nfunc (s *Screen) SetTitle(title string) {\n\ts.txtInput.SetTitle(title)\n}\n\nfunc (s *Screen) SetBuffer(buffer string) {\n\ts.txtInput.SetBuffer(buffer)\n}\n\nfunc (s *Screen) RegisterCallback(f ScreenCB) {\n\ts.callback = f\n}\n\nfunc (s *Screen) Clear() {\n\ts.screen.Clear()\n}\n\nfunc (s *Screen) Show() {\n\ts.screen.Show()\n}\n\nfunc (s *Screen) Fini() {\n\ts.screen.Fini()\n}\n\nfunc (s *Screen) Init() {\n\tscreen, err := tcell.NewScreen()\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\tif err = screen.Init(); err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"%v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\n\t//// some terminal supports scroll\n\t//// disable this for mouse selection\n\t// screen.EnableMouse()\n\tscreen.Clear()\n\n\tw, h := screen.Size()\n\ts.txtLog = NewMemo(screen, 0, 0, w-26, h-2, tcell.StyleDefault.Background(tcell.ColorWhite).Foreground(tcell.ColorBlack))\n\ts.txtInput = NewTextBox(screen, 0, h-2, w, tcell.StyleDefault.Background(tcell.ColorIndianRed).Foreground(tcell.ColorBlue))\n\ts.txtHelp = NewMemo(screen, w-26, 0, 26, h-2, tcell.StyleDefault.Background(tcell.ColorGreen).Foreground(tcell.ColorBlack))\n\n\ts.txtHelp.Println(\"Keyboard shortcut\")\n\ts.txtHelp.Println(\" Escape : Quit\")\n\ts.txtHelp.Println(\" Arrow Up : Scroll Up\")\n\ts.txtHelp.Println(\" Arrow Down : Scroll Down\")\n\ts.txtHelp.Println(\" Arrow Left : First page\")\n\ts.txtHelp.Println(\" Arrow Right: Last page\")\n\ts.txtHelp.Println(\"\")\n\ts.txtHelp.Println(\"\")\n\ts.txtHelp.Println(\"Text command\")\n\ts.txtHelp.Println(\" /new : new rtc\")\n\ts.txtHelp.Println(\" /peer id: set peer\")\n\ts.txtHelp.Println(\" /offer : send offer\")\n\ts.txtHelp.Println(\" /media : add media\")\n\ts.txtHelp.Println(\" /data : add channel\")\n\n\ts.screen = screen\n}\n\nfunc (s *Screen) RenderLoop(quit chan struct{}) {\n\tticker := time.NewTicker(time.Second / 20) // 30 fps\n\tdefer ticker.Stop()\n\tfor {\n\t\tselect {\n\t\tcase <-quit:\n\t\t\treturn\n\t\tcase <-ticker.C:\n\t\t\t// render\n\t\t\ts.txtLog.Render()\n\t\t\ts.txtHelp.Render()\n\t\t\ts.txtInput.Render()\n\t\t}\n\t}\n}\n\nfunc (s *Screen) EventLoop(quit chan struct{}) {\n\tfor {\n\t\tev := s.screen.PollEvent()\n\t\tswitch ev := ev.(type) {\n\t\tcase *tcell.EventKey:\n\t\t\tswitch ev.Key() {\n\t\t\tcase tcell.KeyEscape:\n\t\t\t\tclose(quit)\n\t\t\t\treturn\n\n\t\t\tcase tcell.KeyUp:\n\t\t\t\ts.txtLog.ScrollUp()\n\t\t\tcase tcell.KeyDown:\n\t\t\t\ts.txtLog.ScrollDown()\n\t\t\tcase tcell.KeyLeft:\n\t\t\t\ts.txtLog.ScrollHome()\n\t\t\tcase tcell.KeyRight:\n\t\t\t\ts.txtLog.ScrollEnd()\n\n\t\t\tcase tcell.KeyBackspace, tcell.KeyBackspace2:\n\t\t\t\ts.txtInput.Backspace()\n\n\t\t\tcase tcell.KeyEnter:\n\t\t\t\tdata := s.txtInput.GetBuffer()\n\t\t\t\tif s.callback != nil {\n\t\t\t\t\ts.callback(data)\n\t\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\tr := ev.Rune()\n\t\t\t\tif strconv.IsPrint(r) {\n\t\t\t\t\ts.txtInput.Add(string(r))\n\t\t\t\t}\n\n\t\t\t}\n\n\t\tcase *tcell.EventResize:\n\t\t\ts.Clear()\n\t\t\tw, h := s.screen.Size()\n\t\t\ts.txtLog.Resize(0, 0, w-26, h-2)\n\t\t\ts.txtInput.Resize(0, h-2, w)\n\t\t\ts.txtHelp.Resize(w-26, 0, 26, h-2)\n\t\t\ts.Show()\n\n\t\tcase *tcell.EventMouse:\n\t\t\tbtn := ev.Buttons()\n\t\t\tif btn&tcell.WheelUp != 0 {\n\t\t\t\ts.txtLog.ScrollUp()\n\t\t\t}\n\t\t\tif btn&tcell.WheelDown != 0 {\n\t\t\t\ts.txtLog.ScrollDown()\n\t\t\t}\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.590176522731781, "alphanum_fraction": 0.5998976826667786, "avg_line_length": 17.526065826416016, "blob_id": "2dbb277032899553f2c144dca7256ae5c28d4497", "content_id": "05df8ff1887bc75efb900956bfa3ede0e41b2bcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3909, "license_type": "no_license", "max_line_length": 83, "num_lines": 211, "path": "/go/screen/memo.go", "repo_name": "trichimtrich/testrtc2", "src_encoding": "UTF-8", "text": "package screen\n\nimport (\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gdamore/tcell\"\n\trunewidth \"github.com/mattn/go-runewidth\"\n)\n\ntype Row struct {\n\tid int\n\tstart int\n\tlength int\n}\n\ntype Memo struct {\n\tscreen tcell.Screen\n\tx, y, width, height int\n\tstyle tcell.Style\n\trawBuf []string // actual data buffer\n\trowArr []Row // screen buffer\n\trowCur int\n\tautoScroll bool\n\n\tsnapshotMutex sync.Mutex\n\treRender bool\n}\n\nfunc NewMemo(s tcell.Screen, x, y, width, height int, style tcell.Style) *Memo {\n\treturn &Memo{s, x, y, width, height, style, nil, nil, 0, true, sync.Mutex{}, true}\n}\n\n// relative position\nfunc (m *Memo) puts(x, y int, str string) {\n\ts := m.screen\n\tstyle := m.style\n\t// reposition\n\tx += m.x\n\ty += m.y\n\t// overflow\n\tif len(str) > m.width {\n\t\tstr = str[:m.width]\n\t}\n\n\ti := 0\n\tvar deferred []rune\n\tdwidth := 0\n\tzwj := false\n\tfor _, r := range str {\n\t\tif r == '\\u200d' {\n\t\t\tif len(deferred) == 0 {\n\t\t\t\tdeferred = append(deferred, ' ')\n\t\t\t\tdwidth = 1\n\t\t\t}\n\t\t\tdeferred = append(deferred, r)\n\t\t\tzwj = true\n\t\t\tcontinue\n\t\t}\n\t\tif zwj {\n\t\t\tdeferred = append(deferred, r)\n\t\t\tzwj = false\n\t\t\tcontinue\n\t\t}\n\t\tswitch runewidth.RuneWidth(r) {\n\t\tcase 0:\n\t\t\tif len(deferred) == 0 {\n\t\t\t\tdeferred = append(deferred, ' ')\n\t\t\t\tdwidth = 1\n\t\t\t}\n\t\tcase 1:\n\t\t\tif len(deferred) != 0 {\n\t\t\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\t\t\ti += dwidth\n\t\t\t}\n\t\t\tdeferred = nil\n\t\t\tdwidth = 1\n\t\tcase 2:\n\t\t\tif len(deferred) != 0 {\n\t\t\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\t\t\ti += dwidth\n\t\t\t}\n\t\t\tdeferred = nil\n\t\t\tdwidth = 2\n\t\t}\n\t\tdeferred = append(deferred, r)\n\t}\n\tif len(deferred) != 0 {\n\t\ts.SetContent(x+i, y, deferred[0], deferred[1:], style)\n\t\ti += dwidth\n\t}\n}\n\nfunc (m *Memo) addLineToRow(line string, bufIdx int) (newRow int, numRows int) {\n\tnewRow = len(m.rowArr)\n\tnumRows = 0\n\tlineIdx := 0\n\tlineLen := len(line)\n\tfor {\n\t\tnumRows++\n\t\tif lineIdx+m.width >= lineLen {\n\t\t\tm.rowArr = append(m.rowArr, Row{bufIdx, lineIdx, lineLen - lineIdx})\n\t\t\tbreak\n\t\t} else {\n\t\t\tm.rowArr = append(m.rowArr, Row{bufIdx, lineIdx, m.width})\n\t\t\tlineIdx += m.width\n\t\t}\n\t}\n\n\treturn\n}\n\nfunc (m *Memo) Clear() {\n\tm.snapshotMutex.Lock()\n\tm.rawBuf = nil\n\tm.rowArr = nil\n\tm.rowCur = 0\n\tm.reRender = true\n\tm.snapshotMutex.Unlock()\n}\n\nfunc (m *Memo) Resize(x, y, width, height int) {\n\tm.x = x\n\tm.y = y\n\tm.width = width\n\tm.height = height\n\t// TODO: reparse\n\tm.snapshotMutex.Lock()\n\tm.rowArr = nil\n\tm.snapshotMutex.Unlock()\n\tfor idx := 0; idx < len(m.rawBuf); idx++ {\n\t\tm.addLineToRow(m.rawBuf[idx], idx)\n\t}\n\tm.ScrollEnd()\n}\n\nfunc (m *Memo) Render() {\n\tif !m.reRender {\n\t\treturn\n\t}\n\n\tm.snapshotMutex.Lock()\n\trowArr := m.rowArr\n\trawBuf := m.rawBuf\n\trowIdx := m.rowCur\n\tm.reRender = false\n\tm.snapshotMutex.Unlock()\n\n\t// clear screen\n\tfor x := 0; x < m.width; x++ {\n\t\tfor y := 0; y < m.height; y++ {\n\t\t\tm.puts(x, y, \" \")\n\t\t}\n\t}\n\n\t// print now\n\tfor y := 0; y < Min(m.height, len(rowArr)-rowIdx); y++ {\n\t\tr := rowArr[y+rowIdx]\n\t\tstr := rawBuf[r.id][r.start : r.start+r.length]\n\t\tm.puts(0, y, str)\n\t}\n\n\tm.screen.Sync()\n}\n\nfunc (m *Memo) setCursor(rowIdx int) {\n\tm.snapshotMutex.Lock()\n\tm.rowCur = rowIdx\n\tm.reRender = true\n\tm.snapshotMutex.Unlock()\n}\n\nfunc (m *Memo) Println(rline string) {\n\tfor _, line := range strings.Split(rline, \"\\r\\n\") {\n\t\tbufIdx := len(m.rawBuf)\n\t\tm.rawBuf = append(m.rawBuf, line)\n\t\tm.addLineToRow(line, bufIdx)\n\t}\n\n\tif m.autoScroll {\n\t\tm.setCursor(Max(0, len(m.rowArr)-m.height))\n\t} else {\n\t\tm.setCursor(m.rowCur)\n\t}\n}\n\nfunc (m *Memo) ScrollHome() {\n\tm.autoScroll = false\n\tm.setCursor(0)\n}\n\nfunc (m *Memo) ScrollEnd() {\n\tm.autoScroll = true\n\tm.setCursor(Max(0, len(m.rowArr)-m.height))\n}\n\nfunc (m *Memo) ScrollUp() {\n\tif m.rowCur == 0 {\n\t\treturn\n\t}\n\tm.autoScroll = false\n\tm.setCursor(m.rowCur - 1)\n}\n\nfunc (m *Memo) ScrollDown() {\n\tif m.rowCur >= len(m.rowArr)-m.height {\n\t\tm.autoScroll = true\n\t\treturn\n\t}\n\tm.setCursor(m.rowCur + 1)\n}\n" } ]
11
Nazruden/JSB-Stage-Reseau
https://github.com/Nazruden/JSB-Stage-Reseau
0e987d396f9c69eefd42ffd8507336fa7d319103
a7eb85e2bad5f03cc845fe6a2398e2749a2f6bdb
4f8d58ed3c51df7893c69b86f01cad19802bd580
refs/heads/master
2021-04-28T04:34:09.267564
2018-02-20T06:38:13
2018-02-20T06:38:13
122,163,562
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5253396034240723, "alphanum_fraction": 0.5312173366546631, "avg_line_length": 35.98550796508789, "blob_id": "283cc0e498b522c3117f59bafd606ea7a9a28ce5", "content_id": "13ce000b907e2795b0e5c455e04618a116d9cb7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7696, "license_type": "no_license", "max_line_length": 138, "num_lines": 207, "path": "/game.py", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "####################################\n## JSB Stage - Le morpion aveugle ##\n####################################\n## Fichier : game.py\n## Classe Game : gestion du jeu\n####################################\n\nimport socket\nfrom grid import *\nfrom cmdServ import *\nfrom outils import *\n\n\n# Game class\nclass game:\n # Grids\n grids = [grid(), grid(), grid()]\n\n # Players and spectators\n players = dict()\n spectators = []\n currentPlayer = None\n gameReady = False\n\n # Scores\n scores = dict()\n\n # Game management\n # init Game\n def __init__(self):\n self.grid = grid()\n self.players = dict()\n self.scores = dict()\n self.currentPlayer = J1\n for i in [J1, J2]:\n self.players[i] = None\n self.scores[i] = 0\n\n ##########################################################\n ## Fonctions d'ajouts de joueurs / gestion des spectateurs\n ##########################################################\n # addPlayer method : Ajoute un joueur à la partie\n def addPlayer(self, client):\n # Essai d'affectation en joueur 1\n if self.players[J1] is None:\n self.players[J1] = client\n # TODO : envoi de l'état de la grille au joueur 1\n # Essai d'affectation en joueur 2\n elif self.players[J2] is None:\n self.players[J2] = client\n # TODO : envoi de l'état de la grille au joueur \n # Sinon affectation aux spectateurs\n else:\n self.spectators.append(client)\n # TODO : une fois le cas typique géré\n # Plus de place disponibles pour les joueurs, début de la partie\n if not self.gameReady and self.players[J1] is not None and self.players[J2] is not None:\n self.gameReady = True\n self.startGame()\n\n # removeClient : retire un client (joueur ou spectateur) de la partie\n def removeClient(self, client):\n # Checking in players\n for player in [J1, J2]:\n if self.players[player] == client:\n self.players[player] = None\n # If game was running\n if self.gameReady:\n self.gameReady = False\n print(\"PAUSE - A PLAYER HAS LEFT\")\n self.sendAll(\"PAUSE - A PLAYER HAS LEFT\\n\")\n # Checking in spectators\n for spectator in self.spectators:\n if spectator == client:\n self.spectators.remove(client)\n\n # playerToSpectator method : déplace un joueur en spectateur\n def playerToSpectator(self, player):\n self.spectators.append(self.players[player])\n self.players[player] = None\n\n def spectatorToPlayer(self, spectator):\n self.spectators.remove(spectator)\n self.addPlayer(spectator)\n \n # joinGame method : gestion du join d'un spectateur\n def joinGame(self, client):\n self.spectatorToPlayer(client)\n\n ############################################# \n ## Action de joueur, début et fin de partie\n ############################################# \n # place method : place un jeton sur une case\n def place(self, player, cell):\n if cell is not \"\":\n cell = int(cell)\n if cell < 9 and cell >= 0:\n # Vérification : s'agit il du bon joueur\n if self.players[self.currentPlayer] == player:\n # Vérification : case vide\n if self.grids[0].isEmpty(cell):\n # Mise à jour de la grille du joueur\n self.grids[self.currentPlayer].cells[cell] = self.currentPlayer\n # Mise à jour de la grille publique\n self.grids[0].play(self.currentPlayer, cell)\n # Envoi du nouvel état de la grille au joueur\n # TODO : envoyer l'état de la grille au joueur courant\n\n # Vérification de fin de partie\n if self.grids[0].gameOver() > 0:\n self.endGame()\n # Sinon tour suivant\n else:\n self.currentPlayer = self.currentPlayer % 2 + 1\n # Case non vide\n else:\n # Mise à jour de la grille du joueur\n self.grids[self.currentPlayer].cells[cell] = self.grids[0].cells[cell]\n # Envoi du nouvel état de la grille au joueur\n # TODO : gestion du cas : le joueur a joué sur une case déjà jouée\n # Gestion de déroulement de partie : tour suivant\n if self.gameReady:\n # TODO : informer le joueur courant qu'il doit jouer\n # Mauvais joueur\n else:\n sendError(player, \"Ce n'est pas votre tour.\\n\")\n # Case invalide\n else:\n # TODO : gestion du cas d'erreur : case invalide\n\n # startGame method :\n def startGame(self):\n # Print game beginning and sends START and TURN tokens\n print(\"---- GAME STARTING ----\")\n\n ####################################################\n # TODO : Signifier aux clients le début de la partie\n ####################################################\n\n # endGame method :\n def endGame(self):\n print(\"---- GAME ENDING ----\")\n # Vérification d'un vainqueur - 0 sinon\n winner = self.grids[0].gameOver()\n \n ###############################################\n # TODO : Signifier aux clients la fin de partie\n ###############################################\n \n\n # isPlayer method : vérifie si le joueur passé en paramètre est le joueur courant\n def isPlayer(self, client):\n # Player 1\n if self.players[J1] == client:\n return J1\n # Player 2\n elif self.players[J2] == client:\n return J2\n # Spectator\n else:\n return 0\n\n # sendAll method : envoie un message à tous les clients (joueurs et spectateurs)\n def sendAll(self, msg):\n self.sendPlayers(msg)\n self.sendSpectators(msg)\n\n # sendPlayers method : envoie un message aux joueurs\n def sendPlayers(self, msg):\n for player in [J1, J2]:\n if self.players[player] is not None:\n self.players[player].send(msg)\n\n # sendSpectators method : envoie un message aux spectateurs\n def sendSpectators(self, msg):\n for spectator in self.spectators:\n spectator.send(msg)\n\n # sendScores method : envoi des scores à tout le monde\n def sendScores(self):\n self.sendAll(self.getScore())\n\n # sendState method : sends appropriate state to specified client\n def sendState(self, client):\n client.send(self.getState(client))\n\n # sendTurn method : envoi de l'information \"VOTRE TOUR\" au joueur précisé\n def sendTurn(self, player):\n player.send(\"YOURTURN\\n\")\n\n # getScore method : retourne les scores sous la forme d'une chaîne de caractères\n def getScore(self):\n prefix = \"SCORE \"\n return prefix + str(self.scores[J1]) + \" \" + str(self.scores[J2]) + \"\\n\"\n\n # getState method : retourne l'état de la grille sous la forme d'une chaîne de caractères - 9 entiers concaténés séparés par un espace\n def getState(self, client):\n prefix = \"STATE \"\n # State J1 grid\n if self.isPlayer(client) == J1:\n return prefix + self.grids[J1].toString() + \"\\n\"\n # State J2 grid\n elif self.isPlayer(client) == J2:\n return prefix + self.grids[J2].toString() + \"\\n\"\n # State public grid\n else:\n return prefix + self.grids[0].toString() + \"\\n\"\n" }, { "alpha_fraction": 0.47352495789527893, "alphanum_fraction": 0.4784417450428009, "avg_line_length": 30.10588264465332, "blob_id": "5ea5dc9d289444ba5cdc201e3fd2f787b2e767f6", "content_id": "68d7d735a06bfbf436f71f3ac7bfcfc165c86fbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2662, "license_type": "no_license", "max_line_length": 87, "num_lines": 85, "path": "/client.py", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n####################################\n## JSB Stage - Le morpion aveugle ##\n####################################\n## Fichier : client.py\n## Programme client du morpion aveugle\n####################################\n\nfrom cmdClient import *\nfrom grid import *\nfrom outils import *\nimport select\nimport socket\nimport sys\n\n\ndef prompt():\n sys.stdout.flush()\n\n### Main client\ndef main():\n\n ## Définition des informations de connexion\n host = \"\"\n if len(sys.argv) < 2:\n print('Utilisation : python3 mainClient.py hostname\\n')\n print('Hostname manquant.\\n')\n host = input('Préciser hostname : ')\n sys.exit()\n else:\n host = sys.argv[1]\n port = 7777\n connexion = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n\n ## Connection au serveur\n connect_to_server(connexion, host, port)\n\n\n while True:\n ## Flux entrants - Terminal et hôte distant\n socket_list = [sys.stdin, connexion]\n # Récupération des différents sockets à l'instant T\n read_sockets, write_sockets, error_sockets = select.select(socket_list, [], [])\n\n # Parcours des sockets en attente de lecture\n for sock in read_sockets:\n # Lecture d'un message provenant de l'hôte distant\n if sock == connexion:\n data = sock.recv(1500)\n # Message vide : déconnexion du serveur\n if not data:\n print('\\nDisconnected from server')\n sys.exit()\n else:\n # Analyse paquets serveur\n cmds = split_data(data)\n \n for cmd in cmds:\n print(cmd)\n # START\n if cmd.startswith(b\"START\"):\n # TODO : Gérer la réception du START\n\n # STATE\n if cmd.startswith(b\"STATE\"):\n cmd_getstate(cmd_convert_data_to_grid(cmd))\n\n # YOURTURN\n if cmd.startswith(b\"YOURTURN\"):\n # TODO : Gérer la réception d'un YOURTURN\n\n # SCORE\n if cmd.startswith(b\"SCORE\"):\n # TODO : Gérer la réception du SCORE\n\n # END\n if cmd.startswith(b\"END\"):\n # TODO : Gérer la réception d'un END\n # Lecture d'une entrée utilisateur\n else:\n msg = sys.stdin.readline()\n connexion.send(msg)\n pass\n\nmain()\n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 18, "blob_id": "a87bc9b41195b143ba1b268b5822e48fd476d368", "content_id": "ac61057a3a30e45ee98436e5d45504ed896e3c9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 19, "license_type": "no_license", "max_line_length": 18, "num_lines": 1, "path": "/README.md", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "# JSB-Stage-Reseau\n" }, { "alpha_fraction": 0.525866687297821, "alphanum_fraction": 0.5354666709899902, "avg_line_length": 26.985074996948242, "blob_id": "246a2d350a4eadb66a7d67a8436279647c798399", "content_id": "29b2cfdd5e3b2a7ce9b1fd98ca357a170af87a9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1879, "license_type": "no_license", "max_line_length": 98, "num_lines": 67, "path": "/server.py", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n####################################\n## JSB Stage - Le morpion aveugle ##\n####################################\n## Fichier : server.py\n## Programme serveur du morpion aveugle\n####################################\n\nfrom cmdServer import *\nfrom game import *\nfrom outils import *\nimport random\nimport select\nimport socket\nimport sys\n\n\n# Main serveur\ndef main():\n ## Vars\n # Communication\n clients = list()\n spectators = list()\n # Game\n gameInstance = game()\n\n # Création d'un socket d'écoute - notre \"oreille\"\n ear = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n ear.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n ear.bind(('', 7777))\n ear.listen(3)\n print(\"Serveur lance\")\n print(\"Attente de connexion...\")\n \n ## Boucle principale\n while True:\n tmp = list(clients)\n tmp.append(ear)\n changes = select.select(tmp, list(), list())[0]\n ## Parcours des sockets en attente de lecture\n for client in changes:\n # Traitement du socket d'écoute\n if client == ear:\n data = client.accept()\n print(\"Nouvelle connexion de \" + str(data[1]))\n # Ajout du client\n clients.append(data[0])\n # Ajout du client à la partie\n gameInstance.addPlayer(data[0])\n\n # Traitement\n else:\n\n data = client.recv(1500)\n\n # Traitement deconnexion\n if len(data) == 0: # Si la longueur recue est 0 c'est que l'user s'est deconnecte\n cmd_disconnect(gameInstance, clients, client)\n # CMD : DISCONNECT\n elif data.startswith(b\"DISCONNECT\"):\n cmd_disconnect(gameInstance, clients, client)\n # TODO : gestion de PLACE et JOIN\n\n\n pass\n\nmain()\n" }, { "alpha_fraction": 0.516569197177887, "alphanum_fraction": 0.516569197177887, "avg_line_length": 24.700000762939453, "blob_id": "f09ed6b2961ae1f2562b0d555f3509ed96e2f19c", "content_id": "c3bcf3229ba67e31be5a60f620319a4d27a8bfff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "no_license", "max_line_length": 69, "num_lines": 20, "path": "/outils.py", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "####################################\n## JSB Stage - Le morpion aveugle ##\n####################################\n## Fichier : outils.py\n## Outils pouvant être utilisés par le côté client et le côté serveur\n####################################\n\ndef formalizedata(msg, cmd):\n return msg.replace(cmd, \"\").replace(\"\\n\", \"\")\n\ndef split_data(data):\n return data.split('\\n')\n\ndef sendAll(clients, msg):\n for client in clients:\n client.send(msg)\n\n\ndef sendError(client, msg):\n client.send(\"ERROR \" + msg)" }, { "alpha_fraction": 0.631981611251831, "alphanum_fraction": 0.6350420713424683, "avg_line_length": 28.704545974731445, "blob_id": "3a5635de8abe5b4d27e224b97e7981de29562020", "content_id": "18760a6868f8fb374533ce876af901a7655d19cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1310, "license_type": "no_license", "max_line_length": 88, "num_lines": 44, "path": "/cmdServer.py", "repo_name": "Nazruden/JSB-Stage-Reseau", "src_encoding": "UTF-8", "text": "####################################\n## JSB Stage - Le morpion aveugle ##\n####################################\n## Fichier : cmdServer.py\n## Outils serveur\n####################################\n\nfrom game import *\n\n# Fonction utilisée pour déconnecter un client proprement\ndef cmd_disconnect(game, clients, client):\n # Retrait du client de la liste des clients et de la partie puis fermeture du socket\n clients.remove(client)\n game.removeClient(client)\n client.close() \n print(\"Client deconnecte\")\n\n# Envoi de l'état de la partie gameInstance du point de vue de client\ndef cmd_sendstate(client, gameInstance):\n client.send(gameInstance.getState(client))\n\n# Envoi des scores au client\ndef cmd_sendscore(client, gameInstance):\n client.send(gameInstance.getScore())\n\n# E\ndef cmd_place(client, gameInstance, data):\n client.send(gameInstance.place(client, data))\n\n\ndef cmd_start(players):\n for player in players:\n player.send(\"START\\n\")\n\n# CMD Yourturn : inform a player he has to play\ndef cmd_yourturn(player):\n player.send(\"YOURTURN\")\n\n# CMD End : send END to players with endstate, an int for :\n# - 1 : player 1 victory\n# - 2 : player 2 victory\ndef cmd_end(players, endstate):\n for player in players:\n player.send(\"END \" + endstate)\n" } ]
6
mananjainiitr/img_python_assignment
https://github.com/mananjainiitr/img_python_assignment
c0cc2ddc661015fca7770c2bd4db3a7ff0b9bb67
04809cbfac795d558a2412c12a6f0f6df5271af9
61730ee7ca27c927ef99a5a63a41579a80fc6399
refs/heads/main
2023-07-07T18:50:15.109399
2021-08-05T07:05:53
2021-08-05T07:05:53
392,359,761
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3947828710079193, "alphanum_fraction": 0.43693336844444275, "avg_line_length": 35.13218307495117, "blob_id": "f5424c60b7aece6787efdebeac33dceda5f664bc", "content_id": "c104287dc0a1467bf790d1152f4a1ee48347e9a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6287, "license_type": "no_license", "max_line_length": 100, "num_lines": 174, "path": "/nested.py", "repo_name": "mananjainiitr/img_python_assignment", "src_encoding": "UTF-8", "text": "from logging import exception\nimport unittest\nclass matrices:\n exception =\"\"\n mat = []\n a = []\n det =[]\n def __init__(self,x):\n i = 1\n f = 0\n if type(x)==list:\n if len(x)>1:\n while(i < len(x) and f == 0):\n if(type(x[0])==int):\n f=0\n break\n else:\n if(len(x[i])==len(x[i-1])):\n i = i + 1\n else:\n f =1\n else:\n f = 1\n if(f == 0):\n self.mat = x\n print (self.mat)\n else:\n print(\"invalid matrix\")\n def display(self):\n if(self.mat):\n for i in self.mat:\n print(i)\n return self.mat\n else:\n return(\"invalid matrix\")\n # def __str__(self):\n # string = ','.join([str(elem) for elem in self.mat])\n # return string\n def __add__(self,other):\n if len(self.mat )== len(other.mat)and len(self.mat[0])==len(other.mat[0]):\n a = matrices([])\n a.mat = [ [ 0 for i in range(len(other.mat[0])) ] for j in range(len(other.mat)) ]\n for i in range(len(other.mat)):\n for j in range(len(other.mat[0])):\n a.mat[i][j] = self.mat[i][j]+(other.mat[i][j]) \n return a\n else:\n \n raise Exception(\"Matrices order is different, cannot add\")\n def __sub__(self,other):\n if len(self.mat )== len(other.mat)and len(self.mat[0])==len(other.mat[0]):\n a = matrices([])\n a.mat = [ [ 0 for i in range(len(other.mat[0])) ] for j in range(len(other.mat)) ]\n for i in range(len(other.mat)):\n for j in range(len(other.mat[0])):\n a.mat[i][j] = self.mat[i][j]-(other.mat[i][j]) \n return a\n else:\n raise Exception(\"Matrices order is different, cannot add\")\n def __mul__(self,other):\n if len(self.mat[0]) == len(other.mat):\n a = matrices([])\n a.mat = [ [ 0 for i in range(len(other.mat[0])) ] for j in range(len(self.mat)) ]\n for i in range(len(a.mat)):\n for j in range(len(a.mat[0])):\n sum = 0\n for k in range(len(self.mat[0])):\n sum = sum + self.mat[i][k]*other.mat[k][j]\n a.mat[i][j] = sum\n return a\n else:\n raise Exception(\"Matrices order is different, cannot multiply\")\n def det(self,matrix):\n if len(self.mat) == len(self.mat[0]):\n sum = 0\n n = len(self.mat)\n \n if n == 2 :\n return (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0])\n else:\n for j in range(len(matrix[0])):\n a1 = 0 \n a2 = 0\n m = [ [ 0 for i in range(len(self.mat[0])-1) ] for j in range(len(self.mat)-1) ]\n for i in range(1,len(matrix[0])):\n for k in range(len(matrix[0])):\n if k != j:\n m[a1][a2] = matrix[i][k]\n a2 = ((a2+1)%(n-1))\n a1 = (a1+1)%(n-1)\n obj = matrices(m)\n sum = sum + pow(-1,j)*matrix[0][j]*obj.det(m)\n return sum\n else:\n raise Exception(\"Matrix is not square\")\n \n \n # sum = sum + ((-1).pow(j+1))*det()\n # print (m)\n def __pow__(self,other,modulo = None):\n if len(self.mat) == len(self.mat[0]):\n obj1 = matrices([])\n obj1.mat = self.mat\n for i in range(other-1):\n obj1 = obj1 * self\n return obj1\n else:\n raise Exception(\"Matrix is not square\")\n\n \n\n\nclass Test(unittest.TestCase):\n\n def setUp(self):\n self.matrix1 = matrices([[1, 2, 3], [2, 1, 3], [3, 7, 9]])\n self.matrix2 = matrices([[1, 5, 6], [3, 11, 2], [1, 9, 5]])\n self.expo = 2\n\n def tearDown(self):\n print(\"\\n\")\n\n def test_add(self):\n MatrixSum = self.matrix1 + self.matrix2\n output = matrices([[2, 7, 9], [5, 12, 5], [4, 16, 14]])\n self.assertEqual(MatrixSum.display(), output.display())\n def test_sub(self):\n matrixDiff = self.matrix1 - self.matrix2\n output = matrices([[0, -3, -3], [-1, -10, 1], [2, -2, 4]])\n self.assertEqual(matrixDiff.display(), output.display())\n def test_1(self):\n mat1 = matrices([[0, -3, -3], [-1, -10, 1], [2, -2, 4]])\n mat2 = matrices([[0, -3, -3], [-1, -10, 1]])\n with self.assertRaises(Exception):\n mat1+mat2\n def test_2(self):\n mat1 = matrices([[0, -3, -3], [-1, -10, 1], [2, -2, 4]])\n mat2 = matrices([[0, -3, -3], [-1, -10, 1]])\n with self.assertRaises(Exception):\n mat1-mat2\n def test_3(self):\n mat1 = matrices([[0, -3, -3], [-1, -10, 1], [2, -2, 4]])\n mat2 = matrices([[0, -3, -3], [-1, -10, 1]])\n with self.assertRaises(Exception):\n mat1*mat2\n\n \n def test_multiply(self):\n matrixMul = self.matrix1 * self.matrix2\n output = matrices([[10, 54, 25], [8, 48, 29], [33, 173, 77]])\n self.assertEqual(matrixMul.display(), output.display())\n def test_det(self):\n Det = matrices([[1, 2, 3], [2, 1, 3], [3, 7, 9]])\n det = Det.det([[1, 2, 3], [2, 1, 3], [3, 7, 9]])\n output = 3\n self.assertEqual(det, output)\n def test_exponent(self):\n MatrixExpo = self.matrix1 ** self.expo\n output = matrices([[14,25,36],[13,26,36],[44,76,111]])\n self.assertEqual(MatrixExpo.display(), output.display())\n def test_valid(self):\n matrix = matrices([[1,2,3],[3,4,5],[2,3,1]])\n output = [[1,2,3],[3,4,5],[2,3,1]]\n self.assertEqual(matrix.display(),output)\n def test_valid2(self):\n matrix = matrices([1])\n output = [1]\n self.assertEqual(matrix.display(),output)\n \n\n \n \nif __name__ == \"__main__\":\n unittest.main()\n" }, { "alpha_fraction": 0.5760201811790466, "alphanum_fraction": 0.5894123315811157, "avg_line_length": 29.22381019592285, "blob_id": "301a151fcd3525ef3301924507a07ea508f6ebf2", "content_id": "fd98aa7943720098cfa8ecf871e986f6dfc74438", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6347, "license_type": "no_license", "max_line_length": 169, "num_lines": 210, "path": "/sellinium.py", "repo_name": "mananjainiitr/img_python_assignment", "src_encoding": "UTF-8", "text": "from logging import exception, raiseExceptions\nimport unittest\nfrom typing import Text\nimport mysql.connector\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom time import sleep\nfrom selenium.webdriver.common.by import By\nfrom urllib3.packages.six import raise_from\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options \n\nconn = mysql.connector.connect(user='manan', password='#Manan#2020#', host='localhost',database='user',auth_plugin = \"mysql_native_password\")\n\ncursor = conn.cursor(buffered = True)\nuser = \"\"\ndef checkusername(username):\n mycursor = conn.cursor()\n query = \"SELECT username FROM user WHERE username = '\"+username+\"'\"\n \n mycursor.execute(query)\n result = mycursor.fetchall()\n if(result!=[]):\n \n check(username)\n return result[0]\n \n\n else:\n raise Exception(\"Error data not found\")\n \ndef decoder(func,username):\n return func(username)\ndef check(username):\n mycursor = conn.cursor()\n query = \"SELECT * FROM scrap WHERE userid = '\"+username+\"'\"\n \n mycursor.execute(query)\n result = mycursor.fetchall()\n if(result!=[]):\n objuserid = result[0][0]\n objname = result[0][1]\n objcity = result[0][3]\n objwork = result[0][2]\n objfav = result[0][4]\n obj1 = Person(objname)\n obj1.show(objname,objcity,objwork,objfav)\n\n else:\n scrap(username)\nclass Person:\n name = \"\"\n work =[]\n city = \"\"\n favouraites = {}\n def __init__(self,name,work = [],city = \"Roorkee\"):\n self.name = name\n self.work = work\n self.city = city\n def show(self,name,city,work,favouraites):\n self.name = name\n self.work = work\n self.city = city\n self.favouraites = favouraites\n if self.city == \"\":\n self.city = \"roorkee\"\n \n \n if self.name == \"\" or self.work == []:\n print(\"Error insufficient data\")\n else :\n if self.city == name:\n self.city = \"Roorkee\"\n if(self.name):\n print(\"my name is \"+self.name, end =\" \")\n \n else:\n raise exception(\"name not found\")\n if(self.work):\n print(\"my work is \", end =\" \")\n print(self.work, end =\" \")\n \n else:\n raise exception(\"work not found\")\n\n if(self.city):\n print(\"my city is \"+self.city)\n \n else:\n raise exception(\"city not found\")\n # return (self.name +','+self.city+','+self.work)\nwork = []\nname = \"\"\nlike = {}\ncity = \"\"\n\ndef scrap(username):\n usr=input(\"enter phone no.\")\n pwd=input(\"password\")\n \n driver = webdriver.Chrome(ChromeDriverManager().install())\n driver.get(\"https://m.facebook.com/\")\n print (\"Opened facebook\")\n sleep(1)\n # eng = driver.find_element_by_id('\"locale-selector\"]/div/div[1]/div[3]/span/a')\n # eng.click()\n # sleep(1)\n username_box = driver.find_element_by_id('m_login_email')\n username_box.send_keys(usr)\n print (\"Email Id entered\")\n sleep(5)\n password_box = driver.find_element_by_id('m_login_password')\n password_box.send_keys(pwd)\n print (\"Password entered\")\n \n login_box = driver.find_element_by_id('login_password_step_element')\n print(login_box)\n login_box.click()\n print(login_box)\n\n sleep(10)\n con_box = driver.find_element_by_class_name('_2pii')\n print(login_box)\n con_box.click()\n try:\n driver.get(\"https://m.facebook.com/\"+username+\"/about/\")\n except:\n raise exception(\"Login failed\")\n\n sleep(10)\n name = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[2]/div/div[3]/a').text\n city = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[4]/div/div[1]/div/div[1]/div[2]/div/div[2]/div/div[2]/div/header/h4[1]').text\n \n \n print(name)\n print(city)\n sleep(5)\n \n i = 0\n x = 1\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\n workcount = len(driver.find_elements(By.XPATH,'//*[@id=\"work\"]/div/*'))\n print(work)\n \n while(x<=workcount):\n work.append(driver.find_element(By.XPATH,'//*[@id=\"work\"]/div/div['+str(x)+']/div/div/div[1]/span').text)\n x = x+1\n\n\n print(str(work))\n print(1)\n sleep(3)\n\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\n \n print(workcount)\n sleep(5)\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\n sleep(3)\n \n likecount = len(driver.find_elements_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[1]/div/div[2]/div[12]/div/div/div/div/div/div/div/*'))\n print(likecount)\n y = 1\n while(y<=likecount):\n like[y] = driver.find_element_by_xpath('/html/body/div[1]/div[1]/div[4]/div/div[1]/div/div[2]/div[12]/div/div/div/div/div/div/div/div['+str(y)+']/div/span').text\n y = y+1\n\n print(like)\n \n print (\"Done\")\n\n \n driver.quit()\n obj1 = Person(name)\n obj1.show(name,city,work,like)\n mycursor = conn.cursor()\n workstr = str(work)\n newwork = workstr.replace(\"'\",\"\")\n newwork = newwork.replace(\",\",\" \")\n likestr = str(like)\n newlike = likestr.replace(\"'\",\"\")\n newlike = newlike.replace(\",\",\" \")\n newlike = newlike.replace(\"{\",\"\")\n newlike = newlike.replace(\"}\",\"\")\n query = \"INSERT INTO scrap (userid,name,work,city,favouraites) VALUES (\\'\"+username+\"\\',\\'\"+name+\"\\',\\'\"+newwork+\"\\',\\'\"+city+\"\\',\\'\"+newlike+\"\\');\"\n # connn = mysql.connector.connect(user='manan', password='#Manan#2020#', host='localhost',database='user',auth_plugin = \"mysql_native_password\")\n # cursor = connn.cursor(buffered = True)\n mycursor = conn.cursor()\n mycursor.execute(query)\n conn.commit()\n # print(query)\n # print(\"Finished\")\n \n \n\n \n# print(decoder(checkusername,\"ritvik.jain.52206\"))\n\nclass Test(unittest.TestCase):\n def test_valid2(self):\n with self.assertRaises(Exception):\n decoder(checkusername,\"ritvik.jain.5220\")\n def test_valid3(self):\n with self.assertRaises(Exception):\n decoder(checkusername,\"ritvik.jain.52206\")\n\n\nif __name__ == \"__main__\":\n unittest.main()\n" } ]
2
ADITYAVARDHAN-BLIP/aditya-spark-foundation
https://github.com/ADITYAVARDHAN-BLIP/aditya-spark-foundation
33148c543fd5b4a2691c041be98ced91626651ce
5e185289d2ce79df4e31211f497f802f3d5438e0
80ac98c379ce5a1b86a3dc3a9dab2914eaf10d48
refs/heads/main
2022-12-30T03:59:23.678330
2020-10-18T08:22:01
2020-10-18T08:22:01
305,054,479
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6205421090126038, "alphanum_fraction": 0.636233925819397, "avg_line_length": 23.296297073364258, "blob_id": "1403ecda80394550682f9b9e1ae288ba8637cbdc", "content_id": "01d04a430c21abd286724c8f6035269e898aa4ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 701, "license_type": "no_license", "max_line_length": 71, "num_lines": 27, "path": "/tech.py", "repo_name": "ADITYAVARDHAN-BLIP/aditya-spark-foundation", "src_encoding": "UTF-8", "text": "\r\n ###prediction using decision tree algorithm\r\n\r\n#import important library\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn import tree\r\n\r\n#import the dataset\r\ndf=pd.read_csv(\"Iris.csv\")\r\n\r\n#pre-processing\r\ndf=df.replace({'Iris-setosa':0,'Iris-versicolor':1,'Iris-virginica':2})\r\nx=df.iloc[:,1:-1]\r\ny=df.iloc[:,-1]\r\n\r\n#select and train the model\r\ndtree=DecisionTreeClassifier()\r\ndtree.fit(x,y)\r\n\r\n#plot the decision tree\r\nfig=plt.figure(figsize=(9,9))\r\n_ = tree.plot_tree(dtree,\r\n feature_names=x.columns,\r\n class_names=['0','1','2'],\r\n filled=True)\r\nplt.show()\r\n\r\n" } ]
1
fuzhanrahmanian/Deep-reinforcement-learning
https://github.com/fuzhanrahmanian/Deep-reinforcement-learning
e71cdd32c8d8e22b2d54358d70df6d202707a2c8
92282fb496fa72e7bd05bb04b4435a6313dd9710
44c3dbdc770a9c8e55424bb64774036925c788cc
refs/heads/master
2020-09-01T14:28:13.287355
2020-03-01T17:19:29
2020-03-01T17:19:29
218,979,806
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8110235929489136, "alphanum_fraction": 0.8110235929489136, "avg_line_length": 62, "blob_id": "293dba55fd74d146ff858d0e77b679c46be67fae", "content_id": "541b1720c77d50234e934527d640308d730c52b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 127, "license_type": "no_license", "max_line_length": 109, "num_lines": 2, "path": "/tile-coding/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "## Description \nImplement code to discretize continuous state spaces, to use tabular solution methods to solve complex tasks. \n" }, { "alpha_fraction": 0.7312166094779968, "alphanum_fraction": 0.7456774711608887, "avg_line_length": 42.73239517211914, "blob_id": "3b6ec0fa48109d139dc8d3d57cdef6918c644927", "content_id": "b50b1533457289f8b460350de1e9a7f4a110332e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3181, "license_type": "no_license", "max_line_length": 289, "num_lines": 71, "path": "/Continious_Control/Report.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Report\r\n---\r\nThis project utilised the DDPG (Deep Deterministic Policy Gradient) algorithm.\r\n\r\n## State and Action Spaces\r\nIn this environment, a double-jointed arm can move to target locations. A reward of +0.1 is provided for each step that the agent's hand is in the goal location. Thus, the goal of your agent is to maintain its position at the target location for as many time steps as possible.\r\n\r\nThe observation space consists of 33 variables corresponding to position, rotation, velocity, and angular velocities of the arm. Each action is a vector with four numbers, corresponding to torque applicable to two joints. Every entry in the action vector must be a number between -1 and 1.\r\n\r\n## Learning Algorithm\r\n\r\nThe agent training utilised the `ddpg` function in the Continuous_Control notebook.\r\n\r\nIt continues episodical training via the the ddpg agent until `n_episoses` is at least 100 episodes and reached to the score (average reward) above +30. Note if the number of agents is >1 then the average reward of all agents at that step is used.\r\n\r\nEach episode continues until `max_timesteps` time-steps is reached or until the environment says it's done.\r\n\r\nAs above, a reward of +0.1 is provided for each step that the agent's hand is in the goal location.\r\n\r\nThe DDPG agent is contained in `Agent_DDPG.py`\r\n\r\nFor each time step and agent the Agent acts upon the state utilising a shared (at class level) `replay_buffer`, `actor_local`, `actor_target`, `actor_optimizer`, `critic_local`, `criticl_target` and `critic_optimizer` networks.\r\n\r\n### DDPG Hyper Parameters\r\n- n_episodes (int): maximum number of training episodes\r\n- max_timesteps (int): maximum number of timesteps per episode\r\n- num_agents: number of agents in the environment\r\n\r\nWhere\r\n`n_episodes=600`, `max_timesteps=10000`\r\n\r\n\r\n### DDPG Agent Hyper Parameters\r\n\r\n- BUFFER_SIZE (int): replay buffer size\r\n- BATCH_SIZ (int): mini batch size\r\n- GAMMA (float): discount factor\r\n- TAU (float): for soft update of target parameters\r\n- LR_ACTOR (float): learning rate for optimizer\r\n- LR_CRITIC (float): learning rate for optimizer\r\n- WEIGHT_DECAY (float): L2 weight decay\r\n\r\nWhere \r\n`BUFFER_SIZE = int(1e6)`, `BATCH_SIZE = 128`, `GAMMA = 0.99`, `TAU = 1e-3`, `LR_ACTOR = 1e-4`, `LR_CRITIC = 1e-4` and `WEIGHT_DECAY = 0.0`\r\n\r\n\r\n### Neural Networks\r\n\r\nActor and Critic network models were defined in `Model.py`. \r\n\r\nThe Actor networks utilised two fully connected layers both with 128 units with relu activation and tanh activation for the action space. The network has an initial dimension the same as the state size.\r\n\r\nThe Critic networks utilised two fully connected layers both with 128 units with relu activation. The critic network has an initial dimension the size of the state size plus action size.\r\n\r\n### Rewards plot\r\n\r\n![Plot](Images/plot.png)\r\n\r\n![Episode](Images/episode.PNG)\r\n\r\n\r\n\r\n### Future ideas\r\n\r\nSeveral ideas can be suggested for future work;\r\n\r\n- Using more layers for batch normalization \r\n\r\n- Using dropout on the agent. \r\n\r\n- Exploring other methods including Proximal Policy Optimization (PPO) and Distributed Distributional Deterministic Policy Gradients (D4PG) methods. \r\n\r\n\r\n" }, { "alpha_fraction": 0.6403161883354187, "alphanum_fraction": 0.6613965630531311, "avg_line_length": 38.94736862182617, "blob_id": "4fe9824d4b66b60838f5e059b7f3a066cc293ab8", "content_id": "56048b8b7c0dd2ae5759ec04d126ace93ddefb39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 136, "num_lines": 19, "path": "/p1_navigation/model_representation.py", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass QNetwork(nn.Module):\n\n def __init__(self, state_size, action_size, seed, fc1_hidden=64, fc2_hidden=64): #initialize the parameters inorder to build a model\n super(QNetwork, self).__init__()\n self.seed = torch.manual_seed(seed) #sets the seed for generating random numbers , returns a torch.Generator object\n self.fc1 = nn.Linear(state_size, fc1_hidden)\n self.fc2 = nn.Linear(fc1_hidden, fc2_hidden)\n self.fc3 = nn.Linear(fc2_hidden, action_size)\n\n def forward(self, state): #building a network that map the state to the action values\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n" }, { "alpha_fraction": 0.828125, "alphanum_fraction": 0.828125, "avg_line_length": 41.66666793823242, "blob_id": "e3eb2f7a2285fa40e019a440e887b185826bd834", "content_id": "871b06bd4e278679835a601c02145f6db398d5c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 128, "license_type": "no_license", "max_line_length": 78, "num_lines": 3, "path": "/Policy_Gradient_method/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Description\nPolicy Gradient Method (reinforce)\nuse an implementation of REINFORCE to solve OpenAI Gym's CartPole environment.\n" }, { "alpha_fraction": 0.7887789011001587, "alphanum_fraction": 0.7887789011001587, "avg_line_length": 49.5, "blob_id": "f6b1ff731aef88e47b1ca5d654cab78ac266afa5", "content_id": "dd3e8f3d1b41b5efa9c2f6a23efb84d43580314e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 303, "license_type": "no_license", "max_line_length": 107, "num_lines": 6, "path": "/OpenAi_Taxi_v2/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "## Description \nThe workspace contains three files:\n\n* agent.py: Develop your reinforcement learning agent here. T\n* monitor.py: The interact function tests how well your agent learns from interaction with the environment.\n* main.py: Run this file in the terminal to check the performance of the agent.\n" }, { "alpha_fraction": 0.8103975653648376, "alphanum_fraction": 0.8103975653648376, "avg_line_length": 64.4000015258789, "blob_id": "22b61609ac056ea4675f461d13b26d8c762910ab", "content_id": "78aae04d893978e9d0672cda1ec277fb316d824d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 327, "license_type": "no_license", "max_line_length": 207, "num_lines": 5, "path": "/Proximal_Policy_optimization/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Description\n\nPPO (proximal policy optimization):\nImplementing and train a policy to play atari-pong, using only the pixels as input. The project was solved by using convolutional neural nets, multiprocessing, and pytorch to implement and train the policy. \nOne notebook was solved with REINFORCE and another with PPO method.\n" }, { "alpha_fraction": 0.6855178475379944, "alphanum_fraction": 0.7256597876548767, "avg_line_length": 45.96875, "blob_id": "83ad5cdbc2c9eeb0f5b4c23e2c250bd2daeec079", "content_id": "c458d3c15f01d077e9adbae5c6d79d3ab311aee5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4509, "license_type": "no_license", "max_line_length": 254, "num_lines": 96, "path": "/p1_navigation/Report.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Udacity Deep Reinforcement Learning Nanodegree\n## Project 1: Navigation\n### Train an RL Agent to Collect Bananas\n\n![navigation](https://user-images.githubusercontent.com/52014627/68973702-340bfb00-07ef-11ea-8e13-d238d007fa25.gif)\n*Agent in action*\n\n### Goal\nA reward of +1 is provided for collecting a yellow banana, and a reward of -1 \nis provided for collecting a blue banana. The goal of the agent is to collect as many yellow bananas as possible while avoiding blue bananas. In order to solve the environment, the agent must achieve an average score of +13 over 100 consecutive episodes.\nThis is achieved by using a Unity environment adopted by Udacity available for\n[Windows 64-Bit](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/VisualBanana_Windows_x86_64.zip).\n \n\n ### Approach\n \n #### 1. Start the Environment and import necessary packages\n Basic starting procedure for the initialization of the environment. \n \n #### 2. Examine the State and Action Spaces\n The environment has a dimension of 37, inside which the action can take space. \n These are the possible discrete actions:\n \n - `0` move forward\n- `1` move backward\n- `2` turn left\n- `3` turn right\n\n\n #### 3. Take Random Actions in the Environment\n Below, the agent will select a random action (uniformly), testing it for each time step \n\n```python\nenv_info = env.reset(train_mode=True)[brain_name] # reset the environment\nstate = env_info.vector_observations[0] # get the current state\nscore = 0 # initialize the score\nwhile True:\n action = np.random.randint(action_size) # select an action\n env_info = env.step(action)[brain_name] # send the action to the environment\n next_state = env_info.vector_observations[0] # get the next state\n reward = env_info.rewards[0] # get the reward\n done = env_info.local_done[0] # see if episode has finished\n score += reward # update the score\n state = next_state # roll over the state to next time step\n if done: # exit loop if episode finished\n break\n \nprint(\"Score: {}\".format(score))\n```\n \n #### 4. Training the agent with Deep Q_Network\n The learning algorithm used here is Deep Q_Networks referenced in \n [this paper](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf).\n In the state input vector a deep neural network is used as listed in the following:\n \n- Fully connected layer - input: 37 (state size) output: 64\n- Fully connected layer - input: 64 output 64\n- Fully connected layer - input: 64 output: (action size)\n\nThe DQN algorithm was implemented with the following parameters:\n\n- Maximum steps per episode: 1000\n- Starting epsilon: 1.0\n- Ending epsilon: 0.01\n- Epsilon decay rate: 0.999\n- Number of episodes: 2200\n\nIn every step, the agent will select an action based on the epsilon greedy policy. \nIf the random selected probability is smaller than the epsilon,\n the agent will choose an equiprobable policy (non greedy action and greedy action). \n Else the agent will choose the greedy policy and will take the maximum q-value function.\n ###### &nbsp;\n In order to break the correlation between the experienced tuples and let the agent \n learn more about the past experiences, instead of just focusing on the future steps, \n the replay buffer is used.\n \n \n \n ### Results\n \n![image](https://user-images.githubusercontent.com/52014627/68976454-142c0580-07f6-11ea-97d4-861ca130b00a.png)\n\n ###### &nbsp;\nThis plots shows the rewards gained by the agent during training and at episode 1875 the \nmean-score of the agent reached and surpassed 13.\n\n![image](https://user-images.githubusercontent.com/52014627/68976537-42114a00-07f6-11ea-9eb8-2829532b8321.png)\n\n### Improvements\n- Double DQNs: in order to stop the algorithm from incidental high rewards that may have been obtained by chance.\nThis will stop the DQN from overestimating the Q-Value function. \n- Prioritized experience reply for learning more efficiently from some transitions this algorithm can be applied\nwhich means that the important transition should be sampled with higher probability. \n- Duelling DQNs: since estimating the action of some states does not make difference, this method is presented in order \nto access the value of each state without having to learn the effect of each action and just estimate the value\nof the actions which are prioritized. " }, { "alpha_fraction": 0.7234112620353699, "alphanum_fraction": 0.7451432347297668, "avg_line_length": 57.568626403808594, "blob_id": "3187c7ceb2d7cd19e01d9ca6db53d5fafedf05bd", "content_id": "fc27f744f93129ffd8f221dc1e345e65ca4aed3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3037, "license_type": "no_license", "max_line_length": 308, "num_lines": 51, "path": "/collaboration_and_competition/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "[//]: # (Image References)\r\n\r\n# Project 3: Collaboration and Competition\r\n\r\n### Introduction\r\n\r\n\r\n![Trained Agent](Images/tennis.gif)\r\n\r\nIn this environment, two agents control rackets to bounce a ball over a net. If an agent hits the ball over the net, it receives a reward of +0.1. If an agent lets a ball hit the ground or hits the ball out of bounds, it receives a reward of -0.01. Thus, the goal of each agent is to keep the ball in play.\r\n\r\nThe observation space consists of 8 variables corresponding to the position and velocity of the ball and racket. Each agent receives its own, local observation. Two continuous actions are available, corresponding to movement toward (or away from) the net, and jumping. \r\n\r\nThe task is episodic, and in order to solve the environment, your agents must get an average score of +0.5 (over 100 consecutive episodes, after taking the maximum over both agents). Specifically,\r\n\r\n- After each episode, we add up the rewards that each agent received (without discounting), to get a score for each agent. This yields 2 (potentially different) scores. We then take the maximum of these 2 scores.\r\n- This yields a single **score** for each episode.\r\n\r\nThe environment is considered solved, when the average (over 100 episodes) of those **scores** is at least +0.5.\r\n\r\n### Set up the environment \r\n\r\nDownloading the required environment:\r\n\r\n - Linux: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P3/Tennis/Tennis_Linux.zip)\r\n - Mac OSX: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P3/Tennis/Tennis.app.zip)\r\n - Windows (32-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P3/Tennis/Tennis_Windows_x86.zip)\r\n - Windows (64-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P3/Tennis/Tennis_Windows_x86_64.zip)\r\n \r\n (_For Windows users_) Check out [this link](https://support.microsoft.com/en-us/help/827218/how-to-determine-whether-a-computer-is-running-a-32-bit-version-or-64) if you need help with determining if your computer is running a 32-bit version or 64-bit version of the Windows operating system.\r\n\r\n\r\n\r\n2. Place the file in the DRLND GitHub repository, in the `p3_collab-compet/` folder, and unzip (or decompress) the file. \r\n\r\n### Instructions\r\n\r\nAll of code for the agent is written in the `Tennis.ipynb` file. \r\n\r\n### Strategy and solution \r\n\r\nIn this project 'Multi Agent Deep Deterministic Policy Gradient' algorithm has been used. \r\n\r\nThis project has followed the structure in this [paper](https://arxiv.org/pdf/1509.02971.pdf). Here, the idea is every agent should be modelled based DDPG algorithm (DDPG agent) and each of them has their own actor and critic model.\r\n\r\nEach actor has an observation as the individual state of the agent as an input. The output would be an action. \r\nCritic contains of states and actions of all actors concatenated. \r\n\r\nAt the end, some information will be shared between the agent. \r\n\r\nAll implementaion and hyperparameters are defined in 'Tennis.ipynb'. " }, { "alpha_fraction": 0.8160919547080994, "alphanum_fraction": 0.8160919547080994, "avg_line_length": 56.66666793823242, "blob_id": "07d64d14cd94e92e695fa6c78e4e96efefd559cf", "content_id": "d9d07e32e62ec4df20849689c88cf293612b1fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 174, "license_type": "no_license", "max_line_length": 107, "num_lines": 3, "path": "/Discretization/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "## Description \nConverting continuous space unto a discrete one \nDiscretizing the state-space enable the user to use the existing algorithms with little or no modification. \n" }, { "alpha_fraction": 0.731448769569397, "alphanum_fraction": 0.7536138892173767, "avg_line_length": 61.53061294555664, "blob_id": "6b8955830e451a387a3d66d35225dc30ac5baa9b", "content_id": "0cc7774b9f9d05d321a500eb422a7d124e3747a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3113, "license_type": "no_license", "max_line_length": 390, "num_lines": 49, "path": "/Continious_Control/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "[//]: # (Image References)\r\n\r\n\r\n# Project 2: Continuous Control\r\n\r\n### Introduction\r\n\r\nFor this project, you will work with the [Reacher](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Learning-Environment-Examples.md#reacher) environment. The final goal is solving this environment with utilizing the Reinforcement learning models for continious actions. \r\n\r\n![gif](Images/reacher.gif)\r\n\r\nIn this environment, a double-jointed arm can move to target locations. A reward of +0.1 is provided for each step that the agent's hand is in the goal location. Thus, the goal of your agent is to maintain its position at the target location for as many time steps as possible.\r\n\r\nThe observation space consists of 33 variables corresponding to position, rotation, velocity, and angular velocities of the arm. Each action is a vector with four numbers, corresponding to torque applicable to two joints. Every entry in the action vector should be a number between -1 and 1.\r\n\r\n### Distributed Training\r\n\r\nThis project can be done with two different versions of the unity environment: \r\n- The first version contains a single agent.\r\n- The second version contains 20 identical agents, each with its own copy of the environment. \r\n\r\nThe second version is useful for algorithms like [PPO](https://arxiv.org/pdf/1707.06347.pdf), [A3C](https://arxiv.org/pdf/1602.01783.pdf), and [D4PG](https://openreview.net/pdf?id=SyZipzbCb) that use multiple (non-interacting, parallel) copies of the same agent to distribute the task of gathering experience. \r\n\r\nIn this project, the first version has been used. \r\n\r\n### Solving the Environment with the first version \r\n\r\nThe task is episodic, and in order to solve the environment, your agent must get an average score of +30 over 100 consecutive episodes.\r\n\r\n\r\n### Set up the environment \r\n\r\nThe environment can be downloaded from one of the links below (download link for all operating systems are available).\r\n\r\n - Linux: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/one_agent/Reacher_Linux.zip)\r\n\r\n - Mac OSX: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/one_agent/Reacher.app.zip)\r\n\r\n - Windows (32-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/one_agent/Reacher_Windows_x86.zip)\r\n\r\n - Windows (64-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/one_agent/Reacher_Windows_x86_64.zip)\r\n\r\n### Instruction \r\n \r\n The notebook ['continious_Control.py'](http://localhost:8888/notebooks/Continuous_Control.ipynb) includes the code that is required for setting up the environment. Deep Deterministic Policy Gradient has been used as a suggested solution. The agent, deep Q_Network and memory buffer are implemented in 'Agent_DDPG' as well as the actor and critic model which is written in 'model.py' file. \r\n \r\n This [paper](https://arxiv.org/pdf/1509.02971.pdf) was followed during the project. \r\n\r\n After training, the model weights were saved in the two following files `checkpoint_actor.pth` and `checkpint_critic.pth`.\r\n" }, { "alpha_fraction": 0.739141583442688, "alphanum_fraction": 0.7689539790153503, "avg_line_length": 63.78333282470703, "blob_id": "627414073aa266be0d7dc009910a3ff241ff8ced", "content_id": "7305817f87056acf53d5f3b2c72860f39cfdaf39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3891, "license_type": "no_license", "max_line_length": 336, "num_lines": 60, "path": "/p1_navigation/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "[//]: # (Image References)\n\n[image1]: https://user-images.githubusercontent.com/10624937/42135619-d90f2f28-7d12-11e8-8823-82b970a54d7e.gif \"Trained Agent\"\n\n# Navigation using Deep Reinforcement Learning\n\n###About Deep Reinforcement Learning\n > Reinforcement learning is an important branch of machine\nlearning, where an agent learns to take actions that would yield\nthe most reward by interacting with the environment. Different\nfrom supervised learning, reinforcement learning cannot learn\nfrom samples provided by an experienced external supervisor.\nInstead, it has to operate based on its own experience despite\nthat it faces with significant uncertainty about the environment. Reinforcement learning is defined not characterizing learning\nmethods, but by characterizing a learning problem. Any method\nthat is suitable for solving that problem can be considered as a\nreinforcement learning method [(ref.)](https://link.springer.com/content/pdf/10.1023/A:1022620604568.pdf).\n\n### About the Navigation Project\n\nFor this project, you will train an agent to navigate (and collect bananas!) in a large, square world. \n\n![Trained Agent][image1]\n\n\n\nA reward of +1 is provided for collecting a yellow banana, and a reward of -1 is provided for collecting a blue banana. Thus, the goal of your agent is to collect as many yellow bananas as possible while avoiding blue bananas. \n\nThe state space has 37 dimensions and contains the agent's velocity, along with ray-based perception of objects around agent's forward direction. Given this information, the agent has to learn how to best select actions. Four discrete actions are available, corresponding to:\n- **`0`** - move forward.\n- **`1`** - move backward.\n- **`2`** - turn left.\n- **`3`** - turn right.\n\n\n### About the environment\nThe environment is based on [Unity ML-agents](https://github.com/Unity-Technologies/ml-agents)\n\n> he Unity Machine Learning Agents Toolkit (ML-Agents) is an open-source Unity plugin that enables games and simulations to serve as environments for training intelligent agents. Agents can be trained using reinforcement learning, imitation learning, neuroevolution, \n>or other machine learning methods through a simple-to-use Python API. \n\n\n\n\n### Getting Started\n- Create a Python 3.6 or 3.7 environment with Pythorch 0.4.0\n- Clone this project if it is not already available\n- Install the gym modules in order to use Box2D. \nIf the module does not compile correctly, download and install a pre-compiled version from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/)\n- Download the environment from one of the links below. You need only select the environment that matches your operating system:\n - Linux: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Linux.zip)\n - Mac OSX: [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana.app.zip)\n - Windows (32-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Windows_x86.zip)\n - Windows (64-bit): [click here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Windows_x86_64.zip)\n \n (_For Windows users_) Check out [this link](https://support.microsoft.com/en-us/help/827218/how-to-determine-whether-a-computer-is-running-a-32-bit-version-or-64) if you need help with determining if your computer is running a 32-bit version or 64-bit version of the Windows operating system.\n\n (_For AWS_) If you'd like to train the agent on AWS (and have not [enabled a virtual screen](https://github.com/Unity-Technologies/ml-agents/blob/master/docs/Training-on-Amazon-Web-Service.md)), then please use [this link](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P1/Banana/Banana_Linux_NoVis.zip) to obtain the environment.\n\n- Place the file in the DRLND GitHub repository, in the `p1_navigation/` folder, and unzip (or decompress) the file. \n\n\n\n" }, { "alpha_fraction": 0.7114295363426208, "alphanum_fraction": 0.7320892810821533, "avg_line_length": 39.61111068725586, "blob_id": "e4e7b488aba47832884e6f99055688736a751dcd", "content_id": "c93487395373331902fe1be94d0b4f0a9f9bfd2a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3001, "license_type": "no_license", "max_line_length": 308, "num_lines": 72, "path": "/collaboration_and_competition/Report.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Report\r\n---\r\nThis project utilised the MADDPG (Multi Agent Deep Deterministic Policy Gradient) algorithm.\r\n\r\n## An overview \r\nIn this environment, two agents control rackets to bounce a ball over a net. If an agent hits the ball over the net, it receives a reward of +0.1. If an agent lets a ball hit the ground or hits the ball out of bounds, it receives a reward of -0.01. Thus, the goal of each agent is to keep the ball in play.\r\n\r\nThe observation space consists of 8 variables corresponding to the position and velocity of the ball and racket. Each agent receives its own, local observation. Two continuous actions are available, corresponding to movement toward (or away from) the net, and jumping. \r\n\r\nThe task is episodic, and in order to solve the environment, your agents must get an average score of +0.5 (over 100 consecutive episodes, after taking the maximum over both agents). Specifically,\r\n\r\n- After each episode, we add up the rewards that each agent received (without discounting), to get a score for each agent. This yields 2 (potentially different) scores. We then take the maximum of these 2 scores.\r\n- This yields a single **score** for each episode.\r\n\r\nThe environment is considered solved, when the average (over 100 episodes) of those **scores** is at least +0.5.\r\n\r\n## Learning Algorithm\r\n\r\nFor training the agent the MADDPG algorithm has been implemented. This class uses two DDPG agents. ReplayBuffer is also used as a shared buffer between the agents. \r\n\r\nSo, MADDPG will combine the states, actions, rewards, next-states and dones from both agents and will add them up to the Replay Buffer. \r\n\r\nThe Actor network has 3 linear layers. In the first 2 layers, relu activation has been used and in the last layer, tanh has been utilized. \r\nCritic network has the same structure as actor. \r\n\r\nThe environment has been solved in episode '1278'. The network weights of each agent has been saved in agent1_checkpoint_actor.pth,agent1_checkpoint_critic.pth, agent2_checkpoint_actor.pth and agent2_checkpoint_critic.pth\r\n\r\n### HyperParameters\r\n\r\nBUFFER_SIZE = int(1e5) # replay buffer size\r\n\r\nBATCH_SIZE = 250 # minibatch size\r\n\r\nGAMMA = 0.99 # discount factor\r\n\r\nTAU = 1e-3 # for soft update of target parameters\r\n\r\nLR_ACTOR = 1e-4 # learning rate of the actor\r\n\r\nLR_CRITIC = 1e-3 # learning rate of the critic \r\n\r\nWEIGHT_DECAY = 0 # L2 weight decay\r\n\r\nmu=0\r\n \r\ntheta=0.15\r\n \r\nsigma=0.2\r\n\r\nn_episodes=8000\r\n\r\n\r\n\r\n### Rewards plot\r\n\r\nThe environment has been solved in episode 1278 with an Average score of 0.501. \r\n\r\n![Plot](Images/plot.png)\r\n\r\n![Episode](Images/score.png)\r\n\r\n\r\n\r\n### Future ideas\r\n\r\nSeveral ideas can be suggested for future work;\r\n\r\n- Change the hyperparameters more systematically amd investigate about their effect while training. \r\n\r\n- Using dropout on the agent. \r\n\r\n- Exploring other methods including Multi Agent PPO (Proximal Policy Optimization) and multi agent DQN (Deep Q Network) \r\n\r\n\r\n" }, { "alpha_fraction": 0.824999988079071, "alphanum_fraction": 0.824999988079071, "avg_line_length": 39, "blob_id": "5275c276e28ad7463e6399926a300a27da82ea34", "content_id": "d36bd8c31d7c3fc0d815f6491201c118c2c59d18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 120, "license_type": "no_license", "max_line_length": 81, "num_lines": 3, "path": "/Cross_Entropy/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Description \nCross Entropy Method: \ntrain a Cross-Entropy Method with OpenAI Gym's MountainCarContinuous environment.\n" }, { "alpha_fraction": 0.6835209727287292, "alphanum_fraction": 0.6883188486099243, "avg_line_length": 59.21111297607422, "blob_id": "04cd40578709b4fca676c8727ea1ca3aa53850c4", "content_id": "da1245c635e8f65c70c72cc3d5850c689e194edc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5419, "license_type": "no_license", "max_line_length": 233, "num_lines": 90, "path": "/p1_navigation/DeepQNetwork_Agent.py", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "import numpy as np\nimport random\nfrom collections import namedtuple, deque #namedtuple is factory function for creating tuple subclasses with named fields and deque is list_like container with fast appends and pops on either end\nfrom model_representation import QNetwork\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\n\n\nBUFFER_SIZE = int(1e5) # size of replay buffer\nBATCH_SIZE = 64 # number of minibatch sites\nGAMMA = 0.99 # discount factor\nTAU = 1e-3 # is used for soft update of target parameters\nLR = 5e-4 # value of learning rate\nUPDATE_EVERY = 5 # shows how frequent the network should be updated\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\nclass Agent(): # define the interactions from environment and learn from them\n def __init__(self, state_size, action_size, seed):\n # here I initialized an agent object\n self.state_size = state_size\n self.action_size = action_size\n self.seed = random.seed(seed)\n # Initialiting the Q_Networks\n self.qnetwork_local = QNetwork(state_size, action_size, seed).to(device)\n self.qnetwork_target = QNetwork(state_size, action_size, seed).to(device)\n self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr= LR)\n # initializing the replay memory\n self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)\n self.t_step = 0\n\n def step(self, state, action, reward, next_state, done): # for saving the experience in the replay memory\n self.memory.add(state, action, reward, next_state, done)\n self.t_step = (self.t_step + 1) % UPDATE_EVERY\n if self.t_step == 0:\n if len(self.memory) > BATCH_SIZE: # when the collected samples were enough, then a random subset can be taken and learning process can start\n experiences = self.memory.sample()\n self.learn(experiences, GAMMA)\n\n def act(self, state, eps=0): # choose an action for the given state and based on current policy\n state = torch.from_numpy(state).float().unsqueeze(0).to(device)\n self.qnetwork_local.eval() # turn of the dropout and take the highest performance from the network\n with torch.no_grad(): # shutoff all the gradients\n action_values = self.qnetwork_local(state)\n self.qnetwork_local.train()\n if random.random() > eps: # using the epsilon greedy action\n return np.argmax(action_values.cpu().data.numpy()) # greedy action\n else:\n return random.choice(np.arange(self.action_size))\n\n def learn(self, experiences, gamma): # update the value parameters by using the given batch of experience tuples\n states, actions, rewards, next_states, dones = experiences\n Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1) # geting the maximum predicted Q value for the next states from the target model and us0e detach function to extract all those possible values\n Q_targets = rewards + (gamma * Q_targets_next * (1-dones)) # computing the Q target for the current state\n Q_expected = self.qnetwork_local(states).gather(1, actions) # expected Q value from the local model\n loss = F.mse_loss(Q_expected, Q_targets)\n self.optimizer.zero_grad() # minimize the loss and clear all the gradients of parameters of previous calculation\n loss.backward()\n self.optimizer.step() # update the weight\n self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU) # update the target network\n\n def soft_update(self, local_model, target_model, tau): # soft update model parameters\n for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):\n target_param.data.copy_(tau*local_param.data + (1 - tau)*target_param.data)\n\n\nclass ReplayBuffer: # defining fixed-size buffer to store experience tuples\n def __init__(self, action_size, buffer_size, batch_size, seed):\n self.action_size = action_size\n self.memory = deque(maxlen=buffer_size)\n self.batch_size = batch_size\n self.experience = namedtuple('Experience', field_names=['state', 'action', 'reward', 'next_state', 'done'])\n self.seed = random.seed(seed)\n\n def add(self, state, action, reward, next_state, done): # add a new experience to memory\n e = self.experience(state,action, reward, next_state, done)\n self.memory.append(e)\n\n def sample(self): # randomly sample a batch of experiences from memory\n experiences = random.sample(self.memory, k=self.batch_size)\n states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(device) #np.vstack: stack arrays in sequence vertically (row wise)\n actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(device)\n rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(device)\n next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(device)\n dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(device)\n return (states, actions, rewards, next_states, dones)\n\n def __len__(self): # current size of internal memory\n return len(self.memory)\n" }, { "alpha_fraction": 0.7981651425361633, "alphanum_fraction": 0.7981651425361633, "avg_line_length": 53.5, "blob_id": "e6bcbd2070e39214c4152d7f0552515bb702bc20", "content_id": "950e08837a0992ebd33046267d50981623a00fd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 109, "license_type": "no_license", "max_line_length": 93, "num_lines": 2, "path": "/Deep Q-Networks/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Description \nImplementing a DQN agent and demonstrating how to use it to solve an OpenAI Gym environment.\n" }, { "alpha_fraction": 0.7443946003913879, "alphanum_fraction": 0.7623318433761597, "avg_line_length": 43.599998474121094, "blob_id": "59b82dc23e2e96f15d0a8284238a1e39d32dc4a3", "content_id": "98745f69610129ec559322464846875f50619ba3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 223, "license_type": "no_license", "max_line_length": 61, "num_lines": 5, "path": "/temporal-difference/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "## Description \n* Part 0: Explore CliffWalkingEnv\n* Part 1: Writing an algorithm for TD Control: Sarsa\n* Part 2: Writing an algorithm for TD Control: Q-Learning\n* Part 3: Writing an algorithm for TD Control: Expected Sarsa\n" }, { "alpha_fraction": 0.807692289352417, "alphanum_fraction": 0.807692289352417, "avg_line_length": 33.66666793823242, "blob_id": "37f377fdf70c815c995d9c30ccb1735f5bb33241", "content_id": "4074b87dabff3deee5a912b19dd3cac2db1f1683", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 104, "license_type": "no_license", "max_line_length": 71, "num_lines": 3, "path": "/Hill_Climbing/README.md", "repo_name": "fuzhanrahmanian/Deep-reinforcement-learning", "src_encoding": "UTF-8", "text": "# Description \nHill Climbing: \nExplore an implementation of hill-climbing with adaptive noise scaling.\n" } ]
17
abhishekpandey07/computer_vision
https://github.com/abhishekpandey07/computer_vision
fe4f995d1ee22d9feabd74582f442fdd02cc5ab9
6db8c6a0e03b51f782ec63e887ccff73003bed65
73087153529ef31d8e8d4bc7bdd9e526fe524ba7
refs/heads/master
2020-05-30T08:36:35.169013
2017-10-27T16:10:44
2017-10-27T16:10:44
95,241,790
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5293669104576111, "alphanum_fraction": 0.5751335024833679, "avg_line_length": 32.61538314819336, "blob_id": "0b2508001ed8c57970a2aa8fcedf3fa7f83823b6", "content_id": "ff34b07e3b4eca21d5f7ae048198dbd7f3ca82b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 79, "num_lines": 78, "path": "/snooker_vision_project/ball_tracker.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport matplotlib as plt\nimport common\nimport work_frame\nfrom find_roi import Snooker\n\ndef detectBalls(img):\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n lower = np.array([52,0,0])\n higher = np.array([72,255,255])\n mask = cv2.inRange(hsv,lower,higher)\n mask_inv = cv2.bitwise_not(mask)\n return mask_inv\n\ndef detectHough(img,mask):\n circles = cv2.HoughCircles(mask,cv2.HOUGH_GRADIENT,1.2,10,\n param1=50,param2=7,minRadius=0,\n maxRadius = 15)\n print len(circles[0])\n for i in circles[0,:]:\n cv2.circle(img,(i[0],i[1]),i[2],(255,0,0),2)\n return circles\n\ndef detectBallContour(img,mask):\n _,contours,_ = cv2.findContours(mask,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n circles = []\n for cnt in contours:\n (x,y), r = cv2.minEnclosingCircle(cnt)\n x = int(x)\n y = int(y)\n r = int(r)\n if r < 20:\n if r < 7:\n r = 7\n circles.append([(x,y),r])\n #cv2.circle(img,(int(x),int(y)),int(r),(255,0,0),1)\n \n # x0 = int(x) - 15\n # y0 = int(y) - 10\n # x1 = int(x) + 10\n # y1 = int(y) + 10\n\n #cv2.rectangle(img,(x0,y0),(x1,y1),(255,0,0),1)\n return circles \n\ndef main():\n files = common.getFiles(pattern = 'dataset/captures/*.tiff')\n file = files[2]\n img = cv2.imread(file)\n background = cv2.imread('dataset/background.tiff')\n success,_ , points = work_frame.findAndDrawContours(background.copy())\n snooker = Snooker()\n if success: \n dst = work_frame.changePerspective(points,img)\n dst1 = dst.copy()\n back = work_frame.changePerspective(points,background)\n dst_gray = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)\n back_gray = cv2.cvtColor(back,cv2.COLOR_BGR2GRAY)\n diff = cv2.subtract(dst,back)\n diff_gray = cv2.subtract(dst_gray,back_gray)\n diff_gray1 = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)\n #cv2.imshow('diff_gray',diff_gray)\n #cv2.imshow('diff',diff)\n _ , mask_inv = cv2.threshold(diff_gray,60,255,cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n dilate = cv2.dilate(mask_inv,kernel,iterations = 2)\n #dilate = mask_inv\n circles_cont = detectBallContour(dst1,dilate)\n circles_hough = detectHough(dst,dilate)\n \n cv2.imshow('dst_hough',dst)\n cv2.imshow('dst_contour',dst1)\n cv2.imshow('dilate',dilate)\n cv2.waitKey(0)\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5196629166603088, "alphanum_fraction": 0.5451375246047974, "avg_line_length": 36.95588302612305, "blob_id": "a393dbf58597579df3d5cea87e0ca9d37050dd7f", "content_id": "b2fa6fb730dc562181351ff75fa9bcc6634a7305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10324, "license_type": "no_license", "max_line_length": 111, "num_lines": 272, "path": "/snooker_vision_project/main.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport common\nimport ball_tracker\nimport sys\nfrom sklearn.preprocessing import StandardScaler, LabelBinarizer, LabelEncoder\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport time\nimport cPickle as pickle\nfrom ball_classifier import BallClassifier\nfrom pipeline_draft import ColorSpaceTransformer, HogDescriptor, createHogPipeline, LabelTransform,labelencoder\n\nglobal rectangles_filtered\nglobal changed_img\n\ndef max_area_contour(contours):\n maximum_area = 0\n select = None\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > maximum_area:\n maximum_area = area\n select = cnt\n return select\ndef findContour(img,h=None):\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n if h is None:\n h = np.median(hsv[:,:,0].ravel())\n else:\n h = int(h)\n print 'setting lower h channel to ', h\n lower = np.array([h,0,0])\n higher = np.array([h+20,255,255])\n \n mask = cv2.inRange(hsv,lower,higher)\n _,contours,_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n if len(contours) > 0:\n draw = max_area_contour(contours)\n if draw is not None:\n epsilon = 0.009*cv2.arcLength(draw,True)\n approx = cv2.approxPolyDP(draw,epsilon,True)\n return approx\n\ndef findAndDrawContours(img,h = None):\n\n \n approx = findContour(img,h)\n if approx is not None:\n points = approx.reshape(1,-1)\n points[0][4] = points[0][4] + 1\n points[0][3] = points[0][3] - 3\n points[0][0] = points[0][0] - 3\n points[0][2] = points[0][2] + 4\n points[0][5] = points[0][5] - 5\n points[0][7] = points[0][7] - 5\n points[0][6] = points[0][6] - 3\n points = points.reshape(-1,2)\n\n #changePerspective(points,img)\n #cv2.drawContours(img,[points],-1,[255,0,0],1)\n #x,y,w,h = cv2.boundingRect(approx)\n #cv2.rectangle(img,(x,y-5),(x+w,y+h),(100,0,100),2) \n return True, img, points\n \n return False, None, None\n\nclass changePerspective(BaseEstimator,TransformerMixin):\n def __init__(self, points):\n self.points = points\n\n def fit(self,X,y=None,**fit_params):\n return self\n def transform(self,X):\n r , c = 480, 960\n setpoints = np.float32([[c,r],[c,0],[0,0],[0,r]])\n M = cv2.getPerspectiveTransform(np.float32(self.points),setpoints)\n X = cv2.warpPerspective(X,M,(c,r))\n global changed_img\n changed_img = X\n return X\n\nclass getDilatedMask(BaseEstimator,TransformerMixin):\n def __init__(self,background,method='lol'):\n self.background = background\n self.method = method\n if self.method != 'subtractThenGray':\n self.background = cv2.cvtColor(self.background,cv2.COLOR_BGR2GRAY)\n \n def fit(self,X,y=None,**fit_params):\n return self\n def transform(self,img):\n if self.method == 'subtractThenGray':\n diff = cv2.subtract(img,self.background)\n diff = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)\n else:\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n diff = cv2.subtract(gray,self.background)\n \n _, mask = cv2.threshold(diff,60,255,cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n return (img,cv2.dilate(mask, kernel, iterations=2))\n\nclass GrabBalls(BaseEstimator,TransformerMixin):\n def grabBalls(self,img,circles):\n balls = []\n global rectangles_filtered\n rectangles_filtered = []\n for [(x,y),r] in circles:\n x = x - 15\n y = y - 10\n w = 25\n h = 20\n ball = img[y:y+h,x:x+w]\n if ball.shape[0] == 20 and ball.shape[1] == 25:\n balls.append(ball)\n rectangles_filtered.append([x,y,w,h])\n return balls\n\n def fit(self,X,y=None,**fit_params):\n return self\n\n def transform(self,(img,mask)):\n circles = ball_tracker.detectBallContour(img,mask)\n balls = self.grabBalls(img,circles)\n return balls\n\nclass useLabelPipeline(BaseEstimator,TransformerMixin):\n def __init__(self,pipeline):\n self.pipeline = pipeline\n\n def fit(self,X,y=None,**fit_params):\n return Self\n\n def transform(self,X):\n return self.pipeline.inverse_transform(X)\n\nclass predictionUnion(BaseEstimator,TransformerMixin):\n def fit(self,X,y=None,**fit_params):\n return self\n def transform(self,predictions):\n length = len(predictions)\n length = length/2\n ball_pred = predictions[:length]\n colour_pred = predictions[length:]\n final = []\n for b,c in zip(ball_pred,colour_pred):\n if b != 'false' and c != 'false':\n final.append(c)\n else:\n final.append('false')\n\n return np.array(final)\n \n\ndef main(argv):\n if len(argv) > 1:\n video = argv[1]\n back_address = argv[2]\n h = argv[3]\n if h == 'None':\n h = None\n else:\n h = int(h)\n\n else:\n video = 'dataset/video_data/Ronnie/Ronnie-147.mp4'\n back_address = 'dataset/video_data/Ronnie/background.tiff'\n h = 52\n \n pipeline_address = 'dataset/balls/pipelines/pipeline-'\n #mode = str(argv[4])\n #process = str(argv[5])\n pipeline_ball_address = pipeline_address + 'hog_ova.pkl'\n pipeline_colour_address = pipeline_address + 'hsv_ovo.pkl'\n background = cv2.imread(back_address)\n _,_,points = findAndDrawContours(background.copy(),h)\n perspective = changePerspective(points)\n background = perspective.fit_transform(background)\n cap = cv2.VideoCapture(video)\n\n f = open(pipeline_ball_address,'rb')\n data_ball_pipeline = createHogPipeline()\n label_ball_pipeline = pickle.load(f)\n f.close()\n\n f = open(pipeline_colour_address,'rb')\n data_colour_pipeline = pickle.load(f)\n label_colour_pipeline = pickle.load(f)\n \n if data_colour_pipeline is not None:\n print 'data_colour_pipeline successfully created.'\n if data_ball_pipeline is not None:\n print 'data_ball_pipeline successfully created.'\n if label_colour_pipeline is not None:\n print 'label_colour_pipeline successfully created.'\n if label_ball_pipeline is not None:\n print 'label_ball_pipeline successfully created.'\n\n ball_classifier = BallClassifier('MLP','hog_ova','predictors/models/')\n ball_classifier.load_model()\n\n colour_classifier = BallClassifier('RFC','hsv_ovo','predictors/models/')\n colour_classifier.load_model()\n\n ball_pipeline = Pipeline([('data_ball_pipe',data_ball_pipeline),\n ('ball_classifier',ball_classifier),\n ('label_inverse',useLabelPipeline(label_ball_pipeline))\n ])\n colour_pipeline = Pipeline([('data_colour_pipe',data_colour_pipeline),\n ('colour_classifier',colour_classifier),\n ('label_inverse',useLabelPipeline(label_colour_pipeline))\n ])\n \n frame_pipe = Pipeline([\n ('perspective',perspective),\n ('dilated_mask',getDilatedMask(background,method='lol')),#'subtractThenGray')),\n ('balls',GrabBalls()),\n ('feature_extraction',FeatureUnion([\n ('ball_pipeline',ball_pipeline),\n ('colour_pipeline',colour_pipeline)\n ])),\n ('prediction_union',predictionUnion())\n ])\n \n if frame_pipe is not None:\n print 'frame_pipeline formed'\n\n extract = False\n start = time.time()\n while True:\n ret, frame = cap.read()\n if time.time() - start >7 and not(extract):\n cv2.putText(frame, \"press 'e' to start extracting\",(5,20),\\\n cv2.FONT_HERSHEY_COMPLEX,1,(255,255,255),2)\n cv2.imshow('input',frame)\n \n if extract == True:\n prediction = frame_pipe.transform(frame)\n for predict,[x,y,w,h] in zip(prediction,rectangles_filtered):\n if predict == 'red':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[0,0,255],2)\n elif predict == 'black':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[0,0,0],2)\n elif predict == 'pink':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[255,0,255],2)\n elif predict == 'blue':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[255,0,0],2)\n elif predict == 'brown':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[42,42,165],2)\n elif predict == 'green':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[100,255,0],2)\n elif predict == 'yellow':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[0,255,255],2)\n elif predict == 'cue_ball':\n cv2.rectangle(changed_img,(x,y),(x+w,y+h),[255,255,255],2)\n text = 'reds:'+ str(len(prediction[np.where(prediction == 'red')]))\n cv2.putText(changed_img, text,(5,20),cv2.FONT_HERSHEY_COMPLEX,1,(0,0,255),2)\n cv2.imshow('predicted result', changed_img)\n \n k = cv2.waitKey(1000/100)\n if k == 27:\n break\n elif k == ord('e'):\n extract = not extract\n cv2.destroyAllWindows()\n \nif __name__ == '__main__':\n main(sys.argv)\n" }, { "alpha_fraction": 0.486817330121994, "alphanum_fraction": 0.5414312481880188, "avg_line_length": 24.682926177978516, "blob_id": "f01e445dfd97254bec3de00b81f1a368c34383d4", "content_id": "b3e614d84cffc323d038112f18f604974c5d4a12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 69, "num_lines": 41, "path": "/snooker_vision_project/common.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "from glob import glob\nimport matplotlib.pyplot as plt\nimport cv2\n\ndef getFiles(pattern='dataset/captures/*.tiff'):\n files = glob(pattern)\n return files\n\ndef explore_histogram(img, colour = True, xlim = 256):\n hist = []\n if colour:\n col = ['b','g','r']\n for i, col in enumerate(col):\n hist.append(cv2.calcHist([img],[i],None,[xlim],[0,xlim]))\n # plt.plot(hist, colour = col)\n # plt.xlim([0,xlim])\n else:\n hist.append(cv2.calcHist([img],[0],None,[256],[0,xlim]))\n # plt.plot(hist)\n # plt.xlim([0,xlim])\n #plt.show()\n return hist\n\ndef explore_histogram2d(img):\n return [cv2.calcHist([img],[0,1],None,[180,250],[0,180,0,256])]\n\ndef createGrid(img,size = (8,8)):\n shape = img.shape\n r = size[0]\n c = size[1]\n row = 0\n col = 0\n while row < shape[0]:\n cv2.line(img,(0,row),(shape[1],row),(0,0,255),2)\n row = row+r\n \n while col < shape[1]:\n cv2.line(img,(col,0),(col,shape[0]),(0,0,255),2)\n col = col+c\n\n return img\n \n" }, { "alpha_fraction": 0.5154106020927429, "alphanum_fraction": 0.5534307956695557, "avg_line_length": 31.851852416992188, "blob_id": "6f5bf02734656bbc6d7a005b4300fb9149049141", "content_id": "b270537926625a852a518cd822fa8d831a596999", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4445, "license_type": "no_license", "max_line_length": 85, "num_lines": 135, "path": "/snooker_vision_project/work_frame.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport common\nimport ball_tracker\nimport sys\nfrom sklearn.neural_network import MLPClassifier\nimport cPickle as pickle\nfrom ball_classifier import BallClassifier\n\ndef grabBalls(img,circles):\n balls = []\n for [(x,y),r] in circles:\n x = x - 15\n y = y - 10\n w = 25\n h = 20\n balls.append(img[y:y+h,x:x+w])\n return balls\ndef max_area_contour(contours):\n maximum_area = 0\n select = None\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > maximum_area:\n maximum_area = area\n select = cnt\n return select\ndef findContour(img,h=None):\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n if h is None:\n h = np.median(hsv[:,:,0].ravel())\n else:\n h = int(h)\n print 'setting lower h channel to ', h\n lower = np.array([h,0,0])\n higher = np.array([h+20,255,255])\n \n mask = cv2.inRange(hsv,lower,higher)\n _,contours,_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n if len(contours) > 0:\n draw = max_area_contour(contours)\n if draw is not None:\n epsilon = 0.009*cv2.arcLength(draw,True)\n approx = cv2.approxPolyDP(draw,epsilon,True)\n return approx\n\ndef findAndDrawContours(img,h = None):\n\n \n approx = findContour(img,h)\n if approx is not None:\n points = approx.reshape(1,-1)\n points[0][4] = points[0][4] + 1\n points[0][3] = points[0][3] - 3\n points[0][0] = points[0][0] - 3\n points[0][2] = points[0][2] + 4\n points[0][5] = points[0][5] - 5\n points[0][7] = points[0][7] - 5\n points[0][6] = points[0][6] - 3\n points = points.reshape(-1,2)\n\n #changePerspective(points,img)\n #cv2.drawContours(img,[points],-1,[255,0,0],1)\n #x,y,w,h = cv2.boundingRect(approx)\n #cv2.rectangle(img,(x,y-5),(x+w,y+h),(100,0,100),2) \n return True, img, points\n \n return False, None, None\n\n \ndef changePerspective(points, img):\n r , c = 480, 960\n setpoints = np.float32([[c,r],[c,0],[0,0],[0,r]])\n M = cv2.getPerspectiveTransform(np.float32(self.points),setpoints)\n X = cv2.warpPerspective(img,M,(c,r))\n return X\n\ndef getDilatedMask(img, background, method = 'lol'):\n if method == 'subtractThenGray':\n diff = cv2.subtract(img,background)\n diff = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)\n else:\n background = cv2.cvtColor(background,cv2.COLOR_BGR2GRAY)\n gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n diff = cv2.subtract(gray,background)\n \n _, mask = cv2.threshold(diff,60,255,cv2.THRESH_BINARY)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(3,3))\n return (img,cv2.dilate(mask, kernel, iterations=2))\n\n\n\ndef process_frame(frame,background,points):\n dst = changePerspective(points,frame)\n #background = changePerspective(points,background)\n mask = getDilatedMask(dst,background)\n cv2.imshow('mask',mask)\n circles = ball_tracker.detectBallContour(dst,mask)\n return dst, circles\n\ndef main(argv):\n video = argv[1]\n back_address = argv[2]\n extract = False\n background = cv2.imread(back_address)\n if len(argv) == 4:\n h = argv[3]\n else:\n h = None\n cv2.imshow('back',background)\n cv2.waitKey(0)\n _,_, points = findAndDrawContours(background.copy(),h)\n background = changePerspective(points,background)\n cap = cv2.VideoCapture(video)\n while True:\n ret, frame = cap.read()\n # frame.resize((480,960))\n cv2.imshow('frame',frame)\n dst, circles =process_frame(frame,background,points)\n circle = np.zeros(dst.shape,np.uint8)\n for [(x,y),r] in circles:\n cv2.circle(circle,(x,y),r,(255,255,255),1)\n \n cv2.imshow('changedperspective',dst)\n cv2.imshow('only_circles',circle)\n k = cv2.waitKey(5)\n if k == 27: \n break\n if k == ord('e'):\n extract = not(extract)\n \nif __name__ == '__main__':\n main(sys.argv)\n \n \n" }, { "alpha_fraction": 0.6641221642494202, "alphanum_fraction": 0.6768447756767273, "avg_line_length": 29.230770111083984, "blob_id": "31e03bb4f81597b0eb7fd8793c6e8804e39cdcc2", "content_id": "76a19703c5ce947d741ec697c5cc7aabdcf3ad90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 786, "license_type": "no_license", "max_line_length": 66, "num_lines": 26, "path": "/snooker_vision_project/getBallsDataset.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport common\nimport ball_tracker\nimport work_frame\nfrom glob import glob\n\nbackground_address = 'dataset/background.tiff'\n\ndef main():\n files = common.getFiles()\n background = cv2.imread(background_address)\n _,_,points = work_frame.findAndDrawContours(background.copy())\n background = work_frame.changePerspective(points,background)\n back_gray = cv2.cvtColor(background,cv2.COLOR_BGR2GRAY)\n for f in files:\n img = cv2.imread(f)\n img = work_frame.changePerspective(points,img)\n mask = work_frame.getDilatedMask(img,back_gray)\n circles = ball_tracker.detectBallContour(img,mask)\n cv2.imshow('img',img)\n cv2.waitKey(0)\n cv2.destroyWindow('img')\n \nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.5226130485534668, "alphanum_fraction": 0.5293132066726685, "avg_line_length": 24.717391967773438, "blob_id": "25c72fb9b277ec48290728831c384780a0e2e6cf", "content_id": "2d3f0b6e9a68091888cb46969d7bfc372127da86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1194, "license_type": "no_license", "max_line_length": 64, "num_lines": 46, "path": "/snooker_vision_project/MiscellaneousFiles/dataVisual.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import numpy as np\nimport sys\nimport os\nimport cv2\nimport cPickle as pickle\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\ndef load_data(file):\n f = open(file,'rb')\n if f is not None:\n X_train = pickle.load(f)\n Y_train = pickle.load(f)\n X_test = pickle.load(f)\n Y_test = pickle.load(f)\n mean = pickle.load(f)\n return X_train, Y_train, X_test, Y_test, mean\n else:\n print 'File not Found.'\n raise SystemExit\n\ndef main(argv):\n labels = ['ball','false']\n filename = argv[1]\n if os.path.isfile(filename):\n X_train,Y_train,X_test,Y_test,mean = load_data(filename)\n else:\n print 'File doesnt exist'\n \n print X_train[50:70] \n print np.mean(X_train,axis = 0)==mean\n pca = PCA(n_components=2)\n\n X = pca.fit_transform(X_train)\n for i,(x,y) in enumerate(X):\n for l in labels:\n if Y_train[i]==l:\n if l == 'ball':\n plt.scatter(x,y,color='r')\n else:\n plt.scatter(x,y,color='b')\n \n plt.show()\n \nif __name__ =='__main__':\n main(sys.argv)\n \n\n \n" }, { "alpha_fraction": 0.5849802494049072, "alphanum_fraction": 0.6166008114814758, "avg_line_length": 23.80392074584961, "blob_id": "a2f653a24352d6b43397c5761aab3da97fa3407e", "content_id": "1cef1d311f96bc8c31cd7f7037c1def667b194c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1265, "license_type": "no_license", "max_line_length": 68, "num_lines": 51, "path": "/snooker_vision_project/MiscellaneousFiles/getvalue.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom glob import glob\nglobal hsv\n\nglobal buttondown\nbuttondown = False\nglobal img\nglobal background\nglobal edit\nglobal x0,y0,wf,wh\n\ndef printvalue(event,x,y,flags,param):\n global buttondown, x0,y0,w,h,edit, wf,wh\n if event == cv2.EVENT_LBUTTONDOWN:\n x0,y0 = x,y\n print x0,y0\n buttondown = True\n if event == cv2.EVENT_MOUSEMOVE:\n if buttondown:\n w = np.abs(x-x0)\n h = np.abs(y-y0)\n if event == cv2.EVENT_LBUTTONUP:\n wf = w\n wh = h\n edit = img[y0:y0+wh,x0:x0+wf]\n\n \nimg = cv2.imread('dataset/alain_background-1.tiff')\nbackground = cv2.imread('dataset/alain_background-3.tiff')\ncv2.namedWindow('background')\ncv2.setMouseCallback('background',printvalue)\n\ncanedit = False\n\nwhile(1):\n cv2.imshow('background',background)\n cv2.imshow('img',img)\n if canedit:\n edit_back = background.copy()\n edit_back[y0:y0+wh,x0:x0+wf] = edit\n cv2.imshow('edit_back',edit_back)\n k = cv2.waitKey(20) & 0xFF\n if k == 27:\n break\n if k == ord('c'):\n cv2.imwrite('dataset/alain_background_final.tiff',edit_back)\n print 'file saved'\n if k == ord('e'):\n canedit = not(canedit)\ncv2.destroyAllWindows()\n" }, { "alpha_fraction": 0.5122615694999695, "alphanum_fraction": 0.5277020931243896, "avg_line_length": 29.885713577270508, "blob_id": "d26c40cc6d7462fe6ff376c4ecc8471f1d896a43", "content_id": "a4d2ca7201a5fb61fb5da281c9a43d6c406c5daf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1101, "license_type": "no_license", "max_line_length": 71, "num_lines": 35, "path": "/snooker_vision_project/MiscellaneousFiles/checkDataHistogram.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport common\nfrom glob import glob\nimport matplotlib.pyplot as plt\nimport sys\ndef main(argv):\n global istwoD\n istwoD = argv[1]\n base_directory = 'dataset/balls/balls/'\n labels = ['red','yellow','green','blue','brown',\n 'pink','black','cue_ball','not_balls']\n ext = '.tiff'\n for i,l in enumerate(labels):\n \n directory = base_directory + l + '/*' + ext\n files = glob(directory)\n img = cv2.imread(files[5])\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n number = '52' + str(i+1)\n plt.subplot(int(number))\n if istwoD == 'True':\n hist = common.explore_histogram2d(hsv)\n plt.imshow(hist[0], interpolation = 'nearest')\n else:\n hist = common.explore_histogram(hsv[:,:,0], colour = False)\n colour = ['b','g','r']\n for c,h in enumerate(hist):\n plt.plot(h, color = colour[c] )\n plt.xlim([0,180])\n plt.title(l)\n\n plt.show()\nif __name__ == '__main__':\n main(sys.argv)\n \n\n \n \n" }, { "alpha_fraction": 0.7691926956176758, "alphanum_fraction": 0.7771173715591431, "avg_line_length": 40.20408248901367, "blob_id": "543724be67b1ef1304b4e53611fffb65399ad341", "content_id": "df5f9db6b88a603842fccbead7bd30b09fa0dd39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2019, "license_type": "no_license", "max_line_length": 383, "num_lines": 49, "path": "/snooker_vision_project/README.md", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "# Snooker_Vision_Project\nThis project uses machine learning and image processing to extract a snooker frame from a mounted camera feed and transform it provide a top view of the frame. Machine learning and segmentation is used to detect and classify the balls into their respective colors. This system keeps a track of all the red balls on the table and can be modified to form an autonomous pointing system.\n\nThe coding style makes extensive use of pipelines modules from sklearn.\n\nThe dataset/balls/balls/ directory consists of images of snooker balls in 'labeled' folders. pipeline_draft.py uses pipelines to extract these images and performs the passed computations and feature extraction on the dataset and saves the dataset into the folder dataset/balls/preprocessedDataPipeline folder using cPickle module\n\nSome pretrained classifiers can be found in predictors folders.\n\nThe dataset can be processed in ovo ( colour classification ) and ova ( ball/ not ball for false positives) mode. The classifiers have been trained and saved on each of these modes and with various preprocessing indicated by the prefix of file names.\n\nhue --> HSV colorspace ( only h vector)\n\ngray --> grayscale images\n\nhog --> HOG descriptors\n\n\n![screenshot](screenshots/s2.png)\n\n\n# Demo.\n First go to the project directory.\n \n1. Create a virtual environment for this project( optional)\n2. Use req.txt to install dependent modules thorugh pip\n `pip install -r req.txt`\n3. Install OpenCV.\n Any version should work, but > 3.0 is recommended.\n \n Note: You may have to build it. In which case, make sure you copy the cv2.so file into \n the virtualenv's sitepackes directory.\n \n4. run `python main.py`\n\nAbove command will use the video at `dataset/video_data/Ronnie/Ronnie-147.mp4`\nand file `dataset/video_data/Ronnie/background.tiff` as input. The default hue filtering\nparameter `h` is set to 52 for segmenting the frame from background.\n\n\n![screenshot](screenshots/s0.png)\n\n\n![screenshot](screenshots/s1.png)\n\n\n\n\nENJOY!\n" }, { "alpha_fraction": 0.5644400119781494, "alphanum_fraction": 0.5745959281921387, "avg_line_length": 29.640350341796875, "blob_id": "d0a919cc705d5974cd41dec26dfe93396f316531", "content_id": "bbc34b57fb01fffaa2ecfcb5a63c8e3656f79c0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6991, "license_type": "no_license", "max_line_length": 179, "num_lines": 228, "path": "/snooker_vision_project/dataset_creation/createDataset.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport common\nfrom glob import glob\nimport os\nimport cPickle as pickle\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import LabelBinarizer, StandardScaler, LabelEncoder\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.base import BaseEstimator, TransformerMixin\nimport sys\n\ndef encodeLabels(labels):\n #encoder = LabelBinarizer(sparse_output = False)\n encoder = LabelEncoder()\n labels = encoder.fit_transform(labels)\n return labels, encoder\n\ndef preprocessData(samples,scale = False):\n mean = np.mean(samples,axis = 0)\n samples = np.subtract(samples,mean)\n if scale:\n scaler = StandardScaler()\n scaler.fit_transform(samples)\n return samples,mean,scaler\n else:\n return samples,mean,None\n\ndef load_data(label,X,Y,mode='ovo',process = 'hsv'):\n count = 0\n base_directory = 'dataset/balls/balls/'\n ext = '.tiff'\n pattern = base_directory + label + '/*' + ext\n files = glob(pattern)\n if process == 'hog':\n hog = createHogDescriptor()\n for f in files:\n img = cv2.imread(f)\n if process =='hsv':\n print 'converting ' + f + ' in HSV'\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n x,_,_ = cv2.split(hsv)\n x = x.flatten()\n elif process=='gray':\n print 'converting ' + f + ' in Gray' \n x = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY).flatten()\n\n elif process=='hog':\n x = cv2.cvtColor(cv2.resize(img,(20,20)),cv2.COLOR_BGR2GRAY)\n x = hog.compute(x)\n x = x.flatten()\n else:\n print 'Unknown data process. Please pass \"hsv\" or \"gray\"'\n raise SystemExit\n if len(x) == 500 or process == 'hog':\n X.append(x.flatten())\n if mode == 'ova':\n if label != 'false':\n Y.append('ball')\n else:\n Y.append(label)\n elif mode == 'ovo':\n Y.append(label)\n\n\n\ndef split_data(samples,labels,test_ratio):\n shuffled_indices = np.random.permutation(len(samples))\n test_size = int(len(samples)*test_ratio)\n test_indices = shuffled_indices[:test_size]\n train_indices = shuffled_indices[test_size:]\n X_train = samples[train_indices]\n Y_train = labels[train_indices]\n X_test = samples[test_indices]\n Y_test = labels[test_indices]\n return X_train,Y_train,X_test,Y_test\n\ndef split_stratified(samples,labels):\n skfolds = StratifiedKFold(n_splits = 5, random_state=42)\n for train_index, test_index in skfolds.split(samples,labels):\n X_train = samples[train_index]\n Y_train = labels[train_index]\n X_test = samples[test_index]\n Y_test = labels[test_index]\n\n return X_train,Y_train,X_test,Y_test\n\ndef labelParticipation(Y, labels):\n participation = np.zeros((1,len(labels)))\n \n for y in Y:\n for i,_ in enumerate(labels):\n if y == labels[i]:\n participation[0][i] = participation[0][i] + 1\n\n for i,_ in enumerate(labels):\n print labels[i], ' : ', participation[0][i]\n\nclass ColorSpaceTransformer(BaseEstimator, TransformerMixin):\n def __init__(self,transform):\n self.transform = transform \n def fit(self,X,y=None):\n return self\n def transform(self,X,y=None):\n for i,X in enumerate(X):\n if self.transform == 'hsv':\n x = cv2.cvtColor(X,cv2.COLOR_BGR2HSV)\n x,_,_ = cv2.split(x)\n elif self.transform == 'gray':\n x = cv2.cvtColor(X,cv2.COLOR_BGR2GRAY)\n else:\n print 'Invalid Transform. Please enter \"gray\" or \"hsv\".'\n raise SystemExit\n X[i] = x.flatten()\n return X\n\nclass HogDescriptor(BaseEstimator, TransformerMixin):\n def __init__(self,win_size):\n self.hog = self.creatHogDescriptor()\n\n def createHogDescriptor(self):\n win_size = (20,20)\n block_size = (10,10)\n block_stride = (5,5)\n cell_size = (5,5)\n nbins = 9\n derivAperture = 1\n winSigma = -1\n histogramNormType = 0\n L2hysthreshold = 0.2\n gammacorrection = 1\n nlevels = 64\n signedGradients = True\n \n return cv2.HOGDescriptor(win_size,block_size,block_stride,cell_size,nbins,derivAperture,winSigma,histogramNormType,L2hysthreshold,gammacorrection,nlevels, signedGradients)\n\n def fit(self,X,y=None):\n return self\n def transform(self,X,y=None):\n for x,i in enumerate(X):\n x = cv2.resize(x,(20,20))\n x = self.hog.compute(X)\n X[i] = x.flatten()\n return X\n\nclass labelTransform(TransformerMixin):\n def __init__(self, mode = 'ovo'):\n self.mode = mode\n\n def fit(self,X,y=None):\n return self\n def transform(self,X,y=None):\n if self.mode == 'ovo':\n return X\n elif self.mode == 'ova':\n for x,i in enumerate(X):\n if x != 'false':\n X[i] = 'ball'\n return X\n else:\n print 'Invalid mode selection. Pass \"ovo\" or \"ova\".'\n raise SystemExit\n \ndef main(argv):\n \n save_directory = 'dataset/balls/processedData/'\n save_file = argv[1]\n mode = argv[2]\n process = argv[3]\n scale = argv[4]\n encode = argv[5]\n print 'Save_Directory:',save_directory\n print 'Save_file:', save_file\n print 'Mode:', mode\n print 'Process:', process\n print 'Scale:', scale\n print 'Encode:', encode\n \n labels = ['red','yellow','green','blue','brown',\n 'pink','black','cue_ball','false']\n\n X = []\n Y = []\n for l in labels:\n load_data(l,X,Y,mode,process)\n \n X = np.array(X)\n Y = np.array(Y)\n\n if encode == 'True':\n print 'Encoding Labels'\n Y, label_encoder = encodeLabels(Y)\n \n X_train,Y_train,X_test,Y_test = split_stratified(X,Y)\n print 'Training Data : ',len(X_train)\n print 'Testing Data : ', len(X_test)\n\n if mode == 'ova':\n labels = ['false','ball']\n \n print 'Participation of Stratified splitting:'\n labelParticipation(Y_test,labels)\n\n if process != 'hog':\n print 'Processing Samples. Process is not HOG'\n X_train,mean,scaler = preprocessData(X_train,scale=scale)\n\n if not(os.path.isdir(save_directory)):\n os.makedirs(save_directory)\n\n file_name = save_directory + save_file\n print 'Saving data to :', file_name\n f = open(file_name, 'wb')\n pickle.dump(X_train,f)\n pickle.dump(Y_train,f)\n pickle.dump(X_test,f)\n pickle.dump(Y_test,f)\n if encode == 'True':\n print 'Saving Encoder'\n pickle.dump(label_encoder,f)\n if process != 'hog':\n if scaler is not None:\n print ' Saving Scaler'\n pickle.dump(scaler,f)\n pickle.dump(mean,f)\n \nif __name__ == '__main__':\n main(sys.argv)\n \n" }, { "alpha_fraction": 0.5951471328735352, "alphanum_fraction": 0.5989682674407959, "avg_line_length": 32.76774215698242, "blob_id": "947e3efeca2b28865bb7482ce93145d041eb2c73", "content_id": "9fb98efb7cd28154f78d7279c24867c65e3ab2ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5234, "license_type": "no_license", "max_line_length": 80, "num_lines": 155, "path": "/snooker_vision_project/ball_classifier.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import os\nimport sys\nimport numpy as np\nimport cv2\nfrom sklearn import svm\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neural_network import MLPClassifier\nfrom sklearn.model_selection import StratifiedKFold, cross_val_score\nfrom sklearn.base import clone\nfrom sklearn.metrics import confusion_matrix, precision_score\nfrom sklearn.metrics import recall_score,f1_score,accuracy_score\nimport cPickle as pickle\nimport matplotlib.pyplot as plt\n\nclass BallClassifier:\n def __init__(self,model_type = 'lol', model_name = '0',\n save_dir = 'predictors/models/'):\n self.model_name = model_name\n self.model_type = model_type\n self.save_dir = save_dir+self.model_type+'/'\n if self.model_type == 'SVC':\n self.model = svm.SVC()\n elif self.model_type == 'SGD':\n self.model = SGDClassifier(random_state=7)\n elif self.model_type == 'RFC':\n self.model = RandomForestClassifier()\n elif self.model_type == 'MLP':\n self.model = MLPClassifier()\n # Add more model later\n else:\n print 'Invalid Model Type'\n raise SystemExit\n\n def fit(self,X_train,Y_train):\n self.model.fit(X_train,Y_train)\n return self\n\n def predict(self,y):\n return self.model.predict(y) \n def transform(self,y):\n return self.predict(y)\n \n def score(self,X,y):\n return self.model.score(X,y)\n\n def save_model(self):\n if not(os.path.isdir(self.save_dir)):\n os.makedirs(self.save_dir)\n print 'Directory :', self.save_dir, ' created successfully.'\n \n save_file = self.save_dir+self.model_name+'.pkl'\n f = open(save_file,'wb')\n pickle.dump(self.model,f)\n f.close()\n print 'Model saved successfully to ' + save_file\n\n def load_model(self):\n if not(os.path.isdir(self.save_dir)):\n print 'Load failed. Directory doesnt exist'\n\n else:\n load_file = self.save_dir+self.model_name+'.pkl'\n f = open(load_file,'rb')\n self.model = pickle.load(f)\n if self.model is not None:\n 'Loading successful.'\n else:\n print 'An error occured. Load_failed'\n\ndef load_data(file,process):\n f = open(file,'rb')\n mean = None; label_encoder = None;\n scaler = None;\n if f is not None:\n X_train = pickle.load(f)\n Y_train = pickle.load(f)\n X_test = pickle.load(f)\n Y_test = pickle.load(f)\n return X_train,Y_train,X_test,Y_test\n \ndef cross_validate(classifier,X,Y,n_splits):\n skfolds = StratifiedKFold(n_splits=n_splits,random_state=7)\n best_accuracy = 0\n clones = []\n accuracies = []\n for train_index,test_index in skfolds.split(X,Y): \n clone_clf = clone(classifier.model)\n X_train = X[train_index]\n Y_train = Y[train_index]\n X_test = X[test_index]\n Y_test = Y[test_index]\n clone_clf.fit(X_train,Y_train)\n y_pred = clone_clf.predict(X_test)\n accuracy = accuracy_score(Y_test,y_pred,average=None)\n accuracies.append(accuracy)\n clones.append(clone_clf)\n\n #clones=np.array(clones)\n accuracies = np.array(accuracies)\n print 'accuracies:',precisions\n best_accuracy = 0\n index = -1\n for i,b in enumerate(accuracies):\n if b > best_accuracy:\n index = i\n best_accuracy = b\n best_clone = clones[index]\n print 'Saving best model with accuracy:', best_accuracy\n classifier.model = best_clone\n return accuracies, classifier\n\ndef main(argv):\n load_data_file = argv[1]\n mode = argv[2]\n process = argv[3]\n encode = argv[5]\n scale = argv[4]\n if len(argv) > 2:\n save_model_dir = argv[6]\n model_types = ['SGD','SVC','RFC','MLP']\n\n X_train, Y_train,X_test,Y_test = load_data(load_data_file,process)\n for model in model_types:\n print '\\nTraining and Evaluating a', model,'classifier'\n bclf = BallClassifier(model_type = model, model_name = process+'_'+mode)\n bclf.fit(X_train,Y_train)\n #Y_pred = bclf.predict(X_train)\n #conf = confusion_matrix(Y_train,Y_pred)\n #print \"Printing Confusion Matrix for\",model,\" classifier.\"\n #print conf\n #plt.matshow(conf)\n print 'Cross Validating ', model, 'classifier'\n scores, bclf = cross_validate(bclf,X_train,Y_train,3)\n #plt.show()\n\n print'\\nEvaluating Test set with :'\n y_pred = bclf.predict(X_test)\n conf = confusion_matrix(Y_test,y_pred)\n print conf\n #plt.matshow(conf)\n precision = precision_score(Y_test,y_pred,average='macro')\n recall = recall_score(Y_test,y_pred,average = 'macro')\n # f1 = f1_scrore(Y_test,y_pred)\n accuracy = accuracy_score(Y_test,y_pred)\n print 'Accuracy:', accuracy\n print 'Precision:', precision\n print 'Recall:', recall\n\n print 'Saving the model to', save_model_dir+model+'/'\n bclf.save_model()\n #print 'F1_score:', f1\n #plt.show()\nif __name__ == '__main__':\n main(sys.argv)\n" }, { "alpha_fraction": 0.4777906537055969, "alphanum_fraction": 0.5160293579101562, "avg_line_length": 29.761905670166016, "blob_id": "7f02a2009cad5220b3ecf81bd9ff7b9bc0f4d9f5", "content_id": "ab201198fe7bb34b11a51bb21bfbf38a0d2116d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2589, "license_type": "no_license", "max_line_length": 95, "num_lines": 84, "path": "/snooker_vision_project/find_roi.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nfrom glob import glob\n\nclass Snooker:\n def __init__(self):\n self.roi = None\n\n def max_area_contour(self):\n maximum_area = 0\n select = None\n for cnt in self.contours:\n area = cv2.contourArea(cnt)\n if area > maximum_area:\n maximum_area = area\n select = cnt\n return select\n \n def findROI(self,img):\n lower = np.array([52,0,61])\n higher = np.array([80,255,255])\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n mask = cv2.inRange(hsv,lower,higher)\n _, self.contours,_ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n if self.contours is not(None):\n select = self.max_area_contour()\n if select is not None:\n (x,y,w,h) = cv2.boundingRect(select)\n self.roi = hsv[y-5:y+h,x:x+w]\n return True, img[y-5:y+h,x:x+w]\n return False,None\n\n def findBalls(self,img):\n reds = []\n colors = np.array((-1,6))\n cueball = None\n lower = np.array([[61,255,185],[0,0,0]])\n higher= np.array([[70,255,193],[20,255,255]])\n mask_blue = cv2.inRange(self.roi,lower[0],higher[0])\n mask_red = cv2.inRange(self.roi, lower[1], higher[1])\n\n _,contour_blue,_ = cv2.findContours(mask_blue,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n _,contour_red,_ = cv2.findContours(mask_red,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\n red = np.zeros(self.roi.shape,np.uint8)\n blue = np.zeros(self.roi.shape, np.uint8)\n\n cv2.drawContours(red,contour_red,-1,(0,0,255),2)\n cv2.drawContours(blue,contour_blue,-1,(255,0,0),2)\n\n cv2.imshow('red',red)\n cv2.imshow('blue',blue)\n \n \n\ndef main():\n extract = False\n calibrate = False\n balls = False\n cap = cv2.VideoCapture('dataset/Ronnie-147.mp4')\n snooker = Snooker()\n while True:\n \n ret, frame = cap.read()\n cv2.imshow('frame',frame)\n if extract == True:\n ret, roi = snooker.findROI(frame)\n if balls:\n snooker.findBalls(roi)\n cv2.imshow('roi',roi)\n k = cv2.waitKey(5)\n if k == 27:\n break\n if k == ord('e'):\n extract = True\n if k == ord('c'):\n calibrate = not(calibrate)\n if k == ord('b'):\n balls = not(balls)\n \n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n main()\n \n" }, { "alpha_fraction": 0.5416445732116699, "alphanum_fraction": 0.5877984166145325, "avg_line_length": 22.16666603088379, "blob_id": "0124dd92a0445b5a02fdfc8f7bada97811692bca", "content_id": "d9df4794572bd11ce655ff5388bab356ab2a3cfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1885, "license_type": "no_license", "max_line_length": 87, "num_lines": 78, "path": "/snooker_vision_project/MiscellaneousFiles/ColorObjectTracker.py", "repo_name": "abhishekpandey07/computer_vision", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\nfrom glob import glob\r\n\r\n\r\nglobal isDraw\r\nisDraw = False\r\n\r\ndef draw():\r\n global x,y,w,h\r\n\t_ , contours, heirarchy = cv2.findContours(mask,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\r\n contours = [cv2.approxPolyDP(cnt, 3, True) for cnt in contours]\r\n\tarea = 0 \r\n\tfor x in contours:\r\n\t\tif cv2.contourArea(x) > area:\r\n\t\t\tarea = cv2.contourArea(x)\r\n draw = x\r\n\tcv2.drawContours(frame,[draw],-1,(255,0,0),3,cv2.LINE_AA)\r\n x,y,w,h = cv2.boundingRect(draw)\r\n print x,y,w,h\r\n cv2.rectangle(frame,(x,y-5),(x+w,y+5+h),(0,0,255),3)\r\n\t\r\n \r\n'''captures = 'dataset/captures/*.tiff'\r\nfiles = glob(captures)\r\n\r\nfile = files[4]\r\n\r\nimg = cv2.imread(file)'''\r\n\r\nlower = np.array([0,100,100])\r\nupper = np.array([0,255,255])\r\ncap = cv2.VideoCapture(0)\r\n\r\ndef nothing(x):\r\n\tpass\r\n\r\ndef changeH(h):\r\n\tglobal lower , upper\r\n\tlower.itemset(0,h)\r\n\tupper.itemset(0,h+20)\r\n\t\r\ndef changeS(s):\r\n\tglobal lower , upper\r\n\tlower.itemset(1,s)\r\n\r\ndef changeV(v):\r\n\tglobal lower , upper\r\n\tlower.itemset(2,v)\r\n\r\ncv2.namedWindow('Control',cv2.WINDOW_NORMAL)\t\r\ncv2.createTrackbar('H','Control',0,179,changeH)\r\ncv2.createTrackbar('S','Control',0,255,changeS)\r\ncv2.createTrackbar('V','Control',0,255,changeV)\r\n\r\ncap = cv2.VideoCapture('dataset/Alain-pink.mkv')\r\nwhile True:\r\n\tret, frame = cap.read()\r\n\r\n hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)\r\n\tmask = cv2.inRange(hsv,lower,upper)\r\n\r\n\tres = cv2.bitwise_and(frame,frame,mask = mask)\r\n if isDraw:\r\n draw()\r\n roi = frame[y-5:y+5+h,x:x+w]\r\n if roi.shape[0] > 0 & roi.shape[1] > 0:\r\n cv2.imshow('roi',roi)\r\n\tcv2.imshow('frame',frame)\r\n\tk = cv2.waitKey(5) & 0xFF\r\n\r\n\tif k == ord('x'):\r\n\t\tbreak\r\n\r\n if k == ord('c'):\r\n isDraw = not(isDraw)\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n" } ]
13
furstma/SpeedMap
https://github.com/furstma/SpeedMap
8a161bc12be97ac7a5094fe4a3d4edbc4fd64a94
62dc038fd3d6e0070dd2b91b0b8646a612b1e840
77c34c534052eaf7d837c5a483fcdafda12f02e6
refs/heads/main
2023-05-27T18:03:54.094034
2021-06-16T14:02:00
2021-06-16T14:02:00
377,451,738
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7132866978645325, "alphanum_fraction": 0.7832167744636536, "avg_line_length": 19.428571701049805, "blob_id": "aefea12c38cf0d49f656a8519c5d91ba492295ef", "content_id": "826dbedfb1898ac4c20737b0cec7389ba3817328", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 143, "license_type": "no_license", "max_line_length": 69, "num_lines": 7, "path": "/README.md", "repo_name": "furstma/SpeedMap", "src_encoding": "UTF-8", "text": "# SpeedMap\n\nTool visalising runability on an orienteering map. \n\n\nTODO: \nkalibrace mapy z https://www.tulospalvelu.fi/gps/20210613H21/init.txt\n" }, { "alpha_fraction": 0.6158707737922668, "alphanum_fraction": 0.625, "avg_line_length": 30.66666603088379, "blob_id": "9ce7acee3dedd78bc33a281652a579dc9405a738", "content_id": "e6a4dd7593007160c167ea9c9cbe2b3885fa9a9e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1424, "license_type": "no_license", "max_line_length": 116, "num_lines": 45, "path": "/data_downloader.py", "repo_name": "furstma/SpeedMap", "src_encoding": "UTF-8", "text": "import argparse\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--eventID\", default=\"20210613H21\", type=str, help=\"Event ID from https://www.gpsseuranta.net/\")\n\n\ndef main(args):\n event_folder_path = \"Data\\{}\".format(args.eventID)\n if not os.path.exists(event_folder_path):\n os.makedirs(event_folder_path)\n\n print(\"----- Download started ------\")\n\n URL = 'http://www.tulospalvelu.fi/gps/gpx/?eventID={}'.format(args.eventID)\n page = requests.get(URL)\n\n soap = BeautifulSoup(page.content, 'html.parser')\n\n runners = soap.find_all('li')\n\n for runner in runners:\n name = runner.text.strip()\n if name[0:6] == \"vakant\":\n continue\n link = runner.find('a')['href']\n link = \"http://www.tulospalvelu.fi/gps/gpx/{}\".format(link)\n gpx = requests.get(link, allow_redirects=True)\n with open(event_folder_path + '/{}.gpx'.format(name), 'wb') as f:\n f.write(gpx.content)\n\n map_url = \"https://www.tulospalvelu.fi/gps/{}/map\".format(args.eventID)\n map = requests.get(map_url, allow_redirects=True)\n with open(event_folder_path + '/map.bmp', 'wb') as f:\n f.write(map.content)\n\n print(\"----- Event {} (map and {} runners) successfully downloaded ------\".format(args.eventID, len(runners)))\n\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n main(args)" } ]
2
Luciferiitr/Online-messaging-and-image-sharing-app
https://github.com/Luciferiitr/Online-messaging-and-image-sharing-app
ea83f2630c65b19929b503f76f04aaab3e1c8ac2
8787995e6ce7148ce38a8fdc0c217299590205c9
ea683a65c9eddbe83af0063c213ba2dba14828ef
refs/heads/master
2023-07-30T07:37:08.178521
2021-06-18T11:45:27
2021-06-18T11:45:27
275,356,288
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6284916400909424, "alphanum_fraction": 0.6396648287773132, "avg_line_length": 24.571428298950195, "blob_id": "444628bacd42333f8a2c492aec91da8b8656c877", "content_id": "7a8c0b8af514e391427bd705ada9d6bb2448205f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 358, "license_type": "no_license", "max_line_length": 78, "num_lines": 14, "path": "/Messenger/forms.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "from .models import *\nfrom django import forms\n\n\nclass MessageForm(forms.ModelForm):\n Text = forms.CharField(widget=forms.Textarea(attrs={\"rows\":5, \"cols\":20}))\n class Meta:\n model = Messages\n exclude = [\"From\", \"date_time\"]\n\nclass MessageForm2(forms.ModelForm):\n class Meta():\n model = Messages\n exclude = [\"date_time\"]\n" }, { "alpha_fraction": 0.6723549365997314, "alphanum_fraction": 0.6723549365997314, "avg_line_length": 31.55555534362793, "blob_id": "89211c8cdd5a73f37da8fe49cad6b444a742e889", "content_id": "07b7d5837c1095e3769d80038cec7411dfb760da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 586, "license_type": "no_license", "max_line_length": 84, "num_lines": 18, "path": "/Online_Messaging_app/routing.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "from channels.routing import ProtocolTypeRouter, URLRouter\nfrom django.urls import path\nfrom channels.auth import AuthMiddlewareStack\nfrom channels.security.websocket import AllowedHostsOriginValidator, OriginValidator\n\nfrom Messenger.consumers import ChatConsumer\napplication = ProtocolTypeRouter({\n # Empty for now (http->django views is added by default)\n 'websocket' : AllowedHostsOriginValidator(\n AuthMiddlewareStack(\n URLRouter(\n [\n path('home/<phone>/', ChatConsumer),\n ]\n )\n )\n )\n})\n" }, { "alpha_fraction": 0.5466408729553223, "alphanum_fraction": 0.5524408221244812, "avg_line_length": 28.98550796508789, "blob_id": "0f191d579315c10e3eb794ac1662844e3bc7b6bd", "content_id": "f6af7456561b26710aa781c635f002fc3514a91a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2069, "license_type": "no_license", "max_line_length": 107, "num_lines": 69, "path": "/Messenger/consumers.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "import asyncio\nimport json\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nfrom channels.consumer import AsyncConsumer\nfrom django.contrib.auth import get_user_model\nfrom channels.db import database_sync_to_async\n\n\nimport base64\nfrom django.core.files.base import ContentFile\n\nfrom .models import *\n\nclass ChatConsumer(AsyncConsumer):\n async def websocket_connect(self, event):\n print('connected', event)\n\n\n other_user = self.scope['url_route']['kwargs']['phone']\n me = self.scope['user']\n print(other_user, me)\n self.chat_room = 'chat1';\n await self.channel_layer.group_add(\n self.chat_room,\n self.channel_name\n )\n await self.send({\n 'type' : 'websocket.accept'\n })\n\n async def websocket_receive(self , event):\n print('receive', event)\n msg = event['text']\n data = json.loads(msg)\n # print(data)\n await self.get_photo_url(data)\n await self.channel_layer.group_send(\n self.chat_room,\n {\n 'type' : 'chat_message',\n 'text' : json.dumps(data)\n }\n )\n\n async def chat_message(self, event):\n await self.send({\n 'type' : 'websocket.send',\n 'text' : event['text']\n })\n async def websocket_disconnect(self , event):\n print('disconnected', event)\n\n\n\n @database_sync_to_async\n def get_photo_url(self, msg):\n # if msg['photo']=='':\n obj = list(Messages.objects.filter(From = msg['From'], To = msg['To'], Text = msg['Text']))\n if len(obj)!=0:\n if msg['photo']!='':\n msg['photo'] = obj[0].photo.url\n # else :\n # data = msg['photo']\n # format, imgstr = data.split(';base64,')\n # ext = format.split('/')[-1]\n #\n # data = ContentFile(base64.b64decode(imgstr), name='temp.' + ext)\n #\n # Messages.objects.create(From = msg['From'], To = msg['To'], Text = msg['Text'], photo = data)\n" }, { "alpha_fraction": 0.5861671566963196, "alphanum_fraction": 0.5890489816665649, "avg_line_length": 29.98214340209961, "blob_id": "b38b8375bc6d5b1c8ff1230321aa661e3e25d651", "content_id": "314ba5c05daeabf03bdf7b59b9e1d7f336223ab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1735, "license_type": "no_license", "max_line_length": 77, "num_lines": 56, "path": "/Messenger/views.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponse, FileResponse\nfrom django.template.response import TemplateResponse\nfrom .models import *\nfrom .forms import *\n\n# Create your views here.\ndef index(request):\n return render(request, 'Messenger/index.html')\n\n\n\ndef home(request, phone = \"000\"):\n if request.method == 'POST':\n data = request.POST.copy()\n data['From'] = phone\n formComp = MessageForm2(data)\n fCp = formComp.save(commit = False)\n if 'photo' in request.FILES:\n fCp.photo = request.FILES['photo']\n fCp.save()\n msgs = Messages.objects.all()\n user_msgs = []\n for msg in msgs:\n if msg.From==phone or msg.To==phone:\n user_msg = {}\n user_msg[\"is_from\"] = msg.From == phone\n user_msg[\"other_phone\"] = msg.From if msg.To == phone else msg.To\n user_msg['text'] = msg.Text\n user_msg['date'] = msg.date_time\n user_msg['url'] = msg.photo.url if msg.photo else ''\n user_msg['isphoto'] = True if msg.photo else False\n user_msgs.append(user_msg)\n user_msgs.reverse()\n form = MessageForm()\n mydict = {\n 'form' : form,\n 'user_msgs' : user_msgs,\n 'phone' : phone\n }\n return TemplateResponse(request, 'Messenger/home.html', context = mydict)\n\n\n\n\ndef send_message(request):\n if request.method == 'POST':\n formComp = MessageForm2(request.POST)\n fCp = formComp.save(commit = False)\n if 'photo' in request.FILES:\n fCp.photo = request.FILES['photo']\n fCp.save()\n response = {\n 'message' : 'Message sent'\n }\n return JsonResponse(response)\n" }, { "alpha_fraction": 0.5292096138000488, "alphanum_fraction": 0.5945017337799072, "avg_line_length": 17.1875, "blob_id": "c29074924d5433309f1b2652ba4740cbaf17fdf9", "content_id": "43a819b1cd84430d3f19132cb775ae00bf6485ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 291, "license_type": "no_license", "max_line_length": 47, "num_lines": 16, "path": "/Messenger/migrations/0004_delete_photobank.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.7 on 2020-07-01 19:54\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Messenger', '0003_photobank'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='PhotoBank',\n ),\n ]\n" }, { "alpha_fraction": 0.6915113925933838, "alphanum_fraction": 0.7080745100975037, "avg_line_length": 29.1875, "blob_id": "be6cd7b8812350f48d1254c53fe6b58147635bbd", "content_id": "16bcc8b3443a96eb75eff5d0e216e313d68d96e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 65, "num_lines": 16, "path": "/Messenger/models.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "from django.db import models\nimport datetime\nfrom django.utils import timezone\n\n\ndef return_date_time():\n now = timezone.now()\n return now\n\n# Create your models here.\nclass Messages(models.Model):\n From = models.CharField(max_length = 13)\n To = models.CharField(max_length = 13)\n Text = models.CharField(max_length = 1024, blank = True)\n date_time = models.DateTimeField(default = return_date_time)\n photo = models.ImageField(upload_to = 'images', blank = True)\n" }, { "alpha_fraction": 0.7963370084762573, "alphanum_fraction": 0.797802209854126, "avg_line_length": 55.875, "blob_id": "67576ea6d243707a1be6c5f2e1a21c30c4137087", "content_id": "f73861672c32be3b2b7989abd7bba2e82d0ffd3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1365, "license_type": "no_license", "max_line_length": 326, "num_lines": 24, "path": "/README.md", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "# Online-messaging-and-image-sharing-app\nA chat web application which enables real time communication through web sockets. This app is made on django and makes use of recent but very popular django library called django-channels. The app enables us to send messages or Images which will get transferred real time.\n\n## Installation\n\nDownload and git and redis.\nMake sure you have a python distribution of 3.7 or up\nThen follow the steps below\n\n```\ngit clone https://github.com/Luciferiitr/Online-messaging-and-image-sharing-app.git\ncd Online-messaging-and-image-sharing-app/\npip install -r requirements.txt\npython manage.py runserver\n```\n\n## Deployment\nI would advise heroku for deploment. It provides all the necessary resources with one line of command without any hastle. Deployment is same as normal django app on heroku except for instead of gunicorn , daphne server will be used since we have to handle http as well as web socket requests. A detailed guide can be found at \nhttps://www.codingforentrepreneurs.com/blog/django-channels-to-production/\n\nAn example of app running on live stream : https://lit-earth.herokuapp.com/\n\n## Additional notes\nThe app can cause problems while setting up in Windows operating system. I had a hard time setting up channel layers with redis-server on windows. So I would advise that ,if possible, use ubuntu for installation.\n" }, { "alpha_fraction": 0.5779816508293152, "alphanum_fraction": 0.6215596199035645, "avg_line_length": 21.947368621826172, "blob_id": "a8b0d43ccf7db596cd3a6664966cbcb8cf242dc9", "content_id": "6462a2d3c5bc5013569ee5506b4e7dbc2edb6135", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 436, "license_type": "no_license", "max_line_length": 82, "num_lines": 19, "path": "/Messenger/migrations/0002_messages_date_time.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2020-06-28 15:36\n\nimport Messenger.models\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Messenger', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='messages',\n name='date_time',\n field=models.DateTimeField(default=Messenger.models.return_date_time),\n ),\n ]\n" }, { "alpha_fraction": 0.6256486177444458, "alphanum_fraction": 0.6345441341400146, "avg_line_length": 32.44628143310547, "blob_id": "5ded3f52191f5a3b179d971b5e38f9c02f9fd80b", "content_id": "e24ad0929e9eb05555239c9e317bcfb26cebaa5c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 4047, "license_type": "no_license", "max_line_length": 80, "num_lines": 121, "path": "/static/js/homeScript.js", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "console.log(window.location);\nvar loc = window.location;\nvar wsStart = 'ws://';\nif (loc.protocol == 'https:'){\n wsStart = 'wss://';\n}\nvar endpoint = wsStart + loc.host + loc.pathname;\nvar socket = new ReconnectingWebSocket(endpoint)\n\nlet msg_to = document.getElementById('id_To');\nlet msg_text = document.getElementById('id_Text');\nlet msg_photo = document.getElementById('id_photo');\nlet phone = {{ phone }};\nphone = phone.toString();\n\n\nsocket.onmessage = (e) => {\n console.log('message', e.data);\n var msg = JSON.parse(e.data)\n console.log('msg', msg)\n\n if ( msg['From']==phone || msg['To']==phone){\n //display msg\n let table = document.getElementById('id_table')\n let h4 = document.createElement('H4');\n let other_phone = document.createTextNode(msg['To'])\n let text = document.createTextNode(msg['Text'])\n let x = document.createElement('IMG');\n x.setAttribute(\"src\", \"/media/profile/download.png\");\n x.setAttribute(\"width\", \"70px\");\n x.setAttribute(\"height\", \"70px\");\n let send_receive = document.createTextNode('sent : ');\n if(msg['To']==phone){\n send_receive = document.createTextNode('received : ');\n other_phone = document.createTextNode(msg['From'])\n }\n h4.appendChild(other_phone);\n let td2 = document.createElement('TD')\n td2.appendChild(h4);\n td2.appendChild(send_receive);\n td2.appendChild(text);\n\n let td1 = document.createElement('TD');\n td1.appendChild(x)\n let tr = document.createElement('TR');\n tr.appendChild(td1);\n tr.appendChild(td2);\n table.insertBefore(tr, table.childNodes[0]);\n table.className = \"table-striped\" + \" container\";\n\n\n //display received photo\n if (msg['photo']){\n let table_photo = document.getElementById('id_table_photo')\n let x_photo = document.createElement('IMG');\n x_photo.setAttribute(\"src\", msg['photo']);\n x_photo.setAttribute(\"width\", \"300px\");\n x_photo.setAttribute(\"height\", \"300px\");\n\n let send_receive_photo = document.createTextNode(' sent to : ');\n let other_phone_photo = document.createTextNode(msg['To'])\n if(msg['To']==phone){\n send_receive_photo = document.createTextNode(' received from : ');\n let other_phone_photo = document.createTextNode(msg['From'])\n }\n let tr_photo = document.createElement('TR');\n let br_photo = document.createElement('BR');\n tr_photo.appendChild(x_photo)\n // tr_photo.appendChild(br_photo);\n tr_photo.appendChild(send_receive_photo)\n tr_photo.appendChild(other_phone_photo)\n table_photo.insertBefore(tr_photo, table_photo.childNodes[0]);\n table_photo.className = \"table-striped\" + \" container\";\n }\n }\n\n}\nsocket.onopen = (e) => {\n console.log('open', e)\n formElem.onsubmit = async (event) => {\n event.preventDefault();\n let formData = new FormData(formElem)\n formData.append('From', {{ phone }})\n let response = await fetch('http://127.0.0.1:8000/send_message/', {\n method : 'POST',\n body : formData\n });\n let result = await response.json()\n let data = {\n 'From' : phone,\n 'To' : msg_to.value,\n 'Text' : msg_text.value,\n 'photo' : msg_photo.value\n }\n socket.send(JSON.stringify(data))\n form = document.getElementById('formElem');\n form.reset();\n }\n}\nsocket.onerror = (e) => {\n console.log('error', e)\n}\nsocket.onclose = (e) => {\n console.log('close', e)\n}\n\n//tabs functionality enabled\ndocument.getElementById(\"defaultOpen\").click();\nfunction openCity(evt, cityName) {\n var i, tabcontent, tablinks;\n tabcontent = document.getElementsByClassName(\"tabcontent\");\n for (i = 0; i < tabcontent.length; i++) {\n tabcontent[i].style.display = \"none\";\n }\n tablinks = document.getElementsByClassName(\"tablinks\");\n for (i = 0; i < tablinks.length; i++) {\n tablinks[i].className = tablinks[i].className.replace(\" active\", \"\");\n }\n document.getElementById(cityName).style.display = \"block\";\n evt.currentTarget.className += \" active\";\n}\n" }, { "alpha_fraction": 0.5266187191009521, "alphanum_fraction": 0.5597122311592102, "avg_line_length": 27.95833396911621, "blob_id": "3b2f94a5d489be48cd041642a3ba813e5dafa1a3", "content_id": "eccd10937d07e5b4d9edefc7cb5dd2c1113d6676", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 695, "license_type": "no_license", "max_line_length": 114, "num_lines": 24, "path": "/Messenger/migrations/0001_initial.py", "repo_name": "Luciferiitr/Online-messaging-and-image-sharing-app", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.5 on 2020-06-28 08:47\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='Messages',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('From', models.CharField(max_length=13)),\n ('To', models.CharField(max_length=13)),\n ('Text', models.CharField(blank=True, max_length=1024)),\n ('photo', models.ImageField(blank=True, upload_to='images')),\n ],\n ),\n ]\n" } ]
10
coryshain/MEG_langloc
https://github.com/coryshain/MEG_langloc
05f4824bb8fb793c94bd3e2c7746ed63740e774a
43f5c60d7ec6833394b7820c063daf2ca3efcecb
7b3be6cdedac8882b7458ee7c97e91ef3286e0b9
refs/heads/master
2023-06-21T14:28:40.292315
2021-07-29T13:20:48
2021-07-29T13:20:48
386,955,984
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.47462254762649536, "alphanum_fraction": 0.48522326350212097, "avg_line_length": 37.313846588134766, "blob_id": "a1266900d1c3b34f355187cd2f694cc7a33a52cd", "content_id": "07c702aaa3e6fcf4302237a5a223fd043331af3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12452, "license_type": "no_license", "max_line_length": 162, "num_lines": 325, "path": "/meg_langloc/extract.py", "repo_name": "coryshain/MEG_langloc", "src_encoding": "UTF-8", "text": "import sys\nimport os\nimport re\nimport numpy as np\nimport pandas as pd\nimport nltk\nfrom scipy import io, signal\n\ndef stderr(x):\n sys.stderr.write(x)\n sys.stderr.flush()\n\ndef tag(x):\n if 'stim' in x:\n col = 'stim'\n else:\n col = 'Sentence'\n s = x[col].lower().split()\n tags = tuple([x[1] for x in nltk.pos_tag(s)])\n\n return tags\n\ndef is_noun(x):\n return x.startswith('NN') or x.startswith('PRP')\n\ndef is_verb(x):\n return x.startswith('VB') or x == 'MD'\n\ndef is_nonword(x):\n return x == 'NONW'\n\ndef simplify_tags(x):\n if is_noun(x):\n return 'N'\n if is_verb(x):\n return 'V'\n if is_nonword(x):\n return x\n return 'O'\n\ndef select_tag(x):\n pos = x['position'] - 1\n tag = x['postag'][pos]\n return tag\n\ndef map_cols(x):\n if x == 'behmat1':\n return 'Run'\n if x == 'behmat2':\n return 'Set'\n if x == 'behmat3':\n return 'Trial'\n if x == 'behmat4':\n return 'Condition'\n if x == 'behmat5':\n return 'Sentence'\n if x == 'behmat6':\n return 'Response'\n if x == 'behmat7':\n return 'RT'\n return x\n\nparse_subject = re.compile('.*FED([0-9]+)$')\nparse_file = re.compile('data_(s|nw)([0-9]+)_trial([0-9]+).mat$')\nparse_run = re.compile('.*run([0-9]).csv$')\nparse_condpos = re.compile('(s|nw|stim)([0-9]+)')\nSUBJ = 0\nCOND = 0\nPOS = 1\nTRIAL = 2\nS_FILES = ['stim%d.mat' % i for i in range(1, 13)]\nNW_FILES = ['stim%d.mat' % i for i in range(31, 43)]\n\n\ntopdir = 'data/english/timing_langloc_Eng/behavioral_langloc/'\n\nstderr('Loading stimulus data...\\n')\ndirs = [topdir + x for x in os.listdir(topdir) if os.path.isdir(topdir + x)]\nwords = []\nword_timestamps = []\nfor _dir in dirs:\n subject = os.path.basename(_dir)[:3]\n if int(subject) != 8 and int(subject) != 14: # Filter bugged subjects\n subject = 's' + subject\n\n # Process stimulus tables\n _Y = []\n for behmat in [_dir + '/' + x for x in os.listdir(_dir) if x.endswith('.csv')]:\n __Y = pd.read_csv(behmat)\n __Y = __Y.rename(map_cols, axis=1)\n run = int(parse_run.search(behmat).group(1))\n if 'stim' in __Y:\n col = 'stim'\n else:\n col = 'Sentence'\n\n # Normalize column names and add missing data\n if 'Set' in __Y:\n del __Y['Set']\n if 'Fixation Time' in __Y:\n del __Y['Fixation Time']\n if 'Response time' in __Y:\n __Y['RT'] = __Y['Response time']\n del __Y['Response time']\n if 'Condition' in __Y:\n __Y['cond'] = __Y['Condition']\n del __Y['Condition']\n if 'Run' in __Y:\n __Y['run'] = __Y['Run']\n del __Y['Run']\n else:\n __Y['run'] = run\n if 'Trial' in __Y:\n __Y['trial'] = __Y['Trial']\n del __Y['Trial']\n else:\n __Y['trial'] = np.arange(len(__Y))\n __Y['response'] = __Y['Response']\n del __Y['Response']\n __Y['subject'] = subject\n __Y['postag'] = __Y.apply(tag, axis=1)\n\n # Tile out by word\n __words = __Y[col].str.split(' ').apply(pd.Series, 1).stack().str.lower()\n __words.index = __words.index.droplevel(-1)\n __words.name = 'word'\n __Y = __Y.join(__words)\n del __Y[col]\n\n __Y['position'] = __Y.groupby('trial').cumcount() + 1\n _Y.append(__Y)\n _Y = pd.concat(_Y, axis=0).reset_index(drop=True)\n _Y['postag'] = _Y.apply(select_tag, axis=1)\n _Y['postagsimp'] = _Y['postag'].apply(simplify_tags)\n _Y['wlen'] = _Y['word'].str.len()\n _Y['trial'] = _Y.groupby(['cond', 'position']).cumcount() + 1\n words.append(_Y)\n\n # Process timing tables\n # Try tables named 'sN.mat'/'nwN.mat'\n for basename in [x for x in os.listdir(_dir) if (parse_condpos.match(x) and parse_condpos.match(x).group(1) in ['nw', 's'])]:\n cond, position = parse_condpos.match(basename).groups()\n path = _dir + '/' + basename\n _timestamps = io.loadmat(path)[cond + position][0]\n _timestamps = pd.DataFrame({'time': _timestamps})\n _timestamps['trial'] = np.arange(len(_timestamps)) + 1\n if cond == 'nw':\n _timestamps['cond'] = 'N'\n else:\n _timestamps['cond'] = 'S'\n _timestamps['position'] = int(position)\n _timestamps['subject'] = subject\n word_timestamps.append(_timestamps)\n\n # Now try tables named 'stimN.mat'\n for basename in [x for x in os.listdir(_dir) if (x.startswith('stim') and (x in S_FILES or x in NW_FILES))]:\n cond, position = parse_condpos.match(basename).groups()\n position = int(position)\n path = _dir + '/' + basename\n _timestamps = io.loadmat(path)['stimtime'][0]\n _timestamps = pd.DataFrame({'time': _timestamps})\n _timestamps['trial'] = np.arange(len(_timestamps)) + 1\n if position > 12:\n _timestamps['cond'] = 'N'\n position -= 30\n else:\n _timestamps['cond'] = 'S'\n cond = 'S'\n _timestamps['position'] = int(position)\n _timestamps['subject'] = subject\n word_timestamps.append(_timestamps)\n\n\nwords = pd.concat(words, axis=0).reset_index(drop=True)\nword_timestamps = pd.concat(word_timestamps, axis=0).reset_index(drop=True)\nwords = words.merge(word_timestamps, on=['subject', 'cond', 'trial', 'position'])\nwords = words.sort_values(['subject', 'run', 'time']).reset_index(drop=True)\n\nstderr('Loading MEG data...\\n')\ntopdir = 'data/english/'\ndirs = [topdir + x for x in os.listdir(topdir) if x.startswith('FED')]\n\n# Iterate subjects\nMEG = []\nsubjects = set(words['subject'].unique())\nfor _dir in dirs:\n # Get subject ID\n subject = 's' + parse_subject.match(_dir).groups()[SUBJ]\n if subject in subjects: # Only get MEG timecourses for subjects with valid behavioral data\n # Iterate condition (S,NW) + sequence position (word 1-8)\n for subdir in os.listdir(_dir):\n __dir = _dir + '/' + subdir\n stderr(' %s\\n' % __dir)\n\n # Get indices and names of magnetometer channels\n channels = io.loadmat(__dir + '/channel_vectorview306_acc1.mat')['Channel']\n mag_channel_ix = [i for i, x in enumerate(channels['Type'][0]) if x[0] == 'MEG MAG']\n grad1_channel_ix = [i for i, (x, y) in enumerate(zip(channels['Type'][0], channels['Name'][0])) if (x[0] == 'MEG GRAD' and y[0].endswith('2'))]\n grad2_channel_ix = [i for i, (x, y) in enumerate(zip(channels['Type'][0], channels['Name'][0])) if (x[0] == 'MEG GRAD' and y[0].endswith('3'))]\n mag_channel_names = [channels['Name'][0][i][0] for i in mag_channel_ix]\n grad1_channel_names = [channels['Name'][0][i][0] for i in grad1_channel_ix]\n grad2_channel_names = [channels['Name'][0][i][0] for i in grad2_channel_ix]\n gradnorm_channel_names = ['MEGGN' + x[3:6] for x in mag_channel_names]\n\n # Get names of bad files to drop\n bad_trials = io.loadmat(__dir + '/brainstormstudy.mat')['BadTrials']\n if len(bad_trials):\n bad_trials = {x[0] for x in bad_trials[0]}\n else:\n bad_trials = {}\n\n # Iterate trials (individual presentations of the Nth word of condition C)\n for path in os.listdir(__dir):\n if path.startswith('data'):\n # Get the name of the condition, the position index, and the trial index\n matches = parse_file.match(path).groups()\n cond, position, trial = matches[COND], int(matches[POS]), int(matches[TRIAL])\n if cond == 'nw':\n cond = 'N'\n else:\n cond = 'S'\n\n if cond in ['S', 'N']:\n if path in bad_trials:\n words = words[~(\n (words.subject == subject) &\n (words.cond == cond) &\n (words.position == position) &\n (words.trial == trial)\n )]\n else:\n # Load the timecourses (each 1.4s long measured every 2ms)\n src = io.loadmat(__dir + '/' + path)\n F = src['F']\n F *= 1e15 # convert to fT\n F_mag = F[mag_channel_ix].T\n F_grad1 = F[grad1_channel_ix].T\n F_grad2 = F[grad2_channel_ix].T\n F_gradnorm = np.sqrt(F_grad1 ** 2 + F_grad2 ** 2)\n\n # Currently using gradnorm\n # F = np.concatenate([F_mag, F_grad1, F_grad2, F_gradnorm], axis=1)\n # channel_names = mag_channel_names + grad1_channel_names + grad2_channel_names + gradnorm_channel_names\n F = F_gradnorm\n channel_names = gradnorm_channel_names\n time = src['Time'][0]\n\n # Resample to 10ms chunks, i.e. 1/5 resolution\n F = signal.resample(F, 140, axis=0)\n time_ix = np.arange(3, len(time), 5) # starts at 3, midpoint of 10ms frame\n Y_match = words[\n (words.subject == subject) &\n (words.cond == cond) &\n (words.position == position) &\n (words.trial == trial)\n ]\n time_base = Y_match.time.values\n if not len(time_base):\n stderr('No stimuli matching this series were found in Y. Key: <%s, %s, %s, %s>. Skipping...\\n' % (subject, cond, position, trial))\n continue\n time_base = np.squeeze(time_base)\n time = time[time_ix] + time_base\n run = np.squeeze(Y_match.run)\n\n # Construct the output dataframe\n _X = pd.DataFrame(F, columns=channel_names)\n\n _X['subject'] = subject\n _X['cond'] = cond\n _X['position'] = position\n _X['trial'] = trial\n _X['time'] = time\n _X['run'] = run\n\n MEG.append((subject, run, time_base, cond, trial, position, _X))\n\n# De-epoch by trimming overlapping MEG images.\nMEG = sorted(MEG, key=lambda x: x[:3]) # sorting by subject, run, and time reconstitutes the order of the original series\nkey_series_prev = None\n_X_prev = None\nfor i, _X in enumerate(MEG):\n subject = _X[0]\n run = _X[1]\n key_series = (subject, run)\n time_base = _X[2]\n cond = _X[3]\n trial = _X[4]\n position = _X[5]\n _X = _X[6]\n\n # print('subject')\n # print(subject)\n # print('run')\n # print(run)\n # print('key_series')\n # print(key_series)\n # print('time_base')\n # print(time_base)\n # print('cond')\n # print(cond)\n # print('trial')\n # print(trial)\n # print('position')\n # print(position)\n # input()\n\n if _X_prev is not None and key_series == key_series_prev:\n # Trim measures from the last epoch (if applicable) that\n # extend beyond this epoch's start time.\n _X_prev = MEG[i - 1]\n _X_prev = _X_prev[_X_prev.time < time_base]\n MEG[i - 1] = _X_prev\n\n # Trim measures from this epoch that extend beyond the (trimmed)\n # last epoch's end time\n _X = _X[_X.time > np.max(_X_prev.time)]\n\n MEG[i] = _X\n key_series_prev = key_series\n _X_prev = _X\n\nMEG = pd.concat(MEG, axis=0)\n\nwords.to_csv('data/english/words_eng.csv', sep=' ', index=False, na_rep='NaN')\nMEG.to_csv('data/english/MEG_eng.csv', sep=' ', index=False, na_rep='NaN')\n" }, { "alpha_fraction": 0.5920000076293945, "alphanum_fraction": 0.6173333525657654, "avg_line_length": 30.893617630004883, "blob_id": "5683229b9561c41f7b9119b5b5d8269025b68a3d", "content_id": "0020ca7d7f0e933ae8c41b22b2963529f2d1e583", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1500, "license_type": "no_license", "max_line_length": 103, "num_lines": 47, "path": "/meg_langloc/bootstrap.py", "repo_name": "coryshain/MEG_langloc", "src_encoding": "UTF-8", "text": "import sys\nimport math\nimport numpy as np\nimport pandas as pd\nimport argparse\nfrom sklearn.metrics import f1_score\n\ndef permutation_test(gold, preds, n=10000):\n classes, counts = np.unique(gold, return_counts=True)\n majority = classes[np.argmax(counts)]\n baseline = majority * np.ones_like(gold)\n baseline_f1 = f1_score(gold, baseline, average='macro')\n model_f1 = f1_score(gold, preds, average='macro')\n f1_diff = model_f1 - baseline_f1\n\n pred_table = np.stack([preds, baseline], 1)\n\n hits = 0\n\n for i in range(n):\n if i == 0 or (i + 1) % 10 == 0:\n sys.stderr.write('\\r%d/%d' % (i + 1, n))\n sys.stderr.flush()\n shuffle = (np.random.random((len(pred_table))) > 0.5).astype('int')\n m1 = pred_table[np.arange(len(pred_table)),shuffle]\n m2 = pred_table[np.arange(len(pred_table)),1-shuffle]\n _f1_diff = math.fabs(f1_score(gold, m1, average='macro') - f1_score(gold, m2, average='macro'))\n if _f1_diff >= f1_diff:\n hits += 1\n\n p = float(hits+1)/(n+1)\n\n sys.stderr.write('\\n')\n sys.stderr.flush()\n\n return p, f1_diff\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser('''\n Paired permutation test of classifier F1 against a majority class baseline.\n ''')\n argparser.add_argument('path', help='Path to prediction table.')\n args = argparser.parse_args()\n\n df = pd.read_csv(args.path, sep=' ')\n\n print(permutation_test(df.CDRobs.values, df.CDRpreds.values))\n\n" }, { "alpha_fraction": 0.8387096524238586, "alphanum_fraction": 0.8387096524238586, "avg_line_length": 45.5, "blob_id": "ff6cb33be9b4ab9a8b4326395affa1c105721699", "content_id": "4d38ffe7211017e93d5969c1445e50cb7b1ac152", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 93, "license_type": "no_license", "max_line_length": 78, "num_lines": 2, "path": "/README.md", "repo_name": "coryshain/MEG_langloc", "src_encoding": "UTF-8", "text": "# MEG_langloc\nPostprocessing pipeline for MEG language localizer data from the Fedorenko lab\n" } ]
3
charlesyoussef/ISE_AD_Script
https://github.com/charlesyoussef/ISE_AD_Script
97ea9dd8db6ae51bff64e5204a6ad5debb7e6fe5
1816fcad8c5ffe18fa3efba5235d67b7df1b35f7
7351526bd094e51c2e5e6b1d900f0f70c6858785
refs/heads/master
2020-04-07T12:34:11.747439
2019-05-29T12:44:05
2019-05-29T12:44:05
158,372,539
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6452980041503906, "alphanum_fraction": 0.6512582898139954, "avg_line_length": 45.78480911254883, "blob_id": "bdb33eea3002a2ebbf8405c6eb459280cc73c6b1", "content_id": "a4f6c1b0f6b6ba919b8044d1edf3ee3688a45902", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7550, "license_type": "no_license", "max_line_length": 526, "num_lines": 158, "path": "/ise_ad_script.py", "repo_name": "charlesyoussef/ISE_AD_Script", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"ISE AD Script Console Script\r\n\r\nDue to instability in the AD connector between Cisco ISE and Microsoft Active Directory, triggered by highly tweaked and hardened AD configuration and change activities causing the AD nodes to flap, the connectivity between ISE and Active Directory can go down and stay down even after the specific failed AD node comes back up. The other AD servers are not used even though they stayed up. When this occurs, the only workaround to restore the ISE connectivity to AD servers is to restart the ISE application from the ISE CLI.\r\n\r\nThis script was developed to automatically apply the workaround when the issue happens, a temporary workaround to be used until the issue is permanently fixed in software.\r\n\r\n\"\"\"\r\n\r\nimport paramiko\r\nimport time\r\nimport datetime\r\nimport socket\r\nimport sys\r\nimport smtplib\r\nimport getpass\r\nfrom email.MIMEMultipart import MIMEMultipart\r\nfrom email.MIMEText import MIMEText\r\n\r\ntry:\r\n import env_user\r\nexcept (SyntaxError, ModuleNotFoundError):\r\n print(\"Invalid input in env_file. Please complete the required fields in the proper format.\")\r\n sys.exit(1)\r\n\r\n__author__ = \"Charles Youssef\"\r\n__email__ = \"[email protected]\"\r\n__version__ = \"0.1.0\"\r\n__copyright__ = \"Copyright (c) 2018 Cisco and/or its affiliates.\"\r\n__license__ = \"Cisco Sample Code License, Version 1.1\"\r\n\r\ntry:\r\n ise_address = env_user.ise_address\r\n ise_username = env_user.ise_username\r\n ise_password = env_uesr.ise_password\r\n\r\n probe_address = env_user.probe_address\r\n probe_username = env_user.probe_username\r\n probe_password = env_user.probe_password\r\n\r\n sender_email = env_user.sender_email\r\n # recipient_email is a list of comma-separated email addresses\r\n recipient_email = env_user.recipient_email\r\n smtp_server = env_user.smtp_server\r\n smtp_server_port = env_user.smtp_server_port\r\nexcept (NameError, KeyError):\r\n print(\"Invalid input in env_user file. Please complete the required fields in the proper format.\")\r\n sys.exit(1)\r\n\r\n\r\ndef restart_ise(ise_address, ise_username, ise_password, ise_port):\r\n \"\"\"This function is for restarting ISE server with the specified arguments\r\n \"\"\"\r\n ssh = paramiko.SSHClient()\r\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n try:\r\n print(\"%s: Trying to connect to ISE...\" % str(datetime.datetime.now()))\r\n ssh.connect(ise_address, port=ise_port, username=ise_username, password=ise_password, look_for_keys=False, allow_agent=False)\r\n except socket.error:\r\n print(\"%s: ISE is unreachable. Please verify IP connectivity to ISE and rerun the script.\"\r\n % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n except paramiko.ssh_exception.AuthenticationException:\r\n print(\"%s: Unable to login to ISE. Please verify ISE is reachable, verify proper \" \\\r\n \"username/password is set and rerun the script.\" % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n except paramiko.ssh_exception.NoValidConnectionsError:\r\n print(\"%s: ISE is unreachable. Please verify IP connectivity to ISE and then rerun the script.\"\r\n % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n except paramiko.ssh_exception.SSHException:\r\n print(\"%s: Unable to login to ISE. Please verify ISE is reachable, verify proper \" \\\r\n \"username/password is set and rerun the script.\" % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n print(\"%s: Connected to ISE...\" % str(datetime.datetime.now()))\r\n # sleep timers are set based on lab testing response times:\r\n remote_conn = ssh.invoke_shell()\r\n remote_conn.send(\"\\n\")\r\n time.sleep(2)\r\n remote_conn.send(\"\\n\")\r\n time.sleep(2)\r\n print(\"%s: Stopping ISE application...\" % str(datetime.datetime.now()))\r\n remote_conn.send(\"application stop ise\\n\")\r\n time.sleep(300)\r\n print(\"%s: ISE application has been stopped...\" % str(datetime.datetime.now()))\r\n remote_conn.send(\"application start ise\\n\")\r\n print(\"%s: ISE application is being restarted; Please wait...\" % str(datetime.datetime.now()))\r\n time.sleep(300)\r\n print(\"%s: ISE application is being restarted; Please wait...\" % str(datetime.datetime.now()))\r\n time.sleep(300)\r\n print(\"%s: ISE application has been restarted...\" % str(datetime.datetime.now()))\r\n ssh.close()\r\n\r\ndef send_email(from_email, from_email_password, to_email, smtp_email_server_address, smtp_email_server_port):\r\n \"\"\"Function to send an email\r\n \"\"\"\r\n email_server = smtplib.SMTP(smtp_email_server_address, smtp_email_server_port)\r\n email_server.ehlo()\r\n email_server.starttls()\r\n email_server.ehlo()\r\n email_server.login(from_email, from_email_password)\r\n from_address = from_email\r\n to_address = to_email\r\n msg = MIMEMultipart()\r\n msg['From'] = from_address\r\n msg['To'] = ', '.join(to_address)\r\n msg['Subject'] = \"Attention: ise application was restarted!\"\r\n body = \"ise application was stopped/started at \" + str(datetime.datetime.now())\r\n msg.attach(MIMEText(body, 'plain'))\r\n email_text = msg.as_string()\r\n email_server.sendmail(from_address, to_address, email_text)\r\n print(\"%s: A notification email was sent to \" + \", \".join(str(i) for i in to_email) %\r\n str(datetime.datetime.now()))\r\n\r\n\r\ndef main():\r\n\r\n Email_password = getpass.getpass(prompt=\"Please enter the sender email password: \")\r\n while True:\r\n print(\"%s: Starting the ise monitoring script using probe to %s.\" % (\r\n str(datetime.datetime.now()), probe_address))\r\n\r\n failure_count = 0\r\n while failure_count < 3:\r\n try:\r\n probe = paramiko.SSHClient()\r\n probe.set_missing_host_key_policy(paramiko.AutoAddPolicy())\r\n probe.connect(probe_address, port=22, username=probe_username, password=probe_password)\r\n time.sleep(30)\r\n probe.close()\r\n print(\"%s: Monitoring probe is reachable. No actions needed.\" % str(datetime.datetime.now()))\r\n failure_count = 0\r\n except socket.error:\r\n print(\"%s: Monitor probe is unreachable. Please verify IP connectivity to the probe\" \\\r\n \" and rerun the script.\" str(datetime.datetime.now()))\r\n sys.exit(1)\r\n except paramiko.ssh_exception.AuthenticationException:\r\n failure_count += 1\r\n print(\"%s: Authentication failed %s time(s).\" % (str(datetime.datetime.now())),\r\n str(failure_count))\r\n time.sleep(60)\r\n except paramiko.ssh_exception.NoValidConnectionsError:\r\n print(\"%s: Monitor probe is unreachable. Please verify IP connectivity to the probe\" \\\r\n \" and then rerun the script.\" % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n except paramiko.ssh_exception.SSHException:\r\n print(\"%s: Invalid credentials for the probe. Please set proper username/password \" \\\r\n \"and rerun the script.\" % str(datetime.datetime.now()))\r\n sys.exit(1)\r\n print(\"%s: Authentication to probe unavailable. We will proceed \" \\\r\n \"with the ise restart to recover.\" % str(datetime.datetime.now()))\r\n restart_ise(ise_address, ise_username, ise_password, 22)\r\n send_email(sender_email, Email_password, recipient_email, smtp_server, smtp_server_port)\r\n time.sleep(600)\r\n\r\nif __name__ == '__main__':\r\nmain()\r\n" }, { "alpha_fraction": 0.7940854430198669, "alphanum_fraction": 0.7959108948707581, "avg_line_length": 53.779998779296875, "blob_id": "20352393a536b717e9c87cc5ff03dd8f9189b2dc", "content_id": "d0e3772bccde5d2773181d3f869104ffb80a1460", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2739, "license_type": "no_license", "max_line_length": 526, "num_lines": 50, "path": "/README.md", "repo_name": "charlesyoussef/ISE_AD_Script", "src_encoding": "UTF-8", "text": "Motivation\n\nDue to instability in the AD connector between Cisco ISE and Microsoft Active Directory, triggered by highly tweaked and hardened AD configuration and change activities causing the AD nodes to flap, the connectivity between ISE and Active Directory can go down and stay down even after the specific failed AD node comes back up. The other AD servers are not used even though they stayed up. When this occurs, the only workaround to restore the ISE connectivity to AD servers is to restart the ISE application from the ISE CLI.\n\nThis script was developed to automatically apply the workaround when the issue happens, a temporary workaround to be used until the issue is permanently fixed in software.\nFeatures\n\n The script monitors the success of authentication to a monitoring probe which uses ISE for AAA (Authentication) services.\n In case 3 authentication attempts fail due to unresponsiveness, the script performs the workaround of restarting the ISE application.\n An email notification is also sent to a specified recipient list.\n\nCisco Products & Services:\n\n Cisco Identity Services Engine (ISE)\n\nThird-Party Products & Services:\n\n Microsoft Active Directory Server\n\nUsage\n\n Update the variables with the required information in the environment variables file (env_user.py).\n\n Verify IP reachability between ISE server and the machine where the script is to run, and between ISE server and the AAA client where authentication is to be monitored.\n\n Verify that the username & password used in the authentication checks is valid and can successfully authenticate.\n\n Run the script by: $ python ise_ad_script.py\n\nNotes:\n\n Script will exit when the probe is unreachable\n A failure is considered only when the probe is reachable but authentication via ISE is failing\n When the probe re-authenticates successfully after a failure (failure_count < 3), the failure count is reset and subsequently 3 consecutive failures would be needed to trigger the ISE reset\n Script will exit when ISE is unreachable and when authentication is failing to ISE\n\nFor sample runs of the script, please check the screenshots folder.\nInstallation & Prerequisites:\n\nIt is recommended to install the Python dependencies in a new virtual environment based on Python 2.7 or above. For information on setting up a virtual environment please check: http://docs.python-guide.org/en/latest/dev/virtualenvs/\n\nPython package prerequisites in \"requirements.txt\" file which is located in the root directory of this distribution. To install them: $ pip install -r requirements.txt\nAuthors & Maintainers\n\n Charles Youssef [email protected]\n\nCredits\nLicense\n\nThis project is licensed to you under the terms of the Cisco Sample Code License.\n" } ]
2
gboquizo/hackathon_optimizacion_entregas_material
https://github.com/gboquizo/hackathon_optimizacion_entregas_material
efffecb083a54e57ae6a884dbdd723f51eb7433e
58212f48cbdb2e349fd428caee20720530125f27
cc58a4202edff75eb625c7593fa56300f24a20f1
refs/heads/master
2021-05-22T14:04:31.448637
2020-04-05T19:01:51
2020-04-05T19:01:51
252,956,211
0
0
null
2020-04-04T09:25:16
2020-04-04T09:20:23
2020-04-04T09:20:33
null
[ { "alpha_fraction": 0.6379355788230896, "alphanum_fraction": 0.6450091600418091, "avg_line_length": 31.347457885742188, "blob_id": "461c9c97e49b7ba7f802ad4bd4c4ada423c29efc", "content_id": "22fdc3facb92073dfcc9c97e10ccc6b6d414a404", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3817, "license_type": "no_license", "max_line_length": 96, "num_lines": 118, "path": "/app/modules/donor.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "\"\"\"Routes for donor.\"\"\"\nfrom app import csrf\nfrom app.models import Donor, Product, StockDonor\nfrom flask import Blueprint, request\nfrom flask_login import login_required\nfrom flask import jsonify\n\n# Blueprint Configuration\ndonor_bp = Blueprint('donor', __name__)\n\n@donor_bp.route('/api/v1/donor', methods=['GET'])\ndef get_donors():\n donors = [ donor.json() for donor in Donor.query.all() ]\n return jsonify({'donors': donors })\n\n@donor_bp.route('/api/v1/donor/stock', methods=['GET'])\ndef get_stocks():\n stocks = [ stock.serialize for stock in StockDonor.query.all() ]\n return jsonify({'stocks': stocks })\n\[email protected]\n@donor_bp.route('/api/v1/donor/<id>/stock/', methods=['POST'])\ndef create_donor_stock(id):\n json = request.get_json(force=True)\n donor = Donor.query.filter_by(id=id).first()\n product = Product.query.filter_by(id=json['product_id']).first()\n if donor is None:\n return jsonify({'message': 'Donor does not exists'}), 404\n \n if product is None:\n return jsonify({'message': 'Product does not exits'}), 404\n\n stock = StockDonor.create(json['donor_id'], json['product_id'], json['quantity'])\n\n return jsonify({'stock': stock.serialize})\n\n@donor_bp.route('/api/v1/donor/<id>/stock', methods=['GET'])\ndef get_donor_stock(id):\n donor_stock = [ stock.serialize for stock in StockDonor.query.filter_by(donor_id=id).all() ]\n return jsonify({'donor_stock': donor_stock })\n\[email protected]\n@donor_bp.route('/api/v1/donor/stock/<id>', methods=['PUT'])\ndef update_stock(id):\n stock = StockDonor.query.filter_by(id=id).first()\n json = request.get_json(force=True)\n stock.quantity = json['quantity']\n stock.update()\n return jsonify({'stock': stock.serialize })\n\[email protected]\n@donor_bp.route('/api/v1/donor/stock/<id>', methods=['DELETE'])\ndef delete_stock(id):\n stock = StockDonor.query.filter_by(id=id).first()\n if stock is None:\n return jsonify({'message': 'Stock does not exists'}), 404\n\n stock.delete()\n\n return jsonify({'stock': stock.serialize })\n\n@donor_bp.route('/register', methods=[\"POST\"])\ndef register():\n\n \"\"\"\n # Register user\n call auth method\n register_form = RegisterForm(request.form)\n\n if request.method == 'POST' and register_form.validate_on_submit():\n existing_user = User.query.filter_by(email=register_form.email.data).first()\n\n if existing_user is None:\n user = User(\n email=request.form.get('email'),\n password=request.form.get('password'),\n username=request.form.get('username')\n )\n db.session.add(user)\n db.session.commit()\n login_user(user)\n return redirect(url_for('manager.index'))\n\n flash('A user already exists with that email address')\n return redirect(url_for('auth.register'))\n \"\"\"\n json_data = request.get_json()\n if not json_data:\n return {\"message\": \"No input data provided\"}, 400\n\n # Register address\n # Validate and deserialize input\n try:\n address_data = AddressSchema(json_data)\n except ma.ValidationError as err:\n print(err.messages)\n return err.messages, 422\n\n address = Address(address_data)\n db.session.add(address)\n db.session.commit()\n id_address = AddressSchema().dump(Address.query.get(address.id))\n\n # register donor\n # Validate and deserialize input\n try:\n donor_data = DonorSchema(json_data)\n donor_data['address'] = id_address\n except ma.ValidationError as err:\n print(err.messages)\n return err.messages, 422\n\n donor = Donor(donor_data)\n db.session.add(donor)\n db.session.commit()\n id_donor = DonorSchema().dump(donor.query.get(donor.id))\n\n return {\"message\": \"Donor user registered.\", \"id\": id_donor}, 200\n" }, { "alpha_fraction": 0.6547008752822876, "alphanum_fraction": 0.6606837511062622, "avg_line_length": 27.560976028442383, "blob_id": "f7ebda65d89952cb44c9c5c755e4310e477411f0", "content_id": "51919a824cab3e24cc9a9df4a342d7db5ccc4cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 102, "num_lines": 41, "path": "/app/config.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# app/config.py\n\nimport os\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n\nclass BaseConfig(object):\n \"\"\"Base configuration.\"\"\"\n APP_NAME = os.getenv('APP_NAME', 'Delia')\n BCRYPT_LOG_ROUNDS = 4\n DEBUG_TB_ENABLED = False\n SECRET_KEY = os.getenv('SECRET_KEY', 'secret_key')\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n WTF_CSRF_ENABLED = False\n\n\nclass DevelopmentConfig(BaseConfig):\n \"\"\"Development configuration.\"\"\"\n DEBUG_TB_ENABLED = True\n DEBUG_TB_INTERCEPT_REDIRECTS = False\n SQLALCHEMY_DATABASE_URI = 'sqlite:///{0}'.format(\n os.path.join(basedir, 'dev.sqlite')\n )\n\n\nclass TestingConfig(BaseConfig):\n \"\"\"Testing configuration.\"\"\"\n PRESERVE_CONTEXT_ON_EXCEPTION = False\n SQLALCHEMY_DATABASE_URI = 'sqlite:///'\n TESTING = True\n\n\nclass ProductionConfig(BaseConfig):\n \"\"\"Production configuration.\"\"\"\n DB_NAME = os.getenv('PSQL_DB_NAME', 'example')\n DB_USER = os.getenv('PSQL_DB_USER', 'postgres')\n DB_PASSWD = os.getenv('PSQL_DB_PASSWD', '')\n BCRYPT_LOG_ROUNDS = 13\n SQLALCHEMY_DATABASE_URI = 'postgresql://{0}:{1}@localhost/{2}'.format(DB_USER, DB_PASSWD, DB_NAME)\n WTF_CSRF_ENABLED = True" }, { "alpha_fraction": 0.6303901672363281, "alphanum_fraction": 0.6303901672363281, "avg_line_length": 20.217391967773438, "blob_id": "819f382eacdb46606f31a21f09fe3226e6782f5b", "content_id": "3a6d93d3dcd84add3b9a7ff2c9e06486b2366d72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 487, "license_type": "no_license", "max_line_length": 94, "num_lines": 23, "path": "/app/schemas.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "\"\"\"\n\nMap a database model to json data\nSchemas are equivalent to Django serializers.\n\n\"\"\"\nfrom app import ma\nfrom .models import *\n\n\nclass DonorSchema(ma.Schema):\n\n class Meta:\n model = Donor\n sqla_session = db.session\n fields = ('user', 'address', 'updated_at')\n\nclass AddressSchema(ma.Schema):\n\n class Meta:\n model = Donor\n sqla_session = db.session\n fields = ('state', 'city', 'postal_code', 'street', 'number', 'extra_details_address')" }, { "alpha_fraction": 0.6687219738960266, "alphanum_fraction": 0.6838564872741699, "avg_line_length": 25.235294342041016, "blob_id": "b5e4246d1621d79fe9f4ab05592d1437195ae2f8", "content_id": "047f62dca17166516683d71f883802f9ea2a19cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 76, "num_lines": 68, "path": "/app/__init__.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# app/__init__.py\n\nimport os\n\nfrom flask import Flask, render_template\nfrom flask_debugtoolbar import DebugToolbarExtension\nfrom flask_login import LoginManager\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\nfrom flask_wtf import CSRFProtect\nfrom flask_marshmallow import Marshmallow\n\n# Instantiate the extensions\ndb = SQLAlchemy()\nma = Marshmallow()\ncsrf = CSRFProtect()\nlogin_manager = LoginManager()\nmigrate = Migrate()\ntoolbar = DebugToolbarExtension()\n\n\ndef create_app():\n app = Flask(__name__)\n\n # Set config\n app_settings = os.getenv('APP_SETTINGS', 'app.config.DevelopmentConfig')\n app.config.from_object(app_settings)\n\n # Set up extensions\n login_manager.init_app(app)\n db.init_app(app)\n ma.init_app(app)\n csrf.init_app(app)\n toolbar.init_app(app)\n migrate.init_app(app, db)\n\n with app.app_context():\n from app.modules.auth import auth_bp\n from app.modules.admin import admin_bp\n from app.modules.dealer import dealer_bp\n from app.modules.donor import donor_bp\n app.register_blueprint(auth_bp)\n app.register_blueprint(admin_bp)\n app.register_blueprint(dealer_bp)\n app.register_blueprint(donor_bp)\n\n # Initialize Global db\n db.create_all()\n\n # Error handlers\n @app.errorhandler(403)\n def forbidden_page(error):\n return render_template('errors/403.html'), 403\n\n @app.errorhandler(404)\n def page_not_found(error):\n return render_template('errors/404.html'), 404\n\n @app.errorhandler(500)\n def server_error_page(error):\n return render_template('errors/500.html'), 500\n\n # shell context for flask cli\n @app.shell_context_processor\n def ctx():\n return {'app': app, 'db': db}\n\n return app\n" }, { "alpha_fraction": 0.45093944668769836, "alphanum_fraction": 0.519832968711853, "avg_line_length": 22.950000762939453, "blob_id": "43dbabaae536f46437f271c9031e88c15cbdc14d", "content_id": "792bde4a89ca016e16f019ea1e7d4a744d48e345", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 480, "license_type": "no_license", "max_line_length": 79, "num_lines": 20, "path": "/app/routes.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "import os\nfrom flask import render_template\n\n\[email protected]('/')\[email protected]('/index')\ndef index():\n print(os.getenv('APP_LOCALE'))\n user = {'username': 'Germán'}\n files = [\n {\n 'properties': {'hash': '1234123412341234'},\n 'name': 'try.txt'\n },\n {\n 'properties': {'hash': '1234123412341234'},\n 'name': 'try2.txt'\n }\n ]\n return render_template('index.html', title='Index', user=user, files=files)\n" }, { "alpha_fraction": 0.6846606731414795, "alphanum_fraction": 0.6913909316062927, "avg_line_length": 40.47093200683594, "blob_id": "801249d14c24033b9f83884691f9e67b84be565b", "content_id": "ab92b14f385fca40c9b7e693b3adbba49f7c152d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7132, "license_type": "no_license", "max_line_length": 93, "num_lines": 172, "path": "/app/models.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# app/models.py\n\nimport os\nimport datetime\nimport hashlib\nimport humanfriendly\n\nfrom werkzeug import generate_password_hash, check_password_hash\nfrom flask_login import UserMixin\nfrom app import db\nfrom sqlalchemy import CheckConstraint\n\nclass User(UserMixin, db.Model):\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n name = db.Column(db.String(50), unique=True)\n email = db.Column(db.String(255), unique=True)\n username = db.Column(db.String(255), unique=True, nullable=True)\n password = db.Column(db.String(255), nullable=False)\n token = db.Column(db.String(255))\n admin = db.Column(db.Boolean, nullable=False, default=False)\n status = db.Column(db.Boolean, nullable=False, default= 1)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass Address(db.Model):\n __tablename__ = 'address'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n state = db.Column(db.String(100))\n city = db.Column(db.String(100))\n postal_code = db.Column(db.String(100))\n street = db.Column(db.String(100))\n number = db.Column(db.String(10))\n extra_details_address = db.Column(db.String(255))\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass Donor(db.Model):\n __tablename__ = 'donor'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n address = db.Column(db.Integer, db.ForeignKey('address.id'), nullable=False)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n \nclass Applicant(db.Model):\n __tablename__ = 'applicant'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n address = db.Column(db.Integer, db.ForeignKey('address.id'), nullable=False)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass Dealer(db.Model):\n __tablename__ = 'dealer'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n user = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)\n address = db.Column(db.Integer, db.ForeignKey('address.id'), nullable=False)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass ProductType(db.Model):\n tablename = 'product_type'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n name = db.Column(db.String(50), nullable=False)\n description = db.Column(db.String(100))\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass Product(db.Model):\n __tablename__ = 'product'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n product_type_id = db.Column(db.Integer, db.ForeignKey('product_type.id'), nullable=False)\n description = db.Column(db.String(100), nullable=False)\n image_url = db.Column(db.String(100))\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass StockDonor(db.Model):\n __tablename__ = 'stock_donor'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)\n donor_id = db.Column(db.Integer, db.ForeignKey('donor.id'), nullable=False)\n quantity = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\n @property\n def serialize(self):\n return {\n 'id': self.id,\n 'product_id': self.product_id,\n 'donor_id': self.donor_id,\n 'quantity': self.quantity,\n 'created_at': self.created_at,\n 'updated_at': self.updated_at,\n }\n\n @classmethod\n def create(self, product_id, donor_id, quantity):\n new_stock = StockDonor(product_id=product_id, donor_id=donor_id, quantity=quantity)\n new_stock.save()\n return new_stock\n\n def update(self):\n self.updated_at = datetime.datetime.now()\n self.save()\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\n def delete(self):\n db.session.delete(self)\n db.session.commit()\n\nclass RequestApplicant(db.Model):\n __tablename__ = 'request_applicant'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)\n applicant_id = db.Column(db.Integer, db.ForeignKey('applicant.id'), nullable=False)\n quantitiy = db.Column(db.Integer)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass Journey(db.Model):\n __tablename__ = 'journey'\n \n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n dealer_id = db.Column(db.Integer, db.ForeignKey('dealer.id'), nullable=False)\n initial_lat = db.Column(db.Float)\n initial_long = db.Column(db.Float)\n final_lat = db.Column(db.Float)\n final_long = db.Column(db.Float)\n valoration = db.Column(db.Float)\n status = db.Column(db.Integer, CheckConstraint('status IN (1, 2, 3)'))\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\n\nclass Package(db.Model):\n __tablename__ = 'package'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n journey_id = db.Column(db.Integer, db.ForeignKey('journey.id'), nullable=False)\n donor_id = db.Column(db.Integer, db.ForeignKey('donor.id'), nullable=False)\n applicant_id = db.Column(db.Integer, db.ForeignKey('applicant.id'), nullable=False)\n ts_pickup = db.Column(db.DateTime, nullable=True)\n ts_delivery = db.Column(db.DateTime, nullable=True)\n status = db.Column(db.Integer, default = 0)\n package_valoration = db.Column(db.Float, nullable=True)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)\n\nclass PackageContent(db.Model):\n __tablename__ = 'package_content'\n\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n package_id = db.Column(db.Integer, db.ForeignKey('package.id'), autoincrement=True)\n product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)\n quantity = db.Column(db.Integer, default = 0)\n created_at = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now)\n updated_at = db.Column(db.DateTime, nullable=True)" }, { "alpha_fraction": 0.7149876952171326, "alphanum_fraction": 0.7223587036132812, "avg_line_length": 24.4375, "blob_id": "0c95c1b67caeadf71eec012f3974b3d3b11a5b4c", "content_id": "e41419affc060f9be744f4dee4ad72a647384564", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 59, "num_lines": 16, "path": "/app/modules/admin.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# Blueprint Configuration\nfrom flask import Blueprint, render_template\nfrom flask_login import current_user\nfrom werkzeug.exceptions import abort\n\nfrom app.models import User\n\nadmin_bp = Blueprint('admin', __name__)\n\n\n@admin_bp.route('/admin-panel')\ndef index():\n if not current_user.is_admin():\n abort(403)\n users = User.query.all()\n return render_template('admin/index.html', users=users)\n" }, { "alpha_fraction": 0.8092485666275024, "alphanum_fraction": 0.8150289058685303, "avg_line_length": 16.399999618530273, "blob_id": "ceacbf3988a796d2ac58aac893bc563d289f1b3a", "content_id": "2a529567bcdaf6e57a839ab9ab1843c14ac3b180", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 173, "license_type": "no_license", "max_line_length": 41, "num_lines": 10, "path": "/.env.example", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "FLASK_DEBUG=1\nAPP_NAME=Default\nSECRET_KEY=Key\nAPP_SETTINGS=app.config.DevelopmentConfig\nFLASK_APP=main.py\n\n#POSTGRES\nPSQL_DB_NAME=covid\nPSQL_DB_USER=postgres\nPSQL_DB_PASSWD=" }, { "alpha_fraction": 0.7019230723381042, "alphanum_fraction": 0.7019230723381042, "avg_line_length": 10.55555534362793, "blob_id": "0fc61d1a325c5b48e0bfec7de6a5972fe654d9b8", "content_id": "f14fafb02cd892195b37a323156a282356b39448", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 25, "num_lines": 9, "path": "/app/utils.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "import os\nimport sys\n\nfrom pprint import pprint\n\n\ndef dd(variable):\n pprint(variable)\n sys.exit()\n" }, { "alpha_fraction": 0.6524701714515686, "alphanum_fraction": 0.6678023934364319, "avg_line_length": 29.736841201782227, "blob_id": "0212f612eb0e45705d518653c85cd2ea4daadf1e", "content_id": "33d075eb75689621fe877c0eaaae4e14f5a38dd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 587, "license_type": "no_license", "max_line_length": 91, "num_lines": 19, "path": "/resources/js/dealer/dealer.js", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "\n\n\nvar map = L.map(\"map\").setView([40.28, -3.7], 13);\n\nL.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {\n attribution: '&copy; <a href=\"http://osm.org/copyright\">OpenStreetMap</a> contributors'\n}).addTo(map);\n\nlet DefaultIcon = L.icon({\n iconUrl: 'static/img/marker-icon2.svg',\n // shadowUrl: iconShadow\n});\n\n\nL.Marker.prototype.options.icon = DefaultIcon;\n\nL.Marker.prototype.options.icon = DefaultIcon;\nmap.on(\"contextmenu\", function (event) {\n console.log(\"user right-clicked on map coordinates: \" + event.latlng.toString());\n L.marker(event.latlng).addTo(map);\n});\n" }, { "alpha_fraction": 0.7453415989875793, "alphanum_fraction": 0.7453415989875793, "avg_line_length": 25.83333396911621, "blob_id": "c2dcf0b39cd12524e578a99d86bd9bc646aa3650", "content_id": "b26adb204e987c1e42204e8cddf27a6289d98312", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 90, "num_lines": 18, "path": "/app/modules/dealer.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# app/modules/manager.py\n\nimport os\n\nfrom app import db\nfrom flask import render_template, Blueprint, request, flash, redirect, send_file, jsonify\nfrom flask_login import login_required, current_user\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.exceptions import abort\n\n# Use modules for each logical domain\ndealer_bp = Blueprint('dealer', __name__)\n\n@dealer_bp.route('/map')\ndef index():\n print(\"Llega\")\n \n return render_template('dealer/dealer.html', data={})\n" }, { "alpha_fraction": 0.5155763030052185, "alphanum_fraction": 0.7118380069732666, "avg_line_length": 16.83333396911621, "blob_id": "e62a8b18f63327a0aac92bddf53da20840ff5f1a", "content_id": "635bf5773ca97cc1d6a0591838e0cd26a5afd52c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 642, "license_type": "no_license", "max_line_length": 26, "num_lines": 36, "path": "/requirements.txt", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "alembic==1.3.3\nbcrypt==3.1.7\nblinker==1.4\ncertifi==2019.11.28\ncffi==1.13.2\nchardet==3.0.4\nClick==7.0\nFlask==1.1.1\nFlask-Bcrypt==0.7.1\nFlask-DebugToolbar==0.10.1\nFlask-Login==0.4.1\nflask-marshmallow==0.11.0\nFlask-Migrate==2.5.2\nFlask-SQLAlchemy==2.4.1\nFlask-WTF==0.14.2\nfuncy==1.14\nhumanfriendly==4.18\nitsdangerous==1.1.0\nJinja2==2.11.1\nMako==1.1.1\nMarkupSafe==1.1.1\nmarshmallow==3.5.1\nmbstrdecoder==0.8.4\npipenv==2018.11.26\npycparser==2.19\npyreadline==2.1\npython-dateutil==2.8.1\npython-dotenv==0.10.5\npython-editor==1.0.4\nsix==1.14.0\nSQLAlchemy==1.3.13\ntypepy==0.6.4\nvirtualenv==16.7.9\nvirtualenv-clone==0.5.3\nWerkzeug==0.16.1\nWTForms==2.2.1\n" }, { "alpha_fraction": 0.6274510025978088, "alphanum_fraction": 0.6274510025978088, "avg_line_length": 14.300000190734863, "blob_id": "32bdc1dc3669ffc5c26ffba498c11ff7361d03f1", "content_id": "fe2311ad021cc51a97759d5f8edb08b25d9644eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "no_license", "max_line_length": 43, "num_lines": 10, "path": "/main.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# !usr/bin/env python\n\nimport os\n\nfrom app import create_app\n\napp = create_app()\n\nif __name__ == \"__main__\":\n app.run(debug=os.getenv('FLASK_DEBUG'))\n" }, { "alpha_fraction": 0.655068576335907, "alphanum_fraction": 0.655068576335907, "avg_line_length": 30.463157653808594, "blob_id": "7d9e6380eb8afb7908ed0941da048bebde4f017c", "content_id": "6e6d612b463cfddabc23024411a4de2f531b5342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2989, "license_type": "no_license", "max_line_length": 98, "num_lines": 95, "path": "/app/modules/auth.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# app/modules/auth.py\n\n\"\"\"Routes for user authentication.\"\"\"\nfrom app import login_manager, db\nfrom app.forms import LoginForm, RegisterForm\nfrom app.models import User\nfrom flask import render_template, redirect, flash, url_for, Blueprint, request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom werkzeug.urls import url_parse\n\n# Blueprint Configuration\nauth_bp = Blueprint('auth', __name__)\n\n\n# Middleware to authorization\n@login_manager.unauthorized_handler\ndef unauthorized():\n \"\"\"Redirect unauthorized users to Login page.\"\"\"\n return redirect(url_for('auth.login'))\n\n\n# Middleware to check if a user is authenticated.\n@login_manager.user_loader\ndef load_user(user_id):\n \"\"\"Check if auth is logged-in on every page load.\"\"\"\n if user_id is not None:\n return User.query.get(user_id)\n\n return None\n\n@auth_bp.route('/index')\n@auth_bp.route('/')\ndef index():\n return render_template('auth/index.html', title='Index')\n\n# Route to register a user.\n@auth_bp.route('/register', methods=['GET', 'POST'])\ndef register():\n \"\"\" User registration page.\"\"\"\n register_form = RegisterForm(request.form)\n\n if request.method == 'POST' and register_form.validate_on_submit():\n existing_user = User.query.filter_by(email=register_form.email.data).first()\n\n if existing_user is None:\n user = User(\n email=request.form.get('email'),\n password=request.form.get('password'),\n username=request.form.get('username')\n )\n db.session.add(user)\n db.session.commit()\n login_user(user)\n return redirect(url_for('auth.index'))\n\n flash('A user already exists with that email address')\n return redirect(url_for('auth.register'))\n\n return render_template('auth/register.html', title='Create an Account | ', form=register_form)\n\n\n# Route to sign in a user.\n@auth_bp.route('/login', methods=['GET', 'POST'])\ndef login():\n \"\"\" User login page.\"\"\"\n if current_user.is_authenticated:\n return redirect(url_for('auth.index'))\n\n login_form = LoginForm(request.form)\n\n if request.method == 'POST' and login_form.validate_on_submit():\n user = User.query.filter_by(email=login_form.email.data).first()\n\n if user is None or not user.check_password(login_form.password.data):\n flash('Invalid username or password')\n return redirect(url_for('auth.login'))\n\n login_user(user, remember=login_form.remember_me.data)\n next_page = request.args.get('next')\n\n if not next_page or url_parse(next_page).netloc != '':\n next_page = url_for('auth.show')\n\n return redirect(next_page)\n\n return render_template('auth/login.html', title='Sign in | ', form=login_form)\n\n\n# Route to logout a user.\n@auth_bp.route('/logout')\n@login_required\ndef logout():\n \"\"\"User logout logic.\"\"\"\n logout_user()\n return redirect(url_for('auth.index'))\n" }, { "alpha_fraction": 0.5227765440940857, "alphanum_fraction": 0.5314533710479736, "avg_line_length": 22.84482765197754, "blob_id": "f06be4339dd5fb807877b442bad09ca138127b63", "content_id": "b21fdfe013eb8c04a8b4dabad72c21b756760fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1383, "license_type": "no_license", "max_line_length": 112, "num_lines": 58, "path": "/resources/js/Manager.js", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "export default class Manager {\n constructor () {\n this.loadEvents()\n }\n\n loadEvents () {\n this.download()\n this.destroy()\n }\n\n download () {\n $('.download').click(function () {\n window.location = '/files/download/' + $(this).data('filename')\n })\n }\n\n destroy () {\n const _this = this\n $('.delete').click(function () {\n Swal.fire(_this.preventSwalObject()).then((result) => { if (result.value) { _this.deleteCall($(this)) } })\n })\n }\n\n preventSwalObject() {\n return {\n title: 'Are you sure?',\n text: \"You won't be able to revert this!\",\n icon: 'warning',\n showCancelButton: true,\n confirmButtonColor: '#9c27b0',\n cancelButtonColor: '#d33',\n confirmButtonText: 'Yes, delete it!'\n }\n }\n\n deleteCall(el) {\n axios.delete('/files/delete/' + el.data('id'))\n .then(response => {\n if (response.data.success) {\n Swal.fire({\n position: 'top-end',\n icon: 'success',\n title: response.data.message,\n showConfirmButton: false,\n timer: 1500\n })\n this.removeParent(el)\n }\n })\n }\n\n removeParent (el) {\n if ($('.table > tbody > tr').length === 1) {\n $('.table > tbody').append(\"<th scope='row' colspan='5' class='text-center'>There is no files</th>\")\n }\n el.parent().parent().remove()\n }\n}\n" }, { "alpha_fraction": 0.7085617780685425, "alphanum_fraction": 0.7321805357933044, "avg_line_length": 33.36231994628906, "blob_id": "e5db9114003b95d09fb517b15f0120116064a46d", "content_id": "1a690836c792919a70ffa36fae3153eb91ff378b", "detected_licenses": [ "BSL-1.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2381, "license_type": "permissive", "max_line_length": 89, "num_lines": 69, "path": "/scripts/iespresso's app/README.md", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "iespresso\n=========\n\n![Espresso](https://raw.githubusercontent.com/markgollnick/iespresso/master/espresso.png)\n\nIt’s like `iexpress.exe` on caffeine!\n\n\nWhat is it?\n-----------\n\nThis repo contains tools for creating more useful [iexpress.exe][] packages:\n\n1. Silently extract all files to the current working directory (SFX-style)\n2. Run batch scripts that execute from the current directory instead of %TEMP%\n\nThis functionality is not readily available via [iexpress.exe][] itself.\n\n[iexpress.exe]: https://en.wikipedia.org/wiki/IExpress\n\n\nUsage\n-----\n\n1. Include `iespress.vbs` and `iespress.bat` (along with all your other files)\n in your `iexpress.exe` package or silent installer.\n\n2. The install line (set in the IExpress Wizard) MUST look like the following:\n\n cmd.exe /c iespress.bat \"...\"\n\n3. *Optional:* Replace `\"...\"` above with a command to run AFTER extraction.\n The command will be run with the location of the original package's EXE\n file as the current working directory. (Normally, all such commands would\n be run from whatever %TEMP% directory the `iexpress.exe` package saw fit to\n extract itself to. This gives you a little bit more flexibility.)\n\n4. **Done.** All files in the package (except for the files `iespress.vbs` and\n `iespress.bat`) will be extracted to the current working directory, and\n your installer may be run.\n\n\nKnown Limitations\n-----------------\n\nYou may wish for your files to be extracted to a subdirectory bearing the same\nname as the original package instead of having them expand all willy-nilly to\nthe current working directory. This functionality may come in a future version\nof iespresso, but for now, you’ll just have to hard-package your files in a\nfolder during the IExpress Wizard if you want your files to be expanded to a\ndirectory level below the original package.\n\n\nAcknowledgments\n---------------\n\n- http://msdn.microsoft.com/en-us/library/ff553615.aspx\n- http://stackoverflow.com/questions/13534699/iexpress-extraction-path/13700281#13700281\n- http://msdn.microsoft.com/en-us/library/aa394599(v=vs.85).aspx\n- User “[Pipo][1]” for the beautiful (and free) [Espresso icon][2]! :-)\n\n[1]: https://openclipart.org/user-detail/pipo\n[2]: https://openclipart.org/detail/3741/espresso-by-pipo\n\n\nLicense\n-------\n\nBoost Software License, Version 1.0: <http://www.boost.org/LICENSE_1_0.txt>\n" }, { "alpha_fraction": 0.6530264019966125, "alphanum_fraction": 0.6589940190315247, "avg_line_length": 12.662500381469727, "blob_id": "8d7d5e8e27b2282fb67e3ae9318c968ebfff4a9b", "content_id": "5d9f84b324b09960e5e58e66be603adb20daff5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 92, "num_lines": 80, "path": "/README.md", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "# Hackathon Optimization Material Delivery\r\n\r\n## Getting Started\r\n\r\n### Prerequisites\r\n\r\n### Installing\r\n\r\nThese steps will be on Windows\r\n\r\n```\r\n Use the Del-lia.exe app to automatic generation of all the proyect in a custom folder, or:\r\n\r\n git clone https://github.com/daniel8rc/hackathon_optimizacion_entregas_material.git\r\n py -3 -m venv venv\r\n venv\\Scripts\\activate\r\n pip install -r requirements.txt\r\n pipenv install\r\n npm install\r\n npm run development\r\n python main.py\r\n```\r\n\r\n### Installing Linux\r\n\r\nThese steps will be on Linux\r\n\r\n```\r\n python3 -m venv venv\r\n\r\n source venv/bin/activate\r\n\r\n pip3 install -r requirements.txt\r\n\r\n pipenv install\r\n\r\n npm install\r\n\r\n npm run development or npm run watch\r\n\r\n python3 main.py\r\n```\r\n\r\n### BBDD\r\n\r\n![BBDDv1](mockups/BBDDv1.png)\r\n\r\n## Running the tests\r\n\r\n### Break down into end to end tests\r\n\r\n### And coding style tests\r\n\r\n## Deployment\r\n\r\n### Installing the database\r\n\r\n```\r\nflask db init\r\nflask db migrate -m \"Initial migrate\"\r\nflask db upgrade\r\n```\r\n\r\n### running the server\r\n\r\n```\r\nflask run\r\n```\r\n\r\n## Built With\r\n\r\n## Contributing\r\n\r\n## Versioning\r\n\r\n## Authors\r\n\r\n## License\r\n\r\n## Acknowledgments\r\n" }, { "alpha_fraction": 0.7000742554664612, "alphanum_fraction": 0.7015590071678162, "avg_line_length": 43.900001525878906, "blob_id": "87b9624b1fd6e1874a4960661af4525fe5a7f800", "content_id": "1be5f08a7b472b1c368161ca5fe87281842a2b01", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1360, "license_type": "no_license", "max_line_length": 110, "num_lines": 30, "path": "/app/forms.py", "repo_name": "gboquizo/hackathon_optimizacion_entregas_material", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\nfrom wtforms import StringField, PasswordField, BooleanField, SubmitField\nfrom wtforms.validators import DataRequired, Email, EqualTo, Length\n\n\nclass LoginForm(FlaskForm):\n \"\"\"User Login Form.\"\"\"\n email = StringField('Correo electrónico', validators=[\n Email('Por favor, introduce un correo electrónico válido.'),\n DataRequired('Por favor, introduce un correo.')\n ])\n password = PasswordField('Contraseña', validators=[DataRequired('Oh, ¿y la contraseña?')])\n remember_me = BooleanField('Recuérdame')\n submit = SubmitField('Entrar')\n\n\nclass RegisterForm(FlaskForm):\n \"\"\"User Register Form.\"\"\"\n email = StringField('Email', validators=[\n Email('Por favor, introduce un correo electrónico válido.'),\n DataRequired('Por favor, introduce un correo.')\n ])\n username = StringField('Nombre de usuario', validators=[DataRequired('¡Introduce un nombre de usuario!')])\n password = PasswordField('Contraseña', validators=[\n DataRequired('Por favor, introduzca una contraseña.'),\n Length(min=8, message='La contraseña tiene que ser más fuerte. Al menos 8 caracteres.'),\n EqualTo('password_confirm', message='Las contraseñas tienen que coincidir')\n ])\n password_confirm = PasswordField('Confirma tu contraseña')\n submit = SubmitField('Registrarme')\n" } ]
18
evolutek/cellaserv4-protobuf
https://github.com/evolutek/cellaserv4-protobuf
48ce786f5492f963b15d83ae1b2b30fc4b397720
1c7d3d99b7a1f8dfb565a5e622fb25fc09350f2b
de419b14389ce3f02d7b6d5eca78f2113a608c58
refs/heads/master
2023-02-06T04:54:30.204423
2020-12-24T15:08:55
2020-12-24T15:08:55
324,180,704
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6374781131744385, "alphanum_fraction": 0.6427320241928101, "avg_line_length": 17.419355392456055, "blob_id": "56f3d43d5db79905f4ca3a319fd1c53ecc9dfdcc", "content_id": "c6f715b09d6f4db5e1ebfd03c3e347d2d20916e6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 571, "license_type": "permissive", "max_line_length": 73, "num_lines": 31, "path": "/README.md", "repo_name": "evolutek/cellaserv4-protobuf", "src_encoding": "UTF-8", "text": "cellaserv4-protobuf\n===================\n\n[cellaserv4](https://github.com/evolutek/cellaserv4) source and generated\nprotobuf files.\n\nUse this repository as a submodule in other repos.\n\nDependencies:\n\n* protobuf-compiler\n* protoc-gen-go\n\nHow to get protoc-gen-go?\n-------------------------\n\nRun:\n\n $ go get github.com/golang/protobuf/{proto,protoc-gen-go}\n\nThen add `$GOPATH/bin` to your `$PATH`\n\nFor more informations, see:\n[goprotobuf's README](https://github.com/golang/protobuf)\n\nUpdating protobuf generated files\n---------------------------------\n\nRun:\n\n $ make\n" }, { "alpha_fraction": 0.48275861144065857, "alphanum_fraction": 0.4913793206214905, "avg_line_length": 15.571428298950195, "blob_id": "b2e7084f3ab14d1e896d75b25a5143238bc9e2ac", "content_id": "623435095819c086c8b518a736dd1128810c8c6e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "permissive", "max_line_length": 28, "num_lines": 7, "path": "/__init__.py", "repo_name": "evolutek/cellaserv4-protobuf", "src_encoding": "UTF-8", "text": "from .cellaserv_pb2 import (\n Message,\n Request,\n Reply,\n Subscribe,\n Publish,\n)\n" }, { "alpha_fraction": 0.6803069114685059, "alphanum_fraction": 0.6854220032691956, "avg_line_length": 26.928571701049805, "blob_id": "34688f27f0350cf721b99f143f89f2dafd4e8f53", "content_id": "40832a5b3749bb4ae07ba19354f685a50342be2f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 391, "license_type": "permissive", "max_line_length": 121, "num_lines": 14, "path": "/Makefile", "repo_name": "evolutek/cellaserv4-protobuf", "src_encoding": "UTF-8", "text": "IN = cellaserv.proto\nOUT = cellaserv.pb.go \\\n cellaserv_pb2.py \\\n cpp/cellaserv.pb.cc cpp/cellaserv.pb.h\n\nall: $(OUT)\n\ncpp:\n\tmkdir cpp\n\n$(OUT): $(IN) cpp\n\t# Output to cpp directory otherwise cgo complains about .cc files in\n\t# the same directory as .go files\n\tprotoc --experimental_allow_proto3_optional --cpp_out=cpp --python_out=. --go_out=. --go_opt=paths=source_relative $(IN)\n" } ]
3
chandanmishra-03/maskrcnn-modanet
https://github.com/chandanmishra-03/maskrcnn-modanet
017d7d41c05460d2bd514fc23df545da9c721815
477b573bc012bf710cf3c6fc20d99cd8e987fd74
1f5e43c868c5581ecdb90c48e64ce3b579593b8f
refs/heads/master
2020-12-28T04:03:34.537991
2020-02-05T10:21:10
2020-02-05T10:21:10
238,174,981
1
0
MIT
2020-02-04T10:02:53
2020-01-14T01:37:41
2019-12-16T22:38:21
null
[ { "alpha_fraction": 0.714634120464325, "alphanum_fraction": 0.7335366010665894, "avg_line_length": 20.148387908935547, "blob_id": "31646dd366eefa4d4ebf75c0d8b84b0f07dceb8d", "content_id": "1981b8b6df2c69114b8d784e3d73de6242416c8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3280, "license_type": "permissive", "max_line_length": 140, "num_lines": 155, "path": "/maskrcnn_modanet/download.sh", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ngit lfs install\n\ncd\nmkdir .maskrcnn-modanet\ncd .maskrcnn-modanet\npwd\necho \"saving your path location\"\n\nPATH1=$1\necho $PATH1\n\nFAST=$2\necho \"fast download:\"\necho $FAST\n\ncd $PATH1\n\nmkdir datasets\ncd datasets\n\nif [ ! \"$FAST\" == \"True\" ]\nthen\n\t\n\t# download images dataset\n\tgit clone https://github.com/kyamagu/paperdoll\n\tpwd\n\tcd paperdoll/data/chictopia\n\tpwd\n\n\tif [ ! -d \"./photos.lmdb\" ]\n\tthen\n\t\techo \"If you already have the 40GB file lying around, you can stop the download by closing this program now,\"\n\t\techo \"putting the photos.lmdb file into ./datasets/paperdoll/data/chictopia\"\n\t\techo \"and then restarting this program again so that it thinks it's already downloaded (did you?)\"\n\t\techo \"or you could just wait a few hours of your precious time here..\"\n\t\twget -c http://vision.is.tohoku.ac.jp/chictopia2/photos.lmdb.tar\n\t\ttar xf photos.lmdb.tar\n\t\tif [ -d \"./photos.lmdb\" ]\n\t\tthen\n\t\t\trm photos.lmdb.tar\n\t\telse\n\t\t\techo \"install tar and run again this command!\"\n\t\t\texit 1\n\t\tfi\n\telse echo \"photos database already downloaded!\"\n\tfi\n\n\techo \"unzipping database..\"\n\tgunzip -c chictopia.sql.gz | sqlite3 chictopia.sqlite3\n\tif [ -f \"./chictopia.sqlite3\" ]\n\tthen\n\t\trm chictopia.sql.gz\n\telse\n\t\techo \"install gunzip and sqlite3 and run again this command!\"\n\t\texit 1\n\tfi\n\n\tcd ..\n\tcd ..\n\tcd ..\n\nelse\n\techo \"Skipping downloading PaperDoll\"\nfi\n\npwd\n\ntext=\"\\n\nnow downloading modanet annotations\\n\n\t\t\t\t\t\\t\\t\\ttaken from here:\\n\n\t\t\t\t\t\\t\\t\\thttps://github.com/eBay/modanet\"\n\necho $text\n\n# download images annotations\ngit clone https://github.com/eBay/modanet.git\n\ncd modanet\ncd annotations\n\nwget -O modanet2018_instances_train.json https://github.com/cad0p/maskrcnn-modanet/releases/download/v1.0.3/modanet2018_instances_train.json\n\nwget -O modanet2018_instances_val.json https://github.com/cad0p/maskrcnn-modanet/releases/download/v1.0.3/modanet2018_instances_val.json\n\ncd ..\ncd ..\n\n\nmkdir coco #this will be our dataset final folder\ncd coco\n\nmkdir annotations\n\nif [ \"$FAST\" == \"True\" ]\nthen\n\tpwd\n\techo \"downloading the images folder.. (2 GB)\"\n\tif [ ! -d \"./images\" ]\n\tthen\n\t\twget -c https://github.com/cad0p/maskrcnn-modanet/releases/download/v0.9/images.zip\n\t\techo \"unzipping..\"\n\t\tunzip -q images.zip\n\t\tif [ -d \"./images\" ]\n\t\tthen\n\t\t\trm images.zip\n\t\telse\n\t\t\techo \"could not unzip file. run command again\"\n\t\t\texit 1\n\t\tfi\n\telse\n\t\techo \"images already downloaded!\"\n\tfi\n\n\tcd annotations\n\tpwd\n\n\techo \"now downloading fixed ModaNet annotations (this can also be done with datasets fix command)\"\n\twget -N https://github.com/cad0p/maskrcnn-modanet/releases/download/v0.9/instances_all.json\n\t\n\tcd ..\n\t\nelse\n\techo \"images will be downloaded afterwards by running datasets arrange command\"\n\tmkdir images\nfi\n\n\ncd ..\ncd .. #now in main folder\nmkdir results\ncd results\npwd\n\necho \"downloading the default coco snapshot\"\nwget -N https://github.com/fizyr/keras-maskrcnn/releases/download/0.2.2/resnet50_coco_v0.2.0.h5\n\n\necho \"downloading the last available trained modanet snapshot\"\nwget -N https://github.com/cad0p/maskrcnn-modanet/releases/download/v1.0/resnet50_modanet.h5\n\nmkdir snapshots\nmkdir processedimages\nmkdir logs\n\ncd processedimages\npwd\nmkdir images\nmkdir imagesegments\nmkdir annotations\n\n\n# does not show folders named lib (which clutter the graph)\ntree -d $PATH1 -I lib --matchdirs\n\n\n" }, { "alpha_fraction": 0.7448021173477173, "alphanum_fraction": 0.7587189674377441, "avg_line_length": 45.960628509521484, "blob_id": "533f23a35935d46aea8a63a44703fd721649dc78", "content_id": "cd9dd1a1334803691d03ad69c7779fc0d3f5482d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5964, "license_type": "permissive", "max_line_length": 339, "num_lines": 127, "path": "/README.MD", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "A Mask R-CNN Keras implementation with Modanet annotations on the Paperdoll dataset\n\n# Mask R-CNN with ModaNet\n\nMy bachelor's thesis project.\n\n![ModaNet](https://github.com/eBay/modanet/blob/master/logo/modanet_logo2.png)\n\nTo sum it all up, I created a program that enables you to quickly train any model using [fizyr's keras-maskrcnn](https://github.com/fizyr/keras-maskrcnn) (I spent around a month to make it work).\nAnd in particular to train it using [ModaNet](https://github.com/eBay/modanet).\nModaNet, I discovered, had its flaws, particularly on the footwear and boots. They had the bounding boxes overlap with each other.\nYou can check them out by running `maskrcnn-modanet viewimage --all-set --original`\nWith and without the \"original\" parameter, in parallel in two different terminal tabs/windows.\n\nSo I fixed them (although help is much appreciated to refine it).\n\nThen I ran some tests to check the results and footwear and boots recognition were dramatically improved.\n\nI then formulated a simple application to analyze how many shoes, or skirts, or one of the other 13 labels, are in the user's instagram account, only analyzing images in which there is only one person in the frame. More details again on the [release notes for v1.0](https://github.com/cad0p/maskrcnn-modanet/releases/tag/v1.0).\n\nBelow is the home screen of the program.\n\n```\nUsage: maskrcnn-modanet [OPTIONS] COMMAND [ARGS]...\n\n Main CLI.\n\nOptions:\n --help Show this message and exit.\n\nCommands:\n datasets Manage your datasets run 1 -> maskrcnn-modanet datasets...\n evaluate Evaluate any trained model, average precision and recall.\n instagram Simple implementation to track instagram metrics per...\n processimage View and save processed image and annotations from input...\n savedvars Show and edit saved variables\n train Train using the dataset downloaded usage: maskrcnn-\n modanet...\n viewannotation View and (not yet needed) save dataset images, plain (not...\n viewimage View and (not yet needed) save dataset images, plain (not...\n\n\n```\nI'll be very happy to merge your pull requests that add new implementations, or link to them in a section here!\n\nRegarding the Instagram analyzer, I started from the [Instaloader](https://github.com/instaloader) classes and overrode some methods to get the urls of the posts instead of downloading them.\n\nIt then runs through the COCO model to determine the images that have only one person that is bigger than 10% of the image, and on those images I run the ModaNet model to show some statistics about what type of apparel the user is wearing and even display the instances of them, if you request it.\n\nSay you want to quickly find what skirt (or footwear) your instagram star always wears. With this tool you can! And you can also see how often the instagram user shows himself alone in their images, and what he/she usually shares of him (always pictures with shoes? always only the top part?)\n\n\n[Link to the Thesis Presentation](https://docs.google.com/uc?id=1IPyoPsAxFk7EXtFL3K4AbUWVy_VjKb6K)\n\n[Short Version](https://docs.google.com/uc?id=1Tua2xs1DoY4Kv_bHwbF_rflgV8E7iTUq)\n\n## Getting Started\n```bash\n\nmaskrcnn-modanet train --epochs 25 --batch-size 5 --workers 5 --max-queue-size 30 coco\n```\n\nThis project is written in Python 3, so it works in all major OSes. Although only Linux and MacOS are fully supported.\nKeep in mind to use pip or pip3 depending on your settings.\n\n> UPDATE: My suggestion is to run it using Google Colab. \nJust make a copy of [this notebook](https://colab.research.google.com/drive/11ytb0srMyOGXQtHoF0ocCkKGNTb7fvmq) and click play on the code snippets.\n\n> The code has been optimized to run well on Colab\n\nClone this repo\n\nRun `pip install maskrcnn-modanet`\n\nOr go to the repo you just cloned on the terminal and run `pip install -e .`\n\nIf you see any errors, just install the dependencies manually, just like this: `pip3 install --upgrade cython`\n\nNow that you've installed it, run `maskrcnn-modanet datasets download the/folder/you/want/to/put/data/in`\n\nIt will take a while, about 40GB to download!\nEDIT: it is now reduced to just 2-3 GB. See the [release notes for v1.0](https://github.com/cad0p/maskrcnn-modanet/releases/tag/v1.0) for details on this and on the instagram application. \n\nThen you can explore its features and commands by running `maskrcnn-modanet`\n\n### Prerequisites\n\nInstall Python and Keras\n\nInstall [Git LFS (Large File Storage)](https://github.com/git-lfs/git-lfs/wiki/Installation) to get all the files!\n\n<!--## Files used\n\n* teslasheet [on my Drive](https://docs.google.com/spreadsheets/d/1wCQQs4Db_8AbxcvRWW3v0yB4pYNEC7v6ckFMnnmIEE4/edit?usp=sharing) - created with [SourceFiles](SourceFiles) taken from [Tesla Motors Club Forum](https://teslamotorsclub.com/tmc/threads/breaking-down-the-model-s-range-calculator-hidden-features-and-data.94675/#post-2692441)-->\n\n## Built With\n\n* [Sublime Text](https://www.sublimetext.com/) - The text editor used\n* [Python 3](https://www.python.org) - Language utilized\n* [GitHub Desktop](https://desktop.github.com/) - To manage developement\n* [Sublime Merge](https://www.sublimemerge.com/) - To manage developement\n\n## Contributing\n\nThe following is a copy of PurpleBooth\n> Please read [CONTRIBUTING.md](https://gist.github.com/PurpleBooth/b24679402957c63ec426) for details on our code of conduct, and the process for submitting pull requests to us.\n\n## Versioning\n\nFor the versions available, see the [releases on this repository](../../releases). \n\n## Authors\n\n* **Pier Carlo Cadoppi** - *Initial work*\n\nSee also the list of [contributors](../../contributors) who participated in this project.\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details\n\n## Acknowledgments\n\n* Hat tip to anyone whose code was used\n* * **Billie Thompson** - *README Template* - [PurpleBooth](https://github.com/PurpleBooth)\n* Inspiration\n* etc lol\n" }, { "alpha_fraction": 0.6750524044036865, "alphanum_fraction": 0.6876310110092163, "avg_line_length": 25.47222137451172, "blob_id": "d4d6cbe50cd3c6fb2327dc53d7b5cc8b4d39db7c", "content_id": "83b0c639786b66856074aa97758232dd75d2e914", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 954, "license_type": "permissive", "max_line_length": 83, "num_lines": 36, "path": "/maskrcnn_modanet/evaluatemodel.py", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "\n\ndef evaluateModel(model_path):\n\n\timport json\n\timport os\n\n\twith open(os.path.expanduser('~')+ '/.maskrcnn-modanet/' + 'savedvars.json') as f:\n\t\tsavedvars = json.load(f)\n\tpath = savedvars['datapath']\n\n\tann_path = path + \"datasets/coco/annotations/\"\n\tann_orig_path = path + 'datasets/modanet/annotations/'\n\n\tcoco_path = path + \"datasets/coco/\"\n\n\tfrom keras_maskrcnn import models\n\n\tmodel = models.load_model(model_path, backbone_name='resnet50')\n\n\tfrom keras_retinanet.utils.transform import random_transform_generator\n\n\ttransform_generator = random_transform_generator(flip_x_chance=0.5)\n\n\tfrom maskrcnn_modanet.train.coco import CocoGenerator\n\n\tvalidation_generator = CocoGenerator(\n coco_path,\n 'val',\n batch_size=1,\n config=None,\n image_min_side=800,\n image_max_side=1333\n )\n\n\tfrom keras_maskrcnn.utils.coco_eval import evaluate_coco\n\n\tevaluate_coco(validation_generator, model)" }, { "alpha_fraction": 0.7228915691375732, "alphanum_fraction": 0.7349397540092468, "avg_line_length": 40.5, "blob_id": "b81766ae3d127739dbecd40519984d03fb182486", "content_id": "8f3effb69daa3704fa676b518d1b96a8d89f4717", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": true, "language": "Markdown", "length_bytes": 83, "license_type": "permissive", "max_line_length": 41, "num_lines": 2, "path": "/.gitattributes", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "*.h5 filter=lfs diff=lfs merge=lfs -text\n*.zip filter=lfs diff=lfs merge=lfs -text\n" }, { "alpha_fraction": 0.6593663096427917, "alphanum_fraction": 0.6672168970108032, "avg_line_length": 34.788185119628906, "blob_id": "f7281cf7ba28ea49ffbc2b210d76cd0ca14f16f1", "content_id": "2cac28088c486fb9649e1c84f75f405b542c0347", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24839, "license_type": "permissive", "max_line_length": 236, "num_lines": 694, "path": "/maskrcnn_modanet/instagram_impl.py", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "from instaloader import Instaloader\n\nimport getpass\nimport json\nimport lzma\nimport os\nimport platform\nimport re\nimport shutil\nimport string\nimport sys\nimport tempfile\nfrom contextlib import contextmanager, suppress\nfrom datetime import datetime, timezone\nfrom functools import wraps\nfrom hashlib import md5\nfrom io import BytesIO\nfrom pathlib import Path\n\nimport requests\nimport urllib3 # type: ignore\n\nfrom instaloader.exceptions import *\nfrom instaloader.instaloadercontext import InstaloaderContext\n\nfrom typing import Any, Callable, Iterator, List, Optional, Set, Union\n\nfrom instaloader.structures import (Highlight, JsonExportable, Post, PostLocation, Profile, Story, StoryItem,\n\t\t\t\t\t\t save_structure_to_file, load_structure_from_file)\n\n\nclass ProfileURL(Profile):\n\n\tdef get_posts(self, limit: Optional[int] = None, offset: Optional[int] = 0) -> Iterator[Post]:\n\t\t\"\"\"Retrieve all posts from a profile.\"\"\"\n\t\tself._obtain_metadata()\n\t\tif limit:\n\t\t\t# yield from (Post(self._context, next(self._context.graphql_node_list(\"472f257a40c653c64c666ce877d59d2b\",\n\t\t\t# {'id': self.userid},\n\t\t\t# 'https://www.instagram.com/{0}/'.format(self.username),\n\t\t\t# lambda d: d['data']['user']['edge_owner_to_timeline_media'],\n\t\t\t# self._rhx_gis,\n\t\t\t# self._metadata('edge_owner_to_timeline_media'))), self)\n\t\t\t# for i in range(min(limit) )\n\n\t\t\tposts = []\n\t\t\tfor node_index, node in enumerate(self._context.graphql_node_list(\"472f257a40c653c64c666ce877d59d2b\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t{'id': self.userid},\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'https://www.instagram.com/{0}/'.format(self.username),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlambda d: d['data']['user']['edge_owner_to_timeline_media'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself._rhx_gis,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tself._metadata('edge_owner_to_timeline_media'))):\n\t\t\t\tif node_index < offset:\n\t\t\t\t\tcontinue\n\t\t\t\telif node_index == limit + offset:\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tposts.append(Post(self._context, node, self))\n\t\t\tyield from posts\n\t\telse:\n\t\t\tyield from (Post(self._context, node, self) for node in\n\t\t\t\t\tself._context.graphql_node_list(\"472f257a40c653c64c666ce877d59d2b\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t{'id': self.userid},\n\t\t\t\t\t\t\t\t\t\t\t\t\t'https://www.instagram.com/{0}/'.format(self.username),\n\t\t\t\t\t\t\t\t\t\t\t\t\tlambda d: d['data']['user']['edge_owner_to_timeline_media'],\n\t\t\t\t\t\t\t\t\t\t\t\t\tself._rhx_gis,\n\t\t\t\t\t\t\t\t\t\t\t\t\tself._metadata('edge_owner_to_timeline_media')))\n\nclass InstaloaderURL(Instaloader):\n\n\tdef check_profile_id(self, profile_name: str) -> Profile:\n\t\t\"\"\"\n\t\tConsult locally stored ID of profile with given name, check whether ID matches and whether name\n\t\thas changed and return current name of the profile, and store ID of profile.\n\n\t\t:param profile_name: Profile name\n\t\t:return: Instance of current profile\n\t\t\"\"\"\n\t\tprofile = None\n\t\twith suppress(ProfileNotExistsException):\n\t\t\tprofile = ProfileURL.from_username(self.context, profile_name)\n\t\tprofile_exists = profile is not None\n\t\tid_filename = self._get_id_filename(profile_name)\n\t\ttry:\n\t\t\twith open(id_filename, 'rb') as id_file:\n\t\t\t\tprofile_id = int(id_file.read())\n\t\t\tif (not profile_exists) or \\\n\t\t\t\t\t(profile_id != profile.userid):\n\t\t\t\tif profile_exists:\n\t\t\t\t\tself.context.log(\"Profile {0} does not match the stored unique ID {1}.\".format(profile_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t profile_id))\n\t\t\t\telse:\n\t\t\t\t\tself.context.log(\"Trying to find profile {0} using its unique ID {1}.\".format(profile_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t profile_id))\n\t\t\t\tprofile_from_id = Profile.from_id(self.context, profile_id)\n\t\t\t\tnewname = profile_from_id.username\n\t\t\t\tself.context.log(\"Profile {0} has changed its name to {1}.\".format(profile_name, newname))\n\t\t\t\tif ((format_string_contains_key(self.dirname_pattern, 'profile') or\n\t\t\t\t\t format_string_contains_key(self.dirname_pattern, 'target'))):\n\t\t\t\t\tos.rename(self.dirname_pattern.format(profile=profile_name.lower(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t target=profile_name.lower()),\n\t\t\t\t\t\t\t self.dirname_pattern.format(profile=newname.lower(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t target=newname.lower()))\n\t\t\t\telse:\n\t\t\t\t\tos.rename('{0}/{1}_id'.format(self.dirname_pattern.format(), profile_name.lower()),\n\t\t\t\t\t\t\t '{0}/{1}_id'.format(self.dirname_pattern.format(), newname.lower()))\n\t\t\t\treturn profile_from_id\n\t\t\treturn profile\n\t\texcept (FileNotFoundError, ValueError):\n\t\t\tpass\n\t\tif profile_exists:\n\t\t\tself.save_profile_id(profile)\n\t\t\treturn profile\n\t\traise ProfileNotExistsException(\"Profile {0} does not exist.\".format(profile_name))\n\n\tdef profile_posts_urls(self, profile_name: Union[str, Profile],\n\t\t\t\t\t\t profile_pic: bool = False, profile_pic_only: bool = False,\n\t\t\t\t\t\t fast_update: bool = False,\n\t\t\t\t\t\t download_stories: bool = False, download_stories_only: bool = False,\n\t\t\t\t\t\t download_tagged: bool = False, download_tagged_only: bool = False,\n\t\t\t\t\t\t post_filter: Optional[Callable[[Post], bool]] = None,\n\t\t\t\t\t\t storyitem_filter: Optional[Callable[[StoryItem], bool]] = None,\n\t\t\t\t\t\t limit: Optional[int] = None,\n\t\t\t\t\t\t offset: Optional[int] = 0) -> List[str]:\n\t\t\"\"\"Download one profile\n\n\t\t.. deprecated:: 4.1\n\t\t Use :meth:`Instaloader.download_profiles`.\n\t\t\"\"\"\n\n\t\t# Get profile main page json\n\t\t# check if profile does exist or name has changed since last download\n\t\t# and update name and json data if necessary\n\t\tif isinstance(profile_name, str):\n\t\t\tprofile = self.check_profile_id(profile_name.lower())\n\t\telse:\n\t\t\tprofile = profile_name\n\n\t\tprofile_name = profile.username\n\n\t\turl_pics = []\n\n\t\t# Save metadata as JSON if desired.\n\t\tif self.save_metadata is not False:\n\t\t\tjson_filename = '{0}/{1}_{2}'.format(self.dirname_pattern.format(profile=profile_name, target=profile_name),\n\t\t\t\t\t\t\t\t\t\t\t\t profile_name, profile.userid)\n\t\t\tself.save_metadata_json(json_filename, profile)\n\n\t\tif self.context.is_logged_in and profile.has_blocked_viewer and not profile.is_private:\n\t\t\t# raising ProfileNotExistsException invokes \"trying again anonymously\" logic\n\t\t\traise ProfileNotExistsException(\"Profile {} has blocked you\".format(profile_name))\n\n\t\t# Download profile picture\n\t\tif profile_pic or profile_pic_only:\n\t\t\twith self.context.error_catcher('Download profile picture of {}'.format(profile_name)):\n\t\t\t\t# self.download_profilepic(profile)\n\t\t\t\tpass\n\t\tif profile_pic_only:\n\t\t\treturn\n\n\t\t# Catch some errors\n\t\tif profile.is_private:\n\t\t\tif not self.context.is_logged_in:\n\t\t\t\traise LoginRequiredException(\"profile %s requires login\" % profile_name)\n\t\t\tif not profile.followed_by_viewer and \\\n\t\t\t\t\tself.context.username != profile.username:\n\t\t\t\traise PrivateProfileNotFollowedException(\"Profile %s: private but not followed.\" % profile_name)\n\t\telse:\n\t\t\tif self.context.is_logged_in and not (download_stories or download_stories_only):\n\t\t\t\tself.context.log(\"profile %s could also be downloaded anonymously.\" % profile_name)\n\n\t\t# Download stories, if requested\n\t\tif download_stories or download_stories_only:\n\t\t\tif profile.has_viewable_story:\n\t\t\t\twith self.context.error_catcher(\"Download stories of {}\".format(profile_name)):\n\t\t\t\t\t# self.download_stories(userids=[profile.userid], filename_target=profile_name,\n\t\t\t\t\t\t\t\t\t\t # fast_update=fast_update, storyitem_filter=storyitem_filter)\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.context.log(\"{} does not have any stories.\".format(profile_name))\n\t\tif download_stories_only:\n\t\t\treturn\n\n\t\t# Download tagged, if requested\n\t\tif download_tagged or download_tagged_only:\n\t\t\twith self.context.error_catcher('Download tagged of {}'.format(profile_name)):\n\t\t\t\t# self.download_tagged(profile, fast_update=fast_update, post_filter=post_filter)\n\t\t\t\tpass\n\t\tif download_tagged_only:\n\t\t\treturn\n\n\t\t# Iterate over pictures and download them\n\t\tself.context.log(\"Retrieving posts from profile {}.\".format(profile_name))\n\t\ttotalcount = profile.mediacount\n\t\tcount = 1\n\t\tfor post in profile.get_posts(limit=limit, offset=offset):\n\t\t\tself.context.log(\"[%3i/%3i] \" % (count, totalcount), end=\"\", flush=True)\n\t\t\tcount += 1\n\t\t\tif post_filter is not None and not post_filter(post):\n\t\t\t\tself.context.log('<skipped>')\n\t\t\t\tcontinue\n\t\t\twith self.context.error_catcher('Download URL profile {}'.format(profile_name)):\n\t\t\t\tdownloaded, url_pics_post = self.url_post(post, target=profile_name)\n\t\t\t\tfor url_pic_post in url_pics_post:\n\t\t\t\t\turl_pics.append(url_pic_post)\n\n\t\t\t\tif fast_update and not downloaded:\n\t\t\t\t\tbreak\n\n\t\treturn url_pics\n\n\tdef url_post(self, post: Post, target: Union[str, Path]) -> (bool, List[str]):\n\t\t\"\"\"\n\t\tGet URL of one instagram post node.\n\n\t\t:param post: Post to get URL.\n\t\t:param target: Target name, i.e. profile name, #hashtag, :feed; for filename.\n\t\t:return: True if something was downloaded, False otherwise, i.e. file was already there\n\t\t\"\"\"\n\n\t\t# Download the image(s) / video thumbnail and videos within sidecars if desired\n\t\tdownloaded = True\n\t\turl_pics = []\n\t\tif self.download_pictures:\n\t\t\tif post.typename == 'GraphSidecar':\n\t\t\t\tedge_number = 1\n\t\t\t\tfor sidecar_node in post.get_sidecar_nodes():\n\t\t\t\t\t# Download picture or video thumbnail\n\t\t\t\t\tif not sidecar_node.is_video or self.download_video_thumbnails is True:\n\t\t\t\t\t\tdownloaded &= True\n\t\t\t\t\t\turl_pics.append(sidecar_node.display_url)\n\t\t\t\t\t# Additionally download video if available and desired\n\t\t\t\t\tif sidecar_node.is_video and self.download_videos is True:\n\t\t\t\t\t\t# downloaded &= self.download_pic(filename=filename, url=sidecar_node.video_url,\n\t\t\t\t\t\t# mtime=post.date_local, filename_suffix=str(edge_number))\n\t\t\t\t\t\tpass\n\t\t\t\t\tedge_number += 1\n\t\t\telif post.typename == 'GraphImage':\n\t\t\t\tdownloaded = True\n\t\t\t\turl_pics.append(post.url)\n\t\t\telif post.typename == 'GraphVideo':\n\t\t\t\tif self.download_video_thumbnails is True:\n\t\t\t\t\t# downloaded = self.download_pic(filename=filename, url=post.url, mtime=post.date_local)\n\t\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tself.context.error(\"Warning: {0} has unknown typename: {1}\".format(post, post.typename))\n\n\t\t# # Save caption if desired\n\t\t# metadata_string = _ArbitraryItemFormatter(post).format(self.post_metadata_txt_pattern).strip()\n\t\t# if metadata_string:\n\t\t# self.save_caption(filename=filename, mtime=post.date_local, caption=metadata_string)\n\n\t\t# Download video if desired\n\t\tif post.is_video and self.download_videos is True:\n\t\t\t# downloaded &= self.download_pic(filename=filename, url=post.video_url, mtime=post.date_local)\n\t\t\tpass\n\n\t\t# Download geotags if desired\n\t\tif self.download_geotags and post.location:\n\t\t\t# self.save_location(filename, post.location, post.date_local)\n\t\t\tpass\n\n\t\t# Update comments if desired\n\t\tif self.download_comments is True:\n\t\t\t# self.update_comments(filename=filename, post=post)\n\t\t\tpass\n\n\t\t# Save metadata as JSON if desired.\n\t\tif self.save_metadata is not False:\n\t\t\t# self.save_metadata_json(filename, post)\n\t\t\tpass\n\n\t\tself.context.log()\n\t\treturn downloaded, url_pics\n\n\ndef viewImageFromURL(url_pic):\n\timport requests, cv2\n\tfrom keras_retinanet.utils.image import read_image_bgr\n\timport matplotlib.pyplot as plt\n\n\tr = requests.get(url_pic, allow_redirects=True)\n\timage = read_image_bgr(BytesIO(r.content))\n\n\t# copy to draw on\n\tdraw = image.copy()\n\t\n\tdraw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)\n\n\n\tplt.figure(figsize=(15, 15))\n\tplt.axis('off')\n\tplt.imshow(draw)\n\tplt.show()\n\n\ndef getImageFromURL(url_pic, draw=False):\n\t''' The image is the one that will be processed, the draw is the one to be shown '''\n\timport requests, cv2\n\tfrom keras_retinanet.utils.image import read_image_bgr\n\n\tr = requests.get(url_pic, allow_redirects=True)\n\timage = read_image_bgr(BytesIO(r.content))\n\n\t\n\n\tif draw:\n\t\t# copy to draw on\n\t\tdraw = image.copy()\n\t\t\n\t\tdraw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)\n\n\t\treturn image, draw\n\telse:\n\t\treturn image\n\n\n\ndef getImageFromFilePath(img_path, draw=False):\n\t''' The image is the one that will be processed, the draw is the one to be shown '''\n\timport requests, cv2\n\tfrom keras_retinanet.utils.image import read_image_bgr\n\n\timage = read_image_bgr(img_path)\n\n\t\n\n\tif draw:\n\t\t# copy to draw on\n\t\tdraw = image.copy()\n\t\t\n\t\tdraw = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)\n\n\t\treturn image, draw\n\telse:\n\t\treturn image\n\n\n\ndef instagramImpl(profile, limit=None, offset=0, process_images=True, profile_stats=True, choice=None, restore_result=False): \n\tfrom maskrcnn_modanet.instagram_impl import InstaloaderURL\n\timport matplotlib.pyplot as plt\n\timport cv2\n\n\timport time\n\n\timport json\n\timport codecs\n\timport os\n\n\timport numpy as np\n\n\tfrom maskrcnn_modanet.cli import validators\n\n\tfrom PIL import Image\n\n\n\n\twith open(os.path.expanduser('~')+ '/.maskrcnn-modanet/' + 'savedvars.json') as f:\n\t\tsavedvars = json.load(f)\n\tpath = savedvars['datapath']\n\n\timg_path = path + \"datasets/coco/images/\"\n\tann_path = path + \"datasets/coco/annotations/\"\n\tsnp_path = path + \"results/snapshots\"\n\n\n\ttimestr = time.strftime(\"%Y%m%d-%H%M%S\")\n\n\tprofile_path = path + 'results/instagram/'+ profile + '/'\n\n\tsave_images_path = profile_path + 'images/'\n\n\tsave_segments_path = profile_path + 'segments/'\n\n\tlog_path = profile_path + timestr + '.txt'\n\n\n\tfrom instaloader import (InstaloaderException, InvalidArgumentException, Post, Profile, ProfileNotExistsException,\n\t\t\t StoryItem, __version__, load_structure_from_file, TwoFactorAuthRequiredException,\n\t\t\t BadCredentialsException)\n\t\n\n\tif not restore_result:\n\n\t\tinstaloader = InstaloaderURL(dirname_pattern=path+'/results/instagram/{target}',download_pictures=True, download_videos=False, download_video_thumbnails=False,\n\t\t\t\t\t\t\t\t download_geotags=False,\n\t\t\t\t\t\t\t\t download_comments=False, save_metadata=False,\n\t\t\t\t\t\t\t)\n\n\t\ttarget = profile\n\n\t\tprofile = instaloader.check_profile_id(target)\n\n\t\tlog_file = open(log_path, 'w+')\n\n\t\t\n\t\tif os.path.exists(save_images_path):\n\t\t\tfor the_file in os.listdir(save_images_path):\n\t\t\t\tfile_path = os.path.join(save_images_path, the_file)\n\t\t\t\ttry:\n\t\t\t\t\tif os.path.isfile(file_path):\n\t\t\t\t\t\tos.unlink(file_path)\n\t\t\t\t\t#elif os.path.isdir(file_path): shutil.rmtree(file_path)\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint(e)\n\n\t\tsave_images_path = validators.check_if_folder_exists(None, None, save_images_path)\n\n\t\tprint(profile)\n\n\t\turl_pics = instaloader.profile_posts_urls(profile, limit=limit, offset=offset)\n\n\t\t# print(url_pics)\n\n\t\tpics = []\n\n\t\t# for url_pic in url_pics:\n\n\n\t\tif process_images and not profile_stats:\n\t\t\tfrom maskrcnn_modanet.processimages import loadModel, main\n\n\t\t\tmodel, labels_to_names = loadModel(model_type='default')\n\t\telif process_images and profile_stats:\n\t\t\tfrom maskrcnn_modanet.processimages import loadModel\n\n\t\t\tmodel, labels_to_names = loadModel(model_type='coco')\n\n\t\t\tprint('Now looking for images with only one person in the image..')\n\n\t\t\t\n\t\t\n\t\tfrom keras_retinanet.utils.image import read_image_bgr\n\t\timport requests\n\t\tfrom io import BytesIO\n\n\t\turl_pics_person = []\n\n\t\tpic_index = 0\n\t\tfor url_pic in url_pics:\n\t\t\tif not process_images:\n\t\t\t\tviewImageFromURL(url_pic)\n\t\t\telif process_images and not profile_stats:\n\t\t\t\t# image, draw = getImageFromURL(url_pic, draw=True)\n\n\t\t\t\t# img_anns = apply_mask(model, image, threshold_score=0.5)\n\n\t\t\t\t# for img_ann in img_anns:\n\t\t\t\t# \tif img_ann['category'] == 'person':\n\n\n\t\t\t\tmain(proc_img_path=None, proc_img_url=url_pic, all_set=False, save_images_path=None, model_path=None, \n\t\t\t\t\tsegments=False, annotations=False, threshold_score=0.5, limit=None, model=model, labels_to_names=labels_to_names)\n\t\t\telif process_images and profile_stats:\n\t\t\t\tfrom maskrcnn_modanet.processimages import apply_mask\n\n\t\t\t\tprint(pic_index, end=' ')\n\t\t\t\tprint(pic_index, end=' ', file=log_file)\n\t\t\t\tprint(url_pic, file=log_file)\n\n\t\t\t\ttry:\n\t\t\t\t\timage, draw = getImageFromURL(url_pic, draw=True)\n\t\t\t\texcept Exception:\n\t\t\t\t\tprint('Image ', pic_index, 'failed to download. Url tried below:\\n' + url_pic + '\\n\\n Continuing to next image..')\n\t\t\t\t\tprint('Image ', pic_index, 'failed to download. Url tried below:\\n' + url_pic + '\\n\\n Continuing to next image..', file=log_file)\n\t\t\t\t\tcontinue\n\n\t\t\t\timage_area = len(image) * len(image[0])\n\n\t\t\t\tpic_index += 1\n\n\t\t\t\timg_anns = apply_mask(model, image, draw=draw, labels_to_names=labels_to_names, image_segments=False)\n\n\t\t\t\tone_person = 0\n\t\t\t\tfor img_ann in img_anns:\n\t\t\t\t\tif img_ann['category'] == 'person' and img_ann['bbox'][2] * img_ann['bbox'][3] >= 0.1 * image_area:\n\t\t\t\t\t\tone_person += 1\n\t\t\t\t\t\tprint(one_person, 'person that covers ', round(img_ann['bbox'][2] * img_ann['bbox'][3] / image_area * 100),'% of the image found in this photo', file=log_file)\n\t\t\t\t\tif one_person > 1:\n\t\t\t\t\t\t# we only select images with only one person that covers an area greater than 10% of the image\n\t\t\t\t\t\tprint('Too many people found in this photo', file=log_file)\n\t\t\t\t\t\tone_person = 0\n\t\t\t\t\t\tbreak\n\n\t\t\t\tif one_person:\n\t\t\t\t\t# # show the image\n\t\t\t\t\t# plt.figure(figsize=(15, 15))\n\t\t\t\t\t# plt.axis('off')\n\t\t\t\t\t# plt.imshow(draw)\n\t\t\t\t\t# plt.show()\n\n\t\t\t\t\t# add the pic to the new urls\n\t\t\t\t\turl_pics_person.append([pic_index, url_pic])\n\n\t\tif process_images and profile_stats:\n\t\t\tprint('We\\'ve now selected the images that are probably the ones with only the person who owns this account.')\n\t\t\tif not choice:\n\t\t\t\tchoice = ''\n\t\t\twhile choice not in ['i', 's']:\n\t\t\t\tchoice = input('Do you want to see the images processed or to see some stats? Type \\'i\\' for image, \\'s\\' for stats: ')\n\n\t\t\t# now let's switch to ModaNet and look into the image\n\n\t\t\tmodel, labels_to_names = loadModel(model_type='default')\n\n\t\t\tfor label_index in labels_to_names:\n\t\t\t\tsegment_label_path = save_segments_path + labels_to_names[label_index] + '/'\n\n\t\t\t\t# remove all previous segments saved\n\n\t\t\t\tif os.path.exists(segment_label_path):\n\t\t\t\t\tfor the_file in os.listdir(segment_label_path):\n\t\t\t\t\t\tfile_path = os.path.join(segment_label_path, the_file)\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tif os.path.isfile(file_path):\n\t\t\t\t\t\t\t\tos.unlink(file_path)\n\t\t\t\t\t\t\t#elif os.path.isdir(file_path): shutil.rmtree(file_path)\n\t\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\t\tprint(e)\n\n\t\t\t\tsegment_label_path = validators.check_if_folder_exists(None, None, segment_label_path)\n\n\t\t\tlabels_images = {}\n\n\t\t\tfor pic_index, url_pic in url_pics_person:\n\t\t\t\timage, draw = getImageFromURL(url_pic, draw=True)\n\n\t\t\t\tprint(pic_index, end=' ')\n\t\t\t\tprint(pic_index, end=' ', file=log_file)\n\t\t\t\tprint(url_pic, file=log_file)\n\n\t\t\t\t\n\n\t\t\t\tif choice == 'i':\n\t\t\t\t\timg_anns = apply_mask(model, image, draw=draw, labels_to_names=labels_to_names, image_segments=False)\n\t\t\t\t\t# show the image\n\t\t\t\t\tplt.figure(figsize=(15, 15), num=str(pic_index))\n\t\t\t\t\tplt.axis('off')\n\t\t\t\t\tplt.imshow(draw)\n\n\t\t\t\t\tplt.show()\n\t\t\t\telif choice == 's':\n\t\t\t\t\timg_anns = apply_mask(model, image, draw=draw, labels_to_names=labels_to_names, image_segments=True)\n\n\t\t\t\t\t# save the images for easy retrieval\n\t\t\t\t\t# plt.figure(num=str(pic_index), dpi=400)\n\t\t\t\t\t# plt.axis('off')\n\t\t\t\t\t# plt.imshow(draw)\n\t\t\t\t\t# plt.savefig(save_images_path + str(pic_index) + '.png')\n\t\t\t\t\t# plt.close()\n\t\t\t\t\tprocessed_image = Image.fromarray(draw, 'RGB')\n\t\t\t\t\tprocessed_image.save(save_images_path + str(pic_index) + '.png')\n\t\t\t\t\tdel processed_image\n\n\t\t\t\t\t# let's count\n\t\t\t\t\tlabels_images[pic_index] = {}\n\t\t\t\t\tfor label_index in labels_to_names:\n\t\t\t\t\t\tlabels_images[pic_index][labels_to_names[label_index]] = []\n\n\t\t\t\t\tfor img_ann in img_anns:\n\t\t\t\t\t\tsave_segment_path = save_segments_path + img_ann['category'] + '/' + str(pic_index) + '_.png'\n\t\t\t\t\t\tsegment_counter = 1\n\t\t\t\t\t\twhile os.path.isfile(save_segment_path):\n\t\t\t\t\t\t\tsave_segment_path = \"_\".join(save_segment_path.split(\"_\")[:-1]) + \"_\" + str(segment_counter) + '.png'\n\t\t\t\t\t\t\tsegment_counter += 1\n\t\t\t\t\t\tsegment = Image.fromarray(img_ann.pop('segment'), 'RGB')\n\t\t\t\t\t\tsegment.save(save_segment_path)\n\t\t\t\t\t\tdel segment\n\t\t\t\t\t\timg_ann['segment'] = save_segment_path\n\t\t\t\t\t\tlabels_images[pic_index][img_ann['category']].append(img_ann)\n\n\t\t\tif choice == 's':\n\t\t\t\tresults = {\n\t\t\t\t\t'url_pics': url_pics,\n\t\t\t\t\t'url_pics_person': url_pics_person,\n\t\t\t\t\t'labels_to_names': labels_to_names\n\t\t\t\t}\n\n\t\t\t\tprint('Saving annotations results for easy recovery.. Use -r option later')\n\t\t\t\twith open(profile_path + 'results.json', 'w') as outfile:\n\t\t\t\t\tjson.dump(results, outfile)\n\t\t\t\tprint('Now saving annotations..')\n\t\t\t\twith open(profile_path + 'labels_images.json', 'wb') as outfile:\n\t\t\t\t\tnp.save(outfile, labels_images)\n\n\n\telif restore_result:\n\t\tlog_file = open(log_path, 'w+')\n\t\t\n\t\tprint('Restoring results..')\n\t\twith open(profile_path + 'results.json') as f:\n\t\t\tresults = json.load(f)\n\t\tprint('Restoring annotations..')\n\t\twith open(profile_path + 'labels_images.json', 'rb') as f:\n\t\t\tlabels_images = np.load(f, allow_pickle=True)[()]\n\t\t\t# credit goes to https://stackoverflow.com/questions/30811918/saving-dictionary-of-numpy-arrays\n\n\t\turl_pics = results['url_pics']\n\t\turl_pics_person = results['url_pics_person']\n\t\tlabels_to_names = results['labels_to_names']\n\n\t\tprint('We\\'ve now recovered the images that are probably the ones with only the person who owns this account, processed to look for apparel and clothing items.')\n\t\tif not choice:\n\t\t\tchoice = ''\n\t\twhile choice not in ['i', 's']:\n\t\t\tchoice = input('Do you want to see the images processed or to see some stats? Type \\'i\\' for image, \\'s\\' for stats: ')\n\n\tif process_images and profile_stats:\n\t\tif choice == 'i' and restore_result:\n\t\t\tfor pic_index, url_pic in url_pics_person:\n\t\t\t\timage, draw = getImageFromFilePath(save_images_path + str(pic_index) + '.png', draw=True)\n\t\t\t\tplt.figure(figsize=(9, 9), num=str(pic_index))\n\t\t\t\tplt.axis('off')\n\t\t\t\tplt.imshow(draw)\n\t\t\t\tplt.show()\n\n\n\n\t\telif choice == 's':\n\t\t\tprint('I will now show you all the stats I can think of:')\n\t\t\tprint('I will now show you all the stats I can think of:', file=log_file)\n\t\t\tprint('Total images:', len(url_pics), 'Images with one person: ', len(url_pics_person))\n\t\t\tprint('Total images:', len(url_pics), 'Images with one person: ', len(url_pics_person), file=log_file)\n\t\t\tprint(round(len(url_pics_person)/len(url_pics)*100, 1), '% of the images contain only one main subject (probably the account owner)')\n\t\t\tprint(round(len(url_pics_person)/len(url_pics)*100, 1), '% of the images contain only one main subject (probably the account owner)', file=log_file)\n\n\t\t\t# for label_index in labels_to_names:\n\t\t\t# \tlabel = label[label_index]\n\t\t\t# how many of each label\n\t\t\tlen_labels = {}\n\t\t\t\n\t\t\tfor label_index in labels_to_names:\n\t\t\t\tlen_labels[labels_to_names[label_index]] = 0\n\t\t\t\t\n\t\t\tfor pic_index in labels_images:\n\t\t\t\tfor label in labels_images[pic_index]:\n\t\t\t\t\tlen_labels[label] += len(labels_images[pic_index][label])\n\t\t\tsum_len_labels = sum(len_labels[i] for i in len_labels)\n\t\t\tprint('There are ', sum_len_labels, ' total instances of labels')\n\t\t\tprint('There are ', sum_len_labels, ' total instances of labels', file=log_file)\n\t\t\tprint(f'Instances of labels per image: {sum_len_labels/len(url_pics_person):4.2f}')\n\t\t\tprint(f'Instances of labels per image: {sum_len_labels/len(url_pics_person):4.2f}', file=log_file)\n\t\t\tfor label in len_labels:\n\n\t\t\t\tperc_label = len_labels[label]/sum_len_labels\n\t\t\t\tavg_label = sum(len(labels_images[pic_index][label]) for pic_index in labels_images)/len(labels_images)\n\t\t\t\tprint(f'Label: {label:15} Perc: {len_labels[label]/sum_len_labels:>6.1%} | Per Image: Avg: {len_labels[label]/len(labels_images):>4.2f} Max: {max(len(labels_images[pic_index][label]) for pic_index in labels_images)}')\n\t\t\t\tprint(f'Label: {label:15} Perc: {len_labels[label]/sum_len_labels:>6.1%} | Per Image: Avg: {len_labels[label]/len(labels_images):>4.2f} Max: {max(len(labels_images[pic_index][label]) for pic_index in labels_images)}', file=log_file)\n\n\t\t\tlabel_again = True\n\t\t\twhile label_again:\n\t\t\t\tlabel = ' '\n\t\t\t\twhile label not in len_labels and label != '':\n\t\t\t\t\tlabel = input('Insert a label to see its instances!\\nUseful if you want to see which shoes your favourite instagram user has.\\nYou can see the labels above. Press enter to abort: ')\n\t\t\t\tif label == '':\n\t\t\t\t\tlabel_again = False\n\t\t\t\t\tbreak\n\t\t\t\tsegments = [img_ann['segment'] for pic_index in labels_images\n\t\t\t\t\t\t\t\t\t\t\t\tfor img_ann in labels_images[pic_index][label] ]\n\t\t\t\tif len(segments) > 0:\n\t\t\t\t\tprint('There are ', len(segments), ' results. Tell me the start and the end, as if you were slicing a Python array')\n\t\t\t\t\tprint('You can also find the results in the folder:\\n' + \"/\".join(segments[0].split(\"/\")[:-1]))\n\t\t\t\t\tfrom_i = input('Start: ')\n\t\t\t\t\tif from_i == '':\n\t\t\t\t\t\tfrom_i = None\n\t\t\t\t\telse:\n\t\t\t\t\t\tfrom_i = int(from_i)\n\t\t\t\t\tto_i = input('End: ')\n\t\t\t\t\tif to_i == '':\n\t\t\t\t\t\tto_i = None\n\t\t\t\t\telse:\n\t\t\t\t\t\tto_i = int(to_i)\n\n\t\t\t\t\t\n\n\t\t\t\t\tfor segment_path in segments[from_i:to_i]:\n\t\t\t\t\t\timg = Image.open(segment_path)\n\t\t\t\t\t\timg.show(title=segment_path.split('/')[-1])\n\t\t\t\t\t\tdel img\n\t\t\t\telse:\n\t\t\t\t\tprint('There are no segments to show for this label.\\n')\n\t\t\t\t\t\n\t\t\t\t\t# plt.figure(figsize=(5, 5), num=str(pic_index), dpi=400)\n\t\t\t\t\t# plt.axis('off')\n\t\t\t\t\t# plt.imshow(segment)\n\t\t\t\t\t# plt.show()\n\n\n\n\n\tprint('You can find the logs as a txt file in:\\n' + log_path)\n\n\tlog_file.close()\n\t\n" }, { "alpha_fraction": 0.5742618441581726, "alphanum_fraction": 0.6075469255447388, "avg_line_length": 34.442543029785156, "blob_id": "c3367488d67ddba1334ca45e520c4dd924fb0869", "content_id": "9f507e7442334139e8228c32d6c88a3b6918b696", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 28992, "license_type": "permissive", "max_line_length": 151, "num_lines": 818, "path": "/maskrcnn_modanet/fix_annotations.py", "repo_name": "chandanmishra-03/maskrcnn-modanet", "src_encoding": "UTF-8", "text": "\ndef ShapeIsNearerToFirstMask(shape, mask1, mask2):\n\tfrom statistics import mean\n\tdistancemask1 = []\n\tdistancemask2 = []\n\n\tshape_bbox = [400, 600, 0, 0]\n\tfor xy_index, xy in enumerate(shape):\t\n\t\tif xy < shape_bbox[xy_index % 2]:\n\t\t\tshape_bbox[xy_index % 2] = xy\n\t\telif xy - shape_bbox[xy_index % 2] > shape_bbox[xy_index % 2 + 2]:\n\t\t\tshape_bbox[xy_index % 2 + 2] = xy - shape_bbox[xy_index % 2]\n\n\tfor shape1 in mask1:\n\t\tshape_bbox1 = [400, 600, 0, 0]\n\t\tfor xy_index1, xy1 in enumerate(shape1):\t\n\t\t\tif xy1 < shape_bbox1[xy_index1 % 2]:\n\t\t\t\tshape_bbox1[xy_index1 % 2] = xy1\n\t\t\telif xy1 - shape_bbox1[xy_index1 % 2] > shape_bbox1[xy_index1 % 2 + 2]:\n\t\t\t\tshape_bbox1[xy_index1 % 2 + 2] = xy1 - shape_bbox1[xy_index1 % 2]\n\t\tdistancemask1.append(min(abs(shape_bbox[0] - shape_bbox1[0]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[1] - shape_bbox1[1]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[0] + shape_bbox[2] - shape_bbox1[0] - shape_bbox1[2]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[1] + shape_bbox[3] - shape_bbox1[1] - shape_bbox1[3])\n\t\t\t\t\t\t\t\t))\n\n\tfor shape2 in mask2:\n\t\tshape_bbox2 = [400, 600, 0, 0]\n\t\tfor xy_index2, xy2 in enumerate(shape2):\t\n\t\t\tif xy2 < shape_bbox2[xy_index2 % 2]:\n\t\t\t\tshape_bbox2[xy_index2 % 2] = xy2\n\t\t\telif xy2 - shape_bbox2[xy_index2 % 2] > shape_bbox2[xy_index2 % 2 + 2]:\n\t\t\t\tshape_bbox2[xy_index2 % 2 + 2] = xy2 - shape_bbox2[xy_index2 % 2]\n\t\tdistancemask2.append(min(abs(shape_bbox[0] - shape_bbox2[0]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[1] - shape_bbox2[1]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[0] + shape_bbox[2] - shape_bbox2[0] - shape_bbox2[2]),\n\t\t\t\t\t\t\t\tabs(shape_bbox[1] + shape_bbox[3] - shape_bbox2[1] - shape_bbox2[3])\n\t\t\t\t\t\t\t\t))\n\treturn mean(distancemask1) <= mean(distancemask2)\n\n\ndef ShapeIsNearerToFirstBbox(shape, bbox1, bbox2):\n\n\tshape_bbox = [400, 600, 0, 0]\n\tfor xy_index, xy in enumerate(shape):\t\n\t\tif xy < shape_bbox[xy_index % 2]:\n\t\t\tshape_bbox[xy_index % 2] = xy\n\t\telif xy - shape_bbox[xy_index % 2] > shape_bbox[xy_index % 2 + 2]:\n\t\t\tshape_bbox[xy_index % 2 + 2] = xy - shape_bbox[xy_index % 2]\n\n\n\tdistancebbox1 = min(abs(shape_bbox[0] - bbox1[0]),\n\t\t\t\t\t\t\tabs(shape_bbox[1] - bbox1[1]),\n\t\t\t\t\t\t\tabs(shape_bbox[0] + shape_bbox[2] - bbox1[0] - bbox1[2]),\n\t\t\t\t\t\t\tabs(shape_bbox[1] + shape_bbox[3] - bbox1[1] - bbox1[3])\n\t\t\t\t\t\t\t)\n\n\n\tdistancebbox2 = min(abs(shape_bbox[0] - bbox2[0]),\n\t\t\t\t\t\t\tabs(shape_bbox[1] - bbox2[1]),\n\t\t\t\t\t\t\tabs(shape_bbox[0] + shape_bbox[2] - bbox2[0] - bbox2[2]),\n\t\t\t\t\t\t\tabs(shape_bbox[1] + shape_bbox[3] - bbox2[1] - bbox2[3])\n\t\t\t\t\t\t\t)\n\treturn distancebbox1 <= distancebbox2\n\n\ndef maskBbox(shapes):\n\tshape_bbox = [400, 600, 0, 0]\n\tfor shape in shapes:\n\t\tshape_bbox_i = shapeBbox(shape)\n\t\tif shape_bbox_i[0] < shape_bbox[0]:\n\t\t\tshape_bbox[0] = shape_bbox_i[0]\n\t\tif shape_bbox_i[1] < shape_bbox[1]:\n\t\t\tshape_bbox[1] = shape_bbox_i[1]\n\t\tif shape_bbox_i[2] > shape_bbox[2]:\n\t\t\tshape_bbox[2] = shape_bbox_i[2]\n\t\tif shape_bbox_i[3] > shape_bbox[3]:\n\t\t\tshape_bbox[3] = shape_bbox_i[3]\n\treturn shape_bbox\n\n\ndef shapeBbox(shape):\n\tshape_bbox = [400, 600, 0, 0]\n\tfor xy_index, xy in enumerate(shape):\t\n\t\tif xy < shape_bbox[xy_index % 2]:\n\t\t\tshape_bbox[xy_index % 2] = xy\n\t\telif xy - shape_bbox[xy_index % 2] > shape_bbox[xy_index % 2 + 2]:\n\t\t\tshape_bbox[xy_index % 2 + 2] = xy - shape_bbox[xy_index % 2]\n\treturn shape_bbox\n\n\ndef bboxShapeMargin(bbox, shape, translate=False):\n\tshape_bbox = [400, 600, 0, 0]\n\tfor xy_index, xy in enumerate(shape):\t\n\t\tif xy < shape_bbox[xy_index % 2]:\n\t\t\tshape_bbox[xy_index % 2] = xy\n\t\telif xy - shape_bbox[xy_index % 2] > shape_bbox[xy_index % 2 + 2]:\n\t\t\tshape_bbox[xy_index % 2 + 2] = xy - shape_bbox[xy_index % 2]\n\tif translate:\n\t\t# this way we only consider width and height\n\t\tshape_bbox[0] = bbox[0]\n\t\tshape_bbox[1] = bbox[1]\n\treturn (abs(shape_bbox[0] - bbox[0]) + \n\t\t\tabs(shape_bbox[1] - bbox[1]) + \n\t\t\tabs(bbox[2] - shape_bbox[2]) +\n\t\t\tabs(bbox[3] - shape_bbox[3])\n\t\t\t)\n\ndef bboxContainsShapes(bbox, shapes, error=0.05):\n\tshapes_contained = 0\n\tshapes_total = 0\n\tfor shape in shapes:\n\t\tshape_bbox = shapeBbox(shape)\n\t\tif bboxContainsShape(bbox, shape):\n\t\t\tshapes_contained += shape_bbox[2] * shape_bbox[3]\n\t\tshapes_total += shape_bbox[2] * shape_bbox[3]\n\n\treturn shapes_contained/shapes_total\n\ndef bboxContainsShape(bbox, shape, error=0.05):\n\tshape_bbox = [400, 600, 0, 0]\n\tfor xy_index, xy in enumerate(shape):\t\n\t\tif xy < shape_bbox[xy_index % 2]:\n\t\t\tshape_bbox[xy_index % 2] = xy\n\t\telif xy - shape_bbox[xy_index % 2] > shape_bbox[xy_index % 2 + 2]:\n\t\t\tshape_bbox[xy_index % 2 + 2] = xy - shape_bbox[xy_index % 2]\n\n\treturn (bbox[0] - error * shape_bbox[2] <= shape_bbox[0] and\n\t\t\tbbox[1] - error * shape_bbox[3] <= shape_bbox[1] and\n\t\t\tbbox[0] + bbox[2] + error * shape_bbox[2] >= shape_bbox[0] + shape_bbox[2] and\n\t\t\tbbox[1] + bbox[3] + error * shape_bbox[3] >= shape_bbox[1] + shape_bbox[3]\n\t\t\t)\n\nimport json\nimport os\n\nwith open(os.path.expanduser('~')+ '/.maskrcnn-modanet/' + 'savedvars.json') as f:\n\tsavedvars = json.load(f)\npath = savedvars['datapath']\n\nimport copy\n\nimport random\n\nimport time\n\ntimestr = time.strftime(\"%Y%m%d-%H%M%S\")\n\nlogs = {}\n# log will be saved as file.\n\nann_path = path + \"datasets/coco/annotations/\"\nann_orig_path = path + 'datasets/modanet/annotations/'\n\n\n# if not os.path.isfile(ann_path + 'instances_all.json'):\n# \t# error: the file is needed for fixing the annotatios\n# \tprint('ERROR: run \\'maskrcnn-modanet datasets arrange\\'')\n# \texit()\n\n\n\n\nprint('Now fixing annotations. Just delete the file \\'instances_all.json\\' and rerun this command, if you want to restore it to the original one.')\nprint('It is also useful to delete the file above if you run into any issues at all. It will be recreated automatically')\n\n\nif not os.path.isfile(ann_path + 'instances_all.json'):\n\tprint('Fixing from the original annotations:\\n'+ann_orig_path + 'modanet2018_instances_train.json')\n\twith open(ann_orig_path + 'modanet2018_instances_train.json') as f:\n \t\tinstances = json.load(f)\nelse:\n\t\n\tprint('Using '+ann_path + 'instances_all.json'+ '\\nDelete that file if you want to fix the original')\n\twith open(ann_path + 'instances_all.json') as f:\n \t\tinstances = json.load(f)\n\nprint(\"Annotations:\" + str(len(instances['annotations'])))\n\nimages_index = [ None ] * 1115985\n\n# images_anns_indexes contains all the annotations for each image_id. \n# the key is the image_id, \n# the value is a list of the indexes of the annotations for that id in instances['annotations']\nimages_anns_indexes = [ [] for i in range(1115985) ]\n\nimg_ids = []\nimg_ids_from_anns = []\n\n\nprint('Analyzing the annotations of each image..')\n\nfor img_index, img in enumerate(instances['images']):\n\timg_id = img['id']\n\timg_ids.append(img_id)\n\timages_index[img_id] = img_index\n\nfor ann_index, ann in enumerate(instances['annotations']):\n\t\timg_id = ann['image_id']\n\t\tif len(images_anns_indexes[img_id]) == 0:\n\t\t\timg_ids_from_anns.append(img_id)\n\t\timages_anns_indexes[img_id].append(ann_index)\n\nprint('Finding the wrong ones')\n# let's assume the width and height of the bboxes are correct at least.\n\nprint('Len img ids:' + str([len(img_ids), len(img_ids_from_anns)]))\n\nif len(img_ids) > len(img_ids_from_anns):\n\tlogs['images_deleted'] = {\n\t\t'quantity': None,\n\t\t'images': []\n\t}\n\tprint('Annotations do not cover all the images.')\n\tprint('Deleting the unnecessary images ')\n\tlogs['images_deleted']['quantity'] = len(img_ids) - len(img_ids_from_anns)\n\tprint(str(logs['images_deleted']['quantity']) + ' unnecessary images')\n\timg_diff = list(set(img_ids) - set(img_ids_from_anns))\n\tfor img_id in img_diff:\n\t\tlogs['images_deleted']['images'].append(instances['images'][images_index[img_id]])\n\t\tdel instances['images'][images_index[img_id]]\n\n\t\t# recalculate the index\n\t\timages_index = [ None ] * 1115985\n\t\tfor img_index, img in enumerate(instances['images']):\n\t\t\timg_id = img['id']\n\t\t\timages_index[img_id] = img_index\n\n\tprint(str(len(instances['images']) - len(img_ids_from_anns)) + ' images difference now.')\n\timg_ids = img_ids_from_anns\n\nelif len(img_ids) < len(img_ids_from_anns):\n\tprint('ERROR: There are annotations not related to any image.')\n\texit()\n\nprint('Now looking for bounding boxes that share the same location')\n\nlogs['double_anns'] = []\nlogs['move_box'] = []\n\ncounter = 0; counter1 = 0; counter2 = 0; counter3 = 0; counter4 = 0\n\n# i want to find the bboxes that have same starting point and same label\nfor img_id in img_ids:\n\tfile_name = instances['images'][images_index[img_id]]['file_name']\n\tfor ann_index1 in images_anns_indexes[img_id]:\n\t\tann1 = instances['annotations'][ann_index1]\n\t\tbbox1 = ann1['bbox']\n\t\tlabel1 = ann1['category_id']\n\n\t\tfor ann_index2 in images_anns_indexes[img_id]:\n\t\t\tann2 = instances['annotations'][ann_index2]\n\t\t\tbbox2 = ann2['bbox']\n\t\t\tlabel2 = ann2['category_id']\n\n\t\t\tif bbox1[0] == bbox2[0] and bbox1[1] == bbox2[1] and label1 == label2 and ann1['id'] != ann2['id']:\n\t\t\t\t# try to fit into mask. is one correct, at least?\n\t\t\t\tmask1 = ann1['segmentation']\n\t\t\t\tmask2 = ann2['segmentation']\n\n\t\t\t\tcounter += 1\n\n\t\t\t\twrongbbox1 = False\n\t\t\t\twrongbbox2 = False\n\n\t\t\t\t# now moving and deleting duplicates\n\n\t\t\t\tshape_index1 = 0; shape_index2 = 0\n\n\t\t\t\twhile shape_index1 < len(instances['annotations'][ann_index1]['segmentation']):\n\n\t\t\t\t\tshape1 = instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\twhile shape_index2 < len(instances['annotations'][ann_index2]['segmentation']):\n\n\t\t\t\t\t\tshape2 = instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\tif shape1 == shape2 and shape_index1 < shape_index2:\n\n\t\t\t\t\t\t\tif (len(instances['annotations'][ann_index1]['segmentation']) == 1 and\n\t\t\t\t\t\t\t\tlen(instances['annotations'][ann_index2]['segmentation']) > 1\n\t\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\t\t\tshape_index2 -= 1\n\n\t\t\t\t\t\t\telif (len(instances['annotations'][ann_index1]['segmentation']) > 1 and\n\t\t\t\t\t\t\t\tlen(instances['annotations'][ann_index2]['segmentation']) == 1\n\t\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t\tshape_index1 -= 1\n\t\t\t\t\t\t\t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\telif (len(instances['annotations'][ann_index1]['segmentation']) == 1 and\n\t\t\t\t\t\t\t\tlen(instances['annotations'][ann_index2]['segmentation']) == 1\n\t\t\t\t\t\t\t\t):\n\t\t\t\t\t\t\t\tcontinue\n\n\n\t\t\t\t\t\t\telif (bboxContainsShape(bbox1, shape1) and not bboxContainsShape(bbox2, shape2)):\n\t\t\t\t\t\t\t\twrongbbox2 = True\n\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox1': wrongbbox1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox2': wrongbbox2,\n\t\t\t\t\t\t\t\t\t\t'wrong': 2\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\tdel instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\t\t\tshape_index2 -= 1\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t# indices problem? seems not. update: it probably works because it directly uses the index\n\t\t\t\t\t\t\t\t# update 2 it's a disaster as we could have easily guessed\n\t\t\t\t\t\t\telif not bboxContainsShape(bbox1, shape1) and bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\twrongbbox1 = True\n\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox1': wrongbbox1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox2': wrongbbox2,\n\t\t\t\t\t\t\t\t\t\t'wrong': 1\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\twrongbbox1 = True\n\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t\tshape_index1 -= 1\n\t\t\t\t\t\t\t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telif not bboxContainsShape(bbox1, shape1) and not bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\twrongbbox1 = True\n\t\t\t\t\t\t\t\twrongbbox2 = True\n\t\t\t\t\t\t\t\t# weird situation in which all the bboxes are wrong. we need to decide\n\t\t\t\t\t\t\t\t# who will go in which mask though, and then fit both the boxes\n\t\t\t\t\t\t\t\t# we'll decide based on vicinity score between the masks!\n\t\t\t\t\t\t\t\tif ShapeIsNearerToFirstMask(shape1, mask1, mask2):\n\t\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape1,\n\t\t\t\t\t\t\t\t\t\t'wrong': 2\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\t\t\t\tshape_index2 -= 1\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox1': wrongbbox1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox2': wrongbbox2,\n\t\t\t\t\t\t\t\t\t\t'wrong': 1\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t\t\tshape_index1 -= 1\n\t\t\t\t\t\t\t\t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t# they are all correct, but usually in this case the smaller box is the better, so we'll\n\t\t\t\t\t\t\t\t# go for it and see the results\n\t\t\t\t\t\t\t\t# to do this we'll \n\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape1) >= bboxShapeMargin(bbox2, shape2):\n\t\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox1': wrongbbox1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox2': wrongbbox2,\n\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t\t\tshape_index1 -= 1\n\t\t\t\t\t\t\t\t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tlogs['double_anns'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'shape': shape2,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox1': wrongbbox1,\n\t\t\t\t\t\t\t\t\t\t'wrongbbox2': wrongbbox2,\n\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\t\t\t\tshape_index2 -= 1\n\n\t\t\t\t\t\telif shape1 != shape2 and shape_index1 != shape_index2:\n\t\t\t\t\t\t\t# what we want to do here is split the annotations that could be very distant\n\t\t\t\t\t\t\tif not bboxContainsShape(bbox1, shape1) and bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\twrongbbox1 = True\n\t\t\t\t\t\t\t\t\n\n\t\t\t\t\t\t\telif bboxContainsShape(bbox1, shape1) and not bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\twrongbbox2 = True\n\n\t\t\t\t\t\t\telif not bboxContainsShape(bbox1, shape1) and not bboxContainsShape(bbox2, shape1):\n\t\t\t\t\t\t\t\t# which one should we move?\n\t\t\t\t\t\t\t\t# we should move the one with width and height more similar to the shape\n\n\t\t\t\t\t\t\t\tif (bboxShapeMargin(bbox1, shape1, translate=True) <=\n\t\t\t\t\t\t\t\t\tbboxShapeMargin(bbox2, shape1, translate=True)):\n\t\t\t\t\t\t\t\t\t# this means bbox1 is more fit to his shape: let's keep it and move the box1\n\t\t\t\t\t\t\t\t\twrongbbox1 = True\n\n\t\t\t\t\t\t\t\telif (shapeBbox(shape1)[2] * shapeBbox(shape1)[3] > 1000 and \n\t\t\t\t\t\t\t\t\tlen(instances['annotations'][ann_index1]['segmentation']) > 1):\n\t# THIS PART CAN CAUSE FAULTS i.e. MOVE SHAPES INCORRECTLY\n\t\t\t\t\t\t\t\t\t# this is to avoid moving very small shapes\n\t\t\t\t\t\t\t\t\twrongbbox2 = True\n\t\t\t\t\t\t\t\t\t# the bbox2 is more fit. let's move the shape1 to bbox2! (and then fit the box)\n\t\t\t\t\t\t\t\t\tif shape1 not in instances['annotations'][ann_index2]['segmentation']:\n\t\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['segmentation'].append(shape1)\n\n\t\t\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t\t\tshape_index1 -= 1\n\t\t\t\t\t\t\t\t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t\t\tbreak\n\n\n\t\t\t\t\t\t\t# if not bboxContainsShape(bbox1, shape1) and bboxContainsShape(bbox2, shape1):\n\t\t\t\t\t\t\t# \t# put shape1 into bbox2\n\t\t\t\t\t\t\t# \tif len(instances['annotations'][ann_index1]['segmentation']) > 1:\n\t\t\t\t\t\t\t# \t\tinstances['annotations'][ann_index2]['segmentation'].append(shape1)\n\t\t\t\t\t\t\t# \t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\t# \t\tshape_index1 -= 1\n\t\t\t\t\t\t\t# \t\t# shape1 is done for check next shape1\n\t\t\t\t\t\t\t# \t\tbreak\n\t\t\t\t\t\t\t# if bboxContainsShape(bbox1, shape2) and not bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t# \t# puth shape 2 into bbox1\n\t\t\t\t\t\t\t# \tif len(instances['annotations'][ann_index2]['segmentation']) > 1:\n\t\t\t\t\t\t\t# \t\tinstances['annotations'][ann_index1]['segmentation'].append(shape2)\n\t\t\t\t\t\t\t# \t\tdel instances['annotations'][ann_index2]['segmentation'][shape_index2]\n\t\t\t\t\t\t\t# \t\tshape_index2 -= 1\n\n\n\t\t\t\t\t\tshape_index2 += 1\n\t\t\t\t\tshape_index1 += 1\n\n\n\t\t\t\t# no more duplicates (in theory but you never know for sure)\n\n\t\t\t\tif wrongbbox1 and not wrongbbox2:\n\t\t\t\t\t# let's move bbox1!\n\t\t\t\t\tcounter1 += 1\n\t\t\t\t\tshape_bbox = maskBbox(mask1)\n\t\t\t\t\t# find the left top most\n\n\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox2,\n\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'wrong': 1\n\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\n\t\t\t\t\t# move the annotations under the moved bbox\n\t\t\t\t\t# moveAnnotationsToBbox(shape_bbox,)\n\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\telif not wrongbbox1 and wrongbbox2:\n\t\t\t\t\t# let's move bbox2!\n\t\t\t\t\tcounter2 += 1\n\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t'wrong': 2\n\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\n\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\telif wrongbbox1 and wrongbbox2:\n\t\t\t\t\tcounter3 += 1\n\t\t\t\telif not wrongbbox1 and not wrongbbox2:\n\t\t\t\t\tcounter4 += 1\n\t\t\t\t\t# they are all still to analyze, because we only have analyzed the duplicates to remove them\n\t\t\t\t\t # but usually in this case the smaller box is the better, so we'll\n\t\t\t\t\t# go for it and see the results\n\t\t\t\t\t# to do this we'll\n\n\t\t\t\t\tfor shape_index1, shape1 in enumerate(mask1):\n\t\t\t\t\t\tfor shape_index2, shape2 in enumerate(mask2):\n\n\t\t\t\t\t\t\tif bboxContainsShape(bbox1, shape1) and not bboxContainsShape(bbox1, shape2):\n\t\t\t\t\t\t\t\t# we know shape 2 needs a new box\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape1) < bboxShapeMargin(bbox2, shape1):\n\t\t\t\t\t\t\t\t\t# the shape 1 is more fit to bbox1, so we move bbox2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# the shape 1 is more fit to bbox2, so we move bbox1\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\n\t\t\t\t\t\t\telif not bboxContainsShape(bbox1, shape1) and bboxContainsShape(bbox1, shape2):\n\t\t\t\t\t\t\t\t# we know shape 1 needs a new box\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape2) < bboxShapeMargin(bbox2, shape2):\n\t\t\t\t\t\t\t\t\t# the shape 2 is more fit to bbox1, so we move bbox2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask1)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# the shape 2 is more fit to bbox2, so we move bbox1\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask1)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\telif bboxContainsShape(bbox1, shape1) and bboxContainsShape(bbox1, shape2):\n\t\t\t\t\t\t\t\t# we use the rule of the most fitting!\n\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape1) < bboxShapeMargin(bbox1, shape2):\n\t\t\t\t\t\t\t\t\t# we move the bbox2 to shape 2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# we move bbox1 to shape 2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\n\t\t\t\t\t\t\t# now using bbox2 as a reference\n\t\t\t\t\t\t\tif bboxContainsShape(bbox2, shape1) and not bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\t# we know shape 2 needs a new box\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape1) < bboxShapeMargin(bbox2, shape1):\n\t\t\t\t\t\t\t\t\t# the shape 1 is more fit to bbox1, so we move bbox2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# the shape 1 is more fit to bbox2, so we move bbox1\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask2)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\n\t\t\t\t\t\t\telif not bboxContainsShape(bbox2, shape1) and bboxContainsShape(bbox2, shape2):\n\t\t\t\t\t\t\t\t# we know shape 1 needs a new box\n\t\t\t\t\t\t\t\tif bboxShapeMargin(bbox1, shape2) < bboxShapeMargin(bbox2, shape2):\n\t\t\t\t\t\t\t\t\t# the shape 2 is more fit to bbox1, so we move bbox2\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask1)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['bbox'][1] = shape_bbox[1]\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t# the shape 2 is more fit to bbox2, so we move bbox1\n\t\t\t\t\t\t\t\t\tshape_bbox = maskBbox(mask1)\n\n\t\t\t\t\t\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t\t\t\t\t\t'bbox2': bbox2,\n\t\t\t\t\t\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t\t\t\t\t\t})\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\t\t\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\n\n\n\n\nprint(counter, counter1, counter2, counter3, counter4)\n\nlogs['invalid_boxes'] = []\n\n# images_anns_indexes contains all the annotations for each image_id. \n# the key is the image_id, \n# the value is a list of the indexes of the annotations for that id in instances['annotations']\n# i added categories here\nimages_anns_indexes = [ [ [] for j in range(14) ] for i in range(1115985) ]\n\ncounter_shapes_corrected_double = 0\ncounter_shapes_moved = 0\n\nfor ann_index, ann in enumerate(instances['annotations']):\n\t\timg_id = ann['image_id']\n\t\tlabel = ann['category_id']\n\t\timages_anns_indexes[img_id][label].append(ann_index)\n\nfor img_id in img_ids:\n\tfor label in range(1,14):\n\n\t\t# used to store and group lonely images\n\t\tmask_new = []\n\n\t\tfor ann_index1 in images_anns_indexes[img_id][label]:\n\t\t\tann1 = instances['annotations'][ann_index1]\n\t\t\tbbox1 = ann1['bbox']\n\t\t\tmask1 = ann1['segmentation']\n\t\t\tid1 = ann1['segmentation']\n\t\t\tlabel1 = ann['category_id']\n\n\t\t\tif bbox1 == [400, 600, 0, 0]:\n\t\t\t\tlogs['invalid_boxes'].append({\n\t\t\t\t\t'bbox':bbox1,\n\t\t\t\t\t'category_id':label,\n\t\t\t\t\t'segmentation': mask1,\n\t\t\t\t\t'id': id1,\n\t\t\t\t\t'image_id': img_id,\n\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name']\n\t\t\t\t})\n\n\t\t\tcounter_lonely = 0\n\n\t\t\tfor shape_index1, shape1 in enumerate(mask1):\n\t\t\t\tif not bboxContainsShape(bbox1, shape1) and len(mask1) > 1:\n\t\t\t\t\tlonely = True\n\t\t\t\t\t# want to find if a shape is lonely\n\t\t\t\t\tfor ann_index2 in images_anns_indexes[img_id][label]:\n\t\t\t\t\t\tann2 = instances['annotations'][ann_index2]\n\t\t\t\t\t\tbbox2 = ann2['bbox']\n\t\t\t\t\t\tmask2 = ann2['segmentation']\n\n\t\t\t\t\t\tif ann_index1 != ann_index2 and bboxContainsShape(bbox2, shape1):\n\t\t\t\t\t\t\tlonely = False\n\t\t\t\t\t\t\t# moving the shape to the correct bbox (if not already present) and deleting it from here\n\t\t\t\t\t\t\tif shape1 not in instances['annotations'][ann_index2]['segmentation']:\n\t\t\t\t\t\t\t\tinstances['annotations'][ann_index2]['segmentation'].append(shape1)\n\t\t\t\t\t\t\t\tcounter_shapes_moved += 1\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tcounter_shapes_corrected_double += 1\n\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif lonely:\n\t\t\t\t\t\tmask_new.append(shape1)\n\t\t\t\t\t\tcounter_lonely += 1\n\n\t\t\tif counter_lonely == len(instances['annotations'][ann_index1]['segmentation']):\n\t\t\t\t# all shapes are lonely, so delete them from the new mask\n\t\t\t\t# and fit the old box to the mask\n\t\t\t\tfor lonely_i in range(counter_lonely):\n\t\t\t\t\tmask_new.pop()\n\n\t\t\t\tshape_bbox = maskBbox(instances['annotations'][ann_index1]['segmentation'])\n\n\t\t\t\tlogs['move_box'].append({\n\t\t\t\t\t\t\t'label': label1,\n\t\t\t\t\t\t\t'bbox1': bbox1,\n\t\t\t\t\t\t\t'bbox2': None,\n\t\t\t\t\t\t\t'shapes_box': shape_bbox,\n\t\t\t\t\t\t\t'file_name': instances['images'][images_index[img_id]]['file_name'],\n\t\t\t\t\t\t\t'wrong': 0\n\t\t\t\t\t\t})\n\n\t\t\n\t\t\t\tinstances['annotations'][ann_index1]['bbox'][0] = shape_bbox[0]\n\t\t\t\tinstances['annotations'][ann_index1]['bbox'][1] = shape_bbox[1]\n\t\t\telse:\n\t\t\t\t# the shapes that are lonely must be deleted from the ann1\n\t\t\t\treversed_shape_index_new = 0\n\t\t\t\tfor shape_new in reversed(mask_new):\n\t\t\t\t\tif reversed_shape_index_new == counter_lonely:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tfor shape_index1, shape1 in enumerate(instances['annotations'][ann_index1]['segmentation']):\n\t\t\t\t\t\tif shape1 == shape_new:\n\t\t\t\t\t\t\tdel instances['annotations'][ann_index1]['segmentation'][shape_index1]\n\t\t\t\t\treversed_shape_index_new += 1\n\n\n\t\t\n\t\tif mask_new != []:\n\t\t\tbbox_new = maskBbox(mask_new)\n\t\t\tarea_new = bbox_new[2] * bbox_new[3]\n\t\t\tid_new = len(instances['annotations'])\n\t\t\tinstances['annotations'].append({\n\t\t\t\t\t'iscrowd':0,\n\t\t\t\t\t'category_id':label,\n\t\t\t\t\t'area': area_new,\n\t\t\t\t\t'segmentation': mask_new,\n\t\t\t\t\t'id': id_new,\n\t\t\t\t\t'image_id': img_id,\n\t\t\t\t\t'bbox': bbox_new\n\t\t\t})\n\n\nprint(str(counter_shapes_corrected_double) + ' shapes that were wrongly readded (duplicates) in previous attempts, rest: ' + str(counter_shapes_moved))\n\nprint(\"Now exchanging boxes that were incorrectly moved to the wrong position\")\n\n# check the margins and correct if one is more fit than another one, correct them\n\n\nprint(\"Now writing logs in datasets/fix_logs folder..\")\n\nlog_path = path + 'datasets/fix_logs/'\nif not os.path.exists(log_path):\n\tos.makedirs(log_path)\nwith open(path + 'datasets/fix_logs/' + timestr +'.json', 'w') as outfile:\n\t\tjson.dump(logs, outfile)\n\n\nprint(\"Now writing files..\")\nwith open(ann_path + 'instances_all.json', 'w') as outfile:\n\t\tjson.dump(instances, outfile)\n\nprint('\\nArrange again the dataset using: maskrcnn-modanet datasets arrange')" } ]
6
possatti/kaggle-titanic
https://github.com/possatti/kaggle-titanic
339dfce0e626770acb4dd0192050f07e04b3c29b
025392301510d59e27dc15fb254948fa2f250d9f
2f03894f5398c0e5743f50821874b626e0c18e0e
refs/heads/master
2019-08-31T05:38:57.436459
2017-07-22T04:08:17
2017-07-22T04:08:17
98,005,824
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6978922486305237, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 24.117647171020508, "blob_id": "49bd72ef75fd39cd500722653a53f61366fc7e06", "content_id": "7995542b3c641d5a9df11145ba8e61e80b9e27b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 427, "license_type": "permissive", "max_line_length": 294, "num_lines": 17, "path": "/README.md", "repo_name": "possatti/kaggle-titanic", "src_encoding": "UTF-8", "text": "Titanic\n=======\n\nThis is my attempt on the [Titanic Getting Started Competition on Kaggle](https://www.kaggle.com/c/titanic/). The only model working is the Naive Bayes' one. Using this model I got an accuracy of 75% more or less, and rank 5404, which is probably already different at the time you read this ;).\n\n## Dependencies\n\n - Python 3\n - Numpy\n - Pandas\n - Scikit Learn\n\n## Usage\n\n```sh\npython models/naive_bayes.py\n```\n" }, { "alpha_fraction": 0.7039626836776733, "alphanum_fraction": 0.7079586982727051, "avg_line_length": 34.329410552978516, "blob_id": "2b9fa25493872fbae1ec63a521fe3064f058d36e", "content_id": "dd9e977507d6f87251dab1c3b100403e7d67db2a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3003, "license_type": "permissive", "max_line_length": 111, "num_lines": 85, "path": "/models/naive_bayes.py", "repo_name": "possatti/kaggle-titanic", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function, division\nfrom sklearn.model_selection import train_test_split\n# from sklearn.preprocessing import MinMaxScaler\nfrom sklearn.naive_bayes import GaussianNB\n\nimport pandas as pd\nimport numpy as np\nimport argparse\nimport sys\nimport os\n\nprint(sys.version, file=sys.stderr)\n\ndef preprocessing(X, Y=None):\n\t# Choose attributes.\n\tpreprocessed = X[['Pclass','Sex','Age','SibSp','Parch','Fare']]\n\n\t# Use 1 and 0 to represent the sex.\n\tpreprocessed.loc[:,'Sex'] = np.where(preprocessed['Sex'] == 'female', 1, 0)\n\n\t# Replace nans with means.\n\tmeans = preprocessed.mean(axis=0)\n\tpreprocessed = np.where(np.isnan(preprocessed), means, preprocessed)\n\n\t# # Scale features to the range 0 to 1. And use the same scaler for all data.\n\t# if 'min_max_scaler' not in globals():\n\t# \tglobals()['min_max_scaler'] = MinMaxScaler()\n\t# \tmin_max_scaler.fit(preprocessed)\n\t# preprocessed = min_max_scaler.transform(preprocessed)\n\n\tif Y is None:\n\t\treturn preprocessed\n\telse:\n\t\treturn preprocessed, Y\n\n\ndef main():\n\tnp.random.seed(7)\n\n\tprint('Loading training data...', file=sys.stderr)\n\ttrain_val = pd.read_csv(args.training_data, index_col='PassengerId')\n\ttrain_val_X = train_val[['Pclass','Name','Sex','Age','SibSp','Parch','Ticket','Fare','Cabin','Embarked']]\n\ttrain_val_Y = train_val['Survived']\n\n\tprint('Loading testing data...', file=sys.stderr)\n\ttesting_X = pd.read_csv(args.testing_data, index_col='PassengerId')\n\n\tprint('Training model...', file=sys.stderr)\n\testimator = GaussianNB()\n\ttraining_X, validation_X, training_Y, validation_Y = train_test_split(train_val_X, train_val_Y, test_size=.25)\n\testimator.fit(*preprocessing(training_X, training_Y))\n\n\tprint('Evaluating model...', file=sys.stderr)\n\tacc = estimator.score(*preprocessing(validation_X, validation_Y))\n\tprint('Accuracy:', acc, file=sys.stderr)\n\n\tprint('Predicting for test data...', file=sys.stderr)\n\tpredictions = estimator.predict(preprocessing(testing_X))\n\n\t# Build csv output expected by Kaggle.\n\tcsv_output = pd.DataFrame(data={'Survived': predictions}, index=testing_X.index.values)\n\n\tif args.save:\n\t\tprint('Saving results to `{}`...'.format(args.save), file=sys.stderr)\n\t\tcsv_output.to_csv(args.save, header=True, index_label='PassengerId')\n\telse:\n\t\tprint('Results preview:', file=sys.stderr)\n\t\tprint(csv_output.head(5))\n\n\tprint('Done.', file=sys.stderr)\n\n\nif __name__ == '__main__':\n\t# Arguments and options\n\tdefault_training_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data', 'train.csv'))\n\tdefault_testing_path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'data', 'test.csv'))\n\tparser = argparse.ArgumentParser(description='')\n\tparser.add_argument('--training-data', metavar='file_path', default=default_training_path)\n\tparser.add_argument('--testing-data', metavar='file_path', default=default_testing_path)\n\tparser.add_argument('-s', '--save-to', metavar='csv_path', dest='save')\n\targs = parser.parse_args()\n\tmain()\n" } ]
2
suossssss/Machine-Learning-Spam-Classification
https://github.com/suossssss/Machine-Learning-Spam-Classification
b28ec0c87ee29be889e4434039c72bfc64c07d4a
d4f2b52c1788f7f4b9646d7835a3cc554e14fca1
047026dad5d87f2af3cf20b6fed4fbbf2c3a70c1
refs/heads/master
2021-01-11T11:33:22.548854
2016-12-19T18:31:53
2016-12-19T18:31:53
76,886,480
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6187291145324707, "alphanum_fraction": 0.6220735907554626, "avg_line_length": 20.35714340209961, "blob_id": "7a9f5c9ce9d49a8d8899b569f2b5d2e1b1c9bd57", "content_id": "7e9e3e6f1327c88ae84dc311063fad73173bed98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 897, "license_type": "no_license", "max_line_length": 51, "num_lines": 42, "path": "/wordList_mapReduce.py", "repo_name": "suossssss/Machine-Learning-Spam-Classification", "src_encoding": "UTF-8", "text": "import glob\nimport mincemeat\nimport operator\ntext_files=glob.glob('word/*')\n\ndef file_contents(file_name):\n f=open(file_name)\n try:\n return f.read()\n finally:\n f.close()\n\nsource=dict((file_name,file_contents(file_name))\n for file_name in text_files)\n\ndef mapfn(key, value):\n#print type(content)\n#result_file=open('test.txt','w') \n for w in value.split(' '):\n if w!=' ':\n #result_file.write(word+'\\n')\n yield w,1\n\n\ndef reducefn(key, value): \n result=sum(value)\n return result\n\n# start the server \n \ns = mincemeat.Server() \ns.datasource = source \ns.mapfn = mapfn \ns.reducefn = reducefn \n \nresults = s.run_server(password=\"526918\") \nresult_file=open('wordList.txt','w')\n#save results\nfor result in results:\n if results[result]>30:\n \tresult_file.write(result+'\\n')\n #print result+' '+str(results[result])+'\\n'\n" } ]
1